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
@@ -133,6 +133,22 @@ export type QuestionGridPresentation = {
133
133
  rowEditor?: QuestionGridRowEditor
134
134
  /** OQ-V2-25: authored defaults; per-user widths are preference state outside both documents. */
135
135
  defaultColumnWidthsByQuestionId?: Record<QuestionId, number>
136
+ /**
137
+ * Which of this grid's columns offer a filter control, in authored order (M-054).
138
+ *
139
+ * Legacy stores `filter_ui.questions[]` as an array of objects; DOC-LAW-1 forbids that, and the
140
+ * per-entry flags it carried (`is_multi`, the date-interval bounds) are the *control's* configuration
141
+ * rather than the grid's, so they belong on the column question. What the grid owns is the
142
+ * selection and its order — a primitive id array, maintained one member at a time by
143
+ * `gridColumn.setFilter` so two authors adding different filters concurrently both survive.
144
+ */
145
+ filterQuestionIds?: QuestionId[]
146
+ /**
147
+ * The grid-owned actions, in authored order (M-055) — **ids only, never bodies**. The action
148
+ * records live in `actionsById`; duplicating them here would give one action two homes that could
149
+ * disagree, which is the reason the field map routes grid actions into the root collection.
150
+ */
151
+ actionIds?: ActionId[]
136
152
  [key: string]: unknown
137
153
  }
138
154
 
@@ -165,9 +181,92 @@ export type QnrGridRow = {
165
181
  [key: string]: unknown
166
182
  }
167
183
 
168
- export type QnrTab = { label?: string; [key: string]: unknown }
184
+ /** A tab's positional grid: one placement per question it displays, keyed rather than positional. */
185
+ export type QnrTabLayout = {
186
+ placementsByQuestionId?: Record<QuestionId, LayoutPlacement>
187
+ [key: string]: unknown
188
+ }
189
+
190
+ /**
191
+ * A header tab (M-051).
192
+ *
193
+ * `layout` is the typed successor to legacy `tab_editor.rows[].columns{}`, which is an array of rows
194
+ * each holding an object of columns. DOC-LAW-1 rules that out for the reason it exists: two authors
195
+ * moving different questions produce two whole-array patches, and the second silently discards the
196
+ * first. Keyed placements make those two edits touch two keys instead.
197
+ *
198
+ * The index signature stays: a tab's authored bag is still open (`dependent_question_ids` and friends
199
+ * arrive from the importer), and narrowing it would make an already-stored tab unreadable.
200
+ */
201
+ export type QnrTab = { label?: string; layout?: QnrTabLayout; [key: string]: unknown }
202
+
203
+ /**
204
+ * The **compatibility** action record: `kind` is an arbitrary optional string and the bag is open.
205
+ *
206
+ * Deliberately left broad. It is released, imported documents carry unknown kinds and accidental UI
207
+ * buffers, and narrowing it would make those unreadable — ADR-0008 DEC-006. The typed vocabulary below
208
+ * is additive and closed; a record is "known" only when its `kind` is one of `KNOWN_ACTION_KINDS`, and
209
+ * everything else keeps replaying exactly as before.
210
+ */
169
211
  export type QnrAction = { kind?: string; [key: string]: unknown }
170
212
 
