asma-core-helpers 0.16.0 → 0.18.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 +25 -0
- package/lib/collaboration/index.d.ts.map +1 -0
- package/lib/collaboration/index.js +25 -0
- package/lib/collaboration/index.js.map +1 -0
- package/lib/collaboration/operations.d.ts +90 -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/questionTypes.d.ts +50 -0
- package/lib/collaboration/questionTypes.d.ts.map +1 -0
- package/lib/collaboration/questionTypes.js +105 -0
- package/lib/collaboration/questionTypes.js.map +1 -0
- package/lib/collaboration/templateDocument.d.ts +120 -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 +25 -0
- package/src/collaboration/operations.ts +76 -0
- package/src/collaboration/questionTypes.test.ts +69 -0
- package/src/collaboration/questionTypes.ts +126 -0
- package/src/collaboration/templateDocument.ts +112 -0
|
@@ -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]: { type: op.questionType } },
|
|
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,25 @@
|
|
|
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 './questionTypes.js'
|
|
23
|
+
export * from './templateDocument.js'
|
|
24
|
+
export * from './operations.js'
|
|
25
|
+
export * from './applyOperation.js'
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { AltId, BindingId, BindingTarget, DocScalar, FilterId, NodeId, QuestionId } from './templateDocument.js'
|
|
2
|
+
import type { QuestionType } from './questionTypes.js'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The authoring op vocabulary. `entity.action`, stable-id targets only, append-only —
|
|
6
|
+
* a new op is a new member, never a changed one.
|
|
7
|
+
*
|
|
8
|
+
* `null` in an op payload is the **explicit unset** the way JSON-merge-patch uses it.
|
|
9
|
+
* DOC-LAW-2 bans `null` in the stored document, not in the op that produces it: the op
|
|
10
|
+
* layer is the only place the absent-vs-cleared tri-state survives.
|
|
11
|
+
*
|
|
12
|
+
* @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:380
|
|
13
|
+
* @see _docs/editor/qnrs/cross/2026-07-12-20-20-architecture-qnr-v2-model-collaboration-sync.md:195 (DOC-LAW-2 tri-state)
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** A value an op may write. `null` means unset. */
|
|
17
|
+
export type OpValue = DocScalar | null
|
|
18
|
+
|
|
19
|
+
export type TemplateOp =
|
|
20
|
+
| { type: 'template.updateMeta'; patch: Record<string, OpValue | Record<string, unknown>> }
|
|
21
|
+
// `questionType`, not `type`: the envelope already owns `type` for the op name, so the question's
|
|
22
|
+
// own type (which is what lands in the document) needs a distinct key here.
|
|
23
|
+
| { type: 'question.create'; questionId: QuestionId; questionType: QuestionType; atIndex?: number }
|
|
24
|
+
| { type: 'question.updateField'; questionId: QuestionId; field: string; value: OpValue }
|
|
25
|
+
| { type: 'question.move'; questionId: QuestionId; toIndex: number }
|
|
26
|
+
| { type: 'question.delete'; questionId: QuestionId }
|
|
27
|
+
| { type: 'alternative.create'; questionId: QuestionId; alternativeId: AltId; label?: string; atIndex?: number }
|
|
28
|
+
| { type: 'alternative.delete'; questionId: QuestionId; alternativeId: AltId }
|
|
29
|
+
| { type: 'mappingNode.create'; nodeId: NodeId; entityId: string; parentNodeId?: NodeId; relationshipId?: string }
|
|
30
|
+
| { type: 'mappingNode.delete'; nodeId: NodeId }
|
|
31
|
+
| {
|
|
32
|
+
type: 'mappingBinding.create'
|
|
33
|
+
bindingId: BindingId
|
|
34
|
+
nodeId: NodeId
|
|
35
|
+
fieldId: string
|
|
36
|
+
target: BindingTarget
|
|
37
|
+
}
|
|
38
|
+
| {
|
|
39
|
+
type: 'mappingBinding.update'
|
|
40
|
+
bindingId: BindingId
|
|
41
|
+
patch: { nodeId?: NodeId; fieldId?: string; target?: BindingTarget }
|
|
42
|
+
}
|
|
43
|
+
| { type: 'mappingBinding.delete'; bindingId: BindingId }
|
|
44
|
+
| {
|
|
45
|
+
type: 'mappingFilter.set'
|
|
46
|
+
filterId: FilterId
|
|
47
|
+
nodeId: NodeId
|
|
48
|
+
fieldId: string
|
|
49
|
+
operator: string
|
|
50
|
+
value?: DocScalar
|
|
51
|
+
}
|
|
52
|
+
| { type: 'mappingFilter.delete'; filterId: FilterId }
|
|
53
|
+
|
|
54
|
+
export type TemplateOpType = TemplateOp['type']
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The op types this reducer implements. The vocabulary in the architecture doc is
|
|
58
|
+
* larger (grid rows, tabs, actions, layout, visibility/highlight rules); those slot
|
|
59
|
+
* into the same registry without changing the envelope.
|
|
60
|
+
*/
|
|
61
|
+
export const IMPLEMENTED_OP_TYPES = [
|
|
62
|
+
'template.updateMeta',
|
|
63
|
+
'question.create',
|
|
64
|
+
'question.updateField',
|
|
65
|
+
'question.move',
|
|
66
|
+
'question.delete',
|
|
67
|
+
'alternative.create',
|
|
68
|
+
'alternative.delete',
|
|
69
|
+
'mappingNode.create',
|
|
70
|
+
'mappingNode.delete',
|
|
71
|
+
'mappingBinding.create',
|
|
72
|
+
'mappingBinding.update',
|
|
73
|
+
'mappingBinding.delete',
|
|
74
|
+
'mappingFilter.set',
|
|
75
|
+
'mappingFilter.delete',
|
|
76
|
+
] as const satisfies readonly TemplateOpType[]
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { describe, it } from 'node:test'
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
LEGACY_QUESTION_TYPES,
|
|
6
|
+
LEGACY_TO_V2_QUESTION_TYPE,
|
|
7
|
+
type QuestionType,
|
|
8
|
+
QUESTION_TYPES,
|
|
9
|
+
isQuestionType,
|
|
10
|
+
toLegacyQuestionType,
|
|
11
|
+
toV2QuestionType,
|
|
12
|
+
} from './questionTypes.js'
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The register is a contract between two runtimes and a stored hash, so the failure this guards is
|
|
16
|
+
* not "a test is red" but "a question type exists on one side only" — which shows up as a document
|
|
17
|
+
* nobody can render, or a projection that writes a name the legacy wire rejects.
|
|
18
|
+
*
|
|
19
|
+
* @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-21-20-analysis-qnr-template-field-inventory.md:365 — M-062
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
describe('question type register', () => {
|
|
23
|
+
it('maps every legacy type to a v2 type', () => {
|
|
24
|
+
assert.equal(LEGACY_QUESTION_TYPES.length, 19)
|
|
25
|
+
|
|
26
|
+
for (const legacy of LEGACY_QUESTION_TYPES) {
|
|
27
|
+
const mapped = toV2QuestionType(legacy)
|
|
28
|
+
assert.ok(mapped !== undefined, `${legacy} has no v2 mapping`)
|
|
29
|
+
assert.ok(isQuestionType(mapped), `${legacy} maps to ${String(mapped)}, which is not a v2 type`)
|
|
30
|
+
}
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('round-trips every type in both directions', () => {
|
|
34
|
+
for (const legacy of LEGACY_QUESTION_TYPES) {
|
|
35
|
+
assert.equal(toLegacyQuestionType(LEGACY_TO_V2_QUESTION_TYPE[legacy]), legacy)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
for (const type of QUESTION_TYPES) {
|
|
39
|
+
assert.equal(toV2QuestionType(toLegacyQuestionType(type)), type)
|
|
40
|
+
}
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('covers the whole v2 union, so no type is reachable only from legacy', () => {
|
|
44
|
+
const reachable = new Set<QuestionType>(Object.values(LEGACY_TO_V2_QUESTION_TYPE))
|
|
45
|
+
|
|
46
|
+
assert.equal(QUESTION_TYPES.length, 19)
|
|
47
|
+
assert.deepEqual([...QUESTION_TYPES].sort(), [...reachable].sort())
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it('renames CompositeQuestion and nothing else', () => {
|
|
51
|
+
const renamed = LEGACY_QUESTION_TYPES.filter(
|
|
52
|
+
(legacy) => (LEGACY_TO_V2_QUESTION_TYPE[legacy] as string) !== (legacy as string),
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
// The whole backward-compatibility argument rests on this being exactly one entry: 18 types
|
|
56
|
+
// need no translation, so a mapper bug can only ever affect the grid.
|
|
57
|
+
assert.deepEqual(renamed, ['CompositeQuestion'])
|
|
58
|
+
assert.equal(toV2QuestionType('CompositeQuestion'), 'QuestionGrid')
|
|
59
|
+
assert.equal(toLegacyQuestionType('QuestionGrid'), 'CompositeQuestion')
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('refuses an unknown legacy type instead of passing it through', () => {
|
|
63
|
+
// Passing it through would put a type in the document that no editor can render and no
|
|
64
|
+
// projection can write back; the import mapper has a report to record this in.
|
|
65
|
+
assert.equal(toV2QuestionType('Telepathy'), undefined)
|
|
66
|
+
assert.equal(toV2QuestionType(''), undefined)
|
|
67
|
+
assert.equal(isQuestionType('CompositeQuestion'), false)
|
|
68
|
+
})
|
|
69
|
+
})
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The question-type register — the one place that says what a question can be.
|
|
3
|
+
*
|
|
4
|
+
* `QnrQuestion.type` is this union rather than `string` on purpose: the value is part of the stored
|
|
5
|
+
* document and therefore part of `document_hash`, so a typo cannot be corrected later without a
|
|
6
|
+
* document migration across every stored version. A closed union makes an unknown type a build
|
|
7
|
+
* error on both sides instead of a row nobody can render.
|
|
8
|
+
*
|
|
9
|
+
* **The values are the legacy `QUESTION_TYPE` values verbatim, with exactly one rename**
|
|
10
|
+
* (`CompositeQuestion` → `QuestionGrid`, OQ-V2-17). That is deliberate backward compatibility: 18 of
|
|
11
|
+
* 19 types need no translation at all, so the import mapper and the reverse projection carry a
|
|
12
|
+
* one-row table rather than a whole vocabulary, and the legacy wire keeps receiving the names it
|
|
13
|
+
* always did.
|
|
14
|
+
*
|
|
15
|
+
* Transcribed from `asma-modules/editor/shared/types/questions/fields/Question.constants.ts`
|
|
16
|
+
* (`QUESTION_TYPE`), which stays canonical for the **legacy** contract. It cannot be imported here:
|
|
17
|
+
* it lives in the polyrepo root, outside both service repos' build contexts.
|
|
18
|
+
*
|
|
19
|
+
* @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-21-20-analysis-qnr-template-field-inventory.md:365 — M-062 `q.type` → `question.type` (19-value enum)
|
|
20
|
+
* @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-21-20-analysis-qnr-template-field-inventory.md:417 — M-098 `q.subtype`
|
|
21
|
+
* @see asma-modules/_docs/editor/qnrs/cross/2026-07-12-21-40-plan-qnr-stage2-new-model-editor-and-sync.md — OQ-V2-17 (CompositeQuestion → QuestionGrid)
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** The legacy discriminator values, exactly as `templates.properties` stores them. */
|
|
25
|
+
export const LEGACY_QUESTION_TYPES = [
|
|
26
|
+
'BooleanQuestion',
|
|
27
|
+
'Chart',
|
|
28
|
+
'CheckBoxes',
|
|
29
|
+
'CompositeQuestion',
|
|
30
|
+
'DateField',
|
|
31
|
+
'DocumentUpload',
|
|
32
|
+
'Dropdown',
|
|
33
|
+
'Emoticons',
|
|
34
|
+
'ExpressionQuestion',
|
|
35
|
+
'FormatNumber',
|
|
36
|
+
'LinearScale',
|
|
37
|
+
'Link',
|
|
38
|
+
'RadioButtons',
|
|
39
|
+
'Readonly',
|
|
40
|
+
'Space',
|
|
41
|
+
'TextLong',
|
|
42
|
+
'TextShort',
|
|
43
|
+
'Title',
|
|
44
|
+
'Widget',
|
|
45
|
+
] as const
|
|
46
|
+
|
|
47
|
+
export type LegacyQuestionType = (typeof LEGACY_QUESTION_TYPES)[number]
|
|
48
|
+
|
|
49
|
+
/** What a v2 document stores in `question.type`. */
|
|
50
|
+
export const QUESTION_TYPES = [
|
|
51
|
+
'BooleanQuestion',
|
|
52
|
+
'Chart',
|
|
53
|
+
'CheckBoxes',
|
|
54
|
+
'DateField',
|
|
55
|
+
'DocumentUpload',
|
|
56
|
+
'Dropdown',
|
|
57
|
+
'Emoticons',
|
|
58
|
+
'ExpressionQuestion',
|
|
59
|
+
'FormatNumber',
|
|
60
|
+
'LinearScale',
|
|
61
|
+
'Link',
|
|
62
|
+
'QuestionGrid',
|
|
63
|
+
'RadioButtons',
|
|
64
|
+
'Readonly',
|
|
65
|
+
'Space',
|
|
66
|
+
'TextLong',
|
|
67
|
+
'TextShort',
|
|
68
|
+
'Title',
|
|
69
|
+
'Widget',
|
|
70
|
+
] as const
|
|
71
|
+
|
|
72
|
+
export type QuestionType = (typeof QUESTION_TYPES)[number]
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Only TextShort and TextLong carry one, and this is its whole vocabulary
|
|
76
|
+
* (`TextShortSubtype` in the legacy register). Typed rather than left open because an unrecognized
|
|
77
|
+
* subtype silently changes how an answer validates.
|
|
78
|
+
*/
|
|
79
|
+
export type QuestionSubtype = 'ORDINARY' | 'EMAIL'
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Written out in full rather than derived from the two arrays, so that `Record` makes TypeScript
|
|
83
|
+
* prove the table covers every legacy value — a derived table would need a cast, and the cast is
|
|
84
|
+
* exactly where a missing entry would hide.
|
|
85
|
+
*/
|
|
86
|
+
export const LEGACY_TO_V2_QUESTION_TYPE: Record<LegacyQuestionType, QuestionType> = {
|
|
87
|
+
BooleanQuestion: 'BooleanQuestion',
|
|
88
|
+
Chart: 'Chart',
|
|
89
|
+
CheckBoxes: 'CheckBoxes',
|
|
90
|
+
// The one rename in the whole register (OQ-V2-17): a "composite question" is a grid of
|
|
91
|
+
// questions, and the legacy name says nothing about that.
|
|
92
|
+
CompositeQuestion: 'QuestionGrid',
|
|
93
|
+
DateField: 'DateField',
|
|
94
|
+
DocumentUpload: 'DocumentUpload',
|
|
95
|
+
Dropdown: 'Dropdown',
|
|
96
|
+
Emoticons: 'Emoticons',
|
|
97
|
+
ExpressionQuestion: 'ExpressionQuestion',
|
|
98
|
+
FormatNumber: 'FormatNumber',
|
|
99
|
+
LinearScale: 'LinearScale',
|
|
100
|
+
Link: 'Link',
|
|
101
|
+
RadioButtons: 'RadioButtons',
|
|
102
|
+
Readonly: 'Readonly',
|
|
103
|
+
Space: 'Space',
|
|
104
|
+
TextLong: 'TextLong',
|
|
105
|
+
TextShort: 'TextShort',
|
|
106
|
+
Title: 'Title',
|
|
107
|
+
Widget: 'Widget',
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const V2_TO_LEGACY_QUESTION_TYPE = Object.fromEntries(
|
|
111
|
+
Object.entries(LEGACY_TO_V2_QUESTION_TYPE).map(([legacy, v2]) => [v2, legacy]),
|
|
112
|
+
) as Record<QuestionType, LegacyQuestionType>
|
|
113
|
+
|
|
114
|
+
export const isQuestionType = (value: unknown): value is QuestionType =>
|
|
115
|
+
typeof value === 'string' && (QUESTION_TYPES as readonly string[]).includes(value)
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Legacy → v2. Returns `undefined` for anything not in the register instead of passing the value
|
|
119
|
+
* through: an unmapped type reaching a document would be a question no editor can render, and the
|
|
120
|
+
* import has a report to record it in.
|
|
121
|
+
*/
|
|
122
|
+
export const toV2QuestionType = (legacy: string): QuestionType | undefined =>
|
|
123
|
+
LEGACY_TO_V2_QUESTION_TYPE[legacy as LegacyQuestionType]
|
|
124
|
+
|
|
125
|
+
/** v2 → legacy, for the projection that writes back to the legacy wire. Total by construction. */
|
|
126
|
+
export const toLegacyQuestionType = (type: QuestionType): LegacyQuestionType => V2_TO_LEGACY_QUESTION_TYPE[type]
|