asma-core-helpers 0.29.0 → 0.31.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 +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 +197 -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/package.json +1 -1
  24. package/src/collaboration/applyOperation.ts +736 -9
  25. package/src/collaboration/operations.ts +97 -0
  26. package/src/collaboration/schemas.ts +191 -1
  27. package/src/collaboration/templateDocument.test.ts +94 -0
  28. package/src/collaboration/templateDocument.ts +188 -1
  29. package/src/collaboration/testHelpers/documentGenerator.ts +77 -1
  30. package/src/collaboration/typeContracts.ts +57 -0
  31. package/src/collaboration/typedAuthoring.test.ts +641 -0
  32. package/src/collaboration/typedAuthoringHardening.test.ts +408 -0
@@ -1,5 +1,7 @@
1
1
  import type {
2
2
  ActionId,
3
+ ActionMetadata,
4
+ ActionType,
3
5
  AltId,
4
6
  BindingCardinality,
5
7
  BindingId,
@@ -10,6 +12,7 @@ import type {
10
12
  FilterId,
11
13
  HighlightRuleId,
12
14
  LayoutPlacement,
15
+ MappingFilterPayload,
13
16
  MappingId,
14
17
  NarrativeRuleId,
15
18
  NodeId,
@@ -73,6 +76,32 @@ export type TemplateOp =
73
76
  columnQuestionId: QuestionId
74
77
  placement: LayoutPlacement | null
75
78
  }
79
+ /**
80
+ * Adds, moves or removes one column in the grid's filter selection (M-054).
81
+ *
82
+ * Member-wise rather than a whole-list write, which is the difference that makes concurrent
83
+ * authoring work: two authors adding different filters produce two edits to the *current* list, so
84
+ * both survive. A `filterQuestionIds` array written wholesale would have the second overwrite the
85
+ * first with no conflict raised — the same reason DOC-LAW-1 keys collections by id.
86
+ *
87
+ * `include: true` inserts (at `atIndex`, else appends) and **moves** an id already present when
88
+ * `atIndex` is given; `include: false` removes it. An emptied list is omitted, per DOC-LAW-2.
89
+ */
90
+ | {
91
+ type: 'gridColumn.setFilter'
92
+ questionId: QuestionId
93
+ columnQuestionId: QuestionId
94
+ include: boolean
95
+ atIndex?: number
96
+ }
97
+ /** The same member-wise semantics for the grid's owned action ids (M-055). Ids only, never bodies. */
98
+ | {
99
+ type: 'gridColumn.setAction'
100
+ questionId: QuestionId
101
+ actionId: ActionId
102
+ include: boolean
103
+ atIndex?: number
104
+ }
76
105
  // Authoring-side grid rows are the template's *predefined* rows; instance-added rows
77
106
  // are answer ops (answerOperations.ts). `gridRow.move` is anchor-relative (OQ-V2-24).
78
107
  | { type: 'gridRow.create'; questionId: QuestionId; rowId: RowId; label?: string; atIndex?: number }
@@ -97,10 +126,62 @@ export type TemplateOp =
97
126
  | { type: 'tab.create'; tabId: TabId; label?: string; atIndex?: number }
98
127
  | { type: 'tab.updateField'; tabId: TabId; field: string; value: OpValue }
99
128
  | { type: 'tab.move'; tabId: TabId; toIndex: number }
129
+ /**
130
+ * Writes one question's placement inside a tab's positional grid atomically (M-051).
131
+ *
132
+ * `{row, cell, keepCellSize}` moves as one value, which `tab.updateField` cannot express — an
133
+ * `OpValue` is a scalar or a primitive array — so two dotted updates would be the alternative, and
134
+ * a client that landed one and lost the other would leave a row/cell hybrid the author never
135
+ * authored. `placement: null` clears the entry. Concurrent moves of *different* questions both
136
+ * survive; concurrent moves of the *same* question are last-writer-wins on a whole placement.
137
+ */
138
+ | { type: 'tab.setLayout'; tabId: TabId; questionId: QuestionId; placement: LayoutPlacement | null }
100
139
  | { type: 'tab.delete'; tabId: TabId }
101
140
  // Actions are a set, not an ordered collection (architecture §2.1: `actionsById`, no order array).
102
141
  | { type: 'action.create'; actionId: ActionId; kind?: string }
103
142
  | { type: 'action.updateField'; actionId: ActionId; field: string; value: OpValue }
143
+ /**
144
+ * Creates a **known** action in minimal form, discriminated by kind.
145
+ *
146
+ * Separate from `action.create` (which stays as released, accepting any `kind` string) because the
147
+ * typed path is closed: it cannot mint a UI edit buffer, and it cannot create a kind the reducer
148
+ * has no rules for. Kind is write-once — `action.updateField` refuses to change it.
149
+ */
150
+ /**
151
+ * Two closed arms, not one arm with an optional member: `actionType` is a `gridAction` concept, and a
152
+ * single arm would type-check `{kind: 'topLevelAction', actionType: 'COPY'}` — leaving the reducer as
153
+ * the only thing that noticed, which is a runtime refusal for something the compiler can prevent.
154
+ */
155
+ | { type: 'action.createTyped'; actionId: ActionId; kind: 'topLevelAction'; label?: string; actionType?: never }
156
+ | {
157
+ type: 'action.createTyped'
158
+ actionId: ActionId
159
+ kind: 'gridAction'
160
+ label?: string
161
+ /** A valid draft may omit it; publication is where that is refused. */
162
+ actionType?: ActionType
163
+ }
164
+ /**
165
+ * Adds, moves or removes one grid-action id inside a top-level action's per-grid sequence (M-052).
166
+ *
167
+ * `topLevelAction`-only, member-wise for the same concurrency reason as the grid lists. An emptied
168
+ * sequence drops its grid key, and an emptied map is omitted (DOC-LAW-2).
169
+ */
170
+ | {
171
+ type: 'action.setGridActionRef'
172
+ actionId: ActionId
173
+ gridQuestionId: QuestionId
174
+ gridActionId: ActionId
175
+ include: boolean
176
+ atIndex?: number
177
+ }
178
+ /**
179
+ * Writes or clears one column's metadata on a grid action (M-055).
180
+ *
181
+ * `gridAction`-only. `null` removes the entry; a payload is written canonically, so `{all: true}`
182
+ * stays exclusive with `from`/`to` and an empty object never reaches the document.
183
+ */
184
+ | { type: 'action.setMetadata'; actionId: ActionId; questionId: QuestionId; metadata: ActionMetadata | null }
104
185
  | { type: 'action.delete'; actionId: ActionId }
105
186
  // One entry per mapping root (§2.2a): the root node must exist first (structure pass),
106
187
  // the mapping attaches it to a source (mapping pass). Delete cascades the whole tree.
@@ -162,6 +243,15 @@ export type TemplateOp =
162
243
  operator: string
163
244
  value?: DocScalar
164
245
  }
