asma-core-helpers 0.18.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 (36) 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 +290 -4
  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 +111 -10
  21. package/lib/collaboration/operations.d.ts.map +1 -1
  22. package/lib/collaboration/operations.js +42 -19
  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.test.ts +152 -0
  32. package/src/collaboration/applyOperation.ts +316 -4
  33. package/src/collaboration/canonicalize.ts +209 -0
  34. package/src/collaboration/docLaws.ts +123 -0
  35. package/src/collaboration/operations.ts +114 -23
  36. package/src/collaboration/templateDocument.ts +137 -5
@@ -0,0 +1,123 @@
1
+ import type { JsonValue } from './canonicalize.js'
2
+
3
+ /**
4
+ * The two document laws, as an executable check (plan TASK-003).
5
+ *
6
+ * Both are stated in the architecture as prose and enforced at the storage boundary by a CHECK constraint
7
+ * that can only see one of them. `jsonb_strip_nulls(document) = document` catches DOC-LAW-2's explicit
8
+ * `null`, and nothing in the database can catch DOC-LAW-1 at all — an array of objects is perfectly valid
9
+ * jsonb. So the law that matters most for merges is the one with no guard, which is what this file is.
10
+ *
11
+ * ═══ DOC-LAW-1 · NO ARRAYS OF OBJECTS ═══
12
+ * A collection is `<x>ById` plus a primitive order array. The reason is merge behaviour, not taste: JSON
13
+ * Merge Patch (RFC 7386) — the delta format — replaces an array **wholesale**. For an order array of ids
14
+ * that is exactly right, because reordering *is* a whole-array change. For an array of objects it is a
15
+ * silent data loss: two authors editing different members of one array produce two patches, and the second
16
+ * to land discards the first's edit with no conflict raised. Keying the members by id turns that same
17
+ * situation into two patches touching different keys, which merge cleanly.
18
+ *
19
+ * ═══ DOC-LAW-2 · ABSENT IS THE ONLY ENCODING OF "NOT SET" ═══
20
+ * No explicit `null`, no empty object, no empty array, no key carrying its own default. Two encodings of
21
+ * "not set" means two documents that render identically can hash differently — and the hash is what decides
22
+ * whether a version is minted, whether a re-import diverged, and whether two authors actually conflicted.
23
+ *
24
+ * ═══ WHY A LINT AND NOT A TYPE ═══
25
+ * `QnrQuestion` carries an index signature (`[key: string]: unknown`), because a question's per-type
26
+ * configuration bag is genuinely open. That is the right type and it is also why the compiler cannot see
27
+ * either violation: the legacy import writes into exactly that open space. This check found a real one —
28
+ * `dependent_questions` arrives from legacy as an array of objects and was being stored verbatim.
29
+ *
30
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:193 — DOC-LAW-1
31
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:195 — DOC-LAW-2
32
+ */
33
+
34
+ export type DocLawViolation = {
35
+ law: 'DOC-LAW-1' | 'DOC-LAW-2'
36
+ /** Dotted path to the offending node, array members included as numeric segments. */
37
+ path: string
38
+ detail: string
39
+ }
40
+
41
+ const isPlainObject = (value: unknown): value is Record<string, unknown> => {
42
+ if (typeof value !== 'object' || value === null) return false
43
+ const proto = Object.getPrototypeOf(value)
44
+ return proto === Object.prototype || proto === null
45
+ }
46
+
47
+ const joinPath = (parent: string, key: string) => (parent === '' ? key : `${parent}.${key}`)
48
+
49
+ /**
50
+ * Every violation in a document, deepest-first is not guaranteed — order follows traversal.
51
+ *
52
+ * `revision` is exempt from DOC-LAW-2's default rule: it is `0` on a fresh document and `0` is its
53
+ * meaningful value there, not an omittable default. Nothing else is exempt.
54
+ */
55
+ export const findDocLawViolations = (document: unknown): DocLawViolation[] => {
56
+ const violations: DocLawViolation[] = []
57
+
58
+ const walk = (value: unknown, path: string): void => {
59
+ if (value === null) {
60
+ violations.push({ law: 'DOC-LAW-2', path, detail: 'explicit null; omit the key instead' })
61
+ return
62
+ }
63
+
64
+ if (Array.isArray(value)) {
65
+ if (value.length === 0) {
66
+ violations.push({ law: 'DOC-LAW-2', path, detail: 'empty array; omit the key instead' })
67
+ return
68
+ }
69
+
70
+ value.forEach((member, index) => {
71
+ const memberPath = joinPath(path, String(index))
72
+ if (isPlainObject(member) || Array.isArray(member)) {
73
+ violations.push({
74
+ law: 'DOC-LAW-1',
75
+ path: memberPath,
76
+ detail: `array member is ${Array.isArray(member) ? 'an array' : 'an object'}; use <x>ById plus a primitive order array`,
77
+ })
78
+ }
79
+ walk(member, memberPath)
80
+ })
81
+ return
82
+ }
83
+
84
+ if (isPlainObject(value)) {
85
+ const keys = Object.keys(value)
86
+ if (keys.length === 0 && path !== '') {
87
+ violations.push({ law: 'DOC-LAW-2', path, detail: 'empty object; omit the key instead' })
88
+ return
89
+ }
90
+ for (const key of keys) walk(value[key], joinPath(path, key))
91
+ }
92
+ }
93
+
94
+ walk(document, '')
95
+ return violations
96
+ }
97
+
98
+ /**
99
+ * Rewrites a legacy array-of-objects into the DOC-LAW-1 shape, in place of the array.
100
+ *
101
+ * `{ <field>: [ {...}, {...} ] }` becomes `{ <field>ById: { <id>: {...} }, <field>Order: [ <id>, … ] }`,
102
+ * with ids derived by the caller so they are stable across revisions — a random id would make every
103
+ * re-import look like an edit, which is the same trap `derivedAlternativeId` exists to avoid.
104
+ */
105
+ export const toKeyedCollection = <T>(
106
+ members: readonly T[],
107
+ idOf: (member: T, index: number) => string,
108
+ ): { byId: Record<string, T>; order: string[] } => {
109
+ const byId: Record<string, T> = {}
110
+ const order: string[] = []
111
+
112
+ members.forEach((member, index) => {
113
+ const id = idOf(member, index)
114
+ byId[id] = member
115
+ order.push(id)
116
+ })
117
+
118
+ return { byId, order }
119
+ }
120
+
121
+ /** True when the value is an array carrying at least one object or array member. */
122
+ export const isArrayOfContainers = (value: unknown): value is JsonValue[] =>
123
+ Array.isArray(value) && value.some((member) => isPlainObject(member) || Array.isArray(member))
@@ -1,16 +1,35 @@
1
- import type { AltId, BindingId, BindingTarget, DocScalar, FilterId, NodeId, QuestionId } from './templateDocument.js'
1
+ import type {
2
+ ActionId,
3
+ AltId,
4
+ BindingId,
5
+ BindingTarget,
6
+ DocScalar,
7
+ FilterId,
8
+ HighlightRuleId,
9
+ NodeId,
10
+ QuestionId,
11
+ RowId,
12
+ RuleCondition,
13
+ TabId,
14
+ VisibilityRuleId,
15
+ } from './templateDocument.js'
2
16
  import type { QuestionType } from './questionTypes.js'
