archgraph-argo-beta 0.27.0-beta.2 → 0.27.0-beta.3

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.
@@ -259,8 +259,105 @@ function validateViewElementLimits(document, errors, options = {}) {
259
259
  }
260
260
  }
261
261
 
262
+ // Per-element-type attribute contract (issue #3): required attributes, a
263
+ // controlled vocabulary per attribute (enumByAttr) and uniqueness per attribute.
264
+ // Supplied by the active schema bundle's `attributesByElementType`; absent => no-op
265
+ // (fully backward compatible).
266
+ function attributeEntriesByName(element) {
267
+ const map = new Map();
268
+ const entries = Array.isArray(element && element.attributes) ? element.attributes : [];
269
+ for (const entry of entries) {
270
+ if (!entry || typeof entry !== 'object' || typeof entry.name !== 'string' || entry.name === '') {
271
+ continue;
272
+ }
273
+ if (!map.has(entry.name)) {
274
+ map.set(entry.name, []);
275
+ }
276
+ map.get(entry.name).push(entry);
277
+ }
278
+ return map;
279
+ }
280
+
281
+ function attributeValueOf(entry) {
282
+ if (entry.value !== undefined && entry.value !== null) {
283
+ return entry.value;
284
+ }
285
+ if (entry.content !== undefined && entry.content !== null) {
286
+ return entry.content;
287
+ }
288
+ return undefined;
289
+ }
290
+
291
+ function validateAttributeContracts(document, errors, ontology) {
292
+ const language = resolveOntology(ontology);
293
+ const contracts = language.attributesByElementType;
294
+ if (!contracts || typeof contracts !== 'object') {
295
+ return;
296
+ }
297
+ const uniqueTrackers = new Map();
298
+ for (const type of Object.keys(contracts)) {
299
+ uniqueTrackers.set(type, new Map());
300
+ }
301
+
302
+ for (const element of document.elements || []) {
303
+ if (!element || typeof element !== 'object') {
304
+ continue;
305
+ }
306
+ const contract = contracts[element.type];
307
+ if (!contract || typeof contract !== 'object') {
308
+ continue;
309
+ }
310
+ const byName = attributeEntriesByName(element);
311
+
312
+ for (const name of Array.isArray(contract.required) ? contract.required : []) {
313
+ const entries = byName.get(name);
314
+ const present = Array.isArray(entries) && entries.some((entry) => {
315
+ const value = attributeValueOf(entry);
316
+ return value !== undefined && value !== '';
317
+ });
318
+ if (!present) {
319
+ errors.push(`element '${element.id}' (type '${element.type}') is missing required attribute '${name}'`);
320
+ }
321
+ }
322
+
323
+ const enumByAttr = contract.enumByAttr && typeof contract.enumByAttr === 'object' ? contract.enumByAttr : {};
324
+ for (const [attr, allowed] of Object.entries(enumByAttr)) {
325
+ if (!Array.isArray(allowed)) {
326
+ continue;
327
+ }
328
+ for (const entry of byName.get(attr) || []) {
329
+ const value = attributeValueOf(entry);
330
+ if (value === undefined) {
331
+ continue;
332
+ }
333
+ const matches = allowed.some((option) => option === value || JSON.stringify(option) === JSON.stringify(value));
334
+ if (!matches) {
335
+ errors.push(`element '${element.id}' (type '${element.type}') attribute '${attr}' value ${JSON.stringify(value)} is not one of: ${allowed.map((option) => JSON.stringify(option)).join(', ')}`);
336
+ }
337
+ }
338
+ }
339
+
340
+ for (const attr of Array.isArray(contract.unique) ? contract.unique : []) {
341
+ const tracker = uniqueTrackers.get(element.type);
342
+ for (const entry of byName.get(attr) || []) {
343
+ const value = attributeValueOf(entry);
344
+ if (value === undefined) {
345
+ continue;
346
+ }
347
+ const key = JSON.stringify(value);
348
+ if (tracker.has(key) && tracker.get(key) !== element.id) {
349
+ errors.push(`element '${element.id}' (type '${element.type}') attribute '${attr}' value ${key} duplicates element '${tracker.get(key)}'`);
350
+ } else if (!tracker.has(key)) {
351
+ tracker.set(key, element.id);
352
+ }
353
+ }
354
+ }
355
+ }
356
+ }
357
+
262
358
  module.exports = {
263
359
  validateGraphSemantics,
264
360
  validateArchiMateEndpointMatrix,
265
361
  validateViewElementLimits,
362
+ validateAttributeContracts,
266
363
  };
