asma-core-helpers 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/lib/collaboration/answerDocument.d.ts +50 -0
  2. package/lib/collaboration/answerDocument.d.ts.map +1 -0
  3. package/lib/collaboration/answerDocument.js +10 -0
  4. package/lib/collaboration/answerDocument.js.map +1 -0
  5. package/lib/collaboration/answerOperations.d.ts +40 -0
  6. package/lib/collaboration/answerOperations.d.ts.map +1 -0
  7. package/lib/collaboration/answerOperations.js +9 -0
  8. package/lib/collaboration/answerOperations.js.map +1 -0
  9. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  10. package/lib/collaboration/applyOperation.js +290 -4
  11. package/lib/collaboration/applyOperation.js.map +1 -1
  12. package/lib/collaboration/canonicalize.d.ts +61 -0
  13. package/lib/collaboration/canonicalize.d.ts.map +1 -0
  14. package/lib/collaboration/canonicalize.js +184 -0
  15. package/lib/collaboration/canonicalize.js.map +1 -0
  16. package/lib/collaboration/docLaws.d.ts +58 -0
  17. package/lib/collaboration/docLaws.d.ts.map +1 -0
  18. package/lib/collaboration/docLaws.js +71 -0
  19. package/lib/collaboration/docLaws.js.map +1 -0
  20. package/lib/collaboration/operations.d.ts +111 -10
  21. package/lib/collaboration/operations.d.ts.map +1 -1
  22. package/lib/collaboration/operations.js +42 -19
  23. package/lib/collaboration/operations.js.map +1 -1
  24. package/lib/collaboration/templateDocument.d.ts +128 -4
  25. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  26. package/lib/collaboration/templateDocument.js +3 -3
  27. package/lib/collaboration/templateDocument.js.map +1 -1
  28. package/package.json +2 -1
  29. package/src/collaboration/answerDocument.ts +57 -0
  30. package/src/collaboration/answerOperations.ts +34 -0
  31. package/src/collaboration/applyOperation.test.ts +152 -0
  32. package/src/collaboration/applyOperation.ts +316 -4
  33. package/src/collaboration/canonicalize.ts +209 -0
  34. package/src/collaboration/docLaws.ts +123 -0
  35. package/src/collaboration/operations.ts +114 -23
  36. package/src/collaboration/templateDocument.ts +137 -5
@@ -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
@@ -51,11 +51,38 @@ const targetKey = (target: BindingTarget): string =>
51
51
  ? `question:${target.questionId}`
52
52
  : `gridColumn:${target.gridQuestionId}:${target.columnQuestionId}`
53
53
 
54
- /** Sets a key, or removes it when the op carried an explicit unset. */
54
+ /**
55
+ * Sets a key, or removes it when the op carried an explicit unset.
56
+ *
57
+ * `field` may be a dotted path (`scale.from`). The per-type configuration in the document is nested
58
+ * — `question.scale.{from, to, …}`, `question.numberFormat.{…}` — while an op value is a scalar, so
59
+ * without a path those groups are unauthorable. Intermediate objects are created on write and
60
+ * **removed again when their last key is unset**, because DOC-LAW-2 forbids storing an empty
61
+ * collection: leaving `{ scale: {} }` behind would change `document_hash` for a document that
62
+ * carries no scale at all.
63
+ */
55
64
  const writeField = <T extends Record<string, unknown>>(record: T, field: string, value: unknown): T => {
65
+ const [head, ...rest] = field.split('.')
66
+ if (head === undefined || head === '') return record
67
+
56
68
  const next = { ...record } as Record<string, unknown>
57
- if (value === null || value === undefined) delete next[field]
58
- else next[field] = value
69
+
70
+ if (rest.length === 0) {
71
+ if (value === null || value === undefined) delete next[head]
72
+ else next[head] = value
73
+ return next as T
74
+ }
75
+
76
+ const child = next[head]
77
+ const nested = writeField(
78
+ (typeof child === 'object' && child !== null && !Array.isArray(child) ? child : {}) as Record<string, unknown>,
79
+ rest.join('.'),
80
+ value,
81
+ )
82
+
83
+ if (Object.keys(nested).length === 0) delete next[head]
84
+ else next[head] = nested
85
+
59
86
  return next as T
60
87
  }
61
88
 