3
17
 
4
18
  /**
5
- * The authoring op vocabulary. `entity.action`, stable-id targets only, append-only —
19
+ * The authoring op vocabulary (architecture §5). `entity.action`, stable-id targets only, append-only —
6
20
  * a new op is a new member, never a changed one.
7
21
  *
8
22
  * `null` in an op payload is the **explicit unset** the way JSON-merge-patch uses it.
9
23
  * DOC-LAW-2 bans `null` in the stored document, not in the op that produces it: the op
10
24
  * layer is the only place the absent-vs-cleared tri-state survives.
11
25
  *
12
- * @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:380
13
- * @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:195 (DOC-LAW-2 tri-state)
26
+ * Two move conventions coexist deliberately: `question.move`/`alternative.move`/`tab.move`
27
+ * carry `toIndex` (the established authoring shape), while `gridRow.move` is
28
+ * **anchor-relative** (`afterRowId`, OQ-V2-24) — array position is never identity, and a
29
+ * row index would denote different rows to two clients that disagree by one insert.
30
+ *
31
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:380 (op vocabulary)
32
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:195 (DOC-LAW-2 tri-state)
14
33
  */
15
34
 
16
35
  /** A value an op may write. `null` means unset. */
@@ -18,15 +37,59 @@ export type OpValue = DocScalar | null
18
37
 
