@openplanr/protocol 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +12 -0
  2. package/package.json +9 -1
  3. package/registries/commands.json +8 -8
  4. package/registries/diagram-authoring-capabilities.json +660 -0
  5. package/registries/skills.json +12 -12
  6. package/schemas/v1.11.0/design-handoff-readiness.schema.json +398 -0
  7. package/schemas/v1.11.0/design-implementation-handoff.schema.json +518 -0
  8. package/schemas/v1.11.0/design-planning-lineage.schema.json +106 -0
  9. package/schemas/v1.13.0/diagram-authoring-bundle.schema.json +1079 -0
  10. package/schemas/v1.13.0/diagram-authoring-capabilities.schema.json +211 -0
  11. package/schemas/v1.13.0/diagram-change-proposal.schema.json +3296 -0
  12. package/schemas/v1.13.0/diagram-document.schema.json +435 -0
  13. package/schemas/v1.13.0/diagram-edit-transaction.schema.json +3193 -0
  14. package/schemas/v1.13.0/diagram-fidelity-report.schema.json +157 -0
  15. package/schemas/v1.13.0/diagram-manifest.schema.json +311 -0
  16. package/schemas/v1.13.0/diagram-presentation.schema.json +395 -0
  17. package/schemas/v1.13.0/diagram-publication-state.schema.json +107 -0
  18. package/schemas/v1.13.0/diagram-source-map.schema.json +170 -0
  19. package/src/browser-contracts.d.mts +3 -1
  20. package/src/browser-contracts.mjs +14 -2
  21. package/src/contracts.mjs +27 -1
  22. package/src/design-handoff-contracts.d.mts +92 -0
  23. package/src/design-handoff-contracts.mjs +338 -0
  24. package/src/diagram-authoring-contracts.d.mts +112 -0
  25. package/src/diagram-authoring-contracts.mjs +668 -0
  26. package/src/diagram-contracts.d.mts +1 -1
  27. package/src/diagram-contracts.mjs +7 -4
  28. package/src/generated/canonical-registries.mjs +20 -20
  29. package/src/generated/legacy-diagram-schema.mjs +767 -0
  30. package/src/index.d.mts +2 -0
  31. package/src/index.mjs +4 -0