@@ -110,6 +137,10 @@ const OPTIONAL_COLLECTIONS = [
110
137
  'tabsById',
111
138
  'tabOrder',
112
139
  'actionsById',
140
+ 'visibilityRulesById',
141
+ 'visibilityRuleOrderByQuestionId',
142
+ 'highlightRulesById',
143
+ 'highlightRuleOrderByQuestionId',
113
144
  'dataMappingsById',
114
145
  'mappingNodesById',
115
146
  'mappingBindingsById',
@@ -160,6 +191,17 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
160
191
  return { ...doc, meta }
161
192
  }
162
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
+
163
205
  case 'question.create': {
164
206
  if (doc.questionsById?.[op.questionId]) {
165
207
  throw new OperationConflictError(`Question "${op.questionId}" already exists`)
@@ -206,12 +248,88 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
206
248
  doc.alternativeOrderByQuestionId && omitKey(doc.alternativeOrderByQuestionId, op.questionId),
207
249
  gridRowOrderByQuestionId:
208
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),
209
256
  })
210
257
  // A binding pointing at a deleted question is an unresolvable reference the
211
258
  // compiler would reject at publication; drop it with its target.
212
259
  return dropBindingsForQuestion(withoutQuestion, op.questionId)
213
260
  }
214
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
+
215
333
  case 'alternative.create': {
216
334
  if (!doc.questionsById?.[op.questionId]) {
217
335
  throw new OperationConflictError(`Unknown question "${op.questionId}"`)
@@ -230,6 +348,44 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
230
348
  }
231
349
  }
232
350
 
351
+ case 'alternative.updateField': {
352
+ const alternative = doc.alternativesById?.[op.alternativeId]
353
+ if (!alternative) {
354
+ throw new OperationConflictError(`Unknown alternative "${op.alternativeId}"`)
355
+ }
356
+ // The question is checked too: an alternative id that exists but hangs off a different
357
+ // question means the two clients disagree about the structure, not just the value, and
358
+ // writing the field anyway would hide that behind a successful edit.
359
+ if (!doc.alternativeOrderByQuestionId?.[op.questionId]?.includes(op.alternativeId)) {
360
+ throw new OperationConflictError(
361
+ `Alternative "${op.alternativeId}" does not belong to question "${op.questionId}"`,
362
+ )
363
+ }
364
+ return {
365
+ ...doc,
366
+ alternativesById: {
367
+ ...doc.alternativesById,
368
+ [op.alternativeId]: writeField(alternative, op.field, op.value),
369
+ },
370
+ }
371
+ }
372
+
373
+ case 'alternative.move': {
374
+ const order = doc.alternativeOrderByQuestionId?.[op.questionId]
375
+ if (!order?.includes(op.alternativeId)) {
376
+ throw new OperationConflictError(
377
+ `Alternative "${op.alternativeId}" does not belong to question "${op.questionId}"`,
378
+ )
379
+ }
380
+ return {
381
+ ...doc,
382
+ alternativeOrderByQuestionId: {
383
+ ...doc.alternativeOrderByQuestionId,
384
+ [op.questionId]: moveInOrder(order, op.alternativeId, op.toIndex),
385
+ },
386
+ }
387
+ }
388
+
233
389
  case 'alternative.delete': {
234
390
  const order = doc.alternativeOrderByQuestionId?.[op.questionId] ?? []
235
391
  const remaining = order.filter((id) => id !== op.alternativeId)
@@ -242,6 +398,87 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
242
398
  })
243
399
  }
244
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
+
245
482
  case 'mappingNode.create': {
246
483
  if (doc.mappingNodesById?.[op.nodeId]) {
247
484
  throw new OperationConflictError(`Mapping node "${op.nodeId}" already exists`)
@@ -254,6 +491,25 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
254
491
  return { ...doc, mappingNodesById: { ...(doc.mappingNodesById ?? {}), [op.nodeId]: node } }
255
492
  }
256
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
+
257
513
  case 'mappingNode.delete': {
258
514
  const filterIds = doc.mappingNodesById?.[op.nodeId]?.filterOrder ?? []
259
515
  let filtersById = doc.mappingFiltersById
@@ -349,6 +605,62 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
349
605
  })
350
606
  }
351
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
+
352
664
  default: {
353
665
  // Exhaustiveness: a new op member makes this a compile error, not a silent no-op.
354
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
+ }