213
+ /** The two action kinds the typed path authors (M-052/M-055). Anything else is legacy-readable only. */
214
+ export const KNOWN_ACTION_KINDS = ['topLevelAction', 'gridAction'] as const
215
+ export type KnownActionKind = (typeof KNOWN_ACTION_KINDS)[number]
216
+
217
+ /** A grid action's effect. Absent is a valid incomplete draft; publication refuses it. */
218
+ export const ACTION_TYPES = ['COPY', 'UPDATE'] as const
219
+ export type ActionType = (typeof ACTION_TYPES)[number]
220
+
221
+ export const isKnownActionKind = (kind: unknown): kind is KnownActionKind =>
222
+ typeof kind === 'string' && (KNOWN_ACTION_KINDS as readonly string[]).includes(kind)
223
+
224
+ /**
225
+ * What a top-level action does: for one composite/grid question, run an authored sequence of that
226
+ * grid's existing actions (M-052).
227
+ *
228
+ * **Not a recursive action tree.** The legacy shape reads like one (`actions:[{id, question_id,
229
+ * actions[]}]`), but the inner ids are grid actions that already exist in `actionsById`, so the v2
230
+ * shape is a map from grid question id to an ordered id array. There is deliberately no
231
+ * `childActionOrder` and no `questionId` member on an action.
232
+ */
233
+ export type KnownTopLevelAction = {
234
+ kind: 'topLevelAction'
235
+ label?: string
236
+ actionIdsByGridQuestionId?: Record<QuestionId, ActionId[]>
237
+ }
238
+
239
+ /**
240
+ * One metadata entry of a grid action: which values it copies or updates between.
241
+ *
242
+ * `{ all: true }` is the canonical all-to-all marker and exists because DOC-LAW-2 would otherwise
243
+ * erase the fact: legacy encodes all-to-all as `from: null, to: null`, and a document may carry
244
+ * neither null nor an empty object, so "selected, unbounded" and "not selected at all" would become
245
+ * the same absence. It is exclusive with `from`/`to`, and a bare `{}` is invalid for the same reason.
246
+ */
247
+ /**
248
+ * Every arm excludes the others' members with `?: never`, so the union is closed at COMPILE time and
249
+ * not only in the reducer. Without the exclusions `{all: true, from: 'a'}` structurally satisfies the
250
+ * from-only arm — TypeScript admits extra properties on a non-fresh object — and the exclusivity rule
251
+ * would exist in three places (reducer, schema) but not in the type consumers actually program against.
252
+ */
253
+ export type ActionMetadata =
254
+ | { from: DocScalar; to: DocScalar; all?: never }
255
+ | { from: DocScalar; to?: never; all?: never }
256
+ | { from?: never; to: DocScalar; all?: never }
257
+ | { all: true; from?: never; to?: never }
258
+
259
+ /** A grid-owned action (M-055): its effect, and the per-column values it applies to. */
260
+ export type KnownGridAction = {
261
+ kind: 'gridAction'
262
+ label?: string
263
+ actionType?: ActionType
264
+ metadataByQuestionId?: Record<QuestionId, ActionMetadata>
265
+ }
266
+
267
+ /** The closed typed vocabulary. A stored `QnrAction` is one of these only when its `kind` says so. */
268
+ export type KnownAction = KnownTopLevelAction | KnownGridAction
269
+
171
270
  /**
172
271
  * A typed conditional (OQ-V2-17/architecture §2.2(4)): question visibility/highlight
173
272
  * depends on another question's answer. Legacy `dependent_question`+`dependent_questions`
@@ -345,10 +444,47 @@ export const bindingIsMultiValued = (binding: MappingBinding): boolean =>
345
444
  resolveBindingOptions(binding).cardinality.endsWith('*')
346
445
 
347
446
  /** Carries no `nodeId` back-pointer: the node already lists it (§2.2a). */
447
+ /** The operators the typed path authors and the compiler branches on (engine contract ENG-MD-005). */
448
+ export const MAPPING_FILTER_OPERATORS = ['eq', 'in', 'range', 'isNull'] as const
449
+ export type MappingFilterOperator = (typeof MAPPING_FILTER_OPERATORS)[number]
450
+
451
+ export const isKnownMappingFilterOperator = (operator: unknown): operator is MappingFilterOperator =>
452
+ typeof operator === 'string' && (MAPPING_FILTER_OPERATORS as readonly string[]).includes(operator)
453
+
454
+ /**
455
+ * The payload each known operator carries — one member set per operator, nothing shared.
456
+ *
457
+ * `range` takes at least one bound because a range with neither is not a filter; `in` takes a
458
+ * non-empty list for the same reason. Both are enforced by the schema rather than left to the reducer,
459
+ * so an unusable filter cannot reach a compiled artifact.
460
+ */
461
+ export type MappingFilterPayload =
462
+ | { operator: 'eq'; value: DocScalar }
463
+ | { operator: 'in'; values: DocScalar[] }
464
+ | { operator: 'range'; from: DocScalar; to?: DocScalar }
465
+ | { operator: 'range'; to: DocScalar }
466
+ | { operator: 'isNull'; value: boolean }
467
+
468
+ /**
469
+ * A node filter. Carries no `nodeId` back-pointer: the node already lists it (§2.2a).
470
+ *
471
+ * **`operator` stays a loose `string`, and that is deliberate.** It is released, and stored documents
472
+ * carry operators outside the closed set (`contains` among them) that must remain readable and
473
+ * replayable — ADR-0008 DEC-006. The closed vocabulary arrives as `MAPPING_FILTER_OPERATORS` plus the
474
+ * additive `mappingFilter.setTyped`, which is the only path that can write a payload; publication is
475
+ * where an unknown operator becomes a refusal.
476
+ *
477
+ * `values`/`from`/`to` are additive members for the `in` and `range` payloads. A filter carries only
478
+ * the members of its own operator: `setTyped` rewrites the record rather than patching it, so
479
+ * switching operator cannot leave a stale `value` behind.
480
+ */
348
481
  export type MappingFilter = {
349
482
  fieldId: string
350
483
  operator: string
351
484
  value?: DocScalar
485
+ values?: DocScalar[]
486
+ from?: DocScalar
487
+ to?: DocScalar
352
488
  }
