asma-core-helpers 0.32.0 → 0.33.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 (32) hide show
  1. package/lib/collaboration/applyOperation.d.ts +5 -13
  2. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  3. package/lib/collaboration/applyOperation.js +450 -20
  4. package/lib/collaboration/applyOperation.js.map +1 -1
  5. package/lib/collaboration/operations.d.ts +113 -1
  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 +54 -0
  10. package/lib/collaboration/schemas.d.ts.map +1 -1
  11. package/lib/collaboration/schemas.js +74 -1
  12. package/lib/collaboration/schemas.js.map +1 -1
  13. package/lib/collaboration/templateDocument.d.ts +194 -0
  14. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  15. package/lib/collaboration/templateDocument.js +104 -0
  16. package/lib/collaboration/templateDocument.js.map +1 -1
  17. package/lib/collaboration/testHelpers/documentGenerator.d.ts +24 -0
  18. package/lib/collaboration/testHelpers/documentGenerator.d.ts.map +1 -1
  19. package/lib/collaboration/testHelpers/documentGenerator.js +180 -2
  20. package/lib/collaboration/testHelpers/documentGenerator.js.map +1 -1
  21. package/lib/collaboration/typeContracts.d.ts +73 -1
  22. package/lib/collaboration/typeContracts.d.ts.map +1 -1
  23. package/package.json +1 -1
  24. package/src/collaboration/applyOperation.ts +517 -17
  25. package/src/collaboration/operations.ts +95 -0
  26. package/src/collaboration/property.test.ts +49 -0
  27. package/src/collaboration/schemas.ts +82 -0
  28. package/src/collaboration/templateDocument.ts +238 -1
  29. package/src/collaboration/testHelpers/documentGenerator.ts +201 -2
  30. package/src/collaboration/typeContracts.ts +106 -1
  31. package/src/collaboration/typedAuthoring.test.ts +1091 -0
  32. package/src/collaboration/typedAuthoringHardening.test.ts +344 -1
@@ -36,20 +36,12 @@ export declare class OperationConflictError extends CollaborationError {
36
36
  constructor(message: string);
37
37
  }
38
38
  /**
39
- * The action, if it is a KNOWN one — `kind` inside the closed vocabulary.
39
+ * The reserved path `field` would write, if any.
40
40
  *
41
- * A legacy record with an unknown `kind` is not "known but unrecognised": the typed ops refuse it
42
- * outright rather than half-applying rules written for a different shape, which is what keeps old
43
- * documents replaying byte-identically.
44
- */
45
- /**
46
- * Why `field` may not be written as an ordinary tab field edit, or `undefined` if it may.
47
- *
48
- * `layout.placementsByQuestionId` is reserved for `tab.setLayout`. Unlike the grid's filter list this
49
- * one is not even expressible as an `OpValue` — a placement is an object — so the realistic misuse is a
50
- * write to an ANCESTOR (`layout`, or the placements map cleared wholesale), which would drop every other
51
- * question's placement in one edit. Both directions of overlap are refused; `label` and any other
52
- * authored scalar stay ordinary field edits.
41
+ * Both directions count, as they do for the grid-owned paths: the path itself, a path *below* it
42
+ * (`questionIds.0`), and an *ancestor* whose write would carry the reserved collection with it
43
+ * (`layout`). Checking only exact equality would leave `layout` and `questionIds.0` open, which is a
44
+ * whole-snapshot overwrite by another spelling.
53
45
  */
54
46
  export declare const tabFieldPathRefusal: (field: string) => string | undefined;
