asma-core-helpers 0.19.0 → 0.20.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 (35) hide show
  1. package/lib/collaboration/answerDocument.d.ts +50 -0
  2. package/lib/collaboration/answerDocument.d.ts.map +1 -0
  3. package/lib/collaboration/answerDocument.js +10 -0
  4. package/lib/collaboration/answerDocument.js.map +1 -0
  5. package/lib/collaboration/answerOperations.d.ts +40 -0
  6. package/lib/collaboration/answerOperations.d.ts.map +1 -0
  7. package/lib/collaboration/answerOperations.js +9 -0
  8. package/lib/collaboration/answerOperations.js.map +1 -0
  9. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  10. package/lib/collaboration/applyOperation.js +233 -0
  11. package/lib/collaboration/applyOperation.js.map +1 -1
  12. package/lib/collaboration/canonicalize.d.ts +61 -0
  13. package/lib/collaboration/canonicalize.d.ts.map +1 -0
  14. package/lib/collaboration/canonicalize.js +184 -0
  15. package/lib/collaboration/canonicalize.js.map +1 -0
  16. package/lib/collaboration/docLaws.d.ts +58 -0
  17. package/lib/collaboration/docLaws.d.ts.map +1 -0
  18. package/lib/collaboration/docLaws.js +71 -0
  19. package/lib/collaboration/docLaws.js.map +1 -0
  20. package/lib/collaboration/operations.d.ts +93 -4
  21. package/lib/collaboration/operations.d.ts.map +1 -1
  22. package/lib/collaboration/operations.js +23 -8
  23. package/lib/collaboration/operations.js.map +1 -1
  24. package/lib/collaboration/templateDocument.d.ts +128 -4
  25. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  26. package/lib/collaboration/templateDocument.js +3 -3
  27. package/lib/collaboration/templateDocument.js.map +1 -1
  28. package/package.json +2 -1
  29. package/src/collaboration/answerDocument.ts +57 -0
  30. package/src/collaboration/answerOperations.ts +34 -0
  31. package/src/collaboration/applyOperation.ts +248 -1
  32. package/src/collaboration/canonicalize.ts +209 -0
  33. package/src/collaboration/docLaws.ts +123 -0
  34. package/src/collaboration/operations.ts +87 -12
  35. package/src/collaboration/templateDocument.ts +137 -5
@@ -7,9 +7,9 @@
7
7
  * to a total in-memory model once at the document boundary rather than writing `?? {}`
8
8
  * at each use site.
9
9
  *
10
- * @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:152 (document shape)
11
- * @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:193 (DOC-LAW-1)
12
- * @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:214 (§2.2a mapping graph)
10
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:152 (document shape)
11
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:193 (DOC-LAW-1)
12
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:214 (§2.2a mapping graph)
13
13
  */
14
14
  import type { QuestionSubtype, QuestionType } from './questionTypes.js';
15
15
  export type QuestionId = string;
@@ -21,8 +21,85 @@ export type NodeId = string;
21
21
  export type BindingId = string;
22
22
  export type FilterId = string;
23
23
  export type MappingId = string;
24
+ export type VisibilityRuleId = string;
25
+ export type HighlightRuleId = string;
24
26
  /** A scalar a document may carry. Deliberately not `any`: DOC-LAW-2 bans `null`. */
25
27
  export type DocScalar = string | number | boolean;
