asma-core-helpers 0.28.1 → 0.30.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.
@@ -6,7 +6,13 @@ import { IMPLEMENTED_ANSWER_OP_TYPES } from './answerOperations.js'
6
6
  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
- import { bindingTargetKey } from './templateDocument.js'
9
+ import {
10
+ BINDING_CARDINALITIES,
11
+ BINDING_ON_MANY,
12
+ BINDING_ON_MISSING,
13
+ BINDING_OPTION_DEFAULTS,
14
+ bindingTargetKey,
15
+ } from './templateDocument.js'
10
16
 
11
17
  /**
12
18
  * The ArkType schemas for the two hashed documents and both op vocabularies (plan TASK-003),
@@ -200,13 +206,24 @@ const bindingTargetSchema = type.or(
200
206
  type({ kind: '"gridColumn"', gridQuestionId: 'string', columnQuestionId: 'string' }),
201
207
  )
202
208
 
209
+ /**
210
+ * The three behaviour vocabularies, derived from the single declaration in `templateDocument.ts`
211
+ * rather than re-spelled — a second list of literals here could drift from the one the reducer and
212
+ * the UI branch on, and the drift would only show up as a validation refusal in production.
213
+ */
214
+ const bindingCardinalitySchema = type.enumerated(...BINDING_CARDINALITIES)
215
+ const bindingOnMissingSchema = type.enumerated(...BINDING_ON_MISSING)
216
+ const bindingOnManySchema = type.enumerated(...BINDING_ON_MANY)
217
+
203
218
  const mappingBindingSchema = type({
204
219
  nodeId: 'string',
205
220
  fieldId: 'string',
206
221
  target: bindingTargetSchema,
207
- cardinality: 'string?',
208
- onMissing: 'string?',
209
- onMany: 'string?',
222
+ // Closed sets, not `string?`: these compile into an immutable artifact, so a typo that validates
223
+ // here is a wrong prefill nobody can fix in place afterwards.
224
+ 'cardinality?': bindingCardinalitySchema,
225
+ 'onMissing?': bindingOnMissingSchema,
226
+ 'onMany?': bindingOnManySchema,
210
227
  ...({ '[string]': 'unknown' } as const),
211
228
  })
212
229
 
@@ -376,14 +393,23 @@ export const templateOpSchema = type.or(
376
393
  nodeId: 'string',
377
394
  fieldId: 'string',
378
395
  target: bindingTargetSchema,
396
+ 'cardinality?': bindingCardinalitySchema,
397
+ 'onMissing?': bindingOnMissingSchema,
398
+ 'onMany?': bindingOnManySchema,
379
399
  }),
380
400
  type({
381
401
  type: '"mappingBinding.update"',
382
402
  bindingId: 'string',
403
+ // `| null` on the three behaviours only: the op layer is where the absent-vs-cleared
404
+ // tri-state lives (operations.ts header), so returning a behaviour to its default is
405
+ // expressible without making "leave it alone" and "reset it" the same patch.
383
406
  patch: type({
384
407
  nodeId: 'string?',
385
408
  fieldId: 'string?',
386
- "target?": bindingTargetSchema,
409
+ 'target?': bindingTargetSchema,
410
+ 'cardinality?': bindingCardinalitySchema.or(type.null),
411
+ 'onMissing?': bindingOnMissingSchema.or(type.null),
412
+ 'onMany?': bindingOnManySchema.or(type.null),
387
413
  }),
388
414
  }),
389
415
  type({ type: '"mappingBinding.delete"', bindingId: 'string' }),
@@ -605,8 +631,26 @@ const TEMPLATE_DOCUMENT_DEFAULT_PATHS: readonly string[] = [
605
631
  'timestamps', // question.grid (legacy composite `row_timestamps`)
606
632
  ]
607
633
 
