@miragon/modeler-api 0.0.0-stage → 1.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Miragon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,232 @@
1
- # Temporary Holding Version
1
+ # @miragon/modeler-api
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ONE interface every Miragon modeler implements — the collaborative-modeler
4
+ contract and its conformance test kit.
5
+
6
+ ## Why
7
+
8
+ Embedding a modeler in a collaborative host (a shared Y.Text, re-imports on
9
+ every remote change) exposes behavioral details that are invisible in
10
+ standalone use. Before this contract existed, each drift had to be discovered
11
+ per modeler, against its engine internals:
12
+
13
+ - an `importDSL` that ran `commandStack.clear()` **emitting** a change event —
14
+ unsuppressed, opening a hand-authored file re-exported the canonical
15
+ serialization over it;
16
+ - an import that left the undo stack on stale, removed shapes — undo after a
17
+ co-editor's change silently no-op'd or deleted re-imported shapes by id
18
+ coincidence;
19
+ - a serializer that was not a byte fixpoint of its own parser;
20
+ - config/axis edits that fired their own event instead of the command stack —
21
+ a host observing only the stack lost them.
22
+
23
+ This package turns those lessons into **laws** (see the JSDoc on
24
+ `CollaborativeModeler`) and ships a **conformance kit** that makes every law
25
+ an executable test the modeler repo runs in its own CI. Drift fails the
26
+ modeler's build — not a downstream integration review.
27
+
28
+ ## The contract (1.x)
29
+
30
+ ```ts
31
+ import type { CollaborativeModeler } from "@miragon/modeler-api";
32
+ ```
33
+
34
+ | Law | Requirement |
35
+ | --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
36
+ | L1 | `importText` is **silent**: no change events, undo history erased without emitting — also over existing history and foreign content; an interaction open during an import (a label editor with typed input) never commits |
37
+ | L2 | `exportText` is **canonical**: deterministic, a byte fixpoint on canonical input, idempotent otherwise |
38
+ | L3 | `onContentChanged` fires for **every** user-visible change — element commands, config/axis/title edits, undo/redo — and nothing else; inside a listener `exportText()` already returns the new document |
39
+ | L4 | undo directly after an import is a defined **no-op** — never a stale-history mutation |
40
+ | L5 | view state survives a re-import; an import leaves the view **fitted** to the content; the readback may be a normalised form of what was set |
41
+ | L6 | `exportText` is total after a successful import; foreign content is **preserved** through import → export, never dropped, never a throw |
42
+ | L7 | EVERY rejected import leaves no trace — previous document still rendered and exported, no events, undo history untouched — and the modeler **stays usable** |
43
+
44
+ View state is never part of the document: `setViewState` fires no change
45
+ events and `exportText` is independent of it.
46
+
47
+ Calls made before the first import (`exportText()`, a user command) may
48
+ return or throw whatever the modeler defines, but never wedge the instance:
49
+ the first `importText` still renders and resolves as specified.
50
+
51
+ `meta.editable` tells a viewer mount from an editor: a package that ships a
52
+ `NavigatedViewer`/`Viewer` exposes it under the same contract with
53
+ `editable: false` — it imports, exports, reveals and reports view state like
54
+ the editor and never fires `onContentChanged`, so hosts mount it on read-only
55
+ surfaces without per-package knowledge. A viewer must import without a
56
+ command stack of its own, or register one: the kit's viewer case fails a
57
+ `NavigatedViewer` whose import clears a stack it never registered.
58
+
59
+ Optional `elements` surface (stable ids, `reveal`, a synchronous `selection()`
60
+ and selection events) powers host features like anchored todos, `?element=`
61
+ deep links and the selection half of live presence. Ids are ELEMENT ids
62
+ (a label shape resolves to its target) and survive edits to other elements —
63
+ positional ids that renumber when a line is inserted above break every anchor
64
+ below. The id a session reports is the element's id in the DOCUMENT: after
65
+ `exportText()` → `importText()`, in this instance or any other (a peer, the
66
+ viewer, the next session), the element carries the same id — an element
67
+ created in the session gets an id the serializer writes back, never one that
68
+ lives only in memory. RECOMMENDED: when two peers create different elements
69
+ at the same time, their ids do not collide — random or peer-scoped ids, not a
70
+ per-instance counter such as `event_1`. An id derived from the content (OWM's
71
+ `component_<slug>`) collides only when both users create the same content,
72
+ which the merge has to reconcile anyway.
73
+
74
+ An interaction in progress during an import (an open label editor, a popup
75
+ with typed input) never commits during or because of it (L1): no change
76
+ event, nothing in the imported document or on its undo history, nothing
77
+ applied to an element the import removed. RECOMMENDED: keep the typed input
78
+ and reopen the interaction on the element with the same id when it is still
79
+ there — hosts re-import remote states while the user is typing.
80
+
81
+ ## The conformance kit
82
+
83
+ ```ts
84
+ // e.g. test/conformance.browser.test.ts in a modeler repo (any (name, fn) runner)
85
+ import { attachedHost, registerConformance } from "@miragon/modeler-api/conformance";
86
+ import { test } from "vitest";
87
+
88
+ registerConformance(
89
+ {
90
+ create: async () => mountMyModeler(attachedHost()), // IN the document, sized — see below
91
+ createReadonly: async () => mountMyViewer(attachedHost()), // the viewer mount, if the package ships one
92
+ canonicalTexts: [CANONICAL_SAMPLE_A, CANONICAL_SAMPLE_B], // two DISTINCT, REVIEWED ones — the undo law needs them
93
+ looseTexts: [HAND_AUTHORED_SAMPLE],
94
+ invalidTexts: [HALF_TYPED_SAMPLE], // [] if NOTHING is non-importable (a lenient line DSL)
95
+ foreignTexts: [{ text: SAMPLE_WITH_VENDOR_EXTENSION, mustSurvive: ["x-vendor: keep-me"] }],
96
+ viewState: { x: 120, y: 80, width: 640, height: 480 }, // a panned/zoomed viewport, not the fitted one (the kit compares readbacks, never this literal)
97
+ mutate: (m) => addOneElement(m), // undoable; adds — never renames or deletes
98
+ configMutations: [{ name: "axis labels", run: (m) => renameEvolutionAxis(m) }], // [] if the notation has none
99
+ undo: (m) => triggerUndo(m),
100
+ redo: (m) => triggerRedo(m),
101
+ probeTexts: [CUT_OFF_SAMPLE], // optional: damaged forms your parser meets, on top of the derived probes
102
+ openInteraction: (m) => typeIntoLabelEditor(m, "typed, not committed"), // open an editor, type, do NOT commit
103
+ interactionState: (m) => readOpenLabelEditor(m), // { elementId, text } | undefined
104
+ // engines that debounce change delivery: make this outlast the debounce
105
+ settle: () => new Promise((r) => setTimeout(r, 50)),
106
+ },
107
+ test,
108
+ { onSkip: reportSkip, onAdvisory: reportAdvisory }, // optional: both default to console.warn
109
+ );
110
+ ```
111
+
112
+ **Run it in a real browser.** diagram-js engines compute viewboxes from the
113
+ host's client size and use `getBBox`, which jsdom lacks and a detached or 0×0
114
+ element turns into NaN: mount into `attachedHost()` (a sized element appended
115
+ to `document.body`) under vitest browser mode / Playwright — the modeler
116
+ repos' `test:browser` project — not under the unit project.
117
+
118
+ **Canonical texts are yours to vouch for.** L2 proves `exportText` is a
119
+ fixpoint of the texts you provide. Obtain them by exporting a hand-authored
120
+ document and reviewing the bytes; pasting whatever the current build prints
121
+ proves only that it agrees with itself.
122
+
123
+ **Nothing skips silently.** A case whose harness field is `undefined` reports
124
+ a SKIP (`console.warn` by default, `registerConformance(h, test, { onSkip })`
125
+ to route it) instead of passing. An explicit `[]` (`invalidTexts`,
126
+ `foreignTexts`, `configMutations`, `looseTexts`) is a statement that the
127
+ notation has no such form and skips nothing. Without `openInteraction` the
128
+ L1 interaction case reports a skip; with `openInteraction` but without
129
+ `interactionState` only its keep-and-reopen half does.
130
+
131
+ **Every rejection is probed.** `invalidTexts` lists what MUST reject; the kit
132
+ does not take `[]` on trust. The L7 probe case derives damaged forms from
133
+ every canonical text — its first half, its first third, the text without its
134
+ last character, the text followed by a NUL character — plus your optional
135
+ `probeTexts`, and imports each over a document with undo history. A probe may
136
+ import or reject: one that imports must be silent (L1) with `exportText`
137
+ total (L6); one that rejects must leave the document, its element ids, the
138
+ change events and the undo history untouched (L7). After every probe the next
139
+ valid import must render and the next user command must apply. The case runs
140
+ for every harness and never skips.
141
+
142
+ **Calls before the first import.** A fresh instance gets `exportText()` and
143
+ one `mutate` before any document (throws tolerated — what they return is
144
+ unspecified — and a `mutate` that never settles too: the kit waits 2 s for
145
+ it, so a harness that waits for its command's change event still runs); then
146
+ importing the first two canonical texts must render each exactly like a
147
+ fresh instance does, and the next `mutate` must emit and apply.
148
+
149
+ **Interactions open during an import.** `openInteraction` opens an editor on
150
+ an element of `canonicalTexts[0]` and types without committing. The kit then
151
+ imports over it twice — a different document (`canonicalTexts[1]`, the edited
152
+ element is usually gone; a harness with one canonical text reports that leg
153
+ as skipped) and the same document again (the element is still there) — and
154
+ requires no change event, the imported document as the export and an undo
155
+ that changes nothing (L1, L4). `interactionState` lets it check the
156
+ recommended keep-and-reopen on the same-document import.
157
+
158
+ **Recommendations are advisories.** Where the contract only RECOMMENDS
159
+ (collision-free ids across peers, keep-and-reopen of an open interaction), the
160
+ kit reports what it finds as an ADVISORY through `onAdvisory`
161
+ (`console.warn` by default) and never fails: a recommendation becomes a law,
162
+ with a failing case, only in a major release. The collision check imports the
163
+ same canonical text into two fresh instances, runs `mutate` once on each and
164
+ advises when both allocate the same id — unless both new elements carry the
165
+ same name and the id spells it out (its letters and digits contain the
166
+ name's, as `component_new_component` does for "New Component"). Such an id is
167
+ derived from the content and collides for identical content by design, so
168
+ the check reports a skip instead: let `mutate`'s elements differ in content
169
+ (a counter the harness shares across instances, as the reference harness
170
+ does).
171
+
172
+ **View state is compared by readback.** The kit never compares
173
+ `getViewState()` with your `viewState` literal: it sets it, reads the
174
+ modeler's own (possibly normalised) state back, and requires that readback
175
+ to survive a re-import — a diagram-js viewbox that comes back rounded with
176
+ `scale`/`inner`/`outer` is fine.
177
+
178
+ **Element identity is verified through names.** After an unrelated edit, and
179
+ after an export → import into the same instance, a fresh instance and the
180
+ viewer, every id the session reported must still exist and, where the
181
+ notation has names, still name the same element; a notation whose elements
182
+ carry no names is verified for id existence only.
183
+
184
+ The kit throws plain `Error`s — no assertion-library or runner dependency.
185
+ Its own CI proves it bites: a conforming reference modeler
186
+ ([`test/reference-modeler.ts`](test/reference-modeler.ts) — also the model
187
+ for a harness) passes every case and advises nothing, one deliberately broken
188
+ variant per historical drift AND per kit case fails exactly the case set that
189
+ encodes the violated law (not every individual assertion has a saboteur;
190
+ every case does), and one variant per recommendation fails nothing and
191
+ advises exactly once.
192
+
193
+ ## Versioning
194
+
195
+ One identity: `MODELER_API_VERSION` IS the npm package version — release-please
196
+ rewrites the constant on every release (`extra-files`) and a test pins it to
197
+ `package.json` exactly. Modelers pin the package and put the constant into
198
+ `meta.apiVersion`; hosts match on the major (`apiVersionsCompatible`).
199
+ Releases are tagged `modeler-api-vX.Y.Z`.
200
+
201
+ The contract is first published as 1.0.0, never 0.x: under 0.x,
202
+ `apiVersionsCompatible` matches on the minor too, which would turn every
203
+ additive surface into a lockstep release across all modelers and their
204
+ hosts. A new optional surface (a structured snapshot lane alongside the text
205
+ lane, richer element info) is a minor, and hosts feature-detect it. A new
206
+ required member or a stricter law is a major. A minor may still add a case
207
+ that enforces what the contract text already states; a requirement the text
208
+ does not state yet ships as a RECOMMENDATION with an advisory, so no
209
+ conforming modeler turns red in a minor. A case that needs a new optional
210
+ harness field (`openInteraction`) reports a skip until the harness provides
211
+ it, and a check the harness cannot feed conclusively (the collision check
212
+ when both peers' new elements share a name their id spells out) reports a
213
+ skip too; a suite whose `onSkip` throws, to keep every law verified, turns red on
214
+ that upgrade by its own choice, and the skip names what to add or change.
215
+
216
+ ### Candidates for 2.0
217
+
218
+ Recommendations today, proposed as hard laws for the next major:
219
+
220
+ - **Collision-free element ids across peers** — two instances that import the
221
+ same document and each create a different element never allocate the same
222
+ id for them; ids derived from the content (OWM's `component_<slug>`) meet
223
+ this by construction and collide only for identical content (today:
224
+ `ElementInfo.id` RECOMMENDED, advisory in the elements collision case).
225
+ - **Keep and reopen an interaction across an import** — an interaction open
226
+ during an import is reopened, with its typed input, on the element with the
227
+ same id when that element is still there (today: L1 RECOMMENDED, advisory in
228
+ the L1 interaction case).
229
+
230
+ ## License
231
+
232
+ MIT
@@ -0,0 +1,7 @@
1
+ // src/index.ts
2
+ var MODELER_API_VERSION = "1.1.0";
3
+
4
+ export {
5
+ MODELER_API_VERSION
6
+ };
7
+ //# sourceMappingURL=chunk-32BMH76T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @miragon/modeler-api — ONE interface every Miragon modeler implements.\n *\n * The contract encodes, as REQUIREMENTS, the behavioral drift that had to be\n * discovered per modeler against engine internals before it existed:\n * an `importDSL` that emitted change events (rewriting hand-authored files on\n * open), an import that left the undo stack on stale removed shapes, a\n * serializer that was not a byte fixpoint. A host embedding a conforming\n * modeler needs no per-engine suppression tricks — the laws below hold.\n *\n * The conformance test kit (`@miragon/modeler-api/conformance`) turns each\n * law into an executable case the modeler repo runs in its own CI.\n */\n\n/** the semver of THIS contract — a modeler declares the version it implements\n * in `meta.apiVersion`; hosts check compatibility with `apiVersionsCompatible`\n * (same major; while 0.x, the same minor too). The constant IS the\n * package version: release-please rewrites the literal below on every\n * release (release-please-config.json `extra-files`), and the kit's own\n * test pins it to package.json exactly. Modelers pin the npm package; the\n * constant is what travels in `meta`. */\nexport const MODELER_API_VERSION = \"1.1.0\"; // x-release-please-version\n\nexport interface ModelerMeta {\n /** stable notation id, e.g. \"wardley\", \"team-topology\", \"event-storming\" */\n readonly notation: string;\n /** the MODELER_API_VERSION this modeler implements — compatible when the\n * major matches and, while the contract is 0.x, the minor too (pre-1.0\n * minors may break: bump-minor-pre-major) */\n readonly apiVersion: string;\n /**\n * true on an editing mount (the package's Modeler), false on a VIEWER\n * (its NavigatedViewer/Viewer): a viewer never fires `onContentChanged`,\n * accepts no user commands, and still imports, exports, reveals and\n * reports view state exactly like the editor — hosts mount it on\n * read-only surfaces (an MCP-App widget in read-only mode) without\n * per-package knowledge or a command-stack shim.\n */\n readonly editable: boolean;\n}\n\nexport interface ImportResult {\n /** non-fatal notes from the import (unknown lines kept, migrations run) */\n warnings: string[];\n}\n\nexport interface ElementInfo {\n /**\n * stable element id — identical across re-imports of the same text AND\n * untouched by edits to OTHER elements: hosts anchor todos, presence and\n * `?element=` deep links to it, so an id that renumbers when a line is\n * inserted above (positional edge ids) breaks every anchor below it. An\n * element without an id in the text gets one the serializer WRITES BACK.\n *\n * The id a session reports IS the element's id in the document: after\n * `exportText()` → `importText()` — in this instance or in any other one\n * (a peer, the viewer, the next session) — the element carries the same\n * id. An id that lives only in memory anchors nothing: the todo or deep\n * link a host stored against it points nowhere once the text travels.\n *\n * RECOMMENDED: when two peers create different elements at the same time,\n * their ids do not collide. An id allocated regardless of the content —\n * a per-instance counter (`event_1` on both peers) — does: once both edits\n * merge into one document, two elements share one id; random or\n * peer-scoped ids do not. An id derived from the content (OWM's\n * `component_<slug>`) collides only when both users create the same\n * content, which the merge has to reconcile anyway.\n */\n id: string;\n /** human label, when the notation has one */\n name?: string;\n}\n\n/**\n * Optional element surface — what a host needs for anchored todos, `?element=`\n * deep links and the selection half of live presence. Absent = the notation\n * has no addressable element identity. Ids are ELEMENT ids throughout: a\n * shape that only labels another element (diagram-js external labels) is\n * reported and revealed as its target, never under its own label id.\n */\nexport interface ElementsSurface {\n /** every addressable element currently on the canvas */\n list(): ElementInfo[];\n /** select + scroll the element into view; false when the id is unknown.\n * Revealing is view behavior: it delivers a selection, never a change event */\n reveal(id: string): boolean;\n /** the current selection as stable element ids — synchronous, so a host\n * can read it at the moment of a click (a deep link carrying the\n * selection) without caching every delivery */\n selection(): string[];\n /** selection changes as STABLE element ids; returns the unsubscribe */\n onSelection(cb: (ids: string[]) => void): () => void;\n}\n\n/**\n * The collaborative-modeler contract. The LAWS (verified by the conformance\n * kit) are part of the interface:\n *\n * L1 SILENT IMPORT — `importText` never fires `onContentChanged` and erases\n * the undo history without emitting — also when history exists. Hosts\n * re-import remote states on every sync; an import echo would re-export\n * the canonical serialization over half-typed peer text.\n * An interaction in progress when an import runs (an open label editor,\n * a popup with typed input) never commits during or because of the\n * import: no change event comes from it, its input lands neither in the\n * imported document nor on its fresh undo history, and nothing is\n * applied to an element the import removed. RECOMMENDED: keep the typed\n * input and reopen the interaction on the element with the same id when\n * that element is still there after the import — a remote re-import\n * should not cost the user what they were typing.\n * L2 CANONICAL FIXPOINT — `exportText` is deterministic, and for any text t:\n * with c = exportText() after importText(t), importText(c) followed by\n * exportText() returns c byte-for-byte. Canonicalization is idempotent;\n * opening a file never rewrites it.\n * L3 ONE CHANGE EVENT — every user-visible atomic change (element commands\n * AND config/axis/title/style edits that live in the document, AND\n * undo/redo) fires `onContentChanged` at least once, and nothing else\n * does: not `importText`, not undo-history housekeeping, not view or\n * selection changes. When a listener runs, `exportText()` ALREADY\n * returns the post-change serialization — hosts export inside the\n * listener; an emit-before-apply would lose the last edit.\n * L4 DEFINED UNDO ACROSS IMPORTS — undo directly after an `importText` is a\n * no-op: it must never mutate or resurrect shapes from the pre-import\n * document (id coincidence included).\n * L5 VIEW-STATE ROUND-TRIP — `getViewState`/`setViewState` survive a\n * re-import: snapshot before, restore after, viewport unchanged. An\n * import leaves the view FITTED to the content (the defined post-import\n * view, the same for the same document and host — a host that wants to\n * keep the user's viewport across a remote re-import snapshots before\n * and restores after); before the first import `getViewState()` returns\n * `undefined` or a state `setViewState` accepts, and never throws. The\n * readback may be a NORMALISED form of what was set (a diagram-js\n * viewbox comes back rounded, with scale/inner/outer) — what must hold\n * is that setting a readback yields that readback again.\n * L6 EXPORT IS TOTAL AFTER IMPORT — after a successful import (and any\n * sequence of user commands and undos), `exportText` succeeds. Foreign or\n * auxiliary content the modeler does not understand is PRESERVED through\n * import → export (it comes back in the export, canonicalised like the\n * rest), never dropped and never a reason to throw.\n * L7 REJECTED IMPORTS LEAVE NO TRACE — `importText` on non-importable text\n * REJECTS (resolve-with-warnings means \"imported, with notes\"; rejection\n * means \"nothing imported\"). This holds for EVERY rejection, whatever\n * the input (a truncated or half-typed text included): afterwards the\n * previously imported document is still rendered with its elements,\n * `exportText` still returns it, no change event has fired and the undo\n * history is untouched.\n * The modeler stays USABLE: the next valid import renders, the next user\n * command applies. Hosts re-import half-typed peer text on every sync —\n * \"blank (or wedged) until healed\" is not an acceptable failure mode.\n *\n * View state is NEVER part of the document: `setViewState` fires no change\n * events and `exportText` is independent of it.\n */\nexport interface CollaborativeModeler {\n readonly meta: ModelerMeta;\n\n /** mount the canvas into a host element (once, before the first import).\n * The host must be attached to the document with a non-zero size — a\n * detached or 0×0 element gives diagram-js engines NaN viewboxes.\n * Calls made between mounting and the first import (`exportText()`, a\n * user command) return whatever the modeler defines, or throw (only\n * `getViewState` never does, L5), but they never wedge the instance:\n * the first `importText` still behaves exactly as specified */\n attachTo(host: Element): void;\n\n /** parse + render `text` — SILENT per L1, the view fitted to the content\n * per L5; resolves when rendered, REJECTS when nothing was imported (L7).\n * This holds for the first import too, whatever was called before it — a\n * host may export or route a command before its first document arrives */\n importText(text: string): Promise<ImportResult>;\n\n /** the canonical serialization of the current document (L2, L6) */\n exportText(): string;\n\n /** subscribe to user-visible model changes (L3); returns the unsubscribe */\n onContentChanged(cb: () => void): () => void;\n\n /** opaque viewport snapshot (zoom/scroll) — JSON-serializable (L5) */\n getViewState(): unknown;\n setViewState(state: unknown): void;\n\n readonly elements?: ElementsSurface;\n\n /** tear down DOM + listeners; further calls on the instance are undefined\n * behavior, but a second destroy() must not throw */\n destroy(): void;\n}\n"],"mappings":";AAqBO,IAAM,sBAAsB;","names":[]}