@openplanr/protocol 0.6.1 → 0.6.2

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 (55) hide show
  1. package/lib/dashboard/closed-json-contract.mjs +99 -109
  2. package/lib/dashboard/operate-experience-audit-display-contract.d.mts +128 -153
  3. package/lib/dashboard/operate-experience-audit-display-contract.mjs +530 -585
  4. package/lib/dashboard/operate-experience-display-contract.d.mts +415 -437
  5. package/lib/dashboard/operate-experience-display-contract.mjs +768 -831
  6. package/lib/dashboard/operate-experience-surface-contract.d.mts +143 -148
  7. package/lib/dashboard/operate-experience-surface-contract.mjs +72 -73
  8. package/lib/dashboard/operate-review-contract.d.mts +7 -14
  9. package/lib/dashboard/operate-review-contract.mjs +46 -42
  10. package/lib/dashboard/operate-review-display-workspace-contract.d.mts +2 -5
  11. package/lib/dashboard/operate-review-display-workspace-contract.mjs +158 -104
  12. package/lib/dashboard/operate-review-payload-safety.mjs +4 -2
  13. package/lib/dashboard/operate-review-workspace-projection-v2.d.mts +47 -33
  14. package/lib/protocol/index.d.ts +2647 -543
  15. package/package.json +1 -1
  16. package/registries/commands.json +3 -3
  17. package/registries/skills.json +5 -5
  18. package/src/browser-contracts.d.mts +4 -1
  19. package/src/browser-contracts.mjs +16 -5
  20. package/src/canonical-json.d.mts +3 -1
  21. package/src/canonical-json.mjs +57 -20
  22. package/src/compat/live-evidence-v2.mjs +1604 -485
  23. package/src/compat/operate-experience-live-patch.mjs +67 -15
  24. package/src/compat/operating-planning-contracts.mjs +183 -51
  25. package/src/contracts.d.mts +54 -13
  26. package/src/contracts.mjs +625 -335
  27. package/src/design-contracts.mjs +58 -21
  28. package/src/design-handoff-contracts.d.mts +67 -11
  29. package/src/design-handoff-contracts.mjs +243 -98
  30. package/src/design-publication-contracts.mjs +98 -33
  31. package/src/diagram-authoring-contracts.d.mts +422 -78
  32. package/src/diagram-authoring-contracts.mjs +1697 -326
  33. package/src/diagram-contracts.d.mts +4 -1
  34. package/src/diagram-contracts.mjs +16 -4
  35. package/src/enterprise-contracts.d.mts +211 -46
  36. package/src/enterprise-contracts.mjs +727 -175
  37. package/src/errors.mjs +4 -0
  38. package/src/generated/canonical-registries.mjs +8 -8
  39. package/src/index.d.mts +8 -8
  40. package/src/index.mjs +36 -20
  41. package/src/json-schema.d.mts +21 -6
  42. package/src/json-schema.mjs +66 -18
  43. package/src/planning-contracts.d.mts +8 -2
  44. package/src/planning-contracts.mjs +33 -7
  45. package/src/registries.d.mts +11 -3
  46. package/src/registries.mjs +369 -87
  47. package/src/review-experience-contracts.d.mts +7 -2
  48. package/src/review-experience-contracts.mjs +198 -49
  49. package/src/semver.mjs +5 -1
  50. package/src/skill-source-contracts.d.mts +36 -16
  51. package/src/skill-source-contracts.mjs +25 -6
  52. package/src/task-contracts.d.mts +13 -3
  53. package/src/task-contracts.mjs +181 -40
  54. package/src/workspace-contracts.d.mts +38 -10
  55. package/src/workspace-contracts.mjs +147 -33
@@ -1,10 +1,15 @@
1
- import { canonicalizeJson, sha256Jcs, sha256Hex } from './canonical-json.mjs';
2
- import { validateJson } from './json-schema.mjs';
1
+ // @ts-check
2
+ import { canonicalizeJson, sha256Hex, sha256Jcs } from './canonical-json.mjs';
3
3
  import { DIAGRAM_REGISTRIES } from './generated/diagram-registries.mjs';
4
4
  import { LEGACY_DIAGRAM_DOCUMENT_SCHEMA } from './generated/legacy-diagram-schema.mjs';
5
+ import { validateJson } from './json-schema.mjs';
5
6
 
6
- /** Portable, inert data contracts. Validation confers no authorization or readiness. */
7
+ /**
8
+ * Portable, inert data contracts. Validation confers no authorization or readiness.
9
+ * @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_AUTHORING_PROTOCOL_VERSION}
10
+ */
7
11
  export const DIAGRAM_AUTHORING_PROTOCOL_VERSION = '1.13.0';
12
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_AUTHORING_CONTRACT_VERSION} */
8
13
  export const DIAGRAM_AUTHORING_CONTRACT_VERSION = '1.0.0';
9
14
  const deepFreeze = (value) => {
10
15
  if (value && typeof value === 'object' && !Object.isFrozen(value)) {
@@ -13,47 +18,117 @@ const deepFreeze = (value) => {
13
18
  }
14
19
  return value;
15
20
  };
21
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_EDIT_OPERATION_CLASSES} */
16
22
  export const DIAGRAM_EDIT_OPERATION_CLASSES = deepFreeze([
17
- 'insert-elements', 'update-semantics', 'remove-elements', 'set-membership-order',
18
- 'set-geometry', 'set-appearance-locks',
23
+ 'insert-elements',
24
+ 'update-semantics',
25
+ 'remove-elements',
26
+ 'set-membership-order',
27
+ 'set-geometry',
28
+ 'set-appearance-locks',
19
29
  ]);
30
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_AUTHORING_LIMITS} */
20
31
  export const DIAGRAM_AUTHORING_LIMITS = deepFreeze({
21
- depth: 48, values: 500000, textCodeUnits: 8388608, sourceBytes: 1048576,
22
- elements: 10000, operations: 256, coordinate: 1000000,
32
+ depth: 48,
33
+ values: 500000,
34
+ textCodeUnits: 8388608,
35
+ sourceBytes: 1048576,
36
+ elements: 10000,
37
+ operations: 256,
38
+ coordinate: 1000000,
23
39
  });
24
40
 
25
- const closed = (properties, required = Object.keys(properties)) => ({ type: 'object', additionalProperties: false, properties, required });
26
- const arr = (items, maxItems, minItems = 0, uniqueItems = false) => ({ type: 'array', items, minItems, maxItems, ...(uniqueItems ? { uniqueItems } : {}) });
41
+ const closed = (properties, required = Object.keys(properties)) => ({
42
+ type: 'object',
43
+ additionalProperties: false,
44
+ properties,
45
+ required,
46
+ });
47
+ const arr = (items, maxItems, minItems = 0, uniqueItems = false) => ({
48
+ type: 'array',
49
+ items,
50
+ minItems,
51
+ maxItems,
52
+ ...(uniqueItems ? { uniqueItems } : {}),
53
+ });
27
54
  const nullable = (schema) => ({ anyOf: [{ type: 'null' }, schema] });
28
55
  const str = (maxLength = 4096, minLength = 0) => ({ type: 'string', minLength, maxLength });
29
56
  const enumOf = (...values) => ({ enum: values });
30
- const id = { type: 'string', pattern: '^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$', minLength: 1, maxLength: 128 };
57
+ const id = {
58
+ type: 'string',
59
+ pattern: '^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$',
60
+ minLength: 1,
61
+ maxLength: 128,
62
+ };
31
63
  const digest = { type: 'string', pattern: '^sha256:[a-f0-9]{64}$' };
32
64
  const token = { type: 'string', pattern: '^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$', maxLength: 64 };
33
- const relativePath = { type: 'string', minLength: 1, maxLength: 1024, pattern: '^[A-Za-z0-9][A-Za-z0-9._/-]*$' };
65
+ const relativePath = {
66
+ type: 'string',
67
+ minLength: 1,
68
+ maxLength: 1024,
69
+ pattern: '^[A-Za-z0-9][A-Za-z0-9._/-]*$',
70
+ };
34
71
  const coordinate = { type: 'number', minimum: -1000000, maximum: 1000000 };
35
72
  const positiveSize = { type: 'number', minimum: 0.01, maximum: 1000000 };
36
73
  const index = { type: 'integer', minimum: 0, maximum: 10000 };
37
74
  const ids = arr(id, 10000, 0, true);
38
75
  const semanticKinds = ['process', 'start', 'end', 'decision', 'data-store', 'component'];
39
76
  const relationKinds = ['association', 'dependency', 'flow', 'message', 'transition'];
40
- const node = closed({ id, label: str(), kind: enumOf(...semanticKinds), description: nullable(str()) });
41
- const relation = closed({ id, from: id, to: id, kind: enumOf(...relationKinds), direction: enumOf('forward', 'both', 'none'), label: nullable(str()), weight: nullable({ type: 'number', minimum: 0, maximum: 1000000 }) });
77
+ const node = closed({
78
+ id,
79
+ label: str(),
80
+ kind: enumOf(...semanticKinds),
81
+ description: nullable(str()),
82
+ });
83
+ const relation = closed({
84
+ id,
85
+ from: id,
86
+ to: id,
87
+ kind: enumOf(...relationKinds),
88
+ direction: enumOf('forward', 'both', 'none'),
89
+ label: nullable(str()),
90
+ weight: nullable({ type: 'number', minimum: 0, maximum: 1000000 }),
91
+ });
42
92
  const container = closed({ id, label: str(), members: ids });
43
93
  const annotation = closed({ id, text: str(), targetId: nullable(id) });
44
94
  const emphasis = closed({ targetId: id, level: enumOf('primary', 'secondary', 'muted') });
45
95
  const semanticCollections = {
46
- nodes: arr(node, 4096), relations: arr(relation, 8192), groups: arr(container, 1024),
47
- lanes: arr(container, 256), events: arr(false, 0), series: arr(false, 0), axes: arr(false, 0),
48
- sets: arr(false, 0), annotations: arr(annotation, 1024), emphasis: arr(emphasis, 1024),
96
+ nodes: arr(node, 4096),
97
+ relations: arr(relation, 8192),
98
+ groups: arr(container, 1024),
99
+ lanes: arr(container, 256),
100
+ events: arr(false, 0),
101
+ series: arr(false, 0),
102
+ axes: arr(false, 0),
103
+ sets: arr(false, 0),
104
+ annotations: arr(annotation, 1024),
105
+ emphasis: arr(emphasis, 1024),
49
106
  };
50
107
  const bounds = closed({ x: coordinate, y: coordinate, width: positiveSize, height: positiveSize });
51
108
  const point = closed({ x: coordinate, y: coordinate });
52
- const attachment = closed({ side: enumOf('top', 'right', 'bottom', 'left'), offset: { type: 'number', minimum: 0, maximum: 1 } });
53
- const route = closed({ mode: enumOf('automatic', 'manual'), strategy: enumOf('straight', 'orthogonal'), from: attachment, to: attachment, points: arr(point, 256) });
109
+ const attachment = closed({
110
+ side: enumOf('top', 'right', 'bottom', 'left'),
111
+ offset: { type: 'number', minimum: 0, maximum: 1 },
112
+ });
113
+ const route = closed({
114
+ mode: enumOf('automatic', 'manual'),
115
+ strategy: enumOf('straight', 'orthogonal'),
116
+ from: attachment,
117
+ to: attachment,
118
+ points: arr(point, 256),
119
+ });
54
120
  const labelPlacement = closed({ x: coordinate, y: coordinate, width: positiveSize });