@@ -99,7 +99,8 @@ function relativeLabel(workspaceRoot, absolutePath) {
99
99
 
100
100
  function buildBundle(kind, dir, workspaceRoot) {
101
101
  const schemaFile = path.join(dir, SCHEMA_BASENAME);
102
- const schema = readJsonFile(schemaFile);
102
+ const schemaExists = isFile(schemaFile);
103
+ const schema = schemaExists ? readJsonFile(schemaFile) : null;
103
104
 
104
105
  const configFile = path.join(dir, CONFIG_BASENAME);
105
106
  const fileConfig = isFile(configFile) ? readJsonFile(configFile) : {};
@@ -135,10 +136,9 @@ function buildBundle(kind, dir, workspaceRoot) {
135
136
  kind,
136
137
  dir,
137
138
  relativeDir: relativeLabel(workspaceRoot, dir),
138
- schema: {
139
- absolutePath: schemaFile,
140
- relativePath: relativeLabel(workspaceRoot, schemaFile),
141
- },
139
+ schema: schemaExists
140
+ ? { absolutePath: schemaFile, relativePath: relativeLabel(workspaceRoot, schemaFile) }
141
+ : null,
142
142
  schemaDocument: schema,
143
143
  config: {
144
144
  filePath: isFile(configFile) ? { absolutePath: configFile, relativePath: relativeLabel(workspaceRoot, configFile) } : null,
@@ -154,6 +154,127 @@ function buildBundle(kind, dir, workspaceRoot) {
154
154
  };
155
155
  }
156
156
 
157
+ // --- Bundle inheritance (issue #4) -----------------------------------------
158
+ // A bundle may declare `extends` to inherit a base bundle (the built-in default,
159
+ // or another bundle directory) and add/override on top of it instead of forking
160
+ // the whole rules file. `addElementTypes` / `addRelationships` / `overrideMatrix`
161
+ // are the delta; the effective element universe becomes base ∪ add (single
162
+ // source of truth), matrix/metadata merge by key.
163
+
164
+ function bundleConfig(dir) {
165
+ const configFile = path.join(dir, CONFIG_BASENAME);
166
+ if (!isFile(configFile)) {
167
+ return {};
168
+ }
169
+ try {
170
+ return readJsonFile(configFile);
171
+ } catch {
172
+ return {};
173
+ }
174
+ }
175
+
176
+ function hasExtendsConfig(dir) {
177
+ const config = bundleConfig(dir);
178
+ return typeof config.extends === 'string' && config.extends.trim() !== '';
179
+ }
180
+
181
+ function resolveBaseBundleDir(ext, childDir) {
182
+ const value = String(ext).trim();
183
+ if (value === 'default' || value === 'archimate3.2' || value === 'archimate' || value === 'base') {
184
+ return path.join(getArgoRoot(), 'schema');
185
+ }
186
+ return path.resolve(childDir, value);
187
+ }
188
+
189
+ function deepCloneJson(value) {
190
+ return value === undefined ? undefined : JSON.parse(JSON.stringify(value));
191
+ }
192
+
193
+ function mergeMatrixInto(target, source) {
194
+ if (!source || typeof source !== 'object') {
195
+ return target;
196
+ }
197
+ for (const [relationshipType, bySource] of Object.entries(source)) {
198
+ if (!bySource || typeof bySource !== 'object') {
199
+ target[relationshipType] = deepCloneJson(bySource);
200
+ continue;
201
+ }
202
+ if (!target[relationshipType] || typeof target[relationshipType] !== 'object') {
203
+ target[relationshipType] = {};
204
+ }
205
+ for (const [sourceType, targets] of Object.entries(bySource)) {
206
+ target[relationshipType][sourceType] = deepCloneJson(targets);
207
+ }
208
+ }
209
+ return target;
210
+ }
211
+
212
+ function mergeExtendsBundle(base, child) {
213
+ const baseRules = base.rules || {};
214
+ const childRules = child.rules || {};
215
+ const config = { ...(base.config || {}), ...(child.config || {}) };
216
+
217
+ const elementTypeMetadata = { ...(baseRules.elementTypeMetadata || {}), ...(childRules.elementTypeMetadata || {}) };
218
+ const archimateClassByElementType = { ...(baseRules.archimateClassByElementType || {}), ...(childRules.archimateClassByElementType || {}) };
219
+ const relationshipCategoryByType = { ...(baseRules.relationshipCategoryByType || {}), ...(childRules.relationshipCategoryByType || {}) };
220
+
221
+ const addElementTypes = config.addElementTypes && typeof config.addElementTypes === 'object' ? config.addElementTypes : {};
222
+ for (const [type, meta] of Object.entries(addElementTypes)) {
223
+ if (!elementTypeMetadata[type]) {
224
+ elementTypeMetadata[type] = { layer: (meta && meta.layer) || null, aspect: (meta && meta.aspect) || null };
225
+ }
226
+ if (meta && typeof meta.class === 'string' && meta.class !== '') {
227
+ archimateClassByElementType[type] = meta.class;
228
+ }
229
+ }
230
+ const addRelationships = config.addRelationships && typeof config.addRelationships === 'object' ? config.addRelationships : {};
231
+ for (const [type, category] of Object.entries(addRelationships)) {
232
+ relationshipCategoryByType[type] = category;
233
+ }
234
+
235
+ const relationshipTargetMatrix = deepCloneJson(baseRules.relationshipTargetMatrix || {}) || {};
236
+ mergeMatrixInto(relationshipTargetMatrix, childRules.relationshipTargetMatrix || {});
237
+ mergeMatrixInto(relationshipTargetMatrix, config.overrideMatrix || {});
238
+
239
+ const dialect = childRules.dialect || baseRules.dialect || 'archimate-class-matrix';
240
+ const rules = {
241
+ ...baseRules,
242
+ ...childRules,
243
+ dialect,
244
+ elementTypeMetadata,
245
+ archimateClassByElementType,
246
+ relationshipCategoryByType,
247
+ relationshipTargetMatrix,
248
+ };
249
+
250
+ return {
251
+ ...child,
252
+ schema: child.schema || base.schema,
253
+ schemaDocument: child.schemaDocument || base.schemaDocument,
254
+ rules,
255
+ config,
256
+ inheritedFrom: base.dir,
257
+ };
258
+ }
259
+
260
+ function applyExtends(bundle, workspaceRoot, seen = new Set()) {
261
+ const ext = bundle && bundle.config && typeof bundle.config.extends === 'string' ? bundle.config.extends.trim() : '';
262
+ if (!ext) {
263
+ return bundle;
264
+ }
265
+ seen.add(path.resolve(bundle.dir).toLowerCase());
266
+ const baseDir = resolveBaseBundleDir(ext, bundle.dir);
267
+ const baseKey = path.resolve(baseDir).toLowerCase();
268
+ if (seen.has(baseKey)) {
269
+ throw new Error(`schema bundle extends cycle detected at '${baseDir}'`);
270
+ }
271
+ if (!isFile(path.join(baseDir, SCHEMA_BASENAME)) && !hasExtendsConfig(baseDir)) {
272
+ throw new Error(`schema bundle extends '${ext}' could not be resolved: no schema bundle at '${baseDir}'`);
273
+ }
274
+ const baseBundle = applyExtends(buildBundle('extends', baseDir, workspaceRoot), workspaceRoot, seen);
275
+ return mergeExtendsBundle(baseBundle, bundle);
276
+ }
277
+
157
278
  function resolveSchemaBundle(workspaceRoot, options = {}) {
158
279
  const root = path.resolve(workspaceRoot || process.cwd());
159
280
  const candidates = [];
@@ -172,8 +293,8 @@ function resolveSchemaBundle(workspaceRoot, options = {}) {
172
293
  continue;
173
294
  }
174
295
  seen.add(key);
175
- if (isFile(path.join(candidate.dir, SCHEMA_BASENAME))) {
176
- return buildBundle(candidate.kind, candidate.dir, root);
296
+ if (isFile(path.join(candidate.dir, SCHEMA_BASENAME)) || hasExtendsConfig(candidate.dir)) {
297
+ return applyExtends(buildBundle(candidate.kind, candidate.dir, root), root);
177
298
  }
178
299
  }
179
300
 
@@ -258,7 +379,77 @@ function resolveActorElementType(config) {
258
379
  return DEFAULT_ACTOR_ELEMENT_TYPE;
259
380
  }
260
381
 
261
- function validateBundle({ language, dialect, elementTypes, relationshipTypes, actorElementType, matrix, deliveryDependencies }) {
382
+ // Per-element-type attribute contract (issue #3): declare that an element type
383
+ // must carry certain attributes, that some attribute values are a controlled
384
+ // vocabulary, and that some attribute values are unique within the type.
385
+ // { "Rule": { "required": ["ruleId","normativity"], "unique": ["ruleId"],
386
+ // "enumByAttr": { "normativity": ["MUST","SHOULD","MAY","MUST_NOT"] } } }
387
+ // Absent => no per-type attribute contract (backward compatible).
388
+ function resolveAttributeContracts(config) {
389
+ const raw = config && typeof config.attributesByElementType === 'object' && config.attributesByElementType !== null
390
+ ? config.attributesByElementType
391
+ : null;
392
+ if (!raw) {
393
+ return undefined;
394
+ }
395
+ const contracts = {};
396
+ for (const [type, contract] of Object.entries(raw)) {
397
+ if (!contract || typeof contract !== 'object') {
398
+ contracts[type] = {};
399
+ continue;
400
+ }
401
+ contracts[type] = {
402
+ required: Array.isArray(contract.required) ? contract.required.slice() : undefined,
403
+ unique: Array.isArray(contract.unique) ? contract.unique.slice() : undefined,
404
+ enumByAttr: contract.enumByAttr && typeof contract.enumByAttr === 'object' ? { ...contract.enumByAttr } : undefined,
405
+ };
406
+ }
407
+ return contracts;
408
+ }
409
+
410
+ function validateAttributeContracts(language, elementTypeList, contracts) {
411
+ const errors = [];
412
+ if (!contracts || typeof contracts !== 'object') {
413
+ return errors;
414
+ }
415
+ for (const [type, contract] of Object.entries(contracts)) {
416
+ if (!elementTypeList.includes(type)) {
417
+ errors.push(`schema bundle '${language}' attributesByElementType references unknown element type '${type}'`);
418
+ }
419
+ if (!contract || typeof contract !== 'object') {
420
+ continue;
421
+ }
422
+ for (const key of ['required', 'unique']) {
423
+ const list = contract[key];
424
+ if (list === undefined) {
425
+ continue;
426
+ }
427
+ if (!Array.isArray(list)) {
428
+ errors.push(`schema bundle '${language}' attributesByElementType['${type}'].${key} must be an array`);
429
+ continue;
430
+ }
431
+ for (const name of list) {
432
+ if (typeof name !== 'string' || name === '') {
433
+ errors.push(`schema bundle '${language}' attributesByElementType['${type}'].${key} entries must be non-empty strings`);
434
+ }
435
+ }
436
+ }
437
+ if (contract.enumByAttr !== undefined) {
438
+ if (!contract.enumByAttr || typeof contract.enumByAttr !== 'object') {
439
+ errors.push(`schema bundle '${language}' attributesByElementType['${type}'].enumByAttr must be an object`);
440
+ } else {
441
+ for (const [attr, allowed] of Object.entries(contract.enumByAttr)) {
442
+ if (!Array.isArray(allowed) || allowed.length === 0) {
443
+ errors.push(`schema bundle '${language}' attributesByElementType['${type}'].enumByAttr['${attr}'] must be a non-empty array`);
444
+ }
445
+ }
446
+ }
447
+ }
448
+ }
449
+ return errors;
450
+ }
451
+
452
+ function validateBundle({ language, dialect, elementTypes, relationshipTypes, actorElementType, matrix, deliveryDependencies, attributesByElementType }) {
262
453
  const errors = [];
263
454
  const elementTypeList = Array.isArray(elementTypes) ? elementTypes : [];
264
455
  const relationshipTypeList = Array.isArray(relationshipTypes) ? relationshipTypes : [];
@@ -304,6 +495,7 @@ function validateBundle({ language, dialect, elementTypes, relationshipTypes, ac
304
495
  }
305
496
 
306
497
  errors.push(...validateDeliveryDependencies(language, relationshipTypeList, deliveryDependencies));
498
+ errors.push(...validateAttributeContracts(language, elementTypeList, attributesByElementType));
307
499
 
308
500
  return { status: errors.length === 0 ? 'passed' : 'failed', errors };
309
501
  }
@@ -386,6 +578,7 @@ function buildClassMatrixOntology(bundle) {
386
578
  const relationshipTypes = Array.from(relationshipCategoryByType.keys());
387
579
  const actorElementType = resolveActorElementType(bundle.config);
388
580
  const deliveryDependencies = resolveDeliveryDependencies(bundle.config, 'archimate-class-matrix');
581
+ const attributesByElementType = resolveAttributeContracts(bundle.config);
389
582
  return finalizeOntology({
390
583
  kind: bundle.kind,
391
584
  dialect: 'archimate-class-matrix',
@@ -397,7 +590,8 @@ function buildClassMatrixOntology(bundle) {
397
590
  relationshipTypes,
398
591
  actorElementType,
399
592
  deliveryDependencies,
400
- bundleValidation: validateBundle({ language, dialect: 'archimate-class-matrix', elementTypes, relationshipTypes, actorElementType, matrix: null, deliveryDependencies }),
593
+ attributesByElementType,
594
+ bundleValidation: validateBundle({ language, dialect: 'archimate-class-matrix', elementTypes, relationshipTypes, actorElementType, matrix: null, deliveryDependencies, attributesByElementType }),
401
595
  elementTypeMetadata,
402
596
  relationshipCategoryByType,
403
597
  isSupportedElementType,
@@ -456,6 +650,7 @@ function buildTypeMatrixOntology(bundle) {
456
650
  const elementTypes = Array.from(elementTypeMetadata.keys());
457
651
  const relationshipTypes = Array.from(relationshipCategoryByType.keys());
458
652
  const deliveryDependencies = resolveDeliveryDependencies(config, 'type-matrix');
653
+ const attributesByElementType = resolveAttributeContracts(config);
459
654
  const getArchiMateClass = (elementOrType) => {
460
655
  const type = typeof elementOrType === 'string' ? elementOrType : elementOrType && elementOrType.type;
461
656
  return type;
@@ -494,7 +689,8 @@ function buildTypeMatrixOntology(bundle) {
494
689
  relationshipTypes,
495
690
  actorElementType,
496
691
  deliveryDependencies,
497
- bundleValidation: validateBundle({ language, dialect: 'type-matrix', elementTypes, relationshipTypes, actorElementType, matrix, deliveryDependencies }),
692
+ attributesByElementType,
693
+ bundleValidation: validateBundle({ language, dialect: 'type-matrix', elementTypes, relationshipTypes, actorElementType, matrix, deliveryDependencies, attributesByElementType }),
498
694
  elementTypeMetadata,
499
695
  relationshipCategoryByType,
500
696
  isSupportedElementType: (type) => elementTypeMetadata.has(type),
@@ -130,6 +130,7 @@ const {
130
130
  validateGraphSemantics,
131
131
  validateArchiMateEndpointMatrix,
132
132
  validateViewElementLimits,
133
+ validateAttributeContracts,
133
134
  } = require('./graph-semantics.js');
134
135
  const {
135
136
  loadSchemaBundleAndOntology,
@@ -616,6 +617,7 @@ function validateDocument(document, schema, options = {}) {
616
617
  }
617
618
  validateAgainstSchema(document, schema, '#', errors, schema);
618
619
  validateGraphSemantics(document, errors, ontology);
620
+ validateAttributeContracts(document, errors, ontology);
619
621
  validateArchiMateEndpointMatrix(document, errors, {
620
622
  ontology,
621
623
  touchedRelationshipIds: options.touchedRelationshipIds,
@@ -1389,6 +1391,207 @@ function resolveDuplicateConflict(options, candidates) {
1389
1391
  return { action: 'create', justification: options.justification };
1390
1392
  }
1391
1393
 
1394
+ function mutationNodeId(mutation) {
1395
+ if (!mutation || typeof mutation !== 'object') {
1396
+ return '(invalid)';
1397
+ }
1398
+ if (mutation.type === 'addElement') {
1399
+ return (mutation.element && mutation.element.id) || '(addElement)';
1400
+ }
1401
+ if (mutation.type === 'addRelationship') {
1402
+ return (mutation.relationship && mutation.relationship.id) || '(addRelationship)';
1403
+ }
1404
+ if (mutation.type === 'addView') {
1405
+ return (mutation.view && mutation.view.view_id) || '(addView)';
1406
+ }
1407
+ if (mutation.type === 'updateView') {
1408
+ return mutation.view_id || mutation.id || '(updateView)';
1409
+ }
1410
+ return mutation.id || mutation.view_id || `(${mutation.type})`;
1411
+ }
1412
+
1413
+ // Order a batch so it is order-independent: a mutation that references an object
1414
+ // created later in the SAME batch is applied after its producer. Dependencies:
1415
+ // addElement -> views it joins (view_ids)
1416
+ // addRelationship-> views it joins + its source/target elements
1417
+ // addView -> its parent element + included elements/relationships
1418
+ // update*/remove*-> the object they target (when that object is produced here)
1419
+ // A genuine cycle is reported with the id chain so the caller can split the batch.
1420
+ function orderMutationsForApplication(mutations) {
1421
+ const n = mutations.length;
1422
+ const producers = new Map();
1423
+ const addProducer = (key, index) => {
1424
+ if (!key) {
1425
+ return;
1426
+ }
1427
+ if (!producers.has(key)) {
1428
+ producers.set(key, []);
1429
+ }
1430
+ producers.get(key).push(index);
1431
+ };
1432
+
1433
+ mutations.forEach((mutation, index) => {
1434
+ if (!mutation || typeof mutation !== 'object') {
1435
+ return;
1436
+ }
1437
+ if (mutation.type === 'addElement' && mutation.element) {
1438
+ addProducer('element:' + mutation.element.id, index);
1439
+ }
1440
+ if (mutation.type === 'addRelationship' && mutation.relationship) {
1441
+ addProducer('relationship:' + mutation.relationship.id, index);
1442
+ }
1443
+ if (mutation.type === 'addView' && mutation.view) {
1444
+ addProducer('view:' + mutation.view.view_id, index);
1445
+ }
1446
+ });
1447
+
1448
+ const dependencies = mutations.map(() => new Set());
1449
+ mutations.forEach((mutation, index) => {
1450
+ if (!mutation || typeof mutation !== 'object') {
1451
+ return;
1452
+ }
1453
+ const requireKey = (key) => {
1454
+ const matches = producers.get(key);
1455
+ if (!matches) {
1456
+ return;
1457
+ }
1458
+ for (const producerIndex of matches) {
1459
+ if (producerIndex !== index) {
1460
+ dependencies[index].add(producerIndex);
1461
+ }
1462
+ }
1463
+ };
1464
+
1465
+ if (mutation.type === 'addElement') {
1466
+ for (const viewId of Array.isArray(mutation.view_ids) ? mutation.view_ids : []) {
1467
+ requireKey('view:' + viewId);
1468
+ }
1469
+ } else if (mutation.type === 'addRelationship') {
1470
+ for (const viewId of Array.isArray(mutation.view_ids) ? mutation.view_ids : []) {
1471
+ requireKey('view:' + viewId);
1472
+ }
1473
+ if (mutation.relationship) {
1474
+ requireKey('element:' + mutation.relationship.source_id);
1475
+ requireKey('element:' + mutation.relationship.target_id);
1476
+ }
1477
+ } else if (mutation.type === 'addView') {
1478
+ if (mutation.view) {
1479
+ requireKey('element:' + mutation.view.parent_element_id);
1480
+ for (const elementId of Array.isArray(mutation.view.included_elements) ? mutation.view.included_elements : []) {
1481
+ requireKey('element:' + elementId);
1482
+ }
1483
+ for (const relationshipId of Array.isArray(mutation.view.included_relationships) ? mutation.view.included_relationships : []) {
1484
+ requireKey('relationship:' + relationshipId);
1485
+ }
1486
+ }
1487
+ } else if (mutation.type === 'updateElement') {
1488
+ requireKey('element:' + mutation.id);
1489
+ } else if (mutation.type === 'updateRelationship') {
1490
+ requireKey('relationship:' + mutation.id);
1491
+ } else if (mutation.type === 'updateView') {
1492
+ requireKey('view:' + (mutation.view_id || mutation.id));
1493
+ } else if (mutation.type === 'removeView') {
1494
+ requireKey('view:' + mutation.view_id);
1495
+ } else if (mutation.type === 'removeElement') {
1496
+ requireKey('element:' + mutation.id);
1497
+ } else if (mutation.type === 'removeRelationship') {
1498
+ requireKey('relationship:' + mutation.id);
1499
+ }
1500
+ });
1501
+
1502
+ const indegree = mutations.map((_, index) => dependencies[index].size);
1503
+ const dependents = mutations.map(() => []);
1504
+ dependencies.forEach((set, index) => {
1505
+ for (const dependency of set) {
1506
+ dependents[dependency].push(index);
1507
+ }
1508
+ });
1509
+
1510
+ const remaining = new Set();
1511
+ for (let index = 0; index < n; index += 1) {
1512
+ remaining.add(index);
1513
+ }
1514
+ const ready = [];
1515
+ for (let index = 0; index < n; index += 1) {
1516
+ if (indegree[index] === 0) {
1517
+ ready.push(index);
1518
+ }
1519
+ }
1520
+ ready.sort((a, b) => a - b);
1521
+
1522
+ const ordered = [];
1523
+ while (ready.length > 0) {
1524
+ const index = ready.shift();
1525
+ if (!remaining.has(index)) {
1526
+ continue;
1527
+ }
1528
+ remaining.delete(index);
1529
+ ordered.push(mutations[index]);
1530
+ for (const dependent of dependents[index]) {
1531
+ indegree[dependent] -= 1;
1532
+ if (indegree[dependent] === 0) {
1533
+ ready.push(dependent);
1534
+ }
1535
+ }
1536
+ ready.sort((a, b) => a - b);
1537
+ }
1538
+
1539
+ if (ordered.length !== n) {
1540
+ const chain = findMutationCycle(mutations, dependencies, remaining);
1541
+ throw new Error(
1542
+ `Cyclic mutation dependencies in batch: ${chain.join(' -> ')}. `
1543
+ + 'Order the batch so each referenced object is created first, or split the mutually-dependent objects into separate calls.',
1544
+ );
1545
+ }
1546
+
1547
+ return ordered;
1548
+ }
1549
+
1550
+ function findMutationCycle(mutations, dependencies, remaining) {
1551
+ const visited = new Set();
1552
+ const inStack = new Set();
1553
+ const stack = [];
1554
+ let cycle = null;
1555
+
1556
+ const visit = (index) => {
1557
+ if (cycle) {
1558
+ return;
1559
+ }
1560
+ visited.add(index);
1561
+ inStack.add(index);
1562
+ stack.push(index);
1563
+ for (const dependency of dependencies[index]) {
1564
+ if (!remaining.has(dependency)) {
1565
+ continue;
1566
+ }
1567
+ if (inStack.has(dependency)) {
1568
+ cycle = stack.slice(stack.indexOf(dependency)).concat(dependency);
1569
+ return;
1570
+ }
1571
+ if (!visited.has(dependency)) {
1572
+ visit(dependency);
1573
+ }
1574
+ if (cycle) {
1575
+ return;
1576
+ }
1577
+ }
1578
+ inStack.delete(index);
1579
+ stack.pop();
1580
+ };
1581
+
1582
+ for (const index of remaining) {
1583
+ if (!visited.has(index)) {
1584
+ visit(index);
1585
+ }
1586
+ if (cycle) {
1587
+ break;
1588
+ }
1589
+ }
1590
+
1591
+ const chain = cycle || [...remaining];
1592
+ return chain.map((index) => mutationNodeId(mutations[index]));
1593
+ }
1594
+
1392
1595
  function applyMutations(document, mutations, options = {}) {
1393
1596
  const nextDocument = clone(document);
1394
1597
  const touchedElementIds = new Set();
@@ -1401,7 +1604,11 @@ function applyMutations(document, mutations, options = {}) {
1401
1604
  throw new Error('mutations must contain at least one mutation');
1402
1605
  }
1403
1606
 
1404
- for (const mutation of mutations) {
1607
+ // Apply in dependency order so a batch is order-independent (see
1608
+ // orderMutationsForApplication); a genuine cycle throws with the id chain.
1609
+ const orderedMutations = orderMutationsForApplication(mutations);
1610
+
1611
+ for (const mutation of orderedMutations) {
1405
1612
  if (!mutation || typeof mutation !== 'object' || !HANDLED_MUTATION_TYPES.has(mutation.type)) {
1406
1613
  throw new Error(`Unsupported mutation type: ${mutation && mutation.type}`);
1407
1614
  }
@@ -17,6 +17,7 @@ const {
17
17
  validateGraphSemantics,
18
18
  validateArchiMateEndpointMatrix,
19
19
  validateViewElementLimits,
20
+ validateAttributeContracts,
20
21
  } = require('./graph-semantics.js');
21
22
 
22
23
  function main() {
@@ -43,6 +44,7 @@ function main() {
43
44
  }
44
45
  validateAgainstSchema(document, schema, '#', errors, schema);
45
46
  validateGraphSemantics(document, errors, ontology);
47
+ validateAttributeContracts(document, errors, ontology);
46
48
  validateArchiMateEndpointMatrix(document, errors, { ontology });
47
49
  validateViewElementLimits(document, errors, { ontology });
48
50
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "archgraph-argo-beta",
3
- "version": "0.27.0-beta.2",
3
+ "version": "0.27.0-beta.3",
4
4
  "description": "Deploy the ArchGraph ARGO toolchain, skills, and rules (schema, scripts, argo-init skill, global rule) with one command.",
5
5
  "license": "MIT",
6
6
  "bin": {