asma-core-helpers 0.38.0 → 0.40.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 (40) hide show
  1. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  2. package/lib/collaboration/applyOperation.js +194 -0
  3. package/lib/collaboration/applyOperation.js.map +1 -1
  4. package/lib/collaboration/index.d.ts +1 -0
  5. package/lib/collaboration/index.d.ts.map +1 -1
  6. package/lib/collaboration/index.js +1 -0
  7. package/lib/collaboration/index.js.map +1 -1
  8. package/lib/collaboration/operations.d.ts +98 -0
  9. package/lib/collaboration/operations.d.ts.map +1 -1
  10. package/lib/collaboration/operations.js +4 -0
  11. package/lib/collaboration/operations.js.map +1 -1
  12. package/lib/collaboration/schemas.d.ts +138 -0
  13. package/lib/collaboration/schemas.d.ts.map +1 -1
  14. package/lib/collaboration/schemas.js +198 -10
  15. package/lib/collaboration/schemas.js.map +1 -1
  16. package/lib/collaboration/templateAuthoringMeta.d.ts +424 -0
  17. package/lib/collaboration/templateAuthoringMeta.d.ts.map +1 -0
  18. package/lib/collaboration/templateAuthoringMeta.js +726 -0
  19. package/lib/collaboration/templateAuthoringMeta.js.map +1 -0
  20. package/lib/collaboration/templateDocument.d.ts +136 -14
  21. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  22. package/lib/collaboration/templateDocument.js +19 -0
  23. package/lib/collaboration/templateDocument.js.map +1 -1
  24. package/lib/collaboration/testHelpers/documentGenerator.d.ts.map +1 -1
  25. package/lib/collaboration/testHelpers/documentGenerator.js +53 -0
  26. package/lib/collaboration/testHelpers/documentGenerator.js.map +1 -1
  27. package/lib/collaboration/typeContracts.d.ts +139 -0
  28. package/lib/collaboration/typeContracts.d.ts.map +1 -1
  29. package/package.json +1 -1
  30. package/src/collaboration/applyOperation.ts +251 -0
  31. package/src/collaboration/index.ts +1 -0
  32. package/src/collaboration/operations.ts +100 -0
  33. package/src/collaboration/property.test.ts +56 -1
  34. package/src/collaboration/schemas.test.ts +172 -1
  35. package/src/collaboration/schemas.ts +214 -9
  36. package/src/collaboration/templateAuthoringMeta.test.ts +1286 -0
  37. package/src/collaboration/templateAuthoringMeta.ts +1098 -0
  38. package/src/collaboration/templateDocument.ts +139 -14
  39. package/src/collaboration/testHelpers/documentGenerator.ts +60 -0
  40. package/src/collaboration/typeContracts.ts +155 -0
@@ -1,4 +1,5 @@
1
1
  import type { TemplateOp } from './operations.js';
2
+ import type { MetaField, SettingField } from './templateAuthoringMeta.js';
2
3
  import type { ActionMetadata, AlternativeChartLegend, LegacyBindingOverride, MappingBinding } from './templateDocument.js';
3
4
  /**
4
5
  * Compile-time assertions that the closed unions stay closed.
@@ -121,5 +122,143 @@ export type LegacyOverrideMemberStaysUnknown = Assert<Refuses<MappingBinding['le
121
122
  * a canonical value must still be assignable *into* the member.
122
123
  */
123
124
  export type LegacyOverrideMemberAcceptsCanonical = Assert<Refuses<LegacyBindingOverride, MappingBinding['legacyOverride']> extends false ? true : false>;
