Rules editor: imports typed against the controller's module files (ES modules) - #1220
Draft
evgeny-boger wants to merge 3 commits into
Draft
Rules editor: imports typed against the controller's module files (ES modules)#1220evgeny-boger wants to merge 3 commits into
evgeny-boger wants to merge 3 commits into
Conversation
wb-rules now runs rule files with import/export as ES modules. The editor's language service knew nothing about the imported files, so every import fell to the `declare module "*"` wildcard: everything any, a type import an error, no completions for a module's exports. The service now resolves a rule's import specifiers through the engine's own resolution (the new Editor.ResolveModule RPC: relative next to the file, bare in the module directories, absolute as is), fetches the module sources transitively (bounded: 50 files, depth 8, 5 s) and places them in the virtual FS where TypeScript resolves them - relative ones next to the rule's path, bare ones under /wb-rules-modules mapped by a paths wildcard. An import added while typing is fetched (debounced) and the lint pass re-run when it lands, through the lint refresher. Compiler options follow the engine: module "preserve", allowImportingTsExtensions. Firmware without the RPC keeps the previous behaviour. module-resolution.ts: specifier scan, placement, transitive prefetch (createImportSet); import-refresh.ts: the view plugin; editor-proxy: ResolveModule; the edit page passes the resolver when the method is advertised; wb-rules.d.ts re-synced (ImportMeta); changelog. Tests: module-resolution (scan, placement, bounded prefetch, failure), ts-language-service-imports (bare import typed including a type import, relative .ts import, a module's own relative import followed, unresolvable stays any, refreshImports after an edit); the page test's expected loadTsEditorSupport arguments gain the resolver.
From a from-scratch review of the import typing: - a comment inside a multi-line import clause hid the import from the specifier scan (a quote or `;` in it broke the clause regex): comments are blanked before the scan, which also stops commented-out imports from costing a lookup; specifiers come back in document order; - a reused environment fetched a rule's new imports but never re-linted: the reuse path no longer pre-consumes the refresh, the view's refresh plugin (which re-lints) does it; - the ResolveModule advertisement check no longer gates the language service (a negative answer takes the full advertisement timeout - 3 s on today's firmware): it is folded into the resolver, so only a file with imports pays it, bounded by the prefetch deadline; - the prefetch deadline is a real wall-clock bound: each resolver call is raced against what is left of it, so a hung controller cannot hold the editor; a malformed reply (no absolute path) is treated as unresolved; - an import cycle back to the rule never replaces the edited buffer with the on-disk copy. Tests: import-refresh view plugin (creation run, debounced edit, re-lint on arrival, disabled, destroyed mid-flight), the page-level ResolveModule gate, comment cases, document order, deadline, malformed replies, the cycle guard, an unresolvable relative import.
The engine now loads .mjs/.mts (ES modules by name) and .cjs/.cts (classic scripts by name) next to .js/.ts. The editor treats them as rule files: TypeScript language mode for .mts/.cts, rename and copy keep the file's own extension instead of collapsing it to .js/.ts.
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 95 |
| Duplication | 0 |
NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Что происходит; кому и зачем нужно:
В шаблоны MR и MRWM добавлена опция "Установить выход согласно состоянию входа" для "Действий в безопасном режиме".
Что поменялось для пользователей:
См выше
Как проверял/а:
Запускал шаблон на MR6C v2.
Дополнение: привязка опции к версии прошивки
Опция появилась в прошивке 1.27.0 wb-mr (WB-MR3, WB-MR6C, WB-MR6C/NC, WB-MR6C v.3, WB-MRM2-mini) и 1.26.0 wb-mrwm (WB-MRWM2). Старая прошивка отвергает значение 2 своим валидатором: запись проходит без ошибки Modbus, но регистр остаётся прежним — то есть без привязки к прошивке пользователь выбирал бы вариант, который молча ничего не делает.
Поэтому вместо безусловного расширения
enumиспользованы fw-варианты (wb-mqtt-serial 2.269.0, #1243):out<N>_safety_behaviourобъявлен дважды — базовое объявление сenum: [0, 1]и объявление сfwпрошивки иenum: [0, 1, 2];id,groupиorderберутся из первого объявления. Выбор варианта группы по версии прошивки добавлен в Show a device template group description by the device firmware #1242, отсюдаBreaks: wb-mqtt-homeui (<< 2.255.0~~);parametersв семи шаблонах переведены в массив: в объектной форме два объявления одногоidневозможны. Отрендеренные параметры при этом не изменились, меняется только порядок записи параметров в устройство — по порядку шаблона вместо алфавитного;id. Исправлено отдельным коммитом.Проверка на стенде (WB-MR6C slave 62, драйвер 2.272.0, homeui из #1242): все семь шаблонов проходят валидацию драйвера,
device/Loadотдаёт по одному регистру на параметр, запись значения 2 на 1.27.0 доезжает до регистра, на 1.26.5 — нет. В интерфейсе на 1.26.5 нет ни опции, ни примечания; после обновления на 1.27.0 появляются оба.ИИ: раздел «Дополнение» и правки к нему подготовил ИИ-агент. Разделы выше — текст автора PR.
Модель: claude-opus-5[1m] · Harness: Claude Code CLI 2.1.263
Запустил и отвечает за содержимое: @pgasheev