19
38
  export type TemplateOp =
20
39
  | { type: 'template.updateMeta'; patch: Record<string, OpValue | Record<string, unknown>> }
40
+ | {
41
+ type: 'template.updateSettings'
42
+ /** Dotted-path patch into `meta.settings` (journal wiring, recipient requirements). */
43
+ patch: Record<string, OpValue | Record<string, unknown>>
44
+ }
21
45
  // `questionType`, not `type`: the envelope already owns `type` for the op name, so the question's
22
46
  // own type (which is what lands in the document) needs a distinct key here.
23
47
  | { type: 'question.create'; questionId: QuestionId; questionType: QuestionType; atIndex?: number }
24
48
  | { type: 'question.updateField'; questionId: QuestionId; field: string; value: OpValue }
25
49
  | { type: 'question.move'; questionId: QuestionId; toIndex: number }
26
50
  | { type: 'question.delete'; questionId: QuestionId }
51
+ // Authoring-side grid rows are the template's *predefined* rows; instance-added rows
52
+ // are answer ops (answerOperations.ts). `gridRow.move` is anchor-relative (OQ-V2-24).
53
+ | { type: 'gridRow.create'; questionId: QuestionId; rowId: RowId; label?: string; atIndex?: number }
54
+ | { type: 'gridRow.move'; questionId: QuestionId; rowId: RowId; afterRowId: RowId | null }
55
+ | { type: 'gridRow.delete'; questionId: QuestionId; rowId: RowId }
56
+ | {
57
+ type: 'gridRow.updateCell'
58
+ questionId: QuestionId
59
+ rowId: RowId
60
+ columnQuestionId: QuestionId
61
+ value: OpValue
62
+ }
27
63
  | { type: 'alternative.create'; questionId: QuestionId; alternativeId: AltId; label?: string; atIndex?: number }
64
+ /**
65
+ * Renaming is its own operation rather than delete-then-create because an alternative's id is
66
+ * referenced by every answer that selected it — recreating it under a new id is how the legacy
67
+ * data ended up with ~11,000 answers pointing at options that no longer exist.
68
+ */
69
+ | { type: 'alternative.updateField'; questionId: QuestionId; alternativeId: AltId; field: string; value: OpValue }
70
+ | { type: 'alternative.move'; questionId: QuestionId; alternativeId: AltId; toIndex: number }
28
71
  | { type: 'alternative.delete'; questionId: QuestionId; alternativeId: AltId }
72
+ | { type: 'tab.create'; tabId: TabId; label?: string; atIndex?: number }
73
+ | { type: 'tab.updateField'; tabId: TabId; field: string; value: OpValue }
74
+ | { type: 'tab.move'; tabId: TabId; toIndex: number }
75
+ | { type: 'tab.delete'; tabId: TabId }
76
+ | { type: 'layout.updateQuestion'; questionId: QuestionId; patch: Record<string, OpValue> }
77
+ // Actions are a set, not an ordered collection (architecture §2.1: `actionsById`, no order array).
78
+ | { type: 'action.create'; actionId: ActionId; kind?: string }
79
+ | { type: 'action.updateField'; actionId: ActionId; field: string; value: OpValue }
80
+ | { type: 'action.delete'; actionId: ActionId }
29
81
  | { type: 'mappingNode.create'; nodeId: NodeId; entityId: string; parentNodeId?: NodeId; relationshipId?: string }
82
+ | {
83
+ type: 'mappingNode.update'
84
+ nodeId: NodeId
85
+ patch: {
86
+ entityId?: string
87
+ /** `null` explicitly unsets — the node becomes a root. */
88
+ parentNodeId?: NodeId | null
89
+ relationshipId?: string | null
90
+ filterOrder?: FilterId[]
91
+ }
92
+ }
30
93
  | { type: 'mappingNode.delete'; nodeId: NodeId }
31
94
  | {
32
95
  type: 'mappingBinding.create'
@@ -50,27 +113,55 @@ export type TemplateOp =
50
113
  value?: DocScalar
51
114
  }
52
115
  | { type: 'mappingFilter.delete'; filterId: FilterId }