125
+ /**
126
+ * An arbitrary path must not type-check.
127
+ *
128
+ * This is the assertion that keeps `template.setMetaFieldTyped` from degenerating into the open arm it
129
+ * sits beside: a `field: string` would admit `meta`, a settings group, the import-only `legacy`
130
+ * residue and every unknown member of an imported bag, and the reducer would be the only thing
131
+ * standing between a client and a wholesale metadata overwrite.
132
+ */
133
+ export type SetMetaFieldRefusesArbitraryPath = Assert<Refuses<{
134
+ type: 'template.setMetaFieldTyped';
135
+ field: 'legacy.plan_category';
136
+ value: 'x';
137
+ }, TemplateOp>>;
138
+ /** The import-only residue is not an authoring field, which `MetaField` itself must say. */
139
+ export type MetaFieldExcludesLegacyResidue = Assert<Refuses<'legacy.plan_category', MetaField>>;
140
+ /**
141
+ * A value from the wrong field must not type-check.
142
+ *
143
+ * The correlation is the reason the arms are per-field rather than one `{field; value}` pair: without
144
+ * it `{field: 'visibility', value: 'coordinator'}` compiles, lands in a document, and reaches an
145
+ * immutable version before anything notices.
146
+ */
147
+ export type SetMetaFieldRefusesCrossFieldValue = Assert<Refuses<{
148
+ type: 'template.setMetaFieldTyped';
149
+ field: 'visibility';
150
+ value: 'coordinator';
151
+ }, TemplateOp>>;
152
+ export type SetMetaFieldRefusesWrongPrimitive = Assert<Refuses<{
153
+ type: 'template.setMetaFieldTyped';
154
+ field: 'title';
155
+ value: 42;
156
+ }, TemplateOp>>;
157
+ export type SetMetaFieldRefusesOutOfRangeAccessLevel = Assert<Refuses<{
158
+ type: 'template.setMetaFieldTyped';
159
+ field: 'instancePolicy.requiredAccessLevel';
160
+ value: 5;
161
+ }, TemplateOp>>;
162
+ /** Each legal pair, and the `null` unset, must stay legal or the refusals above prove nothing. */
163
+ export type SetMetaFieldAcceptsLegalPairs = Assert<Refuses<{
164
+ type: 'template.setMetaFieldTyped';
165
+ field: 'visibility';
166
+ value: 'hidden';
167
+ }, TemplateOp> extends false ? Refuses<{
168
+ type: 'template.setMetaFieldTyped';
169
+ field: 'instancePolicy.initiator';
170
+ value: 'recipient';
171
+ }, TemplateOp> extends false ? Refuses<{
172
+ type: 'template.setMetaFieldTyped';
173
+ field: 'instancePolicy.requiredAccessLevel';
174
+ value: 1;
175
+ }, TemplateOp> extends false ? Refuses<{
176
+ type: 'template.setMetaFieldTyped';
177
+ field: 'title';
178
+ value: null;
179
+ }, TemplateOp> extends false ? true : false : false : false : false>;
180
+ /**
181
+ * A typed arm must not accept the OPEN arm's payload member.
182
+ *
183
+ * Without the `patch?: never` exclusions, `{type: 'template.setSettingTyped', field, value, patch}`
184
+ * is structurally assignable — TypeScript admits extra properties on a non-fresh object — so a client
185
+ * assembling an op by spreading an old payload would ship a member nothing refuses until the wire
186
+ * schema's `'+': 'reject'`, and nothing at all on a replayed log.
187
+ */
188
+ export type SetSettingRefusesOpenArmPayload = Assert<Refuses<{
189
+ type: 'template.setSettingTyped';
190
+ field: 'rendering.tabs';
191
+ value: true;
192
+ patch: Record<string, string>;
193
+ }, TemplateOp>>;
194
+ /** A membership payload must not satisfy a leaf arm, or vice versa. */
195
+ export type SetSettingRefusesMembershipPayload = Assert<Refuses<{
196
+ type: 'template.setSettingTyped';
197
+ field: 'rendering.tabs';
198
+ value: true;
199
+ collection: 'consentTemplateIds';
200
+ id: 'c-1';
201
+ }, TemplateOp>>;
202
+ export type AddCompatibilityIdRefusesLeafPayload = Assert<Refuses<{
203
+ type: 'template.addCompatibilityId';
204
+ collection: 'consentTemplateIds';
205
+ id: 'c-1';
206
+ field: 'rendering.tabs';
207
+ value: true;
208
+ }, TemplateOp>>;
209
+ export type SetSettingRefusesUnknownLeaf = Assert<Refuses<{
210
+ type: 'template.setSettingTyped';
211
+ field: 'rendering.not_a_flag';
212
+ value: true;
213
+ }, TemplateOp>>;
214
+ export type SetSettingRefusesNonBoolean = Assert<Refuses<{
215
+ type: 'template.setSettingTyped';
216
+ field: 'rendering.tabs';
217
+ value: 'true';
218
+ }, TemplateOp>>;
219
+ export type SettingFieldExcludesReleasedPhoneSpelling = Assert<Refuses<'recipient.ask_for_phone_nr', SettingField>>;
220
+ export type AddCompatibilityIdRefusesUnknownCollection = Assert<Refuses<{
221
+ type: 'template.addCompatibilityId';
222
+ collection: 'journalTemplateIds';
223
+ id: 'c-1';
224
+ }, TemplateOp>>;
225
+ export type CompatibilityMembershipAcceptsLegalShapes = Assert<Refuses<{
226
+ type: 'template.addCompatibilityId';
227
+ collection: 'consentTemplateIds';
228
+ id: '42';
229
+ }, TemplateOp> extends false ? Refuses<{
230
+ type: 'template.removeCompatibilityId';
231
+ collection: 'smsTemplateIds';
232
+ id: 'sms-1';
233
+ }, TemplateOp> extends false ? true : false : false>;
234
+ /**
235
+ * The two RELEASED open arms must stay open.
236
+ *
237
+ * The one assertion here that guards against a plausible well-meant change rather than a mistake:
238
+ * narrowing `template.updateMeta`/`template.updateSettings` to the new closed vocabulary would look
239
+ * like tightening and would in fact make every already-stored `collab_ops` log unreplayable and every
240
+ * immutable version unverifiable, because the legacy importer and the released client wrote arbitrary
241
+ * dotted patches through exactly these arms.
242
+ */
243
+ /**
244
+ * The patches below carry ONLY unrecognized keys, deliberately. A patch that also carried a known key
245
+ * would still be assignable to an arm narrowed to just that key, so the probe would pass over exactly
246
+ * the narrowing it exists to catch — verified by seeding `patch: Record<'title', OpValue>` and
247
+ * watching the weaker form stay green.
248
+ */
249
+ export type UpdateMetaStaysOpen = Assert<Refuses<{
250
+ type: 'template.updateMeta';
251
+ patch: {
252
+ 'some.unknown.legacy_flag': true;
253
+ security_level: 3;
254
+ };
255
+ }, TemplateOp> extends false ? true : false>;
256
+ export type UpdateSettingsStaysOpen = Assert<Refuses<{
257
+ type: 'template.updateSettings';
258
+ patch: {
259
+ ask_for_phone_nr: true;
260
+ tab_mode: false;
261
+ };
262
+ }, TemplateOp> extends false ? true : false>;
124
263
  export {};