@@ -0,0 +1,668 @@
1
+ import { canonicalizeJson, sha256Jcs, sha256Hex } from './canonical-json.mjs';
2
+ import { validateJson } from './json-schema.mjs';
3
+ import { DIAGRAM_REGISTRIES } from './generated/diagram-registries.mjs';
4
+ import { LEGACY_DIAGRAM_DOCUMENT_SCHEMA } from './generated/legacy-diagram-schema.mjs';
5
+
6
+ /** Portable, inert data contracts. Validation confers no authorization or readiness. */
7
+ export const DIAGRAM_AUTHORING_PROTOCOL_VERSION = '1.13.0';
8
+ export const DIAGRAM_AUTHORING_CONTRACT_VERSION = '1.0.0';
9
+ const deepFreeze = (value) => {
10
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
11
+ Object.values(value).forEach(deepFreeze);
12
+ Object.freeze(value);
13
+ }
14
+ return value;
15
+ };
16
+ export const DIAGRAM_EDIT_OPERATION_CLASSES = deepFreeze([
17
+ 'insert-elements', 'update-semantics', 'remove-elements', 'set-membership-order',
18
+ 'set-geometry', 'set-appearance-locks',
19
+ ]);
20
+ export const DIAGRAM_AUTHORING_LIMITS = deepFreeze({
21
+ depth: 48, values: 500000, textCodeUnits: 8388608, sourceBytes: 1048576,
22
+ elements: 10000, operations: 256, coordinate: 1000000,
23
+ });
24
+
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 } : {}) });
27
+ const nullable = (schema) => ({ anyOf: [{ type: 'null' }, schema] });
28
+ const str = (maxLength = 4096, minLength = 0) => ({ type: 'string', minLength, maxLength });
29
+ const enumOf = (...values) => ({ enum: values });
30
+ const id = { type: 'string', pattern: '^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$', minLength: 1, maxLength: 128 };
31
+ const digest = { type: 'string', pattern: '^sha256:[a-f0-9]{64}$' };
32
+ 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._/-]*$' };
34
+ const coordinate = { type: 'number', minimum: -1000000, maximum: 1000000 };
35
+ const positiveSize = { type: 'number', minimum: 0.01, maximum: 1000000 };
36
+ const index = { type: 'integer', minimum: 0, maximum: 10000 };
37
+ const ids = arr(id, 10000, 0, true);
38
+ const semanticKinds = ['process', 'start', 'end', 'decision', 'data-store', 'component'];
39
+ 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 }) });
42
+ const container = closed({ id, label: str(), members: ids });
43
+ const annotation = closed({ id, text: str(), targetId: nullable(id) });
44
+ const emphasis = closed({ targetId: id, level: enumOf('primary', 'secondary', 'muted') });
45
+ 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),
49
+ };
50
+ const bounds = closed({ x: coordinate, y: coordinate, width: positiveSize, height: positiveSize });
51
+ 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) });
54
+ const labelPlacement = closed({ x: coordinate, y: coordinate, width: positiveSize });
55
+ const appearance = closed({
56
+ shape: enumOf('rectangle', 'rounded-rectangle', 'ellipse', 'diamond', 'cylinder', 'text', 'container', 'connector'),
57
+ fill: enumOf('surface', 'accent', 'success', 'warning', 'danger', 'transparent'),
58
+ stroke: enumOf('default', 'accent', 'muted', 'danger', 'none'),
59
+ strokeWidth: { type: 'number', minimum: 0, maximum: 16 },
60
+ strokeStyle: enumOf('solid', 'dashed', 'dotted'),
61
+ fontSize: { type: 'integer', minimum: 8, maximum: 72 },
62
+ textAlign: enumOf('left', 'center', 'right'),
63
+ });
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 });
67
+ const schema = (name, kind, properties) => ({
68
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
69
+ $id: `https://openplanr.dev/schemas/v1.13.0/${name}.schema.json`,
70
+ '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 }),
72
+ });
73
+
74
+ 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,
78
+ accessibility: closed({ title: str(), description: str(), readingOrder: ids }),
79
+ documentDigest: digest,
80
+ });
81
+ 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,
86
+ });
87
+ const range = closed({ startByte: { type: 'integer', minimum: 0, maximum: 1048576 }, endByte: { type: 'integer', minimum: 0, maximum: 1048576 } });
88
+ const sourceMapSchema = schema('diagram-source-map', 'diagram-source-map', {
89
+ diagramId: id, semanticDigest: digest, sourceDigest: digest,
90
+ sourceByteLength: { type: 'integer', minimum: 0, maximum: 1048576 },
91
+ encoding: { const: 'utf-8' }, parser: closed({ id: token, version: str(64, 1) }),
92
+ 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),
94
+ });
95
+ const fidelityValue = enumOf('lossless', 'partial', 'unsupported');
96
+ 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),
101
+ });
102
+ 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),
115
+ });
116
+ 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() }),
120
+ 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) }),
124
+ ];
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 });
127
+ 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
+ ] };
136
+ const transactionSchema = schema('diagram-edit-transaction', 'diagram-edit-transaction', {
137
+ transactionId: id, diagramId: id, base: snapshot, operations: arr(operation, 256, 1), undoOf: nullable(id),
138
+ });
139
+ 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 }),
142
+ status: enumOf('proposed', 'accepted', 'rejected', 'stale'),
143
+ });
144
+ const publicationSchema = schema('diagram-publication-state', 'diagram-publication-state', {
145
+ diagramId: id, draft: nullable(snapshot), published: nullable(snapshot),
146
+ audience: enumOf('private', 'company', 'public'),
147
+ capabilitySemantics: { const: 'descriptive-only-requires-host-authorization' },
148
+ });
149
+ const manifestSchema = schema('diagram-manifest', 'diagram-manifest', {
150
+ diagramId: id, basis: snapshot, bundle: closed({ path: relativePath, transportDigest: digest }),
151
+ 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),
153
+ });
154
+ // Export consumers record the concrete palette version independently of renderer code.
155
+ 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) });
157
+ 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),
161
+ 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),
168
+ });
169
+ 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,
175
+ };
176
+ 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`])));
178
+ 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 }));
196
+ const profileIds = ['flowchart', 'process', 'swimlane', 'architecture'];
197
+ 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,
200
+ 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 },
204
+ })),
205
+ unsupportedGrammars: DIAGRAM_REGISTRIES['diagram-grammars.json'].grammars.map((entry) => entry.grammarId).filter((value) => !profileIds.includes(value)),
206
+ });
207
+ export function getDiagramAuthoringCapability(grammarId) {
208
+ return DIAGRAM_AUTHORING_CAPABILITIES.profiles.find((entry) => entry.grammarId === grammarId) ?? null;
209
+ }
210
+
211
+ const error = (path, rule, detail) => ({ path, rule, detail });
212
+ // Descriptors are inspected before values; neither validation nor hashing invokes accessors.
213
+ function inspectData(value) {
214
+ const issues = [];
215
+ const ancestors = new Set();
216
+ let count = 0;
217
+ let textSize = 0;
218
+ function visit(current, path, depth) {
219
+ if (issues.length) return;
220
+ 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;
222
+ }
223
+ if (typeof current === 'string') {
224
+ 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.'));
227
+ return;
228
+ }
229
+ 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; }
232
+ 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;
235
+ }
236
+ if (ancestors.has(current)) { issues.push(error(path, 'cycle', 'Cyclic data is not accepted.')); return; }
237
+ ancestors.add(current);
238
+ const descriptors = Object.getOwnPropertyDescriptors(current);
239
+ 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;
242
+ }
243
+ const descriptor = descriptors[key];
244
+ if (descriptor.get || descriptor.set || !('value' in descriptor)) { issues.push(error(path, 'accessor', 'Accessors are not accepted.')); break; }
245
+ 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;
248
+ }
249
+ visit(descriptor.value, Array.isArray(current) ? `${path}[${key}]` : `${path}.${key}`, depth + 1);
250
+ if (issues.length) break;
251
+ }
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.'));
253
+ ancestors.delete(current);
254
+ }
255
+ try { visit(value, '$', 0); } catch { issues.push(error('$', 'plain-data', 'Data cannot be inspected safely.')); }
256
+ return issues;
257
+ }
258
+ function assertData(value) {
259
+ const issues = inspectData(value);
260
+ if (issues.length) throw new TypeError(`${issues[0].path}: ${issues[0].rule}`);
261
+ }
262
+ function digestExcluding(value, field) {
263
+ assertData(value);
264
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Digest input must be an object.');
265
+ const input = { ...value };
266
+ delete input[field];
267
+ return sha256Jcs(input);
268
+ }
269
+ export const diagramDocumentDigest = (value) => digestExcluding(value, 'documentDigest');
270
+ export const diagramPresentationDigest = (value) => digestExcluding(value, 'presentationDigest');
271
+ export const diagramAuthoringBundleDigest = (value) => digestExcluding(value, 'bundleDigest');
272
+ const same = (a, b) => canonicalizeJson(a) === canonicalizeJson(b);
273
+ const sourceDigest = (text) => `sha256:${sha256Hex(text)}`;
274
+ const semanticNames = ['nodes', 'relations', 'groups', 'lanes', 'events', 'series', 'axes', 'sets', 'annotations'];
275
+ const allElements = (doc) => semanticNames.flatMap((name) => doc[name]);
276
+ const expectedSnapshot = (bundle) => ({ bundleDigest: bundle.bundleDigest, semanticDigest: bundle.document.documentDigest, presentationDigest: bundle.presentation.presentationDigest });
277
+ function hasContainmentCycle(parents) {
278
+ const complete = new Set();
279
+ for (const member of parents.keys()) {
280
+ const visited = new Set();
281
+ let current = member;
282
+ while (current && !complete.has(current)) {
283
+ if (visited.has(current)) return true;
284
+ visited.add(current); current = parents.get(current);
285
+ }
286
+ for (const item of visited) complete.add(item);
287
+ }
288
+ return false;
289
+ }
290
+
291
+ function documentIssues(doc, path, issues) {
292
+ const entries = allElements(doc);
293
+ 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
+ }
300
+ 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
+ }));
305
+ 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.')); });
316
+ const emphasisIds = new Set();
317
+ 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.'));
320
+ emphasisIds.add(entry.targetId);
321
+ });
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.'));
324
+ }
325
+ function presentationIssues(value, doc, path, issues) {
326
+ const idsSeen = new Set();
327
+ const byId = doc ? new Map(allElements(doc).map((entry) => [entry.id, entry])) : null;
328
+ const nodes = doc ? new Set(doc.nodes.map((entry) => entry.id)) : null;
329
+ const relations = doc ? new Map(doc.relations.map((entry) => [entry.id, entry])) : null;
330
+ 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.'));
332
+ value.elements.forEach((entry, i) => {
333
+ const location = `${path}.elements[${i}]`;
334
+ geometryIssues(entry, location, issues);
335
+ if (idsSeen.has(entry.elementId)) issues.push(error(`${location}.elementId`, 'duplicate-id', 'Presentation element IDs must be unique.'));
336
+ 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.'));
348
+ });
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.'));
351
+ }
352
+ 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.'));
354
+ const elementIds = doc ? new Set(allElements(doc).map((entry) => entry.id)) : null;
355
+ const sourceIds = new Set();
356
+ let boundaries = null;
357
+ if (text !== undefined) {
358
+ 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] : []));
361
+ boundaries = new Set([0]);
362
+ let cursor = 0;
363
+ for (const character of text) {
364
+ const code = character.codePointAt(0);
365
+ cursor += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4;
366
+ if (requested.has(cursor)) boundaries.add(cursor);
367
+ }
368
+ }
369
+ value.entries.forEach((entry, i) => {
370
+ 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.'));
372
+ 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.'));
374
+ 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.'));
378
+ });
379
+ }
380
+ function bundleIssues(bundle, path, issues) {
381
+ documentIssues(bundle.document, `${path}.document`, issues);
382
+ 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.'));
385
+ 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.'));
388
+ }
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.'));
391
+ }
392
+
393
+ 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.'));
395
+ }
396
+ function transactionIssues(value, bundle, path, issues) {
397
+ 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.'));
399
+ 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;
401
+ const insertedCollections = new Map();
402
+ const inserted = new Set();
403
+ const removed = new Set();
404
+ const capability = bundle ? getDiagramAuthoringCapability(bundle.document.grammar.id) : null;
405
+ const collectionOf = (elementId) => collectionById?.get(elementId) ?? insertedCollections.get(elementId);
406
+ const membershipReferences = (collection, item, location) => {
407
+ if (!collectionById) return;
408
+ 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.'));
411
+ 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.'));
413
+ });
414
+ };
415
+ 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.'));
417
+ };
418
+ const semanticAppearance = (collection, appearance, location) => {
419
+ if (!collection) return;
420
+ 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.'));
425
+ };
426
+ // This inspects references only. Applying changes, checking before-values in sequence,
427
+ // computing inverse operations and committing revisions belong to the edit kernel.
428
+ value.operations.forEach((op, i) => {
429
+ const location = `${path}.operations[${i}]`;
430
+ if (op.type === 'insert-elements' || op.type === 'remove-elements') {
431
+ const entryIds = op.elements.map((entry) => entry.value.id);
432
+ 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.'));
435
+ if (op.type === 'insert-elements' && op.positions) {
436
+ 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.'));
439
+ }
440
+ for (const entry of op.elements) {
441
+ 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.'));
444
+ inserted.add(entry.value.id);
445
+ insertedCollections.set(entry.value.id, entry.collection);
446
+ } 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.'));
450
+ removed.add(entry.value.id);
451
+ }
452
+ }
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
+ });
460
+ // Validate geometry kind and routing even without a semantic context.
461
+ for (const [j, entry] of op.presentation.entries()) {
462
+ const semantic = op.elements.find((item) => item.value.id === entry.elementId);
463
+ geometryIssues(entry, `${location}.presentation[${j}]`, issues);
464
+ semanticGeometry(semantic?.collection, entry, `${location}.presentation[${j}]`);
465
+ semanticAppearance(semantic?.collection, entry.appearance, `${location}.presentation[${j}].appearance`);
466
+ }
467
+ } else if (op.type === 'set-geometry' || op.type === 'set-appearance-locks') {
468
+ const touched = new Set();
469
+ 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.'));
471
+ 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.'));
473
+ for (const side of ['before', 'after']) {
474
+ const changePath = `${location}.changes[${j}].${side}`;
475
+ if (op.type === 'set-geometry') {
476
+ 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`);
479
+ }
480
+ });
481
+ } 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
+ });
494
+ } else if (op.type === 'set-membership-order') {
495
+ for (const side of ['before', 'after']) {
496
+ 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}]`));
499
+ const parents = new Map();
500
+ 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.'));
508
+ }
509
+ }
510
+ });
511
+ }
512
+ 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.'));
518
+ }
519
+ function fidelityIssues(value, bundle, path, issues) {
520
+ basisIssues(value, bundle, path, issues);
521
+ const idsKnown = bundle ? new Set(allElements(bundle.document).map((entry) => entry.id)) : null;
522
+ 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.')); });
525
+ }
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.'));
528
+ 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.'));
533
+ }
534
+ 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.'));
544
+ }
545
+ }
546
+ const validRelativePath = (value) => !value.split('/').some((part) => part === '' || part === '.' || part === '..') && !/^[A-Za-z]:/u.test(value);
547
+
548
+ /** Returns located, value-redacted errors. No option bypasses shape, safety or digest checks. */
549
+ export function validateDiagramAuthoringArtifact(kind, value, options = {}) {
550
+ const issues = inspectData(value);
551
+ if (issues.length) return issues;
552
+ 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.')];
557
+ 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.'));
559
+ // 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
+ }
565
+ 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.')];
567
+ const contextBundle = options.baseBundle ?? options.bundle;
568
+ 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.')];
571
+ 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;
577
+ case 'diagram-change-proposal':
578
+ basisIssues(value, contextBundle, '$', issues);
579
+ 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.'));
581
+ break;
582
+ case 'diagram-fidelity-report': fidelityIssues(value, contextBundle, '$', issues); break;
583
+ case 'diagram-manifest':
584
+ 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.'));
587
+ 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.'));
591
+ 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.'));
593
+ });
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.'));
595
+ break;
596
+ 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.'));
599
+ break;
600
+ 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.'));
602
+ break;
603
+ default: break;
604
+ }
605
+ return issues.slice(0, 128);
606
+ }
607
+ export function assertDiagramAuthoringArtifact(kind, value, options) {
608
+ const errors = validateDiagramAuthoringArtifact(kind, value, options);
609
+ 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;
613
+ }
614
+ return value;
615
+ }
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);
624
+ export function summarizeDiagramAuthoringContent(bundle) {
625
+ assertDiagramAuthoringBundle(bundle);
626
+ const elementCount = allElements(bundle.document).length;
627
+ return { elementCount, hasVisibleContent: elementCount > 0 };
628
+ }
629
+
630
+ // Inspect the generated, exact frozen v1.6 descriptor without creating migrated data.
631
+ export function inspectLegacyDiagramDocument(value) {
632
+ 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.'));
635
+ let grammar = null;
636
+ if (!errors.length) {
637
+ grammar = DIAGRAM_REGISTRIES['diagram-grammars.json'].grammars.find((entry) => entry.grammarId === value.grammar.id);
638
+ 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.'));
640
+ 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.'));
643
+ 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.'));
648
+ });
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
+ 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' };
654
+ 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.'));
657
+ }
658
+ }
659
+ }
660
+ 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);
663
+ 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,
667
+ };
668
+ }