asma-core-helpers 0.30.0 → 0.32.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.
Files changed (42) hide show
  1. package/lib/collaboration/applyOperation.d.ts +33 -1
  2. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  3. package/lib/collaboration/applyOperation.js +633 -9
  4. package/lib/collaboration/applyOperation.js.map +1 -1
  5. package/lib/collaboration/operations.d.ts +109 -2
  6. package/lib/collaboration/operations.d.ts.map +1 -1
  7. package/lib/collaboration/operations.js +7 -0
  8. package/lib/collaboration/operations.js.map +1 -1
  9. package/lib/collaboration/schemas.d.ts +163 -0
  10. package/lib/collaboration/schemas.d.ts.map +1 -1
  11. package/lib/collaboration/schemas.js +173 -3
  12. package/lib/collaboration/schemas.js.map +1 -1
  13. package/lib/collaboration/templateDocument.d.ts +176 -0
  14. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  15. package/lib/collaboration/templateDocument.js +9 -0
  16. package/lib/collaboration/templateDocument.js.map +1 -1
  17. package/lib/collaboration/testHelpers/documentGenerator.js +78 -1
  18. package/lib/collaboration/testHelpers/documentGenerator.js.map +1 -1
  19. package/lib/collaboration/typeContracts.d.ts +53 -0
  20. package/lib/collaboration/typeContracts.d.ts.map +1 -0
  21. package/lib/collaboration/typeContracts.js +2 -0
  22. package/lib/collaboration/typeContracts.js.map +1 -0
  23. package/lib/validation/index.d.ts +1 -1
  24. package/lib/validation/index.d.ts.map +1 -1
  25. package/lib/validation/index.js +1 -1
  26. package/lib/validation/index.js.map +1 -1
  27. package/lib/validation/rules.d.ts +4 -0
  28. package/lib/validation/rules.d.ts.map +1 -1
  29. package/lib/validation/rules.js +18 -1
  30. package/lib/validation/rules.js.map +1 -1
  31. package/package.json +1 -1
  32. package/src/collaboration/applyOperation.ts +736 -9
  33. package/src/collaboration/operations.ts +97 -0
  34. package/src/collaboration/schemas.ts +191 -1
  35. package/src/collaboration/templateDocument.ts +167 -1
  36. package/src/collaboration/testHelpers/documentGenerator.ts +77 -1
  37. package/src/collaboration/typeContracts.ts +57 -0
  38. package/src/collaboration/typedAuthoring.test.ts +641 -0
  39. package/src/collaboration/typedAuthoringHardening.test.ts +408 -0
  40. package/src/validation/index.ts +15 -1
  41. package/src/validation/rules.test.ts +106 -1
  42. package/src/validation/rules.ts +25 -1
@@ -1,4 +1,7 @@
1
- import { BINDING_OPTION_DEFAULTS, bindingTargetKey } from './templateDocument.js';
1
+ import { ACTION_TYPES, BINDING_OPTION_DEFAULTS, MAPPING_FILTER_OPERATORS, bindingTargetKey, isKnownActionKind, } from './templateDocument.js';
2
+ /** Runtime narrowing for the two closed vocabularies the reducer must re-check on replay. */
3
+ const isActionType = (value) => typeof value === 'string' && ACTION_TYPES.includes(value);
4
+ const isDocScalarValue = (value) => typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';
2
5
  /** The behaviour members, so the write loop cannot silently miss one that `BINDING_OPTION_DEFAULTS` gains. */
3
6
  const BINDING_OPTION_KEYS = Object.keys(BINDING_OPTION_DEFAULTS);