125
264
  //# sourceMappingURL=typeContracts.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"typeContracts.d.ts","sourceRoot":"","sources":["../../src/collaboration/typeContracts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,KAAK,EACR,cAAc,EACd,sBAAsB,EACtB,qBAAqB,EACrB,cAAc,EACjB,MAAM,uBAAuB,CAAA;AAE9B;;;;;;;;;;GAUG;AAEH,qDAAqD;AACrD,KAAK,MAAM,CAAC,CAAC,SAAS,IAAI,IAAI,CAAC,CAAA;AAE/B,iGAAiG;AACjG,KAAK,OAAO,CAAC,SAAS,EAAE,MAAM,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,KAAK,GAAG,IAAI,CAAA;AAK7E,MAAM,MAAM,0CAA0C,GAAG,MAAM,CAC3D,OAAO,CACH;IAAE,IAAI,EAAE,oBAAoB,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,gBAAgB,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,EAC5G,UAA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AC,cAAc,EAAE,CAAC,CAAA;KAAE,CAAA;CAAE,EAC/F,UAAU,CACb,SAAS,KAAK,GACT,IAAI,GACJ,KAAK,CACd,CAAA;AACD,MAAM,MAAM,uBAAuB,GAAG,MAAM,CACxC,OAAO,CAAC;IAAE,IAAI,EAAE,yBAAyB,CAAC;IAAC,KAAK,EAAE;QAAE,gBAAgB,EAAE,IAAI,CAAC;QAAC,QAAQ,EAAE,KAAK,CAAA;KAAE,CAAA;CAAE,EAAE,UAAU,CAAC,SAAS,KAAK,GACpH,IAAI,GACJ,KAAK,CACd,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asma-core-helpers",
3
- "version": "0.38.0",
3
+ "version": "0.40.0",
4
4
  "description": "Core helper utilities for ASMA applications",