28
+ /**
29
+ * The required access level of the pinned version (OQ-V2-2): 1 anonymous, 2 identifiable
30
+ * without authentication, 3 lower-assurance authentication, 4 BankID. Never collapsed
31
+ * to a boolean; `invitationRequired` is a separate axis.
32
+ */
33
+ export type RequiredAccessLevel = 1 | 2 | 3 | 4;
34
+ /** Who the questionnaire is initiated by (OQ-V2-15 wire vocabulary). */
35
+ export type Initiator = 'coordinator' | 'recipient';
36
+ /**
37
+ * What happens to in-flight instances when the family publishes a new version
38
+ * (OQ-V2-16, IMM-I5). v1 implements `never`; `always`/`ask` land later.
39
+ */
40
+ export type TemplateUpdateMode = 'never' | 'always' | 'ask';
41
+ /**
42
+ * The typed semantic body of the document (`meta`). Absent means the default, per
43
+ * DOC-LAW-2 — a questionnaire that requires nothing special stores `meta` with only
44
+ * what differs. Fields still open after the naming freeze (Gate-4) ride the index
45
+ * signature; the decided fields are spelled out so a typo is a compile error.
46
+ */
47
+ export type QnrTemplateMeta = {
48
+ title?: string;
49
+ description?: string;
50
+ /** Journal-wiring settings (M-007 aliases normalize here). */
51
+ settings?: {
52
+ journal?: {
53
+ /** `activityId_required`/`soknadid_required`/`sokndaid_required` unify here (architecture §2.2(7)). */
54
+ requires_activity_id?: boolean;
55
+ };
56
+ /** Recipient-side requirements. */
57
+ recipient?: {
58
+ /** Legacy `ask_for_phone_nr`. */
59
+ ask_for_phone_nr?: boolean;
60
+ };
61
+ };
62
+ /** Admission policy of the pinned version (OQ-V2-2/15/16). */
63
+ instancePolicy?: {
64
+ requiredAccessLevel?: RequiredAccessLevel;
65
+ /** Open level-1 is invitation-free; invitation-protected level-1 sets this. */
66
+ invitationRequired?: boolean;
67
+ initiator?: Initiator;
68
+ template_update_mode?: TemplateUpdateMode;
69
+ };
70
+ /** Presentation profiles (PM-6): audience/flow/layout/visibility — still loose pending their editor. */
71
+ presentationProfiles?: Record<string, unknown>;
72
+ /** Owner-domain soft references (REQ-013): ids only, no bodies, no FK validation. */
73
+ compatibility?: {
74
+ consentTemplateIds?: string[];
75
+ smsTemplateIds?: string[];
76
+ };
77
+ [key: string]: unknown;
78
+ };
79
+ /**
80
+ * The per-question-type configuration of a `QuestionGrid` (OQ-V2-17) — the repeat
81
+ * policy of the grid's rows. Lives at `question.grid.*`.
82
+ */
83
+ export type QuestionGridConfig = {
84
+ minRows?: number;
85
+ maxRows?: number;
86
+ /** `single_row` in OQ-V2-17 prose — max 1 row. */
87
+ singleRow?: boolean;
88
+ deletableRows?: boolean;
89
+ alwaysNew?: boolean;
90
+ timestamps?: boolean;
91
+ };
92
+ /**
93
+ * Grid-owned presentation (OQ-V2-17/25): row-editor layout, filters, grid actions,
94
+ * highlight rules, the header-tab reference and authored default column widths live
95
+ * here — there is no parallel `settings_ui` or `layoutByQuestionId` map.
96
+ */
97
+ export type QuestionGridPresentation = {
98
+ headerTabId?: TabId;
99
+ /** OQ-V2-25: authored defaults; per-user widths are preference state outside both documents. */
100
+ defaultColumnWidthsByQuestionId?: Record<QuestionId, number>;
101
+ [key: string]: unknown;
102
+ };
26
103
  /**
27
104
  * `type` is the question's own discriminator (M-062), a closed union rather than a string — see
28
105
  * `questionTypes.ts` for why the value cannot be loose. Not to be confused with the other `kind`
@@ -35,6 +112,10 @@ export type QnrQuestion = {
35
112
  label?: string;
36
113
  required?: boolean;
37
114
  defaultValue?: DocScalar;
115
+ /** `QuestionGrid` only: the row repeat policy. */
116
+ grid?: QuestionGridConfig;
117
+ /** `QuestionGrid` only: grid-owned presentation (layout, filters, actions, column widths). */
118
+ presentation?: QuestionGridPresentation;
38
119
  [key: string]: unknown;
39
120
  };