116
+ | { type: 'visibilityRule.set'; ruleId: VisibilityRuleId; questionId: QuestionId; condition: RuleCondition }
117
+ | { type: 'visibilityRule.delete'; ruleId: VisibilityRuleId }
118
+ | { type: 'highlightRule.set'; ruleId: HighlightRuleId; questionId: QuestionId; condition: RuleCondition }
119
+ | { type: 'highlightRule.delete'; ruleId: HighlightRuleId }
53
120
 
54
121
  export type TemplateOpType = TemplateOp['type']
55
122
 
56
123
  /**
57
- * The op types this reducer implements. The vocabulary in the architecture doc is
58
- * larger (grid rows, tabs, actions, layout, visibility/highlight rules); those slot
59
- * into the same registry without changing the envelope.
124
+ * The op types this reducer implements. Declared as a total `Record` over the union
125
+ * rather than a bare list, so **omitting an op is a compile error**. `satisfies readonly
126
+ * TemplateOpType[]` only rejected entries that are not op types; it could not notice a
127
+ * missing one, and this list is what downstream validators are built against — an op
128
+ * absent here is an op the server rejects at runtime with nothing red anywhere first.
60
129
  */
61
- export const IMPLEMENTED_OP_TYPES = [
62
- 'template.updateMeta',
63
- 'question.create',
64
- 'question.updateField',
65
- 'question.move',
66
- 'question.delete',
67
- 'alternative.create',
68
- 'alternative.delete',
69
- 'mappingNode.create',
70
- 'mappingNode.delete',
71
- 'mappingBinding.create',
72
- 'mappingBinding.update',
73
- 'mappingBinding.delete',
74
- 'mappingFilter.set',
75
- 'mappingFilter.delete',
76
- ] as const satisfies readonly TemplateOpType[]
130
+ const OP_TYPE_COVERAGE: Record<TemplateOpType, true> = {
131
+ 'template.updateMeta': true,
132
+ 'template.updateSettings': true,
133
+ 'question.create': true,
134
+ 'question.updateField': true,
135
+ 'question.move': true,
136
+ 'question.delete': true,
137
+ 'gridRow.create': true,
138
+ 'gridRow.move': true,
139
+ 'gridRow.delete': true,
140
+ 'gridRow.updateCell': true,
141
+ 'alternative.create': true,
142
+ 'alternative.updateField': true,
143
+ 'alternative.move': true,
144
+ 'alternative.delete': true,
145
+ 'tab.create': true,
146
+ 'tab.updateField': true,
147
+ 'tab.move': true,
148
+ 'tab.delete': true,
149
+ 'layout.updateQuestion': true,
150
+ 'action.create': true,
151
+ 'action.updateField': true,
152
+ 'action.delete': true,
153
+ 'mappingNode.create': true,
154
+ 'mappingNode.update': true,
155
+ 'mappingNode.delete': true,
156
+ 'mappingBinding.create': true,
157
+ 'mappingBinding.update': true,
158
+ 'mappingBinding.delete': true,
159
+ 'mappingFilter.set': true,
160
+ 'mappingFilter.delete': true,
161
+ 'visibilityRule.set': true,
162
+ 'visibilityRule.delete': true,
163
+ 'highlightRule.set': true,
164
+ 'highlightRule.delete': true,
165
+ }
166
+
167
+ export const IMPLEMENTED_OP_TYPES = Object.keys(OP_TYPE_COVERAGE) as readonly TemplateOpType[]
@@ -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
  import type { QuestionSubtype, QuestionType } from './questionTypes.js'
@@ -23,10 +23,93 @@ export type NodeId = string
23
23
  export type BindingId = string
24
24
  export type FilterId = string
25
25
  export type MappingId = string
26
+ export type VisibilityRuleId = string
27
+ export type HighlightRuleId = string
26
28
 
27
29
  /** A scalar a document may carry. Deliberately not `any`: DOC-LAW-2 bans `null`. */
28
30
  export type DocScalar = string | number | boolean
29
31
 