55
121
  const appearance = closed({
56
- shape: enumOf('rectangle', 'rounded-rectangle', 'ellipse', 'diamond', 'cylinder', 'text', 'container', 'connector'),
122
+ shape: enumOf(
123
+ 'rectangle',
124
+ 'rounded-rectangle',
125
+ 'ellipse',
126
+ 'diamond',
127
+ 'cylinder',
128
+ 'text',
129
+ 'container',
130
+ 'connector',
131
+ ),
57
132
  fill: enumOf('surface', 'accent', 'success', 'warning', 'danger', 'transparent'),
58
133
  stroke: enumOf('default', 'accent', 'muted', 'danger', 'none'),
59
134
  strokeWidth: { type: 'number', minimum: 0, maximum: 16 },
@@ -61,151 +136,497 @@ const appearance = closed({
61
136
  fontSize: { type: 'integer', minimum: 8, maximum: 72 },
62
137
  textAlign: enumOf('left', 'center', 'right'),
63
138
  });
64
- const locks = closed({ position: { type: 'boolean' }, size: { type: 'boolean' }, route: { type: 'boolean' } });
65
- const placement = closed({ elementId: id, bounds: nullable(bounds), route: nullable(route), label: nullable(labelPlacement), zIndex: index, appearance, locks });
66
- const snapshot = closed({ bundleDigest: digest, semanticDigest: digest, presentationDigest: digest });
139
+ const locks = closed({
140
+ position: { type: 'boolean' },
141
+ size: { type: 'boolean' },
142
+ route: { type: 'boolean' },
143
+ });
144
+ const placement = closed({
145
+ elementId: id,
146
+ bounds: nullable(bounds),
147
+ route: nullable(route),
148
+ label: nullable(labelPlacement),
149
+ zIndex: index,
150
+ appearance,
151
+ locks,
152
+ });
153
+ const snapshot = closed({
154
+ bundleDigest: digest,
155
+ semanticDigest: digest,
156
+ presentationDigest: digest,
157
+ });
67
158
  const schema = (name, kind, properties) => ({
68
159
  $schema: 'https://json-schema.org/draft/2020-12/schema',
69
160
  $id: `https://openplanr.dev/schemas/v1.13.0/${name}.schema.json`,
70
161
  'x-openplanr-contract': { id: name, version: '1.13.0' },
71
- ...closed({ kind: { const: kind }, schemaVersion: { const: '1.0.0' }, protocolVersion: { const: '1.13.0' }, ...properties }),
162
+ ...closed({
163
+ kind: { const: kind },
164
+ schemaVersion: { const: '1.0.0' },
165
+ protocolVersion: { const: '1.13.0' },
166
+ ...properties,
167
+ }),
72
168
  });
73
169
 
74
170
  const documentSchema = schema('diagram-document', 'planr-diagram', {
75
- diagramId: id, title: str(), summary: str(), audience: enumOf('engineer', 'executive', 'mixed'),
76
- grammar: closed({ id: enumOf('flowchart', 'process', 'swimlane', 'architecture'), version: { const: '1.0.0' } }),
77
- ...semanticCollections, laneOrder: ids,
171
+ diagramId: id,
172
+ title: str(),
173
+ summary: str(),
174
+ audience: enumOf('engineer', 'executive', 'mixed'),
175
+ grammar: closed({
176
+ id: enumOf('flowchart', 'process', 'swimlane', 'architecture'),
177
+ version: { const: '1.0.0' },
178
+ }),
179
+ ...semanticCollections,
180
+ laneOrder: ids,
78
181
  accessibility: closed({ title: str(), description: str(), readingOrder: ids }),
79
182
  documentDigest: digest,
80
183
  });
81
184
  const presentationSchema = schema('diagram-presentation', 'diagram-presentation', {
82
- diagramId: id, semanticDigest: digest, coordinateSystem: { const: 'global-canvas' },
83
- layout: closed({ direction: enumOf('top-down', 'left-right', 'right-left', 'bottom-up'), detailTier: enumOf('simplified', 'balanced', 'faithful') }),
84
- theme: closed({ themeId: enumOf('paper', 'slate', 'midnight'), mode: enumOf('light', 'dark', 'auto') }),
85
- elements: arr(placement, 10000), presentationDigest: digest,
185
+ diagramId: id,
186
+ semanticDigest: digest,
187
+ coordinateSystem: { const: 'global-canvas' },
188
+ layout: closed({
189
+ direction: enumOf('top-down', 'left-right', 'right-left', 'bottom-up'),
190
+ detailTier: enumOf('simplified', 'balanced', 'faithful'),
191
+ }),
192
+ theme: closed({
193
+ themeId: enumOf('paper', 'slate', 'midnight'),
194
+ mode: enumOf('light', 'dark', 'auto'),
195
+ }),
196
+ elements: arr(placement, 10000),
197
+ presentationDigest: digest,
198
+ });
199
+ const range = closed({
200
+ startByte: { type: 'integer', minimum: 0, maximum: 1048576 },
201
+ endByte: { type: 'integer', minimum: 0, maximum: 1048576 },
86
202
  });
87
- const range = closed({ startByte: { type: 'integer', minimum: 0, maximum: 1048576 }, endByte: { type: 'integer', minimum: 0, maximum: 1048576 } });
88
203
  const sourceMapSchema = schema('diagram-source-map', 'diagram-source-map', {
89
- diagramId: id, semanticDigest: digest, sourceDigest: digest,
204
+ diagramId: id,
205
+ semanticDigest: digest,
206
+ sourceDigest: digest,
90
207
  sourceByteLength: { type: 'integer', minimum: 0, maximum: 1048576 },
91
- encoding: { const: 'utf-8' }, parser: closed({ id: token, version: str(64, 1) }),
208
+ encoding: { const: 'utf-8' },
209
+ parser: closed({ id: token, version: str(64, 1) }),
92
210
  certificationVersion: { const: 'flowchart-copy-v1' },
93
- entries: arr(closed({ sourceId: nullable(str(128, 1)), elementIds: ids, range: nullable(range), construct: token, confidence: enumOf('exact', 'ambiguous'), losses: arr(str(512, 1), 64) }), 10000),
211
+ entries: arr(
212
+ closed({
213
+ sourceId: nullable(str(128, 1)),
214
+ elementIds: ids,
215
+ range: nullable(range),
216
+ construct: token,
217
+ confidence: enumOf('exact', 'ambiguous'),
218
+ losses: arr(str(512, 1), 64),
219
+ }),
220
+ 10000,
221
+ ),
94
222
  });
95
223
  const fidelityValue = enumOf('lossless', 'partial', 'unsupported');
96
224
  const fidelitySchema = schema('diagram-fidelity-report', 'diagram-fidelity-report', {
97
- diagramId: id, basis: snapshot, sourceDigest: nullable(digest),
98
- sourceFormat: enumOf('mermaid', 'planr-diagram-bundle'), targetFormat: enumOf('mermaid', 'planr-diagram-bundle', 'svg', 'html', 'png'),
99
- semantic: fidelityValue, presentation: fidelityValue, sourceText: fidelityValue,
100
- losses: arr(closed({ dimension: enumOf('semantic', 'presentation', 'sourceText'), code: token, elementIds: ids, message: str(512, 1) }), 1024),
225
+ diagramId: id,
226
+ basis: snapshot,
227
+ sourceDigest: nullable(digest),
228
+ sourceFormat: enumOf('mermaid', 'planr-diagram-bundle'),
229
+ targetFormat: enumOf('mermaid', 'planr-diagram-bundle', 'svg', 'html', 'png'),
230
+ semantic: fidelityValue,
231
+ presentation: fidelityValue,
232
+ sourceText: fidelityValue,
233
+ losses: arr(
234
+ closed({
235
+ dimension: enumOf('semantic', 'presentation', 'sourceText'),
236
+ code: token,
237
+ elementIds: ids,
238
+ message: str(512, 1),
239
+ }),
240
+ 1024,
241
+ ),
101
242
  });
102
243
  const bundleSchema = schema('diagram-authoring-bundle', 'diagram-authoring-bundle', {
103
- diagramId: id, document: documentSchema, presentation: presentationSchema,
104
- originalSource: nullable(closed({ format: { const: 'mermaid' }, text: str(1048576), sourceDigest: digest })),
105
- sourceMap: nullable(sourceMapSchema), bundleDigest: digest,
106
- });
107
- const semanticEntry = { oneOf: [
108
- closed({ collection: { const: 'nodes' }, value: node }), closed({ collection: { const: 'relations' }, value: relation }),
109
- closed({ collection: { const: 'groups' }, value: container }), closed({ collection: { const: 'lanes' }, value: container }),
110
- closed({ collection: { const: 'annotations' }, value: annotation }),
111
- ] };
112
- const editableSemanticValue = (collection, properties) => closed({
113
- type: { const: 'update-semantics' }, collection: { const: collection }, elementId: id,
114
- before: closed(properties), after: closed(properties),
244
+ diagramId: id,
245
+ document: documentSchema,
246
+ presentation: presentationSchema,
247
+ originalSource: nullable(
248
+ closed({ format: { const: 'mermaid' }, text: str(1048576), sourceDigest: digest }),
249
+ ),
250
+ sourceMap: nullable(sourceMapSchema),
251
+ bundleDigest: digest,
115
252
  });
253
+ const semanticEntry = {
254
+ oneOf: [
255
+ closed({ collection: { const: 'nodes' }, value: node }),
256
+ closed({ collection: { const: 'relations' }, value: relation }),
257
+ closed({ collection: { const: 'groups' }, value: container }),
258
+ closed({ collection: { const: 'lanes' }, value: container }),
259
+ closed({ collection: { const: 'annotations' }, value: annotation }),
260
+ ],
261
+ };
262
+ const editableSemanticValue = (collection, properties) =>
263
+ closed({
264
+ type: { const: 'update-semantics' },
265
+ collection: { const: collection },
266
+ elementId: id,
267
+ before: closed(properties),
268
+ after: closed(properties),
269
+ });
116
270
  const updateSchemas = [
117
- editableSemanticValue('nodes', { label: str(), kind: enumOf(...semanticKinds), description: nullable(str()) }),
118
- editableSemanticValue('relations', { from: id, to: id, kind: enumOf(...relationKinds), direction: enumOf('forward', 'both', 'none'), label: nullable(str()), weight: nullable({ type: 'number', minimum: 0, maximum: 1000000 }) }),
119
- editableSemanticValue('groups', { label: str() }), editableSemanticValue('lanes', { label: str() }),
271
+ editableSemanticValue('nodes', {
272
+ label: str(),
273
+ kind: enumOf(...semanticKinds),
274
+ description: nullable(str()),
275
+ }),
276
+ editableSemanticValue('relations', {
277
+ from: id,
278
+ to: id,
279
+ kind: enumOf(...relationKinds),
280
+ direction: enumOf('forward', 'both', 'none'),
281
+ label: nullable(str()),
282
+ weight: nullable({ type: 'number', minimum: 0, maximum: 1000000 }),
283
+ }),
284
+ editableSemanticValue('groups', { label: str() }),
285
+ editableSemanticValue('lanes', { label: str() }),
120
286
  editableSemanticValue('annotations', { text: str(), targetId: nullable(id) }),
121
- closed({ type: { const: 'update-semantics' }, collection: { const: 'emphasis' }, elementId: id, before: nullable(enumOf('primary', 'secondary', 'muted')), after: nullable(enumOf('primary', 'secondary', 'muted')), index: { type: 'integer', minimum: 0, maximum: 1024 } }, ['type', 'collection', 'elementId', 'before', 'after']),
122
- closed({ type: { const: 'update-semantics' }, collection: { const: 'document' }, before: closed({ title: str(), summary: str(), audience: enumOf('engineer', 'executive', 'mixed'), accessibility: documentSchema.properties.accessibility }), after: closed({ title: str(), summary: str(), audience: enumOf('engineer', 'executive', 'mixed'), accessibility: documentSchema.properties.accessibility }) }),
123
- closed({ type: { const: 'update-semantics' }, collection: { const: 'source-map' }, before: nullable(sourceMapSchema), after: nullable(sourceMapSchema) }),
287
+ closed(
288
+ {
289
+ type: { const: 'update-semantics' },
290
+ collection: { const: 'emphasis' },
291
+ elementId: id,
292
+ before: nullable(enumOf('primary', 'secondary', 'muted')),
293
+ after: nullable(enumOf('primary', 'secondary', 'muted')),
294
+ index: { type: 'integer', minimum: 0, maximum: 1024 },
295
+ },
296
+ ['type', 'collection', 'elementId', 'before', 'after'],
297
+ ),
298
+ closed({
299
+ type: { const: 'update-semantics' },
300
+ collection: { const: 'document' },
301
+ before: closed({
302
+ title: str(),
303
+ summary: str(),
304
+ audience: enumOf('engineer', 'executive', 'mixed'),
305
+ accessibility: documentSchema.properties.accessibility,
306
+ }),
307
+ after: closed({
308
+ title: str(),
309
+ summary: str(),
310
+ audience: enumOf('engineer', 'executive', 'mixed'),
311
+ accessibility: documentSchema.properties.accessibility,
312
+ }),
313
+ }),
314
+ closed({
315
+ type: { const: 'update-semantics' },
316
+ collection: { const: 'source-map' },
317
+ before: nullable(sourceMapSchema),
318
+ after: nullable(sourceMapSchema),
319
+ }),
124
320
  ];
125
- const membershipState = closed({ groups: arr(closed({ id, members: ids }), 1024), lanes: arr(closed({ id, members: ids }), 256), laneOrder: ids });
126
- const geometryValue = closed({ bounds: nullable(bounds), route: nullable(route), label: nullable(labelPlacement), zIndex: index });
321
+ const membershipState = closed({
322
+ groups: arr(closed({ id, members: ids }), 1024),
323
+ lanes: arr(closed({ id, members: ids }), 256),
324
+ laneOrder: ids,
325
+ });
326
+ const geometryValue = closed({
327
+ bounds: nullable(bounds),
328
+ route: nullable(route),
329
+ label: nullable(labelPlacement),
330
+ zIndex: index,
331
+ });
127
332
  const appearanceValue = closed({ appearance, locks });
128
- const operation = { oneOf: [
129
- closed({ type: { const: 'insert-elements' }, elements: arr(semanticEntry, 10000, 1), presentation: arr(placement, 10000, 1), positions: arr(closed({ elementId: id, semanticIndex: index, presentationIndex: index }), 10000, 1) }, ['type', 'elements', 'presentation']),
130
- ...updateSchemas,
131
- closed({ type: { const: 'remove-elements' }, elements: arr(semanticEntry, 10000, 1), presentation: arr(placement, 10000, 1) }),
132
- closed({ type: { const: 'set-membership-order' }, before: membershipState, after: membershipState }),
133
- closed({ type: { const: 'set-geometry' }, changes: arr(closed({ elementId: id, before: geometryValue, after: geometryValue }), 10000, 1) }),
134
- closed({ type: { const: 'set-appearance-locks' }, changes: arr(closed({ elementId: id, before: appearanceValue, after: appearanceValue }), 10000, 1) }),
135
- ] };
333
+ const operation = {
334
+ oneOf: [
335
+ closed(
336
+ {
337
+ type: { const: 'insert-elements' },
338
+ elements: arr(semanticEntry, 10000, 1),
339
+ presentation: arr(placement, 10000, 1),
340
+ positions: arr(
341
+ closed({ elementId: id, semanticIndex: index, presentationIndex: index }),
342
+ 10000,
343
+ 1,
344
+ ),
345
+ },
346
+ ['type', 'elements', 'presentation'],
347
+ ),
348
+ ...updateSchemas,
349
+ closed({
350
+ type: { const: 'remove-elements' },
351
+ elements: arr(semanticEntry, 10000, 1),
352
+ presentation: arr(placement, 10000, 1),
353
+ }),
354
+ closed({
355
+ type: { const: 'set-membership-order' },
356
+ before: membershipState,
357
+ after: membershipState,
358
+ }),
359
+ closed({
360
+ type: { const: 'set-geometry' },
361
+ changes: arr(
362
+ closed({ elementId: id, before: geometryValue, after: geometryValue }),
363
+ 10000,
364
+ 1,
365
+ ),
366
+ }),
367
+ closed({
368
+ type: { const: 'set-appearance-locks' },
369
+ changes: arr(
370
+ closed({ elementId: id, before: appearanceValue, after: appearanceValue }),
371
+ 10000,
372
+ 1,
373
+ ),
374
+ }),
375
+ ],
376
+ };
136
377
  const transactionSchema = schema('diagram-edit-transaction', 'diagram-edit-transaction', {
137
- transactionId: id, diagramId: id, base: snapshot, operations: arr(operation, 256, 1), undoOf: nullable(id),
378
+ transactionId: id,
379
+ diagramId: id,
380
+ base: snapshot,
381
+ operations: arr(operation, 256, 1),
382
+ undoOf: nullable(id),
138
383
  });
139
384
  const proposalSchema = schema('diagram-change-proposal', 'diagram-change-proposal', {
140
- proposalId: id, diagramId: id, base: snapshot, transaction: transactionSchema,
141
- summary: str(4096, 1), author: closed({ kind: enumOf('human', 'agent'), id }),
385
+ proposalId: id,
386
+ diagramId: id,
387
+ base: snapshot,
388
+ transaction: transactionSchema,
389
+ summary: str(4096, 1),
390
+ author: closed({ kind: enumOf('human', 'agent'), id }),
142
391
  status: enumOf('proposed', 'accepted', 'rejected', 'stale'),
143
392
  });
144
393
  const publicationSchema = schema('diagram-publication-state', 'diagram-publication-state', {
145
- diagramId: id, draft: nullable(snapshot), published: nullable(snapshot),
394
+ diagramId: id,
395
+ draft: nullable(snapshot),
396
+ published: nullable(snapshot),
146
397
  audience: enumOf('private', 'company', 'public'),
147
398
  capabilitySemantics: { const: 'descriptive-only-requires-host-authorization' },
148
399
  });
149
400
  const manifestSchema = schema('diagram-manifest', 'diagram-manifest', {
150
- diagramId: id, basis: snapshot, bundle: closed({ path: relativePath, transportDigest: digest }),
401
+ diagramId: id,
402
+ basis: snapshot,
403
+ bundle: closed({ path: relativePath, transportDigest: digest }),
151
404
  renderer: closed({ id: token, version: str(64, 1) }),
152
- outputs: arr(closed({ path: relativePath, mediaType: enumOf('image/svg+xml', 'text/html', 'image/png'), transportDigest: digest, fidelity: fidelitySchema }), 32, 1),
405
+ outputs: arr(
406
+ closed({
407
+ path: relativePath,
408
+ mediaType: enumOf('image/svg+xml', 'text/html', 'image/png'),
409
+ transportDigest: digest,
410
+ fidelity: fidelitySchema,
411
+ }),
412
+ 32,
413
+ 1,
414
+ ),
153
415
  });
154
416
  // Export consumers record the concrete palette version independently of renderer code.
155
417
  manifestSchema.properties.theme = closed({ id: token, version: str(64, 1) });
156
- const mermaidConstruct = closed({ construct: token, import: fidelityValue, export: fidelityValue, semanticRoundTrip: fidelityValue, mapping: str(512, 1) });
418
+ const mermaidConstruct = closed({
419
+ construct: token,
420
+ import: fidelityValue,
421
+ export: fidelityValue,
422
+ semanticRoundTrip: fidelityValue,
423
+ mapping: str(512, 1),
424
+ });
157
425
  const capabilityProfile = closed({
158
- grammarId: enumOf('flowchart', 'process', 'swimlane', 'architecture'), authoring: { const: true },
159
- primitives: arr(enumOf('node', 'relation', 'group', 'lane', 'annotation', 'emphasis'), 6, 1, true),
160
- nodeKinds: arr(enumOf(...semanticKinds), 6, 1, true), relationKinds: arr(enumOf(...relationKinds), 5, 1, true),
426
+ grammarId: enumOf('flowchart', 'process', 'swimlane', 'architecture'),
427
+ authoring: { const: true },
428
+ primitives: arr(
429
+ enumOf('node', 'relation', 'group', 'lane', 'annotation', 'emphasis'),
430
+ 6,
431
+ 1,
432
+ true,
433
+ ),
434
+ nodeKinds: arr(enumOf(...semanticKinds), 6, 1, true),
435
+ relationKinds: arr(enumOf(...relationKinds), 5, 1, true),
161
436
  operations: arr(enumOf(...DIAGRAM_EDIT_OPERATION_CLASSES), 6, 6, true),
162
- mermaid: closed({ mode: { const: 'copy' }, certificationVersion: { const: 'flowchart-copy-v1' }, constructs: arr(mermaidConstruct, 32, 1), linkedSource: { const: false } }),
163
- });
164
- const capabilitiesSchema = schema('diagram-authoring-capabilities', 'diagram-authoring-capabilities', {
165
- version: { const: '1.0.0' }, liveCollaboration: { const: false },
166
- profiles: arr(capabilityProfile, 4, 4),
167
- unsupportedGrammars: arr(token, 128, 0, true),
437
+ mermaid: closed({
438
+ mode: { const: 'copy' },
439
+ certificationVersion: { const: 'flowchart-copy-v1' },
440
+ constructs: arr(mermaidConstruct, 32, 1),
441
+ linkedSource: { const: false },
442
+ }),
168
443
  });
444
+ const capabilitiesSchema = schema(
445
+ 'diagram-authoring-capabilities',
446
+ 'diagram-authoring-capabilities',
447
+ {
448
+ version: { const: '1.0.0' },
449
+ liveCollaboration: { const: false },
450
+ profiles: arr(capabilityProfile, 4, 4),
451
+ unsupportedGrammars: arr(token, 128, 0, true),
452
+ },
453
+ );
169
454
  const schemas = {
170
- 'diagram-document': documentSchema, 'diagram-presentation': presentationSchema,
171
- 'diagram-authoring-bundle': bundleSchema, 'diagram-edit-transaction': transactionSchema,
172
- 'diagram-source-map': sourceMapSchema, 'diagram-fidelity-report': fidelitySchema,
173
- 'diagram-manifest': manifestSchema, 'diagram-change-proposal': proposalSchema,
174
- 'diagram-publication-state': publicationSchema, 'diagram-authoring-capabilities': capabilitiesSchema,
455
+ 'diagram-document': documentSchema,
456
+ 'diagram-presentation': presentationSchema,
457
+ 'diagram-authoring-bundle': bundleSchema,
458
+ 'diagram-edit-transaction': transactionSchema,
459
+ 'diagram-source-map': sourceMapSchema,
460
+ 'diagram-fidelity-report': fidelitySchema,
461
+ 'diagram-manifest': manifestSchema,
462
+ 'diagram-change-proposal': proposalSchema,
463
+ 'diagram-publication-state': publicationSchema,
464
+ 'diagram-authoring-capabilities': capabilitiesSchema,
175
465
  };
466
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_AUTHORING_SCHEMAS} */
176
467
  export const DIAGRAM_AUTHORING_SCHEMAS = deepFreeze(schemas);
177
- export const DIAGRAM_AUTHORING_CONTRACT_FILES = deepFreeze(Object.fromEntries(Object.keys(schemas).map((name) => [name, `${name}.schema.json`])));
468
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_AUTHORING_CONTRACT_FILES} */
469
+ export const DIAGRAM_AUTHORING_CONTRACT_FILES = deepFreeze(
470
+ Object.fromEntries(Object.keys(schemas).map((name) => [name, `${name}.schema.json`])),
471
+ );
178
472
  const mermaidConstructs = [
179
- ['flowchart-direction', 'lossless', 'lossless', 'lossless', 'flowchart TB/TD/LR/RL/BT maps to presentation layout direction'],
180
- ['explicit-node-id', 'lossless', 'lossless', 'lossless', 'Explicit source ID maps through source-map to stable semantic node ID; labels never establish identity'],
181
- ['plain-node-label', 'lossless', 'lossless', 'lossless', 'Escaped plain text maps to node label; HTML is inert text and is not executed'],
182
- ['rectangle-node', 'lossless', 'lossless', 'lossless', 'node.kind process and presentation shape rectangle'],
183
- ['rounded-node', 'lossless', 'lossless', 'lossless', 'node.kind process and presentation shape rounded-rectangle'],
184
- ['decision-node', 'lossless', 'lossless', 'lossless', 'node.kind decision and presentation shape diamond'],
185
- ['cylinder-node', 'lossless', 'lossless', 'lossless', 'node.kind data-store and presentation shape cylinder'],
186
- ['directed-edge', 'lossless', 'lossless', 'lossless', 'relation.kind flow and direction forward; source and target IDs are semantic endpoints'],
187
- ['bidirectional-edge', 'lossless', 'lossless', 'lossless', 'relation.kind flow and direction both'],
188
- ['undirected-edge', 'lossless', 'lossless', 'lossless', 'relation.kind association and direction none'],
189
- ['plain-edge-label', 'lossless', 'lossless', 'lossless', 'Escaped plain text maps to relation label'],
190
- ['subgraph', 'lossless', 'lossless', 'lossless', 'Explicit subgraph ID maps to one semantic group in an acyclic single-parent forest'],
191
- ['lane-semantics', 'unsupported', 'partial', 'partial', 'Mermaid subgraphs do not encode lane identity or explicit lane order'],
192
- ['manual-geometry', 'unsupported', 'partial', 'partial', 'Standard Mermaid does not preserve coordinates, routes, attachments, stacking or locks'],
193
- ['styles-and-directives', 'unsupported', 'unsupported', 'unsupported', 'CSS, classDef, init directives, links, callbacks and HTML labels are outside this certified subset'],
194
- ['unsupported-construct', 'unsupported', 'unsupported', 'unsupported', 'Unrecognized syntax is retained as original source with explicit loss diagnostics'],
195
- ].map(([construct, input, output, roundTrip, mapping]) => ({ construct, import: input, export: output, semanticRoundTrip: roundTrip, mapping }));
473
+ [
474
+ 'flowchart-direction',
475
+ 'lossless',
476
+ 'lossless',
477
+ 'lossless',
478
+ 'flowchart TB/TD/LR/RL/BT maps to presentation layout direction',
479
+ ],
480
+ [
481
+ 'explicit-node-id',
482
+ 'lossless',
483
+ 'lossless',
484
+ 'lossless',
485
+ 'Explicit source ID maps through source-map to stable semantic node ID; labels never establish identity',
486
+ ],
487
+ [
488
+ 'plain-node-label',
489
+ 'lossless',
490
+ 'lossless',
491
+ 'lossless',
492
+ 'Escaped plain text maps to node label; HTML is inert text and is not executed',
493
+ ],
494
+ [
495
+ 'rectangle-node',
496
+ 'lossless',
497
+ 'lossless',
498
+ 'lossless',
499
+ 'node.kind process and presentation shape rectangle',
500
+ ],
501
+ [
502
+ 'rounded-node',
503
+ 'lossless',
504
+ 'lossless',
505
+ 'lossless',
506
+ 'node.kind process and presentation shape rounded-rectangle',
507
+ ],
508
+ [
509
+ 'decision-node',
510
+ 'lossless',
511
+ 'lossless',
512
+ 'lossless',
513
+ 'node.kind decision and presentation shape diamond',
514
+ ],
515
+ [
516
+ 'cylinder-node',
517
+ 'lossless',
518
+ 'lossless',
519
+ 'lossless',
520
+ 'node.kind data-store and presentation shape cylinder',
521
+ ],
522
+ [
523
+ 'directed-edge',
524
+ 'lossless',
525
+ 'lossless',
526
+ 'lossless',
527
+ 'relation.kind flow and direction forward; source and target IDs are semantic endpoints',
528
+ ],
529
+ [
530
+ 'bidirectional-edge',
531
+ 'lossless',
532
+ 'lossless',
533
+ 'lossless',
534
+ 'relation.kind flow and direction both',
535
+ ],
536
+ [
537
+ 'undirected-edge',
538
+ 'lossless',
539
+ 'lossless',
540
+ 'lossless',
541
+ 'relation.kind association and direction none',
542
+ ],
543
+ [
544
+ 'plain-edge-label',
545
+ 'lossless',
546
+ 'lossless',
547
+ 'lossless',
548
+ 'Escaped plain text maps to relation label',
549
+ ],
550
+ [
551
+ 'subgraph',
552
+ 'lossless',
553
+ 'lossless',
554
+ 'lossless',
555
+ 'Explicit subgraph ID maps to one semantic group in an acyclic single-parent forest',
556
+ ],
557
+ [
558
+ 'lane-semantics',
559
+ 'unsupported',
560
+ 'partial',
561
+ 'partial',
562
+ 'Mermaid subgraphs do not encode lane identity or explicit lane order',
563
+ ],
564
+ [
565
+ 'manual-geometry',
566
+ 'unsupported',
567
+ 'partial',
568
+ 'partial',
569
+ 'Standard Mermaid does not preserve coordinates, routes, attachments, stacking or locks',
570
+ ],
571
+ [
572
+ 'styles-and-directives',
573
+ 'unsupported',
574
+ 'unsupported',
575
+ 'unsupported',
576
+ 'CSS, classDef, init directives, links, callbacks and HTML labels are outside this certified subset',
577
+ ],
578
+ [
579
+ 'unsupported-construct',
580
+ 'unsupported',
581
+ 'unsupported',
582
+ 'unsupported',
583
+ 'Unrecognized syntax is retained as original source with explicit loss diagnostics',
584
+ ],
585
+ ].map(([construct, input, output, roundTrip, mapping]) => ({
586
+ construct,
587
+ import: input,
588
+ export: output,
589
+ semanticRoundTrip: roundTrip,
590
+ mapping,
591
+ }));
196
592
  const profileIds = ['flowchart', 'process', 'swimlane', 'architecture'];