608
- export const templateDocumentIsDefault: IsDefault = (path, value) =>
609
- value === false && TEMPLATE_DOCUMENT_DEFAULT_PATHS.some((name) => path.endsWith(`.${name}`))
634
+ /**
635
+ * The binding behaviours, whose default is a **value** rather than `false` and whose path must
636
+ * therefore be matched exactly rather than by suffix.
637
+ *
638
+ * Anchored on `mappingBindingsById.<id>.<key>` on purpose: a mapping **node** may also carry a
639
+ * `cardinality`, and its default is the catalog relation's — not a literal. A suffix rule would
640
+ * read a node's deliberately-narrowed `cardinality: '0..1'` over a `0..*` relation as an omittable
641
+ * default and drop the one member that made the node take a single row.
642
+ */
643
+ const BINDING_OPTION_DEFAULT_PATH = /^mappingBindingsById\.[^.]+\.(cardinality|onMissing|onMany)$/
644
+
645
+ export const templateDocumentIsDefault: IsDefault = (path, value) => {
646
+ const option = BINDING_OPTION_DEFAULT_PATH.exec(path)?.[1]
647
+
648
+ if (option !== undefined) {
649
+ return value === BINDING_OPTION_DEFAULTS[option as keyof typeof BINDING_OPTION_DEFAULTS]
650
+ }
651
+
652
+ return value === false && TEMPLATE_DOCUMENT_DEFAULT_PATHS.some((name) => path.endsWith(`.${name}`))
653
+ }
610
654
 
611
655
  /**
612
656
  * The instance-side half of the default lint: every present-and-default field on a stored
@@ -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
+ })
@@ -266,16 +266,84 @@ export const bindingTargetKey = (target: BindingTarget): string =>
266
266
  ? `question:${target.questionId}`
267
267
  : `gridColumn:${target.gridQuestionId}:${target.columnQuestionId}`
268
268
 
269
+ /**
270
+ * A binding's expected cardinality (§13.1). Closed rather than a loose string because the compiler
271
+ * branches on it: `0..1`/`1` fill one slot, `0..*`/`1..*` feed a grid's rows, and a typo would compile
272
+ * into an artifact that is immutable forever.
273
+ *
274
+ * `0..1` is the default, so DOC-LAW-2 means it is **never stored** — a binding that takes at most one
275
+ * value carries no `cardinality` key at all.
276
+ *
277
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-15-20-38-analysis-qnr-external-data-mapping-options.md:840 — the four values
278
+ */
279
+ export const BINDING_CARDINALITIES = ['0..1', '1', '0..*', '1..*'] as const
280
+ export type BindingCardinality = (typeof BINDING_CARDINALITIES)[number]
281
+
282
+ /**
283
+ * What the runtime does when the source yields **no** value for a binding. `omit` leaves the question
284
+ * unfilled (the default); `error` makes the absence a prefill failure the author wants surfaced rather
285
+ * than silently tolerated.
286
+ */
287
+ export const BINDING_ON_MISSING = ['omit', 'error'] as const
288
+ export type BindingOnMissing = (typeof BINDING_ON_MISSING)[number]
289
+
290
+ /**
291
+ * What the runtime does when the source yields **many** values for a binding expecting one. `error` is
292
+ * the default — an ambiguous prefill is a real defect — and `first` is the deliberate opt-in, which is
293
+ * why the node's `orderBy` must make "first" deterministic before it means anything.
294
+ */
295
+ export const BINDING_ON_MANY = ['error', 'first'] as const
296
+ export type BindingOnMany = (typeof BINDING_ON_MANY)[number]
297
+
298
+ /**
299
+ * The three binding behaviours and their defaults, in one place because two rules depend on it: the
300
+ * reducer omits a chosen value that equals its default (DOC-LAW-2 — a key present with its own default
301
+ * is a second encoding of "not set", and the hash is computed on the minimal form), and every reader
302
+ * hydrates the absent key back to the same value.
303
+ *
304
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-15-20-38-analysis-qnr-external-data-mapping-options.md:832 — absent because they equal their defaults
305
+ */
306
+ /** The binding behaviours a reader sees — total, because the stored document is minimal. */
307
+ export type ResolvedBindingOptions = {
308
+ cardinality: BindingCardinality
309
+ onMissing: BindingOnMissing
310
+ onMany: BindingOnMany
311
+ }
312
+
313
+ export const BINDING_OPTION_DEFAULTS = {
314
+ cardinality: '0..1',
315
+ onMissing: 'omit',
316
+ onMany: 'error',
317
+ } as const satisfies ResolvedBindingOptions
318
+
269
319
  export type MappingBinding = {
270
320
  nodeId: NodeId
271
321
  fieldId: string
272
322
  target: BindingTarget
273
- cardinality?: string
274
- onMissing?: string
275
- onMany?: string
323
+ /** Absent means `0..1` (BINDING_OPTION_DEFAULTS) — never stored at its default. */
324
+ cardinality?: BindingCardinality
325
+ /** Absent means `omit`. */
326
+ onMissing?: BindingOnMissing
327
+ /** Absent means `error`. */
328
+ onMany?: BindingOnMany
276
329
  [key: string]: unknown
277
330
  }
