asma-core-helpers 0.19.0 → 0.20.1

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 (44) 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/lib/helpers/EnvironmentsUrls.d.ts +0 -3
  29. package/lib/helpers/EnvironmentsUrls.d.ts.map +1 -1
  30. package/lib/helpers/EnvironmentsUrls.js +0 -3
  31. package/lib/helpers/EnvironmentsUrls.js.map +1 -1
  32. package/lib/helpers/generateEnvConfigsBindings.d.ts +1 -4
  33. package/lib/helpers/generateEnvConfigsBindings.d.ts.map +1 -1
  34. package/lib/helpers/generateEnvConfigsBindings.js.map +1 -1
  35. package/package.json +2 -1
  36. package/src/collaboration/answerDocument.ts +57 -0
  37. package/src/collaboration/answerOperations.ts +34 -0
  38. package/src/collaboration/applyOperation.ts +248 -1
  39. package/src/collaboration/canonicalize.ts +209 -0
  40. package/src/collaboration/docLaws.ts +123 -0
  41. package/src/collaboration/operations.ts +87 -12
  42. package/src/collaboration/templateDocument.ts +137 -5
  43. package/src/helpers/EnvironmentsUrls.ts +0 -3
  44. package/src/helpers/generateEnvConfigsBindings.ts +1 -4
