@kition/kit-layout-ui 0.0.0-stage → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/layout-ui/LICENSE +177 -0
  2. package/layout-ui/NOTICE +209 -0
  3. package/layout-ui/THIRD_PARTY_NOTICES.txt +12429 -0
  4. package/layout-ui/agent/checks.json +51 -0
  5. package/layout-ui/agent/guide.md +301 -0
  6. package/layout-ui/assets/dev-urAth9yG.js +1 -0
  7. package/layout-ui/assets/index-3JO7a523.js +52 -0
  8. package/layout-ui/assets/index-DblcoJ90.js +1 -0
  9. package/layout-ui/assets/index-_eI3PfdK.css +1 -0
  10. package/layout-ui/assets/kitEngine.worker-9PIHJagj-Dwbox6hp.js +13020 -0
  11. package/layout-ui/engine/kition_layout_kit.js +1147 -0
  12. package/layout-ui/engine/kition_layout_kit_bg.wasm +0 -0
  13. package/layout-ui/fonts/BricolageGrotesque-OFL.txt +93 -0
  14. package/layout-ui/fonts/BricolageGrotesque-Variable.ttf +0 -0
  15. package/layout-ui/fonts/DroidSansFallback-NOTICE.txt +190 -0
  16. package/layout-ui/fonts/DroidSansFallbackFull.ttf +0 -0
  17. package/layout-ui/fonts/Inter-OFL.txt +93 -0
  18. package/layout-ui/fonts/Inter-Variable.ttf +0 -0
  19. package/layout-ui/fonts/JetBrainsMono-OFL.txt +93 -0
  20. package/layout-ui/fonts/JetBrainsMono-Variable.ttf +0 -0
  21. package/layout-ui/fonts/Lora-OFL.txt +93 -0
  22. package/layout-ui/fonts/Lora-Variable.ttf +0 -0
  23. package/layout-ui/index.html +14 -0
  24. package/layout-ui/kit-ui.json +1 -0
  25. package/layout-ui/kit.json +173 -0
  26. package/layout-ui/model/schema.json +544 -0
  27. package/layout-ui/templates/editorial.klayout +0 -0
  28. package/layout-ui/templates/editorial.png +0 -0
  29. package/layout-ui/templates/event.klayout +0 -0
  30. package/layout-ui/templates/event.png +0 -0
  31. package/layout-ui/templates/quote.klayout +0 -0
  32. package/layout-ui/templates/quote.png +0 -0
  33. package/layout-ui/templates/sale.klayout +0 -0
  34. package/layout-ui/templates/sale.png +0 -0
  35. package/package.json +31 -4
  36. package/README.md +0 -3