40
121
  export type QnrAlternative = {
@@ -42,8 +123,11 @@ export type QnrAlternative = {
42
123
  value?: DocScalar;
43
124
  [key: string]: unknown;
44
125
  };
126
+ /** An authored predefined grid row; cells are keyed by column question id. */
45
127
  export type QnrGridRow = {
46
128
  label?: string;
129
+ /** Authored default cell values, keyed by the column question id. */
130
+ cells?: Record<QuestionId, DocScalar>;
47
131
  [key: string]: unknown;
48
132
  };
49
133
  export type QnrTab = {
@@ -54,6 +138,26 @@ export type QnrAction = {
54
138
  kind?: string;
55
139
  [key: string]: unknown;
56
140
  };
141
+ /**
142
+ * A typed conditional (OQ-V2-17/architecture §2.2(4)): question visibility/highlight
143
+ * depends on another question's answer. Legacy `dependent_question`+`dependent_questions`
144
+ * duals normalize into rule collections (byId + per-question order, DOC-LAW-1).
145
+ */
146
+ export type RuleCondition = {
147
+ sourceQuestionId: QuestionId;
148
+ alternativeId?: AltId;
149
+ operator?: string;
150
+ value?: DocScalar;
151
+ [key: string]: unknown;
152
+ };
153
+ export type VisibilityRule = {
154
+ condition: RuleCondition;
155
+ [key: string]: unknown;
156
+ };
157
+ export type HighlightRule = {
158
+ condition: RuleCondition;
159
+ [key: string]: unknown;
160
+ };
57
161
  /** One traversal step. Many questions off one entity share a single node (§2.2a). */
58
162
  export type MappingNode = {
59
163
  entityId: string;
@@ -92,7 +196,7 @@ export type MappingFilter = {
92
196
  export type QnrTemplateDocument = {
93
197
  documentId: string;
94
198
  revision: number;
95
- meta?: Record<string, unknown>;
199
+ meta?: QnrTemplateMeta;
96
200
  questionsById?: Record<QuestionId, QnrQuestion>;
97
201
  questionOrder: QuestionId[];
98
202
  gridRowsById?: Record<RowId, QnrGridRow>;
@@ -102,6 +206,10 @@ export type QnrTemplateDocument = {
102
206
  tabsById?: Record<TabId, QnrTab>;
103
207
  tabOrder?: TabId[];
104
208
  actionsById?: Record<ActionId, QnrAction>;
209
+ visibilityRulesById?: Record<VisibilityRuleId, VisibilityRule>;
210
+ visibilityRuleOrderByQuestionId?: Record<QuestionId, VisibilityRuleId[]>;
211
+ highlightRulesById?: Record<HighlightRuleId, HighlightRule>;
212
+ highlightRuleOrderByQuestionId?: Record<QuestionId, HighlightRuleId[]>;
105
213
  dataMappingsById?: Record<MappingId, {
106
214
  sourceId: string;
107
215
  rootNodeId: NodeId;
@@ -111,6 +219,22 @@ export type QnrTemplateDocument = {
111
219
  mappingBindingsById?: Record<BindingId, MappingBinding>;
112
220
  mappingFiltersById?: Record<FilterId, MappingFilter>;
113
221
  };
222
+ /**
223
+ * A reusable question-template bundle (OQ-V2-1): the root question plus every owned
224
+ * child question, alternative, predefined grid row, scoped tab/action, order and
225
+ * internal reference needed to use it. Stored whole in `qnr_question_templates.bundle`;
226
+ * a manual pick deep-copies and validates it into the family document.
227
+ */
228
+ export type QnrQuestionBundle = {
229
+ rootQuestionId: QuestionId;
230
+ questionsById: Record<QuestionId, QnrQuestion>;
231
+ gridRowsById?: Record<RowId, QnrGridRow>;
232
+ gridRowOrderByQuestionId?: Record<QuestionId, RowId[]>;
233
+ alternativesById?: Record<AltId, QnrAlternative>;
234
+ alternativeOrderByQuestionId?: Record<QuestionId, AltId[]>;
235
+ tabsById?: Record<TabId, QnrTab>;
236
+ actionsById?: Record<ActionId, QnrAction>;
237
+ };
114
238
  /**
115
239
  * A new family's document. `questionOrder` is present-and-empty rather than absent
116
240
  * because it is the document's only structural array and every reader indexes it; an
@@ -1 +1 @@
1
- {"version":3,"file":"templateDocument.d.ts","sourceRoot":"","sources":["../../src/collaboration/templateDocument.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAEvE,MAAM,MAAM,UAAU,GAAG,MAAM,CAAA;AAC/B,MAAM,MAAM,KAAK,GAAG,MAAM,CAAA;AAC1B,MAAM,MAAM,KAAK,GAAG,MAAM,CAAA;AAC1B,MAAM,MAAM,KAAK,GAAG,MAAM,CAAA;AAC1B,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAA;AAC7B,MAAM,MAAM,MAAM,GAAG,MAAM,CAAA;AAC3B,MAAM,MAAM,SAAS,GAAG,MAAM,CAAA;AAC9B,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAA;AAC7B,MAAM,MAAM,SAAS,GAAG,MAAM,CAAA;AAE9B,oFAAoF;AACpF,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAA;AAEjD;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GAAG;IACtB,IAAI,EAAE,YAAY,CAAA;IAClB,OAAO,CAAC,EAAE,eAAe,CAAA;IACzB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,YAAY,CAAC,EAAE,SAAS,CAAA;IACxB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CACzB,CAAA;AAED,MAAM,MAAM,cA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AAC,MAAM,EAAE,WAAW,CAAC,CAAA;IAC9C,mBAAmB,CAAC,EAAE,MAAM,CAAC,SAAS,EAAE,cAAc,CAAC,CAAA;IACvD,kBAAkB,CAAC,EAAE,MAAM,CAAC,QAAQ,EAAE,aAAa,CAAC,CAAA;CACvD,CAAA;AAED;;;;;GAKG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC5B,cAAc,EAAE,UAAU,CAAA;IAC1B,aAAa,EAAE,MAAM,CAAC,UAAU,EAAE,WAAW,CAAC,CAAA;IAC9C,YAAY,CAAC,EAAE,MAAM,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;IACxC,wBAAwB,CAAC,EAAE,MAAM,CAAC,UAAU,EAAE,KAAK,EAAE,CAAC,CAAA;IACtD,gBAAgB,CAAC,EAAE,MAAM,CAAC,KAAK,EAAE,cAAc,CAAC,CAAA;IAChD,4BAA4B,CAAC,EAAE,MAAM,CAAC,UAAU,EAAE,KAAK,EAAE,CAAC,CAAA;IAC1D,QAAQ,CAAC,EAAE,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA;IAChC,WAAW,CAAC,EAAE,MAAM,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAA;CAC5C,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,eAAgB,MAAM,KAAG,mBAIzD,CAAA"}
@@ -7,9 +7,9 @@
7
7
  * to a total in-memory model once at the document boundary rather than writing `?? {}`
8
8
  * at each use site.
9
9
  *
10
- * @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:152 (document shape)
11
- * @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:193 (DOC-LAW-1)
12
- * @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:214 (§2.2a mapping graph)
10
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:152 (document shape)
11
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:193 (DOC-LAW-1)
12
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:214 (§2.2a mapping graph)
13
13
  */
14
14
  /**
15
15
  * A new family's document. `questionOrder` is present-and-empty rather than absent
@@ -1 +1 @@
1
- {"version":3,"file":"templateDocument.js","sourceRoot":"","sources":["../../src/collaboration/templateDocument.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AA0FH;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,UAAkB,EAAuB,EAAE,CAAC,CAAC;IAC/E,UAAU;IACV,QAAQ,EAAE,CAAC;IACX,aAAa,EAAE,EAAE;CACpB,CAAC,CAAA"}
1
+ {"version":3,"file":"templateDocument.js","sourceRoot":"","sources":["../../src/collaboration/templateDocument.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AA8NH;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,UAAkB,EAAuB,EAAE,CAAC,CAAC;IAC/E,UAAU;IACV,QAAQ,EAAE,CAAC;IACX,aAAa,EAAE,EAAE;CACpB,CAAC,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asma-core-helpers",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Core helper utilities for ASMA applications",
5
5
  "files": [
6
6
  "lib/**/*",
@@ -45,6 +45,7 @@
45
45
  "@0no-co/graphql.web": "^1.0.9",
46
46
  "@urql/core": "^6.0.3",
47
47
  "@urql/exchange-auth": "^3.0.0",
48
+ "arktype": "^2.2.3",
48
49
  "asma-event-bus": "^0.7.27",
49
50
  "buffer": "^6.0.3",
50
51
  "idb-keyval": "^6.2.1",
@@ -0,0 +1,57 @@
1
+ import type { DocScalar, QuestionId, RowId } from './templateDocument.js'
2
+
3
+ /**
4
+ * The instance answer document (OQ-V2-8/24/44/47) — the filling-side sibling of the
5
+ * template authoring document. It stores **answers only**: the definition comes from the
6
+ * pinned immutable template version, never from here.
7
+ *
8
+ * **DOC-LAW-2's scoped exception lives here.** Absence means "never answered" in answer
9
+ * state, so an explicit `null` encodes the genuinely different fact "answered then
10
+ * cleared" — that is what keeps the journal dispatch from re-sending a prefilled value
11
+ * after the recipient cleared it. The template document keeps the strict no-null rule;
12
+ * this one does not.
13
+ *
14
+ * A grid row added at answer time is owned by this document (`answerGridRowsById` +
15
+ * order arrays), not by the template — the template's predefined rows stay frozen in the
16
+ * pinned version.
17
+ *
18
+ * The op vocabulary for this document (`answer.set/clear`, `gridRow.add/remove/move`,
19
+ * `gridAnswer.set`) is defined in `answerOperations.ts`; the reducer is a Phase-7
20
+ * deliverable, so this file and the op union are contract-only for now.
21
+ *
22
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:181 (QnrAnswerDocument)
23
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:195 (DOC-LAW-2 exception)
24
+ */
25
+
26
+ /**
27
+ * An answer value. `null` is the deliberate-clear marker; a primitive array is legal
28
+ * because DOC-LAW-1 allows primitive arrays (multi-select = selected alternative ids).
29
+ */
30
+ export type AnswerValue = DocScalar | DocScalar[] | null
31
+
32
+ /** One instance-added grid row. `deleted: true` is the tombstone (OQ-V2-24). */
33
+ export type AnswerGridRow = {
34
+ questionGridId: QuestionId
35
+ /** The captured source-row identity — an opaque string, never parsed (OQ-V2-24). */
36
+ entityRef?: string
37
+ deleted?: true
38
+ }
39
+
40
+ export type QnrAnswerDocument = {
41
+ documentId: string
42
+ revision: number
43
+ answersByQuestionId?: Record<QuestionId, AnswerValue>
44
+ gridAnswersByQuestionId?: Record<QuestionId, Record<RowId, Record<QuestionId, AnswerValue>>>
45
+ answerGridRowsById?: Record<RowId, AnswerGridRow>
46
+ answerGridRowOrderByQuestionId?: Record<QuestionId, RowId[]>
47
+ }
48
+
49
+ /**
50
+ * A fresh instance document. `answerGridRowOrderByQuestionId` is absent (no rows yet) —
51
+ * unlike the template's `questionOrder`, nothing here is structural: the template's
52
+ * question order already exists, and row order is only meaningful once rows exist.
53
+ */
54
+ export const emptyAnswerDocument = (documentId: string): QnrAnswerDocument => ({
55
+ documentId,
56
+ revision: 0,
57
+ })
@@ -0,0 +1,34 @@
1
+ import type { AnswerValue } from './answerDocument.js'
2
+ import type { QuestionId, RowId } from './templateDocument.js'
3
+
4
+ /**
5
+ * The filling (answer-document) op vocabulary (architecture §5, OQ-V2-24/44/47).
6
+ *
7
+ * Contract-only for now: the types are the Phase-0 deliverable so both sides of the
8
+ * wire and the Phase-1 DDL agree on the shape; the reducer that applies them
9
+ * (`applyAnswerOperation`) is a Phase-7 deliverable. The authoring vocabulary lives in
10
+ * `operations.ts`; this one is deliberately separate because the two documents have
11
+ * different mutability (OQ-V2-8) and different law regimes (the explicit `null` clear
12
+ * marker is legal in answer state, never in the template document).
13
+ *
14
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:380 (filling vocabulary)
15
+ */
16
+
17
+ export type AnswerOp =
18
+ | { type: 'answer.set'; questionId: QuestionId; value: AnswerValue }
19
+ | { type: 'answer.clear'; questionId: QuestionId }
20
+ | { type: 'gridRow.add'; questionId: QuestionId; rowId: RowId; afterRowId?: RowId }
21
+ | { type: 'gridRow.remove'; questionId: QuestionId; rowId: RowId }
22
+ | { type: 'gridAnswer.set'; questionId: QuestionId; rowId: RowId; columnQuestionId: QuestionId; value: AnswerValue }
23
+
24
+ export type AnswerOpType = AnswerOp['type']
25
+
26
+ const ANSWER_OP_TYPE_COVERAGE: Record<AnswerOpType, true> = {
27
+ 'answer.set': true,
28
+ 'answer.clear': true,
29
+ 'gridRow.add': true,
30
+ 'gridRow.remove': true,
31
+ 'gridAnswer.set': true,
32
+ }
33
+
34
+ export const IMPLEMENTED_ANSWER_OP_TYPES = Object.keys(ANSWER_OP_TYPE_COVERAGE) as readonly AnswerOpType[]
@@ -1,5 +1,5 @@
1
1
  import type { TemplateOp } from './operations.js'
2
- import type { BindingTarget, QnrTemplateDocument, QuestionId } from './templateDocument.js'
2
+ import type { BindingTarget, MappingNode, QnrTemplateDocument, QuestionId } from './templateDocument.js'
3
3
 
4
4
  /**
5
5
  * The authoring reducer. Pure: takes a document and an op, returns a new document with
@@ -137,6 +137,10 @@ const OPTIONAL_COLLECTIONS = [
137
137
  'tabsById',
138
138
  'tabOrder',
139
139
  'actionsById',
140
+ 'visibilityRulesById',
141
+ 'visibilityRuleOrderByQuestionId',
142
+ 'highlightRulesById',
143
+ 'highlightRuleOrderByQuestionId',
140
144
  'dataMappingsById',
141
145
  'mappingNodesById',
142
146
  'mappingBindingsById',
@@ -187,6 +191,17 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
187
191
  return { ...doc, meta }
188
192
  }
189
193
 
194
+ case 'template.updateSettings': {
195
+ let meta = { ...(doc.meta ?? {}) }
196
+ let settings = { ...(meta.settings ?? {}) }
197
+ for (const [key, value] of Object.entries(op.patch)) {
198
+ settings = writeField(settings, key, value)
199
+ }
200
+ if (Object.keys(settings).length === 0) delete meta.settings
201
+ else meta.settings = settings
202
+ return { ...doc, meta }
203
+ }
204
+
190
205
  case 'question.create': {
191
206
  if (doc.questionsById?.[op.questionId]) {
192
207
  throw new OperationConflictError(`Question "${op.questionId}" already exists`)
@@ -233,12 +248,88 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
233
248
  doc.alternativeOrderByQuestionId && omitKey(doc.alternativeOrderByQuestionId, op.questionId),
234
249
  gridRowOrderByQuestionId:
235
250
  doc.gridRowOrderByQuestionId && omitKey(doc.gridRowOrderByQuestionId, op.questionId),
251
+ visibilityRuleOrderByQuestionId:
252
+ doc.visibilityRuleOrderByQuestionId && omitKey(doc.visibilityRuleOrderByQuestionId, op.questionId),
253
+ highlightRuleOrderByQuestionId:
254
+ doc.highlightRuleOrderByQuestionId &&
255
+ omitKey(doc.highlightRuleOrderByQuestionId, op.questionId),
236
256
  })
237
257
  // A binding pointing at a deleted question is an unresolvable reference the
238
258
  // compiler would reject at publication; drop it with its target.
239
259
  return dropBindingsForQuestion(withoutQuestion, op.questionId)
240
260
  }
241
261
 
262
+ case 'gridRow.create': {
263
+ if (!doc.questionsById?.[op.questionId]) {
264
+ throw new OperationConflictError(`Unknown question "${op.questionId}"`)
265
+ }
266
+ if (doc.gridRowsById?.[op.rowId]) {
267
+ throw new OperationConflictError(`Grid row "${op.rowId}" already exists`)
268
+ }
269
+ const order = doc.gridRowOrderByQuestionId?.[op.questionId] ?? []
270
+ return {
271
+ ...doc,
272
+ gridRowsById: {
273
+ ...(doc.gridRowsById ?? {}),
274
+ [op.rowId]: op.label === undefined ? {} : { label: op.label },
275
+ },
276
+ gridRowOrderByQuestionId: {
277
+ ...(doc.gridRowOrderByQuestionId ?? {}),
278
+ [op.questionId]: insertAt(order, op.rowId, op.atIndex),
279
+ },
280
+ }
281
+ }
282
+
283
+ case 'gridRow.move': {
284
+ const order = doc.gridRowOrderByQuestionId?.[op.questionId]
285
+ if (!order?.includes(op.rowId)) {
286
+ throw new OperationConflictError(`Grid row "${op.rowId}" does not belong to question "${op.questionId}"`)
287
+ }
288
+ // Anchor-relative (OQ-V2-24): a null anchor moves to the front. A move is a
289
+ // remove-then-insert, so the anchor is looked up in the row set that no longer
290
+ // contains the moved row itself.
291
+ const without = order.filter((id) => id !== op.rowId)
292
+ const anchorIndex = op.afterRowId === null ? -1 : without.indexOf(op.afterRowId)
293
+ if (op.afterRowId !== null && anchorIndex === -1) {
294
+ throw new OperationConflictError(`Unknown anchor grid row "${op.afterRowId}"`)
295
+ }
296
+ const at = anchorIndex + 1
297
+ return {
298
+ ...doc,
299
+ gridRowOrderByQuestionId: {
300
+ ...(doc.gridRowOrderByQuestionId ?? {}),
301
+ [op.questionId]: [...without.slice(0, at), op.rowId, ...without.slice(at)],
302
+ },
303
+ }
304
+ }
305
+
306
+ case 'gridRow.delete': {
307
+ const order = doc.gridRowOrderByQuestionId?.[op.questionId] ?? []
308
+ const remaining = order.filter((id) => id !== op.rowId)
309
+ return patchDocument(doc, {
310
+ gridRowsById: doc.gridRowsById && omitKey(doc.gridRowsById, op.rowId),
311
+ gridRowOrderByQuestionId: {
312
+ ...(doc.gridRowOrderByQuestionId ?? {}),
313
+ [op.questionId]: remaining,
314
+ },
315
+ })
316
+ }
317
+
318
+ case 'gridRow.updateCell': {
319
+ const row = doc.gridRowsById?.[op.rowId]
320
+ if (!row) {
321
+ throw new OperationConflictError(`Unknown grid row "${op.rowId}"`)
322
+ }
323
+ const cells = writeField({ ...(row.cells ?? {}) }, op.columnQuestionId, op.value)
324
+ return {
325
+ ...doc,
326
+ gridRowsById: {
327
+ ...doc.gridRowsById,
328
+ [op.rowId]: { ...row, cells: Object.keys(cells).length === 0 ? undefined : cells },
329
+ },
330
+ }
331
+ }
332
+
242
333
  case 'alternative.create': {
243
334
  if (!doc.questionsById?.[op.questionId]) {
244
335
  throw new OperationConflictError(`Unknown question "${op.questionId}"`)
@@ -307,6 +398,87 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
307
398
  })
308
399
  }
309
400
 
401
+ case 'tab.create': {
402
+ if (doc.tabsById?.[op.tabId]) {
403
+ throw new OperationConflictError(`Tab "${op.tabId}" already exists`)
404
+ }
405
+ return {
406
+ ...doc,
407
+ tabsById: { ...(doc.tabsById ?? {}), [op.tabId]: op.label === undefined ? {} : { label: op.label } },
408
+ tabOrder: insertAt(doc.tabOrder ?? [], op.tabId, op.atIndex),
409
+ }
410
+ }
411
+
412
+ case 'tab.updateField': {
413
+ const tab = doc.tabsById?.[op.tabId]
414
+ if (!tab) {
415
+ throw new OperationConflictError(`Unknown tab "${op.tabId}"`)
416
+ }
417
+ return { ...doc, tabsById: { ...doc.tabsById, [op.tabId]: writeField(tab, op.field, op.value) } }
418
+ }
419
+
420
+ case 'tab.move': {
421
+ if (!doc.tabOrder?.includes(op.tabId)) {
422
+ throw new OperationConflictError(`Unknown tab "${op.tabId}"`)
423
+ }
424
+ return { ...doc, tabOrder: moveInOrder(doc.tabOrder, op.tabId, op.toIndex) }
425
+ }
426
+
427
+ case 'tab.delete': {
428
+ if (!doc.tabsById?.[op.tabId]) {
429
+ throw new OperationConflictError(`Unknown tab "${op.tabId}"`)
430
+ }
431
+ return patchDocument(doc, {
432
+ tabsById: doc.tabsById && omitKey(doc.tabsById, op.tabId),
433
+ tabOrder: (doc.tabOrder ?? []).filter((id) => id !== op.tabId),
434
+ })
435
+ }
436
+
437
+ case 'layout.updateQuestion': {
438
+ const question = doc.questionsById?.[op.questionId]
439
+ if (!question) {
440
+ throw new OperationConflictError(`Unknown question "${op.questionId}"`)
441
+ }
442
+ let presentation = { ...(question.presentation ?? {}) }
443
+ for (const [key, value] of Object.entries(op.patch)) {
444
+ presentation = writeField(presentation, key, value)
445
+ }
446
+ const next = { ...question }
447
+ if (Object.keys(presentation).length === 0) delete next.presentation
448
+ else next.presentation = presentation
449
+ return { ...doc, questionsById: { ...doc.questionsById, [op.questionId]: next } }
450
+ }
451
+
452
+ case 'action.create': {
453
+ if (doc.actionsById?.[op.actionId]) {
454
+ throw new OperationConflictError(`Action "${op.actionId}" already exists`)
455
+ }
456
+ return {
457
+ ...doc,
458
+ actionsById: {
459
+ ...(doc.actionsById ?? {}),
460
+ [op.actionId]: op.kind === undefined ? {} : { kind: op.kind },
461
+ },
462
+ }
463
+ }
464
+
465
+ case 'action.updateField': {
466
+ const action = doc.actionsById?.[op.actionId]
467
+ if (!action) {
468
+ throw new OperationConflictError(`Unknown action "${op.actionId}"`)
469
+ }
470
+ return { ...doc, actionsById: { ...doc.actionsById, [op.actionId]: writeField(action, op.field, op.value) } }
471
+ }
472
+
473
+ case 'action.delete': {
474
+ if (!doc.actionsById?.[op.actionId]) {
475
+ throw new OperationConflictError(`Unknown action "${op.actionId}"`)
476
+ }
477
+ return patchDocument(doc, {
478
+ actionsById: doc.actionsById && omitKey(doc.actionsById, op.actionId),
479
+ })
480
+ }
481
+
310
482
  case 'mappingNode.create': {
311
483
  if (doc.mappingNodesById?.[op.nodeId]) {
312
484
  throw new OperationConflictError(`Mapping node "${op.nodeId}" already exists`)
@@ -319,6 +491,25 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
319
491
  return { ...doc, mappingNodesById: { ...(doc.mappingNodesById ?? {}), [op.nodeId]: node } }
320
492
  }
321
493
 
494
+ case 'mappingNode.update': {
495
+ const node = doc.mappingNodesById?.[op.nodeId]
496
+ if (!node) {
497
+ throw new OperationConflictError(`Unknown mapping node "${op.nodeId}"`)
498
+ }
499
+ const next: MappingNode = { ...node }
500
+ if (op.patch.entityId !== undefined) next.entityId = op.patch.entityId
501
+ if (op.patch.parentNodeId !== undefined) {
502
+ if (op.patch.parentNodeId === null) delete next.parentNodeId
503
+ else next.parentNodeId = op.patch.parentNodeId
504
+ }
505
+ if (op.patch.relationshipId !== undefined) {
506
+ if (op.patch.relationshipId === null) delete next.relationshipId
507
+ else next.relationshipId = op.patch.relationshipId
508
+ }
509
+ if (op.patch.filterOrder !== undefined) next.filterOrder = op.patch.filterOrder
510
+ return { ...doc, mappingNodesById: { ...doc.mappingNodesById, [op.nodeId]: next } }
511
+ }
512
+
322
513
  case 'mappingNode.delete': {
323
514
  const filterIds = doc.mappingNodesById?.[op.nodeId]?.filterOrder ?? []
324
515
  let filtersById = doc.mappingFiltersById
@@ -414,6 +605,62 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
414
605
  })
415
606
  }
416
607
 
608
+ case 'visibilityRule.set': {
609
+ const order = doc.visibilityRuleOrderByQuestionId?.[op.questionId] ?? []
610
+ return {
611
+ ...doc,
612
+ visibilityRulesById: {
613
+ ...(doc.visibilityRulesById ?? {}),
614
+ [op.ruleId]: { condition: op.condition },
615
+ },
616
+ visibilityRuleOrderByQuestionId: {
617
+ ...(doc.visibilityRuleOrderByQuestionId ?? {}),
618
+ [op.questionId]: order.includes(op.ruleId) ? order : [...order, op.ruleId],
619
+ },
620
+ }
621
+ }
622
+
623
+ case 'visibilityRule.delete': {
624
+ const orders = Object.fromEntries(
625
+ Object.entries(doc.visibilityRuleOrderByQuestionId ?? {}).map(([questionId, ruleIds]) => [
626
+ questionId,
627
+ ruleIds.filter((id) => id !== op.ruleId),
628
+ ]),
629
+ )
630
+ return patchDocument(doc, {
631
+ visibilityRulesById: doc.visibilityRulesById && omitKey(doc.visibilityRulesById, op.ruleId),
632
+ visibilityRuleOrderByQuestionId: orders,
633
+ })
634
+ }
635
+
636
+ case 'highlightRule.set': {
637
+ const order = doc.highlightRuleOrderByQuestionId?.[op.questionId] ?? []
638
+ return {
639
+ ...doc,
640
+ highlightRulesById: {
641
+ ...(doc.highlightRulesById ?? {}),
642
+ [op.ruleId]: { condition: op.condition },
643
+ },
644
+ highlightRuleOrderByQuestionId: {
645
+ ...(doc.highlightRuleOrderByQuestionId ?? {}),
646
+ [op.questionId]: order.includes(op.ruleId) ? order : [...order, op.ruleId],
647
+ },
648
+ }
649
+ }
650
+
651
+ case 'highlightRule.delete': {
652
+ const orders = Object.fromEntries(
653
+ Object.entries(doc.highlightRuleOrderByQuestionId ?? {}).map(([questionId, ruleIds]) => [
654
+ questionId,
655
+ ruleIds.filter((id) => id !== op.ruleId),
656
+ ]),
657
+ )
658
+ return patchDocument(doc, {
659
+ highlightRulesById: doc.highlightRulesById && omitKey(doc.highlightRulesById, op.ruleId),
660
+ highlightRuleOrderByQuestionId: orders,
661
+ })
662
+ }
663
+
417
664
  default: {
418
665
  // Exhaustiveness: a new op member makes this a compile error, not a silent no-op.
419
666
  const unhandled: never = op