246
+ /**
247
+ * Sets a filter to one **closed** operator and exactly that operator's payload.
248
+ *
249
+ * Additive beside `mappingFilter.set`, which stays byte-for-byte as released so stored `contains`
250
+ * filters keep replaying. The reducer REPLACES the record rather than patching it, so switching
251
+ * `eq` → `in` cannot leave a stale `value` next to the new `values`; a filter therefore always
252
+ * carries the members of its own operator and no others.
253
+ */
254
+ | ({ type: 'mappingFilter.setTyped'; filterId: FilterId; nodeId: NodeId; fieldId: string } & MappingFilterPayload)
165
255
  | { type: 'mappingFilter.delete'; filterId: FilterId }
166
256
  | { type: 'visibilityRule.set'; ruleId: VisibilityRuleId; questionId: QuestionId; condition: RuleCondition }
167
257
  | { type: 'visibilityRule.delete'; ruleId: VisibilityRuleId }
@@ -198,6 +288,8 @@ const OP_TYPE_COVERAGE: Record<TemplateOpType, true> = {
198
288
  'gridColumn.create': true,
199
289
  'gridColumn.move': true,
200
290
  'gridColumn.setLayout': true,
291
+ 'gridColumn.setFilter': true,
292
+ 'gridColumn.setAction': true,
201
293
  'gridRow.create': true,
202
294
  'gridRow.move': true,
203
295
  'gridRow.delete': true,
@@ -209,9 +301,13 @@ const OP_TYPE_COVERAGE: Record<TemplateOpType, true> = {
209
301
  'tab.create': true,
210
302
  'tab.updateField': true,
211
303
  'tab.move': true,
304
+ 'tab.setLayout': true,
212
305
  'tab.delete': true,
213
306
  'action.create': true,
214
307
  'action.updateField': true,
308
+ 'action.createTyped': true,
309
+ 'action.setGridActionRef': true,
310
+ 'action.setMetadata': true,
215
311
  'action.delete': true,
216
312
  'dataMapping.create': true,
217
313
  'dataMapping.delete': true,
@@ -222,6 +318,7 @@ const OP_TYPE_COVERAGE: Record<TemplateOpType, true> = {
222
318
  'mappingBinding.update': true,
223
319
  'mappingBinding.delete': true,
224
320
  'mappingFilter.set': true,
321
+ 'mappingFilter.setTyped': true,
225
322
  'mappingFilter.delete': true,
226
323
  'visibilityRule.set': true,
227
324
  'visibilityRule.delete': true,
@@ -7,10 +7,12 @@ import { IMPLEMENTED_OP_TYPES } from './operations.js'
7
7
  import { QUESTION_TYPES } from './questionTypes.js'
8
8
  import type { BindingTarget, QnrTemplateDocument } from './templateDocument.js'
9
9
  import {
10
+ ACTION_TYPES,
10
11
  BINDING_CARDINALITIES,
11
12
  BINDING_ON_MANY,
12
13
  BINDING_ON_MISSING,
13
14
  BINDING_OPTION_DEFAULTS,
15
+ MAPPING_FILTER_OPERATORS,
14
16
  bindingTargetKey,
15
17
  } from './templateDocument.js'
16
18
 
@@ -136,6 +138,10 @@ const questionGridPresentationSchema = type({
136
138
  headerTabId: 'string?',
137
139
  "rowEditor?": questionGridRowEditorSchema,
138
140
  defaultColumnWidthsByQuestionId: 'Record<string, number>?',
141
+ // Primitive id arrays, which DOC-LAW-1 allows: the per-entry filter configuration legacy kept in
142
+ // `filter_ui.questions[]` belongs on the column question, so the grid owns only the selection.
143
+ filterQuestionIds: 'string[]?',
144
+ actionIds: 'string[]?',
139
145
  ...({ '[string]': 'unknown' } as const),
140
146
  })
141
147
 
@@ -183,13 +189,46 @@ const qnrGridRowSchema = type({
183
189
  ...({ '[string]': 'unknown' } as const),
184
190
  })
185
191
 
192
+ const qnrTabLayoutSchema = type({
193
+ "placementsByQuestionId?": recordOf(layoutPlacementSchema),
194
+ ...({ '[string]': 'unknown' } as const),
195
+ })
196
+
186
197
  const qnrTabSchema = type({
187
198
  label: 'string?',
199
+ "layout?": qnrTabLayoutSchema,
188
200
  ...({ '[string]': 'unknown' } as const),
189
201
  })
190
202
 
203
+ /**
204
+ * One metadata entry. `all: true` is the canonical all-to-all marker and is exclusive with the bounds —
205
+ * a bare `{}` is refused, because DOC-LAW-2 would make "selected but unbounded" and "not selected" the
206
+ * same absence.
207
+ */
208
+ const actionMetadataSchema = type.or(
209
+ // Every arm declares the OTHER arms' members `never`. Omitting them would not be enough: an
210
+ // ArkType object admits undeclared keys, so `{all: true, from: 'a'}` would satisfy the bounded arm
211
+ // and the exclusivity rule would exist only in the reducer.
212
+ type({ from: docScalar, to: docScalar, "all?": 'never' }),
213
+ type({ from: docScalar, "to?": 'never', "all?": 'never' }),
214
+ type({ "from?": 'never', to: docScalar, "all?": 'never' }),
215
+ type({ all: 'true', "from?": 'never', "to?": 'never' }),
216
+ )
217
+
218
+ /**
219
+ * The action record stays BROAD: `kind` is an optional string and the bag is open, because released
220
+ * documents carry unknown kinds and accidental UI buffers that must remain readable (ADR-0008 DEC-006).
221
+ *
222
+ * The typed members are declared so a KNOWN action's shape is validated where it is present — an
223
+ * ordered primitive id array per grid, and canonical metadata per column — without making any of it
224
+ * required. Narrowing `kind` here is exactly what the freeze forbids.
225
+ */
191
226
  const qnrActionSchema = type({
192
227
  kind: 'string?',
228
+ label: 'string?',
229
+ "actionType?": type.enumerated(...ACTION_TYPES),
230
+ actionIdsByGridQuestionId: 'Record<string, string[]>?',
231
+ "metadataByQuestionId?": recordOf(actionMetadataSchema),
193
232
  ...({ '[string]': 'unknown' } as const),
194
233
  })
195
234
 
@@ -227,10 +266,18 @@ const mappingBindingSchema = type({
227
266
  ...({ '[string]': 'unknown' } as const),
228
267
  })
229
268
 
269
+ /**
270
+ * The stored filter. `operator` stays `string` — released, and documents carry operators outside the
271
+ * closed set (`contains`) that must remain readable. `values`/`from`/`to` are the additive payload
272
+ * members the typed operator arms write.
273
+ */
230
274
  const mappingFilterSchema = type({
231
275
  fieldId: 'string',
232
276
  operator: 'string',
233
277
  "value?": docScalar,
278
+ "values?": '(string | number | boolean)[]',
279
+ "from?": docScalar,
280
+ "to?": docScalar,
234
281
  })
235
282
 
236
283
  const dataMappingSchema = type({
@@ -340,6 +387,20 @@ export const templateOpSchema = type.or(
340
387
  columnQuestionId: 'string',
341
388
  placement: type.or(layoutPlacementSchema, type('null')),
342
389
  }),
390
+ type({
391
+ type: '"gridColumn.setFilter"',
392
+ questionId: 'string',
393
+ columnQuestionId: 'string',
394
+ include: 'boolean',
395
+ atIndex: 'number?',
396
+ }),
397
+ type({
398
+ type: '"gridColumn.setAction"',
399
+ questionId: 'string',
400
+ actionId: 'string',
401
+ include: 'boolean',
402
+ atIndex: 'number?',
403
+ }),
343
404
  type({ type: '"gridRow.create"', questionId: 'string', rowId: 'string', label: 'string?', atIndex: 'number?' }),
344
405
  type({ type: '"gridRow.move"', questionId: 'string', rowId: 'string', afterRowId: 'string | null' }),
345
406
  type({ type: '"gridRow.delete"', questionId: 'string', rowId: 'string' }),
@@ -363,9 +424,60 @@ export const templateOpSchema = type.or(
363
424
  type({ type: '"tab.create"', tabId: 'string', label: 'string?', atIndex: 'number?' }),
364
425
  type({ type: '"tab.updateField"', tabId: 'string', field: 'string', value: opValue }),
365
426
  type({ type: '"tab.move"', tabId: 'string', toIndex: 'number' }),
427
+ type({
428
+ type: '"tab.setLayout"',
429
+ tabId: 'string',
430
+ questionId: 'string',
431
+ placement: type.or(layoutPlacementSchema, type('null')),
432
+ }),
366
433
  type({ type: '"tab.delete"', tabId: 'string' }),
367
434
  type({ type: '"action.create"', actionId: 'string', kind: 'string?' }),
368
435
  type({ type: '"action.updateField"', actionId: 'string', field: 'string', value: opValue }),
436
+ /**
437
+ * Two arms, discriminated on `kind`. A single arm with an optional `actionType` admitted
438
+ * `{kind: 'topLevelAction', actionType: 'COPY'}` and left the reducer as the only thing that
439
+ * noticed — a runtime refusal for something the wire can close.
440
+ *
441
+ * `actionType?: never` on the top-level arm rather than omission: an ArkType object admits
442
+ * undeclared keys, so leaving it out would let it through. Same reason the UI buffers are spelled
443
+ * out as `never` on both arms.
444
+ */
445
+ type({
446
+ type: '"action.createTyped"',
447
+ actionId: 'string',
448
+ kind: '"topLevelAction"',
449
+ label: 'string?',
450
+ "actionType?": 'never',
451
+ "editableLabel?": 'never',
452
+ "editableType?": 'never',
453
+ "editable_label?": 'never',
454
+ "editable_type?": 'never',
455
+ }),
456
+ type({
457
+ type: '"action.createTyped"',
458
+ actionId: 'string',
459
+ kind: '"gridAction"',
460
+ label: 'string?',
461
+ "actionType?": type.enumerated(...ACTION_TYPES),
462
+ "editableLabel?": 'never',
463
+ "editableType?": 'never',
464
+ "editable_label?": 'never',
465
+ "editable_type?": 'never',
466
+ }),
467
+ type({
468
+ type: '"action.setGridActionRef"',
469
+ actionId: 'string',
470
+ gridQuestionId: 'string',
471
+ gridActionId: 'string',
472
+ include: 'boolean',
473
+ atIndex: 'number?',
474
+ }),
475
+ type({
476
+ type: '"action.setMetadata"',
477
+ actionId: 'string',
478
+ questionId: 'string',
479
+ metadata: type.or(actionMetadataSchema, type('null')),
480
+ }),
369
481
  type({ type: '"action.delete"', actionId: 'string' }),
370
482
  type({ type: '"dataMapping.create"', mappingId: 'string', sourceId: 'string', rootNodeId: 'string' }),
371
483
  type({ type: '"dataMapping.delete"', mappingId: 'string' }),
@@ -421,6 +533,67 @@ export const templateOpSchema = type.or(
421
533
  operator: 'string',
422
534
  value: docScalar,
423
535
  }),
536
+ /**
537
+ * Operator-discriminated, so the payload cannot disagree with the operator: `eq` takes a value,
538
+ * `in` a NON-EMPTY list, `range` at least one bound and no value, `isNull` a boolean. Each arm
539
+ * declares the other operators' members `never`, which is what refuses a mixed record carrying a
540
+ * stale `value` beside new `values`.
541
+ */
542
+ type({
543
+ type: '"mappingFilter.setTyped"',
544
+ filterId: 'string',
545
+ nodeId: 'string',
546
+ fieldId: 'string',
547
+ operator: '"eq"',
548
+ value: docScalar,
549
+ "values?": 'never',
550
+ "from?": 'never',
551
+ "to?": 'never',
552
+ }),
553
+ type({
554
+ type: '"mappingFilter.setTyped"',
555
+ filterId: 'string',
556
+ nodeId: 'string',
557
+ fieldId: 'string',
558
+ operator: '"in"',
559
+ values: '(string | number | boolean)[] > 0',
560
+ "value?": 'never',
561
+ "from?": 'never',
562
+ "to?": 'never',
563
+ }),
564
+ type({
565
+ type: '"mappingFilter.setTyped"',
566
+ filterId: 'string',
567
+ nodeId: 'string',
568
+ fieldId: 'string',
569
+ operator: '"range"',
570
+ from: docScalar,
571
+ "to?": docScalar,
572
+ "value?": 'never',
573
+ "values?": 'never',
574
+ }),
575
+ type({
576
+ type: '"mappingFilter.setTyped"',
577
+ filterId: 'string',
578
+ nodeId: 'string',
579
+ fieldId: 'string',
580
+ operator: '"range"',
581
+ "from?": 'never',
582
+ to: docScalar,
583
+ "value?": 'never',
584
+ "values?": 'never',
585
+ }),
586
+ type({
587
+ type: '"mappingFilter.setTyped"',
588
+ filterId: 'string',
589
+ nodeId: 'string',
590
+ fieldId: 'string',
591
+ operator: '"isNull"',
592
+ value: 'boolean',
593
+ "values?": 'never',
594
+ "from?": 'never',
595
+ "to?": 'never',
596
+ }),
424
597
  type({ type: '"mappingFilter.delete"', filterId: 'string' }),
425
598
  type({ type: '"visibilityRule.set"', ruleId: 'string', questionId: 'string', condition: ruleConditionSchema }),
426
599
  type({ type: '"visibilityRule.delete"', ruleId: 'string' }),
@@ -461,12 +634,23 @@ type JsonSchemaLike = {
461
634
  properties?: { type?: { const?: unknown } }
462
635
  }
463
636
 
637
+ /**
638
+ * The distinct op names a schema validates.
639
+ *
640
+ * **Deduplicated**, because one op type may legitimately span several union arms: an
641
+ * operator-discriminated payload (`mappingFilter.setTyped`) is one op with five mutually exclusive
642
+ * shapes, which is exactly how the payload is prevented from disagreeing with its operator. The parity
643
+ * property is "the schema covers exactly these op TYPES", so counting arms instead of types would make
644
+ * a correctly-modelled discriminated op look like a vocabulary mismatch.
645
+ */
464
646
  const opTypeNames = (schema: Type): string[] => {
465
647
  const json = schema.toJsonSchema() as unknown as JsonSchemaLike
466
648
  const members = json.anyOf ?? [json]
467
- return members
649
+ const names = members
468
650
  .map((member) => member.properties?.type?.const)
469
651
  .filter((value): value is string => typeof value === 'string')
652
+
653
+ return [...new Set(names)]
470
654
  }
471
655
 
472
656
  /**
@@ -642,6 +826,12 @@ const TEMPLATE_DOCUMENT_DEFAULT_PATHS: readonly string[] = [
642
826
  */
643
827
  const BINDING_OPTION_DEFAULT_PATH = /^mappingBindingsById\.[^.]+\.(cardinality|onMissing|onMany)$/
644
828
 
829
+ /**
830
+ * The closed operator set, re-exported through the schema module so a consumer validating a filter and a
831
+ * consumer authoring one read the same list. Declared once in `templateDocument.ts`.
832
+ */
833
+ export const SCHEMA_MAPPING_FILTER_OPERATORS: readonly string[] = MAPPING_FILTER_OPERATORS
834
+
645
835
  export const templateDocumentIsDefault: IsDefault = (path, value) => {
646
836
  const option = BINDING_OPTION_DEFAULT_PATH.exec(path)?.[1]
647
837
 
@@ -0,0 +1,94 @@
1
+ import assert from 'node:assert/strict'
2
+ import { describe, it } from 'node:test'
3
+
4
+ import type { QnrQuestionBundle } from './templateDocument.js'
5
+
6
+ /**
7
+ * The bundle's order contract (OQ-V2-1, ASMA-7683 AC-5).
8
+ *
9
+ * A `QnrQuestionBundle` is stored whole in `qnr_question_templates.bundle`, a **`jsonb`** column, and
10
+ * a pick replays it as ordinary authoring ops. `tab.create` appends, so the order the pick emits tabs
11
+ * in *is* the order they take in the live template's tab bar. That makes "which order were these tabs
12
+ * authored in" a question the stored bundle has to be able to answer.
13
+ *
14
+ * `jsonb` cannot answer it: it normalizes object keys by length, then bytewise. So this suite states
15
+ * the property as a test rather than as a promise in a doc comment — an order that lives in key
16
+ * positions is an order the storage layer is free to change, and it does.
17
+ *
18
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:193 — DOC-LAW-1, array position is identity-by-accident
19
+ */
20
+
21
+ /**
22
+ * PostgreSQL's `jsonb` object-key normalization: shorter keys first, then bytewise.
23
+ *
24
+ * Reproduced here rather than asserted against a live database so the contract is pinned in the
25
+ * package that declares it. Verified against PostgreSQL 17 while diagnosing this gap:
26
+ * `SELECT jsonb_object_keys('{"t-zulu":{},"t-alfa":{}}'::jsonb)` yields `t-alfa` then `t-zulu`, and
27
+ * the same literal cast to `json` yields the authored order — the column type is what decides.
28
+ */
29
+ const asJsonbWouldStoreIt = <T>(record: Record<string, T>): Record<string, T> =>
30
+ Object.fromEntries(
31
+ Object.entries(record).sort(([left], [right]) =>
32
+ left.length === right.length ? left.localeCompare(right, 'en') : left.length - right.length,
33
+ ),
34
+ )
35
+
36
+ describe('QnrQuestionBundle tab order', () => {
37
+ // Deliberately chosen so authored order and jsonb order disagree: equal length, reverse-sorted.
38
+ const authored = ['t-zulu', 't-alfa']
39
+
40
+ const bundle: QnrQuestionBundle = {
41
+ rootQuestionId: 'q-grid',
42
+ questionsById: {
43
+ 'q-grid': { type: 'QuestionGrid', grid: { columnIds: ['q-col'] }, presentation: { headerTabId: 't-zulu' } },
44
+ 'q-col': { type: 'TextShort' },
45
+ },
46
+ tabsById: { 't-zulu': { label: 'Første' }, 't-alfa': { label: 'Andre' } },
47
+ tabOrder: authored,
48
+ }
49
+
50
+ it('loses the authored order when it lives in key positions', () => {
51
+ // The gap this member closes, kept executable: if a future storage change made key order
52
+ // stable, this assertion fails and the member's justification has to be revisited.
53
+ const stored = asJsonbWouldStoreIt(bundle.tabsById ?? {})
54
+
55
+ assert.deepEqual(Object.keys(stored), ['t-alfa', 't-zulu'])
56
+ assert.notDeepEqual(Object.keys(stored), authored)
57
+ })
58
+
59
+ it('normalizes shorter keys first, not plain alphabetically', () => {
60
+ // Pins the rule rather than just "some reordering happens". The two-tab fixture above has
61
+ // equal-length ids, where length-first and alphabetical agree — so on its own it would accept
62
+ // a wrong model of jsonb. Measured: `SELECT jsonb_object_keys('{"bbb":1,"aa":2,"cccc":3}')`
63
+ // yields aa, bbb, cccc, so a longer key sorts after a shorter one whatever the bytes say.
64
+ assert.deepEqual(Object.keys(asJsonbWouldStoreIt({ 't-b': 1, 't-aa': 2 })), ['t-b', 't-aa'])
65
+
66
+ // Alphabetically 't-aa' precedes 't-b', which is the answer this must NOT give.
67
+ assert.notDeepEqual(Object.keys(asJsonbWouldStoreIt({ 't-b': 1, 't-aa': 2 })), ['t-aa', 't-b'])
68
+ })
69
+
70
+ it('round-trips the authored order through tabOrder', () => {
71
+ // An array, so jsonb preserves it — arrays are ordered in both json and jsonb.
72
+ const stored: QnrQuestionBundle = {
73
+ ...bundle,
74
+ tabsById: asJsonbWouldStoreIt(bundle.tabsById ?? {}),
75
+ tabOrder: [...(bundle.tabOrder ?? [])],
76
+ }
77
+
78
+ assert.deepEqual(stored.tabOrder, authored)
79
+ // And it still names exactly the carried tabs — the property a validator checks.
80
+ assert.deepEqual([...(stored.tabOrder ?? [])].sort(), Object.keys(stored.tabsById ?? {}).sort())
81
+ })
82
+
83
+ it('is absent, not empty, on a bundle with nothing to order', () => {
84
+ // DOC-LAW-2's shape rule reaches the fragment too: a single-tab bundle states no order, and
85
+ // `tabOrder: []` would be a second encoding of "not set".
86
+ const singleTab: QnrQuestionBundle = {
87
+ rootQuestionId: 'q-grid',
88
+ questionsById: { 'q-grid': { type: 'QuestionGrid', presentation: { headerTabId: 't-only' } } },
89
+ tabsById: { 't-only': { label: 'Eneste' } },
90
+ }
91
+
92
+ assert.equal('tabOrder' in singleTab, false)
93
+ })
94
+ })