4
7
  /**
@@ -112,6 +115,362 @@ const writeBindingOptions = (binding, options) => {
112
115
  }
113
116
  return next;
114
117
  };
118
+ /**
119
+ * Adds, moves or removes ONE member of an ordered primitive id list.
120
+ *
121
+ * The member-wise discipline three ops share, and the reason they are ops at all rather than whole-list
122
+ * writes: JSON Merge Patch replaces an array wholesale, so two authors adding different ids would
123
+ * produce two patches and the second would silently discard the first with no conflict raised. Editing
124
+ * the *current* list one member at a time makes both edits survive — the same argument DOC-LAW-1 makes
125
+ * for keying collections by id.
126
+ *
127
+ * `include: true` inserts at `atIndex` (else appends) and **moves** an id already present when an
128
+ * `atIndex` is supplied; omitting `atIndex` for an id already present is a no-op rather than a
129
+ * duplicate. `include: false` removes it.
130
+ */
131
+ const setListMember = (list, id, include, atIndex) => {
132
+ if (!include)
133
+ return list.filter((member) => member !== id);
134
+ const without = list.filter((member) => member !== id);
135
+ if (atIndex === undefined)
136
+ return list.includes(id) ? [...list] : [...without, id];
137
+ const at = Math.max(0, Math.min(atIndex, without.length));
138
+ return [...without.slice(0, at), id, ...without.slice(at)];
139
+ };
140
+ /** Writes a grid question's presentation back in minimal form, dropping every emptied container. */
141
+ const writeGridPresentation = (doc, questionId, question, presentation) => {
142
+ const nextQuestion = { ...question };
143
+ if (Object.keys(presentation).length === 0)
144
+ delete nextQuestion.presentation;
145
+ else
146
+ nextQuestion.presentation = presentation;
147
+ return { ...doc, questionsById: { ...doc.questionsById, [questionId]: nextQuestion } };
148
+ };
149
+ /** Sets or clears one of a grid presentation's ordered id lists, omitting it when emptied (DOC-LAW-2). */
150
+ const writePresentationList = (presentation, key, next) => {
151
+ const copy = { ...presentation };
152
+ if (next.length === 0)
153
+ delete copy[key];
154
+ else
155
+ copy[key] = [...next];
156
+ return copy;
157
+ };
158
+ const presentationListOf = (question, key) => {
159
+ const value = (question.presentation ?? {})[key];
160
+ return Array.isArray(value) ? value.filter((member) => typeof member === 'string') : [];
161
+ };
162
+ /** Every grid presentation that lists `actionId`, so a grid action can have at most one owner. */
163
+ const gridsOwningAction = (doc, actionId) => Object.entries(doc.questionsById ?? {})
164
+ .filter(([, question]) => presentationListOf(question, 'actionIds').includes(actionId))
165
+ .map(([questionId]) => questionId);
166
+ /**
167
+ * The action, if it is a KNOWN one — `kind` inside the closed vocabulary.
168
+ *
169
+ * A legacy record with an unknown `kind` is not "known but unrecognised": the typed ops refuse it
170
+ * outright rather than half-applying rules written for a different shape, which is what keeps old
171
+ * documents replaying byte-identically.
172
+ */
173
+ /**
174
+ * Why `field` may not be written as an ordinary tab field edit, or `undefined` if it may.
175
+ *
176
+ * `layout.placementsByQuestionId` is reserved for `tab.setLayout`. Unlike the grid's filter list this
177
+ * one is not even expressible as an `OpValue` — a placement is an object — so the realistic misuse is a
178
+ * write to an ANCESTOR (`layout`, or the placements map cleared wholesale), which would drop every other
179
+ * question's placement in one edit. Both directions of overlap are refused; `label` and any other
180
+ * authored scalar stay ordinary field edits.
181
+ */
182
+ export const tabFieldPathRefusal = (field) => {
183
+ const reserved = 'layout.placementsByQuestionId';
184
+ if (field === reserved || field.startsWith(`${reserved}.`) || reserved.startsWith(`${field}.`)) {
185
+ return `Field "${field}" writes "${reserved}", which only tab.setLayout may author`;
186
+ }
187
+ return undefined;
188
+ };
189
+ /**
190
+ * Validates a `mappingFilter.setTyped` payload in the REDUCER, not only at the wire.
191
+ *
192
+ * The wire schema is the primary gate, but it is not the only path into this reducer: bunjs replays a
193
+ * stored `collab_ops` log without re-validating each op, so an op written by an older or bypassed
194
+ * client arrives here unchecked. Before this, that path accepted an empty `in`, a `range` with no
195
+ * bound, a non-boolean `isNull`, and — worst — an UNKNOWN operator, which fell through the
196
+ * `eq`/`in`/`isNull` tests into the `range` branch and was silently stored as a boundless range.
197
+ * A filter nothing can evaluate then rode into a compiled artifact that is immutable forever.
198
+ *
199
+ * Mirrors the wire schema exactly: closed operator, that operator's members present and correctly
200
+ * typed, and no member belonging to another operator.
201
+ */
202
+ const assertTypedFilterPayload = (op) => {
203
+ if (!MAPPING_FILTER_OPERATORS.includes(op.operator)) {
204
+ throw new OperationConflictError(`"${op.operator}" is not a typed filter operator (${MAPPING_FILTER_OPERATORS.join(' | ')}); use mappingFilter.set for a legacy operator`);
205
+ }
206
+ // Stale members first: a payload carrying another operator's members is ambiguous whatever else is
207
+ // right about it, and the canonical replace would silently drop them rather than refuse.
208
+ const present = ['value', 'values', 'from', 'to'].filter((member) => op[member] !== undefined);
209
+ const allowed = {
210
+ eq: ['value'],
211
+ in: ['values'],
212
+ range: ['from', 'to'],
213
+ isNull: ['value'],
214
+ };
215
+ const stale = present.filter((member) => !(allowed[op.operator] ?? []).includes(member));
216
+ if (stale.length > 0) {
217
+ throw new OperationConflictError(`Operator "${op.operator}" does not carry ${stale.join(', ')}`);
218
+ }
219
+ if (op.operator === 'eq') {
220
+ if (!isDocScalarValue(op.value))
221
+ throw new OperationConflictError('Operator "eq" requires a scalar value');
222
+ return;
223
+ }
224
+ if (op.operator === 'isNull') {
225
+ if (typeof op.value !== 'boolean') {
226
+ throw new OperationConflictError('Operator "isNull" requires a boolean value');
227
+ }
228
+ return;
229
+ }
230
+ if (op.operator === 'in') {
231
+ if (!Array.isArray(op.values) || op.values.length === 0) {
232
+ throw new OperationConflictError('Operator "in" requires a non-empty list');
233
+ }
234
+ if (!op.values.every(isDocScalarValue)) {
235
+ throw new OperationConflictError('Operator "in" requires every member to be a scalar');
236
+ }
237
+ return;
238
+ }
239
+ // range: at least one bound, and every bound present must be a scalar.
240
+ if (op.from === undefined && op.to === undefined) {
241
+ throw new OperationConflictError('Operator "range" requires at least one of "from"/"to"');
242
+ }
243
+ for (const bound of ['from', 'to']) {
244
+ if (op[bound] !== undefined && !isDocScalarValue(op[bound])) {
245
+ throw new OperationConflictError(`Operator "range" requires "${bound}" to be a scalar`);
246
+ }
247
+ }
248
+ };
249
+ /** UI edit buffers, in both spellings. Rejected on known kinds by the whitelist below. */
250
+ const ACTION_UI_BUFFERS = ['editableLabel', 'editableType', 'editable_label', 'editable_type'];
251
+ /**
252
+ * The ONLY fields `action.updateField` may write on a KNOWN action: `label` on either kind, and
253
+ * `actionType` on a `gridAction`.
254
+ *
255
+ * **A whitelist, not a blacklist, and that is the repair.** The first version enumerated what was
256
+ * forbidden — `kind`, the UI buffers, the two keyed collections — which meant `arbitraryField` and every
257
+ * other unlisted name sailed through and persisted. A known action's shape is closed by definition, so
258
+ * the safe default is refusal: anything not named here is not part of the typed vocabulary, and
259
+ * admitting it would turn a typed record back into the broad legacy bag the closed kinds exist to
260
+ * replace. `QnrAction` stays open for LEGACY records precisely so this can be strict.
261
+ *
262
+ * The listed names still carry their own reasons for being writable or not:
263
+ *
264
+ * - **`kind` is write-once.** It selects which rules apply, so changing it reinterprets every member
265
+ * already stored under the old kind.
266
+ * - **UI edit buffers are not document content** (`editable_label`/`editable_type`), so authoring them
267
+ * would mint a version for a designer-side checkbox.
268
+ * - **The two keyed collections are reserved** for `action.setGridActionRef` / `action.setMetadata`,
269
+ * which edit them one member at a time; a field write replaces a map wholesale.
270
+ */
271
+ const KNOWN_ACTION_WRITABLE_FIELDS = {
272
+ topLevelAction: ['label'],
273
+ gridAction: ['label', 'actionType'],
274
+ };
275
+ /** The collections only the typed member-wise ops may author — named for the refusal message. */
276
+ const ACTION_OWNED_FIELD_PATHS = ['actionIdsByGridQuestionId', 'metadataByQuestionId'];
277
+ /**
278
+ * Why `field` may not be written on a KNOWN action, or `undefined` if it may.
279
+ *
280
+ * Applies to known kinds only: a legacy record keeps taking any field, buffers included, because that
281
+ * is what makes an already-stored action replay byte-identically (ADR-0008 DEC-006).
282
+ */
283
+ export const knownActionFieldRefusal = (kind, field) => {
284
+ const writable = KNOWN_ACTION_WRITABLE_FIELDS[kind];
285
+ if (writable.includes(field))
286
+ return undefined;
287
+ // The specific messages first, so the reason a caller reads names their actual mistake rather than
288
+ // "not writable" for a field that is writable on the other kind, or reserved for a dedicated op.
289
+ if (field === 'kind' || field.startsWith('kind.')) {
290
+ return 'Field "kind" is write-once on a known action; create a new action instead';
291
+ }
292
+ if (ACTION_UI_BUFFERS.some((buffer) => field === buffer || field.startsWith(`${buffer}.`))) {
293
+ return `Field "${field}" is a UI edit buffer, not document content`;
294
+ }
295
+ if (field === 'actionType' || field.startsWith('actionType.')) {
296
+ return `Field "actionType" belongs to a gridAction, not a ${kind}`;
297
+ }
298
+ const owned = ACTION_OWNED_FIELD_PATHS.find((path) => field === path || field.startsWith(`${path}.`) || path.startsWith(`${field}.`));
299
+ if (owned !== undefined) {
300
+ return `Field "${field}" writes "${owned}", which only the typed action operations may author`;
301
+ }
302
+ return `Field "${field}" is not part of the ${kind} vocabulary (writable: ${writable.join(', ')})`;
303
+ };
304
+ /**
305
+ * Why `value` may not be written to a permitted known-action field, or `undefined` if it may.
306
+ *
307
+ * The whitelist alone would still let `actionType: 'DELETE'` or a numeric `label` through, turning a
308
+ * typed record into a malformed one that every downstream reader has to re-check. `null` is the explicit
309
+ * unset the op layer carries, so it is legal for both.
310
+ */
311
+ export const knownActionValueRefusal = (field, value) => {
312
+ if (value === null)
313
+ return undefined;
314
+ if (field === 'label' && typeof value !== 'string') {
315
+ return `Field "label" takes a string, not ${typeof value}`;
316
+ }
317
+ if (field === 'actionType' && !isActionType(value)) {
318
+ return `"${String(value)}" is not a valid actionType (${ACTION_TYPES.join(' | ')})`;
319
+ }
320
+ return undefined;
321
+ };
322
+ const requireKnownAction = (doc, actionId, kind) => {
323
+ const action = doc.actionsById?.[actionId];
324
+ if (!action)
325
+ throw new OperationConflictError(`Unknown action "${actionId}"`);
326
+ if (!isKnownActionKind(action.kind)) {
327
+ throw new OperationConflictError(`Action "${actionId}" is a legacy record (kind "${String(action.kind)}"); the typed operations only author known kinds`);
328
+ }
329
+ if (action.kind !== kind) {
330
+ throw new OperationConflictError(`Action "${actionId}" is a ${action.kind}, not a ${kind}`);
331
+ }
332
+ return action;
333
+ };
334
+ /**
335
+ * Canonicalizes one metadata entry, refusing the two shapes DOC-LAW-2 makes ambiguous.
336
+ *
337
+ * `{all: true}` is the all-to-all marker and is exclusive with bounds: legacy writes all-to-all as
338
+ * `from: null, to: null`, and since a document may carry neither a null nor an empty object, "selected
339
+ * but unbounded" and "not selected" would otherwise be the same absence.
340
+ */
341
+ const canonicalActionMetadata = (metadata) => {
342
+ const record = metadata;
343
+ const hasAll = record['all'] === true;
344
+ const hasFrom = record['from'] !== undefined;
345
+ const hasTo = record['to'] !== undefined;
346
+ if (hasAll && (hasFrom || hasTo)) {
347
+ throw new OperationConflictError('Action metadata "all" is exclusive with "from"/"to"');
348
+ }
349
+ if (hasAll)
350
+ return { all: true };
351
+ if (!hasFrom && !hasTo) {
352
+ throw new OperationConflictError('Action metadata must select something: "all", "from" and/or "to"');
353
+ }
354
+ return {
355
+ ...(hasFrom ? { from: record['from'] } : {}),
356
+ ...(hasTo ? { to: record['to'] } : {}),
357
+ };
358
+ };
359
+ /**
360
+ * Drops every top-level reference to one of a grid's actions.
361
+ *
362
+ * A `topLevelAction` entry means "run this GRID's action", so when the grid stops owning the action the
363
+ * reference stops being expressible at the same moment — leaving it would compile into a button that
364
+ * runs nothing. Emptied sequences drop their grid key and an emptied map is omitted (DOC-LAW-2).
365
+ */
366
+ const scrubGridActionRefs = (doc, gridQuestionId, gridActionId) => {
367
+ const actions = Object.entries(doc.actionsById ?? {});
368
+ if (actions.length === 0)
369
+ return doc;
370
+ let changed = false;
371
+ const nextActions = Object.fromEntries(actions.map(([actionId, action]) => {
372
+ const byGrid = (action['actionIdsByGridQuestionId'] ?? {});
373
+ const sequence = byGrid[gridQuestionId];
374
+ if (!Array.isArray(sequence) || !sequence.includes(gridActionId))
375
+ return [actionId, action];
376
+ changed = true;
377
+ const remaining = sequence.filter((id) => id !== gridActionId);
378
+ const nextByGrid = { ...byGrid };
379
+ if (remaining.length === 0)
380
+ delete nextByGrid[gridQuestionId];
381
+ else
382
+ nextByGrid[gridQuestionId] = remaining;
383
+ const nextAction = { ...action };
384
+ if (Object.keys(nextByGrid).length === 0)
385
+ delete nextAction['actionIdsByGridQuestionId'];
386
+ else
387
+ nextAction['actionIdsByGridQuestionId'] = nextByGrid;
388
+ return [actionId, nextAction];
389
+ }));
390
+ return changed ? { ...doc, actionsById: nextActions } : doc;
391
+ };
392
+ /** Drops a deleted question's placement from every tab layout, and every emptied container with it. */
393
+ const scrubTabPlacements = (doc, questionId) => {
394
+ const tabs = Object.entries(doc.tabsById ?? {});
395
+ if (tabs.length === 0)
396
+ return doc;
397
+ let changed = false;
398
+ const nextTabs = Object.fromEntries(tabs.map(([tabId, tab]) => {
399
+ const layout = (tab.layout ?? {});
400
+ const placements = (layout['placementsByQuestionId'] ?? {});
401
+ if (placements[questionId] === undefined)
402
+ return [tabId, tab];
403
+ changed = true;
404
+ const nextPlacements = omitKey(placements, questionId);
405
+ const nextLayout = { ...layout };
406
+ if (Object.keys(nextPlacements).length === 0)
407
+ delete nextLayout['placementsByQuestionId'];
408
+ else
409
+ nextLayout['placementsByQuestionId'] = nextPlacements;
410
+ const nextTab = { ...tab };
411
+ if (Object.keys(nextLayout).length === 0)
412
+ delete nextTab.layout;
413
+ else
414
+ nextTab.layout = nextLayout;
415
+ return [tabId, nextTab];
416
+ }));
417
+ return changed ? { ...doc, tabsById: nextTabs } : doc;
418
+ };
419
+ /** Drops a deleted tab from every grid that named it as its header. */
420
+ const scrubHeaderTabRefs = (doc, tabId) => {
421
+ const questions = Object.entries(doc.questionsById ?? {});
422
+ let changed = false;
423
+ const nextQuestions = Object.fromEntries(questions.map(([questionId, question]) => {
424
+ if (question.presentation?.headerTabId !== tabId)
425
+ return [questionId, question];
426
+ changed = true;
427
+ const presentation = { ...question.presentation };
428
+ delete presentation.headerTabId;
429
+ const nextQuestion = { ...question };
430
+ if (Object.keys(presentation).length === 0)
431
+ delete nextQuestion.presentation;
432
+ else
433
+ nextQuestion.presentation = presentation;
434
+ return [questionId, nextQuestion];
435
+ }));
436
+ return changed ? { ...doc, questionsById: nextQuestions } : doc;
437
+ };
438
+ /** Drops a deleted action from every grid presentation and every top-level sequence naming it. */
439
+ const scrubActionRefs = (doc, actionId) => {
440
+ let next = doc;
441
+ for (const gridQuestionId of gridsOwningAction(doc, actionId)) {
442
+ const grid = next.questionsById?.[gridQuestionId];
443
+ if (!grid)
444
+ continue;
445
+ const presentation = writePresentationList({ ...(grid.presentation ?? {}) }, 'actionIds', presentationListOf(grid, 'actionIds').filter((id) => id !== actionId));
446
+ next = writeGridPresentation(next, gridQuestionId, grid, presentation);
447
+ next = scrubGridActionRefs(next, gridQuestionId, actionId);
448
+ }
449
+ // A top-level action can also be deleted while still referenced by nothing of its own; and a grid
450
+ // action may be referenced under a grid that no longer owns it, so sweep every sequence by value.
451
+ const actions = Object.entries(next.actionsById ?? {});
452
+ let changed = false;
453
+ const nextActions = Object.fromEntries(actions.map(([id, action]) => {
454
+ const byGrid = (action['actionIdsByGridQuestionId'] ?? {});
455
+ const entries = Object.entries(byGrid);
456
+ if (entries.length === 0)
457
+ return [id, action];
458
+ const rebuilt = entries
459
+ .map(([gridId, sequence]) => [gridId, sequence.filter((member) => member !== actionId)])
460
+ .filter(([, sequence]) => sequence.length > 0);
461
+ if (rebuilt.length === entries.length && rebuilt.every(([, seq], index) => seq.length === (entries[index]?.[1].length ?? 0))) {
462
+ return [id, action];
463
+ }
464
+ changed = true;
465
+ const nextAction = { ...action };
466
+ if (rebuilt.length === 0)
467
+ delete nextAction['actionIdsByGridQuestionId'];
468
+ else
469
+ nextAction['actionIdsByGridQuestionId'] = Object.fromEntries(rebuilt.map(([g, seq]) => [g, [...seq]]));
470
+ return [id, nextAction];
471
+ }));
472
+ return changed ? { ...next, actionsById: nextActions } : next;
473
+ };
115
474
  const omitKey = (record, key) => {
116
475
  const { [key]: _removed, ...rest } = record;
117
476
  return rest;
@@ -127,7 +486,16 @@ const omitKey = (record, key) => {
127
486
  * owned by nobody, or every other column's placement dropped in one edit. That is precisely
128
487
  * the atomicity the grid ops exist to provide, so the paths are reserved for them.
129
488
  */
130
- const GRID_OWNED_FIELD_PATHS = ['grid.columnIds', 'presentation.rowEditor.layoutByQuestionId'];
489
+ const GRID_OWNED_FIELD_PATHS = [
490
+ 'grid.columnIds',
491
+ 'presentation.rowEditor.layoutByQuestionId',
492
+ // Maintained member-wise by `gridColumn.setFilter` / `gridColumn.setAction`. An `OpValue` can carry
493
+ // a primitive array, so unlike the layout map these two are *expressible* as a field edit — which is
494
+ // exactly why they must be reserved: a wholesale write is the lost-update the member-wise ops exist
495
+ // to prevent, and it would land silently.
496
+ 'presentation.filterQuestionIds',
497
+ 'presentation.actionIds',
498
+ ];
131
499
  /**
132
500
  * The reserved path `field` would write, if any. Both directions count: the path itself, a
133
501
  * path *below* it (`grid.columnIds.0`), and an *ancestor* whose write would take the reserved
@@ -525,8 +893,68 @@ const deleteQuestion = (doc, questionId) => {
525
893
  });
526
894
  // A binding pointing at a deleted question is an unresolvable reference the
527
895
  // compiler would reject at publication; drop it with its target. A grid column
528
- // list pointing at it is the same class of reference and goes the same way.
529
- return dropBindingsForQuestion(dropFromGridColumns(withoutQuestion, questionId), questionId);
896
+ // list pointing at it is the same class of reference and goes the same way — and so are the
897
+ // presentation references a column earns: its filter chip, its row-editor placement, its default
898
+ // width, and its placement inside any tab's positional grid.
899
+ const withoutRefs = dropBindingsForQuestion(dropFromGridColumns(withoutQuestion, questionId), questionId);
900
+ return scrubTabPlacements(scrubColumnPresentationRefs(withoutRefs, questionId), questionId);
901
+ };
902
+ /**
903
+ * Drops a deleted column from every grid presentation that referenced it.
904
+ *
905
+ * `dropFromGridColumns` removes the ownership entry; these are the three places a column also earns a
906
+ * reference — the filter selection, its row-editor placement and its authored default width. Left
907
+ * behind, each is a key naming a question the document no longer has: unreachable state that still
908
+ * changes `document_hash`, which is what makes it a correctness problem and not tidiness.
909
+ */
910
+ const scrubColumnPresentationRefs = (doc, questionId) => {
911
+ const questions = Object.entries(doc.questionsById ?? {});
912
+ let changed = false;
913
+ const nextQuestions = Object.fromEntries(questions.map(([gridQuestionId, question]) => {
914
+ const presentation = question.presentation;
915
+ if (presentation === undefined)
916
+ return [gridQuestionId, question];
917
+ let next = { ...presentation };
918
+ let touched = false;
919
+ const filters = presentationListOf(question, 'filterQuestionIds');
920
+ if (filters.includes(questionId)) {
921
+ next = writePresentationList(next, 'filterQuestionIds', filters.filter((id) => id !== questionId));
922
+ touched = true;
923
+ }
924
+ const rowEditor = next['rowEditor'];
925
+ if (rowEditor?.layoutByQuestionId?.[questionId] !== undefined) {
926
+ const layout = omitKey(rowEditor.layoutByQuestionId, questionId);
927
+ const nextRowEditor = { ...rowEditor };
928
+ if (Object.keys(layout).length === 0)
929
+ delete nextRowEditor['layoutByQuestionId'];
930
+ else
931
+ nextRowEditor['layoutByQuestionId'] = layout;
932
+ if (Object.keys(nextRowEditor).length === 0)
933
+ delete next['rowEditor'];
934
+ else
935
+ next['rowEditor'] = nextRowEditor;
936
+ touched = true;
937
+ }
938
+ const widths = next['defaultColumnWidthsByQuestionId'];
939
+ if (widths?.[questionId] !== undefined) {
940
+ const remaining = omitKey(widths, questionId);
941
+ if (Object.keys(remaining).length === 0)
942
+ delete next['defaultColumnWidthsByQuestionId'];
943
+ else
944
+ next['defaultColumnWidthsByQuestionId'] = remaining;
945
+ touched = true;
946
+ }
947
+ if (!touched)
948
+ return [gridQuestionId, question];
949
+ changed = true;
950
+ const nextQuestion = { ...question };
951
+ if (Object.keys(next).length === 0)
952
+ delete nextQuestion.presentation;
953
+ else
954
+ nextQuestion.presentation = next;
955
+ return [gridQuestionId, nextQuestion];
956
+ }));
957
+ return changed ? { ...doc, questionsById: nextQuestions } : doc;
530
958
  };
531
959
  export const applyOperation = (document, op) => {
532
960
  const next = reduce(document, op);
@@ -689,6 +1117,38 @@ const reduce = (doc, op) => {
689
1117
  },
690
1118
  };
691
1119
  }
1120
+ case 'gridColumn.setFilter': {
1121
+ const gridQuestion = requireGridQuestion(doc, op.questionId);
1122
+ const columnIds = gridQuestion.grid?.columnIds;
1123
+ // Only a column this grid owns may offer a filter: a top-level question's filter chip would
1124
+ // have no row context to filter, and the reference would dangle on the grid's delete.
1125
+ if (!doc.questionsById?.[op.columnQuestionId] || !columnIds?.includes(op.columnQuestionId)) {
1126
+ throw new OperationConflictError(`Question "${op.columnQuestionId}" does not belong to grid "${op.questionId}"`);
1127
+ }
1128
+ const presentation = writePresentationList({ ...(gridQuestion.presentation ?? {}) }, 'filterQuestionIds', setListMember(presentationListOf(gridQuestion, 'filterQuestionIds'), op.columnQuestionId, op.include, op.atIndex));
1129
+ return writeGridPresentation(doc, op.questionId, gridQuestion, presentation);
1130
+ }
1131
+ case 'gridColumn.setAction': {
1132
+ const gridQuestion = requireGridQuestion(doc, op.questionId);
1133
+ if (op.include) {
1134
+ // A grid may only own a KNOWN gridAction. A `topLevelAction` here would be owned by the
1135
+ // very grid it is supposed to drive, and an unknown legacy record has no `actionType`
1136
+ // vocabulary at all — either way the reference compiles into nothing. `include: false`
1137
+ // deliberately skips this so a malformed or legacy reference can still be scrubbed.
1138
+ requireKnownAction(doc, op.actionId, 'gridAction');
1139
+ // A grid action has at most one owning grid, which is what makes its metadata scope
1140
+ // unambiguous — the same action listed by two grids would have two column vocabularies.
1141
+ const owners = gridsOwningAction(doc, op.actionId).filter((owner) => owner !== op.questionId);
1142
+ if (owners.length > 0) {
1143
+ throw new OperationConflictError(`Action "${op.actionId}" is already owned by grid "${owners[0]}"`);
1144
+ }
1145
+ }
1146
+ const presentation = writePresentationList({ ...(gridQuestion.presentation ?? {}) }, 'actionIds', setListMember(presentationListOf(gridQuestion, 'actionIds'), op.actionId, op.include, op.atIndex));
1147
+ const next = writeGridPresentation(doc, op.questionId, gridQuestion, presentation);
1148
+ // Removing a grid's action also drops it from every top-level sequence for THAT grid: the
1149
+ // reference means "run this grid's action", so it stops being expressible at the same moment.
1150
+ return op.include ? next : scrubGridActionRefs(next, op.questionId, op.actionId);
1151
+ }
692
1152
  case 'gridRow.create': {
693
1153
  if (!doc.questionsById?.[op.questionId]) {
694
1154
  throw new OperationConflictError(`Unknown question "${op.questionId}"`);
@@ -834,6 +1294,9 @@ const reduce = (doc, op) => {
834
1294
  if (!tab) {
835
1295
  throw new OperationConflictError(`Unknown tab "${op.tabId}"`);
836
1296
  }
1297
+ const refusal = tabFieldPathRefusal(op.field);
1298
+ if (refusal !== undefined)
1299
+ throw new OperationConflictError(refusal);
837
1300
  return { ...doc, tabsById: { ...doc.tabsById, [op.tabId]: writeField(tab, op.field, op.value) } };
838
1301
  }
839
1302
  case 'tab.move': {
@@ -842,13 +1305,40 @@ const reduce = (doc, op) => {
842
1305
  }
843
1306
  return { ...doc, tabOrder: moveInOrder(doc.tabOrder, op.tabId, op.toIndex) };
844
1307
  }
1308
+ case 'tab.setLayout': {
1309
+ if (!doc.tabsById?.[op.tabId])
1310
+ throw new OperationConflictError(`Unknown tab "${op.tabId}"`);
1311
+ if (!doc.questionsById?.[op.questionId]) {
1312
+ throw new OperationConflictError(`Unknown question "${op.questionId}"`);
1313
+ }
1314
+ const tab = doc.tabsById[op.tabId] ?? {};
1315
+ const layout = { ...(tab.layout ?? {}) };
1316
+ const placements = { ...(layout['placementsByQuestionId'] ?? {}) };
1317
+ // One whole placement, written or removed as a unit — never a row without its cell.
1318
+ if (op.placement === null)
1319
+ delete placements[op.questionId];
1320
+ else
1321
+ placements[op.questionId] = op.placement;
1322
+ if (Object.keys(placements).length === 0)
1323
+ delete layout['placementsByQuestionId'];
1324
+ else
1325
+ layout['placementsByQuestionId'] = placements;
1326
+ const nextTab = { ...tab };
1327
+ if (Object.keys(layout).length === 0)
1328
+ delete nextTab.layout;
1329
+ else
1330
+ nextTab.layout = layout;
1331
+ return { ...doc, tabsById: { ...doc.tabsById, [op.tabId]: nextTab } };
1332
+ }
845
1333
  case 'tab.delete': {
846
1334
  if (!doc.tabsById?.[op.tabId]) {
847
1335
  throw new OperationConflictError(`Unknown tab "${op.tabId}"`);
848
1336
  }
849
- return patchDocument(doc, {
850
- tabsById: doc.tabsById && omitKey(doc.tabsById, op.tabId),
851
- tabOrder: (doc.tabOrder ?? []).filter((id) => id !== op.tabId),
1337
+ // A grid naming a deleted tab as its header would point at nothing; scrub before removing.
1338
+ const scrubbed = scrubHeaderTabRefs(doc, op.tabId);
1339
+ return patchDocument(scrubbed, {
1340
+ tabsById: scrubbed.tabsById && omitKey(scrubbed.tabsById, op.tabId),
1341
+ tabOrder: (scrubbed.tabOrder ?? []).filter((id) => id !== op.tabId),
852
1342
  });
853
1343
  }
854
1344
  case 'action.create': {
@@ -868,14 +1358,113 @@ const reduce = (doc, op) => {
868
1358
  if (!action) {
869
1359
  throw new OperationConflictError(`Unknown action "${op.actionId}"`);
870
1360
  }
1361
+ // The gate applies to KNOWN kinds only. An unknown-kind record keeps taking any field —
1362
+ // including the UI buffers legacy persisted — so a stored action replays byte-identically.
1363
+ if (isKnownActionKind(action.kind)) {
1364
+ const refusal = knownActionFieldRefusal(action.kind, op.field) ?? knownActionValueRefusal(op.field, op.value);
1365
+ if (refusal !== undefined)
1366
+ throw new OperationConflictError(refusal);
1367
+ }
871
1368
  return { ...doc, actionsById: { ...doc.actionsById, [op.actionId]: writeField(action, op.field, op.value) } };
872
1369
  }
1370
+ case 'action.createTyped': {
1371
+ if (doc.actionsById?.[op.actionId]) {
1372
+ throw new OperationConflictError(`Action "${op.actionId}" already exists`);
1373
+ }
1374
+ // The op union now makes `{kind: 'topLevelAction', actionType}` unrepresentable, so this is
1375
+ // the replay/bypass boundary rather than the primary defence: an op read back from
1376
+ // `collab_ops` was never re-checked against the wire schema.
1377
+ const authoredActionType = op.actionType;
1378
+ if (authoredActionType !== undefined && op.kind !== 'gridAction') {
1379
+ throw new OperationConflictError(`"actionType" belongs to a gridAction, not a ${op.kind}`);
1380
+ }
1381
+ if (authoredActionType !== undefined && !isActionType(authoredActionType)) {
1382
+ throw new OperationConflictError(`"${String(authoredActionType)}" is not a valid actionType`);
1383
+ }
1384
+ // Minimal form: kind plus only what was authored. No empty label, no empty collections.
1385
+ return {
1386
+ ...doc,
1387
+ actionsById: {
1388
+ ...(doc.actionsById ?? {}),
1389
+ [op.actionId]: {
1390
+ kind: op.kind,
1391
+ ...(op.label === undefined ? {} : { label: op.label }),
1392
+ ...(op.actionType === undefined ? {} : { actionType: op.actionType }),
1393
+ },
1394
+ },
1395
+ };
1396
+ }
1397
+ case 'action.setGridActionRef': {
1398
+ const action = requireKnownAction(doc, op.actionId, 'topLevelAction');
1399
+ const grid = doc.questionsById?.[op.gridQuestionId];
1400
+ if (!grid || grid.type !== 'QuestionGrid') {
1401
+ throw new OperationConflictError(`"${op.gridQuestionId}" is not a QuestionGrid`);
1402
+ }
1403
+ if (op.include) {
1404
+ // The referenced action must be a grid action THIS grid owns: a top-level button runs
1405
+ // one of that grid's actions, so a reference to an unowned one would compile to nothing.
1406
+ requireKnownAction(doc, op.gridActionId, 'gridAction');
1407
+ if (!presentationListOf(grid, 'actionIds').includes(op.gridActionId)) {
1408
+ throw new OperationConflictError(`Action "${op.gridActionId}" is not owned by grid "${op.gridQuestionId}"`);
1409
+ }
1410
+ }
1411
+ const byGrid = { ...(action['actionIdsByGridQuestionId'] ?? {}) };
1412
+ const next = setListMember(byGrid[op.gridQuestionId] ?? [], op.gridActionId, op.include, op.atIndex);
1413
+ if (next.length === 0)
1414
+ delete byGrid[op.gridQuestionId];
1415
+ else
1416
+ byGrid[op.gridQuestionId] = next;
1417
+ const nextAction = { ...action };
1418
+ if (Object.keys(byGrid).length === 0)
1419
+ delete nextAction['actionIdsByGridQuestionId'];
1420
+ else
1421
+ nextAction['actionIdsByGridQuestionId'] = byGrid;
1422
+ return { ...doc, actionsById: { ...doc.actionsById, [op.actionId]: nextAction } };
1423
+ }
1424
+ case 'action.setMetadata': {
1425
+ const action = requireKnownAction(doc, op.actionId, 'gridAction');
1426
+ if (op.metadata !== null) {
1427
+ // EXACTLY one owner, never "the first one found". An imported document can list one grid
1428
+ // action under two grids, and resolving the column vocabulary from `owners[0]` made the
1429
+ // same write accepted or refused purely by `questionsById` insertion order — two
1430
+ // documents with identical content and different key order disagreeing is precisely
1431
+ // what DOC-LAW-1 exists to prevent, so the ambiguity is reported instead of resolved.
1432
+ const owners = gridsOwningAction(doc, op.actionId);
1433
+ if (owners.length === 0) {
1434
+ throw new OperationConflictError(`Action "${op.actionId}" is owned by no grid, so its metadata has no column vocabulary`);
1435
+ }
1436
+ if (owners.length > 1) {
1437
+ throw new OperationConflictError(`Action "${op.actionId}" is owned by ${owners.length} grids (${[...owners].sort().join(', ')}); its metadata scope is ambiguous`);
1438
+ }
1439
+ // A metadata key is a COLUMN of the owning grid, not an arbitrary question: the action
1440
+ // copies or updates values within its own rows.
1441
+ const columnIds = doc.questionsById?.[owners[0]]?.grid?.columnIds ?? [];
1442
+ if (!columnIds.includes(op.questionId)) {
1443
+ throw new OperationConflictError(`Question "${op.questionId}" is not a column of grid "${owners[0]}"`);
1444
+ }
1445
+ }
1446
+ // `metadata: null` needs no owner: removal is how a malformed or orphaned record gets
1447
+ // repaired, and requiring an owner would make exactly the documents that need fixing
1448
+ // unfixable.
1449
+ const byQuestion = { ...(action['metadataByQuestionId'] ?? {}) };
1450
+ if (op.metadata === null)
1451
+ delete byQuestion[op.questionId];
1452
+ else
1453
+ byQuestion[op.questionId] = canonicalActionMetadata(op.metadata);
1454
+ const nextAction = { ...action };
1455
+ if (Object.keys(byQuestion).length === 0)
1456
+ delete nextAction['metadataByQuestionId'];
1457
+ else
1458
+ nextAction['metadataByQuestionId'] = byQuestion;
1459
+ return { ...doc, actionsById: { ...doc.actionsById, [op.actionId]: nextAction } };
1460
+ }
873
1461
  case 'action.delete': {
874
1462
  if (!doc.actionsById?.[op.actionId]) {
875
1463
  throw new OperationConflictError(`Unknown action "${op.actionId}"`);
876
1464
  }
877
- return patchDocument(doc, {
878
- actionsById: doc.actionsById && omitKey(doc.actionsById, op.actionId),
1465
+ const scrubbed = scrubActionRefs(doc, op.actionId);
1466
+ return patchDocument(scrubbed, {
1467
+ actionsById: scrubbed.actionsById && omitKey(scrubbed.actionsById, op.actionId),
879
1468
  });
880
1469
  }
881
1470
  case 'dataMapping.create': {
@@ -1072,6 +1661,41 @@ const reduce = (doc, op) => {
1072
1661
  },
1073
1662
  };
1074
1663
  }
1664
+ case 'mappingFilter.setTyped': {
1665
+ assertTypedFilterPayload(op);
1666
+ const node = doc.mappingNodesById?.[op.nodeId];
1667
+ if (!node)
1668
+ throw new OperationConflictError(`Unknown mapping node "${op.nodeId}"`);
1669
+ // REPLACED, not patched: switching `eq` -> `in` must not leave the old `value` beside the
1670
+ // new `values`, which a merge would. A filter carries its own operator's members and no
1671
+ // others, so one operator is always readable from the record alone.
1672
+ const filter = op.operator === 'eq'
1673
+ ? { fieldId: op.fieldId, operator: 'eq', value: op.value }
1674
+ : op.operator === 'in'
1675
+ ? { fieldId: op.fieldId, operator: 'in', values: [...op.values] }
1676
+ : op.operator === 'isNull'
1677
+ ? { fieldId: op.fieldId, operator: 'isNull', value: op.value }
1678
+ : // `range` by elimination is safe ONLY because the validator above closed the
1679
+ // operator set first; before it did, an unknown operator landed here.
1680
+ {
1681
+ fieldId: op.fieldId,
1682
+ operator: 'range',
1683
+ ...('from' in op && op.from !== undefined ? { from: op.from } : {}),
1684
+ ...('to' in op && op.to !== undefined ? { to: op.to } : {}),
1685
+ };
1686
+ const filterOrder = node.filterOrder ?? [];
1687
+ return {
1688
+ ...doc,
1689
+ mappingFiltersById: { ...(doc.mappingFiltersById ?? {}), [op.filterId]: filter },
1690
+ mappingNodesById: {
1691
+ ...doc.mappingNodesById,
1692
+ [op.nodeId]: {
1693
+ ...node,
1694
+ filterOrder: filterOrder.includes(op.filterId) ? filterOrder : [...filterOrder, op.filterId],
1695
+ },
1696
+ },
1697
+ };
1698
+ }
1075
1699
  case 'mappingFilter.delete': {
1076
1700
  const nodes = Object.fromEntries(Object.entries(doc.mappingNodesById ?? {}).map(([nodeId, node]) => {
1077
1701
  if (!node.filterOrder?.includes(op.filterId))