5
5
  "files": [
6
6
  "lib/**/*",
@@ -17,9 +17,25 @@ import type {
17
17
  QnrQuestion,
18
18
  QnrTab,
19
19
  QnrTemplateDocument,
20
+ QnrTemplateMeta,
20
21
  QuestionId,
21
22
  } from './templateDocument.js'
22
23
  import type { QuestionType } from './questionTypes.js'
24
+ import type { JsonValue } from './canonicalize.js'
25
+ import type { CompatibilityCollection } from './templateAuthoringMeta.js'
26
+ import {
27
+ isCompatibilityCollection,
28
+ isMetaField,
29
+ isSettingField,
30
+ isTemplateAuthoringDefault,
31
+ metaFieldPath,
32
+ normalizeCompatibilityId,
33
+ normalizeCompatibilityIds,
34
+ parseCompatibilityOperationId,
35
+ parseMetaFieldValue,
36
+ settingFieldPath,
37
+ templateAliasPathsOf,
38
+ } from './templateAuthoringMeta.js'
23
39
  import {
24
40
  ACTION_TYPES,
25
41
  BINDING_OPTION_DEFAULTS,
@@ -128,6 +144,154 @@ const writeField = <T extends Record<string, unknown>>(record: T, field: string,
128
144
  return next as T
129
145
  }
130
146
 
147
+ // ─────────────── ASMA-8339: the typed metadata/settings write boundary ───────────────
148
+
149
+ /** A container the reducer may descend into. `null` and an array are neither. */
150
+ const isPlainRecord = (value: unknown): value is Record<string, unknown> => {
151
+ if (typeof value !== 'object' || value === null) return false
152
+ const proto = Object.getPrototypeOf(value)
153
+ return proto === Object.prototype || proto === null
154
+ }
155
+
156
+ /**
157
+ * Refuses an operation carrying a payload member outside its closed vocabulary.
158
+ *
159
+ * Re-checked in the reducer and not only at the wire schema, for the reason the ASMA-7683 hardening
160
+ * pass recorded: bunjs replays a stored `collab_ops` log without re-validating each op, so anything
161
+ * the reducer alone permits is reachable by an op written by an older or bypassed client — and unlike
162
+ * a rejected request, it lands in a document and then in an immutable artifact.
163
+ *
164
+ * Keys holding `undefined` are ignored. They carry nothing, cannot survive JSON transport, and
165
+ * refusing them would reject an ordinary `{...base, patch: undefined}` spread.
166
+ */
167
+ const assertClosedPayload = (op: object, allowed: readonly string[]): void => {
168
+ const carried = Object.entries(op as Record<string, unknown>).filter(([, value]) => value !== undefined)
169
+ const extra = carried.map(([key]) => key).filter((key) => !allowed.includes(key))
170
+ if (extra.length > 0) {
171
+ throw new OperationConflictError(
172
+ `Operation "${String((op as Record<string, unknown>)['type'])}" carries unrecognized payload member(s): ${extra
173
+ .map((key) => `"${key}"`)
174
+ .join(', ')}`,
175
+ )
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Canonical loci are document-absolute; the reducer writes into `meta` itself.
181
+ *
182
+ * The guard is not ceremony. A bare `slice(5)` turns a meta-RELATIVE path into silent nonsense
183
+ * (`settings.refresh_button` becomes `ngs.refresh_button`), which then writes to a path no reader
184
+ * looks at and clears no alias — a mutation seeded during review survived the suite for exactly this
185
+ * reason. Failing loudly makes a mis-anchored path a refusal instead of a quiet no-op.
186
+ */
187
+ const metaRelativePath = (documentPath: string): string => {
188
+ if (!documentPath.startsWith('meta.')) {
189
+ throw new OperationConflictError(`"${documentPath}" is not a document-absolute metadata path`)
190
+ }
191
+ return documentPath.slice('meta.'.length)
192
+ }
193
+
194
+ /**
195
+ * Refuses a typed write whose owned ancestor holds something that is not a container.
196
+ *
197
+ * `writeField` creates intermediate objects, so it would REPLACE an imported scalar or array sitting
198
+ * at `meta.settings.rendering` — silently destroying residue this contract is required to preserve.
199
+ * Repairing a malformed owned container is import/publication work, and the released open
200
+ * `template.updateMeta`/`template.updateSettings` arms remain available to clear it, so refusing here
201
+ * loses no capability and is the only non-destructive answer.
202
+ */
203
+ const assertWritableMetaAncestors = (meta: Record<string, unknown>, relativePath: string): void => {
204
+ const segments = relativePath.split('.')
205
+ let current: Record<string, unknown> = meta
206
+ let walked = 'meta'
207
+ for (const segment of segments.slice(0, -1)) {
208
+ walked = `${walked}.${segment}`
209
+ if (!Object.hasOwn(current, segment)) return
210
+ const child = current[segment]
211
+ if (child === undefined) return
212
+ if (!isPlainRecord(child)) {
213
+ throw new OperationConflictError(
214
+ `"${walked}" holds ${Array.isArray(child) ? 'an array' : `a ${typeof child}`}, not a container; ` +
215
+ `the typed metadata operations refuse to overwrite imported residue`,
216
+ )
217
+ }
218
+ current = child
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Writes one canonical metadata leaf: clears its recognized old spellings, then stores the value or
224
+ * omits it.
225
+ *
226
+ * **Alias clearing happens first and unconditionally, and that ordering is the whole point.** Writing
227
+ * `recipient.requires_phone_number: false` stores nothing, because `false` is the declared default —
228
+ * so without the clear a stale `ask_for_phone_nr: true` would still be in the document and the total
229
+ * reader's alias fallback would read the requirement back ON, silently reversing the author's
230
+ * explicit "off". Only the field's OWN recognized aliases are touched: every unrelated unknown member
231
+ * of the same bag is left exactly where the import put it.
232
+ *
233
+ * Restoring a default and an explicit `null` are the same write, because DOC-LAW-2 makes absence the
234
+ * only encoding of "not set" — an author who clicks back to `coordinator` and an author who never
235
+ * touched the control must produce byte-identical documents, or one authored state would carry two
236
+ * `document_hash` values.
237
+ */
238
+ const writeCanonicalMetaLeaf = (
239
+ meta: Record<string, unknown>,
240
+ canonicalPath: string,
241
+ value: JsonValue | null,
242
+ ): Record<string, unknown> => {
243
+ const relative = metaRelativePath(canonicalPath)
244
+ const aliasPaths = templateAliasPathsOf(canonicalPath).map(metaRelativePath)
245
+ for (const path of [relative, ...aliasPaths]) assertWritableMetaAncestors(meta, path)
246
+
247
+ let next = meta
248
+ for (const path of aliasPaths) next = writeField(next, path, null)
249
+
250
+ const stored = value === null || isTemplateAuthoringDefault(canonicalPath, value) ? null : value
251
+ return writeField(next, relative, stored)
252
+ }
253
+
254
+ /**
255
+ * The stored soft-id set as canonical members, or a refusal.
256
+ *
257
+ * Refuses rather than repairs when the collection is not an array, or carries a member that is not a
258
+ * soft id (an object, `null`, a non-finite number, an empty string). Normalising around such a member
259
+ * would drop it, which is silent data loss in a hashed document; the total reader reports the same
260
+ * condition as a `malformed-collection` finding, so an author sees why the control is blocked.
261
+ */
262
+ const readCompatibilitySet = (meta: Record<string, unknown>, collection: CompatibilityCollection): string[] => {
263
+ const compatibility = meta['compatibility']
264
+ if (compatibility === undefined) return []
265
+ if (!isPlainRecord(compatibility)) {
266
+ throw new OperationConflictError(`"meta.compatibility" holds a ${typeof compatibility}, not a container`)
267
+ }
268
+ const stored = compatibility[collection]
269
+ if (stored === undefined) return []
270
+ if (!Array.isArray(stored)) {
271
+ throw new OperationConflictError(
272
+ `"meta.compatibility.${collection}" holds a ${typeof stored}, not an array of soft ids`,
273
+ )
274
+ }
275
+ return stored.map((member, index) => {
276
+ const normalized = normalizeCompatibilityId(member)
277
+ if (normalized === undefined) {
278
+ throw new OperationConflictError(
279
+ `"meta.compatibility.${collection}.${index}" is not a soft id; the typed membership ` +
280
+ `operations refuse to normalize a malformed imported set`,
281
+ )
282
+ }
283
+ return normalized
284
+ })
285
+ }
286
+
287
+ /** Stores a soft-id set in canonical form, or drops the key when the last member left (DOC-LAW-2). */
288
+ const writeCompatibilitySet = (
289
+ meta: Record<string, unknown>,
290
+ collection: CompatibilityCollection,
291
+ ids: readonly string[],
292
+ ): Record<string, unknown> =>
293
+ writeField(meta, `compatibility.${collection}`, ids.length === 0 ? null : [...ids])
294
+
131
295
  /** Inserts `id` at `index`, clamped into range. Absent index appends. */
132
296
  const insertAt = (order: readonly string[], id: string, index?: number): string[] => {
133
297
  const next = [...order]
@@ -1369,6 +1533,93 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
1369
1533
  return { ...doc, meta }
1370
1534
  }
1371
1535
 
1536
+ case 'template.setMetaFieldTyped': {
1537
+ assertClosedPayload(op, ['type', 'field', 'value'])
1538
+ // Re-validated on replay: the closed path and its correlated value type live in the
1539
+ // registry, and an op from an older or bypassed client reaches this switch with no
1540
+ // validator in front of it.
1541
+ if (!isMetaField(op.field)) {
1542
+ throw new OperationConflictError(
1543
+ `"${String(op.field)}" is not an editable template metadata field`,
1544
+ )
1545
+ }
1546
+ if (op.value !== null && parseMetaFieldValue(op.field, op.value) === undefined) {
1547
+ throw new OperationConflictError(
1548
+ `${JSON.stringify(op.value)} is not a valid value for metadata field "${op.field}"`,
1549
+ )
1550
+ }
1551
+ const meta = writeCanonicalMetaLeaf(
1552
+ { ...(doc.meta ?? {}) },
1553
+ metaFieldPath(op.field),
1554
+ op.value,
1555
+ ) as QnrTemplateMeta
1556
+ return { ...doc, meta }
1557
+ }
1558
+
1559
+ case 'template.setSettingTyped': {
1560
+ assertClosedPayload(op, ['type', 'field', 'value'])
1561
+ if (!isSettingField(op.field)) {
1562
+ throw new OperationConflictError(`"${String(op.field)}" is not a template settings leaf`)
1563
+ }
1564
+ // Explicitly type-checked rather than coerced: a legacy `'false'` string is a MALFORMED
1565
+ // known value, and JavaScript truthiness would read it as the opposite of what it says.
1566
+ if (op.value !== null && typeof op.value !== 'boolean') {
1567
+ throw new OperationConflictError(
1568
+ `Setting "${op.field}" takes a boolean or null, not ${typeof op.value}`,
1569
+ )
1570
+ }
1571
+ const meta = writeCanonicalMetaLeaf(
1572
+ { ...(doc.meta ?? {}) },
1573
+ settingFieldPath(op.field),
1574
+ op.value,
1575
+ ) as QnrTemplateMeta
1576
+ return { ...doc, meta }
1577
+ }
1578
+
1579
+ case 'template.addCompatibilityId': {
1580
+ assertClosedPayload(op, ['type', 'collection', 'id'])
1581
+ if (!isCompatibilityCollection(op.collection)) {
1582
+ throw new OperationConflictError(`"${String(op.collection)}" is not a compatibility collection`)
1583
+ }
1584
+ // Strict on a NEW payload, where the wire schema says `string > 0`: a numeric id is
1585
+ // tolerated only when READING a stored legacy member. Accepting one here would let an op
1586
+ // the schema refuses land anyway through a replayed log.
1587
+ const id = parseCompatibilityOperationId(op.id)
1588
+ if (id === undefined) {
1589
+ throw new OperationConflictError(
1590
+ `template.addCompatibilityId requires a nonempty string soft id, not ${typeof op.id}`,
1591
+ )
1592
+ }
1593
+ const meta = { ...(doc.meta ?? {}) } as Record<string, unknown>
1594
+ // Adding an id already present yields the identical set: content-idempotent, so no new
1595
+ // canonical bytes and no spurious version.
1596
+ const members = normalizeCompatibilityIds([...readCompatibilitySet(meta, op.collection), id])
1597
+ return { ...doc, meta: writeCompatibilitySet(meta, op.collection, members) as QnrTemplateMeta }
1598
+ }
1599
+
1600
+ case 'template.removeCompatibilityId': {
1601
+ assertClosedPayload(op, ['type', 'collection', 'id'])
1602
+ if (!isCompatibilityCollection(op.collection)) {
1603
+ throw new OperationConflictError(`"${String(op.collection)}" is not a compatibility collection`)
1604
+ }
1605
+ // Strict on a NEW payload, where the wire schema says `string > 0`: a numeric id is
1606
+ // tolerated only when READING a stored legacy member. Accepting one here would let an op
1607
+ // the schema refuses land anyway through a replayed log.
1608
+ const id = parseCompatibilityOperationId(op.id)
1609
+ if (id === undefined) {
1610
+ throw new OperationConflictError(
1611
+ `template.removeCompatibilityId requires a nonempty string soft id, not ${typeof op.id}`,
1612
+ )
1613
+ }
1614
+ const meta = { ...(doc.meta ?? {}) } as Record<string, unknown>
1615
+ // Removing an absent id is a no-op, which is what makes remove/remove of one id converge.
1616
+ const members = readCompatibilitySet(meta, op.collection).filter((member) => member !== id)
1617
+ return {
1618
+ ...doc,
1619
+ meta: writeCompatibilitySet(meta, op.collection, normalizeCompatibilityIds(members)) as QnrTemplateMeta,
1620
+ }
1621
+ }
1622
+
1372
1623
  case 'question.create': {
1373
1624
  if (doc.questionsById?.[op.questionId]) {
1374
1625
  throw new OperationConflictError(`Question "${op.questionId}" already exists`)
@@ -24,6 +24,7 @@
24
24
 
25
25
  export * from './questionTypes.js'
26
26
  export * from './templateDocument.js'
27
+ export * from './templateAuthoringMeta.js'
27
28
  export * from './answerDocument.js'
28
29
  export * from './operations.js'
29
30
  export * from './answerOperations.js'
@@ -26,6 +26,11 @@ import type {
26
26
  VisibilityRuleId,
27
27
  } from './templateDocument.js'
28
28
  import type { QuestionType } from './questionTypes.js'
29
+ import type {
30
+ CompatibilityCollection,
31
+ SettingField,
32
+ TemplateMetaFieldWrite,
33
+ } from './templateAuthoringMeta.js'
29
34
 
30
35
  /**
31
36
  * The authoring op vocabulary (architecture §5). `entity.action`, stable-id targets only, append-only —
@@ -51,6 +56,16 @@ import type { QuestionType } from './questionTypes.js'
51
56
  */
52
57
  export type OpValue = DocScalar | DocScalar[] | null
53
58
 
59
+ /**
60
+ * Makes each correlated metadata field/value pair nullable, one arm at a time.
61
+ *
62
+ * Distributive on purpose: `{field: F; value: V} | {field: G; value: W}` must become
63
+ * `{field: F; value: V | null} | {field: G; value: W | null}`, not the collapsed
64
+ * `{field: F | G; value: V | W | null}` — the collapsed form is exactly the loose pair this operation
65
+ * exists to avoid, and it would type-check a value from the wrong field.
66
+ */
67
+ type MetaFieldUnset<W> = W extends { field: infer F; value: infer V } ? { field: F; value: V | null } : never
68
+
54
69
  export type TemplateOp =
55
70
  | { type: 'template.updateMeta'; patch: Record<string, OpValue | Record<string, unknown>> }
56
71
  | {
@@ -58,6 +73,87 @@ export type TemplateOp =
58
73
  /** Dotted-path patch into `meta.settings` (journal wiring, recipient requirements). */
59
74
  patch: Record<string, OpValue | Record<string, unknown>>
60
75
  }
76
+ /**
77
+ * Writes ONE metadata leaf, or restores its default (ASMA-8339).
78
+ *
79
+ * **Additive beside the two open arms above, which stay exactly as released.** Those arms accept an
80
+ * arbitrary dotted patch, which is what lets an already-stored `collab_ops` log replay byte-for-byte
81
+ * and what the legacy importer wrote through; narrowing them now would make old logs unreplayable and
82
+ * old immutable versions unverifiable (ADR-0008 DEC-006). So the new authoring path is closed and the
83
+ * old replay path is open, and the authoring app emits only these four arms for this surface.
84
+ *
85
+ * Closed in three senses, each of which a loose `{field: string; value: OpValue}` would lose:
86
+ *
87
+ * 1. **The path is one of seven**, not an arbitrary dotted path — so no operation can reach `meta`
88
+ * wholesale, a settings group, an owner-domain body, the import-only `legacy` residue, or a
89
+ * coincidentally-named unknown member.
90
+ * 2. **The value is correlated with the path** ({@link TemplateMetaFieldWrite}), so
91
+ * `{field: 'visibility', value: 7}` is a compile error rather than a runtime refusal.
92
+ * 3. **No extra payload member is admitted** — `patch`/`collection`/`id` are excluded with `?: never`
93
+ * so an open-arm or membership payload cannot structurally satisfy this arm, and the schema adds
94
+ * `'+': 'reject'` for the wire.
95
+ *
96
+ * `null` restores the default: the leaf is deleted and every ancestor it emptied is pruned, because
97
+ * DOC-LAW-2 makes absence the only encoding of "not set". Writing a value that EQUALS the default does
98
+ * the same thing, so an author who clicks back to `coordinator` and an author who never touched the
99
+ * control produce byte-identical documents.
100
+ */
101
+ | ({
102
+ type: 'template.setMetaFieldTyped'
103
+ patch?: never
104
+ collection?: never
105
+ id?: never
106
+ } & MetaFieldUnset<TemplateMetaFieldWrite>)
107
+ /**
108
+ * Writes ONE settings leaf, or restores its default (ASMA-8339).
109
+ *
110
+ * **A leaf operation, deliberately not a group patch.** A form submit may batch every changed leaf
111
+ * atomically through the existing endpoint, but it must never send a settings group or a hydrated
112
+ * snapshot: two authors editing different flags of one group would then produce two whole-group
113
+ * writes and the second would silently discard the first — the same lost update DOC-LAW-1 keys
114
+ * collections to prevent. Per-leaf writes make those two edits touch two paths instead, so they
115
+ * commute.
116
+ *
117
+ * All 23 leaves are booleans, so the value needs no correlation with the path; `null` restores the
118
+ * default, as does writing the default itself.
119
+ */
120
+ | {
121
+ type: 'template.setSettingTyped'
122
+ field: SettingField
123
+ value: boolean | null
124
+ patch?: never
125
+ collection?: never
126
+ id?: never
127
+ }
128
+ /**
129
+ * Adds one owner-domain soft id to a compatibility set (REQ-013).
130
+ *
131
+ * Membership rather than a whole-array write, for the concurrency reason: two authors adding
132
+ * different consent templates both survive. Different ids therefore commute even inside one
133
+ * collection, and adding an id already present is content-idempotent — the stored set is unchanged,
134
+ * so no new hash and no new version.
135
+ *
136
+ * Ids are nonempty strings, **not** UUIDs: legacy template ids are integers and are preserved by
137
+ * their lossless decimal spelling. No owner body is accepted or stored, and no FK lookup is
138
+ * required — an imported dangling id stays visible instead of being dropped for failing a join.
139
+ */
140
+ | {
141
+ type: 'template.addCompatibilityId'
142
+ collection: CompatibilityCollection
143
+ id: string
144
+ patch?: never
145
+ field?: never
146
+ value?: never
147
+ }
148
+ /** Removes one soft id. Removing an absent id is a no-op; an emptied set is omitted (DOC-LAW-2). */
149
+ | {
150
+ type: 'template.removeCompatibilityId'
151
+ collection: CompatibilityCollection
152
+ id: string
153
+ patch?: never
154
+ field?: never
155
+ value?: never
156
+ }
61
157
  // `questionType`, not `type`: the envelope already owns `type` for the op name, so the question's
62
158
  // own type (which is what lands in the document) needs a distinct key here.
63
159
  | { type: 'question.create'; questionId: QuestionId; questionType: QuestionType; atIndex?: number }
@@ -369,6 +465,10 @@ export type TemplateOpType = TemplateOp['type']
369
465
  const OP_TYPE_COVERAGE: Record<TemplateOpType, true> = {
370
466
  'template.updateMeta': true,
371
467
  'template.updateSettings': true,
468
+ 'template.setMetaFieldTyped': true,
469
+ 'template.setSettingTyped': true,
470
+ 'template.addCompatibilityId': true,
471
+ 'template.removeCompatibilityId': true,
372
472
  'question.create': true,
373
473
  'question.updateField': true,
374
474
  'question.move': true,