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,16 +1,34 @@
1
1
  import type { TemplateOp } from './operations.js'
2
2
  import type {
3
+ ActionMetadata,
3
4
  BindingCardinality,
5
+ KnownActionKind,
4
6
  BindingOnMany,
5
7
  BindingOnMissing,
8
+ LayoutPlacement,
6
9
  MappingBinding,
10
+ MappingFilter,
7
11
  MappingNode,
8
12
  QnrDataMapping,
13
+ QnrAction,
9
14
  QnrQuestion,
10
15
  QnrTemplateDocument,
11
16
  QuestionId,
12
17
  } from './templateDocument.js'
13
- import { BINDING_OPTION_DEFAULTS, bindingTargetKey } from './templateDocument.js'
18
+ import {
19
+ ACTION_TYPES,
20
+ BINDING_OPTION_DEFAULTS,
21
+ MAPPING_FILTER_OPERATORS,
22
+ bindingTargetKey,
23
+ isKnownActionKind,
24
+ } from './templateDocument.js'
25
+
26
+ /** Runtime narrowing for the two closed vocabularies the reducer must re-check on replay. */
27
+ const isActionType = (value: unknown): value is (typeof ACTION_TYPES)[number] =>
28
+ typeof value === 'string' && (ACTION_TYPES as readonly string[]).includes(value)
29
+
30
+ const isDocScalarValue = (value: unknown): value is string | number | boolean =>
31
+ typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
14
32
 
15
33
  /** The behaviour members, so the write loop cannot silently miss one that `BINDING_OPTION_DEFAULTS` gains. */
16
34
  const BINDING_OPTION_KEYS = Object.keys(BINDING_OPTION_DEFAULTS) as ReadonlyArray<keyof typeof BINDING_OPTION_DEFAULTS>
@@ -148,6 +166,419 @@ const writeBindingOptions = (
148
166
  return next
149
167
  }
150
168
 
