Compare commits

..

451 Commits

Author SHA1 Message Date
Nick Shirokov a314ec32fc fix(web-test): fillFields date/time fields — paste instead of selectValue
Date fields have a CB (Choose Button) that opens a calendar, not a selection
form. fillFields detected hasPick → delegated to selectValue → error
"DLB click did not open a popup or selection form".

Fix: detect date fields by `iCalendB` CSS class on CB button (dom.mjs),
propagate `isDate` flag through field mapping, and use clipboard paste
for date fields instead of selectValue. Reference fields with CB (without
iCalendB) continue using selectValue as before.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 18:40:12 +03:00
Nick Shirokov baefeaa05b fix(web-test): clickElement expand:false — idempotent expand/collapse
expand:false was silently ignored because `if (expand || toggle)` evaluates
to false when expand=false. Now uses `expand != null` to enter the branch,
checks current state (gridListH/gridListV for groups, backgroundImage gx=0
for tree nodes), and only clicks when the state needs to change.

- expand:true on collapsed → expand (click)
- expand:true on expanded → noop (idempotent)
- expand:false on expanded → collapse (click)
- expand:false on collapsed → noop (idempotent)
- toggle → always click (unchanged)

Returns `toggled: true/false` in result to indicate whether click happened.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 18:27:40 +03:00
Nick Shirokov 2d88cdc864 fix(web-test): fillTableRow row:N — colindex matching, scroll, field sorting
Root cause: fillTableRow used child-index matching between grid header and
body cells. When headers are merged (e.g. "Бизнес-процесс источник" spanning
two body columns), header has more children than body — indices diverge,
click lands on wrong cell, fields stay empty.

Fixes:
- Use `colindex` attribute (set by 1C platform) to match header→body cells
  reliably across merged headers (cellCoords + nextCoords)
- Add `scrollIntoView()` before clicking — fills cells behind horizontal scroll
- Sort fields by colindex before processing — Tab-loop goes left→right
  regardless of field order in the passed object
- Limit F4 to tree grids only — prevents calculator popup on numeric fields
  in flat grids which breaks Tab-loop focus
- Add paste fallback in directEditForm path for plain-text/numeric fields

Tested: 12/12 automated scenarios (single/multi field, add/edit, scroll,
reverse order, mixed types, tree grid, multiple tables, checkbox).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 18:22:25 +03:00
Nick Shirokov f7695a9534 feat(cfe-borrow): add -BorrowMainAttribute for borrowing object attributes with form
When adding a new attribute to a borrowed form, -BorrowMainAttribute
borrows the form's main attribute ("Объект") and all referenced object
attributes, tabular sections, and their transitive type dependencies.

Two modes: Form (default — only attributes referenced by form DataPath)
and All (all object attributes). Deep paths like Объект.A.B are resolved
transitively. Already-borrowed objects are not overwritten.

Also fixed: CommonPicture auto-borrow from AutoCommandBar, form-attribute
DataPath stripping (keep only Объект.* paths).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 19:56:26 +03:00
Nick Shirokov 252105396b feat(meta-compile): add ManagerModule.bsl for Report and DataProcessor
Create ManagerModule.bsl alongside ObjectModule.bsl for Report and
DataProcessor types — required for reports with НастроитьВариантыОтчета.

Bump version v1.2 → v1.3

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 20:38:13 +03:00
Nick Shirokov 42df4cd6b1 feat(skd-compile): compact AreaTemplate DSL, fix dataPath and presentation fallback
- Fix empty dataPath when field is specified as object { field, title }
- Add title to presentation fallback chain: presentation → title → name
- Add compact DSL for AreaTemplate: rows/widths/style instead of raw XML
- Built-in style presets: header, data, subheader, total
- User-defined presets via skd-styles.json (project-level overrides)
- Support vertical merge ("|"), parameters ("{Name}"), static text, null cells
- Update SKILL.md, skd-dsl-spec.md, skd-guide.md with template DSL docs
- Add examples/skd-styles.json with all supported keys
- Bump version v1.1 → v1.2

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 20:38:04 +03:00
Nick Shirokov b9a04b235f docs(web-test): document error stack, platformDialogs in guide
Add stack auto-fetch and platformDialogs detection to web-test-guide.md.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 19:53:33 +03:00
Nick Shirokov 9bc0240e95 fix(web-test): take error screenshot before fetchErrorStack closes modal
Move screenshot capture to before fetchErrorStack call in the ACTION_FNS
wrapper, so the error modal is still visible on the screenshot. Skip the
duplicate screenshot in catch block when one was already taken.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 19:32:00 +03:00
Nick Shirokov 4cfcaaaa1c feat(web-test): auto-dismiss platform dialogs in dismissPendingErrors
dismissPendingErrors() now detects and closes leftover platform dialogs
(About, Support Info, Error Report) before checking for 1C error modals.
This prevents action functions from failing with timeouts when a stale
platform dialog blocks interaction via modalSurface.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 19:28:01 +03:00
Nick Shirokov f9c3792528 feat(web-test): detect and close platform dialogs in getFormState/closeForm
getFormState() now returns `platformDialogs` array when platform-level
dialogs are open (About, Support Info, Error Report). These dialogs are
invisible to 1C form detection and not closeable via Escape.
closeForm() detects platform dialogs first and closes them via
_closePlatformDialogs() instead of sending Escape, returning
closedPlatformDialogs in the result.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 19:20:32 +03:00
Nick Shirokov 9090a81e43 feat(web-test): auto-fetch error call stack on 1C exceptions
When a 1C error modal is detected, automatically retrieve the full call
stack before throwing. Uses two strategies: Path 1 clicks the OpenReport
link for platform exceptions, Path 2 navigates hamburger → About →
Support Info for handled ВызватьИсключение errors. The stack is returned
as structured {raw, entries[{location, code}], timestamp} in the error
result. Handles unstable modal redraws with a 1.5s re-check delay.
Platform dialogs are always cleaned up via try/finally.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 19:10:52 +03:00
Nick Shirokov f037324ee9 feat(web-test): expose formCount, openForms, modal in getFormState; closed in closeForm
When the open-windows tab bar is hidden in 1C settings, the model had no
way to know how many forms are open or whether a form is modal. Now
getFormState returns openForms/formCount/modal derived from DOM form
elements (independent of tab bar), and closeForm compares form number
before/after Escape to return closed: true/false.

Tested on ncc (tab bar hidden) and bpdemo (tab bar visible).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 17:23:31 +03:00
Nick Shirokov 6f36e36166 feat(web-test): per-caption voice + speechRate for multi-voice narration
- addNarration: use cap.voice override per caption (fallback to global)
- showCaption/showImage/showTitleSlide: pass opts.voice to caption entry
- showCaption: record caption when text is empty but speech is explicit
- startRecording: add speechRate option (default 70ms/char, 85 for ElevenLabs)
- run.mjs: increase exec timeout to 30min for long recordings
- docs: update recording.md and web-test-recording-guide.md

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 16:30:02 +03:00
Nick Shirokov ca0dac2693 docs(db-load-git): trim SKILL.md, update mapping docs for v1.3
Remove redundant sections (Source table, exit codes, mapping internals)
and trim examples from 6 to 2. Update mapping description to reflect
that all non-XML files (not just BSL) are now handled.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 18:37:26 +03:00
Nick Shirokov ab7d82ba20 fix(db-load-git): handle non-XML files (Help HTML) in partial load, fix PY encoding
- Remove .xml/.bsl-only filter — now any changed file (HTML, BSL, etc.)
  maps to parent object XML + pulls entire Ext/ directory
- Fix: ru.html changes without Help.xml in same commit range were silently
  skipped, leaving help text stale in the database
- Fix PY: add encoding="utf-8" to subprocess.run in run_git() — Cyrillic
  paths were garbled on Windows due to default cp1251 decoding
- Bump to v1.3

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 18:28:53 +03:00
Nick Shirokov 669b5f42f2 fix(help-add): remove EPF-specific artifacts, clarify ObjectName as path
v1.2: renamed processorDir→objectDir, removed ProcessorName alias,
generic error messages instead of "epf-init", HTML template "Описание"
instead of "Описание обработки". SKILL.md clarifies ObjectName format
(e.g. Catalogs/МойСправочник).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 15:46:59 +03:00
Nick Shirokov 5b6fcc7c74 fix(web-test): normalize \u00a0 in matching, prefer exact match in clickEddItem
- normYo now replaces \u00a0 (non-breaking space) with regular space — 1C web
  client uses \u00a0 in dropdown items, causing exact match failures
- clickEddItem does two passes: exact match first, then partial — prevents
  "Системы" from matching before "Системы и бизнес-процессы"
- Same \u00a0 fix applied to all inline ny() functions in evaluate scripts

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 15:35:10 +03:00
Nick Shirokov df47128994 fix(web-test): route reference fields without DLB through selectValue
Reference fields with pick button (_CB) but no dropdown button (_DLB)
were going through the plain paste path, which silently failed for
non-editable fields. Now detected via hasPick flag in resolveFieldsScript
and delegated to selectValue (F4 → selection form).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 15:22:44 +03:00
Nick Shirokov ea453e5c97 fix(web-test,web-publish): DLB-first approach for combobox fields, fix relative Apache paths
web-test/browser.mjs: fillReferenceField now tries DLB (DropListButton) click
before falling back to paste approach. Combobox/enum fields are filled cleanly
in one step (click dropdown → select item) instead of the old Shift+F4 → Tab →
refocus → paste flow that caused visual artifacts.

web-publish v1.1: normalize ApachePath to absolute when agent passes a relative
path like "tools/apache24", preventing Apache "Forbidden" errors.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 14:51:28 +03:00
Nick Shirokov 14b0782904 refactor(web-test): replace fade transitions with auto-cleanup of overlays
CSS fade transitions don't work well with CDP screencast (causes desktop
flash between slides). Instead, showImage/showTitleSlide now automatically
remove the other overlay type — no need to call hide before showing next.

Pattern for consecutive slides:
  showTitleSlide(...) → showImage(...) → showImage(...) → hideImage()
No hideTitleSlide() needed between title and first image.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 21:41:17 +03:00
Nick Shirokov b7e3bd876d feat(web-test): add fade transitions to showTitleSlide/showImage overlays
- Fade-in (300ms ease) on show: element created with opacity:0, then
  transitioned to opacity:1 via requestAnimationFrame
- Fade-out (300ms ease) on hide: opacity set to 0, wait 350ms, remove
- Applied to showTitleSlide/hideTitleSlide and showImage/hideImage
- No change to showCaption (instant appearance fits subtitle UX better)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 21:28:33 +03:00
Nick Shirokov b68f4145ce fix(web-test): reduce smart TTS wait from 100ms/char to 70ms/char
Measured real Edge TTS (ru-RU-DmitryNeural) durations:
  57 chars → 4.4s (77ms/char)
  72 chars → 6.0s (84ms/char)
  126 chars → 8.2s (65ms/char)
  745 chars → 48.0s (64ms/char)

Old 100ms/char overestimated by 30-55%, causing long silent pauses
after speech in showImage/showTitleSlide/showCaption. New 70ms/char
gives ~10% safety margin without excessive silence.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 21:05:13 +03:00
Nick Shirokov dc2056a5d5 fix(web-test): resolve file paths relative to project root, not cwd
All user-facing file functions now resolve relative paths from the
project root (where .claude/ lives) instead of process.cwd().
Fixes showImage, startRecording, addNarration, openFile failing when
the skill is installed in a different project.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 20:56:11 +03:00
Nick Shirokov bef4a13ba9 docs(web-test): sync API docs with actual implementation
- recording.md: add speech param to showCaption parameter table
- web-test-guide.md: add showImage, hideImage, addNarration, getCaptions
  to utilities table; add speech to showCaption/showTitleSlide descriptions

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 20:04:58 +03:00
Nick Shirokov c280e52932 docs: update web-test-recording-guide with showImage and titleSlide speech
- Add presentation slides section (showImage with style presets)
- Add speech parameter to title slide example
- Update full example with title speech and image slide

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 20:00:08 +03:00
Nick Shirokov c86bf8779f docs(web-test): document showImage and showTitleSlide speech in recording.md
- Add showImage/hideImage API docs with style presets and scaling behavior
- Add speech parameter to showTitleSlide docs
- Update example to include title speech and image slide

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 19:57:25 +03:00
Nick Shirokov a4e0faaeb3 feat(web-test): add speech support to showTitleSlide
Title slides can now have TTS narration, same as showCaption/showImage.
Pass opts.speech as string for custom narration text, or true to use
the title text. Includes smart wait for video timeline sync.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 19:53:47 +03:00
Nick Shirokov 9d6ceae4f1 fix(web-test): showImage scaling and full preset improvements
- Use min-width/min-height 50% to upscale small images (was showing
  tiny 225px images at native size instead of scaling up)
- Keep max-width/max-height 92% for large images (no regression)
- Change full preset from cover to contain — no content cropping,
  black bars instead of cutting off edges

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 19:36:22 +03:00
Nick Shirokov 18ad662378 feat(web-test): add showImage/hideImage for displaying images during recording
Show image files (PNG, JPG, etc.) as full-screen overlays during video
recording — useful for presentation slides in video instructions.

- Read file → base64 → inject as <img> overlay (same pattern as showTitleSlide)
- Style presets: blur (default), dark, light, full
- blur: blurred+dimmed copy as background with shadow
- full: object-fit cover, fills entire screen
- TTS speech support with smart wait (same as showCaption)
- Custom background overrides preset
- Fixed no-record stubs: showImage/showTitleSlide not stubbed (visual-only)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 19:17:31 +03:00
Nick Shirokov 05fc7eba27 feat(skd): support @file references for query text in skd-compile and skd-edit
Allows using "@path/to/file.sql" instead of inline query text.
Path resolved relative to definition file, then CWD; absolute paths supported.

Closes #9

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 20:06:02 +03:00
Nick Shirokov ffa3189442 feat(meta-info): show LimitLevelCount/LevelCount for hierarchical catalogs
Closes #10

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 19:26:14 +03:00
Nick Shirokov bb02c1b0bd feat(web-test): clickElement support for icon-only frameButton + tumblerItem
Icon-only navigation buttons (Назад, Обновить) now match by idName fallback.
Tumbler segments (Справа/Снизу/Скрыть) collected as new kind in both
getFormState and findClickTarget.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 19:07:59 +03:00
Nick Shirokov 46f0e6be8c fix(web-test): auto-accept native browser dialogs (confirm/alert)
1C web client uses native confirm() for scripts like vis.js file
access. Without handling, these block Playwright execution.
Added page.on('dialog') handler to auto-accept.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 18:34:05 +03:00
Nick Shirokov 38ccded7d9 feat(web-test): auto-load 1C browser extension for file operations
Auto-detect 1C:Enterprise browser extension from Chrome/Edge profiles
and load it via launchPersistentContext. Enables native file dialogs
(Excel import/export) without "install extension" prompt.

- findExtension() scans Chrome/Edge User Data by extension ID
- connect() uses launchPersistentContext when extension found, falls
  back to chromium.launch() otherwise
- isConnected() handles both Browser and BrowserContext objects
- Temp userDataDir cleaned on disconnect()

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 18:09:20 +03:00
Nick Shirokov 4e0ce5ba0f fix(web-test): clickElement normalizes ё in grid row text
Grid row search in findClickTargetScript used raw innerText without
norm() — missed ё→е normalization. Target was normalized but row text
was not, so "расчётным" didn't match "расчетным".

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 14:19:12 +03:00
Nick Shirokov e948d39adb fix(web-test): clickElement expand support for gridGroup in hierarchy mode
When expand/toggle is passed for gridGroup/gridParent elements,
click the .gridListH/.gridListV triangle icon to expand/collapse
in place instead of dblclick which enters the group. Without
expand, dblclick behavior is preserved.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 13:27:38 +03:00
Nick Shirokov d9e7d9c107 fix(web-test): fillTableRow enum support + clickElement tab ambiguity
Three fixes:

1. fillTableRow: match cells by column header text (headerText fallback)
   when INPUT id-based fuzzy match fails due to metadata typos

2. fillTableRow: EDD filter preserves standalone enum values like "Создать"
   by only filtering "Создать элемент/группу/:" patterns (was: startsWith)

3. clickElement: coordinate-based click for tabs without ID, avoiding
   global [data-content] selector that picks invisible duplicates from
   background forms

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 12:39:44 +03:00
Nick Shirokov 1da43109fc Merge branch 'dev' — checkbox support for readTable/getFormState/fillTableRow
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 13:21:19 +03:00
Nick Shirokov 21a0e360ef fix(web-test): fillTableRow stops Tab early when only checkboxes remain
Tab past the last cell in 1C creates extra rows. Now when all unfilled
fields are checkboxes (boolean values), the Tab loop exits immediately
instead of pressing Tab 3 more times on non-INPUT cells.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 13:04:27 +03:00
Nick Shirokov 9f5e244f68 fix(web-test): fillTableRow add+checkbox targets correct row via addedRowIdx
Tab navigation skips checkbox cells (no INPUT). After Tab fill, unfilled
checkbox fields are retried via direct click. Previously the retry hit
the wrong row because the selected row shifted after Tab/commit. Now
we record row count before "Добавить" click and use that index for the
retry, ensuring checkboxes land on the same row as the text fields.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 12:59:06 +03:00
Nick Shirokov 18a198d12b fix(web-test): fillTableRow processes remaining fields after checkbox toggle
Previously fillTableRow returned immediately after toggling the first
checkbox field, ignoring any remaining fields. Now it recursively
processes the rest on the same row.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 12:40:15 +03:00
Nick Shirokov 8fca42193a feat(web-test): readTable/getFormState — expose unnamed checkbox columns
Unnamed checkbox columns (no header text) now appear as "(checkbox)" in
getFormState().tables[].columns and readTable().columns. Checkbox cell
values return "true"/"false" instead of empty strings.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 12:36:38 +03:00
Nick Shirokov b603c7e3fa feat(web-test): expand alias, tree expand fix, fillTableRow checkbox support
- clickElement: add `expand` option (alias for `toggle`) for tree expand/collapse
- clickElement: fallback to dblclick when tree +/- icon not found
- dom.mjs: search [tree="true"] in entire line, not just first imgBox
- fillTableRow: detect checkbox cells via .gridBox > .checkbox, click checkbox
  icon directly (not cell center). Supports named columns (Активен, Проверен)
- SKILL.md: document `expand` instead of `toggle`

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 11:48:40 +03:00
Nick Shirokov b00289e62c feat(web-test): expand alias, tree expand fix, fillTableRow checkbox support
- clickElement: add `expand` option (alias for `toggle`) for tree expand/collapse
- clickElement: fallback to dblclick when tree +/- icon not found (was NumpadAdd)
- dom.mjs: search [tree="true"] in entire line, not just first imgBox
  (fixes trees with checkbox column before tree column)
- fillTableRow: detect checkbox cells after first click, return immediately
  without escalation (dblclick/F4). Checkbox state detected via .select class
- SKILL.md: document `expand` instead of `toggle`

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 11:47:35 +03:00
Nick Shirokov 97820111d5 feat(web-test): expand alias, tree expand fix, fillTableRow checkbox support
- clickElement: add `expand` option (alias for `toggle`) for tree expand/collapse
- clickElement: fallback to dblclick when tree +/- icon not found (was NumpadAdd)
- dom.mjs: search [tree="true"] in entire line, not just first imgBox
  (fixes trees with checkbox column before tree column)
- fillTableRow: detect checkbox cells after first click, return immediately
  without escalation (dblclick/F4). Checkbox state detected via .select class
- SKILL.md: document `expand` instead of `toggle`

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 10:51:20 +03:00
Nick Shirokov 0a2a36dbc6 refactor(form-info): trim SKILL.md further — drop redundant legend
Output is self-documenting; only note Group:AH/AV abbreviations.
217 → 30 lines.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 19:31:39 +03:00
Nick Shirokov b36232ae19 refactor(form-info): trim SKILL.md from 217 to 47 lines
Remove redundant output format docs — the output is self-documenting.
Keep only: command, parameters, and a compact legend for abbreviations.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 19:29:08 +03:00
Nick Shirokov 1479f944f5 feat(form-info): add -Expand parameter for collapsed page drill-down
Pages are collapsed by default showing "(N items)". The new -Expand
parameter allows expanding by name, title, or * for all. A hint line
is shown when collapsed sections exist.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 19:21:51 +03:00
Nick Shirokov 9cffa81bcc fix(web-test): --no-record stubs return proper objects in run.mjs sandbox
The real fix: run.mjs sandbox was stubbing stopRecording/addNarration as
noop (returning undefined). Now returns { file: null, duration: 0 } so
video scripts work transparently with --no-record.
Also: browser.mjs stopRecording/addNarration handle missing state gracefully.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 17:59:30 +03:00
Nick Shirokov 6667ab38ee fix(web-test): stopRecording/addNarration return stub when not recording
Enables --no-record dry-run of video scripts without errors. stopRecording()
returns { file: null, duration: 0, size: 0 } instead of throwing, and
addNarration(null) returns a matching stub.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 17:36:19 +03:00
Nick Shirokov 26c5e849a5 fix(web-test): highlight groups — filter logicGroupContainer, keep _div for grids
Group search in highlight() now filters by !classList.contains('logicGroupContainer')
instead of removing _div selector entirely. This skips invisible Representation=None
groups while preserving grid/table _div elements (frameGrid) that are the actual
highlightable panels (Оргструктура, Системы, БизнесПроцессы).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 16:57:45 +03:00
Nick Shirokov ca681676b4 feat(web-test): highlight groups fix, recording auto-stop, fillField alias
- highlight(): exact match by name ignores size filter (supports Representation=None groups),
  error message lists available elements by category
- startRecording(): { force: true } option to restart if already recording
- executeScript(): auto-stop recording on script error (prevents "Already recording")
- fillField(name, value): silent alias for fillFields({ name: value })

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 15:37:21 +03:00
Nick Shirokov e3a9be0036 feat(web-test): add FormNavigationPanel support, fix --no-record server-side
1. Navigation panel: getFormState() returns `navigation` array with
   form navigation links (e.g. "Основное", "Объекты метаданных").
   clickElement() can now click navigation panel items (kind: navigation).
   DOM: `.navigationItem` inside parent `page{N}` container.

2. --no-record: move recording stub from client-side code injection to
   server-side sandbox export replacement. Stubs startRecording,
   stopRecording, addNarration, showCaption, hideCaption, showTitleSlide,
   hideTitleSlide as no-ops. Covers both direct calls and user wrappers
   like record()/finalize().

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 12:10:19 +03:00
Nick Shirokov 361354cdd4 Merge branch 'dev' 2026-03-14 19:39:32 +03:00
Nick Shirokov 2ce7b12c4c feat(web-test): add --no-record flag for exec, document toggle option
- exec --no-record injects no-op record() to skip video recording during
  debugging/testing
- Document clickElement { toggle: true } for tree node expand/collapse
- Document --no-record in SKILL.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 19:39:29 +03:00
Nick Shirokov f244d5e507 Merge branch 'dev' 2026-03-14 19:32:31 +03:00
Nick Shirokov 6cb54a8f96 fix(web-test): show detailed message in fillFields error instead of error code
Previously fillFields errors showed only the error code (e.g. "not_found"),
making it ambiguous whether the field or the value was not found. Now shows
the message (e.g. 'Value "X" not found') when available.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 19:32:28 +03:00
Nick Shirokov 75f56603b6 Merge branch 'dev' 2026-03-14 18:48:05 +03:00
Nick Shirokov 55ab172ba4 feat(web-test): clickElement on tree nodes defaults to select, toggle is explicit
Previously clickElement always toggled expand/collapse on tree nodes.
Now default = select (click text), and { toggle: true } = expand/collapse
(click tree icon). Hint in response guides the model to use toggle when needed.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 18:47:52 +03:00
Nick Shirokov e9e00c906d Merge branch 'dev' 2026-03-14 18:10:41 +03:00
Nick Shirokov 31792a8a2d feat(web-test): search all visible grids for clickElement row targets
Previously findClickTargetScript used querySelector (first grid only),
making clickElement unable to find rows in second+ grids on multi-grid
forms (e.g. system composition wizard). Now uses querySelectorAll to
search all visible grids, and returns gridId so the tree node handler
can locate the correct grid for expand/collapse.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 18:10:25 +03:00
Nick Shirokov fa2e3dd3e7 Merge branch 'dev' 2026-03-14 15:37:21 +03:00
Nick Shirokov 3e8a0a792f fix(web-test): skip includes() fuzzy match for short strings (< 4 chars)
Prevents false positives like "Да" matching "Удаляемые" (group) or
"КомандаУстановитьВсе" (button). Exact and startsWith still work.
Applied to highlight groups, findClickTargetScript buttons/grid-scoped/grid rows.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 15:36:49 +03:00
Nick Shirokov d5e4bc3f21 Merge branch 'dev' 2026-03-14 14:28:37 +03:00
Nick Shirokov 7a6e63078d fix(web-test): commit fillTableRow by clicking grid header instead of data row
Clicking a different data row to exit edit mode re-entered edit on that
row, blocking subsequent button clicks like "Записать". Now the add-path
commit clicks the grid header which cleanly exits edit mode without
re-entering it.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 14:27:08 +03:00
Nick Shirokov 55b0ffa4fd fix(web-test): pass table scope to highlight in clickElement
highlight() was ignoring the table parameter, always highlighting the
first matching button (e.g. "Добавить" for Входящие instead of
Исходящие). Now clickElement passes { table } to highlight, and
highlight pre-resolves the grid via resolveGridScript to pass
gridSelector to findClickTargetScript — same pattern as clickElement
itself.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 14:20:12 +03:00
Nick Shirokov d06ecb940f Merge branch 'dev' 2026-03-14 13:50:52 +03:00
Nick Shirokov 21de2a4749 fix(web-test): strip dashes in fuzzy match for fillTableRow cell names
CamelCase cell IDs like "ИсходящиеБизнесПроцессПриемник" have no
dashes, but user keys like "Бизнес-процесс приемник" do. The previous
regex only stripped spaces, leaving the dash and causing match failure.
Now strip both spaces and dashes with /[\s\-]+/g in both the Tab-loop
path and the row/dblclick column-lookup path.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 13:50:03 +03:00
Nick Shirokov 07be2bcafd fix(web-test): use includes instead of startsWith for grid button id-prefix fallback
Button ids like allActionsРазделыКоманднаяПанель contain gridName
in the middle, not at the start. Using includes() catches both
prefix patterns (ИсходящиеКоманднаяПанель_Добавить) and infix
patterns (allActionsРазделыКоманднаяПанель).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 12:28:50 +03:00
Nick Shirokov 24a48b4a9f fix(web-test): add Группа+name fallback for grid label extraction
On some forms, #title_div is on the parent group element
(e.g. form0_ГруппаБизнесПроцессы#title_div) rather than
on the grid itself. Add fallback lookup for both getFormState
and resolveGridScript.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 12:11:10 +03:00
Nick Shirokov 91b5204ab2 feat(web-test): add visual label support for multi-grid tables
Extract group title text from #title_div DOM elements so tables can be
referenced by their visible on-screen names (e.g. "Входящие") in addition
to technical attribute names. Labels appear in getFormState().tables[] and
resolveGridScript cascade matching (exact name → exact label → contains).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 12:05:23 +03:00
Nick Shirokov f2bd42c54c docs(web-test): add multi-grid forms pattern to SKILL.md
Add "Work with multi-grid forms" section to Common patterns showing
the discover-then-act workflow: getFormState().tables → use table name.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 11:56:46 +03:00
Nick Shirokov 7e56cd79db fix(web-test): skip checkbox columns in row clicks + document table parameter
Row selection clicks in deleteTableRow and fillTableRow commit now target
the second visible gridBox instead of the first, avoiding accidental
checkbox toggles on forms with checkbox columns (e.g. BP links master).

Also documents the new `table` parameter in SKILL.md for readTable,
clickElement, fillTableRow, deleteTableRow, and getFormState tables[].

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 11:48:57 +03:00
Nick Shirokov 1abc44334c feat(web-test): add table parameter for multi-grid forms
Add semantic table binding to readTable, clickElement, fillTableRow,
and deleteTableRow — resolves the correct grid by name when a form
has multiple tables (e.g. "Входящие"/"Исходящие" in BP links).

- New resolveGridScript() in dom.mjs: cascade match by gridName → columns
- findClickTargetScript: scoped button search within grid's parent container
- getFormState: reports all grids via tables[] array (table still present for compat)
- All grids[grids.length-1] fallbacks wrapped in gridSelector ternary

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 11:27:37 +03:00
Nick Shirokov 0ca2faa6a6 feat(web-test): navigateSection newline normalization + fillTableRow cell skip
navigateSection now normalizes \r\n to spaces, so callers don't need
literal newlines in section names. fillTableRow direct-edit path skips
cells that already contain the desired value (method: 'skip').

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 20:05:12 +03:00
Nick Shirokov 767b9fcaf0 fix(web-test): refactor pickFromSelectionForm + fillTableRow for tree grids and row commit
pickFromSelectionForm:
- 3-step escalation: scan visible → simple search → advanced search (Alt+F)
- Extract helpers: scanGridRows, dblclickAndVerify, advancedSearchInline
- dblclickAndVerify uses click+Enter instead of dblclick (dblclick toggles tree groups)
- Returns ok:false when selection form stays open (group/folder not selectable)
- Distinguish not_found vs not_selectable errors
- trySelect wrapper continues escalation on ok:false

fillTableRow direct-edit (tree grids):
- Click → dblclick → F4 escalation for entering edit mode
- F4 from INPUT mode for tree grid ref fields
- isTypeDialog check + pickFromTypeDialog for composite types
- Commit via click on different row instead of Escape (Escape cancels in tree grids)

fillTableRow regular path:
- Commit new row after fill loop by clicking another row or grid header
- Prevents Escape (e.g. from closeForm) from cancelling uncommitted new row
- Fixes accumulated unclosed forms from closeForm failing to close

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 19:10:31 +03:00
Nick Shirokov 598e223288 Merge branch 'dev' 2026-03-13 10:57:23 +03:00
Nick Shirokov f7a27e750d feat(db-load-xml, db-load-git): add -UpdateDB flag to combine load + update in one Designer run
Closes #8 — adds /UpdateDBCfg parameter support so users can load config
and update database in a single 1C Designer invocation instead of two.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:57:15 +03:00
Nick Shirokov 15840ed1ca Merge branch 'dev' 2026-03-13 10:43:12 +03:00
Nick Shirokov 733418e630 fix(db-load-git): normalize ConfigDir with Resolve-Path for reliable Ext/ path matching
FullName returns canonical Windows paths, but ConfigDir could have
forward slashes. Resolve-Path ensures consistent format so the
Replace() in Ext/ recursion always matches.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:43:11 +03:00
Nick Shirokov b15fb999cf Merge branch 'dev' 2026-03-13 10:38:27 +03:00
Nick Shirokov 5414ac373e fix(db-load-git): use --relative for git diff when configSrc is nested
git diff --name-only returns paths relative to repo root, not cwd.
When configSrc is in a subdirectory (e.g. src/cf), paths were doubled
and files not found. Adding --relative makes git return paths relative
to configSrc. Also filter ErrorRecord objects from PS1 git output.

Fixes #7

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:38:06 +03:00
Nick Shirokov 0c4addaedc Merge branch 'dev' 2026-03-13 10:23:22 +03:00
Nick Shirokov cc0d577fc5 fix(cfe-validate): skip own extension sub-items in check 10
Add is_borrowed_sub_item filter to distinguish borrowed vs own
sub-items inside borrowed objects. Own Attributes/TabularSections/
EnumValues (added by extension) lack ObjectBelonging and
ExtendedConfigurationObject — validating them as borrowed was
a false positive. Inspired by PR #6.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:23:14 +03:00
Nick Shirokov 160a845bd8 Merge branch 'dev' 2026-03-12 17:43:17 +03:00
Nick Shirokov 184e4773a4 fix(web-test): clickElement retries when modal form is still loading
After F4/Enter that opens a modal, clickElement could fail because
detectFormScript found the parent form before the modal appeared.
Now retries up to 2s, re-detecting the form each time.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 17:43:06 +03:00
Nick Shirokov 97105486b5 Merge branch 'dev' 2026-03-12 15:44:51 +03:00
Nick Shirokov 23f4cc0bbd fix(web-test): fillTableRow fuzzy match for CamelCase cell names
Cell IDs in 1C tables are CamelCase without spaces (e.g.
"ВариантыАрхитектурыВариантАрхитектуры"), but users pass keys with
spaces ("Вариант архитектуры"). Added space-stripped fallback to
fuzzy match so fillTableRow correctly maps user keys to grid cells.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 15:44:43 +03:00
Nick Shirokov c5c67600b3 Merge branch 'dev' 2026-03-12 15:15:36 +03:00
Nick Shirokov 85191dc759 fix(web-test): prioritize groups over buttons in highlight() search order
Group names often collide with command bar buttons (e.g. "БизнесПроцессы"
matched a tiny 38x35 button instead of the 959x580 panel). Move group
search before button/field search with min-size filter (100x50).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 15:15:16 +03:00
Nick Shirokov 064e42842e Merge branch 'dev' 2026-03-12 15:00:25 +03:00
Nick Shirokov 4507d9b59c feat(web-test): highlight() now finds form groups and panels
Added group/panel search step to highlight() — matches by visible title
or internal name (e.g. highlight('Оргструктура') finds the group container).
Search priority: popups → commands → form elements → groups → sections.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 15:00:15 +03:00
Nick Shirokov 17be0ca009 Merge branch 'dev' 2026-03-12 13:30:07 +03:00
Nick Shirokov 8f59d3bc66 fix(web-test): sync video timeline with wall-clock during static pauses
CDP screencast doesn't send frames for static pages, causing video to be
shorter than real time (gap-fill capped at 2s, smart pauses are 4-6s).

- Add _flushFrames() helper on recorder to write duplicate frames on demand
- Call _flushFrames() every 1s during smart TTS pauses in showCaption
- Call _flushFrames() in wait() for long explicit pauses during recording
- Call _flushFrames() in stopRecording for final gap before closing ffmpeg
- Increase gap-fill cap from fps*2 to fps*30 as safety net

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 13:22:16 +03:00
Nick Shirokov f93a1560a5 fix(web-test): don't treat small data forms as error modals
checkErrorsScript falsely classified small forms (e.g. register record
form opened by "Установить статус") as error modals because they had
< 100 elements + a pressDefault button + staticText. Added input field
check — forms with editInput elements are data entry forms, not errors.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 12:50:18 +03:00
Nick Shirokov 298589d7cc fix(web-test): fix amix silence with many adelay inputs (int64 overflow)
ffmpeg amix + adelay with large delays causes timestamp overflow
(dts near INT64_MAX), producing silent/truncated audio. Fix: use a
silence reference track as first amix input with duration=first,
so amix runs for full video length regardless of delayed stream
timestamps.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 12:21:30 +03:00
Nick Shirokov c6a84e2f91 feat(web-test): smart TTS pause in showCaption + fix addNarration robustness
showCaption now auto-waits for estimated TTS duration during recording
(~100ms/char, min 2s). Subsequent wait() uses credit system to avoid
double-waiting. addNarration: cap atempo at 1.3x (was 2.5x), replace
-shortest with explicit -t to prevent video truncation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 11:59:57 +03:00
Nick Shirokov de7e943de1 fix(cfe-borrow): strip DataPath from AutoCommandBar buttons in borrowed forms
ERP catalog forms (e.g. Номенклатура.ФормаЭлемента) have buttons inside
AutoCommandBar with <DataPath>Объект.Ref</DataPath> — causes "Неверный
путь к данным" on load. DataPath was only stripped from form-level
ChildItems but not from AutoCommandBar.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 09:49:50 +03:00
Nick Shirokov 4855cd1e01 merge: fix borrowed form CommandSet/ExcludedCommand/RowPictureDataPath stripping 2026-03-10 22:06:05 +03:00
Nick Shirokov 7abe26afee fix(cfe-borrow): strip CommandSet, ExcludedCommand and RowPictureDataPath from borrowed forms
ФормаСписка (list forms) contain elements invalid in extensions:
- <CommandSet><ExcludedCommand>Create</ExcludedCommand></CommandSet> at form root
- <ExcludedCommand> in nested AutoCommandBars within ChildItems
- <RowPictureDataPath> in table elements (e.g. Список.СостояниеДокумента)

All three cause "Неверное имя команды элемента формы" on load.
Verified against Configurator reference dump (ref-ext-dump-6).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 22:05:33 +03:00
Nick Shirokov 512562ca50 Merge branch 'dev' 2026-03-10 21:42:52 +03:00
Nick Shirokov 84d078bd05 fix(cfe-borrow,form-edit,cfe-patch-method): fix borrowed form structure to match Configurator
- cfe-borrow: keep AutoCommandBar ChildItems (buttons) with CommandName=0
  instead of stripping them — Configurator expects buttons to be present
- form-edit: insert Events section after AutoCommandBar, not before —
  matches Configurator's element ordering
- cfe-patch-method(py): fix \r\r\n double line endings by using
  newline="" in open() calls

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 21:40:16 +03:00
Nick Shirokov 8584021446 fix(cfe-validate): remove false DataPath/TitleDataPath check from Check 11
Configurator stores DataPath inside <BaseForm> as original form snapshot —
this is normal behavior, not an error. Removes false WARN on
Configurator-exported extensions like JR2433.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 21:00:20 +03:00
Nick Shirokov e7e6c885c7 feat(cfe-validate): add checks 10-13 for deep extension validation
Add sub-item validation (Attribute, TabularSection, EnumValue, Form),
borrowed form structure checks, form dependency analysis (CommonPicture,
StyleItem with platform whitelist, Enum DesignTimeRef), and TypeLink
validation. Fix DataPath false positive by scoping check to BaseForm
content only. Both PS1 and Python ports updated to v1.2.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 20:58:17 +03:00
Nick Shirokov b5a779bd5d fix(cfe-borrow): fix dict key casing in Python auto-borrow (Uuid/Properties)
read_source_object returns keys with capital letters (Uuid, Properties),
but auto-borrow sections for CommonPicture, StyleItem, and Enum used
lowercase. E2E tested: Python port loads into BP_DEMO successfully.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 20:23:34 +03:00
Nick Shirokov 6df64ae1c1 feat(cfe-borrow): full ChildItems form borrowing with auto-borrow dependencies
Borrow-Form now generates full ChildItems tree (matching Configurator output)
with stripping of DataPath, TitleDataPath, TypeLink, Events, CommandName→0.
Auto-borrows CommonPictures, StyleItems, and Enums+EnumValues referenced by
form elements. Verified loading into BP database with two production forms.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 20:18:12 +03:00
Nick Shirokov 007b4ec69c fix(cfe-borrow): mirror minimal Form.xml changes to Python port
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 19:20:36 +03:00
Nick Shirokov cf5eae6428 fix(cfe-borrow): generate minimal Form.xml without ChildItems for borrowed forms
Configurator generates borrowed forms with only properties + AutoCommandBar +
empty Attributes — no ChildItems. ChildItems appear only when modifications are
added via form-edit. Copying full ChildItems caused XDTO errors on complex forms
due to unresolvable references (CommonPicture, StyleItem, xr: namespace elements).

Changes:
- Remove ChildItems extraction and output from Borrow-Form
- Strip ChildItems from AutoCommandBar (keep only Autofill property)
- Both main and BaseForm sections now contain only properties + minimal AutoCommandBar

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 19:19:35 +03:00
Nick Shirokov c72f2210b5 fix(cfe-borrow): strip DataPath, Events and preserve form properties in Borrow-Form
Borrowed forms failed to load with "Неверный путь к данным" and "Событие не было загружено"
errors. Root cause: base form elements contained DataPath and Events referencing attributes
and handlers not present in the extension.

Changes:
- Strip <DataPath> from base elements in both AutoCommandBar and ChildItems
- Strip element-level <Events> from both sections
- Collect form-level properties (AutoTitle, WindowOpeningMode, etc.) and write them
  into both main and BaseForm sections
- Update 1c-extension-spec.md with rules 5-7

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 19:12:24 +03:00
Nick Shirokov 06584c29b2 Merge branch 'dev' 2026-03-09 20:43:43 +03:00
Nick Shirokov d94ffdea99 fix(skd-compile): quote argument-hint to fix YAML frontmatter parsing
Value starting with `[` was interpreted as YAML flow sequence,
breaking frontmatter parsing and the input hint in UI.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 20:43:08 +03:00
Nick Shirokov 9f370dd499 docs(role-validate): remove misleading OutFile hint for Cyrillic paths
Cyrillic stdout works fine — the hint caused weak models to waste
an extra turn writing to file and reading it back.

Verified: all 9 validate skills pass on Haiku in 4 turns each.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 20:30:49 +03:00
Nick Shirokov 903f1f2750 docs(validate): remove redundant ## Использование from all SKILL.md
The section duplicated ## Команда examples in slash-command format that
the model never needs — it receives arguments directly. Second example
paths moved into ## Команда as additional command lines.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 19:25:00 +03:00
Nick Shirokov 29b124f3fd docs(validate): concrete examples in SKILL.md, remove auto-resolve notes
- Replace abstract <...> placeholders with concrete paths in ## Команда
- Replace abstract examples with concrete paths in ## Использование
- Remove авторезолв notes from meta/epf/cf/cfe-validate
- Clean up erf-validate: remove Вывод/Верификация/Когда использовать,
  add -Detailed parameter, unify format with other validators

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 19:17:12 +03:00
Nick Shirokov ffdee04a95 refactor(validate): auto-detect metadata in role-validate, clean up SKILL.md
role-validate: remove MetadataPath param, auto-detect from RightsPath
(Roles/Name/Ext/Rights.xml → Roles/Name.xml). Always validate metadata
when file exists (was 7 checks, now 10). Deduplicate path computation.

SKILL.md: remove redundant auto-resolve notes (placeholder already shows
directory path), fix role-validate examples, replace mxl-validate
ProcessorName/TemplateName with concrete path examples.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 19:07:16 +03:00
Nick Shirokov b2a2534b5a feat(validate): auto-resolve directory paths, fix SKILL.md placeholders
Scripts now accept directory paths (e.g. Forms/ИмяФормы) and auto-resolve
to the target XML file. Silent fallbacks handle missing Ext/ level and
descriptor-to-file resolution. SKILL.md: concrete placeholders, unified
quotes, auto-resolve notes, role-validate MaxErrors in params.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 18:41:38 +03:00
Nick Shirokov 422e397381 feat(validate): brief output by default, -Detailed for verbose
All 10 validation skills (meta, epf, skd, cf, cfe, form, mxl, role,
subsystem, interface) now output a single summary line on success:
=== Validation OK: Type.Name (N checks) ===

Errors/warnings always shown. Full per-check [OK] output behind -Detailed flag.
Removed all N/A check lines. Unified role-validate output format.
Trimmed SKILL.md files from 42-119 to 51-67 lines.
Version bumps: meta-validate v1.2, all others v1.1.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 18:14:44 +03:00
Nick Shirokov 191706b984 Merge branch 'dev' 2026-03-09 15:02:10 +03:00
Nick Shirokov 93e4130ff2 docs(README): update switch.py examples, remove stale src/ line
- Add claude-code --project-dir example for embedded clone workflow
- Remove misleading src/ directory from quick start tree
- Add note about git pull + re-run for updates

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 15:01:02 +03:00
Nick Shirokov 3f091b209c feat(switch): support claude-code install, smart runtime warnings, .gitignore propagation
- switch.py v1.2: `claude-code --project-dir` now copies skills (was error before)
- Skip runtime conversion for single-runtime skills (e.g. img-grid stays python)
- Distinguish info ("Python-версия не предусмотрена") from real missing-file warnings
- Print .gitignore recommendations for target project on install
- Copy root-level .gitignore from skills dir during install
- Interactive mode asks project path for all platforms, not just claude-code
- Add .gitignore in skills root (__pycache__/) and web-test/ (node_modules, *.png, *.mp4)
- Sync root .gitignore with all 13 platforms from PLATFORMS registry

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 14:58:49 +03:00
Nick Shirokov 5d4ee6c58c chore: add debug/ to .gitignore for skill eval artifacts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 13:06:32 +03:00
Nick Shirokov 86c8440531 merge dev: meta-compile v1.2, meta-edit v1.4, batch mode, validation improvements
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 18:46:52 +03:00
Nick Shirokov 42cc7acdbe chore: bump script versions (meta-compile v1.2, meta-edit v1.4)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 18:45:05 +03:00
Nick Shirokov 72a4015a8d fix(meta-compile,meta-edit): sync type handling and validation between scripts
meta-compile: bare Number→Number(10,0), ValueStorage→xs:base64Binary,
lowercase ref synonyms (catalogref, documentref, enumref).
meta-edit: bare String default 0→10, reserved attribute name warnings.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 18:39:18 +03:00
Nick Shirokov 843916642c docs(meta-compile): restructure trigger — types in trigger, shorter description
Move type enumeration from description to trigger clause for better
skill discovery matching. Remove implementation details from description.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 18:09:53 +03:00
Nick Shirokov 84f3662c02 docs(meta-compile): add workflow steps, remove redundant verification section
Add explicit 4-step workflow (write JSON → run script → /meta-edit →
/meta-validate) to guide the model through the optimal path instead of
free exploration. Remove standalone "Верификация" section as it
duplicates workflow step 4.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 17:53:57 +03:00
Nick Shirokov 4cdd3377ae docs(meta-compile): soften reference guidance, prevent XML hunting
- Replace imperative "read reference before compiling" with conditional
  "if you need properties not shown in examples"
- Add explicit instruction not to search for XML in config dumps
- Rename "справочник" → "reference-файл" to avoid confusion with
  Catalog metadata type

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 17:43:04 +03:00
Nick Shirokov 730daf1089 fix(meta-compile): default bare String to String(10), fix SKILL.md examples
Bare `String` type (without length qualifier) now defaults to String(10)
instead of String(0) — matching 1C Designer behavior. String(0) means
unlimited length (NTEXT in SQL), which is rarely intended.

Also fixes SKILL.md: removes misleading `"synonym": "авто"` from JSON
example, clarifies synonym auto-generation from CamelCase name.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 17:18:29 +03:00
Nick Shirokov c0255c71d0 docs(meta-compile): slim down SKILL.md with pattern-based examples
Replace 12 type-specific examples with 5 DSL pattern examples
(minimal, attributes, tabularSections, register, batch).
Strengthen reference file instruction to "прочитай перед компиляцией".
203 → 121 lines. Tested on Opus and Sonnet — both pass e2e.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 16:45:01 +03:00
Nick Shirokov cf1cd1a711 docs(meta-compile): add progressive disclosure reference files
Replace monolithic docs/meta-dsl-spec.md link with 4 domain-specific
reference files inside the skill directory. Agent reads only the
relevant file when compiling a specific type, reducing context usage.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 16:12:49 +03:00
Nick Shirokov 5a1974be4e fix(meta-compile): parse shorthand syntax for Task AddressingAttributes
AddressingAttribute was taking the entire shorthand string (e.g.
"Name: String(100)") as the attribute name instead of parsing it
through Parse-AttributeShorthand. This caused String type without
length qualifiers (NTEXT in SQL), making Index creation impossible.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 13:47:38 +03:00
Nick Shirokov 589091510b feat(meta-compile): add batch mode — JSON array in single file
Support passing a JSON array of object definitions in a single file.
Each element is compiled independently via subprocess isolation
(Start-Process in PS1, subprocess.call in PY).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 13:21:32 +03:00
Nick Shirokov 19667caccb feat(meta-validate): add batch mode — pipe-separated paths
Accept multiple object paths via pipe separator (|) in -ObjectPath.
Each object is validated separately with individual results, followed
by a summary line: "Batch: N objects, X passed, Y failed".
Single-path mode unchanged. Version bumped to v1.1.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 12:38:21 +03:00
Nick Shirokov 97fc6dbd7f refactor(meta-compile): extract Build-TypeStr helper for type+length combination
Unify inline type string building logic (type + length/precision → "String(100)",
"Number(10,2)") into a shared Build-TypeStr/build_type_str function. Used by both
Parse-AttributeShorthand and Emit-ConstantProperties. Fix: check valueType before
type to avoid treating metadata type name (e.g. "Constant") as data type.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 12:13:46 +03:00
Nick Shirokov 49108f72dc docs(meta-dsl-spec): update to v2.1 — reflect e2e-verified fixes
- §4.2: document separate type+length/precision fields in object form
- §7.4 Constant: add length/precision fields
- §7.7 DefinedType: document valueType (singular) alias
- §7.9 ScheduledJob: document CommonModule. auto-prefix for methodName
- §7.10 EventSubscription: document CommonModule. auto-prefix for handler
- §7.13 ExchangePlan: remove codeType/autonumbering/checkUnique (not valid)
- §7.14 ChartOfCharacteristicTypes: default String length 0→100
- §7.20 BusinessProcess: add task to example

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 11:18:52 +03:00
Nick Shirokov dbb39b7a3e fix(meta-compile): fix String/Number length loss, RegisterRecords format, CommonModule prefix
- Parse-AttributeShorthand: combine type + length/precision from separate
  JSON fields (String→String(N), Number→Number(D,F)) — fixes SDBL error
  "Строка без спецификации длины недопустима"
- Constant valueType: same length combination fix
- DefinedType: accept both valueType (singular) and valueTypes (plural)
- ChartOfCharacteristicTypes: default String length 0→100
- Document RegisterRecords: <xr:Record> → <xr:Item xsi:type="xr:MDObjectRef">
- ScheduledJob.MethodName, EventSubscription.Handler: auto-prepend CommonModule. prefix
- meta-validate check 13: support 3-part method format (CommonModule.Module.Proc)

E2E verified: 18 types (21 objects) pass cf-init → meta-compile → LoadConfigFromFiles → UpdateDBCfg

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 11:05:29 +03:00
Nick Shirokov 87dc18b120 feat(meta-validate): add method reference and DocumentJournal column checks
Check 13: validates EventSubscription.Handler and ScheduledJob.MethodName
reference format (CommonModuleName.ProcedureName), verifies CommonModule
exists and optionally checks BSL for exported procedure.

Check 14: validates DocumentJournal Column References are non-empty
(empty References causes LoadConfigFromFiles to fail).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 22:08:46 +03:00
Nick Shirokov ca328e3e8f feat(meta-validate): add cross-object register-registrar check
Detect configDir by walking up from object path to find
Configuration.xml. For AccumulationRegister, AccountingRegister,
CalculationRegister, and InformationRegister (RecorderSubordinate) scan
Documents/*.xml to verify at least one document references the register
in RegisterRecords. Warn if no registrar found.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 22:00:37 +03:00
Nick Shirokov c2b90a97ef feat(meta-validate): add forbidden property and DocumentJournal checks
Check 12: detect properties that are invalid for a given metadata type
and would cause LoadConfigFromFiles to fail:
- ChartOfCharacteristicTypes: CodeType
- ChartOfAccounts: Autonumbering, Hierarchical
- ChartOfCalculationTypes: CheckUnique, Autonumbering
- ExchangePlan: CodeType, CheckUnique, Autonumbering

Check 10 extensions:
- DocumentJournal: warn on empty RegisteredDocuments
- Add DependenceOnCalculationTypes to enum validation (Check 4)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 21:49:57 +03:00
Nick Shirokov e717d4a57f fix(meta-compile): remove invalid properties from ChartOf* types
ChartOfCharacteristicTypes: remove CodeType (not a valid property).
ChartOfAccounts: remove Autonumbering, Hierarchical (not valid).
ChartOfCalculationTypes: remove CheckUnique, Autonumbering (not valid),
fix DependenceOnCalculationTypes default from NotUsed to DontUse.

Verified against real ACC 8.3.24 dumps. E2E test passed:
cf-init → meta-compile ×18 → LoadConfigFromFiles → UpdateDBCfg.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 21:43:21 +03:00
Nick Shirokov 6051972391 fix(meta-compile,meta-validate): fix 7 e2e bugs, add hints and reserved name checks
Group 1: ExchangePlan — remove invalid CodeType/CheckUnique/Autonumbering;
Flowchart.xml — add version="2.17"; Content.xml — fix namespace + version.

Group 2: Add missing GeneratedType categories — DefinedType, ChartOfAccounts
ExtDimensionTypes/Row, CalculationRegister RecalculationsManager/Recalcs.

Group 3: BusinessProcess — emit <Task> property from DSL.

Group 4: Cross-reference [HINT] output after compilation for AccountingRegister,
CalculationRegister, BusinessProcess, ChartOfAccounts (oriented to /meta-edit DSL).

Group 5: Reserved attribute name warnings in meta-compile and meta-validate
(Check 7b); cross-reference validation in Check 10 with [HINT] output.

All changes synced to both PS1 and PY versions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 21:33:56 +03:00
Nick Shirokov 24751a59de docs(epf-guide): clarify register column category limitation
Explain why stub database may lose DataPath bindings when forms
contain register record sets — source XML lacks dimension/resource/
attribute classification for register fields.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 21:06:28 +03:00
Nick Shirokov b824759a05 docs(skills): remove redundant description paragraphs from epf/erf skills
The intro paragraph on line 14 duplicated the frontmatter description
field. Per Anthropic best practices, the body should contain only
implementation details — the heading and frontmatter are sufficient.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 20:53:13 +03:00
Nick Shirokov fb23cbda56 docs(skills): remove cross-references between epf/erf skills
Drop "см. /erf-*" from epf-build/epf-dump and "Использует общий скрипт
из /epf-*" from erf-build/erf-dump to prevent the model from reading
duplicate skill files and wasting context.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 20:50:14 +03:00
Nick Shirokov 69c89d3d70 fix(meta-compile,stub-db-create): add missing GeneratedType categories
Add 6 missing categories to meta-compile (ps1+py):
- AccountingRegister: ExtDimensions
- ChartOfCharacteristicTypes: Characteristic
- ChartOfCalculationTypes: DisplacingCalculationTypesRow, BaseCalculationTypesRow, LeadingCalculationTypesRow
- BusinessProcess: RoutePointRef

Fix incorrect category name in stub-db-create (ps1+py):
- AccountingRegisterExtDimensionTypes/ExtDimensionTypes → AccountingRegisterExtDimensions/ExtDimensions

Add GeneratedType reference table to 1c-config-objects-spec.md (section 29).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 20:24:31 +03:00
Nick Shirokov dee85e19d5 docs: update build-spec and epf-guide for auto-stub and dump requirements
- build-spec: replace outdated notes about empty base with auto-stub info
- build-spec: add dump notes about irreversible type loss in empty base
- epf-guide: add build/dump section explaining auto-stub and base requirement

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 19:40:25 +03:00
Nick Shirokov 87348ec73c docs(skills): add trigger descriptions, remove redundant sections, fix paths
- Add "Используй когда..." triggers to epf-build, epf-dump, erf-build, erf-dump
- Remove "Коды возврата" sections (trivial info Claude already knows)
- Remove Hierarchical tree diagrams from dump skills (Claude sees output directly)
- Fix Windows backslashes to forward slashes in examples

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 19:35:08 +03:00
Nick Shirokov dd81c85366 fix(stub-db-create): warn about guessed register column categories
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 19:13:31 +03:00
Nick Shirokov c6f499a099 feat(stub-db-create): scan Form.xml for register column names
Parse form attributes of RegisterRecordSet types and extract column
names from DataPath references. Generate matching Dimension/Attribute
stubs in register metadata so form field bindings survive the build.

Limitation: column categories (Dimension vs Resource vs Attribute)
cannot be determined from EPF sources alone — only names are preserved.

Also add /Out log for UpdateDBCfg errors in both PS1 and PY.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 19:10:10 +03:00
Nick Shirokov b5826a61c4 docs(epf-dump,erf-dump): mark database connection as required
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 18:35:44 +03:00
Nick Shirokov 3097811dde fix(epf-dump): require database connection, remove auto-create empty base
Dump in an empty database irreversibly loses reference types (CatalogRef,
DocumentRef, etc.) — they get converted to xs:string. Instead of silently
creating an empty temp database, the script now exits with an error
explaining that a real database is required.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 18:34:32 +03:00
Nick Shirokov f01f9d6ae8 feat(epf-build): auto-create stub database for EPF/ERF with reference types
Add stub-db-create script (.ps1/.py) that scans EPF XML sources for
reference types (CatalogRef, DocumentRef, EnumRef, etc.) and generates
a minimal 1C configuration with metadata stubs. Supports 14 metadata
types including registers, charts, defined types.

epf-build/erf-build: if no database specified, auto-create stub DB
with matching metadata, build EPF, then cleanup temp DB.

epf-dump/erf-dump: if no database specified, create empty DB with
warning that reference types will be converted to strings.

SKILL.md updated: prefer real database from .v8-project.json first,
fall back to auto-created stub only when unavailable.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 18:27:38 +03:00
Nick Shirokov 0a1f8888dc feat(form-compile,form-edit): add type synonym resolution for resilient DSL
Add Resolve-TypeStr/resolve_type_str to form-compile and form-edit (PS+PY)
that silently normalizes Russian type names (Строка→string, Число→decimal,
Булево→boolean, etc.), Number→decimal alias, and Russian reference prefixes
(СправочникСсылка→CatalogRef, etc.). Also accept + as composite type
separator alongside |. This makes form skills more forgiving when the model
uses meta-compile DSL conventions instead of form-specific ones.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 15:47:15 +03:00
Nick Shirokov 66eb0b19ec Merge dev-web: composite types, d5p1 namespace, IndentationError fixes
- meta-edit/meta-compile: composite types via + separator (PS+PY)
- d5p1 namespace for reference types instead of cfg:
- lxml post-processing fix for d5p1 in meta-edit PY
- meta-info/form-info: normalize d5p1 prefix in readers (PS+PY)
- Fix module-level IndentationError in 10 Python scripts
2026-03-05 14:01:18 +03:00
Nick Shirokov 872675652f fix: normalize d5p1 namespace in info scripts and fix Python IndentationErrors
- meta-info, form-info (PS+PY): recognize dNpN: prefix alongside cfg: in type parsing
- Fix module-level sys.stderr.reconfigure indentation in 9 Python scripts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 12:08:07 +03:00
Nick Shirokov fde6d346d7 feat(meta-compile): support composite types and fix d5p1 namespace
- Add composite type support via + separator in Emit-TypeContent (PS/PY)
- Fix reference types: cfg: → d5p1: with local xmlns declaration
  in Emit-TypeContent, valueTypes loop, EventSubscription source
- Fix lxml stripping xmlns:d5p1 in meta-edit.py save_xml (post-process)
- Fix IndentationError in meta-compile.py and meta-validate.py
- Document composite type syntax in SKILL.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 12:00:09 +03:00
Nick Shirokov 4490aeb533 feat(meta-edit): support composite types via + separator
Build-TypeContentXml / build_type_content_xml now detect " + " in type
string, split into parts and recursively generate separate <v8:Type>
entries with qualifiers for each type. JSON DSL supports type as array.

Also fix reference types to use local xmlns:d5p1 declaration instead of
root-level cfg: prefix — prevents "Неизвестное имя типа" build errors.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 11:32:59 +03:00
Nick Shirokov 6958cc558b perf(web-test): detect .confirm notification for early exit in clickElement
Add .confirm CSS selector to the server-response waitForSelector in
clickElement. 1C web client shows notifications (Изменение/Проведение)
as .confirm elements after write/post operations. This allows early
exit instead of waiting the full 10s timeout. Записать: 14s → 2.6s.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 08:58:21 +03:00
Nick Shirokov 8a286d7191 perf(web-test): skip 10s server-wait for grid edit buttons in clickElement
When clicking toolbar buttons like "Добавить" that put focus into a grid
INPUT cell, skip the 10-second waitForSelector for modal/balloon since
no server round-trip is expected. Also replace fixed waits with polling
in fillTableRow add/row paths. Total: 121s → 62s on composite test suite.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 08:44:52 +03:00
Nick Shirokov a5fa730747 perf(web-test): replace fixed waits with polling in type-direct flow
Replace hardcoded waitForTimeout calls with polling loops that check
DOM state and exit early. Saves ~12s on composite-type test suite.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 08:33:02 +03:00
Nick Shirokov 53219cae6c fix(web-test): handle calculator/calendar popups and type inheritance in fillTableRow
When filling composite-type cells (String+Number+Date), the previous code
tried paste first and only fell back to type selection if paste was rejected.
This failed when rows inherited a type from previous rows — paste succeeded
but the value was silently converted to the wrong type.

Now when { value, type } is specified:
1. Always clear the cell first (Shift+F4) to reset inherited type
2. Open type dialog (F4) and select the requested type
3. Dismiss calculator/calendar popups with Escape
4. Re-enter edit mode if focus was lost, then paste the value

Tested with primitive types (Число/Строка/Дата) and reference types
(Физическое лицо via selection form). Regression-tested existing
composite-type flow in Операции.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 08:16:37 +03:00
Nick Shirokov b1187865ec feat(web-test): support composite-type fields in fillTableRow
Cells accepting multiple types (e.g. subconto on account 80.01) now
handled via { value, type } syntax. Paste rejection detected
automatically — F4 opens type dialog, picks type, then selects value
from the catalog form.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 22:18:27 +03:00
Nick Shirokov 22bf17ee00 feat(web-test): support per-field search in selectValue via object syntax
selectValue now accepts search as object { field: value } for per-field
disambiguation in selection forms. All fields use advanced search (Alt+F)
by specific column — more efficient than simple full-text search on large
tables, and navigates to exact row even in virtual grids.

Also fixes filterList modal cleanup: now checks specific dialog form
instead of generic modalSurface, preventing accidental closure of
parent modal forms (e.g. selection forms).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 20:59:07 +03:00
Nick Shirokov 2e0dcb773b fix(web-test): detect ambiguous type matches in selectValue
When multiple types match the search term in the type selection dialog,
throw a descriptive error listing all matches instead of silently
picking the first one. This prevents the model from getting a misleading
"not found" error when the wrong type was selected.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 20:08:35 +03:00
Nick Shirokov c958f3f818 feat(web-test): support composite-type fields in selectValue
Add `{ type }` option to selectValue for fields that accept multiple
types (e.g. DocumentRef.*). When specified, selectValue navigates
through the type selection dialog via Ctrl+F search before opening
the value selection form. Auto-detects composite fields when type
is not specified and throws a helpful error message.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 19:51:08 +03:00
Nick Shirokov 684e97e518 docs(web-test): document icon-only section panel limitation
navigateSection() now gives a clear error message when the section
panel is in icon-only mode instead of a confusing "not found" error.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 15:09:16 +03:00
Nick Shirokov ce5651a5d7 feat(switch): add Windsurf, Kilo Code, Cline, Roo Code, Augment, Agent Skills platforms
Add 6 new platforms to switch.py (v1.0 → v1.1), total 13.
All follow the open Agent Skills standard (agentskills.io).
Update README with full platform table and agentskills.io reference.

Closes #4

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 16:56:02 +03:00
Nick Shirokov e706aca958 Merge branch 'dev-web' 2026-03-03 14:35:55 +03:00
Nick Shirokov 90b3d5d2e9 fix(web-test): require Message element for confirmation detection
Forms with multiple buttons but no form{N}_Message element were
falsely detected as confirmation dialogs. Real 1C confirmations
(Да/Нет) always have a Message element. Now skip forms without it.

Fixes false positives on small EPF forms with custom buttons.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 14:29:57 +03:00
Nick Shirokov 1b37bad331 docs(web-test): add openFile to testing guide
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 14:21:05 +03:00
Nick Shirokov 8b0664b18d fix(web-test): avoid confusing small EPF form with info dialog in openFile
Check form change before checkForErrors() to prevent misidentifying
a small EPF form (< 20 elements) as an informational modal dialog.
Only call checkForErrors() on suspiciously tiny new forms.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 14:19:24 +03:00
Nick Shirokov 2af73d25bf fix(web-test): handle follow-up info dialog after security confirmation in openFile
After clicking "Да" on the security confirmation, check for a second
informational modal ("please re-open the file"). If present, dismiss it
and retry the full Ctrl+O → filechooser cycle.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 14:17:33 +03:00
Nick Shirokov 449e2f667e feat(web-test): add openFile() for opening external processors (EPF/ERF)
Opens EPF/ERF files via Ctrl+O → 1C file dialog → native file picker.
Handles security confirmation dialog with up to 2 attempts for re-open.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 14:11:43 +03:00
Nick Shirokov e032143157 Merge branch 'dev-web': TTS narration, ElevenLabs provider, video recording guide, v8-project reference 2026-03-03 13:18:24 +03:00
Nick Shirokov 09fc3a7f43 docs(v8-project): note that file is in .gitignore due to secrets
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 13:16:45 +03:00
Nick Shirokov 01315839fb docs: add .v8-project.json reference guide
Consolidate project config documentation into a single guide covering all
fields (v8path, databases, webPath, ffmpegPath, tts, webUrl), with "who fills"
column and resolution algorithm. Replace duplicated format sections in
db-guide.md and web-guide.md with links to the new guide.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 13:14:08 +03:00
Nick Shirokov 6505fb1986 docs(web-test): update TTS provider recommendations with ElevenLabs findings
Recommend professional voices with educational/business profile (Olga, Artem,
Denis) for ElevenLabs Russian content. Note articulation issues with
multilingual model on Russian terminology (stress, vowel quality).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 12:55:12 +03:00
Nick Shirokov 9e022c60f9 docs(web-test): add TTS provider recommendations to recording guide
Edge TTS recommended for Russian (better stress, intonation, semantic accents),
ElevenLabs for English/multilingual content (less robotic timbre).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 12:19:23 +03:00
Nick Shirokov e23a235ffa fix(web-test): limit ElevenLabs TTS concurrency to 2 and improve error logging
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 12:10:01 +03:00
Nick Shirokov 5bccca2475 feat(web-test): add ElevenLabs TTS provider
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 11:15:36 +03:00
Nick Shirokov a8d8007846 docs(web-test): update stopRecording return type in recording.md
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 11:00:03 +03:00
Nick Shirokov 37d2a5ee15 docs(web-test): add video recording guide for users
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 10:58:27 +03:00
Nick Shirokov 050d42a457 fix(web-test): use video-time timestamps for precise TTS sync
Caption timestamps now use actual video timeline position (frame
counter) instead of wall-clock time, eliminating sync drift from
non-uniform frame duplication in CDP screencast recordings.

Also replace silence-file concatenation with adelay+amix for
sample-accurate TTS placement, and fix exec timeout for long
scenarios (fetch → http.request with 10min timeout).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 10:13:32 +03:00
Nick Shirokov 5acb586bbf fix(web-test): fix audio-video sync drift in narration
Screencast frame duplication (Math.round) causes video to be ~5% longer
than wall-clock time. Caption timestamps are wall-clock based, so the
audio track drifted ahead by ~8s at the midpoint of a 5-minute video.

Fix:
- stopRecording() saves recordingDuration in captions.json
- addNarration() reads actual video duration via ffprobe and scales
  caption timestamps by videoDuration/recordingDuration ratio
- Phase 2 timeline now tracks actual cumulative position instead of
  computing gaps from previous caption data (prevents MP3 frame
  quantization drift)
- Also fixed findFfmpeg() → resolveFfmpeg() call in addNarration

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 00:45:30 +03:00
Nick Shirokov 7f6ea32533 refactor(web-test): add resolveEdgeTts() with fallback chain
Mirrors resolveFfmpeg() pattern: tries global/project-level import
first, then tools/tts/node_modules/, then throws error with install
instructions. Caches resolved module for subsequent calls.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 00:03:16 +03:00
Nick Shirokov e9b53505ac fix(web-test): move TTS to tools/tts/, use atempo instead of trimming
- node-edge-tts installed in tools/tts/ (alongside tools/ffmpeg/)
- Speed up TTS with ffmpeg atempo when it exceeds gap to next caption,
  instead of hard-cutting the audio

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 23:46:50 +03:00
Nick Shirokov 6ce36f7d9b fix(web-test): resolve node-edge-tts from tools/node_modules
Dynamic import needs file:// URL on Windows and explicit entry point
for ESM resolution. Package installed in tools/ alongside ffmpeg.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 23:29:56 +03:00
Nick Shirokov a13f16e49d feat(web-test): add TTS narration for video recordings
showCaption() collects captions with optional speech parameter,
stopRecording() saves .captions.json, addNarration() generates
TTS voiceover (Edge TTS or OpenAI) and merges audio with video.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 23:10:37 +03:00
Nick Shirokov 8f130f2e83 docs: update project description in README
Reflect the full development cycle the project now covers: from XML
artifacts to database management, web publishing, browser testing,
and video recording.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 20:34:42 +03:00
Nick Shirokov 26ea09e2ff fix(web-test): correct video color range for H.264 players
JPEG full range (0-255) was tagged as pc/full in H.264 output, but most
players (VLC, etc.) expect limited range (16-235). Convert JPEG→limited
with scale filter and tag as tv. Also switch preset ultrafast→fast for
5-6x smaller files on static screen content.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 20:05:32 +03:00
Nick Shirokov 98c416b5a7 fix(web-test): highlight commands before form elements
When the function panel is open over a form, highlight() was finding
buttons from the hidden form instead of visible commands on the panel.
Move command search (cmd_XXX_txt) to step 1 — before form-scoped
search — so visible panel commands always take priority. Form elements
searched at step 2 only if no command matched.

Highlight search order is now:
0. Open submenu/popup (elementFromPoint overlay)
1. Commands on function panel (visible cmd_ elements)
2. Form elements (buttons, fields, grid rows)
3. Sections (sidebar navigation)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 19:14:26 +03:00
Nick Shirokov 98ece6206e fix(web-test): add startsWith matching to findClickTargetScript
The button/link search in findClickTargetScript jumped from exact
to includes matching, causing "Поступление" to match "Поступление
билетов" instead of "Поступление (акты, накладные, УПД)" when the
shorter name appeared first in DOM order. Add startsWith step for
both name and label between exact and includes matching.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 19:03:34 +03:00
Nick Shirokov 0c0a1aea49 docs: add Kiro to supported platforms in README
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 20:43:24 +03:00
Nikolay-Shirokov 5870fa200f Merge pull request #3 from JohnyDeath/main
Добавлена Kiro в switch.py
2026-03-01 20:38:17 +03:00
Nick Shirokov 7c10e5e4b1 fix(web-test): highlight submenu items and command startsWith matching
- Add submenu/popup as priority 0 in highlight() — checks open
  popups before form search, preventing false matches on grid rows
  behind the popup overlay
- Use elementFromPoint + direct overlay for submenu items instead
  of getElementById (1C duplicates IDs in cloud popups — hidden
  copy in form + visible copy in cloud)
- Add startsWith step between exact and includes for section and
  command matching — fixes "Поступление" matching "Поступление
  билетов" instead of "Поступление (акты, накладные, УПД)"

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 18:06:20 +03:00
Nick Shirokov 665d5579d2 docs(web-test): add highlight API to recording docs and guides
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 15:06:12 +03:00
Nick Shirokov 0fec18bbc4 fix(web-test): unhighlight fillFields before Tab, not after
Move unhighlight() before the fill action in fillFields — prevents
our overlay staying visible while platform focus moves to next field
on Tab/Enter. Consistent with clickElement/selectValue pattern:
highlight → wait → unhighlight → action.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 14:34:06 +03:00
Nick Shirokov cc751a344e fix(web-test): fix highlight bugs — search priority, modal overlap, section/command support
- Reorder highlight() search: form elements first, sections/commands as
  fallback. Fixes false match where "ОК" matched section "Покупки" via
  substring .includes() ("пок" contains "ок")
- Unhighlight before action in clickElement/selectValue (was only in
  finally block, causing overlay to cover modals opened by the click)
- Add auto-highlight support to navigateSection and openCommand

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 14:26:49 +03:00
Nick Shirokov f956749e1e feat(web-test): add element highlighting for video recordings
Add highlight/unhighlight/setHighlight/isHighlightMode functions.
Overlay div tracks element position via requestAnimationFrame — follows
layout shifts from async banner loads. Search order: sections → commands
→ buttons/links → fields → grid rows. Auto-highlight mode integrates
with clickElement, fillFields, selectValue.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 13:47:29 +03:00
Nick Shirokov 2a6f4b1d5f fix(web-test): correct video brightness via color_range flag
JPEG frames from CDP screencast use full range (0-255) but H.264
defaults to limited range (16-235). Add -color_range pc to preserve
full range in output MP4, fixing washed-out/bright appearance.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:32:39 +03:00
Nick Shirokov 9318d05535 docs(web-test): fix caption timing pattern in recording example
Show caption before action with wait() pause, not after.
Viewer reads what will happen, then sees it happen.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:33 +03:00
Nick Shirokov bb07bfae14 feat(web-test): add showTitleSlide/hideTitleSlide for video intros
Full-screen overlay with gradient background, centered title text,
optional subtitle. Useful for intro/outro frames in video recordings.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 11:50:25 +03:00
Nick Shirokov 38c82f4a2f docs(web-test): update error handling and ё normalization notes
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 10:34:55 +03:00
Nick Shirokov d5fa5349d4 fix(web-test): ё/е normalization, DLB intercept fix, throw on errors
Three improvements to browser automation reliability:

1. ё→е normalization: fuzzy matching now treats ё and е as equivalent
   across all comparison points in both dom.mjs (norm() functions,
   target variables) and browser.mjs (popup, radio, EDD, grid, confirmation
   dialog, advanced search, filter badges). Prevents silent failures when
   script uses ё but 1C displays е or vice versa.

2. DLB intercept handling in selectValue(): added force click + Escape
   fallback when funcPanel overlay blocks the dropdown button click,
   matching the pattern already used in clickElement().

3. Error handling: all exported functions now throw Error instead of
   returning { error } objects. Error messages include function name,
   what was searched, and available alternatives. Scenarios fail fast
   at the broken step; interactive callers can use try/catch.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 10:33:19 +03:00
Evgeny Martynenkov ebc63c0264 Добавлена Kiro в switch.py 2026-03-01 00:21:33 +03:00
Nick Shirokov 99a5c7168a fix(web-test): real-time video playback via frame duplication
CDP screencast sends frames only on screen changes, causing ffmpeg
to compress pauses and produce sped-up video. Now duplicates the
previous frame to fill timing gaps, maintaining real-time speed.
Also add *.mp4 to .gitignore alongside *.png.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 21:30:46 +03:00
Nick Shirokov 751a6a8f12 fix(web-test): update ffmpeg download links and clarify prerequisites
Use direct gyan.dev URL instead of generic ffmpeg.org. Rewrite recording.md
prerequisites as clear alternatives (project / global / config).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 21:04:31 +03:00
Nick Shirokov 43a2691d6a feat(web-test): add video recording via CDP screencast + ffmpeg
New functions: startRecording, stopRecording, isRecording, showCaption, hideCaption.
Recording guide in recording.md with setup, API, examples, troubleshooting.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 20:49:47 +03:00
Nick Shirokov e6da514b67 chore(web-test): add source header comments to all scripts
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 19:32:39 +03:00
Nick Shirokov 1e5c42fa56 docs: clarify auto-activation as primary usage mode in platform table
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 19:09:58 +03:00
Nick Shirokov 59627b0699 merge: dev-switch → main — unified cross-platform switch.py 2026-02-28 19:06:32 +03:00
Nick Shirokov 7b69228d23 feat: add unified switch.py for cross-platform skill porting
Single script to copy skills between AI platforms (Cursor, Codex,
Copilot, Gemini CLI, OpenCode) with path rewriting and optional
runtime switching. Includes interactive mode for newcomers.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 19:05:12 +03:00
Nick Shirokov da0cedf256 docs: fix web-test description — interaction with web client, not browser automation
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 18:24:01 +03:00
Nick Shirokov cc6b170488 docs(web-test): restructure guide — scenarios first, then technical details
User-facing examples and use cases at the top (navigation, search,
documents, reports, extensions, debugging), followed by modes explanation,
autonomous scenario example, then API reference tables.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 18:12:28 +03:00
Nick Shirokov f9439dce6d docs(web-test): expand guide with detailed API, modes, and complex scenario
- Detailed description of autonomous vs interactive modes with examples
- Full API reference with signatures, return shapes, and code samples
- Complex autonomous scenario: compare stock reports across two warehouses
- Troubleshooting table for common errors
- Keyboard shortcuts reference

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 18:05:35 +03:00
Nick Shirokov 336466ae82 merge: dev-web → main — web-test browser automation skill 2026-02-28 17:59:24 +03:00
Nick Shirokov 59d223d72b docs: add web-test guide and README entry
- New docs/web-test-guide.md with usage scenarios, API overview, DCS filters
- README: add web-test row to skills table, directory structure, Node.js requirement

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 17:55:59 +03:00
Nick Shirokov f56f5dc849 docs(web-test): add anti-loop guidelines to SKILL.md
Prevent models from endlessly retrying the same failed search.
Rules: max 2 attempts per approach, try alternatives not repeats,
report partial results instead of silent retry.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 17:53:04 +03:00
Nick Shirokov 1fd3d8ffb8 docs(web-test): rewrite SKILL.md following Anthropic best practices
- Structured API reference with signatures, return types, and inline examples
- Added readSpreadsheet structured format (title, headers, data, totals)
- Added readTable pagination, tree, hierarchy documentation
- Added DCS reportSettings and human-readable labels for fillFields/selectValue
- Added decision guides (when to use which reading/closing method)
- Progressive disclosure: quick start → modes → API → patterns → notes

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 17:49:40 +03:00
Nick Shirokov d6befb0dc8 feat(web-test): DCS report settings — human-readable labels for fillFields/selectValue/getFormState
fillFields({ 'Склад': 'value' }) now auto-resolves via DCS pair label
and auto-enables the checkbox. getFormState() returns reportSettings
array with readable names instead of raw КомпоновщикНастроек... fields.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 17:05:16 +03:00
Nick Shirokov 5120b135f5 fix(web-test): use e1cib/app/ for reports and data processors
Reports and DataProcessors need e1cib/app/ prefix (opens app form),
while lists/registers/catalogs use e1cib/list/ (opens list form).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 16:38:21 +03:00
Nick Shirokov 5d18bf4501 fix(web-test): scope readSpreadsheet to current form, improve headers
Two fixes:
- Scope iframe scanning to current form container (prevents reading
  stale data from other open report tabs)
- Improved header detection: use LAST row before data as detail header,
  previous row as group header with fill-forward for merged cells.
  Fixes two-level headers like "Начальный остаток / Долг клиента"

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 16:34:42 +03:00
Nick Shirokov 366378c4b5 feat(web-test): structured readSpreadsheet with header detection
Parse SpreadsheetDocument into { title, meta, headers, data, totals }:
- Auto-detect header row (most non-empty before first numeric row)
- Group header prefix for duplicate column names (Сейчас/Доступно)
- Data rows as objects {column: value}, only non-empty cells
- Separate totals row (Итого/Всего)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 16:17:40 +03:00
Nick Shirokov 56203e2b71 feat(web-test): add readSpreadsheet() for extracting report data
Reads 1C SpreadsheetDocument (report output) rendered in iframes.
Collects cells from div[x]/div[y] elements across all frames,
returns { rows: string[][], total }.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 16:07:19 +03:00
Nick Shirokov ff14880871 docs(web-test): simplify navigateLink examples in SKILL.md
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 15:48:12 +03:00
Nick Shirokov a17a81fe98 feat(web-test): normalize navigateLink URLs
- Auto-prepend e1cib/list/ when missing
- Translate English type names to Russian (AccumulationRegister → РегистрНакопления, etc.)
- Accepts: full e1cib/..., short Тип.Имя, or English Type.Имя

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 15:46:30 +03:00
Nick Shirokov e58f5c1f82 feat(web-test): add navigateLink() for direct 1C navigation links
- navigateLink(url): opens form via Shift+F11 dialog with clipboard paste
- Grant clipboard-read/write permissions on browser context creation
- Register navigateLink in ACTION_FNS for auto-error detection
- Document in SKILL.md with examples (e1cib/list/...)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 15:37:58 +03:00
Nick Shirokov 0fbdd298ca docs(web-test): improve SKILL.md API discoverability
- getFormState: clarify returns table meta (columns + rowCount), not row data
- readTable: document return shape, add hint to use for grid contents
- closeForm: document {save} parameter and auto-confirm behavior
- Update closing forms patterns with save:true/false/omit variants

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 15:17:05 +03:00
Nick Shirokov 68fd9bb4a7 feat(web-test): closeForm({ save }) auto-handles confirmation dialog
closeForm now accepts { save: true/false } option:
- save: false → clicks "Нет" on "Save changes?" dialog
- save: true  → clicks "Да" to save and close
- undefined   → returns confirmation as hint (previous behavior)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 15:06:19 +03:00
Nick Shirokov e18e8cd284 fix(web-test): auto-dismiss pending error modals before actions
Action functions now call dismissPendingErrors() at start, so a leftover
error modal from a previous operation doesn't block subsequent actions.
Diagnostic functions (getFormState, screenshot) are unchanged — they
show current state as-is.

Key fixes:
- Target OK button within modal's form container (#formN_container)
  to avoid clicking wrong pressDefault on the page
- Use force:true click to bypass #modalSurface pointer intercept
- Replace local dismissErrors() in fillReferenceField with shared fn

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 15:02:29 +03:00
Nick Shirokov 5ea6414585 fix(web-test): detect modal errors without #modalSurface dependency
1C platform shows some modal dialogs (e.g. "Не удалось записать") via
ps*win floating windows WITHOUT setting #modalSurface visible. Removed
the modalSurface gate from checkErrorsScript — now scans all small forms
for button patterns regardless of overlay state. The elCount > 100
threshold already filters content forms reliably.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 13:57:18 +03:00
Nick Shirokov 75558fe46c fix(web-test): detect server-side errors via waitForSelector and ancestry-based button grouping
Two problems solved:
1. Server-side exceptions (ВызватьИсключение in ПередЗаписью) produce modal dialogs
   AFTER the DOM stabilizes. clickElement now uses waitForSelector with MutationObserver
   (doesn't block JS event loop) to detect #modalSurface or .balloon appearance.
2. checkErrorsScript used button IDs to determine form ownership, but 1C modal dialog
   buttons often have empty IDs. Now uses closest('[id$="_container"]') ancestry to
   group pressButtons by form, correctly separating modal buttons from background form
   buttons (e.g. "Зачет оплаты" in ERP order form).

Tested with ТестОшибки CFE extension on ERP — error detected in 7.7s.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 13:28:23 +03:00
Nick Shirokov 90ca2a7c4a feat(web-test): auto-detect 1C errors and stop script execution
Action functions (clickElement, fillFields, selectValue, etc.) are now
wrapped to check for 1C errors (modal dialogs, validation balloons)
after each call. When detected, execution stops immediately with full
diagnostic context:

- error: human-readable 1C error message
- step: which API function triggered the error
- stepArgs: arguments passed to that function
- onecErrors: raw balloon/messages/modal data from DOM
- formState: complete form state at the moment of error
- screenshot: auto-captured error-shot.png

This enables autonomous scripts (run mode) to fail fast with enough
information for the caller (agent or human) to diagnose and decide on
corrective action.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 12:15:17 +03:00
Nick Shirokov 500e05703e docs(web-test): update SKILL.md — autonomous run mode, cleaner workflow
- Add `run <url> <script>` as preferred mode for complete scenarios
- Reorganize workflow: autonomous (run) vs interactive (start/exec/stop)
- Remove obsolete "batch mode" section (replaced by run)
- Update URL section with .v8-project.json guidance
- Simplify script template

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 12:07:47 +03:00
Nick Shirokov ebda3e6608 feat(web-test): add autonomous run command
`node run.mjs run <url> <script>` — connect, execute, disconnect in one
call. No HTTP server, no session management. Process exits when done.

Useful for CI, subagents, and standalone test scenarios where the full
start/exec/stop lifecycle is unnecessary overhead.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 12:05:34 +03:00
Nick Shirokov 328cb60f18 fix(web-test): strict search input detection in selection forms
Selection forms without a search field (e.g. ERP Соглашения) have only
filter fields like ТипСоглашения. The old code fell back to inputs[0],
typing the search text into the filter field and breaking the form.

Now pickFromSelectionForm only uses inputs whose ID matches known search
field patterns (поиск/search/строкапоиска/SearchString/find). When no
search input is found, it skips text entry and matches rows directly in
the grid — which works because the target value is visible among the rows.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 11:46:10 +03:00
Nick Shirokov 5061d83282 fix(web-test): ERP compatibility — CB button fallback, div-based grid
selectValue: try DLB button first, fallback to CB (Choose Button).
ERP uses _CB suffix instead of _DLB for some reference fields
(Соглашение, Склад).

fillTableRow: handle non-INPUT focus between grid cells. ERP's
div-based grid puts DIV.gridBody focus between editable cells on Tab.
Also treat TEXTAREA cells (e.g. Содержание) as editable grid cells.
Added wrap-around detection to exit when Tab loops back to first cell.

Tested: Заказ клиента in ERP — all fields fill correctly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 11:02:41 +03:00
Nick Shirokov b10802d4d7 revert(web-test): restore fixed delays, keep waitForCondition utility
Smart wait polling showed no measurable speedup in benchmarks
(31.8s vs 32.0s baseline). 1C backend response time (~1.5-2s per
autocomplete) is the real bottleneck, not client-side delay calibration.
Reverted all 5 replacements to original fixed delays to reduce complexity.
Kept waitForCondition() utility for potential future use.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 20:09:15 +03:00
Nick Shirokov ae0c3e3278 refactor(web-test): replace fixed delays with smart waitForCondition polls
Add waitForCondition() utility — polls JS expression every 100ms with
timeout fallback. Replace key fixed delays:
- fillReferenceField paste: 2000ms → poll for EDD/cloud (max 2s)
- fillTableRow add: 1000ms → poll for grid INPUT focus (max 2s)
- fillTableRow cell paste: 1500ms → poll for EDD/value (max 1.5s)
- fillTableRow Tab skip/commit: 300-1000ms → poll for focus change

Benchmark: 31.8s vs 32.0s baseline — no measurable speedup because
1C backend response time (~1.5-2s for autocomplete) is the real
bottleneck, not our delay calibration. Code is correct and will
benefit from faster backends.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 20:05:42 +03:00
Nick Shirokov 00ec14aed3 feat(web-test): add required field detection via markIncomplete CSS class
Fields with 1C fill-check enabled show `required: true` in getFormState()
when empty, allowing proactive filling before posting.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 19:49:05 +03:00
Nick Shirokov 102a7b8849 fix(web-test): force click before Escape on surface intercept
Escape on document forms triggers "save changes?" dialog. Reorder
retry strategy: try force:true first (no side effects), then Escape
as fallback. Applied to both clickElement and fillReferenceField.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 18:43:41 +03:00
Nick Shirokov 68e346d645 fix(web-test): improve modal detection, surface retry, search regex
- detectFormScript: lower modal threshold from >=2 to >=1 visible elements
- clickElement: force:true on third retry when surface overlay persists
- filterList/unfilterList: add SearchString pattern for selection forms
- fillTableRow: wrap body in try/catch for structured error returns
- SKILL.md: add keyboard shortcuts reference (F8, Shift+F4, F4, Alt+F)
- gitignore: exclude *.png screenshot artifacts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 18:31:57 +03:00
Nick Shirokov c8f58b5461 feat(web-test): embed browser automation engine into skill
Move browser.mjs, dom.mjs, run.mjs from external 1c-web-client-mcp
project into .claude/skills/web-test/scripts/. Now the skill is
self-contained — copy .claude/skills/ + npm install is all that's
needed.

- Add scripts/package.json with playwright dependency
- Update SKILL.md with relative runner path and setup section
- Add node_modules/ and .browser-session.json to .gitignore

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 12:15:35 +03:00
Nick Shirokov ba963739d8 docs(web-test): advanced search works on hierarchical catalogs
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 11:57:38 +03:00
Nick Shirokov afe760af4b docs(web-test): fix hierarchical list — simple filterList works
Simple filterList('text') works on hierarchical catalogs after
the search input regex fix. No need to switch view mode.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 10:40:00 +03:00
Nick Shirokov c6eae770f5 docs(web-test): fix hierarchical list — switch to flat mode before filter
The Alt+F (Найти) in 1C navigates the tree instead of filtering.
Correct approach: Ещё → Режим просмотра → Список, then filterList.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 10:32:37 +03:00
Nick Shirokov d28bea8f0a docs(web-test): add dblclick, closeForm, hierarchical, lifecycle docs
- clickElement {dblclick:true} for opening items from lists
- closeForm() API and closing forms patterns table
- Hierarchical lists search gotcha with filterList
- Startup lifecycle: start blocks, run in background
- status command in workflow

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 10:14:33 +03:00
Nick Shirokov 475b6d9544 docs(web-test): rewrite SKILL.md for CLI runner workflow
- Replace MCP-based workflow with run.mjs CLI runner (start/exec/shot/stop)
- Add interactive mode (stdin pipe) and batch mode (file exec)
- Compact API reference table, remove verbose return value docs
- Add filterList/unfilterList/deleteTableRow (missing before)
- Remove implementation details (EDD, DLB internals)
- Universal paths, no hardcoded infrastructure specifics

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 09:38:15 +03:00
Nick Shirokov 2d69ecf709 docs: clarify PS1 as primary runtime, Python as derived port
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 18:45:19 +03:00
Nick Shirokov 88f74e96f0 fix(python): add stderr UTF-8 encoding for Windows compatibility
Without reconfiguring stderr, Cyrillic error messages appear garbled
on Windows (cp1251 default). Mirrors the existing stdout fix.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 18:31:27 +03:00
Nick Shirokov bce2d7c85c fix(epf-build,epf-dump): remove double-quoting in subprocess arguments
Same issue as db-* scripts: embedded quotes in list-based subprocess
args get escaped by list2cmdline, causing 1C to receive literal quote
characters in paths. Python's list2cmdline handles quoting automatically
for separate flag+value pairs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 18:15:53 +03:00
Nick Shirokov 8f3bde5cfc fix(db-create): restore quotes in CREATEINFOBASE connection string
File="path" quotes are part of 1C connection string syntax, not shell
quoting. Previous fix correctly removed quotes from /Out and /F args
(where list2cmdline handles quoting) but incorrectly removed them from
the CREATEINFOBASE connection string too.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 18:00:38 +03:00
Nick Shirokov 85cdea925e fix(db-*): remove double-quoting in subprocess arguments
Python subprocess.run() with list args handles quoting automatically.
Extra f'"{path}"' wrapping made quotes literal, breaking 1cv8.exe CLI.
Removed inner quotes from all 8 db-* scripts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 17:49:05 +03:00
Nick Shirokov 679f6bae94 fix(meta-compile): handle dict-format attributes in tabular sections
Python list(dict) returns only keys, losing values. Added _as_list()
helper to convert dict {"K":"V"} → ["K:V"] before passing to
parse_attribute_shorthand(). Fixes TS attribute generation for all
dict-format inputs (attributes, accountingFlags, etc.).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 17:16:52 +03:00
Nick Shirokov c5abfc3a4f fix(form-add): resolve directory path to sibling .xml file
When ObjectPath is a directory (e.g. Catalogs/Номенклатура),
auto-resolve to the sibling XML file (Catalogs/Номенклатура.xml)
before parsing. Matches behavior of other edit scripts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 17:02:56 +03:00
Nick Shirokov d9ce7b03cc fix(role-info): add missing -NoProfile flag to SKILL.md
Normalize PowerShell invocation to match all other skills,
ensuring clean round-trip through switch-to-python/switch-to-powershell.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 16:38:15 +03:00
Nick Shirokov d6abb2b651 fix(python): add stdout UTF-8 encoding for Windows compatibility
Python on Windows defaults to cp1251 for piped stdout, which cannot
handle Unicode box-drawing characters used in info/analysis output.
Added sys.stdout.reconfigure(encoding="utf-8") to all 59 Python scripts.

Tested on real config data: epf-init, epf-validate, cf-info, cf-validate,
meta-info, form-info, role-info, skd-info, subsystem-info — all passing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 16:29:26 +03:00
Nick Shirokov 86a959a354 feat(crossplatform): add Python 3 ports for all 58 PS1 skill scripts
Add cross-platform Python alternatives alongside existing PowerShell
scripts. PS1 remains the default runtime; Python is opt-in via switch
scripts. All parameters are identical between runtimes.

New files:
- 58 Python scripts in .claude/skills/*/scripts/*.py
- scripts/switch-to-python.py and switch-to-powershell.py
- docs/python-porting-guide.md
- __pycache__/ added to .gitignore

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 16:16:07 +03:00
Nick Shirokov 8e7125d850 docs(web-test): fix navigation limitation — Shift+Tab works in 1C
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 18:27:08 +03:00
Nick Shirokov fa9fae49c2 docs(web-test): add fillTableRow API — table part row filling
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 18:25:27 +03:00
Nick Shirokov c0e18ed428 docs(web-test): update SKILL.md — selectValue 3 patterns, clipboard paste
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 17:17:02 +03:00
Nick Shirokov 64453ebe08 docs(web-test): update SKILL.md — fillFields supports reference fields
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 13:32:56 +03:00
Nick Shirokov c91ad0a158 feat(web): add /web-test skill for browser automation scripting
Skill generates and runs .mjs scripts using browser.mjs API.
Includes function table, script template, and usage notes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:23:49 +03:00
Nick Shirokov 6b5992de34 Merge branch 'dev-web' 2026-02-22 18:53:06 +03:00
Nick Shirokov 9d5cbaab9f docs(readme): add web skills to groups table, specs and repo structure
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 18:51:33 +03:00
Nick Shirokov fe8fa4bc3f fix(web): correct VRD service element format for 1C 8.3
ws uses pointEnableCommon (not publishByDefault), OData is attribute
enableStandardOdata on <point> (not child element). Verified against
live BP-demo: WSDL returns 200, SOAP call succeeds.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 18:46:35 +03:00
Nick Shirokov 028c5292d7 feat(web): publish WS, HTTP services and OData by default
VRD now includes <ws>, <httpServices>, <standardOdata> elements so all
service types are available out of the box. web-info shows [WS HTTP OData]
tags per publication. Docs updated with service URL patterns and scenarios.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 18:38:55 +03:00
Nick Shirokov 31debfb61b fix(web-stop): add restart hint and "after execution" section
- Script: hint now mentions both restart (/web-publish) and delete (/web-unpublish)
- SKILL.md: add "После выполнения" section with restart/delete options

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 18:08:28 +03:00
Nick Shirokov a110c17066 docs(web): add multi-user publishing scenarios
- SKILL.md: add "multiple users" section with replace vs parallel rules
- web-guide: add scenarios for user switch and parallel publications

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 17:48:59 +03:00
Nick Shirokov b535dff609 fix(web): improve skills after haiku agent testing
- web-unpublish: add -All flag to remove all publications at once
- web-stop: add hint about /web-unpublish after stopping
- web-publish SKILL.md: emphasize mandatory -V8Path/-UserName params
- Fix Port default comment (8080 → 8081)
- Clean up descriptions: semantic matching only, no technical details
- web-guide: add "delete all" scenario

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 17:39:02 +03:00
Nick Shirokov 96b400ddb9 chore(web): change default port from 8080 to 8081
8080 is too commonly used (Tomcat, Jenkins, dev servers).
8081 is less likely to conflict in dev environments.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 16:40:33 +03:00
Nick Shirokov b68013b2f2 fix(web): port check, process isolation, startup diagnostics
- web-publish: check port availability before starting, show which process
  holds it; run httpd -t on startup failure for diagnostics
- All scripts: filter httpd processes by path (Resolve-Path match) to avoid
  killing or misidentifying a global Apache installation
- web-info: warn about foreign httpd processes
- web-stop: only stop our Apache instance

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 16:38:53 +03:00
Nick Shirokov e2f765fcc0 fix(web-publish): use WebClient for download, comment default Listen 80
- PS 5.1 Invoke-WebRequest fails on 308 redirects; WebClient handles them
- Updated Apache URL to 2.4.66 VS18 (current release)
- Comment out default Listen 80 when adding marker block to avoid port conflict

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 16:34:43 +03:00
Nick Shirokov a3e9e3c907 chore: add tools/ to .gitignore for portable Apache
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 16:29:34 +03:00
Nick Shirokov bc4778d6cc feat(web): add web publishing skills (web-publish, web-info, web-stop, web-unpublish)
Phase 1 of web publishing: publish 1C infobases via portable Apache HTTP Server.
Closes the feedback loop: edit → load → update → open in browser.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 16:28:22 +03:00
Nick Shirokov 2a0b896f5d Merge branch 'dev' 2026-02-21 20:03:06 +03:00
Nick Shirokov bc9087957f fix(skills): add file-not-found fallback for Dir/Name/Name.xml paths
When a non-existent path like Dir/Name/Name.xml is passed (common when
models construct paths from directory structure), auto-resolve tries
Dir/Name.xml as sibling. Applied to all 7 scripts with path resolution.
Also update meta-info SKILL.md to encourage skill usage over direct XML reads.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:46:38 +03:00
Nick Shirokov 78e252af1e fix(skills): add sibling XML auto-resolve for directory paths
When a directory is passed (e.g. src/Name or Catalogs/Name), the
auto-resolve now also checks for a sibling file ../Name.xml, which
is the standard layout for both 1C config dumps and EPF/ERF sources.

Affected: meta-info, meta-edit, meta-validate, epf-validate,
subsystem-edit, subsystem-info, subsystem-validate (7 scripts).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 19:04:55 +03:00
Nick Shirokov 4c5e10a958 fix(db-run): warn on ERF files passed to /Execute
/Execute is EPF-only; passing .erf causes empty form or type confusion.
db-run now detects .erf extension and launches the database without
/Execute, advising the user to open the report via File→Open.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 18:48:44 +03:00
Nick Shirokov 7d0d2dbf3d Merge branch 'dev' 2026-02-21 17:52:44 +03:00
Nick Shirokov 89d1ad3a12 docs(readme): update status to testing phase, add specs index link
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 17:52:10 +03:00
Nick Shirokov 9c75e9392e Merge branch 'dev' 2026-02-21 17:40:38 +03:00
Nick Shirokov 5f7ee6fcae fix(form-validate): skip DataPath check for base elements in borrowed forms
In extension forms with BaseForm, elements with id < 1000000 belong to the
base configuration and their attributes are not present in the extension.
Skip DataPath→Attribute validation for these elements to avoid false errors.
Show "N base skipped" in output for transparency.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 17:34:36 +03:00
Nick Shirokov 6f32e18e37 improve(skills): auto-resolve ConfigPath, auto-register forms, handle LF line endings
- cfe-init, cfe-borrow SKILL.md: auto-resolve ConfigPath from .v8-project.json configSrc
- form-compile: auto-register <Form> in parent ChildObjects from OutputPath convention
- form-compile SKILL.md: document new workflow (form-add no longer required first)
- cfe-borrow: handle LF line endings in OuterXml split (-split "\r?\n")

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 17:22:05 +03:00
Nick Shirokov 3565e1c97f fix(cfe): 6 fixes from E2E test — Manager types, borrowed form structure, ConfigPath, guard checks
1. meta-compile + cfe-borrow: add Manager GeneratedType for Report/DataProcessor
2. cfe-borrow: rewrite Form.xml generation — extract only visual elements
   (AutoCommandBar + ChildItems), replace CommandName→0, strip Attributes/Events/Parameters
3. cfe-init: add -ConfigPath to auto-resolve Language UUID and CompatibilityMode
4. form-add: guard against overwriting existing Form.xml and Module.bsl
5. docs: update GeneratedType table for Report/DataProcessor
6. docs: rewrite section 5.4.2 with accurate borrowed form structure

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 16:39:27 +03:00
Nick Shirokov 28b967f591 feat(cfe,form): add borrowed form support across 6 skills
- cfe-borrow: borrow forms via Type.Name.Form.FormName, auto-borrow parent,
  generate Form.xml with BaseForm + metadata + empty Module.bsl
- form-edit: formEvents, elementEvents, callType on events/commands,
  auto-detect extension mode (IDs 1000000+)
- form-info: [EXTENSION] marker, callType on events/commands, BaseForm footer
- form-validate: callType value checks, extension ID range warnings,
  BaseForm presence, callType-without-BaseForm detection
- cfe-diff: form-level analysis in Mode A — borrowed/own forms,
  callType interceptors on events and commands
- cfe-patch-method: warn if Form.xml missing for .Form. paths

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 14:59:16 +03:00
Nick Shirokov 9c1985b710 docs(cfe): expand section 5.4 with borrowed form structure (BaseForm, callType, IDs)
Previously section 5.4 only documented the metadata XML of borrowed forms.
Now covers: two-part Form.xml structure (result + BaseForm), callType attribute
(Before/After/Override) on events and commands, ID numbering convention (1000000+),
own forms vs borrowed forms distinction, and form module patterns.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 14:23:33 +03:00
Nick Shirokov 99d37fb494 Merge branch 'dev' 2026-02-16 20:31:52 +03:00
Nick Shirokov 48de4cdc2a fix(db-run): use single-string ArgumentList for Cyrillic /Execute paths
Start-Process without -NoNewWindow uses ShellExecute API which corrupts
Cyrillic characters when ArgumentList is passed as an array. Switching
to a single concatenated string fixes file-not-found errors for paths
like МояОбработка.epf.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 20:15:20 +03:00
Nick Shirokov 544893b781 fix(skills): use forward slashes in script paths per best practices
Bash on Windows strips backslashes in unquoted paths, causing
"file not found" errors. Forward slashes work cross-platform.
Also fix pwsh → powershell.exe in epf-init and epf-add-form.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 20:01:30 +03:00
Nick Shirokov 8ecc5764ed feat(db,epf): add .ps1 wrapper scripts for all 1cv8 CLI skills
Wrap all remaining 1cv8.exe CLI calls with Start-Process .ps1 scripts
to fix Cyrillic parameter corruption in PowerShell 5.1 when using & operator.

New scripts (7):
- db-update.ps1: DESIGNER /UpdateDBCfg with Dynamic/Server/WarningsAsErrors
- db-dump-cf.ps1: DESIGNER /DumpCfg with Extension support
- db-load-cf.ps1: DESIGNER /LoadCfg with Extension support
- db-create.ps1: CREATEINFOBASE with UseTemplate/AddToList
- db-run.ps1: ENTERPRISE with Execute/CParam/URL (background, no wait)
- epf-build.ps1: DESIGNER /LoadExternalDataProcessorOrReportFromFiles (shared with erf-build)
- epf-dump.ps1: DESIGNER /DumpExternalDataProcessorOrReportToFiles (shared with erf-dump)

Updated SKILL.md (9): db-update, db-dump-cf, db-load-cf, db-create,
db-run, epf-build, epf-dump, erf-build, erf-dump — all now reference
powershell.exe -NoProfile -File invocation with parameter tables.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 19:31:18 +03:00
Nick Shirokov 329d94dc55 feat(cfe): add Russian type synonyms to cfe-borrow, improve cfe-diff description
cfe-borrow silently resolves Russian type names (Справочник→Catalog, etc.)
as a fallback when the model uses the wrong type prefix. cfe-diff description
updated with better trigger words for agent discovery.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 18:50:13 +03:00
Nick Shirokov 7268b169d8 feat(skd,subsystem): add -Value param to skd-compile, full mode to skd-info and subsystem-info
- skd-compile: replace mandatory -JsonPath with -DefinitionFile/-Value pair,
  allowing inline JSON without temp files
- skd-info: extract 6 mode bodies into functions, add -Mode full combining
  overview+query+fields+resources+params+variant in one call
- subsystem-info: extract overview/content/ci into functions, add -Mode full
  combining all three in one call
- Update SKILL.md docs and guides accordingly

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 18:29:00 +03:00
Nick Shirokov 2a4d2bf8df fix(skd-edit): add query modification trigger to skill description
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 17:58:32 +03:00
Nick Shirokov 6e7284fc79 Merge branch 'dev' 2026-02-16 17:54:19 +03:00
Nick Shirokov c9e991e1e8 docs(README): add subsystem-guide links to skills table and docs tree
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 17:53:42 +03:00
Nick Shirokov 2a0fff1416 Merge branch 'dev' 2026-02-16 17:38:33 +03:00
Nick Shirokov 1364f22df3 docs: add subsystem and command interface guide
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 17:35:18 +03:00
Nick Shirokov 4b0304d0c8 docs(db-guide): update resolution algorithm, add glob patterns for branches
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 17:14:36 +03:00
Nick Shirokov cfcc633257 docs: update README and guides with epf-validate, erf-validate, meta-remove
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 17:12:25 +03:00
Nick Shirokov d7f012b307 fix(meta-remove): exclude Configuration.xml, ConfigDumpInfo.xml and Subsystems from both search loops
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 17:04:55 +03:00
Nick Shirokov 27bb08d127 fix(meta-remove): add reference check before deletion and fix PS 5.1 variable interpolation
Block deletion when object has references in attributes, code, or forms.
Add -Force parameter to override. Exclude ConfigDumpInfo.xml from ref check.
Fix ${objType}.${objName} syntax for PS 5.1 compatibility.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 16:55:22 +03:00
Nick Shirokov 151ded9bae feat(skills): add epf-validate, erf-validate and meta-remove skills
- epf-validate/erf-validate: 10-check structural validator for EPF/ERF XML
  sources (root structure, InternalInfo/ClassId, properties, ChildObjects
  types/ordering, cross-references, attributes, tabular sections, name
  uniqueness, file existence, form descriptors). Single PS1 script
  auto-detects EPF vs ERF.

- meta-remove: delete metadata objects from config XML dump — removes files,
  deregisters from Configuration.xml ChildObjects, recursively cleans
  subsystem Content references. Supports -DryRun and -KeepFiles.

- db-list: updated resolution algorithm with glob pattern support for
  branch matching and post-execution registration offer.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 16:35:23 +03:00
Nick Shirokov d84a2fb4cf Merge branch 'dev' 2026-02-16 16:13:12 +03:00
Nick Shirokov 05362aeb96 feat(skills): support raw connection params and offer to register untracked databases
Add priority step for user-provided connection parameters (path, server)
before name-based lookup in .v8-project.json. After task completion,
offer to register untracked databases via /db-list add.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 16:05:40 +03:00
Nick Shirokov 01d02065a3 refactor(skills): unify database and platform resolution across all skills
Replace duplicated "Разрешение базы данных" sections in 8 db-* skills
with a compact "Параметры подключения" block referencing .v8-project.json.
Add Git branch-based database resolution priority (databases[].branches
matched against current branch before falling back to default).

Migrate epf-build, epf-dump, erf-build, erf-dump from V8_PATH/V8_BASE
environment variables to .v8-project.json — registered databases are now
preferred over empty build bases, solving XDTO errors with reference types.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 15:52:30 +03:00
Nick Shirokov a711f05acc Merge branch 'dev' 2026-02-15 22:57:46 +03:00
Nick Shirokov 7003a46ad0 fix(meta): emit attribute properties based on stored/non-stored object context
DataProcessor/Report attributes incorrectly included Indexing, FullTextSearch,
DataHistory, FillFromFillingValue, FillValue, and Use properties. Added
"processor" and "processor-tabular" contexts to both meta-compile and meta-edit.
Also fixed Use emitted for Document (should be Catalog-only).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 22:57:35 +03:00
Nick Shirokov e29c184f8e fix(meta-compile): fix invalid XML properties and improve JSON input flexibility
A) XML bugs: skip FillFromFillingValue/FillValue for tabular attributes,
   emit Use=ForItem only for Catalog tabular sections (not Document).
B) JSON input: accept "objectType" as alias for "type", normalize array-format
   tabularSections, add "Каталог" synonym for "Catalog".
C) Update specs to match corrected behavior.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 20:42:04 +03:00
Nick Shirokov 38c0ce11a9 fix: quote argument-hint values starting with [ in YAML frontmatter
YAML parses [value] as array, not string. Added quotes to 7 SKILL.md files.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 20:14:20 +03:00
Nick Shirokov fcc85c9c6e fix(db): improve skill docs after comprehensive testing
- Add Russian morphology-aware matching for aliases and names
- Standardize empty password handling: omit /P entirely
- Add server base examples to db-create, db-load-cf, db-dump-xml, db-load-git
- Fix Unstaged description to include untracked files
- Add Partial mode hint to db-dump-xml

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 20:05:37 +03:00
Nick Shirokov 9331aa7825 Add .v8-project.json to .gitignore
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 19:56:30 +03:00
Nick Shirokov d6ad1eacdb feat(db): add 9 database management skills
- db-list: manage .v8-project.json registry (CRUD, resolve by id/alias/branch)
- db-create: CREATEINFOBASE for file and server databases
- db-dump-cf / db-load-cf: dump/load configuration as CF binary
- db-dump-xml: dump configuration to XML (full/incremental/partial/updateInfo)
- db-load-xml: load configuration from XML (full/partial)
- db-update: UpdateDBCfg with dynamic/background options
- db-run: launch 1C:Enterprise in user mode
- db-load-git: detect Git changes and partial-load into database
- Add db-guide.md, update README.md and build-spec.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 19:55:56 +03:00
Nick Shirokov 52875b4dea Expand build-spec.md to full 1C Designer batch mode reference
Cover configuration operations (CF, XML dump/load, partial load),
DB update, enterprise mode, connection params, authentication,
ConfigDumpInfo.xml — verified against vendor docs and real scripts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 17:26:50 +03:00
Nick Shirokov 2698a2b80b Merge branch 'dev' 2026-02-15 17:12:53 +03:00
Nick Shirokov 8e8660c52b Remove redundant reference.md files for cfe-init and cfe-borrow
After enriching SKILL.md bodies, the reference.md files became 90%+
duplicated. Moved the one unique bit (Version hint) into cfe-init SKILL.md.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 16:41:41 +03:00
Nick Shirokov 5d3eccc8eb Improve skill descriptions: add WHEN triggers, remove technical details
- Add "Используй когда/после..." triggers to 26 skill descriptions for better discovery
- Remove technical implementation details from descriptions (file names, XML elements, check lists)
- Enrich CFE skill SKILL.md bodies with parameters, examples, prerequisites, verification
- Clean description pattern: WHAT the skill does + WHEN to use it (user-facing terms only)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 16:37:12 +03:00
Nick Shirokov b8e3107d14 feat(cfe): add configuration extension skills
Add 5 new skills for 1C configuration extensions (CFE):
- cfe-init: create extension scaffold with Configuration.xml, Languages, Roles
- cfe-borrow: borrow objects from configuration with ObjectBelonging=Adopted
- cfe-patch-method: generate &Перед, &После, &ИзменениеИКонтроль decorators
- cfe-validate: validate extension structure with 9 checks
- cfe-diff: analyze extension and check transfer status

Remove ConfigDumpInfo.xml from cf-init scaffold as it's not required
for 1C configuration source files. Add cfe-guide documentation.
2026-02-15 16:13:55 +03:00
Nick Shirokov aae69664c5 Add CFE extension source format specification
New spec covers: extension Configuration.xml properties, borrowed vs own
objects (ObjectBelonging/ExtendedConfigurationObject), type extension
mechanisms (xr:PropertyState, xr:ExtendedProperty), module interceptors
(&Before/&After/&Instead), diff markers, predefined items, and full
directory structure reference.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 14:36:27 +03:00
Nick Shirokov bd947f2c0b Remove skill references from specs index
Specs index documents file formats only, not skills.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 12:00:31 +03:00
Nick Shirokov 1b6ab2f144 Add configuration root skills (4 new cf-* skills) and guide
New skills for working with root-level 1C configuration files:
- cf-info: analyze configuration structure (3 modes: brief/overview/full)
- cf-init: scaffold empty configuration (Configuration.xml, ConfigDumpInfo.xml, Languages/)
- cf-validate: validate structural correctness (8 checks)
- cf-edit: edit properties, ChildObjects, default roles (6 operations)

Also adds docs/cf-guide.md and updates README and specs index.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 12:00:13 +03:00
Nick Shirokov a6a708d14d Add subsystem and interface skills (6 new skills)
- subsystem-info: analyze subsystem structure (overview, content, ci, tree modes)
- subsystem-compile: create subsystem from JSON definition
- subsystem-edit: edit Content, ChildObjects, properties of existing subsystem
- subsystem-validate: validate subsystem XML structure (13 checks)
- interface-edit: edit CommandInterface.xml (hide/show, place, order)
- interface-validate: validate CommandInterface.xml structure (13 checks)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 21:52:17 +03:00
Nick Shirokov 3ec2d2594c Add root configuration spec and unified specs index
New docs:
- 1c-configuration-spec.md: Configuration.xml properties, ConfigDumpInfo.xml,
  Ext/ directory, Languages, 17 additional object types (CommonPicture,
  SessionParameter, FunctionalOption, etc.), version 2.17→2.20 differences
- 1c-specs-index.md: single entry point linking all 44 object types,
  nested formats (Form, DCS, MXL, Rights), EPF/ERF, and DSL specs

Updated cross-references in 1c-config-objects-spec.md and 1c-subsystem-spec.md.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 20:58:32 +03:00
Nick Shirokov 08d29c0341 Add meta-guide.md and link from README
Guide covers meta-* skills: workflow, 23 object types, inline/JSON modes,
typical scenarios (create, edit, validate), file structure.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 19:25:24 +03:00
Nick Shirokov 37ecb77256 Split meta-edit SKILL.md into compact router + 3 reference files
SKILL.md reduced from 391 to 105 lines (loaded every invocation).
Detailed syntax moved to on-demand reference files:
- child-operations.md: inline ops for attrs, TS, dims, resources, enums
- properties-reference.md: modify-property, Owners, RegisterRecords, etc.
- json-dsl.md: JSON mode structure, synonyms, supported object types

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 19:14:34 +03:00
Nick Shirokov 9cfb62c5b1 Add CommandGroup, CommonCommand and object command specs to subsystem spec
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 18:35:13 +03:00
Nick Shirokov fff77d97ca meta-edit v1.3: positional TS-attr insert, modify-ts, JSON combo example
- add-ts-attribute now respects >> after / << before positioning
- Add modify-ts inline operation for TS properties (synonym, fillChecking, etc.)
- Add JSON combo example (create + edit TS in one definition) to SKILL.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 18:25:53 +03:00
Nick Shirokov 484ee44387 Add subsystem and command interface XML format specification
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 18:23:03 +03:00
Nick Shirokov 47174ee236 Rename docs/1c-xml-format-spec.md → docs/1c-epf-spec.md for consistency
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 18:19:51 +03:00
Nick Shirokov d02ca602a4 Update README and guides for renamed/new ERF skills
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 18:14:05 +03:00
Nick Shirokov f3b3f26af9 Rename /epf-remove-form → /form-remove, /epf-remove-template → /template-remove
Universal naming, ObjectName parameter (alias ProcessorName for compat).
template-remove now clears MainDataCompositionSchema if removed template was referenced.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 18:06:11 +03:00
Nick Shirokov be47935973 Add ERF skills and universalize template/help skills
- Add /erf-init: scaffold external report with optional --WithSKD
- Add /erf-build, /erf-dump: instructive skills for ERF build/dump CLI
- Rename /epf-add-template → /template-add: universal, auto-fill MainDataCompositionSchema for reports
- Rename /epf-add-help → /help-add: universal for any object type
- Extend /form-add: support ExternalDataProcessor and ExternalReport
- Update cross-references in epf-init, epf-bsp-init, epf-build, epf-dump

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 18:00:36 +03:00
Nick Shirokov 1312cd7db4 Expand EPF spec: object attributes, ChildObjects order, DCS template type
Add missing documentation: object-level Attributes with full 23-property
reference table, fixed ChildObjects ordering (Attribute → TabularSection →
Form → Template), DataCompositionSchema template type, expanded TabularSection
attribute properties (FillFromFillingValue/FillValue), cross-reference to
ERF spec.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 16:38:47 +03:00
Nick Shirokov a81c26afda Add TS attribute operations to /meta-edit: add/remove/modify attrs inside tabular sections
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 16:23:21 +03:00
Nick Shirokov 7044f125ed Add external report (ERF) XML format specification
Document the ExternalReport format based on analysis of 6 sample exports
(empty, withEmptySKD, withSimpleSKD, withModuleAndForm, withAttr, ERP report).
Covers differences from EPF: ClassId, Properties, GeneratedType naming,
report-specific form properties (ReportFormType, ReportResult, DetailsData),
object attributes, and module events.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 16:20:10 +03:00
Nick Shirokov 989f4e49d9 Add inline mode and complex properties to /meta-edit skill
- Inline mode (-Operation/-Value) as alternative to JSON -DefinitionFile
  for quick single operations: add/remove/modify attributes, TS, dims,
  resources, enum values, forms, templates, commands
- Batch syntax with ;; separator, positional insertion (>> after, << before)
- Complex property support: Owners, RegisterRecords, BasedOn, InputByString
  with add-*/remove-*/set-* inline ops and JSON modify.properties arrays
- Paren-aware comma splitting for types like Number(15,2) in modify values

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 16:01:53 +03:00
Nick Shirokov cb4b5ec935 Add /meta-edit skill: point editing of 1C metadata objects
New skill for adding/removing/modifying attributes, tabular sections,
dimensions, resources, enum values, forms, templates, commands in
existing metadata XML. Supports Russian/English DSL synonyms,
positional insertion, idempotent add, auto-validation via meta-validate.

Also adds missing Source comment to meta-compile.ps1.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 15:02:23 +03:00
Nick Shirokov 7c5700e40f Fix meta-validate false positives and expand reference data after ERP testing
Cross-checked against spec and tested on 23 ERP 8.3.24 object types.
Fixes: Enum optional StandardAttributes, Column without Type block,
adds missing GeneratedType categories and StandardAttributes for
CalculationRegister, ChartOfCharacteristicTypes, ChartOfCalculationTypes,
BusinessProcess, Report, DataProcessor, DefinedType.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 13:20:20 +03:00
Nick Shirokov a6bf6520ce Add /meta-validate skill: structural validation of 1C metadata XML
11 check categories covering all 23 metadata types:
root structure, InternalInfo, properties, enum values,
StandardAttributes, ChildObjects, child elements (UUID/Name/Type),
name uniqueness, TabularSections, cross-properties,
HTTPService/WebService nested structure.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 13:00:05 +03:00
Nick Shirokov ed45f54594 Improve -info skill descriptions with usage triggers
Add proactive usage hints to form-info, skd-info, mxl-info, role-info
so the model knows when to invoke them as components for composite tasks
(e.g. writing print code, analyzing reports, auditing permissions).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 12:59:07 +03:00
Nick Shirokov 099de2d850 Improve /meta-info skill description for better discoverability
Add trigger keywords (реквизиты, ТЧ, формы, движения, типы) and
proactive usage hint for composite tasks (queries, code).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-14 12:35:04 +03:00
Nick Shirokov 2d79c0b0ee Extend /meta-compile to 23 metadata types (Phase 2)
Add 17 new types: ExchangePlan, ChartOfAccounts, ChartOfCharacteristicTypes,
ChartOfCalculationTypes, AccountingRegister, CalculationRegister,
BusinessProcess, Task, DocumentJournal, Report, DataProcessor,
CommonModule, ScheduledJob, EventSubscription, HTTPService, WebService,
DefinedType. Update DSL spec to v2.0 and improve skill description.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 10:32:48 +03:00
Nick Shirokov acee4bd188 Add /meta-compile skill: JSON DSL → 1C metadata XML
Supports 6 types: Catalog, Document, Enum, Constant,
InformationRegister, AccumulationRegister. Includes DSL spec,
SKILL.md, and PowerShell compiler with CamelCase auto-synonyms,
shorthand attribute syntax, Russian type aliases, Configuration.xml
auto-registration, and module scaffolding.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 21:16:33 +03:00
Nick Shirokov 01b20426fa Update spec and README with 6 new metadata types
Add sections 20-25 to config objects spec (DefinedType, CommonModule,
ScheduledJob, EventSubscription, HTTPService, WebService). Add /meta-info
skill group and spec link to README.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:19:51 +03:00
Nick Shirokov 04e5360e52 Regroup supported types: Ссылочные/Регистры/Сервисные/Прочие
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:09:09 +03:00
Nick Shirokov 33fa6dbe9a Move План обмена into Планы group for consistency
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:06:16 +03:00
Nick Shirokov 11152d2443 Simplify /meta-info description: drop enumeration, keep essence
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:04:06 +03:00
Nick Shirokov daea0a72d1 Refine /meta-info description: "Структура" instead of "Сводка", more concise wording
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:02:48 +03:00
Nick Shirokov b4905fc3e3 Polish /meta-info SKILL.md per best practices: trigger clause in description, forward-slash paths, remove redundant intro and verification section
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 19:58:57 +03:00
Nick Shirokov 23555b513f Rewrite /meta-info SKILL.md: grouped types, generic mode descriptions, relative paths in examples
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 19:54:49 +03:00
Nick Shirokov 8aef749471 Add 6 new metadata types to /meta-info: DefinedType, CommonModule, ScheduledJob, EventSubscription, HTTPService, WebService
Support overview/brief/full modes for all 6 types plus drill-down
for HTTPService (URLTemplate) and WebService (Operation).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 19:46:41 +03:00
Nick Shirokov bd30e48dae Improve /meta-info: Russian translations, sorting, Constants/Reports support
- Translate cfg:Characteristic.X → Характеристика.X (in both v8:Type and v8:TypeSet)
- Translate drill-down values to Russian: Indexing, Use, FillValue
- Translate truncation message to Russian
- Add Constant type display and Report MainDCS/forms/templates in overview
- Add DataProcessor forms/templates/commands in overview mode
- Sort attributes ref-first (references before primitives) in overview/full

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 19:02:37 +03:00
Nick Shirokov 92dc00e152 Add /meta-info skill for compact 1C metadata object summaries
Reads XML metadata files (catalogs, documents, enums, registers, etc.)
and outputs a concise summary with fields, types, tabular sections,
movements, forms. Three modes: overview, brief, full. Supports
drill-down into individual attributes, dimensions, and tabular sections.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 17:56:37 +03:00
Nick Shirokov 45c2587e4a Add configuration metadata objects XML format specification
Comprehensive spec covering all 17 metadata object types (Catalogs, Documents,
Registers, Charts, BusinessProcesses, Tasks, ExchangePlans, Enums, Constants,
Reports, DataProcessors, DocumentJournals) with common structure, type system,
standard attributes, child objects, and platform version differences (2.17→2.20).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 16:45:33 +03:00
Nick Shirokov 08722ff285 Merge branch 'dev' 2026-02-11 22:01:45 +03:00
Nick Shirokov 89c0775c65 Add work-in-progress notice to README
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 22:00:12 +03:00
Nick Shirokov 5c0a55e090 Add /skd-edit to README and skd-guide documentation
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 21:56:17 +03:00
Nick Shirokov 2f2ecca88b Clarify add-conditionalAppearance shorthand syntax in SKILL.md
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 21:13:27 +03:00
Nick Shirokov acb7a4eadc Expand /skd-edit to 25 operations with add-dataSet, add-variant, add-conditionalAppearance
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 21:10:53 +03:00
Nick Shirokov 28b8061d64 Compact skd-edit SKILL.md: remove redundant examples section
Reduce from 309 to 183 lines by removing duplicate full-command examples
(already shown inline per operation) and consolidating remove-*/clear-*
into a single table.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 20:10:49 +03:00
Nick Shirokov 703c3e6f80 Add version headers with source URL to all 22 skill scripts
Each .ps1 now starts with skill name, version (v1.0), and repo link.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 20:01:10 +03:00
Nick Shirokov 2d0835ba17 Fix XML formatting in batch insert and after clear operations
Two bugs caused tag concatenation (e.g. `</item><item`):
- Insert-BeforeElement: place new node before trailing whitespace, not before the preceding newline
- Get-ContainerChildIndent: check for Element children instead of HasChildNodes to correctly detect empty containers after clear-*

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 19:39:07 +03:00
Nick Shirokov a9b7a90672 Expand /skd-edit to 22 operations with modify, clear, structure, and dataSetLink
Add 7 new operations: modify-field, modify-filter, modify-dataParameter,
clear-selection, clear-order, clear-filter, add-dataSetLink, set-structure.
Add selection dedup for add-field/add-calculated-field and order dedup
for add-order. Fix SetAttribute output leak.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 18:50:13 +03:00
Nick Shirokov 69213930b3 Expand /skd-edit to 15 operations with batch mode and duplicate checks
Add 9 new operations: add-dataParameter, add-order, add-selection,
set-outputParameter, remove-field/total/calculated-field/parameter/filter.
Add batch mode (;; separator), duplicate detection with skip, title support
in fields and calculated fields, type support in calculated fields.
Fix set-query double-escaping and Parse-CalcShorthand title extraction.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 17:38:13 +03:00
Nick Shirokov 151d1d77cb Add /skd-edit skill for atomic DCS modifications
New skill for point editing of existing Template.xml: add-field,
add-total, add-calculated-field, add-parameter (with @autoDates),
add-filter, set-query. Uses XmlDocument+PreserveWhitespace pattern
from form-edit and shorthand parsers from skd-compile.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 16:56:02 +03:00
Nick Shirokov 70bb5074c8 Update SKD DSL spec and guide with new features documentation
Add conditionalAppearance, multi-group totalField, viewMode flags
(@normal, @inaccessible), userSettingPresentation, dataParameters
table. Update guide with @autoDates, structure/filter shorthand,
and modern examples.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 16:19:31 +03:00
Nick Shirokov 91d254b718 Add DCS template type, conditional appearance, filter/total enhancements
- epf-add-template: support DataCompositionSchema template type with
  minimal DCS scaffold (dataSource + Local)
- skd-compile: add conditionalAppearance with auto-detect value types
  (Color, LocalStringType, Boolean), selection, filter, presentation
- skd-compile: add @normal, @inaccessible viewMode shorthand flags
- skd-compile: add userSettingPresentation for filters and dataParameters
- skd-compile: support multiple group elements in totalField (array form)
- skd-compile SKILL.md: document all new features with examples

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 16:12:47 +03:00
Nick Shirokov 1382194201 Fix @period role to emit periodNumber/periodType instead of period
Real DCS files use <dcscom:periodNumber>1</dcscom:periodNumber> and
<dcscom:periodType>Main</dcscom:periodType> for period fields.
The element <dcscom:period> does not exist in the XDTO schema and
causes build failures.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 13:22:35 +03:00
Nick Shirokov 7e587b9a3e Emit Auto items only at group level, not top-level settings
Real DCS files place SelectedItemAuto and OrderItemAuto exclusively
inside StructureItem elements (groups, tables, charts), never at the
top-level settings. Added -skipAuto switch to Emit-Selection and
Emit-Order, applied at settings level.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 12:48:52 +03:00
Nick Shirokov 4594c74d21 Document d5p1: inline namespace for reference types in DCS spec
Reference types in valueType use inline xmlns:d5p1 declaration with
URI http://v8.1c.ru/8.1/data/enterprise/current-config, not a
root-level cfg: prefix. Added XML example and supported type list.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 11:47:04 +03:00
Nick Shirokov 2650b1a063 Fix reference types to use d5p1: namespace instead of cfg:
Real DCS files use inline xmlns:d5p1="http://v8.1c.ru/8.1/data/
enterprise/current-config" for reference types like CatalogRef.XXX.
Using cfg: prefix caused XDTO errors because the namespace was
undeclared. With correct d5p1: namespace, EPF builds successfully
in both empty and config-aware bases.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 11:45:01 +03:00
Nick Shirokov f23a3e5536 Add MIT license
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 11:35:47 +03:00
Nick Shirokov eb6f8379e6 Skip cfg: reference types in DCS valueType to fix XDTO build errors
Real 1C DCS files (12,495 analyzed) never include cfg:CatalogRef.XXX
in <valueType> — the platform infers field types from query metadata.
Emitting them causes XDTO exceptions when building EPF. Reference
types in JSON DSL still set field roles but no longer emit valueType.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 11:32:17 +03:00
Nick Shirokov 91e4e1948f Add comprehensive XML escaping to skd-compile
Wrap all user-provided values in Esc-Xml() for safe XML output:
- ValueType references (CatalogRef, DocumentRef, etc.)
- Emit-ParamValue (all type branches: StandardPeriod, dateTime, boolean, decimal)
- DataParameters (variant, boolean, dateTime values, viewMode, userSettingID)
- Filter items (field, comparisonType, viewMode, userSettingID)
- Selection fields, Order fields, GroupItems fields
- GroupTemplates templateType, HorizontalAlign appearance value
- Parameter use element

Verified against 12,495 real DCS files: standard XML entity escaping
(&amp; &lt; &gt; &quot;) matches 1C platform behavior exactly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 09:44:23 +03:00
Nick Shirokov f4d60d67bf Add DSL v2 shorthand improvements to skd-compile
Type synonyms (число/строка/булево/дата/СправочникСсылка, case-insensitive),
@autoDates for auto-generating ДатаНачала/ДатаОкончания from StandardPeriod,
string shorthand for structure ("Организация > details"), filter shorthand
("Организация = _ @off @user"), dataParameters shorthand ("Период = LastMonth
@user"), and default selection/order ["Auto"] on all structure levels.
Compression ratio improved from 3.9x to 5.8x on the medium example.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 22:09:03 +03:00
Nick Shirokov b67f4b21e6 Add SKD group to README, create skd-guide.md
- README: add СКД row to skills table, specs section, directory tree
- docs/skd-guide.md: usage guide with workflow, DSL examples, scenarios

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 21:32:29 +03:00
Nick Shirokov d573f84c9d Add skd-compile and skd-validate skills for DCS schema generation
- skd-compile: JSON DSL → Template.xml (DataCompositionSchema)
  Shorthand parsers for fields, totals, parameters, calculated fields.
  Full type system, settings variants with selection/filter/order/structure.
- skd-validate: structural validation of Template.xml (~30 checks)
  DataSources, DataSets, fields, links, params, templates, variants.
- docs/skd-dsl-spec.md: full DSL specification

Tested on compiled examples and 5+ real DCS from acc_8.3.24 (0 errors).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 21:27:19 +03:00
Nick Shirokov c306d18648 Add templates mode for DCS template binding analysis
- Map (without -Name): field bindings with non-trivial expression
  detection, group bindings organized by group name (groupTemplate,
  groupHeaderTemplate, groupFooterTemplate, fieldTemplate)
- Detail (-Name <group|field>): template content with rows, cells
  (static text and parameters), non-trivial expressions only
- Trivial filter: Field=Field and Field=Представление(Field) hidden
- Updated overview: shows binding type counts, templates hint in Next

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 19:56:56 +03:00
Nick Shirokov d72dd1678e Extract detailed mode examples into modes-reference.md
SKILL.md: 288 -> 72 lines. Compact table of modes with
progressive disclosure pattern, typical workflow, command
reference. Detailed output examples moved to modes-reference.md
(loaded on demand via Read tool, not on every skill invocation).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 19:01:16 +03:00
Nick Shirokov 0ca6d3f089 Add variant list mode, fix stale SKILL.md references
- variant without -Name now shows variant list (progressive disclosure)
- Fix Mode parameter: totals -> calculated, resources
- Fix fields -Name example: dataset name -> field name
- Improved error message when variant not found

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 18:52:20 +03:00
Nick Shirokov dddb9e3dac Make fields -Name drill into specific field for consistency
fields -Name now takes a field dataPath (like calculated -Name and
resources -Name) instead of a dataset name. Shows field detail:
dataset, title, type, role, restrict, format, presentationExpression.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 18:45:15 +03:00
Nick Shirokov f211ffa2f0 Split totals into calculated and resources modes
Each concept now has its own mode with clear naming that matches
the overview labels. Overview now shows "Resources:" instead of
"Totals:" for consistency.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 18:40:50 +03:00
Nick Shirokov 21dded4d1c Add trace mode for field origin analysis
New mode traces a field from title/name to its full origin:
dataset fields, calculated expression with operands, resource
formulas. Searches by dataPath, exact title, or title substring.
Collapses 5-7 manual calls into one.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 18:34:12 +03:00
Nick Shirokov 941fa73803 Add progressive disclosure to fields and totals modes
Without -Name, both modes now show a compact map (field names
per dataset / calculated+resource names). With -Name, they
drill down to full detail. Totals -Name shows both calculated
expression and resource formula when field appears in both.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 18:23:02 +03:00
Nick Shirokov 24358f212f Split fields mode into fields, links, and totals modes
Separate concerns for cleaner output: fields shows only dataset
field tables, links shows dataset connections, totals shows
calculated fields and resources.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 18:00:30 +03:00
Nick Shirokov d210d21079 Add full link details to fields mode
Show dataSetLink field-level mappings (source.field -> dest.field
param=X) at the top of -Mode fields output. Overview keeps compact
dataset-pair summary, fields provides the detail.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 17:46:29 +03:00
Nick Shirokov 2949682ce8 Update SKILL.md examples to match simplified overview
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 17:39:42 +03:00
Nick Shirokov e86620dbd7 Simplify /skd-info overview to pure navigation map
Overview now shows only counts for calculated/totals/templates.
Links compressed to dataset pairs. Params split into visible/hidden
with only visible names listed. Add "Next:" hints with available
modes and dataset names to guide further exploration.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 17:39:16 +03:00
Nick Shirokov 9922f118d1 Improve /skd-info overview for large schemas
Switch to multi-line/compact format when element counts are high:
totals (>5) show grouped by field name, calculated (>10) truncated,
templates (>10) show counts, links (>2) multi-line, variant structure
groups identical items (e.g. "17x Group(...)"). Fix query mode to
prefer nested Query datasets over parent Union with same name.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 17:31:30 +03:00
Nick Shirokov 8c833f042c Add /skd-info skill for DCS (Data Composition Schema) analysis
Implements 5 modes: overview (compact TOC), query (raw SQL with batch
splitting), fields (field table with roles/restrictions), params
(parameter table with types/defaults), variant (structure tree with
filters and output settings). Update DCS spec with totalField group info.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 17:24:43 +03:00
Nick Shirokov 1d593af63a Merge branch 'dev' 2026-02-10 14:11:58 +03:00
Nick Shirokov be216cd064 Document CatalogRef XDTO build failure in empty database
Verified experimentally: EPF build with CatalogRef/DocumentRef
types fails with XDTO exception in empty database (not silent
UUID substitution as previously documented). Updated epf-build,
form-compile, and build-spec accordingly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 14:11:23 +03:00
Nick Shirokov 55b1ef4e06 Merge branch 'dev' 2026-02-10 13:31:23 +03:00
Nick Shirokov e229fc4873 Auto-register role in Configuration.xml
role-compile: after generating files, automatically inserts
<Role>Name</Role> into Configuration.xml ChildObjects (idempotent).
role-validate: checks that the role is registered, warns if not.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 13:29:50 +03:00
Nick Shirokov 3a4c1905f4 Fix Cyrillic encoding in role-info console output
Add [Console]::OutputEncoding = UTF8, matching role-compile
and role-validate scripts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 13:21:00 +03:00
Nick Shirokov 7aaa9fc070 Remove @use preset, merge DataProcessor/Report into @view
The @use preset name conflicted with the Use right semantics.
DataProcessor and Report require Use+View together (View cannot
be set without Use), so @view is the natural fit. Services
(WebService, HTTPService, IntegrationService) use explicit rights.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 13:18:08 +03:00
Nick Shirokov 8b8bc1225a Refactor role-compile SKILL.md with progressive disclosure
Extract detailed preset tables, Russian synonym tables, and extra
examples into dsl-reference.md (318 lines). Compact SKILL.md from
340 to 107 lines. Add role-dsl-spec.md project spec.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 13:13:59 +03:00
Nick Shirokov dc10422f10 Add script-based /role-compile and /role-validate skills
Convert /role-compile from instruction-based to PowerShell script with JSON DSL:
- Presets (@view, @edit, @use) for common right sets
- String shorthand and object form with RLS support
- Russian synonym translation for object types and rights
- Auto UUID generation, UTF-8 BOM output

Add /role-validate for structural validation of Rights.xml:
- XML well-formedness, namespace, global flags
- Right name validation per object type with typo suggestions
- RLS condition and template checks
- Optional metadata validation (UUID, Name, Synonym)

Update README and role-guide with new skills documentation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 10:29:59 +03:00
Nick Shirokov 65afdf2e55 Add 1C Data Composition Schema (DCS) XML format specification
Comprehensive spec covering DataCompositionSchema format based on
analysis of 930 schemas from accounting configuration (8.3.24):
dataSource, dataSet (Query/Object/Union), fields with roles and
restrictions, parameters, dataset links, calculated/total fields,
area templates, and settings variants with structure items.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 09:32:33 +03:00
Nick Shirokov f87c94e832 Merge branch 'dev' 2026-02-09 22:53:50 +03:00
Nick Shirokov 6681758121 Add /form-add skill for configuration objects
Create forms (metadata XML + Form.xml + Module.bsl) for Document,
Catalog, InformationRegister and other configuration object types.
Supports Object/List/Choice/Record purposes with automatic
ChildObjects registration and DefaultForm setup.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 22:53:13 +03:00
Nick Shirokov 89f0788585 Rename form-add to form-edit for clarity
The skill modifies existing forms (adds elements/attributes/commands),
not creates new ones. "form-edit" better reflects its purpose.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 22:05:33 +03:00
Nick Shirokov d27dfbf8e1 Add role-guide.md and update README with role skills
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 21:54:52 +03:00
Nick Shirokov fc24524c75 Add /role-info and /role-compile skills
role-info: PS1 script parsing Rights.xml into compact summary grouped
by object type. Supports -ShowDenied and -OutFile for UTF-8 output.
78K lines XML -> 1924 lines for largest role, ~100 for typical ones.

role-compile: Template-based SKILL.md (no script) with XML templates,
rights catalog per object type, and typical right sets.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 21:21:04 +03:00
Nick Shirokov 2c96c90d45 Add 1C role XML format specification
Complete reference: file structure, rights catalog by object type,
nested object rights, RLS conditions, restriction templates.
Verified across platform versions 8.3.20/8.3.24/8.3.27 and
both ACC and ERP configurations.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 21:06:01 +03:00
Nick Shirokov 8fc30c9b9a Merge dev: form skills (info, compile, validate, add, patterns)
Complete managed form pipeline:
- /form-info: compact XML analysis
- /form-compile: JSON DSL to Form.xml generation
- /form-validate: structural validation
- /form-add: add elements/attributes/commands to existing forms
- /form-patterns: layout guide with archetypes and conventions

Event validation, element-level stdCommand, ERP patterns.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 19:03:45 +03:00
Nick Shirokov ecfb473827 Add /form-patterns skill for loading layout guide into context
Self-contained SKILL.md with all patterns inlined (no external file
dependencies). Archetypes, naming conventions, ERP patterns, DSL examples.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 19:02:00 +03:00
Nick Shirokov dc9e1fe3db Add advanced ERP patterns to form layout guide
Collapsible groups, status banners, popup menus, custom command bars,
hyperlink labels — with DSL examples for each pattern.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 18:35:02 +03:00
Nick Shirokov 5c07dec82c Add form layout patterns guide with real-world conventions
Design patterns extracted from 1C:Accounting 8.3.24 forms:
- 5 archetypes: document, processor, list, catalog, wizard
- Naming conventions for groups, elements, event handlers
- Layout principles (2-column header, footer totals, filter pairs)
- Two complete DSL examples (processing form, list with filters)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 18:12:17 +03:00
Nick Shirokov c5fa794cf3 Add event validation and element-level stdCommand support
- stdCommand dot syntax: "Товары.Add" → Form.Item.Товары.StandardCommand.Add
- Event name validation: warn on unknown events per element type (13 types, ~60 events)
- Form-level event validation (19 known events)
- Document events reference and popup element in SKILL.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 17:39:29 +03:00
Nick Shirokov 7e0e30730c Add unknown key warnings to form-add, update form-guide.md
form-add: warn about unrecognized DSL keys in element definitions,
matching the same validation added to form-compile earlier.

form-guide.md: update form-info output examples to reflect new
Title-in-header format and DSL-friendly command display
(-> Name [cmd], -> Close [std]).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 16:03:17 +03:00
Nick Shirokov ad412dffa2 Expand form-compile SKILL.md with full DSL reference and patterns
Replace minimal docs with comprehensive reference:
- Per-element-type property tables (input, check, label, group,
  table, pages, button, cmdBar) with all supported keys
- Top-level structure documentation (title, properties, events, etc.)
- Table+attribute linkage section explaining the ValueTable pattern
- Three pattern examples: file import dialog, wizard with steps,
  list with filter and table
- Attribute and command definition examples

This helps the model generate correct JSON DSL from natural language
requirements on the first attempt without guessing undocumented keys.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 15:58:15 +03:00
Nick Shirokov c665800916 Improve form skills: validation, docs, round-trip consistency
form-compile: warn about unknown DSL keys in element definitions,
document stdCommand/command button keys and EPF-specific notes.

form-validate: check that form-level Title uses multilingual XML,
not plain text (which causes XDTO errors at build time).

form-add: warn about duplicate element names, clarify after-not-found
message when using into+after together.

form-info: show Title in header instead of Properties line, display
commands as DSL-friendly format (-> Name [cmd], -> Close [std])
instead of raw Form.Command/Form.StandardCommand paths.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 15:44:32 +03:00
Nick Shirokov d05199d048 Replace hidden/disabled with visible/enabled in form DSL
Rename DSL keys to match 1C property names (Visible, Enabled):
- form-compile/form-add: accept "visible": false and "enabled": false
  as primary keys, keep hidden/disabled as synonyms
- form-info: output [visible:false] and [enabled:false] flags
- Update SKILL.md docs and form-guide.md

Improves round-trip consistency: form-info output now directly maps
to form-compile/form-add input keys.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 15:05:14 +03:00
Nick Shirokov a9e59265dd Fix ID scanning in form-add and title emission in form-compile
form-add: Scan column IDs (same pool as attribute IDs) to prevent
duplicate ID collisions. Use XPath .//*[@id] instead of ChildItems
recursion to capture companion element IDs (ExtendedTooltip, ContextMenu).

form-compile: Extract title from properties and route through Emit-MLText
instead of generic Emit-Properties, which produced plain text <Title>
rejected by 1C XDTO schema.

Found during E2E testing of full pipeline (epf-init → form-compile →
form-add → epf-build).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 14:40:23 +03:00
Nick Shirokov 99f57a5ff2 Add form-add skill for modifying existing Form.xml
Adds elements, attributes, and commands to existing managed forms
via JSON input. Supports positional insertion (into/after), auto ID
allocation from correct pools, companion generation, and event handlers.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 13:34:56 +03:00
Nick Shirokov a813c7fd46 Add form-validate skill for structural validation of Form.xml
Checks: unique IDs (per pool), companion elements, DataPath→attribute
refs, button→command refs, event handlers, command actions, MainAttribute.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 12:13:51 +03:00
Nick Shirokov cc2595b57a Add form-compile skill for generating Form.xml from JSON DSL
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 11:57:58 +03:00
Nick Shirokov 580124a971 Add form-info skill for compact analysis of 1C managed forms
Parses Form.xml (up to 28K lines) and outputs a compact summary (40-180 lines):
element tree with group orientation, data bindings, events, visibility flags,
attributes with types, commands, and parameters.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 11:09:42 +03:00
Nick Shirokov 044bc18974 Add img-grid skill and page auto-sizing to mxl-compile
- New skill /img-grid: overlays numbered grid on images to help
  determine column proportions for MXL template generation
- Add "page" field to MXL DSL ("A4-landscape", "A4-portrait", or
  number) that auto-calculates defaultWidth from column proportions
- Update DSL spec, mxl-compile SKILL.md, MXL guide, README

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 22:44:31 +03:00
Nick Shirokov 3819a5f7af Reorganize docs: README as hub + per-group guides
Split monolithic README into:
- README.md — concise hub with quick start and group links
- docs/epf-guide.md — EPF skills guide (content from old README)
- docs/mxl-guide.md — MXL skills guide (new scenarios and examples)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 21:36:44 +03:00
Nick Shirokov 56b1458545 Add ПФ_MXL_ naming convention for print form templates
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 21:16:41 +03:00
Nick Shirokov bca022fba8 Add relative column width support ("Nx" syntax) to mxl-compile
Allows specifying column widths as multiplier of defaultWidth (e.g. "2x",
"0.5x") alongside absolute values. Makes template generation from images
easier — model specifies proportions instead of exact pixel values.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 20:47:32 +03:00
Nick Shirokov 0e680d151d Remove unused styles, add empty row compression to DSL
- Decompiler: remove styles not referenced by any cell or rowStyle
- Decompiler: compress consecutive empty rows into {"empty": N}
- Compiler: support {"empty": N} row placeholder
- DSL spec: document empty field on rows

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 20:09:13 +03:00
Nick Shirokov 8092015807 Optimize mxl-decompile output: deduplicate fonts, remove noise
- Font deduplication: identical fonts reuse existing name (6→4 on Акт)
- Don't emit "rowStyle": "default" for empty styles
- Don't emit "cells": [] on empty rows
- Don't emit "default": {} in styles section
- Result: ~10% smaller JSON output, cleaner for Claude to read/write

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 19:48:00 +03:00
Nick Shirokov 03a6820f69 Add 1C managed form XML format specification
Comprehensive spec based on analysis of 7723 forms from
Бухгалтерия предприятия 3.0.180: all 15 UI control types,
form-level properties, events, attributes/type system,
parameters, commands, and namespace declarations.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 19:34:51 +03:00
Nick Shirokov bfbef3c361 Add mxl-decompile skill for Template.xml → JSON DSL conversion
Reverse of /mxl-compile: reads Template.xml and produces compact
JSON definition with auto-generated font/style names, rowStyle
detection, span/rowspan mapping, and column width compression.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 19:07:08 +03:00
Nick Shirokov 298d503c64 Extract MXL DSL spec to docs/mxl-dsl-spec.md
Shared spec for mxl-compile and future mxl-decompile.
Compiler SKILL.md now references the spec instead of inlining it.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 18:39:40 +03:00
Nick Shirokov 1ed5d783e8 Rename numberFormat to format in mxl-compile DSL
The field covers all 1C format strings: numbers, dates, booleans.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 18:35:44 +03:00
Nick Shirokov f0bb8c860f Add rowspan and numberFormat support to mxl-compile
- rowspan: vertical cell merging with rowStyle gap-fill awareness
- numberFormat: style field generates nested <format> in palette
- Updated SKILL.md: new fields, removed from limitations

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 18:33:41 +03:00
Nick Shirokov 2f260ddb7f Add underline/strikeout fonts, individual borders, thick lines
- Fonts: underline and strikeout fields (default false)
- Borders: individual sides (left, right), comma combos ("top,bottom")
- Lines: borderWidth "thick" generates width=2 line entry
- SKILL.md updated with new fields

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 18:22:13 +03:00
Nick Shirokov 2771424c71 Fix XML escaping in mxl-compile text content
Add Esc-Xml helper to escape &, <, >, " in cell text and
template content to prevent invalid XML generation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 18:18:24 +03:00
Nick Shirokov 96890598f9 Add mxl-compile skill: DSL compiler for SpreadsheetDocument
JSON DSL format compiles to valid 1C Template.xml with correct
format palettes, merges, named areas, and rowStyle gap-filling.
Tested on simple (4 areas) and invoice (7 areas) templates.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 18:08:04 +03:00
Nick Shirokov 50dc9ceec9 Перевести SKILL.md навыков mxl-info и mxl-validate на русский
Для единообразия с остальными навыками проекта.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 16:29:57 +03:00
Nick Shirokov 455c12e6b6 Extract template parameters without -WithText flag
Parameters from [ParamName] placeholders in template text are now always
extracted and shown with [tpl] suffix. Numeric-only placeholders like [5]
(footnote references in legal forms) are filtered out.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 16:17:50 +03:00
Nick Shirokov 1a79e84598 Improve mxl-info output and document how to read it
Script improvements:
- Sort areas by position (top-to-bottom) instead of alphabetically
- Extract detailParameter (drill-down links)
- Show column set sizes in header and per-area [colset 20cols]
- Detect Rows+Columns intersections with GetArea hint

SKILL.md: add "Reading the Output" section explaining area order,
column sets, intersections, detailParameter, and text content.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 16:11:54 +03:00
Nick Shirokov 76a0dd80be Add mxl-info and mxl-validate skills for SpreadsheetDocument analysis
- /mxl-info: extracts compact template structure (areas, parameters,
  column sets) from Template.xml. Supports -WithText for cell content,
  -Format json, and output truncation protection.
- /mxl-validate: 12 structural checks (format/font/line indices,
  column bounds per column set, named area ranges, merge bounds,
  columnsID references). Exit code 1 on errors.

Tested on 3 real templates: label (simple), invoice (medium),
УКД (complex — 7 column sets, Rectangle areas).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 15:59:49 +03:00
Nick Shirokov fdf661192d Add platform version compatibility section to spreadsheet spec
Documented cross-version comparison (8.3.20, 8.3.24, 8.3.27):
Template.xml is byte-identical, only MetaDataObject/Form version
attribute changes (2.17 → 2.20). Confirmed backward compatibility —
8.3.27 accepts version="2.17" files without issues.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 15:01:58 +03:00
Nick Shirokov be3a31ea94 Add advanced spreadsheet features: multiple column sets, verticalUnmerge, Rectangle areas
Based on УКД (universal correction document) template analysis.
Multiple <columns> with UUID allow rows to use independent
column grids. Merges and named areas also reference column sets.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 14:25:11 +03:00
Nick Shirokov 061c73b23d Add SpreadsheetDocument XML format specification
Based on real templates from 1C:Accounting — invoice (horizontal
areas, 33 columns) and label (vertical area, drawing, barcode).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 14:19:20 +03:00
Nick Shirokov 9f9a022659 Add .claude/settings.local.json to .gitignore
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 13:20:35 +03:00
Nick Shirokov 215319382a Simplify scenario 1 example in README
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 13:16:25 +03:00
Nick Shirokov d6660a4d00 Remove docs/ references from skills to avoid confusion
Skills are self-contained — all templates and instructions are
in SKILL.md. Removed spec references that could mislead the
model into trying to read files that may not exist. Updated
README to note that docs/ is not needed when copying skills.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 12:49:44 +03:00
Nick Shirokov 4bc86decf8 Improve usage examples with real-world scenarios
README: replace abstract examples with realistic scenarios — processor
with form for data manipulation, BSP print form with spreadsheet
template, incremental additions. Emphasize natural language over slash
commands.

epf-add-template SKILL.md: add Russian name mapping for template types
(табличный документ, текстовый документ).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 12:37:42 +03:00
Nick Shirokov 34e88d2914 Add natural language usage examples to README
Show that users can describe tasks in free form — Claude will pick
the right skills automatically. Slash commands still work for precise
control.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 12:32:33 +03:00
Nick Shirokov b3dac25729 Add epf-add-help skill and help specification
New skill /epf-add-help creates built-in help files (Help.xml + HTML page)
for external data processors. Also adds IncludeHelpInContents to form
metadata if missing.

New spec docs/1c-help-spec.md documents the help file format, HTML
template, and help button integration on forms.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 22:13:47 +03:00
Nick Shirokov c2348b6b68 Add BSP skills for additional processors/reports registration
New skills for working with BSP (Standard Subsystems Library) mechanism:
- epf-bsp-init: adds СведенияОВнешнейОбработке() to object module
- epf-bsp-add-command: adds commands to existing BSP processor

Both skills use code templates in SKILL.md (no PowerShell scripts) —
Claude modifies BSL code directly via Read/Edit.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 21:48:43 +03:00
Nick Shirokov aaa4f65be1 Update README: argument hints, auto DefaultForm, usage guide
- Added parameters column to skills table
- Noted that remove skills are manual-only
- Removed --main from quick start (first form is auto-main)
- Added "Подключение к проекту" section

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 20:16:31 +03:00
Nick Shirokov d34cbf7272 Add argument-hint to all skills, disable auto-invocation for remove skills
- argument-hint: shows expected parameters when typing /command
- disable-model-invocation on epf-remove-form and epf-remove-template
  prevents Claude from invoking destructive operations autonomously

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 20:02:25 +03:00
Nick Shirokov e3daaf233d Auto-set DefaultForm for the first form added
When adding the first form to a processor, DefaultForm is now set
automatically without requiring the --main flag. The --main flag
is still available to reassign DefaultForm to a different form.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 19:31:19 +03:00
Nick Shirokov 43333f1481 Initial commit: EPF skills for Claude Code
7 skills for working with 1C external data processor XML sources:
- epf-init: scaffold a new processor (root XML + ObjectModule.bsl)
- epf-add-form: add a managed form with BSL module
- epf-add-template: add a template (HTML/Text/SpreadsheetDocument/BinaryData)
- epf-remove-form: remove a form and update root XML
- epf-remove-template: remove a template and update root XML
- epf-build: build EPF from XML (documentation only)
- epf-dump: dump EPF to XML (documentation only)

Includes XML format spec and build/dump command reference.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 19:05:27 +03:00
372 changed files with 76148 additions and 106817 deletions
-150
View File
@@ -1,150 +0,0 @@
# cf-edit — справочник операций
## modify-property
Свойства для редактирования:
### Скалярные
`Name`, `Version`, `Vendor`, `Comment`, `NamePrefix`, `UpdateCatalogAddress`
### LocalString (многоязычные)
`Synonym`, `BriefInformation`, `DetailedInformation`, `Copyright`, `VendorInformationAddress`, `ConfigurationInformationAddress`
### Enum
| Свойство | Допустимые значения |
|----------|---------------------|
| `CompatibilityMode` | `Version8_3_20` ... `Version8_3_28`, `Version8_5_1`, `DontUse` |
| `ConfigurationExtensionCompatibilityMode` | то же |
| `DefaultRunMode` | `ManagedApplication`, `OrdinaryApplication`, `Auto` |
| `ScriptVariant` | `Russian`, `English` |
| `DataLockControlMode` | `Managed`, `Automatic`, `AutomaticAndManaged` |
| `ObjectAutonumerationMode` | `NotAutoFree`, `AutoFree` |
| `ModalityUseMode` | `DontUse`, `Use`, `UseWithWarnings` |
| `SynchronousPlatformExtensionAndAddInCallUseMode` | `DontUse`, `Use`, `UseWithWarnings` |
| `InterfaceCompatibilityMode` | `Version8_2`, `Version8_2EnableTaxi`, `Taxi`, `TaxiEnableVersion8_2`, `TaxiEnableVersion8_5`, `Version8_5EnableTaxi`, `Version8_5` |
| `DatabaseTablespacesUseMode` | `DontUse`, `Use` |
| `MainClientApplicationWindowMode` | `Normal`, `Fullscreen`, `Kiosk` |
### Ref
`DefaultLanguage` — значение вида `Language.Русский`
### Формат batch
`"Version=1.0.0.1 ;; Vendor=Фирма 1С ;; Synonym=Тестовая конфигурация"`
## add-childObject / remove-childObject
Формат: `Type.Name` — XML-тип и имя объекта через точку.
**Важно про `add-childObject`**: регистрирует в `<ChildObjects>` объект, **файл которого уже существует на диске**. Если файла нет — exit 1. Для создания нового объекта используй профильный навык — `/meta-compile` (Catalog, Document, Enum, Report, регистры и т.д.), `/role-compile` (Role), `/subsystem-compile` (Subsystem). Они создают файл И регистрируют его за один вызов.
Batch: `"Catalog.Товары ;; Document.Заказ ;; Enum.ВидыОплат"`
## add-defaultRole / remove-defaultRole / set-defaultRoles
Имя роли: `ПолныеПрава` или `Role.ПолныеПрава` (префикс `Role.` добавляется автоматически).
`set-defaultRoles` полностью заменяет список ролей.
## set-panels
Перезаписывает `Ext/ClientApplicationInterface.xml` — раскладку панелей рабочего пространства Taxi. Файл создаётся с нуля; то, что не упомянуто в `value`, отсутствует на экране.
`value` — объект с ключами `top`, `left`, `right`, `bottom`. Каждый ключ — массив записей. Ключ можно опустить (= пустая сторона).
**Запись** — одна из:
- Строка-алиас (одна панель в этом слоте)
- Объект `{"group": [...]}` (стек: панели/подгруппы внутри располагаются друг под другом)
**Алиасы панелей:**
| Алиас | Панель |
|-------|--------|
| `sections` | Панель разделов |
| `open` | Панель открытых |
| `favorites` | Панель избранного |
| `history` | Панель истории |
| `functions` | Панель функций текущего раздела |
**Семантика:**
- Несколько записей в одной стороне → отдельные слоты «рядом» (несколько тегов `<top>`/...)
- `{"group":[...]}` → один тег с `<group>`-обёрткой, элементы внутри идут стеком
**Пример** (DefinitionFile):
```json
[
{
"operation": "set-panels",
"value": {
"top": ["open"],
"left": ["sections"],
"right": [{ "group": ["favorites", "history"] }],
"bottom": ["functions"]
}
}
]
```
Через `-Value` (CLI): передай объект как JSON-строку — `... -Operation set-panels -Value '{"top":["open"]}'`.
## set-home-page
Перезаписывает `Ext/HomePageWorkArea.xml` — раскладка форм на начальной странице (рабочая область). Файл создаётся с нуля; то, что не упомянуто в `value`, отсутствует.
`value` — объект:
| Ключ | Канонич. (XML) | Описание |
|------|----------------|----------|
| `template` | `WorkingAreaTemplate` | `OneColumn` / `TwoColumnsEqualWidth` (дефолт) / `TwoColumnsVariableWidth` |
| `left` | `LeftColumn` | массив записей форм |
| `right` | `RightColumn` | массив записей форм (запрещён при `OneColumn`) |
Принимаются и короткие и канонич. ключи (XML-имена) — оба работают.
**Запись формы** — одна из:
- Строка `"<form>"` — только имя формы, дефолты `height=10`, `visibility=true`
- Объект `{form, height?, visibility?, roles?}`
| Поле | Канонич. | Дефолт | Описание |
|------|----------|--------|----------|
| `form` | `Form` | — | `CommonForm.X` или `Type.Object.Form.Name` (или UUID) |
| `height` | `Height` | `10` | Высота |
| `visibility` | `Visibility` | `true` | Общая видимость (`<xr:Common>`) |
| `roles` | — | — | `{"Role.Имя": true|false, ...}` — переопределения по ролям |
**Семантика visibility:** `visibility` = общее правило, `roles` — точечные исключения. Скрыть для всех кроме одной роли: `{"visibility": false, "roles": {"Role.Опер": true}}`.
**Пример:**
```json
[
{
"operation": "set-home-page",
"value": {
"template": "TwoColumnsVariableWidth",
"left": [
"CommonForm.НачалоРаботы",
{ "form": "CommonForm.СписокЗадач", "height": 100, "visibility": false },
{ "form": "Catalog.Контрагенты.Form.ФормаСписка", "height": 50 },
{
"form": "CommonForm.РабочийСтолОператора",
"visibility": false,
"roles": { "Role.Оператор": true, "Role.ПолныеПрава": false }
}
],
"right": [
{ "form": "DataProcessor.Поиск.Form.ФормаПоиска", "height": 30 }
]
}
}
]
```
## DefinitionFile (JSON)
```json
[
{ "operation": "modify-property", "value": "Version=2.0.0.1 ;; Vendor=Test" },
{ "operation": "add-childObject", "value": "Catalog.Товары ;; Document.Заказ" },
{ "operation": "add-defaultRole", "value": "ПолныеПрава" }
]
```
-989
View File
@@ -1,989 +0,0 @@
# cf-edit v1.7 — Edit 1C configuration root (Configuration.xml)
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
param(
[Parameter(Mandatory)][Alias('Path')][string]$ConfigPath,
[string]$DefinitionFile,
[ValidateSet("modify-property","add-childObject","remove-childObject","add-defaultRole","remove-defaultRole","set-defaultRoles","set-panels","set-home-page")]
[string]$Operation,
[string]$Value,
[switch]$NoValidate
)
$ErrorActionPreference = "Stop"
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# --- Mode validation ---
if ($DefinitionFile -and $Operation) { Write-Error "Cannot use both -DefinitionFile and -Operation"; exit 1 }
if (-not $DefinitionFile -and -not $Operation) { Write-Error "Either -DefinitionFile or -Operation is required"; exit 1 }
# --- Resolve path ---
if (-not [System.IO.Path]::IsPathRooted($ConfigPath)) {
$ConfigPath = Join-Path (Get-Location).Path $ConfigPath
}
if (Test-Path $ConfigPath -PathType Container) {
$candidate = Join-Path $ConfigPath "Configuration.xml"
if (Test-Path $candidate) { $ConfigPath = $candidate }
else { Write-Error "No Configuration.xml in directory"; exit 1 }
}
if (-not (Test-Path $ConfigPath)) { Write-Error "File not found: $ConfigPath"; exit 1 }
$resolvedPath = (Resolve-Path $ConfigPath).Path
$script:configDir = [System.IO.Path]::GetDirectoryName($resolvedPath)
# --- Support guard (Ext/ParentConfigurations.bin) ---
# See docs/1c-support-state-spec.md. Blocks edits of vendor objects "на замке" /
# read-only configs unless allowed. Trigger = bin present; reaction from
# .v8-project.json editingAllowedCheck (deny|warn|off, default deny). Never
# throws — guard errors degrade to allow.
function Get-RootUuid([string]$xmlPath) {
if (-not (Test-Path $xmlPath)) { return $null }
try {
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
$el = $mx.DocumentElement.FirstChild
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
} catch {}
return $null
}
function Find-V8Project([string]$startDir) {
$d = $startDir
for ($i = 0; $i -lt 20 -and $d; $i++) {
$pj = Join-Path $d ".v8-project.json"
if (Test-Path $pj) { return $pj }
$parent = [System.IO.Path]::GetDirectoryName($d)
if ($parent -eq $d) { break }
$d = $parent
}
return $null
}
function Get-EditMode([string]$cfgDir) {
try {
$pj = Find-V8Project (Get-Location).Path
if (-not $pj) { $pj = Find-V8Project $cfgDir }
if (-not $pj) { return 'deny' }
$proj = Get-Content -Raw $pj | ConvertFrom-Json
$cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
if ($proj.databases) {
foreach ($db in $proj.databases) {
if ($db.configSrc) {
$src = [System.IO.Path]::GetFullPath($db.configSrc).TrimEnd('\', '/')
if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar)) {
if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
}
}
}
}
if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
return 'deny'
} catch { return 'deny' }
}
function Assert-EditAllowed([string]$targetPath, [string]$require) {
try {
$rp = $targetPath
try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).Path } catch {}
$elemUuid = Get-RootUuid $rp
$cfgDir = $null; $binPath = $null
$d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
for ($i = 0; $i -lt 12 -and $d; $i++) {
if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
if (-not $cfgDir) {
$cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
}
if ($elemUuid -and $cfgDir) { break }
$parent = [System.IO.Path]::GetDirectoryName($d)
if ($parent -eq $d) { break }
$d = $parent
}
# New object (no element file): fall back to config root uuid.
if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
if (-not $binPath -or -not (Test-Path $binPath)) { return }
$bytes = [System.IO.File]::ReadAllBytes($binPath)
if ($bytes.Length -le 32) { return }
$start = 0
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
$text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
$hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
if (-not $hm.Success) { return }
$G = [int]$hm.Groups[1].Value
$K = [int]$hm.Groups[2].Value
if ($K -eq 0) { return }
$best = $null
if ($elemUuid) {
$u = [regex]::Escape($elemUuid.ToLower())
foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
$f1 = [int]$m.Groups[1].Value
if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
}
}
$blocked = $false; $code = ""; $reason = ""
if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
elseif ($require -eq 'removed') {
if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
}
else {
if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
}
if (-not $blocked) { return }
$mode = Get-EditMode $cfgDir
if ($mode -eq 'off') { return }
# Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
# latter throws and would be swallowed by this function's own catch.
if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
$head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
$cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
$offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
if ($code -eq "capability-off") {
$state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
$fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
} elseif ($code -eq "not-removed") {
$state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
$fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
} else {
$state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
$fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
}
[Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
exit 1
} catch { return }
}
Assert-EditAllowed $resolvedPath 'editable'
# --- Load XML with PreserveWhitespace ---
$script:xmlDoc = New-Object System.Xml.XmlDocument
$script:xmlDoc.PreserveWhitespace = $true
$script:xmlDoc.Load($resolvedPath)
$script:addCount = 0
$script:removeCount = 0
$script:modifyCount = 0
function Info([string]$msg) { Write-Host "[INFO] $msg" }
function Warn([string]$msg) { Write-Host "[WARN] $msg" }
# --- Detect structure ---
$root = $script:xmlDoc.DocumentElement
$script:mdNs = "http://v8.1c.ru/8.3/MDClasses"
$script:xrNs = "http://v8.1c.ru/8.3/xcf/readable"
$script:xsiNs = "http://www.w3.org/2001/XMLSchema-instance"
$script:v8Ns = "http://v8.1c.ru/8.1/data/core"
$script:cfgEl = $null
foreach ($child in $root.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Configuration") {
$script:cfgEl = $child; break
}
}
if (-not $script:cfgEl) { Write-Error "No <Configuration> element found"; exit 1 }
$script:propsEl = $null
$script:childObjsEl = $null
foreach ($child in $script:cfgEl.ChildNodes) {
if ($child.NodeType -ne 'Element') { continue }
if ($child.LocalName -eq "Properties") { $script:propsEl = $child }
if ($child.LocalName -eq "ChildObjects") { $script:childObjsEl = $child }
}
$script:objName = ""
foreach ($child in $script:propsEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Name") {
$script:objName = $child.InnerText.Trim(); break
}
}
Info "Configuration: $($script:objName)"
# --- Canonical type order for ChildObjects (44 types) ---
$script:typeOrder = @(
"Language","Subsystem","StyleItem","Style",
"CommonPicture","SessionParameter","Role","CommonTemplate",
"FilterCriterion","CommonModule","CommonAttribute","ExchangePlan",
"XDTOPackage","WebService","HTTPService","WSReference",
"EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
"FunctionalOptionsParameter","DefinedType","CommonCommand","CommandGroup",
"Constant","CommonForm","Catalog","Document",
"DocumentNumerator","Sequence","DocumentJournal","Enum",
"Report","DataProcessor","InformationRegister","AccumulationRegister",
"ChartOfCharacteristicTypes","ChartOfAccounts","AccountingRegister",
"ChartOfCalculationTypes","CalculationRegister",
"BusinessProcess","Task","IntegrationService"
)
# --- Type → on-disk directory name (plural) ---
$script:typeToDir = @{
"Language"="Languages"; "Subsystem"="Subsystems"; "StyleItem"="StyleItems"; "Style"="Styles"
"CommonPicture"="CommonPictures"; "SessionParameter"="SessionParameters"; "Role"="Roles"; "CommonTemplate"="CommonTemplates"
"FilterCriterion"="FilterCriteria"; "CommonModule"="CommonModules"; "CommonAttribute"="CommonAttributes"; "ExchangePlan"="ExchangePlans"
"XDTOPackage"="XDTOPackages"; "WebService"="WebServices"; "HTTPService"="HTTPServices"; "WSReference"="WSReferences"
"EventSubscription"="EventSubscriptions"; "ScheduledJob"="ScheduledJobs"; "SettingsStorage"="SettingsStorages"; "FunctionalOption"="FunctionalOptions"
"FunctionalOptionsParameter"="FunctionalOptionsParameters"; "DefinedType"="DefinedTypes"; "CommonCommand"="CommonCommands"; "CommandGroup"="CommandGroups"
"Constant"="Constants"; "CommonForm"="CommonForms"; "Catalog"="Catalogs"; "Document"="Documents"
"DocumentNumerator"="DocumentNumerators"; "Sequence"="Sequences"; "DocumentJournal"="DocumentJournals"; "Enum"="Enums"
"Report"="Reports"; "DataProcessor"="DataProcessors"; "InformationRegister"="InformationRegisters"; "AccumulationRegister"="AccumulationRegisters"
"ChartOfCharacteristicTypes"="ChartsOfCharacteristicTypes"; "ChartOfAccounts"="ChartsOfAccounts"; "AccountingRegister"="AccountingRegisters"
"ChartOfCalculationTypes"="ChartsOfCalculationTypes"; "CalculationRegister"="CalculationRegisters"
"BusinessProcess"="BusinessProcesses"; "Task"="Tasks"; "IntegrationService"="IntegrationServices"
}
# --- XML manipulation helpers (from subsystem-edit pattern) ---
function Get-ChildIndent($container) {
foreach ($child in $container.ChildNodes) {
if ($child.NodeType -eq 'Whitespace' -or $child.NodeType -eq 'SignificantWhitespace') {
if ($child.Value -match '^\r?\n(\t+)$') { return $Matches[1] }
if ($child.Value -match '^\r?\n(\t+)') { return $Matches[1] }
}
}
$depth = 0; $current = $container
while ($current -and $current -ne $script:xmlDoc.DocumentElement) { $depth++; $current = $current.ParentNode }
return "`t" * ($depth + 1)
}
function Insert-BeforeElement($container, $newNode, $refNode, $childIndent) {
$ws = $script:xmlDoc.CreateWhitespace("`r`n$childIndent")
if ($refNode) {
$container.InsertBefore($ws, $refNode) | Out-Null
$container.InsertBefore($newNode, $ws) | Out-Null
} else {
$trailing = $container.LastChild
if ($trailing -and ($trailing.NodeType -eq 'Whitespace' -or $trailing.NodeType -eq 'SignificantWhitespace')) {
$container.InsertBefore($ws, $trailing) | Out-Null
$container.InsertBefore($newNode, $trailing) | Out-Null
} else {
$container.AppendChild($ws) | Out-Null
$container.AppendChild($newNode) | Out-Null
$parentIndent = if ($childIndent.Length -gt 1) { $childIndent.Substring(0, $childIndent.Length - 1) } else { "" }
$closeWs = $script:xmlDoc.CreateWhitespace("`r`n$parentIndent")
$container.AppendChild($closeWs) | Out-Null
}
}
}
function Remove-NodeWithWhitespace($node) {
$parent = $node.ParentNode
$prev = $node.PreviousSibling
$next = $node.NextSibling
if ($prev -and ($prev.NodeType -eq 'Whitespace' -or $prev.NodeType -eq 'SignificantWhitespace')) {
$parent.RemoveChild($prev) | Out-Null
} elseif ($next -and ($next.NodeType -eq 'Whitespace' -or $next.NodeType -eq 'SignificantWhitespace')) {
$parent.RemoveChild($next) | Out-Null
}
$parent.RemoveChild($node) | Out-Null
}
function Expand-SelfClosingElement($container, $parentIndent) {
if (-not $container.HasChildNodes -or $container.IsEmpty) {
$closeWs = $script:xmlDoc.CreateWhitespace("`r`n$parentIndent")
$container.AppendChild($closeWs) | Out-Null
}
}
function Import-Fragment([string]$xmlString) {
$wrapper = "<_W xmlns=`"$($script:mdNs)`" xmlns:xsi=`"$($script:xsiNs)`" xmlns:v8=`"$($script:v8Ns)`" xmlns:xr=`"$($script:xrNs)`" xmlns:xs=`"http://www.w3.org/2001/XMLSchema`">$xmlString</_W>"
$frag = New-Object System.Xml.XmlDocument
$frag.PreserveWhitespace = $true
$frag.LoadXml($wrapper)
$nodes = @()
foreach ($child in $frag.DocumentElement.ChildNodes) {
if ($child.NodeType -eq 'Element') {
$nodes += $script:xmlDoc.ImportNode($child, $true)
}
}
return ,$nodes
}
# --- Parse batch value (split by ;;) ---
function Parse-BatchValue([string]$val) {
$items = @()
foreach ($part in $val.Split(";;")) {
$trimmed = $part.Trim()
if ($trimmed) { $items += $trimmed }
}
return ,$items
}
# --- LocalString properties ---
$mlProps = @("Synonym","BriefInformation","DetailedInformation","Copyright","VendorInformationAddress","ConfigurationInformationAddress")
# Scalar properties
$scalarProps = @("Name","Version","Vendor","Comment","NamePrefix","UpdateCatalogAddress")
# Ref properties
$refProps = @("DefaultLanguage")
# --- Operation: modify-property ---
function Do-ModifyProperty([string]$batchVal) {
$items = Parse-BatchValue $batchVal
foreach ($item in $items) {
$eqIdx = $item.IndexOf("=")
if ($eqIdx -lt 1) {
Write-Error "Invalid property format '$item', expected 'Key=Value'"
exit 1
}
$propName = $item.Substring(0, $eqIdx).Trim()
$propValue = $item.Substring($eqIdx + 1).Trim()
# Find property element
$propEl = $null
foreach ($child in $script:propsEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq $propName) {
$propEl = $child; break
}
}
if (-not $propEl) {
Write-Error "Property '$propName' not found in Properties"
exit 1
}
if ($mlProps -contains $propName) {
# LocalString
if (-not $propValue) {
$propEl.InnerXml = ""
} else {
$indent = Get-ChildIndent $script:propsEl
$escaped = [System.Security.SecurityElement]::Escape($propValue)
$mlXml = "`r`n$indent`t<v8:item>`r`n$indent`t`t<v8:lang>ru</v8:lang>`r`n$indent`t`t<v8:content>$escaped</v8:content>`r`n$indent`t</v8:item>`r`n$indent"
$propEl.InnerXml = $mlXml
}
} elseif ($scalarProps -contains $propName -or $refProps -contains $propName) {
# Simple text
if (-not $propValue) { $propEl.InnerXml = "" }
else { $propEl.InnerText = $propValue }
} else {
# Enum or other — just set text
$propEl.InnerText = $propValue
}
$script:modifyCount++
Info "Set $propName = `"$propValue`""
}
}
# --- Operation: add-childObject ---
function Do-AddChildObject([string]$batchVal) {
if (-not $script:childObjsEl) { Write-Error "No <ChildObjects> element found"; exit 1 }
$items = Parse-BatchValue $batchVal
$cfgIndent = Get-ChildIndent $script:cfgEl
# Expand self-closing if needed
if (-not $script:childObjsEl.HasChildNodes -or $script:childObjsEl.IsEmpty) {
Expand-SelfClosingElement $script:childObjsEl $cfgIndent
}
$childIndent = Get-ChildIndent $script:childObjsEl
foreach ($item in $items) {
$dotIdx = $item.IndexOf(".")
if ($dotIdx -lt 1) {
Write-Error "Invalid format '$item', expected 'Type.Name'"
exit 1
}
$typeName = $item.Substring(0, $dotIdx)
$objNameVal = $item.Substring($dotIdx + 1)
# Check type is valid
$typeIdx = $script:typeOrder.IndexOf($typeName)
if ($typeIdx -lt 0) {
Write-Error "Unknown type '$typeName'"
exit 1
}
# Check that the referenced object actually exists on disk.
# cf-edit add-childObject is a low-level operation for rare scenarios
# (e.g. restoring a rolled-back Configuration.xml when object files are intact).
# For creating NEW objects, meta-compile/role-compile/subsystem-compile already
# auto-register in Configuration.xml — calling cf-edit add-childObject there is
# unnecessary and error-prone.
$typeDir = $script:typeToDir[$typeName]
$objFile = Join-Path (Join-Path $script:configDir $typeDir) "$objNameVal.xml"
if (-not (Test-Path $objFile)) {
$hintSkill = switch ($typeName) {
"Subsystem" { "subsystem-compile" }
"Role" { "role-compile" }
default { "meta-compile" }
}
Write-Error @"
Object file not found: $typeDir/$objNameVal.xml
cf-edit add-childObject only references objects that already exist on disk.
To create a new $typeName, use $hintSkill (auto-registers in Configuration.xml):
/$hintSkill with {"type":"$typeName","name":"$objNameVal"}
"@
exit 1
}
# Dedup check
$existing = $false
foreach ($child in $script:childObjsEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq $typeName -and $child.InnerText -eq $objNameVal) {
$existing = $true; break
}
}
if ($existing) {
Warn "Already exists: $typeName.$objNameVal"
continue
}
# Find insertion point: after last element of same type, or after last element of preceding type
$insertBefore = $null
$lastSameType = $null
$lastPrecedingType = $null
$currentTypeIdx = -1
foreach ($child in $script:childObjsEl.ChildNodes) {
if ($child.NodeType -ne 'Element') { continue }
$childTypeIdx = $script:typeOrder.IndexOf($child.LocalName)
if ($childTypeIdx -lt 0) { continue }
if ($child.LocalName -eq $typeName) {
# Same type — check alphabetical order
if ($child.InnerText -gt $objNameVal -and -not $insertBefore) {
# Insert before this element (alphabetical)
$insertBefore = $child
}
$lastSameType = $child
} elseif ($childTypeIdx -lt $typeIdx) {
$lastPrecedingType = $child
} elseif ($childTypeIdx -gt $typeIdx -and -not $insertBefore) {
# First element of a later type — insert before it
$insertBefore = $child
}
}
# Create element
$newEl = $script:xmlDoc.CreateElement($typeName, $script:mdNs)
$newEl.InnerText = $objNameVal
if ($insertBefore) {
Insert-BeforeElement $script:childObjsEl $newEl $insertBefore $childIndent
} else {
# Append at end (or after last same/preceding type)
Insert-BeforeElement $script:childObjsEl $newEl $null $childIndent
}
$script:addCount++
Info "Added: $typeName.$objNameVal"
}
}
# --- Operation: remove-childObject ---
function Do-RemoveChildObject([string]$batchVal) {
if (-not $script:childObjsEl) { Write-Error "No <ChildObjects> element found"; exit 1 }
$items = Parse-BatchValue $batchVal
foreach ($item in $items) {
$dotIdx = $item.IndexOf(".")
if ($dotIdx -lt 1) {
Write-Error "Invalid format '$item', expected 'Type.Name'"
exit 1
}
$typeName = $item.Substring(0, $dotIdx)
$objNameVal = $item.Substring($dotIdx + 1)
$found = $false
foreach ($child in @($script:childObjsEl.ChildNodes)) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq $typeName -and $child.InnerText -eq $objNameVal) {
Remove-NodeWithWhitespace $child
$script:removeCount++
Info "Removed: $typeName.$objNameVal"
$found = $true
break
}
}
if (-not $found) { Warn "Not found: $typeName.$objNameVal" }
}
}
# --- Operation: add-defaultRole ---
function Do-AddDefaultRole([string]$batchVal) {
$items = Parse-BatchValue $batchVal
# Find DefaultRoles element
$rolesEl = $null
foreach ($child in $script:propsEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "DefaultRoles") {
$rolesEl = $child; break
}
}
if (-not $rolesEl) { Write-Error "No <DefaultRoles> element found in Properties"; exit 1 }
$propsIndent = Get-ChildIndent $script:propsEl
if (-not $rolesEl.HasChildNodes -or $rolesEl.IsEmpty) {
Expand-SelfClosingElement $rolesEl $propsIndent
}
$roleIndent = Get-ChildIndent $rolesEl
foreach ($item in $items) {
$roleName = $item
if (-not $roleName.StartsWith("Role.")) { $roleName = "Role.$roleName" }
# Dedup
$existing = $false
foreach ($child in $rolesEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.InnerText.Trim() -eq $roleName) {
$existing = $true; break
}
}
if ($existing) {
Warn "DefaultRole already exists: $roleName"
continue
}
$fragXml = "<xr:Item xsi:type=`"xr:MDObjectRef`">$roleName</xr:Item>"
$nodes = Import-Fragment $fragXml
if ($nodes.Count -gt 0) {
Insert-BeforeElement $rolesEl $nodes[0] $null $roleIndent
$script:addCount++
Info "Added DefaultRole: $roleName"
}
}
}
# --- Operation: remove-defaultRole ---
function Do-RemoveDefaultRole([string]$batchVal) {
$items = Parse-BatchValue $batchVal
$rolesEl = $null
foreach ($child in $script:propsEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "DefaultRoles") {
$rolesEl = $child; break
}
}
if (-not $rolesEl) { Write-Error "No <DefaultRoles> element found"; exit 1 }
foreach ($item in $items) {
$roleName = $item
if (-not $roleName.StartsWith("Role.")) { $roleName = "Role.$roleName" }
$found = $false
foreach ($child in @($rolesEl.ChildNodes)) {
if ($child.NodeType -eq 'Element' -and $child.InnerText.Trim() -eq $roleName) {
Remove-NodeWithWhitespace $child
$script:removeCount++
Info "Removed DefaultRole: $roleName"
$found = $true
break
}
}
if (-not $found) { Warn "DefaultRole not found: $roleName" }
}
}
# --- Operation: set-panels ---
# Canonical English aliases — preferred form, used in docs and error messages.
$script:panelUuids = @{
"sections" = "b553047f-c9aa-4157-978d-448ecad24248"
"open" = "cbab57f2-a0f3-4f0a-89ea-4cb19570ab75"
"favorites" = "13322b22-3960-4d68-93a6-fe2dd7f28ca3"
"history" = "c933ac92-92cd-459d-81cc-e0c8a83ced99"
"functions" = "b2735bd3-d822-4430-ba59-c9e869693b24"
}
# Russian synonyms — silently accepted (cf-info displays Russian names; users
# may copy them straight into cf-edit value).
$script:panelSynonyms = @{
"разделов" = "sections"; "разделы" = "sections"
"открытых" = "open"; "открытые" = "open"
"избранного" = "favorites";"избранное" = "favorites"
"истории" = "history"; "история" = "history"
"функций" = "functions";"функции" = "functions"
}
function Build-PanelEntryXml($entry, [string]$indent) {
# String alias -> <panel><uuid>...</uuid></panel>
if ($entry -is [string]) {
$key = $entry.ToLowerInvariant()
if ($script:panelSynonyms.ContainsKey($key)) { $key = $script:panelSynonyms[$key] }
if (-not $script:panelUuids.ContainsKey($key)) {
Write-Error "Unknown panel alias '$entry'. Allowed: $(($script:panelUuids.Keys | Sort-Object) -join ', ')"
exit 1
}
$u = $script:panelUuids[$key]
$instId = [guid]::NewGuid().ToString()
return "$indent<panel id=`"$instId`">`r`n$indent`t<uuid>$u</uuid>`r`n$indent</panel>"
}
# Object {group: [...]} -> <group id=""><group><panel/></group>...</group> (stack)
if ($entry.PSObject.Properties['group']) {
$children = $entry.group
if (-not $children -or $children.Count -eq 0) {
Write-Error "group must contain at least one entry"
exit 1
}
$gid = [guid]::NewGuid().ToString()
$inner = ""
foreach ($child in $children) {
$childXml = Build-PanelEntryXml $child "$indent`t`t"
$inner += "$indent`t<group>`r`n$childXml`r`n$indent`t</group>`r`n"
}
return "$indent<group id=`"$gid`">`r`n$inner$indent</group>"
}
Write-Error "Panel entry must be a string alias or object {group:[...]}, got: $($entry | ConvertTo-Json -Compress)"
exit 1
}
function Do-SetPanels($valArg) {
# Accept string (JSON), PSCustomObject, or hashtable
$layout = $valArg
if ($layout -is [string]) {
try { $layout = $layout | ConvertFrom-Json } catch {
Write-Error "set-panels value must be valid JSON object, got: $valArg"
exit 1
}
}
if (-not $layout) {
Write-Error "set-panels value is empty"
exit 1
}
$sides = @("top","left","right","bottom")
$bodyParts = @()
foreach ($side in $sides) {
$entries = $null
if ($layout.PSObject.Properties[$side]) { $entries = $layout.$side }
if ($null -eq $entries) { continue }
# Normalize to array
if ($entries -isnot [System.Array] -and $entries -isnot [System.Collections.IList]) {
$entries = @($entries)
}
foreach ($entry in $entries) {
$entryXml = Build-PanelEntryXml $entry "`t`t"
$bodyParts += "`t<$side>`r`n$entryXml`r`n`t</$side>"
}
}
# Reject unknown side keys (catches typos like "Top" vs "top")
foreach ($prop in $layout.PSObject.Properties) {
if ($sides -notcontains $prop.Name) {
Write-Error "Unknown side '$($prop.Name)'. Allowed: $($sides -join ', ')"
exit 1
}
}
$body = $bodyParts -join "`r`n"
$declarations = @"
<panelDef id="b553047f-c9aa-4157-978d-448ecad24248"/>
<panelDef id="13322b22-3960-4d68-93a6-fe2dd7f28ca3"/>
<panelDef id="c933ac92-92cd-459d-81cc-e0c8a83ced99"/>
<panelDef id="cbab57f2-a0f3-4f0a-89ea-4cb19570ab75"/>
<panelDef id="b2735bd3-d822-4430-ba59-c9e869693b24"/>
"@
$bodyBlock = if ($body) { "$body`r`n" } else { "" }
$caiXml = @"
<?xml version="1.0" encoding="UTF-8"?>
<ClientApplicationInterface xmlns="http://v8.1c.ru/8.2/managed-application/core" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="InterfaceLayouter">
$bodyBlock$declarations
</ClientApplicationInterface>
"@
$extDir = Join-Path $script:configDir "Ext"
if (-not (Test-Path $extDir)) { New-Item -ItemType Directory -Path $extDir -Force | Out-Null }
$caiPath = Join-Path $extDir "ClientApplicationInterface.xml"
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
[System.IO.File]::WriteAllText($caiPath, $caiXml, $utf8Bom)
$script:modifyCount++
Info "Wrote panel layout: $caiPath"
}
# --- Operation: set-home-page ---
# Russian → English type aliases for form-ref normalization
$script:ruTypeMap = @{
"справочник" = "Catalog"
"документ" = "Document"
"перечисление" = "Enum"
"отчёт" = "Report"
"отчет" = "Report"
"обработка" = "DataProcessor"
"общаяформа" = "CommonForm"
"журналдокументов" = "DocumentJournal"
"планвидовхарактеристик" = "ChartOfCharacteristicTypes"
"плансчетов" = "ChartOfAccounts"
"планвидоврасчета" = "ChartOfCalculationTypes"
"планвидоврасчёта" = "ChartOfCalculationTypes"
"регистрсведений" = "InformationRegister"
"регистрнакопления" = "AccumulationRegister"
"регистрбухгалтерии" = "AccountingRegister"
"регистррасчета" = "CalculationRegister"
"регистррасчёта" = "CalculationRegister"
"бизнеспроцесс" = "BusinessProcess"
"задача" = "Task"
"планобмена" = "ExchangePlan"
"хранилищенастроек" = "SettingsStorage"
}
# plural folder → singular type
$script:dirToType = @{}
foreach ($k in $script:typeToDir.Keys) { $script:dirToType[$script:typeToDir[$k].ToLowerInvariant()] = $k }
function Normalize-FormRef([string]$s) {
$s = $s.Trim()
if (-not $s) { return $s }
# UUID — leave as-is
if ($s -match '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$') { return $s }
# Path form?
if ($s.Contains("/") -or $s.Contains("\")) {
$parts = $s.Replace("\","/").Split("/") | Where-Object { $_ -ne "" -and $_.ToLowerInvariant() -ne "ext" }
# Strip trailing Form.xml
if ($parts.Count -gt 0 -and $parts[-1].ToLowerInvariant() -eq "form.xml") {
$parts = @($parts[0..($parts.Count - 2)])
}
if ($parts.Count -ge 2) {
$typeDir = $parts[0]
$typeSingular = $script:dirToType[$typeDir.ToLowerInvariant()]
if ($typeSingular) {
if ($typeSingular -eq "CommonForm" -and $parts.Count -ge 2) {
return "CommonForm.$($parts[1])"
}
if ($parts.Count -ge 4 -and $parts[2].ToLowerInvariant() -eq "forms") {
return "$typeSingular.$($parts[1]).Form.$($parts[3])"
}
}
}
return $s
}
# Dot form — translate Russian head and 'Форма' segment, auto-insert 'Form'
$segs = $s.Split(".")
if ($segs.Count -ge 1) {
$head = $segs[0].ToLowerInvariant()
if ($script:ruTypeMap.ContainsKey($head)) { $segs[0] = $script:ruTypeMap[$head] }
for ($i = 1; $i -lt $segs.Count; $i++) {
if ($segs[$i] -eq "Форма") { $segs[$i] = "Form" }
}
# Auto-insert Form: for object types with 3 segments (Type.Object.FormName)
if ($segs.Count -eq 3 -and $script:typeOrder -contains $segs[0] -and $segs[0] -ne "CommonForm") {
$segs = @($segs[0], $segs[1], "Form", $segs[2])
}
}
return ($segs -join ".")
}
# Accept short DSL or canonical XML keys (silently)
function Get-FieldValue($obj, [string[]]$keys) {
foreach ($k in $keys) {
if ($obj.PSObject.Properties[$k]) { return $obj.PSObject.Properties[$k].Value }
}
return $null
}
function Build-HomePageItemXml($entry, [string]$indent) {
# Resolve fields
if ($entry -is [string]) {
$formRef = Normalize-FormRef $entry
$height = 10
$common = $true
$roles = $null
} else {
$formRaw = Get-FieldValue $entry @("form","Form")
if (-not $formRaw) { Write-Error "Home page item: 'form' is required, got: $($entry | ConvertTo-Json -Compress)"; exit 1 }
$formRef = Normalize-FormRef ([string]$formRaw)
$h = Get-FieldValue $entry @("height","Height")
$height = if ($null -ne $h) { [int]$h } else { 10 }
$vis = Get-FieldValue $entry @("visibility","Visibility")
$common = if ($null -ne $vis) { [bool]$vis } else { $true }
$roles = Get-FieldValue $entry @("roles")
}
$visParts = @()
$visParts += "$indent`t`t<xr:Common>$($common.ToString().ToLower())</xr:Common>"
if ($roles) {
# roles is PSCustomObject {Role.X: bool, ...}
foreach ($prop in $roles.PSObject.Properties) {
$rname = $prop.Name
if (-not $rname.StartsWith("Role.") -and -not ($rname -match '^[0-9a-fA-F]{8}-')) { $rname = "Role.$rname" }
$rval = ([bool]$prop.Value).ToString().ToLower()
$escName = [System.Security.SecurityElement]::Escape($rname)
$visParts += "$indent`t`t<xr:Value name=`"$escName`">$rval</xr:Value>"
}
}
$visBlock = $visParts -join "`r`n"
$escForm = [System.Security.SecurityElement]::Escape($formRef)
return @"
$indent<Item>
$indent`t<Form>$escForm</Form>
$indent`t<Height>$height</Height>
$indent`t<Visibility>
$visBlock
$indent`t</Visibility>
$indent</Item>
"@
}
function Do-SetHomePage($valArg) {
$layout = $valArg
if ($layout -is [string]) {
try { $layout = $layout | ConvertFrom-Json } catch {
Write-Error "set-home-page value must be valid JSON object"; exit 1
}
}
if (-not $layout) { Write-Error "set-home-page value is empty"; exit 1 }
$allowedTemplates = @("OneColumn","TwoColumnsEqualWidth","TwoColumnsVariableWidth")
$tmpl = Get-FieldValue $layout @("template","WorkingAreaTemplate")
if (-not $tmpl) { $tmpl = "TwoColumnsEqualWidth" }
if ($allowedTemplates -notcontains $tmpl) {
Write-Error "Unknown template '$tmpl'. Allowed: $($allowedTemplates -join ', ')"; exit 1
}
$leftItems = Get-FieldValue $layout @("left","LeftColumn")
$rightItems = Get-FieldValue $layout @("right","RightColumn")
# Reject unknown keys
$known = @("template","WorkingAreaTemplate","left","LeftColumn","right","RightColumn")
foreach ($prop in $layout.PSObject.Properties) {
if ($known -notcontains $prop.Name) {
Write-Error "Unknown key '$($prop.Name)'. Allowed: template, left, right"; exit 1
}
}
if ($tmpl -eq "OneColumn" -and $rightItems) {
Write-Error "Template 'OneColumn' cannot have items in 'right' column"; exit 1
}
function Build-Column([string]$tag, $items) {
if (-not $items) { return "`t<$tag/>" }
if ($items -isnot [System.Array] -and $items -isnot [System.Collections.IList]) {
$items = @($items)
}
if ($items.Count -eq 0) { return "`t<$tag/>" }
$itemBlocks = @()
foreach ($it in $items) {
$itemBlocks += Build-HomePageItemXml $it "`t`t"
}
$body = $itemBlocks -join "`r`n"
return "`t<$tag>`r`n$body`r`n`t</$tag>"
}
$leftXml = Build-Column "LeftColumn" $leftItems
$rightXml = Build-Column "RightColumn" $rightItems
$hpXml = @"
<?xml version="1.0" encoding="UTF-8"?>
<HomePageWorkArea xmlns="http://v8.1c.ru/8.3/xcf/extrnprops" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.17">
<WorkingAreaTemplate>$tmpl</WorkingAreaTemplate>
$leftXml
$rightXml
</HomePageWorkArea>
"@
$extDir = Join-Path $script:configDir "Ext"
if (-not (Test-Path $extDir)) { New-Item -ItemType Directory -Path $extDir -Force | Out-Null }
$hpPath = Join-Path $extDir "HomePageWorkArea.xml"
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
[System.IO.File]::WriteAllText($hpPath, $hpXml, $utf8Bom)
$script:modifyCount++
Info "Wrote home page layout: $hpPath"
}
# --- Operation: set-defaultRoles ---
function Do-SetDefaultRoles([string]$batchVal) {
$items = Parse-BatchValue $batchVal
$rolesEl = $null
foreach ($child in $script:propsEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "DefaultRoles") {
$rolesEl = $child; break
}
}
if (-not $rolesEl) { Write-Error "No <DefaultRoles> element found"; exit 1 }
# Clear all existing children
while ($rolesEl.HasChildNodes) {
$rolesEl.RemoveChild($rolesEl.FirstChild) | Out-Null
}
if ($items.Count -eq 0) {
$script:modifyCount++
Info "Cleared DefaultRoles"
return
}
$propsIndent = Get-ChildIndent $script:propsEl
$roleIndent = "$propsIndent`t"
# Add closing whitespace
$closeWs = $script:xmlDoc.CreateWhitespace("`r`n$propsIndent")
$rolesEl.AppendChild($closeWs) | Out-Null
foreach ($item in $items) {
$roleName = $item
if (-not $roleName.StartsWith("Role.")) { $roleName = "Role.$roleName" }
$fragXml = "<xr:Item xsi:type=`"xr:MDObjectRef`">$roleName</xr:Item>"
$nodes = Import-Fragment $fragXml
if ($nodes.Count -gt 0) {
Insert-BeforeElement $rolesEl $nodes[0] $null $roleIndent
}
}
$script:modifyCount++
Info "Set DefaultRoles: $($items.Count) roles"
}
# --- Execute operations ---
$operations = @()
if ($DefinitionFile) {
if (-not [System.IO.Path]::IsPathRooted($DefinitionFile)) {
$DefinitionFile = Join-Path (Get-Location).Path $DefinitionFile
}
$jsonText = Get-Content -Raw -Encoding UTF8 $DefinitionFile
$ops = $jsonText | ConvertFrom-Json
if ($ops -is [System.Array]) {
foreach ($op in $ops) { $operations += $op }
} else {
$operations += $ops
}
} else {
$operations += @{ operation = $Operation; value = $Value }
}
foreach ($op in $operations) {
$opName = if ($op.operation) { "$($op.operation)" } else { "$Operation" }
# Pass value through as-is (object or string); set-panels needs object form
$opValue = if ($null -ne $op.value) { $op.value } else { $Value }
$opValueStr = if ($opValue -is [string]) { $opValue } else { "$opValue" }
switch ($opName) {
"modify-property" { Do-ModifyProperty $opValueStr }
"add-childObject" { Do-AddChildObject $opValueStr }
"remove-childObject" { Do-RemoveChildObject $opValueStr }
"add-defaultRole" { Do-AddDefaultRole $opValueStr }
"remove-defaultRole" { Do-RemoveDefaultRole $opValueStr }
"set-defaultRoles" { Do-SetDefaultRoles $opValueStr }
"set-panels" { Do-SetPanels $opValue }
"set-home-page" { Do-SetHomePage $opValue }
default { Write-Error "Unknown operation: $opName"; exit 1 }
}
}
# --- Save ---
$settings = New-Object System.Xml.XmlWriterSettings
$settings.Encoding = New-Object System.Text.UTF8Encoding($true)
$settings.Indent = $false
$settings.NewLineHandling = [System.Xml.NewLineHandling]::None
$memStream = New-Object System.IO.MemoryStream
$writer = [System.Xml.XmlWriter]::Create($memStream, $settings)
$script:xmlDoc.Save($writer)
$writer.Flush(); $writer.Close()
$bytes = $memStream.ToArray()
$memStream.Close()
$text = [System.Text.Encoding]::UTF8.GetString($bytes)
if ($text.Length -gt 0 -and $text[0] -eq [char]0xFEFF) { $text = $text.Substring(1) }
$text = $text.Replace('encoding="utf-8"', 'encoding="UTF-8"')
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
[System.IO.File]::WriteAllText($resolvedPath, $text, $utf8Bom)
Info "Saved: $resolvedPath"
# --- Auto-validate ---
if (-not $NoValidate) {
$validateScript = Join-Path (Join-Path $PSScriptRoot "..\..\cf-validate") "scripts\cf-validate.ps1"
$validateScript = [System.IO.Path]::GetFullPath($validateScript)
if (Test-Path $validateScript) {
Write-Host ""
Write-Host "--- Running cf-validate ---"
& powershell.exe -NoProfile -File $validateScript -ConfigPath $resolvedPath
}
}
# --- Summary ---
Write-Host ""
Write-Host "=== cf-edit summary ==="
Write-Host " Configuration: $($script:objName)"
Write-Host " Added: $($script:addCount)"
Write-Host " Removed: $($script:removeCount)"
Write-Host " Modified: $($script:modifyCount)"
exit 0
-985
View File
@@ -1,985 +0,0 @@
#!/usr/bin/env python3
# cf-edit v1.7 — Edit 1C configuration root (Configuration.xml)
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import json
import os
import re
import subprocess
import sys
import uuid as _uuid
from html import escape as html_escape
from lxml import etree
# ============================================================
# Support guard (Ext/ParentConfigurations.bin) — see docs/1c-support-state-spec.md
# Blocks edits of vendor objects "на замке" / read-only configs. Trigger = bin
# present; reaction from .v8-project.json editingAllowedCheck (deny|warn|off,
# default deny). Never throws (except sys.exit on deny) — errors degrade to allow.
# ============================================================
def _sg_root_uuid(xml_path):
if not os.path.isfile(xml_path):
return None
try:
mx = etree.parse(xml_path).getroot()
for child in mx:
if isinstance(child.tag, str) and child.get("uuid"):
return child.get("uuid")
except Exception:
return None
return None
def _sg_find_v8project(start_dir):
d = start_dir
for _ in range(20):
if not d:
break
pj = os.path.join(d, ".v8-project.json")
if os.path.isfile(pj):
return pj
parent = os.path.dirname(d)
if parent == d:
break
d = parent
return None
def _sg_get_edit_mode(cfg_dir):
try:
pj = _sg_find_v8project(os.getcwd()) or _sg_find_v8project(cfg_dir)
if not pj:
return "deny"
proj = json.loads(open(pj, encoding="utf-8-sig").read())
cfg_full = os.path.normcase(os.path.abspath(cfg_dir)).rstrip("\\/")
for db in proj.get("databases", []):
src = db.get("configSrc")
if src:
src_full = os.path.normcase(os.path.abspath(src)).rstrip("\\/")
if cfg_full == src_full or cfg_full.startswith(src_full + os.sep):
if db.get("editingAllowedCheck"):
return db["editingAllowedCheck"]
if proj.get("editingAllowedCheck"):
return proj["editingAllowedCheck"]
return "deny"
except Exception:
return "deny"
def assert_edit_allowed(target_path, require):
try:
rp = os.path.abspath(target_path)
elem_uuid = _sg_root_uuid(rp)
cfg_dir = None
bin_path = None
d = rp if os.path.isdir(rp) else os.path.dirname(rp)
for _ in range(12):
if not d:
break
if not elem_uuid:
elem_uuid = _sg_root_uuid(d + ".xml")
if not cfg_dir:
cand = os.path.join(d, "Ext", "ParentConfigurations.bin")
if os.path.exists(cand) or os.path.exists(os.path.join(d, "Configuration.xml")):
cfg_dir = d
bin_path = cand
if elem_uuid and cfg_dir:
break
parent = os.path.dirname(d)
if parent == d:
break
d = parent
if not elem_uuid and cfg_dir:
elem_uuid = _sg_root_uuid(os.path.join(cfg_dir, "Configuration.xml"))
if not bin_path or not os.path.exists(bin_path):
return
data = open(bin_path, "rb").read()
if len(data) <= 32:
return
if data[:3] == b"\xef\xbb\xbf":
data = data[3:]
text = data.decode("utf-8", "replace")
h = re.match(r"\{6,(\d+),(\d+),", text)
if not h:
return
g = int(h.group(1))
k = int(h.group(2))
if k == 0:
return
best = None
if elem_uuid:
for m in re.finditer(r"([0-2]),0," + re.escape(elem_uuid.lower()), text):
f1 = int(m.group(1))
if best is None or f1 < best:
best = f1
blocked = False
code = ""
reason = ""
if g == 1:
blocked = True
code = "capability-off"
reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)"
elif require == "removed":
if best is not None and best != 2:
blocked = True
code = "not-removed"
reason = "объект не снят с поддержки — удаление сломает обновления"
else:
if best is not None and best == 0:
blocked = True
code = "locked"
reason = "объект на замке — редактирование сломает обновления"
if not blocked:
return
mode = _sg_get_edit_mode(cfg_dir)
if mode == "off":
return
if mode == "warn":
sys.stderr.write(f"[support-guard] ПРЕДУПРЕЖДЕНИЕ: {reason}. Цель: {rp}\n")
return
head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
off_note = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
if code == "capability-off":
state = f"Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «{rp}» редактировать нельзя."
fix = (
"Либо снять защиту явно (навык support-edit, два шага):\n"
f' 1. support-edit -Path "{cfg_dir}" -Capability on — включить возможность изменения (объекты пока остаются на замке);\n'
f' 2. support-edit -Path "{rp}" -Set editable — открыть этот объект для редактирования.\n'
" Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
)
elif code == "not-removed":
state = f"Состояние: объект «{rp}» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
fix = (
"Либо сначала снять объект с поддержки, затем удалять:\n"
f' support-edit -Path "{rp}" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно.'
)
else:
state = f"Состояние: объект «{rp}» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
fix = (
"Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):\n"
f' support-edit -Path "{rp}" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);\n'
f' support-edit -Path "{rp}" -Set off-support — снять с поддержки: обновления по объекту больше не приходят.'
)
sys.stderr.write(head + "\n" + state + "\n" + cfe + "\n" + fix + "\n" + off_note + "\n")
sys.exit(1)
except SystemExit:
raise
except Exception:
return
MD_NS = "http://v8.1c.ru/8.3/MDClasses"
XR_NS = "http://v8.1c.ru/8.3/xcf/readable"
XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"
V8_NS = "http://v8.1c.ru/8.1/data/core"
XS_NS = "http://www.w3.org/2001/XMLSchema"
# Canonical type order for ChildObjects (44 types)
TYPE_ORDER = [
"Language", "Subsystem", "StyleItem", "Style",
"CommonPicture", "SessionParameter", "Role", "CommonTemplate",
"FilterCriterion", "CommonModule", "CommonAttribute", "ExchangePlan",
"XDTOPackage", "WebService", "HTTPService", "WSReference",
"EventSubscription", "ScheduledJob", "SettingsStorage", "FunctionalOption",
"FunctionalOptionsParameter", "DefinedType", "CommonCommand", "CommandGroup",
"Constant", "CommonForm", "Catalog", "Document",
"DocumentNumerator", "Sequence", "DocumentJournal", "Enum",
"Report", "DataProcessor", "InformationRegister", "AccumulationRegister",
"ChartOfCharacteristicTypes", "ChartOfAccounts", "AccountingRegister",
"ChartOfCalculationTypes", "CalculationRegister",
"BusinessProcess", "Task", "IntegrationService",
]
# Type → on-disk directory name (plural)
TYPE_TO_DIR = {
"Language": "Languages", "Subsystem": "Subsystems", "StyleItem": "StyleItems", "Style": "Styles",
"CommonPicture": "CommonPictures", "SessionParameter": "SessionParameters", "Role": "Roles", "CommonTemplate": "CommonTemplates",
"FilterCriterion": "FilterCriteria", "CommonModule": "CommonModules", "CommonAttribute": "CommonAttributes", "ExchangePlan": "ExchangePlans",
"XDTOPackage": "XDTOPackages", "WebService": "WebServices", "HTTPService": "HTTPServices", "WSReference": "WSReferences",
"EventSubscription": "EventSubscriptions", "ScheduledJob": "ScheduledJobs", "SettingsStorage": "SettingsStorages", "FunctionalOption": "FunctionalOptions",
"FunctionalOptionsParameter": "FunctionalOptionsParameters", "DefinedType": "DefinedTypes", "CommonCommand": "CommonCommands", "CommandGroup": "CommandGroups",
"Constant": "Constants", "CommonForm": "CommonForms", "Catalog": "Catalogs", "Document": "Documents",
"DocumentNumerator": "DocumentNumerators", "Sequence": "Sequences", "DocumentJournal": "DocumentJournals", "Enum": "Enums",
"Report": "Reports", "DataProcessor": "DataProcessors", "InformationRegister": "InformationRegisters", "AccumulationRegister": "AccumulationRegisters",
"ChartOfCharacteristicTypes": "ChartsOfCharacteristicTypes", "ChartOfAccounts": "ChartsOfAccounts", "AccountingRegister": "AccountingRegisters",
"ChartOfCalculationTypes": "ChartsOfCalculationTypes", "CalculationRegister": "CalculationRegisters",
"BusinessProcess": "BusinessProcesses", "Task": "Tasks", "IntegrationService": "IntegrationServices",
}
ML_PROPS = ["Synonym", "BriefInformation", "DetailedInformation", "Copyright", "VendorInformationAddress", "ConfigurationInformationAddress"]
SCALAR_PROPS = ["Name", "Version", "Vendor", "Comment", "NamePrefix", "UpdateCatalogAddress"]
REF_PROPS = ["DefaultLanguage"]
def localname(el):
return etree.QName(el.tag).localname
def info(msg):
print(f"[INFO] {msg}")
def warn(msg):
print(f"[WARN] {msg}")
def get_child_indent(container):
if container.text and "\n" in container.text:
after_nl = container.text.rsplit("\n", 1)[-1]
if after_nl and not after_nl.strip():
return after_nl
for child in container:
if child.tail and "\n" in child.tail:
after_nl = child.tail.rsplit("\n", 1)[-1]
if after_nl and not after_nl.strip():
return after_nl
depth = 0
current = container
while current is not None:
depth += 1
current = current.getparent()
return "\t" * depth
def insert_before_closing(container, new_el, child_indent):
children = list(container)
if len(children) == 0:
parent_indent = child_indent[:-1] if len(child_indent) > 0 else ""
container.text = "\r\n" + child_indent
new_el.tail = "\r\n" + parent_indent
container.append(new_el)
else:
last = children[-1]
new_el.tail = last.tail
last.tail = "\r\n" + child_indent
container.append(new_el)
def insert_before_ref(container, new_el, ref_el, child_indent):
"""Insert new_el before ref_el inside container."""
idx = list(container).index(ref_el)
prev = ref_el.getprevious()
if prev is not None:
new_el.tail = prev.tail
prev.tail = "\r\n" + child_indent
else:
new_el.tail = container.text
container.text = "\r\n" + child_indent
container.insert(idx, new_el)
def remove_with_indent(el):
parent = el.getparent()
prev = el.getprevious()
if prev is not None:
if el.tail:
prev.tail = el.tail
else:
if el.tail:
parent.text = el.tail
parent.remove(el)
def expand_self_closing(container, parent_indent):
if len(container) == 0 and not (container.text and container.text.strip()):
container.text = "\r\n" + parent_indent
def import_fragment(xml_string):
wrapper = (
f'<_W xmlns="{MD_NS}" xmlns:xsi="{XSI_NS}" xmlns:v8="{V8_NS}" '
f'xmlns:xr="{XR_NS}" xmlns:xs="{XS_NS}">{xml_string}</_W>'
)
frag = etree.fromstring(wrapper.encode("utf-8"))
return list(frag)
def parse_batch_value(val):
items = []
for part in val.split(";;"):
trimmed = part.strip()
if trimmed:
items.append(trimmed)
return items
def save_xml_bom(tree, path):
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
xml_bytes = xml_bytes.replace(b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" encoding="utf-8"?>')
if not xml_bytes.endswith(b"\n"):
xml_bytes += b"\n"
with open(path, "wb") as f:
f.write(b"\xef\xbb\xbf")
f.write(xml_bytes)
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(description="Edit 1C configuration root (Configuration.xml)", allow_abbrev=False)
parser.add_argument("-ConfigPath", "-Path", required=True)
parser.add_argument("-DefinitionFile", default=None)
parser.add_argument("-Operation", default=None, choices=["modify-property", "add-childObject", "remove-childObject", "add-defaultRole", "remove-defaultRole", "set-defaultRoles", "set-panels", "set-home-page"])
parser.add_argument("-Value", default=None)
parser.add_argument("-NoValidate", action="store_true")
args = parser.parse_args()
if args.DefinitionFile and args.Operation:
print("Cannot use both -DefinitionFile and -Operation", file=sys.stderr)
sys.exit(1)
if not args.DefinitionFile and not args.Operation:
print("Either -DefinitionFile or -Operation is required", file=sys.stderr)
sys.exit(1)
config_path = args.ConfigPath
if not os.path.isabs(config_path):
config_path = os.path.join(os.getcwd(), config_path)
if os.path.isdir(config_path):
candidate = os.path.join(config_path, "Configuration.xml")
if os.path.isfile(candidate):
config_path = candidate
else:
print("No Configuration.xml in directory", file=sys.stderr)
sys.exit(1)
if not os.path.isfile(config_path):
print(f"File not found: {config_path}", file=sys.stderr)
sys.exit(1)
resolved_path = os.path.abspath(config_path)
config_dir = os.path.dirname(resolved_path)
assert_edit_allowed(resolved_path, "editable")
xml_parser = etree.XMLParser(remove_blank_text=False)
tree = etree.parse(resolved_path, xml_parser)
xml_root = tree.getroot()
add_count = 0
remove_count = 0
modify_count = 0
cfg_el = None
for child in xml_root:
if isinstance(child.tag, str) and localname(child) == "Configuration":
cfg_el = child
break
if cfg_el is None:
print("No <Configuration> element found", file=sys.stderr)
sys.exit(1)
props_el = None
child_objs_el = None
for child in cfg_el:
if not isinstance(child.tag, str):
continue
if localname(child) == "Properties":
props_el = child
if localname(child) == "ChildObjects":
child_objs_el = child
obj_name = ""
if props_el is not None:
for child in props_el:
if isinstance(child.tag, str) and localname(child) == "Name":
obj_name = (child.text or "").strip()
break
info(f"Configuration: {obj_name}")
# --- Operations ---
def do_modify_property(batch_val):
nonlocal modify_count
items = parse_batch_value(batch_val)
for item in items:
eq_idx = item.find("=")
if eq_idx < 1:
print(f"Invalid property format '{item}', expected 'Key=Value'", file=sys.stderr)
sys.exit(1)
prop_name = item[:eq_idx].strip()
prop_value = item[eq_idx + 1:].strip()
prop_el = None
for child in props_el:
if isinstance(child.tag, str) and localname(child) == prop_name:
prop_el = child
break
if prop_el is None:
print(f"Property '{prop_name}' not found in Properties", file=sys.stderr)
sys.exit(1)
if prop_name in ML_PROPS:
for ch in list(prop_el):
prop_el.remove(ch)
if not prop_value:
prop_el.text = None
else:
indent = get_child_indent(props_el)
item_el = etree.SubElement(prop_el, f"{{{V8_NS}}}item")
lang_el = etree.SubElement(item_el, f"{{{V8_NS}}}lang")
lang_el.text = "ru"
content_el = etree.SubElement(item_el, f"{{{V8_NS}}}content")
content_el.text = prop_value
prop_el.text = "\r\n" + indent + "\t"
item_el.text = "\r\n" + indent + "\t\t"
lang_el.tail = "\r\n" + indent + "\t\t"
content_el.tail = "\r\n" + indent + "\t"
item_el.tail = "\r\n" + indent
elif prop_name in SCALAR_PROPS or prop_name in REF_PROPS:
for ch in list(prop_el):
prop_el.remove(ch)
if not prop_value:
prop_el.text = None
else:
prop_el.text = prop_value
else:
for ch in list(prop_el):
prop_el.remove(ch)
prop_el.text = prop_value
modify_count += 1
info(f'Set {prop_name} = "{prop_value}"')
def do_add_child_object(batch_val):
nonlocal add_count
if child_objs_el is None:
print("No <ChildObjects> element found", file=sys.stderr)
sys.exit(1)
items = parse_batch_value(batch_val)
cfg_indent = get_child_indent(cfg_el)
if len(child_objs_el) == 0 and not (child_objs_el.text and child_objs_el.text.strip()):
expand_self_closing(child_objs_el, cfg_indent)
child_indent = get_child_indent(child_objs_el)
for item in items:
dot_idx = item.find(".")
if dot_idx < 1:
print(f"Invalid format '{item}', expected 'Type.Name'", file=sys.stderr)
sys.exit(1)
type_name = item[:dot_idx]
obj_name_val = item[dot_idx + 1:]
if type_name not in TYPE_ORDER:
print(f"Unknown type '{type_name}'", file=sys.stderr)
sys.exit(1)
type_idx = TYPE_ORDER.index(type_name)
# Check that the referenced object actually exists on disk.
# cf-edit add-childObject is a low-level operation for rare scenarios
# (e.g. restoring a rolled-back Configuration.xml when object files are intact).
# For creating NEW objects, meta-compile/role-compile/subsystem-compile already
# auto-register in Configuration.xml — calling cf-edit add-childObject there is
# unnecessary and error-prone.
type_dir = TYPE_TO_DIR.get(type_name)
obj_file = os.path.join(config_dir, type_dir, f"{obj_name_val}.xml")
if not os.path.exists(obj_file):
hint_skill = {"Subsystem": "subsystem-compile", "Role": "role-compile"}.get(type_name, "meta-compile")
print(
f"Object file not found: {type_dir}/{obj_name_val}.xml\n"
f"cf-edit add-childObject only references objects that already exist on disk.\n"
f"To create a new {type_name}, use {hint_skill} (auto-registers in Configuration.xml):\n"
f' /{hint_skill} with {{"type":"{type_name}","name":"{obj_name_val}"}}',
file=sys.stderr
)
sys.exit(1)
# Dedup
exists = False
for child in child_objs_el:
if isinstance(child.tag, str) and localname(child) == type_name and (child.text or "") == obj_name_val:
exists = True
break
if exists:
warn(f"Already exists: {type_name}.{obj_name_val}")
continue
# Find insertion point
insert_before = None
for child in child_objs_el:
if not isinstance(child.tag, str):
continue
child_type_name = localname(child)
if child_type_name not in TYPE_ORDER:
continue
child_type_idx = TYPE_ORDER.index(child_type_name)
if child_type_name == type_name:
if (child.text or "") > obj_name_val and insert_before is None:
insert_before = child
elif child_type_idx > type_idx and insert_before is None:
insert_before = child
new_el = etree.Element(f"{{{MD_NS}}}{type_name}")
new_el.text = obj_name_val
if insert_before is not None:
insert_before_ref(child_objs_el, new_el, insert_before, child_indent)
else:
insert_before_closing(child_objs_el, new_el, child_indent)
add_count += 1
info(f"Added: {type_name}.{obj_name_val}")
def do_remove_child_object(batch_val):
nonlocal remove_count
if child_objs_el is None:
print("No <ChildObjects> element found", file=sys.stderr)
sys.exit(1)
items = parse_batch_value(batch_val)
for item in items:
dot_idx = item.find(".")
if dot_idx < 1:
print(f"Invalid format '{item}', expected 'Type.Name'", file=sys.stderr)
sys.exit(1)
type_name = item[:dot_idx]
obj_name_val = item[dot_idx + 1:]
found = False
for child in list(child_objs_el):
if isinstance(child.tag, str) and localname(child) == type_name and (child.text or "") == obj_name_val:
remove_with_indent(child)
remove_count += 1
info(f"Removed: {type_name}.{obj_name_val}")
found = True
break
if not found:
warn(f"Not found: {type_name}.{obj_name_val}")
def do_add_default_role(batch_val):
nonlocal add_count
items = parse_batch_value(batch_val)
roles_el = None
for child in props_el:
if isinstance(child.tag, str) and localname(child) == "DefaultRoles":
roles_el = child
break
if roles_el is None:
print("No <DefaultRoles> element found in Properties", file=sys.stderr)
sys.exit(1)
props_indent = get_child_indent(props_el)
if len(roles_el) == 0 and not (roles_el.text and roles_el.text.strip()):
expand_self_closing(roles_el, props_indent)
role_indent = get_child_indent(roles_el)
for item in items:
role_name = item
if not role_name.startswith("Role."):
role_name = f"Role.{role_name}"
exists = False
for child in roles_el:
if isinstance(child.tag, str) and (child.text or "").strip() == role_name:
exists = True
break
if exists:
warn(f"DefaultRole already exists: {role_name}")
continue
frag_xml = f'<xr:Item xsi:type="xr:MDObjectRef">{role_name}</xr:Item>'
nodes = import_fragment(frag_xml)
if nodes:
insert_before_closing(roles_el, nodes[0], role_indent)
add_count += 1
info(f"Added DefaultRole: {role_name}")
def do_remove_default_role(batch_val):
nonlocal remove_count
items = parse_batch_value(batch_val)
roles_el = None
for child in props_el:
if isinstance(child.tag, str) and localname(child) == "DefaultRoles":
roles_el = child
break
if roles_el is None:
print("No <DefaultRoles> element found", file=sys.stderr)
sys.exit(1)
for item in items:
role_name = item
if not role_name.startswith("Role."):
role_name = f"Role.{role_name}"
found = False
for child in list(roles_el):
if isinstance(child.tag, str) and (child.text or "").strip() == role_name:
remove_with_indent(child)
remove_count += 1
info(f"Removed DefaultRole: {role_name}")
found = True
break
if not found:
warn(f"DefaultRole not found: {role_name}")
def do_set_default_roles(batch_val):
nonlocal modify_count
items = parse_batch_value(batch_val)
roles_el = None
for child in props_el:
if isinstance(child.tag, str) and localname(child) == "DefaultRoles":
roles_el = child
break
if roles_el is None:
print("No <DefaultRoles> element found", file=sys.stderr)
sys.exit(1)
# Clear all existing children
for ch in list(roles_el):
roles_el.remove(ch)
roles_el.text = None
if not items:
modify_count += 1
info("Cleared DefaultRoles")
return
props_indent = get_child_indent(props_el)
role_indent = props_indent + "\t"
roles_el.text = "\r\n" + props_indent
for item in items:
role_name = item
if not role_name.startswith("Role."):
role_name = f"Role.{role_name}"
frag_xml = f'<xr:Item xsi:type="xr:MDObjectRef">{role_name}</xr:Item>'
nodes = import_fragment(frag_xml)
if nodes:
insert_before_closing(roles_el, nodes[0], role_indent)
modify_count += 1
info(f"Set DefaultRoles: {len(items)} roles")
# --- set-panels (writes Ext/ClientApplicationInterface.xml from scratch) ---
# Canonical English aliases — preferred form, used in docs and error messages.
PANEL_UUIDS = {
"sections": "b553047f-c9aa-4157-978d-448ecad24248",
"open": "cbab57f2-a0f3-4f0a-89ea-4cb19570ab75",
"favorites": "13322b22-3960-4d68-93a6-fe2dd7f28ca3",
"history": "c933ac92-92cd-459d-81cc-e0c8a83ced99",
"functions": "b2735bd3-d822-4430-ba59-c9e869693b24",
}
# Russian synonyms — silently accepted (cf-info displays Russian names;
# users may copy them straight into cf-edit value).
PANEL_SYNONYMS = {
"разделов": "sections", "разделы": "sections",
"открытых": "open", "открытые": "open",
"избранного": "favorites","избранное": "favorites",
"истории": "history", "история": "history",
"функций": "functions", "функции": "functions",
}
def build_panel_entry_xml(entry, indent):
if isinstance(entry, str):
key = entry.lower()
key = PANEL_SYNONYMS.get(key, key)
if key not in PANEL_UUIDS:
allowed = ", ".join(sorted(PANEL_UUIDS.keys()))
print(f"Unknown panel alias '{entry}'. Allowed: {allowed}", file=sys.stderr)
sys.exit(1)
inst = str(_uuid.uuid4())
return f'{indent}<panel id="{inst}">\r\n{indent}\t<uuid>{PANEL_UUIDS[key]}</uuid>\r\n{indent}</panel>'
if isinstance(entry, dict) and "group" in entry:
children = entry["group"]
if not children:
print("group must contain at least one entry", file=sys.stderr)
sys.exit(1)
gid = str(_uuid.uuid4())
inner = ""
for child in children:
child_xml = build_panel_entry_xml(child, indent + "\t\t")
inner += f"{indent}\t<group>\r\n{child_xml}\r\n{indent}\t</group>\r\n"
return f'{indent}<group id="{gid}">\r\n{inner}{indent}</group>'
print(f"Panel entry must be string alias or {{group:[...]}}, got: {entry!r}", file=sys.stderr)
sys.exit(1)
def do_set_panels(value):
nonlocal modify_count
layout = value
if isinstance(layout, str):
try:
layout = json.loads(layout)
except json.JSONDecodeError:
print(f"set-panels value must be valid JSON object", file=sys.stderr)
sys.exit(1)
if not isinstance(layout, dict) or not layout:
print("set-panels value must be non-empty object", file=sys.stderr)
sys.exit(1)
sides = ("top", "left", "right", "bottom")
# Reject unknown side keys
for k in layout.keys():
if k not in sides:
print(f"Unknown side '{k}'. Allowed: {', '.join(sides)}", file=sys.stderr)
sys.exit(1)
body_parts = []
for side in sides:
entries = layout.get(side)
if entries is None:
continue
if not isinstance(entries, list):
entries = [entries]
for entry in entries:
entry_xml = build_panel_entry_xml(entry, "\t\t")
body_parts.append(f"\t<{side}>\r\n{entry_xml}\r\n\t</{side}>")
body = "\r\n".join(body_parts)
body_block = body + "\r\n" if body else ""
declarations = (
'\t<panelDef id="b553047f-c9aa-4157-978d-448ecad24248"/>\r\n'
'\t<panelDef id="13322b22-3960-4d68-93a6-fe2dd7f28ca3"/>\r\n'
'\t<panelDef id="c933ac92-92cd-459d-81cc-e0c8a83ced99"/>\r\n'
'\t<panelDef id="cbab57f2-a0f3-4f0a-89ea-4cb19570ab75"/>\r\n'
'\t<panelDef id="b2735bd3-d822-4430-ba59-c9e869693b24"/>'
)
cai_xml = (
'<?xml version="1.0" encoding="UTF-8"?>\r\n'
'<ClientApplicationInterface xmlns="http://v8.1c.ru/8.2/managed-application/core" '
'xmlns:xs="http://www.w3.org/2001/XMLSchema" '
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '
'xsi:type="InterfaceLayouter">\r\n'
f'{body_block}{declarations}\r\n'
'</ClientApplicationInterface>'
)
ext_dir = os.path.join(config_dir, "Ext")
os.makedirs(ext_dir, exist_ok=True)
cai_path = os.path.join(ext_dir, "ClientApplicationInterface.xml")
with open(cai_path, "w", encoding="utf-8-sig", newline="") as fh:
fh.write(cai_xml)
modify_count += 1
info(f"Wrote panel layout: {cai_path}")
# --- set-home-page (writes Ext/HomePageWorkArea.xml from scratch) ---
RU_TYPE_MAP = {
"справочник": "Catalog", "документ": "Document", "перечисление": "Enum",
"отчёт": "Report", "отчет": "Report", "обработка": "DataProcessor",
"общаяформа": "CommonForm", "журналдокументов": "DocumentJournal",
"планвидовхарактеристик": "ChartOfCharacteristicTypes",
"плансчетов": "ChartOfAccounts",
"планвидоврасчета": "ChartOfCalculationTypes",
"планвидоврасчёта": "ChartOfCalculationTypes",
"регистрсведений": "InformationRegister",
"регистрнакопления": "AccumulationRegister",
"регистрбухгалтерии": "AccountingRegister",
"регистррасчета": "CalculationRegister",
"регистррасчёта": "CalculationRegister",
"бизнеспроцесс": "BusinessProcess",
"задача": "Task", "планобмена": "ExchangePlan",
"хранилищенастроек": "SettingsStorage",
}
DIR_TO_TYPE = {v.lower(): k for k, v in TYPE_TO_DIR.items()}
UUID_RE = __import__("re").compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
def normalize_form_ref(s):
s = (s or "").strip()
if not s:
return s
if UUID_RE.match(s):
return s
if "/" in s or "\\" in s:
parts = [p for p in s.replace("\\", "/").split("/") if p and p.lower() != "ext"]
if parts and parts[-1].lower() == "form.xml":
parts = parts[:-1]
if len(parts) >= 2:
type_dir = parts[0]
type_singular = DIR_TO_TYPE.get(type_dir.lower())
if type_singular:
if type_singular == "CommonForm" and len(parts) >= 2:
return f"CommonForm.{parts[1]}"
if len(parts) >= 4 and parts[2].lower() == "forms":
return f"{type_singular}.{parts[1]}.Form.{parts[3]}"
return s
segs = s.split(".")
if segs:
head = segs[0].lower()
if head in RU_TYPE_MAP:
segs[0] = RU_TYPE_MAP[head]
for i in range(1, len(segs)):
if segs[i] == "Форма":
segs[i] = "Form"
if len(segs) == 3 and segs[0] in TYPE_ORDER and segs[0] != "CommonForm":
segs = [segs[0], segs[1], "Form", segs[2]]
return ".".join(segs)
def get_field(obj, keys):
for k in keys:
if isinstance(obj, dict) and k in obj:
return obj[k]
return None
def build_home_page_item_xml(entry, indent):
if isinstance(entry, str):
form_ref = normalize_form_ref(entry)
height = 10
common = True
roles = None
elif isinstance(entry, dict):
form_raw = get_field(entry, ["form", "Form"])
if not form_raw:
print(f"Home page item: 'form' is required, got: {entry!r}", file=sys.stderr)
sys.exit(1)
form_ref = normalize_form_ref(str(form_raw))
h = get_field(entry, ["height", "Height"])
height = int(h) if h is not None else 10
vis = get_field(entry, ["visibility", "Visibility"])
common = bool(vis) if vis is not None else True
roles = get_field(entry, ["roles"])
else:
print(f"Home page item must be string or object, got: {entry!r}", file=sys.stderr)
sys.exit(1)
vis_parts = [f"{indent}\t\t<xr:Common>{str(common).lower()}</xr:Common>"]
if roles and isinstance(roles, dict):
for rname, rval in roles.items():
if not rname.startswith("Role.") and not UUID_RE.match(rname):
rname = f"Role.{rname}"
rval_s = str(bool(rval)).lower()
vis_parts.append(f'{indent}\t\t<xr:Value name="{html_escape(rname, quote=True)}">{rval_s}</xr:Value>')
vis_block = "\r\n".join(vis_parts)
esc_form = html_escape(form_ref, quote=True)
return (
f"{indent}<Item>\r\n"
f"{indent}\t<Form>{esc_form}</Form>\r\n"
f"{indent}\t<Height>{height}</Height>\r\n"
f"{indent}\t<Visibility>\r\n"
f"{vis_block}\r\n"
f"{indent}\t</Visibility>\r\n"
f"{indent}</Item>"
)
def do_set_home_page(value):
nonlocal modify_count
layout = value
if isinstance(layout, str):
try:
layout = json.loads(layout)
except json.JSONDecodeError:
print("set-home-page value must be valid JSON object", file=sys.stderr)
sys.exit(1)
if not isinstance(layout, dict) or not layout:
print("set-home-page value must be non-empty object", file=sys.stderr)
sys.exit(1)
allowed_templates = ("OneColumn", "TwoColumnsEqualWidth", "TwoColumnsVariableWidth")
tmpl = get_field(layout, ["template", "WorkingAreaTemplate"]) or "TwoColumnsEqualWidth"
if tmpl not in allowed_templates:
print(f"Unknown template '{tmpl}'. Allowed: {', '.join(allowed_templates)}", file=sys.stderr)
sys.exit(1)
left_items = get_field(layout, ["left", "LeftColumn"])
right_items = get_field(layout, ["right", "RightColumn"])
known = {"template", "WorkingAreaTemplate", "left", "LeftColumn", "right", "RightColumn"}
for k in layout.keys():
if k not in known:
print(f"Unknown key '{k}'. Allowed: template, left, right", file=sys.stderr)
sys.exit(1)
if tmpl == "OneColumn" and right_items:
print("Template 'OneColumn' cannot have items in 'right' column", file=sys.stderr)
sys.exit(1)
def build_column(tag, items):
if not items:
return f"\t<{tag}/>"
if not isinstance(items, list):
items = [items]
if not items:
return f"\t<{tag}/>"
blocks = [build_home_page_item_xml(it, "\t\t") for it in items]
body = "\r\n".join(blocks)
return f"\t<{tag}>\r\n{body}\r\n\t</{tag}>"
left_xml = build_column("LeftColumn", left_items)
right_xml = build_column("RightColumn", right_items)
hp_xml = (
'<?xml version="1.0" encoding="UTF-8"?>\r\n'
'<HomePageWorkArea xmlns="http://v8.1c.ru/8.3/xcf/extrnprops" '
'xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" '
'xmlns:xs="http://www.w3.org/2001/XMLSchema" '
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.17">\r\n'
f'\t<WorkingAreaTemplate>{tmpl}</WorkingAreaTemplate>\r\n'
f'{left_xml}\r\n'
f'{right_xml}\r\n'
'</HomePageWorkArea>'
)
ext_dir = os.path.join(config_dir, "Ext")
os.makedirs(ext_dir, exist_ok=True)
hp_path = os.path.join(ext_dir, "HomePageWorkArea.xml")
with open(hp_path, "w", encoding="utf-8-sig", newline="") as fh:
fh.write(hp_xml)
modify_count += 1
info(f"Wrote home page layout: {hp_path}")
# --- Execute operations ---
operations = []
if args.DefinitionFile:
def_file = args.DefinitionFile
if not os.path.isabs(def_file):
def_file = os.path.join(os.getcwd(), def_file)
with open(def_file, "r", encoding="utf-8-sig") as fh:
ops = json.loads(fh.read())
if isinstance(ops, list):
operations = ops
else:
operations = [ops]
else:
operations = [{"operation": args.Operation, "value": args.Value or ""}]
for op in operations:
op_name = op.get("operation", args.Operation or "")
op_value = op.get("value", args.Value or "")
if op_name == "modify-property":
do_modify_property(op_value if isinstance(op_value, str) else str(op_value))
elif op_name == "add-childObject":
do_add_child_object(op_value if isinstance(op_value, str) else str(op_value))
elif op_name == "remove-childObject":
do_remove_child_object(op_value if isinstance(op_value, str) else str(op_value))
elif op_name == "add-defaultRole":
do_add_default_role(op_value if isinstance(op_value, str) else str(op_value))
elif op_name == "remove-defaultRole":
do_remove_default_role(op_value if isinstance(op_value, str) else str(op_value))
elif op_name == "set-defaultRoles":
do_set_default_roles(op_value if isinstance(op_value, str) else str(op_value))
elif op_name == "set-panels":
do_set_panels(op_value)
elif op_name == "set-home-page":
do_set_home_page(op_value)
else:
print(f"Unknown operation: {op_name}", file=sys.stderr)
sys.exit(1)
# --- Save ---
save_xml_bom(tree, resolved_path)
info(f"Saved: {resolved_path}")
# --- Auto-validate ---
if not args.NoValidate:
validate_script = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..", "cf-validate", "scripts", "cf-validate.py"))
if os.path.isfile(validate_script):
print()
print("--- Running cf-validate ---")
subprocess.run([sys.executable, validate_script, "-ConfigPath", resolved_path])
# --- Summary ---
print()
print("=== cf-edit summary ===")
print(f" Configuration: {obj_name}")
print(f" Added: {add_count}")
print(f" Removed: {remove_count}")
print(f" Modified: {modify_count}")
sys.exit(0)
if __name__ == "__main__":
main()
-29
View File
@@ -1,29 +0,0 @@
---
name: cf-validate
description: Валидация конфигурации 1С. Используй после создания или модификации конфигурации для проверки корректности
argument-hint: <ConfigPath> [-Detailed] [-MaxErrors 30]
allowed-tools:
- Bash
- Read
- Glob
---
# /cf-validate — валидация конфигурации 1С
Проверяет Configuration.xml на структурные ошибки: XML well-formedness, InternalInfo, свойства, enum-значения, ChildObjects, DefaultLanguage, файлы языков, каталоги объектов.
## Параметры
| Параметр | Обяз. | Умолч. | Описание |
|------------|:-----:|---------|-------------------------------------------------|
| ConfigPath | да | — | Путь к Configuration.xml или каталогу выгрузки |
| Detailed | нет | — | Подробный вывод (все проверки, включая успешные) |
| MaxErrors | нет | 30 | Остановиться после N ошибок |
| OutFile | нет | — | Записать результат в файл (UTF-8 BOM) |
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/cf-validate/scripts/cf-validate.ps1" -ConfigPath "upload/cfempty"
powershell.exe -NoProfile -File ".augment/skills/cf-validate/scripts/cf-validate.ps1" -ConfigPath "upload/cfempty/Configuration.xml"
```
-29
View File
@@ -1,29 +0,0 @@
---
name: cfe-validate
description: Валидация расширения конфигурации 1С (CFE). Используй после создания или модификации расширения для проверки корректности
argument-hint: <ExtensionPath> [-Detailed] [-MaxErrors 30]
allowed-tools:
- Bash
- Read
- Glob
---
# /cfe-validate — валидация расширения конфигурации (CFE)
Проверяет структурную корректность расширения: XML-формат, свойства, состав, заимствованные объекты. Аналог `/cf-validate`, но для расширений.
## Параметры
| Параметр | Обяз. | Умолч. | Описание |
|---------------|:-----:|---------|-------------------------------------------------|
| ExtensionPath | да | — | Путь к каталогу или Configuration.xml расширения |
| Detailed | нет | — | Подробный вывод (все проверки, включая успешные) |
| MaxErrors | нет | 30 | Остановиться после N ошибок |
| OutFile | нет | — | Записать результат в файл |
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/cfe-validate/scripts/cfe-validate.ps1" -ExtensionPath "src"
powershell.exe -NoProfile -File ".augment/skills/cfe-validate/scripts/cfe-validate.ps1" -ExtensionPath "src/Configuration.xml"
```
@@ -1,226 +0,0 @@
#!/usr/bin/env python3
# db-create v1.6 — Create 1C information base
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import atexit
import glob
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
def _find_project_v8path():
"""Walk up from CWD to find .v8-project.json and read its v8path."""
d = os.getcwd()
while True:
pf = os.path.join(d, ".v8-project.json")
if os.path.isfile(pf):
try:
with open(pf, encoding="utf-8-sig") as f:
data = json.load(f)
v = data.get("v8path")
if v:
return v
except Exception:
pass
return None
parent = os.path.dirname(d)
if parent == d:
return None
d = parent
def _version_dir(p):
"""Version dir for both Windows (.../1cv8/<ver>/bin/1cv8.exe) and *nix (.../1cv8/<ver>/1cv8)."""
parent = os.path.dirname(p)
if os.path.basename(parent).lower() == "bin":
parent = os.path.dirname(parent)
return os.path.basename(parent)
def _version_key(p):
"""Numeric sort key from version dir name."""
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
def resolve_v8path(v8path):
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
if not v8path:
v8path = _find_project_v8path()
if not v8path:
if os.name == "nt":
candidates = (
glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
+ glob.glob(r"C:\Program Files (x86)\1cv8\*\bin\1cv8.exe")
)
else:
# PY-only: PS-порт на *nix не исполняется, поэтому *nix-раскладки нет в .ps1.
candidates = glob.glob("/opt/1cv8/*/1cv8")
if candidates:
v8path = max(candidates, key=_version_key)
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
else:
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
sys.exit(1)
if os.path.isdir(v8path):
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
v8path = os.path.join(v8path, exe)
if not os.path.isfile(v8path):
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
sys.exit(1)
return v8path
IBCMD_NOUSER_HINT = (
"[ibcmd] No -UserName/-Password given; the infobase may require authentication. "
"On Windows ibcmd reads credentials from the console (stdin is ignored), so this "
"call may block instead of failing. If it does not return promptly, abort and "
"re-run with -UserName and -Password.\n"
)
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
"""Run an ibcmd command non-interactively.
input="" closes stdin (EOF) so ibcmd's auth prompt fast-fails instead of hanging.
On Windows without -UserName ibcmd reads the console directly and may still block —
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
"""
if warn_no_user and os.name == "nt" and not has_username:
sys.stderr.write(IBCMD_NOUSER_HINT)
sys.stderr.flush()
return subprocess.run(cmd, input="", capture_output=True, encoding="utf-8", errors="replace")
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(
description="Create 1C information base",
allow_abbrev=False,
)
parser.add_argument("-V8Path", default="")
parser.add_argument("-InfoBasePath", default="")
parser.add_argument("-InfoBaseServer", default="")
parser.add_argument("-InfoBaseRef", default="")
parser.add_argument("-UseTemplate", default="")
parser.add_argument("-AddToList", action="store_true")
parser.add_argument("-ListName", default="")
args = parser.parse_args()
v8path = resolve_v8path(args.V8Path)
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
# --- Validate connection ---
if engine == "ibcmd":
if not args.InfoBasePath:
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
sys.exit(1)
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
sys.exit(1)
# --- Validate template ---
if args.UseTemplate and not os.path.exists(args.UseTemplate):
print(f"Error: template file not found: {args.UseTemplate}", file=sys.stderr)
sys.exit(1)
# --- ibcmd branch (file infobase only) ---
if engine == "ibcmd":
arguments = ["infobase", "create", f"--db-path={args.InfoBasePath}", "--create-database"]
if args.UseTemplate:
if os.path.splitext(args.UseTemplate)[1].lower() == ".dt":
arguments.append(f"--restore={args.UseTemplate}")
else:
arguments.extend([f"--load={args.UseTemplate}", "--apply"])
ib_data = tempfile.mkdtemp(prefix="ibcmd_data_")
atexit.register(shutil.rmtree, ib_data, ignore_errors=True)
arguments.append(f"--data={ib_data}")
print(f"Running: ibcmd {' '.join(arguments)}")
result = run_ibcmd([v8path] + arguments, warn_no_user=False)
if result.returncode == 0:
print(f"Information base created successfully: {args.InfoBasePath}")
else:
print(f"Error creating information base (code: {result.returncode})", file=sys.stderr)
if result.stdout:
print(result.stdout)
if result.stderr:
print(result.stderr, file=sys.stderr)
sys.exit(result.returncode)
# --- Temp dir ---
temp_dir = os.path.join(tempfile.gettempdir(), f"db_create_{random.randint(0, 999999)}")
os.makedirs(temp_dir, exist_ok=True)
try:
# --- Build arguments ---
arguments = ["CREATEINFOBASE"]
if args.InfoBaseServer and args.InfoBaseRef:
# No embedded quotes: subprocess quotes the whole token; 1C's argv parser
# strips outer quotes. Inner quotes get escaped by list2cmdline and break parsing.
arguments.append(f'Srvr={args.InfoBaseServer};Ref={args.InfoBaseRef}')
else:
arguments.append(f'File={args.InfoBasePath}')
# --- Template ---
if args.UseTemplate:
arguments.extend(["/UseTemplate", args.UseTemplate])
# --- Add to list ---
if args.AddToList:
if args.ListName:
arguments.extend(["/AddToList", args.ListName])
else:
arguments.append("/AddToList")
# --- Output ---
out_file = os.path.join(temp_dir, "create_log.txt")
arguments.extend(["/Out", out_file])
arguments.append("/DisableStartupDialogs")
# --- Execute ---
print(f"Running: 1cv8.exe {' '.join(arguments)}")
result = subprocess.run(
[v8path] + arguments,
capture_output=True,
text=True,
)
exit_code = result.returncode
# --- Result ---
if exit_code == 0:
if args.InfoBaseServer and args.InfoBaseRef:
print(f"Information base created successfully: {args.InfoBaseServer}/{args.InfoBaseRef}")
else:
print(f"Information base created successfully: {args.InfoBasePath}")
else:
print(f"Error creating information base (code: {exit_code})", file=sys.stderr)
if os.path.isfile(out_file):
try:
with open(out_file, "r", encoding="utf-8-sig") as f:
log_content = f.read()
if log_content:
print("--- Log ---")
print(log_content)
print("--- End ---")
except Exception:
pass
sys.exit(exit_code)
finally:
if os.path.isdir(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=True)
if __name__ == "__main__":
main()
@@ -1,230 +0,0 @@
#!/usr/bin/env python3
# db-dump-cf v1.6 — Dump 1C configuration to CF file
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import atexit
import glob
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
def _find_project_v8path():
"""Walk up from CWD to find .v8-project.json and read its v8path."""
d = os.getcwd()
while True:
pf = os.path.join(d, ".v8-project.json")
if os.path.isfile(pf):
try:
with open(pf, encoding="utf-8-sig") as f:
data = json.load(f)
v = data.get("v8path")
if v:
return v
except Exception:
pass
return None
parent = os.path.dirname(d)
if parent == d:
return None
d = parent
def _version_dir(p):
"""Version dir for both Windows (.../1cv8/<ver>/bin/1cv8.exe) and *nix (.../1cv8/<ver>/1cv8)."""
parent = os.path.dirname(p)
if os.path.basename(parent).lower() == "bin":
parent = os.path.dirname(parent)
return os.path.basename(parent)
def _version_key(p):
"""Numeric sort key from version dir name."""
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
def resolve_v8path(v8path):
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
if not v8path:
v8path = _find_project_v8path()
if not v8path:
if os.name == "nt":
candidates = (
glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
+ glob.glob(r"C:\Program Files (x86)\1cv8\*\bin\1cv8.exe")
)
else:
# PY-only: PS-порт на *nix не исполняется, поэтому *nix-раскладки нет в .ps1.
candidates = glob.glob("/opt/1cv8/*/1cv8")
if candidates:
v8path = max(candidates, key=_version_key)
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
else:
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
sys.exit(1)
if os.path.isdir(v8path):
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
v8path = os.path.join(v8path, exe)
if not os.path.isfile(v8path):
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
sys.exit(1)
return v8path
IBCMD_NOUSER_HINT = (
"[ibcmd] No -UserName/-Password given; the infobase may require authentication. "
"On Windows ibcmd reads credentials from the console (stdin is ignored), so this "
"call may block instead of failing. If it does not return promptly, abort and "
"re-run with -UserName and -Password.\n"
)
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
"""Run an ibcmd command non-interactively.
input="" closes stdin (EOF) so ibcmd's auth prompt fast-fails instead of hanging.
On Windows without -UserName ibcmd reads the console directly and may still block —
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
"""
if warn_no_user and os.name == "nt" and not has_username:
sys.stderr.write(IBCMD_NOUSER_HINT)
sys.stderr.flush()
return subprocess.run(cmd, input="", capture_output=True, encoding="utf-8", errors="replace")
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(
description="Dump 1C configuration to CF file",
allow_abbrev=False,
)
parser.add_argument("-V8Path", default="")
parser.add_argument("-InfoBasePath", default="")
parser.add_argument("-InfoBaseServer", default="")
parser.add_argument("-InfoBaseRef", default="")
parser.add_argument("-UserName", default="")
parser.add_argument("-Password", default="")
parser.add_argument("-OutputFile", required=True)
parser.add_argument("-Extension", default="")
parser.add_argument("-AllExtensions", action="store_true")
args = parser.parse_args()
v8path = resolve_v8path(args.V8Path)
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
# --- Validate connection ---
if engine == "ibcmd":
if not args.InfoBasePath:
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
sys.exit(1)
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
sys.exit(1)
# --- Ensure output directory exists ---
out_dir = os.path.dirname(args.OutputFile)
if out_dir and not os.path.isdir(out_dir):
os.makedirs(out_dir, exist_ok=True)
# --- ibcmd branch (file infobase only) ---
if engine == "ibcmd":
if args.AllExtensions:
print("Error: ibcmd config save does not support -AllExtensions (use -Extension)", file=sys.stderr)
sys.exit(1)
arguments = ["infobase", "config", "save", f"--db-path={args.InfoBasePath}"]
if args.Extension:
arguments.append(f"--extension={args.Extension}")
arguments.append(args.OutputFile)
ib_data = tempfile.mkdtemp(prefix="ibcmd_data_")
atexit.register(shutil.rmtree, ib_data, ignore_errors=True)
if args.UserName:
arguments.append(f"--user={args.UserName}")
if args.Password:
arguments.append(f"--password={args.Password}")
arguments.append(f"--data={ib_data}")
print(f"Running: ibcmd {' '.join(arguments)}")
result = run_ibcmd([v8path] + arguments, bool(args.UserName))
if result.returncode == 0:
print(f"Configuration dumped successfully to: {args.OutputFile}")
else:
print(f"Error dumping configuration (code: {result.returncode})", file=sys.stderr)
if result.stdout:
print(result.stdout)
if result.stderr:
print(result.stderr, file=sys.stderr)
sys.exit(result.returncode)
# --- Temp dir ---
temp_dir = os.path.join(tempfile.gettempdir(), f"db_dump_cf_{random.randint(0, 999999)}")
os.makedirs(temp_dir, exist_ok=True)
try:
# --- Build arguments ---
arguments = ["DESIGNER"]
if args.InfoBaseServer and args.InfoBaseRef:
arguments.extend(["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"])
else:
arguments.extend(["/F", args.InfoBasePath])
if args.UserName:
arguments.append(f"/N{args.UserName}")
if args.Password:
arguments.append(f"/P{args.Password}")
arguments.extend(["/DumpCfg", args.OutputFile])
# --- Extensions ---
if args.Extension:
arguments.extend(["-Extension", args.Extension])
elif args.AllExtensions:
arguments.append("-AllExtensions")
# --- Output ---
out_file = os.path.join(temp_dir, "dump_cf_log.txt")
arguments.extend(["/Out", out_file])
arguments.append("/DisableStartupDialogs")
# --- Execute ---
print(f"Running: 1cv8.exe {' '.join(arguments)}")
result = subprocess.run(
[v8path] + arguments,
capture_output=True,
text=True,
)
exit_code = result.returncode
# --- Result ---
if exit_code == 0:
print(f"Configuration dumped successfully to: {args.OutputFile}")
else:
print(f"Error dumping configuration (code: {exit_code})", file=sys.stderr)
if os.path.isfile(out_file):
try:
with open(out_file, "r", encoding="utf-8-sig") as f:
log_content = f.read()
if log_content:
print("--- Log ---")
print(log_content)
print("--- End ---")
except Exception:
pass
sys.exit(exit_code)
finally:
if os.path.isdir(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=True)
if __name__ == "__main__":
main()
-72
View File
@@ -1,72 +0,0 @@
---
name: db-dump-dt
description: Выгрузка информационной базы 1С в DT-файл (вся база — конфигурация + данные). Используй когда нужно выгрузить информационную базу, выгрузить архив базы, сделать бэкап, выгрузить dt
argument-hint: "[database] [output.dt]"
allowed-tools:
- Bash
- Read
- Glob
- AskUserQuestion
---
# /db-dump-dt — Выгрузка информационной базы в DT-файл
Выгружает информационную базу целиком (конфигурация **+ данные**) в DT-файл — полный снимок ИБ.
> В отличие от `/db-dump-cf` (только конфигурация), `.dt` содержит **всю базу**: данные,
> настройки, пользователей. Это бэкап/точка отката, а не выгрузка метаданных.
## Usage
```
/db-dump-dt [database] [output.dt]
/db-dump-dt dev backup.dt
/db-dump-dt — база по умолчанию, имя файла по базе и дате
```
## Параметры подключения
Прочитай `.v8-project.json` из корня проекта. Возьми `v8path` (путь к платформе) и разреши базу:
1. Если пользователь указал параметры подключения (путь, сервер) — используй напрямую
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
4. Если ветка не совпала — используй `default`
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
Если файла нет — предложи `/db-list add`.
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/db-dump-dt/scripts/db-dump-dt.ps1" <параметры>
```
### Параметры скрипта
| Параметр | Обязательный | Описание |
|----------|:------------:|----------|
| `-V8Path <путь>` | нет | Каталог bin платформы, или полный путь к `1cv8.exe` / `ibcmd.exe` |
| `-InfoBasePath <путь>` | * | Файловая база |
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
| `-UserName <имя>` | нет | Имя пользователя |
| `-Password <пароль>` | нет | Пароль |
| `-OutputFile <путь>` | да | Путь к выходному DT-файлу |
> `*` — нужен либо `-InfoBasePath`, либо пара `-InfoBaseServer` + `-InfoBaseRef`
## Примеры
```powershell
# Выгрузка ИБ (файловая база)
powershell.exe -NoProfile -File ".augment/skills/db-dump-dt/scripts/db-dump-dt.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -OutputFile "C:\backup\base.dt"
# Серверная база
powershell.exe -NoProfile -File ".augment/skills/db-dump-dt/scripts/db-dump-dt.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Dev" -UserName "Admin" -Password "secret" -OutputFile "base.dt"
```
## Связанные навыки
- `/db-load-dt` — загрузка ИБ из DT (обратная операция)
- `/db-dump-cf` — выгрузка только конфигурации (без данных)
- `/db-create` — создать новую базу (в т.ч. из DT-шаблона)
@@ -1,226 +0,0 @@
# db-dump-dt v1.5 — Dump 1C information base to DT file
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
<#
.SYNOPSIS
Выгрузка информационной базы 1С в DT-файл
.DESCRIPTION
Выгружает информационную базу целиком (конфигурация + данные) в DT-файл.
.PARAMETER V8Path
Путь к каталогу bin платформы или к 1cv8.exe
.PARAMETER InfoBasePath
Путь к файловой информационной базе
.PARAMETER InfoBaseServer
Сервер 1С (для серверной базы)
.PARAMETER InfoBaseRef
Имя базы на сервере
.PARAMETER UserName
Имя пользователя 1С
.PARAMETER Password
Пароль пользователя
.PARAMETER OutputFile
Путь к выходному DT-файлу
.EXAMPLE
.\db-dump-dt.ps1 -InfoBasePath "C:\Bases\MyDB" -OutputFile "backup.dt"
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[string]$V8Path,
[Parameter(Mandatory=$false)]
[string]$InfoBasePath,
[Parameter(Mandatory=$false)]
[string]$InfoBaseServer,
[Parameter(Mandatory=$false)]
[string]$InfoBaseRef,
[Parameter(Mandatory=$false)]
[string]$UserName,
[Parameter(Mandatory=$false)]
[string]$Password,
[Parameter(Mandatory=$true)]
[string]$OutputFile
)
$OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# --- Resolve V8Path ---
function Find-ProjectV8Path {
$dir = (Get-Location).Path
while ($dir) {
$pf = Join-Path $dir ".v8-project.json"
if (Test-Path $pf) {
try {
$j = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
if ($j.v8path) { return [string]$j.v8path }
} catch {}
return $null
}
$parent = Split-Path $dir -Parent
if (-not $parent -or $parent -eq $dir) { break }
$dir = $parent
}
return $null
}
if (-not $V8Path) {
$V8Path = Find-ProjectV8Path
}
if (-not $V8Path) {
$found = Get-ChildItem @("C:\Program Files\1cv8\*\bin\1cv8.exe", "C:\Program Files (x86)\1cv8\*\bin\1cv8.exe") -ErrorAction SilentlyContinue |
Sort-Object { try { [version]$_.Directory.Parent.Name } catch { [version]"0.0" } } -Descending |
Select-Object -First 1
if ($found) {
$V8Path = $found.FullName
Write-Host "Auto-selected platform $($found.Directory.Parent.Name): $V8Path" -ForegroundColor Yellow
} else {
Write-Host "Error: 1C executable not found. Specify -V8Path" -ForegroundColor Red
exit 1
}
}
if (Test-Path $V8Path -PathType Container) {
$V8Path = Join-Path $V8Path "1cv8.exe"
}
if (-not (Test-Path $V8Path)) {
Write-Host "Error: 1C executable not found at $V8Path" -ForegroundColor Red
exit 1
}
# --- Detect engine (ibcmd vs 1cv8) by exe name ---
function Invoke-IbcmdProcess {
# Run ibcmd non-interactively: a closed stdin pipe (EOF) makes ibcmd's auth prompt
# fast-fail instead of hanging. Returns @{ Output; ExitCode }. cp866 decodes ibcmd's
# native OEM output. The 1cv8/DESIGNER branch keeps using Start-Process.
param([string]$Exe, [string[]]$IbArgs)
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $Exe
$psi.Arguments = ($IbArgs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.RedirectStandardInput = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
try {
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding(866)
$psi.StandardErrorEncoding = [System.Text.Encoding]::GetEncoding(866)
} catch {}
$p = [System.Diagnostics.Process]::Start($psi)
$p.StandardInput.Close()
$out = $p.StandardOutput.ReadToEnd()
$err = $p.StandardError.ReadToEnd()
$p.WaitForExit()
if ($err) { $out += $err }
return [pscustomobject]@{ Output = $out; ExitCode = $p.ExitCode }
}
$engine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
# --- Validate connection ---
if ($engine -eq "ibcmd") {
if (-not $InfoBasePath) {
Write-Host "Error: ibcmd supports file infobases only (use -InfoBasePath)" -ForegroundColor Red
exit 1
}
} elseif (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
exit 1
}
# --- Ensure output directory exists ---
$outDir = Split-Path $OutputFile -Parent
if ($outDir -and -not (Test-Path $outDir)) {
New-Item -ItemType Directory -Path $outDir -Force | Out-Null
}
# --- Temp dir ---
$tempDir = Join-Path $env:TEMP "db_dump_dt_$(Get-Random)"
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
try {
if ($engine -eq "ibcmd") {
# --- ibcmd branch (file infobase only) ---
$arguments = @("infobase", "dump", "--db-path=$InfoBasePath")
if ($UserName) { $arguments += "--user=$UserName" }
if ($Password) { $arguments += "--password=$Password" }
$arguments += "$OutputFile"
$arguments += "--data=$tempDir"
Write-Host "Running: ibcmd $($arguments -join ' ')"
$__ib = Invoke-IbcmdProcess $V8Path $arguments
$output = $__ib.Output
$exitCode = $__ib.ExitCode
if ($exitCode -eq 0) {
Write-Host "Information base dumped successfully to: $OutputFile" -ForegroundColor Green
} else {
Write-Host "Error dumping information base (code: $exitCode)" -ForegroundColor Red
}
if ($output) { Write-Host ($output | Out-String) }
exit $exitCode
}
# --- 1cv8 branch ---
# --- Build arguments ---
$arguments = @("DESIGNER")
if ($InfoBaseServer -and $InfoBaseRef) {
$arguments += "/S", "`"$InfoBaseServer/$InfoBaseRef`""
} else {
$arguments += "/F", "`"$InfoBasePath`""
}
if ($UserName) { $arguments += "/N`"$UserName`"" }
if ($Password) { $arguments += "/P`"$Password`"" }
$arguments += "/DumpIB", "`"$OutputFile`""
# --- Output ---
$outFile = Join-Path $tempDir "dump_dt_log.txt"
$arguments += "/Out", "`"$outFile`""
$arguments += "/DisableStartupDialogs"
# --- Execute ---
Write-Host "Running: 1cv8.exe $($arguments -join ' ')"
$process = Start-Process -FilePath $V8Path -ArgumentList $arguments -NoNewWindow -Wait -PassThru
$exitCode = $process.ExitCode
# --- Result ---
if ($exitCode -eq 0) {
Write-Host "Information base dumped successfully to: $OutputFile" -ForegroundColor Green
} else {
Write-Host "Error dumping information base (code: $exitCode)" -ForegroundColor Red
}
if (Test-Path $outFile) {
$logContent = Get-Content $outFile -Raw -ErrorAction SilentlyContinue
if ($logContent) {
Write-Host "--- Log ---"
Write-Host $logContent
Write-Host "--- End ---"
}
}
exit $exitCode
} finally {
if (Test-Path $tempDir) {
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
}
}
@@ -1,217 +0,0 @@
#!/usr/bin/env python3
# db-dump-dt v1.5 — Dump 1C information base to DT file
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import atexit
import glob
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
def _find_project_v8path():
"""Walk up from CWD to find .v8-project.json and read its v8path."""
d = os.getcwd()
while True:
pf = os.path.join(d, ".v8-project.json")
if os.path.isfile(pf):
try:
with open(pf, encoding="utf-8-sig") as f:
data = json.load(f)
v = data.get("v8path")
if v:
return v
except Exception:
pass
return None
parent = os.path.dirname(d)
if parent == d:
return None
d = parent
def _version_dir(p):
"""Version dir for both Windows (.../1cv8/<ver>/bin/1cv8.exe) and *nix (.../1cv8/<ver>/1cv8)."""
parent = os.path.dirname(p)
if os.path.basename(parent).lower() == "bin":
parent = os.path.dirname(parent)
return os.path.basename(parent)
def _version_key(p):
"""Numeric sort key from version dir name."""
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
def resolve_v8path(v8path):
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
if not v8path:
v8path = _find_project_v8path()
if not v8path:
if os.name == "nt":
candidates = (
glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
+ glob.glob(r"C:\Program Files (x86)\1cv8\*\bin\1cv8.exe")
)
else:
# PY-only: PS-порт на *nix не исполняется, поэтому *nix-раскладки нет в .ps1.
candidates = glob.glob("/opt/1cv8/*/1cv8")
if candidates:
v8path = max(candidates, key=_version_key)
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
else:
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
sys.exit(1)
if os.path.isdir(v8path):
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
v8path = os.path.join(v8path, exe)
if not os.path.isfile(v8path):
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
sys.exit(1)
return v8path
IBCMD_NOUSER_HINT = (
"[ibcmd] No -UserName/-Password given; the infobase may require authentication. "
"On Windows ibcmd reads credentials from the console (stdin is ignored), so this "
"call may block instead of failing. If it does not return promptly, abort and "
"re-run with -UserName and -Password.\n"
)
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
"""Run an ibcmd command non-interactively.
input="" closes stdin (EOF) so ibcmd's auth prompt fast-fails instead of hanging.
On Windows without -UserName ibcmd reads the console directly and may still block —
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
"""
if warn_no_user and os.name == "nt" and not has_username:
sys.stderr.write(IBCMD_NOUSER_HINT)
sys.stderr.flush()
return subprocess.run(cmd, input="", capture_output=True, encoding="utf-8", errors="replace")
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(
description="Dump 1C information base to DT file",
allow_abbrev=False,
)
parser.add_argument("-V8Path", default="")
parser.add_argument("-InfoBasePath", default="")
parser.add_argument("-InfoBaseServer", default="")
parser.add_argument("-InfoBaseRef", default="")
parser.add_argument("-UserName", default="")
parser.add_argument("-Password", default="")
parser.add_argument("-OutputFile", required=True)
args = parser.parse_args()
v8path = resolve_v8path(args.V8Path)
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
# --- Validate connection ---
if engine == "ibcmd":
if not args.InfoBasePath:
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
sys.exit(1)
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
sys.exit(1)
# --- Ensure output directory exists ---
out_dir = os.path.dirname(args.OutputFile)
if out_dir and not os.path.isdir(out_dir):
os.makedirs(out_dir, exist_ok=True)
# --- ibcmd branch (file infobase only) ---
if engine == "ibcmd":
arguments = ["infobase", "dump", f"--db-path={args.InfoBasePath}"]
if args.UserName:
arguments.append(f"--user={args.UserName}")
if args.Password:
arguments.append(f"--password={args.Password}")
arguments.append(args.OutputFile)
ib_data = tempfile.mkdtemp(prefix="ibcmd_data_")
atexit.register(shutil.rmtree, ib_data, ignore_errors=True)
arguments.append(f"--data={ib_data}")
print(f"Running: ibcmd {' '.join(arguments)}")
result = run_ibcmd([v8path] + arguments, bool(args.UserName))
if result.returncode == 0:
print(f"Information base dumped successfully to: {args.OutputFile}")
else:
print(f"Error dumping information base (code: {result.returncode})", file=sys.stderr)
if result.stdout:
print(result.stdout)
if result.stderr:
print(result.stderr, file=sys.stderr)
sys.exit(result.returncode)
# --- Temp dir ---
temp_dir = os.path.join(tempfile.gettempdir(), f"db_dump_dt_{random.randint(0, 999999)}")
os.makedirs(temp_dir, exist_ok=True)
try:
# --- Build arguments ---
arguments = ["DESIGNER"]
if args.InfoBaseServer and args.InfoBaseRef:
arguments.extend(["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"])
else:
arguments.extend(["/F", args.InfoBasePath])
if args.UserName:
arguments.append(f"/N{args.UserName}")
if args.Password:
arguments.append(f"/P{args.Password}")
arguments.extend(["/DumpIB", args.OutputFile])
# --- Output ---
out_file = os.path.join(temp_dir, "dump_dt_log.txt")
arguments.extend(["/Out", out_file])
arguments.append("/DisableStartupDialogs")
# --- Execute ---
print(f"Running: 1cv8.exe {' '.join(arguments)}")
result = subprocess.run(
[v8path] + arguments,
capture_output=True,
text=True,
)
exit_code = result.returncode
# --- Result ---
if exit_code == 0:
print(f"Information base dumped successfully to: {args.OutputFile}")
else:
print(f"Error dumping information base (code: {exit_code})", file=sys.stderr)
if os.path.isfile(out_file):
try:
with open(out_file, "r", encoding="utf-8-sig") as f:
log_content = f.read()
if log_content:
print("--- Log ---")
print(log_content)
print("--- End ---")
except Exception:
pass
sys.exit(exit_code)
finally:
if os.path.isdir(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=True)
if __name__ == "__main__":
main()
@@ -1,285 +0,0 @@
#!/usr/bin/env python3
# db-dump-xml v1.8 — Dump 1C configuration to XML files
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import atexit
import glob
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
def _find_project_v8path():
"""Walk up from CWD to find .v8-project.json and read its v8path."""
d = os.getcwd()
while True:
pf = os.path.join(d, ".v8-project.json")
if os.path.isfile(pf):
try:
with open(pf, encoding="utf-8-sig") as f:
data = json.load(f)
v = data.get("v8path")
if v:
return v
except Exception:
pass
return None
parent = os.path.dirname(d)
if parent == d:
return None
d = parent
def _version_dir(p):
"""Version dir for both Windows (.../1cv8/<ver>/bin/1cv8.exe) and *nix (.../1cv8/<ver>/1cv8)."""
parent = os.path.dirname(p)
if os.path.basename(parent).lower() == "bin":
parent = os.path.dirname(parent)
return os.path.basename(parent)
def _version_key(p):
"""Numeric sort key from version dir name."""
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
def resolve_v8path(v8path):
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
if not v8path:
v8path = _find_project_v8path()
if not v8path:
if os.name == "nt":
candidates = (
glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
+ glob.glob(r"C:\Program Files (x86)\1cv8\*\bin\1cv8.exe")
)
else:
# PY-only: PS-порт на *nix не исполняется, поэтому *nix-раскладки нет в .ps1.
candidates = glob.glob("/opt/1cv8/*/1cv8")
if candidates:
v8path = max(candidates, key=_version_key)
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
else:
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
sys.exit(1)
if os.path.isdir(v8path):
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
v8path = os.path.join(v8path, exe)
if not os.path.isfile(v8path):
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
sys.exit(1)
return v8path
IBCMD_NOUSER_HINT = (
"[ibcmd] No -UserName/-Password given; the infobase may require authentication. "
"On Windows ibcmd reads credentials from the console (stdin is ignored), so this "
"call may block instead of failing. If it does not return promptly, abort and "
"re-run with -UserName and -Password.\n"
)
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
"""Run an ibcmd command non-interactively.
input="" closes stdin (EOF) so ibcmd's auth prompt fast-fails instead of hanging.
On Windows without -UserName ibcmd reads the console directly and may still block —
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
"""
if warn_no_user and os.name == "nt" and not has_username:
sys.stderr.write(IBCMD_NOUSER_HINT)
sys.stderr.flush()
return subprocess.run(cmd, input="", capture_output=True, encoding="utf-8", errors="replace")
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(
description="Dump 1C configuration to XML files",
allow_abbrev=False,
)
parser.add_argument("-V8Path", default="", help="Path to 1cv8.exe or its bin directory")
parser.add_argument("-InfoBasePath", default="", help="Path to file infobase")
parser.add_argument("-InfoBaseServer", default="", help="1C server (for server infobase)")
parser.add_argument("-InfoBaseRef", default="", help="Infobase name on server")
parser.add_argument("-UserName", default="", help="1C user name")
parser.add_argument("-Password", default="", help="1C user password")
parser.add_argument("-ConfigDir", required=True, help="Directory for configuration dump")
parser.add_argument(
"-Mode",
default="Changes",
choices=["Full", "Changes", "Partial", "UpdateInfo"],
help="Dump mode (default: Changes)",
)
parser.add_argument("-Objects", default="", help="Comma-separated metadata object names (for Partial mode)")
parser.add_argument("-Extension", default="", help="Extension name to dump")
parser.add_argument("-AllExtensions", action="store_true", help="Dump all extensions")
parser.add_argument(
"-Format",
default="Hierarchical",
choices=["Hierarchical", "Plain"],
help="Dump format (default: Hierarchical)",
)
args = parser.parse_args()
# --- Resolve V8Path ---
v8path = resolve_v8path(args.V8Path)
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
# --- Validate connection ---
if engine == "ibcmd":
if not args.InfoBasePath:
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
sys.exit(1)
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
sys.exit(1)
# --- Validate Partial mode ---
if args.Mode == "Partial" and not args.Objects:
print("Error: -Objects required for Partial mode", file=sys.stderr)
sys.exit(1)
# --- Create output dir if needed ---
if not os.path.exists(args.ConfigDir):
os.makedirs(args.ConfigDir, exist_ok=True)
print(f"Created output directory: {args.ConfigDir}")
# --- ibcmd branch (file infobase only; hierarchical Full/Changes) ---
if engine == "ibcmd":
if args.Format == "Plain":
print("Error: ibcmd config export supports hierarchical format only (use -Format Hierarchical or 1cv8)", file=sys.stderr)
sys.exit(1)
if args.AllExtensions:
arguments = ["infobase", "config", "export", "all-extensions", args.ConfigDir, f"--db-path={args.InfoBasePath}"]
elif args.Mode == "UpdateInfo":
print("Error: ibcmd config export does not support Mode UpdateInfo; use 1cv8", file=sys.stderr)
sys.exit(1)
elif args.Mode == "Partial":
obj_list = [o.strip() for o in args.Objects.split(",") if o.strip()]
arguments = ["infobase", "config", "export", "objects"] + obj_list
arguments += [f"--out={args.ConfigDir}", f"--db-path={args.InfoBasePath}"]
if args.Extension:
arguments.append(f"--extension={args.Extension}")
else:
arguments = ["infobase", "config", "export", f"--db-path={args.InfoBasePath}"]
if args.Extension:
arguments.append(f"--extension={args.Extension}")
arguments.append(args.ConfigDir)
ib_data = tempfile.mkdtemp(prefix="ibcmd_data_")
atexit.register(shutil.rmtree, ib_data, ignore_errors=True)
if args.UserName:
arguments.append(f"--user={args.UserName}")
if args.Password:
arguments.append(f"--password={args.Password}")
arguments.append(f"--data={ib_data}")
print(f"Running: ibcmd {' '.join(arguments)}")
result = run_ibcmd([v8path] + arguments, bool(args.UserName))
if result.returncode == 0:
print(f"Configuration exported successfully to: {args.ConfigDir}")
else:
print(f"Error exporting configuration (code: {result.returncode})", file=sys.stderr)
if result.stdout:
print(result.stdout)
if result.stderr:
print(result.stderr, file=sys.stderr)
sys.exit(result.returncode)
# --- Temp dir ---
temp_dir = os.path.join(tempfile.gettempdir(), f"db_dump_xml_{random.randint(0, 999999)}")
os.makedirs(temp_dir, exist_ok=True)
try:
# --- Build arguments ---
arguments = ["DESIGNER"]
if args.InfoBaseServer and args.InfoBaseRef:
arguments += ["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"]
else:
arguments += ["/F", args.InfoBasePath]
if args.UserName:
arguments.append(f"/N{args.UserName}")
if args.Password:
arguments.append(f"/P{args.Password}")
arguments += ["/DumpConfigToFiles", args.ConfigDir]
arguments += ["-Format", args.Format]
if args.Mode == "Full":
print("Executing full configuration dump...")
elif args.Mode == "Changes":
print("Executing incremental configuration dump...")
arguments.append("-update")
arguments.append("-force")
elif args.Mode == "Partial":
print("Executing partial configuration dump...")
object_list = [obj.strip() for obj in args.Objects.split(",") if obj.strip()]
list_file = os.path.join(temp_dir, "dump_list.txt")
with open(list_file, "w", encoding="utf-8-sig") as f:
f.write("\n".join(object_list))
arguments += ["-listFile", list_file]
print(f"Objects to dump: {len(object_list)}")
for obj in object_list:
print(f" {obj}")
elif args.Mode == "UpdateInfo":
print("Updating ConfigDumpInfo.xml...")
arguments.append("-configDumpInfoOnly")
# --- Extensions ---
if args.Extension:
arguments += ["-Extension", args.Extension]
elif args.AllExtensions:
arguments.append("-AllExtensions")
# --- Output ---
out_file = os.path.join(temp_dir, "dump_log.txt")
arguments += ["/Out", out_file]
arguments.append("/DisableStartupDialogs")
# --- Execute ---
print(f"Running: 1cv8.exe {' '.join(arguments)}")
result = subprocess.run(
[v8path] + arguments,
capture_output=True,
text=True,
)
exit_code = result.returncode
# --- Result ---
if exit_code == 0:
print("Dump completed successfully")
print(f"Configuration dumped to: {args.ConfigDir}")
else:
print(f"Error dumping configuration (code: {exit_code})", file=sys.stderr)
if os.path.isfile(out_file):
try:
with open(out_file, "r", encoding="utf-8-sig") as f:
log_content = f.read()
if log_content:
print("--- Log ---")
print(log_content)
print("--- End ---")
except Exception:
pass
sys.exit(exit_code)
finally:
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=True)
if __name__ == "__main__":
main()
@@ -1,230 +0,0 @@
#!/usr/bin/env python3
# db-load-cf v1.6 — Load 1C configuration from CF file
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import atexit
import glob
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
def _find_project_v8path():
"""Walk up from CWD to find .v8-project.json and read its v8path."""
d = os.getcwd()
while True:
pf = os.path.join(d, ".v8-project.json")
if os.path.isfile(pf):
try:
with open(pf, encoding="utf-8-sig") as f:
data = json.load(f)
v = data.get("v8path")
if v:
return v
except Exception:
pass
return None
parent = os.path.dirname(d)
if parent == d:
return None
d = parent
def _version_dir(p):
"""Version dir for both Windows (.../1cv8/<ver>/bin/1cv8.exe) and *nix (.../1cv8/<ver>/1cv8)."""
parent = os.path.dirname(p)
if os.path.basename(parent).lower() == "bin":
parent = os.path.dirname(parent)
return os.path.basename(parent)
def _version_key(p):
"""Numeric sort key from version dir name."""
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
def resolve_v8path(v8path):
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
if not v8path:
v8path = _find_project_v8path()
if not v8path:
if os.name == "nt":
candidates = (
glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
+ glob.glob(r"C:\Program Files (x86)\1cv8\*\bin\1cv8.exe")
)
else:
# PY-only: PS-порт на *nix не исполняется, поэтому *nix-раскладки нет в .ps1.
candidates = glob.glob("/opt/1cv8/*/1cv8")
if candidates:
v8path = max(candidates, key=_version_key)
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
else:
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
sys.exit(1)
if os.path.isdir(v8path):
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
v8path = os.path.join(v8path, exe)
if not os.path.isfile(v8path):
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
sys.exit(1)
return v8path
IBCMD_NOUSER_HINT = (
"[ibcmd] No -UserName/-Password given; the infobase may require authentication. "
"On Windows ibcmd reads credentials from the console (stdin is ignored), so this "
"call may block instead of failing. If it does not return promptly, abort and "
"re-run with -UserName and -Password.\n"
)
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
"""Run an ibcmd command non-interactively.
input="" closes stdin (EOF) so ibcmd's auth prompt fast-fails instead of hanging.
On Windows without -UserName ibcmd reads the console directly and may still block —
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
"""
if warn_no_user and os.name == "nt" and not has_username:
sys.stderr.write(IBCMD_NOUSER_HINT)
sys.stderr.flush()
return subprocess.run(cmd, input="", capture_output=True, encoding="utf-8", errors="replace")
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(
description="Load 1C configuration from CF file",
allow_abbrev=False,
)
parser.add_argument("-V8Path", default="")
parser.add_argument("-InfoBasePath", default="")
parser.add_argument("-InfoBaseServer", default="")
parser.add_argument("-InfoBaseRef", default="")
parser.add_argument("-UserName", default="")
parser.add_argument("-Password", default="")
parser.add_argument("-InputFile", required=True)
parser.add_argument("-Extension", default="")
parser.add_argument("-AllExtensions", action="store_true")
args = parser.parse_args()
v8path = resolve_v8path(args.V8Path)
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
# --- Validate connection ---
if engine == "ibcmd":
if not args.InfoBasePath:
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
sys.exit(1)
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
sys.exit(1)
# --- Validate input file ---
if not os.path.isfile(args.InputFile):
print(f"Error: input file not found: {args.InputFile}", file=sys.stderr)
sys.exit(1)
# --- ibcmd branch (file infobase only) ---
if engine == "ibcmd":
if args.AllExtensions:
print("Error: ibcmd config load does not support -AllExtensions (use -Extension)", file=sys.stderr)
sys.exit(1)
arguments = ["infobase", "config", "load", f"--db-path={args.InfoBasePath}"]
if args.Extension:
arguments.append(f"--extension={args.Extension}")
arguments.append(args.InputFile)
ib_data = tempfile.mkdtemp(prefix="ibcmd_data_")
atexit.register(shutil.rmtree, ib_data, ignore_errors=True)
if args.UserName:
arguments.append(f"--user={args.UserName}")
if args.Password:
arguments.append(f"--password={args.Password}")
arguments.append(f"--data={ib_data}")
print(f"Running: ibcmd {' '.join(arguments)}")
result = run_ibcmd([v8path] + arguments, bool(args.UserName))
if result.returncode == 0:
print(f"Configuration loaded successfully from: {args.InputFile}")
else:
print(f"Error loading configuration (code: {result.returncode})", file=sys.stderr)
if result.stdout:
print(result.stdout)
if result.stderr:
print(result.stderr, file=sys.stderr)
sys.exit(result.returncode)
# --- Temp dir ---
temp_dir = os.path.join(tempfile.gettempdir(), f"db_load_cf_{random.randint(0, 999999)}")
os.makedirs(temp_dir, exist_ok=True)
try:
# --- Build arguments ---
arguments = ["DESIGNER"]
if args.InfoBaseServer and args.InfoBaseRef:
arguments.extend(["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"])
else:
arguments.extend(["/F", args.InfoBasePath])
if args.UserName:
arguments.append(f"/N{args.UserName}")
if args.Password:
arguments.append(f"/P{args.Password}")
arguments.extend(["/LoadCfg", args.InputFile])
# --- Extensions ---
if args.Extension:
arguments.extend(["-Extension", args.Extension])
elif args.AllExtensions:
arguments.append("-AllExtensions")
# --- Output ---
out_file = os.path.join(temp_dir, "load_cf_log.txt")
arguments.extend(["/Out", out_file])
arguments.append("/DisableStartupDialogs")
# --- Execute ---
print(f"Running: 1cv8.exe {' '.join(arguments)}")
result = subprocess.run(
[v8path] + arguments,
capture_output=True,
text=True,
)
exit_code = result.returncode
# --- Result ---
if exit_code == 0:
print(f"Configuration loaded successfully from: {args.InputFile}")
else:
print(f"Error loading configuration (code: {exit_code})", file=sys.stderr)
if os.path.isfile(out_file):
try:
with open(out_file, "r", encoding="utf-8-sig") as f:
log_content = f.read()
if log_content:
print("--- Log ---")
print(log_content)
print("--- End ---")
except Exception:
pass
sys.exit(exit_code)
finally:
if os.path.isdir(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=True)
if __name__ == "__main__":
main()
-92
View File
@@ -1,92 +0,0 @@
---
name: db-load-dt
description: Загрузка информационной базы 1С из DT-файла — полная перезапись базы (конфигурация + данные). Используй когда нужно загрузить архив информационной базы, восстановить базу, загрузить dt
disable-model-invocation: true
argument-hint: <input.dt> [database]
allowed-tools:
- Bash
- Read
- Glob
- AskUserQuestion
---
# /db-load-dt — Загрузка информационной базы из DT-файла
Восстанавливает информационную базу целиком (конфигурация **+ данные**) из DT-файла.
> ⚠️ **Необратимая операция.** Загрузка `.dt` **полностью перезаписывает базу** — и
> конфигурацию, и все данные. Текущее содержимое базы будет потеряно. После загрузки
> `/db-update` **не нужен** — конфигурация БД уже синхронна внутри снимка.
## Когда НЕ использовать
- Нужно создать **новую** базу из `.dt` → используй `/db-create` (из DT-шаблона), а не загрузку
в существующую.
- Нужно обновить только конфигурацию (без данных) → `/db-load-cf` или `/db-load-xml`.
## Usage
```
/db-load-dt <input.dt> [database]
/db-load-dt backup.dt dev
```
## Порядок действий перед загрузкой
1. Предложи пользователю сначала сделать `/db-dump-dt` текущего состояния базы — это точка
отката (восстановиться будет нечем, если не сохранить).
2. Запроси **явное подтверждение**: вся база (данные + конфигурация) будет перезаписана.
3. Только после подтверждения выполняй загрузку.
## Параметры подключения
Прочитай `.v8-project.json` из корня проекта. Возьми `v8path` (путь к платформе) и разреши базу:
1. Если пользователь указал параметры подключения (путь, сервер) — используй напрямую
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
4. Если ветка не совпала — используй `default`
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
Если файла нет — предложи `/db-list add`.
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/db-load-dt/scripts/db-load-dt.ps1" <параметры>
```
### Параметры скрипта
| Параметр | Обязательный | Описание |
|----------|:------------:|----------|
| `-V8Path <путь>` | нет | Каталог bin платформы, или полный путь к `1cv8.exe` / `ibcmd.exe` |
| `-InfoBasePath <путь>` | * | Файловая база |
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
| `-UserName <имя>` | нет | Имя пользователя |
| `-Password <пароль>` | нет | Пароль |
| `-InputFile <путь>` | да | Путь к DT-файлу |
| `-JobsCount <N>` | нет | Число фоновых заданий загрузки (0 = по числу процессоров) |
| `-UnlockCode <код>` | нет | Код разблокировки (`/UC`), если заблокировано начало сеансов |
> `*` — нужен либо `-InfoBasePath`, либо пара `-InfoBaseServer` + `-InfoBaseRef`
## После выполнения
Если база занята (активные сеансы), загрузка не выполнится — для серверной базы можно
передать `-UnlockCode`; иначе освободи базу и повтори.
## Примеры
```powershell
# Файловая база
powershell.exe -NoProfile -File ".augment/skills/db-load-dt/scripts/db-load-dt.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -InputFile "C:\backup\base.dt"
# Серверная база с ускорением загрузки
powershell.exe -NoProfile -File ".augment/skills/db-load-dt/scripts/db-load-dt.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Test" -UserName "Admin" -Password "secret" -InputFile "base.dt" -JobsCount 4
```
## Связанные навыки
- `/db-dump-dt` — выгрузка ИБ в DT (обратная операция, точка отката перед загрузкой)
- `/db-create` — создать новую базу (в т.ч. из DT-шаблона)
@@ -1,242 +0,0 @@
# db-load-dt v1.5 — Load 1C information base from DT file
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
<#
.SYNOPSIS
Загрузка информационной базы 1С из DT-файла
.DESCRIPTION
Загружает информационную базу целиком (конфигурация + данные) из DT-файла.
ВНИМАНИЕ: операция полностью перезаписывает базу.
.PARAMETER V8Path
Путь к каталогу bin платформы или к 1cv8.exe
.PARAMETER InfoBasePath
Путь к файловой информационной базе
.PARAMETER InfoBaseServer
Сервер 1С (для серверной базы)
.PARAMETER InfoBaseRef
Имя базы на сервере
.PARAMETER UserName
Имя пользователя 1С
.PARAMETER Password
Пароль пользователя
.PARAMETER InputFile
Путь к DT-файлу для загрузки
.PARAMETER JobsCount
Количество фоновых заданий для загрузки (0 = по числу процессоров)
.PARAMETER UnlockCode
Код разблокировки базы (/UC) — если заблокировано начало сеансов
.EXAMPLE
.\db-load-dt.ps1 -InfoBasePath "C:\Bases\MyDB" -InputFile "backup.dt"
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[string]$V8Path,
[Parameter(Mandatory=$false)]
[string]$InfoBasePath,
[Parameter(Mandatory=$false)]
[string]$InfoBaseServer,
[Parameter(Mandatory=$false)]
[string]$InfoBaseRef,
[Parameter(Mandatory=$false)]
[string]$UserName,
[Parameter(Mandatory=$false)]
[string]$Password,
[Parameter(Mandatory=$true)]
[string]$InputFile,
[Parameter(Mandatory=$false)]
[int]$JobsCount = 0,
[Parameter(Mandatory=$false)]
[string]$UnlockCode
)
$OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# --- Resolve V8Path ---
function Find-ProjectV8Path {
$dir = (Get-Location).Path
while ($dir) {
$pf = Join-Path $dir ".v8-project.json"
if (Test-Path $pf) {
try {
$j = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
if ($j.v8path) { return [string]$j.v8path }
} catch {}
return $null
}
$parent = Split-Path $dir -Parent
if (-not $parent -or $parent -eq $dir) { break }
$dir = $parent
}
return $null
}
if (-not $V8Path) {
$V8Path = Find-ProjectV8Path
}
if (-not $V8Path) {
$found = Get-ChildItem @("C:\Program Files\1cv8\*\bin\1cv8.exe", "C:\Program Files (x86)\1cv8\*\bin\1cv8.exe") -ErrorAction SilentlyContinue |
Sort-Object { try { [version]$_.Directory.Parent.Name } catch { [version]"0.0" } } -Descending |
Select-Object -First 1
if ($found) {
$V8Path = $found.FullName
Write-Host "Auto-selected platform $($found.Directory.Parent.Name): $V8Path" -ForegroundColor Yellow
} else {
Write-Host "Error: 1C executable not found. Specify -V8Path" -ForegroundColor Red
exit 1
}
}
if (Test-Path $V8Path -PathType Container) {
$V8Path = Join-Path $V8Path "1cv8.exe"
}
if (-not (Test-Path $V8Path)) {
Write-Host "Error: 1C executable not found at $V8Path" -ForegroundColor Red
exit 1
}
# --- Detect engine (ibcmd vs 1cv8) by exe name ---
function Invoke-IbcmdProcess {
# Run ibcmd non-interactively: a closed stdin pipe (EOF) makes ibcmd's auth prompt
# fast-fail instead of hanging. Returns @{ Output; ExitCode }. cp866 decodes ibcmd's
# native OEM output. The 1cv8/DESIGNER branch keeps using Start-Process.
param([string]$Exe, [string[]]$IbArgs)
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $Exe
$psi.Arguments = ($IbArgs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.RedirectStandardInput = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
try {
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding(866)
$psi.StandardErrorEncoding = [System.Text.Encoding]::GetEncoding(866)
} catch {}
$p = [System.Diagnostics.Process]::Start($psi)
$p.StandardInput.Close()
$out = $p.StandardOutput.ReadToEnd()
$err = $p.StandardError.ReadToEnd()
$p.WaitForExit()
if ($err) { $out += $err }
return [pscustomobject]@{ Output = $out; ExitCode = $p.ExitCode }
}
$engine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
# --- Validate connection ---
if ($engine -eq "ibcmd") {
if (-not $InfoBasePath) {
Write-Host "Error: ibcmd supports file infobases only (use -InfoBasePath)" -ForegroundColor Red
exit 1
}
} elseif (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
exit 1
}
# --- Validate input file ---
if (-not (Test-Path $InputFile)) {
Write-Host "Error: input file not found: $InputFile" -ForegroundColor Red
exit 1
}
# --- Temp dir ---
$tempDir = Join-Path $env:TEMP "db_load_dt_$(Get-Random)"
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
try {
if ($engine -eq "ibcmd") {
# --- ibcmd branch (file infobase only) ---
$arguments = @("infobase", "restore", "--db-path=$InfoBasePath")
if (-not (Test-Path (Join-Path $InfoBasePath "1Cv8.1CD"))) { $arguments += "--create-database" }
if ($UserName) { $arguments += "--user=$UserName" }
if ($Password) { $arguments += "--password=$Password" }
$arguments += "$InputFile"
$arguments += "--data=$tempDir"
Write-Host "Running: ibcmd $($arguments -join ' ')"
$__ib = Invoke-IbcmdProcess $V8Path $arguments
$output = $__ib.Output
$exitCode = $__ib.ExitCode
if ($exitCode -eq 0) {
Write-Host "Information base restored successfully from: $InputFile" -ForegroundColor Green
} else {
Write-Host "Error restoring information base (code: $exitCode)" -ForegroundColor Red
}
if ($output) { Write-Host ($output | Out-String) }
exit $exitCode
}
# --- 1cv8 branch ---
# --- Build arguments ---
$arguments = @("DESIGNER")
if ($InfoBaseServer -and $InfoBaseRef) {
$arguments += "/S", "`"$InfoBaseServer/$InfoBaseRef`""
} else {
$arguments += "/F", "`"$InfoBasePath`""
}
if ($UserName) { $arguments += "/N`"$UserName`"" }
if ($Password) { $arguments += "/P`"$Password`"" }
if ($UnlockCode) { $arguments += "/UC`"$UnlockCode`"" }
$arguments += "/RestoreIB", "`"$InputFile`""
if ($JobsCount -gt 0) { $arguments += "-JobsCount", "$JobsCount" }
# --- Output ---
$outFile = Join-Path $tempDir "load_dt_log.txt"
$arguments += "/Out", "`"$outFile`""
$arguments += "/DisableStartupDialogs"
# --- Execute ---
Write-Host "Running: 1cv8.exe $($arguments -join ' ')"
$process = Start-Process -FilePath $V8Path -ArgumentList $arguments -NoNewWindow -Wait -PassThru
$exitCode = $process.ExitCode
# --- Result ---
if ($exitCode -eq 0) {
Write-Host "Information base restored successfully from: $InputFile" -ForegroundColor Green
} else {
Write-Host "Error restoring information base (code: $exitCode)" -ForegroundColor Red
}
if (Test-Path $outFile) {
$logContent = Get-Content $outFile -Raw -ErrorAction SilentlyContinue
if ($logContent) {
Write-Host "--- Log ---"
Write-Host $logContent
Write-Host "--- End ---"
}
}
exit $exitCode
} finally {
if (Test-Path $tempDir) {
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
}
}
@@ -1,225 +0,0 @@
#!/usr/bin/env python3
# db-load-dt v1.5 — Load 1C information base from DT file
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import atexit
import glob
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
def _find_project_v8path():
"""Walk up from CWD to find .v8-project.json and read its v8path."""
d = os.getcwd()
while True:
pf = os.path.join(d, ".v8-project.json")
if os.path.isfile(pf):
try:
with open(pf, encoding="utf-8-sig") as f:
data = json.load(f)
v = data.get("v8path")
if v:
return v
except Exception:
pass
return None
parent = os.path.dirname(d)
if parent == d:
return None
d = parent
def _version_dir(p):
"""Version dir for both Windows (.../1cv8/<ver>/bin/1cv8.exe) and *nix (.../1cv8/<ver>/1cv8)."""
parent = os.path.dirname(p)
if os.path.basename(parent).lower() == "bin":
parent = os.path.dirname(parent)
return os.path.basename(parent)
def _version_key(p):
"""Numeric sort key from version dir name."""
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
def resolve_v8path(v8path):
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
if not v8path:
v8path = _find_project_v8path()
if not v8path:
if os.name == "nt":
candidates = (
glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
+ glob.glob(r"C:\Program Files (x86)\1cv8\*\bin\1cv8.exe")
)
else:
# PY-only: PS-порт на *nix не исполняется, поэтому *nix-раскладки нет в .ps1.
candidates = glob.glob("/opt/1cv8/*/1cv8")
if candidates:
v8path = max(candidates, key=_version_key)
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
else:
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
sys.exit(1)
if os.path.isdir(v8path):
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
v8path = os.path.join(v8path, exe)
if not os.path.isfile(v8path):
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
sys.exit(1)
return v8path
IBCMD_NOUSER_HINT = (
"[ibcmd] No -UserName/-Password given; the infobase may require authentication. "
"On Windows ibcmd reads credentials from the console (stdin is ignored), so this "
"call may block instead of failing. If it does not return promptly, abort and "
"re-run with -UserName and -Password.\n"
)
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
"""Run an ibcmd command non-interactively.
input="" closes stdin (EOF) so ibcmd's auth prompt fast-fails instead of hanging.
On Windows without -UserName ibcmd reads the console directly and may still block —
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
"""
if warn_no_user and os.name == "nt" and not has_username:
sys.stderr.write(IBCMD_NOUSER_HINT)
sys.stderr.flush()
return subprocess.run(cmd, input="", capture_output=True, encoding="utf-8", errors="replace")
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(
description="Load 1C information base from DT file",
allow_abbrev=False,
)
parser.add_argument("-V8Path", default="")
parser.add_argument("-InfoBasePath", default="")
parser.add_argument("-InfoBaseServer", default="")
parser.add_argument("-InfoBaseRef", default="")
parser.add_argument("-UserName", default="")
parser.add_argument("-Password", default="")
parser.add_argument("-InputFile", required=True)
parser.add_argument("-JobsCount", type=int, default=0)
parser.add_argument("-UnlockCode", default="")
args = parser.parse_args()
v8path = resolve_v8path(args.V8Path)
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
# --- Validate connection ---
if engine == "ibcmd":
if not args.InfoBasePath:
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
sys.exit(1)
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
sys.exit(1)
# --- Validate input file ---
if not os.path.isfile(args.InputFile):
print(f"Error: input file not found: {args.InputFile}", file=sys.stderr)
sys.exit(1)
# --- ibcmd branch (file infobase only) ---
if engine == "ibcmd":
arguments = ["infobase", "restore", f"--db-path={args.InfoBasePath}"]
if not os.path.isfile(os.path.join(args.InfoBasePath, "1Cv8.1CD")):
arguments.append("--create-database")
if args.UserName:
arguments.append(f"--user={args.UserName}")
if args.Password:
arguments.append(f"--password={args.Password}")
arguments.append(args.InputFile)
ib_data = tempfile.mkdtemp(prefix="ibcmd_data_")
atexit.register(shutil.rmtree, ib_data, ignore_errors=True)
arguments.append(f"--data={ib_data}")
print(f"Running: ibcmd {' '.join(arguments)}")
result = run_ibcmd([v8path] + arguments, bool(args.UserName))
if result.returncode == 0:
print(f"Information base restored successfully from: {args.InputFile}")
else:
print(f"Error restoring information base (code: {result.returncode})", file=sys.stderr)
if result.stdout:
print(result.stdout)
if result.stderr:
print(result.stderr, file=sys.stderr)
sys.exit(result.returncode)
# --- Temp dir ---
temp_dir = os.path.join(tempfile.gettempdir(), f"db_load_dt_{random.randint(0, 999999)}")
os.makedirs(temp_dir, exist_ok=True)
try:
# --- Build arguments ---
arguments = ["DESIGNER"]
if args.InfoBaseServer and args.InfoBaseRef:
arguments.extend(["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"])
else:
arguments.extend(["/F", args.InfoBasePath])
if args.UserName:
arguments.append(f"/N{args.UserName}")
if args.Password:
arguments.append(f"/P{args.Password}")
if args.UnlockCode:
arguments.append(f"/UC{args.UnlockCode}")
arguments.extend(["/RestoreIB", args.InputFile])
if args.JobsCount > 0:
arguments.extend(["-JobsCount", str(args.JobsCount)])
# --- Output ---
out_file = os.path.join(temp_dir, "load_dt_log.txt")
arguments.extend(["/Out", out_file])
arguments.append("/DisableStartupDialogs")
# --- Execute ---
print(f"Running: 1cv8.exe {' '.join(arguments)}")
result = subprocess.run(
[v8path] + arguments,
capture_output=True,
text=True,
)
exit_code = result.returncode
# --- Result ---
if exit_code == 0:
print(f"Information base restored successfully from: {args.InputFile}")
else:
print(f"Error restoring information base (code: {exit_code})", file=sys.stderr)
if os.path.isfile(out_file):
try:
with open(out_file, "r", encoding="utf-8-sig") as f:
log_content = f.read()
if log_content:
print("--- Log ---")
print(log_content)
print("--- End ---")
except Exception:
pass
sys.exit(exit_code)
finally:
if os.path.isdir(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=True)
if __name__ == "__main__":
main()
@@ -1,418 +0,0 @@
# db-load-xml v1.12 — Load 1C configuration from XML files
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
<#
.SYNOPSIS
Загрузка конфигурации 1С из XML-файлов
.DESCRIPTION
Загружает конфигурацию в информационную базу из XML-файлов.
Поддерживает полную и частичную загрузку.
.PARAMETER V8Path
Путь к каталогу bin платформы или к 1cv8.exe
.PARAMETER InfoBasePath
Путь к файловой информационной базе
.PARAMETER InfoBaseServer
Сервер 1С (для серверной базы)
.PARAMETER InfoBaseRef
Имя базы на сервере
.PARAMETER UserName
Имя пользователя 1С
.PARAMETER Password
Пароль пользователя
.PARAMETER ConfigDir
Каталог XML-исходников конфигурации
.PARAMETER Mode
Режим загрузки: Full или Partial (по умолчанию Full)
.PARAMETER Files
Относительные пути файлов через запятую (для режима Partial)
.PARAMETER ListFile
Путь к файлу со списком файлов (альтернатива -Files, для режима Partial)
.PARAMETER Extension
Имя расширения для загрузки
.PARAMETER AllExtensions
Загрузить все расширения
.PARAMETER Format
Формат файлов: Hierarchical или Plain (по умолчанию Hierarchical)
.EXAMPLE
.\db-load-xml.ps1 -InfoBasePath "C:\Bases\MyDB" -ConfigDir "C:\src" -Mode Full
.EXAMPLE
.\db-load-xml.ps1 -InfoBasePath "C:\Bases\MyDB" -ConfigDir "C:\src" -Mode Partial -Files "Catalogs/Номенклатура.xml,Catalogs/Номенклатура/Ext/ObjectModule.bsl"
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[string]$V8Path,
[Parameter(Mandatory=$false)]
[string]$InfoBasePath,
[Parameter(Mandatory=$false)]
[string]$InfoBaseServer,
[Parameter(Mandatory=$false)]
[string]$InfoBaseRef,
[Parameter(Mandatory=$false)]
[string]$UserName,
[Parameter(Mandatory=$false)]
[string]$Password,
[Parameter(Mandatory=$true)]
[string]$ConfigDir,
[Parameter(Mandatory=$false)]
[ValidateSet("Full", "Partial")]
[string]$Mode = "Full",
[Parameter(Mandatory=$false)]
[string]$Files,
[Parameter(Mandatory=$false)]
[string]$ListFile,
[Parameter(Mandatory=$false)]
[string]$Extension,
[Parameter(Mandatory=$false)]
[switch]$AllExtensions,
[Parameter(Mandatory=$false)]
[ValidateSet("Hierarchical", "Plain")]
[string]$Format = "Hierarchical",
[Parameter(Mandatory=$false)]
[switch]$UpdateDB,
[Parameter(Mandatory=$false)]
[switch]$StrictLog
)
$OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# --- Resolve V8Path ---
function Find-ProjectV8Path {
$dir = (Get-Location).Path
while ($dir) {
$pf = Join-Path $dir ".v8-project.json"
if (Test-Path $pf) {
try {
$j = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
if ($j.v8path) { return [string]$j.v8path }
} catch {}
return $null
}
$parent = Split-Path $dir -Parent
if (-not $parent -or $parent -eq $dir) { break }
$dir = $parent
}
return $null
}
if (-not $V8Path) {
$V8Path = Find-ProjectV8Path
}
if (-not $V8Path) {
$found = Get-ChildItem @("C:\Program Files\1cv8\*\bin\1cv8.exe", "C:\Program Files (x86)\1cv8\*\bin\1cv8.exe") -ErrorAction SilentlyContinue |
Sort-Object { try { [version]$_.Directory.Parent.Name } catch { [version]"0.0" } } -Descending |
Select-Object -First 1
if ($found) {
$V8Path = $found.FullName
Write-Host "Auto-selected platform $($found.Directory.Parent.Name): $V8Path" -ForegroundColor Yellow
} else {
Write-Host "Error: 1C executable not found. Specify -V8Path" -ForegroundColor Red
exit 1
}
}
if (Test-Path $V8Path -PathType Container) {
$V8Path = Join-Path $V8Path "1cv8.exe"
}
if (-not (Test-Path $V8Path)) {
Write-Host "Error: 1C executable not found at $V8Path" -ForegroundColor Red
exit 1
}
# --- Detect engine (ibcmd vs 1cv8) by exe name ---
function Invoke-IbcmdProcess {
# Run ibcmd non-interactively: a closed stdin pipe (EOF) makes ibcmd's auth prompt
# fast-fail instead of hanging. Returns @{ Output; ExitCode }. cp866 decodes ibcmd's
# native OEM output. The 1cv8/DESIGNER branch keeps using Start-Process.
param([string]$Exe, [string[]]$IbArgs)
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $Exe
$psi.Arguments = ($IbArgs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.RedirectStandardInput = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
try {
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding(866)
$psi.StandardErrorEncoding = [System.Text.Encoding]::GetEncoding(866)
} catch {}
$p = [System.Diagnostics.Process]::Start($psi)
$p.StandardInput.Close()
$out = $p.StandardOutput.ReadToEnd()
$err = $p.StandardError.ReadToEnd()
$p.WaitForExit()
if ($err) { $out += $err }
return [pscustomobject]@{ Output = $out; ExitCode = $p.ExitCode }
}
$engine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
# --- Validate connection ---
if ($engine -eq "ibcmd") {
if (-not $InfoBasePath) {
Write-Host "Error: ibcmd supports file infobases only (use -InfoBasePath)" -ForegroundColor Red
exit 1
}
} elseif (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
exit 1
}
# --- Validate config dir ---
if (-not (Test-Path $ConfigDir)) {
Write-Host "Error: config directory not found: $ConfigDir" -ForegroundColor Red
exit 1
}
# --- Validate Partial mode ---
if ($Mode -eq "Partial" -and -not $Files -and -not $ListFile) {
Write-Host "Error: -Files or -ListFile required for Partial mode" -ForegroundColor Red
exit 1
}
# --- Temp dir ---
$tempDir = Join-Path $env:TEMP "db_load_xml_$(Get-Random)"
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
try {
if ($engine -eq "ibcmd") {
# --- ibcmd branch (file infobase only; hierarchical full-directory import) ---
if ($Format -eq "Plain") {
Write-Host "Error: ibcmd config import supports hierarchical format only (use -Format Hierarchical or 1cv8)" -ForegroundColor Red
exit 1
}
if ($AllExtensions) {
$arguments = @("infobase", "config", "import", "all-extensions", "$ConfigDir", "--db-path=$InfoBasePath")
} elseif ($Mode -eq "Partial" -or $Files -or $ListFile) {
# partial: import specific files (relative to ConfigDir)
$fileList = @()
if ($ListFile) {
if (-not (Test-Path $ListFile)) {
Write-Host "Error: list file not found: $ListFile" -ForegroundColor Red
exit 1
}
$fileList = @(Get-Content -Path $ListFile -Encoding UTF8 | ForEach-Object { $_.Trim() } | Where-Object { $_ })
} elseif ($Files) {
$fileList = @($Files -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
}
if ($fileList.Count -eq 0) {
Write-Host "Error: -Files or -ListFile required for partial import" -ForegroundColor Red
exit 1
}
$arguments = @("infobase", "config", "import", "files") + $fileList
$arguments += "--base-dir=$ConfigDir", "--db-path=$InfoBasePath"
if ($Extension) { $arguments += "--extension=$Extension" }
} else {
$arguments = @("infobase", "config", "import", "--db-path=$InfoBasePath")
if ($Extension) { $arguments += "--extension=$Extension" }
$arguments += "$ConfigDir"
}
if ($UserName) { $arguments += "--user=$UserName" }
if ($Password) { $arguments += "--password=$Password" }
$arguments += "--data=$tempDir"
Write-Host "Running: ibcmd $($arguments -join ' ')"
$__ib = Invoke-IbcmdProcess $V8Path $arguments
$output = $__ib.Output
$exitCode = $__ib.ExitCode
if ($exitCode -ne 0) {
Write-Host "Error loading configuration from files (code: $exitCode)" -ForegroundColor Red
if ($output) { Write-Host ($output | Out-String) }
exit $exitCode
}
Write-Host "Configuration loaded successfully from: $ConfigDir" -ForegroundColor Green
if ($output) { Write-Host ($output | Out-String) }
if ($UpdateDB) {
$applyArgs = @("infobase", "config", "apply", "--db-path=$InfoBasePath", "--force")
if ($UserName) { $applyArgs += "--user=$UserName" }
if ($Password) { $applyArgs += "--password=$Password" }
$applyArgs += "--data=$tempDir"
Write-Host "Running: ibcmd $($applyArgs -join ' ')"
$__ib = Invoke-IbcmdProcess $V8Path $applyArgs
$applyOut = $__ib.Output
$exitCode = $__ib.ExitCode
if ($exitCode -eq 0) {
Write-Host "Database configuration updated successfully" -ForegroundColor Green
} else {
Write-Host "Error updating database configuration (code: $exitCode)" -ForegroundColor Red
}
if ($applyOut) { Write-Host ($applyOut | Out-String) }
}
exit $exitCode
}
# --- 1cv8 branch ---
# --- Build arguments ---
$arguments = @("DESIGNER")
if ($InfoBaseServer -and $InfoBaseRef) {
$arguments += "/S", "`"$InfoBaseServer/$InfoBaseRef`""
} else {
$arguments += "/F", "`"$InfoBasePath`""
}
if ($UserName) { $arguments += "/N`"$UserName`"" }
if ($Password) { $arguments += "/P`"$Password`"" }
$arguments += "/LoadConfigFromFiles", "`"$ConfigDir`""
if ($Mode -eq "Full") {
Write-Host "Executing full configuration load..."
} else {
Write-Host "Executing partial configuration load..."
# Build list file
$rawList = @()
if ($ListFile) {
if (-not (Test-Path $ListFile)) {
Write-Host "Error: list file not found: $ListFile" -ForegroundColor Red
exit 1
}
$rawList = @(Get-Content -Path $ListFile -Encoding UTF8 | ForEach-Object { $_.Trim() } | Where-Object { $_ })
} else {
$rawList = @($Files -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
}
# Support-state service files are NOT partially loadable — exclude with a hint.
$supportRe = 'ParentConfigurations\.bin$|(^|[\\/])ConfigDumpInfo\.xml$'
$supportFiles = @($rawList | Where-Object { $_ -match $supportRe })
$fileList = @($rawList | Where-Object { $_ -notmatch $supportRe })
if ($supportFiles.Count -gt 0) {
Write-Host "[ВНИМАНИЕ] Служебные файлы состояния поддержки исключены из частичной загрузки (частично не грузятся):" -ForegroundColor Yellow
foreach ($sf in $supportFiles) { Write-Host " - $sf" -ForegroundColor Yellow }
Write-Host " Смена состояния поддержки применяется только полной загрузкой: -Mode Full." -ForegroundColor Yellow
}
if ($fileList.Count -eq 0) {
Write-Host "Error: после исключения служебных файлов поддержки загружать нечего. Для смены поддержки используйте -Mode Full." -ForegroundColor Red
exit 1
}
$generatedListFile = Join-Path $tempDir "load_list.txt"
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
[System.IO.File]::WriteAllLines($generatedListFile, $fileList, $utf8Bom)
Write-Host "Files to load: $($fileList.Count)"
foreach ($f in $fileList) { Write-Host " $f" }
$arguments += "-listFile", "`"$generatedListFile`""
$arguments += "-partial"
$arguments += "-updateConfigDumpInfo"
}
$arguments += "-Format", $Format
# --- Extensions ---
if ($Extension) {
$arguments += "-Extension", "`"$Extension`""
} elseif ($AllExtensions) {
$arguments += "-AllExtensions"
}
# --- UpdateDB ---
if ($UpdateDB) {
$arguments += "/UpdateDBCfg"
}
# --- Output ---
$outFile = Join-Path $tempDir "load_log.txt"
$arguments += "/Out", "`"$outFile`""
$arguments += "/DisableStartupDialogs"
# --- Execute ---
Write-Host "Running: 1cv8.exe $($arguments -join ' ')"
$process = Start-Process -FilePath $V8Path -ArgumentList $arguments -NoNewWindow -Wait -PassThru
$exitCode = $process.ExitCode
# --- Read log ---
$logContent = $null
if (Test-Path $outFile) {
$logContent = Get-Content $outFile -Raw -ErrorAction SilentlyContinue
}
# --- Scan log for silent rejections ---
# Platform often writes load-time rejections into /Out but exits with code 0.
# These patterns flag cases where metadata was dropped or rejected silently.
$fatalLogPatterns = @(
'Неверное свойство объекта метаданных',
'не входит в состав объекта метаданных',
'Неизвестное имя типа',
'Неизвестный объект метаданных',
'Ни один из документов не является регистратором для регистра',
'Неверное значение перечисления',
'не может быть приведен к типу'
)
$silentFailures = @()
if ($logContent) {
foreach ($line in ($logContent -split "`r?`n")) {
foreach ($pat in $fatalLogPatterns) {
if ($line -match [regex]::Escape($pat)) {
$silentFailures += $line.Trim()
break
}
}
}
}
# --- Result ---
# Default: mirror platform's verdict via exit code. Log content (including any
# rejection warnings) is always printed to stdout for visibility. With -StrictLog,
# elevate exit code to 1 when rejection patterns are found even if platform said 0.
if ($exitCode -eq 0) {
Write-Host "Load completed successfully" -ForegroundColor Green
} else {
Write-Host "Error loading configuration (code: $exitCode)" -ForegroundColor Red
}
if ($logContent) {
Write-Host "--- Log ---"
Write-Host $logContent
Write-Host "--- End ---"
}
if ($silentFailures.Count -gt 0) {
$msg = "[warning] log contains $($silentFailures.Count) rejection(s) — platform loaded config but dropped properties/refs"
if (-not $StrictLog) { $msg += " (pass -StrictLog to treat as error)" }
Write-Host $msg -ForegroundColor Yellow
foreach ($f in $silentFailures) { Write-Host " $f" -ForegroundColor Yellow }
if ($StrictLog -and $exitCode -eq 0) { $exitCode = 1 }
}
exit $exitCode
} finally {
if (Test-Path $tempDir) {
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
}
}
@@ -1,382 +0,0 @@
#!/usr/bin/env python3
# db-load-xml v1.12 — Load 1C configuration from XML files
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import atexit
import glob
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
def _find_project_v8path():
"""Walk up from CWD to find .v8-project.json and read its v8path."""
d = os.getcwd()
while True:
pf = os.path.join(d, ".v8-project.json")
if os.path.isfile(pf):
try:
with open(pf, encoding="utf-8-sig") as f:
data = json.load(f)
v = data.get("v8path")
if v:
return v
except Exception:
pass
return None
parent = os.path.dirname(d)
if parent == d:
return None
d = parent
def _version_dir(p):
"""Version dir for both Windows (.../1cv8/<ver>/bin/1cv8.exe) and *nix (.../1cv8/<ver>/1cv8)."""
parent = os.path.dirname(p)
if os.path.basename(parent).lower() == "bin":
parent = os.path.dirname(parent)
return os.path.basename(parent)
def _version_key(p):
"""Numeric sort key from version dir name."""
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
def resolve_v8path(v8path):
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
if not v8path:
v8path = _find_project_v8path()
if not v8path:
if os.name == "nt":
candidates = (
glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
+ glob.glob(r"C:\Program Files (x86)\1cv8\*\bin\1cv8.exe")
)
else:
# PY-only: PS-порт на *nix не исполняется, поэтому *nix-раскладки нет в .ps1.
candidates = glob.glob("/opt/1cv8/*/1cv8")
if candidates:
v8path = max(candidates, key=_version_key)
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
else:
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
sys.exit(1)
if os.path.isdir(v8path):
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
v8path = os.path.join(v8path, exe)
if not os.path.isfile(v8path):
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
sys.exit(1)
return v8path
IBCMD_NOUSER_HINT = (
"[ibcmd] No -UserName/-Password given; the infobase may require authentication. "
"On Windows ibcmd reads credentials from the console (stdin is ignored), so this "
"call may block instead of failing. If it does not return promptly, abort and "
"re-run with -UserName and -Password.\n"
)
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
"""Run an ibcmd command non-interactively.
input="" closes stdin (EOF) so ibcmd's auth prompt fast-fails instead of hanging.
On Windows without -UserName ibcmd reads the console directly and may still block —
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
"""
if warn_no_user and os.name == "nt" and not has_username:
sys.stderr.write(IBCMD_NOUSER_HINT)
sys.stderr.flush()
return subprocess.run(cmd, input="", capture_output=True, encoding="utf-8", errors="replace")
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(
description="Load 1C configuration from XML files",
allow_abbrev=False,
)
parser.add_argument("-V8Path", default="", help="Path to 1cv8.exe or its bin directory")
parser.add_argument("-InfoBasePath", default="", help="Path to file infobase")
parser.add_argument("-InfoBaseServer", default="", help="1C server (for server infobase)")
parser.add_argument("-InfoBaseRef", default="", help="Infobase name on server")
parser.add_argument("-UserName", default="", help="1C user name")
parser.add_argument("-Password", default="", help="1C user password")
parser.add_argument("-ConfigDir", required=True, help="Directory with XML configuration sources")
parser.add_argument(
"-Mode",
default="Full",
choices=["Full", "Partial"],
help="Load mode (default: Full)",
)
parser.add_argument("-Files", default="", help="Comma-separated relative file paths (for Partial mode)")
parser.add_argument("-ListFile", default="", help="Path to file list (alternative to -Files, for Partial mode)")
parser.add_argument("-Extension", default="", help="Extension name to load")
parser.add_argument("-AllExtensions", action="store_true", help="Load all extensions")
parser.add_argument(
"-Format",
default="Hierarchical",
choices=["Hierarchical", "Plain"],
help="File format (default: Hierarchical)",
)
parser.add_argument("-UpdateDB", action="store_true", help="Also update database configuration after load")
parser.add_argument(
"-StrictLog",
action="store_true",
help="Treat silent rejection warnings in the log as errors (elevate exit code to 1)",
)
args = parser.parse_args()
# --- Resolve V8Path ---
v8path = resolve_v8path(args.V8Path)
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
# --- Validate connection ---
if engine == "ibcmd":
if not args.InfoBasePath:
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
sys.exit(1)
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
sys.exit(1)
# --- Validate config dir ---
if not os.path.exists(args.ConfigDir):
print(f"Error: config directory not found: {args.ConfigDir}", file=sys.stderr)
sys.exit(1)
# --- Validate Partial mode ---
if args.Mode == "Partial" and not args.Files and not args.ListFile:
print("Error: -Files or -ListFile required for Partial mode", file=sys.stderr)
sys.exit(1)
# --- ibcmd branch (file infobase only; hierarchical full-directory import) ---
if engine == "ibcmd":
if args.Format == "Plain":
print("Error: ibcmd config import supports hierarchical format only (use -Format Hierarchical or 1cv8)", file=sys.stderr)
sys.exit(1)
if args.AllExtensions:
arguments = ["infobase", "config", "import", "all-extensions", args.ConfigDir, f"--db-path={args.InfoBasePath}"]
elif args.Mode == "Partial" or args.Files or args.ListFile:
# partial: import specific files (relative to ConfigDir)
if args.ListFile:
if not os.path.isfile(args.ListFile):
print(f"Error: list file not found: {args.ListFile}", file=sys.stderr)
sys.exit(1)
with open(args.ListFile, encoding="utf-8-sig") as f:
file_list = [ln.strip() for ln in f if ln.strip()]
elif args.Files:
file_list = [p.strip() for p in args.Files.split(",") if p.strip()]
else:
file_list = []
if not file_list:
print("Error: -Files or -ListFile required for partial import", file=sys.stderr)
sys.exit(1)
arguments = ["infobase", "config", "import", "files"] + file_list
arguments += [f"--base-dir={args.ConfigDir}", f"--db-path={args.InfoBasePath}"]
if args.Extension:
arguments.append(f"--extension={args.Extension}")
else:
arguments = ["infobase", "config", "import", f"--db-path={args.InfoBasePath}"]
if args.Extension:
arguments.append(f"--extension={args.Extension}")
arguments.append(args.ConfigDir)
ib_data = tempfile.mkdtemp(prefix="ibcmd_data_")
atexit.register(shutil.rmtree, ib_data, ignore_errors=True)
if args.UserName:
arguments.append(f"--user={args.UserName}")
if args.Password:
arguments.append(f"--password={args.Password}")
arguments.append(f"--data={ib_data}")
print(f"Running: ibcmd {' '.join(arguments)}")
result = run_ibcmd([v8path] + arguments, bool(args.UserName))
if result.returncode != 0:
print(f"Error loading configuration from files (code: {result.returncode})", file=sys.stderr)
if result.stdout:
print(result.stdout)
if result.stderr:
print(result.stderr, file=sys.stderr)
sys.exit(result.returncode)
print(f"Configuration loaded successfully from: {args.ConfigDir}")
if result.stdout:
print(result.stdout)
exit_code = 0
if args.UpdateDB:
apply_args = ["infobase", "config", "apply", f"--db-path={args.InfoBasePath}", "--force"]
if args.UserName:
apply_args.append(f"--user={args.UserName}")
if args.Password:
apply_args.append(f"--password={args.Password}")
apply_args.append(f"--data={ib_data}")
print(f"Running: ibcmd {' '.join(apply_args)}")
ar = run_ibcmd([v8path] + apply_args, bool(args.UserName))
exit_code = ar.returncode
if exit_code == 0:
print("Database configuration updated successfully")
else:
print(f"Error updating database configuration (code: {exit_code})", file=sys.stderr)
if ar.stdout:
print(ar.stdout)
if ar.stderr:
print(ar.stderr, file=sys.stderr)
sys.exit(exit_code)
# --- Temp dir ---
temp_dir = os.path.join(tempfile.gettempdir(), f"db_load_xml_{random.randint(0, 999999)}")
os.makedirs(temp_dir, exist_ok=True)
try:
# --- Build arguments ---
arguments = ["DESIGNER"]
if args.InfoBaseServer and args.InfoBaseRef:
arguments += ["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"]
else:
arguments += ["/F", args.InfoBasePath]
if args.UserName:
arguments.append(f"/N{args.UserName}")
if args.Password:
arguments.append(f"/P{args.Password}")
arguments += ["/LoadConfigFromFiles", args.ConfigDir]
if args.Mode == "Full":
print("Executing full configuration load...")
else:
print("Executing partial configuration load...")
# Build list file
if args.ListFile:
if not os.path.isfile(args.ListFile):
print(f"Error: list file not found: {args.ListFile}", file=sys.stderr)
sys.exit(1)
with open(args.ListFile, encoding="utf-8-sig") as f:
raw_list = [ln.strip() for ln in f if ln.strip()]
else:
raw_list = [f.strip() for f in args.Files.split(",") if f.strip()]
# Support-state service files are NOT partially loadable — exclude with a hint.
support_re = re.compile(r"ParentConfigurations\.bin$|(^|[\\/])ConfigDumpInfo\.xml$")
support_files = [x for x in raw_list if support_re.search(x)]
file_list = [x for x in raw_list if not support_re.search(x)]
if support_files:
print("[ВНИМАНИЕ] Служебные файлы состояния поддержки исключены из частичной загрузки (частично не грузятся):", file=sys.stderr)
for sf in support_files:
print(f" - {sf}", file=sys.stderr)
print(" Смена состояния поддержки применяется только полной загрузкой: -Mode Full.", file=sys.stderr)
if not file_list:
print("Error: после исключения служебных файлов поддержки загружать нечего. Для смены поддержки используйте -Mode Full.", file=sys.stderr)
sys.exit(1)
generated_list_file = os.path.join(temp_dir, "load_list.txt")
with open(generated_list_file, "w", encoding="utf-8-sig") as f:
f.write("\n".join(file_list))
print(f"Files to load: {len(file_list)}")
for fl in file_list:
print(f" {fl}")
arguments += ["-listFile", generated_list_file]
arguments.append("-partial")
arguments.append("-updateConfigDumpInfo")
arguments += ["-Format", args.Format]
# --- Extensions ---
if args.Extension:
arguments += ["-Extension", args.Extension]
elif args.AllExtensions:
arguments.append("-AllExtensions")
# --- UpdateDB ---
if args.UpdateDB:
arguments.append("/UpdateDBCfg")
# --- Output ---
out_file = os.path.join(temp_dir, "load_log.txt")
arguments += ["/Out", out_file]
arguments.append("/DisableStartupDialogs")
# --- Execute ---
print(f"Running: 1cv8.exe {' '.join(arguments)}")
result = subprocess.run(
[v8path] + arguments,
capture_output=True,
text=True,
)
exit_code = result.returncode
# --- Read log ---
log_content = ""
if os.path.isfile(out_file):
try:
with open(out_file, "r", encoding="utf-8-sig") as f:
log_content = f.read()
except Exception:
log_content = ""
# --- Scan log for silent rejections ---
# Platform often writes load-time rejections into /Out but exits with code 0.
# These patterns flag cases where metadata was dropped or rejected silently.
fatal_log_patterns = [
"Неверное свойство объекта метаданных",
"не входит в состав объекта метаданных",
"Неизвестное имя типа",
"Неизвестный объект метаданных",
"Ни один из документов не является регистратором для регистра",
"Неверное значение перечисления",
"не может быть приведен к типу",
]
silent_failures = []
if log_content:
for line in log_content.splitlines():
for pat in fatal_log_patterns:
if pat in line:
silent_failures.append(line.strip())
break
# --- Result ---
# Default: mirror platform's verdict via exit code. Log content (including any
# rejection warnings) is always printed to stdout for visibility. With -StrictLog,
# elevate exit code to 1 when rejection patterns are found even if platform said 0.
if exit_code == 0:
print("Load completed successfully")
else:
print(f"Error loading configuration (code: {exit_code})", file=sys.stderr)
if log_content:
print("--- Log ---")
print(log_content)
print("--- End ---")
if silent_failures:
suffix = "" if args.StrictLog else " (pass -StrictLog to treat as error)"
print(
f"[warning] log contains {len(silent_failures)} rejection(s) — "
f"platform loaded config but dropped properties/refs{suffix}",
file=sys.stderr,
)
for f in silent_failures:
print(f" {f}", file=sys.stderr)
if args.StrictLog and exit_code == 0:
exit_code = 1
sys.exit(exit_code)
finally:
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=True)
if __name__ == "__main__":
main()
@@ -1,239 +0,0 @@
#!/usr/bin/env python3
# db-update v1.6 — Update 1C database configuration
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import atexit
import glob
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
def _find_project_v8path():
"""Walk up from CWD to find .v8-project.json and read its v8path."""
d = os.getcwd()
while True:
pf = os.path.join(d, ".v8-project.json")
if os.path.isfile(pf):
try:
with open(pf, encoding="utf-8-sig") as f:
data = json.load(f)
v = data.get("v8path")
if v:
return v
except Exception:
pass
return None
parent = os.path.dirname(d)
if parent == d:
return None
d = parent
def _version_dir(p):
"""Version dir for both Windows (.../1cv8/<ver>/bin/1cv8.exe) and *nix (.../1cv8/<ver>/1cv8)."""
parent = os.path.dirname(p)
if os.path.basename(parent).lower() == "bin":
parent = os.path.dirname(parent)
return os.path.basename(parent)
def _version_key(p):
"""Numeric sort key from version dir name."""
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
def resolve_v8path(v8path):
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
if not v8path:
v8path = _find_project_v8path()
if not v8path:
if os.name == "nt":
candidates = (
glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
+ glob.glob(r"C:\Program Files (x86)\1cv8\*\bin\1cv8.exe")
)
else:
# PY-only: PS-порт на *nix не исполняется, поэтому *nix-раскладки нет в .ps1.
candidates = glob.glob("/opt/1cv8/*/1cv8")
if candidates:
v8path = max(candidates, key=_version_key)
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
else:
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
sys.exit(1)
if os.path.isdir(v8path):
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
v8path = os.path.join(v8path, exe)
if not os.path.isfile(v8path):
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
sys.exit(1)
return v8path
IBCMD_NOUSER_HINT = (
"[ibcmd] No -UserName/-Password given; the infobase may require authentication. "
"On Windows ibcmd reads credentials from the console (stdin is ignored), so this "
"call may block instead of failing. If it does not return promptly, abort and "
"re-run with -UserName and -Password.\n"
)
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
"""Run an ibcmd command non-interactively.
input="" closes stdin (EOF) so ibcmd's auth prompt fast-fails instead of hanging.
On Windows without -UserName ibcmd reads the console directly and may still block —
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
"""
if warn_no_user and os.name == "nt" and not has_username:
sys.stderr.write(IBCMD_NOUSER_HINT)
sys.stderr.flush()
return subprocess.run(cmd, input="", capture_output=True, encoding="utf-8", errors="replace")
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(
description="Update 1C database configuration",
allow_abbrev=False,
)
parser.add_argument("-V8Path", default="")
parser.add_argument("-InfoBasePath", default="")
parser.add_argument("-InfoBaseServer", default="")
parser.add_argument("-InfoBaseRef", default="")
parser.add_argument("-UserName", default="")
parser.add_argument("-Password", default="")
parser.add_argument("-Extension", default="")
parser.add_argument("-AllExtensions", action="store_true")
parser.add_argument("-Dynamic", default="", choices=["", "+", "-"])
parser.add_argument("-Server", action="store_true")
parser.add_argument("-WarningsAsErrors", action="store_true")
args = parser.parse_args()
v8path = resolve_v8path(args.V8Path)
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
# --- Validate connection ---
if engine == "ibcmd":
if not args.InfoBasePath:
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
sys.exit(1)
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
sys.exit(1)
# --- ibcmd branch (file infobase only) ---
if engine == "ibcmd":
if args.AllExtensions:
print("Error: ibcmd config apply does not support -AllExtensions (use -Extension)", file=sys.stderr)
sys.exit(1)
arguments = ["infobase", "config", "apply", f"--db-path={args.InfoBasePath}", "--force"]
if args.Dynamic == "+":
arguments.append("--dynamic=auto")
elif args.Dynamic == "-":
arguments.append("--dynamic=disable")
if args.Extension:
arguments.append(f"--extension={args.Extension}")
ib_data = tempfile.mkdtemp(prefix="ibcmd_data_")
atexit.register(shutil.rmtree, ib_data, ignore_errors=True)
if args.UserName:
arguments.append(f"--user={args.UserName}")
if args.Password:
arguments.append(f"--password={args.Password}")
arguments.append(f"--data={ib_data}")
print(f"Running: ibcmd {' '.join(arguments)}")
result = run_ibcmd([v8path] + arguments, bool(args.UserName))
if result.returncode == 0:
print("Database configuration updated successfully")
else:
print(f"Error updating database configuration (code: {result.returncode})", file=sys.stderr)
if result.stdout:
print(result.stdout)
if result.stderr:
print(result.stderr, file=sys.stderr)
sys.exit(result.returncode)
# --- Temp dir ---
temp_dir = os.path.join(tempfile.gettempdir(), f"db_update_{random.randint(0, 999999)}")
os.makedirs(temp_dir, exist_ok=True)
try:
# --- Build arguments ---
arguments = ["DESIGNER"]
if args.InfoBaseServer and args.InfoBaseRef:
arguments.extend(["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"])
else:
arguments.extend(["/F", args.InfoBasePath])
if args.UserName:
arguments.append(f"/N{args.UserName}")
if args.Password:
arguments.append(f"/P{args.Password}")
arguments.append("/UpdateDBCfg")
# --- Options ---
if args.Dynamic:
arguments.append(f"-Dynamic{args.Dynamic}")
if args.Server:
arguments.append("-Server")
if args.WarningsAsErrors:
arguments.append("-WarningsAsErrors")
# --- Extensions ---
if args.Extension:
arguments.extend(["-Extension", args.Extension])
elif args.AllExtensions:
arguments.append("-AllExtensions")
# --- Output ---
out_file = os.path.join(temp_dir, "update_log.txt")
arguments.extend(["/Out", out_file])
arguments.append("/DisableStartupDialogs")
# --- Execute ---
print(f"Running: 1cv8.exe {' '.join(arguments)}")
result = subprocess.run(
[v8path] + arguments,
capture_output=True,
text=True,
)
exit_code = result.returncode
# --- Result ---
if exit_code == 0:
print("Database configuration updated successfully")
else:
print(f"Error updating database configuration (code: {exit_code})", file=sys.stderr)
if os.path.isfile(out_file):
try:
with open(out_file, "r", encoding="utf-8-sig") as f:
log_content = f.read()
if log_content:
print("--- Log ---")
print(log_content)
print("--- End ---")
except Exception:
pass
sys.exit(exit_code)
finally:
if os.path.isdir(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=True)
if __name__ == "__main__":
main()
@@ -1,233 +0,0 @@
#!/usr/bin/env python3
# epf-dump v1.6 — Dump external data processor or report (EPF/ERF) to XML sources
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import atexit
import glob
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
def _find_project_v8path():
"""Walk up from CWD to find .v8-project.json and read its v8path."""
d = os.getcwd()
while True:
pf = os.path.join(d, ".v8-project.json")
if os.path.isfile(pf):
try:
with open(pf, encoding="utf-8-sig") as f:
data = json.load(f)
v = data.get("v8path")
if v:
return v
except Exception:
pass
return None
parent = os.path.dirname(d)
if parent == d:
return None
d = parent
def _version_dir(p):
"""Version dir for both Windows (.../1cv8/<ver>/bin/1cv8.exe) and *nix (.../1cv8/<ver>/1cv8)."""
parent = os.path.dirname(p)
if os.path.basename(parent).lower() == "bin":
parent = os.path.dirname(parent)
return os.path.basename(parent)
def _version_key(p):
"""Numeric sort key from version dir name."""
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
def resolve_v8path(v8path):
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
if not v8path:
v8path = _find_project_v8path()
if not v8path:
if os.name == "nt":
candidates = (
glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
+ glob.glob(r"C:\Program Files (x86)\1cv8\*\bin\1cv8.exe")
)
else:
# PY-only: PS-порт на *nix не исполняется, поэтому *nix-раскладки нет в .ps1.
candidates = glob.glob("/opt/1cv8/*/1cv8")
if candidates:
v8path = max(candidates, key=_version_key)
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
else:
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
sys.exit(1)
if os.path.isdir(v8path):
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
v8path = os.path.join(v8path, exe)
if not os.path.isfile(v8path):
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
sys.exit(1)
return v8path
IBCMD_NOUSER_HINT = (
"[ibcmd] No -UserName/-Password given; the infobase may require authentication. "
"On Windows ibcmd reads credentials from the console (stdin is ignored), so this "
"call may block instead of failing. If it does not return promptly, abort and "
"re-run with -UserName and -Password.\n"
)
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
"""Run an ibcmd command non-interactively.
input="" closes stdin (EOF) so ibcmd's auth prompt fast-fails instead of hanging.
On Windows without -UserName ibcmd reads the console directly and may still block —
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
"""
if warn_no_user and os.name == "nt" and not has_username:
sys.stderr.write(IBCMD_NOUSER_HINT)
sys.stderr.flush()
return subprocess.run(cmd, input="", capture_output=True, encoding="utf-8", errors="replace")
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(
description="Dump external data processor or report (EPF/ERF) to XML sources",
allow_abbrev=False,
)
parser.add_argument("-V8Path", default="", help="Path to 1cv8.exe or its bin directory")
parser.add_argument("-InfoBasePath", default="", help="Path to file infobase")
parser.add_argument("-InfoBaseServer", default="", help="1C server (for server infobase)")
parser.add_argument("-InfoBaseRef", default="", help="Infobase name on server")
parser.add_argument("-UserName", default="", help="1C user name")
parser.add_argument("-Password", default="", help="1C user password")
parser.add_argument("-InputFile", required=True, help="Path to EPF/ERF file")
parser.add_argument("-OutputDir", required=True, help="Directory for dumped XML sources")
parser.add_argument(
"-Format",
default="Hierarchical",
choices=["Hierarchical", "Plain"],
help="Dump format (default: Hierarchical)",
)
args = parser.parse_args()
# --- Resolve V8Path ---
v8path = resolve_v8path(args.V8Path)
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
# --- Validate database connection ---
if not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
print("Error: database connection required. Specify -InfoBasePath or -InfoBaseServer/-InfoBaseRef", file=sys.stderr)
print("Dump in an empty database loses reference types (CatalogRef, DocumentRef, etc.) irreversibly.")
sys.exit(1)
if engine == "ibcmd":
if not args.InfoBasePath:
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
sys.exit(1)
if args.Format == "Plain":
print("Error: ibcmd config export supports hierarchical format only (use -Format Hierarchical or 1cv8)", file=sys.stderr)
sys.exit(1)
# --- Validate input file ---
if not os.path.isfile(args.InputFile):
print(f"Error: input file not found: {args.InputFile}", file=sys.stderr)
sys.exit(1)
# --- Ensure output directory exists ---
if not os.path.exists(args.OutputDir):
os.makedirs(args.OutputDir, exist_ok=True)
# --- Temp dir ---
temp_dir = os.path.join(tempfile.gettempdir(), f"epf_dump_{random.randint(0, 999999)}")
os.makedirs(temp_dir, exist_ok=True)
try:
if engine == "ibcmd":
# --- ibcmd branch: dump EPF/ERF via config export --file ---
arguments = ["infobase", "config", "export", f"--file={args.InputFile}", args.OutputDir, f"--db-path={args.InfoBasePath}"]
ib_data = tempfile.mkdtemp(prefix="ibcmd_data_")
atexit.register(shutil.rmtree, ib_data, ignore_errors=True)
if args.UserName:
arguments.append(f"--user={args.UserName}")
if args.Password:
arguments.append(f"--password={args.Password}")
arguments.append(f"--data={ib_data}")
print(f"Running: ibcmd {' '.join(arguments)}")
result = run_ibcmd([v8path] + arguments, warn_no_user=False)
if result.returncode == 0:
print(f"External data processor/report dumped successfully to: {args.OutputDir}")
else:
print(f"Error dumping external data processor/report (code: {result.returncode})", file=sys.stderr)
if result.stdout:
print(result.stdout)
if result.stderr:
print(result.stderr, file=sys.stderr)
sys.exit(result.returncode)
# --- Build arguments ---
arguments = ["DESIGNER"]
if args.InfoBaseServer and args.InfoBaseRef:
arguments += ["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"]
else:
arguments += ["/F", args.InfoBasePath]
if args.UserName:
arguments.append(f"/N{args.UserName}")
if args.Password:
arguments.append(f"/P{args.Password}")
arguments += ["/DumpExternalDataProcessorOrReportToFiles", args.OutputDir, args.InputFile]
arguments += ["-Format", args.Format]
# --- Output ---
out_file = os.path.join(temp_dir, "dump_log.txt")
arguments += ["/Out", out_file]
arguments.append("/DisableStartupDialogs")
# --- Execute ---
print(f"Running: 1cv8.exe {' '.join(arguments)}")
result = subprocess.run(
[v8path] + arguments,
capture_output=True,
text=True,
)
exit_code = result.returncode
# --- Result ---
if exit_code == 0:
print(f"Dump completed successfully to: {args.OutputDir}")
else:
print(f"Error dumping (code: {exit_code})", file=sys.stderr)
if os.path.isfile(out_file):
try:
with open(out_file, "r", encoding="utf-8-sig") as f:
log_content = f.read()
if log_content:
print("--- Log ---")
print(log_content)
print("--- End ---")
except Exception:
pass
sys.exit(exit_code)
finally:
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=True)
if __name__ == "__main__":
main()
-30
View File
@@ -1,30 +0,0 @@
---
name: epf-validate
description: Валидация внешней обработки 1С (EPF). Используй после создания или модификации обработки для проверки корректности
argument-hint: <ObjectPath> [-Detailed] [-MaxErrors 30]
allowed-tools:
- Bash
- Read
- Glob
---
# /epf-validate — валидация внешней обработки (EPF)
Проверяет структурную корректность XML-исходников внешней обработки: корневую структуру, InternalInfo, свойства, ChildObjects, реквизиты, табличные части, уникальность имён, наличие файлов форм и макетов. Также работает для внешних отчётов (ERF).
## Параметры
| Параметр | Обяз. | Умолч. | Описание |
|------------|:-----:|---------|-------------------------------------------------|
| ObjectPath | да | — | Путь к корневому XML или каталогу обработки |
| Detailed | нет | — | Подробный вывод (все проверки, включая успешные) |
| MaxErrors | нет | 30 | Остановиться после N ошибок |
| OutFile | нет | — | Записать результат в файл (UTF-8 BOM) |
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/epf-validate/scripts/epf-validate.ps1" -ObjectPath "src/МояОбработка"
powershell.exe -NoProfile -File ".augment/skills/epf-validate/scripts/epf-validate.ps1" -ObjectPath "src/МояОбработка/МояОбработка.xml"
```
-32
View File
@@ -1,32 +0,0 @@
---
name: erf-validate
description: Валидация внешнего отчёта 1С (ERF). Используй после создания или модификации отчёта для проверки корректности
argument-hint: <ObjectPath> [-Detailed] [-MaxErrors 30]
allowed-tools:
- Bash
- Read
- Glob
---
# /erf-validate — валидация внешнего отчёта (ERF)
Проверяет структурную корректность XML-исходников внешнего отчёта: корневую структуру, InternalInfo, свойства (включая MainDataCompositionSchema), ChildObjects, реквизиты, табличные части, уникальность имён, наличие файлов форм и макетов.
Использует тот же скрипт, что и `/epf-validate` — автоопределение по типу элемента (ExternalReport).
## Параметры
| Параметр | Обяз. | Умолч. | Описание |
|------------|:-----:|---------|-------------------------------------------------|
| ObjectPath | да | — | Путь к корневому XML или каталогу отчёта |
| Detailed | нет | — | Подробный вывод (все проверки, включая успешные) |
| MaxErrors | нет | 30 | Остановиться после N ошибок |
| OutFile | нет | — | Записать результат в файл (UTF-8 BOM) |
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/epf-validate/scripts/epf-validate.ps1" -ObjectPath "src/МойОтчёт"
powershell.exe -NoProfile -File ".augment/skills/epf-validate/scripts/epf-validate.ps1" -ObjectPath "src/МойОтчёт/МойОтчёт.xml"
```
@@ -1,126 +0,0 @@
# Form Presets
Пресеты управляют раскладкой форм, генерируемых в режиме `--from-object`.
## Как работает
Цепочка merge (каждый следующий уровень перезаписывает предыдущий через deep merge):
1. **Hardcoded defaults** -- встроены в скрипт, ориентированы на ERP
2. **Built-in preset** -- файл из этой папки (`erp-standard.json` по умолчанию)
3. **Project-level preset** -- файл `presets/skills/form/<name>.json`, поиск вверх от OutputPath
Имя пресета задаётся параметром `--preset` (по умолчанию `erp-standard`).
## Project-level пресет
Чтобы переопределить стандартный пресет в своём проекте, создайте файл:
```
<project-root>/presets/skills/form/erp-standard.json
```
Скрипт ищет этот файл, поднимаясь от OutputPath к корню. Первый найденный файл применяется поверх built-in через deep merge -- не нужно копировать весь пресет, достаточно указать только переопределяемые ключи.
## Секции
Ключи верхнего уровня в JSON -- секции вида `{тип}.{назначение}`:
| Секция | Тип объекта | Назначение формы |
|--------|-------------|------------------|
| `document.item` | Document | Форма документа |
| `document.list` | Document | Форма списка |
| `document.choice` | Document | Форма выбора |
| `catalog.item` | Catalog | Форма элемента |
| `catalog.folder` | Catalog | Форма группы |
| `catalog.list` | Catalog | Форма списка |
| `catalog.choice` | Catalog | Форма выбора |
| `informationRegister.record` | InformationRegister | Форма записи |
| `informationRegister.list` | InformationRegister | Форма списка |
| `accumulationRegister.list` | AccumulationRegister | Форма списка |
| `chartOfCharacteristicTypes.*` | ChartOfCharacteristicTypes | item/folder/list/choice |
| `exchangePlan.*` | ExchangePlan | item/list/choice |
| `chartOfAccounts.*` | ChartOfAccounts | item/folder/list/choice |
### basedOn
Секция может наследовать от другой:
```json
{
"document.choice": {
"basedOn": "document.list",
"properties": { "windowOpeningMode": "LockOwnerWindow" }
}
}
```
## Ключи секций
### Форма объекта (Item/Record)
| Ключ | Описание | Допустимые значения |
|------|----------|---------------------|
| `header.position` | Где размещать шапку | `"insidePage"` -- на первой странице, `"abovePages"` -- над страницами |
| `header.layout` | Колонки шапки | `"1col"`, `"2col"` |
| `header.distribute` | Распределение в 2 колонках | `"even"`, `"left"`, `"right"` |
| `header.dateTitle` | Заголовок даты (Document) | строка, напр. `"от"` |
| `footer.fields` | Поля в подвале | массив имён реквизитов, напр. `["Комментарий"]` |
| `footer.position` | Где размещать подвал | `"insidePage"`, `"belowPages"`, `"none"` |
| `tabularSections.container` | Контейнер табчастей | `"pages"` -- на вкладках, `"inline"` -- в корне, `"single-no-pages"` -- одна ТЧ без страниц |
| `tabularSections.exclude` | Исключить табчасти | массив имён, напр. `["ДополнительныеРеквизиты"]` |
| `tabularSections.lineNumber` | Колонка НомерСтроки | `true` / `false` |
| `additional.position` | Блок доп. реквизитов | `"page"` -- отдельная вкладка, `"below"` -- под табчастями, `"none"` -- не создавать |
| `additional.layout` | Колонки доп. блока | `"1col"`, `"2col"` |
| `additional.bspGroup` | Группа ДополнительныеРеквизиты | `true` / `false` |
| `codeDescription.layout` | Код + Наименование | `"horizontal"`, `"vertical"` |
| `codeDescription.order` | Порядок Код/Наименование | `"descriptionFirst"`, `"codeFirst"` |
| `parent.title` | Заголовок поля Родитель | строка, напр. `"Входит в группу"` |
| `parent.position` | Позиция поля Родитель | `"beforeCodeDescription"`, `"afterCodeDescription"`, `"inHeader"` |
| `owner.readOnly` | Владелец только для чтения | `true` / `false` |
| `owner.position` | Позиция поля Владелец | `"first"` |
| `fieldDefaults.ref.choiceButton` | Кнопка выбора для ссылок | `true` / `false` |
| `fieldDefaults.boolean.element` | Элемент для Boolean | `"check"` (флажок) |
| `commandBar` | Командная панель формы | `"auto"`, `"none"` |
| `properties` | Свойства формы | объект: `autoTitle`, `windowOpeningMode` и др. |
### Форма списка (List/Choice)
| Ключ | Описание | Допустимые значения |
|------|----------|---------------------|
| `columns` | Какие колонки показывать | `"all"` -- все реквизиты, или массив имён |
| `columnType` | Тип элемента колонки | `"labelField"`, `"input"` |
| `hiddenRef` | Скрытая колонка Ref | `true` / `false` |
| `tableCommandBar` | Командная панель таблицы | `"auto"`, `"none"` |
| `commandBar` | Командная панель формы | `"auto"`, `"none"` |
| `choiceMode` | Режим выбора (ChoiceForm) | `true` / `false` |
| `properties` | Свойства формы | объект: `windowOpeningMode` и др. |
## Пример project-level пресета
```json
{
"name": "my-project",
"description": "Стиль форм нашего проекта",
"document.item": {
"header": {
"layout": "1col"
},
"tabularSections": {
"exclude": ["ДополнительныеРеквизиты", "СведенияОСертификатах"]
},
"additional": {
"position": "none"
}
},
"catalog.item": {
"codeDescription": {
"order": "codeFirst"
}
}
}
```
Этот файл переопределяет только указанные ключи -- остальное наследуется из built-in пресета.
@@ -1,68 +0,0 @@
{
"name": "erp-standard",
"description": "ERP 8.3.24 standard form layout",
"document.item": {
"header": {
"position": "insidePage",
"layout": "2col",
"distribute": "even",
"dateTitle": "от"
},
"footer": {
"fields": ["Комментарий"],
"position": "insidePage"
},
"tabularSections": {
"container": "pages",
"exclude": ["ДополнительныеРеквизиты"],
"lineNumber": true
},
"additional": {
"position": "page",
"layout": "2col",
"bspGroup": true
},
"properties": {
"autoTitle": false
}
},
"catalog.item": {
"codeDescription": {
"layout": "horizontal",
"order": "descriptionFirst"
},
"parent": {
"title": "Входит в группу",
"position": "afterCodeDescription"
},
"tabularSections": {
"exclude": ["ДополнительныеРеквизиты", "Представления"]
}
},
"informationRegister.record": {
"properties": {
"windowOpeningMode": "LockOwnerWindow"
}
},
"informationRegister.list": {},
"accumulationRegister.list": {},
"chartOfCharacteristicTypes.item": {
"basedOn": "catalog.item"
},
"exchangePlan.item": {
"basedOn": "catalog.item"
},
"chartOfAccounts.item": {
"parent": {
"title": "Подчинен счету"
}
}
}
@@ -1,123 +0,0 @@
# Оформление
Два независимых механизма: **оформление элемента** (постоянные цвета/шрифт/граница на конкретном элементе) и **условное оформление формы** (`conditionalAppearance` — правила, применяемые при выполнении условия).
## Оформление элемента (цвета / шрифты / граница)
Свойства задаются прямо на элементе. Применимо к полям (`input`/`check`/`radio`/`labelField`/`picField`/`calendar`), декорациям (`label`/`picture`), кнопкам (`button`), группам (`group`/`columnGroup`), страницам (`page`/`pages`), попапам (`popup`) и таблицам (`table`). Каждое свойство необязательно.
| Ключ | Что задаёт |
|------|-----------|
| `textColor` | Цвет текста |
| `backColor` | Цвет фона |
| `borderColor` | Цвет рамки |
| `font` | Шрифт |
| `border` | Граница |
| `titleTextColor` / `titleBackColor` / `titleFont` | Цвет текста / цвет фона / шрифт заголовка колонки (`labelField`, колонки таблицы); у `page`/`pages`/`popup``titleTextColor`/`titleFont` заголовка страницы/попапа |
| `footerTextColor` / `footerBackColor` / `footerFont` | Цвет текста / цвет фона / шрифт подвала колонки |
Те же свойства доступны и через словарь `appearance` элемента — под русскими именами параметров платформы: `ЦветТекста`, `ЦветФона`, `ЦветРамки`, `Шрифт`, `Граница`, `ЦветТекстаЗаголовка`, `ЦветФонаЗаголовка`, `ШрифтЗаголовка`, `ЦветТекстаПодвала`, `ЦветФонаПодвала`, `ШрифтПодвала`. Это та же запись, что и в правилах условного оформления (ниже) и в `appearance` поля дин-списка.
### Цвет
Строка в одной из форм:
| Форма | Значение |
|-------|----------|
| `web:Имя` | Цвет из web-палитры, напр. `web:Red`, `web:FireBrick`, `web:HoneyDew` |
| `win:Имя` | Системный цвет Windows, напр. `win:MenuBar`, `win:ButtonText`, `win:DisabledText` |
| `style:ИмяСтиля` | Ссылка на элемент стиля конфигурации/платформы, напр. `style:FormBackColor`, `style:BorderColor` |
| `#RRGGBB` | RGB-hex, напр. `#FF0000` |
Имя должно существовать в своей палитре (несуществующий web-/win-цвет или ссылка на отсутствующий `style:`-элемент — ошибка загрузки формы).
### Шрифт (`font` / `titleFont` / `footerFont`)
- Строка `"style:ИмяСтиля"` — шрифт из элемента стиля. Минимальная форма.
- Объект — задаются только нужные атрибуты:
| Ключ | Назначение |
|------|-----------|
| `ref` | Ссылка на стиль (`"style:X"`) или системный шрифт (`"sys:…"`) |
| `faceName` | Имя гарнитуры (для собственного шрифта) |
| `height` | Размер |
| `bold` / `italic` / `underline` / `strikeout` | `true`/`false` — начертание |
| `scale` | Масштаб, % |
| `kind` | `Absolute` (собственный шрифт — с `faceName`+`height`) / `WindowsFont` (системный — с `ref:"sys:…"`) |
```json
{ "label": "Внимание!", "textColor": "web:FireBrick",
"font": { "faceName": "Arial", "height": 12, "bold": true, "kind": "Absolute", "scale": 100 } }
```
### Граница (`border`)
- Строка `"style:ИмяСтиля"` (или объект `{ "ref": "style:X" }`) — граница из стиля.
- Объект `{ "width": N, "style": "..." }` — собственная граница. `style` — один из: `Single`, `Double`, `Underline`, `DoubleUnderline`, `Overline`, `Embossed`, `Indented`, `WithoutBorder`.
```json
{ "input": "Цена", "path": "Объект.Цена", "textColor": "#FF0000",
"borderColor": "style:BorderColor", "border": { "width": 1, "style": "Single" } }
{ "labelField": "Код", "titleTextColor": "web:HoneyDew", "border": "style:ControlBorder" }
```
## Условное оформление формы (`conditionalAppearance`)
Форменный ключ верхнего уровня — массив правил. Каждое правило применяет оформление к перечисленным полям, когда выполняется его условие.
```json
"conditionalAppearance": [
{ "selection": ["ОбычноеПоле"], "filter": ["ЧисловоеПоле > 100"],
"appearance": { "ЦветФона": "style:FormBackColor" },
"presentation": { "ru": "Подсветка", "en": "Highlight" } }
]
```
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `selection` | array | Имена форматируемых полей формы |
| `filter` | array | Условие применения (грамматика — ниже) |
| `appearance` | object | Словарь «параметр платформы: значение» |
| `presentation` | string / object | Подпись правила в списке настроек |
| `use` | bool | `false` — правило отключено |
| `viewMode` | string | Режим отображения настройки |
| `userSettingID` | string | Идентификатор пользовательской настройки; `"auto"` — сгенерировать |
### filter
Та же грамматика, что в отборе списка — shorthand `"Поле оператор значение @флаги"` или объект:
```json
"filter": [
"Статус = 3",
{ "field": "Сумма", "op": ">=", "value": 1000 },
{ "group": "Or", "items": [ "Просрочено = true", "Заблокирован = true" ] }
]
```
- **Операторы:** `=` `<>` `>` `>=` `<` `<=`, `in` / `notIn`, `inHierarchy`, `contains` / `notContains`, `beginsWith` / `notBeginsWith`, `like` / `notLike` (`%`-шаблон), `filled` / `notFilled`.
- **Флаги:** `@off` (отключён), `@user`, `@quickAccess`; `_` = пустое значение.
- **Группа:** `{ "group": "And"|"Or"|"Not", "items": [...], "use"? }`.
- **Дата-значение:** ISO-дата `"2024-01-01T00:00:00"` — фиксированная дата; именованный относительный период — строкой `"BeginningOfThisWeek"` с `"valueType": "v8:StandardBeginningDate"` (варианты `BeginningOfThisDay`/`BeginningOfThisWeek`/`BeginningOfThisMonth`/`BeginningOfThisYear`/…).
### appearance
Словарь «параметр платформы: значение». Имена параметров — русские: `ЦветТекста`, `ЦветФона`, `Шрифт`, `Граница`, `Текст`, `Заголовок`, `Формат`, `ВидимостьЭлемента`, `Доступность` и другие параметры оформления компоновки.
Значения:
- **Цвет** (`ЦветТекста`/`ЦветФона`/…) и **шрифт** (`Шрифт`) — те же формы, что в оформлении элемента выше (`web:`/`win:`/`style:`/`#RRGGBB`; шрифт — строка `"style:X"` или объект).
- **Текстовые параметры** (`Текст`/`Заголовок`/`Формат`) — по форме значения:
- голая строка → нелокализованный литерал (`""` → пустое значение);
- объект `{ "ru": "...", "en": "..." }` → локализуемая строка;
- объект `{ "field": "путь" }` → ссылка на поле компоновки.
```json
"conditionalAppearance": [
{ "selection": ["Остаток"], "filter": ["Остаток < 0"],
"appearance": { "ЦветТекста": "web:Red", "Шрифт": { "bold": true } } },
{ "selection": ["Комментарий"], "filter": ["Комментарий notFilled"],
"appearance": { "Текст": { "ru": "— нет данных —" }, "ЦветТекста": "win:DisabledText" } }
]
```
> Условное оформление **самого дин-списка** задаётся не здесь, а в `settings.conditionalAppearance` реквизита-списка — см. `references/dynamic-list.md`.
@@ -1,143 +0,0 @@
# Диаграммы, диаграмма Ганта, планировщик
Поле-диаграмма (`chart` / `ganttChart`), поле-планировщик (`planner`) и дендрограмма выводят значение из реквизита соответствующего типа. Конструкция всегда двойная:
1. **Реквизит** chart/planner-типа (несёт данные и, при необходимости, design-time конфиг).
2. **Элемент** формы, привязанный к реквизиту через `path`.
Минимум — реквизит нужного типа плюс элемент с тем же `path`:
```json
"attributes": [ { "name": "Диаграмма", "type": "d5p1:Chart" } ],
"items": [ { "chart": "ПолеДиаграммы", "path": "Диаграмма" } ]
```
Реквизит, заполняемый в коде (без встроенной настройки), достаточно объявить типом — элемент привязывается и работает.
## Типы реквизита и элемента
| Элемент | Ключ типа | Тип реквизита | Что несёт элемент дополнительно |
|---------|-----------|---------------|---------------------------------|
| Диаграмма | `chart` | `d5p1:Chart` | — |
| Диаграмма Ганта | `ganttChart` | `d5p1:GanttChart` | `ganttTable` — вложенная таблица (см. ниже) |
| Планировщик | `planner` | `pl:Planner` | — |
| График. схема | `graphicalSchema` | `d5p1:FlowchartContextType` | `edit`, `warningOnEditRepresentation` |
| Период | `periodField` | `v8:StandardPeriod` | — |
| Дендрограмма | `dendrogram` | — | — |
Имя элемента — значение ключа (`"chart": "ПолеДиаграммы"`); `path` — короткое имя реквизита.
### Элемент диаграммы Ганта (`ganttTable`)
У поля Ганта внутри лежит полноценная таблица — задаётся ключом `ganttTable` (та же грамматика, что у обычной `table`):
```json
{ "ganttChart": "Ганта", "path": "Ганта",
"ganttTable": { "table": "ТаблицаГанта", "path": "Ганта", "height": 3 } }
```
## Design-time конфиг диаграммы (`chart`)
Реквизит типа `d5p1:Chart` / `d5p1:GanttChart` может нести встроенную настройку диаграммы — объект `chart` на реквизите. Платформа всегда пишет полный набор свойств (~127: тип, серии, легенда, заголовок, шкалы, цвета, шрифты, оси), поэтому **авторинг с нуля непрактичен** — возьмите рабочую диаграмму за основу и правьте смысловое ядро.
Ключи `chart` = канонические имена свойств диаграммы; задавайте только те, что меняете:
```json
{ "name": "Диаграмма", "type": "d5p1:Chart", "chart": {
"chartType": "Line",
"isSeriesDesign": true, "realSeriesCount": "2",
"realSeriesData": [
{ "id": "1", "color": "auto", "line": {"width":2,"gap":false,"style":"Solid"},
"marker": "Auto", "text": "Серия 1", "strIsChanged": false, "isExpand": false,
"isIndicator": false, "colorPriority": false }
],
"isShowTitle": true, "title": "Продажи",
"isShowLegend": true, "legendPlacement": "Bottom",
"paletteKind": "Auto"
} }
```
Смысловое ядро для правки:
| Ключ | Назначение |
|------|------------|
| `chartType` | Тип: `Line` / `Pie` / `Bar` / `Histogram` / `Column` / `Area` / … |
| `realSeriesData` | Массив серий — объекты `{ id, text, color, line, marker, … }` |
| `isShowTitle` + `title` | Показ и текст заголовка |
| `isShowLegend` + `legendPlacement` | Показ и расположение легенды (`Bottom` / `Right` / …) |
| `paletteKind` | Палитра (`Auto` / …) |
| `bkgColor` / `labelsColor` / … | Базовые цвета |
Формы значений внутри `chart`:
- **Цвета** — verbatim: `auto`, `style:ИмяСтиля`, `web:Red`, `#hex`.
- **`line`** — `{ width, gap, style }` (стиль линии: `Solid` / …).
- **`border`** — `{ width, style }`.
- **`font`** — `{ kind: "AutoFont" }` либо атрибуты шрифта.
- **Локализуемые строки** (`title`, `vsFormat`, `lbFormat`, `labelFormat`, серия `text`, …) — голая строка либо `{ "ru": "…", "en": "…" }`.
- **Области** (`elementsChart` / `elementsLegend` / `elementsTitle`) — `{ left, right, top, bottom }`.
- **Серии** (`realSeriesData` / `realExSeriesData`) — массивы объектов.
Любое из ~127 свойств переопределяется по каноническому имени; остальное оставляйте дефолтным (не указывайте — берётся из основы).
### Диаграмма Ганта (`d5p1:GanttChart`)
Реквизит типа `d5p1:GanttChart` использует **тот же** ключ `chart`. Внутри — вложенный полный `chart`-блок плюс гант-специфика (`points` / `series` / `timeScale` / `drawEmpty` / …). Так же берите рабочую диаграмму Ганта за основу.
> **Ограничение.** Диаграммы (Chart/Gantt) с заполненными **точками/осями** (`realPointData` / `realDataItems`, заполненные `valuesAxis` / `pointsAxis`) генерик-движком не поддержаны — это редкий вариант. Частые дашборд-диаграммы и диаграммы Ганта (серии / легенда / оформление / шкалы) поддержаны полностью.
## Design-time конфиг планировщика (`planner`)
Реквизит типа `pl:Planner` несёт встроенную настройку планировщика — объект `planner`. Компилятор подставляет умолчания для пропущенных ключей, поэтому авторинг может быть кратким:
```json
{ "name": "Планировщик", "type": "pl:Planner", "planner": {
"items": [
{ "text": "Встреча", "begin": "2026-06-09T01:00:00", "end": "2026-06-09T04:00:00",
"borderColor": "auto", "backColor": "auto", "deleted": false, "editMode": "EnableEdit" }
],
"period": { "begin": "2026-06-09T00:00:00", "end": "2026-06-09T23:59:59" },
"displayCurrentDate": true, "itemsTimeRepresentation": "BeginTime",
"timeScale": { "placement": "Left", "levels": [ { "measure": "Hour", "interval": 1 } ] }
} }
```
Минимум — один `item`:
```json
"planner": { "items": [ { "text": "Встреча", "begin": "2026-06-09T01:00:00", "end": "2026-06-09T04:00:00" } ] }
```
| Ключ `planner` | Тип | Назначение |
|----------------|-----|------------|
| `items` | array | Элементы расписания. Поля элемента: `text`, `tooltip`, `begin`, `end`, `value`, `borderColor`, `backColor`, `textColor`, `font`, `border`, `replacementDate`, `deleted` (bool), `editMode` (`EnableEdit` / …), `id` (необязательно — авто-GUID), `textFormatted` |
| `dimensions` | array | Измерения (разрезы) планировщика. Поля: `value` (объект разреза — ссылка `Enum.X.EnumValue.Y` / `Справочник.X`; опустить → пусто), `text` (заголовок), `borderColor`, `backColor`, `textColor`, `font`, `textFormatted`, `elements`. `elements` — элементы измерения, рекурсивны (могут нести вложенные `elements`): `value`, `text`, цвета, `font`, `showOnlySubordinatesAreas` (bool), `textFormatted` |
| `period` | object | Отображаемый период `{ begin, end }` (необязательно) |
| `timeScale` | object | Шкала времени (см. ниже) |
| `borderColor` / `backColor` / `textColor` / `lineColor` | color | Цвета (умолч. `auto`) |
| `font` | font | Шрифт (умолч. `{ kind: "AutoFont" }`) |
| `border` | border | Рамка `{ width, style }` |
| `beginOfRepresentationPeriod` / `endOfRepresentationPeriod` | dateTime | Период представления |
| `displayCurrentDate` / `displayWrapHeaders` / `displayTimeScaleWrapHeaders` / `alignElementsOfTimeScale` | bool | Флаги отображения |
| `timeScaleWrapHeadersFormat` | ML | Формат перенесённых заголовков шкалы |
| `timeScaleWrapBeginIndent` / `timeScaleWrapEndIndent` | int | Отступы переноса шкалы |
| `periodicVariantUnit` / `periodicVariantRepetition` | value / int | Единица и кратность периодического варианта |
| `itemsTimeRepresentation` | value | Представление времени элементов (`BeginTime` / …) |
| `itemsBehaviorWhenSpaceInsufficient` / `newItemsTextType` / `fixDimensionsHeader` / `fixTimeScaleHeader` | value | Поведение элементов и заголовков |
| `autoMinColumnWidth` / `autoMinRowHeight` | bool | Авто-минимум размеров |
| `minColumnWidth` / `minRowHeight` | int | Минимальные размеры |
Шкала времени (`timeScale`):
```json
"timeScale": {
"placement": "Left",
"levels": [ { "measure": "Hour", "interval": 1 } ]
}
```
Ключи: `placement`, `levels` (массив уровней), `transparent`, `backColor`, `textColor`, `currentLevel`. Уровень: `measure` (`Hour` / `Day` / …), `interval`, `show`, `line` (`{ width, gap, style }`), `scaleColor`, `dayFormatRule`, `format` (ML), `labels` (`{ ticks }`), `backColor`, `textColor`, `showPereodicalLabels`.
Формы значений в `planner` те же, что у диаграммы: цвета verbatim (`auto` / `style:X` / `web:Red` / `#hex`); шрифт `{ kind: "AutoFont" }` либо ref-строка; граница `{ width, style }`; ML-форматы — строка или `{ "ru": …, "en": … }`.
> **Ограничение.** Привязка элемента расписания к элементам измерений (`item.dimensionValues`) пока всегда пустая. Сами измерения (`dimensions`) задавать можно.
@@ -1,73 +0,0 @@
# Параметры выбора и связь по типу
Свойства поля ввода (`input`), управляющие выбором значения: чем ограничен список выбора и каким будет тип значения. Имена параметров — строки 1С как есть (`"Отбор.Х"`).
```json
{ "input": "Контрагент", "path": "Объект.Контрагент",
"choiceParameters": [
{ "name": "Отбор.Активный", "value": true },
{ "name": "Отбор.ВидПродукции", "value": ["Enum.Виды.Агрохимикат", "Enum.Виды.Пестицид"] }
],
"choiceParameterLinks": [
{ "name": "Отбор.Организация", "dataPath": "Объект.Организация" },
{ "name": "Отбор.Тип", "dataPath": "Объект.Тип", "valueChange": "DontChange" }
],
"typeLink": { "dataPath": "Объект.ЗначениеДата", "linkItem": 0 }
}
```
## Параметры выбора (`choiceParameters`)
Фиксированные значения параметров выбора, отбирающие список значений независимо от данных формы. Массив объектов `{ name, value }`:
- `name` — имя параметра (`"Отбор.Активный"`).
- `value` — значение. Допустимы: bool, число, строка, ISO-дата (`"2020-01-01T00:00:00"`), ссылка-путь (`Enum.X.Y`, `Catalog.X`). **Массив** значений задаёт фиксированный массив.
Короткая форма — строки `"name=value"`; значение с запятыми становится массивом, `true`/`false` → bool, число → число, остальное → строка/ссылка:
```json
"choiceParameters": [
"Отбор.Активный=true",
"Отбор.ВидПродукции=Enum.Виды.Агрохимикат, Enum.Виды.Пестицид"
]
```
## Связи параметров выбора (`choiceParameterLinks`)
Параметры выбора, значение которых берётся из **другого поля формы** (а не задано фиксированно). Типовой случай — отбор списка договоров по выбранному контрагенту. Массив объектов `{ name, dataPath, valueChange? }`:
- `name` — имя параметра выбора.
- `dataPath` — путь к полю формы, чьё значение подставляется в параметр.
- `valueChange` — что делать с уже выбранным значением при смене источника: `Clear` (очистить, необязательно — поведение по умолчанию) / `DontChange` (не менять).
```json
{ "input": "Договор", "path": "Объект.Договор",
"choiceParameterLinks": [
{ "name": "Отбор.Владелец", "dataPath": "Объект.Контрагент" }
]
}
```
Короткая форма — строки `"name=dataPath"`, опциональный хвост `:Clear` / `:DontChange`:
```json
"choiceParameterLinks": [ "Отбор.Организация=Объект.Организация", "Отбор.Тип=Объект.Тип:DontChange" ]
```
## Связь по типу (`typeLink`)
Тип значения поля определяется другим полем формы (напр. поле «Значение» субконто, тип которого задаётся выбранным видом субконто). Объект `{ dataPath, linkItem }`:
- `dataPath` — путь к полю, задающему тип.
- `linkItem` — индекс элемента связи (необязательно, по умолчанию `0`).
```json
"typeLink": { "dataPath": "Объект.ВидСубконто", "linkItem": 0 }
```
Короткая форма — строка `"dataPath"` либо `"dataPath#linkItem"`:
```json
"typeLink": "Объект.ВидСубконто"
"typeLink": "Объект.ВидСубконто#1"
```
@@ -1,86 +0,0 @@
# Командный интерфейс формы
Форменный ключ `commandInterface` управляет расстановкой команд по двум панелям формы:
- `commandBar` — командная панель формы;
- `navigationPanel` — панель навигации.
Указывать нужно **только команды, у которых меняется расстановка по умолчанию** (видимость, группа, порядок). Команды, которые платформа размещает автоматически и без изменений, в блок не включают.
```json
"commandInterface": {
"commandBar": [
{ "command": "Form.Command.Печать", "defaultVisible": false, "group": "FormCommandBarImportant",
"visible": { "common": false, "roles": { "Бухгалтер": true } } },
"CommonCommand.История"
],
"navigationPanel": {
"important": [ { "command": "CommonCommand.СвязанныеДокументы", "defaultVisible": false, "visible": false } ],
"seeAlso": [ { "command": "CommonCommand.Заметки", "defaultVisible": false, "visible": false } ]
}
}
```
## Элемент-команда
Каждый элемент панели — объект, либо строка-shorthand (= голый `command` со всеми остальными свойствами по умолчанию):
```json
"CommonCommand.История"
```
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `command` | string | Ссылка на команду дословно: `CommonCommand.X`, `Document.X.StandardCommand.Y`, `Form.Command.X`, `Form.StandardCommand.OK`, `"0"` (пустой / разделитель) |
| `type` | string | `Auto` (по умолчанию, необязательно) или `Added` |
| `defaultVisible` | bool | Видимость по умолчанию. На практике задаётся только `false` — чтобы скрыть команду, которая иначе видна |
| `visible` | bool / object | Видимость с исключениями по ролям: `bool` либо `{ "common": bool, "roles": { "Имя": bool } }` |
| `group` | string | Группа размещения дословно: предопределённая (`FormCommandBarImportant`, `FormNavigationPanelGoTo`, …), именованная (`CommandGroup.X`) или GUID-группа расширения |
| `index` | int | Порядок команды внутри группы |
| `attribute` | string | Путь реквизита для элемента панели навигации |
## Две формы записи панели
Панель можно описать **плоским массивом** или **деревом по группам** — выбирайте любую.
**Плоский массив** — каждый элемент при необходимости несёт собственный `group`:
```json
"commandBar": [
{ "command": "Form.Command.Печать", "group": "FormCommandBarImportant", "defaultVisible": false },
{ "command": "CommonCommand.История", "group": "FormCommandBarImportant", "index": 1 }
]
```
**Дерево** — объект `{ группа: [команды] }`; группа берётся из ключа, элементы её не повторяют:
```json
"navigationPanel": {
"important": [ "CommonCommand.СвязанныеДокументы" ],
"goTo": [ { "command": "Document.Заказ.StandardCommand.Movements", "defaultVisible": false, "visible": false } ],
"seeAlso": [ "CommonCommand.Заметки" ]
}
```
Ключи-группы дерева зависят от панели:
- `navigationPanel`: `important`, `goTo`, `seeAlso` (можно по-русски — `важное`, `перейти`, `смТакже`);
- `commandBar`: `important`, `createBasedOn`;
- любой другой ключ (`CommandGroup.X` или GUID) подставляется в группу дословно.
## Скрыть видимую команду
Самый частый случай — убрать команду, которую платформа показывает по умолчанию:
```json
"commandBar": [
{ "command": "Form.Command.Печать", "defaultVisible": false, "visible": false }
]
```
Показать команду только некоторым ролям:
```json
{ "command": "Form.Command.Печать", "defaultVisible": false,
"visible": { "common": false, "roles": { "Бухгалтер": true } } }
```
@@ -1,131 +0,0 @@
# Companion-панели и расширенная подсказка элемента
Любой элемент формы может нести свой собственный контент в трёх companion-свойствах: расширенную подсказку (`extendedTooltip`), командную панель (`commandBar`) и контекстное меню (`contextMenu`). Все три задаются ключами прямо на объекте элемента.
```jsonc
{ "table": "Список", "path": "Список",
"commandBar": { "children": [ ] },
"contextMenu": { "children": [ ] },
"extendedTooltip": "Двойной клик открывает карточку" }
```
## Расширенная подсказка (`extendedTooltip`)
Подсказка-надпись рядом с элементом. Две формы записи.
**Текст-форма** — просто текст подсказки:
```jsonc
"extendedTooltip": "Укажите ИНН контрагента"
"extendedTooltip": { "ru": "Сумма с НДС", "en": "Amount incl. VAT" }
"extendedTooltip": { "text": "Всего <b>с НДС</b>", "formatted": true }
```
- строка — ru-текст;
- `{ "ru": …, "en": … }` — многоязычный (как `title`);
- `{ "text": …, "formatted": true }` — форматированный текст (inline-разметка 1С: `<b>…</>`, `<i>`, `<u>`, `<color web:Red>…</>`, `<bgColor …>`, `<font …>`, `<fontSize …>`, `<link URL>…</>`, `<img …>`; закрывающий тег — `</>`). `formatted` нужен только когда текст содержит такую разметку.
**Own-content форма** — объект с раскладкой/оформлением/флагами, когда подсказке нужны размеры, цвет, гиперссылка и т.п.:
```jsonc
"extendedTooltip": {
"text": "Перейти к инструкции",
"hyperlink": true,
"textColor": "web:Blue",
"events": { "URLProcessing": "ПодсказкаОбработкаНавигационнойСсылки" }
}
```
Ключи own-content объекта (все необязательны):
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `text` | string/ML | Текст подсказки (с `formatted` — форматированный) |
| `formatted` | bool | Интерпретировать inline-разметку в `text` |
| `tooltip` | string/ML | Всплывающая подсказка самой расширенной подсказки (редко; ≠ обычному `tooltip` элемента) |
| `hyperlink` | bool | Сделать подсказку гиперссылкой |
| `visible` / `enabled` | bool | Видимость / доступность подсказки |
| `width` / `height` | number | Размеры |
| `maxWidth` / `autoMaxWidth` | number / bool | Максимальная ширина / авто-максимум |
| `titleHeight` | number | Высота заголовка |
| `horizontalStretch` | bool | Горизонтальное растяжение |
| `verticalAlign` | string | Вертикальное выравнивание |
| `textColor` / `font` | string/object | Цвет текста / шрифт (см. `references/appearance.md`) |
| `events` | object | Обработчики событий подсказки, напр. `{ "URLProcessing": "Имя" }` у гиперссылочной подсказки |
## Командная панель (`commandBar`)
Собственная командная панель элемента (обычно таблицы или группы).
**Значение** — массив или объект:
```jsonc
"commandBar": [ { "button": "Создать", "command": "СоздатьЭлемент" } ]
"commandBar": {
"autofill": false,
"horizontalAlign": "Right",
"children": [
{ "button": "Создать", "command": "СоздатьЭлемент" },
{ "buttonGroup": "Печать", "children": [ ] }
]
}
```
- массив `[ … ]` — краткая запись для `{ "children": [ … ] }`;
- объект — `children` плюс необязательные `autofill` и `horizontalAlign`.
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `children` | array | Содержимое панели — обычная грамматика кнопок (см. основную инструкцию) |
| `autofill` | bool | `false` — подавить автозаполнение панели стандартными командами. Необязательно (по умолчанию панель автозаполняется) |
| `horizontalAlign` | string | Горизонтальное выравнивание содержимого: `Left` / `Center` / `Right`. Необязательно |
`children` — кнопки: `button` (с `command` / `commandName` / `stdCommand`), `buttonGroup`, `popup` — как в основной инструкции по кнопкам.
> Для таблицы динамического списка панель по умолчанию подавлена (чтобы не дублировать командную панель формы). Чтобы оставить автозаполняемую панель у самой таблицы — задайте `commandBar: { "autofill": true }`.
## Контекстное меню (`contextMenu`)
Собственное контекстное меню элемента. Грамматика та же, что у `commandBar`, но без `horizontalAlign`.
```jsonc
"contextMenu": [ { "button": "Карта маршрута", "commandName": "CommonCommand.КартаМаршрута" } ]
"contextMenu": {
"autofill": false,
"children": [
{ "button": "Скопировать ссылку", "command": "СкопироватьСсылку" }
]
}
```
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `children` | array | Пункты меню — обычная грамматика кнопок |
| `autofill` | bool | `false` — подавить автозаполнение меню. Необязательно |
## Пример: таблица со своим меню и инфо-баннером
```jsonc
{ "table": "Заказы", "path": "Объект.Заказы",
"extendedTooltip": {
"text": "Строки с просрочкой выделены <color web:FireBrick>красным</>",
"formatted": true
},
"commandBar": {
"autofill": false,
"horizontalAlign": "Right",
"children": [
{ "button": "Добавить", "command": "ДобавитьЗаказ" },
{ "button": "Удалить", "command": "УдалитьЗаказ" }
]
},
"contextMenu": {
"children": [
{ "button": "Открыть документ", "command": "ОткрытьЗаказ" },
{ "buttonGroup": "Экспорт", "children": [
{ "button": "В Excel", "command": "ВыгрузитьВExcel" } ] }
]
} }
```
@@ -1,144 +0,0 @@
# Динамический список
Реквизит с `type: "DynamicList"` (обычно `main: true`) — основа формы списка. Объект `settings` описывает источник данных и настройки списка. Минимум — указать источник:
```json
{ "name": "Список", "type": "DynamicList", "main": true,
"settings": { "mainTable": "Catalog.Контрагенты" } }
```
К списку привязывается таблица-элемент (`table`), ссылающаяся на реквизит через `path` — см. основную инструкцию.
## Источник данных
Два взаимоисключающих режима:
**Таблично-ориентированный** — основная таблица метаданных:
```json
"settings": { "mainTable": "Catalog.Контрагенты" }
```
**Запросный** — произвольный запрос:
```json
"settings": {
"query": "ВЫБРАТЬ Т.Ссылка, Т.Наименование, Т.Сумма ИЗ Документ.Заказ КАК Т ГДЕ Т.Сумма > &Порог",
"mainTable": "Document.Заказ"
}
```
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `mainTable` | string | Основная таблица (`Catalog.X` / `Document.X` / …). Можно вместе с `query` |
| `query` | string | Текст запроса. Поддерживает `@file.sql` (путь к файлу запроса рядом с JSON) |
| `keyType` | string | Запросный список без `mainTable`: тип ключа набора — `FieldValue` / `RowKey` / `RowNumber` |
| `keyFields` | array | Поля ключа набора (для `keyType` без `mainTable`) |
Параметры запроса (`&Имя`) задаются в `parameters` (ниже).
`"dynamicDataRead": false` отключает динамическое считывание (список читается обычным запросом, без фонового обновления) — нужно для тяжёлых/агрегатных запросов.
## Параметры запроса (`parameters`)
Значения для `&параметров` текста запроса. Shorthand `"Имя [Заголовок]: тип = Значение"` (всё кроме имени необязательно) либо объект:
```json
"settings": {
"query": "… ГДЕ Т.Артикул = &Артикул И Т.Цена ПОДОБНО &Маска",
"parameters": [
"Артикул",
"Маска: string = %",
{ "name": "ВидЦен", "valueListAllowed": true },
{ "name": "Период", "type": "dateTime" }
]
}
```
Ключи объекта: `name`, `title`, `type` (грамматика типов — см. основную инструкцию), `value`, `valueListAllowed` (разрешить список значений), `availableValues` (`[{ value, presentation }]`), `expression`, `use`.
## Значения параметров в настройках (`dataParameters`)
Предустановленные значения параметров на уровне настроек списка. Shorthand `"Имя = Значение"` или объект `{ parameter, value?, use?, viewMode? }`:
```json
"dataParameters": [ "Организация = _", "ВидЦен" ]
```
## Поля набора (`fields`)
Обычно поля выводятся из источника сами — `fields` нужен **только чтобы переопределить** свойства отдельного поля:
```json
"fields": [
{ "field": "Сумма", "title": "Сумма, руб", "appearance": { "Формат": "ЧДЦ=2" } },
{ "field": "Остаток", "valueType": "number(15,2)" }
]
```
Ключи поля: `field`, `dataPath`, `title`, `valueType`, `appearance` (как в условном оформлении), `presentationExpression`, `inputParameters` (связь по параметрам выбора), `typeLink` (`{ field, linkItem }` — связь по типу, напр. субконто).
## Вычисляемые поля (`calculatedFields`)
Поля, считаемые выражением. Shorthand `"Имя [Заголовок]: тип = Выражение"`:
```json
"calculatedFields": [
"Метка = Code + \" \" + Description",
"Маржа [Маржа, руб]: number(15,2) = Цена - Закупка"
]
```
Объектная форма — для `presentationExpression` / `orderExpression`:
```json
{ "dataPath": "Сорт", "expression": "Code", "title": "Сорт",
"valueType": "string(10)", "presentationExpression": "Code" }
```
## Отбор (`filter`)
Shorthand `"Поле оператор значение @флаги"` или объект:
```json
"filter": [
"Организация = _ @off @user",
"Сумма > 1000",
{ "field": "Дата", "op": ">=", "value": "2024-01-01T00:00:00" },
{ "group": "Or", "items": [ "Статус = 1", "Статус = 2" ] }
]
```
- **Операторы:** `=` `<>` `>` `>=` `<` `<=`, `in` / `notIn`, `inHierarchy`, `contains` / `notContains`, `beginsWith` / `notBeginsWith`, `like` / `notLike` (`%`-шаблон), `filled` / `notFilled`.
- **Флаги:** `@off` (отключён), `@user` (в пользовательских настройках), `@quickAccess`; `_` = пустое значение.
- **Группа:** `{ group: "And"|"Or"|"Not", items: [...] }`.
- **Дата-значение:** ISO-дата `"2024-01-01T00:00:00"` — фиксированная дата. Именованный относительный период — строкой с типом: `{ "value": "BeginningOfThisWeek", "valueType": "v8:StandardBeginningDate" }` (варианты `BeginningOfThisDay`/`BeginningOfThisWeek`/`BeginningOfThisMonth`/`BeginningOfThisYear`/…).
## Сортировка (`order`)
Строка `"Поле"` (по возр.) / `"Поле desc"`, либо объект `{ field, direction? }`. `"Auto"` — автосортировка:
```json
"order": [ "Дата desc", "Наименование", "Auto" ]
```
## Группировка строк (`grouping`)
Линейная цепочка уровней (внешний → внутренний). Шорткат `>` или массив:
```json
"grouping": "Контрагент > Договор"
"grouping": [ "Контрагент", { "field": "Дата", "groupType": "Hierarchy" } ]
```
Ключи уровня-объекта: `field`, `groupType` (`Items` / `Hierarchy`).
## Условное оформление (`conditionalAppearance`)
```json
"conditionalAppearance": [
{ "filter": [ "Просрочено = true" ], "appearance": { "ЦветТекста": "web:Red" } }
]
```
`filter` — та же грамматика, что выше. `appearance` — словарь «параметр платформы: значение» (`ЦветТекста`, `ЦветФона`, `Шрифт`, `Текст`, `Формат`, …). Значение `Текст`/`Заголовок`/`Формат`: голая строка — нелокализованный литерал; `{ru,en}` — локализуемая строка; `{ field: "путь" }` — ссылка на поле. Подробнее об оформлении — `references/appearance.md`.
@@ -1,111 +0,0 @@
# Продвинутая раскладка
Тонкая настройка размещения элемента внутри родителя сверх базовой геометрии (`width`/`height`/`horizontalStretch`/`verticalStretch`/`visible`/`enabled` и ориентации групп/страниц — они в основной инструкции). Все ключи ниже задаются прямо на элементе и **необязательны** — без них действует поведение платформы по умолчанию.
## Выравнивание внутри родителя
Различают **выравнивание самого элемента** в отведённой ему ячейке и **выравнивание содержимого** элемента.
| Ключ | Значения | Что выравнивает |
|------|----------|-----------------|
| `groupHorizontalAlign` | `Left` / `Center` / `Right` | Положение **элемента** по горизонтали в родительской группе (когда элемент у́же доступного места) |
| `groupVerticalAlign` | `Top` / `Center` / `Bottom` | Положение **элемента** по вертикали в родительской группе |
| `horizontalAlign` | `Left` / `Center` / `Right` | Выравнивание **содержимого** (текста/значения) внутри самого элемента |
| `verticalAlign` | `Top` / `Center` / `Bottom` | Выравнивание содержимого по вертикали внутри элемента |
`group*Align` отвечает на вопрос «куда сдвинуть нерастянутый элемент в его ячейке», `horizontalAlign`/`verticalAlign` — «как разместить текст внутри элемента». Это разные оси настройки, их часто комбинируют.
```json
{ "button": "ОК", "groupHorizontalAlign": "Right" }
{ "input": "Сумма", "path": "Объект.Сумма", "horizontalAlign": "Right" }
{ "label": "Итого", "groupHorizontalAlign": "Center", "horizontalAlign": "Center" }
```
## Ограничение максимального размера
По умолчанию растягивающийся элемент имеет авто-вычисляемый предел ширины/высоты. Чтобы задать жёсткий предел или вовсе снять авто-предел:
| Ключ | Значения | Назначение |
|------|----------|-----------|
| `maxWidth` | число | Жёсткий максимум ширины элемента |
| `maxHeight` | число | Жёсткий максимум высоты элемента |
| `autoMaxWidth` | `false` | Отключить авто-предел ширины (элемент тянется без ограничения сверху) |
| `autoMaxHeight` | `false` | Отключить авто-предел высоты |
`autoMaxWidth: false` нужен, например, для широкого многострочного поля или растянутого по всей форме поля ввода, чтобы платформа не «прижимала» его к авто-пределу. Указывают именно отклонение от дефолта; обычное значение `true` писать не нужно.
```json
{ "input": "Комментарий", "path": "Объект.Комментарий", "multiLine": true,
"horizontalStretch": true, "autoMaxWidth": false }
{ "input": "Поиск", "path": "СтрокаПоиска", "horizontalStretch": true, "maxWidth": 600 }
```
## Поведение при вводе и активации
| Ключ | Значения | Назначение |
|------|----------|-----------|
| `skipOnInput` | `true` / `false` | Пропускать элемент при обходе по Enter/Tab (фокус через него не проходит). Указывают явно, в т.ч. `false` чтобы вернуть в обход поле, которое платформа пропустила бы |
| `defaultItem` | `true` | Элемент получает фокус по умолчанию при открытии формы (поле/таблица для немедленного ввода) |
```json
{ "input": "Идентификатор", "path": "Объект.Идентификатор", "skipOnInput": true }
{ "input": "Штрихкод", "path": "Штрихкод", "defaultItem": true }
```
`skipOnInput: true` — для служебных/расчётных полей, которые видны, но не редактируются вводом с клавиатуры в общем потоке. `defaultItem: true` ставят на одном элементе формы — точке, с которой пользователь начнёт работу.
## Перетаскивание
| Ключ | Значения | Назначение |
|------|----------|-----------|
| `enableStartDrag` | `true` | Разрешить начинать перетаскивание из элемента (источник drag-n-drop) |
Для таблиц приём/перемещение строк управляется ключами таблицы (`enableDrag`, `changeRowOrder`) — см. основную инструкцию; `enableStartDrag` — общий низкоуровневый флаг «этот элемент может быть источником перетаскивания».
## Закрепление колонки в таблице (`fixingInTable`)
Свойство поля-колонки внутри таблицы: закрепить колонку у края, чтобы она не уходила при горизонтальной прокрутке.
| Значения |
|----------|
| `None` (по умолчанию — не закреплена) / `Left` / `Right` |
```json
{ "table": "Товары", "path": "Объект.Товары", "columns": [
{ "input": "Номенклатура", "path": "Объект.Товары.Номенклатура", "fixingInTable": "Left" },
{ "input": "Количество", "path": "Объект.Товары.Количество" },
{ "input": "Сумма", "path": "Объект.Товары.Сумма", "fixingInTable": "Right" } ] }
```
Закрепляют ключевые колонки (идентифицирующую слева, итоговую справа), чтобы они оставались видны при прокрутке широкой таблицы.
## Ячейки колонок: шапка и подвал
Для поля-колонки внутри таблицы (и `columnGroup`) — размещение в шапке/подвале и выравнивание текста ячеек. Применять только к элементам внутри `columns` таблицы.
| Ключ | Значения | Назначение |
|------|----------|-----------|
| `showInHeader` | `true` / `false` | Показывать колонку в шапке таблицы |
| `showInFooter` | `true` / `false` | Показывать колонку в подвале (нужно для итогов; подвал самой таблицы включается `footer: true`) |
| `headerHorizontalAlign` | `Left` / `Right` / `Center` / `Auto` | Выравнивание текста в шапке колонки |
| `footerHorizontalAlign` | `Left` / `Right` / `Center` | Выравнивание текста в подвале колонки |
| `autoCellHeight` | `true` / `false` | Авто-высота ячейки (перенос содержимого на несколько строк) |
```json
{ "table": "Товары", "path": "Объект.Товары", "footer": true, "columns": [
{ "input": "Номенклатура", "path": "Объект.Товары.Номенклатура", "autoCellHeight": true },
{ "input": "Сумма", "path": "Объект.Товары.Сумма",
"headerHorizontalAlign": "Right", "showInFooter": true, "footerHorizontalAlign": "Right" } ] }
```
## Адаптивная важность (`displayImportance`)
| Значения |
|----------|
| `VeryHigh` / `High` / `Usual` / `VeryLow` / `Low` |
Приоритет элемента при адаптивной перекомпоновке формы на узких/мобильных экранах: элементы с меньшей важностью сворачиваются/прячутся первыми. Применимо к любому элементу.
```json
{ "input": "Комментарий", "path": "Объект.Комментарий", "displayImportance": "Low" }
```
@@ -1,79 +0,0 @@
# Форма отчёта
Форма, подключённая к объекту-отчёту (`Report`). Кроме обычных свойств формы у неё есть несколько свойств в `properties`, связывающих форму с механизмом компоновки (СКД): куда выводится результат, где данные расшифровки, какого она типа. Все они задаются в блоке `properties` верхнего уровня.
```json
"properties": {
"reportFormType": "Main",
"reportResult": "РезультатОтчета",
"detailsData": "ДанныеРасшифровки"
}
```
Ни одно из этих свойств не обязательно — указывайте только те, что нужны конкретной форме.
## Тип формы отчёта (`reportFormType`)
Роль формы в составе отчёта:
| Значение | Назначение |
|----------|-----------|
| `Main` | Основная форма отчёта (результат + настройки) |
| `Settings` | Форма настроек |
| `Variant` | Форма варианта |
```json
"reportFormType": "Main"
```
## Привязка к компоновке
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `reportResult` | string | Имя реквизита-результата формы (табличный документ, куда выводится отчёт) |
| `detailsData` | string | Имя реквизита данных расшифровки |
| `variantAppearance` | string | Имя реквизита оформления варианта |
Значение каждого ключа — имя реквизита формы (а не путь к данным). Реквизит с таким именем должен присутствовать в `attributes` формы.
## Группа пользовательских настроек (`customSettingsFolder`)
Группа-элемент формы, в которую генерируются пользовательские настройки компоновщика. Задаётся **по имени** элемента-группы:
```json
"customSettingsFolder": "ГруппаПользовательскихНастроек"
```
## Прочие свойства компоновки
Редкие, задавайте только при явной необходимости:
| Ключ | Значения | Назначение |
|------|----------|-----------|
| `autoShowState` | `Auto`, `DontShow`, `ShowOnComposition` | Автопоказ состояния формирования |
| `reportResultViewMode` | `Auto` | Режим просмотра результата |
| `viewModeApplicationOnSetReportResult` | `Auto` | Применение режима просмотра при установке результата |
## Реалистичный пример
Основная форма отчёта со СКД: реквизит-результат, данные расшифровки и группа пользовательских настроек.
```json
{
"properties": {
"reportFormType": "Main",
"reportResult": "РезультатОтчета",
"detailsData": "ДанныеРасшифровки",
"customSettingsFolder": "ГруппаПользовательскихНастроек"
},
"attributes": [
{ "name": "РезультатОтчета", "type": "SpreadsheetDocument" },
{ "name": "ДанныеРасшифровки", "type": "DataCompositionDetailsData" }
],
"elements": [
{ "group": "vertical", "name": "ГруппаПользовательскихНастроек" },
{ "spreadsheet": "РезультатОтчета", "path": "РезультатОтчета",
"titleLocation": "none" }
]
}
```
@@ -1,73 +0,0 @@
# Доступ по ролям
Единый механизм платформы для разграничения по ролям: задаётся общее значение для всех ролей плюс исключения для конкретных ролей. Один и тот же формат значения у четырёх ключей — каждый на своём владельце:
| Ключ | Владелец | Смысл |
|------|----------|-------|
| `userVisible` | элемент формы | пользовательская видимость элемента |
| `view` | реквизит формы | право просмотра |
| `edit` | реквизит формы | право редактирования |
| `use` | команда формы | доступность команды |
Ключ необязателен: его отсутствие = полный доступ для всех ролей.
## Значение
Две формы (одинаковы для всех четырёх ключей):
**Скаляр** `true` / `false` — общее значение для всех ролей, без исключений:
```json
{ "input": "Поле", "userVisible": false }
```
**Объект** `{ "common": <bool>, "roles": { "ИмяРоли": <bool>, … } }` — общее значение `common` плюс явные исключения по ролям:
```json
{ "name": "Реквизит",
"edit": { "common": false, "roles": { "ПолныеПрава": true } } }
```
Роль, **не указанная** в `roles`, наследует `common`. Указанная — задаёт явный `true`/`false` (может и совпадать с `common`).
## Имя роли
Ключи в `roles` — имена ролей конфигурации (`ПолныеПрава`, `Бухгалтер`, …).
## Примеры
Элемент скрыт у всех пользователей:
```json
{ "input": "Комментарий", "userVisible": false }
```
Реквизит не виден никому и редактируется только одной ролью:
```json
{ "name": "СуммаБонуса",
"view": false,
"edit": { "common": false, "roles": { "ПолныеПрава": true } } }
```
Поле доступно для просмотра всем, но редактируемо только администратору:
```json
{ "name": "Статус",
"view": true,
"edit": { "common": false, "roles": { "Администратор": true } } }
```
Команда недоступна по умолчанию, разрешена только бухгалтеру:
```json
{ "name": "ПровестиЗакрытие",
"use": { "common": false, "roles": { "Бухгалтер": true } } }
```
Обратный случай — доступно всем, кроме одной роли:
```json
{ "name": "РедактироватьЦену",
"edit": { "common": true, "roles": { "Кладовщик": false } } }
```
@@ -1,109 +0,0 @@
# Спец-поля «документ/датчик»
Поля для отображения специальных данных: табличный документ, HTML, текст, форматированный документ, индикатор, ползунок. Каждое привязывается к реквизиту своего платформенного типа.
Структурно это обычные поля — поддерживают общий скелет поля (`path`, `title`, `titleLocation`, флаги `readOnly`/`enabled`/`visible`, `layout`, оформление, события). Ниже — только ключ `type` (имя элемента задаётся значением ключа) и собственные скаляры каждого семейства. Все скаляры необязательны.
| Ключ типа | Тип реквизита |
|-----------|---------------|
| `spreadsheet` | `mxl:SpreadsheetDocument` (ТабличныйДокумент) |
| `html` | `string` |
| `textDoc` | `d5p1:TextDocument` (ТекстовыйДокумент) |
| `formattedDoc` | `fd:FormattedDocument` (ФорматированныйДокумент) |
| `progressBar` | число |
| `trackBar` | число |
## spreadsheet — поле табличного документа
Просмотр/редактирование табличного документа (отчёт, печатная форма).
```json
{ "spreadsheet": "ТаблицаОтчета", "path": "ТаблицаОтчета",
"titleLocation": "none", "readOnly": true,
"output": "Disable", "protection": true }
```
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `output` | string | Использование вывода: `Enable` / `Disable` |
| `protection` | bool | Защита от изменений |
| `edit` | bool | Разрешить редактирование |
| `showGrid` | bool | Показывать сетку |
| `showHeaders` | bool | Показывать заголовки строк/колонок |
| `showGroups` | bool | Показывать группировки |
| `showRowAndColumnNames` | bool | Показывать имена строк и колонок |
| `showCellNames` | bool | Показывать имена ячеек |
| `verticalScrollBar` / `horizontalScrollBar` | string | Режим полос прокрутки |
| `viewScalingMode` | string | Режим масштабирования просмотра |
| `selectionShowMode` | string | Режим отображения выделения |
| `pointerType` | string | Тип указателя |
| `enableDrag` / `enableStartDrag` | bool | Разрешить перетаскивание / начало перетаскивания |
## html — поле HTML-документа
Просмотр HTML. Реквизит — строка (содержит HTML-текст или адрес).
```json
{ "html": "Просмотр", "path": "СодержимоеHTML", "titleLocation": "none",
"output": "Enable", "warningOnEditRepresentation": false }
```
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `output` | string | Использование вывода: `Enable` / `Disable` |
| `warningOnEditRepresentation` | bool | Предупреждать при изменении представления |
## textDoc — поле текстового документа
Просмотр/редактирование текстового документа.
```json
{ "textDoc": "Текст", "path": "ТекстДокумента", "editMode": "Edit" }
```
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `editMode` | string | Режим редактирования (напр. `Edit` / `View`) |
## formattedDoc — поле форматированного документа
Просмотр/редактирование форматированного документа.
```json
{ "formattedDoc": "Описание", "path": "ФорматированноеОписание", "editMode": "Edit" }
```
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `editMode` | string | Режим редактирования (напр. `Edit` / `View`) |
## progressBar — поле индикатора
Индикатор прогресса. Реквизит — числовой.
```json
{ "progressBar": "Прогресс", "path": "Прогресс",
"minValue": 0, "maxValue": 100, "showPercent": true }
```
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `minValue` / `maxValue` | число | Минимальное / максимальное значение |
| `showPercent` | bool | Показывать проценты |
## trackBar — поле ползунка
Регулятор-ползунок. Реквизит — числовой.
```json
{ "trackBar": "Масштаб", "path": "Масштаб",
"minValue": 20, "maxValue": 400, "markingStep": 20 }
```
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `minValue` / `maxValue` | число | Минимальное / максимальное значение |
| `step` | число | Шаг изменения |
| `largeStep` | число | Крупный шаг |
| `markingStep` | число | Шаг разметки |
| `markingAppearance` | string | Оформление разметки |
@@ -1,132 +0,0 @@
# Таблица — продвинутые возможности
Базовый элемент таблицы (`type: "table"`, колонки, основные свойства) описан в основной инструкции, раздел «Таблица (table)». Здесь — продвинутые возможности: дополнения командной панели, специфика таблицы динамического списка и неочевидные свойства/режимы.
## Представление (`representation`)
Как таблица рисует строки:
```json
{ "table": "Список", "path": "Список", "representation": "Tree" }
```
`List` — плоский список (по умолчанию), `Tree` — дерево, `HierarchicalList` — иерархический список (группы + элементы на одном уровне).
Для дерева/иерархии управляйте раскрытием уровней через `initialTreeView` (`ExpandTopLevel` / `ExpandAllLevels` / `NoExpand`).
## Выделение и текущая строка
| Ключ | Значения | Назначение |
|------|----------|-----------|
| `selectionMode` | `SingleRow` / `MultiRow` | Режим выделения строк |
| `multipleChoice` | bool | Разрешить множественный выбор (для форм выбора) |
| `currentRowUse` | `DontUse` / `Use` / `SelectionPresentation` / `SelectionPresentationAndChoice` / `Choice` | Использование текущей строки таблицы |
```json
{ "table": "Список", "path": "Список", "selectionMode": "MultiRow", "multipleChoice": true }
```
## Поиск при вводе (`searchOnInput`)
Поведение встроенного поиска при наборе текста в таблице:
```json
{ "table": "Список", "path": "Список", "searchOnInput": "Use" }
```
`Auto` (по умолчанию) / `Use` (искать) / `DontUse` (не искать).
Где располагать сами элементы поиска — управляется `searchStringLocation` / `viewStatusLocation` / `searchControlLocation` (`None` / `Top` / `Bottom` / `CommandBar` / `Auto`).
## Прочие свойства таблицы
| Ключ | Тип | Назначение |
|------|-----|-----------|
| `useAlternationRowColor` | bool | Чередование цвета строк |
| `verticalLines` / `horizontalLines` | bool | Линии сетки (укажите `false`, чтобы скрыть) |
| `markIncomplete` | bool | Автоотметка незаполненных ячеек |
| `heightInTableRows` | int | Высота элемента в строках (отдельно от `height`) |
| `autoInsertNewRow` | bool | Автодобавление новой строки при вводе в последнюю |
| `rowsPicture` | string \| object | Картинка строк. Ссылка (`"CommonPicture.X"`, `"abs:..."`) либо объект `{ src, loadTransparent?, transparentPixel? }` |
| `tooltipRepresentation` | string | Режим показа подсказки таблицы: `None`, `Button`, `ShowBottom`, `ShowTop`, `ShowLeft`, `ShowRight`, `ShowAuto`, `Balloon` |
## Фиксация колонки (`fixingInTable`)
Свойство **колонки** (на `input` / `labelField` / `check` / `picField` внутри `columns`), а не самой таблицы. Закрепляет колонку у края при горизонтальной прокрутке:
```json
{ "table": "Товары", "path": "Объект.Товары", "columns": [
{ "input": "Номенклатура", "path": "Объект.Товары.Номенклатура", "fixingInTable": "Left" },
{ "input": "Количество", "path": "Объект.Товары.Количество" }
]}
```
`Left` / `Right` / `None`.
## Исключённые команды (`excludedCommands`)
Убрать стандартные команды редактора таблицы (кнопки добавления/перемещения/сортировки):
```json
{ "table": "Товары", "path": "Объект.Товары",
"excludedCommands": [ "Add", "Delete", "MoveUp", "SortListAsc" ] }
```
Свойство работает на любом поле и на уровне формы; для таблицы значимы команды вида `Add` / `Delete` / `MoveUp` / `MoveDown` / `SortListAsc` / `SortListDesc`.
## Дополнения командной панели (`additions`)
Дополнения — это «представления» встроенного поиска таблицы:
- `searchString` — отображение строки поиска,
- `viewStatus` — состояние просмотра,
- `searchControl` — управление поиском.
Каждое дополнение — полноценный элемент (полный набор свойств поля). Размещать их можно двумя способами.
**(1) Стандартные дополнения** генерирует платформа на уровне таблицы. В DSL указывайте **только отклонения** от стандартного вида — через карту `additions` (ключ = тип дополнения):
```json
{ "table": "Список", "path": "Список",
"additions": { "viewStatus": { "horizontalLocation": "left" } } }
```
**(2) Кастомное дополнение**, размещённое прямо в командной панели — обычный элемент в `commandBar` с ключом-типом:
```json
{ "table": "Список", "path": "Список", "commandBar": [
{ "searchString": "ПоискСписка", "source": "Список", "width": 15, "horizontalStretch": true }
]}
```
- Тип-ключ: `searchString` / `viewStatus` / `searchControl`.
- `source` — имя таблицы-источника; необязательно, по умолчанию = имя родительской таблицы.
- `horizontalLocation`: `auto` (по умолчанию) / `left` / `right`. Применимо и к обычным элементам командных панелей.
- Прочие свойства как у поля: `title`, `visible`, `userVisible`, `enabled`, `tooltip`, оформление, `width` / `maxWidth` / `autoMaxWidth` / `horizontalStretch` / `groupHorizontalAlign` и др.
## Таблица динамического списка
Когда `path` таблицы указывает на реквизит `type: "DynamicList"` (см. `references/dynamic-list.md`), доступен блок специфичных свойств. Указывайте **только отличия** от умолчания.
| Ключ | Тип | Умолчание | Назначение |
|------|-----|-----------|-----------|
| `rowPictureDataPath` | string | картинка осн. таблицы | Путь к картинке строки. `""` — подавить картинку |
| `rowsPicture` | string | — | Картинка строк (`"CommonPicture.X"`) |
| `autoRefresh` | bool | `false` | Автообновление списка |
| `autoRefreshPeriod` | int | `60` | Период автообновления, сек |
| `updateOnDataChange` | string | `Auto` | Обновлять при изменении данных: `Auto` / `DontUpdate` |
| `choiceFoldersAndItems` | string | `Items` | Что выбирать: `Items` / `Folders` / `FoldersAndItems` |
| `restoreCurrentRow` | bool | `false` | Восстанавливать текущую строку при обновлении |
| `showRoot` | bool | `true` | Показывать корень |
| `allowRootChoice` | bool | `false` | Разрешить выбор корня |
| `allowGettingCurrentRowURL` | bool | `true` | Разрешить получение URL текущей строки |
| `userSettingsGroup` | string | — | Группа пользовательских настроек (привязка к одноимённой группе настроек) |
```json
{ "table": "Список", "path": "Список",
"representation": "Tree",
"rowPictureDataPath": "Список.DefaultPicture",
"choiceFoldersAndItems": "FoldersAndItems",
"allowRootChoice": true,
"updateOnDataChange": "DontUpdate" }
```
@@ -1,77 +0,0 @@
# Продвинутые конструкции типов
Примитивы (`string(n)`, `number(p,s)`, `boolean`, `date`/`dateTime`, …) и одиночные ссылки (`CatalogRef.Контрагенты`, `DocumentRef.Заказ`, `EnumRef.X`, …) описаны в основной инструкции. Здесь — типы, которые нельзя выразить одним именем: составные типы, наборы типов и платформенные наборы ссылок.
Любая из этих конструкций пишется в поле `type` реквизита, реквизита-параметра или поля.
## Составные типы
Несколько типов на одном реквизите — части перечисляются через разделитель `" | "` (можно `+`). Реквизит сможет принимать значение любого из перечисленных типов:
```json
{ "name": "Плательщик",
"type": "CatalogRef.Организации | CatalogRef.ИндивидуальныеПредприниматели" }
```
Смешивать можно типы из разных категорий — ссылки, примитивы, наборы типов:
```json
{ "name": "Источник",
"type": "CatalogRef.Контрагенты | DocumentRef.Заказ | string(150)" }
```
Каждая часть — самостоятельный токен из этого файла или из основной инструкции. Порядок частей произвольный.
## Наборы типов (TypeSet)
«Набор типов» подставляется вместо конкретного типа — это один токен, а не перечисление. Применимо и в составном типе как одна из частей.
| Токен `type` | Смысл |
|------|-------|
| `"DefinedType.ИмяТипа"` | определяемый тип конфигурации |
| `"Characteristic.ИмяПлана"` | тип значения характеристики (по плану видов характеристик) |
| `"AnyRef"` | любая ссылка |
| `"AnyIBRef"` | любая ссылка информационной базы |
Определяемый тип — реквизит принимает то, что задано в определяемом типе конфигурации (например `DefinedType.ДенежнаяСумма`):
```json
{ "name": "Сумма", "type": "DefinedType.ДенежнаяСумма" }
```
Характеристика — тип значения берётся из плана видов характеристик:
```json
{ "name": "Значение", "type": "Characteristic.ДополнительныеРеквизиты" }
```
## Платформенные наборы ссылок
«Голый» ссылочный токен **без `.Имя`** означает «любая ссылка этой категории объектов»:
| Токен `type` | Смысл |
|------|-------|
| `"CatalogRef"` | любая ссылка справочника |
| `"DocumentRef"` | любая ссылка документа |
| `"EnumRef"` | любая ссылка перечисления |
| `"ExchangePlanRef"` | любая ссылка плана обмена |
| `"TaskRef"` | любая ссылка задачи |
| `"BusinessProcessRef"` | любая ссылка бизнес-процесса |
| `"ChartOfCharacteristicTypesRef"` | любая ссылка плана видов характеристик |
| `"ChartOfAccountsRef"` | любая ссылка плана счетов |
| `"ChartOfCalculationTypesRef"` | любая ссылка плана видов расчёта |
Различие с одиночной ссылкой — только в наличии `.Имя`:
- `"CatalogRef.Валюты"` — конкретный справочник «Валюты»;
- `"CatalogRef"` — любой справочник.
```json
{ "name": "ЛюбойСправочник", "type": "CatalogRef" }
```
Эти наборы тоже комбинируются в составном типе:
```json
{ "name": "Объект", "type": "CatalogRef | DocumentRef" }
```
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-48
View File
@@ -1,48 +0,0 @@
---
name: form-decompile
description: Декомпиляция управляемой формы 1С (Form.xml) в JSON-черновик в формате form-compile. Используй для scaffold новой формы по образцу или структурного рефакторинга. Не для точечных правок
argument-hint: <FormPath> [-OutputPath <out.json>]
disable-model-invocation: true
allowed-tools:
- Bash
- Read
- Write
- Glob
---
# /form-decompile — JSON-черновик из Form.xml управляемой формы
Читает Form.xml и эмитит компактный JSON в формате `form-compile`. **Результат — черновик**, а не обратимое представление: см. раздел «Что получаешь».
## Когда использовать
- **Scaffold новой формы по образцу** — взять существующую форму, получить JSON, поправить и скомпилировать в новую.
- **Структурный рефакторинг** — перебрать дерево элементов, реквизиты, команды.
## Когда **не** использовать
- **Точечные правки готовой формы** (добавить элемент, реквизит, команду) → `/form-edit`. Цикл «декомпиляция → правка JSON → компиляция» переписывает форму целиком, может терять непокрытые конструкции и даёт большой diff. `/form-edit` правит адресно.
## Параметры
| Параметр | Описание |
|----------|----------|
| `FormPath` | Путь к Form.xml (обязательный) |
| `OutputPath` | Путь к выходному JSON. Если не задан — JSON в stdout |
```powershell
powershell.exe -NoProfile -File ".augment/skills/form-decompile/scripts/form-decompile.ps1" -FormPath "<Form.xml>" -OutputPath "<out.json>"
```
## Что получаешь
JSON-черновик в формате `/form-compile`**не полное обратимое представление**: раундтрип `xml → json → xml` не гарантируется, часть конструкций DSL не покрывает и **теряет молча**.
Критичные конструкции (`ConditionalAppearance` со scope, design-time диаграммы/планировщики на реквизите, неизвестный тип элемента, не-Form root) → скрипт падает с ненулевым кодом и сообщением в stderr; для правок такой формы — `/form-edit`.
## Workflow
1. `/form-decompile <Form.xml> -OutputPath draft.json` — получить черновик.
2. Поправить JSON под задачу.
3. `/form-compile -JsonPath draft.json -OutputPath new/Form.xml` — собрать обратно.
4. `/form-validate` + `/form-info` — проверить результат.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-29
View File
@@ -1,29 +0,0 @@
---
name: form-validate
description: Валидация управляемой формы 1С. Используй после создания или модификации формы для проверки корректности. При наличии BaseForm автоматически проверяет callType и ID расширений
argument-hint: <FormPath> [-Detailed] [-MaxErrors 30]
allowed-tools:
- Bash
- Read
- Glob
---
# /form-validate — валидация управляемой формы 1С
Проверяет Form.xml на структурные ошибки: уникальность ID, наличие companion-элементов, корректность ссылок DataPath и команд.
## Параметры
| Параметр | Обяз. | Умолч. | Описание |
|-----------|:-----:|---------|-----------------------------------------|
| FormPath | да | — | Путь к файлу Form.xml |
| Detailed | нет | — | Подробный вывод (все проверки, включая успешные) |
| MaxErrors | нет | 30 | Остановиться после N ошибок |
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/form-validate/scripts/form-validate.ps1" -FormPath "Catalogs/Номенклатура/Forms/ФормаЭлемента"
powershell.exe -NoProfile -File ".augment/skills/form-validate/scripts/form-validate.ps1" -FormPath "src/МояОбработка/Forms/Форма/Ext/Form.xml"
```
@@ -1,259 +0,0 @@
# help-add v1.7 — Add built-in help to 1C object
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
param(
[Parameter(Mandatory)]
[string]$ObjectName,
[string]$Lang = "ru",
[string]$SrcDir = "src"
)
$ErrorActionPreference = "Stop"
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
# --- Support guard (Ext/ParentConfigurations.bin) ---
# See docs/1c-support-state-spec.md. Blocks edits of vendor objects "на замке" /
# read-only configs unless allowed. Trigger = bin present; reaction from
# .v8-project.json editingAllowedCheck (deny|warn|off, default deny). Never
# throws — guard errors degrade to allow.
function Get-RootUuid([string]$xmlPath) {
if (-not (Test-Path $xmlPath)) { return $null }
try {
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
$el = $mx.DocumentElement.FirstChild
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
} catch {}
return $null
}
function Find-V8Project([string]$startDir) {
$d = $startDir
for ($i = 0; $i -lt 20 -and $d; $i++) {
$pj = Join-Path $d ".v8-project.json"
if (Test-Path $pj) { return $pj }
$parent = [System.IO.Path]::GetDirectoryName($d)
if ($parent -eq $d) { break }
$d = $parent
}
return $null
}
function Get-EditMode([string]$cfgDir) {
try {
$pj = Find-V8Project (Get-Location).Path
if (-not $pj) { $pj = Find-V8Project $cfgDir }
if (-not $pj) { return 'deny' }
$proj = Get-Content -Raw $pj | ConvertFrom-Json
$cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
if ($proj.databases) {
foreach ($db in $proj.databases) {
if ($db.configSrc) {
$src = [System.IO.Path]::GetFullPath($db.configSrc).TrimEnd('\', '/')
if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar)) {
if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
}
}
}
}
if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
return 'deny'
} catch { return 'deny' }
}
function Assert-EditAllowed([string]$targetPath, [string]$require) {
try {
$rp = $targetPath
try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).Path } catch {}
$elemUuid = Get-RootUuid $rp
$cfgDir = $null; $binPath = $null
$d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
for ($i = 0; $i -lt 12 -and $d; $i++) {
if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
if (-not $cfgDir) {
$cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
}
if ($elemUuid -and $cfgDir) { break }
$parent = [System.IO.Path]::GetDirectoryName($d)
if ($parent -eq $d) { break }
$d = $parent
}
# New object (no element file): fall back to config root uuid.
if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
if (-not $binPath -or -not (Test-Path $binPath)) { return }
$bytes = [System.IO.File]::ReadAllBytes($binPath)
if ($bytes.Length -le 32) { return }
$start = 0
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
$text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
$hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
if (-not $hm.Success) { return }
$G = [int]$hm.Groups[1].Value
$K = [int]$hm.Groups[2].Value
if ($K -eq 0) { return }
$best = $null
if ($elemUuid) {
$u = [regex]::Escape($elemUuid.ToLower())
foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
$f1 = [int]$m.Groups[1].Value
if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
}
}
$blocked = $false; $code = ""; $reason = ""
if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
elseif ($require -eq 'removed') {
if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
}
else {
if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
}
if (-not $blocked) { return }
$mode = Get-EditMode $cfgDir
if ($mode -eq 'off') { return }
# Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
# latter throws and would be swallowed by this function's own catch.
if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
$head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
$cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
$offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
if ($code -eq "capability-off") {
$state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
$fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
} elseif ($code -eq "not-removed") {
$state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
$fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
} else {
$state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
$fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
}
[Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
exit 1
} catch { return }
}
# --- Detect format version ---
function Detect-FormatVersion([string]$dir) {
$d = $dir
while ($d) {
$cfgPath = Join-Path $d "Configuration.xml"
if (Test-Path $cfgPath) {
$content = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8)
$head = $content.Substring(0, [Math]::Min(2000, $content.Length))
if ($head -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
}
$parent = Split-Path $d -Parent
if ($parent -eq $d) { break }
$d = $parent
}
return "2.17"
}
$formatVersion = Detect-FormatVersion (Resolve-Path $SrcDir).Path
# --- Проверки ---
$objectDir = Join-Path $SrcDir $ObjectName
$extDir = Join-Path $objectDir "Ext"
if (-not (Test-Path $extDir)) {
Write-Error "Каталог объекта не найден: $extDir. Проверьте путь ObjectName (например Catalogs/МойСправочник)."
exit 1
}
$helpXmlPath = Join-Path $extDir "Help.xml"
if (Test-Path $helpXmlPath) {
Write-Error "Справка уже существует: $helpXmlPath"
exit 1
}
Assert-EditAllowed $objectDir 'editable'
# --- Кодировка ---
$encBom = New-Object System.Text.UTF8Encoding($true)
# --- 1. Help.xml ---
$helpXml = @"
<?xml version="1.0" encoding="UTF-8"?>
<Help xmlns="http://v8.1c.ru/8.3/xcf/extrnprops" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="$formatVersion">
<Page>$Lang</Page>
</Help>
"@
[System.IO.File]::WriteAllText($helpXmlPath, $helpXml, $encBom)
# --- 2. Help/<lang>.html ---
$helpDir = Join-Path $extDir "Help"
New-Item -ItemType Directory -Path $helpDir -Force | Out-Null
$helpHtmlPath = Join-Path $helpDir "$Lang.html"
$helpHtml = @"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" type="text/css" href="v8help://service_book/service_style"/>
</head>
<body>
<h1>$ObjectName</h1>
<p>Описание.</p>
</body>
</html>
"@
[System.IO.File]::WriteAllText($helpHtmlPath, $helpHtml, $encBom)
# --- 3. Проверка IncludeHelpInContents в метаданных форм ---
$formsDir = Join-Path $objectDir "Forms"
if (Test-Path $formsDir) {
$formMetaFiles = Get-ChildItem -Path $formsDir -Filter "*.xml" -File
foreach ($formMeta in $formMetaFiles) {
$xmlDoc = New-Object System.Xml.XmlDocument
$xmlDoc.PreserveWhitespace = $true
$xmlDoc.Load($formMeta.FullName)
$nsMgr = New-Object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
$nsMgr.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
$includeHelp = $xmlDoc.SelectSingleNode("//md:IncludeHelpInContents", $nsMgr)
if (-not $includeHelp) {
# Добавить после <FormType>
$formType = $xmlDoc.SelectSingleNode("//md:FormType", $nsMgr)
if ($formType) {
$newElem = $xmlDoc.CreateElement("IncludeHelpInContents", "http://v8.1c.ru/8.3/MDClasses")
$newElem.InnerText = "false"
$parent = $formType.ParentNode
$nextSibling = $formType.NextSibling
# Вставить перенос + табуляцию + элемент
$ws = $xmlDoc.CreateWhitespace("`n`t`t`t")
if ($nextSibling) {
$parent.InsertBefore($ws, $nextSibling) | Out-Null
$parent.InsertBefore($newElem, $ws) | Out-Null
} else {
$parent.AppendChild($ws) | Out-Null
$parent.AppendChild($newElem) | Out-Null
}
$settings = New-Object System.Xml.XmlWriterSettings
$settings.Encoding = $encBom
$settings.Indent = $false
$stream = New-Object System.IO.FileStream($formMeta.FullName, [System.IO.FileMode]::Create)
$writer = [System.Xml.XmlWriter]::Create($stream, $settings)
$xmlDoc.Save($writer)
$writer.Close()
$stream.Close()
Write-Host " IncludeHelpInContents добавлен: $($formMeta.Name)"
}
}
}
}
Write-Host "[OK] Создана справка: $ObjectName"
Write-Host " Метаданные: $helpXmlPath"
Write-Host " Страница: $helpHtmlPath"
@@ -1,328 +0,0 @@
#!/usr/bin/env python3
# add-help v1.7 — Add built-in help to 1C object
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import json
import os
import re
import sys
from lxml import etree
NSMAP = {"md": "http://v8.1c.ru/8.3/MDClasses"}
# ============================================================
# Support guard (Ext/ParentConfigurations.bin) — see docs/1c-support-state-spec.md
# Blocks edits of vendor objects "на замке" / read-only configs. Trigger = bin
# present; reaction from .v8-project.json editingAllowedCheck (deny|warn|off,
# default deny). Never throws (except sys.exit on deny) — errors degrade to allow.
# ============================================================
def _sg_root_uuid(xml_path):
if not os.path.isfile(xml_path):
return None
try:
mx = etree.parse(xml_path).getroot()
for child in mx:
if isinstance(child.tag, str) and child.get("uuid"):
return child.get("uuid")
except Exception:
return None
return None
def _sg_find_v8project(start_dir):
d = start_dir
for _ in range(20):
if not d:
break
pj = os.path.join(d, ".v8-project.json")
if os.path.isfile(pj):
return pj
parent = os.path.dirname(d)
if parent == d:
break
d = parent
return None
def _sg_get_edit_mode(cfg_dir):
try:
pj = _sg_find_v8project(os.getcwd()) or _sg_find_v8project(cfg_dir)
if not pj:
return "deny"
proj = json.loads(open(pj, encoding="utf-8-sig").read())
cfg_full = os.path.normcase(os.path.abspath(cfg_dir)).rstrip("\\/")
for db in proj.get("databases", []):
src = db.get("configSrc")
if src:
src_full = os.path.normcase(os.path.abspath(src)).rstrip("\\/")
if cfg_full == src_full or cfg_full.startswith(src_full + os.sep):
if db.get("editingAllowedCheck"):
return db["editingAllowedCheck"]
if proj.get("editingAllowedCheck"):
return proj["editingAllowedCheck"]
return "deny"
except Exception:
return "deny"
def assert_edit_allowed(target_path, require):
try:
rp = os.path.abspath(target_path)
elem_uuid = _sg_root_uuid(rp)
cfg_dir = None
bin_path = None
d = rp if os.path.isdir(rp) else os.path.dirname(rp)
for _ in range(12):
if not d:
break
if not elem_uuid:
elem_uuid = _sg_root_uuid(d + ".xml")
if not cfg_dir:
cand = os.path.join(d, "Ext", "ParentConfigurations.bin")
if os.path.exists(cand) or os.path.exists(os.path.join(d, "Configuration.xml")):
cfg_dir = d
bin_path = cand
if elem_uuid and cfg_dir:
break
parent = os.path.dirname(d)
if parent == d:
break
d = parent
if not elem_uuid and cfg_dir:
elem_uuid = _sg_root_uuid(os.path.join(cfg_dir, "Configuration.xml"))
if not bin_path or not os.path.exists(bin_path):
return
data = open(bin_path, "rb").read()
if len(data) <= 32:
return
if data[:3] == b"\xef\xbb\xbf":
data = data[3:]
text = data.decode("utf-8", "replace")
h = re.match(r"\{6,(\d+),(\d+),", text)
if not h:
return
g = int(h.group(1))
k = int(h.group(2))
if k == 0:
return
best = None
if elem_uuid:
for m in re.finditer(r"([0-2]),0," + re.escape(elem_uuid.lower()), text):
f1 = int(m.group(1))
if best is None or f1 < best:
best = f1
blocked = False
code = ""
reason = ""
if g == 1:
blocked = True
code = "capability-off"
reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)"
elif require == "removed":
if best is not None and best != 2:
blocked = True
code = "not-removed"
reason = "объект не снят с поддержки — удаление сломает обновления"
else:
if best is not None and best == 0:
blocked = True
code = "locked"
reason = "объект на замке — редактирование сломает обновления"
if not blocked:
return
mode = _sg_get_edit_mode(cfg_dir)
if mode == "off":
return
if mode == "warn":
sys.stderr.write(f"[support-guard] ПРЕДУПРЕЖДЕНИЕ: {reason}. Цель: {rp}\n")
return
head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
off_note = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
if code == "capability-off":
state = f"Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «{rp}» редактировать нельзя."
fix = (
"Либо снять защиту явно (навык support-edit, два шага):\n"
f' 1. support-edit -Path "{cfg_dir}" -Capability on — включить возможность изменения (объекты пока остаются на замке);\n'
f' 2. support-edit -Path "{rp}" -Set editable — открыть этот объект для редактирования.\n'
" Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
)
elif code == "not-removed":
state = f"Состояние: объект «{rp}» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
fix = (
"Либо сначала снять объект с поддержки, затем удалять:\n"
f' support-edit -Path "{rp}" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно.'
)
else:
state = f"Состояние: объект «{rp}» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
fix = (
"Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):\n"
f' support-edit -Path "{rp}" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);\n'
f' support-edit -Path "{rp}" -Set off-support — снять с поддержки: обновления по объекту больше не приходят.'
)
sys.stderr.write(head + "\n" + state + "\n" + cfe + "\n" + fix + "\n" + off_note + "\n")
sys.exit(1)
except SystemExit:
raise
except Exception:
return
def detect_format_version(d):
while d:
cfg_path = os.path.join(d, "Configuration.xml")
if os.path.isfile(cfg_path):
with open(cfg_path, "r", encoding="utf-8-sig") as f:
head = f.read(2000)
m = re.search(r'<MetaDataObject[^>]+version="(\d+\.\d+)"', head)
if m:
return m.group(1)
parent = os.path.dirname(d)
if parent == d:
break
d = parent
return "2.17"
def save_xml_with_bom(tree, path):
"""Save XML tree to file with UTF-8 BOM."""
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
xml_bytes = xml_bytes.replace(b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" encoding="utf-8"?>')
if not xml_bytes.endswith(b"\n"):
xml_bytes += b"\n"
with open(path, "wb") as f:
f.write(b"\xef\xbb\xbf")
f.write(xml_bytes)
def write_text_with_bom(path, text):
"""Write text to file with UTF-8 BOM."""
with open(path, "w", encoding="utf-8-sig") as f:
f.write(text)
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(description="Add built-in help to 1C object", allow_abbrev=False)
parser.add_argument("-ObjectName", required=True)
parser.add_argument("-Lang", default="ru")
parser.add_argument("-SrcDir", default="src")
args = parser.parse_args()
object_name = args.ObjectName
lang = args.Lang
src_dir = args.SrcDir
format_version = detect_format_version(os.path.abspath(src_dir))
# --- Checks ---
object_dir = os.path.join(src_dir, object_name)
ext_dir = os.path.join(object_dir, "Ext")
if not os.path.isdir(ext_dir):
print(f"Каталог объекта не найден: {ext_dir}. Проверьте путь ObjectName (например Catalogs/МойСправочник).", file=sys.stderr)
sys.exit(1)
help_xml_path = os.path.join(ext_dir, "Help.xml")
if os.path.exists(help_xml_path):
print(f"Справка уже существует: {help_xml_path}", file=sys.stderr)
sys.exit(1)
assert_edit_allowed(object_dir, "editable")
# --- 1. Help.xml ---
help_xml = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<Help xmlns="http://v8.1c.ru/8.3/xcf/extrnprops"'
' xmlns:xs="http://www.w3.org/2001/XMLSchema"'
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
f' version="{format_version}">\n'
f'\t<Page>{lang}</Page>\n'
'</Help>'
)
write_text_with_bom(help_xml_path, help_xml)
# --- 2. Help/<lang>.html ---
help_dir = os.path.join(ext_dir, "Help")
os.makedirs(help_dir, exist_ok=True)
help_html_path = os.path.join(help_dir, f"{lang}.html")
help_html = (
'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\n'
'<html>\n'
'<head>\n'
' <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>\n'
' <link rel="stylesheet" type="text/css" href="v8help://service_book/service_style"/>\n'
'</head>\n'
'<body>\n'
f' <h1>{object_name}</h1>\n'
' <p>Описание.</p>\n'
'</body>\n'
'</html>'
)
write_text_with_bom(help_html_path, help_html)
# --- 3. Check IncludeHelpInContents in form metadata ---
forms_dir = os.path.join(object_dir, "Forms")
if os.path.isdir(forms_dir):
for entry in os.listdir(forms_dir):
if not entry.endswith(".xml"):
continue
form_meta_full = os.path.join(forms_dir, entry)
if not os.path.isfile(form_meta_full):
continue
parser_xml = etree.XMLParser(remove_blank_text=False)
form_tree = etree.parse(form_meta_full, parser_xml)
form_root = form_tree.getroot()
include_help = form_root.find(".//md:IncludeHelpInContents", NSMAP)
if include_help is not None:
continue
# Add after <FormType>
form_type = form_root.find(".//md:FormType", NSMAP)
if form_type is None:
continue
parent = form_type.getparent()
ns = "http://v8.1c.ru/8.3/MDClasses"
new_elem = etree.SubElement(parent, f"{{{ns}}}IncludeHelpInContents")
new_elem.text = "false"
# Remove SubElement's auto-placement (it appends to end) and insert after FormType
parent.remove(new_elem)
# Find index of FormType in parent
form_type_idx = list(parent).index(form_type)
# Insert after FormType
parent.insert(form_type_idx + 1, new_elem)
# Whitespace handling: copy FormType's tail as new_elem's tail,
# and set FormType's tail to include newline + indent
new_elem.tail = form_type.tail
form_type.tail = "\n\t\t\t"
save_xml_with_bom(form_tree, form_meta_full)
print(f" IncludeHelpInContents добавлен: {entry}")
print(f"[OK] Создана справка: {object_name}")
print(f" Метаданные: {help_xml_path}")
print(f" Страница: {help_html_path}")
if __name__ == "__main__":
main()
@@ -1,29 +0,0 @@
---
name: interface-validate
description: Валидация командного интерфейса 1С. Используй после настройки командного интерфейса подсистемы для проверки корректности
argument-hint: <CIPath> [-Detailed] [-MaxErrors 30]
allowed-tools:
- Bash
- Read
- Glob
---
# /interface-validate — валидация CommandInterface.xml
Проверяет XML командного интерфейса на структурные ошибки: корневой элемент, допустимые секции, порядок, формат ссылок на команды, дубликаты.
## Параметры
| Параметр | Обяз. | Умолч. | Описание |
|-----------|:-----:|---------|-----------------------------------------|
| CIPath | да | — | Путь к CommandInterface.xml |
| Detailed | нет | — | Подробный вывод (все проверки, включая успешные) |
| MaxErrors | нет | 30 | Остановиться после N ошибок |
| OutFile | нет | — | Записать результат в файл (UTF-8 BOM) |
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/interface-validate/scripts/interface-validate.ps1" -CIPath "Subsystems/Продажи"
powershell.exe -NoProfile -File ".augment/skills/interface-validate/scripts/interface-validate.ps1" -CIPath "Subsystems/Продажи/Ext/CommandInterface.xml"
```
-60
View File
@@ -1,60 +0,0 @@
---
name: meta-remove
description: Удалить объект метаданных из конфигурации 1С. Используй когда нужно удалить, убрать объект из конфигурации
argument-hint: <ConfigDir> -Object <Type.Name>
allowed-tools:
- Bash
- Read
- Glob
- AskUserQuestion
---
# /meta-remove — удаление объекта метаданных
Безопасно удаляет объект из XML-выгрузки конфигурации. Перед удалением проверяет ссылки на объект в реквизитах, коде и других метаданных. Если ссылки найдены — удаление блокируется.
## Использование
```
/meta-remove <ConfigDir> -Object <Type.Name>
```
## Параметры
| Параметр | Обязательный | Описание |
|------------|:------------:|-------------------------------------------------|
| ConfigDir | да | Корневая директория выгрузки (где Configuration.xml) |
| Object | да | Тип и имя объекта: `Catalog.Товары`, `Document.Заказ` и т.д. |
| DryRun | нет | Только показать что будет удалено, без изменений |
| KeepFiles | нет | Не удалять файлы, только дерегистрировать |
| Force | нет | Удалить несмотря на найденные ссылки |
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/meta-remove/scripts/meta-remove.ps1" -ConfigDir "<путь>" -Object "Catalog.Товары"
```
## Поддерживаемые типы
Catalog, Document, Enum, Constant, InformationRegister, AccumulationRegister, AccountingRegister, CalculationRegister, ChartOfAccounts, ChartOfCharacteristicTypes, ChartOfCalculationTypes, BusinessProcess, Task, ExchangePlan, DocumentJournal, Report, DataProcessor, CommonModule, ScheduledJob, EventSubscription, HTTPService, WebService, DefinedType, Role, Subsystem, CommonForm, CommonTemplate, CommonPicture, CommonAttribute, SessionParameter, FunctionalOption, FunctionalOptionsParameter, Sequence, FilterCriterion, SettingsStorage, XDTOPackage, WSReference, StyleItem, Language
## Примеры
```powershell
# Проверка ссылок + dry run
... -ConfigDir C:\WS\tasks\cfsrc\acc_8.3.24 -Object "Catalog.Устаревший" -DryRun
# Удалить объект без ссылок
... -ConfigDir C:\WS\tasks\cfsrc\acc_8.3.24 -Object "Catalog.Устаревший"
# Принудительно удалить несмотря на ссылки
... -ConfigDir C:\WS\tasks\cfsrc\acc_8.3.24 -Object "Catalog.Устаревший" -Force
# Только дерегистрировать (файлы оставить)
... -ConfigDir C:\WS\tasks\cfsrc\acc_8.3.24 -Object "Report.Старый" -KeepFiles
# Удалить общий модуль
... -ConfigDir src -Object "CommonModule.МойМодуль"
```
-29
View File
@@ -1,29 +0,0 @@
---
name: meta-validate
description: Валидация объекта метаданных 1С. Используй после создания или модификации объекта конфигурации для проверки корректности
argument-hint: <ObjectPath> [-Detailed] [-MaxErrors 30] — pipe-separated paths for batch
allowed-tools:
- Bash
- Read
- Glob
---
# /meta-validate — валидация объекта метаданных 1С
Проверяет XML объекта метаданных из выгрузки конфигурации на структурные ошибки.
## Параметры
| Параметр | Обяз. | Умолч. | Описание |
|------------|:-----:|---------|-------------------------------------------------|
| ObjectPath | да | — | Путь к XML-файлу или каталогу. Через `\|` для batch |
| Detailed | нет | — | Подробный вывод (все проверки, включая успешные) |
| MaxErrors | нет | 30 | Остановиться после N ошибок (per object) |
| OutFile | нет | — | Записать результат в файл (UTF-8 BOM) |
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/meta-validate/scripts/meta-validate.ps1" -ObjectPath "Catalogs/Номенклатура/Номенклатура.xml"
powershell.exe -NoProfile -File ".augment/skills/meta-validate/scripts/meta-validate.ps1" -ObjectPath "Catalogs/Банки|Documents/Заказ"
```
-29
View File
@@ -1,29 +0,0 @@
---
name: mxl-validate
description: Валидация макета табличного документа (MXL). Используй после создания или модификации макета для проверки корректности
argument-hint: <TemplatePath> [-Detailed] [-MaxErrors 20]
allowed-tools:
- Bash
- Read
- Glob
---
# /mxl-validate — валидация макета табличного документа (MXL)
Проверяет Template.xml на структурные ошибки: индексы, ссылки на палитры, диапазоны именованных областей и объединений.
## Параметры
| Параметр | Обяз. | Умолч. | Описание |
|---------------|:-----:|---------|--------------------------------------------|
| TemplatePath | да | — | Путь к макету (директория или Template.xml) |
| Detailed | нет | — | Подробный вывод (все проверки, включая успешные) |
| MaxErrors | нет | 20 | Остановиться после N ошибок |
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/mxl-validate/scripts/mxl-validate.ps1" -TemplatePath "Catalogs/Номенклатура/Templates/Макет"
powershell.exe -NoProfile -File ".augment/skills/mxl-validate/scripts/mxl-validate.ps1" -TemplatePath "src/МояОбработка/Templates/ПечатнаяФорма"
```
-27
View File
@@ -1,27 +0,0 @@
---
name: role-validate
description: Валидация роли 1С. Используй после создания или модификации роли для проверки корректности
argument-hint: <RightsPath> [-Detailed] [-MaxErrors 30]
allowed-tools:
- Bash
- Read
---
# /role-validate — валидация роли 1С
Проверяет корректность `Rights.xml` роли: формат XML, namespace, глобальные флаги, типы объектов, имена прав, RLS-ограничения, шаблоны. Опционально проверяет метаданные роли (UUID, имя, синоним).
## Параметры
| Параметр | Обяз. | Умолч. | Описание |
|--------------|:-----:|---------|-------------------------------------------------|
| RightsPath | да | — | Путь к роли (директория или `Rights.xml`) |
| Detailed | нет | — | Подробный вывод (все проверки, включая успешные) |
| MaxErrors | нет | 30 | Макс. ошибок до остановки (по умолчанию 30) |
| OutFile | нет | — | Записать результат в файл (UTF-8 BOM) |
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/role-validate/scripts/role-validate.ps1" -RightsPath "Roles/МояРоль"
```
-436
View File
@@ -1,436 +0,0 @@
---
name: skd-compile
description: Компиляция схемы компоновки данных 1С (СКД) из компактного JSON-определения. Используй когда нужно создать СКД с нуля
argument-hint: "[-DefinitionFile <json> | -Value <json-string>] -OutputPath <Template.xml>"
allowed-tools:
- Bash
- Read
- Write
- Glob
---
# /skd-compile — генерация СКД из JSON DSL
Принимает JSON-определение схемы компоновки данных → генерирует Template.xml (DataCompositionSchema).
## Параметры и команда
| Параметр | Описание |
|----------|----------|
| `DefinitionFile` | Путь к JSON-файлу с определением СКД (взаимоисключающий с Value) |
| `Value` | JSON-строка с определением СКД (взаимоисключающий с DefinitionFile) |
| `OutputPath` | Путь к выходному Template.xml |
```powershell
# Из файла
powershell.exe -NoProfile -File ".augment/skills/skd-compile/scripts/skd-compile.ps1" -DefinitionFile "<json>" -OutputPath "<Template.xml>"
# Из строки (без промежуточного файла)
powershell.exe -NoProfile -File ".augment/skills/skd-compile/scripts/skd-compile.ps1" -Value '<json-string>' -OutputPath "<Template.xml>"
```
## JSON DSL — краткий справочник
Справочник ниже. Все примеры компилируемы как есть.
### Корневая структура
```json
{
"dataSets": [...],
"calculatedFields": [...],
"totalFields": [...],
"parameters": [...],
"templates": [...],
"groupTemplates": [...],
"dataSetLinks": [...],
"settingsVariants": [...]
}
```
Умолчания: `dataSources` → авто `ИсточникДанных1/Local`; `settingsVariants` → авто "Основной" с деталями.
### Наборы данных
Тип по ключу: `query` → DataSetQuery, `objectName` → DataSetObject, `items` → DataSetUnion.
```json
{ "name": "Продажи", "query": "ВЫБРАТЬ ...", "fields": [...] }
```
Запрос поддерживает `@file` — ссылку на внешний .sql файл вместо inline-текста: `"query": "@queries/sales.sql"`. Путь разрешается относительно JSON-файла, затем CWD.
**DataSetObject** — внешний набор данных (без источника-запроса). Поля описываются явно; данные передаются вторым параметром `ПроцессорКомпоновкиДанных.Инициализировать(Макет, Новый Структура("<objectName>", ТЗ), ...)`.
```json
{ "name": "ЖурналОшибок", "objectName": "ЖурналОшибок", "fields": [
{ "field": "ТекстСообщения", "title": "Текст сообщения", "type": "string(150)" },
{ "field": "Расшифровка", "title": "Описание", "type": "CatalogRef.СтруктураПредприятия" }
]}
```
`name` — имя набора в схеме, `objectName` — ключ в структуре передачи данных.
### Поля — shorthand и объектная форма
```
"Наименование" — просто имя
"Количество: decimal(15,2)" — имя + тип
"Организация: CatalogRef.Организации @dimension" — + роль
"Служебное: string #noFilter #noOrder" — + ограничения
```
Объектная форма — когда нужен title или другие свойства:
```json
{ "field": "ОстатокНаНачалоПериода", "title": "Остаток на начало периода" }
```
`dataPath` автоматически берётся из `field`, если не указан явно.
Многоязычный заголовок: `"title": { "ru": "...", "en": "..." }`. Применимо везде, где принимается title/presentation (поля, calculatedFields, parameters, settingsVariants, availableValues и пр.). Строка эквивалентна `{ "ru": "..." }`.
Типы: `string`, `string(N)`, `decimal`, `decimal(D)`, `decimal(D,F)`, `boolean`, `date`, `dateTime`, `CatalogRef.X`, `DocumentRef.X`, `EnumRef.X`, `StandardPeriod`. Ссылочные типы эмитируются с inline namespace `d5p1:` (`http://v8.1c.ru/8.1/data/enterprise/current-config`). Сборка EPF со ссылочными типами требует базу с соответствующей конфигурацией.
`decimal` без скобок = `10,2` (деньги по умолчанию), `decimal(N)` = `N,0` (целое); `,nonneg` в конце скобок → AllowedSign=Nonnegative.
Составной тип (несколько типов значений) — массив в объектной форме: `"type": ["CatalogRef.A", "CatalogRef.B"]`. Квалификаторы (`(N)`, `(D,F)`) применяются к каждому элементу.
Роли (shorthand или объект):
- `@`-флаги: `@dimension`, `@account`, `@balance`, `@period`, `@required`, `@autoOrder`, `@ignoreNullValues`
- KV: `balanceGroupName`, `balanceType` (`OpeningBalance`/`ClosingBalance`), `parentDimension`, `accountTypeExpression`, `expression`, `orderType` (`Asc`/`Desc`), `periodNumber`, `periodType`
```
"Сумма: decimal(15,2) @balance balanceGroupName=Сумма balanceType=OpeningBalance"
```
Ограничения: `#noField`, `#noFilter`, `#noGroup`, `#noOrder`.
В объектной форме: `"useRestriction": { "field": true, "condition": true, "group": true, "order": true }` или `"restrict": ["noField", "noFilter"]`.
Дополнительные ключи объектной формы:
- `"presentationExpression": "<выражение>"` — что показывать вместо значения поля. Исходное значение остаётся «под капотом» для перехода/расшифровки.
- `"appearance": { "<параметр>": "<значение>" }` — оформление колонки по умолчанию (применяется во всех вариантах настроек). Ключи — параметры платформы (`ГоризонтальноеПоложение`, `МинимальнаяШирина`, `Формат`, `Текст` и т.п.).
- `"orderExpression": { "expression": "<выражение>", "orderType": "Asc"/"Desc", "autoOrder": true/false }` — сортировка поля по выражению (например `ЕстьNULL(Поле.Порядок, 10000)`).
```json
{ "field": "Сумма", "title": "Сумма продажи", "type": "decimal(15,2)",
"appearance": { "ГоризонтальноеПоложение": "Right", "МинимальнаяШирина": "80" } }
```
### Вычисляемые поля (calculatedFields)
Shorthand: `"Имя [Заголовок]: тип = Выражение #noField #noFilter #noGroup #noOrder"` — все части кроме имени опциональны.
```json
"calculatedFields": [
"Маржа = Цена - Закупка",
"Наценка [Наценка, %]: decimal(10,2) = Маржа / Закупка * 100",
"Служебное: string = \"\" #noField #noFilter #noGroup #noOrder"
]
```
Объектная форма — когда нужна `appearance`:
```json
{ "name": "Маржа", "title": "Маржа", "expression": "Цена - Закупка", "type": "decimal(15,2)", "useRestriction": "#noField #noFilter" }
```
### Итоги (shorthand)
```json
"totalFields": ["Количество: Сумма", "Стоимость: Сумма(Кол * Цена)"]
```
### Параметры (shorthand + @autoDates)
```json
"parameters": [
"Период [Отчетный период]: StandardPeriod = LastMonth @autoDates"
]
```
Shorthand: `"Имя [Заголовок]: тип = значение @флаги"`. `[Заголовок]` опциональный — добавляет `<title>` (LocalStringType).
Флаги shorthand:
- `@autoDates` — добавляет к параметру StandardPeriod пару дат `НачалоПериода`/`КонецПериода`, вычисляемых из него. Используй их в тексте запроса как `&НачалоПериода`/`&КонецПериода`; пользователь выбирает только сам период. По умолчанию сам параметр получает `use=Always` и `denyIncompleteValues=true` (чтобы производные даты всегда были заполнены); в объектной форме можно явно переопределить.
- `@valueList``<valueListAllowed>true</valueListAllowed>` — разрешает передавать список значений (при значении-списке ниже подразумевается автоматически)
- `@hidden` — скрытый параметр: `availableAsField=false` + исключается из `"dataParameters": "auto"`
Объектная форма: `title`, `hidden: true`, `valueListAllowed: true`, `availableAsField: false`, `denyIncompleteValues: true`, `use: "Always"`.
Значение-список: несколько значений по умолчанию через запятую в `значение` (для запятой внутри значения — кавычки `'...'`). В объектной форме — массив в `value`.
```json
"parameters": [
"Виды: ChartOfCharacteristicTypesRef.ВидыСубконтоХозрасчетные = ПланВидовХарактеристик.ВидыСубконтоХозрасчетные.Контрагенты, ПланВидовХарактеристик.ВидыСубконтоХозрасчетные.Договоры"
]
```
Если значения по умолчанию нет — пропусти `=` в shorthand или укажи `"value": null` в объектной форме.
Список допустимых значений (availableValues):
```json
{
"name": "ПорядокОкругления",
"type": "EnumRef.Округления",
"value": "Перечисление.Округления.Окр1_00",
"use": "Always",
"denyIncompleteValues": true,
"availableValues": [
{"value": "Перечисление.Округления.Окр1_00", "presentation": "руб. коп"},
{"value": "Перечисление.Округления.Окр1", "presentation": "руб."},
{"value": "Перечисление.Округления.Окр1000", "presentation": "тыс. руб"}
]
}
```
В варианте настроек `"dataParameters": "auto"` выводит все не-hidden параметры с `userSettingID`. Значения по умолчанию наследуются и остаются активными; параметры без значения по умолчанию отключаются (пользователь включит их в настройках).
### Фильтры — shorthand
```json
"filter": [
"Организация = _ @off @user",
"Дата >= 2024-01-01T00:00:00",
"Статус filled"
]
```
Формат: `"Поле оператор значение @флаги"`. Значение `_` = пустое (placeholder). Флаги: `@off` (use=false), `@user` (userSettingID=auto), `@quickAccess`, `@normal`, `@inaccessible`.
В объектной форме доступны: `viewMode`, `userSettingID`, `userSettingPresentation`.
Группы фильтров (Or/And/Not):
```json
{ "group": "Or", "items": [
{ "group": "And", "items": [
{ "field": "Статус", "op": "=", "value": "Активен" },
{ "field": "Сумма", "op": ">", "value": 1000 }
]},
{ "field": "Количество", "op": "filled" }
]}
```
### Параметры данных — shorthand
```json
"dataParameters": [
"Период = LastMonth @user",
"Организация @off @user"
]
```
Формат: `"Имя [= значение] @флаги"`. Для StandardPeriod варианты (LastMonth, ThisYear и т.д.) распознаются автоматически.
### Структура — string shorthand
```json
"structure": "Организация > details"
"structure": "Организация > Номенклатура > details"
```
`>` разделяет уровни группировки. `details` (или `детали`) = детальные записи. `selection` и `order` по умолчанию `["Auto"]` на каждом уровне.
Объектная форма — для сложных случаев (именованные группировки, selection/filter на уровне группировки, таблицы, диаграммы):
```json
"structure": [
{
"name": "ПоОрганизациям",
"groupFields": ["Организация"],
"selection": ["Организация", "Сумма", "Auto"],
"children": [{ "groupFields": [] }]
}
]
```
`type` по умолчанию `"group"` (можно не указывать). `groupFields` — алиас для `groupBy`. Поддержка `name`, `selection`, `order`, `filter`, `outputParameters`, рекурсивных `children`.
### Варианты настроек
```json
"settingsVariants": [{
"name": "Основной",
"title": "Продажи по организациям",
"settings": {
"selection": ["Номенклатура", "Количество", "Auto"],
"filter": ["Организация = _ @off @user"],
"order": ["Количество desc", "Auto"],
"conditionalAppearance": [
{
"filter": ["Просрочено = true"],
"appearance": { "ЦветТекста": "style:ПросроченныеДанныеЦвет" },
"presentation": "Выделять просроченные",
"viewMode": "Normal",
"userSettingID": "auto"
}
],
"outputParameters": { "Заголовок": "Мой отчёт" },
"dataParameters": ["Период = LastMonth @user"],
"structure": "Организация > details"
}
}]
```
### Условное оформление (conditionalAppearance)
```json
"conditionalAppearance": [
{
"selection": ["Поле1"],
"filter": ["Поле1 notFilled"],
"appearance": { "Текст": "Не указано", "ЦветТекста": "style:XXX" },
"presentation": "Описание",
"viewMode": "Normal",
"userSettingID": "auto"
}
]
```
Типы значений appearance: `style:XXX`/`web:XXX`/`win:XXX` → Color, `true`/`false` → Boolean, параметр `Формат`/`Текст`/`Заголовок` → LocalStringType, прочее → String.
Типы значений фильтра: `Перечисление.*`/`Справочник.*`/`ПланСчетов.*`/`Документ.*` → DesignTimeValue (автодетект).
OrGroup в фильтре: `{"group": "Or", "items": ["условие1", "условие2"]}`.
Folder в selection: `{"folder": "Поступление", "items": ["ПолеА", "ПолеБ"]}` → SelectedItemFolder с lwsTitle и placement=Auto.
### Итоги с привязкой к группировкам
```json
"totalFields": [
{ "dataPath": "Кол", "expression": "Сумма(Кол)", "group": ["Группа1", "Группа1 Иерархия", "ОбщийИтог"] }
]
```
### Шаблоны вывода — компактный DSL
Вместо raw XML (`template`) — табличное описание через `rows` + именованный стиль `style`:
```json
"templates": [
{
"name": "Макет1",
"style": "header",
"widths": [36, 33, 16, 17],
"minHeight": 24.75,
"rows": [
["Виды кассы", "Валюта", "Остаток на начало\nпериода", "Остаток на\nконец периода"],
["|", "|", "|", "|"],
["К1", "К2", "К3", "К4"]
]
},
{
"name": "Макет2",
"style": "data",
"widths": [36, 33, 16, 17],
"rows": [["{ВидКассы}", "{Валюта}", "{Остаток}", "{ОстатокКонец}"]],
"parameters": [
{ "name": "ВидКассы", "expression": "Представление(Счет)" },
{ "name": "Остаток", "expression": "ОстатокНаНачалоПериода" }
]
}
]
```
Синтаксис ячеек: `"текст"` — статика, `"{Имя}"` — параметр, `"|"` — объединение с ячейкой выше, `">"` — объединение с ячейкой слева, `null` — пустая.
Двухуровневая шапка с горизонтальным объединением:
```json
"rows": [
["Вид актива", "Остаток начало", "Поступление", ">", ">", ">", "Выбытие", ">", ">", "Остаток конец"],
["|", "|", "из произв.", "из п/ф", "со сч.40", "прочее", "Реализ.", "отгруж.", "прочее", "|"],
["К1", "К2", "К3", "К4", "К5", "К6", "К7", "К8", "К9", "К10"]
]
```
Встроенные стили: `header` (фон, центр, перенос), `data` (фон группы), `subheader` (без фона, центр), `total` (без фона). Все — Arial 10, рамки Solid 1px, цвета через стили платформы.
Пользовательские стили: файл `skd-styles.json` рядом с JSON-определением, в текущей директории, или в `presets/skills/skd/skd-styles.json` (поиск вверх от OutputPath). Первый найденный файл побеждает. Все допустимые ключи и формат цветов — в `examples/skd-styles.json`.
Raw XML (`"template": "<...>"`) остаётся как fallback. Детект: если есть `rows` — DSL, иначе — raw.
### Расшифровка (drilldown) в параметрах шаблона
Ключ `drilldown` в параметре шаблона автоматически генерирует `DetailsAreaTemplateParameter` и привязку `Расшифровка` в appearance ячеек:
```json
"parameters": [
{ "name": "Сырье", "expression": "ПоступлениеСырья", "drilldown": "ПоступлениеСырья" }
]
```
Генерирует: `ExpressionAreaTemplateParameter` (обычный) + `DetailsAreaTemplateParameter` с именем `Расшифровка_ПоступлениеСырья`, `fieldExpression` по полю `ИмяРесурса`, `mainAction=DrillDown`. Ячейки `{Сырье}` автоматически получают appearance `Расшифровка = Расшифровка_ПоступлениеСырья`.
### Привязки макетов к группировкам
```json
"groupTemplates": [
{ "groupName": "ДанныеОтчета", "templateType": "GroupHeader", "template": "Макет1" },
{ "groupField": "Счет", "templateType": "Header", "template": "Макет2" },
{ "groupField": "Счет", "templateType": "OverallHeader", "template": "Макет3" }
]
```
`groupField` — привязка к полю группировки, `groupName` — к именованной группировке в структуре варианта.
`templateType`: `Header` (строки данных) → `<groupTemplate>`, `OverallHeader` (итоги) → `<groupTemplate>`, `GroupHeader` (шапка) → `<groupHeaderTemplate>`.
## Примеры
### Минимальный
```json
{
"dataSets": [{
"query": "ВЫБРАТЬ Номенклатура.Наименование КАК Наименование ИЗ Справочник.Номенклатура КАК Номенклатура",
"fields": ["Наименование"]
}]
}
```
### С запросом из внешнего файла (@file)
```json
{
"dataSets": [{
"query": "@queries/sales.sql",
"fields": ["Номенклатура: СправочникСсылка.Номенклатура @dimension", "Количество: число(15,3)", "Сумма: число(15,2)"]
}]
}
```
### С ресурсами, параметрами и @autoDates
```json
{
"dataSets": [{
"query": "ВЫБРАТЬ Продажи.Организация, Продажи.Номенклатура, Продажи.КоличествоОборот КАК Количество, Продажи.СуммаОборот КАК Сумма ИЗ РегистрНакопления.Продажи.Обороты(&НачалоПериода, &КонецПериода) КАК Продажи",
"fields": [
"Организация: СправочникСсылка.Организации @dimension",
"Номенклатура: СправочникСсылка.Номенклатура @dimension",
"Количество: число(15,3)",
"Сумма: число(15,2)"
]
}],
"totalFields": ["Количество: Сумма", "Сумма: Сумма"],
"parameters": ["Период: СтандартныйПериод = LastMonth @autoDates"],
"settingsVariants": [{
"name": "Основной",
"settings": {
"selection": ["Организация", "Номенклатура", "Количество", "Сумма"],
"filter": ["Организация = _ @off @user"],
"dataParameters": "auto",
"structure": "Организация > details"
}
}]
}
```
## Верификация
```
/skd-validate <OutputPath> — валидация структуры XML
/skd-info <OutputPath> — визуальная сводка
/skd-info <OutputPath> -Mode variant -Name 1 — проверка варианта настроек
```
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-52
View File
@@ -1,52 +0,0 @@
---
name: skd-decompile
description: Декомпиляция схемы компоновки данных 1С (СКД) в JSON-черновик в формате skd-compile. Используй для scaffold нового отчёта по образцу или структурного рефакторинга. Не для точечных правок
argument-hint: <TemplatePath> [-OutputPath <out.json>]
disable-model-invocation: true
allowed-tools:
- Bash
- Read
- Write
- Glob
---
# /skd-decompile — JSON-черновик из Template.xml СКД
Читает Template.xml и эмитит JSON в формате `skd-compile`. **Результат — черновик**, а не обратимое представление: см. раздел «Что получаешь».
## Когда использовать
- **Scaffold нового отчёта по образцу** — взять существующий СКД, получить JSON, поправить и скомпилировать в новый.
- **Структурный рефакторинг** — переписать вариант, перерисовать шаблон, перебрать набор полей.
## Когда **не** использовать
- **Точечные правки готового отчёта** (добавить поле, фильтр, итог, переименовать) → `/skd-edit`. Цикл «декомпиляция → правка JSON → компиляция» переписывает шаблон целиком, может терять непокрытые конструкции и даёт большой diff в исходниках. `/skd-edit` правит адресно, без полной реконструкции.
## Параметры
| Параметр | Описание |
|----------|----------|
| `TemplatePath` | Путь к Template.xml (обязательный) |
| `OutputPath` | Путь к выходному JSON. Если не задан — JSON в stdout |
```powershell
powershell.exe -NoProfile -File ".augment/skills/skd-decompile/scripts/skd-decompile.ps1" -TemplatePath "<Template.xml>" -OutputPath "<out.json>"
```
## Что получаешь
JSON-черновик в формате `/skd-compile`**не полное обратимое представление СКД**. На вход компилятору такой JSON напрямую может не пойти: в нём встречаются sentinel-узлы (маркер `__unsupported__`).
- **Готовые узлы** — большая часть СКД (поля, параметры, шаблоны, варианты со structure/filter/order/conditionalAppearance и т.п.) ложится в JSON как обычные узлы DSL.
- **Sentinel-узлы** — места, где встретилась конструкция, которую декомпилятор не умеет выразить в DSL. JSON остаётся валидным, но компилятор откажется его собирать, пока sentinel не **заменён ручной реализацией** (явный raw `template`, прописанный appearance и т.п.) **или не удалён**, если в новом отчёте конструкция не нужна. Это намеренный барьер — чтобы непокрытое не уехало в финальный отчёт незамеченным.
- **`<basename>.warnings.md`** рядом с `OutputPath` — список всех sentinel-узлов с координатами в исходнике, по нему удобно обходить места под ручную доработку.
- **Критичные конструкции** (Picture cells, ХранилищеЗначения, вложенные схемы, не-СКД root) — скрипт падает с ненулевым кодом и сообщением в stderr; такой Template как образец не годится.
## Workflow
1. `/skd-decompile <Template.xml> -OutputPath draft.json` — получить черновик.
2. Открыть `draft.warnings.md`, посмотреть, что не покрылось.
3. Поправить JSON под задачу. Sentinel-узлы — заменить на ручную реализацию (через явный raw `template`, через ручное описание appearance и т.п.) либо удалить, если конструкция в новом отчёте не нужна.
4. `/skd-compile -DefinitionFile draft.json -OutputPath new-Template.xml` — собрать обратно.
5. `/skd-validate` + `/skd-info` — проверить.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-373
View File
@@ -1,373 +0,0 @@
---
name: skd-edit
description: Точечное редактирование схемы компоновки данных 1С (СКД). Используй когда нужно модифицировать существующую СКД — добавить поля, итоги, фильтры, параметры, изменить текст запроса
argument-hint: <TemplatePath> -Operation <op> -Value <value>
allowed-tools:
- Bash
- Read
- Write
- Glob
---
# /skd-edit — точечное редактирование СКД (Template.xml)
Атомарные операции модификации существующей схемы компоновки данных: добавление, удаление и модификация полей, итогов, фильтров, параметров, настроек варианта, управление структурой, замена запроса.
## Параметры и команда
| Параметр | Описание |
|----------|----------|
| `TemplatePath` | Путь к Template.xml (или к папке — автодополнение Ext/Template.xml) |
| `Operation` | Операция (см. список ниже) |
| `Value` | Значение операции (shorthand-строка или текст запроса) |
| `DataSet` | (опц.) Имя набора данных (умолч. первый) |
| `Variant` | (опц.) Имя варианта настроек (умолч. первый) |
| `NoSelection` | (опц.) Не добавлять поле в selection варианта |
```powershell
powershell.exe -NoProfile -File ".augment/skills/skd-edit/scripts/skd-edit.ps1" -TemplatePath "<path>" -Operation <op> -Value "<value>"
```
## Пакетный режим (batch)
Несколько значений в одном вызове через разделитель `;;`:
```powershell
-Operation add-field -Value "Цена: decimal(15,2) ;; Количество: decimal(15,3) ;; Сумма: decimal(15,2)"
```
Работает для всех операций кроме `set-query`, `set-structure` и `add-dataSet`.
## Операции
### add-field — добавить поле в набор данных
Shorthand: `"Имя [Заголовок]: тип @роль #ограничение"`.
```
"Цена: decimal(15,2)"
"Организация [Орг-ция]: CatalogRef.Организации @dimension"
"Служебное: string #noFilter #noOrder"
```
Поле добавляется в набор и в selection варианта (если нет `-NoSelection`). Дубликат dataPath — предупреждение, пропуск.
Чтобы поле попало в selection не варианта, а конкретной группировки структуры — используй `-NoSelection` и затем `add-selection "Имя @group=ИмяГруппы"`.
### add-total — добавить итог
Shorthand: `"<dataPath>: <выражение>"`. Если выражение — известная аггрегатная функция без скобок (`Сумма`, `Количество`, `Минимум`, `Максимум`, `Среднее`), оно автоматически оборачивается в `Func(dataPath)`. Если функция со скобками или произвольное выражение — используется как есть.
```
"Цена: Среднее" # → Среднее(Цена)
"Стоимость: Сумма(Кол * Цена)" # → как есть
"Проверка: Проверка" # identity: выражение = Проверка
```
### add-calculated-field — добавить вычисляемое поле
Shorthand: `"Имя [Заголовок]: тип = Выражение #noFilter #noOrder #noGroup"`.
```
"Маржа = Продажа - Закупка"
"Наценка [Наценка, %]: decimal(10,2) = Маржа / Закупка * 100"
"Служебное: string = \"\" #noFilter #noOrder #noGroup"
```
`#noFilter`, `#noOrder`, `#noGroup`, `#noField``<useRestriction>` (аналогично add-field).
Также добавляется в selection варианта.
### add-parameter — добавить параметр
```
"Период [Отчетный период]: StandardPeriod = LastMonth @autoDates"
"Организация: CatalogRef.Организации"
```
Shorthand: `"Имя [Заголовок]: тип = значение [availableValue=список] [@флаги]"`. `[Заголовок]` опциональный — добавляет `<title>`.
Флаги:
- `@autoDates` — генерирует пару скрытых параметров `ДатаНачала`/`ДатаОкончания` для StandardPeriod-параметра.
- `@hidden` — скрывает параметр от пользовательских настроек (для параметров-констант, используемых в запросе).
- `@always` — параметр всегда подставляется в запрос. Часто вместе с `@hidden`, но используется и отдельно (для видимых обязательных параметров типа отчётного периода).
- `@valueList` — разрешает передавать в параметр список значений (при значении-списке ниже подразумевается автоматически, отдельно указывать не обязательно).
Значение-список: несколько значений по умолчанию задаются через запятую в `значение`. Для запятой внутри одного значения — кавычки `'...'`.
```
"Виды [Виды субконто]: ChartOfCharacteristicTypesRef.ВидыСубконтоХозрасчетные = ПланВидовХарактеристик.ВидыСубконтоХозрасчетные.Контрагенты, ПланВидовХарактеристик.ВидыСубконтоХозрасчетные.Договоры"
```
```
"ПС: CatalogRef.Контрагенты = Справочник.Контрагенты.ПустаяСсылка @hidden"
"Период: StandardPeriod = LastMonth @always"
"ПСчет: ChartOfAccountsRef.Хозрасчетный = ПланСчетов.Хозрасчетный.X @hidden @always"
"Округление: EnumRef.Округления = Окр1 availableValue=Перечисление.Округления.Окр1: руб., Перечисление.Округления.Окр1000: тыс."
```
`availableValue=` задаёт начальный список допустимых значений. Формат списка: `v1[: p1], v2[: p2], ...` — элементы через `,`, представление после `:`. Если в значении или представлении встречается `,` или `:` — оборачивай в одинарные кавычки `'...'`:
```
"Округление: ... = Окр1 availableValue=Окр1_00: 'руб., коп.', Окр1: руб."
```
### modify-parameter — изменить существующий параметр
Shorthand: `"ИмяПараметра [Заголовок] [ключ=значение]... [@флаги]"`. Находит параметр по имени, обновляет указанные свойства.
```
"ПорядокОкругления use=Always"
"ПорядокОкругления [Округление сумм] denyIncompleteValues=true"
"ПериодОтчета [Отчетный период]" # только title
"ПорядокОкругления availableValue=Перечисление.Округления.Окр1: руб., Перечисление.Округления.Окр1000: тыс."
"СчетПС value=ПланСчетов.Хозрасчетный.КассаПредприятия"
"Виды value=ПланВидовХарактеристик.ВидыСубконтоХозрасчетные.Контрагенты, ПланВидовХарактеристик.ВидыСубконтоХозрасчетные.Договоры"
"Контрагент @hidden @always"
```
`[Заголовок]` опциональный — устанавливает или заменяет `<title>`. Можно вызывать без других kv-пар, чтобы только обновить title.
`availableValue=` **заменяет весь список** допустимых значений (старые удаляются). Формат и кавычки — те же, что в `add-parameter`.
`value=` заменяет значение параметра. Несколько значений через запятую → **список значений** (заменяет все прежние); для запятой внутри значения — кавычки `'...'`.
Флаги `@hidden` / `@always` — те же, что и в `add-parameter`. Идемпотентны.
### rename-parameter — переименовать параметр
Shorthand: `"OldName => NewName"`. Атомарно обновляет имя параметра, ссылки `&Имя` в выражениях других параметров (только полные совпадения, `&ПериодX` не задевается), и записи в `dataParameters` всех вариантов. Текст запроса не трогает — переименование строго в области параметров.
```
"Период => ПериодОтчета"
```
### reorder-parameters — переставить параметры в указанном порядке
Shorthand: `"Имя1, Имя2, Имя3"`. Частичный список — указанные параметры идут первыми в заданном порядке, остальные сохраняют исходный порядок и идут в конце. Параметры из списка, которых нет в схеме — warning, пропуск.
```
"ПериодОтчета, НачалоПериода, КонецПериода"
```
### add-filter — добавить фильтр в вариант
Shorthand: `"Поле оператор значение @флаги"`. Флаги: `@off` (use=false), `@user` (userSettingID=auto), `@quickAccess`, `@normal`, `@inaccessible`.
```
"Номенклатура = _ @off @user"
"Дата >= 2024-01-01T00:00:00"
"Статус filled"
```
### add-dataParameter — добавить параметр данных в вариант
Shorthand: `"Имя [= значение] @флаги"`.
```
"Период = LastMonth @user"
"Организация @off @user"
```
### add-order — добавить сортировку
Shorthand: `"Поле [desc]"`. По умолчанию asc. `Auto` — авто-элемент.
```
"Количество desc"
"Auto"
```
### add-selection — добавить элемент выборки
```
"Номенклатура"
"Auto"
"Folder(Поступление: ПолеА, ПолеБ, ПолеВ)"
```
`Folder(Название: поле1, поле2)` — группа полей (SelectedItemFolder) с заголовком и `placement=Auto`.
`@group=ИмяГруппировки` — добавить в selection именованной группировки (вместо уровня варианта):
```
"Folder(Поступление: ПолеА, ПолеБ) @group=ДанныеОтчета"
```
### add-dataSetLink — добавить связь наборов данных
Shorthand: `"Источник > Приёмник on ВырИсточника = ВырПриёмника [param Имя]"`.
```
"Набор1 > Набор2 on Поле1 = Поле2"
"Набор1 > Набор2 on Поле1 = Поле2 [param Связь]"
```
### add-dataSet — добавить набор данных
Shorthand: `"Имя: ТЕКСТ_ЗАПРОСА"` или `"ТЕКСТ_ЗАПРОСА"` (авто-имя `НаборДанныхN`).
```
"Доп: ВЫБРАТЬ 1 КАК Тест"
"ВЫБРАТЬ Ссылка ИЗ Справочник.Номенклатура"
"Продажи: @queries/sales.sql"
```
`dataSource` берётся из первого существующего. Дубликат имени — предупреждение, пропуск. Не поддерживает пакетный режим (запрос может содержать `;;`).
### add-variant — добавить вариант настроек
Shorthand: `"Имя [Представление]"`. Представление опционально, по умолчанию = имя.
```
"Детальный"
"Детальный [Детальный отчёт]"
```
Создаёт вариант с Auto selection + detail group. Дубликат имени — предупреждение, пропуск.
### add-conditionalAppearance — добавить условное оформление
Shorthand: `"Параметр = значение [when условие] [for Поле1, Поле2]"`. Блок `when` — синтаксис `add-filter` (Поле оператор значение).
```
"ЦветТекста = web:Red when Сумма < 0"
"ЦветФона = web:LightGreen when Статус = Одобрен for Статус"
"МинимальнаяШирина = 50 for Организация"
"Формат = ЧДЦ=2 for Цена, Сумма"
```
Типы значений appearance (автодетект): `web:*`/`style:*`/`win:*` → Color, `true`/`false` → Boolean, параметр `Формат`/`Текст`/`Заголовок` → LocalStringType, иначе String.
Типы значений фильтра (автодетект): `Перечисление.*`/`Справочник.*`/`ПланСчетов.*`/`Документ.*` → DesignTimeValue, `true`/`false` → Boolean, дата → DateTime, числа → Decimal, иначе String.
OrGroup: несколько условий через ` or ` в `when` объединяются в FilterItemGroup/OrGroup:
```
"Формат = ЧЦ=15; ЧДЦ=0 when ПараметрыДанных.Округление = Перечисление.Округления.Окр1 or ПараметрыДанных.Округление = Перечисление.Округления.Окр1000"
```
**Важно**: для параметров данных используйте префикс `ПараметрыДанных.` в поле фильтра.
### add-drilldown — подключить расшифровку к ресурсам в шаблонах
Value — имена ресурсов (как в полях/вычисляемых полях СКД) через запятую.
```
"ПоступлениеИзПроизводства, ВыбытиеПрочее"
"Сумма_Дт83, Сумма_Дт99, Сумма_68, Сумма_84"
```
Подключает DrillDown по `ИмяРесурса` ко всем шаблонам, содержащим указанные ресурсы. Идемпотентно.
### set-query — заменить текст запроса
Не поддерживает пакетный режим. Value — полный текст запроса или `@path/to/file.sql` (ссылка на внешний файл). Путь разрешается относительно Template.xml, затем CWD.
Когда что: **существенная переработка** (добавить поля, соединения, переписать пакет) → выгрузи запрос через `/skd-info <tpl> -Mode query -Name <набор> -Raw -OutFile file.sql`, отредактируй файл, верни `set-query @file`. `-Raw` отдаёт запрос целиком без декораций, поэтому выгрузка ↔ возврат точны (включая многопакетные запросы). **Точечная замена** (переименовать идентификатор, заменить подстроку) → выгрузка не нужна, используй `patch-query` ниже.
### patch-query — точечная замена в тексте запроса
Shorthand: `"старое => новое [@once]"`. По умолчанию заменяет все вхождения подстроки. Поддерживает пакетный режим и `-DataSet`.
```
"СубконтоДт1) В => СубконтоКт1) В"
"КАК ВТ_СтароеИмя => КАК ВТ_НовоеИмя @once"
```
`@once` — упасть с ошибкой, если в запросе не **ровно одно** вхождение. Защищает от случайных замен в комментариях и однотипных идентификаторах.
Многострочные подстроки поддерживаются.
### set-outputParameter — установить параметр вывода
```
"Заголовок = Мой отчёт"
"ВыводитьЗаголовок = true"
```
Если параметр уже существует — заменяет значение.
### set-structure — установить структуру варианта
Shorthand: `"Поле1 > Поле2 > details"`. `>` — вложенный уровень группировки, `,` — несколько полей в одном уровне, `details` — детальные записи. **Заменяет всю структуру полностью** (включая Selection/order/filter/conditionalAppearance каждой группы). Для точечной модификации полей группировки с сохранением настроек — используй `modify-structure`. Не поддерживает пакетный режим.
```
"Организация > Номенклатура > details"
"Валюта, НаименованиеБанка, ИНН"
"details"
"СчетМеждународногоУчета @name=ДанныеОтчета"
```
`@name=Имя` — присваивает имя группировке (`<dcsset:name>`). Используется для привязки шаблонов через `groupName`.
### modify-structure — изменить поля группировки существующей группы
Тот же shorthand что и `set-structure`. Находит группу по `@name=`, заменяет только `<groupItems>` (поля группировки). Selection/order/filter/conditionalAppearance/outputParameters группы сохраняются. Без `@name=` — ошибка.
```
"Валюта @name=ДанныеОтчета"
"Валюта, НаименованиеБанка @name=ДанныеОтчета"
"details @name=ДанныеОтчета"
```
### modify-field — изменить существующее поле
Тот же shorthand что и `add-field`. Находит по dataPath, объединяет свойства (непустые переопределяют), сохраняет позицию.
```
"Цена [Цена USD]: decimal(10,4) @dimension"
```
### set-field-role — установить роль поля
Shorthand: `"<dataPath> [@флаги] [kv=значение]"`. **Полностью заменяет** роль поля. Если в значении только dataPath без флагов/kv — удаляет роль.
```
"Сумма" # снять роль полностью
"СуммаОстаток @balance" # простая балансовая роль
"СуммаНач @balance balanceGroupName=Сумма balanceType=OpeningBalance" # с уточнением
"Контрагент @dimension parentDimension=Группа"
"Период @period" # роль периода
```
Флаги: `@balance`, `@dimension`, `@account`, `@period`, `@required`, `@autoOrder`, `@ignoreNullValues`.
KV: `balanceGroupName`, `balanceType` (OpeningBalance/ClosingBalance), `parentDimension`, `accountTypeExpression`, `orderType` (Asc/Desc), `expression`, `periodNumber`, `periodType`.
Поддерживает пакетный режим (`;;`).
### modify-filter — изменить существующий фильтр
Тот же shorthand что и `add-filter`. Находит по полю, обновляет оператор/значение/флаги. См. правило для `<use>` ниже.
### modify-dataParameter — изменить параметр данных
Тот же shorthand что и `add-dataParameter`. Находит по имени, обновляет значение/флаги. См. правило для `<use>` ниже.
#### Правило `<use>` для modify-filter / modify-dataParameter
В отличие от `add-*`, в `modify-*` поле `<use>` обновляется **только если флаг задан явно**:
- `@off` — установить `<use>false</use>`
- `@on` — убрать существующий `<use>false</use>` (включить параметр)
- ни `@off`, ни `@on` не задано — `<use>` не трогается, существующее значение сохраняется (важно: это значит, что отключённый параметр останется отключённым после модификации других свойств)
### remove-* и clear-*
| Операция | Value | Действие |
|----------|-------|----------|
| `remove-field` | dataPath | Удаляет поле из набора + из selection варианта |
| `remove-total` | dataPath | Удаляет итог |
| `remove-calculated-field` | dataPath | Удаляет вычисляемое поле + из selection |
| `remove-parameter` | name | Удаляет параметр |
| `remove-filter` | поле | Удаляет первый фильтр с указанным полем |
| `clear-selection` | `*` | Очищает все элементы selection |
| `clear-order` | `*` | Очищает все элементы order |
| `clear-filter` | `*` | Очищает все элементы filter |
| `clear-conditionalAppearance` | `*` | Очищает все правила условного оформления |
## Верификация
```
/skd-validate <TemplatePath> — валидация структуры после редактирования
/skd-info <TemplatePath> — визуальная сводка
```
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-29
View File
@@ -1,29 +0,0 @@
---
name: skd-validate
description: Валидация схемы компоновки данных 1С (СКД). Используй после создания или модификации СКД для проверки корректности
argument-hint: <TemplatePath> [-Detailed] [-MaxErrors 20]
allowed-tools:
- Bash
- Read
- Glob
---
# /skd-validate — валидация СКД (DataCompositionSchema)
Проверяет структурную корректность Template.xml схемы компоновки данных. Выявляет ошибки формата, битые ссылки, дубликаты имён.
## Параметры
| Параметр | Обяз. | Умолч. | Описание |
|--------------|:-----:|---------|---------------------------------------------------------|
| TemplatePath | да | — | Путь к Template.xml или каталогу макета |
| Detailed | нет | — | Подробный вывод (все проверки, включая успешные) |
| MaxErrors | нет | 20 | Остановиться после N ошибок |
| OutFile | нет | — | Записать результат в файл |
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/skd-validate/scripts/skd-validate.ps1" -TemplatePath "src/МойОтчёт/Templates/ОсновнаяСхема"
powershell.exe -NoProfile -File ".augment/skills/skd-validate/scripts/skd-validate.ps1" -TemplatePath "Catalogs/Номенклатура/Templates/СКД/Ext/Template.xml"
```
@@ -1,673 +0,0 @@
# subsystem-compile v1.8 — Create 1C subsystem from JSON definition
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
param(
[string]$DefinitionFile,
[string]$Value,
[Parameter(Mandatory)][string]$OutputDir,
[string]$Parent,
[switch]$NoValidate
)
$ErrorActionPreference = "Stop"
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# --- 1. Load JSON ---
if ($DefinitionFile -and $Value) {
Write-Error "Cannot use both -DefinitionFile and -Value"
exit 1
}
if (-not $DefinitionFile -and -not $Value) {
Write-Error "Either -DefinitionFile or -Value is required"
exit 1
}
if ($DefinitionFile) {
if (-not [System.IO.Path]::IsPathRooted($DefinitionFile)) {
$DefinitionFile = Join-Path (Get-Location).Path $DefinitionFile
}
if (-not (Test-Path $DefinitionFile)) {
Write-Error "Definition file not found: $DefinitionFile"
exit 1
}
$json = Get-Content -Raw -Encoding UTF8 $DefinitionFile
} else {
$json = $Value
}
$def = $json | ConvertFrom-Json
if (-not $def.name) {
Write-Error "JSON must have 'name' field"
exit 1
}
$objName = "$($def.name)"
# Resolve OutputDir
if (-not [System.IO.Path]::IsPathRooted($OutputDir)) {
$OutputDir = Join-Path (Get-Location).Path $OutputDir
}
# --- Support guard (Ext/ParentConfigurations.bin) ---
# See docs/1c-support-state-spec.md. Blocks edits of vendor objects "на замке" /
# read-only configs unless allowed. Trigger = bin present; reaction from
# .v8-project.json editingAllowedCheck (deny|warn|off, default deny). Never
# throws — guard errors degrade to allow.
function Get-RootUuid([string]$xmlPath) {
if (-not (Test-Path $xmlPath)) { return $null }
try {
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
$el = $mx.DocumentElement.FirstChild
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
} catch {}
return $null
}
function Find-V8Project([string]$startDir) {
$d = $startDir
for ($i = 0; $i -lt 20 -and $d; $i++) {
$pj = Join-Path $d ".v8-project.json"
if (Test-Path $pj) { return $pj }
$parent = [System.IO.Path]::GetDirectoryName($d)
if ($parent -eq $d) { break }
$d = $parent
}
return $null
}
function Get-EditMode([string]$cfgDir) {
try {
$pj = Find-V8Project (Get-Location).Path
if (-not $pj) { $pj = Find-V8Project $cfgDir }
if (-not $pj) { return 'deny' }
$proj = Get-Content -Raw $pj | ConvertFrom-Json
$cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
if ($proj.databases) {
foreach ($db in $proj.databases) {
if ($db.configSrc) {
$src = [System.IO.Path]::GetFullPath($db.configSrc).TrimEnd('\', '/')
if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar)) {
if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
}
}
}
}
if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
return 'deny'
} catch { return 'deny' }
}
function Assert-EditAllowed([string]$targetPath, [string]$require) {
try {
$rp = $targetPath
try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).Path } catch {}
$elemUuid = Get-RootUuid $rp
$cfgDir = $null; $binPath = $null
$d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
for ($i = 0; $i -lt 12 -and $d; $i++) {
if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
if (-not $cfgDir) {
$cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
}
if ($elemUuid -and $cfgDir) { break }
$parent = [System.IO.Path]::GetDirectoryName($d)
if ($parent -eq $d) { break }
$d = $parent
}
# New object (no element file): fall back to config root uuid.
if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
if (-not $binPath -or -not (Test-Path $binPath)) { return }
$bytes = [System.IO.File]::ReadAllBytes($binPath)
if ($bytes.Length -le 32) { return }
$start = 0
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
$text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
$hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
if (-not $hm.Success) { return }
$G = [int]$hm.Groups[1].Value
$K = [int]$hm.Groups[2].Value
if ($K -eq 0) { return }
$best = $null
if ($elemUuid) {
$u = [regex]::Escape($elemUuid.ToLower())
foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
$f1 = [int]$m.Groups[1].Value
if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
}
}
$blocked = $false; $code = ""; $reason = ""
if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
elseif ($require -eq 'removed') {
if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
}
else {
if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
}
if (-not $blocked) { return }
$mode = Get-EditMode $cfgDir
if ($mode -eq 'off') { return }
# Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
# latter throws and would be swallowed by this function's own catch.
if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
$head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
$cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
$offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
if ($code -eq "capability-off") {
$state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
$fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
} elseif ($code -eq "not-removed") {
$state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
$fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
} else {
$state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
$fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
}
[Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
exit 1
} catch { return }
}
Assert-EditAllowed $OutputDir 'editable'
# --- 2. XML helpers ---
$script:xml = New-Object System.Text.StringBuilder 8192
function X([string]$text) {
$script:xml.AppendLine($text) | Out-Null
}
function Esc-Xml([string]$s) {
return $s.Replace('&','&amp;').Replace('<','&lt;').Replace('>','&gt;').Replace('"','&quot;')
}
function Split-CamelCase([string]$name) {
if (-not $name) { return $name }
$result = [regex]::Replace($name, '([a-z\u0430-\u044F\u0451])([A-Z\u0410-\u042F\u0401])', '$1 $2')
if ($result.Length -gt 1) {
$result = $result.Substring(0,1) + $result.Substring(1).ToLower()
}
return $result
}
function Emit-MLText([string]$indent, [string]$tag, [string]$text) {
if (-not $text) {
X "$indent<$tag/>"
return
}
X "$indent<$tag>"
X "$indent`t<v8:item>"
X "$indent`t`t<v8:lang>ru</v8:lang>"
X "$indent`t`t<v8:content>$(Esc-Xml $text)</v8:content>"
X "$indent`t</v8:item>"
X "$indent</$tag>"
}
function New-Guid-String {
return [System.Guid]::NewGuid().ToString()
}
function Write-ChildSubsystemStub([string]$childPath, [string]$childName, [string]$formatVersion, [System.Text.Encoding]$utf8Bom) {
$childUuid = New-Guid-String
$sb = New-Object System.Text.StringBuilder 2048
[void]$sb.AppendLine('<?xml version="1.0" encoding="UTF-8"?>')
[void]$sb.AppendLine("<MetaDataObject xmlns=`"http://v8.1c.ru/8.3/MDClasses`" xmlns:app=`"http://v8.1c.ru/8.2/managed-application/core`" xmlns:cfg=`"http://v8.1c.ru/8.1/data/enterprise/current-config`" xmlns:cmi=`"http://v8.1c.ru/8.2/managed-application/cmi`" xmlns:ent=`"http://v8.1c.ru/8.1/data/enterprise`" xmlns:lf=`"http://v8.1c.ru/8.2/managed-application/logform`" xmlns:style=`"http://v8.1c.ru/8.1/data/ui/style`" xmlns:sys=`"http://v8.1c.ru/8.1/data/ui/fonts/system`" xmlns:v8=`"http://v8.1c.ru/8.1/data/core`" xmlns:v8ui=`"http://v8.1c.ru/8.1/data/ui`" xmlns:web=`"http://v8.1c.ru/8.1/data/ui/colors/web`" xmlns:win=`"http://v8.1c.ru/8.1/data/ui/colors/windows`" xmlns:xen=`"http://v8.1c.ru/8.3/xcf/enums`" xmlns:xpr=`"http://v8.1c.ru/8.3/xcf/predef`" xmlns:xr=`"http://v8.1c.ru/8.3/xcf/readable`" xmlns:xs=`"http://www.w3.org/2001/XMLSchema`" xmlns:xsi=`"http://www.w3.org/2001/XMLSchema-instance`" version=`"$formatVersion`">")
[void]$sb.AppendLine("`t<Subsystem uuid=`"$childUuid`">")
[void]$sb.AppendLine("`t`t<Properties>")
[void]$sb.AppendLine("`t`t`t<Name>$(Esc-Xml $childName)</Name>")
[void]$sb.AppendLine("`t`t`t<Synonym/>")
[void]$sb.AppendLine("`t`t`t<Comment/>")
[void]$sb.AppendLine("`t`t`t<IncludeHelpInContents>true</IncludeHelpInContents>")
[void]$sb.AppendLine("`t`t`t<IncludeInCommandInterface>true</IncludeInCommandInterface>")
[void]$sb.AppendLine("`t`t`t<UseOneCommand>false</UseOneCommand>")
[void]$sb.AppendLine("`t`t`t<Explanation/>")
[void]$sb.AppendLine("`t`t`t<Picture/>")
[void]$sb.AppendLine("`t`t`t<Content/>")
[void]$sb.AppendLine("`t`t</Properties>")
[void]$sb.AppendLine("`t`t<ChildObjects/>")
[void]$sb.AppendLine("`t</Subsystem>")
[void]$sb.AppendLine('</MetaDataObject>')
[System.IO.File]::WriteAllText($childPath, $sb.ToString(), $utf8Bom)
}
# --- 3. Content type normalization (plural→singular, Russian→English) ---
$script:contentTypeMap = @{
# Plural English → Singular
"Catalogs" = "Catalog"
"Documents" = "Document"
"Enums" = "Enum"
"Constants" = "Constant"
"Reports" = "Report"
"DataProcessors" = "DataProcessor"
"InformationRegisters" = "InformationRegister"
"AccumulationRegisters" = "AccumulationRegister"
"AccountingRegisters" = "AccountingRegister"
"CalculationRegisters" = "CalculationRegister"
"ChartsOfAccounts" = "ChartOfAccounts"
"ChartsOfCharacteristicTypes" = "ChartOfCharacteristicTypes"
"ChartsOfCalculationTypes" = "ChartOfCalculationTypes"
"BusinessProcesses" = "BusinessProcess"
"Tasks" = "Task"
"ExchangePlans" = "ExchangePlan"
"DocumentJournals" = "DocumentJournal"
"CommonModules" = "CommonModule"
"CommonCommands" = "CommonCommand"
"CommonForms" = "CommonForm"
"CommonPictures" = "CommonPicture"
"CommonTemplates" = "CommonTemplate"
"CommonAttributes" = "CommonAttribute"
"CommandGroups" = "CommandGroup"
"Roles" = "Role"
"SessionParameters" = "SessionParameter"
"FilterCriteria" = "FilterCriterion"
"XDTOPackages" = "XDTOPackage"
"WebServices" = "WebService"
"HTTPServices" = "HTTPService"
"WSReferences" = "WSReference"
"EventSubscriptions" = "EventSubscription"
"ScheduledJobs" = "ScheduledJob"
"SettingsStorages" = "SettingsStorage"
"FunctionalOptions" = "FunctionalOption"
"FunctionalOptionsParameters" = "FunctionalOptionsParameter"
"DefinedTypes" = "DefinedType"
"DocumentNumerators" = "DocumentNumerator"
"Sequences" = "Sequence"
"Subsystems" = "Subsystem"
"StyleItems" = "StyleItem"
"IntegrationServices" = "IntegrationService"
# Russian singular → English
"Справочник" = "Catalog"
"Каталог" = "Catalog"
"Документ" = "Document"
"Перечисление" = "Enum"
"Константа" = "Constant"
"Отчёт" = "Report"
"Отчет" = "Report"
"Обработка" = "DataProcessor"
"РегистрСведений" = "InformationRegister"
"РегистрНакопления" = "AccumulationRegister"
"РегистрБухгалтерии" = "AccountingRegister"
"РегистрРасчёта" = "CalculationRegister"
"РегистрРасчета" = "CalculationRegister"
"ПланСчетов" = "ChartOfAccounts"
"ПланВидовХарактеристик" = "ChartOfCharacteristicTypes"
"ПланВидовРасчёта" = "ChartOfCalculationTypes"
"ПланВидовРасчета" = "ChartOfCalculationTypes"
"БизнесПроцесс" = "BusinessProcess"
"Задача" = "Task"
"ПланОбмена" = "ExchangePlan"
"ЖурналДокументов" = "DocumentJournal"
"ОбщийМодуль" = "CommonModule"
"ОбщаяКоманда" = "CommonCommand"
"ОбщаяФорма" = "CommonForm"
"ОбщаяКартинка" = "CommonPicture"
"ОбщийМакет" = "CommonTemplate"
"ОбщийРеквизит" = "CommonAttribute"
"ГруппаКоманд" = "CommandGroup"
"Роль" = "Role"
"ПараметрСеанса" = "SessionParameter"
"КритерийОтбора" = "FilterCriterion"
"ПакетXDTO" = "XDTOPackage"
"ВебСервис" = "WebService"
"HTTPСервис" = "HTTPService"
"WSСсылка" = "WSReference"
"ПодпискаНаСобытие" = "EventSubscription"
"РегламентноеЗадание" = "ScheduledJob"
"ХранилищеНастроек" = "SettingsStorage"
"ФункциональнаяОпция" = "FunctionalOption"
"ПараметрФункциональныхОпций" = "FunctionalOptionsParameter"
"ОпределяемыйТип" = "DefinedType"
"НумераторДокументов" = "DocumentNumerator"
"Последовательность" = "Sequence"
"Подсистема" = "Subsystem"
"ЭлементСтиля" = "StyleItem"
"СервисИнтеграции" = "IntegrationService"
# Russian plural → English
"Справочники" = "Catalog"
"Документы" = "Document"
"Перечисления" = "Enum"
"Константы" = "Constant"
"Отчёты" = "Report"
"Отчеты" = "Report"
"Обработки" = "DataProcessor"
"РегистрыСведений" = "InformationRegister"
"РегистрыНакопления" = "AccumulationRegister"
"РегистрыБухгалтерии" = "AccountingRegister"
"РегистрыРасчёта" = "CalculationRegister"
"РегистрыРасчета" = "CalculationRegister"
"ПланыСчетов" = "ChartOfAccounts"
"ПланыВидовХарактеристик" = "ChartOfCharacteristicTypes"
"ПланыВидовРасчёта" = "ChartOfCalculationTypes"
"ПланыВидовРасчета" = "ChartOfCalculationTypes"
"БизнесПроцессы" = "BusinessProcess"
"Задачи" = "Task"
"ПланыОбмена" = "ExchangePlan"
"ЖурналыДокументов" = "DocumentJournal"
"ОбщиеМодули" = "CommonModule"
"ОбщиеКоманды" = "CommonCommand"
"ОбщиеФормы" = "CommonForm"
"ОбщиеКартинки" = "CommonPicture"
"ОбщиеМакеты" = "CommonTemplate"
"ОбщиеРеквизиты" = "CommonAttribute"
"ГруппыКоманд" = "CommandGroup"
"Роли" = "Role"
"ПараметрыСеанса" = "SessionParameter"
"КритерииОтбора" = "FilterCriterion"
"ПакетыXDTO" = "XDTOPackage"
"ВебСервисы" = "WebService"
"HTTPСервисы" = "HTTPService"
"WSСсылки" = "WSReference"
"ПодпискиНаСобытия" = "EventSubscription"
"РегламентныеЗадания" = "ScheduledJob"
"ХранилищаНастроек" = "SettingsStorage"
"ФункциональныеОпции" = "FunctionalOption"
"ОпределяемыеТипы" = "DefinedType"
"Подсистемы" = "Subsystem"
"ЭлементыСтиля" = "StyleItem"
"СервисыИнтеграции" = "IntegrationService"
}
function Normalize-ContentRef([string]$ref) {
if (-not $ref -or -not $ref.Contains('.')) { return $ref }
$dotIdx = $ref.IndexOf('.')
$typePart = $ref.Substring(0, $dotIdx)
$namePart = $ref.Substring($dotIdx + 1)
if ($script:contentTypeMap.ContainsKey($typePart)) {
$typePart = $script:contentTypeMap[$typePart]
}
return "$typePart.$namePart"
}
# --- 4. Resolve defaults ---
$synonym = if ($def.synonym) { "$($def.synonym)" } else { Split-CamelCase $objName }
$comment = if ($def.comment) { "$($def.comment)" } else { "" }
$includeHelpInContents = "true"
$includeInCI = if ($null -ne $def.includeInCommandInterface) { "$($def.includeInCommandInterface)".ToLower() } else { "true" }
$useOneCommand = if ($null -ne $def.useOneCommand) { "$($def.useOneCommand)".ToLower() } else { "false" }
$explanation = if ($def.explanation) { "$($def.explanation)" } else { "" }
$picture = if ($def.picture) { "$($def.picture)" } else { "" }
# Synonym: accept "objects" as alias for "content"
if (-not $def.content -and $def.objects) { $def | Add-Member -NotePropertyName content -NotePropertyValue $def.objects }
$contentItems = @()
$normalizedCount = 0
if ($def.content) {
foreach ($c in $def.content) {
$raw = "$c"
$normalized = Normalize-ContentRef $raw
if ($normalized -ne $raw) {
Write-Host "[NORM] Content: $raw -> $normalized"
$normalizedCount++
}
$contentItems += $normalized
}
}
if ($normalizedCount -gt 0) {
Write-Host "[INFO] Normalized $normalizedCount content reference(s) to singular English form"
}
$children = @()
if ($def.children) {
foreach ($ch in $def.children) { $children += "$ch" }
}
# --- Detect format version ---
function Detect-FormatVersion([string]$dir) {
$d = $dir
while ($d) {
$cfgPath = Join-Path $d "Configuration.xml"
if (Test-Path $cfgPath) {
$head = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8).Substring(0, [Math]::Min(2000, (Get-Item $cfgPath).Length))
if ($head -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
}
$parent = Split-Path $d -Parent
if ($parent -eq $d) { break }
$d = $parent
}
return "2.17"
}
$formatVersion = Detect-FormatVersion $OutputDir
# --- 4. Build XML ---
$uuid = New-Guid-String
$indent = "`t`t`t"
X '<?xml version="1.0" encoding="UTF-8"?>'
X "<MetaDataObject xmlns=`"http://v8.1c.ru/8.3/MDClasses`" xmlns:app=`"http://v8.1c.ru/8.2/managed-application/core`" xmlns:cfg=`"http://v8.1c.ru/8.1/data/enterprise/current-config`" xmlns:cmi=`"http://v8.1c.ru/8.2/managed-application/cmi`" xmlns:ent=`"http://v8.1c.ru/8.1/data/enterprise`" xmlns:lf=`"http://v8.1c.ru/8.2/managed-application/logform`" xmlns:style=`"http://v8.1c.ru/8.1/data/ui/style`" xmlns:sys=`"http://v8.1c.ru/8.1/data/ui/fonts/system`" xmlns:v8=`"http://v8.1c.ru/8.1/data/core`" xmlns:v8ui=`"http://v8.1c.ru/8.1/data/ui`" xmlns:web=`"http://v8.1c.ru/8.1/data/ui/colors/web`" xmlns:win=`"http://v8.1c.ru/8.1/data/ui/colors/windows`" xmlns:xen=`"http://v8.1c.ru/8.3/xcf/enums`" xmlns:xpr=`"http://v8.1c.ru/8.3/xcf/predef`" xmlns:xr=`"http://v8.1c.ru/8.3/xcf/readable`" xmlns:xs=`"http://www.w3.org/2001/XMLSchema`" xmlns:xsi=`"http://www.w3.org/2001/XMLSchema-instance`" version=`"$formatVersion`">"
X "`t<Subsystem uuid=`"$uuid`">"
X "`t`t<Properties>"
# Name
X "`t`t`t<Name>$(Esc-Xml $objName)</Name>"
# Synonym
Emit-MLText "`t`t`t" "Synonym" $synonym
# Comment
if ($comment) {
X "`t`t`t<Comment>$(Esc-Xml $comment)</Comment>"
} else {
X "`t`t`t<Comment/>"
}
# Boolean properties
X "`t`t`t<IncludeHelpInContents>$includeHelpInContents</IncludeHelpInContents>"
X "`t`t`t<IncludeInCommandInterface>$includeInCI</IncludeInCommandInterface>"
X "`t`t`t<UseOneCommand>$useOneCommand</UseOneCommand>"
# Explanation
Emit-MLText "`t`t`t" "Explanation" $explanation
# Picture
if ($picture) {
X "`t`t`t<Picture>"
X "`t`t`t`t<xr:Ref>$picture</xr:Ref>"
X "`t`t`t`t<xr:LoadTransparent>false</xr:LoadTransparent>"
X "`t`t`t</Picture>"
} else {
X "`t`t`t<Picture/>"
}
# Content
if ($contentItems.Count -gt 0) {
X "`t`t`t<Content>"
foreach ($item in $contentItems) {
X "`t`t`t`t<xr:Item xsi:type=`"xr:MDObjectRef`">$(Esc-Xml $item)</xr:Item>"
}
X "`t`t`t</Content>"
} else {
X "`t`t`t<Content/>"
}
X "`t`t</Properties>"
# ChildObjects
if ($children.Count -gt 0) {
X "`t`t<ChildObjects>"
foreach ($ch in $children) {
X "`t`t`t<Subsystem>$(Esc-Xml $ch)</Subsystem>"
}
X "`t`t</ChildObjects>"
} else {
X "`t`t<ChildObjects/>"
}
X "`t</Subsystem>"
X '</MetaDataObject>'
# --- 5. Write files ---
# Determine target directory
if ($Parent) {
# Nested subsystem
if (-not [System.IO.Path]::IsPathRooted($Parent)) {
$Parent = Join-Path (Get-Location).Path $Parent
}
if (-not (Test-Path $Parent)) {
Write-Error "Parent subsystem not found: $Parent"
exit 1
}
$parentDir = [System.IO.Path]::GetDirectoryName($Parent)
$parentBaseName = [System.IO.Path]::GetFileNameWithoutExtension($Parent)
$subsDir = Join-Path (Join-Path $parentDir $parentBaseName) "Subsystems"
} else {
# Top-level subsystem
$subsDir = Join-Path $OutputDir "Subsystems"
}
if (-not (Test-Path $subsDir)) {
New-Item -ItemType Directory -Path $subsDir -Force | Out-Null
}
$targetXml = Join-Path $subsDir "$objName.xml"
# Write XML
$xmlContent = $script:xml.ToString()
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
[System.IO.File]::WriteAllText($targetXml, $xmlContent, $utf8Bom)
Write-Host "[OK] Created: $targetXml"
# Create subdirectory and stub files for children if they exist
if ($children.Count -gt 0) {
$childSubsDir = Join-Path (Join-Path $subsDir $objName) "Subsystems"
if (-not (Test-Path $childSubsDir)) {
New-Item -ItemType Directory -Path $childSubsDir -Force | Out-Null
Write-Host "[OK] Created directory: $childSubsDir"
}
$seen = @{}
foreach ($ch in $children) {
if ($seen.ContainsKey($ch)) { continue }
$seen[$ch] = $true
$childXml = Join-Path $childSubsDir "$ch.xml"
if (-not (Test-Path $childXml)) {
Write-ChildSubsystemStub $childXml $ch $formatVersion $utf8Bom
Write-Host "[OK] Created stub: $childXml"
}
}
}
# --- 6. Register in parent ---
$parentXmlPath = $null
if ($Parent) {
$parentXmlPath = $Parent
} else {
$configXml = Join-Path $OutputDir "Configuration.xml"
if (Test-Path $configXml) {
$parentXmlPath = $configXml
}
}
if ($parentXmlPath -and (Test-Path $parentXmlPath)) {
$doc = New-Object System.Xml.XmlDocument
$doc.PreserveWhitespace = $true
$doc.Load($parentXmlPath)
$ns = New-Object System.Xml.XmlNamespaceManager($doc.NameTable)
$ns.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
# Find ChildObjects
$childObjects = $null
if ($Parent) {
$childObjects = $doc.SelectSingleNode("//md:Subsystem/md:ChildObjects", $ns)
} else {
$childObjects = $doc.SelectSingleNode("//md:Configuration/md:ChildObjects", $ns)
}
if ($childObjects) {
# Check for self-closing tag
$isSelfClosing = (-not $childObjects.HasChildNodes) -or ($childObjects.IsEmpty)
# Check if already registered
$alreadyExists = $false
foreach ($child in $childObjects.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Subsystem" -and $child.InnerText -eq $objName) {
$alreadyExists = $true
break
}
}
if (-not $alreadyExists) {
$newEl = $doc.CreateElement("Subsystem", "http://v8.1c.ru/8.3/MDClasses")
$newEl.InnerText = $objName
if ($isSelfClosing) {
# Expand self-closing tag
$parentIndent = ""
$prev = $childObjects.PreviousSibling
if ($prev -and ($prev.NodeType -eq 'Whitespace' -or $prev.NodeType -eq 'SignificantWhitespace')) {
if ($prev.Value -match '(\t+)$') { $parentIndent = $Matches[1] }
}
$childIndent = "$parentIndent`t"
$ws1 = $doc.CreateWhitespace("`r`n$childIndent")
$ws2 = $doc.CreateWhitespace("`r`n$parentIndent")
$childObjects.AppendChild($ws1) | Out-Null
$childObjects.AppendChild($newEl) | Out-Null
$childObjects.AppendChild($ws2) | Out-Null
} else {
# Insert before trailing whitespace
$childIndent = "`t`t`t"
foreach ($child in $childObjects.ChildNodes) {
if ($child.NodeType -eq 'Whitespace' -or $child.NodeType -eq 'SignificantWhitespace') {
if ($child.Value -match '^\r?\n(\t+)') { $childIndent = $Matches[1]; break }
}
}
$trailing = $childObjects.LastChild
$ws = $doc.CreateWhitespace("`r`n$childIndent")
if ($trailing -and ($trailing.NodeType -eq 'Whitespace' -or $trailing.NodeType -eq 'SignificantWhitespace')) {
$childObjects.InsertBefore($ws, $trailing) | Out-Null
$childObjects.InsertBefore($newEl, $trailing) | Out-Null
} else {
$childObjects.AppendChild($ws) | Out-Null
$childObjects.AppendChild($newEl) | Out-Null
}
}
# Save parent XML
$settings = New-Object System.Xml.XmlWriterSettings
$settings.Encoding = New-Object System.Text.UTF8Encoding($true)
$settings.Indent = $false
$settings.NewLineHandling = [System.Xml.NewLineHandling]::None
$memStream = New-Object System.IO.MemoryStream
$writer = [System.Xml.XmlWriter]::Create($memStream, $settings)
$doc.Save($writer)
$writer.Flush(); $writer.Close()
$bytes = $memStream.ToArray()
$memStream.Close()
$text = [System.Text.Encoding]::UTF8.GetString($bytes)
if ($text.Length -gt 0 -and $text[0] -eq [char]0xFEFF) { $text = $text.Substring(1) }
$text = $text.Replace('encoding="utf-8"', 'encoding="UTF-8"')
[System.IO.File]::WriteAllText($parentXmlPath, $text, $utf8Bom)
Write-Host "[OK] Registered in: $parentXmlPath"
} else {
Write-Host "[SKIP] Already registered in: $parentXmlPath"
}
} else {
Write-Host "[WARN] ChildObjects not found in: $parentXmlPath"
}
} else {
Write-Host "[INFO] No parent XML to register in"
}
# --- 7. Auto-validate ---
if (-not $NoValidate) {
$validateScript = Join-Path (Join-Path $PSScriptRoot "..\..\subsystem-validate") "scripts\subsystem-validate.ps1"
$validateScript = [System.IO.Path]::GetFullPath($validateScript)
if (Test-Path $validateScript) {
Write-Host ""
Write-Host "--- Running subsystem-validate ---"
& powershell.exe -NoProfile -File $validateScript -SubsystemPath $targetXml
}
}
Write-Host ""
Write-Host "=== subsystem-compile summary ==="
Write-Host " Name: $objName"
Write-Host " UUID: $uuid"
Write-Host " Content: $($contentItems.Count) objects"
Write-Host " Children: $($children.Count)"
Write-Host " File: $targetXml"
exit 0
@@ -1,613 +0,0 @@
#!/usr/bin/env python3
# subsystem-compile v1.8 — Create 1C subsystem from JSON definition
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import json
import os
import re
import subprocess
import sys
import uuid
import xml.etree.ElementTree as ET
from lxml import etree
# ============================================================
# Support guard (Ext/ParentConfigurations.bin) — see docs/1c-support-state-spec.md
# Blocks edits of vendor objects "на замке" / read-only configs. Trigger = bin
# present; reaction from .v8-project.json editingAllowedCheck (deny|warn|off,
# default deny). Never throws (except sys.exit on deny) — errors degrade to allow.
# ============================================================
def _sg_root_uuid(xml_path):
if not os.path.isfile(xml_path):
return None
try:
mx = etree.parse(xml_path).getroot()
for child in mx:
if isinstance(child.tag, str) and child.get("uuid"):
return child.get("uuid")
except Exception:
return None
return None
def _sg_find_v8project(start_dir):
d = start_dir
for _ in range(20):
if not d:
break
pj = os.path.join(d, ".v8-project.json")
if os.path.isfile(pj):
return pj
parent = os.path.dirname(d)
if parent == d:
break
d = parent
return None
def _sg_get_edit_mode(cfg_dir):
try:
pj = _sg_find_v8project(os.getcwd()) or _sg_find_v8project(cfg_dir)
if not pj:
return "deny"
proj = json.loads(open(pj, encoding="utf-8-sig").read())
cfg_full = os.path.normcase(os.path.abspath(cfg_dir)).rstrip("\\/")
for db in proj.get("databases", []):
src = db.get("configSrc")
if src:
src_full = os.path.normcase(os.path.abspath(src)).rstrip("\\/")
if cfg_full == src_full or cfg_full.startswith(src_full + os.sep):
if db.get("editingAllowedCheck"):
return db["editingAllowedCheck"]
if proj.get("editingAllowedCheck"):
return proj["editingAllowedCheck"]
return "deny"
except Exception:
return "deny"
def assert_edit_allowed(target_path, require):
try:
rp = os.path.abspath(target_path)
elem_uuid = _sg_root_uuid(rp)
cfg_dir = None
bin_path = None
d = rp if os.path.isdir(rp) else os.path.dirname(rp)
for _ in range(12):
if not d:
break
if not elem_uuid:
elem_uuid = _sg_root_uuid(d + ".xml")
if not cfg_dir:
cand = os.path.join(d, "Ext", "ParentConfigurations.bin")
if os.path.exists(cand) or os.path.exists(os.path.join(d, "Configuration.xml")):
cfg_dir = d
bin_path = cand
if elem_uuid and cfg_dir:
break
parent = os.path.dirname(d)
if parent == d:
break
d = parent
if not elem_uuid and cfg_dir:
elem_uuid = _sg_root_uuid(os.path.join(cfg_dir, "Configuration.xml"))
if not bin_path or not os.path.exists(bin_path):
return
data = open(bin_path, "rb").read()
if len(data) <= 32:
return
if data[:3] == b"\xef\xbb\xbf":
data = data[3:]
text = data.decode("utf-8", "replace")
h = re.match(r"\{6,(\d+),(\d+),", text)
if not h:
return
g = int(h.group(1))
k = int(h.group(2))
if k == 0:
return
best = None
if elem_uuid:
for m in re.finditer(r"([0-2]),0," + re.escape(elem_uuid.lower()), text):
f1 = int(m.group(1))
if best is None or f1 < best:
best = f1
blocked = False
code = ""
reason = ""
if g == 1:
blocked = True
code = "capability-off"
reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)"
elif require == "removed":
if best is not None and best != 2:
blocked = True
code = "not-removed"
reason = "объект не снят с поддержки — удаление сломает обновления"
else:
if best is not None and best == 0:
blocked = True
code = "locked"
reason = "объект на замке — редактирование сломает обновления"
if not blocked:
return
mode = _sg_get_edit_mode(cfg_dir)
if mode == "off":
return
if mode == "warn":
sys.stderr.write(f"[support-guard] ПРЕДУПРЕЖДЕНИЕ: {reason}. Цель: {rp}\n")
return
head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
off_note = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
if code == "capability-off":
state = f"Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «{rp}» редактировать нельзя."
fix = (
"Либо снять защиту явно (навык support-edit, два шага):\n"
f' 1. support-edit -Path "{cfg_dir}" -Capability on — включить возможность изменения (объекты пока остаются на замке);\n'
f' 2. support-edit -Path "{rp}" -Set editable — открыть этот объект для редактирования.\n'
" Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
)
elif code == "not-removed":
state = f"Состояние: объект «{rp}» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
fix = (
"Либо сначала снять объект с поддержки, затем удалять:\n"
f' support-edit -Path "{rp}" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно.'
)
else:
state = f"Состояние: объект «{rp}» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
fix = (
"Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):\n"
f' support-edit -Path "{rp}" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);\n'
f' support-edit -Path "{rp}" -Set off-support — снять с поддержки: обновления по объекту больше не приходят.'
)
sys.stderr.write(head + "\n" + state + "\n" + cfe + "\n" + fix + "\n" + off_note + "\n")
sys.exit(1)
except SystemExit:
raise
except Exception:
return
def detect_format_version(d):
while d:
cfg_path = os.path.join(d, "Configuration.xml")
if os.path.isfile(cfg_path):
with open(cfg_path, "r", encoding="utf-8-sig") as f:
head = f.read(2000)
m = re.search(r'<MetaDataObject[^>]+version="(\d+\.\d+)"', head)
if m:
return m.group(1)
parent = os.path.dirname(d)
if parent == d:
break
d = parent
return "2.17"
def esc_xml(s):
return s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;')
def emit_mltext(lines, indent, tag, text):
if not text:
lines.append(f"{indent}<{tag}/>")
return
lines.append(f"{indent}<{tag}>")
lines.append(f"{indent}\t<v8:item>")
lines.append(f"{indent}\t\t<v8:lang>ru</v8:lang>")
lines.append(f"{indent}\t\t<v8:content>{esc_xml(text)}</v8:content>")
lines.append(f"{indent}\t</v8:item>")
lines.append(f"{indent}</{tag}>")
def new_uuid():
return str(uuid.uuid4())
def write_utf8_bom(path, content):
with open(path, 'w', encoding='utf-8-sig', newline='') as f:
f.write(content)
def split_camel_case(name):
if not name:
return name
result = re.sub(r'([a-z\u0430-\u044f\u0451])([A-Z\u0410-\u042f\u0401])', r'\1 \2', name)
if len(result) > 1:
result = result[0] + result[1:].lower()
return result
def write_child_subsystem_stub(child_path, child_name, format_version):
child_uuid = new_uuid()
lines = []
lines.append('<?xml version="1.0" encoding="UTF-8"?>')
lines.append(
'<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" '
'xmlns:app="http://v8.1c.ru/8.2/managed-application/core" '
'xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" '
'xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" '
'xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" '
'xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" '
'xmlns:style="http://v8.1c.ru/8.1/data/ui/style" '
'xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" '
'xmlns:v8="http://v8.1c.ru/8.1/data/core" '
'xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" '
'xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" '
'xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" '
'xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" '
'xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" '
'xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" '
'xmlns:xs="http://www.w3.org/2001/XMLSchema" '
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '
f'version="{format_version}">'
)
lines.append(f'\t<Subsystem uuid="{child_uuid}">')
lines.append('\t\t<Properties>')
lines.append(f'\t\t\t<Name>{esc_xml(child_name)}</Name>')
lines.append('\t\t\t<Synonym/>')
lines.append('\t\t\t<Comment/>')
lines.append('\t\t\t<IncludeHelpInContents>true</IncludeHelpInContents>')
lines.append('\t\t\t<IncludeInCommandInterface>true</IncludeInCommandInterface>')
lines.append('\t\t\t<UseOneCommand>false</UseOneCommand>')
lines.append('\t\t\t<Explanation/>')
lines.append('\t\t\t<Picture/>')
lines.append('\t\t\t<Content/>')
lines.append('\t\t</Properties>')
lines.append('\t\t<ChildObjects/>')
lines.append('\t</Subsystem>')
lines.append('</MetaDataObject>')
write_utf8_bom(child_path, '\n'.join(lines) + '\n')
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(description='Compile 1C subsystem from JSON definition', allow_abbrev=False)
parser.add_argument('-DefinitionFile', type=str, default=None)
parser.add_argument('-Value', type=str, default=None)
parser.add_argument('-OutputDir', type=str, required=True)
parser.add_argument('-Parent', type=str, default=None)
parser.add_argument('-NoValidate', action='store_true', default=False)
args = parser.parse_args()
# --- 1. Load JSON ---
if args.DefinitionFile and args.Value:
print("Cannot use both -DefinitionFile and -Value", file=sys.stderr)
sys.exit(1)
if not args.DefinitionFile and not args.Value:
print("Either -DefinitionFile or -Value is required", file=sys.stderr)
sys.exit(1)
if args.DefinitionFile:
def_file = args.DefinitionFile
if not os.path.isabs(def_file):
def_file = os.path.join(os.getcwd(), def_file)
if not os.path.exists(def_file):
print(f"Definition file not found: {def_file}", file=sys.stderr)
sys.exit(1)
with open(def_file, 'r', encoding='utf-8-sig') as f:
json_text = f.read()
else:
json_text = args.Value
defn = json.loads(json_text)
if not defn.get('name'):
print("JSON must have 'name' field", file=sys.stderr)
sys.exit(1)
obj_name = str(defn['name'])
# Resolve OutputDir
output_dir = args.OutputDir
if not os.path.isabs(output_dir):
output_dir = os.path.join(os.getcwd(), output_dir)
assert_edit_allowed(output_dir, "editable")
# --- 2. Content type normalization (plural→singular, Russian→English) ---
CONTENT_TYPE_MAP = {
# Plural English → Singular
'Catalogs': 'Catalog', 'Documents': 'Document', 'Enums': 'Enum',
'Constants': 'Constant', 'Reports': 'Report', 'DataProcessors': 'DataProcessor',
'InformationRegisters': 'InformationRegister', 'AccumulationRegisters': 'AccumulationRegister',
'AccountingRegisters': 'AccountingRegister', 'CalculationRegisters': 'CalculationRegister',
'ChartsOfAccounts': 'ChartOfAccounts', 'ChartsOfCharacteristicTypes': 'ChartOfCharacteristicTypes',
'ChartsOfCalculationTypes': 'ChartOfCalculationTypes',
'BusinessProcesses': 'BusinessProcess', 'Tasks': 'Task',
'ExchangePlans': 'ExchangePlan', 'DocumentJournals': 'DocumentJournal',
'CommonModules': 'CommonModule', 'CommonCommands': 'CommonCommand',
'CommonForms': 'CommonForm', 'CommonPictures': 'CommonPicture',
'CommonTemplates': 'CommonTemplate', 'CommonAttributes': 'CommonAttribute',
'CommandGroups': 'CommandGroup', 'Roles': 'Role',
'SessionParameters': 'SessionParameter', 'FilterCriteria': 'FilterCriterion',
'XDTOPackages': 'XDTOPackage', 'WebServices': 'WebService',
'HTTPServices': 'HTTPService', 'WSReferences': 'WSReference',
'EventSubscriptions': 'EventSubscription', 'ScheduledJobs': 'ScheduledJob',
'SettingsStorages': 'SettingsStorage', 'FunctionalOptions': 'FunctionalOption',
'FunctionalOptionsParameters': 'FunctionalOptionsParameter',
'DefinedTypes': 'DefinedType', 'DocumentNumerators': 'DocumentNumerator',
'Sequences': 'Sequence', 'Subsystems': 'Subsystem',
'StyleItems': 'StyleItem', 'IntegrationServices': 'IntegrationService',
# Russian singular → English
'Справочник': 'Catalog', 'Каталог': 'Catalog', 'Документ': 'Document',
'Перечисление': 'Enum', 'Константа': 'Constant',
'Отчёт': 'Report', 'Отчет': 'Report', 'Обработка': 'DataProcessor',
'РегистрСведений': 'InformationRegister', 'РегистрНакопления': 'AccumulationRegister',
'РегистрБухгалтерии': 'AccountingRegister',
'РегистрРасчёта': 'CalculationRegister', 'РегистрРасчета': 'CalculationRegister',
'ПланСчетов': 'ChartOfAccounts', 'ПланВидовХарактеристик': 'ChartOfCharacteristicTypes',
'ПланВидовРасчёта': 'ChartOfCalculationTypes', 'ПланВидовРасчета': 'ChartOfCalculationTypes',
'БизнесПроцесс': 'BusinessProcess', 'Задача': 'Task',
'ПланОбмена': 'ExchangePlan', 'ЖурналДокументов': 'DocumentJournal',
'ОбщийМодуль': 'CommonModule', 'ОбщаяКоманда': 'CommonCommand',
'ОбщаяФорма': 'CommonForm', 'ОбщаяКартинка': 'CommonPicture',
'ОбщийМакет': 'CommonTemplate', 'ОбщийРеквизит': 'CommonAttribute',
'ГруппаКоманд': 'CommandGroup', 'Роль': 'Role',
'ПараметрСеанса': 'SessionParameter', 'КритерийОтбора': 'FilterCriterion',
'ПакетXDTO': 'XDTOPackage', 'ВебСервис': 'WebService',
'HTTPСервис': 'HTTPService', 'WSСсылка': 'WSReference',
'ПодпискаНаСобытие': 'EventSubscription', 'РегламентноеЗадание': 'ScheduledJob',
'ХранилищеНастроек': 'SettingsStorage', 'ФункциональнаяОпция': 'FunctionalOption',
'ПараметрФункциональныхОпций': 'FunctionalOptionsParameter',
'ОпределяемыйТип': 'DefinedType', 'НумераторДокументов': 'DocumentNumerator',
'Последовательность': 'Sequence', 'Подсистема': 'Subsystem',
'ЭлементСтиля': 'StyleItem', 'СервисИнтеграции': 'IntegrationService',
# Russian plural → English
'Справочники': 'Catalog', 'Документы': 'Document', 'Перечисления': 'Enum',
'Константы': 'Constant', 'Отчёты': 'Report', 'Отчеты': 'Report',
'Обработки': 'DataProcessor', 'РегистрыСведений': 'InformationRegister',
'РегистрыНакопления': 'AccumulationRegister', 'РегистрыБухгалтерии': 'AccountingRegister',
'РегистрыРасчёта': 'CalculationRegister', 'РегистрыРасчета': 'CalculationRegister',
'ПланыСчетов': 'ChartOfAccounts', 'ПланыВидовХарактеристик': 'ChartOfCharacteristicTypes',
'ПланыВидовРасчёта': 'ChartOfCalculationTypes', 'ПланыВидовРасчета': 'ChartOfCalculationTypes',
'БизнесПроцессы': 'BusinessProcess', 'Задачи': 'Task',
'ПланыОбмена': 'ExchangePlan', 'ЖурналыДокументов': 'DocumentJournal',
'ОбщиеМодули': 'CommonModule', 'ОбщиеКоманды': 'CommonCommand',
'ОбщиеФормы': 'CommonForm', 'ОбщиеКартинки': 'CommonPicture',
'ОбщиеМакеты': 'CommonTemplate', 'ОбщиеРеквизиты': 'CommonAttribute',
'ГруппыКоманд': 'CommandGroup', 'Роли': 'Role',
'ПараметрыСеанса': 'SessionParameter', 'КритерииОтбора': 'FilterCriterion',
'ПакетыXDTO': 'XDTOPackage', 'ВебСервисы': 'WebService',
'HTTPСервисы': 'HTTPService', 'WSСсылки': 'WSReference',
'ПодпискиНаСобытия': 'EventSubscription', 'РегламентныеЗадания': 'ScheduledJob',
'ХранилищаНастроек': 'SettingsStorage', 'ФункциональныеОпции': 'FunctionalOption',
'ОпределяемыеТипы': 'DefinedType', 'Подсистемы': 'Subsystem',
'ЭлементыСтиля': 'StyleItem', 'СервисыИнтеграции': 'IntegrationService',
}
def normalize_content_ref(ref):
if not ref or '.' not in ref:
return ref
dot_idx = ref.index('.')
type_part = ref[:dot_idx]
name_part = ref[dot_idx + 1:]
if type_part in CONTENT_TYPE_MAP:
type_part = CONTENT_TYPE_MAP[type_part]
return f'{type_part}.{name_part}'
format_version = detect_format_version(output_dir)
# --- 3. Resolve defaults ---
synonym = str(defn['synonym']) if defn.get('synonym') else split_camel_case(obj_name)
comment = str(defn['comment']) if defn.get('comment') else ''
include_help_in_contents = 'true'
include_in_ci = str(defn['includeInCommandInterface']).lower() if defn.get('includeInCommandInterface') is not None else 'true'
use_one_command = str(defn['useOneCommand']).lower() if defn.get('useOneCommand') is not None else 'false'
explanation = str(defn['explanation']) if defn.get('explanation') else ''
picture = str(defn['picture']) if defn.get('picture') else ''
# Synonym: accept "objects" as alias for "content"
if not defn.get('content') and defn.get('objects'):
defn['content'] = defn['objects']
content_items = []
normalized_count = 0
if defn.get('content'):
for c in defn['content']:
raw = str(c)
normalized = normalize_content_ref(raw)
if normalized != raw:
print(f'[NORM] Content: {raw} -> {normalized}')
normalized_count += 1
content_items.append(normalized)
if normalized_count > 0:
print(f'[INFO] Normalized {normalized_count} content reference(s) to singular English form')
children = []
if defn.get('children'):
for ch in defn['children']:
children.append(str(ch))
# --- 3. Build XML ---
uid = new_uuid()
lines = []
lines.append('<?xml version="1.0" encoding="UTF-8"?>')
lines.append(f'<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="{format_version}">')
lines.append(f'\t<Subsystem uuid="{uid}">')
lines.append('\t\t<Properties>')
# Name
lines.append(f'\t\t\t<Name>{esc_xml(obj_name)}</Name>')
# Synonym
emit_mltext(lines, '\t\t\t', 'Synonym', synonym)
# Comment
if comment:
lines.append(f'\t\t\t<Comment>{esc_xml(comment)}</Comment>')
else:
lines.append('\t\t\t<Comment/>')
# Boolean properties
lines.append(f'\t\t\t<IncludeHelpInContents>{include_help_in_contents}</IncludeHelpInContents>')
lines.append(f'\t\t\t<IncludeInCommandInterface>{include_in_ci}</IncludeInCommandInterface>')
lines.append(f'\t\t\t<UseOneCommand>{use_one_command}</UseOneCommand>')
# Explanation
emit_mltext(lines, '\t\t\t', 'Explanation', explanation)
# Picture
if picture:
lines.append('\t\t\t<Picture>')
lines.append(f'\t\t\t\t<xr:Ref>{picture}</xr:Ref>')
lines.append('\t\t\t\t<xr:LoadTransparent>false</xr:LoadTransparent>')
lines.append('\t\t\t</Picture>')
else:
lines.append('\t\t\t<Picture/>')
# Content
if len(content_items) > 0:
lines.append('\t\t\t<Content>')
for item in content_items:
lines.append(f'\t\t\t\t<xr:Item xsi:type="xr:MDObjectRef">{esc_xml(item)}</xr:Item>')
lines.append('\t\t\t</Content>')
else:
lines.append('\t\t\t<Content/>')
lines.append('\t\t</Properties>')
# ChildObjects
if len(children) > 0:
lines.append('\t\t<ChildObjects>')
for ch in children:
lines.append(f'\t\t\t<Subsystem>{esc_xml(ch)}</Subsystem>')
lines.append('\t\t</ChildObjects>')
else:
lines.append('\t\t<ChildObjects/>')
lines.append('\t</Subsystem>')
lines.append('</MetaDataObject>')
# --- 4. Write files ---
parent = args.Parent
if parent:
# Nested subsystem
if not os.path.isabs(parent):
parent = os.path.join(os.getcwd(), parent)
if not os.path.exists(parent):
print(f"Parent subsystem not found: {parent}", file=sys.stderr)
sys.exit(1)
parent_dir = os.path.dirname(parent)
parent_base_name = os.path.splitext(os.path.basename(parent))[0]
subs_dir = os.path.join(parent_dir, parent_base_name, 'Subsystems')
else:
# Top-level subsystem
subs_dir = os.path.join(output_dir, 'Subsystems')
os.makedirs(subs_dir, exist_ok=True)
target_xml = os.path.join(subs_dir, f'{obj_name}.xml')
# Write XML
xml_content = '\n'.join(lines) + '\n'
write_utf8_bom(target_xml, xml_content)
print(f"[OK] Created: {target_xml}")
# Create subdirectory and stub files for children if they exist
if len(children) > 0:
child_subs_dir = os.path.join(subs_dir, obj_name, 'Subsystems')
if not os.path.exists(child_subs_dir):
os.makedirs(child_subs_dir, exist_ok=True)
print(f"[OK] Created directory: {child_subs_dir}")
seen = set()
for ch in children:
if ch in seen:
continue
seen.add(ch)
child_xml = os.path.join(child_subs_dir, f'{ch}.xml')
if not os.path.exists(child_xml):
write_child_subsystem_stub(child_xml, ch, format_version)
print(f"[OK] Created stub: {child_xml}")
# --- 5. Register in parent ---
parent_xml_path = None
if parent:
parent_xml_path = parent
else:
config_xml = os.path.join(output_dir, 'Configuration.xml')
if os.path.exists(config_xml):
parent_xml_path = config_xml
if parent_xml_path and os.path.exists(parent_xml_path):
with open(parent_xml_path, 'r', encoding='utf-8-sig') as f:
raw_text = f.read()
doc = ET.ElementTree(ET.fromstring(raw_text))
root = doc.getroot()
md_ns = 'http://v8.1c.ru/8.3/MDClasses'
# Find ChildObjects
child_objects = None
if parent:
for sub in root.iter(f'{{{md_ns}}}Subsystem'):
child_objects = sub.find(f'{{{md_ns}}}ChildObjects')
break
else:
for cfg in root.iter(f'{{{md_ns}}}Configuration'):
child_objects = cfg.find(f'{{{md_ns}}}ChildObjects')
break
if child_objects is not None:
# Check if already registered
already_exists = False
for child in child_objects:
if child.tag == f'{{{md_ns}}}Subsystem' and child.text == obj_name:
already_exists = True
break
if not already_exists:
new_el = ET.SubElement(child_objects, f'{{{md_ns}}}Subsystem')
new_el.text = obj_name
# Re-serialize with whitespace preservation via raw text manipulation instead
# Since ElementTree doesn't preserve whitespace well, use regex-based insertion
# Find </ChildObjects> or <ChildObjects/> and inject
pass # Fall through to raw text approach below
if not already_exists:
# Use raw text manipulation to preserve formatting
if '<ChildObjects/>' in raw_text:
replacement = f'<ChildObjects>\n\t\t\t<Subsystem>{esc_xml(obj_name)}</Subsystem>\n\t\t</ChildObjects>'
raw_text = raw_text.replace('<ChildObjects/>', replacement, 1)
elif '</ChildObjects>' in raw_text:
insert_line = f'\t\t\t<Subsystem>{esc_xml(obj_name)}</Subsystem>\n'
raw_text = raw_text.replace('</ChildObjects>', insert_line + '\t\t</ChildObjects>', 1)
write_utf8_bom(parent_xml_path, raw_text)
print(f"[OK] Registered in: {parent_xml_path}")
else:
print(f"[SKIP] Already registered in: {parent_xml_path}")
else:
print(f"[WARN] ChildObjects not found in: {parent_xml_path}")
else:
print("[INFO] No parent XML to register in")
# --- 6. Auto-validate ---
if not args.NoValidate:
script_dir = os.path.dirname(os.path.abspath(__file__))
validate_script = os.path.normpath(os.path.join(script_dir, '..', '..', 'subsystem-validate', 'scripts', 'subsystem-validate.py'))
if os.path.isfile(validate_script):
print()
print("--- Running subsystem-validate ---")
subprocess.run([sys.executable, validate_script, "-SubsystemPath", target_xml])
# --- 7. Summary ---
print()
print("=== subsystem-compile summary ===")
print(f" Name: {obj_name}")
print(f" UUID: {uid}")
print(f" Content: {len(content_items)} objects")
print(f" Children: {len(children)}")
print(f" File: {target_xml}")
sys.exit(0)
if __name__ == '__main__':
main()
@@ -1,666 +0,0 @@
# subsystem-edit v1.5 — Edit existing 1C subsystem XML
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
param(
[Parameter(Mandatory)][Alias('Path')][string]$SubsystemPath,
[string]$DefinitionFile,
[ValidateSet("add-content","remove-content","add-child","remove-child","set-property")]
[string]$Operation,
[string]$Value,
[switch]$NoValidate
)
$ErrorActionPreference = "Stop"
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# --- Content type normalization (plural→singular, Russian→English) ---
$script:contentTypeMap = @{
"Catalogs"="Catalog"; "Documents"="Document"; "Enums"="Enum"; "Constants"="Constant"
"Reports"="Report"; "DataProcessors"="DataProcessor"
"InformationRegisters"="InformationRegister"; "AccumulationRegisters"="AccumulationRegister"
"AccountingRegisters"="AccountingRegister"; "CalculationRegisters"="CalculationRegister"
"ChartsOfAccounts"="ChartOfAccounts"; "ChartsOfCharacteristicTypes"="ChartOfCharacteristicTypes"
"ChartsOfCalculationTypes"="ChartOfCalculationTypes"
"BusinessProcesses"="BusinessProcess"; "Tasks"="Task"
"ExchangePlans"="ExchangePlan"; "DocumentJournals"="DocumentJournal"
"CommonModules"="CommonModule"; "CommonCommands"="CommonCommand"
"CommonForms"="CommonForm"; "CommonPictures"="CommonPicture"
"CommonTemplates"="CommonTemplate"; "CommonAttributes"="CommonAttribute"
"CommandGroups"="CommandGroup"; "Roles"="Role"
"SessionParameters"="SessionParameter"; "FilterCriteria"="FilterCriterion"
"XDTOPackages"="XDTOPackage"; "WebServices"="WebService"
"HTTPServices"="HTTPService"; "WSReferences"="WSReference"
"EventSubscriptions"="EventSubscription"; "ScheduledJobs"="ScheduledJob"
"SettingsStorages"="SettingsStorage"; "FunctionalOptions"="FunctionalOption"
"FunctionalOptionsParameters"="FunctionalOptionsParameter"
"DefinedTypes"="DefinedType"; "DocumentNumerators"="DocumentNumerator"
"Sequences"="Sequence"; "Subsystems"="Subsystem"
"StyleItems"="StyleItem"; "IntegrationServices"="IntegrationService"
# Russian singular
"Справочник"="Catalog"; "Каталог"="Catalog"; "Документ"="Document"
"Перечисление"="Enum"; "Константа"="Constant"
"Отчёт"="Report"; "Отчет"="Report"; "Обработка"="DataProcessor"
"РегистрСведений"="InformationRegister"; "РегистрНакопления"="AccumulationRegister"
"РегистрБухгалтерии"="AccountingRegister"
"РегистрРасчёта"="CalculationRegister"; "РегистрРасчета"="CalculationRegister"
"ПланСчетов"="ChartOfAccounts"; "ПланВидовХарактеристик"="ChartOfCharacteristicTypes"
"ПланВидовРасчёта"="ChartOfCalculationTypes"; "ПланВидовРасчета"="ChartOfCalculationTypes"
"БизнесПроцесс"="BusinessProcess"; "Задача"="Task"
"ПланОбмена"="ExchangePlan"; "ЖурналДокументов"="DocumentJournal"
"ОбщийМодуль"="CommonModule"; "ОбщаяКоманда"="CommonCommand"
"ОбщаяФорма"="CommonForm"; "ОбщаяКартинка"="CommonPicture"
"ОбщийМакет"="CommonTemplate"; "ОбщийРеквизит"="CommonAttribute"
"ГруппаКоманд"="CommandGroup"; "Роль"="Role"
"ПараметрСеанса"="SessionParameter"; "КритерийОтбора"="FilterCriterion"
"ПакетXDTO"="XDTOPackage"; "ВебСервис"="WebService"
"HTTPСервис"="HTTPService"; "WSСсылка"="WSReference"
"ПодпискаНаСобытие"="EventSubscription"; "РегламентноеЗадание"="ScheduledJob"
"ХранилищеНастроек"="SettingsStorage"; "ФункциональнаяОпция"="FunctionalOption"
"ПараметрФункциональныхОпций"="FunctionalOptionsParameter"
"ОпределяемыйТип"="DefinedType"; "Подсистема"="Subsystem"
"ЭлементСтиля"="StyleItem"; "СервисИнтеграции"="IntegrationService"
# Russian plural
"Справочники"="Catalog"; "Документы"="Document"; "Перечисления"="Enum"
"Константы"="Constant"; "Отчёты"="Report"; "Отчеты"="Report"
"Обработки"="DataProcessor"; "РегистрыСведений"="InformationRegister"
"РегистрыНакопления"="AccumulationRegister"; "РегистрыБухгалтерии"="AccountingRegister"
"РегистрыРасчёта"="CalculationRegister"; "РегистрыРасчета"="CalculationRegister"
"ПланыСчетов"="ChartOfAccounts"; "ПланыВидовХарактеристик"="ChartOfCharacteristicTypes"
"ПланыВидовРасчёта"="ChartOfCalculationTypes"; "ПланыВидовРасчета"="ChartOfCalculationTypes"
"БизнесПроцессы"="BusinessProcess"; "Задачи"="Task"
"ПланыОбмена"="ExchangePlan"; "ЖурналыДокументов"="DocumentJournal"
"ОбщиеМодули"="CommonModule"; "ОбщиеКоманды"="CommonCommand"
"ОбщиеФормы"="CommonForm"; "ОбщиеКартинки"="CommonPicture"
"ОбщиеМакеты"="CommonTemplate"; "ОбщиеРеквизиты"="CommonAttribute"
"ГруппыКоманд"="CommandGroup"; "Роли"="Role"
"ПараметрыСеанса"="SessionParameter"; "КритерииОтбора"="FilterCriterion"
"ПакетыXDTO"="XDTOPackage"; "ВебСервисы"="WebService"
"HTTPСервисы"="HTTPService"; "WSСсылки"="WSReference"
"ПодпискиНаСобытия"="EventSubscription"; "РегламентныеЗадания"="ScheduledJob"
"ХранилищаНастроек"="SettingsStorage"; "ФункциональныеОпции"="FunctionalOption"
"ОпределяемыеТипы"="DefinedType"; "Подсистемы"="Subsystem"
"ЭлементыСтиля"="StyleItem"; "СервисыИнтеграции"="IntegrationService"
}
function Normalize-ContentRef([string]$ref) {
if (-not $ref -or -not $ref.Contains('.')) { return $ref }
$dotIdx = $ref.IndexOf('.')
$typePart = $ref.Substring(0, $dotIdx)
$namePart = $ref.Substring($dotIdx + 1)
if ($script:contentTypeMap.ContainsKey($typePart)) {
$typePart = $script:contentTypeMap[$typePart]
}
return "$typePart.$namePart"
}
# --- Mode validation ---
if ($DefinitionFile -and $Operation) { Write-Error "Cannot use both -DefinitionFile and -Operation"; exit 1 }
if (-not $DefinitionFile -and -not $Operation) { Write-Error "Either -DefinitionFile or -Operation is required"; exit 1 }
# --- Resolve path ---
if (-not [System.IO.Path]::IsPathRooted($SubsystemPath)) {
$SubsystemPath = Join-Path (Get-Location).Path $SubsystemPath
}
if (Test-Path $SubsystemPath -PathType Container) {
$dirName = Split-Path $SubsystemPath -Leaf
$candidate = Join-Path $SubsystemPath "$dirName.xml"
$sibling = Join-Path (Split-Path $SubsystemPath) "$dirName.xml"
if (Test-Path $candidate) { $SubsystemPath = $candidate }
elseif (Test-Path $sibling) { $SubsystemPath = $sibling }
else { Write-Error "No $dirName.xml found in directory or as sibling"; exit 1 }
}
# File not found — check Dir/Name/Name.xml → Dir/Name.xml
if (-not (Test-Path $SubsystemPath)) {
$fn = [System.IO.Path]::GetFileNameWithoutExtension($SubsystemPath)
$pd = Split-Path $SubsystemPath
if ($fn -eq (Split-Path $pd -Leaf)) {
$c = Join-Path (Split-Path $pd) "$fn.xml"
if (Test-Path $c) { $SubsystemPath = $c }
}
}
if (-not (Test-Path $SubsystemPath)) { Write-Error "File not found: $SubsystemPath"; exit 1 }
$resolvedPath = (Resolve-Path $SubsystemPath).Path
$script:resolvedPath = $resolvedPath
# --- Support guard (Ext/ParentConfigurations.bin) ---
# See docs/1c-support-state-spec.md. Blocks edits of vendor objects "на замке" /
# read-only configs unless allowed. Trigger = bin present; reaction from
# .v8-project.json editingAllowedCheck (deny|warn|off, default deny). Never
# throws — guard errors degrade to allow.
function Get-RootUuid([string]$xmlPath) {
if (-not (Test-Path $xmlPath)) { return $null }
try {
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
$el = $mx.DocumentElement.FirstChild
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
} catch {}
return $null
}
function Find-V8Project([string]$startDir) {
$d = $startDir
for ($i = 0; $i -lt 20 -and $d; $i++) {
$pj = Join-Path $d ".v8-project.json"
if (Test-Path $pj) { return $pj }
$parent = [System.IO.Path]::GetDirectoryName($d)
if ($parent -eq $d) { break }
$d = $parent
}
return $null
}
function Get-EditMode([string]$cfgDir) {
try {
$pj = Find-V8Project (Get-Location).Path
if (-not $pj) { $pj = Find-V8Project $cfgDir }
if (-not $pj) { return 'deny' }
$proj = Get-Content -Raw $pj | ConvertFrom-Json
$cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
if ($proj.databases) {
foreach ($db in $proj.databases) {
if ($db.configSrc) {
$src = [System.IO.Path]::GetFullPath($db.configSrc).TrimEnd('\', '/')
if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar)) {
if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
}
}
}
}
if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
return 'deny'
} catch { return 'deny' }
}
function Assert-EditAllowed([string]$targetPath, [string]$require) {
try {
$rp = $targetPath
try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).Path } catch {}
$elemUuid = Get-RootUuid $rp
$cfgDir = $null; $binPath = $null
$d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
for ($i = 0; $i -lt 12 -and $d; $i++) {
if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
if (-not $cfgDir) {
$cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
}
if ($elemUuid -and $cfgDir) { break }
$parent = [System.IO.Path]::GetDirectoryName($d)
if ($parent -eq $d) { break }
$d = $parent
}
# New object (no element file): fall back to config root uuid.
if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
if (-not $binPath -or -not (Test-Path $binPath)) { return }
$bytes = [System.IO.File]::ReadAllBytes($binPath)
if ($bytes.Length -le 32) { return }
$start = 0
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
$text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
$hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
if (-not $hm.Success) { return }
$G = [int]$hm.Groups[1].Value
$K = [int]$hm.Groups[2].Value
if ($K -eq 0) { return }
$best = $null
if ($elemUuid) {
$u = [regex]::Escape($elemUuid.ToLower())
foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
$f1 = [int]$m.Groups[1].Value
if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
}
}
$blocked = $false; $code = ""; $reason = ""
if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
elseif ($require -eq 'removed') {
if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
}
else {
if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
}
if (-not $blocked) { return }
$mode = Get-EditMode $cfgDir
if ($mode -eq 'off') { return }
# Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
# latter throws and would be swallowed by this function's own catch.
if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
$head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
$cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
$offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
if ($code -eq "capability-off") {
$state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
$fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
} elseif ($code -eq "not-removed") {
$state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
$fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
} else {
$state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
$fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
}
[Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
exit 1
} catch { return }
}
Assert-EditAllowed $resolvedPath 'editable'
# --- Load XML with PreserveWhitespace ---
$script:xmlDoc = New-Object System.Xml.XmlDocument
$script:xmlDoc.PreserveWhitespace = $true
$script:xmlDoc.Load($resolvedPath)
$script:formatVersion = $script:xmlDoc.DocumentElement.GetAttribute("version")
if (-not $script:formatVersion) { $script:formatVersion = "2.17" }
$script:utf8Bom = New-Object System.Text.UTF8Encoding($true)
$script:addCount = 0
$script:removeCount = 0
$script:modifyCount = 0
function Info([string]$msg) { Write-Host "[INFO] $msg" }
function Warn([string]$msg) { Write-Host "[WARN] $msg" }
# --- Detect structure ---
$root = $script:xmlDoc.DocumentElement
$script:mdNs = "http://v8.1c.ru/8.3/MDClasses"
$script:xrNs = "http://v8.1c.ru/8.3/xcf/readable"
$script:xsiNs = "http://www.w3.org/2001/XMLSchema-instance"
$script:v8Ns = "http://v8.1c.ru/8.1/data/core"
$script:sub = $null
foreach ($child in $root.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Subsystem") {
$script:sub = $child; break
}
}
if (-not $script:sub) { Write-Error "No <Subsystem> element found"; exit 1 }
$script:propsEl = $null
$script:childObjsEl = $null
foreach ($child in $script:sub.ChildNodes) {
if ($child.NodeType -ne 'Element') { continue }
if ($child.LocalName -eq "Properties") { $script:propsEl = $child }
if ($child.LocalName -eq "ChildObjects") { $script:childObjsEl = $child }
}
$script:objName = ""
foreach ($child in $script:propsEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Name") {
$script:objName = $child.InnerText.Trim(); break
}
}
Info "Subsystem: $($script:objName)"
# --- XML manipulation helpers (from meta-edit pattern) ---
function Esc-Xml([string]$s) {
return $s.Replace('&','&amp;').Replace('<','&lt;').Replace('>','&gt;').Replace('"','&quot;')
}
function New-Guid-String {
return [System.Guid]::NewGuid().ToString()
}
function Write-ChildSubsystemStub([string]$childPath, [string]$childName, [string]$formatVersion, [System.Text.Encoding]$utf8Bom) {
$childUuid = New-Guid-String
$sb = New-Object System.Text.StringBuilder 2048
[void]$sb.AppendLine('<?xml version="1.0" encoding="UTF-8"?>')
[void]$sb.AppendLine("<MetaDataObject xmlns=`"http://v8.1c.ru/8.3/MDClasses`" xmlns:app=`"http://v8.1c.ru/8.2/managed-application/core`" xmlns:cfg=`"http://v8.1c.ru/8.1/data/enterprise/current-config`" xmlns:cmi=`"http://v8.1c.ru/8.2/managed-application/cmi`" xmlns:ent=`"http://v8.1c.ru/8.1/data/enterprise`" xmlns:lf=`"http://v8.1c.ru/8.2/managed-application/logform`" xmlns:style=`"http://v8.1c.ru/8.1/data/ui/style`" xmlns:sys=`"http://v8.1c.ru/8.1/data/ui/fonts/system`" xmlns:v8=`"http://v8.1c.ru/8.1/data/core`" xmlns:v8ui=`"http://v8.1c.ru/8.1/data/ui`" xmlns:web=`"http://v8.1c.ru/8.1/data/ui/colors/web`" xmlns:win=`"http://v8.1c.ru/8.1/data/ui/colors/windows`" xmlns:xen=`"http://v8.1c.ru/8.3/xcf/enums`" xmlns:xpr=`"http://v8.1c.ru/8.3/xcf/predef`" xmlns:xr=`"http://v8.1c.ru/8.3/xcf/readable`" xmlns:xs=`"http://www.w3.org/2001/XMLSchema`" xmlns:xsi=`"http://www.w3.org/2001/XMLSchema-instance`" version=`"$formatVersion`">")
[void]$sb.AppendLine("`t<Subsystem uuid=`"$childUuid`">")
[void]$sb.AppendLine("`t`t<Properties>")
[void]$sb.AppendLine("`t`t`t<Name>$(Esc-Xml $childName)</Name>")
[void]$sb.AppendLine("`t`t`t<Synonym/>")
[void]$sb.AppendLine("`t`t`t<Comment/>")
[void]$sb.AppendLine("`t`t`t<IncludeHelpInContents>true</IncludeHelpInContents>")
[void]$sb.AppendLine("`t`t`t<IncludeInCommandInterface>true</IncludeInCommandInterface>")
[void]$sb.AppendLine("`t`t`t<UseOneCommand>false</UseOneCommand>")
[void]$sb.AppendLine("`t`t`t<Explanation/>")
[void]$sb.AppendLine("`t`t`t<Picture/>")
[void]$sb.AppendLine("`t`t`t<Content/>")
[void]$sb.AppendLine("`t`t</Properties>")
[void]$sb.AppendLine("`t`t<ChildObjects/>")
[void]$sb.AppendLine("`t</Subsystem>")
[void]$sb.AppendLine('</MetaDataObject>')
[System.IO.File]::WriteAllText($childPath, $sb.ToString(), $utf8Bom)
}
function Import-Fragment([string]$xmlString) {
$wrapper = "<_W xmlns=`"$($script:mdNs)`" xmlns:xsi=`"$($script:xsiNs)`" xmlns:v8=`"$($script:v8Ns)`" xmlns:xr=`"$($script:xrNs)`" xmlns:xs=`"http://www.w3.org/2001/XMLSchema`">$xmlString</_W>"
$frag = New-Object System.Xml.XmlDocument
$frag.PreserveWhitespace = $true
$frag.LoadXml($wrapper)
$nodes = @()
foreach ($child in $frag.DocumentElement.ChildNodes) {
if ($child.NodeType -eq 'Element') {
$nodes += $script:xmlDoc.ImportNode($child, $true)
}
}
return ,$nodes
}
function Get-ChildIndent($container) {
foreach ($child in $container.ChildNodes) {
if ($child.NodeType -eq 'Whitespace' -or $child.NodeType -eq 'SignificantWhitespace') {
if ($child.Value -match '^\r?\n(\t+)$') { return $Matches[1] }
if ($child.Value -match '^\r?\n(\t+)') { return $Matches[1] }
}
}
$depth = 0; $current = $container
while ($current -and $current -ne $script:xmlDoc.DocumentElement) { $depth++; $current = $current.ParentNode }
return "`t" * ($depth + 1)
}
function Insert-BeforeElement($container, $newNode, $refNode, $childIndent) {
$ws = $script:xmlDoc.CreateWhitespace("`r`n$childIndent")
if ($refNode) {
$container.InsertBefore($ws, $refNode) | Out-Null
$container.InsertBefore($newNode, $ws) | Out-Null
} else {
$trailing = $container.LastChild
if ($trailing -and ($trailing.NodeType -eq 'Whitespace' -or $trailing.NodeType -eq 'SignificantWhitespace')) {
$container.InsertBefore($ws, $trailing) | Out-Null
$container.InsertBefore($newNode, $trailing) | Out-Null
} else {
$container.AppendChild($ws) | Out-Null
$container.AppendChild($newNode) | Out-Null
$parentIndent = if ($childIndent.Length -gt 1) { $childIndent.Substring(0, $childIndent.Length - 1) } else { "" }
$closeWs = $script:xmlDoc.CreateWhitespace("`r`n$parentIndent")
$container.AppendChild($closeWs) | Out-Null
}
}
}
function Remove-NodeWithWhitespace($node) {
$parent = $node.ParentNode
$prev = $node.PreviousSibling
$next = $node.NextSibling
if ($prev -and ($prev.NodeType -eq 'Whitespace' -or $prev.NodeType -eq 'SignificantWhitespace')) {
$parent.RemoveChild($prev) | Out-Null
} elseif ($next -and ($next.NodeType -eq 'Whitespace' -or $next.NodeType -eq 'SignificantWhitespace')) {
$parent.RemoveChild($next) | Out-Null
}
$parent.RemoveChild($node) | Out-Null
}
function Expand-SelfClosingElement($container, $parentIndent) {
# If the element is self-closing (empty), add whitespace for children
if (-not $container.HasChildNodes -or $container.IsEmpty) {
$childIndent = "$parentIndent`t"
# The element is self-closing; we need to add something to make it non-empty
# Adding a whitespace node will force opening+closing tags
$closeWs = $script:xmlDoc.CreateWhitespace("`r`n$parentIndent")
$container.AppendChild($closeWs) | Out-Null
}
}
# --- Parse value: string or JSON array ---
function Parse-ValueList([string]$val) {
$val = $val.Trim()
if ($val.StartsWith("[")) {
$arr = $val | ConvertFrom-Json
$result = @(); foreach ($item in $arr) { $result += "$item" }
return ,$result
}
return @($val)
}
# --- Operations ---
function Do-AddContent([string[]]$items) {
$contentEl = $null
foreach ($child in $script:propsEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Content") {
$contentEl = $child; break
}
}
if (-not $contentEl) { Write-Error "No <Content> element found"; exit 1 }
# Get existing items for dedup
$existing = @()
foreach ($child in $contentEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Item") {
$existing += $child.InnerText.Trim()
}
}
# Determine indentation
$propsIndent = Get-ChildIndent $script:propsEl
$contentIndent = "$propsIndent`t"
# Expand self-closing if needed
if (-not $contentEl.HasChildNodes -or $contentEl.IsEmpty) {
Expand-SelfClosingElement $contentEl $propsIndent
$contentIndent = "$propsIndent`t"
} else {
$contentIndent = Get-ChildIndent $contentEl
}
foreach ($rawItem in $items) {
$item = Normalize-ContentRef $rawItem
if ($item -ne $rawItem) { Write-Host "[NORM] Content: $rawItem -> $item" }
if ($item -in $existing) {
Warn "Content already contains: $item"
continue
}
$fragXml = "<xr:Item xsi:type=`"xr:MDObjectRef`">$item</xr:Item>"
$nodes = Import-Fragment $fragXml
if ($nodes.Count -gt 0) {
Insert-BeforeElement $contentEl $nodes[0] $null $contentIndent
$script:addCount++
Info "Added content: $item"
}
}
}
function Do-RemoveContent([string[]]$items) {
$contentEl = $null
foreach ($child in $script:propsEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Content") {
$contentEl = $child; break
}
}
if (-not $contentEl) { Write-Error "No <Content> element found"; exit 1 }
foreach ($item in $items) {
$found = $false
foreach ($child in @($contentEl.ChildNodes)) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Item" -and $child.InnerText.Trim() -eq $item) {
Remove-NodeWithWhitespace $child
$script:removeCount++
Info "Removed content: $item"
$found = $true
break
}
}
if (-not $found) { Warn "Content item not found: $item" }
}
}
function Do-AddChild([string]$childName) {
if (-not $script:childObjsEl) { Write-Error "No <ChildObjects> element found"; exit 1 }
# Dedup check
foreach ($child in $script:childObjsEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Subsystem" -and $child.InnerText.Trim() -eq $childName) {
Warn "ChildObjects already contains: $childName"
return
}
}
$subIndent = Get-ChildIndent $script:sub
if (-not $script:childObjsEl.HasChildNodes -or $script:childObjsEl.IsEmpty) {
Expand-SelfClosingElement $script:childObjsEl $subIndent
}
$childIndent = Get-ChildIndent $script:childObjsEl
$newEl = $script:xmlDoc.CreateElement("Subsystem", $script:mdNs)
$newEl.InnerText = $childName
Insert-BeforeElement $script:childObjsEl $newEl $null $childIndent
$script:addCount++
Info "Added child subsystem: $childName"
# Write stub XML for the new child if it doesn't exist yet
$parentDir = [System.IO.Path]::GetDirectoryName($script:resolvedPath)
$parentBaseName = [System.IO.Path]::GetFileNameWithoutExtension($script:resolvedPath)
$childSubsDir = Join-Path (Join-Path $parentDir $parentBaseName) "Subsystems"
if (-not (Test-Path $childSubsDir)) {
New-Item -ItemType Directory -Path $childSubsDir -Force | Out-Null
Info "Created directory: $childSubsDir"
}
$childXml = Join-Path $childSubsDir "$childName.xml"
if (-not (Test-Path $childXml)) {
Write-ChildSubsystemStub $childXml $childName $script:formatVersion $script:utf8Bom
Info "Created stub: $childXml"
}
}
function Do-RemoveChild([string]$childName) {
if (-not $script:childObjsEl) { Write-Error "No <ChildObjects> element found"; exit 1 }
$found = $false
foreach ($child in @($script:childObjsEl.ChildNodes)) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Subsystem" -and $child.InnerText.Trim() -eq $childName) {
Remove-NodeWithWhitespace $child
$script:removeCount++
Info "Removed child subsystem: $childName"
$found = $true
break
}
}
if (-not $found) { Warn "Child subsystem not found: $childName" }
}
function Do-SetProperty([string]$jsonVal) {
$propDef = $jsonVal | ConvertFrom-Json
$propName = "$($propDef.name)"
$propValue = "$($propDef.value)"
$propEl = $null
foreach ($child in $script:propsEl.ChildNodes) {
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq $propName) {
$propEl = $child; break
}
}
if (-not $propEl) {
Write-Error "Property '$propName' not found in Properties"
exit 1
}
$boolProps = @("IncludeInCommandInterface","UseOneCommand","IncludeHelpInContents")
if ($propName -in $boolProps) {
$propEl.InnerText = $propValue.ToLower()
$script:modifyCount++
Info "Set $propName = $propValue"
return
}
$mlProps = @("Synonym","Explanation")
if ($propName -in $mlProps) {
if (-not $propValue) {
# Clear - make self-closing
$propEl.InnerXml = ""
$script:modifyCount++
Info "Cleared $propName"
} else {
$indent = Get-ChildIndent $script:propsEl
$mlXml = "`r`n$indent`t<v8:item>`r`n$indent`t`t<v8:lang>ru</v8:lang>`r`n$indent`t`t<v8:content>$([System.Security.SecurityElement]::Escape($propValue))</v8:content>`r`n$indent`t</v8:item>`r`n$indent"
$propEl.InnerXml = $mlXml
$script:modifyCount++
Info "Set $propName = `"$propValue`""
}
return
}
if ($propName -eq "Comment") {
if (-not $propValue) { $propEl.InnerXml = "" }
else { $propEl.InnerText = $propValue }
$script:modifyCount++
Info "Set Comment = `"$propValue`""
return
}
if ($propName -eq "Picture") {
if (-not $propValue) {
$propEl.InnerXml = ""
} else {
$indent = Get-ChildIndent $script:propsEl
$picXml = "`r`n$indent`t<xr:Ref>$propValue</xr:Ref>`r`n$indent`t<xr:LoadTransparent>false</xr:LoadTransparent>`r`n$indent"
$propEl.InnerXml = $picXml
}
$script:modifyCount++
Info "Set Picture = `"$propValue`""
return
}
# Generic text property
$propEl.InnerText = $propValue
$script:modifyCount++
Info "Set $propName = `"$propValue`""
}
# --- Execute operations ---
$operations = @()
if ($DefinitionFile) {
if (-not [System.IO.Path]::IsPathRooted($DefinitionFile)) {
$DefinitionFile = Join-Path (Get-Location).Path $DefinitionFile
}
$jsonText = Get-Content -Raw -Encoding UTF8 $DefinitionFile
$ops = $jsonText | ConvertFrom-Json
if ($ops -is [System.Array]) {
foreach ($op in $ops) { $operations += $op }
} else {
$operations += $ops
}
} else {
$operations += @{ operation = $Operation; value = $Value }
}
foreach ($op in $operations) {
$opName = if ($op.operation) { "$($op.operation)" } else { "$Operation" }
$opValue = if ($op.value) { "$($op.value)" } else { "$Value" }
switch ($opName) {
"add-content" { Do-AddContent (Parse-ValueList $opValue) }
"remove-content" { Do-RemoveContent (Parse-ValueList $opValue) }
"add-child" { Do-AddChild $opValue }
"remove-child" { Do-RemoveChild $opValue }
"set-property" { Do-SetProperty $opValue }
default { Write-Error "Unknown operation: $opName"; exit 1 }
}
}
# --- Save ---
$settings = New-Object System.Xml.XmlWriterSettings
$settings.Encoding = New-Object System.Text.UTF8Encoding($true)
$settings.Indent = $false
$settings.NewLineHandling = [System.Xml.NewLineHandling]::None
$memStream = New-Object System.IO.MemoryStream
$writer = [System.Xml.XmlWriter]::Create($memStream, $settings)
$script:xmlDoc.Save($writer)
$writer.Flush(); $writer.Close()
$bytes = $memStream.ToArray()
$memStream.Close()
$text = [System.Text.Encoding]::UTF8.GetString($bytes)
if ($text.Length -gt 0 -and $text[0] -eq [char]0xFEFF) { $text = $text.Substring(1) }
$text = $text.Replace('encoding="utf-8"', 'encoding="UTF-8"')
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
[System.IO.File]::WriteAllText($resolvedPath, $text, $utf8Bom)
Info "Saved: $resolvedPath"
# --- Auto-validate ---
if (-not $NoValidate) {
$validateScript = Join-Path (Join-Path $PSScriptRoot "..\..\subsystem-validate") "scripts\subsystem-validate.ps1"
$validateScript = [System.IO.Path]::GetFullPath($validateScript)
if (Test-Path $validateScript) {
Write-Host ""
Write-Host "--- Running subsystem-validate ---"
& powershell.exe -NoProfile -File $validateScript -SubsystemPath $resolvedPath
}
}
# --- Summary ---
Write-Host ""
Write-Host "=== subsystem-edit summary ==="
Write-Host " Subsystem: $($script:objName)"
Write-Host " Added: $($script:addCount)"
Write-Host " Removed: $($script:removeCount)"
Write-Host " Modified: $($script:modifyCount)"
exit 0
@@ -1,780 +0,0 @@
#!/usr/bin/env python3
# subsystem-edit v1.5 — Edit existing 1C subsystem XML
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import json
import os
import re
import subprocess
import sys
import uuid
from lxml import etree
# ============================================================
# Support guard (Ext/ParentConfigurations.bin) — see docs/1c-support-state-spec.md
# Blocks edits of vendor objects "на замке" / read-only configs. Trigger = bin
# present; reaction from .v8-project.json editingAllowedCheck (deny|warn|off,
# default deny). Never throws (except sys.exit on deny) — errors degrade to allow.
# ============================================================
def _sg_root_uuid(xml_path):
if not os.path.isfile(xml_path):
return None
try:
mx = etree.parse(xml_path).getroot()
for child in mx:
if isinstance(child.tag, str) and child.get("uuid"):
return child.get("uuid")
except Exception:
return None
return None
def _sg_find_v8project(start_dir):
d = start_dir
for _ in range(20):
if not d:
break
pj = os.path.join(d, ".v8-project.json")
if os.path.isfile(pj):
return pj
parent = os.path.dirname(d)
if parent == d:
break
d = parent
return None
def _sg_get_edit_mode(cfg_dir):
try:
pj = _sg_find_v8project(os.getcwd()) or _sg_find_v8project(cfg_dir)
if not pj:
return "deny"
proj = json.loads(open(pj, encoding="utf-8-sig").read())
cfg_full = os.path.normcase(os.path.abspath(cfg_dir)).rstrip("\\/")
for db in proj.get("databases", []):
src = db.get("configSrc")
if src:
src_full = os.path.normcase(os.path.abspath(src)).rstrip("\\/")
if cfg_full == src_full or cfg_full.startswith(src_full + os.sep):
if db.get("editingAllowedCheck"):
return db["editingAllowedCheck"]
if proj.get("editingAllowedCheck"):
return proj["editingAllowedCheck"]
return "deny"
except Exception:
return "deny"
def assert_edit_allowed(target_path, require):
try:
rp = os.path.abspath(target_path)
elem_uuid = _sg_root_uuid(rp)
cfg_dir = None
bin_path = None
d = rp if os.path.isdir(rp) else os.path.dirname(rp)
for _ in range(12):
if not d:
break
if not elem_uuid:
elem_uuid = _sg_root_uuid(d + ".xml")
if not cfg_dir:
cand = os.path.join(d, "Ext", "ParentConfigurations.bin")
if os.path.exists(cand) or os.path.exists(os.path.join(d, "Configuration.xml")):
cfg_dir = d
bin_path = cand
if elem_uuid and cfg_dir:
break
parent = os.path.dirname(d)
if parent == d:
break
d = parent
if not elem_uuid and cfg_dir:
elem_uuid = _sg_root_uuid(os.path.join(cfg_dir, "Configuration.xml"))
if not bin_path or not os.path.exists(bin_path):
return
data = open(bin_path, "rb").read()
if len(data) <= 32:
return
if data[:3] == b"\xef\xbb\xbf":
data = data[3:]
text = data.decode("utf-8", "replace")
h = re.match(r"\{6,(\d+),(\d+),", text)
if not h:
return
g = int(h.group(1))
k = int(h.group(2))
if k == 0:
return
best = None
if elem_uuid:
for m in re.finditer(r"([0-2]),0," + re.escape(elem_uuid.lower()), text):
f1 = int(m.group(1))
if best is None or f1 < best:
best = f1
blocked = False
code = ""
reason = ""
if g == 1:
blocked = True
code = "capability-off"
reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)"
elif require == "removed":
if best is not None and best != 2:
blocked = True
code = "not-removed"
reason = "объект не снят с поддержки — удаление сломает обновления"
else:
if best is not None and best == 0:
blocked = True
code = "locked"
reason = "объект на замке — редактирование сломает обновления"
if not blocked:
return
mode = _sg_get_edit_mode(cfg_dir)
if mode == "off":
return
if mode == "warn":
sys.stderr.write(f"[support-guard] ПРЕДУПРЕЖДЕНИЕ: {reason}. Цель: {rp}\n")
return
head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
off_note = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
if code == "capability-off":
state = f"Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «{rp}» редактировать нельзя."
fix = (
"Либо снять защиту явно (навык support-edit, два шага):\n"
f' 1. support-edit -Path "{cfg_dir}" -Capability on — включить возможность изменения (объекты пока остаются на замке);\n'
f' 2. support-edit -Path "{rp}" -Set editable — открыть этот объект для редактирования.\n'
" Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
)
elif code == "not-removed":
state = f"Состояние: объект «{rp}» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
fix = (
"Либо сначала снять объект с поддержки, затем удалять:\n"
f' support-edit -Path "{rp}" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно.'
)
else:
state = f"Состояние: объект «{rp}» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
fix = (
"Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):\n"
f' support-edit -Path "{rp}" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);\n'
f' support-edit -Path "{rp}" -Set off-support — снять с поддержки: обновления по объекту больше не приходят.'
)
sys.stderr.write(head + "\n" + state + "\n" + cfe + "\n" + fix + "\n" + off_note + "\n")
sys.exit(1)
except SystemExit:
raise
except Exception:
return
def new_uuid():
return str(uuid.uuid4())
def esc_xml(s):
return s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;')
def write_utf8_bom(path, content):
with open(path, 'w', encoding='utf-8-sig', newline='') as f:
f.write(content)
def write_child_subsystem_stub(child_path, child_name, format_version):
child_uuid = new_uuid()
lines = []
lines.append('<?xml version="1.0" encoding="UTF-8"?>')
lines.append(
'<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" '
'xmlns:app="http://v8.1c.ru/8.2/managed-application/core" '
'xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" '
'xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" '
'xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" '
'xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" '
'xmlns:style="http://v8.1c.ru/8.1/data/ui/style" '
'xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" '
'xmlns:v8="http://v8.1c.ru/8.1/data/core" '
'xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" '
'xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" '
'xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" '
'xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" '
'xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" '
'xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" '
'xmlns:xs="http://www.w3.org/2001/XMLSchema" '
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '
f'version="{format_version}">'
)
lines.append(f'\t<Subsystem uuid="{child_uuid}">')
lines.append('\t\t<Properties>')
lines.append(f'\t\t\t<Name>{esc_xml(child_name)}</Name>')
lines.append('\t\t\t<Synonym/>')
lines.append('\t\t\t<Comment/>')
lines.append('\t\t\t<IncludeHelpInContents>true</IncludeHelpInContents>')
lines.append('\t\t\t<IncludeInCommandInterface>true</IncludeInCommandInterface>')
lines.append('\t\t\t<UseOneCommand>false</UseOneCommand>')
lines.append('\t\t\t<Explanation/>')
lines.append('\t\t\t<Picture/>')
lines.append('\t\t\t<Content/>')
lines.append('\t\t</Properties>')
lines.append('\t\t<ChildObjects/>')
lines.append('\t</Subsystem>')
lines.append('</MetaDataObject>')
write_utf8_bom(child_path, '\n'.join(lines) + '\n')
MD_NS = "http://v8.1c.ru/8.3/MDClasses"
XR_NS = "http://v8.1c.ru/8.3/xcf/readable"
XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"
V8_NS = "http://v8.1c.ru/8.1/data/core"
XS_NS = "http://www.w3.org/2001/XMLSchema"
NSMAP_WRAPPER = {
None: MD_NS,
"xsi": XSI_NS,
"v8": V8_NS,
"xr": XR_NS,
"xs": XS_NS,
}
CONTENT_TYPE_MAP = {
'Catalogs': 'Catalog', 'Documents': 'Document', 'Enums': 'Enum',
'Constants': 'Constant', 'Reports': 'Report', 'DataProcessors': 'DataProcessor',
'InformationRegisters': 'InformationRegister', 'AccumulationRegisters': 'AccumulationRegister',
'AccountingRegisters': 'AccountingRegister', 'CalculationRegisters': 'CalculationRegister',
'ChartsOfAccounts': 'ChartOfAccounts', 'ChartsOfCharacteristicTypes': 'ChartOfCharacteristicTypes',
'ChartsOfCalculationTypes': 'ChartOfCalculationTypes',
'BusinessProcesses': 'BusinessProcess', 'Tasks': 'Task',
'ExchangePlans': 'ExchangePlan', 'DocumentJournals': 'DocumentJournal',
'CommonModules': 'CommonModule', 'CommonCommands': 'CommonCommand',
'CommonForms': 'CommonForm', 'CommonPictures': 'CommonPicture',
'CommonTemplates': 'CommonTemplate', 'CommonAttributes': 'CommonAttribute',
'CommandGroups': 'CommandGroup', 'Roles': 'Role',
'SessionParameters': 'SessionParameter', 'FilterCriteria': 'FilterCriterion',
'XDTOPackages': 'XDTOPackage', 'WebServices': 'WebService',
'HTTPServices': 'HTTPService', 'WSReferences': 'WSReference',
'EventSubscriptions': 'EventSubscription', 'ScheduledJobs': 'ScheduledJob',
'SettingsStorages': 'SettingsStorage', 'FunctionalOptions': 'FunctionalOption',
'FunctionalOptionsParameters': 'FunctionalOptionsParameter',
'DefinedTypes': 'DefinedType', 'DocumentNumerators': 'DocumentNumerator',
'Sequences': 'Sequence', 'Subsystems': 'Subsystem',
'StyleItems': 'StyleItem', 'IntegrationServices': 'IntegrationService',
# Russian singular
'Справочник': 'Catalog', 'Каталог': 'Catalog', 'Документ': 'Document',
'Перечисление': 'Enum', 'Константа': 'Constant',
'Отчёт': 'Report', 'Отчет': 'Report', 'Обработка': 'DataProcessor',
'РегистрСведений': 'InformationRegister', 'РегистрНакопления': 'AccumulationRegister',
'РегистрБухгалтерии': 'AccountingRegister',
'РегистрРасчёта': 'CalculationRegister', 'РегистрРасчета': 'CalculationRegister',
'ПланСчетов': 'ChartOfAccounts', 'ПланВидовХарактеристик': 'ChartOfCharacteristicTypes',
'ПланВидовРасчёта': 'ChartOfCalculationTypes', 'ПланВидовРасчета': 'ChartOfCalculationTypes',
'БизнесПроцесс': 'BusinessProcess', 'Задача': 'Task',
'ПланОбмена': 'ExchangePlan', 'ЖурналДокументов': 'DocumentJournal',
'ОбщийМодуль': 'CommonModule', 'ОбщаяКоманда': 'CommonCommand',
'ОбщаяФорма': 'CommonForm', 'ОбщаяКартинка': 'CommonPicture',
'ОбщийМакет': 'CommonTemplate', 'ОбщийРеквизит': 'CommonAttribute',
'ГруппаКоманд': 'CommandGroup', 'Роль': 'Role',
'ПараметрСеанса': 'SessionParameter', 'КритерийОтбора': 'FilterCriterion',
'ПакетXDTO': 'XDTOPackage', 'ВебСервис': 'WebService',
'HTTPСервис': 'HTTPService', 'WSСсылка': 'WSReference',
'ПодпискаНаСобытие': 'EventSubscription', 'РегламентноеЗадание': 'ScheduledJob',
'ХранилищеНастроек': 'SettingsStorage', 'ФункциональнаяОпция': 'FunctionalOption',
'ПараметрФункциональныхОпций': 'FunctionalOptionsParameter',
'ОпределяемыйТип': 'DefinedType', 'Подсистема': 'Subsystem',
'ЭлементСтиля': 'StyleItem', 'СервисИнтеграции': 'IntegrationService',
# Russian plural
'Справочники': 'Catalog', 'Документы': 'Document', 'Перечисления': 'Enum',
'Константы': 'Constant', 'Отчёты': 'Report', 'Отчеты': 'Report',
'Обработки': 'DataProcessor', 'РегистрыСведений': 'InformationRegister',
'РегистрыНакопления': 'AccumulationRegister', 'РегистрыБухгалтерии': 'AccountingRegister',
'РегистрыРасчёта': 'CalculationRegister', 'РегистрыРасчета': 'CalculationRegister',
'ПланыСчетов': 'ChartOfAccounts', 'ПланыВидовХарактеристик': 'ChartOfCharacteristicTypes',
'ПланыВидовРасчёта': 'ChartOfCalculationTypes', 'ПланыВидовРасчета': 'ChartOfCalculationTypes',
'БизнесПроцессы': 'BusinessProcess', 'Задачи': 'Task',
'ПланыОбмена': 'ExchangePlan', 'ЖурналыДокументов': 'DocumentJournal',
'ОбщиеМодули': 'CommonModule', 'ОбщиеКоманды': 'CommonCommand',
'ОбщиеФормы': 'CommonForm', 'ОбщиеКартинки': 'CommonPicture',
'ОбщиеМакеты': 'CommonTemplate', 'ОбщиеРеквизиты': 'CommonAttribute',
'ГруппыКоманд': 'CommandGroup', 'Роли': 'Role',
'ПараметрыСеанса': 'SessionParameter', 'КритерииОтбора': 'FilterCriterion',
'ПакетыXDTO': 'XDTOPackage', 'ВебСервисы': 'WebService',
'HTTPСервисы': 'HTTPService', 'WSСсылки': 'WSReference',
'ПодпискиНаСобытия': 'EventSubscription', 'РегламентныеЗадания': 'ScheduledJob',
'ХранилищаНастроек': 'SettingsStorage', 'ФункциональныеОпции': 'FunctionalOption',
'ОпределяемыеТипы': 'DefinedType', 'Подсистемы': 'Subsystem',
'ЭлементыСтиля': 'StyleItem', 'СервисыИнтеграции': 'IntegrationService',
}
def normalize_content_ref(ref):
if not ref or '.' not in ref:
return ref
dot_idx = ref.index('.')
type_part = ref[:dot_idx]
name_part = ref[dot_idx + 1:]
if type_part in CONTENT_TYPE_MAP:
type_part = CONTENT_TYPE_MAP[type_part]
return f'{type_part}.{name_part}'
def localname(el):
return etree.QName(el.tag).localname
def info(msg):
print(f"[INFO] {msg}")
def warn(msg):
print(f"[WARN] {msg}")
def get_child_indent(container):
"""Detect indentation of children inside a container element."""
if container.text and "\n" in container.text:
after_nl = container.text.rsplit("\n", 1)[-1]
if after_nl and not after_nl.strip():
return after_nl
for child in container:
if child.tail and "\n" in child.tail:
after_nl = child.tail.rsplit("\n", 1)[-1]
if after_nl and not after_nl.strip():
return after_nl
# Fallback: count depth
depth = 0
current = container
while current is not None:
depth += 1
current = current.getparent()
return "\t" * depth
def insert_before_closing(container, new_el, child_indent):
"""Insert new_el before the closing tag of container, with proper indentation."""
children = list(container)
if len(children) == 0:
# Empty element: set text to newline+indent, tail of new_el to newline+parent_indent
parent_indent = child_indent[:-1] if len(child_indent) > 0 else ""
container.text = "\r\n" + child_indent
new_el.tail = "\r\n" + parent_indent
container.append(new_el)
else:
last = children[-1]
new_el.tail = last.tail
last.tail = "\r\n" + child_indent
container.append(new_el)
def remove_with_indent(el):
"""Remove element and clean up surrounding whitespace."""
parent = el.getparent()
prev = el.getprevious()
if prev is not None:
# Transfer el.tail to prev.tail
if el.tail and el.tail.strip() == "":
pass # just drop extra whitespace
prev.tail = el.tail if el.tail and el.tail.strip() else (prev.tail or "")
# Actually try to keep the prev's tail as the closing indent
# Better approach: set prev.tail to what el.tail was (newline+indent of next or closing)
if el.tail:
prev.tail = el.tail
else:
# First child: adjust parent.text
if el.tail:
parent.text = el.tail
parent.remove(el)
def expand_self_closing(container, parent_indent):
"""If container is self-closing (no children, no text), add closing whitespace."""
if len(container) == 0 and not (container.text and container.text.strip()):
container.text = "\r\n" + parent_indent
def import_fragment(xml_string, doc_root):
"""Parse an XML fragment in the MD namespace context and return elements."""
wrapper = (
f'<_W xmlns="{MD_NS}" xmlns:xsi="{XSI_NS}" xmlns:v8="{V8_NS}" '
f'xmlns:xr="{XR_NS}" xmlns:xs="{XS_NS}">{xml_string}</_W>'
)
frag = etree.fromstring(wrapper.encode("utf-8"))
nodes = []
for child in frag:
nodes.append(child)
return nodes
def parse_value_list(val):
"""Parse a string or JSON array into a list of strings."""
val = val.strip()
if val.startswith("["):
arr = json.loads(val)
return [str(item) for item in arr]
return [val]
def save_xml_bom(tree, path):
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
xml_bytes = xml_bytes.replace(b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" encoding="utf-8"?>')
if not xml_bytes.endswith(b"\n"):
xml_bytes += b"\n"
with open(path, "wb") as f:
f.write(b"\xef\xbb\xbf")
f.write(xml_bytes)
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(description="Edit existing 1C subsystem XML", allow_abbrev=False)
parser.add_argument("-SubsystemPath", "-Path", required=True)
parser.add_argument("-DefinitionFile", default=None)
parser.add_argument("-Operation", default=None, choices=["add-content", "remove-content", "add-child", "remove-child", "set-property"])
parser.add_argument("-Value", default=None)
parser.add_argument("-NoValidate", action="store_true")
args = parser.parse_args()
# --- Mode validation ---
if args.DefinitionFile and args.Operation:
print("Cannot use both -DefinitionFile and -Operation", file=sys.stderr)
sys.exit(1)
if not args.DefinitionFile and not args.Operation:
print("Either -DefinitionFile or -Operation is required", file=sys.stderr)
sys.exit(1)
# --- Resolve path ---
subsystem_path = args.SubsystemPath
if not os.path.isabs(subsystem_path):
subsystem_path = os.path.join(os.getcwd(), subsystem_path)
if os.path.isdir(subsystem_path):
dir_name = os.path.basename(subsystem_path)
candidate = os.path.join(subsystem_path, f"{dir_name}.xml")
sibling = os.path.join(os.path.dirname(subsystem_path), f"{dir_name}.xml")
if os.path.isfile(candidate):
subsystem_path = candidate
elif os.path.isfile(sibling):
subsystem_path = sibling
else:
print(f"No {dir_name}.xml found in directory or as sibling", file=sys.stderr)
sys.exit(1)
if not os.path.isfile(subsystem_path):
fn = os.path.splitext(os.path.basename(subsystem_path))[0]
pd = os.path.dirname(subsystem_path)
if fn == os.path.basename(pd):
c = os.path.join(os.path.dirname(pd), f"{fn}.xml")
if os.path.isfile(c):
subsystem_path = c
if not os.path.isfile(subsystem_path):
print(f"File not found: {subsystem_path}", file=sys.stderr)
sys.exit(1)
resolved_path = os.path.abspath(subsystem_path)
assert_edit_allowed(resolved_path, "editable")
# --- Load XML ---
xml_parser = etree.XMLParser(remove_blank_text=False)
tree = etree.parse(resolved_path, xml_parser)
xml_root = tree.getroot()
format_version = xml_root.get("version") or "2.17"
add_count = 0
remove_count = 0
modify_count = 0
# --- Detect structure ---
sub = None
for child in xml_root:
if isinstance(child.tag, str) and localname(child) == "Subsystem":
sub = child
break
if sub is None:
print("No <Subsystem> element found", file=sys.stderr)
sys.exit(1)
props_el = None
child_objs_el = None
for child in sub:
if not isinstance(child.tag, str):
continue
if localname(child) == "Properties":
props_el = child
if localname(child) == "ChildObjects":
child_objs_el = child
obj_name = ""
if props_el is not None:
for child in props_el:
if isinstance(child.tag, str) and localname(child) == "Name":
obj_name = (child.text or "").strip()
break
info(f"Subsystem: {obj_name}")
# --- Operations ---
def do_add_content(items):
nonlocal add_count
content_el = None
for child in props_el:
if isinstance(child.tag, str) and localname(child) == "Content":
content_el = child
break
if content_el is None:
print("No <Content> element found", file=sys.stderr)
sys.exit(1)
existing = set()
for child in content_el:
if isinstance(child.tag, str) and localname(child) == "Item":
existing.add((child.text or "").strip())
props_indent = get_child_indent(props_el)
if len(content_el) == 0 and not (content_el.text and content_el.text.strip()):
expand_self_closing(content_el, props_indent)
content_indent = get_child_indent(content_el)
for raw_item in items:
item = normalize_content_ref(raw_item)
if item != raw_item:
print(f'[NORM] Content: {raw_item} -> {item}')
if item in existing:
warn(f"Content already contains: {item}")
continue
frag_xml = f'<xr:Item xsi:type="xr:MDObjectRef">{item}</xr:Item>'
nodes = import_fragment(frag_xml, xml_root)
if nodes:
insert_before_closing(content_el, nodes[0], content_indent)
add_count += 1
info(f"Added content: {item}")
def do_remove_content(items):
nonlocal remove_count
content_el = None
for child in props_el:
if isinstance(child.tag, str) and localname(child) == "Content":
content_el = child
break
if content_el is None:
print("No <Content> element found", file=sys.stderr)
sys.exit(1)
for item in items:
found = False
for child in list(content_el):
if isinstance(child.tag, str) and localname(child) == "Item" and (child.text or "").strip() == item:
remove_with_indent(child)
remove_count += 1
info(f"Removed content: {item}")
found = True
break
if not found:
warn(f"Content item not found: {item}")
def do_add_child(child_name):
nonlocal add_count
if child_objs_el is None:
print("No <ChildObjects> element found", file=sys.stderr)
sys.exit(1)
for child in child_objs_el:
if isinstance(child.tag, str) and localname(child) == "Subsystem" and (child.text or "").strip() == child_name:
warn(f"ChildObjects already contains: {child_name}")
return
sub_indent = get_child_indent(sub)
if len(child_objs_el) == 0 and not (child_objs_el.text and child_objs_el.text.strip()):
expand_self_closing(child_objs_el, sub_indent)
ci = get_child_indent(child_objs_el)
new_el = etree.SubElement(child_objs_el, f"{{{MD_NS}}}Subsystem")
# Actually we need to use insert_before_closing pattern
child_objs_el.remove(new_el)
new_el = etree.Element(f"{{{MD_NS}}}Subsystem")
new_el.text = child_name
insert_before_closing(child_objs_el, new_el, ci)
add_count += 1
info(f"Added child subsystem: {child_name}")
# Write stub XML for the new child if it doesn't exist yet
parent_dir = os.path.dirname(resolved_path)
parent_base_name = os.path.splitext(os.path.basename(resolved_path))[0]
child_subs_dir = os.path.join(parent_dir, parent_base_name, 'Subsystems')
if not os.path.exists(child_subs_dir):
os.makedirs(child_subs_dir, exist_ok=True)
info(f"Created directory: {child_subs_dir}")
child_xml = os.path.join(child_subs_dir, f'{child_name}.xml')
if not os.path.exists(child_xml):
write_child_subsystem_stub(child_xml, child_name, format_version)
info(f"Created stub: {child_xml}")
def do_remove_child(child_name):
nonlocal remove_count
if child_objs_el is None:
print("No <ChildObjects> element found", file=sys.stderr)
sys.exit(1)
found = False
for child in list(child_objs_el):
if isinstance(child.tag, str) and localname(child) == "Subsystem" and (child.text or "").strip() == child_name:
remove_with_indent(child)
remove_count += 1
info(f"Removed child subsystem: {child_name}")
found = True
break
if not found:
warn(f"Child subsystem not found: {child_name}")
def do_set_property(json_val):
nonlocal modify_count
prop_def = json.loads(json_val)
prop_name = str(prop_def["name"])
prop_value = str(prop_def.get("value", ""))
prop_el = None
for child in props_el:
if isinstance(child.tag, str) and localname(child) == prop_name:
prop_el = child
break
if prop_el is None:
print(f"Property '{prop_name}' not found in Properties", file=sys.stderr)
sys.exit(1)
bool_props = ["IncludeInCommandInterface", "UseOneCommand", "IncludeHelpInContents"]
if prop_name in bool_props:
prop_el.text = prop_value.lower()
# Clear children
for ch in list(prop_el):
prop_el.remove(ch)
modify_count += 1
info(f"Set {prop_name} = {prop_value}")
return
ml_props = ["Synonym", "Explanation"]
if prop_name in ml_props:
if not prop_value:
# Clear - make self-closing
for ch in list(prop_el):
prop_el.remove(ch)
prop_el.text = None
modify_count += 1
info(f"Cleared {prop_name}")
else:
for ch in list(prop_el):
prop_el.remove(ch)
indent = get_child_indent(props_el)
item_el = etree.SubElement(prop_el, f"{{{V8_NS}}}item")
lang_el = etree.SubElement(item_el, f"{{{V8_NS}}}lang")
lang_el.text = "ru"
content_el = etree.SubElement(item_el, f"{{{V8_NS}}}content")
content_el.text = prop_value
# Set whitespace
prop_el.text = "\r\n" + indent + "\t"
item_el.text = "\r\n" + indent + "\t\t"
lang_el.tail = "\r\n" + indent + "\t\t"
content_el.tail = "\r\n" + indent + "\t"
item_el.tail = "\r\n" + indent
modify_count += 1
info(f'Set {prop_name} = "{prop_value}"')
return
if prop_name == "Comment":
for ch in list(prop_el):
prop_el.remove(ch)
if not prop_value:
prop_el.text = None
else:
prop_el.text = prop_value
modify_count += 1
info(f'Set Comment = "{prop_value}"')
return
if prop_name == "Picture":
for ch in list(prop_el):
prop_el.remove(ch)
if not prop_value:
prop_el.text = None
else:
indent = get_child_indent(props_el)
ref_el = etree.SubElement(prop_el, f"{{{XR_NS}}}Ref")
ref_el.text = prop_value
load_el = etree.SubElement(prop_el, f"{{{XR_NS}}}LoadTransparent")
load_el.text = "false"
prop_el.text = "\r\n" + indent + "\t"
ref_el.tail = "\r\n" + indent + "\t"
load_el.tail = "\r\n" + indent
modify_count += 1
info(f'Set Picture = "{prop_value}"')
return
# Generic text property
for ch in list(prop_el):
prop_el.remove(ch)
prop_el.text = prop_value
modify_count += 1
info(f'Set {prop_name} = "{prop_value}"')
# --- Execute operations ---
operations = []
if args.DefinitionFile:
def_file = args.DefinitionFile
if not os.path.isabs(def_file):
def_file = os.path.join(os.getcwd(), def_file)
with open(def_file, "r", encoding="utf-8-sig") as fh:
ops = json.loads(fh.read())
if isinstance(ops, list):
operations = ops
else:
operations = [ops]
else:
operations = [{"operation": args.Operation, "value": args.Value or ""}]
for op in operations:
op_name = op.get("operation", args.Operation or "")
op_value = op.get("value", args.Value or "")
if op_name == "add-content":
do_add_content(parse_value_list(op_value))
elif op_name == "remove-content":
do_remove_content(parse_value_list(op_value))
elif op_name == "add-child":
do_add_child(op_value)
elif op_name == "remove-child":
do_remove_child(op_value)
elif op_name == "set-property":
do_set_property(op_value)
else:
print(f"Unknown operation: {op_name}", file=sys.stderr)
sys.exit(1)
# --- Save ---
save_xml_bom(tree, resolved_path)
info(f"Saved: {resolved_path}")
# --- Auto-validate ---
if not args.NoValidate:
validate_script = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..", "subsystem-validate", "scripts", "subsystem-validate.py"))
if os.path.isfile(validate_script):
print()
print("--- Running subsystem-validate ---")
subprocess.run([sys.executable, validate_script, "-SubsystemPath", resolved_path])
# --- Summary ---
print()
print("=== subsystem-edit summary ===")
print(f" Subsystem: {obj_name}")
print(f" Added: {add_count}")
print(f" Removed: {remove_count}")
print(f" Modified: {modify_count}")
sys.exit(0)
if __name__ == "__main__":
main()
@@ -1,29 +0,0 @@
---
name: subsystem-validate
description: Валидация подсистемы 1С. Используй после создания или модификации подсистемы для проверки корректности
argument-hint: <SubsystemPath> [-Detailed] [-MaxErrors 30]
allowed-tools:
- Bash
- Read
- Glob
---
# /subsystem-validate — валидация подсистемы 1С
Проверяет структурную корректность XML-файла подсистемы из выгрузки конфигурации.
## Параметры
| Параметр | Обяз. | Умолч. | Описание |
|---------------|:-----:|---------|--------------------------------------------|
| SubsystemPath | да | — | Путь к XML-файлу подсистемы |
| Detailed | нет | — | Подробный вывод (все проверки, включая успешные) |
| MaxErrors | нет | 30 | Остановиться после N ошибок |
| OutFile | нет | — | Записать результат в файл |
## Команда
```powershell
powershell.exe -NoProfile -File ".augment/skills/subsystem-validate/scripts/subsystem-validate.ps1" -SubsystemPath "Subsystems/Продажи"
powershell.exe -NoProfile -File ".augment/skills/subsystem-validate/scripts/subsystem-validate.ps1" -SubsystemPath "Subsystems/Продажи.xml"
```
-41
View File
@@ -1,41 +0,0 @@
---
name: support-edit
description: Переключение состояния поддержки типовой конфигурации 1С. Используй когда нужно включить возможность редактирования конфигурации или конкретного объекта на поддержке («на замке»)
argument-hint: -Path <путь> -Set editable|off-support|locked | -Capability on|off
allowed-tools:
- Bash
- Read
- Write
- Glob
---
# /support-edit — переключение состояния поддержки 1С
Меняет правила поддержки типовой конфигурации: разрешает правку объекта/конфигурации «на замке», снимает с поддержки, включает/выключает возможность изменения. Это осознанное действие — обычно после отказа `support-guard` (готовую команду под конкретный случай печатает сам отказ).
Действует только на выгрузку; чтобы применить в информационной базе — загрузить выгрузку (полная загрузка).
## Команды
| Что нужно | Команда |
|-----------|---------|
| Разрешить правку объекта | `-Path <объект> -Set editable` |
| Снять объект с поддержки | `-Path <объект> -Set off-support` |
| Вернуть объект «на замок» | `-Path <объект> -Set locked` |
| Разрешить добавление новых объектов в конфигурацию | `-Path <каталог дампа> -Set editable` |
| Включить / выключить возможность изменения всей конфигурации | `-Path <каталог дампа> -Capability on` / `off` |
`-Path` — тот же путь, который отклонил `support-guard` (объект, форма, макет или каталог дампа).
```powershell
powershell.exe -NoProfile -File ".augment/skills/support-edit/scripts/support-edit.ps1" -Path "Catalogs/Контрагенты.xml" -Set editable
```
## editable или off-support?
- **editable** — правки разрешены, объект **продолжает получать обновления вендора** (при обновлении возможны конфликты слияния). Бери, когда хочешь дорабатывать и дальше получать обновления.
- **off-support** — объект **снят с поддержки**: правки свободны, обновления вендора по нему больше не приходят. Это не удаление объекта. Бери, когда объект уводишь из-под обновлений.
## Если возможность изменения выключена
Если вся конфигурация read-only (типовая «из коробки»), пообъектный `-Set` не сработает — навык подскажет сначала выполнить `-Capability on`. Это включает возможность изменения (все объекты при этом остаются на замке), после чего открываешь нужные точечно через `-Set editable`.
@@ -1,130 +0,0 @@
# support-edit v1.0 — Toggle 1C configuration support state (Ext/ParentConfigurations.bin)
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
param(
[Parameter(Mandatory=$true)][Alias('Path')][string]$TargetPath,
[ValidateSet("editable","off-support","locked")]
[string]$Set,
[ValidateSet("on","off")]
[string]$Capability
)
$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
if ((-not $Set -and -not $Capability) -or ($Set -and $Capability)) {
[Console]::Error.WriteLine("Укажите ровно одно: -Set editable|off-support|locked ЛИБО -Capability on|off")
exit 1
}
# --- Resolve target uuid + config root + bin (walk-up, same as support-guard) ---
function Get-RootUuid([string]$xmlPath) {
if (-not (Test-Path $xmlPath)) { return $null }
try {
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
$el = $mx.DocumentElement.FirstChild
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
} catch {}
return $null
}
if (-not (Test-Path $TargetPath)) {
[Console]::Error.WriteLine("Путь не найден: $TargetPath")
exit 1
}
$rp = (Resolve-Path $TargetPath).Path
$elemUuid = Get-RootUuid $rp
$cfgDir = $null; $binPath = $null
$d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
for ($i = 0; $i -lt 12 -and $d; $i++) {
if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
if (-not $cfgDir) {
$cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
}
if ($elemUuid -and $cfgDir) { break }
$parent = [System.IO.Path]::GetDirectoryName($d)
if ($parent -eq $d) { break }
$d = $parent
}
if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
if (-not $cfgDir) {
[Console]::Error.WriteLine("Не найден корень конфигурации (Configuration.xml) над путём: $rp")
exit 1
}
if (-not (Test-Path $binPath)) {
Write-Host "Конфигурация не на поддержке (Ext/ParentConfigurations.bin отсутствует) — переключать нечего."
exit 0
}
# --- Read bin (UTF-8 text with BOM) ---
$bytes = [System.IO.File]::ReadAllBytes($binPath)
if ($bytes.Length -le 32) {
Write-Host "Поддержка снята полностью (пустой ParentConfigurations.bin) — переключать нечего."
exit 0
}
$start = 0
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
$text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
$hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
if (-not $hm.Success) {
[Console]::Error.WriteLine("Неизвестный формат ParentConfigurations.bin")
exit 1
}
$G = [int]$hm.Groups[1].Value
$K = [int]$hm.Groups[2].Value
function Save-Bin([string]$txt) {
[System.IO.File]::WriteAllText($binPath, $txt, (New-Object System.Text.UTF8Encoding($true)))
}
# === Capability (global G) ===
if ($Capability) {
$target = if ($Capability -eq 'on') { '0' } else { '1' }
if ($G -eq [int]$target) {
$word = if ($Capability -eq 'on') { 'включена' } else { 'выключена' }
Write-Host "Возможность изменения конфигурации уже $word — изменений нет."
exit 0
}
# G + X (per block) + bulk f1
$text = [regex]::Replace($text, '^(\{6,)\d+(,)', "`${1}$target`$2")
$text = [regex]::Replace($text, '([0-9a-f-]{36}),\d+,([0-9a-f-]{36})', "`$1,$target,`$2")
$text = [regex]::Replace($text, '[0-2],0,([0-9a-f-]{36})', "$target,0,`$1")
Save-Bin $text
if ($Capability -eq 'on') {
Write-Host "Возможность изменения конфигурации ВКЛЮЧЕНА. Все объекты поставщика — на замке."
Write-Host "Включайте редактирование точечно: support-edit -Path <объект> -Set editable"
} else {
Write-Host "Возможность изменения конфигурации ВЫКЛЮЧЕНА. Вся конфигурация стала read-only; пообъектные правила сброшены."
}
exit 0
}
# === Per-object -Set ===
if ($G -eq 1) {
[Console]::Error.WriteLine("Возможность изменения конфигурации выключена — пообъектное переключение недоступно.`n Сначала: support-edit -Path $TargetPath -Capability on")
exit 1
}
if (-not $elemUuid) {
[Console]::Error.WriteLine("Не удалось определить объект по пути: $rp")
exit 1
}
$u = [regex]::Escape($elemUuid.ToLower())
$matches = [regex]::Matches($text, "([0-2]),0,$u")
if ($matches.Count -eq 0) {
Write-Host "Объект (uuid $elemUuid) не на поддержке (своё добавление или не найден в bin) — переключать нечего."
exit 0
}
$newF1 = switch ($Set) { 'editable' { '1' } 'off-support' { '2' } 'locked' { '0' } }
# Replacement string has no group refs — uuid is fixed, f1 is rewritten.
$text = [regex]::Replace($text, "([0-2]),0,$u", "$newF1,0,$($elemUuid.ToLower())")
Save-Bin $text
$state = switch ($Set) {
'editable' { "редактируется с сохранением поддержки (объект продолжит получать обновления вендора — возможны конфликты при обновлении)" }
'off-support' { "снят с поддержки (обновления вендора по этому объекту прекращаются)" }
'locked' { "на замке (правка запрещена)" }
}
Write-Host "Объект uuid $elemUuid$state."
Write-Host "Записей в bin изменено: $($matches.Count). Цель: $rp"
exit 0
@@ -1,134 +0,0 @@
#!/usr/bin/env python3
# support-edit v1.0 — Toggle 1C configuration support state (Ext/ParentConfigurations.bin)
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import os
import re
import sys
from lxml import etree
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(description="Toggle 1C support state", allow_abbrev=False)
parser.add_argument("-Path", "-TargetPath", dest="Path", required=True, help="Путь к объекту/форме/макету или каталогу дампа")
parser.add_argument("-Set", choices=["editable", "off-support", "locked"], default=None)
parser.add_argument("-Capability", choices=["on", "off"], default=None)
args = parser.parse_args()
if (not args.Set and not args.Capability) or (args.Set and args.Capability):
sys.stderr.write("Укажите ровно одно: -Set editable|off-support|locked ЛИБО -Capability on|off\n")
sys.exit(1)
def root_uuid(xml_path):
if not os.path.isfile(xml_path):
return None
try:
mx = etree.parse(xml_path).getroot()
for child in mx:
if isinstance(child.tag, str) and child.get("uuid"):
return child.get("uuid")
except Exception:
return None
return None
target_path = args.Path
if not os.path.exists(target_path):
sys.stderr.write(f"Путь не найден: {target_path}\n")
sys.exit(1)
rp = os.path.abspath(target_path)
elem_uuid = root_uuid(rp)
cfg_dir = None
bin_path = None
d = rp if os.path.isdir(rp) else os.path.dirname(rp)
for _ in range(12):
if not d:
break
if not elem_uuid:
elem_uuid = root_uuid(d + ".xml")
if not cfg_dir:
cand = os.path.join(d, "Ext", "ParentConfigurations.bin")
if os.path.exists(cand) or os.path.exists(os.path.join(d, "Configuration.xml")):
cfg_dir = d
bin_path = cand
if elem_uuid and cfg_dir:
break
parent = os.path.dirname(d)
if parent == d:
break
d = parent
if not elem_uuid and cfg_dir:
elem_uuid = root_uuid(os.path.join(cfg_dir, "Configuration.xml"))
if not cfg_dir:
sys.stderr.write(f"Не найден корень конфигурации (Configuration.xml) над путём: {rp}\n")
sys.exit(1)
if not os.path.exists(bin_path):
print("Конфигурация не на поддержке (Ext/ParentConfigurations.bin отсутствует) — переключать нечего.")
sys.exit(0)
raw = open(bin_path, "rb").read()
if len(raw) <= 32:
print("Поддержка снята полностью (пустой ParentConfigurations.bin) — переключать нечего.")
sys.exit(0)
text = raw[3:].decode("utf-8") if raw[:3] == b"\xef\xbb\xbf" else raw.decode("utf-8")
hm = re.match(r"\{6,(\d+),(\d+),", text)
if not hm:
sys.stderr.write("Неизвестный формат ParentConfigurations.bin\n")
sys.exit(1)
g = int(hm.group(1))
k = int(hm.group(2))
def save_bin(txt):
open(bin_path, "wb").write(b"\xef\xbb\xbf" + txt.encode("utf-8"))
# === Capability (global G) ===
if args.Capability:
target = "0" if args.Capability == "on" else "1"
if g == int(target):
word = "включена" if args.Capability == "on" else "выключена"
print(f"Возможность изменения конфигурации уже {word} — изменений нет.")
sys.exit(0)
text = re.sub(r"^(\{6,)\d+(,)", r"\g<1>" + target + r"\g<2>", text)
text = re.sub(r"([0-9a-f-]{36}),\d+,([0-9a-f-]{36})", r"\1," + target + r",\2", text)
text = re.sub(r"[0-2],0,([0-9a-f-]{36})", target + r",0,\1", text)
save_bin(text)
if args.Capability == "on":
print("Возможность изменения конфигурации ВКЛЮЧЕНА. Все объекты поставщика — на замке.")
print("Включайте редактирование точечно: support-edit -Path <объект> -Set editable")
else:
print("Возможность изменения конфигурации ВЫКЛЮЧЕНА. Вся конфигурация стала read-only; пообъектные правила сброшены.")
sys.exit(0)
# === Per-object -Set ===
if g == 1:
sys.stderr.write(
"Возможность изменения конфигурации выключена — пообъектное переключение недоступно.\n"
f" Сначала: support-edit -Path {target_path} -Capability on\n"
)
sys.exit(1)
if not elem_uuid:
sys.stderr.write(f"Не удалось определить объект по пути: {rp}\n")
sys.exit(1)
u = re.escape(elem_uuid.lower())
n = len(re.findall(r"[0-2],0," + u, text))
if n == 0:
print(f"Объект (uuid {elem_uuid}) не на поддержке (своё добавление или не найден в bin) — переключать нечего.")
sys.exit(0)
new_f1 = {"editable": "1", "off-support": "2", "locked": "0"}[args.Set]
text = re.sub(r"[0-2],0," + u, new_f1 + ",0," + elem_uuid.lower(), text)
save_bin(text)
state = {
"editable": "редактируется с сохранением поддержки (объект продолжит получать обновления вендора — возможны конфликты при обновлении)",
"off-support": "снят с поддержки (обновления вендора по этому объекту прекращаются)",
"locked": "на замке (правка запрещена)",
}[args.Set]
print(f"Объект uuid {elem_uuid}{state}.")
print(f"Записей в bin изменено: {n}. Цель: {rp}")
sys.exit(0)
@@ -1,386 +0,0 @@
# template-add v1.7 — Add template to 1C object
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
param(
[Parameter(Mandatory)]
[Alias("ProcessorName")]
[string]$ObjectName,
[Parameter(Mandatory)]
[string]$TemplateName,
[Parameter(Mandatory)]
[ValidateSet("HTML", "Text", "SpreadsheetDocument", "BinaryData", "DataCompositionSchema")]
[string]$TemplateType,
[string]$Synonym = $TemplateName,
[string]$SrcDir = "src",
[switch]$SetMainSKD
)
$ErrorActionPreference = "Stop"
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
# --- Support guard (Ext/ParentConfigurations.bin) ---
# See docs/1c-support-state-spec.md. Blocks edits of vendor objects "на замке" /
# read-only configs unless allowed. Trigger = bin present; reaction from
# .v8-project.json editingAllowedCheck (deny|warn|off, default deny). Never
# throws — guard errors degrade to allow.
function Get-RootUuid([string]$xmlPath) {
if (-not (Test-Path $xmlPath)) { return $null }
try {
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
$el = $mx.DocumentElement.FirstChild
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
} catch {}
return $null
}
function Find-V8Project([string]$startDir) {
$d = $startDir
for ($i = 0; $i -lt 20 -and $d; $i++) {
$pj = Join-Path $d ".v8-project.json"
if (Test-Path $pj) { return $pj }
$parent = [System.IO.Path]::GetDirectoryName($d)
if ($parent -eq $d) { break }
$d = $parent
}
return $null
}
function Get-EditMode([string]$cfgDir) {
try {
$pj = Find-V8Project (Get-Location).Path
if (-not $pj) { $pj = Find-V8Project $cfgDir }
if (-not $pj) { return 'deny' }
$proj = Get-Content -Raw $pj | ConvertFrom-Json
$cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
if ($proj.databases) {
foreach ($db in $proj.databases) {
if ($db.configSrc) {
$src = [System.IO.Path]::GetFullPath($db.configSrc).TrimEnd('\', '/')
if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar)) {
if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
}
}
}
}
if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
return 'deny'
} catch { return 'deny' }
}
function Assert-EditAllowed([string]$targetPath, [string]$require) {
try {
$rp = $targetPath
try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).Path } catch {}
$elemUuid = Get-RootUuid $rp
$cfgDir = $null; $binPath = $null
$d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
for ($i = 0; $i -lt 12 -and $d; $i++) {
if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
if (-not $cfgDir) {
$cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
}
if ($elemUuid -and $cfgDir) { break }
$parent = [System.IO.Path]::GetDirectoryName($d)
if ($parent -eq $d) { break }
$d = $parent
}
# New object (no element file): fall back to config root uuid.
if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
if (-not $binPath -or -not (Test-Path $binPath)) { return }
$bytes = [System.IO.File]::ReadAllBytes($binPath)
if ($bytes.Length -le 32) { return }
$start = 0
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
$text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
$hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
if (-not $hm.Success) { return }
$G = [int]$hm.Groups[1].Value
$K = [int]$hm.Groups[2].Value
if ($K -eq 0) { return }
$best = $null
if ($elemUuid) {
$u = [regex]::Escape($elemUuid.ToLower())
foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
$f1 = [int]$m.Groups[1].Value
if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
}
}
$blocked = $false; $code = ""; $reason = ""
if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
elseif ($require -eq 'removed') {
if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
}
else {
if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
}
if (-not $blocked) { return }
$mode = Get-EditMode $cfgDir
if ($mode -eq 'off') { return }
# Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
# latter throws and would be swallowed by this function's own catch.
if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
$head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
$cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
$offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
if ($code -eq "capability-off") {
$state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
$fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
} elseif ($code -eq "not-removed") {
$state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
$fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
} else {
$state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
$fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
}
[Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
exit 1
} catch { return }
}
# --- Маппинг типов ---
$typeMap = @{
"HTML" = @{ TemplateType = "HTMLDocument"; Ext = ".html" }
"Text" = @{ TemplateType = "TextDocument"; Ext = ".txt" }
"SpreadsheetDocument" = @{ TemplateType = "SpreadsheetDocument"; Ext = ".xml" }
"BinaryData" = @{ TemplateType = "BinaryData"; Ext = ".bin" }
"DataCompositionSchema" = @{ TemplateType = "DataCompositionSchema"; Ext = ".xml" }
}
$tmpl = $typeMap[$TemplateType]
# --- Проверки ---
$objectTypeFolders = @(
"Reports", "DataProcessors", "Documents", "Catalogs",
"InformationRegisters", "AccumulationRegisters",
"ChartsOfCharacteristicTypes", "ChartsOfAccounts", "ChartsOfCalculationTypes",
"BusinessProcesses", "Tasks", "ExchangePlans"
)
$rootXmlPath = Join-Path $SrcDir "$ObjectName.xml"
if (-not (Test-Path $rootXmlPath)) {
$candidates = @()
foreach ($folder in $objectTypeFolders) {
$probe = Join-Path (Join-Path $SrcDir $folder) "$ObjectName.xml"
if (Test-Path $probe) { $candidates += (Join-Path $SrcDir $folder) }
}
if ($candidates.Count -eq 1) {
$SrcDir = $candidates[0]
$rootXmlPath = Join-Path $SrcDir "$ObjectName.xml"
Write-Host "[INFO] SrcDir расширен до: $SrcDir"
} elseif ($candidates.Count -gt 1) {
Write-Error "Объект '$ObjectName' найден в нескольких подпапках: $($candidates -join ', ')`nУкажи SrcDir явно"
exit 1
} else {
Write-Error "Корневой файл объекта не найден: $rootXmlPath`nОжидается: <SrcDir>/<ObjectName>.xml`nПодсказка: SrcDir должен указывать на папку типа объектов (например Reports), а не на корень конфигурации"
exit 1
}
}
$processorDir = Join-Path $SrcDir $ObjectName
$templatesDir = Join-Path $processorDir "Templates"
$templateMetaPath = Join-Path $templatesDir "$TemplateName.xml"
if (Test-Path $templateMetaPath) {
Write-Error "Макет уже существует: $templateMetaPath"
exit 1
}
Assert-EditAllowed $rootXmlPath 'editable'
# --- Создание каталогов ---
$templateExtDir = Join-Path (Join-Path $templatesDir $TemplateName) "Ext"
New-Item -ItemType Directory -Path $templateExtDir -Force | Out-Null
# --- Кодировка ---
$encBom = New-Object System.Text.UTF8Encoding($true)
# --- Detect format version ---
function Detect-FormatVersion([string]$dir) {
$d = $dir
while ($d) {
$cfgPath = Join-Path $d "Configuration.xml"
if (Test-Path $cfgPath) {
$head = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8).Substring(0, [Math]::Min(2000, (Get-Item $cfgPath).Length))
if ($head -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
}
$parent = Split-Path $d -Parent
if ($parent -eq $d) { break }
$d = $parent
}
return "2.17"
}
$formatVersion = Detect-FormatVersion (Resolve-Path $SrcDir).Path
# --- 1. Метаданные макета (Templates/<TemplateName>.xml) ---
$templateUuid = [guid]::NewGuid().ToString()
$templateMetaXml = @"
<?xml version="1.0" encoding="UTF-8"?>
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version=`"$formatVersion`">
<Template uuid="$templateUuid">
<Properties>
<Name>$TemplateName</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>$Synonym</v8:content>
</v8:item>
</Synonym>
<Comment/>
<TemplateType>$($tmpl.TemplateType)</TemplateType>
</Properties>
</Template>
</MetaDataObject>
"@
[System.IO.File]::WriteAllText($templateMetaPath, $templateMetaXml, $encBom)
# --- 2. Содержимое макета (Templates/<TemplateName>/Ext/Template.<ext>) ---
$templateFilePath = Join-Path $templateExtDir "Template$($tmpl.Ext)"
switch ($TemplateType) {
"HTML" {
$content = @"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
</html>
"@
[System.IO.File]::WriteAllText($templateFilePath, $content, $encBom)
}
"Text" {
[System.IO.File]::WriteAllText($templateFilePath, "", $encBom)
}
"SpreadsheetDocument" {
$content = @"
<?xml version="1.0" encoding="UTF-8"?>
<SpreadsheetDocument xmlns="http://v8.1c.ru/spreadsheet/document" xmlns:ss="http://v8.1c.ru/spreadsheet/document" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:xs="http://www.w3.org/2001/XMLSchema">
</SpreadsheetDocument>
"@
[System.IO.File]::WriteAllText($templateFilePath, $content, $encBom)
}
"BinaryData" {
[System.IO.File]::WriteAllBytes($templateFilePath, @())
}
"DataCompositionSchema" {
$content = @"
<?xml version="1.0" encoding="UTF-8"?>
<DataCompositionSchema xmlns="http://v8.1c.ru/8.1/data-composition-system/schema"
xmlns:dcscom="http://v8.1c.ru/8.1/data-composition-system/common"
xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core"
xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings"
xmlns:v8="http://v8.1c.ru/8.1/data/core"
xmlns:v8ui="http://v8.1c.ru/8.1/data/ui"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<dataSource>
<name>ИсточникДанных1</name>
<dataSourceType>Local</dataSourceType>
</dataSource>
</DataCompositionSchema>
"@
[System.IO.File]::WriteAllText($templateFilePath, $content, $encBom)
}
}
# --- 3. Модификация корневого XML ---
$rootXmlFull = Resolve-Path $rootXmlPath
$xmlDoc = New-Object System.Xml.XmlDocument
$xmlDoc.PreserveWhitespace = $true
$xmlDoc.Load($rootXmlFull.Path)
$nsMgr = New-Object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
$nsMgr.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
$childObjects = $xmlDoc.SelectSingleNode("//md:ChildObjects", $nsMgr)
if (-not $childObjects) {
Write-Error "Не найден элемент ChildObjects в $rootXmlPath"
exit 1
}
# Добавить <Template> в конец ChildObjects
$templateElem = $xmlDoc.CreateElement("Template", "http://v8.1c.ru/8.3/MDClasses")
$templateElem.InnerText = $TemplateName
if ($childObjects.ChildNodes.Count -eq 0) {
$childObjects.AppendChild($xmlDoc.CreateWhitespace("`n`t`t`t")) | Out-Null
$childObjects.AppendChild($templateElem) | Out-Null
$childObjects.AppendChild($xmlDoc.CreateWhitespace("`n`t`t")) | Out-Null
} else {
$lastChild = $childObjects.LastChild
# Вставить перед закрывающим whitespace (если есть), или в конец
if ($lastChild.NodeType -eq [System.Xml.XmlNodeType]::Whitespace) {
$childObjects.InsertBefore($xmlDoc.CreateWhitespace("`n`t`t`t"), $lastChild) | Out-Null
$childObjects.InsertBefore($templateElem, $lastChild) | Out-Null
} else {
$childObjects.AppendChild($xmlDoc.CreateWhitespace("`n`t`t`t")) | Out-Null
$childObjects.AppendChild($templateElem) | Out-Null
$childObjects.AppendChild($xmlDoc.CreateWhitespace("`n`t`t")) | Out-Null
}
}
# --- 4. MainDataCompositionSchema (для ExternalReport / Report) ---
$mainDCSUpdated = $false
if ($TemplateType -eq "DataCompositionSchema") {
# Определяем корневой элемент объекта
$reportLikeTypes = @("ExternalReport", "Report")
$objectTypeNode = $null
$objectTypeName = $null
foreach ($rt in $reportLikeTypes) {
$node = $xmlDoc.SelectSingleNode("//md:$rt", $nsMgr)
if ($node) {
$objectTypeNode = $node
$objectTypeName = $rt
break
}
}
if ($objectTypeNode) {
$mainDCS = $xmlDoc.SelectSingleNode("//md:${objectTypeName}/md:Properties/md:MainDataCompositionSchema", $nsMgr)
if ($mainDCS) {
$isEmpty = [string]::IsNullOrWhiteSpace($mainDCS.InnerText)
if ($isEmpty -or $SetMainSKD) {
$objName = $xmlDoc.SelectSingleNode("//md:${objectTypeName}/md:Properties/md:Name", $nsMgr).InnerText
$mainDCS.InnerText = "$objectTypeName.$objName.Template.$TemplateName"
$mainDCSUpdated = $true
}
}
}
}
# Сохранить с BOM
$settings = New-Object System.Xml.XmlWriterSettings
$settings.Encoding = $encBom
$settings.Indent = $false
$stream = New-Object System.IO.FileStream($rootXmlFull.Path, [System.IO.FileMode]::Create)
$writer = [System.Xml.XmlWriter]::Create($stream, $settings)
$xmlDoc.Save($writer)
$writer.Close()
$stream.Close()
Write-Host "[OK] Создан макет: $TemplateName ($TemplateType)"
Write-Host " Метаданные: $templateMetaPath"
Write-Host " Содержимое: $templateFilePath"
if ($mainDCSUpdated) {
Write-Host " MainDataCompositionSchema: $($mainDCS.InnerText)"
}
@@ -1,457 +0,0 @@
#!/usr/bin/env python3
# add-template v1.7 — Add template to 1C object
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import argparse
import json
import os
import re
import sys
import uuid
from lxml import etree
NSMAP = {"md": "http://v8.1c.ru/8.3/MDClasses"}
# ============================================================
# Support guard (Ext/ParentConfigurations.bin) — see docs/1c-support-state-spec.md
# Blocks edits of vendor objects "на замке" / read-only configs. Trigger = bin
# present; reaction from .v8-project.json editingAllowedCheck (deny|warn|off,
# default deny). Never throws (except sys.exit on deny) — errors degrade to allow.
# ============================================================
def _sg_root_uuid(xml_path):
if not os.path.isfile(xml_path):
return None
try:
mx = etree.parse(xml_path).getroot()
for child in mx:
if isinstance(child.tag, str) and child.get("uuid"):
return child.get("uuid")
except Exception:
return None
return None
def _sg_find_v8project(start_dir):
d = start_dir
for _ in range(20):
if not d:
break
pj = os.path.join(d, ".v8-project.json")
if os.path.isfile(pj):
return pj
parent = os.path.dirname(d)
if parent == d:
break
d = parent
return None
def _sg_get_edit_mode(cfg_dir):
try:
pj = _sg_find_v8project(os.getcwd()) or _sg_find_v8project(cfg_dir)
if not pj:
return "deny"
proj = json.loads(open(pj, encoding="utf-8-sig").read())
cfg_full = os.path.normcase(os.path.abspath(cfg_dir)).rstrip("\\/")
for db in proj.get("databases", []):
src = db.get("configSrc")
if src:
src_full = os.path.normcase(os.path.abspath(src)).rstrip("\\/")
if cfg_full == src_full or cfg_full.startswith(src_full + os.sep):
if db.get("editingAllowedCheck"):
return db["editingAllowedCheck"]
if proj.get("editingAllowedCheck"):
return proj["editingAllowedCheck"]
return "deny"
except Exception:
return "deny"
def assert_edit_allowed(target_path, require):
try:
rp = os.path.abspath(target_path)
elem_uuid = _sg_root_uuid(rp)
cfg_dir = None
bin_path = None
d = rp if os.path.isdir(rp) else os.path.dirname(rp)
for _ in range(12):
if not d:
break
if not elem_uuid:
elem_uuid = _sg_root_uuid(d + ".xml")
if not cfg_dir:
cand = os.path.join(d, "Ext", "ParentConfigurations.bin")
if os.path.exists(cand) or os.path.exists(os.path.join(d, "Configuration.xml")):
cfg_dir = d
bin_path = cand
if elem_uuid and cfg_dir:
break
parent = os.path.dirname(d)
if parent == d:
break
d = parent
if not elem_uuid and cfg_dir:
elem_uuid = _sg_root_uuid(os.path.join(cfg_dir, "Configuration.xml"))
if not bin_path or not os.path.exists(bin_path):
return
data = open(bin_path, "rb").read()
if len(data) <= 32:
return
if data[:3] == b"\xef\xbb\xbf":
data = data[3:]
text = data.decode("utf-8", "replace")
h = re.match(r"\{6,(\d+),(\d+),", text)
if not h:
return
g = int(h.group(1))
k = int(h.group(2))
if k == 0:
return
best = None
if elem_uuid:
for m in re.finditer(r"([0-2]),0," + re.escape(elem_uuid.lower()), text):
f1 = int(m.group(1))
if best is None or f1 < best:
best = f1
blocked = False
code = ""
reason = ""
if g == 1:
blocked = True
code = "capability-off"
reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)"
elif require == "removed":
if best is not None and best != 2:
blocked = True
code = "not-removed"
reason = "объект не снят с поддержки — удаление сломает обновления"
else:
if best is not None and best == 0:
blocked = True
code = "locked"
reason = "объект на замке — редактирование сломает обновления"
if not blocked:
return
mode = _sg_get_edit_mode(cfg_dir)
if mode == "off":
return
if mode == "warn":
sys.stderr.write(f"[support-guard] ПРЕДУПРЕЖДЕНИЕ: {reason}. Цель: {rp}\n")
return
head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
off_note = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
if code == "capability-off":
state = f"Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «{rp}» редактировать нельзя."
fix = (
"Либо снять защиту явно (навык support-edit, два шага):\n"
f' 1. support-edit -Path "{cfg_dir}" -Capability on — включить возможность изменения (объекты пока остаются на замке);\n'
f' 2. support-edit -Path "{rp}" -Set editable — открыть этот объект для редактирования.\n'
" Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
)
elif code == "not-removed":
state = f"Состояние: объект «{rp}» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
fix = (
"Либо сначала снять объект с поддержки, затем удалять:\n"
f' support-edit -Path "{rp}" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно.'
)
else:
state = f"Состояние: объект «{rp}» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
fix = (
"Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):\n"
f' support-edit -Path "{rp}" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);\n'
f' support-edit -Path "{rp}" -Set off-support — снять с поддержки: обновления по объекту больше не приходят.'
)
sys.stderr.write(head + "\n" + state + "\n" + cfe + "\n" + fix + "\n" + off_note + "\n")
sys.exit(1)
except SystemExit:
raise
except Exception:
return
TYPE_MAP = {
"HTML": {"TemplateType": "HTMLDocument", "Ext": ".html"},
"Text": {"TemplateType": "TextDocument", "Ext": ".txt"},
"SpreadsheetDocument": {"TemplateType": "SpreadsheetDocument", "Ext": ".xml"},
"BinaryData": {"TemplateType": "BinaryData", "Ext": ".bin"},
"DataCompositionSchema": {"TemplateType": "DataCompositionSchema", "Ext": ".xml"},
}
def save_xml_with_bom(tree, path):
"""Save XML tree to file with UTF-8 BOM."""
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
xml_bytes = xml_bytes.replace(b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" encoding="utf-8"?>')
if not xml_bytes.endswith(b"\n"):
xml_bytes += b"\n"
with open(path, "wb") as f:
f.write(b"\xef\xbb\xbf")
f.write(xml_bytes)
def write_text_with_bom(path, text):
"""Write text to file with UTF-8 BOM."""
with open(path, "w", encoding="utf-8-sig") as f:
f.write(text)
def detect_format_version(d):
while d:
cfg_path = os.path.join(d, "Configuration.xml")
if os.path.isfile(cfg_path):
with open(cfg_path, "r", encoding="utf-8-sig") as f:
head = f.read(2000)
m = re.search(r'<MetaDataObject[^>]+version="(\d+\.\d+)"', head)
if m:
return m.group(1)
parent = os.path.dirname(d)
if parent == d:
break
d = parent
return "2.17"
def main():
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
parser = argparse.ArgumentParser(description="Add template to 1C object", allow_abbrev=False)
parser.add_argument("-ObjectName", "-ProcessorName", required=True)
parser.add_argument("-TemplateName", required=True)
parser.add_argument("-TemplateType", required=True,
choices=["HTML", "Text", "SpreadsheetDocument", "BinaryData", "DataCompositionSchema"])
parser.add_argument("-Synonym", default=None)
parser.add_argument("-SrcDir", default="src")
parser.add_argument("-SetMainSKD", action="store_true")
args = parser.parse_args()
object_name = args.ObjectName
template_name = args.TemplateName
template_type = args.TemplateType
synonym = args.Synonym if args.Synonym is not None else template_name
src_dir = args.SrcDir
set_main_skd = args.SetMainSKD
tmpl = TYPE_MAP[template_type]
format_version = detect_format_version(os.path.abspath(src_dir))
# --- Checks ---
object_type_folders = [
"Reports", "DataProcessors", "Documents", "Catalogs",
"InformationRegisters", "AccumulationRegisters",
"ChartsOfCharacteristicTypes", "ChartsOfAccounts", "ChartsOfCalculationTypes",
"BusinessProcesses", "Tasks", "ExchangePlans",
]
root_xml_path = os.path.join(src_dir, f"{object_name}.xml")
if not os.path.exists(root_xml_path):
candidates = []
for folder in object_type_folders:
probe = os.path.join(src_dir, folder, f"{object_name}.xml")
if os.path.exists(probe):
candidates.append(os.path.join(src_dir, folder))
if len(candidates) == 1:
src_dir = candidates[0]
root_xml_path = os.path.join(src_dir, f"{object_name}.xml")
print(f"[INFO] SrcDir расширен до: {src_dir}")
elif len(candidates) > 1:
print(f"Объект '{object_name}' найден в нескольких подпапках: {', '.join(candidates)}", file=sys.stderr)
print(f"Укажи SrcDir явно", file=sys.stderr)
sys.exit(1)
else:
print(f"Корневой файл объекта не найден: {root_xml_path}", file=sys.stderr)
print(f"Ожидается: <SrcDir>/<ObjectName>.xml", file=sys.stderr)
print(f"Подсказка: SrcDir должен указывать на папку типа объектов (например Reports), а не на корень конфигурации", file=sys.stderr)
sys.exit(1)
processor_dir = os.path.join(src_dir, object_name)
templates_dir = os.path.join(processor_dir, "Templates")
template_meta_path = os.path.join(templates_dir, f"{template_name}.xml")
if os.path.exists(template_meta_path):
print(f"Макет уже существует: {template_meta_path}", file=sys.stderr)
sys.exit(1)
assert_edit_allowed(root_xml_path, "editable")
# --- Create directories ---
template_ext_dir = os.path.join(templates_dir, template_name, "Ext")
os.makedirs(template_ext_dir, exist_ok=True)
# --- 1. Template metadata (Templates/<TemplateName>.xml) ---
template_uuid = str(uuid.uuid4())
template_meta_xml = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses"'
' xmlns:app="http://v8.1c.ru/8.2/managed-application/core"'
' xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config"'
' xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi"'
' xmlns:ent="http://v8.1c.ru/8.1/data/enterprise"'
' xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform"'
' xmlns:style="http://v8.1c.ru/8.1/data/ui/style"'
' xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system"'
' xmlns:v8="http://v8.1c.ru/8.1/data/core"'
' xmlns:v8ui="http://v8.1c.ru/8.1/data/ui"'
' xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web"'
' xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows"'
' xmlns:xen="http://v8.1c.ru/8.3/xcf/enums"'
' xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef"'
' xmlns:xr="http://v8.1c.ru/8.3/xcf/readable"'
' xmlns:xs="http://www.w3.org/2001/XMLSchema"'
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
f' version="{format_version}">\n'
f'\t<Template uuid="{template_uuid}">\n'
'\t\t<Properties>\n'
f'\t\t\t<Name>{template_name}</Name>\n'
'\t\t\t<Synonym>\n'
'\t\t\t\t<v8:item>\n'
'\t\t\t\t\t<v8:lang>ru</v8:lang>\n'
f'\t\t\t\t\t<v8:content>{synonym}</v8:content>\n'
'\t\t\t\t</v8:item>\n'
'\t\t\t</Synonym>\n'
'\t\t\t<Comment/>\n'
f'\t\t\t<TemplateType>{tmpl["TemplateType"]}</TemplateType>\n'
'\t\t</Properties>\n'
'\t</Template>\n'
'</MetaDataObject>'
)
write_text_with_bom(template_meta_path, template_meta_xml)
# --- 2. Template content (Templates/<TemplateName>/Ext/Template.<ext>) ---
template_file_path = os.path.join(template_ext_dir, f"Template{tmpl['Ext']}")
if template_type == "HTML":
content = (
'<!DOCTYPE html>\n'
'<html>\n'
'<head>\n'
'\t<meta charset="UTF-8">\n'
'\t<title></title>\n'
'</head>\n'
'<body>\n'
'</body>\n'
'</html>'
)
write_text_with_bom(template_file_path, content)
elif template_type == "Text":
write_text_with_bom(template_file_path, "")
elif template_type == "SpreadsheetDocument":
content = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<SpreadsheetDocument xmlns="http://v8.1c.ru/spreadsheet/document"'
' xmlns:ss="http://v8.1c.ru/spreadsheet/document"'
' xmlns:v8="http://v8.1c.ru/8.1/data/core"'
' xmlns:xs="http://www.w3.org/2001/XMLSchema">\n'
'</SpreadsheetDocument>'
)
write_text_with_bom(template_file_path, content)
elif template_type == "BinaryData":
with open(template_file_path, "wb") as f:
pass # empty file
elif template_type == "DataCompositionSchema":
content = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<DataCompositionSchema xmlns="http://v8.1c.ru/8.1/data-composition-system/schema"\n'
'\t\txmlns:dcscom="http://v8.1c.ru/8.1/data-composition-system/common"\n'
'\t\txmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core"\n'
'\t\txmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings"\n'
'\t\txmlns:v8="http://v8.1c.ru/8.1/data/core"\n'
'\t\txmlns:v8ui="http://v8.1c.ru/8.1/data/ui"\n'
'\t\txmlns:xs="http://www.w3.org/2001/XMLSchema"\n'
'\t\txmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n'
'\t<dataSource>\n'
'\t\t<name>ИсточникДанных1</name>\n'
'\t\t<dataSourceType>Local</dataSourceType>\n'
'\t</dataSource>\n'
'</DataCompositionSchema>'
)
write_text_with_bom(template_file_path, content)
# --- 3. Modify root XML ---
root_xml_full = os.path.abspath(root_xml_path)
parser_xml = etree.XMLParser(remove_blank_text=False)
tree = etree.parse(root_xml_full, parser_xml)
root = tree.getroot()
ns = "http://v8.1c.ru/8.3/MDClasses"
child_objects = root.find(".//md:ChildObjects", NSMAP)
if child_objects is None:
print(f"Не найден элемент ChildObjects в {root_xml_path}", file=sys.stderr)
sys.exit(1)
# Add <Template> to end of ChildObjects
template_elem = etree.SubElement(child_objects, f"{{{ns}}}Template")
template_elem.text = template_name
# Remove auto-appended element to reinsert with proper whitespace
child_objects.remove(template_elem)
children = list(child_objects)
if len(children) == 0 and (child_objects.text is None or child_objects.text.strip() == ""):
# Empty ChildObjects (self-closing)
child_objects.text = "\n\t\t\t"
child_objects.append(template_elem)
template_elem.tail = "\n\t\t"
else:
if len(children) > 0:
last_child = children[-1]
# last_child.tail is the trailing whitespace before </ChildObjects>
old_tail = last_child.tail
last_child.tail = "\n\t\t\t"
child_objects.append(template_elem)
template_elem.tail = old_tail if old_tail else "\n\t\t"
else:
# Has text content but no element children
child_objects.text = (child_objects.text or "") + "\n\t\t\t"
child_objects.append(template_elem)
template_elem.tail = "\n\t\t"
# --- 4. MainDataCompositionSchema (for ExternalReport / Report) ---
main_dcs_updated = False
if template_type == "DataCompositionSchema":
report_like_types = ["ExternalReport", "Report"]
object_type_node = None
object_type_name = None
for rt in report_like_types:
node = root.find(f".//md:{rt}", NSMAP)
if node is not None:
object_type_node = node
object_type_name = rt
break
if object_type_node is not None:
main_dcs = root.find(f".//md:{object_type_name}/md:Properties/md:MainDataCompositionSchema", NSMAP)
if main_dcs is not None:
is_empty = main_dcs.text is None or main_dcs.text.strip() == ""
if is_empty or set_main_skd:
obj_name_node = root.find(f".//md:{object_type_name}/md:Properties/md:Name", NSMAP)
obj_name = obj_name_node.text if obj_name_node is not None else ""
main_dcs.text = f"{object_type_name}.{obj_name}.Template.{template_name}"
main_dcs_updated = True
# Save with BOM
save_xml_with_bom(tree, root_xml_full)
print(f"[OK] Создан макет: {template_name} ({template_type})")
print(f" Метаданные: {template_meta_path}")
print(f" Содержимое: {template_file_path}")
if main_dcs_updated:
print(f" MainDataCompositionSchema: {main_dcs.text}")
if __name__ == "__main__":
main()
-424
View File
@@ -1,424 +0,0 @@
# Regression suite authoring
Use this when the user asks to cover a 1C solution with automated regression tests, build out a test suite, or run an existing suite and analyse failures. For ad-hoc single-script automation, stay with the `run`/`exec` modes from SKILL.md instead.
The runner is the same `run.mjs`. The mode is `test`:
```bash
node $RUN test <dir|file>... [flags]
```
Positional args are test paths (files and/or dirs, multiple allowed). URL is NOT positional — it comes from `webtest.config.mjs`; override with `--url=<url>`.
Tests live next to the project they cover (not inside the skill). Convention: `tests/` at the project root, with `_hooks.mjs` and `webtest.config.mjs` at the suite root. Tests are ES modules with `*.test.mjs` suffix.
## When to choose `test` over `exec`
| Goal | Mode |
|------|------|
| Explore a form, prototype a single step, debug one selector | `exec` (interactive session) |
| Reproduce a bug as a failing test before fixing it | `test` |
| Cover a feature so future changes are checked automatically | `test` |
| Run the project's regression on a new build | `test` |
| Generate a screencast walkthrough | `exec` with `startRecording` |
Don't write a `.test.mjs` for a one-shot user request. Don't drive a regression suite through chained `exec` calls.
## Before writing tests — recon
Two layers, in order.
**1. Static recon — metadata.** Never invent identifiers. For every metadata object the user mentions, run the matching info skill first: `/meta-info` (attributes/tabular sections), `/form-info` (form layout), `/skd-info` (DCS), `/mxl-info` (templates), `/role-info` (rights), `/subsystem-info` (composition / command interface). If the user names objects you can't find — stop and ask.
**2. Live recon — interactive walkthrough.** For any non-trivial scenario, walk the path live in `exec` mode before transcribing it. Metadata tells you what exists; the live walkthrough tells you what actually happens. Capture from `getFormState()`: exact button names (`'Провести и закрыть'`, not `'Сохранить'`), table section names for multi-grid forms, required fields, places where a real async wait is needed. Then transcribe the working sequence into `*.test.mjs`, wrapping logical chunks in `step('...', async () => { ... })`.
The mechanics of `exec` / `getFormState` / `fillFields` / `clickElement` are in [SKILL.md](SKILL.md) — read it before recon if you haven't already.
When live recon is overkill: trivial reads (`navigateSection` + `readTable` + assert non-empty), or scenarios you've already proven once in this session. When it's essential: confirmation dialogs, posting/cancellation flows, reports with custom filters, multi-grid forms, user-customised forms.
## Suite layout
**Each application gets its own subfolder under `tests/`.** A single repo may host several independent suites side by side — they must not share `_hooks.mjs` or `webtest.config.mjs`, because each suite restores a different DB, publishes to a different URL, and ships its own test data.
```
tests/
<app-name>/ # application regression — one per solution
_hooks.mjs
webtest.config.mjs
_allure/ # optional static Allure config
01-login/
02-counterparties/
...
<another-app>/ # second solution, fully isolated
```
Inside the application subfolder, organize by **feature**, not by metadata kind. Numeric prefixes on both folder and file enforce run order — discovery walks recursively and sorts files by full relative path; entries starting with `_` or `.` are skipped (so `_hooks.mjs`, `_allure/` won't be picked up as tests).
```
tests/<app-name>/
01-login/
01-open-base.test.mjs
02-section-navigation.test.mjs
02-counterparties/
01-create.test.mjs
02-edit-phone.test.mjs
03-goods-receipt/
01-fill.test.mjs
02-post.test.mjs
05-approval-process/
01-end-to-end.test.mjs # multi-user
```
Per-folder `_hooks.mjs` / `webtest.config.mjs` inside the application subfolder are NOT supported — only the application-root copies are loaded.
## Test file anatomy
```js
export const name = 'Создание контрагента'; // required
export const tags = ['catalog', 'create']; // optional, used for filtering + Allure
export const timeout = 60000; // optional, default 30000
// export const skip = 'pending fix #123'; // optional: true | string
// export const only = true; // debug-only — never commit
// export const context = 'manager'; // optional, single non-default context
// export const contexts = ['clerk', 'manager']; // optional, multi-user test
// export const severity = 'critical'; // optional, overrides config severity
export async function setup(ctx) {
// per-test prep — runs before default. Skip if not needed.
}
export async function teardown(ctx) {
// per-test cleanup — runs after default, always (even on failure).
}
export default async function(ctx) {
const { navigateSection, openCommand, clickElement, fillFields,
readTable, closeForm, getFormState,
assert, step, log } = ctx;
await step('Открыть список контрагентов', async () => {
await navigateSection('Продажи');
await openCommand('Контрагенты');
});
await step('Создать нового контрагента', async () => {
await clickElement('Создать');
await fillFields({ 'Наименование': 'Тест ' + Date.now() });
await clickElement('Записать и закрыть');
});
await step('Убедиться, что элемент появился в списке', async () => {
const t = await readTable();
assert.tableHasRow(t, r => r['Наименование']?.startsWith('Тест '));
});
}
```
**Step names — in Russian, descriptive.** Step labels surface in the console output, in JSON/JUnit, and as Allure step nodes. Russian-speaking QA reads them. Use a full action phrase (`'Создать нового контрагента'`), not a tag (`'create'`) and not a transliteration. Same applies to `export const name` and `displayName` in `webtest.config.mjs`.
## `ctx` contract
The runner injects every `browser.mjs` export into `ctx` (all 1C action functions auto-detect platform errors — see SKILL.md), plus the test utilities below.
### Test utilities
```js
step(name, fn) // async wrapper. Records start/stop. Nested calls supported.
// On throw: marks the step failed, re-throws.
// On screenshot='every-step': captures after fn().
log(...args) // adds a line to ctx.testInfo's output (goes into JSON / Allure
// attachment). Use instead of console.log inside tests.
assert.* // see "Assertions" below
```
### `ctx.testInfo` (always set, read-only)
```js
{
name, // 'Навигация по разделам' (with params substituted)
file, // '01-navigation.test.mjs' (basename)
filePath, // relative path inside testDir
tags, // ['nav', 'smoke']
timeout, // ms
attempt, // 1..maxAttempts (1-based)
maxAttempts, // 1 + retry
param, // { ... } | undefined (only when export const params is set)
contexts: { // mirrors config.contexts; includes custom fields like displayName
clerk: { url, isolation, displayName, ... },
manager: { ... },
},
primaryContext, // 'clerk' — name of the context active at test entry
// (= t.context for single, t.contexts[0] for multi)
}
```
### `ctx.testResult` (only in `afterEach`)
```js
{
status, // 'passed' | 'failed'
duration, // ms
attempts, // attempts actually executed
error, // { message, step?, screenshot? } | null
steps, // array of step results (each: { name, start, stop, status, error?, steps[] })
}
```
### Context shape
- **Single-context (default or `export const context = 'manager'`):** all API on `ctx` top-level — `ctx.clickElement(...)`, `ctx.getFormState()`, etc.
- **Multi-context (`export const contexts = ['clerk', 'manager']`):** each name is its own scoped namespace — `ctx.clerk.clickElement(...)`, `ctx.manager.fillFields(...)`. `step`, `assert`, `log`, `testInfo` stay top-level. Scoped methods auto-switch the active page before each call.
## Assertions
All on `ctx.assert`. Throw `AssertionError` with `.message`, `.actual`, `.expected`. No dependencies.
```js
// generic
assert.ok(value, msg?) // truthy
assert.equal(actual, expected, msg?) // ===
assert.notEqual(actual, expected, msg?) // !==
assert.deepEqual(actual, expected, msg?) // JSON-compare
assert.includes(haystack, needle, msg?) // string.includes / array.includes
assert.match(string, regex, msg?) // regex.test(string)
await assert.throws(asyncFn, msg?) // passes if fn throws (use await)
// 1C-specific — operate on getFormState() / readTable() output
assert.formHasField(state, 'Контрагент', msg?) // state.fields[name] exists
assert.formTitle(state, expected, msg?) // state.title includes expected
assert.tableHasRow(table, predicate, msg?) // predicate: object (partial match) or fn(row) => bool
// object form: { 'Наименование': 'Тест' }
// fn form: r => r['Сумма'] > 100
assert.tableRowCount(table, expected, msg?) // table.rows.length === expected
assert.noErrors(state, msg?) // !state.errors
```
Beyond these, just use plain JS (`throw new Error(...)`) — there's no custom matcher extension API. The 1C-specific helpers are the ones worth preferring over hand-rolled equivalents because their error messages name the actual fields/rows present, which speeds up triage.
## webtest.config.mjs
```js
export default {
// Single-context shorthand:
url: 'http://localhost:9191/myapp/ru_RU',
// OR multi-context:
// contexts: {
// clerk: { url: 'http://localhost:9191/myapp-clerk/ru_RU', displayName: 'Кладовщик' },
// manager: { url: 'http://localhost:9191/myapp-manager/ru_RU', displayName: 'Менеджер' },
// },
// defaultContext: 'clerk',
timeout: 30000,
retries: 0,
screenshot: 'on-failure', // 'every-step' | 'off'
record: false,
// Severity → tags mapping for Allure. Each tag at most one bucket.
severity: {
critical: ['smoke', 'crud'],
minor: ['recording'],
},
defaultSeverity: 'normal',
};
```
CLI flags override config. Use latin context IDs + Russian `displayName` for ergonomics — `ctx.testInfo.contexts.clerk.displayName` is friendlier than mixed-case Cyrillic keys.
## _hooks.mjs
Two layers. Infra hooks run without a browser; testlevel hooks receive `ctx`.
```js
import { execSync } from 'child_process';
// Infra — runs once around the whole suite.
export async function prepare({ hookArgs, log, config }) {
// hookArgs: everything after `--` on the CLI, as a string[]. Parse yourself.
const force = hookArgs.includes('--rebuild-stand');
const dataArg = hookArgs.find(a => a.startsWith('--data='))?.slice('--data='.length);
log('preparing stand, force=', force, 'data=', dataArg);
// Idempotent hash-locks on inputs (config sources, EPF spec, DB dump) keep
// warm starts to a liveness probe.
}
export async function cleanup({ log, config }) { /* optional */ }
// Testlevel — runs with browser ctx.
export async function beforeAll(ctx) { /* once after first context opens */ }
export async function afterAll(ctx) { /* once before final teardown */ }
export async function beforeEach(ctx) { /* ctx.testInfo is set */ }
export async function afterEach(ctx) { /* ctx.testInfo + ctx.testResult set */ }
// Per-context — runs whenever a context is created/closed.
export async function afterOpenContext(ctx, name, spec) { /* spec = config.contexts[name] */ }
export async function beforeCloseContext(ctx, name, spec) { }
```
Built-in state reset (`dismissPendingErrors` + close all forms) runs after `afterEach` automatically. Don't reimplement it in `afterEach`.
Pass hook args after `--`:
```bash
node $RUN test tests/<app-name>/ --bail -- --rebuild-stand --data=demo
└─runner─┘ └────── hookArgs ─────────┘
```
**Where to put data setup:**
- DB restore, publication, EPF build → `prepare()`. Make it idempotent (hash-locks).
- Test-specific seed data → per-test `setup`.
- Shared session-wide warmup → `beforeAll`.
## Ready-to-paste patterns
A minimal CRUD shape is in *Test file anatomy* above — use it as the rhythm for catalog/document tests, swapping in the right section/command/fields. The patterns below cover what's specific to the regression engine, not the browser API (those live in SKILL.md).
### DCS report
```js
await openCommand('Остатки товаров');
// Reset user settings — 1C persists them between sessions.
await clickElement('Ещё');
await clickElement('Установить стандартные настройки');
await selectValue('Номенклатура', 'Товар 02'); // auto-enables the filter checkbox
await clickElement('Сформировать');
await wait(3);
const r = await readSpreadsheet();
assert.deepEqual(r.headers, ['Номенклатура', 'Количество', 'Сумма']);
assert.ok(r.data.length >= 1);
assert.ok(r.totals?.['Сумма']);
```
### Multi-user process
```js
export const contexts = ['clerk', 'manager'];
export default async function({ clerk, manager, step, assert }) {
await step('Кладовщик создаёт накладную', async () => {
await clerk.navigateSection('Склад');
await clerk.openCommand('Приходные накладные');
await clerk.clickElement('Создать');
await clerk.fillFields({ 'Контрагент': 'ООО Север' });
await clerk.clickElement('Записать');
});
await step('Менеджер утверждает накладную', async () => {
await manager.navigateSection('Согласование');
await manager.openCommand('На утверждении');
await manager.clickElement('ООО Север', { dblclick: true });
await manager.clickElement('Утвердить');
});
await step('Кладовщик видит новый статус', async () => {
const s = await clerk.getFormState();
assert.equal(s.fields['Статус']?.value, 'Утверждён');
});
await step('Освободить сессию кладовщика', async () => {
await manager.closeContext('clerk'); // free a 1C license for the next test
});
}
```
Close contexts you no longer need (`manager.closeContext('clerk')`) before the next multi-user test starts — frees a 1C web-client license and stops the previous role from holding state.
### Failing-test repro
```js
export const name = 'Bug #123: накладная без контрагента не должна проводиться';
export const tags = ['bug', 'validation'];
export default async function({ openCommand, clickElement, getFormState, assert, step }) {
await openCommand('Приходные накладные');
await clickElement('Создать');
await clickElement('Провести');
const s = await getFormState();
assert.ok(s.errorModal || s.fields['Контрагент']?.required,
'Должна быть ошибка валидации или поле помечено обязательным');
}
```
Write it red first, hand it to the user, fix the underlying issue, re-run green.
### Parameterised test
```js
export const name = 'Заполнение поля {type}';
export const params = [
{ type: 'String', field: 'Наименование', value: 'Тест' },
{ type: 'Number', field: 'Цена', value: '100.50' },
{ type: 'Date', field: 'ДатаПоступления', value: '01.01.2024' },
];
export default async function({ fillFields, getFormState, assert }, { type, field, value }) {
await fillFields({ [field]: value });
const state = await getFormState();
assert.equal(state.fields[field]?.value, String(value));
}
```
Each `params` entry becomes its own test in the report. `{key}` placeholders in `name` get substituted; without placeholders, a `[index]` suffix is added. `ctx.testInfo.param` carries the current row.
## Running
```bash
node $RUN test tests/<app-name>/ # full app suite
node $RUN test tests/<app-name>/03-goods-receipt/ # one feature folder
node $RUN test tests/<app-name>/02-counterparties/01-create.test.mjs # one file
node $RUN test tests/<app-name>/02-x.test.mjs tests/<app-name>/05-y.test.mjs # several files
node $RUN test tests/<app-name>/ --tags=smoke # by tag (intersection)
node $RUN test tests/<app-name>/ --grep='накладн' # by name regex
node $RUN test tests/<app-name>/ --bail --retry=1 # stop on first fail, allow 1 retry
node $RUN test tests/<app-name>/ --report=allure-results --format=allure --report-dir=allure-results
node $RUN test tests/<app-name>/ --report=- # machine JSON to stdout, progress to stderr
node $RUN test tests/<app-name>/ -- --rebuild-stand # after `--` → hookArgs
```
**Output contract.** `test` behaves like a test runner: by default the human report (with the summary as the last line) goes to **stdout** — read the tail of stdout + exit code. The machine report is opt-in via `--report`: `--report=path` writes it to a file (default JSON; XML for `--format=junit`), `--report=-` writes it to stdout while progress moves to stderr. Allure needs `--format=allure` + a directory (`-` is invalid for allure). For detailed triage use `--report=path` or `--report=-`. **In `--report=-` mode never use `2>&1`** — it merges stderr progress into the stdout JSON. (In the default mode there is no JSON in stdout, so `… | tail` is safe.)
### Allure static config — `_allure/`
The runner copies `<testDir>/_allure/` into the report directory before generating Allure output. Drop in `categories.json` (regex-based failure classification — useful for 1C-specific buckets: license pool exhaustion, platform exceptions, runner timeouts, assertion failures), `environment.properties` (optional, often emitted dynamically by `prepare()`), `executor.json` (CI metadata, skip locally). The underscore prefix keeps the directory out of test discovery.
## Severity guidance
When the user doesn't dictate, default to:
| Test kind | Severity |
|-----------|----------|
| Login + section navigation, basic CRUD on covered entities | `critical` (also tag `smoke`) |
| Documents posting, report generation, end-to-end processes | `critical` |
| Field-level edge cases, formatting, optional flows | `normal` |
| Cosmetic / recording / non-functional | `minor` |
| Reserved for show-stopper protections | `blocker` (use sparingly) |
Don't promote everything to `critical` — it loses signal in the Allure dashboard.
## Anti-patterns
- **Sleeps as a substitute for assertions.** `wait(5)` after `openCommand` is fine; `wait(30)` because something flakes is a bug — wait on `getFormState` instead.
- **Retry as a substitute for understanding.** "Not found" twice means the data isn't there or the label is wrong. Don't loop.
- **Position-based row identification** (`rows[0]`) when the DB has shared seed data. Filter by a unique marker (`Date.now()` suffix) instead.
- **Hand-writing reset code in `afterEach`.** The runner already closes forms and dismisses errors after the hook.
- **Cross-test state assumptions.** Each test must start from the desktop and seed its own data. Order-of-execution coupling is a regression-suite trap.
- **`tags: ['smoke']` on a 90-second test.** Smoke means fast.
- **Skipping recon** because "I know what this catalog looks like." The project's customisation almost certainly differs from stock.
(General browser-API anti-patterns — raw DOM, `clickElement('Закрыть')` instead of `closeForm()` — live in SKILL.md.)
## After a run — failure triage
1. Scan the JSON or Allure summary for `failed`.
2. For each failure, read `error.message` + `error.step` + screenshot.
3. If `error.onecError.stack` is present — it's a 1C exception, look at the platform trace.
4. Classify:
- **Test bug** — selector wrong, expectation wrong, race with no anchor → fix the test.
- **Application bug** — actual misbehaviour reproduced → report to the user with the failing step name and the platform stack.
- **Stand flake** — Apache timeout, login form not loading, license shortage → fix the hook idempotency or session-cleanup logic, not the test.
5. After fixes, re-run only the affected files before the full suite.
Report back to the user with the classification, not raw failure dumps.
## Reference
- Browser API: [SKILL.md](SKILL.md)
- Video and narration: [recording.md](recording.md)
@@ -1,56 +0,0 @@
// web-test browser v1.18 — engine facade: re-exports the public API from engine/*
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
/**
* Public API of the web-test engine. Pure re-export facade no logic here.
* Implementation lives in `./engine/*`. External callers (run.mjs, exec scripts,
* tests) import from this file; engine internals import each other directly.
*/
// ── core ──────────────────────────────────────────────────────────────────
export {
isConnected, getPage, ensureConnected, setPreserveClipboard,
} from './engine/core/state.mjs';
export {
pasteText, saveClipboard, restoreClipboard,
} from './engine/core/clipboard.mjs';
export { getFormState } from './engine/forms/state.mjs';
export { fetchErrorStack } from './engine/core/errors.mjs';
export { clickElement } from './engine/core/click.mjs';
// ── session ───────────────────────────────────────────────────────────────
export {
connect, disconnect, attach, detach, getSession,
createContext, setActiveContext, listContexts, getActiveContext,
hasContext, closeContext,
} from './engine/core/session.mjs';
// ── navigation ────────────────────────────────────────────────────────────
export {
getPageState, getSections, navigateSection, getCommands,
openCommand, switchTab, openFile, navigateLink,
} from './engine/nav/navigation.mjs';
// ── forms ─────────────────────────────────────────────────────────────────
export { selectValue } from './engine/forms/select-value.mjs';
export { fillFields, fillField } from './engine/forms/fill.mjs';
export { closeForm } from './engine/forms/close.mjs';
// ── tables ────────────────────────────────────────────────────────────────
export { readTable, deleteTableRow } from './engine/table/grid.mjs';
export { readSpreadsheet } from './engine/spreadsheet/spreadsheet.mjs';
export { fillTableRow } from './engine/table/row-fill.mjs';
export { filterList, unfilterList } from './engine/table/filter.mjs';
// ── recording / overlays ──────────────────────────────────────────────────
export {
screenshot, wait, isRecording, startRecording, stopRecording,
} from './engine/recording/capture.mjs';
export {
showCaption, hideCaption, getCaptions,
showTitleSlide, hideTitleSlide,
showImage, hideImage,
} from './engine/recording/captions.mjs';
export {
highlight, unhighlight, setHighlight, isHighlightMode,
} from './engine/recording/highlight.mjs';
export { addNarration } from './engine/recording/narration.mjs';
@@ -1,36 +0,0 @@
// web-test cli/commands/exec v1.0 — send script to running server
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import http from 'http';
import { readFileSync } from 'fs';
import { resolve } from 'path';
import { out, die, readStdin } from '../util.mjs';
import { loadSession } from '../session.mjs';
export async function cmdExec(fileOrDash, flags = {}) {
if (!fileOrDash) die('Usage: node src/run.mjs exec <file|-> [--no-record]');
const code = fileOrDash === '-'
? await readStdin()
: readFileSync(resolve(fileOrDash), 'utf-8');
const sess = loadSession();
const headers = {};
if (flags.noRecord) headers['x-no-record'] = '1';
const timeoutMs = flags.execTimeoutMs ?? 30 * 60 * 1000;
const result = await new Promise((resolveP, reject) => {
const req = http.request({
hostname: '127.0.0.1', port: sess.port, path: '/exec',
method: 'POST', timeout: timeoutMs, headers,
}, res => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => { try { resolveP(JSON.parse(data)); } catch { reject(new Error(data)); } });
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(new Error(`Exec timeout (${Math.round(timeoutMs / 60000)} min)`)); });
req.write(code);
req.end();
});
out(result);
if (!result.ok) process.exit(1);
}
@@ -1,22 +0,0 @@
// web-test cli/commands/run v1.0 — autonomous connect → exec → disconnect (no server)
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { readFileSync } from 'fs';
import { resolve } from 'path';
import * as browser from '../../browser.mjs';
import { out, die, readStdin } from '../util.mjs';
import { executeScript } from '../exec-context.mjs';
export async function cmdRun(url, fileOrDash) {
if (!url || !fileOrDash) die('Usage: node src/run.mjs run <url> <file|->');
const code = fileOrDash === '-'
? await readStdin()
: readFileSync(resolve(fileOrDash), 'utf-8');
await browser.connect(url);
const result = await executeScript(code);
await browser.disconnect();
out(result);
if (!result.ok) process.exit(1);
}
@@ -1,18 +0,0 @@
// web-test cli/commands/shot v1.0 — take screenshot via server
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { writeFileSync } from 'fs';
import { out, die } from '../util.mjs';
import { loadSession } from '../session.mjs';
export async function cmdShot(file) {
const sess = loadSession();
const resp = await fetch(`http://127.0.0.1:${sess.port}/shot`);
if (!resp.ok) {
const err = await resp.text();
die(`Screenshot failed: ${err}`);
}
const buf = Buffer.from(await resp.arrayBuffer());
const outFile = file || 'shot.png';
writeFileSync(outFile, buf);
out({ ok: true, file: outFile });
}
@@ -1,33 +0,0 @@
// web-test cli/commands/start v1.0
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import http from 'http';
import { writeFileSync } from 'fs';
import * as browser from '../../browser.mjs';
import { out, die } from '../util.mjs';
import { SESSION_FILE, cleanup } from '../session.mjs';
import { handleRequest } from '../server.mjs';
export async function cmdStart(url) {
if (!url) die('Usage: node src/run.mjs start <url>');
const state = await browser.connect(url);
const httpServer = http.createServer(handleRequest);
httpServer.listen(0, '127.0.0.1', () => {
const port = httpServer.address().port;
const session = {
port,
url,
pid: process.pid,
startedAt: new Date().toISOString()
};
writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));
out({ ok: true, message: 'Browser ready', port, ...state });
});
process.on('SIGINT', async () => {
await browser.disconnect();
cleanup();
process.exit(0);
});
}
@@ -1,14 +0,0 @@
// web-test cli/commands/status v1.0 — check session
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { existsSync, readFileSync } from 'fs';
import { out } from '../util.mjs';
import { SESSION_FILE } from '../session.mjs';
export function cmdStatus() {
if (!existsSync(SESSION_FILE)) {
out({ ok: false, message: 'No active session' });
process.exit(1);
}
const sess = JSON.parse(readFileSync(SESSION_FILE, 'utf-8'));
out({ ok: true, ...sess });
}
@@ -1,17 +0,0 @@
// web-test cli/commands/stop v1.0 — send stop to server
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { out } from '../util.mjs';
import { loadSession, cleanup } from '../session.mjs';
export async function cmdStop() {
const sess = loadSession();
try {
const resp = await fetch(`http://127.0.0.1:${sess.port}/stop`, { method: 'POST' });
const result = await resp.json();
out(result);
} catch {
// Server may have already exited before responding
out({ ok: true, message: 'Stopped' });
}
cleanup();
}
@@ -1,458 +0,0 @@
// web-test cli/commands/test v1.3 — regression test runner
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { existsSync, writeFileSync, mkdirSync } from 'fs';
import { resolve, dirname, basename, relative } from 'path';
import * as browser from '../../browser.mjs';
import { out, die, elapsed, slugify, formatDuration, interpolate, printSteps } from '../util.mjs';
import { buildContext, buildScopedContext } from '../exec-context.mjs';
import { createAssertions } from '../test-runner/assertions.mjs';
import { buildSeverityIndex } from '../test-runner/severity.mjs';
import { writeAllure, buildJUnit, syncAllureExtras } from '../test-runner/reporters.mjs';
import { discoverTests, resetState } from '../test-runner/discover.mjs';
export async function cmdTest(rawArgs) {
// Split off everything after `--` — those args belong to user-defined hooks
// (see spec §6: "all arguments after `--` are forwarded verbatim to _hooks.mjs
// via the hookArgs field; the runner does not interpret them").
const sepIdx = rawArgs.indexOf('--');
const ownArgs = sepIdx >= 0 ? rawArgs.slice(0, sepIdx) : rawArgs;
const hookArgs = sepIdx >= 0 ? rawArgs.slice(sepIdx + 1) : [];
// Parse flags
const opts = { bail: false, retry: 0, timeout: 30000, report: null, format: 'json', screenshot: null, reportDir: null, record: false };
let tags = null, grep = null, urlFlag = null;
const positional = [];
for (const a of ownArgs) {
if (a.startsWith('--tags=')) tags = a.slice(7).split(',');
else if (a.startsWith('--grep=')) grep = new RegExp(a.slice(7), 'i');
else if (a.startsWith('--url=')) urlFlag = a.slice(6);
else if (a === '--bail') opts.bail = true;
else if (a.startsWith('--retry=')) opts.retry = parseInt(a.slice(8)) || 0;
else if (a.startsWith('--timeout=')) opts.timeout = parseInt(a.slice(10)) || 30000;
else if (a.startsWith('--report=')) opts.report = a.slice(9);
else if (a.startsWith('--format=')) opts.format = a.slice(9);
else if (a.startsWith('--screenshot=')) opts.screenshot = a.slice(13);
else if (a.startsWith('--report-dir=')) opts.reportDir = a.slice(13);
else if (a === '--record') opts.record = true;
else if (!a.startsWith('--')) positional.push(a);
}
// Positional args are ALWAYS test paths (one or many). URL comes from --url= or config
// (see webtest.config.mjs). This matches pytest/jest/playwright; a positional that looks
// like a URL is a mistake → fail fast with a hint instead of feeding it to page.goto().
const isUrl = (s) => /^https?:\/\//i.test(s);
let url = urlFlag || null;
const testPaths = [...positional];
if (testPaths.length === 0) {
die('Usage: node run.mjs test <dir|file>... [--url=URL] [--tags=...] [--grep=...] [--bail] [--retry=N] [--timeout=ms] [--report=path]');
}
for (const p of testPaths) {
if (existsSync(resolve(p))) continue;
if (isUrl(p)) {
die(`"${p}" looks like a URL — use --url=<url>; positional args are test paths.`);
}
die(`Test path not found: "${p}". To run a subset use --grep= / --tags=, or pass an existing dir/file.`);
}
// Load config if exists. config (webtest.config.mjs) and hooks (_hooks.mjs) resolve from
// the FIRST path's directory — list paths from the same suite folder.
const firstPath = resolve(testPaths[0]);
const isFile = firstPath.endsWith('.test.mjs');
const testDir = isFile ? dirname(firstPath) : firstPath;
const configPath = resolve(testDir, 'webtest.config.mjs');
let config = {};
if (existsSync(configPath)) {
const mod = await import('file:///' + configPath.replace(/\\/g, '/'));
config = mod.default || {};
}
const severityIndex = buildSeverityIndex(config);
// Build context registry: name → url. Supports config.contexts or single config.url / CLI url.
const contextSpecs = {};
let defaultContextName = 'default';
const defaultIsolation = config.isolation || 'tab';
if (config.contexts && typeof config.contexts === 'object' && Object.keys(config.contexts).length) {
for (const [n, spec] of Object.entries(config.contexts)) {
contextSpecs[n] = { ...spec };
}
defaultContextName = config.defaultContext || Object.keys(config.contexts)[0];
if (url) contextSpecs[defaultContextName] = { ...contextSpecs[defaultContextName], url };
} else {
const fallbackUrl = url || config.url;
if (!fallbackUrl) die('No URL provided and no webtest.config.mjs found');
contextSpecs.default = { url: fallbackUrl };
}
if (!contextSpecs[defaultContextName]) {
die(`defaultContext "${defaultContextName}" not found in contexts: [${Object.keys(contextSpecs).join(', ')}]`);
}
if (!url) url = contextSpecs[defaultContextName].url;
// Apply config defaults (CLI flags override)
if (!tags && config.tags) tags = config.tags;
opts.timeout = ownArgs.some(a => a.startsWith('--timeout=')) ? opts.timeout : (config.timeout || opts.timeout);
opts.retry = ownArgs.some(a => a.startsWith('--retry=')) ? opts.retry : (config.retries || opts.retry);
if (config.preserveClipboard === false && !ownArgs.includes('--no-preserve-clipboard')) {
browser.setPreserveClipboard(false);
}
opts.record = opts.record || !!config.record;
opts.screenshot = opts.screenshot || config.screenshot || 'on-failure';
if (!['on-failure', 'every-step', 'off'].includes(opts.screenshot)) {
die(`Invalid --screenshot=${opts.screenshot} (expected on-failure|every-step|off)`);
}
if (!['json', 'allure', 'junit'].includes(opts.format)) {
die(`Invalid --format=${opts.format} (expected json|allure|junit)`);
}
if (opts.format === 'junit' && !opts.report) {
die('--format=junit requires --report=path.xml');
}
// `--report=-` means "machine report to stdout" (Unix `-` convention).
// Only meaningful for streamable formats (json/junit); allure is a directory.
const reportToStdout = opts.report === '-';
if (reportToStdout && opts.format === 'allure') {
die('--report=- (stdout) is not valid with --format=allure: allure emits a directory of files, not a single stream. Use --report-dir=<dir> instead.');
}
const reportDir = opts.reportDir
? resolve(opts.reportDir)
: (opts.report && !reportToStdout ? dirname(resolve(opts.report)) : testDir);
if (opts.screenshot !== 'off') {
try { mkdirSync(reportDir, { recursive: true }); } catch {}
}
// Discover test files
const testFiles = discoverTests(testPaths);
if (!testFiles.length) die(`No *.test.mjs files found in ${testPaths.join(', ')}`);
// Import and filter tests
const tests = [];
let hasOnly = false;
for (const file of testFiles) {
const mod = await import('file:///' + file.replace(/\\/g, '/'));
const base = {
file: relative(testDir, file).replace(/\\/g, '/'),
name: mod.name || basename(file, '.test.mjs'),
tags: mod.tags || [],
timeout: mod.timeout || opts.timeout,
skip: mod.skip || false,
only: mod.only || false,
setup: mod.setup,
teardown: mod.teardown,
fn: mod.default,
param: undefined,
context: mod.context || null,
contexts: Array.isArray(mod.contexts) ? mod.contexts : null,
severity: typeof mod.severity === 'string' ? mod.severity : null,
};
if (base.only) hasOnly = true;
if (Array.isArray(mod.params) && mod.params.length) {
for (let i = 0; i < mod.params.length; i++) {
const p = mod.params[i];
const name = base.name.includes('{') ? interpolate(base.name, p) : `${base.name}[${i}]`;
tests.push({ ...base, name, param: p });
}
} else {
tests.push(base);
}
}
// Filter
const filtered = tests.filter(t => {
if (hasOnly && !t.only) return false;
if (tags && !tags.some(tag => t.tags.includes(tag))) return false;
if (grep && !grep.test(t.name)) return false;
return true;
});
// Load hooks
const hooksPath = resolve(testDir, '_hooks.mjs');
let hooks = {};
if (existsSync(hooksPath)) {
hooks = await import('file:///' + hooksPath.replace(/\\/g, '/'));
}
// Human-readable report goes to stdout (test-runner convention: jest/pytest/playwright).
// In `--report -` mode the machine JSON/XML takes over stdout, so progress moves to stderr.
const W = reportToStdout ? process.stderr : process.stdout;
W.write(`\nweb-test -- ${url}\n`);
W.write(`Running ${filtered.length} tests from ${relative(process.cwd(), testDir).replace(/\\/g, '/') || '.'}/\n\n`);
const startedAt = new Date().toISOString();
const results = [];
let passCount = 0, failCount = 0, skipCount = 0;
const hookLog = (...a) => W.write(`[hooks] ${a.map(String).join(' ')}\n`);
const hookEnv = { hookArgs, log: hookLog, config };
if (hooks.prepare) await hooks.prepare(hookEnv);
// Lazy context creation
async function ensureContext(name) {
if (browser.hasContext(name)) return;
const spec = contextSpecs[name];
if (!spec) throw new Error(`Unknown context "${name}". Defined: [${Object.keys(contextSpecs).join(', ')}]`);
await browser.createContext(name, spec.url, { isolation: spec.isolation || defaultIsolation });
if (hooks.afterOpenContext && hookCtx) {
try { await hooks.afterOpenContext(hookCtx, name, spec); }
catch (e) { hookLog(`afterOpenContext("${name}") threw: ${e.message.split('\n')[0]}`); }
}
}
let hookCtx = null;
function wrapCloseContextHook(target) {
const orig = target.closeContext;
if (typeof orig !== 'function') return;
target.closeContext = async (name) => {
if (hooks.beforeCloseContext) {
try { await hooks.beforeCloseContext(target, name, contextSpecs[name]); }
catch (e) { hookLog(`beforeCloseContext("${name}") threw: ${e.message.split('\n')[0]}`); }
}
return await orig(name);
};
}
try {
// Connect: create default context up front
await ensureContext(defaultContextName);
const ctx = buildContext({ noRecord: false });
ctx.assert = createAssertions();
ctx.log = (...a) => { /* per-test, overridden below */ };
wrapCloseContextHook(ctx);
hookCtx = ctx;
// Default context was created BEFORE hookCtx existed → fire afterOpenContext now.
if (hooks.afterOpenContext) {
try { await hooks.afterOpenContext(ctx, defaultContextName, contextSpecs[defaultContextName]); }
catch (e) { hookLog(`afterOpenContext("${defaultContextName}") threw: ${e.message.split('\n')[0]}`); }
}
if (hooks.beforeAll) await hooks.beforeAll(ctx);
let testIdx = 0;
for (const t of filtered) {
testIdx++;
const declaredContexts = t.contexts && t.contexts.length
? t.contexts
: [t.context || defaultContextName];
if (t.skip) {
const reason = typeof t.skip === 'string' ? t.skip : '';
W.write(`${t.name}${reason ? ` (skip: ${reason})` : ' (skip)'}\n`);
results.push({ name: t.name, file: t.file, tags: t.tags, contexts: declaredContexts, status: 'skipped', duration: 0, attempts: 0, steps: [], output: '', error: null, screenshot: null });
skipCount++;
continue;
}
const testContextNames = declaredContexts;
try {
for (const cn of testContextNames) await ensureContext(cn);
await browser.setActiveContext(testContextNames[0]);
} catch (e) {
W.write(`${t.name} (context setup failed: ${e.message})\n`);
results.push({ name: t.name, file: t.file, tags: t.tags, contexts: declaredContexts, status: 'failed', duration: 0, attempts: 0, steps: [], output: '', error: { message: e.message }, screenshot: null });
failCount++;
if (opts.bail) break;
continue;
}
let lastError = null;
let testResult = null;
const maxAttempts = 1 + opts.retry;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const output = [];
let steps = [];
let currentSteps = steps;
let stepIdx = 0;
const t0 = Date.now();
ctx.testInfo = {
name: t.name,
file: basename(t.file),
filePath: t.file,
tags: t.tags,
timeout: t.timeout,
attempt,
maxAttempts,
param: t.param,
contexts: Object.fromEntries(testContextNames.map(n => [n, contextSpecs[n]])),
primaryContext: testContextNames[0],
};
ctx.testResult = null;
let videoFile = null;
if (opts.record) {
videoFile = resolve(reportDir, `${testIdx}-${slugify(t.name)}.mp4`);
try { await browser.startRecording(videoFile, { force: true }); } catch { videoFile = null; }
}
ctx.log = (...a) => output.push(a.map(String).join(' '));
ctx.step = async (name, fn) => {
const s = { name, start: Date.now(), status: 'passed', steps: [] };
currentSteps.push(s);
const prev = currentSteps;
currentSteps = s.steps;
stepIdx++;
const myIdx = stepIdx;
try {
await fn();
} catch (e) {
s.status = 'failed';
s.error = e.message;
throw e;
} finally {
s.stop = Date.now();
currentSteps = prev;
if (opts.screenshot === 'every-step' && s.status === 'passed') {
try {
const slug = slugify(name);
const file = resolve(reportDir, `${testIdx}-${myIdx}-${slug}.png`);
const png = await browser.screenshot();
writeFileSync(file, png);
s.screenshot = file;
} catch {}
}
}
};
const scopedKeys = [];
if (t.contexts && t.contexts.length) {
for (const cn of t.contexts) {
ctx[cn] = buildScopedContext(cn);
wrapCloseContextHook(ctx[cn]);
scopedKeys.push(cn);
}
}
try {
if (hooks.beforeEach) await hooks.beforeEach(ctx);
if (t.setup) await t.setup(ctx);
let timeoutTimer;
try {
await Promise.race([
t.fn(ctx, t.param),
new Promise((_, reject) => { timeoutTimer = setTimeout(() => reject(new Error(`Timeout (${t.timeout}ms)`)), t.timeout); }),
]);
} finally {
// Clear the guard timer — otherwise it stays armed in the event loop and,
// since the success path never calls process.exit(), node can't exit until
// it fires (up to `timeout` ms after the last test finished).
clearTimeout(timeoutTimer);
}
if (t.teardown) try { await t.teardown(ctx); } catch {}
ctx.testResult = { status: 'passed', duration: elapsed(t0), attempts: attempt, error: null, steps };
if (hooks.afterEach) try { await hooks.afterEach(ctx); } catch {}
for (const cn of testContextNames) {
try { await browser.setActiveContext(cn); await resetState(ctx); } catch {}
}
for (const k of scopedKeys) delete ctx[k];
if (videoFile) {
try { await browser.stopRecording(); } catch {}
}
const dur = elapsed(t0);
testResult = { name: t.name, file: t.file, tags: t.tags, contexts: testContextNames, severity: t.severity, status: 'passed', duration: dur, attempts: attempt, start: t0, stop: Date.now(), steps, output: output.join('\n'), error: null, screenshot: null, video: videoFile };
lastError = null;
break;
} catch (e) {
// Screenshot on failure FIRST — before teardown/afterEach/resetState reset the UI.
let shotFile = e.onecError?.screenshot;
if (!shotFile && opts.screenshot !== 'off') {
try {
const png = await browser.screenshot();
shotFile = resolve(reportDir, `error-${testIdx}-${slugify(t.file.replace(/\.test\.mjs$/, ''))}.png`);
writeFileSync(shotFile, png);
} catch {}
}
if (t.teardown) try { await t.teardown(ctx); } catch {}
const errInfo = { message: e.message, step: e.onecError?.step, screenshot: shotFile, onecError: e.onecError };
ctx.testResult = { status: 'failed', duration: elapsed(t0), attempts: attempt, error: errInfo, steps };
if (hooks.afterEach) try { await hooks.afterEach(ctx); } catch {}
for (const cn of testContextNames) {
try { await browser.setActiveContext(cn); await resetState(ctx); } catch {}
}
for (const k of scopedKeys) delete ctx[k];
if (videoFile) {
try { await browser.stopRecording(); } catch {}
}
lastError = errInfo;
const dur = elapsed(t0);
testResult = { name: t.name, file: t.file, tags: t.tags, contexts: testContextNames, severity: t.severity, status: 'failed', duration: dur, attempts: attempt, start: t0, stop: Date.now(), steps, output: output.join('\n'), error: errInfo, screenshot: shotFile, video: videoFile };
}
}
results.push(testResult);
if (testResult.status === 'passed') {
passCount++;
W.write(`${t.name} (${testResult.duration}s)\n`);
} else {
failCount++;
W.write(`${t.name} (${testResult.duration}s)\n`);
printSteps(W, testResult.steps, ' ');
if (lastError?.message) W.write(` ${lastError.message}\n`);
if (lastError?.screenshot) W.write(` screenshot: ${lastError.screenshot}\n`);
}
if (opts.bail && testResult.status === 'failed') break;
}
if (hooks.afterAll) try { await hooks.afterAll(ctx); } catch {}
} finally {
// Per-context teardown
try {
const remaining = browser.listContexts();
if (remaining.length > 0) {
const survivor = remaining[0];
try { await browser.setActiveContext(survivor); } catch {}
for (let i = remaining.length - 1; i >= 1; i--) {
const name = remaining[i];
if (hooks.beforeCloseContext && hookCtx) {
try { await hooks.beforeCloseContext(hookCtx, name, contextSpecs[name]); }
catch (e) { hookLog(`beforeCloseContext("${name}") threw: ${e.message.split('\n')[0]}`); }
}
try { await browser.closeContext(name); }
catch (e) { hookLog(`closeContext("${name}") failed: ${e.message.split('\n')[0]}`); }
}
if (hooks.beforeCloseContext && hookCtx) {
try { await hooks.beforeCloseContext(hookCtx, survivor, contextSpecs[survivor]); }
catch (e) { hookLog(`beforeCloseContext("${survivor}") threw: ${e.message.split('\n')[0]}`); }
}
}
} catch (e) {
hookLog(`final teardown loop failed: ${e.message.split('\n')[0]}`);
}
try { await browser.disconnect(); } catch {}
if (hooks.cleanup) try { await hooks.cleanup(hookEnv); } catch {}
}
const finishedAt = new Date().toISOString();
const totalDuration = results.reduce((s, r) => s + r.duration, 0);
W.write(`\n${passCount} passed, ${failCount} failed, ${skipCount} skipped (${formatDuration(totalDuration)})\n\n`);
const report = {
runner: 'web-test', url, startedAt, finishedAt,
duration: totalDuration,
summary: { total: results.length, passed: passCount, failed: failCount, skipped: skipCount },
tests: results,
};
if (opts.format === 'allure') {
writeAllure(results, reportDir, severityIndex);
syncAllureExtras(testDir, reportDir);
} else if (opts.format === 'junit') {
if (reportToStdout) process.stdout.write(buildJUnit(report, testDir) + '\n');
else writeFileSync(resolve(opts.report), buildJUnit(report, testDir));
} else if (reportToStdout) {
out(report);
} else if (opts.report) {
writeFileSync(resolve(opts.report), JSON.stringify(report, null, 2));
}
if (failCount > 0) process.exit(1);
}
@@ -1,148 +0,0 @@
// web-test cli/exec-context v1.0 — buildContext + executeScript для run/exec/test
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { readFileSync, writeFileSync } from 'fs';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import * as browser from '../browser.mjs';
import { elapsed } from './util.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const ERROR_SHOT_PATH = resolve(__dirname, '..', '..', 'error-shot.png');
/**
* Build a per-context wrapper: same shape as buildContext output, but every call
* is prefixed with `setActiveContext(name)` so the test can interleave actions
* across contexts (`ctx.a.click(...); ctx.b.click(...)`).
*/
export function buildScopedContext(name) {
const inner = buildContext({ noRecord: false });
const scoped = {};
for (const [k, v] of Object.entries(inner)) {
if (typeof v === 'function') {
scoped[k] = async (...args) => {
await browser.setActiveContext(name);
return v(...args);
};
} else {
scoped[k] = v;
}
}
return scoped;
}
export function buildContext({ noRecord = false } = {}) {
const ctx = {};
for (const [k, v] of Object.entries(browser)) {
if (k !== 'default') ctx[k] = v;
}
ctx.writeFileSync = writeFileSync;
ctx.readFileSync = readFileSync;
// --no-record: stub recording/narration functions to return safe defaults
if (noRecord) {
const noop = async () => {};
ctx.startRecording = noop;
ctx.stopRecording = async () => ({ file: null, duration: 0, size: 0 });
ctx.addNarration = async () => ({ file: null, duration: 0, size: 0, captions: 0 });
for (const fn of ['showCaption', 'hideCaption']) {
ctx[fn] = noop;
}
ctx.isRecording = () => false;
ctx.getCaptions = () => [];
}
// Wrap action functions to auto-detect 1C errors (modal, balloon)
// and stop execution immediately with diagnostic info
const ACTION_FNS = [
'clickElement', 'fillFields', 'fillField', 'selectValue', 'fillTableRow',
'deleteTableRow', 'openCommand', 'navigateSection', 'navigateLink', 'openFile',
'closeForm', 'filterList', 'unfilterList'
];
for (const name of ACTION_FNS) {
if (typeof ctx[name] !== 'function') continue;
const orig = ctx[name];
ctx[name] = async (...args) => {
const result = await orig(...args);
const errors = result?.errors;
if (errors?.modal || errors?.balloon) {
// Screenshot while the error modal is still visible (before fetchErrorStack closes it)
let errorShot;
try {
const png = await ctx.screenshot();
errorShot = ERROR_SHOT_PATH;
writeFileSync(errorShot, png);
} catch {}
// Try to fetch call stack for modal errors before throwing
let stack = null;
if (errors?.modal && typeof ctx.fetchErrorStack === 'function') {
try {
stack = await ctx.fetchErrorStack(errors.modal.formNum, errors.modal.hasReport);
} catch { /* don't fail if stack fetch fails */ }
}
const msg = errors.modal?.message || errors.balloon?.message || 'Unknown 1C error';
const err = new Error(msg);
err.onecError = { step: name, args, errors, formState: result, stack, screenshot: errorShot };
throw err;
}
return result;
};
}
return ctx;
}
export async function executeScript(code, { noRecord } = {}) {
const output = [];
const origLog = console.log;
const origErr = console.error;
console.log = (...a) => output.push(a.map(String).join(' '));
console.error = (...a) => output.push('[ERR] ' + a.map(String).join(' '));
const t0 = Date.now();
try {
const ctx = buildContext({ noRecord });
// Normalize Windows backslash paths to prevent JS parse errors
// (e.g. C:\Users\... → \u triggers "Invalid Unicode escape sequence")
code = code.replace(/[A-Za-z]:\\[^\s'"`;\n)}\]]+/g, m => m.replace(/\\/g, '/'));
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
const fn = new AsyncFunction(...Object.keys(ctx), code);
await fn(...Object.values(ctx));
console.log = origLog;
console.error = origErr;
return { ok: true, output: output.join('\n'), elapsed: elapsed(t0) };
} catch (e) {
console.log = origLog;
console.error = origErr;
// Auto-stop recording if active (prevents "Already recording" on next exec)
if (browser.isRecording()) {
try { await browser.stopRecording(); } catch {}
}
// Error screenshot (skip if already taken before fetchErrorStack closed the modal)
let shotFile = e.onecError?.screenshot;
if (!shotFile) {
try {
const png = await browser.screenshot();
shotFile = ERROR_SHOT_PATH;
writeFileSync(shotFile, png);
} catch {}
}
const result = { ok: false, error: e.message, output: output.join('\n'), screenshot: shotFile, elapsed: elapsed(t0) };
// Enrich with 1C error context if available
if (e.onecError) {
result.step = e.onecError.step;
result.stepArgs = e.onecError.args;
result.onecErrors = e.onecError.errors;
result.formState = e.onecError.formState;
if (e.onecError.stack) result.stack = e.onecError.stack;
}
return result;
}
}
@@ -1,37 +0,0 @@
// web-test cli/server v1.0 — HTTP server для exec/shot/stop/status в процессе start
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import * as browser from '../browser.mjs';
import { json, readBody } from './util.mjs';
import { cleanup } from './session.mjs';
import { executeScript } from './exec-context.mjs';
export async function handleRequest(req, res) {
try {
if (req.method === 'POST' && req.url === '/exec') {
const code = await readBody(req);
const noRecord = req.headers['x-no-record'] === '1';
const result = await executeScript(code, { noRecord });
json(res, result);
} else if (req.method === 'GET' && req.url === '/shot') {
const png = await browser.screenshot();
res.writeHead(200, { 'Content-Type': 'image/png' });
res.end(png);
} else if (req.method === 'POST' && req.url === '/stop') {
json(res, { ok: true, message: 'Stopping' });
await browser.disconnect();
cleanup();
process.exit(0);
} else if (req.method === 'GET' && req.url === '/status') {
json(res, { ok: true, connected: browser.isConnected() });
} else {
res.writeHead(404);
res.end('Not found');
}
} catch (e) {
json(res, { ok: false, error: e.message }, 500);
}
}
@@ -1,20 +0,0 @@
// web-test cli/session v1.0 — session-file helpers for HTTP-server mode
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { existsSync, readFileSync, unlinkSync } from 'fs';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import { die } from './util.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
export const SESSION_FILE = resolve(__dirname, '..', '..', '.browser-session.json');
export function loadSession() {
if (!existsSync(SESSION_FILE)) {
die('No active session. Run: node src/run.mjs start <url>');
}
return JSON.parse(readFileSync(SESSION_FILE, 'utf-8'));
}
export function cleanup() {
try { unlinkSync(SESSION_FILE); } catch {}
}
@@ -1,64 +0,0 @@
// web-test cli/test-runner/assertions v1.0 — ctx.assert API
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
export function createAssertions() {
class AssertionError extends Error {
constructor(msg, actual, expected) {
super(msg);
this.name = 'AssertionError';
this.actual = actual;
this.expected = expected;
}
}
return {
ok(value, msg) {
if (!value) throw new AssertionError(msg || `Expected truthy, got ${JSON.stringify(value)}`, value, true);
},
equal(actual, expected, msg) {
if (actual !== expected) throw new AssertionError(msg || `Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`, actual, expected);
},
notEqual(actual, expected, msg) {
if (actual === expected) throw new AssertionError(msg || `Expected not ${JSON.stringify(expected)}`, actual, expected);
},
deepEqual(actual, expected, msg) {
const a = JSON.stringify(actual), b = JSON.stringify(expected);
if (a !== b) throw new AssertionError(msg || `Deep equal failed:\n actual: ${a}\n expected: ${b}`, actual, expected);
},
includes(haystack, needle, msg) {
const h = Array.isArray(haystack) ? haystack : String(haystack);
if (!h.includes(needle)) throw new AssertionError(msg || `Expected ${JSON.stringify(h)} to include ${JSON.stringify(needle)}`, haystack, needle);
},
match(string, regex, msg) {
if (!regex.test(string)) throw new AssertionError(msg || `Expected ${JSON.stringify(string)} to match ${regex}`, string, regex);
},
async throws(fn, msg) {
try { await fn(); } catch { return; }
throw new AssertionError(msg || 'Expected function to throw');
},
// 1C-specific
formHasField(state, fieldName, msg) {
if (!state?.fields?.[fieldName]) throw new AssertionError(msg || `Field "${fieldName}" not found in form. Available: ${Object.keys(state?.fields || {}).join(', ')}`, null, fieldName);
},
formTitle(state, expected, msg) {
if (!state?.title?.includes(expected)) throw new AssertionError(msg || `Form title "${state?.title}" does not contain "${expected}"`, state?.title, expected);
},
tableHasRow(table, predicate, msg) {
const rows = table?.rows || [];
let found;
if (typeof predicate === 'function') {
found = rows.some(predicate);
} else {
found = rows.some(r => Object.entries(predicate).every(([k, v]) => r[k] === v));
}
if (!found) throw new AssertionError(msg || `No row matching predicate in table (${rows.length} rows)`, null, predicate);
},
tableRowCount(table, expected, msg) {
const actual = table?.rows?.length ?? 0;
if (actual !== expected) throw new AssertionError(msg || `Expected ${expected} rows, got ${actual}`, actual, expected);
},
noErrors(state, msg) {
if (state?.errors) throw new AssertionError(msg || `Form has errors: ${JSON.stringify(state.errors)}`, state.errors, null);
},
};
}
@@ -1,43 +0,0 @@
// web-test cli/test-runner/discover v1.1 — test file discovery + state reset between tests
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { existsSync, readdirSync } from 'fs';
import { resolve } from 'path';
// Accepts a single path or an array of paths (files and/or dirs). Each .test.mjs file is
// taken directly; each directory is walked recursively (skipping _ / . prefixes). Results
// are deduped and sorted — sorting preserves the numeric-prefix order the suite relies on
// (00-, 01-, …) even when paths are listed out of order.
export function discoverTests(testPaths) {
const paths = Array.isArray(testPaths) ? testPaths : [testPaths];
const files = [];
function walk(dir) {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.name.startsWith('_') || entry.name.startsWith('.')) continue;
const full = resolve(dir, entry.name);
if (entry.isDirectory()) walk(full);
else if (entry.name.endsWith('.test.mjs')) files.push(full);
}
}
for (const p of paths) {
const full = resolve(p);
if (full.endsWith('.test.mjs')) {
if (existsSync(full)) files.push(full);
} else if (existsSync(full)) {
walk(full);
}
}
return [...new Set(files)].sort();
}
export async function resetState(ctx) {
try { if (typeof ctx.dismissPendingErrors === 'function') await ctx.dismissPendingErrors(); } catch {}
for (let i = 0; i < 10; i++) {
try {
const state = await ctx.getFormState();
// form === null means no form open (desktop). form === 0 is a real background form
// 1C exposes in some states — must still close it to fully reset.
if (state.form == null) break;
await ctx.closeForm({ save: false });
} catch { break; }
}
}
@@ -1,113 +0,0 @@
// web-test cli/test-runner/reporters v1.0 — Allure/JUnit writers + extras sync
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { writeFileSync, existsSync, readdirSync, copyFileSync, statSync } from 'fs';
import { resolve, dirname, basename, relative } from 'path';
import { randomUUID } from 'crypto';
import { xmlEscape } from '../util.mjs';
import { resolveSeverity } from './severity.mjs';
/**
* Copy any files from `<testDir>/_allure/` into `reportDir`. Convention for
* Allure customization that doesn't fit inside per-test JSON:
* - `categories.json` failure classification (regex bucket)
* - `environment.properties` values shown in the Environment widget
* - `executor.json` CI/CD metadata
* Underscored folder mirrors `_hooks.mjs` convention (infra, not a test).
* Silent if folder absent.
*/
export function syncAllureExtras(testDir, reportDir) {
const extrasDir = resolve(testDir, '_allure');
if (!existsSync(extrasDir)) return;
try {
if (!statSync(extrasDir).isDirectory()) return;
} catch { return; }
for (const entry of readdirSync(extrasDir, { withFileTypes: true })) {
if (!entry.isFile()) continue;
try { copyFileSync(resolve(extrasDir, entry.name), resolve(reportDir, entry.name)); }
catch { /* best-effort */ }
}
}
export function writeAllure(results, reportDir, severityIndex) {
for (const tr of results) {
if (tr.status === 'skipped') continue; // Allure ignores skipped without start/stop
const uuid = randomUUID();
const suite = dirname(tr.file);
const suiteLabel = (suite && suite !== '.') ? suite : 'root';
const severity = resolveSeverity(tr, severityIndex);
const out = {
uuid,
name: tr.name,
fullName: tr.file,
status: tr.status,
stage: 'finished',
start: tr.start,
stop: tr.stop,
labels: [
...(tr.tags || []).map(t => ({ name: 'tag', value: t })),
{ name: 'suite', value: suiteLabel },
{ name: 'severity', value: severity },
],
steps: (tr.steps || []).map(allureStep),
attachments: [
...(tr.screenshot ? [{ name: 'Screenshot on failure', source: basename(tr.screenshot), type: 'image/png' }] : []),
...(tr.video ? [{ name: 'Video', source: basename(tr.video), type: 'video/mp4' }] : []),
],
};
if (tr.status === 'failed' && tr.error) {
const traceParts = [];
if (tr.output) traceParts.push(tr.output);
const onecStack = tr.error.onecError?.stack?.raw;
if (onecStack) {
if (traceParts.length) traceParts.push('\n--- 1C stack ---\n');
traceParts.push(onecStack);
}
out.statusDetails = { message: tr.error.message || '', trace: traceParts.join('') };
}
writeFileSync(resolve(reportDir, `${uuid}-result.json`), JSON.stringify(out, null, 2));
}
}
function allureStep(s) {
const out = {
name: s.name,
status: s.status,
stage: 'finished',
start: s.start,
stop: s.stop,
steps: (s.steps || []).map(allureStep),
};
if (s.screenshot) {
out.attachments = [{ name: 'Screenshot', source: basename(s.screenshot), type: 'image/png' }];
}
if (s.status === 'failed' && s.error) {
out.statusDetails = { message: s.error, trace: s.error };
}
return out;
}
export function buildJUnit(report, testDir) {
const { summary, duration, tests } = report;
const suiteName = relative(process.cwd(), testDir).replace(/\\/g, '/') || '.';
const lines = ['<?xml version="1.0" encoding="UTF-8"?>'];
lines.push(`<testsuites name="web-test" tests="${summary.total}" failures="${summary.failed}" skipped="${summary.skipped}" time="${duration.toFixed(3)}">`);
lines.push(` <testsuite name="${xmlEscape(suiteName)}" tests="${summary.total}" failures="${summary.failed}" skipped="${summary.skipped}" time="${duration.toFixed(3)}">`);
for (const t of tests) {
const attrs = `name="${xmlEscape(t.name)}" classname="${xmlEscape(t.file)}" time="${(t.duration || 0).toFixed(3)}"`;
if (t.status === 'passed') {
lines.push(` <testcase ${attrs}/>`);
} else if (t.status === 'skipped') {
lines.push(` <testcase ${attrs}><skipped/></testcase>`);
} else {
lines.push(` <testcase ${attrs}>`);
const msg = t.error?.message || '';
const trace = t.output || '';
lines.push(` <failure message="${xmlEscape(msg)}">${xmlEscape(trace)}</failure>`);
if (t.screenshot) lines.push(` <system-out>screenshot: ${xmlEscape(t.screenshot)}</system-out>`);
lines.push(` </testcase>`);
}
}
lines.push(` </testsuite>`);
lines.push(`</testsuites>`);
return lines.join('\n');
}
@@ -1,66 +0,0 @@
// web-test cli/test-runner/severity v1.0 — Allure severity policy resolver
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { die } from '../util.mjs';
export const SEVERITY_RANK = { blocker: 5, critical: 4, normal: 3, minor: 2, trivial: 1 };
export const SEVERITY_LEVELS = Object.keys(SEVERITY_RANK);
/**
* Validate config.severity (inverted map: severity [tags]) at config load time.
* Returns:
* - tagToSeverity: Map<tag, severity> (precomputed lookup for the resolver)
* - defaultSeverity: string (validated, defaults to 'normal')
* Throws (via die) on invalid keys, invalid default, or duplicate tag across buckets.
*/
export function buildSeverityIndex(config) {
const tagToSeverity = new Map();
const sev = config.severity || {};
if (typeof sev !== 'object' || Array.isArray(sev)) {
die(`config.severity must be an object, got ${typeof sev}`);
}
for (const [level, tags] of Object.entries(sev)) {
if (!SEVERITY_LEVELS.includes(level)) {
die(`config.severity: unknown level "${level}". Allowed: ${SEVERITY_LEVELS.join('|')}`);
}
if (!Array.isArray(tags)) {
die(`config.severity.${level} must be an array of tag names, got ${typeof tags}`);
}
for (const tag of tags) {
if (tagToSeverity.has(tag)) {
die(`config.severity: tag "${tag}" listed under both "${tagToSeverity.get(tag)}" and "${level}" — pick one`);
}
tagToSeverity.set(tag, level);
}
}
const def = config.defaultSeverity || 'normal';
if (!SEVERITY_LEVELS.includes(def)) {
die(`config.defaultSeverity: "${def}" is not a valid level. Allowed: ${SEVERITY_LEVELS.join('|')}`);
}
return { tagToSeverity, defaultSeverity: def };
}
/**
* Resolve a test's severity. Precedence:
* 1. explicit `export const severity` from the test module
* 2. max-rank severity found among tags (either standard severity name, or mapped via config)
* 3. defaultSeverity from config (or 'normal' if not set)
* Returns one of SEVERITY_LEVELS.
*/
export function resolveSeverity(t, severityIndex) {
if (t.severity) {
if (!SEVERITY_LEVELS.includes(t.severity)) {
return severityIndex.defaultSeverity;
}
return t.severity;
}
let best = null;
for (const tag of t.tags || []) {
let candidate = null;
if (SEVERITY_LEVELS.includes(tag)) candidate = tag;
else if (severityIndex.tagToSeverity.has(tag)) candidate = severityIndex.tagToSeverity.get(tag);
if (candidate && (best === null || SEVERITY_RANK[candidate] > SEVERITY_RANK[best])) {
best = candidate;
}
}
return best || severityIndex.defaultSeverity;
}
@@ -1,113 +0,0 @@
// web-test cli/util v1.2 — generic helpers for CLI commands
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
export function out(obj) {
process.stdout.write(JSON.stringify(obj, null, 2) + '\n');
}
export function die(msg) {
process.stderr.write(msg + '\n');
process.exit(1);
}
export function json(res, obj, status = 200) {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(obj, null, 2));
}
export async function readBody(req) {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
return Buffer.concat(chunks).toString('utf-8');
}
export async function readStdin() {
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
return Buffer.concat(chunks).toString('utf-8');
}
export function elapsed(t0) {
return Math.round((Date.now() - t0) / 100) / 10;
}
export function elapsed2(start, stop) {
return Math.round(((stop || Date.now()) - start) / 100) / 10;
}
export function slugify(s) {
return String(s).trim()
.replace(/[\s/\\:*?"<>|]+/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 60) || 'step';
}
export function formatDuration(seconds) {
if (seconds < 60) return `${Math.round(seconds * 10) / 10}s`;
const m = Math.floor(seconds / 60);
const s = Math.round((seconds - m * 60) * 10) / 10;
return `${m}m ${s}s`;
}
export function xmlEscape(s) {
return String(s == null ? '' : s)
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/"/g, '&quot;').replace(/'/g, '&apos;');
}
export function interpolate(template, params) {
return String(template).replace(/\{(\w+)\}/g, (_, key) =>
params[key] !== undefined ? String(params[key]) : `{${key}}`);
}
export function printSteps(W, steps, indent) {
for (let i = 0; i < steps.length; i++) {
const s = steps[i];
const last = i === steps.length - 1;
const prefix = last ? '└' : '├';
const mark = s.status === 'failed' ? '✗ ' : '';
W.write(`${indent}${prefix} ${mark}${s.name} (${elapsed2(s.start, s.stop)}s)\n`);
if (s.error && s.status === 'failed') {
W.write(`${indent} ${s.error}\n`);
}
if (s.steps.length) printSteps(W, s.steps, indent + ' ');
}
}
export function usage() {
die(`Usage: node run.mjs <command> [args]
Commands:
start <url> Launch browser and connect to 1C web client
run <url> <file|-> Autonomous: connect, execute script, disconnect
exec <file|-> [options] Execute script (file path or - for stdin)
shot [file] Take screenshot (default: shot.png)
stop Logout and close browser
status Check session status
test <dir|file>... Run regression tests (*.test.mjs); accepts multiple paths
Options for exec:
--no-record Skip video recording (record() becomes no-op)
Global options (any command):
--no-preserve-clipboard Don't save/restore OS clipboard around action calls.
Default: on (env: WEB_TEST_PRESERVE_CLIPBOARD=0 to disable globally).
Options for test:
--url=URL Override the base URL (default: from webtest.config.mjs)
--tags=smoke,crud Filter tests by tags
--grep=pattern Filter tests by name (regex)
--bail Stop on first failure
--retry=N Retry failed tests N times
--timeout=ms Per-test timeout (default: 30000)
--report=path Write machine report (JSON/JUnit) to file
--report=- Write machine report to stdout (progress moves to stderr)
--report-dir=path Directory for screenshots and other artifacts
--screenshot=mode on-failure (default) | every-step | off
--format=fmt json (default) | allure | junit
--record Record video for each test (mp4 in report-dir)
-- <hook-args...> Everything after \`--\` is forwarded to _hooks.mjs
prepare/cleanup as hookArgs (runner does not parse it).
Example: ... tests/web-test/ -- --rebuild-stand`);
}
-95
View File
@@ -1,95 +0,0 @@
// web-test dom v1.16 — facade re-exporting injectable DOM scripts from dom/
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
/**
* Facade: re-exports DOM selector & semantic mapping script generators.
* Внутренности живут в dom/*. Публичный набор имён неизменен.
*
* All functions return JavaScript strings for page.evaluate().
* They produce clean semantic structures no DOM IDs or CSS classes leak out.
* Only non-default property values are included to minimize response size.
*/
export {
detectFormScript,
readFormScript,
findClickTargetScript,
findFieldButtonScript,
resolveFieldsScript,
detectNewFormScript,
findSearchInputScript,
findNamedButtonScript,
findCompareTypeRadioScript,
isFormVisibleScript,
findPatternInputIdScript,
isTypeDialogScript,
isNotInListCloudVisibleScript,
clickShowAllInNotInListCloudScript,
findChildFormByButtonScript,
readTypeDialogVisibleRowsScript,
} from './dom/forms.mjs';
export {
findFirstGridCellCoordsScript,
findColumnFirstCellCoordsScript,
readFieldSelectorInfoScript,
pickFieldInSelectorDropdownScript,
readFilterDialogInfoScript,
findFilterBadgeCloseScript,
findFirstFilterBadgeCloseScript,
} from './dom/filter.mjs';
export {
isInputFocusedScript,
isInputFocusedInGridScript,
findOpenPopupScript,
} from './dom/edit-state.mjs';
export {
readEddScript,
isEddVisibleScript,
clickEddItemViaDispatchScript,
clickShowAllInEddScript,
} from './dom/edd.mjs';
export { getFormStateScript } from './dom/form-state.mjs';
export {
resolveGridScript,
readTableScript,
countGridRowsScript,
isTreeGridScript,
findGridHeadCenterCoordsScript,
getSelectedOrLastRowIndexScript,
findGridCellScript,
findFocusCellScript,
snapshotGridScript,
resolveCellTargetScript,
} from './dom/grid.mjs';
export {
sortFieldKeysByColindexScript,
findCellCoordsByFieldsScript,
findNextCellCoordsByKeyScript,
findCheckboxAtPointScript,
findRowCommitClickCoordsScript,
getGridEditCheckScript,
readActiveGridCellScript,
getElementCenterCoordsByIdScript,
} from './dom/grid-edit.mjs';
export {
readSectionsScript,
readTabsScript,
switchTabScript,
readCommandsScript,
navigateSectionScript,
openCommandScript,
} from './dom/nav.mjs';
export {
readSubmenuScript,
clickPopupItemScript,
readCloudDDScript,
} from './dom/submenu.mjs';
export { checkErrorsScript } from './dom/errors.mjs';
@@ -1,486 +0,0 @@
// web-test dom shared v1.2 — embedded JS function constants
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
/**
* Shared function strings embedded into page.evaluate() generators.
* Не экспортируются наружу через dom.mjs facade внутренняя кухня.
*/
/** Find visible #modalSurface. 1C may leave multiple #modalSurface in DOM (duplicate id),
* e.g. when a second form (drill-down) creates its own alongside a stale one from the first
* form. getElementById returns the FIRST in document order, which may be hidden. Scan all. */
export const HAS_VISIBLE_MODAL_FN = `function hasVisibleModal() {
const all = document.querySelectorAll('#modalSurface');
for (const el of all) { if (el.offsetWidth > 0) return true; }
return false;
}`;
/**
* Click point INSIDE a grid row's first visible text cell NOT the row-line centre.
*
* A wide multi-column row's centre `x = line.x + line.width/2` lands far beyond the
* form's horizontal viewport (the `.gridLine` spans ALL columns, frozen + scrollable),
* so `mouse.click` at that X falls on an overlay outside the visible grid and the row
* is never hit the click silently does nothing. Seen on narrow modal selection forms
* with many columns (множественный выбор) and the `not_selectable` bug on selection forms.
*
* Picks the first visible non-checkbox cell that HAS text (so center-clicking never
* toggles a checkbox/picture mark), skips the first column on tree grids (it holds the
* expand toggle), and clamps X near the left edge (`min(width/2, 60)`) so a wide first
* column still lands in the viewport.
*
* @param line a `.gridLine` element
* @param body the grid's `.gridBody` (for tree detection); may be null
* @returns `{ x, y }` rounded, or `null` when the row has no usable cell.
*/
export const ROW_CLICK_POINT_FN = `function rowClickPoint(line, body) {
const isTree = !!(body && body.querySelector('.gridBoxTree'));
let cells = [...line.children]
.filter(b => b.offsetWidth > 0)
.map(b => ({ r: b.getBoundingClientRect(), checkbox: !!b.querySelector('.checkbox'), hasText: !!b.querySelector('.gridBoxText') }));
if (isTree && cells.length > 1) cells = cells.slice(1);
const pick = cells.find(c => !c.checkbox && c.hasText) || cells.find(c => !c.checkbox) || cells[0];
if (!pick) return null;
return { x: Math.round(pick.r.x + Math.min(pick.r.width / 2, 60)), y: Math.round(pick.r.y + pick.r.height / 2) };
}`;
/**
* Single source of truth for column derivation on HEADERLESS grids (no `.gridHead`).
* 1C still puts `colindex` on body cells, so anchoring works without a header.
* Returns ordered descriptors consumed identically by readers (readTable, getFormState)
* and resolvers (findCellCoords, findGridCell, scanGridRows) so a synthesized name like
* "Колонка1" always maps to the same physical cell on both read and write.
*
* Descriptor: { name, kind:'data'|'checkbox'|'picture', colindex, subTarget:'checkbox'|'title'|'text'|null }
* - colindex anchor: find the cell via line.children box with matching getAttribute('colindex').
* - subTarget node inside that box: 'checkbox' .checkbox, 'title' .gridBoxTitle,
* 'text' .gridBoxText, null box itself.
*
* A COMBINED mark-box (one box holding BOTH .checkbox AND non-empty .gridBoxTitle, e.g. the
* value-list checkbox mark-lists) is split into TWO logical columns sharing one colindex:
* "(checkbox)" (subTarget:checkbox) + "КолонкаN" (subTarget:title). Data columns are numbered
* КолонкаN among themselves (checkbox/picture don't consume a number); duplicate
* "(checkbox)"/"(picture)" get a " 2", " 3" suffix.
*/
export const HEADERLESS_GRID_FN = `function synthHeaderlessColumns(grid) {
function picInfo(cell) {
if (!cell) return null;
if (cell.querySelector('.gridListH, .gridListV, [tree="true"], .gridBoxTree')) return null;
const dib = cell.querySelector('.gridBoxImg .dIB');
if (!dib) return null;
const bg = dib.style.backgroundImage || '';
if (!bg.includes('pictureCollection/picture/')) return null;
const m = bg.match(/[?&]gx=(\\d+)/);
return { gx: m ? m[1] : '0' };
}
const body = grid.querySelector('.gridBody');
if (!body) return [];
const line = body.querySelector('.gridLine');
if (!line) return [];
const cols = [];
let dataN = 0;
const uniq = (base) => {
if (!cols.some(c => c.name === base)) return base;
let n = 2; while (cols.some(c => c.name === base + ' ' + n)) n++;
return base + ' ' + n;
};
[...line.children].forEach(box => {
if (box.offsetWidth === 0) return;
const ci = box.getAttribute('colindex');
if (ci == null) return;
const chk = box.querySelector('.checkbox');
const titleEl = box.querySelector('.gridBoxTitle');
const textEl = box.querySelector('.gridBoxText');
const titleTxt = ((titleEl ? titleEl.innerText : '') || '').trim();
if (chk && titleTxt) {
cols.push({ name: uniq('(checkbox)'), kind: 'checkbox', colindex: ci, subTarget: 'checkbox' });
cols.push({ name: 'Колонка' + (++dataN), kind: 'data', colindex: ci, subTarget: 'title' });
} else if (chk) {
cols.push({ name: uniq('(checkbox)'), kind: 'checkbox', colindex: ci, subTarget: 'checkbox' });
} else if (picInfo(box)) {
cols.push({ name: uniq('(picture)'), kind: 'picture', colindex: ci, subTarget: null });
} else {
cols.push({ name: 'Колонка' + (++dataN), kind: 'data', colindex: ci, subTarget: textEl ? 'text' : (titleEl ? 'title' : null) });
}
});
return cols;
}`;
/** Detect active form number. Picks form with most visible elements, skipping form0.
* When modalSurface is visible prefer the highest-numbered form (modal dialog). */
export const DETECT_FORM_FN = HAS_VISIBLE_MODAL_FN + `
function detectForm() {
const counts = {};
document.querySelectorAll('input.editInput[id], textarea[id], a.press[id]').forEach(el => {
if (el.offsetWidth === 0) return;
const m = el.id.match(/^form(\\d+)_/);
if (m) counts[m[1]] = (counts[m[1]] || 0) + 1;
});
const nums = Object.keys(counts).map(Number);
if (!nums.length) return null;
const candidates = nums.filter(n => n > 0);
if (!candidates.length) return nums[0];
// When modal surface is visible, prefer the highest-numbered form (modal dialog)
if (hasVisibleModal()) {
const maxForm = Math.max(...candidates);
if (counts[maxForm] >= 1) return maxForm;
}
return candidates.reduce((best, n) => counts[n] > counts[best] ? n : best);
}`;
/** Detect all open forms + modal state. Returns { activeForm, allForms, formCount, modal }.
* Works even when the open-windows tab bar is hidden. */
export const DETECT_FORMS_FN = HAS_VISIBLE_MODAL_FN + `
function detectForms() {
const counts = {};
document.querySelectorAll('input.editInput[id], textarea[id], a.press[id]').forEach(el => {
if (el.offsetWidth === 0) return;
const m = el.id.match(/^form(\\d+)_/);
if (m) counts[m[1]] = (counts[m[1]] || 0) + 1;
});
const nums = Object.keys(counts).map(Number);
return { allForms: nums.sort((a, b) => a - b), formCount: nums.length, modal: hasVisibleModal() };
}`;
/** Read form state given prefix p. Returns { fields, buttons, tabs, texts, hyperlinks, table, iframes }. */
export const READ_FORM_FN = HEADERLESS_GRID_FN + `
function readForm(p) {
const result = {};
const fields = [];
const buttons = [];
const formTabs = [];
const texts = [];
const hyperlinks = [];
// Normalize non-breaking spaces to regular spaces
const nbsp = s => (s || '').replace(/\\u00a0/g, ' ');
// Fields (inputs)
document.querySelectorAll('input.editInput[id^="' + p + '"]').forEach(el => {
if (el.offsetWidth === 0) return;
const name = el.id.replace(p, '').replace(/_i\\d+$/, '');
const titleEl = document.getElementById(p + name + '#title_text')
|| document.getElementById(p + name + '#title_div');
const label = nbsp((titleEl?.innerText?.trim() || '').replace(/\\n/g, ' '));
const actions = [];
if (document.getElementById(p + name + '_DLB')?.offsetWidth > 0) actions.push('select');
if (document.getElementById(p + name + '_OB')?.offsetWidth > 0) actions.push('open');
if (document.getElementById(p + name + '_CLR')?.offsetWidth > 0) actions.push('clear');
if (document.getElementById(p + name + '_CB')?.offsetWidth > 0) actions.push('pick');
const field = { name, value: el.value || '' };
// Multi-value reference fields keep their value in .chipsItem chips, not in input.value
if (!field.value) {
const labelEl = document.getElementById(p + name);
if (labelEl) {
const chipTexts = [...labelEl.querySelectorAll('.chipsItem .chipsTitle')]
.map(c => nbsp(c.innerText?.trim() || ''))
.filter(Boolean);
if (chipTexts.length) field.value = chipTexts.join(', ');
}
}
if (label && label !== name) field.label = label;
if (el.readOnly) field.readonly = true;
if (el.disabled) field.disabled = true;
if (el.type && el.type !== 'text') field.type = el.type;
if (document.activeElement === el) field.focused = true;
if (actions.length) field.actions = actions;
if (el.closest('.inputsBox')?.classList.contains('markIncomplete')) field.required = true;
fields.push(field);
});
// Textareas
document.querySelectorAll('textarea[id^="' + p + '"]').forEach(el => {
if (el.offsetWidth === 0) return;
const name = el.id.replace(p, '').replace(/_i\\d+$/, '');
const titleEl = document.getElementById(p + name + '#title_text')
|| document.getElementById(p + name + '#title_div');
const label = nbsp((titleEl?.innerText?.trim() || '').replace(/\\n/g, ' '));
const field = { name, value: el.value || '', type: 'textarea' };
if (label && label !== name) field.label = label;
if (el.readOnly) field.readonly = true;
if (el.disabled) field.disabled = true;
if (document.activeElement === el) field.focused = true;
if (el.closest('.inputsBox')?.classList.contains('markIncomplete')) field.required = true;
fields.push(field);
});
// Checkboxes
document.querySelectorAll('[id^="' + p + '"].checkbox').forEach(el => {
if (el.offsetWidth === 0) return;
const name = el.id.replace(p, '');
const titleEl = document.getElementById(p + name + '#title_text');
const label = nbsp(titleEl?.innerText?.trim() || '');
const field = {
name,
value: el.classList.contains('checked') || el.classList.contains('checkboxOn') || el.classList.contains('select'),
type: 'checkbox'
};
if (label && label !== name) field.label = label;
fields.push(field);
});
// Radio buttons — base element is option 0, others are #N#radio (N >= 1)
const radioGroups = {};
document.querySelectorAll('[id^="' + p + '"].radio').forEach(el => {
if (el.offsetWidth === 0) return;
const id = el.id.replace(p, '');
const m = id.match(/^(.+?)#(\\d+)#radio$/);
if (m) {
// Options 1, 2, ... have explicit #N#radio suffix
const [, groupName, idx] = m;
if (!radioGroups[groupName]) radioGroups[groupName] = [];
const labelEl = document.getElementById(p + groupName + '#' + idx + '#radio_text');
const label = nbsp(labelEl?.innerText?.trim() || 'option' + idx);
radioGroups[groupName].push({ index: parseInt(idx), label, selected: el.classList.contains('select') });
} else if (!id.includes('#')) {
// Base element = option 0 (no #0#radio suffix)
if (!radioGroups[id]) radioGroups[id] = [];
const labelEl = document.getElementById(p + id + '#0#radio_text');
const label = nbsp(labelEl?.innerText?.trim() || 'option0');
radioGroups[id].unshift({ index: 0, label, selected: el.classList.contains('select') });
}
});
for (const [name, options] of Object.entries(radioGroups)) {
const titleEl = document.getElementById(p + name + '#title_text');
const label = titleEl?.innerText?.trim() || '';
const selected = options.find(o => o.selected);
const field = {
name,
value: selected?.label || '',
type: 'radio',
options: options.map(o => o.label)
};
if (label && label !== name) field.label = label;
fields.push(field);
}
// Buttons (a.press)
document.querySelectorAll('a.press[id^="' + p + '"]').forEach(el => {
if (el.offsetWidth === 0) return;
const idName = el.id.replace(p, '');
if (/_(?:DLB|CLR|OB|CB)$/.test(idName)) return;
const span = el.querySelector('.submenuText') || el.querySelector('span');
const text = nbsp(span?.textContent?.trim() || el.innerText?.trim() || '');
if (!text && !el.classList.contains('pressCommand')) return;
const btn = { name: text || idName };
if (el.classList.contains('pressDefault')) btn.default = true;
if (el.classList.contains('pressDisabled')) btn.disabled = true;
// Icon-only buttons: expose tooltip from DOM title attribute (1C puts title on parent .framePress)
if (!text) {
const tip = nbsp(el.title || el.parentElement?.title || '');
if (tip) btn.tooltip = tip;
}
buttons.push(btn);
});
// Frame buttons
document.querySelectorAll('[id^="' + p + '"].frameButton, [id^="' + p + '"] .frameButton').forEach(el => {
if (el.offsetWidth === 0) return;
const text = nbsp(el.innerText?.trim() || '');
const idName = el.id?.replace(p, '') || '';
if (!text && !idName) return;
buttons.push({ name: text || idName, frame: true });
});
// Tumbler items
document.querySelectorAll('[id^="' + p + '"].tumblerItem').forEach(el => {
if (el.offsetWidth === 0) return;
const text = el.innerText?.trim();
const idName = el.id?.replace(p, '') || '';
buttons.push({ name: text || idName, tumbler: true });
});
// Tabs — scoped to form by checking ancestor IDs
document.querySelectorAll('[data-content]').forEach(el => {
if (el.offsetWidth === 0) return;
let node = el.parentElement;
let inForm = false;
while (node) {
if (node.id && node.id.startsWith(p)) { inForm = true; break; }
node = node.parentElement;
}
if (!inForm) return;
const tab = { name: el.dataset.content };
if (el.classList.contains('select')) tab.active = true;
formTabs.push(tab);
});
// Static texts and hyperlinks
document.querySelectorAll('[id^="' + p + '"].staticText').forEach(el => {
if (el.offsetWidth === 0) return;
const name = el.id.replace(p, '');
if (name.endsWith('_div') || name.includes('#title')) return;
const text = el.innerText?.trim();
if (!text) return;
if (el.classList.contains('staticTextHyper')) {
hyperlinks.push({ name: text });
} else {
const titleEl = document.getElementById(p + name + '#title_text');
const label = titleEl?.innerText?.trim() || '';
const entry = { name, value: text };
if (label) entry.label = label;
texts.push(entry);
}
});
// Tables/grids — collect ALL visible grids
const allGrids = [...document.querySelectorAll('[id^="' + p + '"].grid, [id^="' + p + '"] .grid')]
.filter(g => g.offsetWidth > 0 && g.offsetHeight > 0);
if (allGrids.length > 0) {
const tables = allGrids.map(grid => {
const name = grid.id ? grid.id.replace(p, '') : '';
const head = grid.querySelector('.gridHead');
const body = grid.querySelector('.gridBody');
const columns = [];
if (head) {
const headLine = head.querySelector('.gridLine') || head;
[...headLine.children].forEach(box => {
if (box.offsetWidth === 0) return;
const textEl = box.querySelector('.gridBoxText');
const text = (textEl || box).innerText?.trim().replace(/\\n/g, ' ') || '';
if (text) {
const r = box.getBoundingClientRect();
columns.push({ text, x: r.x, right: r.x + r.width, y: r.y, h: r.height });
} else {
// Unnamed column — check if data cells contain checkboxes
const firstLine = body?.querySelector('.gridLine');
if (firstLine) {
const visibleHeaders = [...headLine.children].filter(c => c.offsetWidth > 0);
const idx = visibleHeaders.indexOf(box);
const cells = [...firstLine.children].filter(c => c.offsetWidth > 0);
if (cells[idx]?.querySelector('.checkbox')) {
columns.push({ text: '(checkbox)', x: 0, right: 0, y: 0, h: 0 });
}
}
}
});
// Expand single merged headers with multiple data sub-rows (e.g. "Субконто Дт" → 1/2/3)
const firstLine = body?.querySelector('.gridLine');
if (firstLine && columns.length > 0) {
const xGrp = new Map();
columns.forEach(c => {
const k = Math.round(c.x) + ':' + Math.round(c.right);
if (!xGrp.has(k)) xGrp.set(k, []);
xGrp.get(k).push(c);
});
for (const [k, hdrs] of xGrp) {
if (hdrs.length !== 1) continue;
let cnt = 0;
[...firstLine.children].forEach(box => {
if (box.offsetWidth === 0) return;
const r = box.getBoundingClientRect();
const cx = r.x + r.width / 2;
if (cx >= hdrs[0].x && cx < hdrs[0].right) cnt++;
});
if (cnt > 1) {
const base = hdrs[0];
const baseIdx = columns.indexOf(base);
columns.splice(baseIdx, 1);
for (let si = 0; si < cnt; si++) {
columns.splice(baseIdx + si, 0, { text: base.text + ' ' + (si + 1), x: base.x, right: base.right, y: 0, h: 0 });
}
}
}
}
} else if (body) {
// Headerless grid — synthesize columns by colindex (single source).
synthHeaderlessColumns(grid).forEach(c => columns.push({ text: c.name, x: 0, right: 0, y: 0, h: 0 }));
}
const colNames = columns.map(c => c.text);
const rowCount = body ? body.querySelectorAll('.gridLine').length : 0;
// Visual label from group title (e.g. "Входящие:" for grid "Входящие")
const titleEl = document.getElementById(p + name + '#title_div')
|| document.getElementById(p + 'Группа' + name + '#title_div');
const label = titleEl ? (titleEl.innerText?.trim().replace(/:\\s*$/, '').replace(/\\u00a0/g, ' ') || null) : null;
return { name, columns: colNames, rowCount, ...(label ? { label } : {}) };
});
result.tables = tables;
// Backward compat: table = first grid summary
const first = tables[0];
result.table = { present: true, columns: first.columns, rowCount: first.rowCount };
}
// Active filters (train badges above grid: *СостояниеПросмотра)
const filters = [];
document.querySelectorAll('[id^="' + p + '"].trainItem').forEach(el => {
if (el.offsetWidth === 0) return;
const titleEl = el.querySelector('.trainName');
const valueEl = el.querySelector('.trainTitle');
if (!titleEl && !valueEl) return;
const field = (titleEl?.innerText?.trim() || '').replace(/\\n/g, ' ').replace(/\\s*:$/, '').trim();
const value = valueEl?.innerText?.trim()?.replace(/\\n/g, ' ') || '';
if (field || value) filters.push({ field, value });
});
// Also check search field value
const searchInput = [...document.querySelectorAll('input.editInput[id^="' + p + '"]')]
.find(el => el.offsetWidth > 0 && /Строк[аи]Поиска|SearchString/i.test(el.id));
if (searchInput?.value) {
filters.push({ type: 'search', value: searchInput.value });
}
if (filters.length) result.filters = filters;
// Navigation panel (FormNavigationPanel) — lives in parent page{N} container
const navigation = [];
const formEl = document.querySelector('[id^="' + p + '"]');
if (formEl) {
let pageEl = formEl.parentElement;
while (pageEl && !(pageEl.id && /^page\\d+$/.test(pageEl.id))) pageEl = pageEl.parentElement;
if (pageEl) {
pageEl.querySelectorAll('.navigationItem').forEach(el => {
if (el.offsetWidth === 0) return;
const nameEl = el.querySelector('.navigationItemName');
const text = (nameEl?.innerText?.trim() || '').replace(/\\u00a0/g, ' ');
if (!text) return;
const nav = { name: text };
if (el.classList.contains('select')) nav.active = true;
navigation.push(nav);
});
}
}
// Iframes
let iframeCount = 0;
document.querySelectorAll('[id^="' + p + '"] iframe, iframe[id^="' + p + '"]').forEach(el => {
if (el.offsetWidth > 0 && el.offsetHeight > 0) iframeCount++;
});
if (iframeCount) result.iframes = iframeCount;
if (fields.length) result.fields = fields;
if (buttons.length) result.buttons = buttons;
if (formTabs.length) result.tabs = formTabs;
if (navigation.length) result.navigation = navigation;
if (texts.length) result.texts = texts;
if (hyperlinks.length) result.hyperlinks = hyperlinks;
// Group DCS report settings into readable format
if (result.fields) {
const dcsRe = /^(.+Элемент(\\d+))(Использование|Значение|ВидСравнения)$/;
const dcsGroups = {};
const dcsNames = new Set();
for (const f of result.fields) {
const m = f.name.match(dcsRe);
if (!m) continue;
if (!dcsGroups[m[1]]) dcsGroups[m[1]] = { _n: parseInt(m[2]) };
dcsGroups[m[1]][m[3]] = f;
dcsNames.add(f.name);
}
const dcsEntries = Object.entries(dcsGroups).sort((a, b) => a[1]._n - b[1]._n);
if (dcsEntries.length) {
result.reportSettings = dcsEntries.map(([, g]) => {
const cb = g['Использование'];
const val = g['Значение'];
if (!cb && !val) return null;
// No checkbox present (class="staticText" instead of .checkbox) — setting is always enabled
const label = (val?.label || cb?.label || val?.name || cb?.name || '').replace(/:$/, '').trim();
const s = { name: label, enabled: cb ? !!cb.value : true };
if (val) {
s.value = val.value || '';
if (val.actions && val.actions.length) s.actions = val.actions;
}
return s;
}).filter(Boolean);
result.fields = result.fields.filter(f => !dcsNames.has(f.name));
if (!result.fields.length) delete result.fields;
}
}
return result;
}`;
@@ -1,108 +0,0 @@
// web-test dom/edd v1.0 — DOM scripts for the #editDropDown autocomplete popup
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
/**
* Read the `#editDropDown` autocomplete popup.
*
* Returns `{ visible: false }` when EDD is absent/hidden, or
* `{ visible: true, items: [{ name, x, y }] }` with center coords suitable
* for `page.mouse.click(x, y)`.
*
* Note: `page.mouse.click` is often intercepted by `div.surface` overlays
* from DLB prefer `clickEddItemViaDispatchScript` for those cases.
*/
export function readEddScript() {
return `(() => {
const edd = document.getElementById('editDropDown');
if (!edd || edd.offsetWidth === 0) return { visible: false };
const eddTexts = [...edd.querySelectorAll('.eddText')].filter(el => el.offsetWidth > 0);
return {
visible: true,
items: eddTexts.map(el => {
const r = el.getBoundingClientRect();
return { name: el.innerText?.trim() || '', x: r.x + r.width / 2, y: r.y + r.height / 2 };
})
};
})()`;
}
/**
* Is the EDD popup currently visible? Returns boolean.
* Lighter than `readEddScript` when only presence matters.
*/
export function isEddVisibleScript() {
return `(() => {
const edd = document.getElementById('editDropDown');
return !!(edd && edd.offsetWidth > 0);
})()`;
}
/**
* Click an EDD item by name via `dispatchEvent` bypasses `div.surface`
* overlays from DLB that intercept `page.mouse.click`.
*
* Matching is fuzzy: exact (with optional `(suffix)` strip) includes,
* normalizes ё/е and NBSP.
*
* Returns the clicked item's innerText (trimmed), or `null` when no match.
*/
export function clickEddItemViaDispatchScript(itemName) {
return `(() => {
const edd = document.getElementById('editDropDown');
if (!edd || edd.offsetWidth === 0) return null;
const ny = s => s.replace(/ё/gi, 'е').replace(/\\u00a0/g, ' ');
const target = ny(${JSON.stringify(itemName.toLowerCase())});
const items = [...edd.querySelectorAll('.eddText')].filter(el => el.offsetWidth > 0);
function clickEl(el) {
const r = el.getBoundingClientRect();
const opts = { bubbles: true, cancelable: true, clientX: r.x + r.width/2, clientY: r.y + r.height/2 };
el.dispatchEvent(new MouseEvent('mousedown', opts));
el.dispatchEvent(new MouseEvent('mouseup', opts));
el.dispatchEvent(new MouseEvent('click', opts));
return el.innerText.trim();
}
// Pass 1: exact match (prefer over partial)
for (const el of items) {
const t = ny((el.innerText?.trim() || '').toLowerCase());
if (t === target) return clickEl(el);
const stripped = t.replace(/\\s*\\([^)]*\\)\\s*$/, '');
if (stripped === target) return clickEl(el);
}
// Pass 2: partial match
for (const el of items) {
const t = ny((el.innerText?.trim() || '').toLowerCase());
if (t.includes(target) || target.includes(t.replace(/\\s*\\([^)]*\\)\\s*$/, ''))) return clickEl(el);
}
return null;
})()`;
}
/**
* Click the "Показать все" / "Show all" link in the EDD footer via
* `dispatchEvent`. Tries `.eddBottom .hyperlink` first, then falls back
* to scanning for span/div/a with the literal text.
*
* Returns boolean whether the link was found and clicked.
*/
export function clickShowAllInEddScript() {
return `(() => {
const edd = document.getElementById('editDropDown');
if (!edd || edd.offsetWidth === 0) return false;
let el = edd.querySelector('.eddBottom .hyperlink');
if (!el || el.offsetWidth === 0) {
const candidates = [...edd.querySelectorAll('span, div, a')]
.filter(e => e.offsetWidth > 0 && e.children.length === 0);
el = candidates.find(e => {
const t = (e.innerText?.trim() || '').toLowerCase();
return t === 'показать все' || t === 'show all';
});
}
if (!el) return false;
const r = el.getBoundingClientRect();
const opts = { bubbles: true, cancelable: true, clientX: r.x + r.width/2, clientY: r.y + r.height/2 };
el.dispatchEvent(new MouseEvent('mousedown', opts));
el.dispatchEvent(new MouseEvent('mouseup', opts));
el.dispatchEvent(new MouseEvent('click', opts));
return true;
})()`;
}
@@ -1,63 +0,0 @@
// web-test dom/edit-state v1.1 — focus and popup detection inside the 1C web client
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
/**
* Is the currently focused element an INPUT (optionally TEXTAREA too)?
* Returns boolean.
*
* @param {object} [opts]
* @param {boolean} [opts.allowTextarea=false] also return true for TEXTAREA.
*/
export function isInputFocusedScript({ allowTextarea = false } = {}) {
const cond = allowTextarea
? `f.tagName === 'INPUT' || f.tagName === 'TEXTAREA'`
: `f.tagName === 'INPUT'`;
return `(() => {
const f = document.activeElement;
return !!(f && (${cond}));
})()`;
}
/**
* Is the currently focused INPUT/TEXTAREA inside a `.grid` ancestor?
* Used to verify grid edit-mode (active cell editor).
*
* @param {string} [gridSelector] when given, only `true` if the focused input
* is inside that specific grid. Without it any `.grid` ancestor counts.
*
* Returns boolean.
*/
export function isInputFocusedInGridScript(gridSelector) {
const sel = gridSelector ? JSON.stringify(gridSelector) : 'null';
return `(() => {
const f = document.activeElement;
if (!f || (f.tagName !== 'INPUT' && f.tagName !== 'TEXTAREA')) return false;
const sel = ${sel};
if (sel) {
const grid = document.querySelector(sel);
return !!(grid && grid.contains(f));
}
let n = f;
while (n) {
if (n.classList?.contains('grid')) return true;
n = n.parentElement;
}
return false;
})()`;
}
/**
* Is a calculator (`.calculate`) or calendar (`.frameCalendar`) popup visible?
* Returns `'calculator' | 'calendar' | null`.
*
* For the "popup gone" check, callers use: `!await findOpenPopup()`.
*/
export function findOpenPopupScript() {
return `(() => {
const calc = document.querySelector('.calculate');
if (calc && calc.offsetWidth > 0) return 'calculator';
const cal = document.querySelector('.frameCalendar');
if (cal && cal.offsetWidth > 0) return 'calendar';
return null;
})()`;
}
@@ -1,65 +0,0 @@
// web-test dom/errors-stack v1.0 — DOM scripts for fetching error stack via OpenReport link.
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
//
// Path-1 flow for platform exceptions: click "Сформировать отчет об ошибке" link,
// open detailed error dialog, read textarea, close cleanup dialogs.
/** Find OpenReport link coordinates on the error modal for given formNum. */
export function getOpenReportCoordsScript(formNum) {
return `(() => {
const el = document.getElementById('form${formNum}_OpenReport#text');
if (!el || el.offsetWidth <= 2) return null;
const rect = el.getBoundingClientRect();
return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
})()`;
}
/** Check whether the "подробный текст ошибки" link is visible (signals report dialog ready). */
export function isErrorDetailLinkVisibleScript() {
return `(() => {
const links = document.querySelectorAll('a, [class*="hyper"], span');
for (const el of links) {
if (el.offsetWidth > 0 && el.textContent.includes('подробный текст ошибки')) return true;
}
return false;
})()`;
}
/** Read the largest visible non-empty textarea — contains the detailed error stack. */
export function readLargestVisibleTextareaScript() {
return `(() => {
let best = null;
document.querySelectorAll('textarea').forEach(ta => {
if (ta.offsetWidth > 0 && ta.value.length > 0) {
if (!best || ta.value.length > best.value.length) best = ta;
}
});
return best?.value || null;
})()`;
}
/** Click the OK button in the topmost cloud window (closes "Подробный текст ошибки"). */
export function clickTopCloudOkButtonScript() {
return `(() => {
const psWins = [...document.querySelectorAll('[id^="ps"][id$="win"]')]
.filter(w => w.offsetWidth > 0)
.sort((a, b) => parseInt(b.style?.zIndex || '0') - parseInt(a.style?.zIndex || '0'));
for (const w of psWins) {
const ok = w.querySelector('button.webBtn, .pressDefault');
if (ok && ok.textContent.trim() === 'OK') { ok.click(); return true; }
}
return false;
})()`;
}
/** Click the × CloseButton in the topmost visible cloud window (closes "Отчет об ошибке"). */
export function clickReportCloseButtonScript() {
return `(() => {
const psWins = [...document.querySelectorAll('[id^="ps"][id$="win"]')]
.filter(w => w.offsetWidth > 0);
for (const w of psWins) {
const closeBtn = w.querySelector('[id$="_cmd_CloseButton"]');
if (closeBtn && closeBtn.offsetWidth > 0) { closeBtn.click(); break; }
}
})()`;
}
@@ -1,127 +0,0 @@
// web-test dom/errors v1.0 — error/diagnostic detection (balloon, messages, modal, stateWindow)
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
/**
* Check for validation errors / diagnostics after an action.
* Detects three patterns:
* 1. Inline balloon tooltip (div.balloon with .balloonMessage)
* 2. Messages panel (div.messages with msg0, msg1... grid rows)
* 3. Modal error dialog (high-numbered form with pressDefault + static texts)
* Returns { balloon, messages[], modal } or null if no errors.
*/
export function checkErrorsScript() {
return `(() => {
const result = {};
// 1. Inline balloon tooltip
const balloon = document.querySelector('.balloon');
if (balloon && balloon.offsetWidth > 0) {
const msg = balloon.querySelector('.balloonMessage');
const title = balloon.querySelector('.balloonTitle');
if (msg) {
result.balloon = {
title: title?.innerText?.trim() || 'Ошибка',
message: msg.innerText?.trim() || ''
};
// Count navigation arrows to indicate total errors
const fwd = balloon.querySelector('.balloonJumpFwd');
const back = balloon.querySelector('.balloonJumpBack');
const fwdDisabled = fwd?.classList.contains('disabled');
const backDisabled = back?.classList.contains('disabled');
if (fwd && !fwdDisabled) result.balloon.hasNext = true;
if (back && !backDisabled) result.balloon.hasPrev = true;
}
}
// 2. Messages panel (div.messages — pick visible one, multiple may exist across tabs)
const msgPanels = [...document.querySelectorAll('.messages')].filter(el => el.offsetWidth > 0);
for (const msgPanel of msgPanels) {
const msgs = [];
msgPanel.querySelectorAll('[id^="msg"]').forEach(line => {
if (line.offsetWidth === 0) return;
const textEl = line.querySelector('.gridBoxText');
const text = (textEl || line).innerText?.trim();
if (text) msgs.push(text);
});
if (msgs.length > 0) { result.messages = msgs; break; }
}
// 3+4. Modal dialogs: confirmation (multiple buttons) or error (single pressDefault)
// Uses form container ancestry to group buttons — pressButton elements often lack form-prefixed IDs
// Note: 1C shows some modals WITHOUT #modalSurface (e.g. "Не удалось записать" uses ps*win floating window)
// so we always scan for small forms with button patterns, regardless of modalSurface state
const formButtons = {};
[...document.querySelectorAll('a.press.pressButton')].forEach(btn => {
if (btn.offsetWidth === 0) return;
const container = btn.closest('[id$="_container"]');
const m = container?.id?.match(/^form(\\d+)_/);
if (!m) return;
const fn = m[1];
if (!formButtons[fn]) formButtons[fn] = [];
formButtons[fn].push(btn);
});
for (const [fn, buttons] of Object.entries(formButtons)) {
const p = 'form' + fn + '_';
const elCount = document.querySelectorAll('[id^="' + p + '"]').length;
if (elCount > 100) continue; // Skip large content forms
if (buttons.length > 1) {
// Confirmation dialog (multiple buttons: Да/Нет, OK/Отмена, etc.)
// Must have a Message element — real 1C confirmations always have form{N}_Message.
// Without it, this is just a regular form with multiple buttons (e.g. EPF form).
const msgEl = document.getElementById(p + 'Message');
if (!msgEl || msgEl.offsetWidth === 0) continue;
const message = msgEl.innerText?.trim() || '';
const btnNames = buttons.map(el => {
const b = { name: el.innerText?.trim() || '' };
if (el.classList.contains('pressDefault')) b.default = true;
return b;
}).filter(b => b.name);
result.confirmation = { message, buttons: btnNames.map(b => b.name), formNum: parseInt(fn) };
break;
}
}
// Single-button modal: error dialog with pressDefault + staticText
// Skip forms with input fields — those are data entry forms (e.g. register record),
// not error dialogs. Real error modals only have staticText + buttons.
if (!result.confirmation) {
for (const [fn, buttons] of Object.entries(formButtons)) {
const p = 'form' + fn + '_';
const elCount = document.querySelectorAll('[id^="' + p + '"]').length;
if (elCount > 100) continue;
if (buttons.length !== 1 || !buttons[0].classList.contains('pressDefault')) continue;
const hasInputs = document.querySelectorAll('input.editInput[id^="' + p + '"], textarea[id^="' + p + '"]').length > 0;
if (hasInputs) continue;
const texts = [...document.querySelectorAll('[id^="' + p + '"].staticText')]
.filter(el => el.offsetWidth > 0)
.map(el => el.innerText?.trim())
.filter(Boolean);
if (texts.length > 0) {
result.modal = { message: texts.join(' '), formNum: parseInt(fn), button: buttons[0].innerText?.trim() || '' };
// Check if OpenReport link is available (platform exceptions have visible link text)
const reportLink = document.getElementById(p + 'OpenReport#text');
if (reportLink && reportLink.offsetWidth > 2 && reportLink.textContent.trim()) {
result.modal.hasReport = true;
}
// Grab AdditionalInfo/ServerText if filled (may contain extra error details)
const addInfo = document.getElementById(p + 'AdditionalInfo');
if (addInfo && addInfo.textContent && addInfo.textContent.trim()) result.modal.additionalInfo = addInfo.textContent.trim();
const srvText = document.getElementById(p + 'ServerText');
if (srvText && srvText.textContent && srvText.textContent.trim()) result.modal.serverText = srvText.textContent.trim();
break;
}
}
}
// 5. SpreadsheetDocument state window (info bar inside moxelContainer)
// Shows messages like "Не установлено значение параметра X" or "Отчет не сформирован"
const stateWins = [...document.querySelectorAll('.stateWindowSupportSurface')].filter(el => el.offsetWidth > 0);
if (stateWins.length) {
const texts = stateWins.map(el => el.innerText?.trim()).filter(Boolean);
if (texts.length) result.stateText = texts;
}
return (result.balloon || result.messages || result.modal || result.confirmation || result.stateText) ? result : null;
})()`;
}
@@ -1,187 +0,0 @@
// web-test dom/filter v1.0 — DOM scripts for filterList / unfilterList
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
/**
* Find the first grid cell on the form and return its center coords.
* Used as a fallback target for Alt+F when there's no search input.
*
* Returns `{ x, y } | null`.
*/
export function findFirstGridCellCoordsScript(formNum) {
return `(() => {
const p = 'form${formNum}_';
const grid = [...document.querySelectorAll('[id^="' + p + '"].grid, [id^="' + p + '"] .grid')]
.find(g => g.offsetWidth > 0);
if (!grid) return null;
const rows = [...grid.querySelectorAll('.gridBody .gridLine')];
if (!rows.length) return null;
const cells = [...rows[0].querySelectorAll('.gridBox')];
if (!cells.length) return null;
const r = cells[0].getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) };
})()`;
}
/**
* Find the grid cell of the first row in the column whose header text matches `field`
* (fuzzy: exact startsWith includes; normalizes ё/е and NBSP).
*
* If the column isn't in the grid, returns coords of the first cell + `needDlb: true`
* so the caller can use DLB to switch FieldSelector after opening the dialog.
*
* Returns:
* - `{ x, y, needDlb? } ` coords to click (advanced search target)
* - `{ error }` `'no_grid' | 'no_rows' | 'no_cells' | 'cell_not_found'`
*/
export function findColumnFirstCellCoordsScript(formNum, field) {
return `(() => {
const p = 'form${formNum}_';
const grid = [...document.querySelectorAll('[id^="' + p + '"].grid, [id^="' + p + '"] .grid')]
.find(g => g.offsetWidth > 0);
if (!grid) return { error: 'no_grid' };
const targetField = ${JSON.stringify(field)};
const headers = [...grid.querySelectorAll('.gridHead .gridBox')];
let colIndex = -1;
let startsWithIdx = -1;
let includesIdx = -1;
for (let i = 0; i < headers.length; i++) {
const t = headers[i].innerText?.trim().replace(/\\u00a0/g, ' ');
if (!t) continue;
const ny = s => s.replace(/ё/gi, 'е').replace(/\\u00a0/g, ' ');
const tl = ny(t.toLowerCase()), fl = ny(targetField.toLowerCase());
if (tl === fl) { colIndex = i; break; }
if (startsWithIdx < 0 && tl.startsWith(fl)) { startsWithIdx = i; }
else if (includesIdx < 0 && tl.includes(fl)) { includesIdx = i; }
}
if (colIndex < 0) colIndex = startsWithIdx >= 0 ? startsWithIdx : includesIdx;
const rows = [...grid.querySelectorAll('.gridBody .gridLine')];
if (!rows.length) return { error: 'no_rows' };
if (colIndex < 0) {
const cells = [...rows[0].querySelectorAll('.gridBox')];
if (!cells.length) return { error: 'no_cells' };
const r = cells[0].getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2), needDlb: true };
}
const cells = [...rows[0].querySelectorAll('.gridBox')];
if (colIndex >= cells.length) return { error: 'cell_not_found' };
const r = cells[colIndex].getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) };
})()`;
}
/**
* Read FieldSelector input + its DLB button coords on the advanced search dialog.
* Returns `{ current, dlbX, dlbY }` (zero coords if DLB not visible).
*/
export function readFieldSelectorInfoScript(dialogForm) {
return `(() => {
const p = 'form' + ${JSON.stringify(String(dialogForm))} + '_';
const fsInput = [...document.querySelectorAll('input.editInput[id^="' + p + '"]')]
.find(el => el.offsetWidth > 0 && /FieldSelector/i.test(el.id));
const dlb = document.getElementById(p + 'FieldSelector_DLB');
return {
current: fsInput?.value?.trim() || '',
dlbX: dlb && dlb.offsetWidth > 0 ? Math.round(dlb.getBoundingClientRect().x + dlb.getBoundingClientRect().width / 2) : 0,
dlbY: dlb && dlb.offsetWidth > 0 ? Math.round(dlb.getBoundingClientRect().y + dlb.getBoundingClientRect().height / 2) : 0
};
})()`;
}
/**
* Pick a field name in the FieldSelector EDD dropdown (fuzzy: exact includes,
* normalizes ё/е and NBSP).
*
* Returns:
* - `{ x, y, name }` coords + matched name to click
* - `{ error, available? }` `'no_dropdown'` or `'field_not_found'` with list of available names
*/
export function pickFieldInSelectorDropdownScript(field) {
return `(() => {
const edd = document.getElementById('editDropDown');
if (!edd || edd.offsetWidth === 0) return { error: 'no_dropdown' };
const ny = s => s.replace(/ё/gi, 'е').replace(/\\u00a0/g, ' ');
const target = ny(${JSON.stringify(field.toLowerCase())});
const items = [...edd.querySelectorAll('div')].filter(el =>
el.offsetWidth > 0 && el.innerText?.trim() && !el.innerText.includes('\\n'));
const match = items.find(el => ny(el.innerText.trim().toLowerCase()) === target)
|| items.find(el => ny(el.innerText.trim().toLowerCase()).includes(target));
if (!match) return { error: 'field_not_found', available: items.map(el => el.innerText.trim()) };
const r = match.getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2), name: match.innerText.trim() };
})()`;
}
/**
* Read advanced search dialog state FieldSelector value, Pattern input id+value,
* and field type flags (isDate via iCalendB button, isRef via iDLB button on Pattern).
*
* Returns `{ fieldSelector, patternValue, patternId, isDate, isRef }`.
*/
export function readFilterDialogInfoScript(dialogForm) {
return `(() => {
const p = 'form' + ${JSON.stringify(String(dialogForm))} + '_';
const fsInput = [...document.querySelectorAll('input.editInput[id^="' + p + '"]')]
.find(el => el.offsetWidth > 0 && /FieldSelector/i.test(el.id));
const ptInput = [...document.querySelectorAll('input.editInput[id^="' + p + '"]')]
.find(el => el.offsetWidth > 0 && /Pattern/i.test(el.id));
const ptLabel = ptInput?.closest('label');
const btns = ptLabel ? [...ptLabel.querySelectorAll('span.btn')].map(b => b.className) : [];
const isDate = btns.some(c => c.includes('iCalendB'));
const isRef = !isDate && btns.some(c => c.includes('iDLB'));
return {
fieldSelector: fsInput?.value?.trim() || '',
patternValue: ptInput?.value?.trim() || '',
patternId: ptInput?.id || '',
isDate,
isRef
};
})()`;
}
/**
* Find the × close button on the filter badge whose title matches `field`
* (exact includes; normalizes ё/е and NBSP).
*
* Returns:
* - `{ x, y, field }` coords + actual field title from the badge
* - `{ error, available }` `'not_found'` with list of available badge titles
*/
export function findFilterBadgeCloseScript(formNum, field) {
return `(() => {
const p = 'form${formNum}_';
const norm = s => s?.trim().replace(/\\u00a0/g, ' ').replace(/:$/, '').replace(/\\n/g, ' ') || '';
const ny = s => s.replace(/ё/gi, 'е').replace(/\\u00a0/g, ' ');
const target = ny(${JSON.stringify(field.toLowerCase())});
const items = [...document.querySelectorAll('[id^="' + p + '"].trainItem')].filter(el => el.offsetWidth > 0);
for (const item of items) {
const titleEl = item.querySelector('.trainName');
const title = ny(norm(titleEl?.innerText).toLowerCase());
if (title === target || title.includes(target)) {
const close = item.querySelector('.trainClose');
if (close) {
const r = close.getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2), field: norm(titleEl?.innerText) };
}
}
}
const available = items.map(item => norm(item.querySelector('.trainName')?.innerText));
return { error: 'not_found', available };
})()`;
}
/**
* Find the × close button on the FIRST visible filter badge (for clear-all loop).
* Returns `{ x, y } | null`.
*/
export function findFirstFilterBadgeCloseScript(formNum) {
return `(() => {
const p = 'form${formNum}_';
const item = [...document.querySelectorAll('[id^="' + p + '"].trainItem')]
.find(el => el.offsetWidth > 0);
if (!item) return null;
const close = item.querySelector('.trainClose');
if (!close) return null;
const r = close.getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) };
})()`;
}
@@ -1,34 +0,0 @@
// web-test dom/form-state v1.0 — combined detectForm + readForm + open tabs
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { DETECT_FORM_FN, DETECT_FORMS_FN, READ_FORM_FN } from './_shared.mjs';
/**
* Combined: detect form + read form + read open tabs.
* Single evaluate call instead of 3. Used by browser.getFormState().
*/
export function getFormStateScript() {
return `(() => {
${DETECT_FORM_FN}
${DETECT_FORMS_FN}
${READ_FORM_FN}
const formNum = detectForm();
const meta = detectForms();
if (formNum === null) return { form: null, formCount: 0, message: 'No form detected' };
const p = 'form' + formNum + '_';
const formData = readForm(p);
// Open tabs bar (present only when tab panel is enabled in 1C settings)
const openTabs = [];
document.querySelectorAll('[id^="openedCell_cmd_"]').forEach(el => {
const text = el.innerText?.trim();
if (!text) return;
const entry = { name: text };
if (el.classList.contains('select')) entry.active = true;
openTabs.push(entry);
});
const activeTab = openTabs.find(t => t.active)?.name || null;
const result = { form: formNum, activeTab, openForms: meta.allForms, formCount: meta.formCount, ...formData };
if (meta.modal) result.modal = true;
if (openTabs.length) result.openTabs = openTabs;
return result;
})()`;
}
@@ -1,653 +0,0 @@
// web-test dom/forms v1.7 — form detection, content read, click-target/field-button resolution
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { DETECT_FORM_FN, READ_FORM_FN, ROW_CLICK_POINT_FN } from './_shared.mjs';
/**
* Detect the active form number.
* Picks the form with the most visible elements (excluding form0 = home page).
*/
export function detectFormScript() {
return `(() => {
${DETECT_FORM_FN}
return detectForm();
})()`;
}
/**
* Read full form state for a given form number.
* Uses shared READ_FORM_FN.
*/
export function readFormScript(formNum) {
const p = `form${formNum}_`;
return `(() => {
${READ_FORM_FN}
return readForm(${JSON.stringify(p)});
})()`;
}
/**
* Find a clickable element on the current form (button, hyperlink, tab, frame button).
* Returns { id, kind, name } for Playwright page.click(), or { error, available }.
* Supports synonym matching: visible text AND internal name from DOM ID.
* Fuzzy order: exact name -> exact label -> includes name -> includes label.
*/
export function findClickTargetScript(formNum, text, { tableName, gridSelector } = {}) {
const p = `form${formNum}_`;
return `(() => {
${ROW_CLICK_POINT_FN}
const norm = s => (s?.trim().replace(/\\u00a0/g, ' ') || '').replace(/ё/gi, 'е');
const target = ${JSON.stringify(text.toLowerCase().replace(/ё/g, 'е'))};
const p = ${JSON.stringify(p)};
const tableName = ${JSON.stringify(tableName || '')};
const gridSelector = ${JSON.stringify(gridSelector || '')};
const items = [];
// Buttons (a.press)
[...document.querySelectorAll('a.press[id^="' + p + '"]')].filter(el => el.offsetWidth > 0).forEach(el => {
const idName = el.id.replace(p, '');
if (/_(?:DLB|CLR|OB|CB)$/.test(idName)) return;
const span = el.querySelector('.submenuText') || el.querySelector('span');
const text = norm(span?.textContent) || norm(el.innerText);
if (!text && !el.classList.contains('pressCommand')) return;
const isSubmenu = /^(?:Подменю|allActions)/i.test(idName);
const item = { id: el.id, name: text || idName, label: idName, kind: isSubmenu ? 'submenu' : 'button' };
// Icon-only buttons: use tooltip for fuzzy match (1C puts title on parent .framePress)
if (!text) { const tip = norm(el.title || el.parentElement?.title || ''); if (tip) item.tooltip = tip; }
items.push(item);
});
// Hyperlinks (staticTextHyper)
[...document.querySelectorAll('[id^="' + p + '"].staticTextHyper')].filter(el => el.offsetWidth > 0).forEach(el => {
const idName = el.id.replace(p, '');
const text = norm(el.innerText);
items.push({ id: el.id, name: text, label: idName, kind: 'hyperlink' });
});
// Frame buttons
[...document.querySelectorAll('[id^="' + p + '"] .frameButton, [id^="' + p + '"].frameButton')].filter(el => el.offsetWidth > 0).forEach(el => {
const text = norm(el.innerText);
const idName = el.id.replace(p, '');
if (!text && !idName) return;
items.push({ id: el.id, name: text || idName, label: text ? '' : idName, kind: 'frameButton' });
});
// Tumbler items (toggle switch segments)
[...document.querySelectorAll('[id^="' + p + '"].tumblerItem')].filter(el => el.offsetWidth > 0).forEach(el => {
const idName = el.id.replace(p, '');
const text = norm(el.innerText);
items.push({ id: el.id, name: text || idName, label: idName, kind: 'tumbler' });
});
// Checkboxes (div.checkbox) — match by label or internal name
[...document.querySelectorAll('[id^="' + p + '"].checkbox')].filter(el => el.offsetWidth > 0).forEach(el => {
const idName = el.id.replace(p, '');
const titleEl = document.getElementById(p + idName + '#title_text');
const label = norm(titleEl?.innerText || '').replace(/:/g, '').trim();
items.push({ id: el.id, name: label || idName, label: idName, kind: 'checkbox' });
});
// Tabs (scoped to form)
[...document.querySelectorAll('[data-content]')].filter(el => {
if (el.offsetWidth === 0) return false;
let node = el.parentElement;
while (node) {
if (node.id && node.id.startsWith(p)) return true;
node = node.parentElement;
}
return false;
}).forEach(el => {
const r = el.getBoundingClientRect();
items.push({ id: el.id, name: el.dataset.content, label: '', kind: 'tab',
x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) });
});
// Navigation panel items (FormNavigationPanel) — in parent page{N}
const formEl = document.querySelector('[id^="' + p + '"]');
if (formEl) {
let pageEl = formEl.parentElement;
while (pageEl && !(pageEl.id && /^page\\d+$/.test(pageEl.id))) pageEl = pageEl.parentElement;
if (pageEl) {
pageEl.querySelectorAll('.navigationItem').forEach(el => {
if (el.offsetWidth === 0) return;
const nameEl = el.querySelector('.navigationItemName');
const text = norm(nameEl?.innerText || '');
if (!text) return;
items.push({ id: el.id, name: text, label: '', kind: 'navigation' });
});
}
}
// When table is specified, scope button search to grid's parent container
if (gridSelector) {
const gridEl = document.querySelector(gridSelector);
if (gridEl) {
// Find parent container that has id with formPrefix and contains the grid
let container = gridEl.parentElement;
while (container && container !== document.body) {
if (container.id && container.id.startsWith(p)) break;
container = container.parentElement;
}
// Filter items to those inside the container
const containerItems = container && container !== document.body
? items.filter(i => { const el = document.getElementById(i.id); return el && container.contains(el); })
: [];
// Try fuzzy match within container first
let cf = containerItems.find(i => i.name.toLowerCase() === target);
if (!cf) cf = containerItems.find(i => i.label && i.label.toLowerCase() === target);
if (!cf && target.length >= 4) cf = containerItems.find(i => i.name.toLowerCase().includes(target));
if (!cf && target.length >= 4) cf = containerItems.find(i => i.label && i.label.toLowerCase().includes(target));
if (cf) { const res = { id: cf.id, kind: cf.kind, name: cf.name }; if (cf.x != null) { res.x = cf.x; res.y = cf.y; } return res; }
// Fallback: filter by gridName id-prefix (e.g. ИсходящиеКоманднаяПанель_Добавить)
const gridName = gridEl.id ? gridEl.id.replace(p, '') : '';
if (gridName) {
const prefixItems = items.filter(i => i.label && i.label.includes(gridName));
let pf = prefixItems.find(i => i.name.toLowerCase() === target);
if (!pf && target.length >= 4) pf = prefixItems.find(i => i.label && i.label.toLowerCase().includes(target));
if (!pf && target.length >= 4) pf = prefixItems.find(i => i.name.toLowerCase().includes(target));
if (pf) { const res = { id: pf.id, kind: pf.kind, name: pf.name }; if (pf.x != null) { res.x = pf.x; res.y = pf.y; } return res; }
}
}
// Fall through to unscoped search
}
// Fuzzy match: exact name -> exact label -> exact tooltip -> startsWith name -> startsWith label -> includes name -> includes label -> includes tooltip
// Skip includes() for short strings (< 4 chars) to avoid false positives
// e.g. "Да" matching "КомандаУстановитьВсе"
let found = items.find(i => i.name.toLowerCase() === target);
if (!found) found = items.find(i => i.label && i.label.toLowerCase() === target);
if (!found) found = items.find(i => i.tooltip && i.tooltip.toLowerCase() === target);
if (!found) found = items.find(i => i.name.toLowerCase().startsWith(target));
if (!found) found = items.find(i => i.label && i.label.toLowerCase().startsWith(target));
if (!found && target.length >= 4) found = items.find(i => i.name.toLowerCase().includes(target));
if (!found && target.length >= 4) found = items.find(i => i.label && i.label.toLowerCase().includes(target));
if (!found && target.length >= 4) found = items.find(i => i.tooltip && i.tooltip.toLowerCase().includes(target));
if (found) {
const res = { id: found.id, kind: found.kind, name: found.name };
if (found.x != null) { res.x = found.x; res.y = found.y; }
return res;
}
// Grid rows — fallback: search in table rows (for hierarchical/tree navigation)
// Search ALL visible grids (or specific grid when table parameter is set)
let grids;
if (gridSelector) {
const g = document.querySelector(gridSelector);
grids = g ? [g] : [];
} else {
grids = [...document.querySelectorAll('[id^="' + p + '"].grid')].filter(g => g.offsetWidth > 0);
}
for (const grid of grids) {
const body = grid.querySelector('.gridBody');
if (!body) continue;
const lines = [...body.querySelectorAll('.gridLine')];
for (const line of lines) {
const textBoxes = [...line.querySelectorAll('.gridBoxText')].filter(b => b.offsetWidth > 0);
const rowTexts = textBoxes.map(b => norm(b.innerText) || '').filter(Boolean);
const firstCell = rowTexts[0]?.toLowerCase() || '';
const rowText = rowTexts.join(' ').toLowerCase();
if (firstCell === target || rowText === target || (target.length >= 4 && (firstCell.includes(target) || rowText.includes(target)))) {
const imgBox = line.querySelector('.gridBoxImg');
const isGroup = imgBox?.querySelector('.gridListH') !== null;
const isParent = imgBox?.querySelector('.gridListV') !== null;
const isTreeNode = line.querySelector('.gridBoxTree') !== null;
const hasChildren = line.querySelector('[tree="true"]') !== null;
let kind;
if (isGroup) kind = 'gridGroup';
else if (isParent) kind = 'gridParent';
else if (isTreeNode && hasChildren) kind = 'gridTreeNode';
else kind = 'gridRow';
// Click point: first visible text cell of the row, NOT the row-line centre.
// A wide multi-column row's centre lands beyond the form's viewport (e.g. on
// narrow modal selection forms) so mouse.click misses the row. See ROW_CLICK_POINT_FN.
const pt = rowClickPoint(line, body);
const r = line.getBoundingClientRect();
return { id: '', kind, name: rowTexts[0] || '', gridId: grid.id,
x: pt ? pt.x : Math.round(r.x + r.width / 2),
y: pt ? pt.y : Math.round(r.y + r.height / 2) };
}
}
}
// Form input fields — LAST resort: focus a field by name/label without changing its value.
// Only when no table scope is given ("если нет уточнения таблицы"): grid cells are handled elsewhere.
// Reached only after every clickable target (button/link/tab/nav/grid row) failed to match,
// so collisions between a field name and a real control are unlikely.
const fields = [];
if (!tableName) {
[...document.querySelectorAll('input.editInput[id^="' + p + '"], textarea[id^="' + p + '"]')].forEach(el => {
if (el.offsetWidth === 0) return;
// Skip inputs inside a grid — those are table cells, not form fields.
let n = el.parentElement; let inGrid = false;
while (n) { if (n.classList && n.classList.contains('grid')) { inGrid = true; break; } n = n.parentElement; }
if (inGrid) return;
const idName = el.id.replace(p, '').replace(/_i\\d+$/, '');
const titleEl = document.getElementById(p + idName + '#title_text') || document.getElementById(p + idName + '#title_div');
const label = norm(titleEl?.innerText || '').replace(/:/g, '').trim();
fields.push({ id: el.id, name: idName, label });
});
let ff = fields.find(f => f.label && f.label.toLowerCase() === target);
if (!ff) ff = fields.find(f => f.name.toLowerCase() === target);
if (!ff) ff = fields.find(f => f.label && f.label.toLowerCase().startsWith(target));
if (!ff) ff = fields.find(f => f.name.toLowerCase().startsWith(target));
if (!ff && target.length >= 4) ff = fields.find(f => f.label && f.label.toLowerCase().includes(target));
if (!ff && target.length >= 4) ff = fields.find(f => f.name.toLowerCase().includes(target));
if (ff) return { id: ff.id, kind: 'field', name: ff.label || ff.name };
}
const available = items.map(i => i.tooltip ? i.name + ' [' + i.tooltip + ']' : i.name).filter(Boolean);
for (const f of fields) { const nm = f.label || f.name; if (nm && !available.includes(nm)) available.push(nm); }
return { error: 'not_found', available };
})()`;
}
/**
* Find a field's action button (DLB, OB, CLR, CB) by fuzzy field name.
* Returns { fieldName, buttonId, buttonType } or { error, available }.
*/
export function findFieldButtonScript(formNum, fieldName, buttonSuffix = 'DLB') {
const p = `form${formNum}_`;
return `(() => {
const p = ${JSON.stringify(p)};
const target = ${JSON.stringify(fieldName.toLowerCase().replace(/ё/g, 'е'))};
const suffix = ${JSON.stringify(buttonSuffix)};
const allFields = [];
document.querySelectorAll('input.editInput[id^="' + p + '"], textarea[id^="' + p + '"]').forEach(el => {
if (el.offsetWidth === 0) return;
const name = el.id.replace(p, '').replace(/_i\\d+$/, '');
const titleEl = document.getElementById(p + name + '#title_text')
|| document.getElementById(p + name + '#title_div');
const label = (titleEl?.innerText?.trim() || '').replace(/\\n/g, ' ').replace(/:$/, '');
allFields.push({ name, label });
});
// Also collect checkboxes for DCS pair matching
const allCheckboxes = [];
document.querySelectorAll('[id^="' + p + '"].checkbox').forEach(el => {
if (el.offsetWidth === 0) return;
const name = el.id.replace(p, '');
const titleEl = document.getElementById(p + name + '#title_text');
const label = (titleEl?.innerText?.trim() || '').replace(/\\n/g, ' ').replace(/:$/, '');
allCheckboxes.push({ inputId: el.id, name, label });
});
// Build DCS pairs: checkbox label → paired value field
const dcsPairs = {};
for (const f of [...allFields, ...allCheckboxes]) {
const m = f.name.match(/^(.+Элемент\\d+)(Использование|Значение)$/);
if (!m) continue;
if (!dcsPairs[m[1]]) dcsPairs[m[1]] = {};
dcsPairs[m[1]][m[2]] = f;
}
let found = allFields.find(f => f.name.toLowerCase() === target);
if (!found) found = allFields.find(f => f.label && f.label.toLowerCase() === target);
if (!found) found = allFields.find(f => f.name.toLowerCase().includes(target));
if (!found) found = allFields.find(f => f.label && f.label.toLowerCase().includes(target));
// DCS pair: match checkbox or value label → resolve to paired value field
let dcsCheckbox = null;
if (!found) {
for (const pair of Object.values(dcsPairs)) {
const cb = pair['Использование'];
const val = pair['Значение'];
if (!cb || !val) continue;
const pairLabel = ((val.label || cb.label || '').replace(/:$/, '')).toLowerCase();
if (pairLabel && (pairLabel === target || pairLabel.includes(target) || target.includes(pairLabel))) {
found = val;
dcsCheckbox = cb;
break;
}
}
}
if (!found) {
return { error: 'field_not_found', available: allFields.map(f => f.label ? f.name + ' (' + f.label + ')' : f.name) };
}
const btnId = p + found.name + '_' + suffix;
const btn = document.getElementById(btnId);
if (!btn || btn.offsetWidth === 0) {
return { error: 'button_not_found', fieldName: found.name, message: suffix + ' button not visible for field ' + found.name };
}
const result = { fieldName: found.name, buttonId: btnId, buttonType: suffix };
if (dcsCheckbox) result.dcsCheckbox = { inputId: dcsCheckbox.inputId };
return result;
})()`;
}
/**
* Resolve field names to element IDs for Playwright page.fill().
* Returns [{ field, inputId, name, label }] or [{ field, error, available }].
* Supports synonym matching: internal name AND visible label.
* Fuzzy order: exact name -> exact label -> includes name -> includes label.
*/
export function resolveFieldsScript(formNum, fields) {
const p = `form${formNum}_`;
return `(() => {
const p = ${JSON.stringify(p)};
const fieldNames = ${JSON.stringify(Object.keys(fields))};
const results = [];
// Build field map with name + label for synonym matching
const allFields = [];
document.querySelectorAll('input.editInput[id^="' + p + '"], textarea[id^="' + p + '"]').forEach(el => {
if (el.offsetWidth === 0) return;
const name = el.id.replace(p, '').replace(/_i\\d+$/, '');
const titleEl = document.getElementById(p + name + '#title_text')
|| document.getElementById(p + name + '#title_div');
const label = (titleEl?.innerText?.trim() || '').replace(/\\n/g, ' ').replace(/:$/, '');
const last = { inputId: el.id, name, label };
if (document.getElementById(p + name + '_DLB')?.offsetWidth > 0) last.hasSelect = true;
const cbEl = document.getElementById(p + name + '_CB');
if (cbEl?.offsetWidth > 0) {
last.hasPick = true;
if (cbEl.classList.contains('iCalendB')) last.isDate = true;
else if (cbEl.classList.contains('iCalcB')) last.isCalc = true;
}
allFields.push(last);
});
// Checkboxes
document.querySelectorAll('[id^="' + p + '"].checkbox').forEach(el => {
if (el.offsetWidth === 0) return;
const name = el.id.replace(p, '');
const titleEl = document.getElementById(p + name + '#title_text');
const label = (titleEl?.innerText?.trim() || '').replace(/\\n/g, ' ').replace(/:$/, '');
const checked = el.classList.contains('checked') || el.classList.contains('checkboxOn') || el.classList.contains('select');
allFields.push({ inputId: el.id, name, label, isCheckbox: true, checked });
});
// Radio button groups — base element = option 0, others are #N#radio
const radioSeen = new Set();
document.querySelectorAll('[id^="' + p + '"].radio').forEach(el => {
if (el.offsetWidth === 0) return;
const id = el.id.replace(p, '');
// Skip if already processed or if it's a sub-element (#N#radio)
const m = id.match(/^(.+?)#(\\d+)#radio$/);
const groupName = m ? m[1] : (!id.includes('#') ? id : null);
if (!groupName || radioSeen.has(groupName)) return;
radioSeen.add(groupName);
const titleEl = document.getElementById(p + groupName + '#title_text');
const label = (titleEl?.innerText?.trim() || '').replace(/\\n/g, ' ').replace(/:$/, '');
// Collect options: option 0 is the base element, options 1+ have #N#radio
const options = [];
// Option 0: base element
const base = document.getElementById(p + groupName);
if (base && base.classList.contains('radio') && base.offsetWidth > 0) {
const textEl = document.getElementById(p + groupName + '#0#radio_text');
options.push({ index: 0, label: textEl?.innerText?.trim() || '', selected: base.classList.contains('select') });
}
// Options 1+
for (let i = 1; i < 20; i++) {
const opt = document.getElementById(p + groupName + '#' + i + '#radio');
if (!opt || opt.offsetWidth === 0) break;
const textEl = document.getElementById(p + groupName + '#' + i + '#radio_text');
options.push({ index: i, label: textEl?.innerText?.trim() || '', selected: opt.classList.contains('select') });
}
allFields.push({ inputId: p + groupName, name: groupName, label, isRadio: true, options });
});
// Build DCS pairs: checkbox label → paired value field
const dcsPairs = {};
for (const f of allFields) {
const m = f.name.match(/^(.+Элемент\\d+)(Использование|Значение)$/);
if (!m) continue;
if (!dcsPairs[m[1]]) dcsPairs[m[1]] = {};
dcsPairs[m[1]][m[2]] = f;
}
for (const fieldName of fieldNames) {
const target = fieldName.toLowerCase().replace(/\\n/g, ' ').replace(/:$/, '');
// Fuzzy: exact name -> exact label -> includes name -> includes label
let found = allFields.find(f => f.name.toLowerCase() === target);
if (!found) found = allFields.find(f => f.label && f.label.toLowerCase() === target);
if (!found) found = allFields.find(f => f.name.toLowerCase().includes(target));
if (!found) found = allFields.find(f => f.label && f.label.toLowerCase().includes(target));
// DCS pair: match checkbox or value label → resolve to paired value field
if (!found) {
for (const pair of Object.values(dcsPairs)) {
const cb = pair['Использование'];
const val = pair['Значение'];
if (!cb || !val) continue;
const pairLabel = ((val.label || cb.label || '').replace(/:$/, '')).toLowerCase();
if (pairLabel && (pairLabel === target || pairLabel.includes(target) || target.includes(pairLabel))) {
found = val;
found._dcsCheckbox = cb;
break;
}
}
}
if (found) {
const entry = { field: fieldName, inputId: found.inputId, name: found.name, label: found.label };
if (found.isCheckbox) { entry.isCheckbox = true; entry.checked = found.checked; }
if (found.isRadio) { entry.isRadio = true; entry.options = found.options; }
if (found.hasSelect) entry.hasSelect = true;
if (found.hasPick) entry.hasPick = true;
if (found.isDate) entry.isDate = true;
if (found.isCalc) entry.isCalc = true;
if (found._dcsCheckbox) {
entry.dcsCheckbox = { inputId: found._dcsCheckbox.inputId, checked: found._dcsCheckbox.checked };
delete found._dcsCheckbox;
}
results.push(entry);
} else {
const available = allFields.map(f => f.label ? f.name + ' (' + f.label + ')' : f.name);
results.push({ field: fieldName, error: 'not_found', available });
}
}
return results;
})()`;
}
/**
* Detect a new form opened above `prevFormNum`. Two modes:
* default (broad) counts any visible `[id]` element; finds dialogs whose
* `a.press` buttons have empty IDs. Used by selectValue / fillTableRow.
* `{ strict: true }` only counts visible interactive elements
* (`input.editInput[id], a.press[id]`); used by fillReferenceField.
*
* Returns the highest new form number or `null`.
*/
export function detectNewFormScript(prevFormNum, { strict = false } = {}) {
const selector = strict ? 'input.editInput[id], a.press[id]' : '[id]';
const visibleCheck = strict
? 'el.offsetWidth === 0'
: 'el.offsetWidth === 0 && el.offsetHeight === 0';
return `(() => {
const forms = {};
document.querySelectorAll(${JSON.stringify(selector)}).forEach(el => {
if (${visibleCheck}) return;
const m = el.id.match(/^form(\\d+)_/);
if (m) forms[m[1]] = true;
});
const nums = Object.keys(forms).map(Number).filter(n => n > ${prevFormNum});
return nums.length > 0 ? Math.max(...nums) : null;
})()`;
}
/**
* Find the search input on a list form (matches `SearchString` / `ПоискаСтроки` id).
* Returns `{ id, value } | null`.
*/
export function findSearchInputScript(formNum) {
return `(() => {
const p = 'form${formNum}_';
const el = [...document.querySelectorAll('input.editInput[id^="' + p + '"]')]
.find(el => el.offsetWidth > 0 && /Строк[аи]Поиска|SearchString/i.test(el.id));
return el ? { id: el.id, value: el.value || '' } : null;
})()`;
}
/**
* Find a visible `a.press` button by its exact innerText (after trim).
* Returns `{ x, y } | null` for `page.mouse.click(x, y)`.
*
* Used for modal dialog buttons (Найти, OK) where page.click may be blocked.
*/
export function findNamedButtonScript(buttonText) {
return `(() => {
const btns = [...document.querySelectorAll('a.press')].filter(el => el.offsetWidth > 0);
const btn = btns.find(el => el.innerText?.trim() === ${JSON.stringify(buttonText)});
if (!btn) return null;
const r = btn.getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) };
})()`;
}
/**
* Find a CompareType radio button by index (1 = "contains", 2 = "exact", etc.)
* on a search/filter dialog.
*
* Returns:
* - `{ already: true }` the group is disabled OR the radio is already selected
* - `{ x, y } | null` coords to click, or null if radio not present
*/
export function findCompareTypeRadioScript(dialogForm, radioIndex) {
return `(() => {
const p = 'form' + ${JSON.stringify(String(dialogForm))} + '_';
const group = document.getElementById(p + 'CompareType');
if (group && group.classList.contains('disabled')) return { already: true };
const el = document.getElementById(p + 'CompareType#' + ${JSON.stringify(String(radioIndex))} + '#radio');
if (!el || el.offsetWidth === 0) return null;
if (el.classList.contains('select')) return { already: true };
const r = el.getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) };
})()`;
}
/**
* Is any element of `form{dialogForm}_` currently visible?
* Used to poll dialog dismissal after Escape.
*/
export function isFormVisibleScript(dialogForm) {
return `(() => {
const p = 'form${dialogForm}_';
return [...document.querySelectorAll('[id^="' + p + '"]')].some(el => el.offsetWidth > 0);
})()`;
}
/**
* Find the Pattern input id on a search/filter dialog. Returns `id | null`.
*/
export function findPatternInputIdScript(dialogForm) {
return `(() => {
const p = 'form${dialogForm}_';
const el = [...document.querySelectorAll('input.editInput[id^="' + p + '"]')]
.find(el => el.offsetWidth > 0 && /Pattern/i.test(el.id));
return el ? el.id : null;
})()`;
}
/**
* Is the given form a type selection dialog ("Выбор типа данных")?
*
* Detection signals (any one is sufficient):
* - `form{N}_OK` element exists (selection forms use "Выбрать", not "OK")
* - `form{N}_ValueList` grid exists (specific to type/value list dialogs)
* - window title contains "Выбор типа" on a visible `.toplineBoxTitle`
*
* Returns boolean.
*/
export function isTypeDialogScript(formNum) {
return `(() => {
const p = 'form' + ${formNum} + '_';
const hasOK = !!document.getElementById(p + 'OK');
const hasValueList = !!document.getElementById(p + 'ValueList');
const hasTitle = [...document.querySelectorAll('.toplineBoxTitle')]
.some(el => el.offsetWidth > 0 && /выбор типа/i.test(el.getAttribute('title') || ''));
return hasOK || hasValueList || hasTitle;
})()`;
}
/**
* Click the "Показать все" / "Show all" link inside the "нет в списке"
* cloud popup via `dispatchEvent`. Returns boolean whether clicked.
*/
export function clickShowAllInNotInListCloudScript() {
return `(() => {
for (const el of document.querySelectorAll('div')) {
if (el.offsetWidth === 0 || el.offsetHeight === 0) continue;
const s = getComputedStyle(el);
if (s.position !== 'absolute' && s.position !== 'fixed') continue;
if ((parseInt(s.zIndex) || 0) < 100) continue;
if (!(el.innerText || '').includes('нет в списке')) continue;
const links = [...el.querySelectorAll('a, span, div')]
.filter(e => e.offsetWidth > 0 && e.children.length === 0);
const showAll = links.find(e => {
const t = (e.innerText?.trim() || '').toLowerCase();
return t === 'показать все' || t === 'show all';
});
if (showAll) {
const r = showAll.getBoundingClientRect();
const opts = { bubbles:true, cancelable:true,
clientX: r.x + r.width/2, clientY: r.y + r.height/2 };
showAll.dispatchEvent(new MouseEvent('mousedown', opts));
showAll.dispatchEvent(new MouseEvent('mouseup', opts));
showAll.dispatchEvent(new MouseEvent('click', opts));
return true;
}
return false;
}
return false;
})()`;
}
/**
* Is the "нет в списке" cloud popup visible? 1C shows it as a positioned div
* (absolute/fixed, high z-index) whose text contains "нет в списке".
* Returns boolean.
*/
export function isNotInListCloudVisibleScript() {
return `(() => {
const divs = document.querySelectorAll('div');
for (const el of divs) {
if (el.offsetWidth === 0 || el.offsetHeight === 0) continue;
const style = getComputedStyle(el);
if (style.position !== 'absolute' && style.position !== 'fixed') continue;
const z = parseInt(style.zIndex) || 0;
if (z < 100) continue;
if ((el.innerText || '').includes('нет в списке')) return true;
}
return false;
})()`;
}
/**
* Find a child form opened above `prevFormNum` whose `form{N}_{buttonName}` button is visible.
* Used by type-dialog Ctrl+F flow to locate the "Найти" sub-dialog form number.
* Returns the form number or `null`.
*/
export function findChildFormByButtonScript(prevFormNum, buttonName, range = 20) {
return `(() => {
for (let n = ${prevFormNum} + 1; n < ${prevFormNum} + ${range}; n++) {
const btn = document.getElementById('form' + n + '_' + ${JSON.stringify(buttonName)});
if (btn && btn.offsetWidth > 0) return n;
}
return null;
})()`;
}
/**
* Read visible rows of a type-dialog ValueList grid and return rows that fuzzy-match `typeNorm`.
*
* `typeNorm` should already be lowercased, NBSP-normalized, ёе normalized (use `normYo`).
*
* Returns `{ visible: string[], matches: Array<{ text, x, y }> }`.
*/
export function readTypeDialogVisibleRowsScript(formNum, typeNorm) {
return `(() => {
const grid = document.getElementById('form${formNum}_ValueList');
if (!grid) return { visible: [], matches: [] };
const body = grid.querySelector('.gridBody');
if (!body) return { visible: [], matches: [] };
const lines = body.querySelectorAll('.gridLine');
const norm = s => (s || '').replace(/\\u00a0/g, ' ').trim();
const typeNorm = ${JSON.stringify(typeNorm)};
const visible = [];
const matches = [];
for (const line of lines) {
const text = norm(line.innerText);
if (!text) continue;
visible.push(text);
if (text.toLowerCase().replace(/ё/gi, 'е').includes(typeNorm)) {
const r = line.getBoundingClientRect();
matches.push({ text, x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) });
}
}
return { visible, matches };
})()`;
}
@@ -1,334 +0,0 @@
// web-test dom/grid-edit v1.2 — DOM scripts for row-fill (grid edit-time operations)
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
//
import { HEADERLESS_GRID_FN } from './_shared.mjs';
//
// All helpers below accept an optional `gridSelector`. When passed, they target
// that exact grid; when null/undefined they pick the LAST visible `.grid` on
// the page (this matches the implicit "current grid" used by row-fill).
/** Inline JS fragment that resolves the target grid into `const grid`. */
function gridResolver(gridSelector) {
return gridSelector
? `document.querySelector(${JSON.stringify(gridSelector)})`
: `(() => { const grids = [...document.querySelectorAll('.grid')].filter(el => el.offsetWidth > 0); return grids[grids.length - 1]; })()`;
}
/**
* Read the grid's column header texts paired with their `colindex` attribute,
* fuzzy-match `fieldKeys` (lowercased) against them, and return the keys in
* left-to-right colindex order.
*
* Keys that don't match a column get colindex `999` (pushed to the end);
* caller is expected to preserve their original relative order.
*
* Returns `string[] | null` (null when no grid or no head).
*/
export function sortFieldKeysByColindexScript(gridSelector, fieldKeys) {
return `(() => {
${HEADERLESS_GRID_FN}
const grid = ${gridResolver(gridSelector)};
if (!grid) return null;
const head = grid.querySelector('.gridHead');
const cols = [];
if (head) {
const headLine = head.querySelector('.gridLine') || head;
[...headLine.children].forEach(box => {
if (box.offsetWidth === 0) return;
const t = ((box.querySelector('.gridBoxText') || box).innerText?.trim() || '').toLowerCase();
const ci = parseInt(box.getAttribute('colindex') || '-1');
if (t) cols.push({ text: t, colindex: ci });
});
} else {
// Headerless: synthesized columns (КолонкаN/(checkbox)) ordered by colindex
synthHeaderlessColumns(grid).forEach(c => cols.push({ text: c.name.toLowerCase(), colindex: parseInt(c.colindex) }));
}
const keys = ${JSON.stringify(fieldKeys)};
const mapped = keys.map(k => {
const exact = cols.find(c => c.text === k);
if (exact) return { key: k, colindex: exact.colindex };
const inc = cols.find(c => c.text.includes(k) || k.includes(c.text));
return { key: k, colindex: inc ? inc.colindex : 999 };
});
mapped.sort((a, b) => a.colindex - b.colindex);
return mapped.map(m => m.key);
})()`;
}
/**
* Resolve cell coords for row `row` by matching the first column whose header
* fuzzy-matches any of `fieldKeys` (lowercased). Falls back to the second
* visible (non-`.gridBoxComp`) box when no header matches.
*
* Returns one of:
* - `{ x, y, currentText }` coords + cell text
* - `{ error: 'no_grid' | 'no_grid_body' | 'no_cell' }`
* - `{ error: 'row_out_of_range', total }`
*/
export function findCellCoordsByFieldsScript(gridSelector, row, fieldKeys) {
return `(() => {
${HEADERLESS_GRID_FN}
const grid = ${gridResolver(gridSelector)};
if (!grid) return { error: 'no_grid' };
const head = grid.querySelector('.gridHead');
const body = grid.querySelector('.gridBody');
if (!body) return { error: 'no_grid_body' };
// Read columns to find target colindex (+ subTarget for headerless split mark-boxes)
const cols = [];
if (head) {
const headLine = head.querySelector('.gridLine') || head;
[...headLine.children].forEach(box => {
if (box.offsetWidth === 0) return;
const t = box.querySelector('.gridBoxText');
const ci = box.getAttribute('colindex');
cols.push({ colindex: ci, text: ((t || box).innerText?.trim() || '').toLowerCase(), subTarget: null });
});
} else {
synthHeaderlessColumns(grid).forEach(c => cols.push({ colindex: c.colindex, text: c.name.toLowerCase(), subTarget: c.subTarget }));
}
const keys = ${JSON.stringify(fieldKeys)};
let targetColindex = null, targetSub = null;
for (const key of keys) {
const exact = cols.find(c => c.text === key);
if (exact) { targetColindex = exact.colindex; targetSub = exact.subTarget; break; }
const inc = cols.find(c => c.text.includes(key) || key.includes(c.text));
if (inc) { targetColindex = inc.colindex; targetSub = inc.subTarget; break; }
}
const rows = [...body.querySelectorAll('.gridLine')];
if (${row} >= rows.length) return { error: 'row_out_of_range', total: rows.length };
const line = rows[${row}];
// Find body cell by colindex (reliable across merged headers)
let box = null;
if (targetColindex != null) {
box = [...line.children].find(b => b.offsetWidth > 0 && b.getAttribute('colindex') === targetColindex);
}
// Fallback: second visible box (skip checkbox/N column)
if (!box) {
const boxes = [...line.children].filter(b => b.offsetWidth > 0 && !b.classList.contains('gridBoxComp'));
box = boxes.length > 1 ? boxes[1] : boxes[0];
}
if (!box) return { error: 'no_cell' };
box.scrollIntoView({ block: 'nearest', inline: 'nearest' });
// subTarget-aware cell node: 'checkbox' → box itself (row-fill then uses findCheckboxAtPoint),
// 'title' → .gridBoxTitle, else (headed default / 'text') → .gridBoxText || box.
let cell;
if (targetSub === 'checkbox') cell = box;
else if (targetSub === 'title') cell = box.querySelector('.gridBoxTitle') || box;
else cell = box.querySelector('.gridBoxText') || box;
const r = cell.getBoundingClientRect();
const currentText = (cell.innerText?.trim() || '').replace(/\\u00a0/g, ' ');
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2), currentText };
})()`;
}
/**
* Like `findCellCoordsByFieldsScript` but for a SINGLE key, with extra
* "no-space/no-dash" fuzzy fallback (e.g. "Группа Контрагентов" header matches
* key "ГруппаКонтрагентов").
*
* Returns `{ x, y, currentText } | null`.
*/
export function findNextCellCoordsByKeyScript(gridSelector, row, key) {
return `(() => {
${HEADERLESS_GRID_FN}
const grid = ${gridResolver(gridSelector)};
if (!grid) return null;
const head = grid.querySelector('.gridHead');
const body = grid.querySelector('.gridBody');
if (!body) return null;
const cols = [];
if (head) {
const headLine = head.querySelector('.gridLine') || head;
[...headLine.children].forEach(box => {
if (box.offsetWidth === 0) return;
const t = box.querySelector('.gridBoxText');
const ci = box.getAttribute('colindex');
cols.push({ colindex: ci, text: ((t || box).innerText?.trim() || '').toLowerCase(), subTarget: null });
});
} else {
synthHeaderlessColumns(grid).forEach(c => cols.push({ colindex: c.colindex, text: c.name.toLowerCase(), subTarget: c.subTarget }));
}
const kl = ${JSON.stringify(key.toLowerCase())};
const klNoSpace = kl.replace(/[\\s\\-]+/g, '');
let targetColindex = null, targetSub = null;
const exact = cols.find(c => c.text === kl);
if (exact) { targetColindex = exact.colindex; targetSub = exact.subTarget; }
else {
const inc = cols.find(c => c.text.includes(kl) || kl.includes(c.text)
|| c.text.includes(klNoSpace) || klNoSpace.includes(c.text));
if (inc) { targetColindex = inc.colindex; targetSub = inc.subTarget; }
}
if (targetColindex == null) return null;
const rows = [...body.querySelectorAll('.gridLine')];
if (${row} >= rows.length) return null;
const line = rows[${row}];
const box = [...line.children].find(b => b.offsetWidth > 0 && b.getAttribute('colindex') === targetColindex);
if (!box) return null;
box.scrollIntoView({ block: 'nearest', inline: 'nearest' });
let cell;
if (targetSub === 'checkbox') cell = box;
else if (targetSub === 'title') cell = box.querySelector('.gridBoxTitle') || box;
else cell = box.querySelector('.gridBoxText') || box;
const r = cell.getBoundingClientRect();
const currentText = (cell.innerText?.trim() || '').replace(/\\u00a0/g, ' ');
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2), currentText };
})()`;
}
/**
* Inspect the element at point `(x, y)`. If it's inside a `.gridBox` containing
* a `.checkbox`, return `{ checked, x, y }` (coords of the checkbox center for
* direct click).
*
* Returns `null` when there's no cell, or the cell isn't a checkbox cell.
*/
export function findCheckboxAtPointScript(x, y) {
return `(() => {
const el = document.elementFromPoint(${x}, ${y});
const cell = el?.closest('.gridBox');
if (!cell) return null;
const chk = cell.querySelector('.checkbox');
if (!chk) return null;
const r = chk.getBoundingClientRect();
return { checked: chk.classList.contains('select'), x: Math.round(r.x + r.width/2), y: Math.round(r.y + r.height/2) };
})()`;
}
/**
* Find center coords of the first VISIBLE non-`.gridBoxComp` cell on a row
* OTHER than `row` (used to commit an edit by clicking off the edited row
* Escape would cancel in tree grids).
*
* For `row === 0`, targets row 1; otherwise targets row 0.
*
* Returns `{ x, y } | null` (null when there's no other row).
*/
export function findRowCommitClickCoordsScript(gridSelector, row) {
return `(() => {
const grid = ${gridResolver(gridSelector)};
if (!grid) return null;
const body = grid.querySelector('.gridBody');
if (!body) return null;
const rows = [...body.querySelectorAll('.gridLine')];
const otherIdx = ${row} === 0 ? 1 : 0;
const other = rows[otherIdx];
if (!other) return null;
const visBoxes = [...other.children].filter(b => b.offsetWidth > 0 && !b.classList.contains('gridBoxComp'));
const box = visBoxes.length > 1 ? visBoxes[1] : visBoxes[0];
if (!box) return null;
const r = box.getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) };
})()`;
}
/**
* Diagnostic: are we in grid edit mode (active INPUT inside `.grid` or
* `.gridContent`)? Returns an OBJECT (not a boolean) suitable for diagnostics:
* - `{ inEdit: true }` good
* - `{ inEdit: false, tag: 'DIV' }` active element wasn't INPUT
* - `{ inEdit: false, hint: 'input not inside grid' }` input but no grid ancestor
*/
export function getGridEditCheckScript() {
return `(() => {
const f = document.activeElement;
if (!f || f.tagName !== 'INPUT') return { inEdit: false, tag: f?.tagName };
let node = f;
while (node) {
if (node.classList?.contains('grid') || node.classList?.contains('gridContent')) return { inEdit: true };
node = node.parentElement;
}
return { inEdit: false, hint: 'input not inside grid' };
})()`;
}
/**
* Read the currently focused element if it's an editable grid cell (INPUT or
* TEXTAREA inside `.grid` / `.gridContent`). Resolves the header text by
* matching x-overlap of the input's bounding rect against header boxes.
*
* Returns one of:
* - `{ tag: 'INPUT', id, fullName, headerText }` editable cell
* - `{ tag: 'DIV' | 'BODY' | ... }` focused but not an editable cell
* - `{ tag: 'none' }` nothing focused
*
* `fullName` strips both `form{N}_` prefix and `_i{M}` suffix.
*/
export function readActiveGridCellScript() {
return `(() => {
${HEADERLESS_GRID_FN}
const f = document.activeElement;
if (!f) return { tag: 'none' };
if (f.tagName === 'INPUT' || f.tagName === 'TEXTAREA') {
const inGrid = (() => { let n = f; while (n) { if (n.classList?.contains('grid') || n.classList?.contains('gridContent')) return true; n = n.parentElement; } return false; })();
if (inGrid) {
let headerText = '';
let grid = f; while (grid && !grid.classList?.contains('grid')) grid = grid.parentElement;
if (grid) {
const fr = f.getBoundingClientRect();
const head = grid.querySelector('.gridHead');
const hl = head?.querySelector('.gridLine') || head;
if (hl) for (const h of hl.children) {
if (h.offsetWidth === 0) continue;
const hr = h.getBoundingClientRect();
if (fr.x >= hr.x && fr.x < hr.x + hr.width) {
const t = h.querySelector('.gridBoxText');
headerText = (t || h).innerText?.trim() || '';
break;
}
}
if (!head) {
// Headerless: the editing INPUT is rendered in an overlay (.inputs) OUTSIDE
// the .gridBox, so walking ancestors for colindex fails. Resolve colindex by
// matching the input's x against the body cells (same idea as the headed branch).
const bl = grid.querySelector('.gridBody .gridLine');
let ci = null;
if (bl) for (const b of bl.children) {
if (b.offsetWidth === 0) continue;
const br = b.getBoundingClientRect();
if (fr.x >= br.x && fr.x < br.x + br.width) { ci = b.getAttribute('colindex'); break; }
}
if (ci != null) {
const sc = synthHeaderlessColumns(grid).find(c => c.kind === 'data' && c.colindex === ci);
if (sc) headerText = sc.name;
}
}
}
// Classify the cell's choice button (if any): ref (_DLB), calc/date (_CB iCalcB/iCalendB),
// or bare 'choice' (_CB iCB — value picked from a programmatic list, e.g. НачалоВыбора).
let buttonKind = null;
const base = f.id.replace(/_i\\d+$/, '');
const dlb = document.getElementById(base + '_DLB');
const cb = document.getElementById(base + '_CB');
if (dlb && dlb.offsetWidth > 0) buttonKind = 'ref';
else if (cb && cb.offsetWidth > 0) {
if (cb.classList.contains('iCalcB')) buttonKind = 'calc';
else if (cb.classList.contains('iCalendB')) buttonKind = 'date';
else buttonKind = 'choice';
}
return {
tag: 'INPUT', id: f.id,
fullName: f.id.replace(/^form\\d+_/, '').replace(/_i\\d+$/, ''),
headerText, buttonKind
};
}
}
return { tag: f.tagName || 'none' };
})()`;
}
/**
* Return center coords of the element with the given id.
* Returns `{ x, y } | null`.
*/
export function getElementCenterCoordsByIdScript(elementId) {
return `(() => {
const el = document.getElementById(${JSON.stringify(elementId)});
if (!el) return null;
const r = el.getBoundingClientRect();
return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
})()`;
}
@@ -1,966 +0,0 @@
// web-test dom/grid v1.12 — grid resolution + table reading + edit-time helpers
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { ROW_CLICK_POINT_FN, HEADERLESS_GRID_FN } from './_shared.mjs';
/**
* Resolve a specific grid by semantic name (table parameter).
* Cascade: exact gridName match gridName contains column contains.
* Returns { gridSelector, gridId, gridName, gridIndex, columns } or { error, available }.
*/
export function resolveGridScript(formNum, tableName) {
const p = `form${formNum}_`;
return `(() => {
const p = ${JSON.stringify(p)};
const target = ${JSON.stringify(tableName.toLowerCase().replace(/ё/g, 'е'))};
const norm = s => (s || '').replace(/ё/gi, 'е');
const allGrids = [...document.querySelectorAll('[id^="' + p + '"].grid, [id^="' + p + '"] .grid')]
.filter(g => g.offsetWidth > 0 && g.offsetHeight > 0);
if (!allGrids.length) return { error: 'no_grids', message: 'No grids found on form' };
const infos = allGrids.map((g, idx) => {
const gridId = g.id || '';
const gridName = gridId.replace(p, '');
const head = g.querySelector('.gridHead');
const columns = [];
if (head) {
const headLine = head.querySelector('.gridLine') || head;
[...headLine.children].forEach(box => {
if (box.offsetWidth === 0) return;
const textEl = box.querySelector('.gridBoxText');
const text = (textEl || box).innerText?.trim().replace(/\\n/g, ' ') || '';
if (text) columns.push(text);
});
}
// Visual label from group title element
const titleEl = document.getElementById(p + gridName + '#title_div')
|| document.getElementById(p + 'Группа' + gridName + '#title_div');
const label = titleEl ? (titleEl.innerText?.trim().replace(/:\s*$/, '').replace(/ /g, ' ') || '') : '';
return { idx, gridId, gridName, label, columns, el: g };
});
// 1. Exact gridName match (case-insensitive)
let found = infos.find(i => norm(i.gridName).toLowerCase() === target);
// 2. Exact label match
if (!found) found = infos.find(i => i.label && norm(i.label).toLowerCase() === target);
// 3. gridName contains target
if (!found) found = infos.find(i => norm(i.gridName).toLowerCase().includes(target));
// 4. Label contains target
if (!found) found = infos.find(i => i.label && norm(i.label).toLowerCase().includes(target));
// 5. Any column contains target
if (!found) found = infos.find(i => i.columns.some(c => norm(c).toLowerCase().includes(target)));
if (found) {
return {
gridSelector: found.gridId ? '#' + CSS.escape(found.gridId) : null,
gridId: found.gridId,
gridName: found.gridName,
gridIndex: found.idx,
columns: found.columns
};
}
return {
error: 'not_found',
message: 'Table "' + ${JSON.stringify(tableName)} + '" not found',
available: infos.map(i => ({ name: i.gridName, ...(i.label ? { label: i.label } : {}), columns: i.columns }))
};
})()`;
}
/**
* Read table/grid data with pagination.
* Parses grid.innerText \n separates rows, \t separates cells.
* First row = column headers.
* Returns { name, columns[], rows[{col:val}], total, offset, shown }.
*/
export function readTableScript(formNum, { maxRows = 20, offset = 0, gridSelector } = {}) {
const p = `form${formNum}_`;
return `(() => {
const p = ${JSON.stringify(p)};
const grid = ${gridSelector
? `document.querySelector(${JSON.stringify(gridSelector)})`
: `[...document.querySelectorAll('[id^="' + p + '"].grid, [id^="' + p + '"] .grid')]
.find(g => g.offsetWidth > 0 && g.offsetHeight > 0)`};
if (!grid) return { error: 'no_table', message: 'No table found on form ${formNum}' };
const name = grid.id ? grid.id.replace(p, '') : '';
// Detect a "picture value" cell: a sprite from a picture collection
// (.gridBoxImg .dIB with background-image .../pictureCollection/picture/<id>?...&gx=<N>).
// Excludes decorative tree/group markers (gridListH/gridListV/[tree]/gridBoxTree).
// Returns { gx } — the sprite frame index that encodes the cell state, or null.
function picInfo(cell) {
if (!cell) return null;
if (cell.querySelector('.gridListH, .gridListV, [tree="true"], .gridBoxTree')) return null;
const dib = cell.querySelector('.gridBoxImg .dIB');
if (!dib) return null;
const bg = dib.style.backgroundImage || '';
if (!bg.includes('pictureCollection/picture/')) return null;
const m = bg.match(/[?&]gx=(\\d+)/);
return { gx: m ? m[1] : '0' };
}
${HEADERLESS_GRID_FN}
// DOM-based parsing: gridHead → columns, gridBody → gridLine rows → gridBox cells
const head = grid.querySelector('.gridHead');
const body = grid.querySelector('.gridBody');
if (!body) {
// Fallback: innerText-based (for non-standard grids without a body)
const gText = grid.innerText?.trim() || '';
const lines = gText.split('\\n').filter(Boolean);
return { name, columns: [], rows: [], total: lines.length, offset: 0, shown: 0,
hint: 'Grid has no gridHead/gridBody structure' };
}
// HEADERLESS grid (body but no .gridHead) — synthesize columns by colindex.
// Single source: synthHeaderlessColumns. Headed path below is left untouched.
if (!head) {
const synth = synthHeaderlessColumns(grid);
const colNames = synth.map(c => c.name);
const allLines = body.querySelectorAll('.gridLine');
const total = allLines.length;
const rows = [];
const end = Math.min(${offset} + ${maxRows}, total);
for (let i = ${offset}; i < end; i++) {
const line = allLines[i];
if (!line) break;
const row = {};
const boxes = [...line.children].filter(b => b.offsetWidth > 0);
synth.forEach(c => {
const box = boxes.find(b => b.getAttribute('colindex') === c.colindex);
let val = '';
if (box) {
if (c.subTarget === 'checkbox') {
const chk = box.querySelector('.checkbox');
val = chk && chk.classList.contains('select') ? 'true' : 'false';
} else if (c.subTarget === 'title') {
val = (box.querySelector('.gridBoxTitle')?.innerText || '').trim().replace(/\\n/g, ' ');
} else if (c.subTarget === 'text') {
val = (box.querySelector('.gridBoxText')?.innerText || '').trim().replace(/\\n/g, ' ');
} else {
const pic = picInfo(box);
val = pic ? 'pic:' + pic.gx : ((box.innerText || '').trim().replace(/\\n/g, ' '));
}
}
row[c.name] = val;
});
// Row meta — mirrors the headed path (group/parent/tree/level/selected)
const imgBox = line.querySelector('.gridBoxImg');
if (imgBox) {
if (imgBox.querySelector('.gridListH')) row._kind = 'group';
else if (imgBox.querySelector('.gridListV')) row._kind = 'parent';
}
const treeBox = line.querySelector('.gridBoxTree');
if (treeBox) {
const treeIcon = imgBox?.querySelector('[tree="true"]');
if (treeIcon) { const bg = treeIcon.style.backgroundImage || ''; row._tree = bg.includes('gx=0') ? 'expanded' : 'collapsed'; }
row._level = imgBox ? imgBox.querySelectorAll('.dIB').length - 1 : 0;
}
if (line.classList.contains('selRow') || line.classList.contains('select')) row._selected = true;
rows.push(row);
}
// hasMore — mirrors the headed path
let hasMore;
const turnsBox = document.getElementById('vertButtonScroll_' + grid.id);
if (turnsBox && turnsBox.offsetHeight > 0) {
const upBtns = turnsBox.querySelectorAll('[data-home], [data-up]');
const dnBtns = turnsBox.querySelectorAll('[data-down], [data-end]');
hasMore = { above: [...upBtns].some(b => !b.classList.contains('disabled')),
below: [...dnBtns].some(b => !b.classList.contains('disabled')) };
} else {
const vs = document.getElementById('vertScroll_' + grid.id);
if (vs && vs.classList.contains('scrollV') && vs.offsetWidth > 0) {
const back = vs.querySelector('[data-track-back]')?.offsetHeight ?? 0;
const next = vs.querySelector('[data-track-next]')?.offsetHeight ?? 0;
hasMore = { above: back > 0, below: next > 0 };
} else {
hasMore = { below: body.scrollHeight > body.clientHeight };
}
}
const isTree = !!body.querySelector('.gridBoxTree');
const hasGroups = rows.some(r => r._kind === 'group');
const result = { name, columns: colNames, rows, total, offset: ${offset}, shown: rows.length, hasMore };
if (isTree) result.viewMode = 'tree';
if (hasGroups) result.hierarchical = true;
return result;
}
// Extract column headers with X-coordinates for alignment
const columns = [];
const headLine = head.querySelector('.gridLine') || head;
[...headLine.children].forEach(box => {
if (box.offsetWidth === 0) return;
const textEl = box.querySelector('.gridBoxText');
const text = (textEl || box).innerText?.trim().replace(/\\n/g, ' ') || '';
if (!text) {
// Unnamed column — check if data cells contain checkboxes or pictures.
// Picture columns have no header text (only an icon + a title tooltip); 1С
// doesn't expose the technical column name in the DOM, so we name them by
// the header's title attribute, falling back to '(picture)'.
const firstLine = body?.querySelector('.gridLine');
const visibleHeaders = [...headLine.children].filter(c => c.offsetWidth > 0);
const idx = visibleHeaders.indexOf(box);
const cells = firstLine ? [...firstLine.children].filter(c => c.offsetWidth > 0) : [];
const r = box.getBoundingClientRect();
if (cells[idx]?.querySelector('.checkbox')) {
columns.push({ text: '(checkbox)', x: r.x, w: r.width, right: r.x + r.width, y: r.y, h: r.height });
} else if (picInfo(box) || picInfo(cells[idx])) {
let title = (box.getAttribute('title') || '').trim() || '(picture)';
// Disambiguate duplicate picture-column names with a numeric suffix.
if (columns.some(c => c.text === title)) {
let n = 2;
while (columns.some(c => c.text === title + ' ' + n)) n++;
title = title + ' ' + n;
}
columns.push({ text: title, x: r.x, w: r.width, right: r.x + r.width, y: r.y, h: r.height });
}
return;
}
const r = box.getBoundingClientRect();
columns.push({ text, x: r.x, w: r.width, right: r.x + r.width, y: r.y, h: r.height });
});
// Multi-row grid support: detect stacked/merged headers.
// Group headers by X-range. For each group, count data sub-rows from first line.
// - Stacked headers (2+ headers at same X) with multiple data rows → match by Y-order
// - Single merged header with multiple data rows → expand to numbered columns (e.g. "Субконто Дт 1")
const xGroups = new Map();
columns.forEach(c => {
const key = Math.round(c.x) + ':' + Math.round(c.right);
if (!xGroups.has(key)) xGroups.set(key, []);
xGroups.get(key).push(c);
});
for (const [, hdrs] of xGroups) hdrs.sort((a, b) => a.y - b.y);
const firstDataLine = body?.querySelector('.gridLine');
const subRowMap = new Map();
if (firstDataLine) {
[...firstDataLine.children].forEach(box => {
if (box.offsetWidth === 0) return;
const r = box.getBoundingClientRect();
const cx = r.x + r.width / 2;
for (const [key, hdrs] of xGroups) {
const h0 = hdrs[0];
if (cx >= h0.x && cx < h0.right) {
if (!subRowMap.has(key)) subRowMap.set(key, []);
subRowMap.get(key).push({ y: r.y });
break;
}
}
});
for (const [, subs] of subRowMap) subs.sort((a, b) => a.y - b.y);
}
const multiRowGroups = new Map();
for (const [key, hdrs] of xGroups) {
const subs = subRowMap.get(key);
if (!subs || subs.length <= 1) continue;
if (hdrs.length >= 2) {
multiRowGroups.set(key, hdrs);
} else if (hdrs.length === 1 && subs.length > 1) {
const base = hdrs[0];
const baseIdx = columns.indexOf(base);
columns.splice(baseIdx, 1);
const expanded = [];
for (let si = 0; si < subs.length; si++) {
const numbered = {
text: base.text + ' ' + (si + 1),
x: base.x, w: base.w, right: base.right,
y: base.y + si, h: base.h / subs.length, _subIdx: si
};
columns.splice(baseIdx + si, 0, numbered);
expanded.push(numbered);
}
multiRowGroups.set(key, expanded);
}
}
function matchColumn(cellX, cellW, cellY) {
const cx = cellX + cellW / 2;
for (const [key, hdrs] of multiRowGroups) {
const h0 = hdrs[0];
if (cx >= h0.x && cx < h0.right) {
const subs = subRowMap.get(key);
if (subs) {
const subIdx = subs.findIndex(s => Math.abs(s.y - cellY) < 5);
if (subIdx >= 0 && subIdx < hdrs.length) return hdrs[subIdx];
}
let best = hdrs[0], bestDist = Infinity;
for (const h of hdrs) {
const dist = Math.abs(cellY - h.y);
if (dist < bestDist) { bestDist = dist; best = h; }
}
return best;
}
}
return columns.find(c => cx >= c.x && cx < c.right);
}
// Extract data rows from gridBody
const allLines = body.querySelectorAll('.gridLine');
const total = allLines.length;
const rows = [];
const end = Math.min(${offset} + ${maxRows}, total);
for (let i = ${offset}; i < end; i++) {
const line = allLines[i];
if (!line) break;
const row = {};
columns.forEach(c => { row[c.text] = ''; });
[...line.children].forEach(box => {
if (box.offsetWidth === 0) return;
const textEl = box.querySelector('.gridBoxText');
const chk = box.querySelector('.checkbox');
let val;
if (chk) {
val = chk.classList.contains('select') ? 'true' : 'false';
} else {
val = (textEl || box).innerText?.trim().replace(/\\n/g, ' ') || '';
if (!val) {
// Empty text → maybe a picture cell. 'pic:<gx>' encodes the sprite frame
// (state). Absent picture stays '' (truthy check distinguishes presence).
const pic = picInfo(box);
if (pic) val = 'pic:' + pic.gx;
else return;
}
}
// Match cell to column by X+Y overlap (multi-row aware)
const r = box.getBoundingClientRect();
const col = matchColumn(r.x, r.width, r.y);
if (col) {
row[col.text] = row[col.text] ? row[col.text] + ' / ' + val : val;
}
});
// Detect row kind: group (gridListH), parent/up (gridListV), or element
const imgBox = line.querySelector('.gridBoxImg');
if (imgBox) {
if (imgBox.querySelector('.gridListH')) row._kind = 'group';
else if (imgBox.querySelector('.gridListV')) row._kind = 'parent';
}
// Tree mode: detect expand/collapse state and indent level
const treeBox = line.querySelector('.gridBoxTree');
if (treeBox) {
const treeIcon = imgBox?.querySelector('[tree="true"]');
if (treeIcon) {
const bg = treeIcon.style.backgroundImage || '';
row._tree = bg.includes('gx=0') ? 'expanded' : 'collapsed';
}
row._level = imgBox ? imgBox.querySelectorAll('.dIB').length - 1 : 0;
}
// Selection state: selRow = selected row in grid
if (line.classList.contains('selRow') || line.classList.contains('select')) row._selected = true;
rows.push(row);
}
const isTree = !!body.querySelector('.gridBoxTree');
const hasGroups = rows.some(r => r._kind === 'group');
// Virtualization-aware hasMore signal. Three sources in priority order:
// 1. Dynamic-list turn buttons (#vertButtonScroll_<gridId>, sibling of grid).
// Buttons carry data-home/data-up (above) and data-down/data-end (below);
// class "disabled" on a direction means nothing to show there.
// 2. Tabular-section scrollbar (#vertScroll_<gridId>, class scrollV) —
// track-back/track-next pixel heights tell us above/below precisely.
// 3. Fallback: scrollHeight>clientHeight for "below"; "above" unknown.
let hasMore;
const turnsBox = document.getElementById('vertButtonScroll_' + grid.id);
if (turnsBox && turnsBox.offsetHeight > 0) {
const upBtns = turnsBox.querySelectorAll('[data-home], [data-up]');
const dnBtns = turnsBox.querySelectorAll('[data-down], [data-end]');
hasMore = {
above: [...upBtns].some(b => !b.classList.contains('disabled')),
below: [...dnBtns].some(b => !b.classList.contains('disabled')),
};
} else {
const vsId = 'vertScroll_' + grid.id;
const vs = document.getElementById(vsId);
if (vs && vs.classList.contains('scrollV') && vs.offsetWidth > 0) {
const back = vs.querySelector('[data-track-back]')?.offsetHeight ?? 0;
const next = vs.querySelector('[data-track-next]')?.offsetHeight ?? 0;
hasMore = { above: back > 0, below: next > 0 };
} else {
hasMore = { below: body.scrollHeight > body.clientHeight };
}
}
const result = { name, columns: columns.map(c => c.text), rows, total, offset: ${offset}, shown: rows.length, hasMore };
if (isTree) result.viewMode = 'tree';
if (hasGroups) result.hierarchical = true;
return result;
})()`;
}
// ─── Edit-time grid helpers (for fillTableRow / row-fill) ────────────────────
//
// All helpers below accept an optional `gridSelector`. When passed, they target
// that exact grid; when null/undefined they pick the LAST visible `.grid` on
// the page (this matches the implicit "current grid" used by row-fill).
/** Inline JS fragment that resolves the target grid into `const grid`. */
function gridResolver(gridSelector) {
return gridSelector
? `document.querySelector(${JSON.stringify(gridSelector)})`
: `(() => { const grids = [...document.querySelectorAll('.grid')].filter(el => el.offsetWidth > 0); return grids[grids.length - 1]; })()`;
}
/**
* Find center coords of a target row for click-select (used by deleteTableRow).
* Picks the second visible gridBox container in the row (skips row-number/checkbox col).
*
* Returns `{ x, y, total } | { error: 'no_grid'|'no_grid_body'|'row_out_of_range'|'no_cell', total? }`.
*/
export function findDeleteRowCoordsScript(gridSelector, row) {
return `(() => {
const grid = ${gridResolver(gridSelector)};
if (!grid) return { error: 'no_grid' };
const body = grid.querySelector('.gridBody');
if (!body) return { error: 'no_grid_body' };
const rows = [...body.querySelectorAll('.gridLine')];
if (${row} >= rows.length) return { error: 'row_out_of_range', total: rows.length };
const line = rows[${row}];
// Use visible gridBox containers (not gridBoxText) to avoid clicking checkboxes
const boxes = [...line.children].filter(b => b.offsetWidth > 0 && !b.classList.contains('gridBoxComp'));
// Skip first column (row number / checkbox) — pick second visible box
const box = boxes.length > 1 ? boxes[1] : boxes[0];
if (!box) return { error: 'no_cell' };
const cell = box.querySelector('.gridBoxText') || box;
const r = cell.getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2), total: rows.length };
})()`;
}
/**
* Count `.gridLine` rows in the body of the target grid.
* Returns the row count, or `0` when grid/body absent.
*/
export function countGridRowsScript(gridSelector) {
return `(() => {
const grid = ${gridResolver(gridSelector)};
const body = grid?.querySelector('.gridBody');
return body ? body.querySelectorAll('.gridLine').length : 0;
})()`;
}
/**
* Is the target grid a tree grid? (presence of `.gridBoxTree`)
* Returns boolean.
*/
export function isTreeGridScript(gridSelector) {
return `(() => {
const grid = ${gridResolver(gridSelector)};
return grid ? !!grid.querySelector('.gridBoxTree') : false;
})()`;
}
/**
* Return center coords of the grid's `.gridHead` element.
* Used as a click target to commit a pending cell edit (clicking the header
* defocuses the input without selecting another row).
*
* Returns `{ x, y } | null`.
*/
export function findGridHeadCenterCoordsScript(gridSelector) {
return `(() => {
const grid = ${gridResolver(gridSelector)};
if (!grid) return null;
const head = grid.querySelector('.gridHead');
if (!head) {
// Headerless editable grid: no header to click for commit-defocus. Click the
// thin strip at the grid's very top edge (above the first row) so the active
// edit commits without landing on a .gridLine (which would re-enter edit).
const gr = grid.getBoundingClientRect();
return { x: Math.round(gr.x + gr.width / 2), y: Math.round(gr.y + 1) };
}
const r = head.getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) };
})()`;
}
/**
* Return the index of the currently selected row in the target grid, or
* fall back to the last row when nothing is selected.
*
* Returns row index, or `-1` when no rows.
*/
export function getSelectedOrLastRowIndexScript(gridSelector) {
return `(() => {
const grid = ${gridResolver(gridSelector)};
if (!grid) return -1;
const body = grid.querySelector('.gridBody');
if (!body) return -1;
const lines = [...body.querySelectorAll('.gridLine')];
const sel = lines.findIndex(l => l.classList.contains('selected'));
return sel >= 0 ? sel : lines.length - 1;
})()`;
}
/**
* Scan a selection-form grid for the row matching `search` and return a click
* point INSIDE that row's first visible text cell NOT the row-line centre.
* (A wide multi-column row's centre `x = r.x + r.width/2` lands beyond the form's
* horizontal viewport, on an overlay, so `mouse.click` misses the row Enter
* doesn't select form stays open. That was the `not_selectable` bug.)
*
* `search` is either:
* - a string matched per-cell (case/ё/NBSP-insensitive), preferring
* exact-cell startsWith includes (so "Кабель" wins over "Кабель ВВГ");
* - an object `{ column: value, ... }` each key fuzzy-resolved to a header
* column, a row matches when EVERY column's cell includes its value (AND),
* preferring rows where every column's cell equals its value exactly.
* Empty `search` first row (fallback).
*
* Returns:
* `{ rowCount, x, y, isGroup, matchKind, visibleSample }` when found,
* `{ rowCount, visibleSample, error? }` when rows present but unmatched,
* `{ rowCount: 0 }` for an empty grid, or `null` when no grid.
* `visibleSample` = first-cell text of visible rows, for actionable error messages.
*/
export function scanGridRowsScript(formNum, search) {
return `(() => {
${ROW_CLICK_POINT_FN}
${HEADERLESS_GRID_FN}
const p = 'form${formNum}_';
const grid = document.querySelector('[id^="' + p + '"].grid, [id^="' + p + '"] .grid');
if (!grid) return null;
const body = grid.querySelector('.gridBody');
if (!body) return null;
const lines = [...body.querySelectorAll('.gridLine')];
if (!lines.length) return { rowCount: 0 };
const search = ${JSON.stringify(search ?? '')};
const isObj = search && typeof search === 'object';
const norm = s => (s || '').replace(/\\u00a0/g, ' ').replace(/\\s+/g, ' ').trim().toLowerCase().replace(/ё/gi, 'е');
const disp = s => (s || '').replace(/\\u00a0/g, ' ').replace(/\\s+/g, ' ').trim();
const cellText = b => (b.querySelector('.gridBoxText') ? b.querySelector('.gridBoxText').innerText : b.innerText) || '';
const visCells = line => [...line.children].filter(b => b.offsetWidth > 0);
const visibleSample = lines.slice(0, 10)
.map(l => disp(l.querySelector('.gridBoxText') ? l.querySelector('.gridBoxText').innerText : ''))
.filter(Boolean);
let sel = null, matchKind = null;
if (!search || (isObj && !Object.keys(search).length)) {
sel = lines[0]; matchKind = 'first';
} else if (isObj) {
// Resolve each key to a header column (fuzzy, normalised) — mirror resolveCol.
const headLine = grid.querySelector('.gridHead .gridLine') || grid.querySelector('.gridHead');
let headers;
if (headLine) {
headers = [...headLine.children]
.filter(c => c.offsetWidth > 0)
.map(c => {
const t = (c.querySelector('.gridBoxText') || c).innerText || '';
const title = c.getAttribute('title') || '';
const r = c.getBoundingClientRect();
return { name: disp(t) || disp(title), text: t, title, x: r.x, right: r.x + r.width };
})
.filter(h => h.name);
} else {
// Headerless: synthesized columns anchored by colindex.
headers = synthHeaderlessColumns(grid).map(c => ({ name: c.name, text: c.name, title: '', x: 0, right: 0, colindex: c.colindex }));
}
const resolveCol = name => {
const n = norm(name);
const cand = h => [h.text, h.title].filter(Boolean);
return headers.find(h => cand(h).some(t => norm(t) === n))
|| headers.find(h => cand(h).some(t => norm(t).includes(n)));
};
const cellAtCol = (line, col) => {
if (col.colindex != null) return visCells(line).find(b => b.getAttribute('colindex') === col.colindex);
return visCells(line).find(b => {
const r = b.getBoundingClientRect();
const cx = r.x + r.width / 2;
return cx >= col.x && cx < col.right;
});
};
const keys = Object.keys(search);
const cols = {};
for (const k of keys) {
const c = resolveCol(k);
if (!c) return { rowCount: lines.length, error: 'filter_column_not_found', column: k, visibleSample };
cols[k] = c;
}
let bestRank = 0;
for (const line of lines) {
let allIncludes = true, allExact = true;
for (const k of keys) {
const v = norm(search[k]);
if (!v) continue;
const cell = cellAtCol(line, cols[k]);
const t = norm(cell ? cellText(cell) : '');
if (!t.includes(v)) { allIncludes = false; break; }
if (t !== v) allExact = false;
}
if (!allIncludes) continue;
const rank = allExact ? 2 : 1;
if (rank > bestRank) { bestRank = rank; sel = line; matchKind = allExact ? 'object-exact' : 'object'; if (rank === 2) break; }
}
} else {
// String: per-cell, prefer exact-cell → startsWith → includes.
const v = norm(search);
let bestRank = 0;
for (const line of lines) {
let rowRank = 0;
for (const b of visCells(line)) {
const t = norm(cellText(b));
if (!t) continue;
let r = 0;
if (t === v) r = 3; else if (t.startsWith(v)) r = 2; else if (t.includes(v)) r = 1;
if (r > rowRank) rowRank = r;
}
if (rowRank > bestRank) { bestRank = rowRank; sel = line; matchKind = rowRank === 3 ? 'exact' : rowRank === 2 ? 'startsWith' : 'includes'; if (rowRank === 3) break; }
}
}
if (!sel) return { rowCount: lines.length, visibleSample };
// Click point: first visible text cell of the row (skip checkboxes; on tree grids
// skip the expand-toggle column; clamp X near the left). Shared with the
// clickElement row-select path — see ROW_CLICK_POINT_FN.
const pt = rowClickPoint(sel, body);
if (!pt) return { rowCount: lines.length, visibleSample };
const imgBox = sel.querySelector('.gridBoxImg');
const isGroup = imgBox ? !!imgBox.querySelector('.gridListH') : false;
return {
rowCount: lines.length,
x: pt.x,
y: pt.y,
isGroup, matchKind, visibleSample
};
})()`;
}
// ─── Cell-click DOM scripts (for clickElement({row, column}) on grids) ───────
/**
* Resolve a target cell in a grid by (row, column).
* - `column` matched: exact (case+ё-insensitive) endsWith ' / X' includes.
* - `row`: number = index in current DOM window; object = {col: value, ...} filter
* (matches first non-group/parent row where every column condition passes).
*
* Returns `{ x, y, cellX, cellRight, gridX, gridRight, columnText, rowIdx, cellText, visible } | { error, ... }`.
*
* Visibility (`visible`) is true when the cell is fully within the grid's horizontal viewport.
* Callers should horizontally scroll first if `visible === false`.
*/
export function findGridCellScript(formNum, gridSelector, { row, column }) {
const p = `form${formNum}_`;
return `(() => {
const norm = s => (s || '').replace(/\\u00a0/g, ' ').replace(/ё/gi, 'е').trim();
const lo = s => norm(s).toLowerCase();
const p = ${JSON.stringify(p)};
const grid = ${gridSelector
? `document.querySelector(${JSON.stringify(gridSelector)})`
: `[...document.querySelectorAll('[id^="' + p + '"].grid, [id^="' + p + '"] .grid')]
.find(g => g.offsetWidth > 0 && g.offsetHeight > 0)`};
if (!grid) return { error: 'no_grid' };
const head = grid.querySelector('.gridHead');
const body = grid.querySelector('.gridBody');
if (!body) return { error: 'no_grid_structure' };
${HEADERLESS_GRID_FN}
const isHeadless = !head;
// Header X-ranges (mirror of readTableScript logic, simplified). We also
// remember whether each header is frozen (gridBoxFix) — frozen and scrollable
// columns can share X coordinates after horizontal scroll, so cell matching
// must respect the frozen/scrollable partition.
let headers;
if (head) {
const headLine = head.querySelector('.gridLine') || head;
headers = [...headLine.children]
.filter(c => c.offsetWidth > 0)
.map(c => {
const textEl = c.querySelector('.gridBoxText');
const text = (textEl || c).innerText?.trim().replace(/\\n/g, ' ') || '';
// Picture/icon columns have no header text — fall back to the title tooltip
// (mirrors readTable naming) so they can still be targeted for clicking.
const title = (c.getAttribute('title') || '').trim();
const r = c.getBoundingClientRect();
return { text, title, name: text || title, x: r.x, right: r.x + r.width, fixed: c.classList.contains('gridBoxFix') };
})
.filter(h => h.name);
} else {
// Headerless: synthesized columns anchored by colindex (cellAtColX matches by colindex).
headers = synthHeaderlessColumns(grid).map(c => ({ text: c.name, title: '', name: c.name, x: 0, right: 0, fixed: false, colindex: c.colindex, subTarget: c.subTarget }));
}
const resolveCol = (name) => {
const suffix = ' / ' + name;
const cand = h => [h.text, h.title].filter(Boolean);
return headers.find(h => cand(h).some(t => lo(t) === lo(name)))
|| headers.find(h => cand(h).some(t => t.endsWith(suffix)))
|| headers.find(h => cand(h).some(t => lo(t).includes(lo(name))));
};
const targetCol = ${JSON.stringify(column)};
const col = resolveCol(targetCol);
if (!col) return { error: 'column_not_found', column: targetCol, available: headers.map(h => h.name) };
const lines = [...body.querySelectorAll('.gridLine')];
if (lines.length === 0) return { error: 'empty_grid' };
// Match cell to column by X overlap, but only among cells with the same
// fixed/scrollable kind as the header. After horizontal scroll a scrollable
// cell may have the same x as a frozen one — without this guard cellAtColX
// would silently return the frozen cell for a scrollable header.
const cellAtColX = (line, c) => {
// Headerless columns carry colindex → match the body cell directly (robust,
// and returns the same box for both logical columns of a combined mark-box).
if (c.colindex != null) {
return [...line.children].find(b => b.offsetWidth > 0 && b.getAttribute('colindex') === c.colindex);
}
return [...line.children]
.filter(b => b.offsetWidth > 0 && b.classList.contains('gridBoxFix') === c.fixed)
.find(b => {
const r = b.getBoundingClientRect();
const cx = r.x + r.width / 2;
return cx >= c.x && cx < c.right;
});
};
const cellText = (b) => norm(b?.querySelector('.gridBoxText')?.innerText || b?.innerText || '');
const target = ${JSON.stringify(row)};
let line, rowIdx;
if (typeof target === 'number') {
if (target < 0 || target >= lines.length) {
return { error: 'row_out_of_range', row: target, loaded: lines.length };
}
line = lines[target];
rowIdx = target;
} else if (target && typeof target === 'object') {
const entries = Object.entries(target);
const colsByKey = {};
for (const [k] of entries) {
const c = resolveCol(k);
if (!c) return { error: 'filter_column_not_found', column: k, available: headers.map(h => h.name) };
colsByKey[k] = c;
}
const matches = (ln) => {
for (const [k, v] of entries) {
const c = colsByKey[k];
const cell = cellAtColX(ln, c);
const txt = cellText(cell);
const wanted = lo(v);
if (!txt) return false;
const t = txt.toLowerCase();
if (!(t === wanted || t.includes(wanted))) return false;
}
return true;
};
rowIdx = lines.findIndex(matches);
if (rowIdx < 0) return { error: 'row_not_found', filter: target };
line = lines[rowIdx];
} else {
return { error: 'invalid_row_type' };
}
const cell = cellAtColX(line, col);
if (!cell) return { error: 'cell_not_in_dom', column: col.name, rowIdx };
// Headerless: click coords target the subTarget node (checkbox image / title),
// no frozen/scroll partition in these narrow grids → trivially visible.
if (isHeadless) {
let node = cell;
if (col.subTarget === 'checkbox') node = cell.querySelector('.checkbox') || cell;
else if (col.subTarget === 'title') node = cell.querySelector('.gridBoxTitle') || cell;
else if (col.subTarget === 'text') node = cell.querySelector('.gridBoxText') || cell;
const rr = node.getBoundingClientRect();
const gb = grid.getBoundingClientRect();
return { x: Math.round(rr.x + rr.width / 2), y: Math.round(rr.y + rr.height / 2),
cellX: Math.round(rr.x), cellRight: Math.round(rr.x + rr.width),
gridX: Math.round(gb.x), gridRight: Math.round(gb.x + gb.width), scrollableLeft: Math.round(gb.x),
columnText: col.name, rowIdx, isFixed: false, cellText: cellText(cell), visible: true };
}
const r = cell.getBoundingClientRect();
const gridBox = grid.getBoundingClientRect();
// Frozen columns (.gridBoxFix) stay pinned at the left edge of the grid even
// when the rest scrolls horizontally. For non-frozen cells, "visible" means
// inside the SCROLLABLE viewport (right of any frozen columns). Frozen cells
// are always visible by definition.
const isFixed = cell.classList.contains('gridBoxFix');
let scrollableLeft = gridBox.x;
if (!isFixed) {
[...line.children].forEach(b => {
if (b.offsetWidth > 0 && b.classList.contains('gridBoxFix')) {
const br = b.getBoundingClientRect();
if (br.x + br.width > scrollableLeft) scrollableLeft = br.x + br.width;
}
});
}
// "Visible enough to click" — the cell's CENTER is inside the scrollable area
// and the cell's right edge is inside the grid. Strict left-edge check would
// reject cells that 1С rendered touching the frozen-column boundary (off by 1px).
const center = r.x + r.width / 2;
const visible = center >= scrollableLeft && center <= (gridBox.x + gridBox.width) && (r.x + r.width) <= (gridBox.x + gridBox.width);
return {
x: Math.round(r.x + r.width / 2),
y: Math.round(r.y + r.height / 2),
cellX: Math.round(r.x), cellRight: Math.round(r.x + r.width),
gridX: Math.round(gridBox.x), gridRight: Math.round(gridBox.x + gridBox.width),
scrollableLeft: Math.round(scrollableLeft),
columnText: col.name, rowIdx, isFixed,
cellText: cellText(cell),
visible
};
})()`;
}
/**
* Pick coordinates for a focus-click on a safe cell within the grid.
*
* Used both for vertical reveal-loop focus and for horizontal-scroll edge focus.
* The caller passes a profile that selects which row, which cells to exclude,
* and (for horizontal scroll) which edge of the row to take.
*
* @param {string} gridSelector
* @param {object} opts
* @param {number} [opts.rowIdx] - Pick from this row; falls back to first non-group/parent data row.
* @param {'ArrowRight'|'ArrowLeft'} [opts.direction]
* - When set, restricts to non-frozen FULLY visible cells and picks the edge
* cell in that direction (rightmost for ArrowRight, leftmost for ArrowLeft).
* - When omitted, picks a generic safe cell (skips first column to avoid tree-toggles).
*
* Always prefers non-checkbox cells (center-click on a checkbox would toggle it).
*
* Returns `{ x, y } | null`.
*/
export function findFocusCellScript(gridSelector, { rowIdx, direction } = {}) {
return `(() => {
const grid = ${gridResolver(gridSelector)};
if (!grid) return null;
const body = grid.querySelector('.gridBody');
if (!body) return null;
const lines = [...body.querySelectorAll('.gridLine')];
if (!lines.length) return null;
const rowIdx = ${rowIdx == null ? 'null' : JSON.stringify(rowIdx)};
const direction = ${direction ? JSON.stringify(direction) : 'null'};
const line = (rowIdx != null && lines[rowIdx])
|| lines.find(ln => {
const imgBox = ln.querySelector('.gridBoxImg');
return !imgBox?.querySelector('.gridListH, .gridListV');
})
|| lines[0];
if (!line) return null;
let candidates;
if (direction) {
// Horizontal-scroll mode: edge cell in the scrollable area, exclude frozen.
const gridBox = grid.getBoundingClientRect();
let scrollableLeft = gridBox.x;
[...line.children].forEach(b => {
if (b.offsetWidth > 0 && b.classList.contains('gridBoxFix')) {
const br = b.getBoundingClientRect();
if (br.x + br.width > scrollableLeft) scrollableLeft = br.x + br.width;
}
});
const visible = [...line.children]
.filter(b => b.offsetWidth > 0 && !b.classList.contains('gridBoxFix'))
.map(b => ({ b, r: b.getBoundingClientRect(), checkbox: !!b.querySelector('.checkbox') }))
.filter(({ r }) => r.x >= scrollableLeft && (r.x + r.width) <= (gridBox.x + gridBox.width));
if (!visible.length) return null;
visible.sort((a, b) => a.r.x - b.r.x);
candidates = direction === 'ArrowRight' ? [...visible].reverse() : visible;
} else {
// Generic focus mode (used by reveal-loop): pick the FIRST visible cell —
// typically a Reference column (Номенклатура in документах) which doesn't
// auto-enter edit mode on click. Number/Date/String cells auto-edit and
// break subsequent PageDown navigation.
// For tree grids (presence of .gridBoxTree), skip first column to avoid
// toggling expand/collapse of the row.
const isTree = !!body.querySelector('.gridBoxTree');
const cells = [...line.children]
.filter(b => b.offsetWidth > 0)
.map(b => ({ b, r: b.getBoundingClientRect(), checkbox: !!b.querySelector('.checkbox') }));
if (!cells.length) return null;
candidates = isTree && cells.length > 1 ? cells.slice(1) : cells;
}
const pick = candidates.find(v => !v.checkbox) || candidates[0];
if (!pick) return null;
return { x: Math.round(pick.r.x + pick.r.width / 2), y: Math.round(pick.r.y + pick.r.height / 2) };
})()`;
}
/**
* Snapshot grid state for reveal-loop end detection.
* Returns `{ firstText, lastText, lineCount, selIdx, hasBelow }`.
*
* `firstText`/`lastText` use the first cell's `.gridBoxText` content.
* `hasBelow` is derived from scrollbar widget tracks when visible, else from scrollHeight>clientHeight.
*/
export function snapshotGridScript(gridSelector) {
return `(() => {
const grid = ${gridResolver(gridSelector)};
if (!grid) return null;
const body = grid.querySelector('.gridBody');
if (!body) return null;
const lines = body.querySelectorAll('.gridLine');
// Full-row signature: join EVERY cell's text, not just the first column.
// A low-cardinality first column (e.g. all "Товар 0X") would otherwise make
// two different windows look identical and abort the reveal-loop early.
const txt = ln => ln ? [...ln.querySelectorAll('.gridBoxText')].map(b => (b.innerText || '').trim()).join('|') : '';
const selIdx = [...lines].findIndex(l => l.classList.contains('selRow') || l.classList.contains('select'));
// hasBelow priority: (1) dynamic-list turn buttons, (2) tabular scrollbar tracks, (3) scrollHeight.
let hasBelow;
const turnsBox = document.getElementById('vertButtonScroll_' + grid.id);
if (turnsBox && turnsBox.offsetHeight > 0) {
const dnBtns = turnsBox.querySelectorAll('[data-down], [data-end]');
hasBelow = [...dnBtns].some(b => !b.classList.contains('disabled'));
} else {
const vs = document.getElementById('vertScroll_' + grid.id);
if (vs && vs.classList.contains('scrollV') && vs.offsetWidth > 0) {
hasBelow = (vs.querySelector('[data-track-next]')?.offsetHeight ?? 0) > 0;
} else {
hasBelow = body.scrollHeight > body.clientHeight;
}
}
return {
firstText: txt(lines[0]),
lastText: txt(lines[lines.length - 1]),
lineCount: lines.length,
selIdx,
hasBelow
};
})()`;
}
/**
* Resolve the click target kind for `clickElement({row, column})`.
*
* Routing:
* - `tableName` specified: try to match a visible grid by name (exact contains).
* If matched grid. Else if form has a spreadsheet iframe spreadsheet. Else error.
* - `tableName` omitted: spreadsheet iframe present spreadsheet (backward-compat).
* Else first visible grid. Else error.
*
* Returns `{ kind: 'spreadsheet' } | { kind: 'grid', gridSelector, gridName } | { error, ... }`.
*/
export function resolveCellTargetScript(formNum, tableName) {
const p = `form${formNum}_`;
return `(() => {
const p = ${JSON.stringify(p)};
const tableName = ${JSON.stringify(tableName || '')};
// Spreadsheet = iframe under form prefix with non-trivial width.
const hasSpreadsheet = [...document.querySelectorAll('iframe')].some(f => {
if (f.offsetWidth < 100) return false;
let el = f.parentElement;
for (let d = 0; el && d < 30; d++, el = el.parentElement) {
if (el.id && el.id.startsWith(p)) return true;
}
return false;
});
const grids = [...document.querySelectorAll('[id^="' + p + '"].grid, [id^="' + p + '"] .grid')]
.filter(g => g.offsetWidth > 0 && g.offsetHeight > 0);
const norm = s => (s || '').replace(/ё/gi, 'е').toLowerCase();
if (tableName) {
const target = norm(tableName);
const matched = grids.find(g => norm(g.id.replace(p, '')) === target)
|| grids.find(g => norm(g.id.replace(p, '')).includes(target));
if (matched) {
return { kind: 'grid', gridSelector: '#' + CSS.escape(matched.id), gridName: matched.id.replace(p, '') };
}
if (hasSpreadsheet) return { kind: 'spreadsheet' };
return { error: 'table_not_found', table: tableName, availableGrids: grids.map(g => g.id.replace(p, '')) };
}
if (hasSpreadsheet) return { kind: 'spreadsheet' };
if (grids.length > 0) {
const g = grids[0];
return { kind: 'grid', gridSelector: '#' + CSS.escape(g.id), gridName: g.id.replace(p, '') };
}
return { error: 'no_spreadsheet_or_grid' };
})()`;
}
@@ -1,93 +0,0 @@
// web-test dom/nav v1.0 — sections panel, tabs bar, function panel commands
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
/** Read sections panel (left sidebar). */
export function readSectionsScript() {
return `(() => {
const sections = [];
document.querySelectorAll('[id^="themesCell_theme_"]').forEach(el => {
const entry = { name: el.innerText?.trim() || '' };
if (el.classList.contains('select')) entry.active = true;
sections.push(entry);
});
return sections;
})()`;
}
/** Read open tabs bar. */
export function readTabsScript() {
return `(() => {
const norm = s => (s?.trim().replace(/\\u00a0/g, ' ') || '').replace(/ё/gi, 'е');
const tabs = [];
document.querySelectorAll('[id^="openedCell_cmd_"]').forEach(el => {
const text = norm(el.innerText);
if (!text) return;
const entry = { name: text };
if (el.classList.contains('select')) entry.active = true;
tabs.push(entry);
});
return tabs;
})()`;
}
/** Switch to a tab by name (fuzzy match). Returns matched name or { error, available }. */
export function switchTabScript(name) {
return `(() => {
const norm = s => (s?.trim().replace(/\\u00a0/g, ' ') || '').replace(/ё/gi, 'е');
const target = ${JSON.stringify(name.toLowerCase().replace(/ё/g, 'е'))};
const tabs = [...document.querySelectorAll('[id^="openedCell_cmd_"]')].filter(el => el.offsetWidth > 0 && norm(el.innerText));
let best = tabs.find(el => norm(el.innerText).toLowerCase() === target);
if (!best) best = tabs.find(el => norm(el.innerText).toLowerCase().includes(target));
if (best) { best.click(); return norm(best.innerText); }
return { error: 'not_found', available: tabs.map(el => norm(el.innerText)) };
})()`;
}
/** Read commands in the function panel (current section). */
export function readCommandsScript() {
return `(() => {
const groups = [];
const container = document.querySelector('#funcPanel_container table tr');
if (!container) return groups;
for (const td of container.children) {
const commands = [];
td.querySelectorAll('[id^="cmd_"][id$="_txt"]').forEach(el => {
if (el.offsetWidth === 0) return;
commands.push(el.innerText?.trim() || '');
});
if (commands.length > 0) groups.push(commands);
}
return groups;
})()`;
}
/**
* Navigate to a section by name (fuzzy match).
* Returns the matched section name, or { error, available }.
*/
export function navigateSectionScript(name) {
return `(() => {
const norm = s => (s?.trim().replace(/\\u00a0/g, ' ').replace(/[\\r\\n]+/g, ' ').replace(/ +/g, ' ') || '').replace(/ё/gi, 'е');
const target = ${JSON.stringify(name.toLowerCase().replace(/ё/g, 'е').replace(/[\r\n]+/g, ' ').replace(/ +/g, ' '))};
const els = [...document.querySelectorAll('[id^="themesCell_theme_"]')];
let bestEl = els.find(el => norm(el.innerText).toLowerCase() === target);
if (!bestEl) bestEl = els.find(el => norm(el.innerText).toLowerCase().includes(target));
if (bestEl) { bestEl.click(); return norm(bestEl.innerText); }
return { error: 'not_found', available: els.map(el => norm(el.innerText)).filter(Boolean) };
})()`;
}
/**
* Open a command from function panel by name (fuzzy match).
*/
export function openCommandScript(name) {
return `(() => {
const norm = s => (s?.trim().replace(/\\u00a0/g, ' ') || '').replace(/ё/gi, 'е');
const target = ${JSON.stringify(name.toLowerCase().replace(/ё/g, 'е'))};
const els = [...document.querySelectorAll('[id^="cmd_"][id$="_txt"]')].filter(el => el.offsetWidth > 0);
let bestEl = els.find(el => norm(el.innerText).toLowerCase() === target);
if (!bestEl) bestEl = els.find(el => norm(el.innerText).toLowerCase().includes(target));
if (bestEl) { bestEl.click(); return norm(bestEl.innerText); }
return { error: 'not_found', available: els.map(el => norm(el.innerText)).filter(Boolean) };
})()`;
}
@@ -1,178 +0,0 @@
// web-test dom/submenu v1.1 — popup/submenu reading and clicking
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
/**
* Read open popup/submenu items.
* Looks for absolutely positioned visible popup containers with a.press items inside.
* Returns [{ id, name }] or { error }.
*/
export function readSubmenuScript() {
return `(() => {
const items = [];
const norm = s => (s?.trim().replace(/\\u00a0/g, ' ') || '').replace(/ё/gi, 'е');
// 1. DLB dropdown (#editDropDown with .eddText items)
const edd = document.getElementById('editDropDown');
if (edd && edd.offsetWidth > 0 && edd.offsetHeight > 0) {
edd.querySelectorAll('.eddText').forEach(el => {
if (el.offsetWidth === 0) return;
const text = norm(el.innerText);
if (!text) return;
const r = el.getBoundingClientRect();
items.push({ id: '', name: text, kind: 'dropdown',
x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) });
});
// Detect "Показать все" link in EDD footer
// Structure: div.eddBottom > div > span.hyperlink "Показать все"
let showAllEl = edd.querySelector('.eddBottom .hyperlink');
if (!showAllEl || showAllEl.offsetWidth === 0) {
// Fallback: scan all visible elements for text match
const candidates = [...edd.querySelectorAll('a.press, a, span, div')]
.filter(el => el.offsetWidth > 0 && el.children.length === 0);
showAllEl = candidates.find(el => {
const t = norm(el.innerText).toLowerCase();
return t === 'показать все' || t === 'show all';
});
}
if (showAllEl) {
const r = showAllEl.getBoundingClientRect();
items.push({ id: showAllEl.id || '', name: norm(showAllEl.innerText), kind: 'showAll',
x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) });
}
if (items.length > 0) return items;
}
// 2. Cloud submenu (allActions / command panel menus — div.cloud with .submenuText items)
// Read ALL visible high-z clouds (main menu + nested submenus)
const clouds = [...document.querySelectorAll('.cloud')].filter(c => c.offsetWidth > 0 && c.offsetHeight > 0);
const seen = new Set();
clouds.forEach(c => {
const z = parseInt(getComputedStyle(c).zIndex) || 0;
if (z <= 1000) return;
c.querySelectorAll('.submenuText').forEach(el => {
if (el.offsetWidth === 0) return;
const text = norm(el.innerText);
if (!text || seen.has(text)) return;
seen.add(text);
const block = el.closest('.submenuBlock');
if (block && block.classList.contains('submenuBlockDisabled')) return;
const hasSub = block && /_sub$/.test(block.id);
const r = el.getBoundingClientRect();
items.push({ id: block?.id || '', name: text, kind: hasSub ? 'submenuArrow' : 'submenu',
x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) });
});
});
if (items.length > 0) return items;
// 3. Submenu popups — find the topmost positioned container with non-form a.press items
const popups = [...document.querySelectorAll('div')].filter(c => {
const style = getComputedStyle(c);
return (style.position === 'absolute' || style.position === 'fixed')
&& c.offsetWidth > 0 && c.offsetHeight > 0;
}).sort((a, b) => {
const za = parseInt(getComputedStyle(a).zIndex) || 0;
const zb = parseInt(getComputedStyle(b).zIndex) || 0;
return zb - za;
});
for (const container of popups) {
// Only direct a.press children or those not nested in another positioned div
const menuItems = [...container.querySelectorAll('a.press')].filter(el => {
if (el.offsetWidth === 0) return false;
if (el.id && /^form\\d+_/.test(el.id)) return false;
// Skip if this a.press is inside a deeper positioned container
let parent = el.parentElement;
while (parent && parent !== container) {
const ps = getComputedStyle(parent).position;
if (ps === 'absolute' || ps === 'fixed') return false;
parent = parent.parentElement;
}
return true;
});
if (menuItems.length < 2) continue; // Not a real menu
const seen = new Set();
menuItems.forEach(el => {
const text = norm(el.innerText);
if (!text) return;
if (seen.has(text)) return;
seen.add(text);
const r = el.getBoundingClientRect();
items.push({ id: el.id || '', name: text, kind: 'submenu',
x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) });
});
if (items.length > 0) break; // Found the popup menu
}
if (items.length === 0) return { error: 'no_popup', message: 'No open popup/submenu found' };
return items;
})()`;
}
/**
* Click a popup/dropdown item by text match (evaluate-based for items without IDs).
* Returns true if clicked, false if not found.
*/
export function clickPopupItemScript(text) {
return `(() => {
const target = ${JSON.stringify(text.toLowerCase().replace(/ё/g, 'е'))};
// 1. DLB dropdown (#editDropDown .eddText items)
const edd = document.getElementById('editDropDown');
if (edd && edd.offsetWidth > 0) {
for (const el of edd.querySelectorAll('.eddText')) {
if (el.offsetWidth === 0) continue;
const t = el.innerText?.trim() || '';
if (t.toLowerCase() === target || t.toLowerCase().includes(target)) {
el.click();
return t;
}
}
}
// 2. Submenu popups (a.press in absolutely positioned containers)
const containers = [...document.querySelectorAll('div')].filter(c => {
const style = getComputedStyle(c);
return (style.position === 'absolute' || style.position === 'fixed')
&& c.offsetWidth > 0 && c.offsetHeight > 0;
});
for (const container of containers) {
const items = [...container.querySelectorAll('a.press')]
.filter(el => el.offsetWidth > 0);
for (const el of items) {
const t = el.innerText?.trim() || '';
if (t.toLowerCase() === target || t.toLowerCase().includes(target)) {
el.click();
return t;
}
}
}
return null;
})()`;
}
/**
* Read a platform "cloud dropdown" checkbox list (`.cloudDD`) the inline
* quick-choice multi-select dropdown (e.g. a catalog with QuickChoice opened via F4).
* NOT handled by readSubmenuScript (which reads `.eddText`/`.cloud`/popup `a.press`).
*
* Returns `[{ text, checked, x, y }]` `checked` from `.checkbox.select`, `x/y` =
* the checkbox center (click there to toggle). Toggle via page.mouse.click (a
* `.surface` backdrop swallows selector clicks); confirm by clicking OUTSIDE the panel.
* Returns `{ error: 'no_clouddd' }` when no visible `.cloudDD` panel.
*/
export function readCloudDDScript() {
return `(() => {
const norm = s => (s?.trim().replace(/\\u00a0/g, ' ') || '').replace(/\\s+/g, ' ').replace(/ё/gi, 'е');
const panel = [...document.querySelectorAll('.cloudDD')].find(p => p.offsetWidth > 0 && p.offsetHeight > 0);
if (!panel) return { error: 'no_clouddd' };
const items = [];
panel.querySelectorAll('.checkbox').forEach(chk => {
if (chk.offsetWidth === 0) return;
// The text label sits beside the checkbox — climb until a container has text.
let row = chk;
for (let k = 0; k < 4 && row.parentElement; k++) { row = row.parentElement; if ((row.innerText || '').trim()) break; }
const r = chk.getBoundingClientRect();
items.push({ text: norm(row.innerText || ''), checked: chk.classList.contains('select'),
x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) });
});
return items;
})()`;
}
@@ -1,129 +0,0 @@
// web-test core/click v1.22 — clickElement dispatcher: routes to spreadsheet / popup / grid-row / form-element / field-focus handlers by target kind.
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
import { page, ensureConnected, highlightMode } from './state.mjs';
import {
detectFormScript, findClickTargetScript, resolveGridScript,
readSubmenuScript, resolveCellTargetScript,
} from '../../dom.mjs';
import { dismissPendingErrors, checkForErrors } from './errors.mjs';
import { waitForStable } from './wait.mjs';
import { highlight, unhighlight } from '../recording/highlight.mjs';
import { modifierClick, returnFormState } from './helpers.mjs';
import {
clickGridGroupTarget, clickGridTreeNodeTarget, clickGridRowTarget,
} from '../table/click-row.mjs';
import { clickGridCell } from '../table/click-cell.mjs';
import {
clickConfirmationButton, tryClickPopupItem,
} from '../forms/click-popup.mjs';
import { clickFormTarget, focusFormField } from '../forms/click-form.mjs';
import {
clickSpreadsheetCell, findSpreadsheetCellByText,
} from '../spreadsheet/spreadsheet.mjs';
/** Click a button/hyperlink/tab on the current form. Use {dblclick: true} to double-click (open items from lists).
* First argument can also be an object { row, column } to click a cell in a SpreadsheetDocument (отчёт) or a form grid (таблица/табчасть). */
export async function clickElement(text, { dblclick, table, toggle, expand, modifier, scroll, timeout } = {}) {
ensureConnected();
// Dispatch to cell handler when first arg is { row, column }.
// Routing (see resolveCellTargetScript):
// - `table` named: matches grid → grid cell; falls back to spreadsheet if it's the spreadsheet's name.
// - no `table`: form has spreadsheet → spreadsheet cell (backward-compat);
// else first visible grid → grid cell.
if (typeof text === 'object' && text !== null && text.column != null) {
await dismissPendingErrors();
const formNum = await page.evaluate(detectFormScript());
if (formNum === null) throw new Error('clickElement: no form found');
const route = await page.evaluate(resolveCellTargetScript(formNum, table));
if (route.error === 'table_not_found') {
throw new Error(`clickElement: table "${table}" not found. Available grids: ${(route.availableGrids || []).join(', ') || 'none'}`);
}
if (route.error) {
throw new Error(`clickElement: no spreadsheet or grid on form to click cell in.`);
}
if (route.kind === 'spreadsheet') {
return clickSpreadsheetCell(text, { dblclick, modifier });
}
// route.kind === 'grid'
return clickGridCell(text, {
formNum,
gridSelector: route.gridSelector,
gridName: route.gridName,
modifier, dblclick, scroll,
});
}
await dismissPendingErrors();
if (highlightMode) {
try { await highlight(text, { table }); await page.waitForTimeout(500); await unhighlight(); } catch {}
}
try {
// 1. Intercept open confirmation dialog (Да/Нет/Отмена) — match button by text.
const pending = await checkForErrors();
if (pending?.confirmation) {
return await clickConfirmationButton(text);
}
// 2. Intercept open popup (from previous submenu/split-button click).
// Returns null if popup is open but `text` doesn't match — fall through.
const popupItems = await page.evaluate(readSubmenuScript());
if (Array.isArray(popupItems) && popupItems.length > 0) {
const popupResult = await tryClickPopupItem(text, popupItems);
if (popupResult) return popupResult;
}
// 3. Find a target on the current form.
let formNum = await page.evaluate(detectFormScript());
if (formNum === null) throw new Error(`clickElement: no form found`);
let gridSelector;
if (table) {
const resolved = await page.evaluate(resolveGridScript(formNum, table));
if (resolved.error) throw new Error(`clickElement: table "${table}" not found. Available: ${resolved.available?.map(a => a.name).join(', ') || 'none'}`);
gridSelector = resolved.gridSelector;
}
let target = await page.evaluate(findClickTargetScript(formNum, text, { tableName: table, gridSelector }));
// Retry: if not found, a modal form may still be loading (e.g. after F4).
if (target?.error) {
for (let retry = 0; retry < 4; retry++) {
await page.waitForTimeout(500);
const newForm = await page.evaluate(detectFormScript());
if (newForm !== null && newForm !== formNum) {
formNum = newForm;
target = await page.evaluate(findClickTargetScript(formNum, text, { tableName: table, gridSelector }));
if (!target?.error) break;
}
}
}
// Spreadsheet fallback: search iframes for text match before giving up.
if (target?.error) {
const ssCell = await findSpreadsheetCellByText(formNum, text);
if (ssCell) {
const cx = ssCell.box.x + ssCell.box.width / 2;
const cy = ssCell.box.y + ssCell.box.height / 2;
await modifierClick(cx, cy, modifier, { dbl: !!dblclick });
await waitForStable();
return returnFormState({
clicked: { kind: 'spreadsheetCell', name: ssCell.text, ...(dblclick ? { dblclick: true } : {}) },
});
}
throw new Error(`clickElement: "${text}" not found. Available: ${target.available?.join(', ') || 'none'}`);
}
// 4. Dispatch to the right handler by target kind.
const ctx = { formNum, modifier, dblclick, toggle, expand, timeout, table, gridSelector };
if (target.kind === 'gridGroup' || target.kind === 'gridParent') return await clickGridGroupTarget(target, ctx);
if (target.kind === 'gridTreeNode') return await clickGridTreeNodeTarget(target, ctx);
if (target.kind === 'gridRow') return await clickGridRowTarget(target, ctx);
if (target.kind === 'field') return await focusFormField(target, ctx);
return await clickFormTarget(target, ctx);
} finally {
if (highlightMode) try { await unhighlight(); } catch {}
}
}
@@ -1,97 +0,0 @@
// web-test engine/core/clipboard v1.17 — OS-clipboard preservation around trusted paste.
// Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
//
// pasteText() — the only path 1C respects for autocomplete and Cyrillic input.
// saveClipboard/restoreClipboard preserve full clipboard contents (all MIME
// types) around the writeText+Ctrl+V pair so a user's concurrent Ctrl+C isn't
// clobbered. Blobs are stashed on `window` to avoid CDP serialization.
import {
page, preserveClipboard, clipboardWarnLogged, setClipboardWarnLogged,
} from './state.mjs';
export async function saveClipboard() {
if (!page) return;
try {
await page.evaluate(async () => {
try {
const items = await navigator.clipboard.read();
const saved = [];
for (const item of items) {
const types = {};
for (const t of item.types) types[t] = await item.getType(t);
saved.push(types);
}
window.__webTestSavedClipboard = saved;
delete window.__webTestClipboardError;
} catch (e) {
window.__webTestSavedClipboard = null;
window.__webTestClipboardError = e?.name || String(e);
}
});
} catch {
// page.evaluate itself failed (closed page, navigation in flight) — skip.
}
}
export async function restoreClipboard() {
if (!page) return;
let err = null;
try {
err = await page.evaluate(async () => {
const saved = window.__webTestSavedClipboard;
const captured = window.__webTestClipboardError || null;
delete window.__webTestSavedClipboard;
delete window.__webTestClipboardError;
try {
if (!saved || saved.length === 0) {
// Save failed (e.g. CF_HDROP from Explorer not readable via Clipboard API)
// or buffer was empty. Either way, the test's writeText already destroyed
// any prior native formats in the OS clipboard, so explicitly clear here
// to avoid leaking the test value into the user's clipboard.
await navigator.clipboard.writeText('');
return captured;
}
const items = saved.map(types => new ClipboardItem(types));
await navigator.clipboard.write(items);
return null;
} catch (e) {
return e?.name || String(e);
}
});
} catch {
return;
}
if (err && !clipboardWarnLogged) {
setClipboardWarnLogged(true);
console.error(`[web-test] clipboard preserve skipped: ${err} (logged once per session)`);
}
}
/**
* Paste `text` via OS clipboard (the only trusted-paste path that 1C respects
* for autocomplete and Cyrillic). Wraps the writeText+confirm-key pair in a
* narrow save/restore so a user's clipboard survives the test run the window
* between save and restore is microseconds.
*
* - `confirm` key (string) or sequence (array) to press after writeText.
* Defaults to 'Control+V'. Use ['Control+a', 'Control+v'] for select-all-then-paste,
* or 'Shift+F11' for the goto-link dialog.
* - `postDelay` ms to wait between confirm-press and restore, for dialogs
* that read clipboard asynchronously (e.g. Shift+F11). Default 0.
*/
export async function pasteText(text, { confirm = 'Control+V', postDelay = 0 } = {}) {
if (!page) return;
if (preserveClipboard) await saveClipboard();
try {
await page.evaluate(`navigator.clipboard.writeText(${JSON.stringify(String(text))})`);
if (Array.isArray(confirm)) {
for (const key of confirm) await page.keyboard.press(key);
} else if (confirm) {
await page.keyboard.press(confirm);
}
if (postDelay) await page.waitForTimeout(postDelay);
} finally {
if (preserveClipboard) await restoreClipboard();
}
}

Some files were not shown because too many files have changed in this diff Show More