32
+ /**
33
+ * The required access level of the pinned version (OQ-V2-2): 1 anonymous, 2 identifiable
34
+ * without authentication, 3 lower-assurance authentication, 4 BankID. Never collapsed
35
+ * to a boolean; `invitationRequired` is a separate axis.
36
+ */
37
+ export type RequiredAccessLevel = 1 | 2 | 3 | 4
38
+
39
+ /** Who the questionnaire is initiated by (OQ-V2-15 wire vocabulary). */
40
+ export type Initiator = 'coordinator' | 'recipient'
41
+
42
+ /**
43
+ * What happens to in-flight instances when the family publishes a new version
44
+ * (OQ-V2-16, IMM-I5). v1 implements `never`; `always`/`ask` land later.
45
+ */
46
+ export type TemplateUpdateMode = 'never' | 'always' | 'ask'
47
+
48
+ /**
49
+ * The typed semantic body of the document (`meta`). Absent means the default, per
50
+ * DOC-LAW-2 — a questionnaire that requires nothing special stores `meta` with only
51
+ * what differs. Fields still open after the naming freeze (Gate-4) ride the index
52
+ * signature; the decided fields are spelled out so a typo is a compile error.
53
+ */
54
+ export type QnrTemplateMeta = {
55
+ title?: string
56
+ description?: string
57
+ /** Journal-wiring settings (M-007 aliases normalize here). */
58
+ settings?: {
59
+ journal?: {
60
+ /** `activityId_required`/`soknadid_required`/`sokndaid_required` unify here (architecture §2.2(7)). */
61
+ requires_activity_id?: boolean
62
+ }
63
+ /** Recipient-side requirements. */
64
+ recipient?: {
65
+ /** Legacy `ask_for_phone_nr`. */
66
+ ask_for_phone_nr?: boolean
67
+ }
68
+ }
69
+ /** Admission policy of the pinned version (OQ-V2-2/15/16). */
70
+ instancePolicy?: {
71
+ requiredAccessLevel?: RequiredAccessLevel
72
+ /** Open level-1 is invitation-free; invitation-protected level-1 sets this. */
73
+ invitationRequired?: boolean
74
+ initiator?: Initiator
75
+ template_update_mode?: TemplateUpdateMode
76
+ }
77
+ /** Presentation profiles (PM-6): audience/flow/layout/visibility — still loose pending their editor. */
78
+ presentationProfiles?: Record<string, unknown>
79
+ /** Owner-domain soft references (REQ-013): ids only, no bodies, no FK validation. */
80
+ compatibility?: {
81
+ consentTemplateIds?: string[]
82
+ smsTemplateIds?: string[]
83
+ }
84
+ [key: string]: unknown
85
+ }
86
+
87
+ /**
88
+ * The per-question-type configuration of a `QuestionGrid` (OQ-V2-17) — the repeat
89
+ * policy of the grid's rows. Lives at `question.grid.*`.
90
+ */
91
+ export type QuestionGridConfig = {
92
+ minRows?: number
93
+ maxRows?: number
94
+ /** `single_row` in OQ-V2-17 prose — max 1 row. */
95
+ singleRow?: boolean
96
+ deletableRows?: boolean
97
+ alwaysNew?: boolean
98
+ timestamps?: boolean
99
+ }
100
+
101
+ /**
102
+ * Grid-owned presentation (OQ-V2-17/25): row-editor layout, filters, grid actions,
103
+ * highlight rules, the header-tab reference and authored default column widths live
104
+ * here — there is no parallel `settings_ui` or `layoutByQuestionId` map.
105
+ */
106
+ export type QuestionGridPresentation = {
107
+ headerTabId?: TabId
108
+ /** OQ-V2-25: authored defaults; per-user widths are preference state outside both documents. */
109
+ defaultColumnWidthsByQuestionId?: Record<QuestionId, number>
110
+ [key: string]: unknown
111
+ }
112
+
30
113
  /**
31
114
  * `type` is the question's own discriminator (M-062), a closed union rather than a string — see
32
115
  * `questionTypes.ts` for why the value cannot be loose. Not to be confused with the other `kind`
@@ -39,14 +122,42 @@ export type QnrQuestion = {
39
122
  label?: string
40
123
  required?: boolean
41
124
  defaultValue?: DocScalar
125
+ /** `QuestionGrid` only: the row repeat policy. */
126
+ grid?: QuestionGridConfig
127
+ /** `QuestionGrid` only: grid-owned presentation (layout, filters, actions, column widths). */
128
+ presentation?: QuestionGridPresentation
42
129
  [key: string]: unknown