169
+ /**
170
+ * Adds, moves or removes ONE member of an ordered primitive id list.
171
+ *
172
+ * The member-wise discipline three ops share, and the reason they are ops at all rather than whole-list
173
+ * writes: JSON Merge Patch replaces an array wholesale, so two authors adding different ids would
174
+ * produce two patches and the second would silently discard the first with no conflict raised. Editing
175
+ * the *current* list one member at a time makes both edits survive — the same argument DOC-LAW-1 makes
176
+ * for keying collections by id.
177
+ *
178
+ * `include: true` inserts at `atIndex` (else appends) and **moves** an id already present when an
179
+ * `atIndex` is supplied; omitting `atIndex` for an id already present is a no-op rather than a
180
+ * duplicate. `include: false` removes it.
181
+ */
182
+ const setListMember = (list: readonly string[], id: string, include: boolean, atIndex?: number): string[] => {
183
+ if (!include) return list.filter((member) => member !== id)
184
+
185
+ const without = list.filter((member) => member !== id)
186
+ if (atIndex === undefined) return list.includes(id) ? [...list] : [...without, id]
187
+
188
+ const at = Math.max(0, Math.min(atIndex, without.length))
189
+ return [...without.slice(0, at), id, ...without.slice(at)]
190
+ }
191
+
192
+ /** Writes a grid question's presentation back in minimal form, dropping every emptied container. */
193
+ const writeGridPresentation = (
194
+ doc: QnrTemplateDocument,
195
+ questionId: QuestionId,
196
+ question: QnrQuestion,
197
+ presentation: Record<string, unknown>,
198
+ ): QnrTemplateDocument => {
199
+ const nextQuestion = { ...question }
200
+ if (Object.keys(presentation).length === 0) delete nextQuestion.presentation
201
+ else nextQuestion.presentation = presentation
202
+
203
+ return { ...doc, questionsById: { ...doc.questionsById, [questionId]: nextQuestion } }
204
+ }
205
+
206
+ /** Sets or clears one of a grid presentation's ordered id lists, omitting it when emptied (DOC-LAW-2). */
207
+ const writePresentationList = (
208
+ presentation: Record<string, unknown>,
209
+ key: 'filterQuestionIds' | 'actionIds',
210
+ next: readonly string[],
211
+ ): Record<string, unknown> => {
212
+ const copy = { ...presentation }
213
+ if (next.length === 0) delete copy[key]
214
+ else copy[key] = [...next]
215
+ return copy
216
+ }
217
+
218
+ const presentationListOf = (question: QnrQuestion, key: 'filterQuestionIds' | 'actionIds'): string[] => {
219
+ const value = (question.presentation ?? {})[key]
220
+ return Array.isArray(value) ? (value as string[]).filter((member): member is string => typeof member === 'string') : []
221
+ }
222
+
223
+ /** Every grid presentation that lists `actionId`, so a grid action can have at most one owner. */
224
+ const gridsOwningAction = (doc: QnrTemplateDocument, actionId: string): QuestionId[] =>
225
+ Object.entries(doc.questionsById ?? {})
226
+ .filter(([, question]) => presentationListOf(question, 'actionIds').includes(actionId))
227
+ .map(([questionId]) => questionId)
228
+
229
+ /**
230
+ * The action, if it is a KNOWN one — `kind` inside the closed vocabulary.
231
+ *
232
+ * A legacy record with an unknown `kind` is not "known but unrecognised": the typed ops refuse it
233
+ * outright rather than half-applying rules written for a different shape, which is what keeps old
234
+ * documents replaying byte-identically.
235
+ */
236
+ /**
237
+ * Why `field` may not be written as an ordinary tab field edit, or `undefined` if it may.
238
+ *
239
+ * `layout.placementsByQuestionId` is reserved for `tab.setLayout`. Unlike the grid's filter list this
240
+ * one is not even expressible as an `OpValue` — a placement is an object — so the realistic misuse is a
241
+ * write to an ANCESTOR (`layout`, or the placements map cleared wholesale), which would drop every other
242
+ * question's placement in one edit. Both directions of overlap are refused; `label` and any other
243
+ * authored scalar stay ordinary field edits.
244
+ */
245
+ export const tabFieldPathRefusal = (field: string): string | undefined => {
246
+ const reserved = 'layout.placementsByQuestionId'
247
+
248
+ if (field === reserved || field.startsWith(`${reserved}.`) || reserved.startsWith(`${field}.`)) {
249
+ return `Field "${field}" writes "${reserved}", which only tab.setLayout may author`
250
+ }
251
+
252
+ return undefined
253
+ }
254
+
255
+ /**
256
+ * Validates a `mappingFilter.setTyped` payload in the REDUCER, not only at the wire.
257
+ *
258
+ * The wire schema is the primary gate, but it is not the only path into this reducer: bunjs replays a
259
+ * stored `collab_ops` log without re-validating each op, so an op written by an older or bypassed
260
+ * client arrives here unchecked. Before this, that path accepted an empty `in`, a `range` with no
261
+ * bound, a non-boolean `isNull`, and — worst — an UNKNOWN operator, which fell through the
262
+ * `eq`/`in`/`isNull` tests into the `range` branch and was silently stored as a boundless range.
263
+ * A filter nothing can evaluate then rode into a compiled artifact that is immutable forever.
264
+ *
265
+ * Mirrors the wire schema exactly: closed operator, that operator's members present and correctly
266
+ * typed, and no member belonging to another operator.
267
+ */
268
+ const assertTypedFilterPayload = (op: {
269
+ operator: string
270
+ value?: unknown
271
+ values?: unknown
272
+ from?: unknown
273
+ to?: unknown
274
+ }): void => {
275
+ if (!(MAPPING_FILTER_OPERATORS as readonly string[]).includes(op.operator)) {
276
+ throw new OperationConflictError(
277
+ `"${op.operator}" is not a typed filter operator (${MAPPING_FILTER_OPERATORS.join(' | ')}); use mappingFilter.set for a legacy operator`,
278
+ )
279
+ }
280
+
281
+ // Stale members first: a payload carrying another operator's members is ambiguous whatever else is
282
+ // right about it, and the canonical replace would silently drop them rather than refuse.
283
+ const present = (['value', 'values', 'from', 'to'] as const).filter((member) => op[member] !== undefined)
284
+ const allowed: Record<string, readonly string[]> = {
285
+ eq: ['value'],
286
+ in: ['values'],
287
+ range: ['from', 'to'],
288
+ isNull: ['value'],
289
+ }
290
+ const stale = present.filter((member) => !(allowed[op.operator] ?? []).includes(member))
291
+ if (stale.length > 0) {
292
+ throw new OperationConflictError(`Operator "${op.operator}" does not carry ${stale.join(', ')}`)
293
+ }
294
+
295
+ if (op.operator === 'eq') {
296
+ if (!isDocScalarValue(op.value)) throw new OperationConflictError('Operator "eq" requires a scalar value')
297
+ return
298
+ }
299
+
300
+ if (op.operator === 'isNull') {
301
+ if (typeof op.value !== 'boolean') {
302
+ throw new OperationConflictError('Operator "isNull" requires a boolean value')
303
+ }
304
+ return
305
+ }
306
+
307
+ if (op.operator === 'in') {
308
+ if (!Array.isArray(op.values) || op.values.length === 0) {
309
+ throw new OperationConflictError('Operator "in" requires a non-empty list')
310
+ }
311
+ if (!op.values.every(isDocScalarValue)) {
312
+ throw new OperationConflictError('Operator "in" requires every member to be a scalar')
313
+ }
314
+ return
315
+ }
316
+
317
+ // range: at least one bound, and every bound present must be a scalar.
318
+ if (op.from === undefined && op.to === undefined) {
319
+ throw new OperationConflictError('Operator "range" requires at least one of "from"/"to"')
320
+ }
321
+ for (const bound of ['from', 'to'] as const) {
322
+ if (op[bound] !== undefined && !isDocScalarValue(op[bound])) {
323
+ throw new OperationConflictError(`Operator "range" requires "${bound}" to be a scalar`)
324
+ }
325
+ }
326
+ }
327
+
328
+ /** UI edit buffers, in both spellings. Rejected on known kinds by the whitelist below. */
329
+ const ACTION_UI_BUFFERS = ['editableLabel', 'editableType', 'editable_label', 'editable_type'] as const
330
+
331
+ /**
332
+ * The ONLY fields `action.updateField` may write on a KNOWN action: `label` on either kind, and
333
+ * `actionType` on a `gridAction`.
334
+ *
335
+ * **A whitelist, not a blacklist, and that is the repair.** The first version enumerated what was
336
+ * forbidden — `kind`, the UI buffers, the two keyed collections — which meant `arbitraryField` and every
337
+ * other unlisted name sailed through and persisted. A known action's shape is closed by definition, so
338
+ * the safe default is refusal: anything not named here is not part of the typed vocabulary, and
339
+ * admitting it would turn a typed record back into the broad legacy bag the closed kinds exist to
340
+ * replace. `QnrAction` stays open for LEGACY records precisely so this can be strict.
341
+ *
342
+ * The listed names still carry their own reasons for being writable or not:
343
+ *
344
+ * - **`kind` is write-once.** It selects which rules apply, so changing it reinterprets every member
345
+ * already stored under the old kind.
346
+ * - **UI edit buffers are not document content** (`editable_label`/`editable_type`), so authoring them
347
+ * would mint a version for a designer-side checkbox.
348
+ * - **The two keyed collections are reserved** for `action.setGridActionRef` / `action.setMetadata`,
349
+ * which edit them one member at a time; a field write replaces a map wholesale.
350
+ */
351
+ const KNOWN_ACTION_WRITABLE_FIELDS: Readonly<Record<KnownActionKind, readonly string[]>> = {
352
+ topLevelAction: ['label'],
353
+ gridAction: ['label', 'actionType'],
354
+ }
355
+
356
+ /** The collections only the typed member-wise ops may author — named for the refusal message. */
357
+ const ACTION_OWNED_FIELD_PATHS = ['actionIdsByGridQuestionId', 'metadataByQuestionId'] as const
358
+
359
+ /**
360
+ * Why `field` may not be written on a KNOWN action, or `undefined` if it may.
361
+ *
362
+ * Applies to known kinds only: a legacy record keeps taking any field, buffers included, because that
363
+ * is what makes an already-stored action replay byte-identically (ADR-0008 DEC-006).
364
+ */
365
+ export const knownActionFieldRefusal = (kind: KnownActionKind, field: string): string | undefined => {
366
+ const writable = KNOWN_ACTION_WRITABLE_FIELDS[kind]
367
+ if (writable.includes(field)) return undefined
368
+
369
+ // The specific messages first, so the reason a caller reads names their actual mistake rather than
370
+ // "not writable" for a field that is writable on the other kind, or reserved for a dedicated op.
371
+ if (field === 'kind' || field.startsWith('kind.')) {
372
+ return 'Field "kind" is write-once on a known action; create a new action instead'
373
+ }
374
+ if (ACTION_UI_BUFFERS.some((buffer) => field === buffer || field.startsWith(`${buffer}.`))) {
375
+ return `Field "${field}" is a UI edit buffer, not document content`
376
+ }
377
+ if (field === 'actionType' || field.startsWith('actionType.')) {
378
+ return `Field "actionType" belongs to a gridAction, not a ${kind}`
379
+ }
380
+ const owned = ACTION_OWNED_FIELD_PATHS.find(
381
+ (path) => field === path || field.startsWith(`${path}.`) || path.startsWith(`${field}.`),
382
+ )
383
+ if (owned !== undefined) {
384
+ return `Field "${field}" writes "${owned}", which only the typed action operations may author`
385
+ }
386
+
387
+ return `Field "${field}" is not part of the ${kind} vocabulary (writable: ${writable.join(', ')})`
388
+ }
389
+
390
+ /**
391
+ * Why `value` may not be written to a permitted known-action field, or `undefined` if it may.
392
+ *
393
+ * The whitelist alone would still let `actionType: 'DELETE'` or a numeric `label` through, turning a
394
+ * typed record into a malformed one that every downstream reader has to re-check. `null` is the explicit
395
+ * unset the op layer carries, so it is legal for both.
396
+ */
397
+ export const knownActionValueRefusal = (field: string, value: unknown): string | undefined => {
398
+ if (value === null) return undefined
399
+
400
+ if (field === 'label' && typeof value !== 'string') {
401
+ return `Field "label" takes a string, not ${typeof value}`
402
+ }
403
+ if (field === 'actionType' && !isActionType(value)) {
404
+ return `"${String(value)}" is not a valid actionType (${ACTION_TYPES.join(' | ')})`
405
+ }
406
+
407
+ return undefined
408
+ }
409
+
410
+ const requireKnownAction = (doc: QnrTemplateDocument, actionId: string, kind: 'topLevelAction' | 'gridAction'): QnrAction => {
411
+ const action = doc.actionsById?.[actionId]
412
+ if (!action) throw new OperationConflictError(`Unknown action "${actionId}"`)
413
+ if (!isKnownActionKind(action.kind)) {
414
+ throw new OperationConflictError(
415
+ `Action "${actionId}" is a legacy record (kind "${String(action.kind)}"); the typed operations only author known kinds`,
416
+ )
417
+ }
418
+ if (action.kind !== kind) {
419
+ throw new OperationConflictError(`Action "${actionId}" is a ${action.kind}, not a ${kind}`)
420
+ }
421
+ return action
422
+ }
423
+
424
+ /**
425
+ * Canonicalizes one metadata entry, refusing the two shapes DOC-LAW-2 makes ambiguous.
426
+ *
427
+ * `{all: true}` is the all-to-all marker and is exclusive with bounds: legacy writes all-to-all as
428
+ * `from: null, to: null`, and since a document may carry neither a null nor an empty object, "selected
429
+ * but unbounded" and "not selected" would otherwise be the same absence.
430
+ */
431
+ const canonicalActionMetadata = (metadata: ActionMetadata): ActionMetadata => {
432
+ const record = metadata as Record<string, unknown>
433
+ const hasAll = record['all'] === true
434
+ const hasFrom = record['from'] !== undefined
435
+ const hasTo = record['to'] !== undefined
436
+
437
+ if (hasAll && (hasFrom || hasTo)) {
438
+ throw new OperationConflictError('Action metadata "all" is exclusive with "from"/"to"')
439
+ }
440
+ if (hasAll) return { all: true }
441
+ if (!hasFrom && !hasTo) {
442
+ throw new OperationConflictError('Action metadata must select something: "all", "from" and/or "to"')
443
+ }
444
+
445
+ return {
446
+ ...(hasFrom ? { from: record['from'] as never } : {}),
447
+ ...(hasTo ? { to: record['to'] as never } : {}),
448
+ } as ActionMetadata
449
+ }
450
+
451
+ /**
452
+ * Drops every top-level reference to one of a grid's actions.
453
+ *
454
+ * A `topLevelAction` entry means "run this GRID's action", so when the grid stops owning the action the
455
+ * reference stops being expressible at the same moment — leaving it would compile into a button that
456
+ * runs nothing. Emptied sequences drop their grid key and an emptied map is omitted (DOC-LAW-2).
457
+ */
458
+ const scrubGridActionRefs = (
459
+ doc: QnrTemplateDocument,
460
+ gridQuestionId: QuestionId,
461
+ gridActionId: string,
462
+ ): QnrTemplateDocument => {
463
+ const actions = Object.entries(doc.actionsById ?? {})
464
+ if (actions.length === 0) return doc
465
+
466
+ let changed = false
467
+ const nextActions = Object.fromEntries(
468
+ actions.map(([actionId, action]) => {
469
+ const byGrid = (action['actionIdsByGridQuestionId'] ?? {}) as Record<string, string[]>
470
+ const sequence = byGrid[gridQuestionId]
471
+ if (!Array.isArray(sequence) || !sequence.includes(gridActionId)) return [actionId, action]
472
+
473
+ changed = true
474
+ const remaining = sequence.filter((id) => id !== gridActionId)
475
+ const nextByGrid = { ...byGrid }
476
+ if (remaining.length === 0) delete nextByGrid[gridQuestionId]
477
+ else nextByGrid[gridQuestionId] = remaining
478
+
479
+ const nextAction = { ...action }
480
+ if (Object.keys(nextByGrid).length === 0) delete nextAction['actionIdsByGridQuestionId']
481
+ else nextAction['actionIdsByGridQuestionId'] = nextByGrid
482
+ return [actionId, nextAction]
483
+ }),
484
+ )
485
+
486
+ return changed ? { ...doc, actionsById: nextActions } : doc
487
+ }
488
+
489
+ /** Drops a deleted question's placement from every tab layout, and every emptied container with it. */
490
+ const scrubTabPlacements = (doc: QnrTemplateDocument, questionId: QuestionId): QnrTemplateDocument => {
491
+ const tabs = Object.entries(doc.tabsById ?? {})
492
+ if (tabs.length === 0) return doc
493
+
494
+ let changed = false
495
+ const nextTabs = Object.fromEntries(
496
+ tabs.map(([tabId, tab]) => {
497
+ const layout = (tab.layout ?? {}) as Record<string, unknown>
498
+ const placements = (layout['placementsByQuestionId'] ?? {}) as Record<string, LayoutPlacement>
499
+ if (placements[questionId] === undefined) return [tabId, tab]
500
+
501
+ changed = true
502
+ const nextPlacements = omitKey(placements, questionId)
503
+ const nextLayout = { ...layout }
504
+ if (Object.keys(nextPlacements).length === 0) delete nextLayout['placementsByQuestionId']
505
+ else nextLayout['placementsByQuestionId'] = nextPlacements
506
+
507
+ const nextTab = { ...tab }
508
+ if (Object.keys(nextLayout).length === 0) delete nextTab.layout
509
+ else nextTab.layout = nextLayout
510
+ return [tabId, nextTab]
511
+ }),
512
+ )
513
+
514
+ return changed ? { ...doc, tabsById: nextTabs } : doc
515
+ }
516
+
517
+ /** Drops a deleted tab from every grid that named it as its header. */
518
+ const scrubHeaderTabRefs = (doc: QnrTemplateDocument, tabId: string): QnrTemplateDocument => {
519
+ const questions = Object.entries(doc.questionsById ?? {})
520
+ let changed = false
521
+ const nextQuestions = Object.fromEntries(
522
+ questions.map(([questionId, question]) => {
523
+ if (question.presentation?.headerTabId !== tabId) return [questionId, question]
524
+
525
+ changed = true
526
+ const presentation = { ...question.presentation }
527
+ delete presentation.headerTabId
528
+ const nextQuestion = { ...question }
529
+ if (Object.keys(presentation).length === 0) delete nextQuestion.presentation
530
+ else nextQuestion.presentation = presentation
531
+ return [questionId, nextQuestion]
532
+ }),
533
+ )
534
+
535
+ return changed ? { ...doc, questionsById: nextQuestions } : doc
536
+ }
537
+
538
+ /** Drops a deleted action from every grid presentation and every top-level sequence naming it. */
539
+ const scrubActionRefs = (doc: QnrTemplateDocument, actionId: string): QnrTemplateDocument => {
540
+ let next = doc
541
+
542
+ for (const gridQuestionId of gridsOwningAction(doc, actionId)) {
543
+ const grid = next.questionsById?.[gridQuestionId]
544
+ if (!grid) continue
545
+ const presentation = writePresentationList(
546
+ { ...(grid.presentation ?? {}) },
547
+ 'actionIds',
548
+ presentationListOf(grid, 'actionIds').filter((id) => id !== actionId),
549
+ )
550
+ next = writeGridPresentation(next, gridQuestionId, grid, presentation)
551
+ next = scrubGridActionRefs(next, gridQuestionId, actionId)
552
+ }
553
+
554
+ // A top-level action can also be deleted while still referenced by nothing of its own; and a grid
555
+ // action may be referenced under a grid that no longer owns it, so sweep every sequence by value.
556
+ const actions = Object.entries(next.actionsById ?? {})
557
+ let changed = false
558
+ const nextActions = Object.fromEntries(
559
+ actions.map(([id, action]) => {
560
+ const byGrid = (action['actionIdsByGridQuestionId'] ?? {}) as Record<string, string[]>
561
+ const entries = Object.entries(byGrid)
562
+ if (entries.length === 0) return [id, action]
563
+
564
+ const rebuilt = entries
565
+ .map(([gridId, sequence]) => [gridId, sequence.filter((member) => member !== actionId)] as const)
566
+ .filter(([, sequence]) => sequence.length > 0)
567
+ if (rebuilt.length === entries.length && rebuilt.every(([, seq], index) => seq.length === (entries[index]?.[1].length ?? 0))) {
568
+ return [id, action]
569
+ }
570
+
571
+ changed = true
572
+ const nextAction = { ...action }
573
+ if (rebuilt.length === 0) delete nextAction['actionIdsByGridQuestionId']
574
+ else nextAction['actionIdsByGridQuestionId'] = Object.fromEntries(rebuilt.map(([g, seq]) => [g, [...seq]]))
575
+ return [id, nextAction]
576
+ }),
577
+ )
578
+
579
+ return changed ? { ...next, actionsById: nextActions } : next
580
+ }
581
+
151
582
  const omitKey = <V>(record: Record<string, V>, key: string): Record<string, V> => {
152
583
  const { [key]: _removed, ...rest } = record
153
584
  return rest
@@ -164,7 +595,16 @@ const omitKey = <V>(record: Record<string, V>, key: string): Record<string, V> =
164
595
  * owned by nobody, or every other column's placement dropped in one edit. That is precisely
165
596
  * the atomicity the grid ops exist to provide, so the paths are reserved for them.
166
597
  */
167
- const GRID_OWNED_FIELD_PATHS = ['grid.columnIds', 'presentation.rowEditor.layoutByQuestionId'] as const
598
+ const GRID_OWNED_FIELD_PATHS = [
599
+ 'grid.columnIds',
600
+ 'presentation.rowEditor.layoutByQuestionId',
601
+ // Maintained member-wise by `gridColumn.setFilter` / `gridColumn.setAction`. An `OpValue` can carry
602
+ // a primitive array, so unlike the layout map these two are *expressible* as a field edit — which is
603
+ // exactly why they must be reserved: a wholesale write is the lost-update the member-wise ops exist
604
+ // to prevent, and it would land silently.
605
+ 'presentation.filterQuestionIds',
606
+ 'presentation.actionIds',
607
+ ] as const
168
608
 
169
609
  /**
170
610
  * The reserved path `field` would write, if any. Both directions count: the path itself, a
@@ -584,8 +1024,69 @@ const deleteQuestion = (doc: QnrTemplateDocument, questionId: QuestionId): QnrTe
584
1024
  })
585
1025
  // A binding pointing at a deleted question is an unresolvable reference the
586
1026
  // compiler would reject at publication; drop it with its target. A grid column
587
- // list pointing at it is the same class of reference and goes the same way.
588
- return dropBindingsForQuestion(dropFromGridColumns(withoutQuestion, questionId), questionId)
1027
+ // list pointing at it is the same class of reference and goes the same way — and so are the
1028
+ // presentation references a column earns: its filter chip, its row-editor placement, its default
1029
+ // width, and its placement inside any tab's positional grid.
1030
+ const withoutRefs = dropBindingsForQuestion(dropFromGridColumns(withoutQuestion, questionId), questionId)
1031
+ return scrubTabPlacements(scrubColumnPresentationRefs(withoutRefs, questionId), questionId)
1032
+ }
1033
+
1034
+ /**
1035
+ * Drops a deleted column from every grid presentation that referenced it.
1036
+ *
1037
+ * `dropFromGridColumns` removes the ownership entry; these are the three places a column also earns a
1038
+ * reference — the filter selection, its row-editor placement and its authored default width. Left
1039
+ * behind, each is a key naming a question the document no longer has: unreachable state that still
1040
+ * changes `document_hash`, which is what makes it a correctness problem and not tidiness.
1041
+ */
1042
+ const scrubColumnPresentationRefs = (doc: QnrTemplateDocument, questionId: QuestionId): QnrTemplateDocument => {
1043
+ const questions = Object.entries(doc.questionsById ?? {})
1044
+ let changed = false
1045
+
1046
+ const nextQuestions = Object.fromEntries(
1047
+ questions.map(([gridQuestionId, question]) => {
1048
+ const presentation = question.presentation
1049
+ if (presentation === undefined) return [gridQuestionId, question]
1050
+
1051
+ let next: Record<string, unknown> = { ...presentation }
1052
+ let touched = false
1053
+
1054
+ const filters = presentationListOf(question, 'filterQuestionIds')
1055
+ if (filters.includes(questionId)) {
1056
+ next = writePresentationList(next, 'filterQuestionIds', filters.filter((id) => id !== questionId))
1057
+ touched = true
1058
+ }
1059
+
1060
+ const rowEditor = next['rowEditor'] as { layoutByQuestionId?: Record<string, unknown> } | undefined
1061
+ if (rowEditor?.layoutByQuestionId?.[questionId] !== undefined) {
1062
+ const layout = omitKey(rowEditor.layoutByQuestionId, questionId)
1063
+ const nextRowEditor: Record<string, unknown> = { ...rowEditor }
1064
+ if (Object.keys(layout).length === 0) delete nextRowEditor['layoutByQuestionId']
1065
+ else nextRowEditor['layoutByQuestionId'] = layout
1066
+ if (Object.keys(nextRowEditor).length === 0) delete next['rowEditor']
1067
+ else next['rowEditor'] = nextRowEditor
1068
+ touched = true
1069
+ }
1070
+
1071
+ const widths = next['defaultColumnWidthsByQuestionId'] as Record<string, number> | undefined
1072
+ if (widths?.[questionId] !== undefined) {
1073
+ const remaining = omitKey(widths, questionId)
1074
+ if (Object.keys(remaining).length === 0) delete next['defaultColumnWidthsByQuestionId']
1075
+ else next['defaultColumnWidthsByQuestionId'] = remaining
1076
+ touched = true
1077
+ }
1078
+
1079
+ if (!touched) return [gridQuestionId, question]
1080
+ changed = true
1081
+
1082
+ const nextQuestion = { ...question }
1083
+ if (Object.keys(next).length === 0) delete nextQuestion.presentation
1084
+ else nextQuestion.presentation = next
1085
+ return [gridQuestionId, nextQuestion]
1086
+ }),
1087
+ )
1088
+
1089
+ return changed ? { ...doc, questionsById: nextQuestions } : doc
589
1090
  }
590
1091
 
591
1092
  export const applyOperation = (document: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument => {
@@ -762,6 +1263,55 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
762
1263
  }
763
1264
  }
764
1265
 
1266
+ case 'gridColumn.setFilter': {
1267
+ const gridQuestion = requireGridQuestion(doc, op.questionId)
1268
+ const columnIds = gridQuestion.grid?.columnIds
1269
+ // Only a column this grid owns may offer a filter: a top-level question's filter chip would
1270
+ // have no row context to filter, and the reference would dangle on the grid's delete.
1271
+ if (!doc.questionsById?.[op.columnQuestionId] || !columnIds?.includes(op.columnQuestionId)) {
1272
+ throw new OperationConflictError(
1273
+ `Question "${op.columnQuestionId}" does not belong to grid "${op.questionId}"`,
1274
+ )
1275
+ }
1276
+
1277
+ const presentation = writePresentationList(
1278
+ { ...(gridQuestion.presentation ?? {}) },
1279
+ 'filterQuestionIds',
1280
+ setListMember(presentationListOf(gridQuestion, 'filterQuestionIds'), op.columnQuestionId, op.include, op.atIndex),
1281
+ )
1282
+ return writeGridPresentation(doc, op.questionId, gridQuestion, presentation)
1283
+ }
1284
+
1285
+ case 'gridColumn.setAction': {
1286
+ const gridQuestion = requireGridQuestion(doc, op.questionId)
1287
+ if (op.include) {
1288
+ // A grid may only own a KNOWN gridAction. A `topLevelAction` here would be owned by the
1289
+ // very grid it is supposed to drive, and an unknown legacy record has no `actionType`
1290
+ // vocabulary at all — either way the reference compiles into nothing. `include: false`
1291
+ // deliberately skips this so a malformed or legacy reference can still be scrubbed.
1292
+ requireKnownAction(doc, op.actionId, 'gridAction')
1293
+ // A grid action has at most one owning grid, which is what makes its metadata scope
1294
+ // unambiguous — the same action listed by two grids would have two column vocabularies.
1295
+ const owners = gridsOwningAction(doc, op.actionId).filter((owner) => owner !== op.questionId)
1296
+ if (owners.length > 0) {
1297
+ throw new OperationConflictError(
1298
+ `Action "${op.actionId}" is already owned by grid "${owners[0]}"`,
1299
+ )
1300
+ }
1301
+ }
1302
+
1303
+ const presentation = writePresentationList(
1304
+ { ...(gridQuestion.presentation ?? {}) },
1305
+ 'actionIds',
1306
+ setListMember(presentationListOf(gridQuestion, 'actionIds'), op.actionId, op.include, op.atIndex),
1307
+ )
1308
+ const next = writeGridPresentation(doc, op.questionId, gridQuestion, presentation)
1309
+
1310
+ // Removing a grid's action also drops it from every top-level sequence for THAT grid: the
1311
+ // reference means "run this grid's action", so it stops being expressible at the same moment.
1312
+ return op.include ? next : scrubGridActionRefs(next, op.questionId, op.actionId)
1313
+ }
1314
+
765
1315
  case 'gridRow.create': {
766
1316
  if (!doc.questionsById?.[op.questionId]) {
767
1317
  throw new OperationConflictError(`Unknown question "${op.questionId}"`)
@@ -928,6 +1478,8 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
928
1478
  if (!tab) {
929
1479
  throw new OperationConflictError(`Unknown tab "${op.tabId}"`)
930
1480
  }
1481
+ const refusal = tabFieldPathRefusal(op.field)
1482
+ if (refusal !== undefined) throw new OperationConflictError(refusal)
931
1483
  return { ...doc, tabsById: { ...doc.tabsById, [op.tabId]: writeField(tab, op.field, op.value) } }
932
1484
  }
933
1485
 
@@ -938,13 +1490,39 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
938
1490
  return { ...doc, tabOrder: moveInOrder(doc.tabOrder, op.tabId, op.toIndex) }
939
1491
  }
940
1492
 
1493
+ case 'tab.setLayout': {
1494
+ if (!doc.tabsById?.[op.tabId]) throw new OperationConflictError(`Unknown tab "${op.tabId}"`)
1495
+ if (!doc.questionsById?.[op.questionId]) {
1496
+ throw new OperationConflictError(`Unknown question "${op.questionId}"`)
1497
+ }
1498
+
1499
+ const tab = doc.tabsById[op.tabId] ?? {}
1500
+ const layout = { ...((tab.layout ?? {}) as Record<string, unknown>) }
1501
+ const placements = { ...((layout['placementsByQuestionId'] ?? {}) as Record<string, LayoutPlacement>) }
1502
+
1503
+ // One whole placement, written or removed as a unit — never a row without its cell.
1504
+ if (op.placement === null) delete placements[op.questionId]
1505
+ else placements[op.questionId] = op.placement
1506
+
1507
+ if (Object.keys(placements).length === 0) delete layout['placementsByQuestionId']
1508
+ else layout['placementsByQuestionId'] = placements
1509
+
1510
+ const nextTab = { ...tab }
1511
+ if (Object.keys(layout).length === 0) delete nextTab.layout
1512
+ else nextTab.layout = layout
1513
+
1514
+ return { ...doc, tabsById: { ...doc.tabsById, [op.tabId]: nextTab } }
1515
+ }
1516
+
941
1517
  case 'tab.delete': {
942
1518
  if (!doc.tabsById?.[op.tabId]) {
943
1519
  throw new OperationConflictError(`Unknown tab "${op.tabId}"`)
944
1520
  }
945
- return patchDocument(doc, {
946
- tabsById: doc.tabsById && omitKey(doc.tabsById, op.tabId),
947
- tabOrder: (doc.tabOrder ?? []).filter((id) => id !== op.tabId),
1521
+ // A grid naming a deleted tab as its header would point at nothing; scrub before removing.
1522
+ const scrubbed = scrubHeaderTabRefs(doc, op.tabId)
1523
+ return patchDocument(scrubbed, {
1524
+ tabsById: scrubbed.tabsById && omitKey(scrubbed.tabsById, op.tabId),
1525
+ tabOrder: (scrubbed.tabOrder ?? []).filter((id) => id !== op.tabId),
948
1526
  })
949
1527
  }
950
1528
 
@@ -966,15 +1544,126 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
966
1544
  if (!action) {
967
1545
  throw new OperationConflictError(`Unknown action "${op.actionId}"`)
968
1546
  }
1547
+ // The gate applies to KNOWN kinds only. An unknown-kind record keeps taking any field —
1548
+ // including the UI buffers legacy persisted — so a stored action replays byte-identically.
1549
+ if (isKnownActionKind(action.kind)) {
1550
+ const refusal =
1551
+ knownActionFieldRefusal(action.kind, op.field) ?? knownActionValueRefusal(op.field, op.value)
1552
+ if (refusal !== undefined) throw new OperationConflictError(refusal)
1553
+ }
969
1554
  return { ...doc, actionsById: { ...doc.actionsById, [op.actionId]: writeField(action, op.field, op.value) } }
970
1555
  }
971
1556
 
1557
+ case 'action.createTyped': {
1558
+ if (doc.actionsById?.[op.actionId]) {
1559
+ throw new OperationConflictError(`Action "${op.actionId}" already exists`)
1560
+ }
1561
+ // The op union now makes `{kind: 'topLevelAction', actionType}` unrepresentable, so this is
1562
+ // the replay/bypass boundary rather than the primary defence: an op read back from
1563
+ // `collab_ops` was never re-checked against the wire schema.
1564
+ const authoredActionType = (op as { actionType?: unknown }).actionType
1565
+ if (authoredActionType !== undefined && op.kind !== 'gridAction') {
1566
+ throw new OperationConflictError(`"actionType" belongs to a gridAction, not a ${op.kind}`)
1567
+ }
1568
+ if (authoredActionType !== undefined && !isActionType(authoredActionType)) {
1569
+ throw new OperationConflictError(`"${String(authoredActionType)}" is not a valid actionType`)
1570
+ }
1571
+
1572
+ // Minimal form: kind plus only what was authored. No empty label, no empty collections.
1573
+ return {
1574
+ ...doc,
1575
+ actionsById: {
1576
+ ...(doc.actionsById ?? {}),
1577
+ [op.actionId]: {
1578
+ kind: op.kind,
1579
+ ...(op.label === undefined ? {} : { label: op.label }),
1580
+ ...(op.actionType === undefined ? {} : { actionType: op.actionType }),
1581
+ },
1582
+ },
1583
+ }
1584
+ }
1585
+
1586
+ case 'action.setGridActionRef': {
1587
+ const action = requireKnownAction(doc, op.actionId, 'topLevelAction')
1588
+ const grid = doc.questionsById?.[op.gridQuestionId]
1589
+ if (!grid || grid.type !== 'QuestionGrid') {
1590
+ throw new OperationConflictError(`"${op.gridQuestionId}" is not a QuestionGrid`)
1591
+ }
1592
+ if (op.include) {
1593
+ // The referenced action must be a grid action THIS grid owns: a top-level button runs
1594
+ // one of that grid's actions, so a reference to an unowned one would compile to nothing.
1595
+ requireKnownAction(doc, op.gridActionId, 'gridAction')
1596
+ if (!presentationListOf(grid, 'actionIds').includes(op.gridActionId)) {
1597
+ throw new OperationConflictError(
1598
+ `Action "${op.gridActionId}" is not owned by grid "${op.gridQuestionId}"`,
1599
+ )
1600
+ }
1601
+ }
1602
+
1603
+ const byGrid = { ...((action['actionIdsByGridQuestionId'] ?? {}) as Record<string, string[]>) }
1604
+ const next = setListMember(byGrid[op.gridQuestionId] ?? [], op.gridActionId, op.include, op.atIndex)
1605
+ if (next.length === 0) delete byGrid[op.gridQuestionId]
1606
+ else byGrid[op.gridQuestionId] = next
1607
+
1608
+ const nextAction = { ...action }
1609
+ if (Object.keys(byGrid).length === 0) delete nextAction['actionIdsByGridQuestionId']
1610
+ else nextAction['actionIdsByGridQuestionId'] = byGrid
1611
+
1612
+ return { ...doc, actionsById: { ...doc.actionsById, [op.actionId]: nextAction } }
1613
+ }
1614
+
1615
+ case 'action.setMetadata': {
1616
+ const action = requireKnownAction(doc, op.actionId, 'gridAction')
1617
+
1618
+ if (op.metadata !== null) {
1619
+ // EXACTLY one owner, never "the first one found". An imported document can list one grid
1620
+ // action under two grids, and resolving the column vocabulary from `owners[0]` made the
1621
+ // same write accepted or refused purely by `questionsById` insertion order — two
1622
+ // documents with identical content and different key order disagreeing is precisely
1623
+ // what DOC-LAW-1 exists to prevent, so the ambiguity is reported instead of resolved.
1624
+ const owners = gridsOwningAction(doc, op.actionId)
1625
+ if (owners.length === 0) {
1626
+ throw new OperationConflictError(
1627
+ `Action "${op.actionId}" is owned by no grid, so its metadata has no column vocabulary`,
1628
+ )
1629
+ }
1630
+ if (owners.length > 1) {
1631
+ throw new OperationConflictError(
1632
+ `Action "${op.actionId}" is owned by ${owners.length} grids (${[...owners].sort().join(', ')}); its metadata scope is ambiguous`,
1633
+ )
1634
+ }
1635
+
1636
+ // A metadata key is a COLUMN of the owning grid, not an arbitrary question: the action
1637
+ // copies or updates values within its own rows.
1638
+ const columnIds = doc.questionsById?.[owners[0] as string]?.grid?.columnIds ?? []
1639
+ if (!columnIds.includes(op.questionId)) {
1640
+ throw new OperationConflictError(
1641
+ `Question "${op.questionId}" is not a column of grid "${owners[0]}"`,
1642
+ )
1643
+ }
1644
+ }
1645
+ // `metadata: null` needs no owner: removal is how a malformed or orphaned record gets
1646
+ // repaired, and requiring an owner would make exactly the documents that need fixing
1647
+ // unfixable.
1648
+
1649
+ const byQuestion = { ...((action['metadataByQuestionId'] ?? {}) as Record<string, ActionMetadata>) }
1650
+ if (op.metadata === null) delete byQuestion[op.questionId]
1651
+ else byQuestion[op.questionId] = canonicalActionMetadata(op.metadata)
1652
+
1653
+ const nextAction = { ...action }
1654
+ if (Object.keys(byQuestion).length === 0) delete nextAction['metadataByQuestionId']
1655
+ else nextAction['metadataByQuestionId'] = byQuestion
1656
+
1657
+ return { ...doc, actionsById: { ...doc.actionsById, [op.actionId]: nextAction } }
1658
+ }
1659
+
972
1660
  case 'action.delete': {
973
1661
  if (!doc.actionsById?.[op.actionId]) {
974
1662
  throw new OperationConflictError(`Unknown action "${op.actionId}"`)
975
1663
  }
976
- return patchDocument(doc, {
977
- actionsById: doc.actionsById && omitKey(doc.actionsById, op.actionId),
1664
+ const scrubbed = scrubActionRefs(doc, op.actionId)
1665
+ return patchDocument(scrubbed, {
1666
+ actionsById: scrubbed.actionsById && omitKey(scrubbed.actionsById, op.actionId),
978
1667
  })
979
1668
  }
980
1669
 
@@ -1203,6 +1892,44 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
1203
1892
  }
1204
1893
  }
1205
1894
 
1895
+ case 'mappingFilter.setTyped': {
1896
+ assertTypedFilterPayload(op)
1897
+ const node = doc.mappingNodesById?.[op.nodeId]
1898
+ if (!node) throw new OperationConflictError(`Unknown mapping node "${op.nodeId}"`)
1899
+
1900
+ // REPLACED, not patched: switching `eq` -> `in` must not leave the old `value` beside the
1901
+ // new `values`, which a merge would. A filter carries its own operator's members and no
1902
+ // others, so one operator is always readable from the record alone.
1903
+ const filter: MappingFilter =
1904
+ op.operator === 'eq'
1905
+ ? { fieldId: op.fieldId, operator: 'eq', value: op.value }
1906
+ : op.operator === 'in'
1907
+ ? { fieldId: op.fieldId, operator: 'in', values: [...op.values] }
1908
+ : op.operator === 'isNull'
1909
+ ? { fieldId: op.fieldId, operator: 'isNull', value: op.value }
1910
+ : // `range` by elimination is safe ONLY because the validator above closed the
1911
+ // operator set first; before it did, an unknown operator landed here.
1912
+ {
1913
+ fieldId: op.fieldId,
1914
+ operator: 'range',
1915
+ ...('from' in op && op.from !== undefined ? { from: op.from } : {}),
1916
+ ...('to' in op && op.to !== undefined ? { to: op.to } : {}),
1917
+ }
1918
+
1919
+ const filterOrder = node.filterOrder ?? []
1920
+ return {
1921
+ ...doc,
1922
+ mappingFiltersById: { ...(doc.mappingFiltersById ?? {}), [op.filterId]: filter },
1923
+ mappingNodesById: {
1924
+ ...doc.mappingNodesById,
1925
+ [op.nodeId]: {
1926
+ ...node,
1927
+ filterOrder: filterOrder.includes(op.filterId) ? filterOrder : [...filterOrder, op.filterId],
1928
+ },
1929
+ },
1930
+ }
1931
+ }
1932
+
1206
1933
  case 'mappingFilter.delete': {
1207
1934
  const nodes = Object.fromEntries(
1208
1935
  Object.entries(doc.mappingNodesById ?? {}).map(([nodeId, node]) => {