asma-core-helpers 0.16.0 → 0.17.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.
- package/lib/collaboration/applyOperation.d.ts +34 -0
- package/lib/collaboration/applyOperation.d.ts.map +1 -0
- package/lib/collaboration/applyOperation.js +319 -0
- package/lib/collaboration/applyOperation.js.map +1 -0
- package/lib/collaboration/index.d.ts +24 -0
- package/lib/collaboration/index.d.ts.map +1 -0
- package/lib/collaboration/index.js +24 -0
- package/lib/collaboration/index.js.map +1 -0
- package/lib/collaboration/operations.d.ts +89 -0
- package/lib/collaboration/operations.d.ts.map +1 -0
- package/lib/collaboration/operations.js +22 -0
- package/lib/collaboration/operations.js.map +1 -0
- package/lib/collaboration/templateDocument.d.ts +112 -0
- package/lib/collaboration/templateDocument.d.ts.map +1 -0
- package/lib/collaboration/templateDocument.js +24 -0
- package/lib/collaboration/templateDocument.js.map +1 -0
- package/package.json +5 -1
- package/src/collaboration/applyOperation.test.ts +124 -0
- package/src/collaboration/applyOperation.ts +358 -0
- package/src/collaboration/index.ts +24 -0
- package/src/collaboration/operations.ts +73 -0
- package/src/collaboration/templateDocument.ts +103 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The template authoring document — a normalized entity graph with stable ids and
|
|
3
|
+
* explicit order arrays, in DOC-LAW-1 / DOC-LAW-2 minimal form.
|
|
4
|
+
*
|
|
5
|
+
* Every collection is optional because DOC-LAW-2 forbids storing an empty one: a
|
|
6
|
+
* document with no alternatives has no `alternativesById` key at all. Readers hydrate
|
|
7
|
+
* to a total in-memory model once at the document boundary rather than writing `?? {}`
|
|
8
|
+
* at each use site.
|
|
9
|
+
*
|
|
10
|
+
* @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:152 (document shape)
|
|
11
|
+
* @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:193 (DOC-LAW-1)
|
|
12
|
+
* @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:214 (§2.2a mapping graph)
|
|
13
|
+
*/
|
|
14
|
+
export type QuestionId = string;
|
|
15
|
+
export type RowId = string;
|
|
16
|
+
export type AltId = string;
|
|
17
|
+
export type TabId = string;
|
|
18
|
+
export type ActionId = string;
|
|
19
|
+
export type NodeId = string;
|
|
20
|
+
export type BindingId = string;
|
|
21
|
+
export type FilterId = string;
|
|
22
|
+
export type MappingId = string;
|
|
23
|
+
/** A scalar a document may carry. Deliberately not `any`: DOC-LAW-2 bans `null`. */
|
|
24
|
+
export type DocScalar = string | number | boolean;
|
|
25
|
+
export type QnrQuestion = {
|
|
26
|
+
kind: string;
|
|
27
|
+
label?: string;
|
|
28
|
+
required?: boolean;
|
|
29
|
+
defaultValue?: DocScalar;
|
|
30
|
+
[key: string]: unknown;
|
|
31
|
+
};
|
|
32
|
+
export type QnrAlternative = {
|
|
33
|
+
label?: string;
|
|
34
|
+
value?: DocScalar;
|
|
35
|
+
[key: string]: unknown;
|
|
36
|
+
};
|
|
37
|
+
export type QnrGridRow = {
|
|
38
|
+
label?: string;
|
|
39
|
+
[key: string]: unknown;
|
|
40
|
+
};
|
|
41
|
+
export type QnrTab = {
|
|
42
|
+
label?: string;
|
|
43
|
+
[key: string]: unknown;
|
|
44
|
+
};
|
|
45
|
+
export type QnrAction = {
|
|
46
|
+
kind?: string;
|
|
47
|
+
[key: string]: unknown;
|
|
48
|
+
};
|
|
49
|
+
/** One traversal step. Many questions off one entity share a single node (§2.2a). */
|
|
50
|
+
export type MappingNode = {
|
|
51
|
+
entityId: string;
|
|
52
|
+
parentNodeId?: NodeId;
|
|
53
|
+
relationshipId?: string;
|
|
54
|
+
filterOrder?: FilterId[];
|
|
55
|
+
[key: string]: unknown;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* A binding's target. A `gridColumn` target is a pair, which is why the binding key is
|
|
59
|
+
* a synthetic id rather than the question id (§2.2a).
|
|
60
|
+
*/
|
|
61
|
+
export type BindingTarget = {
|
|
62
|
+
kind: 'question';
|
|
63
|
+
questionId: QuestionId;
|
|
64
|
+
} | {
|
|
65
|
+
kind: 'gridColumn';
|
|
66
|
+
gridQuestionId: QuestionId;
|
|
67
|
+
columnQuestionId: QuestionId;
|
|
68
|
+
};
|
|
69
|
+
export type MappingBinding = {
|
|
70
|
+
nodeId: NodeId;
|
|
71
|
+
fieldId: string;
|
|
72
|
+
target: BindingTarget;
|
|
73
|
+
cardinality?: string;
|
|
74
|
+
onMissing?: string;
|
|
75
|
+
onMany?: string;
|
|
76
|
+
[key: string]: unknown;
|
|
77
|
+
};
|
|
78
|
+
/** Carries no `nodeId` back-pointer: the node already lists it (§2.2a). */
|
|
79
|
+
export type MappingFilter = {
|
|
80
|
+
fieldId: string;
|
|
81
|
+
operator: string;
|
|
82
|
+
value?: DocScalar;
|
|
83
|
+
};
|
|
84
|
+
export type QnrTemplateDocument = {
|
|
85
|
+
documentId: string;
|
|
86
|
+
revision: number;
|
|
87
|
+
meta?: Record<string, unknown>;
|
|
88
|
+
questionsById?: Record<QuestionId, QnrQuestion>;
|
|
89
|
+
questionOrder: QuestionId[];
|
|
90
|
+
gridRowsById?: Record<RowId, QnrGridRow>;
|
|
91
|
+
gridRowOrderByQuestionId?: Record<QuestionId, RowId[]>;
|
|
92
|
+
alternativesById?: Record<AltId, QnrAlternative>;
|
|
93
|
+
alternativeOrderByQuestionId?: Record<QuestionId, AltId[]>;
|
|
94
|
+
tabsById?: Record<TabId, QnrTab>;
|
|
95
|
+
tabOrder?: TabId[];
|
|
96
|
+
actionsById?: Record<ActionId, QnrAction>;
|
|
97
|
+
dataMappingsById?: Record<MappingId, {
|
|
98
|
+
sourceId: string;
|
|
99
|
+
rootNodeId: NodeId;
|
|
100
|
+
bindingOrder?: BindingId[];
|
|
101
|
+
}>;
|
|
102
|
+
mappingNodesById?: Record<NodeId, MappingNode>;
|
|
103
|
+
mappingBindingsById?: Record<BindingId, MappingBinding>;
|
|
104
|
+
mappingFiltersById?: Record<FilterId, MappingFilter>;
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* A new family's document. `questionOrder` is present-and-empty rather than absent
|
|
108
|
+
* because it is the document's only structural array and every reader indexes it; an
|
|
109
|
+
* absent order array would make "no questions yet" and "malformed" the same shape.
|
|
110
|
+
*/
|
|
111
|
+
export declare const emptyTemplateDocument: (documentId: string) => QnrTemplateDocument;
|
|
112
|
+
//# sourceMappingURL=templateDocument.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"templateDocument.d.ts","sourceRoot":"","sources":["../../src/collaboration/templateDocument.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,MAAM,MAAM,UAAU,GAAG,MAAM,CAAA;AAC/B,MAAM,MAAM,KAAK,GAAG,MAAM,CAAA;AAC1B,MAAM,MAAM,KAAK,GAAG,MAAM,CAAA;AAC1B,MAAM,MAAM,KAAK,GAAG,MAAM,CAAA;AAC1B,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAA;AAC7B,MAAM,MAAM,MAAM,GAAG,MAAM,CAAA;AAC3B,MAAM,MAAM,SAAS,GAAG,MAAM,CAAA;AAC9B,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAA;AAC7B,MAAM,MAAM,SAAS,GAAG,MAAM,CAAA;AAE9B,oFAAoF;AACpF,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAA;AAEjD,MAAM,MAAM,WAAW,GAAG;IACtB,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,YAAY,CAAC,EAAE,SAAS,CAAA;IACxB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CACzB,CAAA;AAED,MAAM,MAAM,cAAc,GAAG;IAAE,KAAK,CAA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,CAAC,EAAE,MAAM,CAAC,QAAQ,EAAE,aAAa,CAAC,CAAA;CACvD,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,eAAgB,MAAM,KAAG,mBAIzD,CAAA"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The template authoring document — a normalized entity graph with stable ids and
|
|
3
|
+
* explicit order arrays, in DOC-LAW-1 / DOC-LAW-2 minimal form.
|
|
4
|
+
*
|
|
5
|
+
* Every collection is optional because DOC-LAW-2 forbids storing an empty one: a
|
|
6
|
+
* document with no alternatives has no `alternativesById` key at all. Readers hydrate
|
|
7
|
+
* to a total in-memory model once at the document boundary rather than writing `?? {}`
|
|
8
|
+
* at each use site.
|
|
9
|
+
*
|
|
10
|
+
* @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:152 (document shape)
|
|
11
|
+
* @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:193 (DOC-LAW-1)
|
|
12
|
+
* @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:214 (§2.2a mapping graph)
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* A new family's document. `questionOrder` is present-and-empty rather than absent
|
|
16
|
+
* because it is the document's only structural array and every reader indexes it; an
|
|
17
|
+
* absent order array would make "no questions yet" and "malformed" the same shape.
|
|
18
|
+
*/
|
|
19
|
+
export const emptyTemplateDocument = (documentId) => ({
|
|
20
|
+
documentId,
|
|
21
|
+
revision: 0,
|
|
22
|
+
questionOrder: [],
|
|
23
|
+
});
|
|
24
|
+
//# sourceMappingURL=templateDocument.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"templateDocument.js","sourceRoot":"","sources":["../../src/collaboration/templateDocument.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAiFH;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,UAAkB,EAAuB,EAAE,CAAC,CAAC;IAC/E,UAAU;IACV,QAAQ,EAAE,CAAC;IACX,aAAa,EAAE,EAAE;CACpB,CAAC,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "asma-core-helpers",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"description": "Core helper utilities for ASMA applications",
|
|
5
5
|
"files": [
|
|
6
6
|
"lib/**/*",
|
|
@@ -14,6 +14,10 @@
|
|
|
14
14
|
"./urql": {
|
|
15
15
|
"types": "./lib/helpers/urql.d.ts",
|
|
16
16
|
"default": "./lib/helpers/urql.js"
|
|
17
|
+
},
|
|
18
|
+
"./collaboration": {
|
|
19
|
+
"types": "./lib/collaboration/index.d.ts",
|
|
20
|
+
"default": "./lib/collaboration/index.js"
|
|
17
21
|
}
|
|
18
22
|
},
|
|
19
23
|
"scripts": {
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { describe, it } from 'node:test'
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
CollaborationError,
|
|
6
|
+
OperationConflictError,
|
|
7
|
+
UnknownOperationError,
|
|
8
|
+
applyOperation,
|
|
9
|
+
} from './applyOperation.js'
|
|
10
|
+
import type { TemplateOp } from './operations.js'
|
|
11
|
+
import { emptyTemplateDocument } from './templateDocument.js'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Guards the invariants a consumer would notice if a publish broke them. The exhaustive
|
|
15
|
+
* per-op suite lives with the service that owns the storage; this one exists because this
|
|
16
|
+
* package publishes on every push to master, so the reducer must not be able to ship
|
|
17
|
+
* broken without a red build here first.
|
|
18
|
+
*
|
|
19
|
+
* @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:380 (op vocabulary)
|
|
20
|
+
* @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:195 (DOC-LAW-2)
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const doc0 = emptyTemplateDocument('tpl-1')
|
|
24
|
+
|
|
25
|
+
const apply = (ops: TemplateOp[], from = doc0) => ops.reduce((doc, op) => applyOperation(doc, op), from)
|
|
26
|
+
|
|
27
|
+
const threeQuestions = apply([
|
|
28
|
+
{ type: 'question.create', questionId: 'q-1', kind: 'text' },
|
|
29
|
+
{ type: 'question.create', questionId: 'q-2', kind: 'text' },
|
|
30
|
+
{ type: 'question.create', questionId: 'q-3', kind: 'text', atIndex: 0 },
|
|
31
|
+
])
|
|
32
|
+
|
|
33
|
+
describe('applyOperation', () => {
|
|
34
|
+
it('bumps the revision by one and leaves its input untouched', () => {
|
|
35
|
+
const next = applyOperation(doc0, { type: 'question.create', questionId: 'q-1', kind: 'text' })
|
|
36
|
+
|
|
37
|
+
assert.equal(next.revision, 1)
|
|
38
|
+
assert.equal(doc0.revision, 0)
|
|
39
|
+
assert.deepEqual(doc0.questionOrder, [])
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('inserts at the requested index and clamps one past the end', () => {
|
|
43
|
+
assert.deepEqual(threeQuestions.questionOrder, ['q-3', 'q-1', 'q-2'])
|
|
44
|
+
|
|
45
|
+
const clamped = applyOperation(threeQuestions, {
|
|
46
|
+
type: 'question.create',
|
|
47
|
+
questionId: 'q-4',
|
|
48
|
+
kind: 'text',
|
|
49
|
+
atIndex: 99,
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
assert.deepEqual(clamped.questionOrder, ['q-3', 'q-1', 'q-2', 'q-4'])
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it('moves by removing first, so the index counts the other questions only', () => {
|
|
56
|
+
const moved = applyOperation(threeQuestions, { type: 'question.move', questionId: 'q-2', toIndex: 0 })
|
|
57
|
+
|
|
58
|
+
assert.deepEqual(moved.questionOrder, ['q-2', 'q-3', 'q-1'])
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('drops the bindings that targeted a deleted question, keeping the shared node', () => {
|
|
62
|
+
const bound = apply([
|
|
63
|
+
{ type: 'question.create', questionId: 'q-1', kind: 'text' },
|
|
64
|
+
{ type: 'mappingNode.create', nodeId: 'n-1', entityId: 'Actor' },
|
|
65
|
+
{
|
|
66
|
+
type: 'mappingBinding.create',
|
|
67
|
+
bindingId: 'b-1',
|
|
68
|
+
nodeId: 'n-1',
|
|
69
|
+
fieldId: 'Navn',
|
|
70
|
+
target: { kind: 'question', questionId: 'q-1' },
|
|
71
|
+
},
|
|
72
|
+
])
|
|
73
|
+
assert.ok(bound.mappingBindingsById?.['b-1'])
|
|
74
|
+
|
|
75
|
+
const deleted = applyOperation(bound, { type: 'question.delete', questionId: 'q-1' })
|
|
76
|
+
|
|
77
|
+
assert.equal(deleted.mappingBindingsById, undefined)
|
|
78
|
+
assert.ok(deleted.mappingNodesById?.['n-1'])
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
it('removes a collection that just became empty rather than storing it empty', () => {
|
|
82
|
+
const withAlternative = apply([
|
|
83
|
+
{ type: 'question.create', questionId: 'q-1', kind: 'radio' },
|
|
84
|
+
{ type: 'alternative.create', questionId: 'q-1', alternativeId: 'a-1', label: 'Yes' },
|
|
85
|
+
])
|
|
86
|
+
assert.deepEqual(withAlternative.alternativesById, { 'a-1': { label: 'Yes' } })
|
|
87
|
+
|
|
88
|
+
const removed = applyOperation(withAlternative, {
|
|
89
|
+
type: 'alternative.delete',
|
|
90
|
+
questionId: 'q-1',
|
|
91
|
+
alternativeId: 'a-1',
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
assert.equal(removed.alternativesById, undefined)
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it('refuses a duplicate create as a conflict', () => {
|
|
98
|
+
const once = applyOperation(doc0, { type: 'question.create', questionId: 'q-1', kind: 'text' })
|
|
99
|
+
|
|
100
|
+
assert.throws(
|
|
101
|
+
() => applyOperation(once, { type: 'question.create', questionId: 'q-1', kind: 'text' }),
|
|
102
|
+
(error: unknown) => {
|
|
103
|
+
assert.ok(error instanceof OperationConflictError)
|
|
104
|
+
assert.equal(error.statusCode, 409)
|
|
105
|
+
assert.equal(error.code, 'qnr_operation_conflict')
|
|
106
|
+
return true
|
|
107
|
+
},
|
|
108
|
+
)
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
it('reports an unknown op in the shape the service error resolver maps', () => {
|
|
112
|
+
assert.throws(
|
|
113
|
+
() => applyOperation(doc0, { type: 'question.teleport' } as unknown as TemplateOp),
|
|
114
|
+
(error: unknown) => {
|
|
115
|
+
assert.ok(error instanceof UnknownOperationError)
|
|
116
|
+
// bunjs keys the HTTP envelope off this base class, not off CustomError.
|
|
117
|
+
assert.ok(error instanceof CollaborationError)
|
|
118
|
+
assert.equal(error.statusCode, 422)
|
|
119
|
+
assert.equal(error.code, 'qnr_unknown_operation')
|
|
120
|
+
return true
|
|
121
|
+
},
|
|
122
|
+
)
|
|
123
|
+
})
|
|
124
|
+
})
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import type { TemplateOp } from './operations.js'
|
|
2
|
+
import type { BindingTarget, QnrTemplateDocument, QuestionId } from './templateDocument.js'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The authoring reducer. Pure: takes a document and an op, returns a new document with
|
|
6
|
+
* `revision` bumped by one. The frontend applies it locally before the op leaves the
|
|
7
|
+
* client and bunjs applies it authoritatively before the op becomes durable, so any
|
|
8
|
+
* divergence between the two is a data-loss bug — hence one implementation, not two.
|
|
9
|
+
*
|
|
10
|
+
* Idempotency by `op_id` and revision assignment on the wire are persistence concerns
|
|
11
|
+
* and deliberately live outside this function.
|
|
12
|
+
*
|
|
13
|
+
* @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:380 (vocabulary)
|
|
14
|
+
* @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:384 (authoring dataflow)
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Base for the reducer's typed failures. A plain `Error` subclass on purpose: this module
|
|
19
|
+
* also runs in the browser, and bunjs's `CustomError` reaches `@hono/zod-openapi`, the AI
|
|
20
|
+
* vendor error and the logger — none of which can ship to a client. It carries the two
|
|
21
|
+
* fields the service's error resolver reads, so bunjs maps it losslessly to the same
|
|
22
|
+
* status and code the `CustomError` subclasses produced (`processErrorDoNotNotify`).
|
|
23
|
+
*/
|
|
24
|
+
export class CollaborationError extends Error {
|
|
25
|
+
readonly statusCode: number
|
|
26
|
+
readonly code: string
|
|
27
|
+
|
|
28
|
+
constructor(message: string, statusCode: number, code: string) {
|
|
29
|
+
super(message)
|
|
30
|
+
this.name = 'CollaborationError'
|
|
31
|
+
this.statusCode = statusCode
|
|
32
|
+
this.code = code
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export class UnknownOperationError extends CollaborationError {
|
|
37
|
+
constructor(type: string) {
|
|
38
|
+
super(`Unknown qnr template operation "${type}"`, 422, 'qnr_unknown_operation')
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class OperationConflictError extends CollaborationError {
|
|
43
|
+
constructor(message: string) {
|
|
44
|
+
super(message, 409, 'qnr_operation_conflict')
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Serialises a binding target so the "one binding per target" invariant is checkable. */
|
|
49
|
+
const targetKey = (target: BindingTarget): string =>
|
|
50
|
+
target.kind === 'question'
|
|
51
|
+
? `question:${target.questionId}`
|
|
52
|
+
: `gridColumn:${target.gridQuestionId}:${target.columnQuestionId}`
|
|
53
|
+
|
|
54
|
+
/** Sets a key, or removes it when the op carried an explicit unset. */
|
|
55
|
+
const writeField = <T extends Record<string, unknown>>(record: T, field: string, value: unknown): T => {
|
|
56
|
+
const next = { ...record } as Record<string, unknown>
|
|
57
|
+
if (value === null || value === undefined) delete next[field]
|
|
58
|
+
else next[field] = value
|
|
59
|
+
return next as T
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Inserts `id` at `index`, clamped into range. Absent index appends. */
|
|
63
|
+
const insertAt = (order: readonly string[], id: string, index?: number): string[] => {
|
|
64
|
+
const next = [...order]
|
|
65
|
+
const at = index === undefined ? next.length : Math.max(0, Math.min(index, next.length))
|
|
66
|
+
next.splice(at, 0, id)
|
|
67
|
+
return next
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const moveInOrder = (order: readonly string[], id: string, toIndex: number): string[] => {
|
|
71
|
+
const without = order.filter((entry) => entry !== id)
|
|
72
|
+
const at = Math.max(0, Math.min(toIndex, without.length))
|
|
73
|
+
return [...without.slice(0, at), id, ...without.slice(at)]
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const omitKey = <V>(record: Record<string, V>, key: string): Record<string, V> => {
|
|
77
|
+
const { [key]: _removed, ...rest } = record
|
|
78
|
+
return rest
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Spreads `patch` onto `base`, **omitting** keys whose value is `undefined` rather than
|
|
83
|
+
* assigning it. Required by `exactOptionalPropertyTypes`: `{ ...doc, x: undefined }` is
|
|
84
|
+
* a type error, and it is also the wrong shape — an absent key and a key holding
|
|
85
|
+
* `undefined` serialise differently.
|
|
86
|
+
*/
|
|
87
|
+
const patchDocument = <T extends object>(base: T, patch: Record<string, unknown>): T => {
|
|
88
|
+
const next = { ...base } as Record<string, unknown>
|
|
89
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
90
|
+
if (value === undefined) delete next[key]
|
|
91
|
+
else next[key] = value
|
|
92
|
+
}
|
|
93
|
+
return next as T
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* DOC-LAW-2 at the document boundary: an optional collection that just became empty is
|
|
98
|
+
* removed, so two documents with the same content are the same document.
|
|
99
|
+
*
|
|
100
|
+
* `questionOrder` is exempt — it is the one structural array every reader indexes, and
|
|
101
|
+
* making "no questions yet" indistinguishable from "malformed" would buy nothing.
|
|
102
|
+
*/
|
|
103
|
+
const OPTIONAL_COLLECTIONS = [
|
|
104
|
+
'meta',
|
|
105
|
+
'questionsById',
|
|
106
|
+
'gridRowsById',
|
|
107
|
+
'gridRowOrderByQuestionId',
|
|
108
|
+
'alternativesById',
|
|
109
|
+
'alternativeOrderByQuestionId',
|
|
110
|
+
'tabsById',
|
|
111
|
+
'tabOrder',
|
|
112
|
+
'actionsById',
|
|
113
|
+
'dataMappingsById',
|
|
114
|
+
'mappingNodesById',
|
|
115
|
+
'mappingBindingsById',
|
|
116
|
+
'mappingFiltersById',
|
|
117
|
+
] as const
|
|
118
|
+
|
|
119
|
+
const prune = (doc: QnrTemplateDocument): QnrTemplateDocument => {
|
|
120
|
+
const next = { ...doc } as Record<string, unknown>
|
|
121
|
+
for (const key of OPTIONAL_COLLECTIONS) {
|
|
122
|
+
const value = next[key]
|
|
123
|
+
if (value === undefined) continue
|
|
124
|
+
const isEmpty = Array.isArray(value)
|
|
125
|
+
? value.length === 0
|
|
126
|
+
: typeof value === 'object' && value !== null && Object.keys(value).length === 0
|
|
127
|
+
if (isEmpty) delete next[key]
|
|
128
|
+
}
|
|
129
|
+
return next as QnrTemplateDocument
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Drops every binding whose target no longer resolves to an existing question. */
|
|
133
|
+
const dropBindingsForQuestion = (doc: QnrTemplateDocument, questionId: QuestionId): QnrTemplateDocument => {
|
|
134
|
+
if (!doc.mappingBindingsById) return doc
|
|
135
|
+
const kept = Object.entries(doc.mappingBindingsById).filter(([, binding]) => {
|
|
136
|
+
const { target } = binding
|
|
137
|
+
return target.kind === 'question'
|
|
138
|
+
? target.questionId !== questionId
|
|
139
|
+
: target.gridQuestionId !== questionId && target.columnQuestionId !== questionId
|
|
140
|
+
})
|
|
141
|
+
return { ...doc, mappingBindingsById: Object.fromEntries(kept) }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export const applyOperation = (document: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument => {
|
|
145
|
+
const next = reduce(document, op)
|
|
146
|
+
return prune({ ...next, revision: document.revision + 1 })
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* One switch over a closed vocabulary. Splitting it per entity family would hide the
|
|
151
|
+
* `never` exhaustiveness check that turns an unhandled op into a compile error.
|
|
152
|
+
*/
|
|
153
|
+
const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument => {
|
|
154
|
+
switch (op.type) {
|
|
155
|
+
case 'template.updateMeta': {
|
|
156
|
+
let meta = { ...(doc.meta ?? {}) }
|
|
157
|
+
for (const [key, value] of Object.entries(op.patch)) {
|
|
158
|
+
meta = writeField(meta, key, value)
|
|
159
|
+
}
|
|
160
|
+
return { ...doc, meta }
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
case 'question.create': {
|
|
164
|
+
if (doc.questionsById?.[op.questionId]) {
|
|
165
|
+
throw new OperationConflictError(`Question "${op.questionId}" already exists`)
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
...doc,
|
|
169
|
+
questionsById: { ...(doc.questionsById ?? {}), [op.questionId]: { kind: op.kind } },
|
|
170
|
+
questionOrder: insertAt(doc.questionOrder, op.questionId, op.atIndex),
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
case 'question.updateField': {
|
|
175
|
+
const question = doc.questionsById?.[op.questionId]
|
|
176
|
+
if (!question) {
|
|
177
|
+
throw new OperationConflictError(`Unknown question "${op.questionId}"`)
|
|
178
|
+
}
|
|
179
|
+
return {
|
|
180
|
+
...doc,
|
|
181
|
+
questionsById: {
|
|
182
|
+
...doc.questionsById,
|
|
183
|
+
[op.questionId]: writeField(question, op.field, op.value),
|
|
184
|
+
},
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
case 'question.move': {
|
|
189
|
+
if (!doc.questionsById?.[op.questionId]) {
|
|
190
|
+
throw new OperationConflictError(`Unknown question "${op.questionId}"`)
|
|
191
|
+
}
|
|
192
|
+
return { ...doc, questionOrder: moveInOrder(doc.questionOrder, op.questionId, op.toIndex) }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
case 'question.delete': {
|
|
196
|
+
const alternativeIds = doc.alternativeOrderByQuestionId?.[op.questionId] ?? []
|
|
197
|
+
let alternativesById = doc.alternativesById
|
|
198
|
+
if (alternativesById) {
|
|
199
|
+
alternativesById = alternativeIds.reduce((acc, id) => omitKey(acc, id), alternativesById)
|
|
200
|
+
}
|
|
201
|
+
const withoutQuestion = patchDocument(doc, {
|
|
202
|
+
questionsById: doc.questionsById && omitKey(doc.questionsById, op.questionId),
|
|
203
|
+
questionOrder: doc.questionOrder.filter((id) => id !== op.questionId),
|
|
204
|
+
alternativesById,
|
|
205
|
+
alternativeOrderByQuestionId:
|
|
206
|
+
doc.alternativeOrderByQuestionId && omitKey(doc.alternativeOrderByQuestionId, op.questionId),
|
|
207
|
+
gridRowOrderByQuestionId:
|
|
208
|
+
doc.gridRowOrderByQuestionId && omitKey(doc.gridRowOrderByQuestionId, op.questionId),
|
|
209
|
+
})
|
|
210
|
+
// A binding pointing at a deleted question is an unresolvable reference the
|
|
211
|
+
// compiler would reject at publication; drop it with its target.
|
|
212
|
+
return dropBindingsForQuestion(withoutQuestion, op.questionId)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
case 'alternative.create': {
|
|
216
|
+
if (!doc.questionsById?.[op.questionId]) {
|
|
217
|
+
throw new OperationConflictError(`Unknown question "${op.questionId}"`)
|
|
218
|
+
}
|
|
219
|
+
const order = doc.alternativeOrderByQuestionId?.[op.questionId] ?? []
|
|
220
|
+
return {
|
|
221
|
+
...doc,
|
|
222
|
+
alternativesById: {
|
|
223
|
+
...(doc.alternativesById ?? {}),
|
|
224
|
+
[op.alternativeId]: op.label === undefined ? {} : { label: op.label },
|
|
225
|
+
},
|
|
226
|
+
alternativeOrderByQuestionId: {
|
|
227
|
+
...(doc.alternativeOrderByQuestionId ?? {}),
|
|
228
|
+
[op.questionId]: insertAt(order, op.alternativeId, op.atIndex),
|
|
229
|
+
},
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
case 'alternative.delete': {
|
|
234
|
+
const order = doc.alternativeOrderByQuestionId?.[op.questionId] ?? []
|
|
235
|
+
const remaining = order.filter((id) => id !== op.alternativeId)
|
|
236
|
+
return patchDocument(doc, {
|
|
237
|
+
alternativesById: doc.alternativesById && omitKey(doc.alternativesById, op.alternativeId),
|
|
238
|
+
alternativeOrderByQuestionId: {
|
|
239
|
+
...(doc.alternativeOrderByQuestionId ?? {}),
|
|
240
|
+
[op.questionId]: remaining,
|
|
241
|
+
},
|
|
242
|
+
})
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
case 'mappingNode.create': {
|
|
246
|
+
if (doc.mappingNodesById?.[op.nodeId]) {
|
|
247
|
+
throw new OperationConflictError(`Mapping node "${op.nodeId}" already exists`)
|
|
248
|
+
}
|
|
249
|
+
const node = writeField(
|
|
250
|
+
writeField({ entityId: op.entityId }, 'parentNodeId', op.parentNodeId ?? null),
|
|
251
|
+
'relationshipId',
|
|
252
|
+
op.relationshipId ?? null,
|
|
253
|
+
)
|
|
254
|
+
return { ...doc, mappingNodesById: { ...(doc.mappingNodesById ?? {}), [op.nodeId]: node } }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
case 'mappingNode.delete': {
|
|
258
|
+
const filterIds = doc.mappingNodesById?.[op.nodeId]?.filterOrder ?? []
|
|
259
|
+
let filtersById = doc.mappingFiltersById
|
|
260
|
+
if (filtersById) {
|
|
261
|
+
filtersById = filterIds.reduce((acc, id) => omitKey(acc, id), filtersById)
|
|
262
|
+
}
|
|
263
|
+
const bindings = Object.entries(doc.mappingBindingsById ?? {}).filter(
|
|
264
|
+
([, binding]) => binding.nodeId !== op.nodeId,
|
|
265
|
+
)
|
|
266
|
+
return patchDocument(doc, {
|
|
267
|
+
mappingNodesById: doc.mappingNodesById && omitKey(doc.mappingNodesById, op.nodeId),
|
|
268
|
+
mappingFiltersById: filtersById,
|
|
269
|
+
mappingBindingsById: Object.fromEntries(bindings),
|
|
270
|
+
})
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
case 'mappingBinding.create': {
|
|
274
|
+
if (!doc.mappingNodesById?.[op.nodeId]) {
|
|
275
|
+
throw new OperationConflictError(`Unknown mapping node "${op.nodeId}"`)
|
|
276
|
+
}
|
|
277
|
+
const wanted = targetKey(op.target)
|
|
278
|
+
const clash = Object.entries(doc.mappingBindingsById ?? {}).find(
|
|
279
|
+
([, binding]) => targetKey(binding.target) === wanted,
|
|
280
|
+
)
|
|
281
|
+
if (clash) {
|
|
282
|
+
throw new OperationConflictError(
|
|
283
|
+
`Target ${wanted} is already bound by "${clash[0]}" — at most one binding per target`,
|
|
284
|
+
)
|
|
285
|
+
}
|
|
286
|
+
return {
|
|
287
|
+
...doc,
|
|
288
|
+
mappingBindingsById: {
|
|
289
|
+
...(doc.mappingBindingsById ?? {}),
|
|
290
|
+
[op.bindingId]: { nodeId: op.nodeId, fieldId: op.fieldId, target: op.target },
|
|
291
|
+
},
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
case 'mappingBinding.update': {
|
|
296
|
+
const binding = doc.mappingBindingsById?.[op.bindingId]
|
|
297
|
+
if (!binding) {
|
|
298
|
+
throw new OperationConflictError(`Unknown mapping binding "${op.bindingId}"`)
|
|
299
|
+
}
|
|
300
|
+
if (op.patch.nodeId && !doc.mappingNodesById?.[op.patch.nodeId]) {
|
|
301
|
+
throw new OperationConflictError(`Unknown mapping node "${op.patch.nodeId}"`)
|
|
302
|
+
}
|
|
303
|
+
return {
|
|
304
|
+
...doc,
|
|
305
|
+
mappingBindingsById: {
|
|
306
|
+
...doc.mappingBindingsById,
|
|
307
|
+
[op.bindingId]: { ...binding, ...op.patch },
|
|
308
|
+
},
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
case 'mappingBinding.delete':
|
|
313
|
+
return patchDocument(doc, {
|
|
314
|
+
mappingBindingsById: doc.mappingBindingsById && omitKey(doc.mappingBindingsById, op.bindingId),
|
|
315
|
+
})
|
|
316
|
+
|
|
317
|
+
case 'mappingFilter.set': {
|
|
318
|
+
const node = doc.mappingNodesById?.[op.nodeId]
|
|
319
|
+
if (!node) {
|
|
320
|
+
throw new OperationConflictError(`Unknown mapping node "${op.nodeId}"`)
|
|
321
|
+
}
|
|
322
|
+
const filterOrder = node.filterOrder ?? []
|
|
323
|
+
const filter = writeField({ fieldId: op.fieldId, operator: op.operator }, 'value', op.value ?? null)
|
|
324
|
+
return {
|
|
325
|
+
...doc,
|
|
326
|
+
mappingFiltersById: { ...(doc.mappingFiltersById ?? {}), [op.filterId]: filter },
|
|
327
|
+
mappingNodesById: {
|
|
328
|
+
...doc.mappingNodesById,
|
|
329
|
+
[op.nodeId]: {
|
|
330
|
+
...node,
|
|
331
|
+
filterOrder: filterOrder.includes(op.filterId) ? filterOrder : [...filterOrder, op.filterId],
|
|
332
|
+
},
|
|
333
|
+
},
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
case 'mappingFilter.delete': {
|
|
338
|
+
const nodes = Object.fromEntries(
|
|
339
|
+
Object.entries(doc.mappingNodesById ?? {}).map(([nodeId, node]) => [
|
|
340
|
+
nodeId,
|
|
341
|
+
node.filterOrder?.includes(op.filterId)
|
|
342
|
+
? { ...node, filterOrder: node.filterOrder.filter((id) => id !== op.filterId) }
|
|
343
|
+
: node,
|
|
344
|
+
]),
|
|
345
|
+
)
|
|
346
|
+
return patchDocument(doc, {
|
|
347
|
+
mappingFiltersById: doc.mappingFiltersById && omitKey(doc.mappingFiltersById, op.filterId),
|
|
348
|
+
mappingNodesById: nodes,
|
|
349
|
+
})
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
default: {
|
|
353
|
+
// Exhaustiveness: a new op member makes this a compile error, not a silent no-op.
|
|
354
|
+
const unhandled: never = op
|
|
355
|
+
throw new UnknownOperationError((unhandled as { type?: string })?.type ?? 'undefined')
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The QNR authoring collaboration contract: the normalized template document, the op
|
|
3
|
+
* vocabulary, and the reducer that turns one into the other.
|
|
4
|
+
*
|
|
5
|
+
* Published as its own subpath (`asma-core-helpers/collaboration`) rather than through the
|
|
6
|
+
* root barrel, and that is load-bearing rather than tidiness: the root barrel re-exports
|
|
7
|
+
* modules that read `window` and `localStorage` at module top level (`helpers/getSubdomain`,
|
|
8
|
+
* `helpers/initEnvConfigsVars`), and ESM evaluates every re-exported module on import — so
|
|
9
|
+
* importing the barrel from a Bun/Node service throws `ReferenceError: window is not
|
|
10
|
+
* defined` before any of this code runs. This entry point is browser- and server-safe
|
|
11
|
+
* because nothing under it imports anything at all.
|
|
12
|
+
*
|
|
13
|
+
* Both sides of the questionnaire editor consume exactly this module: the frontend applies
|
|
14
|
+
* an op locally before it leaves the client, bunjs applies the same op authoritatively
|
|
15
|
+
* before it becomes durable. Two implementations would make every divergence a data-loss
|
|
16
|
+
* bug, which is why the contract lives here instead of in either consumer.
|
|
17
|
+
*
|
|
18
|
+
* @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:422 (shared contracts package)
|
|
19
|
+
* @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-21-40-plan-qnr-stage2-new-model-editor-and-sync.md:690 (FILE-001)
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export * from './templateDocument.js'
|
|
23
|
+
export * from './operations.js'
|
|
24
|
+
export * from './applyOperation.js'
|