43
130
  }
44
131
 
45
132
  export type QnrAlternative = { label?: string; value?: DocScalar; [key: string]: unknown }
46
- export type QnrGridRow = { label?: string; [key: string]: unknown }
133
+
134
+ /** An authored predefined grid row; cells are keyed by column question id. */
135
+ export type QnrGridRow = {
136
+ label?: string
137
+ /** Authored default cell values, keyed by the column question id. */
138
+ cells?: Record<QuestionId, DocScalar>
139
+ [key: string]: unknown
140
+ }
141
+
47
142
  export type QnrTab = { label?: string; [key: string]: unknown }
48
143
  export type QnrAction = { kind?: string; [key: string]: unknown }
49
144
 
145
+ /**
146
+ * A typed conditional (OQ-V2-17/architecture §2.2(4)): question visibility/highlight
147
+ * depends on another question's answer. Legacy `dependent_question`+`dependent_questions`
148
+ * duals normalize into rule collections (byId + per-question order, DOC-LAW-1).
149
+ */
150
+ export type RuleCondition = {
151
+ sourceQuestionId: QuestionId
152
+ alternativeId?: AltId
153
+ operator?: string
154
+ value?: DocScalar
155
+ [key: string]: unknown
156
+ }
157
+
158
+ export type VisibilityRule = { condition: RuleCondition; [key: string]: unknown }
159
+ export type HighlightRule = { condition: RuleCondition; [key: string]: unknown }
160
+
50
161
  /** One traversal step. Many questions off one entity share a single node (§2.2a). */
51
162
  export type MappingNode = {
52
163
  entityId: string
@@ -84,7 +195,7 @@ export type MappingFilter = {
84
195
  export type QnrTemplateDocument = {
85
196
  documentId: string
86
197
  revision: number
87
- meta?: Record<string, unknown>
198
+ meta?: QnrTemplateMeta
88
199
  questionsById?: Record<QuestionId, QnrQuestion>
89
200
  questionOrder: QuestionId[]
90
201
  gridRowsById?: Record<RowId, QnrGridRow>
@@ -94,12 +205,33 @@ export type QnrTemplateDocument = {
94
205
  tabsById?: Record<TabId, QnrTab>
95
206
  tabOrder?: TabId[]
96
207
  actionsById?: Record<ActionId, QnrAction>
208
+ visibilityRulesById?: Record<VisibilityRuleId, VisibilityRule>
209
+ visibilityRuleOrderByQuestionId?: Record<QuestionId, VisibilityRuleId[]>
210
+ highlightRulesById?: Record<HighlightRuleId, HighlightRule>
211
+ highlightRuleOrderByQuestionId?: Record<QuestionId, HighlightRuleId[]>
97
212
  dataMappingsById?: Record<MappingId, { sourceId: string; rootNodeId: NodeId; bindingOrder?: BindingId[] }>
98
213
  mappingNodesById?: Record<NodeId, MappingNode>
99
214
  mappingBindingsById?: Record<BindingId, MappingBinding>
100
215
  mappingFiltersById?: Record<FilterId, MappingFilter>
101
216
  }
102
217
 
218
+ /**
219
+ * A reusable question-template bundle (OQ-V2-1): the root question plus every owned
220
+ * child question, alternative, predefined grid row, scoped tab/action, order and
221
+ * internal reference needed to use it. Stored whole in `qnr_question_templates.bundle`;
222
+ * a manual pick deep-copies and validates it into the family document.
223
+ */
224
+ export type QnrQuestionBundle = {
225
+ rootQuestionId: QuestionId
226
+ questionsById: Record<QuestionId, QnrQuestion>
227
+ gridRowsById?: Record<RowId, QnrGridRow>
228
+ gridRowOrderByQuestionId?: Record<QuestionId, RowId[]>
229
+ alternativesById?: Record<AltId, QnrAlternative>
230
+ alternativeOrderByQuestionId?: Record<QuestionId, AltId[]>
231
+ tabsById?: Record<TabId, QnrTab>
232
+ actionsById?: Record<ActionId, QnrAction>
233
+ }
234
+
103
235
  /**
104
236
  * A new family's document. `questionOrder` is present-and-empty rather than absent
105
237
  * because it is the document's only structural array and every reader indexes it; an