593
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_AUTHORING_CAPABILITIES} */
197
594
  export const DIAGRAM_AUTHORING_CAPABILITIES = deepFreeze({
198
- kind: 'diagram-authoring-capabilities', schemaVersion: '1.0.0', protocolVersion: '1.13.0',
199
- version: '1.0.0', liveCollaboration: false,
595
+ kind: 'diagram-authoring-capabilities',
596
+ schemaVersion: '1.0.0',
597
+ protocolVersion: '1.13.0',
598
+ version: '1.0.0',
599
+ liveCollaboration: false,
200
600
  profiles: profileIds.map((grammarId) => ({
201
- grammarId, authoring: true, primitives: ['node', 'relation', 'group', ...(grammarId === 'process' || grammarId === 'swimlane' ? ['lane'] : []), 'annotation', 'emphasis'],
202
- nodeKinds: [...semanticKinds], relationKinds: [...relationKinds], operations: [...DIAGRAM_EDIT_OPERATION_CLASSES],
203
- mermaid: { mode: 'copy', certificationVersion: 'flowchart-copy-v1', constructs: mermaidConstructs.map((entry) => ({ ...entry })), linkedSource: false },
601
+ grammarId,
602
+ authoring: true,
603
+ primitives: [
604
+ 'node',
605
+ 'relation',
606
+ 'group',
607
+ ...(grammarId === 'process' || grammarId === 'swimlane' ? ['lane'] : []),
608
+ 'annotation',
609
+ 'emphasis',
610
+ ],
611
+ nodeKinds: [...semanticKinds],
612
+ relationKinds: [...relationKinds],
613
+ operations: [...DIAGRAM_EDIT_OPERATION_CLASSES],
614
+ mermaid: {
615
+ mode: 'copy',
616
+ certificationVersion: 'flowchart-copy-v1',
617
+ constructs: mermaidConstructs.map((entry) => ({ ...entry })),
618
+ linkedSource: false,
619
+ },
204
620
  })),
205
- unsupportedGrammars: DIAGRAM_REGISTRIES['diagram-grammars.json'].grammars.map((entry) => entry.grammarId).filter((value) => !profileIds.includes(value)),
621
+ unsupportedGrammars: DIAGRAM_REGISTRIES['diagram-grammars.json'].grammars
622
+ .map((entry) => entry.grammarId)
623
+ .filter((value) => !profileIds.includes(value)),
206
624
  });
625
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').getDiagramAuthoringCapability} */
207
626
  export function getDiagramAuthoringCapability(grammarId) {
208
- return DIAGRAM_AUTHORING_CAPABILITIES.profiles.find((entry) => entry.grammarId === grammarId) ?? null;
627
+ return (
628
+ DIAGRAM_AUTHORING_CAPABILITIES.profiles.find((entry) => entry.grammarId === grammarId) ?? null
629
+ );
209
630
  }
210
631
 
211
632
  const error = (path, rule, detail) => ({ path, rule, detail });