@@ -0,0 +1,51 @@
1
+ [
2
+ {
3
+ "code": "layout.overset",
4
+ "fixture": "check-overset.klayout",
5
+ "overflow": "text",
6
+ "severity": "error",
7
+ "summary": "A story has more text than its frames hold, so the rest does not print."
8
+ },
9
+ {
10
+ "code": "layout.missing-font",
11
+ "fixture": "check-missing-font.klayout",
12
+ "severity": "error",
13
+ "summary": "Text uses a font that is not available here, so it is drawn with a substitute."
14
+ },
15
+ {
16
+ "code": "layout.missing-glyphs",
17
+ "fixture": "check-missing-glyphs.klayout",
18
+ "severity": "error",
19
+ "summary": "Characters are drawn as their font's missing glyph because the font lacks them."
20
+ },
21
+ {
22
+ "code": "layout.missing-link",
23
+ "fixture": "check-missing-link.klayout",
24
+ "severity": "error",
25
+ "summary": "A placed graphic's file is missing, so it prints as an empty frame."
26
+ },
27
+ {
28
+ "code": "layout.unsupported-typography",
29
+ "fixture": "check-unsupported-typography.klayout",
30
+ "severity": "warning",
31
+ "summary": "Text uses a typography feature this build does not compose yet, so it may differ from the original."
32
+ },
33
+ {
34
+ "code": "layout.low-resolution",
35
+ "fixture": "check-low-resolution.klayout",
36
+ "severity": "warning",
37
+ "summary": "A placed image in a print document has fewer pixels per inch than print needs at its placed size."
38
+ },
39
+ {
40
+ "code": "layout.empty-frame",
41
+ "fixture": "check-empty-frame.klayout",
42
+ "severity": "warning",
43
+ "summary": "A text frame holds no text; removing it changes nothing on the page."
44
+ },
45
+ {
46
+ "code": "layout.rgb-in-print",
47
+ "fixture": "check-rgb-in-print.klayout",
48
+ "severity": "warning",
49
+ "summary": "A print document uses an RGB swatch, which a printer converts unpredictably."
50
+ }
51
+ ]
@@ -0,0 +1,301 @@
1
+ # Layout kit
2
+
3
+ The Layout kit opens, edits and checks page layouts for print and screen (`.klayout`; IDML files
4
+ open as imports). Pages hold frames, text flows through threaded text frames as stories, and a live
5
+ preflight reports what would go wrong in print. An agent can make and arrange frames, write and
6
+ format text, manage swatches and styles, place graphics, check the document with the preflight, and
7
+ export it to PDF, PNG, JPEG, HTML, IDML or EPUB.
8
+
9
+ ## Tools
10
+
11
+ The kit's prefix is `layout`. Its tools are:
12
+
13
+ | Tool | Does |
14
+ |---|---|
15
+ | `layout_inspect` | The document as JSON (pages, items with ids and bounds, stories, swatches and styles), with a preview on request: the whole layout, or with `target` one page (`{page}`, from 1), spread (`{spread}`, from 0) or object (`{path: "item:<id>"}`, as a diagnostic names it) |
16
+ | `layout_query` | Reads objects of the document's object model by id, or by following fields from the root |
17
+ | `layout_commands` | Finds commands by keywords, each with its parameter schema |
18
+ | `layout_run` | Runs a list of command steps |
19
+ | `layout_batch` | Runs one batch of object-model operations |
20
+ | `layout_check` | The live preflight: what is wrong with the document, as diagnostics |
21
+ | `layout_create` | Makes a new `.klayout` document |
22
+ | `layout_export` | Writes the document to a new PDF, PNG, JPEG, HTML, IDML or EPUB file |
23
+ | `layout_draft_ready`, `layout_draft_reopen` | Asks the person to review your draft, or takes it back to edit |
24
+
25
+ Every tool takes `path`, the document's path in the workspace. With `draft: true` your edits go to
26
+ your draft of the document and leave the file as it is; only the person merges or discards a draft.
27
+
28
+ ## Addressing and coordinates
29
+
30
+ - A document has **spreads** of **pages**, **layers**, **swatches**, and paragraph and character
31
+ **styles**. `settings.intent` is `print`, `web` or `mobile`; a print document is checked for
32
+ print problems (RGB colour, image resolution).
33
+ - Page items are text frames, graphic frames, rectangles, ellipses, polygons, lines and groups. A
34
+ text frame shows part of a **story**; a story can thread through several frames.
35
+ - Coordinates are **points** in spread coordinates: `(0, 0)` is the top-left corner of the spread's
36
+ first page, `x` grows right and `y` grows **down**. A rectangle is `[x0, y0, x1, y1]`.
37
+ - A `spread` parameter counts spreads from **0**. Diagnostics' `target.page` counts pages from
38
+ **1**.
39
+ - Items and stories are named by numeric **ids**: `layout_inspect` lists `spreads[].items[]` (each
40
+ with `id`, `kind`, `bounds`, and `story` for text frames) and `stories[]` (each with `id`,
41
+ `frames` and `overset`). [`frame.create`](/kits/layout/commands/frame.create/) answers `{id}` and,
42
+ for a text frame, `{id, story}`.
43
+ - Ids are stored in the document: an object keeps its id when the document is saved and opened
44
+ again, in another session, and in your draft. Two people who
45
+ each make an object at the same moment may get one id; after their edits merge, the newer
46
+ object has the next free id, so read the ids of objects you just made from `completed[].result`.
47
+ - Query, batch, and declared command object parameters share tool addresses. Spreads, pages,
48
+ layers, items, stories and assets use their stored numeric `number` (a decimal string is also
49
+ accepted). Guides, sections, inlines, tables, rows, columns, cells, styles, swatches, opaque
50
+ records and comments use their immutable `address`. The root is `layout`. An integer in a
51
+ parameter is an object address only when that command declares it as one.
52
+ - Style and swatch lookups accept names or their queried addresses. A name that two definitions of
53
+ the family share (a swatch in a colour group, for example) is refused: name one by its address. A style address must belong
54
+ to the command's style family. Newly assigned names are values, not lookups. Local table and
55
+ note numbers are places within their holder, not global object ids; table places currently
56
+ resolve through the story/cell selection. Stable-address command support for local notes and
57
+ settings records is incomplete; use query/batch addresses for those records.
58
+ - Diagnostics name an item as `target.path` `item:<id>`.
59
+ - Commands that take `ids` act on those items; without `ids` they act on the selection. Character
60
+ formatting ([`type.char`](/kits/layout/commands/type.char/)) acts on selected text: select it
61
+ first with [`text.select`](/kits/layout/commands/text.select/) `{story, anchor, focus}`, where
62
+ `anchor` and `focus` are UTF-8 byte offsets in the story, counted from 0.
63
+
64
+ ## Workflow
65
+
66
+ 1. `layout_inspect {path}`: pages, items with ids and bounds, stories (with `overset`), swatches
67
+ and styles; `preview: true` for a picture of the layout, `target` for one page, spread or object.
68
+ 2. `layout_commands {path, query}`: find commands by keywords (`"text frame create"`,
69
+ `"fill swatch"`, `"align page"`). Use the exact id it returns and follow its parameter schema;
70
+ never guess a command id.
71
+ 3. `layout_run {path, steps}` a few steps per call. A failing step stops the call and the kit undoes
72
+ the steps before it, so the document is as it was before the call and nothing is saved: read
73
+ `error.index` for the failing step, fix it, and send the whole run again. A call that succeeds
74
+ saves the document (`save` defaults to `true`).
75
+ 4. `layout_check {path}`: the live preflight. Fix what it reports and check again.
76
+ 5. `layout_inspect {path, preview: true}` to look at the result.
77
+
78
+ ## Observations and stale writes
79
+
80
+ Keep the `revision` returned by an observation and pass it as `basis` on the subsequent write.
81
+ The default `premise` guard checks the facts that call holds against the observed revision.
82
+ Unrelated outside changes can apply; the receipt's `others` describes those changes. A refusal
83
+ reports `deleted`, `relocated`, `changed` or `unknown`. Observe again before deciding how to
84
+ retry. `epoch` refuses every outside document change; `off` permits stale writes.
85
+
86
+ Commands publish typed object/name parameters, place parameters, and editor state in `reads`.
87
+ Raw model batches must leave text frames linked to stories and groups with tree children;
88
+ inconsistent content conversions refuse atomically before merge repair runs.
89
+ An explicit `on` supplies an item selection for the call. Layout has no implicit current page
90
+ or time: use each command's explicit page/spread parameters. A call saves and restores the
91
+ selection (including text/cells/anchors), active layer, tool, preferences, clipboards, repeat
92
+ history, loaded cursor and auxiliary session state. A live gesture/data preview cannot accept
93
+ an explicit call context. Tool gesture internals are not serialised.
94
+
95
+ These are the currently audited per-call premises, implemented in `bindings/wasm/src/place.rs`:
96
+
97
+ | Commands | Facts held |
98
+ |---|---|
99
+ | `object.rename`, `fill`, `opacity`, `label`, `altText`, `lock`, `hide`, `setFlags`, `attributes`, `transparencyGroup`, `setLayer`; `layer.set` | The fields written, without placement. Fill holds swatch and tint; opacity also holds blend when supplied. Referenced swatches/layers are declared objects. |
100
+ | Non-copy `transform.move` | Target lock and transform/ownership placement; ancestor transforms/ownership. `toSpread` also holds the destination spread and its index window. An unrelated target property may change. |
101
+ | `object.align` with `to` page, margins or spread | The targets, and the size, margins and place of the page under them (every page of the spread for `spread`). |
102
+ | `object.group` | Members' layer, transform and ownership placement. Only top-level members in one spread are accepted. |
103
+ | `xml.deleteTag` | The set of items tagged with the name (an item another writer tagged or created tagged refuses `relocated`; one untagged, deleted or tagged otherwise does not), the tag's definition and the style-to-tag mappings. |
104
+ | `form.set` without `name` | The existing form fields' names, which the default name avoids: another writer's new or renamed field on an existing item refuses. A new item created as a form field after the observation is not held (the command has no place parameter for the guard to ask about); the name chosen is still unused when the write runs. |
105
+ | Writes that map spread coordinates into an item or its path out to the spread (`path.split`, `path.erase`/`smooth`/`addAnchor`/`appendAnchor`/`moveAnchors`, `path.convertAnchor` with `to`, `object.gradientFeather`/`object.gradient` with `from`/`to`, `object.makeCompoundPath`, `object.pathfinder`, `anchored.insert`, `object.caption`, `edit.pasteInto`, `transform.set`, `text.placeCaret`, `table.dropCells`) | Each ancestor group's transform and place, besides the target. |
106
+ | `layout.deleteAlternate`, `layout.createAlternate` | Deletion: the layout's pages (its `name` is a place), their items, stories, assets and parents, and the sections. Creation: the source layout's pages, their items, stories, assets and parents, the sections and the spread list (a page added anywhere refuses). |
107
+ | `liquid.pageRule`, `page.background` without `pages`; `page.transition` with `all` | Every page's stored fields and the spread list: a page another writer adds or changes refuses. |
108
+ | `data.source.remove`, `data.placeholder.add` | The data sources (`settings.dataMerge.sources`); the placeholder's story or item as named. |
109
+ | `layer.move` | Source placement and destination list gap in stored order, accounting for removal of the source. |
110
+ | `layer.new`, `layer.others`, `layer.deleteUnused` | Creation holds the layer count used for naming/color. Others holds the sorted layer identity set and affected flags, leaving an excluded layer's other fields free. Unused deletion holds layer and used-layer identity sets, plus the first stored layer when none is used. Reordering does not refuse when only count or membership matters. |
111
+ | `layer.delete`; `object.setLayer` | Deletion holds the layer, every item on it and `~layerItems`, the set of items the engine deletes with it; that set is also a place of the layer (its `id`), so an item another writer changes on the layer, moves onto it or creates on it refuses, and one put on another layer does not. Assigning a layer holds the layer's stored fields, not its items. |
112
+ | A `spread` counted from 0 that a command creates or acts in (`frame.create`, `line.create`, `path.create`, `file.place`, `guide.add`, `layout.createGuides`, ...); `button.set` `page`; `toc.generate`, `index.generate`, `file.place` `page`; `page.transition` `pages` or `spread`; `liquid.pageRule` and `page.background` `pages` | The counted spread and page prefix (an insertion or deletion before refuses `relocated`) and the addressed spread's or page's identity. `gap.move`'s `spread` holds the prefix spreads' places but not an insertion before them (a `within` window beside `covers` is not checked at this pin). |
113
+ | `states.show`/`rename` `index`, `path.deleteAnchor`/`convertAnchor` `anchor`/`subpath`, `path.moveAnchors` `anchors`, `anchored.options`/`release` `index`, `xref.setFormat` `index`, `text.select` `anchor`/`focus` | The object the position counts in (item or story), whole. |
114
+ | `guide.move`, `guide.delete`, `guide.liquid` | The counted spread and page prefix, and the guide at that index on its page, including every guide before it (guides are stored by position); a parent spread named by its prefix also holds that prefix and name. Move/delete also hold the layer's effective visible/unlocked/show-guides predicate. |
115
+ | `find.changeObjects` | Matched target fields and query membership, evaluated by the engine's shared matcher against historical scalar facts. Layer names and typed addresses use one resolver. |
116
+ | Parent application and page insertion | Parent prefix or full label identity, not its definition. The omitted insertion parent holds the first parent's identity and list position. |
117
+ | Page-number writes (`pages.insert/delete/move/applyParent/toSpread`, page size, margins, section, overrides); spread duplicate/shuffle/rotation | Resolved page/spread, the identities and placement of the prefix counted by the address, and insertion windows. Page deletion also holds the removed items, their stories/assets and `~pageItems`, the set of items the engine deletes with the page, so an item another writer puts on the page refuses; other page writes hold the page's stored fields, not its items. Page source and reshuffling dependencies are still being reviewed. |
118
+ | `story.replaceRange`, `spelling.change`, `anchored.insert` with `story` and `pos` | Offsets are UTF-8 **byte offsets**, not character counts, and a positional address: the write rests on the story's text before and inside its range, not on text after it. Another writer's edit before the range or inside it refuses `relocated` (inside is reported as `relocated`, not `changed`); an edit after the range applies. A change whose place a change set cannot tell refuses `relocated` with `place.unknown`: a formatting-only change anywhere in the story, and an insertion into repeated text that could have been made at or before the range's end. Change sets give a story over 80 characters as an excerpt: the kit finds the observed text among the texts its process held (opened, changed, inspected); when it held none or several that fit (after a restart of the kit, or past its memory budget) the write refuses with `place.unknown`. Anchored objects, notes and tables inside the range are held whole. |
119
+ | Other text editing and formatting | Resolved stories, whole, including text and owned content: an edit anywhere in the story refuses. This includes `text.select` with `anchor`/`focus` and the selection-based writes after it. Formatting selected frames, also one frame of a threaded story, acts on the whole story, not just the text visible in that frame, and so holds the whole story. Point-to-caret reflow dependencies remain under review. |
120
+ | Copy/cut/clear, content conversion, duplicate, copy-move, step and repeat, outlines, spread duplicate, library/conveyor collection; update linked story | Source descendants and their referenced stories/assets; linked updates also hold the source parent story. Outlines hold used paragraph, character, table and cell styles, including based-on chains and nested styles. A clipboard already copied in the session is a frozen source. |
121
+ | Named styles and swatches | The resolved definition's name for applications/references (also `toc.generate`'s `styles` and `entries[].style`), its content for edits/deletes. Five read-only scoped style lookup keys are maintained for commands with a fixed family, including direct model batches. `style.group` and `style.exportTag` still use the SDK's generic name check and can falsely refuse after a same-spelling rename in another family. |
122
+ | `object.gradient` | The target and the current fill's swatch definition: changing a gradient copies and modifies its current stops, rather than merely assigning a style identity. |
123
+ | Hyperlink record edits/deletes; placeholder removal | The settings entry selected by its stored id, rather than a same-valued global object number. |
124
+ | Bookmark rename/delete | The settings bookmark prefix counted by the index. |
125
+ | `document.applyTemplate`; `font.replace`; destructive `type.pathOptions` | Templates hold the whole replaced document. Font replacement conservatively holds all stories and, unless disabled, paragraph/character/composite definitions; unrelated item properties can change. Removing path text holds its story. |
126
+ | Conditions, text variables, named lists, custom strokes, articles | The settings entry selected by its name, including its content. These entries lack immutable keys: rename/delete refuse as `changed`, rather than a refined identity reason. |
127
+ | `xref.defineFormat`, `style.compositeFont.set`, `swatch.ungroupColorGroup`, `swatch.renameColorGroup`, `ink.options` with `allToProcess` | The named definition/group consumed or overwritten; group rename holds source/destination names while allowing member changes. The ink flag is held as its effective default-aware value. Other groups/definitions and per-ink options can change independently. Per-swatch group membership and other ink-option branches remain under review. |
128
+ | `xref.insert`, `xref.setFormat` | The assigned format's existence/name, including insertion's default format. A definition-content edit may apply because assignment stores its name; a rename-away refuses. |
129
+ | Footnote/endnote options and insertion | The document's note options; endnotes also hold their generated story reference. |
130
+ | `document.preferences`, `edit.transparencyBlendSpace`, `changes.track`, dictionary words and hyphenation exceptions | The stored settings fields they overwrite. |
131
+ | `object.globalLight`, `object.primaryTextFrame` | The root's `setup.globalLight` and `setup.primaryStory`, respectively. The primary-frame command's omitted `on` toggles from the observed primary story. |
132
+ | `frame.fitText` | The resolved story, threaded frame geometry and used paragraph, character, table and cell definitions through based-on chains. Point-to-caret and outlines hold these too, and the story's `~compositionFrames`: each frame's area, options, wrap exclusions and page, as the composer reads them. Fonts are not held: a composite font redefined (`style.compositeFont.set`) or a font file added to or removed from the machine changes what fitting computes without refusing; a font replaced in the document (`font.replace`) changes the story's formatting and so refuses. |
133
+ | `frame.thread`, `frame.unthread`, `frame.loadText` | The referenced frames and their stories, including both endpoints when joining stories. |
134
+ | `gap.move` | Exact engine gap neighbours, geometry/visibility/lock, their layers and page geometry. Historical substitutions are applied together; unsupported historical structure returns unknown. |
135
+ | Existing-table commands; `style.cell.apply`, `style.table.apply` | Cell non-stroke edits hold the addressed cells and possible merged owners, with counted row/column prefixes. Row height and column width edits hold addressed line definitions. Insertions hold copied neighbouring cell formats and row kinds; deletions hold removed/displaced cells; merge/unmerge hold addressed cells and merged spans. Anchor deletion/conversion also holds story text. Split, move/sort, strokes (which mirror to neighbours), table styles and composed row distribution still hold the whole table. Header/footer rows use the engine's resolved range. |
136
+ | Rules read from the blind readings (`bindings/wasm/src/place/rests.rs`) | One table per command of what the handler reads besides its targets and parameters. Typing/special characters/deletion: `setup.trackChanges`. Page insertion/move/document setup: the setup, the sections and the items repagination moves; page size and margins with Adjust Layout: the items on those pages. Arrange: each sibling's place in the item tree. Unlock/show all: every top-level item's flag. Style deletion, object-style application, style groups, change acceptance, condition/variable deletion, find next, table drops: every story's text. Table selection: the table's rows and columns. Layer deletion: the layer count (`~layerCount`); a page background: the last layer (`~lastLayer`). Creation defaults: a new text frame (also captions, linked stories) holds the default paragraph and text-frame styles, that object style and the binding (a new story's direction); a size step, OpenType toggle, broken link, paragraph rule patch or style from the selection holds the formatted text's style chains; a table insertion the insertion story's text and frames; a new condition the conditions; a new parent the setup size, facing pages, first page's margins and columns and, without a prefix, the parents' prefixes. Paste: the selected story whole, track changes and the first spread. Cell/table style edits: every cell's/table's style and properties. `variables.insert`: the whole variable list (an instance stores its index). Misc: articles, data-merge sources/placeholders/options with hyperlink ranges, hyperlinks, bookmarks, stroke styles and XML settings whole; `links.goTo` every item's graphic; `object.layerOptions` the placed asset; `math.insert` the first page and active layer; `data.merge` and `script.run` the whole document. |
137
+ | Effects, corners, wrap, stroke, export options | The one effect (`effects.dropShadow`, ...) or field the handler patches on each target: another writer's rename, move or paint of the same item applies. |
138
+
139
+ `~boundsX0`, `~boundsY0`, `~boundsX1`, `~boundsY1` are derived from an item's path/content/transform and owned group children, in the
140
+ parent coordinate system; it is not a stored field or a world-space box. Group transform receipts
141
+ use `carried` to report the descendant count whose world location follows the group, without
142
+ one edit per descendant. Scalar bounds allow the SDK's offset footprints to state all moved
143
+ objects without a truncated detailed list. Page/spread `~placeSpread` identifies the spread in
144
+ historical spatial evaluation, including after deletion.
145
+
146
+ An independent reading covers all 460 registry handlers, including all 395
147
+ journaled commands. Counts include query and session-only handlers. Per source family:
148
+
149
+ - Objects: object 63/63, paths 6/6, edit 14/14, select 9/9, thread 4/4, fit_text 1/1,
150
+ path_type 2/2, anchored 4/4, captions 1/1, linked 4/4, library 12/12.
151
+ - Text: text 37/37, style 29/29, table 41/41, find 5/5, fonts 3/3, spelling 8/8,
152
+ notes 6/6, endnotes 5/5, xref 7/7, toc 3/3, index 4/4, editorial 5/5, changes 6/6,
153
+ variables 4/4, lists 2/2, conditions 5/5.
154
+ - Layout: layout 23/23, overrides 3/3, guides 6/6, liquid 6/6, background 1/1,
155
+ transitions 2/2, file 21/21, templates 2/2, interchange 2/2, export 6/6,
156
+ export_bytes 1/1, export_image 1/1, prefs 3/3, print 2/2, package 2/2, preflight 1/1.
157
+ - Other: anchors 5/5, articles 6/6, book 10/10, buttons 6/6, colorsettings 3/3,
158
+ datamerge 10/10, interactive 9/9, links 6/6, mathexpr 2/2, media 2/2, pdflayers 2/2,
159
+ qr 1/1, scripts 1/1, states 5/5, strokes 3/3, xml 12/12, inspect 5/5.
160
+
161
+ These readings follow direct mutation operations and the composition entry/frame-input
162
+ paths, not every deeper shaping, table composition, variable expansion or export codec
163
+ algorithm. The prose rows and the 345 projection inputs are written without the declarations,
164
+ and the 66 misc commands have blind projections written from their prose rows, so all 395
165
+ journaled commands are compared. Over all 395, 165 commands differ: 1 holds less than the
166
+ handler reads and 165 hold more (false refusals). The one held-less command is
167
+ `file.importXml` (agent-blocked), which reads its target story's frame list: a premise on a list
168
+ field holds the members' content at the pinned SDK, so holding it would refuse unrelated frame
169
+ paint. Held more: 79 commands whose free probes the declaration holds (mostly a target held whole
170
+ by the SDK's default where the handler reads a few fields) and 120 that declare `mode` (or another
171
+ editor axis) the blind reading does not name. Layout keeps no mode in its editor state; `mode` is
172
+ declared on every journaled command because smart reflow and live captions read session
173
+ preferences, which the three-family readers count as `mode` and the misc reader does not: that
174
+ disagreement between readers is unresolved. Each class of held fact has an outside-writer test
175
+ (`bindings/headless/tests/outside/read3.rs`). These are probe counts: conditional paths and
176
+ coarse translations remain, and free probes do not enumerate every excessive hold.
177
+ The guard asks a later step's premises on a copy of the document after the earlier steps ran, so
178
+ a source cell or text an earlier step of the same run selects is held
179
+ (`waiting_for_sdk_read2_selection_step_source_premises` refuses the changed source and applies
180
+ an unrelated change).
181
+ The blind selection/active-layer expectations are checked against the declarations of every
182
+ journaled command. An outside-writer regression verifies `story.setDirection` with frame
183
+ selection context: a changed story refuses, while an unrelated item rename applies.
184
+ `layout.pages.move` returns an unsupported error if any non-shuffling multi-page spread exists
185
+ (except a no-op move). Moves within preserved spreads are not implemented: they need stable page
186
+ identities across repagination, spread membership rebuilt around kept spreads, page-relative
187
+ item translation, and sections, parents, guides and shuffle flags carried with each page.
188
+
189
+ The guard audit is incomplete. Other commands retain the SDK's default checks on declared objects;
190
+ that does not establish all dependencies. Ordered pages, guide/local-note/settings places,
191
+ selection-addressed text ranges, reflow/captions and style application need further implementation review. Shared
192
+ style names across the five namespaces may cause a conservative name refusal. Historical page,
193
+ hierarchy and nested-child geometry substitutions can return unknown even for an unrelated edit.
194
+ Derived values (`~pageItems`, `~layerItems`, `~compositionFrames`) are declared in the object model.
195
+ The SDK re-reads a derived value after another agent's write on the same server only for the
196
+ objects that write names, and an item put on a page or layer or a wrap object moved names neither
197
+ the page, the layer nor the story. So page and layer deletion also name the items they delete
198
+ as objects under their place (an item another agent created on or moved onto the page or
199
+ layer refuses), and composition premises also hold the root's `~compositionFrames.<story>`. The
200
+ root's value is compared whole at the pinned SDK: after another writer changes any story's
201
+ composition inputs, every composition-dependent write refuses, including ones the change did not
202
+ touch (waiting for the SDK to compare a derived value at a premise's sub-path).
203
+ At the pinned SDK, deletion/move-out before an index gap can still let a stale batch insert apply;
204
+ batch deletion of a nonempty group is also refused. A command with both `covers` and `within`
205
+ does not get an index-window check at this pin. The outside-writer tests cover the audited forms,
206
+ not a blanket guarantee for all Layout commands.
207
+
208
+ ## Example 1: a branded band and a centred line of type
209
+
210
+ ```json
211
+ layout_run {"path": "Flyer.klayout", "steps": [
212
+ {"command": "swatch.create", "params": {"name": "Brand", "color": {"c": 70, "m": 75, "y": 0, "k": 0}}},
213
+ {"command": "frame.create", "params": {"rect": [72, 300, 540, 420], "content": "unassigned"}},
214
+ {"command": "frame.create", "params": {"rect": [72, 450, 540, 520], "content": "text", "text": "Saturday 8 pm, Town Hall"}}
215
+ ]}
216
+ ```
217
+
218
+ Answer: `completed: [{result: {name: "Brand"}}, {result: {id: 9}}, {result: {id: 10, story: 11}}]`.
219
+ Use those ids:
220
+
221
+ ```json
222
+ layout_run {"path": "Flyer.klayout", "steps": [
223
+ {"command": "object.fill", "params": {"swatch": "Brand", "ids": [9]}},
224
+ {"command": "text.select", "params": {"story": 11, "anchor": 0, "focus": 24}},
225
+ {"command": "type.char", "params": {"attrs": {"size": 28, "fill": "Brand"}}},
226
+ {"command": "object.align", "params": {"edge": "hcenter", "to": "page", "ids": [10]}}
227
+ ]}
228
+ layout_check {"path": "Flyer.klayout"}
229
+ → {"diagnostics": []}
230
+ ```
231
+
232
+ ## Example 2: fix what the check reports
233
+
234
+ ```json
235
+ layout_check {"path": "Programme.klayout"}
236
+ → {"diagnostics": [{"code": "layout.overset", "severity": "error", "target": {"page": 1, "path": "item:10"},
237
+ "message": "Overset text: 1123 characters.", "fix": {"command": "frame.fitText", "params": {"ids": [10]}}}]}
238
+ ```
239
+
240
+ Over a thousand characters do not fit, so the fix would shrink the type to a couple of points
241
+ ([`frame.fitText`](/kits/layout/commands/frame.fitText/) answers `{stories: [{size: 2.0}]}`). Make
242
+ room instead, then check again:
243
+
244
+ ```json
245
+ layout_run {"path": "Programme.klayout", "steps": [
246
+ {"command": "transform.resize", "params": {"ids": [10], "from": [72, 300, 200, 320], "to": [72, 300, 540, 720]}}
247
+ ]}
248
+ layout_check {"path": "Programme.klayout"}
249
+ ```
250
+
251
+ A missing font is replaced as the fix says:
252
+
253
+ ```json
254
+ layout_check {"path": "Poster.klayout"}
255
+ → {"diagnostics": [{"code": "layout.missing-font", "severity": "error", "message": "Missing font: Kition Missing Sans.",
256
+ "fix": {"command": "font.replace", "params": {"family": "Kition Missing Sans", "toFamily": "Source Serif 4"}}}]}
257
+ layout_run {"path": "Poster.klayout", "steps": [
258
+ {"command": "font.replace", "params": {"family": "Kition Missing Sans", "toFamily": "Source Serif 4"}}
259
+ ]}
260
+ layout_check {"path": "Poster.klayout"}
261
+ → {"diagnostics": []}
262
+ ```
263
+
264
+ ## Pitfalls
265
+
266
+ - **Frame content:** [`frame.create`](/kits/layout/commands/frame.create/) needs `content`: `text`
267
+ (with `text`), `graphic`, or `unassigned` (a shape).
268
+ - **Select text first:** [`type.char`](/kits/layout/commands/type.char/) `{attrs}` changes the
269
+ selected text only; run [`text.select`](/kits/layout/commands/text.select/) first.
270
+ - **Results of earlier steps:** steps in one `layout_run` cannot refer to an earlier step's result.
271
+ Create, read the ids from `completed[].result`, then use them in the next call.
272
+ - **Print colour:** colours in a print document should be CMYK swatches (`{c, m, y, k}`, each 0 to
273
+ 100); a `#rrggbb` swatch is RGB and the check reports it.
274
+ - **Fitting text:** [`frame.fitText`](/kits/layout/commands/frame.fitText/) can shrink a long story
275
+ to an unreadable size; prefer a larger or threaded frame when much text is overset.
276
+ - **Files:** commands that read or write files are not offered through `layout_run`; graphics and
277
+ text come in with [`file.place`](/kits/layout/commands/file.place/) `{path}` (a file in the
278
+ workspace, by its path) or `{base64, name}`. A path outside the workspace (absolute, `../` that
279
+ climbs out, a URL, a hidden name) is refused, and links in a document that name one are never
280
+ read. Printing is not available.
281
+ - **Undo:** your [`edit.undo`](/kits/layout/commands/edit.undo/) takes back your own steps only; the
282
+ person's edits stay.
283
+
284
+ ## Checks
285
+
286
+ `layout_check` lists what is wrong with the document. Each diagnostic has a stable `code`, a
287
+ `severity` (`error`, `warning` or `info`), a `message`, a `target` and, for some, a `fix`: a
288
+ command step to run as it is. Act on the code, not on the message. A `fix` is a suggestion: run it
289
+ only when it is what the person asked for. Every code the kit reports is on the
290
+ [checks page](/kits/layout/checks/).
291
+
292
+ | Code | Severity | What to do |
293
+ |---|---|---|
294
+ | `layout.overset` | error | Text does not fit: enlarge the frame, thread a new frame, cut text, or `fix` [`frame.fitText`](/kits/layout/commands/frame.fitText/) `{ids}` (shrinks the type to fit: check the answered `size`) |
295
+ | `layout.missing-font` | error | `fix` replaces it with the bundled family ([`font.replace`](/kits/layout/commands/font.replace/) `{family, toFamily}`); pick another available one with [`font.families`](/kits/layout/commands/font.families/) if the person wants |
296
+ | `layout.missing-glyphs` | error | The font lacks those characters: use a font that has them |
297
+ | `layout.missing-link` | error | A placed graphic's file is gone or outside the workspace (never read from there): put it in the workspace and place it again ([`file.place`](/kits/layout/commands/file.place/) `{path}`), or remove the frame |
298
+ | `layout.unsupported-typography` | warning | A setting the kit keeps but does not compose (kinsoku, mojikumi, Arabic justification); tell the person |
299
+ | `layout.low-resolution` | warning | The image is too small for print at its size: place a larger image or scale the frame down |
300
+ | `layout.empty-frame` | warning | `fix` removes the empty text frame ([`edit.clear`](/kits/layout/commands/edit.clear/) `{ids}`) |
301
+ | `layout.rgb-in-print` | warning | Use a CMYK swatch ([`swatch.create`](/kits/layout/commands/swatch.create/) `{name, color: {c, m, y, k}}`) in a print document |
@@ -0,0 +1 @@
1
+ import{e as $e,j as Se,r as xe,t as Le,F as ie,G as Ce,c as C,h as qe,v as Ae,i as Oe,s as ze,u as Ue,f as Ie,a as je,Z as Ee,O as ve,o as Pe,y as Re,b as Ne,J as be}from"./index-DblcoJ90.js";function v(e,t){return new C(-32e3,t,{reason:e})}const _=e=>new C(-32602,e),fe=e=>Object.prototype.toString.call(e)==="[object ArrayBuffer]";function G(e){const t=e.lastIndexOf(".");return t>0?e.slice(t+1).toLowerCase():""}const Be=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;function he(e){let t=(e.split(/[\\/]/).pop()??"").replace(/[\u0000-\u001f\u007f<>:"|?*]/g,"").trim().replace(/^\.+/,"").replace(/[. ]+$/,"");const n=t.indexOf("."),s=n<0?t:t.slice(0,n);if(Be.test(s)&&(t=`${s}_${t.slice(s.length)}`),t.length>255){const r=G(t);t=r?`${t.slice(0,254-r.length)}.${r}`:t.slice(0,255)}return t||"Untitled"}async function We(e,t){const n=e.lastIndexOf("."),[s,r]=n>0?[e.slice(0,n),e.slice(n)]:[e,""];for(let c=1;c<1e4;c+=1){const u=c===1?e:`${s} ${c}${r}`;if(!await t(u))return u}throw v("io-error","no unused name is left for this file")}function pe(){const e=new Uint8Array(16);return crypto.getRandomValues(e),be+Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}const Me=e=>e.split(/[\\/]/).filter(Boolean).pop()??e,Fe=()=>{var e,t;return((t=(e=globalThis.navigator)==null?void 0:e.userActivation)==null?void 0:t.isActive)??!0},oe=e=>(e??[]).map(t=>t.replace(/^\./,"").toLowerCase());function Je(e,t,n){let s=[];return{append:async r=>void s.push(r),commit:async()=>{const r=new Uint8Array(s.reduce((y,k)=>y+k.byteLength,0));let c=0;for(const y of s)r.set(y,c),c+=y.byteLength;const u=await e.commit(t(),r,n());return s=[],u},abort:async()=>{s=[]}}}const Te=["files/pick","files/create","files/stat","files/read","files/list","files/write","files/release","files/print"];function De(e){var Z,te,X,H;const{storage:t}=e,n=pe().slice(be.length),s={read:oe((Z=e.manifest)==null?void 0:Z.read),create:oe((te=e.manifest)==null?void 0:te.create),folders:((X=e.manifest)==null?void 0:X.folders)===!0,print:((H=e.manifest)==null?void 0:H.print)===!0},r=t.name??Me,c=e.gesture??Fe,u=new Map;let y=!1,k=0;const L=["files",...e.pick?["files-pick"]:[],...e.print?["print"]:[]],b=i=>({handle:i.handle,name:i.name,kind:i.kind,...i.size!==void 0?{size:i.size}:{},...i.mime!==void 0?{mime:i.mime}:{},version:i.version,rights:[...i.rights]}),q=(i,a,d,g,f={})=>{var j;const m={handle:pe(),session:n,kit:e.kit,principal:e.principal,flow:g,rights:d,kind:(a==null?void 0:a.kind)??"file",name:f.name??r(i),ref:i,folder:f.folder??null,accept:f.accept??[],mime:f.mime??(a==null?void 0:a.mime),version:(a==null?void 0:a.version)??null,size:a==null?void 0:a.size,committed:!1,staging:null,staged:0,written:0,expected:null};u.set(m.handle,m);const{handle:U,session:M,kit:D,principal:ne,kind:h,name:A}=m;return(j=e.log)==null||j.call(e,{handle:U,session:M,kit:D,principal:ne,flow:g,rights:[...d],kind:h,name:A}),m},$=(i,a,d)=>{if(y)throw v("file-not-granted","the session has ended");const g=typeof i=="string"?u.get(i):void 0;if(!g)throw v("file-not-granted","this handle was not granted to this session");if(a&&!g.rights.includes(a))throw v("file-not-granted",`this handle has no ${a} right`);if(d&&g.kind!==d)throw v("file-not-granted",`this handle is not a ${d}`);return g},p=async i=>{try{return await i()}catch(a){throw a instanceof C?a:v("io-error","the host could not reach the file")}},z=async i=>{u.delete(i.handle);const a=i.staging;i.staging=null,a&&await a.abort().catch(()=>{})},P=i=>{if(!c())throw v("no-gesture",`${i} needs a person's gesture in the kit`)},R=async(i,a)=>{const d=new Set([...u.values()].filter(f=>f.rights.includes("create")&&f.kind==="file"&&!f.committed).map(f=>f.ref)),g=await We(a,async f=>{const m=t.child(i,f);return d.has(m)||await t.stat(m)!==null});return{name:g,ref:t.child(i,g)}},N=(i,a=s.read)=>{const d=G(i);if(!s.read.includes(d)||!a.includes(d))throw v("not-allowed",`the kit may not read .${d||"(none)"} files`)},B=i=>{const a=G(i);if(!s.create.includes(a))throw v("not-allowed",`the kit may not create .${a||"(none)"} files`)},J=(i,a)=>{const d=oe(i);if(d.some(g=>!a.includes(g)))throw v("not-allowed","the kit asked for a file type its manifest does not declare");return d.length?d:a},T=async i=>{if(!e.pick)throw v("unsupported","this host has no picker");if((i==null?void 0:i.mode)!=="open"&&(i==null?void 0:i.mode)!=="folder"&&(i==null?void 0:i.mode)!=="save")throw _("mode is open, folder, or save");if(P("files/pick"),i.mode==="folder"&&!s.folders)throw v("not-allowed","the kit may not ask for folders");const a=J(i.accept,i.mode==="save"?s.create:s.read);i.mode==="save"&&i.suggestedName!=null&&B(he(i.suggestedName));const d=await p(()=>e.pick(i)),g=[];for(const f of i.mode==="open"&&!i.multiple?d.slice(0,1):d){const m=await p(()=>t.stat(f));if(i.mode==="folder"){if((m==null?void 0:m.kind)!=="folder")continue;const U=s.create.length?["read","create"]:["read"];g.push(b(q(f,m,U,"pick",{accept:a})))}else if(i.mode==="open"){if((m==null?void 0:m.kind)!=="file"||!a.includes(G(r(f))))continue;g.push(b(q(f,m,["read"],"pick")))}else{if(!a.includes(G(r(f))))throw v("not-allowed","the kit may not create this file type");if((m==null?void 0:m.kind)==="folder")continue;if(m&&e.readOnly)throw v("not-allowed","a read-only session replaces no file");g.push(b(q(f,m,m?["write"]:["create"],"pick")));break}}return{files:g}},o=async i=>{if(typeof(i==null?void 0:i.suggestedName)!="string")throw _("suggestedName is a string");const a=i.folder===void 0?null:$(i.folder,"create","folder"),d=he(i.suggestedName);B(d);const{name:g,ref:f}=await p(()=>R((a==null?void 0:a.ref)??null,d));return b(q(f,null,["create"],"create",{name:g,folder:(a==null?void 0:a.ref)??null,mime:typeof i.mime=="string"?i.mime:void 0}))},l=async({handle:i,offset:a,length:d})=>{const g=$(i,"read","file"),f=a??0;if(!Number.isSafeInteger(f)||f<0||d!==void 0&&(!Number.isSafeInteger(d)||d<0))throw _("offset and length are whole numbers");const m=await p(()=>t.read(g.ref,f,d));return g.version=m.version,g.size=m.size,m},S=async({handle:i})=>{const a=$(i,"read","folder"),d=await p(()=>t.list(a.ref)),g=[];for(const f of d){if(!a.accept.includes(G(r(f)))||!s.read.includes(G(r(f))))continue;const m=await p(()=>t.stat(f));(m==null?void 0:m.kind)==="file"&&g.push(b(q(f,m,["read"],"list")))}return{files:g}},W=async i=>{var U,M;const a=$(i==null?void 0:i.handle,void 0,"file"),d=a.rights.includes("create");if(!d&&!a.rights.includes("write"))throw v("file-not-granted","this handle has no create or write right");if(d&&a.committed)throw v("already-committed","this file was already committed");if(!fe(i.bytes))throw _("bytes is an ArrayBuffer");if(i.offset!==a.staged)throw _(`offset is ${a.staged}, the bytes staged so far`);const g=i.bytes.byteLength;if(((U=e.quota)==null?void 0:U.perGrant)!==void 0&&a.written+g>e.quota.perGrant||((M=e.quota)==null?void 0:M.perSession)!==void 0&&k+g>e.quota.perSession)throw v("quota","this write passes the host's cap");if(i.final&&!d){if(typeof i.expected!="string")throw v("conflict","the final chunk carries the version it replaces");if(await p(()=>{var D;return((D=t.unsaved)==null?void 0:D.call(t,a.ref))??!1}))throw v("unsaved-edits","the file is open with unsaved edits");a.expected=i.expected}if(!a.staging){const D=()=>d?{mode:"create"}:{mode:"replace",expected:a.expected??""};a.staging=t.stage?t.stage(a.ref,D):Je(t,()=>a.ref,D)}const f=a.staging;if(await p(()=>f.append(new Uint8Array(i.bytes.slice(0)))),a.staged+=g,a.written+=g,k+=g,!i.final)return{};const m=await O(a,f,d);return a.staging=null,a.staged=0,a.expected=null,a.version=m.version,d&&(a.committed=!0),{version:m.version}},O=async(i,a,d)=>{var g;for(let f=0;;f+=1)try{return await p(()=>a.commit())}catch(m){const U=m instanceof C&&((g=m.data)==null?void 0:g.reason)==="conflict";if(!d||!U||i.flow!=="create"||t.stage||f>=8)throw m;const M=await p(()=>R(i.folder,i.name));i.ref=M.ref,i.name=M.name}},V=async({handles:i})=>{for(const a of Array.isArray(i)?i:[]){const d=typeof a=="string"?u.get(a):void 0;d&&await z(d)}return{}},ee=async i=>{if(!e.print)throw v("unsupported","this host does not print");if(!s.print)throw v("not-allowed","the kit may not print");P("files/print");let a;if(!i||typeof i!="object")throw _("a print takes PDF bytes or a handle");if("handle"in i){const g=$(i.handle,"read","file");if(G(g.name)!=="pdf"&&g.mime!=="application/pdf")throw v("not-allowed","only a PDF prints");a=await K(g.ref)}else{if(i.mime!=="application/pdf"||!fe(i.bytes))throw _("a print takes PDF bytes or a handle");a=new Uint8Array(i.bytes.slice(0))}const d=typeof i.title=="string"?i.title:"";return{printed:await p(()=>e.print({bytes:a,title:d}))===!0}},K=async i=>{const a=[];let d=0;for(;;){const{bytes:m,size:U}=await p(()=>t.read(i,d,void 0));if(a.push(new Uint8Array(m)),d+=m.byteLength,d>=U||m.byteLength===0)break}const g=new Uint8Array(d);let f=0;for(const m of a)g.set(m,f),f+=m.byteLength;return g},Q={"files/pick":T,"files/create":o,"files/stat":async({handle:i})=>{const a=$(i);if(a.rights.includes("create")&&!a.committed&&a.kind==="file")return b(a);const d=await p(()=>t.stat(a.ref));if(!d)throw v("file-not-granted","the file is gone");return Object.assign(a,{version:d.version,size:d.size,mime:d.mime??a.mime}),b(a)},"files/read":l,"files/list":S,"files/write":W,"files/release":V,"files/print":ee};return{id:n,capabilities:L,grant:async(i,a,{flow:d,approved:g})=>{if(y)throw v("file-not-granted","the session has ended");const f=await p(()=>t.stat(i)),m=r(i);if(a.includes("write")){if(e.readOnly)throw v("not-allowed","a read-only session replaces no file");if(d==="agent"&&g!==!0)throw v("not-allowed","an agent replaces a file only through a draft or the person's approval");if((f==null?void 0:f.kind)!=="file")throw v("not-allowed","there is no such file to replace");B(m)}if(a.includes("read")){if(!f)throw v("not-allowed","there is no such file");if(f.kind==="file")N(m);else if(!s.folders)throw v("not-allowed","the kit may not read folders")}if(a.includes("create")&&(!f||f.kind==="file")){if(f)throw v("not-allowed","a create grant never names an existing file");B(m)}return b(q(i,f,[...new Set(a)],d,(f==null?void 0:f.kind)==="folder"?{accept:s.read}:{}))},revoke:async i=>{var d;const a=[];for(const g of i){const f=u.get(g);f&&(await z(f),a.push(g))}a.length&&((d=e.revoked)==null||d.call(e,a))},grants:()=>[...u.values()].map(({handle:i,session:a,kit:d,principal:g,flow:f,rights:m,kind:U,name:M})=>({handle:i,session:a,kit:d,principal:g,flow:f,rights:[...m],kind:U,name:M})),serve:async(i,a)=>{var d;if((d=e.trace)==null||d.call(e,i,a),y)throw v("file-not-granted","the session has ended");return Q[i](a)},end:async()=>{y=!0;for(const i of[...u.values()])await z(i)}}}function ue(e){if(/^([A-Za-z]:)?[\\/]/.test(e))return null;const t=[];for(const n of e.replace(/\\/g,"/").split("/"))if(!(!n||n==="."))if(n===".."){if(!t.length)return null;t.pop()}else t.push(n);return t.length?t.join("/"):null}function He(e,t,n){const s=ue(e),r=[];for(const c of n){const u=typeof(c==null?void 0:c.path)=="string"?ue(c.path):null;if(!u||u===s||u.split("/").some(b=>b.startsWith(".")))continue;const y=u.split("/").pop(),k=y.includes(".")?y.slice(y.lastIndexOf(".")+1).toLowerCase():"";if(!t.accept.includes(k))continue;const L={path:Ne(e,u),name:y,version:typeof c.version=="string"?c.version:null};if(r.some(b=>b.path===L.path)||r.push(L),!t.multiple)break}return r}function E(e){throw new C(-32601,`${e} is not supported by this host`)}function Ge(e,t){const{handlers:n}=t,s={agent:n.openAgent,"pick-file":n.pick,replica:n.replicaRead&&n.replicaWrite,customize:n.customize,lease:n.leases,presence:n.presence},r=Object.entries(s).filter(([,b])=>b).map(([b])=>b);n.generate&&r.push("generate"),n.open&&r.push("open-file"),n.openUrl&&r.push("open-url");const c=t.document.readOnly===!0;n.pickLinks&&!c&&r.push("links-pick"),n.fetchImage&&!c&&r.push("fetch-image");const u=Object.entries(n.actions??{}).filter(([,b])=>typeof b=="function");r.push(...u.map(([b])=>`${$e}${b}`));const y=Object.entries(n.services??{}).filter(([b,q])=>typeof q=="function"&&Se.includes(b)&&xe(b,t.document));r.push(...y.map(([b])=>`${Le}${b}`)),n.comments&&r.push("comment-anchors"),t.files&&r.push("files",...t.files.pick?["files-pick"]:[],...t.files.print?["print"]:[]);const k=t.timeoutMs??12e4,L=(b,q)=>{var T;const $=new MessageChannel,p=new qe($.port1,"h");let z=null;p.handle("host/read",o=>n.read(o)),p.handle("host/stamp",o=>n.stamp(o)),p.handle("host/write",o=>n.write(o)),p.handle("host/pick",o=>n.pick?n.pick(o):E("host/pick")),p.handle("host/openAgent",async o=>(n.openAgent||E("host/openAgent"),await n.openAgent(o),{}));const{replicaRead:P,replicaWrite:R}=n;p.handle("host/replicaRead",o=>P&&R?P(o):E("host/replicaRead")),p.handle("host/replicaWrite",async o=>((!P||!R)&&E("host/replicaWrite"),await R(o),{})),p.handle("host/customize",async o=>(n.customize||E("host/customize"),await n.customize(o),{})),p.handle("host/leaseAcquire",o=>n.leases?n.leases.acquire(o):E("host/leaseAcquire")),p.handle("host/leaseRelease",async o=>(n.leases||E("host/leaseRelease"),await n.leases.release(o),{})),p.handle("host/leases",async()=>(n.leases||E("host/leases"),{leases:await n.leases.list()})),p.handle("host/generate",o=>{if(n.generate||E("host/generate"),!Ae(o==null?void 0:o.purpose,z))throw new C(-32e3,`a kit may not generate for ${JSON.stringify(o==null?void 0:o.purpose)}`,{reason:"not-allowed"});return n.generate(o)}),p.handle("host/action",o=>{var S;const l=typeof(o==null?void 0:o.id)=="string"?(S=u.find(([W])=>W===o.id))==null?void 0:S[1]:void 0;if(!l)throw new C(-32e3,`this host does not serve the action ${String(o==null?void 0:o.id)}`,{reason:"not-allowed"});return l(o.params&&typeof o.params=="object"?o.params:{})}),p.handle("host/open",async o=>{var S;n.open||E("host/open");const l=Oe(o);if(!l)throw new C(-32602,"host/open needs a link with a path, a name, or a docId");return{opened:((S=await n.open(l))==null?void 0:S.opened)!==!1}}),p.handle("host/openUrl",async o=>{var l;if(n.openUrl||E("host/openUrl"),!ze(o==null?void 0:o.url))throw new C(-32e3,"a host opens only https:, http:, and mailto: addresses",{reason:"not-allowed"});return{opened:((l=await n.openUrl({url:o.url}))==null?void 0:l.opened)!==!1}}),p.handle("host/fetchImage",async o=>{if(n.fetchImage||E("host/fetchImage"),c)throw new C(-32e3,"a read-only document fetches no pictures",{reason:"read-only"});if(!Ue(o==null?void 0:o.url))throw new C(-32e3,"a host fetches only https: and http: addresses",{reason:"not-allowed"});const l=await n.fetchImage({url:o.url});if(!((l==null?void 0:l.bytes)instanceof ArrayBuffer)||!Ie.includes(l.mime))throw new C(-32e3,`${o.url} is not a picture`,{reason:"unsupported"});return{bytes:l.bytes,mime:l.mime}}),p.handle("links/pick",async o=>{if(n.pickLinks||E("links/pick"),c)throw new C(-32e3,"a read-only document links no files",{reason:"read-only"});const l=je(o);if(!l)throw new C(-32602,"links/pick needs a purpose and at least one extension without the dot");return{links:He(t.document.path,l,await n.pickLinks(l)??[])}});const N=t.files?De({...t.files,readOnly:c,revoked:o=>p.notify("files/revoked",{handles:o})}):null;if(N)for(const o of Te)p.handle(o,l=>N.serve(o,l));p.on("document/conflicts",o=>{var l;return(l=n.conflicts)==null?void 0:l.call(n,o)}),p.on("document/schema",o=>{var S;const l=Ee(o);l&&((S=n.schema)==null||S.call(n,l))}),p.on("draft/changed",o=>{var l;return(l=n.draftChanged)==null?void 0:l.call(n,o)}),p.on("presence/set",o=>{var S;const l=ve(o);l&&((S=n.presence)==null||S.call(n,l))}),p.on("document/changed",o=>n.changed(o)),p.on("replica/changed",o=>{var l;return(l=n.replicaChanged)==null?void 0:l.call(n,o)}),p.on("host/notify",o=>{var l;return(l=n.notify)==null?void 0:l.call(n,o)}),p.on("host/shortcut",o=>{var l;return(l=n.shortcut)==null?void 0:l.call(n,o)}),p.on("ui/action",o=>{var l;return(l=n.action)==null?void 0:l.call(n,o)}),p.handle("host/service",o=>{var O;const l=o==null?void 0:o.service,S=(O=y.find(([V])=>V===l))==null?void 0:O[1];if(!S)throw new C(-32e3,`this host does not serve ${String(l)}`,{reason:"not-allowed"});const W=Pe(o);if(!W)throw new C(-32602,`bad params for ${String(l)}`);return S(W.params)}),p.on("comments/activated",o=>{var l;typeof(o==null?void 0:o.id)=="string"&&o.id&&((l=n.comments)==null||l.activated(o.id))}),b.postMessage({kitionKitUi:1,protocol:ie,id:q},t.origin,[$.port2]);const B={...t.document,bytes:(T=t.document.bytes)==null?void 0:T.slice(0)},J=p.request("ui/initialize",{protocol:ie,host:t.host,document:B,theme:t.theme,locale:t.locale,shortcuts:t.shortcuts,capabilities:r,capabilitySets:t.capabilitySets??[],ui:t.ui},{transfer:!0});return J.then(o=>{var l;z=typeof((l=o==null?void 0:o.kit)==null?void 0:l.id)=="string"?o.kit.id:null},()=>{}),{peer:p,files:N,initialized:J}};return new Promise((b,q)=>{var B,J,T;let $=null;const p=o=>{var l;o==null||o.peer.close(),(l=o==null?void 0:o.files)==null||l.end()},z=()=>{var o;clearTimeout(R),window.removeEventListener("message",N),(o=t.signal)==null||o.removeEventListener("abort",P)},P=()=>{z(),p($),q(new Error("the kit mount was abandoned"))};if((B=t.signal)!=null&&B.aborted){q(new Error("the kit mount was abandoned"));return}(J=t.signal)==null||J.addEventListener("abort",P);const R=setTimeout(()=>{z(),p($),q(new Error("the kit did not open the document in time"))},k),N=o=>{if(o.source!==e.contentWindow||!Ce(o.data)||o.data.ready!==ie||t.origin!=="*"&&o.origin!==t.origin||($==null?void 0:$.id)===o.data.id)return;p($);const{peer:l,files:S,initialized:W}=L(o.source,o.data.id);$={peer:l,files:S,id:o.data.id},W.then(O=>{($==null?void 0:$.peer)===l&&(z(),b(_e(l,O,S)))},O=>{($==null?void 0:$.peer)===l&&(z(),S==null||S.end(),q(O instanceof Error?O:new Error(String(O))))})};window.addEventListener("message",N),(T=e.contentWindow)==null||T.postMessage({kitionKitUi:1,hello:ie},t.origin)})}function _e(e,t,n){return{kit:t.kit,capabilities:t.capabilities,state:()=>e.request("document/state",{}),save:()=>e.request("document/save",{}),fileChanged:s=>e.notify("document/fileChanged",{version:s}),fileHeld:s=>e.notify("document/held",{version:s}),setTheme:s=>e.notify("ui/theme",{theme:s}),setLocale:s=>e.notify("ui/locale",{locale:s}),focus:()=>e.notify("ui/focus",{}),configure:s=>e.notify("ui/configure",{ui:s}),leasesChanged:s=>e.notify("lease/changed",{leases:s}),peersChanged:s=>e.notify("presence/peers",{peers:s}),reveal:s=>e.notify("document/reveal",{view:s}),showComments:s=>{const r=s.flatMap(c=>{const u=Re(c.anchor);return u&&typeof c.id=="string"?[{id:c.id,anchor:u,resolved:c.resolved===!0,count:Number.isSafeInteger(c.count)?c.count:0}]:[]});e.notify("comments/show",{threads:r})},locateComments:async s=>{if(!t.capabilities.includes("comment-anchors"))return s.map(()=>!1);const{found:r}=await e.request("comments/locate",{anchors:s});return s.map((c,u)=>(r==null?void 0:r[u])===!0)},onPresence:s=>e.on("presence/set",r=>{const c=ve(r);c&&s(c)}),elements:()=>e.request("ui/elements",{}),check:async s=>t.capabilities.includes("check")?(await e.request("document/check",s!=null&&s.draft?{draft:!0}:{})).diagnostics:[],ai:{inspect:s=>e.request("ai/inspect",s??{}),commands:s=>e.request("ai/commands",{query:s}),run:(s,r,c)=>e.request("ai/run",{steps:s,save:r,...c!=null&&c.draft?{draft:!0}:{},...c!=null&&c.origin?{origin:c.origin}:{},...(c==null?void 0:c.originLabel)!=null?{originLabel:c.originLabel}:{}}),preview:(s,r)=>e.request("ai/preview",r!=null&&r.draft?{maxSize:s,draft:!0}:{maxSize:s}),version:async()=>(await e.request("ai/version",{})).version,premise:(s,r)=>e.request("ai/premise",{method:s,params:r}),changes:(s,r)=>e.request("ai/changes",r?{since:s,schema:r}:{since:s})},draft:{state:()=>e.request("draft/state",{}),ready:()=>e.request("draft/ready",{}),reopen:()=>e.request("draft/reopen",{}),compare:s=>e.request("draft/compare",s??{}),merge:(s,r)=>e.request("draft/merge",r?{origin:s,schema:r}:{origin:s}),discard:()=>e.request("draft/discard",{})},replica:{version:async()=>(await e.request("replica/version",{})).version,exportChanges:s=>e.request("replica/export",{since:s}),importChanges:(s,r)=>e.request("replica/import",{changes:s,blobs:r}),info:async()=>(await e.request("replica/info",{})).docId,onChanged:s=>e.on("replica/changed",r=>s(r.version))},model:{describe:s=>e.request("model/describe",s?{schema:s}:{}),batch:s=>e.request("model/batch",s)},files:n&&{grant:n.grant,revoke:n.revoke,grants:n.grants},close:()=>{e.close(),n==null||n.end()}}}const Ve=new Set(["purpose","title"]),Ze=new Set(["mime"]),Ke=/^(application|audio|example|font|haptics|image|message|model|multipart|text|video)\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}(\s*;\s*[a-z0-9!#$&^_.+-]+=("[^"\\/]*"|[^\s;"\\/]+))*$/i,Qe=/(^|[\s"'(=])(\/(?:Users|home|root|var|tmp|private|Volumes|mnt|media|etc|opt|srv|data|workspace)\b|[A-Za-z]:[\\/]|\\\\[^\\\s]|~[\\/]|file:)/i;function me(e,t=!1){return Qe.test(e)?!0:!t&&(/[\\/]/.test(e)||/^\.\.?$/.test(e))}function Xe(e){return Ke.test(e)}function ce(e,t,n,s,r=0){if(typeof e=="string"){(n==="mime"?!Xe(e)&&me(e):me(e,n==="free"))&&s.push({at:t,value:e});return}if(!(e===null||typeof e!="object"||r>8||e instanceof ArrayBuffer||ArrayBuffer.isView(e)))if(Array.isArray(e))e.forEach((c,u)=>ce(c,`${t}[${u}]`,n,s,r+1));else for(const[c,u]of Object.entries(e))ce(u,t?`${t}.${c}`:c,Ve.has(c)?"free":Ze.has(c)?"mime":"name",s,r+1)}function Ye(e){const t=[];for(const{method:n,params:s}of e){if(!n.startsWith("files/"))continue;const r=[];ce(s,"","name",r);for(const c of r)t.push({method:n,...c})}return t}const et={pdf:"application/pdf",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",txt:"text/plain",json:"application/json"},ae=e=>e.split("/").some(t=>t.startsWith(".")||t===""),re=e=>e.includes("/")?e.slice(0,e.lastIndexOf("/")):"";function tt(e,t,n=new Set){const s=r=>n.has(r)||[...e.keys()].some(c=>c.startsWith(`${r}/`));return{stat:r=>{var u;if(ae(r))return null;const c=e.get(r);if(c){const y=et[((u=r.split(".").pop())==null?void 0:u.toLowerCase())??""];return{kind:"file",size:c.bytes.byteLength,version:String(c.version),...y?{mime:y}:{}}}return s(r)?{kind:"folder",version:null}:null},read:async(r,c,u)=>{const y=ae(r)?void 0:e.get(r);if(!y)throw v("file-not-granted","the file is gone");const k=u===void 0?y.bytes.byteLength:Math.min(y.bytes.byteLength,c+u);return{bytes:y.bytes.slice(c,k),version:String(y.version),size:y.bytes.byteLength}},list:r=>{const c=new Set;for(const u of[...e.keys(),...n]){if(!u.startsWith(`${r}/`)||ae(u))continue;const y=u.slice(r.length+1);c.add(`${r}/${y.split("/")[0]}`)}return[...c].sort()},child:(r,c)=>{const u=r??t();return u?`${u}/${c}`:c},commit:async(r,c,u)=>{const y=e.get(r);if(u.mode==="create"&&(y||s(r)))throw v("conflict","a file with this name exists");if(u.mode==="replace"&&(!y||String(y.version)!==u.expected))throw v("conflict","the file changed since it was read");!s(re(r))&&re(r)!==""&&n.add(re(r));const k=((y==null?void 0:y.version)??0)+1;return e.set(r,{bytes:c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength),version:k}),{version:String(k)}}}}const ge={light:{colorScheme:"light",tokens:{"--kit-primary":"#5645d4","--kit-surface":"#ffffff","--kit-surface-muted":"#fafaf9","--kit-canvas":"#f6f5f4","--kit-text":"#1a1a1a","--kit-text-muted":"#5d5b54","--kit-border":"#e5e3df"}},dark:{colorScheme:"dark",tokens:{"--kit-primary":"#8b7ff0","--kit-surface":"#1b1e23","--kit-surface-muted":"#22262c","--kit-canvas":"#15171b","--kit-text":"#eceff1","--kit-text-muted":"#a9b0ba","--kit-border":"#33373e"}}};function we(e,t){var s;const n=((s=t.split(".").pop())==null?void 0:s.toLowerCase())??"";return!(e!=null&&e.length)||e.some(r=>r.replace(/^\./,"").toLowerCase()===n)}function nt(e){return e!=="viewer"&&e!=="commenter"?{}:{readOnly:!0,comments:{me:`dev-${e}`,name:e==="viewer"?"Viewer":"Commenter",canComment:e==="commenter",othersReadOnly:!1}}}function ye(e){const t=[];for(const n of e.split("/"))if(!(!n||n==="."))if(n===".."){if(!t.length)return null;t.pop()}else t.push(n);return t.join("/")}function st(e,t,n){const s=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"";if(e.path){const L=ye(e.path.startsWith("/")?e.path:`${s}/${e.path}`);return L?{path:L,exists:n.has(L)}:null}if(!e.name||e.name.includes("/"))return null;const r=t.includes(".")?t.slice(t.lastIndexOf(".")):"",c=L=>(L.split("/").pop()??"").replace(/\.[^.]*$/,"").toLowerCase(),u=[...n.keys()].filter(L=>c(L)===e.name.toLowerCase()),y=u.find(L=>L.endsWith(r))??u[0];if(y)return{path:y,exists:!0};const k=ye(`${s}/${e.name}${r}`);return k?{path:k,exists:!1}:null}const ke=["menus","line","classic","focus"];function it(e){const t=[];for(const n of(e??"").split(",").map(s=>s.trim()).filter(Boolean))ke.includes(n)?t.push(n):console.warn(`kit-dev-host: ?modes= names an unknown display mode "${n}" (one of ${ke.join(", ")})`);return t.length?{allowed:t,default:t[0]}:void 0}function ot(e={}){var ne;const t=new Map,n=document.getElementById("kit"),s=document.getElementById("status"),r=document.getElementById("file"),c=[],u=e.entry??"./index.html",y=e.pickable??/\.(png|jpe?g|gif|svg|webp)$/i;let k=null;const L=e.presence===!0||new URLSearchParams(location.search).get("presence")==="1",b=[],q=[];let $=[];const p=new Set,z=[],P=[],R=[],N=[],B=e.generate===!0||new URLSearchParams(location.search).get("generate")==="1",J=[],T=[],o=e.open===!0||new URLSearchParams(location.search).get("open")==="1",l=[],S=[],W=[];let O="";const V=`kit-dev-host:personal:${location.pathname}`,ee=[];let K=new URLSearchParams(location.search).get("scheme")==="dark"?"dark":"light";const Q=it(new URLSearchParams(location.search).get("modes"));let Z=Q?{modes:Q}:{};const te=()=>{try{return JSON.parse(localStorage.getItem(V)??"[]")}catch{return[]}},X=()=>({...Z,personal:{hide:te()}}),H=document.createElement("details");H.innerHTML='<summary>UI configuration</summary><textarea rows="6" cols="60" spellcheck="false">{}</textarea><button type="button">Apply</button><select><option value="light">Light</option><option value="dark">Dark</option></select>',(ne=s.parentElement)==null||ne.append(H);const i=H.querySelector("textarea"),a=H.querySelector("select");a.value=K,H.querySelector("button").addEventListener("click",()=>{try{d(JSON.parse(i.value))}catch(h){s.textContent=`configuration: ${h instanceof Error?h.message:String(h)}`}}),a.addEventListener("change",()=>g(a.value==="dark"?"dark":"light"));function d(h){Z={hide:h.hide,disable:h.disable,add:h.add,modes:h.modes??Q},i.value=JSON.stringify(Z,null,2),k==null||k.configure(X())}function g(h){K=h,a.value=h,k==null||k.setTheme(ge[h])}async function f(h,A,j={}){k==null||k.close(),O=h,t.set(h,{bytes:A,version:1}),s.textContent=`opening ${h}…`,n.src=`${u}?${Date.now()}`;const se=t.get(h);try{k=await Ge(n,{origin:location.origin,host:{name:"Development host",version:"1"},document:{path:h,name:h.split("/").pop()??h,bytes:se.bytes.slice(0),version:String(se.version),lend:e.lend?{root:new URL(e.lend.root,location.href).href,folder:e.lend.folder}:void 0,...nt(new URLSearchParams(location.search).get("role")),...j.view?{view:j.view}:{}},theme:ge[K],locale:new URLSearchParams(location.search).get("locale")??navigator.language,shortcuts:["Cmd+W","Cmd+N","Cmd+O","Cmd+,"],ui:X(),handlers:{read:({path:w,offset:x,length:I})=>{const F=t.get(w);if(!F)throw new Error(`${w} is not in the workspace`);const Y=x??0;return{bytes:x!=null||I!=null?F.bytes.slice(Y,I!=null?Y+I:void 0):F.bytes.slice(0),version:String(F.version),size:F.bytes.byteLength}},stamp:({path:w})=>({version:t.has(w)?String(t.get(w).version):null}),write:({path:w,bytes:x,mode:I})=>{var le;let F=w;if(I!=="save")for(let de=2;t.has(F);de+=1)F=w.replace(/(\.[^./]+)?$/,` ${de}$1`);const Y=(((le=t.get(F))==null?void 0:le.version)??0)+1;return t.set(F,{bytes:x,version:Y}),{path:F,version:String(Y)}},pick:({accept:w})=>({path:[...t.keys()].find(x=>y.test(x)&&we(w,x))??null}),pickLinks:w=>{W.push(w);const x=S.shift();return(x?typeof x=="function"?x(w):x:[...t.keys()].filter(I=>I!==h&&y.test(I)&&we(w.accept,I))).filter(I=>t.has(I)).map(I=>({path:I,version:String(t.get(I).version)}))},openAgent:()=>{s.textContent="the editor asked for the agent"},changed:w=>{c.push(w),s.textContent=`${h}: revision ${w.revision}${w.dirty?", unsaved":""}`},notify:w=>{s.textContent=`${w.level}: ${w.title}`},shortcut:w=>{s.textContent=`host shortcut ${w.key}`},customize:({personal:w})=>{localStorage.setItem(V,JSON.stringify(w.hide))},action:w=>{ee.push(w),s.textContent=`host button ${w.id}`},schema:w=>{q.push(w)},...L?{presence:w=>void b.push(w)}:{},...B?{generate:w=>m(w)}:{},...o?{open:w=>U(w),openUrl:w=>M(w)}:{}},...e.kitFiles?{files:{storage:tt(t,()=>O.includes("/")?O.slice(0,O.lastIndexOf("/")):"",p),kit:"dev-kit",principal:"dev-person",manifest:e.kitFiles,pick:async w=>{const x=z.shift();return typeof x=="function"?x(w):x??[]},print:async({bytes:w,title:x})=>(N.push({title:x,size:w.byteLength}),window.devHost.printAnswer),log:w=>void P.push(w),trace:(w,x)=>void R.push({method:w,params:x})}}:{}}),L&&$.length&&k.peersChanged($),s.textContent=`${h} open in ${k.kit.id} ${k.kit.version}`}catch(w){s.textContent=`could not open ${h}: ${w instanceof Error?w.message:String(w)}`}}async function m(h){J.push(h),s.textContent=`the editor asked to generate for ${h.purpose}`;const A=T.shift()??{refuse:"unavailable"},j=typeof A=="function"?await A(h):A;if("refuse"in j)throw new C(-32e3,`the development host refused: ${j.refuse}`,{reason:j.refuse});return j}async function U(h){l.push({method:"host/open",params:h}),s.textContent=`the editor asked to open ${JSON.stringify(h.link)}`;const A=st(h.link,O,t);if(!A)throw new C(-32e3,"the link is not in the workspace",{reason:"not-found"});if(!A.exists){if(!h.create)throw new C(-32e3,`${A.path} is not in the workspace`,{reason:"not-found"});t.set(A.path,{bytes:new ArrayBuffer(0),version:1})}return{opened:window.devHost.openAnswer}}async function M(h){return l.push({method:"host/openUrl",params:h}),s.textContent=`the editor asked to open ${h.url}`,{opened:window.devHost.openAnswer}}function D(h){$=h,L&&(k==null||k.peersChanged(h))}window.devHost={files:t,connection:()=>k,open:f,changes:c,configure:d,actions:ee,setScheme:g,presences:b,setPeers:D,schemas:q,folders:p,scriptPick:(...h)=>void z.push(...h),grants:P,fileRequests:R,prints:N,printAnswer:!0,checkNoPaths:()=>Ye(R),generated:J,scriptGenerate:(...h)=>void T.push(...h),opens:l,openAnswer:!0,scriptLinkPick:(...h)=>void S.push(...h),linkPicks:W},r==null||r.addEventListener("change",async()=>{var A;const h=(A=r.files)==null?void 0:A[0];h&&await f(h.name,await h.arrayBuffer())}),(async()=>{var j;for(const[se,w]of Object.entries(e.files??{})){const x=await fetch(w).catch(()=>null);x!=null&&x.ok&&t.set(se,{bytes:await x.arrayBuffer(),version:1})}if(!e.sample){s.textContent="choose a file";return}const h=await fetch(e.sample).catch(()=>null);if(!(h!=null&&h.ok)){s.textContent="choose a file";return}const A=decodeURIComponent(e.sample.split("/").pop()??"Sample");await f((j=e.lend)!=null&&j.folder?`${e.lend.folder}/${A}`:A,await h.arrayBuffer())})()}ot({sample:"./sample/Sample.klayout"});