278
331
 
332
+ /**
333
+ * Hydrates a stored binding's behaviours to the total set (§2.2a: "the hydrated in-memory binding is
334
+ * a total object"). One place rather than `?? 'omit'` at each use site — a reader that spelled the
335
+ * fallback itself would be a second declaration of the default, free to drift from the reducer's.
336
+ */
337
+ export const resolveBindingOptions = (binding: MappingBinding): ResolvedBindingOptions => ({
338
+ cardinality: binding.cardinality ?? BINDING_OPTION_DEFAULTS.cardinality,
339
+ onMissing: binding.onMissing ?? BINDING_OPTION_DEFAULTS.onMissing,
340
+ onMany: binding.onMany ?? BINDING_OPTION_DEFAULTS.onMany,
341
+ })
342
+
343
+ /** Whether a binding's cardinality means "many values", i.e. it feeds a grid's rows rather than one slot. */
344
+ export const bindingIsMultiValued = (binding: MappingBinding): boolean =>
345
+ resolveBindingOptions(binding).cardinality.endsWith('*')
346
+
279
347
  /** Carries no `nodeId` back-pointer: the node already lists it (§2.2a). */
280
348
  export type MappingFilter = {
281
349
  fieldId: string
@@ -340,6 +408,27 @@ export type QnrQuestionBundle = {
340
408
  alternativesById?: Record<AltId, QnrAlternative>
341
409
  alternativeOrderByQuestionId?: Record<QuestionId, AltId[]>
342
410
  tabsById?: Record<TabId, QnrTab>
411
+ /**
412
+ * The carried tabs in authored order — the one order this bundle could not state.
413
+ *
414
+ * Every other collection here already pairs its record with an order (`gridRowOrderByQuestionId`,
415
+ * `alternativeOrderByQuestionId`) or derives one (a column's place is its position in the owning
416
+ * grid's `grid.columnIds`; actions are a set by design, architecture §2.1). Tabs had neither, and
417
+ * **key order is not an order contract**: `qnr_question_templates.bundle` is `jsonb`, which
418
+ * normalizes object keys by length then bytes, so a two-tab bundle authored `t-zulu, t-alfa` reads
419
+ * back `t-alfa, t-zulu`. Measured on PostgreSQL 17, and the same payload as `json` keeps the
420
+ * authored order — so this is the column type destroying it, not the client sending it wrong.
421
+ *
422
+ * Consequence for the pick: a pick synthesizes one `tab.create` per tab and `tab.create` appends,
423
+ * so emission order *is* the resulting `tabOrder` in the live template. Without this member the
424
+ * only choices were to sort by id or to trust key order — both invent an order the author never
425
+ * chose, and the tab bar is something they look at.
426
+ *
427
+ * Optional because a bundle with fewer than two tabs has no order to state; the library's
428
+ * validator is where "two or more tabs must declare it" belongs, since that is the writer's rule
429
+ * rather than a property of the shape.
430
+ */
431
+ tabOrder?: TabId[]
343
432
  actionsById?: Record<ActionId, QnrAction>
344
433
  }
345
434