@jxsuite/schema 2.1.0 → 2.3.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/src/doc-ops.ts ADDED
@@ -0,0 +1,348 @@
1
+ /**
2
+ * The canonical Jx document-op vocabulary, its pure applier, and its inverse. A `JxDocOp` is a
3
+ * value-carrying, replayable mutation of a plain-JSON Jx document tree, addressed by `JxPath`
4
+ * (alternating "children" / index segments for structure, plus node keys). Studio's transaction
5
+ * pipeline records forward/inverse pairs of these for history replay; the collab bridge mirrors
6
+ * them into a shared Y.Doc.
7
+ *
8
+ * This module is deliberately yjs-free and imports types only: the slim canvas-iframe bundle
9
+ * imports the applier for its non-reactive shadow doc, and it MUST stay byte-identical in behavior
10
+ * to the parent's history replay — both sides import this one implementation. It lives in
11
+ * `@jxsuite/schema`, beside the document types, so any host can edit a document the way Studio does
12
+ * without taking yjs: a Durable Object, a headless tool, a test. `@jxsuite/collab/ops` re-exports
13
+ * it.
14
+ *
15
+ * @module @jxsuite/schema/doc-ops
16
+ */
17
+
18
+ import type { JxMutableNode, JxPath } from "../types.ts";
19
+
20
+ /** Value-carrying document mutation, replayable in either direction. */
21
+ export type JxDocOp =
22
+ /** Set (or delete, when value is undefined) a key on the node at path. */
23
+ | { op: "set-key"; path: JxPath; key: string; value?: unknown }
24
+ /** Insert a node at parentPath.children[index]. */
25
+ | { op: "insert-child"; parentPath: JxPath; index: number; node: unknown }
26
+ /** Remove parentPath.children[index]. */
27
+ | { op: "remove-child"; parentPath: JxPath; index: number }
28
+ /** Replace parentPath.children[index] with node. */
29
+ | { op: "set-child"; parentPath: JxPath; index: number; node: unknown }
30
+ /** Raw two-splice move: remove fromParent.children[fromIndex], insert at toParent[toIndex]. */
31
+ | {
32
+ op: "move-child";
33
+ fromParentPath: JxPath;
34
+ fromIndex: number;
35
+ toParentPath: JxPath;
36
+ toIndex: number;
37
+ };
38
+
39
+ export interface JxDocOpPair {
40
+ forward: JxDocOp;
41
+ inverse: JxDocOp;
42
+ }
43
+
44
+ /** JSON round-trip clone — also normalizes away reactive proxies / functions / undefined. */
45
+ function jsonClone<T>(value: T): T {
46
+ // oxlint-disable-next-line unicorn/prefer-structured-clone -- structuredClone throws on reactive proxies; JSON normalization is the point
47
+ return JSON.parse(JSON.stringify(value)) as T;
48
+ }
49
+
50
+ /** Deep-clone a recorded value (undefined/null pass through; reactive proxies are read through). */
51
+ export function cloneValue<T>(v: T): T {
52
+ return v === undefined || v === null ? v : (jsonClone(v as object) as T);
53
+ }
54
+
55
+ /**
56
+ * Walk a plain document tree by path. Paths address nodes by construction; missing segments and
57
+ * non-node leaves surface as undefined (typed as node for caller ergonomics, matching Studio's
58
+ * historical helper).
59
+ */
60
+ export function getNodeAtPath(doc: JxMutableNode, path: JxPath): JxMutableNode {
61
+ let node = doc;
62
+ for (const key of path) {
63
+ if (node == null) {
64
+ return undefined as unknown as JxMutableNode;
65
+ }
66
+ node = node[key] as JxMutableNode;
67
+ }
68
+ return node;
69
+ }
70
+
71
+ /** The node's children array, lazily created; throws if `node` is itself a children array or mapped. */
72
+ export function childArray(node: JxMutableNode): (JxMutableNode | string)[] {
73
+ // Defense-in-depth: a path that resolves to a children array (rather than a node) would
74
+ // Otherwise get a bogus `.children` property tacked on here, silently storing the insert where
75
+ // Nothing renders. Callers must pass a node; fail loudly if they don't.
76
+ if (Array.isArray(node)) {
77
+ throw new TypeError("Cannot insert into a children array; parentPath must point at a node");
78
+ }
79
+ if (!node.children) {
80
+ node.children = [];
81
+ }
82
+ if (!Array.isArray(node.children)) {
83
+ throw new TypeError("Cannot insert into mapped-array children; edit the map template instead");
84
+ }
85
+ return node.children;
86
+ }
87
+
88
+ /**
89
+ * Apply a replayable doc op to a bare document tree. Values/nodes are cloned in, so the tree never
90
+ * aliases the op object. Throws (with a machine-readable reason) when a target path is missing.
91
+ */
92
+ export function applyDocOpToDoc(doc: JxMutableNode, op: JxDocOp): void {
93
+ switch (op.op) {
94
+ case "set-key": {
95
+ const node = getNodeAtPath(doc, op.path);
96
+ if (!node) {
97
+ throw new Error(`doc-op-node-not-found:${op.path.join("/")}`);
98
+ }
99
+ const target = node as Record<string, unknown>;
100
+ if (op.value === undefined) {
101
+ delete target[op.key];
102
+ } else {
103
+ target[op.key] = cloneValue(op.value);
104
+ }
105
+ return;
106
+ }
107
+ case "insert-child": {
108
+ const parent = getNodeAtPath(doc, op.parentPath);
109
+ childArray(parent).splice(op.index, 0, cloneValue(op.node) as JxMutableNode);
110
+ return;
111
+ }
112
+ case "remove-child": {
113
+ const parent = getNodeAtPath(doc, op.parentPath);
114
+ childArray(parent).splice(op.index, 1);
115
+ return;
116
+ }
117
+ case "set-child": {
118
+ const parent = getNodeAtPath(doc, op.parentPath);
119
+ childArray(parent).splice(op.index, 1, cloneValue(op.node) as JxMutableNode);
120
+ return;
121
+ }
122
+ case "move-child": {
123
+ assertNotIntoOwnSubtree(op);
124
+ const fromParent = getNodeAtPath(doc, op.fromParentPath);
125
+ const toParent = getNodeAtPath(doc, op.toParentPath);
126
+ /* Both arrays are resolved BEFORE the source is spliced, so a move whose target cannot receive
127
+ children throws with the document untouched rather than having detached the node it could
128
+ not place. */
129
+ const from = childArray(fromParent);
130
+ const to = childArray(toParent);
131
+ const [node] = from.splice(op.fromIndex, 1);
132
+ to.splice(op.toIndex, 0, node!);
133
+ return;
134
+ }
135
+ default: {
136
+ break;
137
+ }
138
+ }
139
+ throw new Error(`unknown-doc-op:${(op as JxDocOp).op}`);
140
+ }
141
+
142
+ /**
143
+ * Translate `path` into post-splice coordinates when it descends through `parentPath`'s children at
144
+ * or beyond the spliced index: a removal (delta -1) at the index shifts deeper paths down; an
145
+ * insertion (delta +1, inclusive) shifts them up. Returns `path` unchanged when the splice does not
146
+ * affect it — including when `path` IS `parentPath`, since a splice moves a node's children, never
147
+ * the node.
148
+ */
149
+ function shiftThroughSplice(
150
+ parentPath: JxPath,
151
+ path: JxPath,
152
+ spliceIndex: number,
153
+ delta: number,
154
+ inclusive: boolean,
155
+ ): JxPath {
156
+ const depth = parentPath.length;
157
+ const isProperPrefix = depth < path.length && parentPath.every((seg, i) => seg === path[i]);
158
+ if (!isProperPrefix || path[depth] !== "children" || typeof path[depth + 1] !== "number") {
159
+ return path;
160
+ }
161
+ const index = path[depth + 1] as number;
162
+ if (inclusive ? index < spliceIndex : index <= spliceIndex) {
163
+ return path;
164
+ }
165
+ const shifted = [...path];
166
+ shifted[depth + 1] = index + delta;
167
+ return shifted;
168
+ }
169
+
170
+ /**
171
+ * Refuse a move into the moved node itself or into its own subtree. Splicing the node out first
172
+ * would detach the very parent the insert was to land in, so the subtree would vanish and no
173
+ * inverse could bring it back.
174
+ */
175
+ function assertNotIntoOwnSubtree(op: Extract<JxDocOp, { op: "move-child" }>): void {
176
+ const moved = [...op.fromParentPath, "children", op.fromIndex];
177
+ const target = op.toParentPath;
178
+ if (target.length >= moved.length && moved.every((seg, i) => seg === target[i])) {
179
+ throw new Error(`doc-op-move-into-self:${target.join("/")}`);
180
+ }
181
+ }
182
+
183
+ /**
184
+ * The index a `splice(index, 0, …)` into `length` elements actually inserts at: a negative index
185
+ * counts from the end and an index past the end appends. The applier inserts with `splice`, so an
186
+ * inverse must name the slot the node really landed in, not the one the op asked for.
187
+ */
188
+ function insertionSlot(index: number, length: number): number {
189
+ return index < 0 ? Math.max(length + index, 0) : Math.min(index, length);
190
+ }
191
+
192
+ /**
193
+ * The op that undoes `op`, computed against `doc` as it stands BEFORE `op` is applied.
194
+ *
195
+ * Every inverse is expressed in the coordinates of the document after `op` ran, because that is the
196
+ * document it will be applied to. For four kinds that is the op's own coordinates. `move-child` is
197
+ * the one that is not: removing the node shifts every sibling path after it under the source
198
+ * parent, and inserting it shifts every sibling path at or after the target index under the
199
+ * destination parent, so each parent path of the inverse is translated through the other splice.
200
+ * The rule is the one Studio's own move has always recorded.
201
+ *
202
+ * **One residue is not undone, deliberately.** Inserting or moving a node into a parent with no
203
+ * `children` creates the array (the applier's `childArray` does), and undoing it removes the node
204
+ * but leaves `children: []`. A single op cannot both move a node back and delete a key, and
205
+ * Studio's own history has always recorded exactly these inverses, so matching it is the contract;
206
+ * an empty `children` array renders as nothing and validates as the absent key does.
207
+ *
208
+ * An index the applier would clamp (`splice` appends past the end and counts a negative index from
209
+ * it) is recorded as the slot the node actually lands in.
210
+ *
211
+ * Throws when the op cannot be applied: its target does not resolve, an insert or move targets
212
+ * something that cannot hold children, or a move targets the moved node's own subtree. An op that
213
+ * cannot be applied has nothing to undo, and a caller that computed an inverse for it would record
214
+ * a history entry for an edit that never happened.
215
+ *
216
+ * @param {JxMutableNode} doc - The document the op is about to be applied to
217
+ * @param {JxDocOp} op
218
+ * @returns {JxDocOp}
219
+ */
220
+ export function inverseOf(doc: JxMutableNode, op: JxDocOp): JxDocOp {
221
+ switch (op.op) {
222
+ case "set-key": {
223
+ const node = getNodeAtPath(doc, op.path);
224
+ if (!node) {
225
+ throw new Error(`doc-op-node-not-found:${op.path.join("/")}`);
226
+ }
227
+ const before = cloneValue((node as Record<string, unknown>)[op.key]);
228
+ return before === undefined
229
+ ? { key: op.key, op: "set-key", path: op.path }
230
+ : { key: op.key, op: "set-key", path: op.path, value: before };
231
+ }
232
+ case "insert-child": {
233
+ const { length } = insertableChildren(doc, op.parentPath);
234
+ return {
235
+ index: insertionSlot(op.index, length),
236
+ op: "remove-child",
237
+ parentPath: op.parentPath,
238
+ };
239
+ }
240
+ case "remove-child": {
241
+ const removed = existingChild(doc, op.parentPath, op.index);
242
+ return { index: op.index, node: removed, op: "insert-child", parentPath: op.parentPath };
243
+ }
244
+ case "set-child": {
245
+ const replaced = existingChild(doc, op.parentPath, op.index);
246
+ return { index: op.index, node: replaced, op: "set-child", parentPath: op.parentPath };
247
+ }
248
+ case "move-child": {
249
+ assertNotIntoOwnSubtree(op);
250
+ const source = childrenAt(doc, op.fromParentPath);
251
+ assertIndex(source, op.fromParentPath, op.fromIndex);
252
+ const target = insertableChildren(doc, op.toParentPath);
253
+ // The target's length after the removal: the same array when the move stays in one parent.
254
+ const toIndex = insertionSlot(op.toIndex, target.length - (target === source ? 1 : 0));
255
+ return {
256
+ fromIndex: toIndex,
257
+ // The removal shifted paths under the source parent; the insertion, under the target.
258
+ fromParentPath: shiftThroughSplice(
259
+ op.fromParentPath,
260
+ op.toParentPath,
261
+ op.fromIndex,
262
+ -1,
263
+ false,
264
+ ),
265
+ op: "move-child",
266
+ toIndex: op.fromIndex,
267
+ toParentPath: shiftThroughSplice(op.toParentPath, op.fromParentPath, toIndex, 1, true),
268
+ };
269
+ }
270
+ default: {
271
+ break;
272
+ }
273
+ }
274
+ throw new Error(`unknown-doc-op:${(op as JxDocOp).op}`);
275
+ }
276
+
277
+ /** The node's existing children array, or null when it has none (or is not a node). */
278
+ function childrenAt(doc: JxMutableNode, parentPath: JxPath): (JxMutableNode | string)[] | null {
279
+ const parent = getNodeAtPath(doc, parentPath);
280
+ return parent && Array.isArray(parent.children) ? parent.children : null;
281
+ }
282
+
283
+ /** Throw the applier's reason unless `children` holds an element at `index`. */
284
+ function assertIndex(
285
+ children: (JxMutableNode | string)[] | null,
286
+ parentPath: JxPath,
287
+ index: number,
288
+ ): asserts children is (JxMutableNode | string)[] {
289
+ if (!children || index < 0 || index >= children.length) {
290
+ throw new Error(`doc-op-node-not-found:${[...parentPath, "children", index].join("/")}`);
291
+ }
292
+ }
293
+
294
+ /** A clone of `parentPath`'s child at `index`, or the applier's reason when there is none. */
295
+ function existingChild(doc: JxMutableNode, parentPath: JxPath, index: number): unknown {
296
+ const children = childrenAt(doc, parentPath);
297
+ assertIndex(children, parentPath, index);
298
+ return cloneValue(children[index]);
299
+ }
300
+
301
+ /**
302
+ * The children array an insert into `parentPath` lands in — an empty stand-in when the node has no
303
+ * `children` yet, since the applier creates one — or the reason it cannot land: no node there, a
304
+ * children array addressed as if it were a node, or a mapped-array `children`.
305
+ */
306
+ function insertableChildren(doc: JxMutableNode, parentPath: JxPath): (JxMutableNode | string)[] {
307
+ const node = getNodeAtPath(doc, parentPath) as unknown as { children?: unknown } | null;
308
+ if (!node || typeof node !== "object" || Array.isArray(node)) {
309
+ throw new Error(`doc-op-node-not-found:${parentPath.join("/")}`);
310
+ }
311
+ if (node.children === undefined) {
312
+ return [];
313
+ }
314
+ if (!Array.isArray(node.children)) {
315
+ throw new TypeError(`doc-op-mapped-children:${parentPath.join("/")}`);
316
+ }
317
+ return node.children as (JxMutableNode | string)[];
318
+ }
319
+
320
+ /**
321
+ * Apply `ops` to `doc` in order, answering the forward/inverse pair for each — the record a history
322
+ * entry, an undo stack or a journal needs. Each inverse is computed against the document as it
323
+ * stands just before its own op, so a sequence whose later ops address what earlier ones created is
324
+ * recorded correctly. Undo applies the inverses in REVERSE order.
325
+ *
326
+ * Stops at the first op that does not apply and rethrows its reason; the ops before it have been
327
+ * applied, and their pairs are on the error as `applied`, so a caller can roll them back.
328
+ *
329
+ * @param {JxMutableNode} doc
330
+ * @param {readonly JxDocOp[]} ops
331
+ * @returns {JxDocOpPair[]}
332
+ */
333
+ export function applyDocOpsWithInverse(doc: JxMutableNode, ops: readonly JxDocOp[]): JxDocOpPair[] {
334
+ const pairs: JxDocOpPair[] = [];
335
+ for (const forward of ops) {
336
+ let inverse: JxDocOp;
337
+ try {
338
+ inverse = inverseOf(doc, forward);
339
+ applyDocOpToDoc(doc, forward);
340
+ } catch (error) {
341
+ throw Object.assign(error instanceof Error ? error : new Error(String(error)), {
342
+ applied: pairs,
343
+ });
344
+ }
345
+ pairs.push({ forward, inverse });
346
+ }
347
+ return pairs;
348
+ }
package/src/guards.ts CHANGED
@@ -192,9 +192,17 @@ export function bodyReturnsValue(body: string): boolean {
192
192
 
193
193
  // ─── Style guards & accessors ───────────────────────────────────────────────────
194
194
 
195
- /** A nested style object (selector/media block), as opposed to a scalar CSS value. */
196
- export function isNestedStyle(value: string | number | JxStyle | undefined): value is JxStyle {
197
- return typeof value === "object" && value !== null;
195
+ /**
196
+ * A nested style object (selector/media block), as opposed to a scalar CSS value.
197
+ *
198
+ * An ARRAY of blocks is not one: it is a key written more than once (`@font-face`, spec.md §9.4),
199
+ * and every caller here reads or edits a single block. Answering true for it would hand a caller an
200
+ * array to look properties up on, which finds nothing and reports nothing.
201
+ */
202
+ export function isNestedStyle(
203
+ value: string | number | JxStyle | JxStyle[] | undefined,
204
+ ): value is JxStyle {
205
+ return typeof value === "object" && value !== null && !Array.isArray(value);
198
206
  }
199
207
 
200
208
  /** Read a nested style block (`:hover`, `@--md`, `& > li`, …), if present. */
@@ -243,9 +251,39 @@ export function paramNames(parameters: JxFunctionDef["parameters"]): string[] {
243
251
  return parameters.map((p) => (typeof p === "string" ? p : p.name));
244
252
  }
245
253
 
246
- /** Whether an element's `tagName` is a choice rather than a name. */
254
+ /**
255
+ * Whether an element's `tagName` is a choice rather than a name.
256
+ *
257
+ * **It reads the WHOLE shape, because it promises the whole shape.**
258
+ * `defs/tag-expression.schema.ts` admits exactly two forms — `?:` with a `TagName` in `value` and
259
+ * `initial`, and `switch` with a `TagName` per case and a required `default` — and this predicate
260
+ * is the only thing standing between that promise and the four readers who trust it
261
+ * ({@link tagNameCandidates}, the runtime's `resolveTagName`, the compiler's `resolveStaticTagName`
262
+ * and its two target emitters). Answering `true` for any `{ $expression: … }` at all was the
263
+ * unsound half: a general formula in tag position — which the Inspector's Tag row let a user pick
264
+ * out of the formula catalog — then reached `Object.values(expression.cases)` with no `cases` to
265
+ * read, and `Cannot convert undefined or null to object` came out of the Command Bar, the jump bar,
266
+ * the Inspector and the canvas renderer at once.
267
+ *
268
+ * A `$expression` this refuses is not a tag choice, so it has no candidates and no static tag; the
269
+ * readers fall back to their own "nothing declared" answer (`[]`, `"div"`) instead of throwing.
270
+ */
247
271
  export function isTagExpression(tagName: unknown): tagName is { $expression: JxTagExpression } {
248
- return isJsonObject(tagName) && isJsonObject(tagName.$expression);
272
+ if (!isJsonObject(tagName) || !isJsonObject(tagName.$expression)) {
273
+ return false;
274
+ }
275
+ const expression = tagName.$expression;
276
+ if (expression.operator === "?:") {
277
+ return typeof expression.value === "string" && typeof expression.initial === "string";
278
+ }
279
+ if (expression.operator === "switch") {
280
+ return (
281
+ isJsonObject(expression.cases) &&
282
+ Object.values(expression.cases).every((tag) => typeof tag === "string") &&
283
+ typeof expression.default === "string"
284
+ );
285
+ }
286
+ return false;
249
287
  }
250
288
 
251
289
  /**