@@ -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
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Canonical form for hashed documents.
3
+ *
4
+ * Two separable steps, because two consumers need different amounts of it:
5
+ *
6
+ * 1. `reduceToMinimalForm` — DOC-LAW-2: absent is the only encoding of "not set".
7
+ * 2. `canonicalJson` — RFC 8785 (JCS): sorted members, no whitespace, ECMAScript
8
+ * numbers, plus NFC normalisation, which JCS deliberately leaves out.
9
+ *
10
+ * The template/answer documents reduce their whole body; the data engine's
11
+ * `structureHash` reduces only four members of the structure document and then runs
12
+ * the identical serialiser — same bytes, different selection.
13
+ *
14
+ * This is the single shared implementation: the frontend, bunjs and the data engine
15
+ * all produce the same bytes from here. `hashCanonical` is the one function that needs
16
+ * a platform primitive (SHA-256), so it takes an injectable hasher with a WebCrypto
17
+ * default that works in browsers, Node 18+ and Bun alike.
18
+ *
19
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:195 (DOC-LAW-2)
20
+ * @see asma-modules/_docs/qnr-data-engine/specs/2026-07-30-00-11-spec-qnr-data-engine-contract.md:652 (§8.2)
21
+ */
22
+
23
+ export type JsonValue = string | number | boolean | null | JsonValue[] | { [k: string]: JsonValue }
24
+
25
+ /** Returns true when `value` at `path` equals the schema default and must be omitted. */
26
+ export type IsDefault = (path: string, value: unknown) => boolean
27
+
28
+ export type ReduceOptions = {
29
+ isDefault?: IsDefault
30
+ }
31
+
32
+ /**
33
+ * A prototype check, not a `typeof` check. `typeof new Date() === 'object'` and a Date
34
+ * has no own enumerable keys, so a `typeof` test would serialise it as `{}` — silently
35
+ * erasing a timestamp from a hashed document.
36
+ */
37
+ const isPlainObject = (value: unknown): value is Record<string, unknown> => {
38
+ if (typeof value !== 'object' || value === null) return false
39
+ const proto = Object.getPrototypeOf(value)
40
+ return proto === Object.prototype || proto === null
41
+ }
42
+
43
+ const joinPath = (parent: string, key: string) => (parent === '' ? key : `${parent}.${key}`)
44
+
45
+ /**
46
+ * DOC-LAW-2 reduction. Drops explicit `null`, `[]`, `{}` and any key carrying its own
47
+ * default — recursively, so a container that becomes empty is itself dropped and the
48
+ * result is a fixed point (reducing twice is a no-op).
49
+ *
50
+ * The root container is always returned, even if it reduces to empty: a caller asking
51
+ * to canonicalize a document wants a document back, not `undefined`.
52
+ */
53
+ export const reduceToMinimalForm = <T>(value: T, options: ReduceOptions = {}): T => {
54
+ const reduced = reduceNode(value, '', options)
55
+ if (reduced !== undefined) return reduced as T
56
+ return (Array.isArray(value) ? [] : {}) as T
57
+ }
58
+
59
+ const reduceNode = (value: unknown, path: string, options: ReduceOptions): unknown => {
60
+ if (value === null) return undefined
61
+
62
+ if (Array.isArray(value)) {
63
+ // ponytail: array members are reduced but never removed. Dropping one would
64
+ // silently change length and order, and order is the only ordering carrier
65
+ // (DOC-LAW-1) — a null member is a schema violation for the lint to catch,
66
+ // not something to paper over here.
67
+ let anyMemberSurvived = false
68
+
69
+ const members = value.map((member, index) => {
70
+ const reducedMember = reduceNode(member, joinPath(path, String(index)), options)
71
+ if (reducedMember !== undefined) {
72
+ anyMemberSurvived = true
73
+ return reducedMember
74
+ }
75
+
76
+ // A container member that reduces away becomes the EMPTY container, not the original.
77
+ // Restoring the original would put back the very nulls this reduction exists to remove, and
78
+ // the storage guard `document = jsonb_strip_nulls(document)` then rejects the row — which is
79
+ // exactly how this was found, on the first real import against dev. A primitive `null` member
80
+ // is kept: `jsonb_strip_nulls` removes null object *fields* only, so an array null is legal,
81
+ // and dropping it would change the length this branch is protecting.
82
+ if (Array.isArray(member)) return []
83
+ if (isPlainObject(member)) return {}
84
+ return member
85
+ })
86
+
87
+ if (members.length === 0) return undefined
88
+
89
+ // An array in which NOTHING survived reduction carries no information, so the key goes — same rule
90
+ // as an empty object, reached one level later. Length is not worth protecting here because there is
91
+ // no content whose position it could describe.
92
+ //
93
+ // Measured, and the reason this branch exists: legacy `dependent_questions` members hold exactly
94
+ // `{dependent_question_id, dependent_composite_question_id}` and **all 3,702 members sampled on dev
95
+ // have both fields null**. Without this rule the port stored 620 arrays of `{}` per version —
96
+ // simultaneously a DOC-LAW-1 violation (array of objects) and a DOC-LAW-2 one (empty object), and
97
+ // invisible to the storage CHECK because `jsonb_strip_nulls` does not remove empty objects.
98
+ //
99
+ // A MIXED array — some members surviving, some not — is deliberately still kept with its empties, so
100
+ // the surviving members keep their positions. That case is left for `findDocLawViolations` to report
101
+ // rather than papered over here, because papering over it would move a real content position.
102
+ if (!anyMemberSurvived) return undefined
103
+
104
+ return members
105
+ }
106
+
107
+ if (isPlainObject(value)) {
108
+ const result: Record<string, unknown> = {}
109
+ for (const [key, member] of Object.entries(value)) {
110
+ const memberPath = joinPath(path, key)
111
+ if (options.isDefault?.(memberPath, member)) continue
112
+ const reducedMember = reduceNode(member, memberPath, options)
113
+ if (reducedMember === undefined) continue
114
+ result[key] = reducedMember
115
+ }
116
+ return Object.keys(result).length === 0 ? undefined : result
117
+ }
118
+
119
+ return value
120
+ }
121
+
122
+ /**
123
+ * RFC 8785 JSON Canonicalization Scheme over the value, plus NFC.
124
+ *
125
+ * Refuses anything JSON cannot carry rather than emitting a lossy encoding — an
126
+ * `undefined` silently vanishing from a hashed document is exactly the class of bug
127
+ * a canonical form exists to prevent.
128
+ */
129
+ export const canonicalJson = (value: unknown): string => serialize(value, '')
130
+
131
+ const serialize = (value: unknown, path: string): string => {
132
+ if (value === null) return 'null'
133
+
134
+ switch (typeof value) {
135
+ case 'boolean':
136
+ return value ? 'true' : 'false'
137
+ case 'string':
138
+ // JSON.stringify already produces ECMAScript-minimal escaping, which is
139
+ // what JCS mandates.
140
+ return JSON.stringify(value.normalize('NFC'))
141
+ case 'number':
142
+ if (!Number.isFinite(value)) {
143
+ throw new Error(`canonicalJson: ${value} is not finite at "${path || '<root>'}"`)
144
+ }
145
+ // JSON.stringify uses Number::toString, which is JCS's number rule.
146
+ return JSON.stringify(value)
147
+ case 'undefined':
148
+ throw new Error(`canonicalJson: undefined at "${path || '<root>'}"`)
149
+ case 'bigint':
150
+ throw new Error(`canonicalJson: bigint is unsupported at "${path || '<root>'}"`)
151
+ case 'function':
152
+ case 'symbol':
153
+ throw new Error(`canonicalJson: ${typeof value} is unsupported at "${path || '<root>'}"`)
154
+ }
155
+
156
+ if (Array.isArray(value)) {
157
+ return `[${value.map((member, index) => serialize(member, joinPath(path, String(index)))).join(',')}]`
158
+ }
159
+
160
+ if (!isPlainObject(value)) {
161
+ const name = Object.prototype.toString.call(value).slice(8, -1)
162
+ throw new Error(`canonicalJson: ${name} is unsupported at "${path || '<root>'}"`)
163
+ }
164
+
165
+ // Normalise before sorting: normalisation can change the code units that sorting
166
+ // compares, so the other order would not be stable.
167
+ const members = new Map<string, unknown>()
168
+ for (const [key, member] of Object.entries(value)) {
169
+ const normalized = key.normalize('NFC')
170
+ if (members.has(normalized)) {
171
+ throw new Error(`canonicalJson: keys "${key}" and its NFC twin collide at "${path || '<root>'}"`)
172
+ }
173
+ members.set(normalized, member)
174
+ }
175
+
176
+ const body = [...members.keys()]
177
+ .sort() // default comparison is by UTF-16 code unit, which is JCS's rule
178
+ .map((key) => `${JSON.stringify(key)}:${serialize(members.get(key), joinPath(path, key))}`)
179
+ .join(',')
180
+
181
+ return `{${body}}`
182
+ }
183
+
184
+ /** `sha256:<lowercase hex>` over the canonical bytes of the value. */
185
+ export type Sha256Hex = (utf8: string) => string | Promise<string>
186
+
187
+ const bytesToHex = (bytes: Uint8Array): string =>
188
+ [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('')
189
+
190
+ /**
191
+ * WebCrypto SHA-256 — the default hasher. Present in browsers, Node 18+ and Bun as
192
+ * `globalThis.crypto`, so one implementation serves every consumer of this package.
193
+ * A server-side consumer with a sync hot path may inject its own hasher instead.
194
+ */
195
+ export const webCryptoSha256: Sha256Hex = async (utf8) => {
196
+ const bytes = new TextEncoder().encode(utf8)
197
+ const digest = await crypto.subtle.digest('SHA-256', bytes)
198
+ return bytesToHex(new Uint8Array(digest))
199
+ }
200
+
201
+ /**
202
+ * Canonical hash of a document: `sha256:` over RFC 8785 + NFC bytes of its minimal
203
+ * form. `hasher` is injectable so a server can use sync node:crypto while the browser
204
+ * keeps the WebCrypto default — the bytes hashed are identical either way.
205
+ */
206
+ export const hashCanonical = (value: unknown, hasher: Sha256Hex = webCryptoSha256): Promise<string> => {
207
+ const maybeHex = hasher(canonicalJson(value))
208
+ return Promise.resolve(maybeHex).then((hex) => `sha256:${hex}`)
209
+ }
@@ -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))