55
47
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"applyOperation.d.ts","sourceRoot":"","sources":["../../src/collaboration/applyOperation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,KAAK,EAGR,eAAe,EAUf,mBAAmB,EAEtB,MAAM,uBAAuB,CAAA;AAmB9B;;;;;;;;;;;;;;;;GAgBG;AAEH;;;;;;GAMG;AACH,qBAAa,kBAAmB,SAAQ,KAAK;IACzC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IAErB,YAAY,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAK5D;CACJ;AAED,qBAAa,qBAAsB,SAAQ,kBAAkB;IACzD,YAAY,IAAI,EAAE,MAAM,EAEvB;CACJ;AAED,qBAAa,sBAAuB,SAAQ,kBAAkB;IAC1D,YAAY,OAAO,EAAE,MAAM,EAE1B;CACJ;AAkJD;;;;;;GAMG;AACH;;;;;;;;GAQG;AACH,eAAO,MAAM,mBAAmB,UAAW,MAAM,KAAG,MAAM,GAAG,SAQ5D,CAAA;AA0GD;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,SAAU,eAAe,SAAS,MAAM,KAAG,MAAM,GAAG,SAuBvF,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,uBAAuB,UAAW,MAAM,SAAS,OAAO,KAAG,MAAM,GAAG,SAWhF,CAAA;AA4qBD,eAAO,MAAM,cAAc,aAAc,mBAAmB,MAAM,UAAU,KAAG,mBAG9E,CAAA"}
1
+ {"version":3,"file":"applyOperation.d.ts","sourceRoot":"","sources":["../../src/collaboration/applyOperation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,KAAK,EAKR,eAAe,EAYf,mBAAmB,EAEtB,MAAM,uBAAuB,CAAA;AAuB9B;;;;;;;;;;;;;;;;GAgBG;AAEH;;;;;;GAMG;AACH,qBAAa,kBAAmB,SAAQ,KAAK;IACzC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IAErB,YAAY,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAK5D;CACJ;AAED,qBAAa,qBAAsB,SAAQ,kBAAkB;IACzD,YAAY,IAAI,EAAE,MAAM,EAEvB;CACJ;AAED,qBAAa,sBAAuB,SAAQ,kBAAkB;IAC1D,YAAY,OAAO,EAAE,MAAM,EAE1B;CACJ;AA+KD;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,UAAW,MAAM,KAAG,MAAM,GAAG,SAQ5D,CAAA;AA6ID;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,SAAU,eAAe,SAAS,MAAM,KAAG,MAAM,GAAG,SAuBvF,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,uBAAuB,UAAW,MAAM,SAAS,OAAO,KAAG,MAAM,GAAG,SAWhF,CAAA;AAs2BD,eAAO,MAAM,cAAc,aAAc,mBAAmB,MAAM,UAAU,KAAG,mBAG9E,CAAA"}
@@ -1,4 +1,4 @@
1
- import { ACTION_TYPES, BINDING_OPTION_DEFAULTS, MAPPING_FILTER_OPERATORS, bindingTargetKey, isKnownActionKind, } from './templateDocument.js';
1
+ import { ACTION_TYPES, BINDING_OPTION_DEFAULTS, MAPPING_FILTER_OPERATORS, bindingTargetKey, isKnownActionKind, makeExpressionAlternativeToken, makeExpressionTargetToken, parseLegacyBindingOverride, } from './templateDocument.js';
2
2
  /** Runtime narrowing for the two closed vocabularies the reducer must re-check on replay. */
3
3
  const isActionType = (value) => typeof value === 'string' && ACTION_TYPES.includes(value);
4
4
  const isDocScalarValue = (value) => typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';
@@ -179,13 +179,67 @@ const gridsOwningAction = (doc, actionId) => Object.entries(doc.questionsById ??
179
179
  * question's placement in one edit. Both directions of overlap are refused; `label` and any other
180
180
  * authored scalar stay ordinary field edits.
181
181
  */
182
+ /**
183
+ * The tab-owned collections `tab.updateField` may not write, and the operation that owns each.
184
+ *
185
+ * All three are maintained one member at a time. A whole-snapshot write through `updateField` would
186
+ * reintroduce exactly the lost update the member-wise operations exist to prevent: two authors editing
187
+ * different members would produce two full-collection patches and the second would discard the first.
188
+ */
189
+ const TAB_OWNED_FIELD_PATHS = [
190
+ ['layout.placementsByQuestionId', 'tab.setLayout'],
191
+ ['questionIds', 'tab.setQuestion'],
192
+ ['rowCountQuestionIds', 'tab.setRowCountQuestion'],
193
+ ];
194
+ /**
195
+ * The reserved path `field` would write, if any.
196
+ *
197
+ * Both directions count, as they do for the grid-owned paths: the path itself, a path *below* it
198
+ * (`questionIds.0`), and an *ancestor* whose write would carry the reserved collection with it
199
+ * (`layout`). Checking only exact equality would leave `layout` and `questionIds.0` open, which is a
200
+ * whole-snapshot overwrite by another spelling.
201
+ */
182
202
  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`;
203
+ for (const [reserved, owner] of TAB_OWNED_FIELD_PATHS) {
204
+ if (field === reserved || field.startsWith(`${reserved}.`) || reserved.startsWith(`${field}.`)) {
205
+ return `Field "${field}" writes "${reserved}", which only ${owner} may author`;
206
+ }
186
207
  }
187
208
  return undefined;
188
209
  };
210
+ /** One tab-owned primitive id list, defensively filtered: the tab bag is open and may hold anything. */
211
+ const tabListOf = (tab, key) => {
212
+ const value = tab[key];
213
+ return Array.isArray(value) ? value.filter((member) => typeof member === 'string') : [];
214
+ };
215
+ /** Writes one tab-owned list back, omitting it when empty — DOC-LAW-2 admits no stored `[]`. */
216
+ const writeTabList = (tab, key, next) => {
217
+ const copy = { ...tab };
218
+ if (next.length === 0)
219
+ delete copy[key];
220
+ else
221
+ copy[key] = [...next];
222
+ return copy;
223
+ };
224
+ /** Drops a question from a tab's layout, pruning the emptied placements map and layout object. */
225
+ const withoutTabPlacement = (tab, questionId) => {
226
+ const layout = (tab['layout'] ?? {});
227
+ const placements = (layout['placementsByQuestionId'] ?? {});
228
+ if (placements[questionId] === undefined)
229
+ return tab;
230
+ const nextPlacements = omitKey(placements, questionId);
231
+ const nextLayout = { ...layout };
232
+ if (Object.keys(nextPlacements).length === 0)
233
+ delete nextLayout['placementsByQuestionId'];
234
+ else
235
+ nextLayout['placementsByQuestionId'] = nextPlacements;
236
+ const next = { ...tab };
237
+ if (Object.keys(nextLayout).length === 0)
238
+ delete next['layout'];
239
+ else
240
+ next['layout'] = nextLayout;
241
+ return next;
242
+ };
189
243
  /**
190
244
  * Validates a `mappingFilter.setTyped` payload in the REDUCER, not only at the wire.
191
245
  *
@@ -390,32 +444,195 @@ const scrubGridActionRefs = (doc, gridQuestionId, gridActionId) => {
390
444
  return changed ? { ...doc, actionsById: nextActions } : doc;
391
445
  };
392
446
  /** Drops a deleted question's placement from every tab layout, and every emptied container with it. */
393
- const scrubTabPlacements = (doc, questionId) => {
447
+ const scrubTabQuestionRefs = (doc, questionId) => {
394
448
  const tabs = Object.entries(doc.tabsById ?? {});
395
449
  if (tabs.length === 0)
396
450
  return doc;
397
451
  let changed = false;
398
452
  const nextTabs = Object.fromEntries(tabs.map(([tabId, tab]) => {
453
+ const members = tabListOf(tab, 'questionIds');
454
+ const counted = tabListOf(tab, 'rowCountQuestionIds');
399
455
  const layout = (tab.layout ?? {});
400
456
  const placements = (layout['placementsByQuestionId'] ?? {});
401
- if (placements[questionId] === undefined)
457
+ const inMembers = members.includes(questionId);
458
+ const inCounted = counted.includes(questionId);
459
+ const inLayout = placements[questionId] !== undefined;
460
+ if (!inMembers && !inCounted && !inLayout)
402
461
  return [tabId, tab];
403
462
  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];
463
+ let next = { ...tab };
464
+ if (inMembers)
465
+ next = writeTabList(next, 'questionIds', members.filter((id) => id !== questionId));
466
+ if (inCounted) {
467
+ next = writeTabList(next, 'rowCountQuestionIds', counted.filter((id) => id !== questionId));
468
+ }
469
+ if (inLayout)
470
+ next = withoutTabPlacement(next, questionId);
471
+ return [tabId, next];
416
472
  }));
417
473
  return changed ? { ...doc, tabsById: nextTabs } : doc;
418
474
  };
475
+ /**
476
+ * The question types that may be an Expression/Chart target: they carry alternatives to score, plus
477
+ * `LinearScale`, whose numeric range legacy also admits.
478
+ *
479
+ * `Chart` is excluded even though it carries alternatives — a chart scoring a chart is the cycle legacy
480
+ * never allowed.
481
+ *
482
+ * **A deliberately explicit opt-in literal, not derived from anything.** There is no selectable-type
483
+ * register in `questionTypes.ts` to derive it from, and inventing one would make targetability a
484
+ * side-effect of how a type is classified elsewhere. Adding a question type must be a decision taken
485
+ * here, in this list.
486
+ *
487
+ * `satisfies readonly QuestionType[]` is what stops that literal from rotting: a typo'd or removed
488
+ * question type fails `ts:check` instead of becoming silently dead code that refuses a legitimate
489
+ * target forever. The membership itself — which six types, and no others — is pinned in both directions
490
+ * by a table-driven test, because the type system cannot tell a deliberate list from a wrong one.
491
+ */
492
+ const EXPRESSION_TARGET_TYPES = [
493
+ 'BooleanQuestion',
494
+ 'CheckBoxes',
495
+ 'Dropdown',
496
+ 'Emoticons',
497
+ 'LinearScale',
498
+ 'RadioButtons',
499
+ ];
500
+ /**
501
+ * Whether one question may be cited as an Expression target or a Chart assignment target.
502
+ *
503
+ * `flags.is_expression` must be explicitly `true`. The flags bag is open, so a merely *present* flag is
504
+ * not enough: a question carrying `is_expression: 'no'` or an imported non-boolean would otherwise pass.
505
+ */
506
+ const isExpressionTarget = (question) => {
507
+ if (!question)
508
+ return false;
509
+ if (!EXPRESSION_TARGET_TYPES.includes(question.type))
510
+ return false;
511
+ const flags = question['flags'];
512
+ if (typeof flags !== 'object' || flags === null || Array.isArray(flags))
513
+ return false;
514
+ return flags['is_expression'] === true;
515
+ };
516
+ /** A question of the required type, or a refusal naming what was wrong. */
517
+ const requireQuestionOfType = (doc, questionId, type) => {
518
+ const question = doc.questionsById?.[questionId];
519
+ if (!question)
520
+ throw new OperationConflictError(`Unknown question "${questionId}"`);
521
+ if (question.type !== type) {
522
+ throw new OperationConflictError(`Question "${questionId}" is not a ${type}`);
523
+ }
524
+ return question;
525
+ };
526
+ /** Refuses unless the alternative is in that exact question's order — ownership, not mere existence. */
527
+ const requireOwnedAlternative = (doc, questionId, alternativeId) => {
528
+ if (!doc.alternativeOrderByQuestionId?.[questionId]?.includes(alternativeId)) {
529
+ throw new OperationConflictError(`Alternative "${alternativeId}" does not belong to question "${questionId}"`);
530
+ }
531
+ return doc.alternativesById?.[alternativeId] ?? {};
532
+ };
533
+ /** One Chart question's legend record and order, defensively read out of the open `chart` bag. */
534
+ const chartOf = (question) => {
535
+ const chart = (question['chart'] ?? {});
536
+ const legendsById = (chart['legendsById'] ?? {});
537
+ const rawOrder = chart['legendsOrder'];
538
+ const order = Array.isArray(rawOrder) ? rawOrder.filter((id) => typeof id === 'string') : [];
539
+ return { chart, legendsById, order };
540
+ };
541
+ /** Writes a Chart bag back onto its question, pruning emptied containers without deleting the question. */
542
+ const writeChart = (doc, questionId, question, chart) => {
543
+ const next = { ...question };
544
+ if (Object.keys(chart).length === 0)
545
+ delete next['chart'];
546
+ else
547
+ next['chart'] = chart;
548
+ return { ...doc, questionsById: { ...doc.questionsById, [questionId]: next } };
549
+ };
550
+ /**
551
+ * Removes one alternative's exact canonical `<exp_...>` token from its owning question's base formula.
552
+ *
553
+ * Scoped to the owner and to the canonical spelling on purpose: a substring scan would corrupt author
554
+ * text, and rewriting another question's formula would be an edit no operation asked for.
555
+ */
556
+ const withoutExpressionAlternativeToken = (doc, questionId, alternativeId) => {
557
+ const question = doc.questionsById?.[questionId];
558
+ const expression = question?.['expression'];
559
+ if (typeof expression !== 'object' || expression === null || Array.isArray(expression))
560
+ return doc;
561
+ const base = expression['base'];
562
+ const token = makeExpressionAlternativeToken(alternativeId);
563
+ if (typeof base !== 'string' || !base.includes(token))
564
+ return doc;
565
+ const nextBase = base.split(token).join('');
566
+ const nextExpression = { ...expression };
567
+ if (nextBase === '')
568
+ delete nextExpression['base'];
569
+ else
570
+ nextExpression['base'] = nextBase;
571
+ const nextQuestion = { ...question };
572
+ if (Object.keys(nextExpression).length === 0)
573
+ delete nextQuestion['expression'];
574
+ else
575
+ nextQuestion['expression'] = nextExpression;
576
+ return {
577
+ ...doc,
578
+ questionsById: { ...doc.questionsById, [questionId]: nextQuestion },
579
+ };
580
+ };
581
+ /** One question's canonical `expressionTargets` list, defensively filtered — the bag is open. */
582
+ const expressionTargetsOf = (alternative) => {
583
+ const value = alternative['expressionTargets'];
584
+ return Array.isArray(value) ? value.filter((member) => typeof member === 'string') : [];
585
+ };
586
+ /**
587
+ * Drops a deleted question from every canonical Expression target list and Chart assignment.
588
+ *
589
+ * Three edits on one alternative, all keyed on the **exact canonical** form:
590
+ * - the id leaves `expressionTargets`;
591
+ * - its canonical `<target_...>` token in `value` becomes `0`, so the formula still parses as
592
+ * arithmetic instead of carrying a reference to a question that no longer exists;
593
+ * - a `chartLegend` whose `questionIdMap` cites it is cleared whole.
594
+ *
595
+ * **Exact token replacement, never substring matching.** A legacy formula holds truncated
596
+ * last-eight-character tokens and arbitrary author text; scanning for a fragment would rewrite text
597
+ * this reducer has no claim on. Only the full canonical token is replaced, which is why it is generated
598
+ * here from the same constructor the authoring path uses rather than pattern-matched.
599
+ */
600
+ const scrubExpressionAndChartRefs = (doc, questionId) => {
601
+ const alternatives = Object.entries(doc.alternativesById ?? {});
602
+ if (alternatives.length === 0)
603
+ return doc;
604
+ const token = makeExpressionTargetToken(questionId);
605
+ let changed = false;
606
+ const nextAlternatives = Object.fromEntries(alternatives.map(([alternativeId, alternative]) => {
607
+ const targets = expressionTargetsOf(alternative);
608
+ const hasTarget = targets.includes(questionId);
609
+ const formula = alternative['value'];
610
+ const hasToken = typeof formula === 'string' && formula.includes(token);
611
+ const assignment = alternative['chartLegend'];
612
+ const hasAssignment = typeof assignment === 'object' &&
613
+ assignment !== null &&
614
+ !Array.isArray(assignment) &&
615
+ assignment['questionIdMap'] === questionId;
616
+ if (!hasTarget && !hasToken && !hasAssignment)
617
+ return [alternativeId, alternative];
618
+ changed = true;
619
+ const next = { ...alternative };
620
+ if (hasTarget) {
621
+ const remaining = targets.filter((id) => id !== questionId);
622
+ if (remaining.length === 0)
623
+ delete next['expressionTargets'];
624
+ else
625
+ next['expressionTargets'] = remaining;
626
+ }
627
+ // `split`/`join` replaces every occurrence: one formula may cite the same target twice.
628
+ if (hasToken)
629
+ next['value'] = formula.split(token).join('0');
630
+ if (hasAssignment)
631
+ delete next['chartLegend'];
632
+ return [alternativeId, next];
633
+ }));
634
+ return changed ? { ...doc, alternativesById: nextAlternatives } : doc;
635
+ };
419
636
  /** Drops a deleted tab from every grid that named it as its header. */
420
637
  const scrubHeaderTabRefs = (doc, tabId) => {
421
638
  const questions = Object.entries(doc.questionsById ?? {});
@@ -897,7 +1114,7 @@ const deleteQuestion = (doc, questionId) => {
897
1114
  // presentation references a column earns: its filter chip, its row-editor placement, its default
898
1115
  // width, and its placement inside any tab's positional grid.
899
1116
  const withoutRefs = dropBindingsForQuestion(dropFromGridColumns(withoutQuestion, questionId), questionId);
900
- return scrubTabPlacements(scrubColumnPresentationRefs(withoutRefs, questionId), questionId);
1117
+ return scrubExpressionAndChartRefs(scrubTabQuestionRefs(scrubColumnPresentationRefs(withoutRefs, questionId), questionId), questionId);
901
1118
  };
902
1119
  /**
903
1120
  * Drops a deleted column from every grid presentation that referenced it.
@@ -1274,10 +1491,162 @@ const reduce = (doc, op) => {
1274
1491
  throw new OperationConflictError(`Alternative "${op.alternativeId}" does not belong to question "${op.questionId}"`);
1275
1492
  }
1276
1493
  const remaining = order.filter((id) => id !== op.alternativeId);
1277
- return patchDocument(doc, {
1494
+ const withoutAlternative = patchDocument(doc, {
1278
1495
  alternativesById: doc.alternativesById && omitKey(doc.alternativesById, op.alternativeId),
1279
1496
  alternativeOrderByQuestionId: setOrRemoveOrder(doc.alternativeOrderByQuestionId, op.questionId, remaining),
1280
1497
  });
1498
+ // An ExpressionQuestion's `expression.base` cites its alternatives by canonical token. The
1499
+ // token must go with the alternative, and only from THIS question's formula: another
1500
+ // question's text is not this operation's to rewrite, and a legacy truncated token is not
1501
+ // canonical so it is deliberately left alone for publication to report.
1502
+ return withoutExpressionAlternativeToken(withoutAlternative, op.questionId, op.alternativeId);
1503
+ }
1504
+ case 'alternative.setExpressionFormula': {
1505
+ requireQuestionOfType(doc, op.questionId, 'ExpressionQuestion');
1506
+ const alternative = requireOwnedAlternative(doc, op.questionId, op.alternativeId);
1507
+ // Duplicates first: the list is an ordered set, and a repeated target would make one
1508
+ // question contribute twice to a formula that names it once.
1509
+ const seen = new Set();
1510
+ for (const targetId of op.expressionTargets) {
1511
+ if (seen.has(targetId)) {
1512
+ throw new OperationConflictError(`Expression target "${targetId}" is listed twice`);
1513
+ }
1514
+ seen.add(targetId);
1515
+ if (!doc.questionsById?.[targetId]) {
1516
+ throw new OperationConflictError(`Unknown question "${targetId}"`);
1517
+ }
1518
+ if (!isExpressionTarget(doc.questionsById[targetId])) {
1519
+ throw new OperationConflictError(`Question "${targetId}" is not a selectable or LinearScale question with flags.is_expression`);
1520
+ }
1521
+ }
1522
+ // Formula text and target list land together. The two are NOT cross-checked: a partially
1523
+ // typed formula must save, so a token with no target and a target with no token are both
1524
+ // legal drafts that publication reports rather than the reducer refusing.
1525
+ const next = { ...alternative, value: op.value };
1526
+ if (op.expressionTargets.length === 0)
1527
+ delete next['expressionTargets'];
1528
+ else
1529
+ next['expressionTargets'] = [...op.expressionTargets];
1530
+ return {
1531
+ ...doc,
1532
+ alternativesById: { ...doc.alternativesById, [op.alternativeId]: next },
1533
+ };
1534
+ }
1535
+ case 'alternative.setChartLegend': {
1536
+ const question = requireQuestionOfType(doc, op.questionId, 'Chart');
1537
+ const alternative = requireOwnedAlternative(doc, op.questionId, op.alternativeId);
1538
+ if (op.chartLegend === null) {
1539
+ // Clearing needs no valid stored value: that is what makes it able to repair an imported
1540
+ // dangling or non-radar assignment.
1541
+ if (alternative['chartLegend'] === undefined)
1542
+ return doc;
1543
+ const cleared = { ...alternative };
1544
+ delete cleared['chartLegend'];
1545
+ return {
1546
+ ...doc,
1547
+ alternativesById: { ...doc.alternativesById, [op.alternativeId]: cleared },
1548
+ };
1549
+ }
1550
+ // Authoring a new assignment requires the canonical subtype; a stored `pie` or unknown type
1551
+ // stays readable and clearable but never becomes writable through the typed path.
1552
+ const { legendsById } = chartOf(question);
1553
+ if (question['chart'] === undefined || question['chart']['type'] !== 'radar') {
1554
+ throw new OperationConflictError(`Question "${op.questionId}" is not a radar chart`);
1555
+ }
1556
+ const legend = legendsById[op.chartLegend.id];
1557
+ if (!legend) {
1558
+ throw new OperationConflictError(`Unknown chart legend "${op.chartLegend.id}" on question "${op.questionId}"`);
1559
+ }
1560
+ const target = doc.questionsById?.[op.chartLegend.questionIdMap];
1561
+ if (!target) {
1562
+ throw new OperationConflictError(`Unknown question "${op.chartLegend.questionIdMap}"`);
1563
+ }
1564
+ if (!isExpressionTarget(target)) {
1565
+ throw new OperationConflictError(`Question "${op.chartLegend.questionIdMap}" is not a selectable or LinearScale question with flags.is_expression`);
1566
+ }
1567
+ // One write of the whole value, with `label` derived here rather than taken from the client:
1568
+ // a client label would let one legend id carry two labels, i.e. two hashes for one state.
1569
+ const assignment = {
1570
+ id: op.chartLegend.id,
1571
+ questionIdMap: op.chartLegend.questionIdMap,
1572
+ label: legend.label,
1573
+ };
1574
+ return {
1575
+ ...doc,
1576
+ alternativesById: {
1577
+ ...doc.alternativesById,
1578
+ [op.alternativeId]: { ...alternative, chartLegend: assignment },
1579
+ },
1580
+ };
1581
+ }
1582
+ case 'chartLegend.create': {
1583
+ const question = requireQuestionOfType(doc, op.questionId, 'Chart');
1584
+ if (op.legendId === '')
1585
+ throw new OperationConflictError('A chart legend id may not be empty');
1586
+ if (op.label === '')
1587
+ throw new OperationConflictError('A chart legend label may not be empty');
1588
+ const { chart, legendsById, order } = chartOf(question);
1589
+ // Creation is the one Chart operation that requires the canonical subtype: deletion and
1590
+ // clearing must stay available to repair imported `pie`/unknown content.
1591
+ if (chart['type'] !== 'radar') {
1592
+ throw new OperationConflictError(`Question "${op.questionId}" is not a radar chart`);
1593
+ }
1594
+ if (legendsById[op.legendId] !== undefined) {
1595
+ throw new OperationConflictError(`Chart legend "${op.legendId}" already exists`);
1596
+ }
1597
+ // Legacy compares labels by exact equality, and two legends with one label are
1598
+ // indistinguishable in the radar the author is looking at.
1599
+ if (Object.values(legendsById).some((existing) => existing.label === op.label)) {
1600
+ throw new OperationConflictError(`Chart legend label "${op.label}" is already used`);
1601
+ }
1602
+ // Record and order in one write: a record with no order entry is unreachable state that
1603
+ // still moves the hash, and an order entry with no record dangles.
1604
+ const nextChart = {
1605
+ ...chart,
1606
+ legendsById: { ...legendsById, [op.legendId]: { id: op.legendId, label: op.label } },
1607
+ legendsOrder: insertAt(order, op.legendId, op.atIndex),
1608
+ };
1609
+ return writeChart(doc, op.questionId, question, nextChart);
1610
+ }
1611
+ case 'chartLegend.delete': {
1612
+ const question = requireQuestionOfType(doc, op.questionId, 'Chart');
1613
+ const { chart, legendsById, order } = chartOf(question);
1614
+ if (legendsById[op.legendId] === undefined) {
1615
+ throw new OperationConflictError(`Unknown chart legend "${op.legendId}" on question "${op.questionId}"`);
1616
+ }
1617
+ const remainingLegends = omitKey(legendsById, op.legendId);
1618
+ const remainingOrder = order.filter((id) => id !== op.legendId);
1619
+ const nextChart = { ...chart };
1620
+ if (Object.keys(remainingLegends).length === 0)
1621
+ delete nextChart['legendsById'];
1622
+ else
1623
+ nextChart['legendsById'] = remainingLegends;
1624
+ if (remainingOrder.length === 0)
1625
+ delete nextChart['legendsOrder'];
1626
+ else
1627
+ nextChart['legendsOrder'] = remainingOrder;
1628
+ const withoutLegend = writeChart(doc, op.questionId, question, nextChart);
1629
+ // The cascade matches the legacy effect: a legend that disappears stops appearing on
1630
+ // alternatives. Scoped to THIS Chart's own alternatives — an identical legend id on another
1631
+ // question is a different legend, and imported ids do collide across questions.
1632
+ const ownedAlternativeIds = withoutLegend.alternativeOrderByQuestionId?.[op.questionId] ?? [];
1633
+ let alternativesById = withoutLegend.alternativesById;
1634
+ let changed = false;
1635
+ for (const alternativeId of ownedAlternativeIds) {
1636
+ const alternative = alternativesById?.[alternativeId];
1637
+ const assignment = alternative?.['chartLegend'];
1638
+ if (typeof assignment !== 'object' ||
1639
+ assignment === null ||
1640
+ Array.isArray(assignment) ||
1641
+ assignment['id'] !== op.legendId) {
1642
+ continue;
1643
+ }
1644
+ const cleared = { ...alternative };
1645
+ delete cleared['chartLegend'];
1646
+ alternativesById = { ...alternativesById, [alternativeId]: cleared };
1647
+ changed = true;
1648
+ }
1649
+ return changed && alternativesById ? { ...withoutLegend, alternativesById } : withoutLegend;
1281
1650
  }
1282
1651
  case 'tab.create': {
1283
1652
  if (doc.tabsById?.[op.tabId]) {
@@ -1330,6 +1699,45 @@ const reduce = (doc, op) => {
1330
1699
  nextTab.layout = layout;
1331
1700
  return { ...doc, tabsById: { ...doc.tabsById, [op.tabId]: nextTab } };
1332
1701
  }
1702
+ case 'tab.setQuestion': {
1703
+ const tab = doc.tabsById?.[op.tabId];
1704
+ if (!tab)
1705
+ throw new OperationConflictError(`Unknown tab "${op.tabId}"`);
1706
+ // Only inclusion needs a live question. Exclusion stays available with no question at all so
1707
+ // an imported document naming a question it never had can be repaired.
1708
+ if (op.include && !doc.questionsById?.[op.questionId]) {
1709
+ throw new OperationConflictError(`Unknown question "${op.questionId}"`);
1710
+ }
1711
+ let next = writeTabList({ ...tab }, 'questionIds', setListMember(tabListOf(tab, 'questionIds'), op.questionId, op.include, op.atIndex));
1712
+ // Dropping membership drops what membership entitled the question to. A counted row or a
1713
+ // placement for a question the tab no longer shows is a reference to nothing, and it still
1714
+ // changes `document_hash`.
1715
+ if (!op.include) {
1716
+ next = writeTabList(next, 'rowCountQuestionIds', tabListOf(tab, 'rowCountQuestionIds').filter((id) => id !== op.questionId));
1717
+ next = withoutTabPlacement(next, op.questionId);
1718
+ }
1719
+ return { ...doc, tabsById: { ...doc.tabsById, [op.tabId]: next } };
1720
+ }
1721
+ case 'tab.setRowCountQuestion': {
1722
+ const tab = doc.tabsById?.[op.tabId];
1723
+ if (!tab)
1724
+ throw new OperationConflictError(`Unknown tab "${op.tabId}"`);
1725
+ if (op.include) {
1726
+ const question = doc.questionsById?.[op.questionId];
1727
+ if (!question)
1728
+ throw new OperationConflictError(`Unknown question "${op.questionId}"`);
1729
+ // Only a grid has rows to count, and only a member of this tab contributes to its count.
1730
+ if (question.type !== 'QuestionGrid') {
1731
+ throw new OperationConflictError(`Question "${op.questionId}" is not a question grid`);
1732
+ }
1733
+ if (!tabListOf(tab, 'questionIds').includes(op.questionId)) {
1734
+ throw new OperationConflictError(`Question "${op.questionId}" is not a member of tab "${op.tabId}"`);
1735
+ }
1736
+ }
1737
+ // Membership and layout are untouched: this operation owns exactly one list.
1738
+ const next = writeTabList({ ...tab }, 'rowCountQuestionIds', setListMember(tabListOf(tab, 'rowCountQuestionIds'), op.questionId, op.include, op.atIndex));
1739
+ return { ...doc, tabsById: { ...doc.tabsById, [op.tabId]: next } };
1740
+ }
1333
1741
  case 'tab.delete': {
1334
1742
  if (!doc.tabsById?.[op.tabId]) {
1335
1743
  throw new OperationConflictError(`Unknown tab "${op.tabId}"`);
@@ -1638,6 +2046,28 @@ const reduce = (doc, op) => {
1638
2046
  },
1639
2047
  };
1640
2048
  }
2049
+ case 'mappingBinding.setLegacyOverride': {
2050
+ const binding = doc.mappingBindingsById?.[op.bindingId];
2051
+ if (!binding) {
2052
+ throw new OperationConflictError(`Unknown mapping binding "${op.bindingId}"`);
2053
+ }
2054
+ // Re-validated on replay, not only at the schema boundary: a log replays through here with
2055
+ // no validator in front of it, and a malformed value must not become canonical by replay.
2056
+ if (op.legacyOverride !== null && parseLegacyBindingOverride(op.legacyOverride).status !== 'known') {
2057
+ throw new OperationConflictError(`Operation mappingBinding.setLegacyOverride carries a value that is not a canonical legacy override`);
2058
+ }
2059
+ // Member-only: every other member is carried over untouched, so no node, field, target,
2060
+ // behaviour option or mapping `bindingOrder` can move when an exception is set or cleared.
2061
+ const next = { ...binding };
2062
+ if (op.legacyOverride === null)
2063
+ delete next['legacyOverride'];
2064
+ else
2065
+ next['legacyOverride'] = op.legacyOverride;
2066
+ return {
2067
+ ...doc,
2068
+ mappingBindingsById: { ...doc.mappingBindingsById, [op.bindingId]: next },
2069
+ };
2070
+ }
1641
2071
  case 'mappingBinding.delete':
1642
2072
  return scrubBindingOrders(patchDocument(doc, {
1643
2073
  mappingBindingsById: doc.mappingBindingsById && omitKey(doc.mappingBindingsById, op.bindingId),