353
489
 
354
490
  /**
@@ -408,7 +544,58 @@ export type QnrQuestionBundle = {
408
544
  alternativesById?: Record<AltId, QnrAlternative>
409
545
  alternativeOrderByQuestionId?: Record<QuestionId, AltId[]>
410
546
  tabsById?: Record<TabId, QnrTab>
547
+ /**
548
+ * The carried tabs in authored order — the one order this bundle could not state.
549
+ *
550
+ * Every other collection here already pairs its record with an order (`gridRowOrderByQuestionId`,
551
+ * `alternativeOrderByQuestionId`) or derives one (a column's place is its position in the owning
552
+ * grid's `grid.columnIds`; actions are a set by design, architecture §2.1). Tabs had neither, and
553
+ * **key order is not an order contract**: `qnr_question_templates.bundle` is `jsonb`, which
554
+ * normalizes object keys by length then bytes, so a two-tab bundle authored `t-zulu, t-alfa` reads
555
+ * back `t-alfa, t-zulu`. Measured on PostgreSQL 17, and the same payload as `json` keeps the
556
+ * authored order — so this is the column type destroying it, not the client sending it wrong.
557
+ *
558
+ * Consequence for the pick: a pick synthesizes one `tab.create` per tab and `tab.create` appends,
559
+ * so emission order *is* the resulting `tabOrder` in the live template. Without this member the
560
+ * only choices were to sort by id or to trust key order — both invent an order the author never
561
+ * chose, and the tab bar is something they look at.
562
+ *
563
+ * Optional because a bundle with fewer than two tabs has no order to state; the library's
564
+ * validator is where "two or more tabs must declare it" belongs, since that is the writer's rule
565
+ * rather than a property of the shape.
566
+ */
567
+ tabOrder?: TabId[]
411
568
  actionsById?: Record<ActionId, QnrAction>
569
+ /**
570
+ * The mapping-graph fragment its questions are bound through — the same four normalized
571
+ * collections the document root carries, scoped to this root question's subtree.
572
+ *
573
+ * **Why a bundle carries mapping at all.** Mapping is one root-level graph, not per-question state
574
+ * (OQ-V2-28 ✅, §2.2a), so a bundle that copied only questions would lose every binding the moment
575
+ * it was picked: the pick splices this fragment into the family document's root graph precisely so
576
+ * a picked question does not arrive unmapped. The pre-DDL guardrails state it as part of what the
577
+ * column stores — "plus its mapping-graph fragment (the nodes, bindings, and filters its questions
578
+ * are bound through)".
579
+ *
580
+ * The same records and the same laws as the document, deliberately: `dataMappingsById` keyed by
581
+ * mapping id with a primitive `bindingOrder`, nodes keyed by node id with a primitive `filterOrder`,
582
+ * every default omitted. **No new document shape** — a pick replays ordinary authoring ops under
583
+ * fresh ids (`mappingNode.create`, then filters via `mappingFilter.set` or the typed
584
+ * `mappingFilter.setTyped`, then `mappingBinding.create`, and `dataMapping.create` last so the
585
+ * reducer adopts its bindings in the authored order), so anything expressible in a document is
586
+ * expressible in a bundle and nothing else is.
587
+ *
588
+ * All four are optional and independently so: a bundle for an unmapped question carries none of
589
+ * them, and a fragment mid-authoring may carry nodes with no bindings yet. Completeness is a
590
+ * publication question (G-25), never a condition of storing or picking one.
591
+ *
592
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-13-23-25-architecture-qnr-v2-db-design-pre-ddl-guardrails.md:187
593
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-13-23-25-architecture-qnr-v2-db-design-pre-ddl-guardrails.md:587 — OQ-V2-28
594
+ */
595
+ dataMappingsById?: Record<MappingId, QnrDataMapping>
596
+ mappingNodesById?: Record<NodeId, MappingNode>
597
+ mappingBindingsById?: Record<BindingId, MappingBinding>
598
+ mappingFiltersById?: Record<FilterId, MappingFilter>
412
599
  }
413
600
 