@@ -218,41 +639,90 @@ function inspectData(value) {
218
639
  function visit(current, path, depth) {
219
640
  if (issues.length) return;
220
641
  if (++count > DIAGRAM_AUTHORING_LIMITS.values || depth > DIAGRAM_AUTHORING_LIMITS.depth) {
221
- issues.push(error(path, 'resource-limit', 'Data exceeds the portable value or nesting limit.')); return;
642
+ issues.push(
643
+ error(path, 'resource-limit', 'Data exceeds the portable value or nesting limit.'),
644
+ );
645
+ return;
222
646
  }
223
647
  if (typeof current === 'string') {
224
648
  textSize += current.length;
225
- if (textSize > DIAGRAM_AUTHORING_LIMITS.textCodeUnits) issues.push(error(path, 'resource-limit', 'Data exceeds the portable text limit.'));
226
- else if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(current)) issues.push(error(path, 'unicode', 'Unpaired Unicode surrogate is not portable UTF-8.'));
649
+ if (textSize > DIAGRAM_AUTHORING_LIMITS.textCodeUnits)
650
+ issues.push(error(path, 'resource-limit', 'Data exceeds the portable text limit.'));
651
+ else if (
652
+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(current)
653
+ )
654
+ issues.push(error(path, 'unicode', 'Unpaired Unicode surrogate is not portable UTF-8.'));
227
655
  return;
228
656
  }
229
657
  if (current === null || typeof current === 'boolean') return;
230
- if (typeof current === 'number') { if (!Number.isFinite(current)) issues.push(error(path, 'finite-number', 'Numbers must be finite.')); return; }
231
- if (typeof current !== 'object') { issues.push(error(path, 'plain-data', 'Only JSON data is accepted.')); return; }
658
+ if (typeof current === 'number') {
659
+ if (!Number.isFinite(current))
660
+ issues.push(error(path, 'finite-number', 'Numbers must be finite.'));
661
+ return;
662
+ }
663
+ if (typeof current !== 'object') {
664
+ issues.push(error(path, 'plain-data', 'Only JSON data is accepted.'));
665
+ return;
666
+ }
232
667
  const proto = Object.getPrototypeOf(current);
233
- if (Array.isArray(current) ? proto !== Array.prototype : proto !== Object.prototype && proto !== null) {
234
- issues.push(error(path, 'plain-data', 'Custom prototypes are not accepted.')); return;
668
+ if (
669
+ Array.isArray(current)
670
+ ? proto !== Array.prototype
671
+ : proto !== Object.prototype && proto !== null
672
+ ) {
673
+ issues.push(error(path, 'plain-data', 'Custom prototypes are not accepted.'));
674
+ return;
675
+ }
676
+ if (ancestors.has(current)) {
677
+ issues.push(error(path, 'cycle', 'Cyclic data is not accepted.'));
678
+ return;
235
679
  }
236
- if (ancestors.has(current)) { issues.push(error(path, 'cycle', 'Cyclic data is not accepted.')); return; }
237
680
  ancestors.add(current);
238
681
  const descriptors = Object.getOwnPropertyDescriptors(current);
239
682
  for (const key of Reflect.ownKeys(descriptors)) {
240
- if (typeof key !== 'string' || key === '__proto__' || key === 'constructor' || key === 'prototype') {
241
- issues.push(error(path, 'unsafe-key', 'Unsafe or symbolic object key.')); break;
683
+ if (
684
+ typeof key !== 'string' ||
685
+ key === '__proto__' ||
686
+ key === 'constructor' ||
687
+ key === 'prototype'
688
+ ) {
689
+ issues.push(error(path, 'unsafe-key', 'Unsafe or symbolic object key.'));
690
+ break;
242
691
  }
243
692
  const descriptor = descriptors[key];
244
- if (descriptor.get || descriptor.set || !('value' in descriptor)) { issues.push(error(path, 'accessor', 'Accessors are not accepted.')); break; }
693
+ if (descriptor.get || descriptor.set || !('value' in descriptor)) {
694
+ issues.push(error(path, 'accessor', 'Accessors are not accepted.'));
695
+ break;
696
+ }
245
697
  if (Array.isArray(current) && key === 'length') continue;
246
- if (!descriptor.enumerable || (Array.isArray(current) && (!/^(0|[1-9][0-9]*)$/u.test(key) || Number(key) >= current.length))) {
247
- issues.push(error(path, 'plain-data', 'Non-JSON properties are not accepted.')); break;
698
+ if (
699
+ !descriptor.enumerable ||
700
+ (Array.isArray(current) &&
701
+ (!/^(0|[1-9][0-9]*)$/u.test(key) || Number(key) >= current.length))
702
+ ) {
703
+ issues.push(error(path, 'plain-data', 'Non-JSON properties are not accepted.'));
704
+ break;
248
705
  }
249
- visit(descriptor.value, Array.isArray(current) ? `${path}[${key}]` : `${path}.${key}`, depth + 1);
706
+ visit(
707
+ descriptor.value,
708
+ Array.isArray(current) ? `${path}[${key}]` : `${path}.${key}`,
709
+ depth + 1,
710
+ );
250
711
  if (issues.length) break;
251
712
  }
252
- if (!issues.length && Array.isArray(current) && Object.keys(descriptors).length !== current.length + 1) issues.push(error(path, 'sparse-array', 'Sparse arrays are not accepted.'));
713
+ if (
714
+ !issues.length &&
715
+ Array.isArray(current) &&
716
+ Object.keys(descriptors).length !== current.length + 1
717
+ )
718
+ issues.push(error(path, 'sparse-array', 'Sparse arrays are not accepted.'));
253
719
  ancestors.delete(current);
254
720
  }
255
- try { visit(value, '$', 0); } catch { issues.push(error('$', 'plain-data', 'Data cannot be inspected safely.')); }
721
+ try {
722
+ visit(value, '$', 0);
723
+ } catch {
724
+ issues.push(error('$', 'plain-data', 'Data cannot be inspected safely.'));
725
+ }
256
726
  return issues;
257
727
  }
258
728
  function assertData(value) {
@@ -261,19 +731,37 @@ function assertData(value) {
261
731
  }
262
732
  function digestExcluding(value, field) {
263
733
  assertData(value);
264
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Digest input must be an object.');
734
+ if (!value || typeof value !== 'object' || Array.isArray(value))
735
+ throw new TypeError('Digest input must be an object.');
265
736
  const input = { ...value };
266
737
  delete input[field];
267
738
  return sha256Jcs(input);
268
739
  }
740
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').diagramDocumentDigest} */
269
741
  export const diagramDocumentDigest = (value) => digestExcluding(value, 'documentDigest');
742
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').diagramPresentationDigest} */
270
743
  export const diagramPresentationDigest = (value) => digestExcluding(value, 'presentationDigest');
744
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').diagramAuthoringBundleDigest} */
271
745
  export const diagramAuthoringBundleDigest = (value) => digestExcluding(value, 'bundleDigest');
272
746
  const same = (a, b) => canonicalizeJson(a) === canonicalizeJson(b);
273
747
  const sourceDigest = (text) => `sha256:${sha256Hex(text)}`;
274
- const semanticNames = ['nodes', 'relations', 'groups', 'lanes', 'events', 'series', 'axes', 'sets', 'annotations'];
748
+ const semanticNames = [
749
+ 'nodes',
750
+ 'relations',
751
+ 'groups',
752
+ 'lanes',
753
+ 'events',
754
+ 'series',
755
+ 'axes',
756
+ 'sets',
757
+ 'annotations',
758
+ ];
275
759
  const allElements = (doc) => semanticNames.flatMap((name) => doc[name]);
276
- const expectedSnapshot = (bundle) => ({ bundleDigest: bundle.bundleDigest, semanticDigest: bundle.document.documentDigest, presentationDigest: bundle.presentation.presentationDigest });
760
+ const expectedSnapshot = (bundle) => ({
761
+ bundleDigest: bundle.bundleDigest,
762
+ semanticDigest: bundle.document.documentDigest,
763
+ presentationDigest: bundle.presentation.presentationDigest,
764
+ });
277
765
  function hasContainmentCycle(parents) {
278
766
  const complete = new Set();
279
767
  for (const member of parents.keys()) {
@@ -281,7 +769,8 @@ function hasContainmentCycle(parents) {
281
769
  let current = member;
282
770
  while (current && !complete.has(current)) {
283
771
  if (visited.has(current)) return true;
284
- visited.add(current); current = parents.get(current);
772
+ visited.add(current);
773
+ current = parents.get(current);
285
774
  }
286
775
  for (const item of visited) complete.add(item);
287
776
  }
@@ -291,36 +780,105 @@ function hasContainmentCycle(parents) {
291
780
  function documentIssues(doc, path, issues) {
292
781
  const entries = allElements(doc);
293
782
  const byId = new Map();
294
- if (entries.length + doc.emphasis.length > 10000) issues.push(error(path, 'resource-limit', 'Too many semantic primitive entries.'));
295
- for (const collection of semanticNames) for (let i = 0; i < doc[collection].length; i += 1) {
296
- const entry = doc[collection][i];
297
- if (byId.has(entry.id)) issues.push(error(`${path}.${collection}[${i}].id`, 'duplicate-id', 'Semantic element IDs must be globally unique.'));
298
- byId.set(entry.id, { ...entry, collection });
299
- }
783
+ if (entries.length + doc.emphasis.length > 10000)
784
+ issues.push(error(path, 'resource-limit', 'Too many semantic primitive entries.'));
785
+ for (const collection of semanticNames)
786
+ for (let i = 0; i < doc[collection].length; i += 1) {
787
+ const entry = doc[collection][i];
788
+ if (byId.has(entry.id))
789
+ issues.push(
790
+ error(
791
+ `${path}.${collection}[${i}].id`,
792
+ 'duplicate-id',
793
+ 'Semantic element IDs must be globally unique.',
794
+ ),
795
+ );
796
+ byId.set(entry.id, { ...entry, collection });
797
+ }
300
798
  const capability = getDiagramAuthoringCapability(doc.grammar.id);
301
- if (!capability.primitives.includes('lane') && doc.lanes.length) issues.push(error(`${path}.lanes`, 'profile-primitive', 'This authoring profile does not support lanes.'));
302
- doc.relations.forEach((edge, i) => ['from', 'to'].forEach((key) => {
303
- if (byId.get(edge[key])?.collection !== 'nodes') issues.push(error(`${path}.relations[${i}].${key}`, 'endpoint', 'Relationship endpoints must reference semantic nodes.'));
304
- }));
799
+ if (capability && !capability.primitives.includes('lane') && doc.lanes.length)
800
+ issues.push(
801
+ error(`${path}.lanes`, 'profile-primitive', 'This authoring profile does not support lanes.'),
802
+ );
803
+ doc.relations.forEach((edge, i) =>
804
+ ['from', 'to'].forEach((key) => {
805
+ if (byId.get(edge[key])?.collection !== 'nodes')
806
+ issues.push(
807
+ error(
808
+ `${path}.relations[${i}].${key}`,
809
+ 'endpoint',
810
+ 'Relationship endpoints must reference semantic nodes.',
811
+ ),
812
+ );
813
+ }),
814
+ );
305
815
  const parent = new Map();
306
- for (const collection of ['groups', 'lanes']) doc[collection].forEach((group, i) => group.members.forEach((member, j) => {
307
- const child = byId.get(member);
308
- const memberPath = `${path}.${collection}[${i}].members[${j}]`;
309
- if (!child || !['nodes', 'groups', 'lanes', 'annotations'].includes(child.collection)) issues.push(error(memberPath, 'containment-reference', 'Container members must reference a placeable semantic element.'));
310
- if (parent.has(member)) issues.push(error(memberPath, 'multiple-parents', 'An element has more than one immediate container.'));
311
- parent.set(member, group.id);
312
- }));
313
- if (hasContainmentCycle(parent)) issues.push(error(path, 'containment-cycle', 'Container membership must form a forest.'));
314
- if (!same([...doc.laneOrder].sort(), doc.lanes.map((item) => item.id).sort())) issues.push(error(`${path}.laneOrder`, 'lane-order', 'Every lane must occur exactly once in laneOrder.'));
315
- doc.annotations.forEach((entry, i) => { if (entry.targetId !== null && !byId.has(entry.targetId)) issues.push(error(`${path}.annotations[${i}].targetId`, 'reference', 'Annotation target is missing.')); });
816
+ for (const collection of ['groups', 'lanes'])
817
+ doc[collection].forEach((group, i) =>
818
+ group.members.forEach((member, j) => {
819
+ const child = byId.get(member);
820
+ const memberPath = `${path}.${collection}[${i}].members[${j}]`;
821
+ if (!child || !['nodes', 'groups', 'lanes', 'annotations'].includes(child.collection))
822
+ issues.push(
823
+ error(
824
+ memberPath,
825
+ 'containment-reference',
826
+ 'Container members must reference a placeable semantic element.',
827
+ ),
828
+ );
829
+ if (parent.has(member))
830
+ issues.push(
831
+ error(
832
+ memberPath,
833
+ 'multiple-parents',
834
+ 'An element has more than one immediate container.',
835
+ ),
836
+ );
837
+ parent.set(member, group.id);
838
+ }),
839
+ );
840
+ if (hasContainmentCycle(parent))
841
+ issues.push(error(path, 'containment-cycle', 'Container membership must form a forest.'));
842
+ if (!same([...doc.laneOrder].sort(), doc.lanes.map((item) => item.id).sort()))
843
+ issues.push(
844
+ error(`${path}.laneOrder`, 'lane-order', 'Every lane must occur exactly once in laneOrder.'),
845
+ );
846
+ doc.annotations.forEach((entry, i) => {
847
+ if (entry.targetId !== null && !byId.has(entry.targetId))
848
+ issues.push(
849
+ error(`${path}.annotations[${i}].targetId`, 'reference', 'Annotation target is missing.'),
850
+ );
851
+ });
316
852
  const emphasisIds = new Set();
317
853
  doc.emphasis.forEach((entry, i) => {
318
- if (!byId.has(entry.targetId)) issues.push(error(`${path}.emphasis[${i}].targetId`, 'reference', 'Emphasis target is missing.'));
319
- if (emphasisIds.has(entry.targetId)) issues.push(error(`${path}.emphasis[${i}].targetId`, 'duplicate-id', 'Only one emphasis entry is allowed per target.'));
854
+ if (!byId.has(entry.targetId))
855
+ issues.push(
856
+ error(`${path}.emphasis[${i}].targetId`, 'reference', 'Emphasis target is missing.'),
857
+ );
858
+ if (emphasisIds.has(entry.targetId))
859
+ issues.push(
860
+ error(
861
+ `${path}.emphasis[${i}].targetId`,
862
+ 'duplicate-id',
863
+ 'Only one emphasis entry is allowed per target.',
864
+ ),
865
+ );
320
866
  emphasisIds.add(entry.targetId);
321
867
  });
322
- doc.accessibility.readingOrder.forEach((entry, i) => { if (!byId.has(entry)) issues.push(error(`${path}.accessibility.readingOrder[${i}]`, 'reference', 'Reading order target is missing.')); });
323
- if (doc.documentDigest !== diagramDocumentDigest(doc)) issues.push(error(`${path}.documentDigest`, 'digest', 'Semantic content digest does not match.'));
868
+ doc.accessibility.readingOrder.forEach((entry, i) => {
869
+ if (!byId.has(entry))
870
+ issues.push(
871
+ error(
872
+ `${path}.accessibility.readingOrder[${i}]`,
873
+ 'reference',
874
+ 'Reading order target is missing.',
875
+ ),
876
+ );
877
+ });
878
+ if (doc.documentDigest !== diagramDocumentDigest(doc))
879
+ issues.push(
880
+ error(`${path}.documentDigest`, 'digest', 'Semantic content digest does not match.'),
881
+ );
324
882
  }
325
883
  function presentationIssues(value, doc, path, issues) {
326
884
  const idsSeen = new Set();
@@ -328,36 +886,109 @@ function presentationIssues(value, doc, path, issues) {
328
886
  const nodes = doc ? new Set(doc.nodes.map((entry) => entry.id)) : null;
329
887
  const relations = doc ? new Map(doc.relations.map((entry) => [entry.id, entry])) : null;
330
888
  const containers = doc ? new Set([...doc.groups, ...doc.lanes].map((entry) => entry.id)) : null;
331
- if (doc && (value.diagramId !== doc.diagramId || value.semanticDigest !== doc.documentDigest)) issues.push(error(path, 'basis', 'Presentation does not reference the exact semantic document.'));
889
+ if (doc && (value.diagramId !== doc.diagramId || value.semanticDigest !== doc.documentDigest))
890
+ issues.push(
891
+ error(path, 'basis', 'Presentation does not reference the exact semantic document.'),
892
+ );
332
893
  value.elements.forEach((entry, i) => {
333
894
  const location = `${path}.elements[${i}]`;
334
895
  geometryIssues(entry, location, issues);
335
- if (idsSeen.has(entry.elementId)) issues.push(error(`${location}.elementId`, 'duplicate-id', 'Presentation element IDs must be unique.'));
896
+ if (idsSeen.has(entry.elementId))
897
+ issues.push(
898
+ error(`${location}.elementId`, 'duplicate-id', 'Presentation element IDs must be unique.'),
899
+ );
336
900
  idsSeen.add(entry.elementId);
337
- if (byId && !byId.has(entry.elementId)) issues.push(error(`${location}.elementId`, 'reference', 'Presentation element is not in the semantic document.'));
338
- if (entry.route !== null && entry.bounds !== null) issues.push(error(location, 'geometry-kind', 'A connector has a route; a shape has bounds.'));
339
- if (entry.route === null && entry.bounds === null) issues.push(error(location, 'geometry-kind', 'A placed element requires bounds or a route.'));
340
- if (entry.route?.mode === 'manual' && entry.route.points.length < 2) issues.push(error(`${location}.route.points`, 'manual-route', 'A manual route requires at least two global points.'));
341
- if (entry.route?.mode === 'automatic' && entry.route.points.length !== 0) issues.push(error(`${location}.route.points`, 'automatic-route', 'Automatic route geometry is derived and must not carry authored points.'));
342
- if (entry.route && entry.appearance.shape !== 'connector') issues.push(error(`${location}.appearance.shape`, 'shape-kind', 'Routes must use the connector shape.'));
343
- if (entry.bounds && entry.appearance.shape === 'connector') issues.push(error(`${location}.appearance.shape`, 'shape-kind', 'Bounded elements cannot use the connector shape.'));
344
- if (relations?.has(entry.elementId) && !entry.route) issues.push(error(location, 'geometry-kind', 'Semantic relations require route geometry.'));
345
- if (doc && !relations.has(entry.elementId) && !entry.bounds) issues.push(error(location, 'geometry-kind', 'Non-relation elements require bounds.'));
346
- if (containers?.has(entry.elementId) && entry.appearance.shape !== 'container') issues.push(error(`${location}.appearance.shape`, 'shape-kind', 'Containers require the container visual shape.'));
347
- if (nodes?.has(entry.elementId) && ['container', 'text'].includes(entry.appearance.shape)) issues.push(error(`${location}.appearance.shape`, 'shape-kind', 'Nodes require a node visual shape.'));
901
+ if (byId && !byId.has(entry.elementId))
902
+ issues.push(
903
+ error(
904
+ `${location}.elementId`,
905
+ 'reference',
906
+ 'Presentation element is not in the semantic document.',
907
+ ),
908
+ );
909
+ if (entry.route !== null && entry.bounds !== null)
910
+ issues.push(error(location, 'geometry-kind', 'A connector has a route; a shape has bounds.'));
911
+ if (entry.route === null && entry.bounds === null)
912
+ issues.push(error(location, 'geometry-kind', 'A placed element requires bounds or a route.'));
913
+ if (entry.route?.mode === 'manual' && entry.route.points.length < 2)
914
+ issues.push(
915
+ error(
916
+ `${location}.route.points`,
917
+ 'manual-route',
918
+ 'A manual route requires at least two global points.',
919
+ ),
920
+ );
921
+ if (entry.route?.mode === 'automatic' && entry.route.points.length !== 0)
922
+ issues.push(
923
+ error(
924
+ `${location}.route.points`,
925
+ 'automatic-route',
926
+ 'Automatic route geometry is derived and must not carry authored points.',
927
+ ),
928
+ );
929
+ if (entry.route && entry.appearance.shape !== 'connector')
930
+ issues.push(
931
+ error(`${location}.appearance.shape`, 'shape-kind', 'Routes must use the connector shape.'),
932
+ );
933
+ if (entry.bounds && entry.appearance.shape === 'connector')
934
+ issues.push(
935
+ error(
936
+ `${location}.appearance.shape`,
937
+ 'shape-kind',
938
+ 'Bounded elements cannot use the connector shape.',
939
+ ),
940
+ );
941
+ if (relations?.has(entry.elementId) && !entry.route)
942
+ issues.push(error(location, 'geometry-kind', 'Semantic relations require route geometry.'));
943
+ if (relations && !relations.has(entry.elementId) && !entry.bounds)
944
+ issues.push(error(location, 'geometry-kind', 'Non-relation elements require bounds.'));
945
+ if (containers?.has(entry.elementId) && entry.appearance.shape !== 'container')
946
+ issues.push(
947
+ error(
948
+ `${location}.appearance.shape`,
949
+ 'shape-kind',
950
+ 'Containers require the container visual shape.',
951
+ ),
952
+ );
953
+ if (nodes?.has(entry.elementId) && ['container', 'text'].includes(entry.appearance.shape))
954
+ issues.push(
955
+ error(`${location}.appearance.shape`, 'shape-kind', 'Nodes require a node visual shape.'),
956
+ );
348
957
  });
349
- if (byId && (idsSeen.size !== byId.size || [...byId.keys()].some((key) => !idsSeen.has(key)))) issues.push(error(`${path}.elements`, 'presentation-coverage', 'Every semantic element must have exactly one placement.'));
350
- if (value.presentationDigest !== diagramPresentationDigest(value)) issues.push(error(`${path}.presentationDigest`, 'digest', 'Presentation content digest does not match.'));
958
+ if (byId && (idsSeen.size !== byId.size || [...byId.keys()].some((key) => !idsSeen.has(key))))
959
+ issues.push(
960
+ error(
961
+ `${path}.elements`,
962
+ 'presentation-coverage',
963
+ 'Every semantic element must have exactly one placement.',
964
+ ),
965
+ );
966
+ if (value.presentationDigest !== diagramPresentationDigest(value))
967
+ issues.push(
968
+ error(`${path}.presentationDigest`, 'digest', 'Presentation content digest does not match.'),
969
+ );
351
970
  }
352
971
  function sourceMapIssues(value, doc, text, path, issues) {
353
- if (doc && (value.diagramId !== doc.diagramId || value.semanticDigest !== doc.documentDigest)) issues.push(error(path, 'basis', 'Source map does not reference the exact semantic document.'));
972
+ if (doc && (value.diagramId !== doc.diagramId || value.semanticDigest !== doc.documentDigest))
973
+ issues.push(error(path, 'basis', 'Source map does not reference the exact semantic document.'));
354
974
  const elementIds = doc ? new Set(allElements(doc).map((entry) => entry.id)) : null;
355
975
  const sourceIds = new Set();
356
976
  let boundaries = null;
357
977
  if (text !== undefined) {
358
978
  const byteLength = new TextEncoder().encode(text).length;
359
- if (value.sourceDigest !== sourceDigest(text) || value.sourceByteLength !== byteLength) issues.push(error(path, 'source-digest', 'Source digest and byte length must match exact UTF-8 source text.'));
360
- const requested = new Set(value.entries.flatMap((entry) => entry.range ? [entry.range.startByte, entry.range.endByte] : []));
979
+ if (value.sourceDigest !== sourceDigest(text) || value.sourceByteLength !== byteLength)
980
+ issues.push(
981
+ error(
982
+ path,
983
+ 'source-digest',
984
+ 'Source digest and byte length must match exact UTF-8 source text.',
985
+ ),
986
+ );
987
+ const requested = new Set(
988
+ value.entries.flatMap((entry) =>
989
+ entry.range ? [entry.range.startByte, entry.range.endByte] : [],
990
+ ),
991
+ );
361
992
  boundaries = new Set([0]);
362
993
  let cursor = 0;
363
994
  for (const character of text) {
@@ -368,60 +999,197 @@ function sourceMapIssues(value, doc, text, path, issues) {
368
999
  }
369
1000
  value.entries.forEach((entry, i) => {
370
1001
  const location = `${path}.entries[${i}]`;
371
- if (entry.sourceId !== null && sourceIds.has(entry.sourceId)) issues.push(error(`${location}.sourceId`, 'ambiguous-source-id', 'Duplicate explicit source IDs must be represented by one ambiguous entry.'));
1002
+ if (entry.sourceId !== null && sourceIds.has(entry.sourceId))
1003
+ issues.push(
1004
+ error(
1005
+ `${location}.sourceId`,
1006
+ 'ambiguous-source-id',
1007
+ 'Duplicate explicit source IDs must be represented by one ambiguous entry.',
1008
+ ),
1009
+ );
372
1010
  if (entry.sourceId !== null) sourceIds.add(entry.sourceId);
373
- if (entry.confidence === 'exact' && ((entry.sourceId === null && entry.range === null) || entry.elementIds.length !== 1)) issues.push(error(location, 'source-identity', 'Exact correspondence requires a source ID or exact range and one semantic element.'));
1011
+ if (
1012
+ entry.confidence === 'exact' &&
1013
+ ((entry.sourceId === null && entry.range === null) || entry.elementIds.length !== 1)
1014
+ )
1015
+ issues.push(
1016
+ error(
1017
+ location,
1018
+ 'source-identity',
1019
+ 'Exact correspondence requires a source ID or exact range and one semantic element.',
1020
+ ),
1021
+ );
374
1022
  const certification = mermaidConstructs.find((item) => item.construct === entry.construct);
375
- if (!certification || (certification.import === 'unsupported' && (entry.confidence === 'exact' || entry.losses.length === 0))) issues.push(error(`${location}.construct`, 'source-certification', 'Unsupported syntax requires the certified loss record and cannot claim exact correspondence.'));
376
- if (elementIds) entry.elementIds.forEach((item, j) => { if (!elementIds.has(item)) issues.push(error(`${location}.elementIds[${j}]`, 'reference', 'Source map semantic element is missing.')); });
377
- if (entry.range && (entry.range.startByte > entry.range.endByte || entry.range.endByte > value.sourceByteLength || (boundaries && (!boundaries.has(entry.range.startByte) || !boundaries.has(entry.range.endByte))))) issues.push(error(`${location}.range`, 'source-range', 'Source range must lie on UTF-8 boundaries within the original source.'));
1023
+ if (
1024
+ !certification ||
1025
+ (certification.import === 'unsupported' &&
1026
+ (entry.confidence === 'exact' || entry.losses.length === 0))
1027
+ )
1028
+ issues.push(
1029
+ error(
1030
+ `${location}.construct`,
1031
+ 'source-certification',
1032
+ 'Unsupported syntax requires the certified loss record and cannot claim exact correspondence.',
1033
+ ),
1034
+ );
1035
+ if (elementIds)
1036
+ entry.elementIds.forEach((item, j) => {
1037
+ if (!elementIds.has(item))
1038
+ issues.push(
1039
+ error(
1040
+ `${location}.elementIds[${j}]`,
1041
+ 'reference',
1042
+ 'Source map semantic element is missing.',
1043
+ ),
1044
+ );
1045
+ });
1046
+ if (
1047
+ entry.range &&
1048
+ (entry.range.startByte > entry.range.endByte ||
1049
+ entry.range.endByte > value.sourceByteLength ||
1050
+ (boundaries &&
1051
+ (!boundaries.has(entry.range.startByte) || !boundaries.has(entry.range.endByte))))
1052
+ )
1053
+ issues.push(
1054
+ error(
1055
+ `${location}.range`,
1056
+ 'source-range',
1057
+ 'Source range must lie on UTF-8 boundaries within the original source.',
1058
+ ),
1059
+ );
378
1060
  });
379
1061
  }
380
1062
  function bundleIssues(bundle, path, issues) {
381
1063
  documentIssues(bundle.document, `${path}.document`, issues);
382
1064
  presentationIssues(bundle.presentation, bundle.document, `${path}.presentation`, issues);
383
- if (bundle.diagramId !== bundle.document.diagramId || bundle.diagramId !== bundle.presentation.diagramId) issues.push(error(`${path}.diagramId`, 'diagram-id', 'Bundle members must identify one diagram.'));
384
- if ((bundle.originalSource === null) !== (bundle.sourceMap === null)) issues.push(error(path, 'source-pair', 'Original source and its correspondence map must be retained together.'));
1065
+ if (
1066
+ bundle.diagramId !== bundle.document.diagramId ||
1067
+ bundle.diagramId !== bundle.presentation.diagramId
1068
+ )
1069
+ issues.push(
1070
+ error(`${path}.diagramId`, 'diagram-id', 'Bundle members must identify one diagram.'),
1071
+ );
1072
+ if ((bundle.originalSource === null) !== (bundle.sourceMap === null))
1073
+ issues.push(
1074
+ error(
1075
+ path,
1076
+ 'source-pair',
1077
+ 'Original source and its correspondence map must be retained together.',
1078
+ ),
1079
+ );
385
1080
  if (bundle.originalSource) {
386
- if (new TextEncoder().encode(bundle.originalSource.text).length > DIAGRAM_AUTHORING_LIMITS.sourceBytes) issues.push(error(`${path}.originalSource.text`, 'resource-limit', 'Original source exceeds the UTF-8 byte limit.'));
387
- if (bundle.originalSource.sourceDigest !== sourceDigest(bundle.originalSource.text)) issues.push(error(`${path}.originalSource.sourceDigest`, 'source-digest', 'Source digest must match exact original UTF-8 bytes.'));
1081
+ if (
1082
+ new TextEncoder().encode(bundle.originalSource.text).length >
1083
+ DIAGRAM_AUTHORING_LIMITS.sourceBytes
1084
+ )
1085
+ issues.push(
1086
+ error(
1087
+ `${path}.originalSource.text`,
1088
+ 'resource-limit',
1089
+ 'Original source exceeds the UTF-8 byte limit.',
1090
+ ),
1091
+ );
1092
+ if (bundle.originalSource.sourceDigest !== sourceDigest(bundle.originalSource.text))
1093
+ issues.push(
1094
+ error(
1095
+ `${path}.originalSource.sourceDigest`,
1096
+ 'source-digest',
1097
+ 'Source digest must match exact original UTF-8 bytes.',
1098
+ ),
1099
+ );
388
1100
  }
389
- if (bundle.sourceMap) sourceMapIssues(bundle.sourceMap, bundle.document, bundle.originalSource?.text, `${path}.sourceMap`, issues);
390
- if (bundle.bundleDigest !== diagramAuthoringBundleDigest(bundle)) issues.push(error(`${path}.bundleDigest`, 'digest', 'Bundle content digest does not match.'));
1101
+ if (bundle.sourceMap)
1102
+ sourceMapIssues(
1103
+ bundle.sourceMap,
1104
+ bundle.document,
1105
+ bundle.originalSource?.text,
1106
+ `${path}.sourceMap`,
1107
+ issues,
1108
+ );
1109
+ if (bundle.bundleDigest !== diagramAuthoringBundleDigest(bundle))
1110
+ issues.push(error(`${path}.bundleDigest`, 'digest', 'Bundle content digest does not match.'));
391
1111
  }
392
1112
 
393
1113
  function basisIssues(value, bundle, path, issues) {
394
- if (bundle && (value.diagramId !== bundle.diagramId || !same(value.base ?? value.basis, expectedSnapshot(bundle)))) issues.push(error(path, 'basis', 'The artifact does not reference the exact supplied bundle snapshot.'));
1114
+ if (
1115
+ bundle &&
1116
+ (value.diagramId !== bundle.diagramId ||
1117
+ !same(value.base ?? value.basis, expectedSnapshot(bundle)))
1118
+ )
1119
+ issues.push(
1120
+ error(path, 'basis', 'The artifact does not reference the exact supplied bundle snapshot.'),
1121
+ );
395
1122
  }
396
1123
  function transactionIssues(value, bundle, path, issues) {
397
1124
  basisIssues(value, bundle, path, issues);
398
- if (value.undoOf === value.transactionId) issues.push(error(`${path}.undoOf`, 'undo-reference', 'An inverse cannot reference its own transaction.'));
1125
+ if (value.undoOf === value.transactionId)
1126
+ issues.push(
1127
+ error(`${path}.undoOf`, 'undo-reference', 'An inverse cannot reference its own transaction.'),
1128
+ );
399
1129
  const available = bundle ? new Set(allElements(bundle.document).map((entry) => entry.id)) : null;
400
- const collectionById = bundle ? new Map(semanticNames.flatMap((name) => bundle.document[name].map((entry) => [entry.id, name]))) : null;
1130
+ const collectionById = bundle
1131
+ ? new Map(
1132
+ semanticNames.flatMap((name) => bundle.document[name].map((entry) => [entry.id, name])),
1133
+ )
1134
+ : null;
401
1135
  const insertedCollections = new Map();
402
1136
  const inserted = new Set();
403
1137
  const removed = new Set();
404
1138
  const capability = bundle ? getDiagramAuthoringCapability(bundle.document.grammar.id) : null;
405
- const collectionOf = (elementId) => collectionById?.get(elementId) ?? insertedCollections.get(elementId);
1139
+ const collectionOf = (elementId) =>
1140
+ collectionById?.get(elementId) ?? insertedCollections.get(elementId);
406
1141
  const membershipReferences = (collection, item, location) => {
407
1142
  if (!collectionById) return;
408
1143
  const actualCollection = collectionOf(item.id);
409
- if (!actualCollection) issues.push(error(`${location}.id`, 'containment-reference', 'Membership container is not in the base or inserts.'));
410
- else if (actualCollection !== collection) issues.push(error(`${location}.id`, 'element-class', 'Membership container must match its semantic collection.'));
1144
+ if (!actualCollection)
1145
+ issues.push(
1146
+ error(
1147
+ `${location}.id`,
1148
+ 'containment-reference',
1149
+ 'Membership container is not in the base or inserts.',
1150
+ ),
1151
+ );
1152
+ else if (actualCollection !== collection)
1153
+ issues.push(
1154
+ error(
1155
+ `${location}.id`,
1156
+ 'element-class',
1157
+ 'Membership container must match its semantic collection.',
1158
+ ),
1159
+ );
411
1160
  item.members.forEach((member, j) => {
412
- if (!['nodes', 'groups', 'lanes', 'annotations'].includes(collectionOf(member))) issues.push(error(`${location}.members[${j}]`, 'containment-reference', 'Container members must reference placeable elements in the base or inserts.'));
1161
+ if (!['nodes', 'groups', 'lanes', 'annotations'].includes(collectionOf(member)))
1162
+ issues.push(
1163
+ error(
1164
+ `${location}.members[${j}]`,
1165
+ 'containment-reference',
1166
+ 'Container members must reference placeable elements in the base or inserts.',
1167
+ ),
1168
+ );
413
1169
  });
414
1170
  };
415
1171
  const semanticGeometry = (collection, geometry, location) => {
416
- if (collection && ((collection === 'relations') !== (geometry.route !== null))) issues.push(error(location, 'geometry-kind', 'Geometry must match the semantic element class.'));
1172
+ if (collection && (collection === 'relations') !== (geometry.route !== null))
1173
+ issues.push(
1174
+ error(location, 'geometry-kind', 'Geometry must match the semantic element class.'),
1175
+ );
417
1176
  };
418
1177
  const semanticAppearance = (collection, appearance, location) => {
419
1178
  if (!collection) return;
420
1179
  const shape = appearance.shape;
421
- if ((collection === 'relations' && shape !== 'connector')
422
- || (collection !== 'relations' && shape === 'connector')
423
- || (['groups', 'lanes'].includes(collection) && shape !== 'container')
424
- || (collection === 'nodes' && ['container', 'text'].includes(shape))) issues.push(error(`${location}.shape`, 'shape-kind', 'Appearance must match the semantic element class.'));
1180
+ if (
1181
+ (collection === 'relations' && shape !== 'connector') ||
1182
+ (collection !== 'relations' && shape === 'connector') ||
1183
+ (['groups', 'lanes'].includes(collection) && shape !== 'container') ||
1184
+ (collection === 'nodes' && ['container', 'text'].includes(shape))
1185
+ )
1186
+ issues.push(
1187
+ error(
1188
+ `${location}.shape`,
1189
+ 'shape-kind',
1190
+ 'Appearance must match the semantic element class.',
1191
+ ),
1192
+ );
425
1193
  };
426
1194
  // This inspects references only. Applying changes, checking before-values in sequence,
427
1195
  // computing inverse operations and committing revisions belong to the edit kernel.
@@ -430,197 +1198,700 @@ function transactionIssues(value, bundle, path, issues) {
430
1198
  if (op.type === 'insert-elements' || op.type === 'remove-elements') {
431
1199
  const entryIds = op.elements.map((entry) => entry.value.id);
432
1200
  const presentationIds = op.presentation.map((entry) => entry.elementId);
433
- if (new Set(entryIds).size !== entryIds.length) issues.push(error(`${location}.elements`, 'duplicate-id', 'Each operation must identify unique semantic elements.'));
434
- if (!same([...entryIds].sort(), [...presentationIds].sort())) issues.push(error(`${location}.presentation`, 'presentation-coverage', 'Inserted or removed semantic elements require matching presentation entries.'));
1201
+ if (new Set(entryIds).size !== entryIds.length)
1202
+ issues.push(
1203
+ error(
1204
+ `${location}.elements`,
1205
+ 'duplicate-id',
1206
+ 'Each operation must identify unique semantic elements.',
1207
+ ),
1208
+ );
1209
+ if (!same([...entryIds].sort(), [...presentationIds].sort()))
1210
+ issues.push(
1211
+ error(
1212
+ `${location}.presentation`,
1213
+ 'presentation-coverage',
1214
+ 'Inserted or removed semantic elements require matching presentation entries.',
1215
+ ),
1216
+ );
435
1217
  if (op.type === 'insert-elements' && op.positions) {
436
1218
  const positionedIds = op.positions.map((entry) => entry.elementId);
437
- if (new Set(positionedIds).size !== positionedIds.length) issues.push(error(`${location}.positions`, 'duplicate-id', 'Insertion positions must identify each element once.'));
438
- if (!same([...entryIds].sort(), [...positionedIds].sort())) issues.push(error(`${location}.positions`, 'position-coverage', 'Insertion positions must cover exactly the inserted elements.'));
1219
+ if (new Set(positionedIds).size !== positionedIds.length)
1220
+ issues.push(
1221
+ error(
1222
+ `${location}.positions`,
1223
+ 'duplicate-id',
1224
+ 'Insertion positions must identify each element once.',
1225
+ ),
1226
+ );
1227
+ if (!same([...entryIds].sort(), [...positionedIds].sort()))
1228
+ issues.push(
1229
+ error(
1230
+ `${location}.positions`,
1231
+ 'position-coverage',
1232
+ 'Insertion positions must cover exactly the inserted elements.',
1233
+ ),
1234
+ );
439
1235
  }
440
1236
  for (const entry of op.elements) {
441
1237
  if (op.type === 'insert-elements') {
442
- if (entry.collection === 'lanes' && capability && !capability.primitives.includes('lane')) issues.push(error(`${location}.elements`, 'profile-primitive', 'This authoring profile does not support lanes.'));
443
- if (inserted.has(entry.value.id) || available?.has(entry.value.id)) issues.push(error(`${location}.elements`, 'duplicate-id', 'An insert must allocate a new stable element ID.'));
1238
+ if (entry.collection === 'lanes' && capability && !capability.primitives.includes('lane'))
1239
+ issues.push(
1240
+ error(
1241
+ `${location}.elements`,
1242
+ 'profile-primitive',
1243
+ 'This authoring profile does not support lanes.',
1244
+ ),
1245
+ );
1246
+ if (inserted.has(entry.value.id) || available?.has(entry.value.id))
1247
+ issues.push(
1248
+ error(
1249
+ `${location}.elements`,
1250
+ 'duplicate-id',
1251
+ 'An insert must allocate a new stable element ID.',
1252
+ ),
1253
+ );
444
1254
  inserted.add(entry.value.id);
445
1255
  insertedCollections.set(entry.value.id, entry.collection);
446
1256
  } else {
447
- if (removed.has(entry.value.id)) issues.push(error(`${location}.elements`, 'duplicate-id', 'An element cannot be removed twice.'));
448
- if (available && !available.has(entry.value.id) && !inserted.has(entry.value.id)) issues.push(error(`${location}.elements`, 'reference', 'Removed element is not in the base or earlier inserts.'));
449
- if (collectionById && (collectionById.get(entry.value.id) ?? insertedCollections.get(entry.value.id)) !== entry.collection) issues.push(error(`${location}.elements`, 'element-class', 'Removed entry must identify the actual semantic element class.'));
1257
+ if (removed.has(entry.value.id))
1258
+ issues.push(
1259
+ error(`${location}.elements`, 'duplicate-id', 'An element cannot be removed twice.'),
1260
+ );
1261
+ if (available && !available.has(entry.value.id) && !inserted.has(entry.value.id))
1262
+ issues.push(
1263
+ error(
1264
+ `${location}.elements`,
1265
+ 'reference',
1266
+ 'Removed element is not in the base or earlier inserts.',
1267
+ ),
1268
+ );
1269
+ if (
1270
+ collectionById &&
1271
+ (collectionById.get(entry.value.id) ?? insertedCollections.get(entry.value.id)) !==
1272
+ entry.collection
1273
+ )
1274
+ issues.push(
1275
+ error(
1276
+ `${location}.elements`,
1277
+ 'element-class',
1278
+ 'Removed entry must identify the actual semantic element class.',
1279
+ ),
1280
+ );
450
1281
  removed.add(entry.value.id);
451
1282
  }
452
1283
  }
453
- if (op.type === 'insert-elements' && collectionById) op.elements.forEach((entry, j) => {
454
- if (entry.collection === 'relations') for (const endpoint of ['from', 'to']) {
455
- if ((collectionById.get(entry.value[endpoint]) ?? insertedCollections.get(entry.value[endpoint])) !== 'nodes') issues.push(error(`${location}.elements[${j}].value.${endpoint}`, 'endpoint', 'Relationship endpoints must identify nodes in the base or this insertion.'));
456
- }
457
- if (['groups', 'lanes'].includes(entry.collection)) membershipReferences(entry.collection, entry.value, `${location}.elements[${j}].value`);
458
- if (entry.collection === 'annotations' && entry.value.targetId !== null && !collectionOf(entry.value.targetId)) issues.push(error(`${location}.elements[${j}].value.targetId`, 'reference', 'Annotation target is not in the base or inserts.'));
459
- });
1284
+ if (op.type === 'insert-elements' && collectionById)
1285
+ op.elements.forEach((entry, j) => {
1286
+ if (entry.collection === 'relations')
1287
+ for (const endpoint of ['from', 'to']) {
1288
+ if (
1289
+ (collectionById.get(entry.value[endpoint]) ??
1290
+ insertedCollections.get(entry.value[endpoint])) !== 'nodes'
1291
+ )
1292
+ issues.push(
1293
+ error(
1294
+ `${location}.elements[${j}].value.${endpoint}`,
1295
+ 'endpoint',
1296
+ 'Relationship endpoints must identify nodes in the base or this insertion.',
1297
+ ),
1298
+ );
1299
+ }
1300
+ if (['groups', 'lanes'].includes(entry.collection))
1301
+ membershipReferences(entry.collection, entry.value, `${location}.elements[${j}].value`);
1302
+ if (
1303
+ entry.collection === 'annotations' &&
1304
+ entry.value.targetId !== null &&
1305
+ !collectionOf(entry.value.targetId)
1306
+ )
1307
+ issues.push(
1308
+ error(
1309
+ `${location}.elements[${j}].value.targetId`,
1310
+ 'reference',
1311
+ 'Annotation target is not in the base or inserts.',
1312
+ ),
1313
+ );
1314
+ });
460
1315
  // Validate geometry kind and routing even without a semantic context.
461
1316
  for (const [j, entry] of op.presentation.entries()) {
462
1317
  const semantic = op.elements.find((item) => item.value.id === entry.elementId);
463
1318
  geometryIssues(entry, `${location}.presentation[${j}]`, issues);
464
1319
  semanticGeometry(semantic?.collection, entry, `${location}.presentation[${j}]`);
465
- semanticAppearance(semantic?.collection, entry.appearance, `${location}.presentation[${j}].appearance`);
1320
+ semanticAppearance(
1321
+ semantic?.collection,
1322
+ entry.appearance,
1323
+ `${location}.presentation[${j}].appearance`,
1324
+ );
466
1325
  }
467
1326
  } else if (op.type === 'set-geometry' || op.type === 'set-appearance-locks') {
468
1327
  const touched = new Set();
469
1328
  op.changes.forEach((change, j) => {
470
- if (touched.has(change.elementId)) issues.push(error(`${location}.changes[${j}].elementId`, 'duplicate-id', 'An operation must list each affected element once.'));
1329
+ if (touched.has(change.elementId))
1330
+ issues.push(
1331
+ error(
1332
+ `${location}.changes[${j}].elementId`,
1333
+ 'duplicate-id',
1334
+ 'An operation must list each affected element once.',
1335
+ ),
1336
+ );
471
1337
  touched.add(change.elementId);
472
- if (available && !available.has(change.elementId) && !inserted.has(change.elementId)) issues.push(error(`${location}.changes[${j}].elementId`, 'reference', 'Affected element is not in the base or earlier inserts.'));
1338
+ if (available && !available.has(change.elementId) && !inserted.has(change.elementId))
1339
+ issues.push(
1340
+ error(
1341
+ `${location}.changes[${j}].elementId`,
1342
+ 'reference',
1343
+ 'Affected element is not in the base or earlier inserts.',
1344
+ ),
1345
+ );
473
1346
  for (const side of ['before', 'after']) {
474
1347
  const changePath = `${location}.changes[${j}].${side}`;
475
1348
  if (op.type === 'set-geometry') {
476
1349
  geometryIssues(change[side], changePath, issues);
477
- if (collectionById) semanticGeometry(collectionOf(change.elementId), change[side], changePath);
478
- } else if (collectionById) semanticAppearance(collectionOf(change.elementId), change[side].appearance, `${changePath}.appearance`);
1350
+ if (collectionById)
1351
+ semanticGeometry(collectionOf(change.elementId), change[side], changePath);
1352
+ } else if (collectionById)
1353
+ semanticAppearance(
1354
+ collectionOf(change.elementId),
1355
+ change[side].appearance,
1356
+ `${changePath}.appearance`,
1357
+ );
479
1358
  }
480
1359
  });
481
1360
  } else if (op.type === 'update-semantics') {
482
- if (op.collection === 'emphasis' && op.index !== undefined && (op.before !== null || op.after === null)) issues.push(error(`${location}.index`, 'insertion-position', 'An emphasis index is only valid when inserting an emphasis entry.'));
483
- if (!['document', 'source-map'].includes(op.collection) && available && !available.has(op.elementId) && !inserted.has(op.elementId)) issues.push(error(`${location}.elementId`, 'reference', 'Affected semantic element is not in the base or earlier inserts.'));
484
- if (!['document', 'source-map', 'emphasis'].includes(op.collection) && collectionById && (collectionById.get(op.elementId) ?? insertedCollections.get(op.elementId)) !== op.collection) issues.push(error(`${location}.collection`, 'element-class', 'An update cannot change the class of its semantic element.'));
485
- if (op.collection === 'relations') for (const side of ['before', 'after']) for (const end of ['from', 'to']) {
486
- if (collectionById && (collectionById.get(op[side][end]) ?? insertedCollections.get(op[side][end])) !== 'nodes') issues.push(error(`${location}.${side}.${end}`, 'endpoint', 'Relationship endpoints must identify nodes in the base or inserts.'));
487
- }
488
- if (collectionById && op.collection === 'annotations') for (const side of ['before', 'after']) {
489
- if (op[side].targetId !== null && !collectionOf(op[side].targetId)) issues.push(error(`${location}.${side}.targetId`, 'reference', 'Annotation target is not in the base or inserts.'));
490
- }
491
- if (collectionById && op.collection === 'document') for (const side of ['before', 'after']) op[side].accessibility.readingOrder.forEach((elementId, j) => {
492
- if (!collectionOf(elementId)) issues.push(error(`${location}.${side}.accessibility.readingOrder[${j}]`, 'reference', 'Reading order target is not in the base or inserts.'));
493
- });
1361
+ if (
1362
+ op.collection === 'emphasis' &&
1363
+ op.index !== undefined &&
1364
+ (op.before !== null || op.after === null)
1365
+ )
1366
+ issues.push(
1367
+ error(
1368
+ `${location}.index`,
1369
+ 'insertion-position',
1370
+ 'An emphasis index is only valid when inserting an emphasis entry.',
1371
+ ),
1372
+ );
1373
+ if (
1374
+ !['document', 'source-map'].includes(op.collection) &&
1375
+ available &&
1376
+ !available.has(op.elementId) &&
1377
+ !inserted.has(op.elementId)
1378
+ )
1379
+ issues.push(
1380
+ error(
1381
+ `${location}.elementId`,
1382
+ 'reference',
1383
+ 'Affected semantic element is not in the base or earlier inserts.',
1384
+ ),
1385
+ );
1386
+ if (
1387
+ !['document', 'source-map', 'emphasis'].includes(op.collection) &&
1388
+ collectionById &&
1389
+ (collectionById.get(op.elementId) ?? insertedCollections.get(op.elementId)) !==
1390
+ op.collection
1391
+ )
1392
+ issues.push(
1393
+ error(
1394
+ `${location}.collection`,
1395
+ 'element-class',
1396
+ 'An update cannot change the class of its semantic element.',
1397
+ ),
1398
+ );
1399
+ if (op.collection === 'relations')
1400
+ for (const side of ['before', 'after'])
1401
+ for (const end of ['from', 'to']) {
1402
+ if (
1403
+ collectionById &&
1404
+ (collectionById.get(op[side][end]) ?? insertedCollections.get(op[side][end])) !==
1405
+ 'nodes'
1406
+ )
1407
+ issues.push(
1408
+ error(
1409
+ `${location}.${side}.${end}`,
1410
+ 'endpoint',
1411
+ 'Relationship endpoints must identify nodes in the base or inserts.',
1412
+ ),
1413
+ );
1414
+ }
1415
+ if (collectionById && op.collection === 'annotations')
1416
+ for (const side of ['before', 'after']) {
1417
+ if (op[side].targetId !== null && !collectionOf(op[side].targetId))
1418
+ issues.push(
1419
+ error(
1420
+ `${location}.${side}.targetId`,
1421
+ 'reference',
1422
+ 'Annotation target is not in the base or inserts.',
1423
+ ),
1424
+ );
1425
+ }
1426
+ if (collectionById && op.collection === 'document')
1427
+ for (const side of ['before', 'after'])
1428
+ op[side].accessibility.readingOrder.forEach((elementId, j) => {
1429
+ if (!collectionOf(elementId))
1430
+ issues.push(
1431
+ error(
1432
+ `${location}.${side}.accessibility.readingOrder[${j}]`,
1433
+ 'reference',
1434
+ 'Reading order target is not in the base or inserts.',
1435
+ ),
1436
+ );
1437
+ });
494
1438
  } else if (op.type === 'set-membership-order') {
495
1439
  for (const side of ['before', 'after']) {
496
1440
  const state = op[side];
497
- if (state.lanes.length && capability && !capability.primitives.includes('lane')) issues.push(error(`${location}.${side}.lanes`, 'profile-primitive', 'This authoring profile does not support lanes.'));
498
- for (const collection of ['groups', 'lanes']) state[collection].forEach((item, j) => membershipReferences(collection, item, `${location}.${side}.${collection}[${j}]`));
1441
+ if (state.lanes.length && capability && !capability.primitives.includes('lane'))
1442
+ issues.push(
1443
+ error(
1444
+ `${location}.${side}.lanes`,
1445
+ 'profile-primitive',
1446
+ 'This authoring profile does not support lanes.',
1447
+ ),
1448
+ );
1449
+ for (const collection of ['groups', 'lanes'])
1450
+ state[collection].forEach((item, j) =>
1451
+ membershipReferences(collection, item, `${location}.${side}.${collection}[${j}]`),
1452
+ );
499
1453
  const parents = new Map();
500
1454
  const containers = [...state.groups, ...state.lanes];
501
- if (new Set(containers.map((item) => item.id)).size !== containers.length) issues.push(error(`${location}.${side}`, 'duplicate-id', 'Membership lists require distinct container IDs.'));
502
- for (const item of containers) for (const member of item.members) {
503
- if (parents.has(member)) issues.push(error(`${location}.${side}`, 'multiple-parents', 'Membership assigns more than one immediate parent.'));
504
- parents.set(member, item.id);
505
- }
506
- if (hasContainmentCycle(parents)) issues.push(error(`${location}.${side}`, 'containment-cycle', 'Membership must form a forest.'));
507
- if (!same([...state.laneOrder].sort(), state.lanes.map((item) => item.id).sort())) issues.push(error(`${location}.${side}.laneOrder`, 'lane-order', 'Membership includes every lane in explicit order.'));
1455
+ if (new Set(containers.map((item) => item.id)).size !== containers.length)
1456
+ issues.push(
1457
+ error(
1458
+ `${location}.${side}`,
1459
+ 'duplicate-id',
1460
+ 'Membership lists require distinct container IDs.',
1461
+ ),
1462
+ );
1463
+ for (const item of containers)
1464
+ for (const member of item.members) {
1465
+ if (parents.has(member))
1466
+ issues.push(
1467
+ error(
1468
+ `${location}.${side}`,
1469
+ 'multiple-parents',
1470
+ 'Membership assigns more than one immediate parent.',
1471
+ ),
1472
+ );
1473
+ parents.set(member, item.id);
1474
+ }
1475
+ if (hasContainmentCycle(parents))
1476
+ issues.push(
1477
+ error(`${location}.${side}`, 'containment-cycle', 'Membership must form a forest.'),
1478
+ );
1479
+ if (!same([...state.laneOrder].sort(), state.lanes.map((item) => item.id).sort()))
1480
+ issues.push(
1481
+ error(
1482
+ `${location}.${side}.laneOrder`,
1483
+ 'lane-order',
1484
+ 'Membership includes every lane in explicit order.',
1485
+ ),
1486
+ );
508
1487
  }
509
1488
  }
510
1489
  });
511
1490
  }
512
1491
  function geometryIssues(entry, path, issues) {
513
- if ((entry.bounds === null) === (entry.route === null)) issues.push(error(path, 'geometry-kind', 'Geometry requires exactly one of bounds or route.'));
514
- if (entry.route?.mode === 'manual' && entry.route.points.length < 2) issues.push(error(`${path}.route.points`, 'manual-route', 'Manual routes require at least two global points.'));
515
- if (entry.route?.mode === 'automatic' && entry.route.points.length !== 0) issues.push(error(`${path}.route.points`, 'automatic-route', 'Automatic route points are derived.'));
516
- if (entry.route?.mode === 'manual' && entry.route.strategy === 'straight' && entry.route.points.length !== 2) issues.push(error(`${path}.route.points`, 'route-strategy', 'A straight manual route has exactly two endpoint points.'));
517
- if (entry.route?.mode === 'manual' && entry.route.strategy === 'orthogonal' && entry.route.points.some((point, i, points) => i > 0 && point.x !== points[i - 1].x && point.y !== points[i - 1].y)) issues.push(error(`${path}.route.points`, 'route-strategy', 'Every orthogonal segment must be horizontal or vertical.'));
1492
+ if ((entry.bounds === null) === (entry.route === null))
1493
+ issues.push(error(path, 'geometry-kind', 'Geometry requires exactly one of bounds or route.'));
1494
+ if (entry.route?.mode === 'manual' && entry.route.points.length < 2)
1495
+ issues.push(
1496
+ error(
1497
+ `${path}.route.points`,
1498
+ 'manual-route',
1499
+ 'Manual routes require at least two global points.',
1500
+ ),
1501
+ );
1502
+ if (entry.route?.mode === 'automatic' && entry.route.points.length !== 0)
1503
+ issues.push(
1504
+ error(`${path}.route.points`, 'automatic-route', 'Automatic route points are derived.'),
1505
+ );
1506
+ if (
1507
+ entry.route?.mode === 'manual' &&
1508
+ entry.route.strategy === 'straight' &&
1509
+ entry.route.points.length !== 2
1510
+ )
1511
+ issues.push(
1512
+ error(
1513
+ `${path}.route.points`,
1514
+ 'route-strategy',
1515
+ 'A straight manual route has exactly two endpoint points.',
1516
+ ),
1517
+ );
1518
+ if (
1519
+ entry.route?.mode === 'manual' &&
1520
+ entry.route.strategy === 'orthogonal' &&
1521
+ entry.route.points.some(
1522
+ (point, i, points) => i > 0 && point.x !== points[i - 1].x && point.y !== points[i - 1].y,
1523
+ )
1524
+ )
1525
+ issues.push(
1526
+ error(
1527
+ `${path}.route.points`,
1528
+ 'route-strategy',
1529
+ 'Every orthogonal segment must be horizontal or vertical.',
1530
+ ),
1531
+ );
518
1532
  }
519
1533
  function fidelityIssues(value, bundle, path, issues) {
520
1534
  basisIssues(value, bundle, path, issues);
521
1535
  const idsKnown = bundle ? new Set(allElements(bundle.document).map((entry) => entry.id)) : null;
522
1536
  for (const [i, loss] of value.losses.entries()) {
523
- if (value[loss.dimension] === 'lossless') issues.push(error(`${path}.${loss.dimension}`, 'fidelity', 'A dimension with reported loss cannot claim lossless fidelity.'));
524
- if (idsKnown) loss.elementIds.forEach((entry, j) => { if (!idsKnown.has(entry)) issues.push(error(`${path}.losses[${i}].elementIds[${j}]`, 'reference', 'Fidelity loss refers to an unknown semantic element.')); });
1537
+ if (value[loss.dimension] === 'lossless')
1538
+ issues.push(
1539
+ error(
1540
+ `${path}.${loss.dimension}`,
1541
+ 'fidelity',
1542
+ 'A dimension with reported loss cannot claim lossless fidelity.',
1543
+ ),
1544
+ );
1545
+ if (idsKnown)
1546
+ loss.elementIds.forEach((entry, j) => {
1547
+ if (!idsKnown.has(entry))
1548
+ issues.push(
1549
+ error(
1550
+ `${path}.losses[${i}].elementIds[${j}]`,
1551
+ 'reference',
1552
+ 'Fidelity loss refers to an unknown semantic element.',
1553
+ ),
1554
+ );
1555
+ });
525
1556
  }
526
- if (bundle && value.sourceDigest !== (bundle.originalSource?.sourceDigest ?? null)) issues.push(error(`${path}.sourceDigest`, 'source-digest', 'Fidelity report must identify the retained source, if any.'));
527
- if (value.sourceFormat === 'mermaid' && value.sourceDigest === null) issues.push(error(`${path}.sourceDigest`, 'source-digest', 'A Mermaid import report must identify its exact source bytes.'));
1557
+ if (bundle && value.sourceDigest !== (bundle.originalSource?.sourceDigest ?? null))
1558
+ issues.push(
1559
+ error(
1560
+ `${path}.sourceDigest`,
1561
+ 'source-digest',
1562
+ 'Fidelity report must identify the retained source, if any.',
1563
+ ),
1564
+ );
1565
+ if (value.sourceFormat === 'mermaid' && value.sourceDigest === null)
1566
+ issues.push(
1567
+ error(
1568
+ `${path}.sourceDigest`,
1569
+ 'source-digest',
1570
+ 'A Mermaid import report must identify its exact source bytes.',
1571
+ ),
1572
+ );
528
1573
  if (bundle && value.sourceFormat === 'mermaid') {
529
- const uncertain = bundle.sourceMap?.entries.some((entry) => entry.confidence === 'ambiguous' || entry.losses.length || mermaidConstructs.find((item) => item.construct === entry.construct)?.import !== 'lossless');
530
- if (uncertain && value.semantic === 'lossless') issues.push(error(`${path}.semantic`, 'fidelity', 'Source correspondence records ambiguity or unsupported content; semantic fidelity cannot be lossless.'));
531
- const lostPresentation = bundle.sourceMap?.entries.some((entry) => ['styles-and-directives', 'manual-geometry', 'unsupported-construct'].includes(entry.construct));
532
- if (lostPresentation && value.presentation === 'lossless') issues.push(error(`${path}.presentation`, 'fidelity', 'Unsupported source presentation cannot be reported as retained without loss.'));
1574
+ const uncertain = bundle.sourceMap?.entries.some(
1575
+ (entry) =>
1576
+ entry.confidence === 'ambiguous' ||
1577
+ entry.losses.length ||
1578
+ mermaidConstructs.find((item) => item.construct === entry.construct)?.import !== 'lossless',
1579
+ );
1580
+ if (uncertain && value.semantic === 'lossless')
1581
+ issues.push(
1582
+ error(
1583
+ `${path}.semantic`,
1584
+ 'fidelity',
1585
+ 'Source correspondence records ambiguity or unsupported content; semantic fidelity cannot be lossless.',
1586
+ ),
1587
+ );
1588
+ const lostPresentation = bundle.sourceMap?.entries.some((entry) =>
1589
+ ['styles-and-directives', 'manual-geometry', 'unsupported-construct'].includes(
1590
+ entry.construct,
1591
+ ),
1592
+ );
1593
+ if (lostPresentation && value.presentation === 'lossless')
1594
+ issues.push(
1595
+ error(
1596
+ `${path}.presentation`,
1597
+ 'fidelity',
1598
+ 'Unsupported source presentation cannot be reported as retained without loss.',
1599
+ ),
1600
+ );
533
1601
  }
534
1602
  if (bundle && value.targetFormat === 'mermaid') {
535
- if (bundle.presentation.elements.length && value.presentation === 'lossless') issues.push(error(`${path}.presentation`, 'fidelity', 'Standard Mermaid does not retain authored global geometry, stacking, attachment offsets or locks.'));
536
- const appearances = new Map(bundle.presentation.elements.map((entry) => [entry.elementId, entry.appearance.shape]));
537
- const supportedNodes = bundle.document.nodes.every((entry) => (
538
- (entry.kind === 'process' && ['rectangle', 'rounded-rectangle'].includes(appearances.get(entry.id)))
539
- || (entry.kind === 'decision' && appearances.get(entry.id) === 'diamond')
540
- || (entry.kind === 'data-store' && appearances.get(entry.id) === 'cylinder')
541
- ));
542
- const supportedRelations = bundle.document.relations.every((entry) => (entry.kind === 'flow' && ['forward', 'both'].includes(entry.direction)) || (entry.kind === 'association' && entry.direction === 'none'));
543
- if ((!supportedNodes || !supportedRelations || bundle.document.lanes.length || bundle.document.annotations.length || bundle.document.emphasis.length) && value.semantic === 'lossless') issues.push(error(`${path}.semantic`, 'fidelity', 'The certified Mermaid subset cannot preserve all authored semantic roles or primitives.'));
1603
+ if (bundle.presentation.elements.length && value.presentation === 'lossless')
1604
+ issues.push(
1605
+ error(
1606
+ `${path}.presentation`,
1607
+ 'fidelity',
1608
+ 'Standard Mermaid does not retain authored global geometry, stacking, attachment offsets or locks.',
1609
+ ),
1610
+ );
1611
+ const appearances = new Map(
1612
+ bundle.presentation.elements.map((entry) => [entry.elementId, entry.appearance.shape]),
1613
+ );
1614
+ const supportedNodes = bundle.document.nodes.every(
1615
+ (entry) =>
1616
+ (entry.kind === 'process' &&
1617
+ ['rectangle', 'rounded-rectangle'].includes(appearances.get(entry.id))) ||
1618
+ (entry.kind === 'decision' && appearances.get(entry.id) === 'diamond') ||
1619
+ (entry.kind === 'data-store' && appearances.get(entry.id) === 'cylinder'),
1620
+ );
1621
+ const supportedRelations = bundle.document.relations.every(
1622
+ (entry) =>
1623
+ (entry.kind === 'flow' && ['forward', 'both'].includes(entry.direction)) ||
1624
+ (entry.kind === 'association' && entry.direction === 'none'),
1625
+ );
1626
+ if (
1627
+ (!supportedNodes ||
1628
+ !supportedRelations ||
1629
+ bundle.document.lanes.length ||
1630
+ bundle.document.annotations.length ||
1631
+ bundle.document.emphasis.length) &&
1632
+ value.semantic === 'lossless'
1633
+ )
1634
+ issues.push(
1635
+ error(
1636
+ `${path}.semantic`,
1637
+ 'fidelity',
1638
+ 'The certified Mermaid subset cannot preserve all authored semantic roles or primitives.',
1639
+ ),
1640
+ );
544
1641
  }
545
1642
  }
546
- const validRelativePath = (value) => !value.split('/').some((part) => part === '' || part === '.' || part === '..') && !/^[A-Za-z]:/u.test(value);
1643
+ const validRelativePath = (value) =>
1644
+ !value.split('/').some((part) => part === '' || part === '.' || part === '..') &&
1645
+ !/^[A-Za-z]:/u.test(value);
547
1646
 
548
- /** Returns located, value-redacted errors. No option bypasses shape, safety or digest checks. */
1647
+ /**
1648
+ * Returns located, value-redacted errors. No option bypasses shape, safety or digest checks.
1649
+ * @param {import('./diagram-authoring-contracts.d.mts').DiagramAuthoringValidationOptions} [options]
1650
+ * @returns {ReturnType<typeof import('./diagram-authoring-contracts.d.mts').validateDiagramAuthoringArtifact>}
1651
+ */
549
1652
  export function validateDiagramAuthoringArtifact(kind, value, options = {}) {
550
1653
  const issues = inspectData(value);
551
1654
  if (issues.length) return issues;
552
1655
  const optionIssues = inspectData(options);
553
- if (optionIssues.length) return optionIssues.map((entry) => ({ ...entry, path: entry.path.replace(/^\$/u, '$options') }));
554
- if (!options || Array.isArray(options) || typeof options !== 'object' || Object.keys(options).some((key) => !['document', 'bundle', 'baseBundle', 'sourceText'].includes(key))) return [error('$options', 'options', 'Only explicit document, bundle, baseBundle and sourceText contexts are accepted.')];
555
- if (options.sourceText !== undefined && typeof options.sourceText !== 'string') return [error('$options.sourceText', 'type', 'Source text context must be a string.')];
556
- if (typeof kind !== 'string' || !Object.hasOwn(DIAGRAM_AUTHORING_SCHEMAS, kind)) return [error('$', 'contract', 'Unknown diagram authoring contract.')];
1656
+ if (optionIssues.length)
1657
+ return optionIssues.map((entry) => ({
1658
+ ...entry,
1659
+ path: entry.path.replace(/^\$/u, '$options'),
1660
+ }));
1661
+ if (
1662
+ !options ||
1663
+ Array.isArray(options) ||
1664
+ typeof options !== 'object' ||
1665
+ Object.keys(options).some(
1666
+ (key) => !['document', 'bundle', 'baseBundle', 'sourceText'].includes(key),
1667
+ )
1668
+ )
1669
+ return [
1670
+ error(
1671
+ '$options',
1672
+ 'options',
1673
+ 'Only explicit document, bundle, baseBundle and sourceText contexts are accepted.',
1674
+ ),
1675
+ ];
1676
+ if (options.sourceText !== undefined && typeof options.sourceText !== 'string')
1677
+ return [error('$options.sourceText', 'type', 'Source text context must be a string.')];
1678
+ if (typeof kind !== 'string' || !Object.hasOwn(DIAGRAM_AUTHORING_SCHEMAS, kind))
1679
+ return [error('$', 'contract', 'Unknown diagram authoring contract.')];
557
1680
  const shapeIssues = validateJson(value, DIAGRAM_AUTHORING_SCHEMAS[kind]);
558
- if (shapeIssues.length) return shapeIssues.slice(0, 128).map(({ path, rule }) => error(path, rule, 'Value does not satisfy the diagram authoring contract.'));
1681
+ if (shapeIssues.length)
1682
+ return shapeIssues
1683
+ .slice(0, 128)
1684
+ .map(({ path, rule }) =>
1685
+ error(path, rule, 'Value does not satisfy the diagram authoring contract.'),
1686
+ );
559
1687
  // Context is untrusted too. Validate it before reading nested fields or using a digest.
560
- for (const name of ['document', 'bundle', 'baseBundle']) if (options[name] !== undefined) {
561
- const contextKind = name === 'document' ? 'diagram-document' : 'diagram-authoring-bundle';
562
- const failures = validateDiagramAuthoringArtifact(contextKind, options[name]);
563
- issues.push(...failures.map((entry) => ({ ...entry, path: entry.path.replace(/^\$/u, `$options.${name}`) })));
564
- }
1688
+ for (const name of ['document', 'bundle', 'baseBundle'])
1689
+ if (options[name] !== undefined) {
1690
+ const contextKind = name === 'document' ? 'diagram-document' : 'diagram-authoring-bundle';
1691
+ const failures = validateDiagramAuthoringArtifact(contextKind, options[name]);
1692
+ issues.push(
1693
+ ...failures.map((entry) => ({
1694
+ ...entry,
1695
+ path: entry.path.replace(/^\$/u, `$options.${name}`),
1696
+ })),
1697
+ );
1698
+ }
565
1699
  if (issues.length) return issues;
566
- if (options.bundle && options.baseBundle && !same(options.bundle, options.baseBundle)) return [error('$options', 'basis', 'Conflicting bundle contexts are not accepted.')];
1700
+ if (options.bundle && options.baseBundle && !same(options.bundle, options.baseBundle))
1701
+ return [error('$options', 'basis', 'Conflicting bundle contexts are not accepted.')];
567
1702
  const contextBundle = options.baseBundle ?? options.bundle;
568
1703
  const contextDoc = options.document ?? contextBundle?.document;
569
- if (options.document && contextBundle && !same(options.document, contextBundle.document)) return [error('$options.document', 'basis', 'Document context must match the supplied bundle.')];
570
- if (options.sourceText !== undefined && contextBundle?.originalSource && options.sourceText !== contextBundle.originalSource.text) return [error('$options.sourceText', 'source-digest', 'Source text context must match the supplied bundle.')];
1704
+ if (options.document && contextBundle && !same(options.document, contextBundle.document))
1705
+ return [
1706
+ error('$options.document', 'basis', 'Document context must match the supplied bundle.'),
1707
+ ];
1708
+ if (
1709
+ options.sourceText !== undefined &&
1710
+ contextBundle?.originalSource &&
1711
+ options.sourceText !== contextBundle.originalSource.text
1712
+ )
1713
+ return [
1714
+ error(
1715
+ '$options.sourceText',
1716
+ 'source-digest',
1717
+ 'Source text context must match the supplied bundle.',
1718
+ ),
1719
+ ];
571
1720
  switch (kind) {
572
- case 'diagram-document': documentIssues(value, '$', issues); break;
573
- case 'diagram-presentation': presentationIssues(value, contextDoc, '$', issues); break;
574
- case 'diagram-authoring-bundle': bundleIssues(value, '$', issues); break;
575
- case 'diagram-source-map': sourceMapIssues(value, contextDoc, options.sourceText ?? contextBundle?.originalSource?.text, '$', issues); break;
576
- case 'diagram-edit-transaction': transactionIssues(value, contextBundle, '$', issues); break;
1721
+ case 'diagram-document':
1722
+ documentIssues(value, '$', issues);
1723
+ break;
1724
+ case 'diagram-presentation':
1725
+ presentationIssues(value, contextDoc, '$', issues);
1726
+ break;
1727
+ case 'diagram-authoring-bundle':
1728
+ bundleIssues(value, '$', issues);
1729
+ break;
1730
+ case 'diagram-source-map':
1731
+ sourceMapIssues(
1732
+ value,
1733
+ contextDoc,
1734
+ options.sourceText ?? contextBundle?.originalSource?.text,
1735
+ '$',
1736
+ issues,
1737
+ );
1738
+ break;
1739
+ case 'diagram-edit-transaction':
1740
+ transactionIssues(value, contextBundle, '$', issues);
1741
+ break;
577
1742
  case 'diagram-change-proposal':
578
1743
  basisIssues(value, contextBundle, '$', issues);
579
1744
  transactionIssues(value.transaction, contextBundle, '$.transaction', issues);
580
- if (value.diagramId !== value.transaction.diagramId || !same(value.base, value.transaction.base)) issues.push(error('$.transaction', 'basis', 'Proposal and transaction must identify the same exact diagram snapshot.'));
1745
+ if (
1746
+ value.diagramId !== value.transaction.diagramId ||
1747
+ !same(value.base, value.transaction.base)
1748
+ )
1749
+ issues.push(
1750
+ error(
1751
+ '$.transaction',
1752
+ 'basis',
1753
+ 'Proposal and transaction must identify the same exact diagram snapshot.',
1754
+ ),
1755
+ );
1756
+ break;
1757
+ case 'diagram-fidelity-report':
1758
+ fidelityIssues(value, contextBundle, '$', issues);
581
1759
  break;
582
- case 'diagram-fidelity-report': fidelityIssues(value, contextBundle, '$', issues); break;
583
1760
  case 'diagram-manifest':
584
1761
  basisIssues(value, contextBundle, '$', issues);
585
- if (!validRelativePath(value.bundle.path)) issues.push(error('$.bundle.path', 'relative-path', 'Bundle path must remain within its artifact scope.'));
586
- if (!value.bundle.path.endsWith('.planr-diagram-bundle.json')) issues.push(error('$.bundle.path', 'bundle-path', 'The canonical bundle uses the planr-diagram-bundle.json extension.'));
1762
+ if (!validRelativePath(value.bundle.path))
1763
+ issues.push(
1764
+ error(
1765
+ '$.bundle.path',
1766
+ 'relative-path',
1767
+ 'Bundle path must remain within its artifact scope.',
1768
+ ),
1769
+ );
1770
+ if (!value.bundle.path.endsWith('.planr-diagram-bundle.json'))
1771
+ issues.push(
1772
+ error(
1773
+ '$.bundle.path',
1774
+ 'bundle-path',
1775
+ 'The canonical bundle uses the planr-diagram-bundle.json extension.',
1776
+ ),
1777
+ );
587
1778
  value.outputs.forEach((entry, i) => {
588
- if (!validRelativePath(entry.path)) issues.push(error(`$.outputs[${i}].path`, 'relative-path', 'Output path must remain within its artifact scope.'));
589
- if (entry.path === value.bundle.path) issues.push(error(`$.outputs[${i}].path`, 'canonical-output-collision', 'A derived output must not overwrite the canonical bundle.'));
590
- if (entry.fidelity.targetFormat !== ({ 'image/svg+xml': 'svg', 'text/html': 'html', 'image/png': 'png' })[entry.mediaType]) issues.push(error(`$.outputs[${i}].fidelity.targetFormat`, 'output-format', 'Output fidelity must describe the declared media type.'));
1779
+ if (!validRelativePath(entry.path))
1780
+ issues.push(
1781
+ error(
1782
+ `$.outputs[${i}].path`,
1783
+ 'relative-path',
1784
+ 'Output path must remain within its artifact scope.',
1785
+ ),
1786
+ );
1787
+ if (entry.path === value.bundle.path)
1788
+ issues.push(
1789
+ error(
1790
+ `$.outputs[${i}].path`,
1791
+ 'canonical-output-collision',
1792
+ 'A derived output must not overwrite the canonical bundle.',
1793
+ ),
1794
+ );
1795
+ if (
1796
+ entry.fidelity.targetFormat !==
1797
+ { 'image/svg+xml': 'svg', 'text/html': 'html', 'image/png': 'png' }[entry.mediaType]
1798
+ )
1799
+ issues.push(
1800
+ error(
1801
+ `$.outputs[${i}].fidelity.targetFormat`,
1802
+ 'output-format',
1803
+ 'Output fidelity must describe the declared media type.',
1804
+ ),
1805
+ );
591
1806
  fidelityIssues(entry.fidelity, contextBundle, `$.outputs[${i}].fidelity`, issues);
592
- if (entry.fidelity.diagramId !== value.diagramId || !same(entry.fidelity.basis, value.basis)) issues.push(error(`$.outputs[${i}].fidelity`, 'basis', 'Every output must identify the manifest snapshot.'));
1807
+ if (
1808
+ entry.fidelity.diagramId !== value.diagramId ||
1809
+ !same(entry.fidelity.basis, value.basis)
1810
+ )
1811
+ issues.push(
1812
+ error(
1813
+ `$.outputs[${i}].fidelity`,
1814
+ 'basis',
1815
+ 'Every output must identify the manifest snapshot.',
1816
+ ),
1817
+ );
593
1818
  });
594
- if (new Set(value.outputs.map((entry) => entry.path)).size !== value.outputs.length) issues.push(error('$.outputs', 'duplicate-path', 'Output paths must be unique.'));
1819
+ if (new Set(value.outputs.map((entry) => entry.path)).size !== value.outputs.length)
1820
+ issues.push(error('$.outputs', 'duplicate-path', 'Output paths must be unique.'));
595
1821
  break;
596
1822
  case 'diagram-publication-state':
597
- if (value.draft === null && value.published === null) issues.push(error('$', 'publication-reference', 'Publication metadata must identify at least one snapshot.'));
598
- if (contextBundle && (value.diagramId !== contextBundle.diagramId || ![value.draft, value.published].some((entry) => entry && same(entry, expectedSnapshot(contextBundle))))) issues.push(error('$', 'basis', 'Publication metadata does not reference the supplied snapshot.'));
1823
+ if (value.draft === null && value.published === null)
1824
+ issues.push(
1825
+ error(
1826
+ '$',
1827
+ 'publication-reference',
1828
+ 'Publication metadata must identify at least one snapshot.',
1829
+ ),
1830
+ );
1831
+ if (
1832
+ contextBundle &&
1833
+ (value.diagramId !== contextBundle.diagramId ||
1834
+ ![value.draft, value.published].some(
1835
+ (entry) => entry && same(entry, expectedSnapshot(contextBundle)),
1836
+ ))
1837
+ )
1838
+ issues.push(
1839
+ error('$', 'basis', 'Publication metadata does not reference the supplied snapshot.'),
1840
+ );
599
1841
  break;
600
1842
  case 'diagram-authoring-capabilities':
601
- if (!same(value, DIAGRAM_AUTHORING_CAPABILITIES)) issues.push(error('$', 'capability-certification', 'Capability claims must match the versioned certification catalog exactly.'));
1843
+ if (!same(value, DIAGRAM_AUTHORING_CAPABILITIES))
1844
+ issues.push(
1845
+ error(
1846
+ '$',
1847
+ 'capability-certification',
1848
+ 'Capability claims must match the versioned certification catalog exactly.',
1849
+ ),
1850
+ );
1851
+ break;
1852
+ default:
602
1853
  break;
603
- default: break;
604
1854
  }
605
1855
  return issues.slice(0, 128);
606
1856
  }
1857
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').assertDiagramAuthoringArtifact} */
607
1858
  export function assertDiagramAuthoringArtifact(kind, value, options) {
608
1859
  const errors = validateDiagramAuthoringArtifact(kind, value, options);
609
1860
  if (errors.length) {
610
- const failure = new TypeError(`Invalid ${kind}: ${errors.map((entry) => `${entry.path}: ${entry.rule}`).join('; ')}`);
611
- failure.errors = errors;
612
- throw failure;
1861
+ throw Object.assign(
1862
+ new TypeError(
1863
+ `Invalid ${kind}: ${errors.map((entry) => `${entry.path}: ${entry.rule}`).join('; ')}`,
1864
+ ),
1865
+ { errors },
1866
+ );
613
1867
  }
614
1868
  return value;
615
1869
  }
616
- export const validateDiagramDocument = (value, options) => validateDiagramAuthoringArtifact('diagram-document', value, options);
617
- export const assertDiagramDocument = (value, options) => assertDiagramAuthoringArtifact('diagram-document', value, options);
618
- export const validateDiagramPresentation = (value, options) => validateDiagramAuthoringArtifact('diagram-presentation', value, options);
619
- export const assertDiagramPresentation = (value, options) => assertDiagramAuthoringArtifact('diagram-presentation', value, options);
620
- export const validateDiagramAuthoringBundle = (value, options) => validateDiagramAuthoringArtifact('diagram-authoring-bundle', value, options);
621
- export const assertDiagramAuthoringBundle = (value, options) => assertDiagramAuthoringArtifact('diagram-authoring-bundle', value, options);
622
- export const validateDiagramEditTransaction = (value, options) => validateDiagramAuthoringArtifact('diagram-edit-transaction', value, options);
623
- export const assertDiagramEditTransaction = (value, options) => assertDiagramAuthoringArtifact('diagram-edit-transaction', value, options);
1870
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').validateDiagramDocument} */
1871
+ export const validateDiagramDocument = (value, options) =>
1872
+ validateDiagramAuthoringArtifact('diagram-document', value, options);
1873
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').assertDiagramDocument} */
1874
+ export const assertDiagramDocument = (value, options) =>
1875
+ assertDiagramAuthoringArtifact('diagram-document', value, options);
1876
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').validateDiagramPresentation} */
1877
+ export const validateDiagramPresentation = (value, options) =>
1878
+ validateDiagramAuthoringArtifact('diagram-presentation', value, options);
1879
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').assertDiagramPresentation} */
1880
+ export const assertDiagramPresentation = (value, options) =>
1881
+ assertDiagramAuthoringArtifact('diagram-presentation', value, options);
1882
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').validateDiagramAuthoringBundle} */
1883
+ export const validateDiagramAuthoringBundle = (value, options) =>
1884
+ validateDiagramAuthoringArtifact('diagram-authoring-bundle', value, options);
1885
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').assertDiagramAuthoringBundle} */
1886
+ export const assertDiagramAuthoringBundle = (value, options) =>
1887
+ assertDiagramAuthoringArtifact('diagram-authoring-bundle', value, options);
1888
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').validateDiagramEditTransaction} */
1889
+ export const validateDiagramEditTransaction = (value, options) =>
1890
+ validateDiagramAuthoringArtifact('diagram-edit-transaction', value, options);
1891
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').assertDiagramEditTransaction} */
1892
+ export const assertDiagramEditTransaction = (value, options) =>
1893
+ assertDiagramAuthoringArtifact('diagram-edit-transaction', value, options);
1894
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').summarizeDiagramAuthoringContent} */
624
1895
  export function summarizeDiagramAuthoringContent(bundle) {
625
1896
  assertDiagramAuthoringBundle(bundle);
626
1897
  const elementCount = allElements(bundle.document).length;
@@ -628,41 +1899,141 @@ export function summarizeDiagramAuthoringContent(bundle) {
628
1899
  }
629
1900
 
630
1901
  // Inspect the generated, exact frozen v1.6 descriptor without creating migrated data.
1902
+ /** @returns {ReturnType<typeof import('./diagram-authoring-contracts.d.mts').inspectLegacyDiagramDocument>} */
631
1903
  export function inspectLegacyDiagramDocument(value) {
632
1904
  let errors = inspectData(value);
633
- if (!errors.length && value && typeof value === 'object' && (value.protocolVersion !== '1.6.0' || value.schemaVersion !== '1.0.0')) errors.push(error('$', 'unsupported-version', 'This inspector accepts only the frozen v1.6 diagram contract.'));
634
- if (!errors.length) errors = validateJson(value, LEGACY_DIAGRAM_DOCUMENT_SCHEMA).slice(0, 128).map(({ path, rule }) => error(path, rule, 'Value does not satisfy the legacy diagram contract.'));
1905
+ if (
1906
+ !errors.length &&
1907
+ value &&
1908
+ typeof value === 'object' &&
1909
+ (value.protocolVersion !== '1.6.0' || value.schemaVersion !== '1.0.0')
1910
+ )
1911
+ errors.push(
1912
+ error(
1913
+ '$',
1914
+ 'unsupported-version',
1915
+ 'This inspector accepts only the frozen v1.6 diagram contract.',
1916
+ ),
1917
+ );
1918
+ if (!errors.length)
1919
+ errors = validateJson(value, LEGACY_DIAGRAM_DOCUMENT_SCHEMA)
1920
+ .slice(0, 128)
1921
+ .map(({ path, rule }) =>
1922
+ error(path, rule, 'Value does not satisfy the legacy diagram contract.'),
1923
+ );
635
1924
  let grammar = null;
636
1925
  if (!errors.length) {
637
- grammar = DIAGRAM_REGISTRIES['diagram-grammars.json'].grammars.find((entry) => entry.grammarId === value.grammar.id);
1926
+ grammar = DIAGRAM_REGISTRIES['diagram-grammars.json'].grammars.find(
1927
+ (entry) => entry.grammarId === value.grammar.id,
1928
+ );
638
1929
  if (!grammar) errors.push(error('$.grammar.id', 'grammar', 'Unknown legacy grammar.'));
639
- if (value.documentDigest !== diagramDocumentDigest(value)) errors.push(error('$.documentDigest', 'digest', 'Legacy semantic digest does not match.'));
1930
+ if (value.documentDigest !== diagramDocumentDigest(value))
1931
+ errors.push(error('$.documentDigest', 'digest', 'Legacy semantic digest does not match.'));
640
1932
  const elements = allElements(value);
641
- if (!elements.length && !value.emphasis.length) errors.push(error('$', 'visible-content', 'The legacy document contract requires content.'));
642
- if (elements.length + value.emphasis.length > 10000) errors.push(error('$', 'resource-limit', 'Too many legacy semantic primitive entries.'));
1933
+ if (!elements.length && !value.emphasis.length)
1934
+ errors.push(error('$', 'visible-content', 'The legacy document contract requires content.'));
1935
+ if (elements.length + value.emphasis.length > 10000)
1936
+ errors.push(error('$', 'resource-limit', 'Too many legacy semantic primitive entries.'));
643
1937
  const itemIds = new Set(elements.map((entry) => entry.id));
644
- if (itemIds.size !== elements.length) errors.push(error('$', 'duplicate-id', 'Legacy semantic IDs must be unique.'));
645
- for (const collection of ['relations', 'groups', 'lanes', 'sets', 'annotations', 'emphasis']) value[collection].forEach((entry, i) => {
646
- const refs = collection === 'relations' ? [entry.from, entry.to] : entry.members ?? (entry.targetId == null ? [] : [entry.targetId]);
647
- if (refs.some((ref) => !itemIds.has(ref))) errors.push(error(`$.${collection}[${i}]`, 'reference', 'Legacy semantic reference is missing.'));
1938
+ if (itemIds.size !== elements.length)
1939
+ errors.push(error('$', 'duplicate-id', 'Legacy semantic IDs must be unique.'));
1940
+ for (const collection of ['relations', 'groups', 'lanes', 'sets', 'annotations', 'emphasis'])
1941
+ value[collection].forEach((entry, i) => {
1942
+ const refs =
1943
+ collection === 'relations'
1944
+ ? [entry.from, entry.to]
1945
+ : (entry.members ?? (entry.targetId == null ? [] : [entry.targetId]));
1946
+ if (refs.some((ref) => !itemIds.has(ref)))
1947
+ errors.push(
1948
+ error(`$.${collection}[${i}]`, 'reference', 'Legacy semantic reference is missing.'),
1949
+ );
1950
+ });
1951
+ value.accessibility.readingOrder.forEach((entry, i) => {
1952
+ if (!itemIds.has(entry))
1953
+ errors.push(
1954
+ error(
1955
+ `$.accessibility.readingOrder[${i}]`,
1956
+ 'reference',
1957
+ 'Legacy reading order target is missing.',
1958
+ ),
1959
+ );
648
1960
  });
649
- value.accessibility.readingOrder.forEach((entry, i) => { if (!itemIds.has(entry)) errors.push(error(`$.accessibility.readingOrder[${i}]`, 'reference', 'Legacy reading order target is missing.')); });
650
1961
  if (grammar) {
651
- if (!grammar.directions.includes(value.layout.direction)) errors.push(error('$.layout.direction', 'profile-direction', 'Direction is not supported by the legacy grammar.'));
652
- if (!['quadrant', 'scatter', 'wardley'].includes(grammar.grammarId) && value.nodes.some((entry) => entry.semanticPosition != null)) errors.push(error('$.nodes', 'semantic-position', 'Semantic position is not supported by this legacy grammar.'));
653
- const plural = { node: 'nodes', relation: 'relations', group: 'groups', lane: 'lanes', event: 'events', series: 'series', axis: 'axes', set: 'sets', annotation: 'annotations', emphasis: 'emphasis' };
1962
+ if (!grammar.directions.includes(value.layout.direction))
1963
+ errors.push(
1964
+ error(
1965
+ '$.layout.direction',
1966
+ 'profile-direction',
1967
+ 'Direction is not supported by the legacy grammar.',
1968
+ ),
1969
+ );
1970
+ if (
1971
+ !['quadrant', 'scatter', 'wardley'].includes(grammar.grammarId) &&
1972
+ value.nodes.some((entry) => entry.semanticPosition != null)
1973
+ )
1974
+ errors.push(
1975
+ error(
1976
+ '$.nodes',
1977
+ 'semantic-position',
1978
+ 'Semantic position is not supported by this legacy grammar.',
1979
+ ),
1980
+ );
1981
+ const plural = {
1982
+ node: 'nodes',
1983
+ relation: 'relations',
1984
+ group: 'groups',
1985
+ lane: 'lanes',
1986
+ event: 'events',
1987
+ series: 'series',
1988
+ axis: 'axes',
1989
+ set: 'sets',
1990
+ annotation: 'annotations',
1991
+ emphasis: 'emphasis',
1992
+ };
654
1993
  for (const [primitive, collection] of Object.entries(plural)) {
655
- if (value[collection].length && !grammar.allowedPrimitives.includes(primitive)) errors.push(error(`$.${collection}`, 'profile-primitive', 'Primitive is not allowed by this legacy grammar.'));
656
- if (!value[collection].length && grammar.requiredPrimitives.includes(primitive)) errors.push(error(`$.${collection}`, 'required-primitive', 'Required legacy primitive is missing.'));
1994
+ if (value[collection].length && !grammar.allowedPrimitives.includes(primitive))
1995
+ errors.push(
1996
+ error(
1997
+ `$.${collection}`,
1998
+ 'profile-primitive',
1999
+ 'Primitive is not allowed by this legacy grammar.',
2000
+ ),
2001
+ );
2002
+ if (!value[collection].length && grammar.requiredPrimitives.includes(primitive))
2003
+ errors.push(
2004
+ error(`$.${collection}`, 'required-primitive', 'Required legacy primitive is missing.'),
2005
+ );
657
2006
  }
658
2007
  }
659
2008
  }
660
2009
  const valid = errors.length === 0;
661
- const unsupportedNodeKinds = valid ? [...new Set(value.nodes.filter((entry) => !semanticKinds.includes(entry.kind)).map((entry) => entry.kind))] : [];
662
- const authoringAvailable = valid && getDiagramAuthoringCapability(value.grammar.id) !== null && !unsupportedNodeKinds.length && !value.relations.some((entry) => entry.kind === 'containment') && !['events', 'series', 'axes', 'sets'].some((key) => value[key].length) && !(value.grammar.id === 'flowchart' || value.grammar.id === 'architecture' ? value.lanes.length : false);
2010
+ const unsupportedNodeKinds = valid
2011
+ ? [
2012
+ ...new Set(
2013
+ value.nodes
2014
+ .filter((entry) => !semanticKinds.includes(entry.kind))
2015
+ .map((entry) => entry.kind),
2016
+ ),
2017
+ ]
2018
+ : [];
2019
+ const authoringAvailable =
2020
+ valid &&
2021
+ getDiagramAuthoringCapability(value.grammar.id) !== null &&
2022
+ !unsupportedNodeKinds.length &&
2023
+ !value.relations.some((entry) => entry.kind === 'containment') &&
2024
+ !['events', 'series', 'axes', 'sets'].some((key) => value[key].length) &&
2025
+ !(value.grammar.id === 'flowchart' || value.grammar.id === 'architecture'
2026
+ ? value.lanes.length
2027
+ : false);
663
2028
  return {
664
- valid, errors, diagramId: valid ? value.diagramId : null, grammarId: valid ? value.grammar.id : null,
665
- authoringAvailable, requiresDerivedPresentation: valid, unsupportedNodeKinds,
666
- adoption: 'explicit-save-required', sourceModified: false,
2029
+ valid,
2030
+ errors,
2031
+ diagramId: valid ? value.diagramId : null,
2032
+ grammarId: valid ? value.grammar.id : null,
2033
+ authoringAvailable,
2034
+ requiresDerivedPresentation: valid,
2035
+ unsupportedNodeKinds,
2036
+ adoption: 'explicit-save-required',
2037
+ sourceModified: false,
667
2038
  };
668
2039
  }