414
601
  /**
@@ -211,7 +211,7 @@ const nextOp = (random: () => number, pools: IdPools): TemplateOp => {
211
211
 
212
212
  /** Operations added by ASMA-7676, kept in a dedicated mix so every seeded run exercises them. */
213
213
  const nextAddedContractOp = (random: () => number, pools: IdPools): TemplateOp => {
214
- const choice = Math.floor(random() * 9)
214
+ const choice = Math.floor(random() * 16)
215
215
  const columnQuestionId = pickOrFallback(random, pools.columns, 'c-ghost')
216
216
  const ownerQuestionId = pools.columnOwnerById[columnQuestionId] ?? pickOrFallback(random, pools.grids, 'g-ghost')
217
217
  const questionId = idOrNew(random, pools.questions, NEW_QUESTION_ID)
@@ -264,6 +264,76 @@ const nextAddedContractOp = (random: () => number, pools: IdPools): TemplateOp =
264
264
  return { type: 'qnrRule.delete', ruleId: pickOrFallback(random, pools.qnrRules, 'qr-ghost') }
265
265
  case 7:
266
266
  return { type: 'question.move', questionId: columnQuestionId, toIndex: Math.floor(random() * 5) }
267
+ // ── ASMA-7683 additive ops. Generated alongside the released vocabulary so the property run
268
+ // exercises them against the same invariants (DOC-law, ownership, hash stability) rather than
269
+ // only in their own hand-written cases.
270
+ case 8:
271
+ return {
272
+ type: 'gridColumn.setFilter',
273
+ questionId: ownerQuestionId,
274
+ columnQuestionId,
275
+ include: maybe(random, 0.7),
276
+ ...(maybe(random, 0.5) ? { atIndex: Math.floor(random() * 3) } : {}),
277
+ }
278
+ case 9:
279
+ return {
280
+ type: 'gridColumn.setAction',
281
+ questionId: pickOrFallback(random, pools.grids, 'g-ghost'),
282
+ actionId: pickOrFallback(random, pools.actions, 'x-ghost'),
283
+ include: maybe(random, 0.7),
284
+ ...(maybe(random, 0.5) ? { atIndex: Math.floor(random() * 3) } : {}),
285
+ }
286
+ case 10:
287
+ return {
288
+ type: 'tab.setLayout',
289
+ tabId: pickOrFallback(random, pools.tabs, 't-ghost'),
290
+ questionId: pickOrFallback(random, pools.questions, 'q-ghost'),
291
+ placement: maybe(random, 0.25)
292
+ ? null
293
+ : { row: Math.floor(random() * 3), cell: Math.floor(random() * 4) },
294
+ }
295
+ case 11:
296
+ return {
297
+ type: 'mappingFilter.setTyped',
298
+ filterId: NEW_FILTER_ID(pools.filters.length),
299
+ nodeId: pickOrFallback(random, pools.nodes, 'n-ghost'),
300
+ fieldId: `fld-${Math.floor(random() * 4)}`,
301
+ operator: 'eq',
302
+ value: `v-${Math.floor(random() * 3)}`,
303
+ }
304
+ case 12:
305
+ return {
306
+ type: 'mappingFilter.setTyped',
307
+ filterId: pickOrFallback(random, pools.filters, NEW_FILTER_ID(pools.filters.length)),
308
+ nodeId: pickOrFallback(random, pools.nodes, 'n-ghost'),
309
+ fieldId: `fld-${Math.floor(random() * 4)}`,
310
+ operator: 'in',
311
+ values: [`v-${Math.floor(random() * 3)}`, Math.floor(random() * 9)],
312
+ }
313
+ case 13:
314
+ return {
315
+ type: 'mappingFilter.setTyped',
316
+ filterId: pickOrFallback(random, pools.filters, NEW_FILTER_ID(pools.filters.length)),
317
+ nodeId: pickOrFallback(random, pools.nodes, 'n-ghost'),
318
+ fieldId: `fld-${Math.floor(random() * 4)}`,
319
+ operator: 'range',
320
+ from: Math.floor(random() * 5),
321
+ ...(maybe(random, 0.5) ? { to: 5 + Math.floor(random() * 5) } : {}),
322
+ }
323
+ case 14:
324
+ return {
325
+ type: 'action.createTyped',
326
+ actionId: NEW_ACTION_ID(pools.actions.length),
327
+ kind: maybe(random, 0.5) ? 'topLevelAction' : 'gridAction',
328
+ ...(maybe(random, 0.6) ? { label: `Handling ${Math.floor(random() * 5)}` } : {}),
329
+ }
330
+ case 15:
331
+ return {
332
+ type: 'action.setMetadata',
333
+ actionId: pickOrFallback(random, pools.actions, 'x-ghost'),
334
+ questionId: columnQuestionId,
335
+ metadata: maybe(random, 0.3) ? null : maybe(random, 0.5) ? { all: true } : { from: 'a', to: 'b' },
336
+ }
267
337
  default:
268
338
  return {
269
339
  type: 'gridColumn.setLayout',
@@ -277,6 +347,12 @@ const nextAddedContractOp = (random: () => number, pools: IdPools): TemplateOp =
277
347
  const updatePools = (op: TemplateOp, ok: boolean, pools: IdPools): void => {
278
348
  if (!ok) return
279
349
  switch (op.type) {
350
+ case 'mappingFilter.setTyped':
351
+ if (!pools.filters.includes(op.filterId)) pools.filters.push(op.filterId)
352
+ return
353
+ case 'action.createTyped':
354
+ pools.actions.push(op.actionId)
355
+ return
280
356
  case 'question.create':
281
357
  pools.questions.push(op.questionId)
282
358
  if (op.questionType === 'QuestionGrid') pools.grids.push(op.questionId)
@@ -0,0 +1,57 @@
1
+ import type { TemplateOp } from './operations.js'
2
+ import type { ActionMetadata } from './templateDocument.js'
3
+
4
+ /**
5
+ * Compile-time assertions that the closed unions stay closed.
6
+ *
7
+ * **Why these live in `src` and not in a test.** `tsconfig.json` excludes every `.test.ts` file from
8
+ * `ts:check`, and the runtime (`node --import tsx --test`) strips types without checking them — so a
9
+ * `@ts-expect-error` inside a test file is never evaluated by anything. A probe that cannot fail is
10
+ * worse than no probe: it reads like a guarantee. These assertions are in a checked module instead, so
11
+ * reopening either union turns `pnpm ts:check` red.
12
+ *
13
+ * Type-only: this module emits no runtime code.
14
+ */
15
+
16
+ /** Fails to compile unless `T` is exactly `true`. */
17
+ type Assert<T extends true> = T
18
+
19
+ /** `true` when `Candidate` is NOT assignable to `Target` — the shape is refused by the union. */
20
+ type Refuses<Candidate, Target> = [Candidate] extends [Target] ? false : true
21
+
22
+ // ─── action.createTyped is discriminated on `kind` ───
23
+ // `actionType` is a gridAction concept. A single arm with an optional member type-checked the
24
+ // combination below and left the reducer as the only thing that noticed.
25
+ export type ActionCreateTypedRefusesTopLevelActionType = Assert<
26
+ Refuses<
27
+ { type: 'action.createTyped'; actionId: string; kind: 'topLevelAction'; label?: string; actionType: 'COPY' },
28
+ TemplateOp
29
+ >
30
+ >
31
+
32
+ /** The same member on the gridAction arm must still be accepted, or the assertion above proves nothing. */
33
+ export type ActionCreateTypedAcceptsGridActionType = Assert<
34
+ Refuses<{ type: 'action.createTyped'; actionId: string; kind: 'gridAction'; actionType: 'COPY' }, TemplateOp> extends true
35
+ ? false
36
+ : true
37
+ >
38
+
39
+ // ─── ActionMetadata arms are mutually exclusive ───
40
+ // `all: true` is the all-to-all marker; carrying a bound beside it is two answers to one question, and
41
+ // a bare `{}` is indistinguishable from absent once DOC-LAW-2 strips empties.
42
+ export type ActionMetadataRefusesAllWithFrom = Assert<Refuses<{ all: true; from: string }, ActionMetadata>>
43
+ export type ActionMetadataRefusesAllWithTo = Assert<Refuses<{ all: true; to: string }, ActionMetadata>>
44
+ export type ActionMetadataRefusesEmpty = Assert<Refuses<Record<string, never>, ActionMetadata>>
45
+
46
+ /** The four legal shapes stay legal. */
47
+ export type ActionMetadataAcceptsLegalShapes = Assert<
48
+ Refuses<{ all: true }, ActionMetadata> extends false
49
+ ? Refuses<{ from: string }, ActionMetadata> extends false
50
+ ? Refuses<{ to: string }, ActionMetadata> extends false
51
+ ? Refuses<{ from: string; to: string }, ActionMetadata> extends false
52
+ ? true
53
+ : false
54
+ : false
55
+ : false
56
+ : false
57
+ >