From ab569f73dff729e8e2b2ee8ae9b4515d194f23d1 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 18:16:27 +0100 Subject: [PATCH 1/2] fix(core): use Structurizr DSL identifiers for element ids and patches - Element ids come from erode.id, then the structurizr.dsl.identifier property the DSL parser writes, then an ASCII slug of the name - Numeric JSON ids stay internal and are never written to DSL - Patches reference DSL identifiers; relationships to elements without one, and new components with invalid ids, are skipped with a reason - Element type comes from the JSON array, not the id depth - Duplicate resolved ids fail the load and name both elements - ADR-003 amendment and an Upgrading note in the Structurizr docs --- .../core/src/adapters/architecture-adapter.ts | 6 + packages/core/src/adapters/base-patcher.ts | 33 +- packages/core/src/adapters/model-patcher.ts | 2 + .../__tests__/adapter-dsl-identifiers.test.ts | 287 ++++++++++++++++++ .../__tests__/adapter-id-tags.test.ts | 30 +- .../structurizr/__tests__/adapter.test.ts | 70 +++-- .../fixtures/dsl-export/workspace.dsl | 25 ++ .../fixtures/dsl-export/workspace.json | 122 ++++++++ .../__tests__/fixtures/mock-workspace.ts | 30 +- .../__tests__/patcher-dsl-references.test.ts | 147 +++++++++ .../core/src/adapters/structurizr/adapter.ts | 258 +++++----------- .../src/adapters/structurizr/element-ids.ts | 145 +++++++++ .../core/src/adapters/structurizr/patcher.ts | 62 +++- packages/core/src/pipelines/analyze.ts | 1 + packages/core/src/schemas/common.schema.ts | 13 +- .../003-architecture-model-adapter-system.md | 1 + .../content/docs/docs/models/structurizr.md | 19 +- 17 files changed, 998 insertions(+), 253 deletions(-) create mode 100644 packages/core/src/adapters/structurizr/__tests__/adapter-dsl-identifiers.test.ts create mode 100644 packages/core/src/adapters/structurizr/__tests__/fixtures/dsl-export/workspace.dsl create mode 100644 packages/core/src/adapters/structurizr/__tests__/fixtures/dsl-export/workspace.json create mode 100644 packages/core/src/adapters/structurizr/__tests__/patcher-dsl-references.test.ts create mode 100644 packages/core/src/adapters/structurizr/element-ids.ts diff --git a/packages/core/src/adapters/architecture-adapter.ts b/packages/core/src/adapters/architecture-adapter.ts index 26d62342..abad0de6 100644 --- a/packages/core/src/adapters/architecture-adapter.ts +++ b/packages/core/src/adapters/architecture-adapter.ts @@ -66,6 +66,12 @@ export interface ArchitectureModelAdapter { /** Optional: element ID to absolute path of the file declaring it, from the last load. */ getElementSourceFiles?(): ReadonlyMap; + /** + * Optional: element ID to the identifier that references it in the model source, for + * formats whose element IDs are not valid source references (Structurizr). + */ + getDslReferences?(): ReadonlyMap; + /** Optional: check version compatibility for the model format. */ checkVersion?(path: string): VersionCheckResult; diff --git a/packages/core/src/adapters/base-patcher.ts b/packages/core/src/adapters/base-patcher.ts index 4754029d..f42bf6f7 100644 --- a/packages/core/src/adapters/base-patcher.ts +++ b/packages/core/src/adapters/base-patcher.ts @@ -48,10 +48,23 @@ export abstract class BasePatcher implements ModelPatcher { protected abstract generateDslLines( unique: StructuredRelationship[], - existing: ModelRelationship[] + existing: ModelRelationship[], + context?: ModelPatchOptions ): string[]; - protected abstract generateComponentDslLines(components: NewComponent[]): string[]; + protected abstract generateComponentDslLines( + components: NewComponent[], + context?: ModelPatchOptions + ): string[]; + + /** Formats that cannot write every new component drop it here and record why in `skipped`. */ + protected filterNewComponents( + components: NewComponent[], + _skipped: PatchResult['skipped'], + _context?: ModelPatchOptions + ): NewComponent[] { + return components; + } protected abstract findTargetFile(modelPath: string): string | null; @@ -89,8 +102,10 @@ export abstract class BasePatcher implements ModelPatcher { this.debugLog('Input relationships', relationships); // 0. Filter new components — skip any that already exist in the model - const genuinelyNew = (options.newComponents ?? []).filter( - (c) => !componentIndex.byId.has(c.id) + const genuinelyNew = this.filterNewComponents( + (options.newComponents ?? []).filter((c) => !componentIndex.byId.has(c.id)), + skipped, + options ); const pendingComponentIds = new Set(genuinelyNew.map((c) => c.id)); @@ -106,7 +121,8 @@ export abstract class BasePatcher implements ModelPatcher { relationships, componentIndex, skipped, - pendingComponentIds + pendingComponentIds, + options ); if (skipped.length > 0) { @@ -130,9 +146,9 @@ export abstract class BasePatcher implements ModelPatcher { // 3. Generate DSL lines — components first, then relationships const componentDslLines = - genuinelyNew.length > 0 ? this.generateComponentDslLines(genuinelyNew) : []; + genuinelyNew.length > 0 ? this.generateComponentDslLines(genuinelyNew, options) : []; const relationshipDslLines = - unique.length > 0 ? this.generateDslLines(unique, existingRelationships) : []; + unique.length > 0 ? this.generateDslLines(unique, existingRelationships, options) : []; const insertedLines = [...componentDslLines, ...relationshipDslLines]; this.debugLog('Generated DSL lines', insertedLines); @@ -207,7 +223,8 @@ export abstract class BasePatcher implements ModelPatcher { relationships: StructuredRelationship[], componentIndex: ComponentIndex, skipped: PatchResult['skipped'], - pendingComponentIds?: Set + pendingComponentIds?: Set, + _context?: ModelPatchOptions ): StructuredRelationship[] { return relationships.filter((rel) => { if (!componentIndex.byId.has(rel.source) && !pendingComponentIds?.has(rel.source)) { diff --git a/packages/core/src/adapters/model-patcher.ts b/packages/core/src/adapters/model-patcher.ts index 0ccd7b9e..0e525aa9 100644 --- a/packages/core/src/adapters/model-patcher.ts +++ b/packages/core/src/adapters/model-patcher.ts @@ -61,6 +61,8 @@ export interface ModelPatchOptions { validationBaseline?: readonly ValidationDiagnostic[]; /** Element ID to absolute path of its declaring file, used to pick the file to patch */ elementSourceFiles?: ReadonlyMap; + /** Element ID to its DSL reference; when set, relationships to elements without one are skipped */ + dslReferences?: ReadonlyMap; } export interface ModelPatcher { diff --git a/packages/core/src/adapters/structurizr/__tests__/adapter-dsl-identifiers.test.ts b/packages/core/src/adapters/structurizr/__tests__/adapter-dsl-identifiers.test.ts new file mode 100644 index 00000000..fae65b2a --- /dev/null +++ b/packages/core/src/adapters/structurizr/__tests__/adapter-dsl-identifiers.test.ts @@ -0,0 +1,287 @@ +import path from 'path'; +import { fileURLToPath } from 'url'; +import { describe, it, expect, beforeEach } from 'vitest'; +import { StructurizrAdapter } from '../adapter.js'; +import { AdapterError } from '../../../errors.js'; +import type { StructurizrWorkspace } from '../structurizr-types.js'; +import { TestStructurizrAdapter } from './adapter.test.js'; + +const fixtures = path.join(path.dirname(fileURLToPath(import.meta.url)), 'fixtures'); +const DSL_ID = 'structurizr.dsl.identifier'; + +describe('StructurizrAdapter - DSL export identifiers', () => { + let adapter: StructurizrAdapter; + + beforeEach(async () => { + adapter = new StructurizrAdapter(); + await adapter.loadFromPath(path.join(fixtures, 'dsl-export', 'workspace.json')); + }); + + it('takes ids from structurizr.dsl.identifier and never exposes numeric JSON ids', () => { + const ids = adapter.getAllComponents().map((c) => c.id); + expect(ids).toEqual([ + 'customer', + 'shop', + 'storefront', + 'orders', + 'orderApi', + 'orders.payment_adapter', + 'payments', + ]); + expect(ids.some((id) => /^\d+$/.test(id) || /(^|\.)\d+(\.|$)/.test(id))).toBe(false); + }); + + it('takes element types from the JSON arrays', () => { + const types = Object.fromEntries(adapter.getAllComponents().map((c) => [c.id, c.type])); + expect(types).toEqual({ + customer: 'person', + shop: 'softwareSystem', + storefront: 'container', + orders: 'container', + orderApi: 'component', + 'orders.payment_adapter': 'component', + payments: 'softwareSystem', + }); + }); + + it('resolves numeric sourceId and destinationId to element ids', () => { + expect(adapter.isAllowedDependency('customer', 'storefront')).toBe(true); + expect(adapter.isAllowedDependency('storefront', 'orders')).toBe(true); + expect(adapter.isAllowedDependency('orderApi', 'payments')).toBe(true); + expect(adapter.findComponentByRepository('https://github.com/example/orders')?.id).toBe( + 'orders' + ); + }); + + it('maps only elements with a stable DSL identifier to a DSL reference', () => { + const references = Object.fromEntries(adapter.getDslReferences()); + expect(references).toEqual({ + customer: 'customer', + shop: 'shop', + storefront: 'storefront', + orders: 'orders', + orderApi: 'orderApi', + payments: 'payments', + }); + }); + + it('lists components with the same ids and kinds', async () => { + const listed = await new StructurizrAdapter().loadAndListComponents( + path.join(fixtures, 'dsl-export') + ); + expect(listed.find((c) => c.id === 'orderApi')?.kind).toBe('component'); + expect(listed.find((c) => c.id === 'storefront')?.links).toEqual([ + 'https://github.com/example/storefront', + ]); + }); +}); + +describe('StructurizrAdapter - erode.id fixture is unchanged', () => { + it('keeps erode.id values as ids and has no DSL references', async () => { + const adapter = new StructurizrAdapter(); + await adapter.loadFromPath(path.join(fixtures, 'sample-workspace', 'workspace.json')); + + expect(adapter.getAllComponents().map((c) => c.id)).toEqual([ + 'frontend', + 'api_gateway', + 'user_service', + 'product_service', + 'database', + ]); + expect(adapter.getDslReferences().size).toBe(0); + }); +}); + +describe('StructurizrAdapter - id resolution rules', () => { + let adapter: TestStructurizrAdapter; + + beforeEach(() => { + adapter = new TestStructurizrAdapter(); + }); + + const load = (model: StructurizrWorkspace['model']): void => { + adapter.setMockWorkspace({ name: 'Test', model }); + }; + + it('uses hierarchical identifiers verbatim', () => { + load({ + softwareSystems: [ + { + id: '1', + name: 'Shop', + properties: { [DSL_ID]: 'shop' }, + containers: [ + { + id: '2', + name: 'API', + properties: { [DSL_ID]: 'shop.api' }, + components: [{ id: '3', name: 'Auth', properties: { [DSL_ID]: 'shop.api.auth' } }], + }, + ], + }, + ], + }); + + expect(adapter.getAllComponents().map((c) => [c.id, c.type])).toEqual([ + ['shop', 'softwareSystem'], + ['shop.api', 'container'], + ['shop.api.auth', 'component'], + ]); + expect(adapter.getDslReferences().get('shop.api.auth')).toBe('shop.api.auth'); + }); + + it('ignores identifiers with a UUID segment from anonymous hierarchical parents', () => { + const uuid = '0f1e2d3c-4b5a-4968-8776-655443322110'; + load({ + softwareSystems: [ + { + id: '1', + name: 'Legacy', + properties: { [DSL_ID]: uuid }, + containers: [{ id: '2', name: 'Worker', properties: { [DSL_ID]: `${uuid}.worker` } }], + }, + ], + }); + + expect(adapter.getAllComponents().map((c) => c.id)).toEqual(['legacy', 'legacy.worker']); + expect(adapter.getDslReferences().size).toBe(0); + }); + + it('types children by array, not by dots in an erode.id', () => { + load({ + softwareSystems: [ + { + id: '1', + name: 'Shop', + properties: { 'erode.id': 'shop.core' }, + containers: [{ id: '2', name: 'API', properties: { 'erode.id': 'shop.core.api' } }], + }, + ], + }); + + expect(adapter.findComponentById('shop.core')?.type).toBe('softwareSystem'); + expect(adapter.findComponentById('shop.core.api')?.type).toBe('container'); + }); + + it('keeps erode.id ahead of the DSL identifier but still exposes the DSL reference', () => { + load({ + softwareSystems: [ + { id: '1', name: 'Svc', properties: { 'erode.id': 'custom', [DSL_ID]: 'svc' } }, + ], + }); + + expect(adapter.findComponentById('custom')).toBeDefined(); + expect(adapter.getDslReferences().get('custom')).toBe('svc'); + }); + + it('builds ASCII fallback ids from accented names', () => { + load({ + softwareSystems: [ + { id: '1', name: 'Café Résumé' }, + { id: '2', name: 'Платежи Service' }, + ], + }); + + expect(adapter.getAllComponents().map((c) => c.id)).toEqual(['cafe_resume', 'service']); + }); + + it('rejects an element whose name yields no fallback id', () => { + expect(() => { + load({ softwareSystems: [{ id: '1', name: '---' }] }); + }).toThrow(/Cannot derive an id/); + }); + + const expectDuplicate = (model: StructurizrWorkspace['model'], names: string[]): void => { + let error: unknown; + try { + load(model); + } catch (e) { + error = e; + } + expect(error).toBeInstanceOf(AdapterError); + for (const name of names) { + expect((error as AdapterError).message).toContain(`"${name}"`); + } + }; + + it('rejects two elements with the same erode.id', () => { + expectDuplicate( + { + softwareSystems: [ + { id: '1', name: 'Alpha', properties: { 'erode.id': 'svc' } }, + { id: '2', name: 'Beta', properties: { 'erode.id': 'svc' } }, + ], + }, + ['Alpha', 'Beta'] + ); + }); + + it('rejects names that slug to the same fallback id', () => { + expectDuplicate( + { + softwareSystems: [ + { id: '1', name: 'Payment Service' }, + { id: '2', name: 'Payment-Service' }, + ], + }, + ['Payment Service', 'Payment-Service'] + ); + }); + + it('rejects an erode.id that collides with another element DSL identifier', () => { + expectDuplicate( + { + softwareSystems: [ + { id: '1', name: 'Orders', properties: { [DSL_ID]: 'orders' } }, + { id: '2', name: 'Billing', properties: { 'erode.id': 'orders' } }, + ], + }, + ['Orders', 'Billing'] + ); + }); +}); + +describe('StructurizrAdapter - fallback slug and reload', () => { + const load = (model: StructurizrWorkspace['model']): TestStructurizrAdapter => { + const adapter = new TestStructurizrAdapter(); + adapter.setMockWorkspace({ name: 'Test', model }); + return adapter; + }; + + it('slugs non-ASCII names to ids the response schema accepts', () => { + const id = load({ + softwareSystems: [{ id: '1', name: 'Betalningstjänst' }], + }).getAllComponents()[0]?.id; + expect(id).toBe('betalningstjanst'); + expect(id).toMatch(/^[a-zA-Z0-9._-]+$/); + }); + + it('fails with an erode.id hint when no ASCII letters or digits remain', () => { + let error: unknown; + try { + load({ softwareSystems: [{ id: '1', name: '支付' }] }); + } catch (e) { + error = e; + } + expect(error).toBeInstanceOf(AdapterError); + expect((error as AdapterError).suggestions?.join(' ')).toContain('erode.id'); + }); + + it('drops index, relationships and references from an earlier load', async () => { + const adapter = new StructurizrAdapter(); + await adapter.loadFromPath(path.join(fixtures, 'dsl-export', 'workspace.json')); + expect(adapter.getDslReferences().size).toBeGreaterThan(0); + + await adapter.loadAndListComponents(path.join(fixtures, 'sample-workspace', 'workspace.json')); + + expect(() => adapter.getAllComponents()).toThrow(AdapterError); + expect(() => adapter.getAllRelationships()).toThrow(AdapterError); + expect(adapter.getDslReferences().has('storefront')).toBe(false); + }); + + it('builds the references map once per load', async () => { + const adapter = new StructurizrAdapter(); + await adapter.loadFromPath(path.join(fixtures, 'dsl-export', 'workspace.json')); + expect(adapter.getDslReferences()).toBe(adapter.getDslReferences()); + }); +}); diff --git a/packages/core/src/adapters/structurizr/__tests__/adapter-id-tags.test.ts b/packages/core/src/adapters/structurizr/__tests__/adapter-id-tags.test.ts index b1119f01..a37496a2 100644 --- a/packages/core/src/adapters/structurizr/__tests__/adapter-id-tags.test.ts +++ b/packages/core/src/adapters/structurizr/__tests__/adapter-id-tags.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect, beforeEach } from 'vitest'; import type { StructurizrWorkspace } from '../structurizr-types.js'; import { TestStructurizrAdapter } from './adapter.test.js'; +import { dslElement } from './fixtures/mock-workspace.js'; describe('StructurizrAdapter - Built-in tag filtering', () => { let adapter: TestStructurizrAdapter; @@ -12,7 +13,7 @@ describe('StructurizrAdapter - Built-in tag filtering', () => { model: { softwareSystems: [ { - id: 'svc', + ...dslElement('svc'), name: 'My Service', // Built-in Structurizr tags that should be filtered out tags: 'Element,Software System,myCustomTag', @@ -20,7 +21,7 @@ describe('StructurizrAdapter - Built-in tag filtering', () => { ], people: [ { - id: 'usr', + ...dslElement('usr'), name: 'User', tags: 'Element,Person,externalUser', }, @@ -52,17 +53,17 @@ describe('StructurizrAdapter - Built-in tag filtering', () => { model: { softwareSystems: [ { - id: 'sys', + ...dslElement('sys'), name: 'System', tags: 'Element,Software System', containers: [ { - id: 'ctr', + ...dslElement('sys.ctr'), name: 'Container', tags: 'Element,Container,myContainerTag', components: [ { - id: 'cmp', + ...dslElement('sys.ctr.cmp'), name: 'Component', tags: 'Element,Component,myComponentTag', }, @@ -96,7 +97,7 @@ describe('StructurizrAdapter - ID resolution', () => { const workspace: StructurizrWorkspace = { name: 'Test', model: { - softwareSystems: [{ id: 'my_service', name: 'My Service' }], + softwareSystems: [{ ...dslElement('my_service', '1'), name: 'My Service' }], }, }; adapter.setMockWorkspace(workspace); @@ -124,9 +125,12 @@ describe('StructurizrAdapter - ID resolution', () => { model: { softwareSystems: [ { - id: 'dsl_identifier', + id: '1', name: 'Service With Custom ID', - properties: { 'erode.id': 'custom_erode_id' }, + properties: { + 'erode.id': 'custom_erode_id', + 'structurizr.dsl.identifier': 'dsl_identifier', + }, }, ], }, @@ -144,9 +148,9 @@ describe('StructurizrAdapter - ID resolution', () => { model: { softwareSystems: [ { - id: 'parent_sys', + ...dslElement('parent_sys'), name: 'Parent System', - containers: [{ id: 'child_svc', name: 'Child Service' }], + containers: [{ ...dslElement('parent_sys.child_svc'), name: 'Child Service' }], }, ], }, @@ -164,13 +168,13 @@ describe('StructurizrAdapter - ID resolution', () => { model: { softwareSystems: [ { - id: 'sys', + ...dslElement('sys'), name: 'System', containers: [ { - id: 'container', + ...dslElement('sys.container'), name: 'Container', - components: [{ id: 'component', name: 'Component' }], + components: [{ ...dslElement('sys.container.component'), name: 'Component' }], }, ], }, diff --git a/packages/core/src/adapters/structurizr/__tests__/adapter.test.ts b/packages/core/src/adapters/structurizr/__tests__/adapter.test.ts index a67923ee..3c8a9d47 100644 --- a/packages/core/src/adapters/structurizr/__tests__/adapter.test.ts +++ b/packages/core/src/adapters/structurizr/__tests__/adapter.test.ts @@ -3,24 +3,12 @@ import { StructurizrAdapter } from '../adapter.js'; import { AdapterError, ErrorCode } from '../../../errors.js'; import type { ArchitecturalComponent } from '../../architecture-types.js'; import type { StructurizrWorkspace } from '../structurizr-types.js'; -import { createMockWorkspace } from './fixtures/mock-workspace.js'; +import { createMockWorkspace, dslElement } from './fixtures/mock-workspace.js'; export class TestStructurizrAdapter extends StructurizrAdapter { public setMockWorkspace(workspace: StructurizrWorkspace): void { this.workspace = workspace; - - const adapter = this as unknown as { - identifierMap: Map; - buildIdentifierMap(): Map; - componentIndex: unknown; - relationships: unknown; - }; - adapter.identifierMap = adapter.buildIdentifierMap(); - - const components = this.extractComponents(); - const relationships = this.extractRelationships(); - adapter.relationships = relationships; - adapter.componentIndex = this.buildComponentIndex(components); + this.indexWorkspace(); } public override extractComponents(): ArchitecturalComponent[] { @@ -141,7 +129,9 @@ describe('StructurizrAdapter', () => { const workspace: StructurizrWorkspace = { name: 'Test', model: { - softwareSystems: [{ id: 'svc', name: 'Service', url: 'https://github.com/org/repo.git' }], + softwareSystems: [ + { ...dslElement('svc'), name: 'Service', url: 'https://github.com/org/repo.git' }, + ], }, }; adapter.setMockWorkspace(workspace); @@ -152,7 +142,9 @@ describe('StructurizrAdapter', () => { const workspace: StructurizrWorkspace = { name: 'Test', model: { - softwareSystems: [{ id: 'svc', name: 'Service', url: 'https://example.com/not-github' }], + softwareSystems: [ + { ...dslElement('svc'), name: 'Service', url: 'https://example.com/not-github' }, + ], }, }; adapter.setMockWorkspace(workspace); @@ -164,7 +156,11 @@ describe('StructurizrAdapter', () => { name: 'Test', model: { softwareSystems: [ - { id: 'gl_svc', name: 'GL Service', url: 'https://gitlab.com/org/my-service' }, + { + ...dslElement('gl_svc'), + name: 'GL Service', + url: 'https://gitlab.com/org/my-service', + }, ], }, }; @@ -179,7 +175,11 @@ describe('StructurizrAdapter', () => { name: 'Test', model: { softwareSystems: [ - { id: 'bb_svc', name: 'BB Service', url: 'https://bitbucket.org/org/my-service' }, + { + ...dslElement('bb_svc'), + name: 'BB Service', + url: 'https://bitbucket.org/org/my-service', + }, ], }, }; @@ -194,7 +194,11 @@ describe('StructurizrAdapter', () => { name: 'Test', model: { softwareSystems: [ - { id: 'gl_svc', name: 'GL Service', url: 'https://gitlab.com/org/my-service' }, + { + ...dslElement('gl_svc'), + name: 'GL Service', + url: 'https://gitlab.com/org/my-service', + }, ], }, }; @@ -209,7 +213,11 @@ describe('StructurizrAdapter', () => { name: 'Test', model: { softwareSystems: [ - { id: 'bb_svc', name: 'BB Service', url: 'https://bitbucket.org/org/my-service' }, + { + ...dslElement('bb_svc'), + name: 'BB Service', + url: 'https://bitbucket.org/org/my-service', + }, ], }, }; @@ -285,13 +293,13 @@ describe('StructurizrAdapter', () => { model: { softwareSystems: [ { - id: 'a', + ...dslElement('a'), name: 'Service A', relationships: [ { sourceId: 'a', destinationId: 'b', description: 'calls', technology: 'https' }, ], }, - { id: 'b', name: 'Service B' }, + { ...dslElement('b'), name: 'Service B' }, ], relationships: [ { sourceId: 'a', destinationId: 'b', description: 'calls', technology: 'https' }, @@ -312,14 +320,14 @@ describe('StructurizrAdapter', () => { model: { softwareSystems: [ { - id: 'a', + ...dslElement('a'), name: 'Service A', relationships: [ { sourceId: 'a', destinationId: 'b', description: 'calls', technology: 'https' }, { sourceId: 'a', destinationId: 'b', description: 'calls', technology: 'grpc' }, ], }, - { id: 'b', name: 'Service B' }, + { ...dslElement('b'), name: 'Service B' }, ], }, }; @@ -397,9 +405,17 @@ describe('StructurizrAdapter', () => { name: 'Test', model: { softwareSystems: [ - { id: 'svc_a', name: 'Service A', url: 'https://github.com/example/monorepo' }, - { id: 'svc_b', name: 'Service B', url: 'https://github.com/example/monorepo' }, - { id: 'svc_c', name: 'Service C', url: 'https://github.com/example/other' }, + { + ...dslElement('svc_a'), + name: 'Service A', + url: 'https://github.com/example/monorepo', + }, + { + ...dslElement('svc_b'), + name: 'Service B', + url: 'https://github.com/example/monorepo', + }, + { ...dslElement('svc_c'), name: 'Service C', url: 'https://github.com/example/other' }, ], }, }; diff --git a/packages/core/src/adapters/structurizr/__tests__/fixtures/dsl-export/workspace.dsl b/packages/core/src/adapters/structurizr/__tests__/fixtures/dsl-export/workspace.dsl new file mode 100644 index 00000000..67f2fe48 --- /dev/null +++ b/packages/core/src/adapters/structurizr/__tests__/fixtures/dsl-export/workspace.dsl @@ -0,0 +1,25 @@ +workspace "Shop" "DSL export fixture: flat identifiers, no erode.id" { + model { + customer = person "Customer" + + shop = softwareSystem "Shop" { + storefront = container "Storefront" { + technology "TypeScript" + url "https://github.com/example/storefront" + } + orders = container "Order Service" { + technology "Java" + url "https://github.com/example/orders" + + orderApi = component "Order API" + component "Payment Adapter" + } + } + + payments = softwareSystem "Payment Provider" + + customer -> storefront "Browses" + storefront -> orders "Places orders" "HTTPS" + orderApi -> payments "Charges cards" + } +} diff --git a/packages/core/src/adapters/structurizr/__tests__/fixtures/dsl-export/workspace.json b/packages/core/src/adapters/structurizr/__tests__/fixtures/dsl-export/workspace.json new file mode 100644 index 00000000..ab1d5f7f --- /dev/null +++ b/packages/core/src/adapters/structurizr/__tests__/fixtures/dsl-export/workspace.json @@ -0,0 +1,122 @@ +{ + "id": 0, + "name": "Shop", + "description": "DSL export fixture: flat identifiers, no erode.id", + "model": { + "people": [ + { + "id": "1", + "name": "Customer", + "tags": "Element,Person", + "location": "Unspecified", + "properties": { + "structurizr.dsl.identifier": "customer" + }, + "relationships": [ + { + "id": "8", + "sourceId": "1", + "destinationId": "3", + "description": "Browses", + "tags": "Relationship" + }, + { + "id": "9", + "sourceId": "1", + "destinationId": "2", + "description": "Browses", + "linkedRelationshipId": "8" + } + ] + } + ], + "softwareSystems": [ + { + "id": "2", + "name": "Shop", + "tags": "Element,Software System", + "location": "Unspecified", + "properties": { + "structurizr.dsl.identifier": "shop" + }, + "containers": [ + { + "id": "3", + "name": "Storefront", + "technology": "TypeScript", + "url": "https://github.com/example/storefront", + "tags": "Element,Container", + "properties": { + "structurizr.dsl.identifier": "storefront" + }, + "relationships": [ + { + "id": "10", + "sourceId": "3", + "destinationId": "4", + "description": "Places orders", + "technology": "HTTPS", + "tags": "Relationship" + } + ] + }, + { + "id": "4", + "name": "Order Service", + "technology": "Java", + "url": "https://github.com/example/orders", + "tags": "Element,Container", + "properties": { + "structurizr.dsl.identifier": "orders" + }, + "relationships": [ + { + "id": "12", + "sourceId": "4", + "destinationId": "7", + "description": "Charges cards", + "linkedRelationshipId": "11" + } + ], + "components": [ + { + "id": "5", + "name": "Order API", + "tags": "Element,Component", + "properties": { + "structurizr.dsl.identifier": "orderApi" + }, + "relationships": [ + { + "id": "11", + "sourceId": "5", + "destinationId": "7", + "description": "Charges cards", + "tags": "Relationship" + } + ] + }, + { + "id": "6", + "name": "Payment Adapter", + "tags": "Element,Component", + "properties": { + "structurizr.dsl.identifier": "3f2b8c1e-5d4a-4e7b-9c6d-1a2b3c4d5e6f" + } + } + ] + } + ] + }, + { + "id": "7", + "name": "Payment Provider", + "tags": "Element,Software System", + "location": "Unspecified", + "properties": { + "structurizr.dsl.identifier": "payments" + } + } + ] + } +} diff --git a/packages/core/src/adapters/structurizr/__tests__/fixtures/mock-workspace.ts b/packages/core/src/adapters/structurizr/__tests__/fixtures/mock-workspace.ts index cfae13fa..9e97710c 100644 --- a/packages/core/src/adapters/structurizr/__tests__/fixtures/mock-workspace.ts +++ b/packages/core/src/adapters/structurizr/__tests__/fixtures/mock-workspace.ts @@ -6,14 +6,14 @@ export function createMockWorkspace(): StructurizrWorkspace { model: { softwareSystems: [ { - id: 'frontend', + ...dslElement('frontend'), name: 'Web Frontend', technology: 'React', tags: 'ui', url: 'https://github.com/example/frontend', }, { - id: 'api_gateway', + ...dslElement('api_gateway'), name: 'API Gateway', technology: 'Node.js', tags: 'backend', @@ -34,7 +34,7 @@ export function createMockWorkspace(): StructurizrWorkspace { ], }, { - id: 'user_service', + ...dslElement('user_service'), name: 'User Service', technology: 'Java', tags: 'backend,microservice', @@ -49,7 +49,7 @@ export function createMockWorkspace(): StructurizrWorkspace { ], }, { - id: 'product_service', + ...dslElement('product_service'), name: 'Product Service', technology: 'Python', tags: 'backend,microservice', @@ -64,43 +64,43 @@ export function createMockWorkspace(): StructurizrWorkspace { ], }, { - id: 'database', + ...dslElement('database'), name: 'PostgreSQL Database', technology: 'PostgreSQL', tags: 'storage', }, { - id: 'azure_infrastructure', + ...dslElement('azure_infrastructure'), name: 'Azure Infrastructure', description: 'Shared Azure infrastructure', tags: 'infrastructure', containers: [ { - id: 'vnet', + ...dslElement('azure_infrastructure.vnet'), name: 'Virtual Network', tags: 'infrastructure,networking', }, ], }, { - id: 'experimental', + ...dslElement('experimental'), name: 'Experimental', tags: 'experimental', containers: [ { - id: 'new_feature', + ...dslElement('experimental.new_feature'), name: 'Experimental Feature', tags: 'experimental', }, ], }, { - id: 'temp', + ...dslElement('temp'), name: 'Temporary', tags: 'temp', containers: [ { - id: 'test_service', + ...dslElement('temp.test_service'), name: 'Temporary Test Service', tags: 'temp', }, @@ -130,3 +130,11 @@ export function createMockWorkspace(): StructurizrWorkspace { }, }; } + +/** JSON id and DSL identifier property, as a Structurizr DSL export carries them. */ +export function dslElement( + identifier: string, + jsonId = identifier +): { id: string; properties: Record } { + return { id: jsonId, properties: { 'structurizr.dsl.identifier': identifier } }; +} diff --git a/packages/core/src/adapters/structurizr/__tests__/patcher-dsl-references.test.ts b/packages/core/src/adapters/structurizr/__tests__/patcher-dsl-references.test.ts new file mode 100644 index 00000000..4774b2fc --- /dev/null +++ b/packages/core/src/adapters/structurizr/__tests__/patcher-dsl-references.test.ts @@ -0,0 +1,147 @@ +import { copyFileSync, mkdtempSync, rmSync } from 'fs'; +import { tmpdir } from 'os'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { StructurizrAdapter } from '../adapter.js'; +import { StructurizrPatcher } from '../patcher.js'; +import type { ModelPatchOptions } from '../../model-patcher.js'; +import type { AIProvider } from '../../../providers/ai-provider.js'; + +vi.mock('child_process', async (importOriginal) => ({ + ...(await importOriginal()), + execFileSync: vi.fn(() => '/repo'), +})); + +vi.mock('../dsl-validator.js', () => ({ + validateStructurizrDsl: vi.fn().mockResolvedValue({ valid: true }), +})); + +const fixture = path.join( + path.dirname(fileURLToPath(import.meta.url)), + 'fixtures', + 'dsl-export', + 'workspace' +); +// A relationship line the Structurizr DSL can parse: identifier references only +const RELATIONSHIP_LINE = + /^\s*[A-Za-z_][\w-]*(\.[A-Za-z_][\w-]*)* -> [A-Za-z_][\w-]*(\.[A-Za-z_][\w-]*)* "[^"]*"( "[^"]*")?$/; + +const provider: AIProvider = { extractDependencies: vi.fn(), analyzeDrift: vi.fn() }; + +describe('StructurizrPatcher - DSL references', () => { + let adapter: StructurizrAdapter; + let options: Omit; + let modelDir: string; + + beforeEach(async () => { + modelDir = mkdtempSync(path.join(tmpdir(), 'erode-structurizr-refs-')); + copyFileSync(`${fixture}.dsl`, path.join(modelDir, 'workspace.dsl')); + adapter = new StructurizrAdapter(); + const model = await adapter.loadFromPath(`${fixture}.json`); + options = { + modelPath: modelDir, + existingRelationships: model.relationships, + componentIndex: model.componentIndex, + provider, + dslReferences: adapter.getDslReferences(), + }; + }); + + afterEach(() => { + rmSync(modelDir, { recursive: true, force: true }); + }); + + it('writes relationships with DSL identifiers', async () => { + const result = await new StructurizrPatcher().patch({ + ...options, + relationships: [ + { source: 'storefront', target: 'payments', kind: 'HTTPS', description: 'Gets "status"' }, + ], + }); + + expect(result?.relationshipLines).toEqual([ + ` storefront -> payments "Gets 'status'" "HTTPS"`, + ]); + for (const line of result?.relationshipLines ?? []) { + expect(line).toMatch(RELATIONSHIP_LINE); + } + expect(result?.content).toContain(`storefront -> payments "Gets 'status'" "HTTPS"`); + }); + + it('skips a relationship whose element has no DSL identifier', async () => { + const result = await new StructurizrPatcher().patch({ + ...options, + relationships: [ + { source: 'orders.payment_adapter', target: 'payments', description: 'Charges' }, + { source: 'orderApi', target: 'storefront', description: 'Notifies' }, + ], + }); + + expect(result?.relationshipLines).toEqual([' orderApi -> storefront "Notifies"']); + expect(result?.skipped).toHaveLength(1); + expect(result?.skipped[0]).toMatchObject({ + source: 'orders.payment_adapter', + target: 'payments', + }); + expect(result?.skipped[0]?.reason).toContain('No DSL identifier for orders.payment_adapter'); + }); + + it('returns no patch when every relationship lacks a DSL identifier', async () => { + const result = await new StructurizrPatcher().patch({ + ...options, + relationships: [{ source: 'orders.payment_adapter', target: 'shop', description: 'x' }], + }); + + expect(result).toBeNull(); + }); + + it('writes the reference, not the erode.id, when they differ', async () => { + const component = { name: 'Billing', tags: [], type: 'softwareSystem' }; + const result = await new StructurizrPatcher().patch({ + ...options, + relationships: [{ source: 'billing.v2', target: 'orders', description: 'Reads' }], + componentIndex: { + byRepository: new Map(), + byId: new Map([ + ['billing.v2', { id: 'billing.v2', ...component }], + ['orders', { id: 'orders', ...component }], + ]), + }, + existingRelationships: [], + dslReferences: new Map([ + ['billing.v2', 'billing'], + ['orders', 'shop.orders'], + ]), + }); + + expect(result?.relationshipLines).toEqual([' billing -> shop.orders "Reads"']); + }); + + it('skips new components with non-identifier ids and the relationships to them', async () => { + const result = await new StructurizrPatcher().patch({ + ...options, + newComponents: [ + { id: 'shop.billing', kind: 'container', name: 'Billing', description: 'Bills' }, + { id: 'ledger', kind: 'container', name: 'Ledger', description: 'Keeps books' }, + ], + relationships: [ + { source: 'storefront', target: 'shop.billing', description: 'Calls' }, + { source: 'storefront', target: 'ledger', description: 'Posts' }, + { source: 'storefront', target: 'payments', description: 'Pays' }, + ], + }); + + expect(result?.newComponents?.map((c) => c.id)).toEqual(['ledger']); + expect(result?.content).not.toContain('shop.billing ='); + expect(result?.relationshipLines).toEqual([ + ' storefront -> ledger "Posts"', + ' storefront -> payments "Pays"', + ]); + const reasons = result?.skipped.map((s) => s.reason).join('\n') ?? ''; + expect(reasons).toContain('"shop.billing" is not a valid DSL identifier'); + expect( + result?.skipped.some((s) => s.target === 'shop.billing' && s.source === 'storefront') + ).toBe(true); + }); +}); diff --git a/packages/core/src/adapters/structurizr/adapter.ts b/packages/core/src/adapters/structurizr/adapter.ts index 6e8259c3..416ecba8 100644 --- a/packages/core/src/adapters/structurizr/adapter.ts +++ b/packages/core/src/adapters/structurizr/adapter.ts @@ -16,17 +16,8 @@ import type { ArchitectureModel, SimpleComponent, } from '../architecture-types.js'; -import type { - StructurizrWorkspace, - StructurizrSoftwareSystem, - StructurizrContainer, - StructurizrComponent, - StructurizrPerson, - StructurizrRelationship, -} from './structurizr-types.js'; - -type StructurizrElement = - StructurizrPerson | StructurizrSoftwareSystem | StructurizrContainer | StructurizrComponent; +import type { StructurizrWorkspace, StructurizrRelationship } from './structurizr-types.js'; +import { resolveElements, type ResolvedElement, type StructurizrElement } from './element-ids.js'; const BUILTIN_TAGS = new Set([ 'Element', @@ -42,61 +33,42 @@ export class StructurizrAdapter implements ArchitectureModelAdapter { protected workspace: StructurizrWorkspace | null = null; private componentIndex: ComponentIndex | null = null; private relationships: ModelRelationship[] | null = null; - private identifierMap = new Map(); + private elements: ResolvedElement[] = []; + private dslReferences: ReadonlyMap = new Map(); async loadFromPath(dslPath: string): Promise { - const resolvedPath = this.resolveWorkspacePath(resolve(dslPath)); - validatePath(resolvedPath, 'file'); - - try { - const rawWorkspace = await this.parseWorkspace(resolvedPath); - this.workspace = validate(StructurizrWorkspaceSchema, rawWorkspace, 'Structurizr workspace'); - } catch (error) { - throw AdapterError.fromStructurizrError(error); - } - - this.identifierMap = this.buildIdentifierMap(); - const components = this.extractComponents(); - this.relationships = this.extractRelationships(); - this.componentIndex = this.buildComponentIndex(components); - - return { - components, - relationships: this.relationships, - componentIndex: this.componentIndex, - }; + await this.loadWorkspace(dslPath); + return this.indexWorkspace(); } async loadAndListComponents(dslPath: string): Promise { - const resolvedPath = this.resolveWorkspacePath(resolve(dslPath)); - validatePath(resolvedPath, 'file'); - - try { - const rawWorkspace = await this.parseWorkspace(resolvedPath); - this.workspace = validate(StructurizrWorkspaceSchema, rawWorkspace, 'Structurizr workspace'); - } catch (error) { - throw AdapterError.fromStructurizrError(error); - } + await this.loadWorkspace(dslPath); + this.setElements(resolveElements(this.workspace?.model)); + + return this.elements.map(({ element, id, kind }) => ({ + id, + title: element.name, + kind, + links: element.url ? [element.url] : [], + tags: this.parseTags(element.tags), + })); + } - this.identifierMap = this.buildIdentifierMap(); - const components: SimpleComponent[] = []; - - this.walkElements((element, parentPath) => { - const localId = element.id ?? this.toSnakeCase(element.name ?? ''); - const resolvedId = this.resolveElementId(element, localId, parentPath); - const url = element.url; - const links = url ? [url] : []; - - components.push({ - id: resolvedId, - title: element.name, - kind: this.getElementType(element, parentPath), - links, - tags: this.parseTags(element.tags), - }); - }); + /** Element id to the identifier that references it in DSL, for elements that have one. */ + getDslReferences(): ReadonlyMap { + return this.dslReferences; + } - return components; + /** Replaces the element list and drops everything derived from an earlier load. */ + private setElements(elements: ResolvedElement[]): void { + this.elements = elements; + this.componentIndex = null; + this.relationships = null; + const references = new Map(); + for (const { id, dslReference } of elements) { + if (dslReference) references.set(id, dslReference); + } + this.dslReferences = references; } protected async parseWorkspace(resolvedPath: string): Promise { @@ -107,32 +79,36 @@ export class StructurizrAdapter implements ArchitectureModelAdapter { return exportDslToJson(resolvedPath); } - protected extractComponents(): ArchitecturalComponent[] { + protected indexWorkspace(): ArchitectureModel { if (!this.workspace) { throw AdapterError.notLoaded('structurizr'); } + this.setElements(resolveElements(this.workspace.model)); + const components = this.extractComponents(); + this.relationships = this.extractRelationships(); + this.componentIndex = this.buildComponentIndex(components); - const components: ArchitecturalComponent[] = []; + return { + components, + relationships: this.relationships, + componentIndex: this.componentIndex, + }; + } - this.walkElements((element, parentPath) => { - const localId = element.id ?? this.toSnakeCase(element.name ?? ''); - const resolvedId = this.resolveElementId(element, localId, parentPath); - const tags = this.parseTags(element.tags); - const repository = this.extractRepositoryUrl(element); - const type = this.getElementType(element, parentPath); - - components.push({ - id: resolvedId, - name: element.name ?? localId, - description: element.description, - repository, - tags, - type, - technology: typeof element.technology === 'string' ? element.technology : undefined, - }); - }); + protected extractComponents(): ArchitecturalComponent[] { + if (!this.workspace) { + throw AdapterError.notLoaded('structurizr'); + } - return components; + return this.elements.map(({ element, id, kind }) => ({ + id, + name: element.name ?? id, + description: element.description, + repository: this.extractRepositoryUrl(element), + tags: this.parseTags(element.tags), + type: kind, + technology: typeof element.technology === 'string' ? element.technology : undefined, + })); } protected extractRelationships(): ModelRelationship[] { @@ -140,12 +116,13 @@ export class StructurizrAdapter implements ArchitectureModelAdapter { throw AdapterError.notLoaded('structurizr'); } + const idByKey = new Map(this.elements.map((e) => [e.key, e.id])); const relationships: ModelRelationship[] = []; const seen = new Set(); const addRelationship = (rel: StructurizrRelationship): void => { - const source = this.resolveIdentifier(rel.sourceId); - const target = this.resolveIdentifier(rel.destinationId); + const source = idByKey.get(rel.sourceId); + const target = idByKey.get(rel.destinationId); if (!source || !target) return; @@ -161,20 +138,14 @@ export class StructurizrAdapter implements ArchitectureModelAdapter { }); }; - this.walkElements((element) => { - if (element.relationships) { - for (const rel of element.relationships) { - addRelationship(rel); - } - } - }); - - const modelRels = this.workspace.model?.relationships; - if (modelRels) { - for (const rel of modelRels) { + for (const { element } of this.elements) { + for (const rel of element.relationships ?? []) { addRelationship(rel); } } + for (const rel of this.workspace.model?.relationships ?? []) { + addRelationship(rel); + } return relationships; } @@ -302,6 +273,18 @@ export class StructurizrAdapter implements ArchitectureModelAdapter { return false; } + private async loadWorkspace(dslPath: string): Promise { + const resolvedPath = this.resolveWorkspacePath(resolve(dslPath)); + validatePath(resolvedPath, 'file'); + + try { + const rawWorkspace = await this.parseWorkspace(resolvedPath); + this.workspace = validate(StructurizrWorkspaceSchema, rawWorkspace, 'Structurizr workspace'); + } catch (error) { + throw AdapterError.fromStructurizrError(error); + } + } + private resolveWorkspacePath(inputPath: string): string { try { if (!statSync(inputPath).isDirectory()) { @@ -327,72 +310,6 @@ export class StructurizrAdapter implements ArchitectureModelAdapter { ); } - private buildIdentifierMap(): Map { - const map = new Map(); - - this.walkElements((element, parentPath) => { - const localId = element.id ?? this.toSnakeCase(element.name ?? ''); - const resolvedId = this.resolveElementId(element, localId, parentPath); - - map.set(localId, resolvedId); - - const dottedPath = parentPath ? `${parentPath}.${localId}` : localId; - if (dottedPath !== localId) { - map.set(dottedPath, resolvedId); - } - }); - - return map; - } - - private walkElements(callback: (element: StructurizrElement, parentPath: string) => void): void { - if (!this.workspace?.model) return; - - const walk = (elements: StructurizrElement[] | undefined, parentPath: string): void => { - if (!elements) return; - for (const element of elements) { - const localId = element.id ?? this.toSnakeCase(element.name ?? ''); - const resolvedId = this.resolveElementId(element, localId, parentPath); - callback(element, parentPath); - - if ('containers' in element && Array.isArray(element.containers)) { - walk(element.containers as StructurizrElement[], resolvedId); - } - if ('components' in element && Array.isArray(element.components)) { - walk(element.components as StructurizrElement[], resolvedId); - } - } - }; - - walk(this.workspace.model.people, ''); - walk(this.workspace.model.softwareSystems, ''); - } - - private resolveElementId( - element: StructurizrElement, - localId: string, - parentPath: string - ): string { - // Priority 1: erode.id property - if (element.properties?.['erode.id']) { - return element.properties['erode.id']; - } - - return parentPath ? `${parentPath}.${localId}` : localId; - } - - private resolveIdentifier(ref: string): string | undefined { - const resolved = this.identifierMap.get(ref); - if (resolved) return resolved; - - // Try as-is (might already be a resolved ID) - for (const value of this.identifierMap.values()) { - if (value === ref) return ref; - } - - return undefined; - } - private extractRepositoryUrl(element: StructurizrElement): string | undefined { const url = element.url; if (!url) return undefined; @@ -407,29 +324,4 @@ export class StructurizrAdapter implements ArchitectureModelAdapter { .map((t) => t.trim()) .filter((t) => t.length > 0 && !BUILTIN_TAGS.has(t)); } - - private getElementType(element: StructurizrElement, parentPath: string): string { - // Infer from position in hierarchy or explicit type from parser - if ('containers' in element && element.containers) return 'softwareSystem'; - if ('components' in element && element.components) return 'container'; - - if ( - this.workspace?.model?.people?.some((p) => p.id === element.id && p.name === element.name) - ) { - return 'person'; - } - - // Infer from nesting depth - if (!parentPath) return 'softwareSystem'; - if (parentPath.split('.').length === 1) return 'container'; - return 'component'; - } - - private toSnakeCase(name: string): string { - return name - .replace(/([a-z])([A-Z])/g, '$1_$2') - .replace(/[^a-zA-Z0-9]+/g, '_') - .replace(/^_|_$/g, '') - .toLowerCase(); - } } diff --git a/packages/core/src/adapters/structurizr/element-ids.ts b/packages/core/src/adapters/structurizr/element-ids.ts new file mode 100644 index 00000000..108f0ee6 --- /dev/null +++ b/packages/core/src/adapters/structurizr/element-ids.ts @@ -0,0 +1,145 @@ +import { AdapterError, ErrorCode } from '../../errors.js'; +import { exportedDslIdentifierPattern } from '../../schemas/common.schema.js'; +import type { + StructurizrWorkspace, + StructurizrSoftwareSystem, + StructurizrContainer, + StructurizrComponent, + StructurizrPerson, +} from './structurizr-types.js'; + +export type StructurizrElement = + StructurizrPerson | StructurizrSoftwareSystem | StructurizrContainer | StructurizrComponent; + +type StructurizrElementKind = 'person' | 'softwareSystem' | 'container' | 'component'; + +export interface ResolvedElement { + element: StructurizrElement; + kind: StructurizrElementKind; + /** Id erode exposes to the pipeline, prompts and users */ + id: string; + /** Key that relationship `sourceId`/`destinationId` refer to (the JSON id) */ + key: string; + /** Identifier usable in DSL at model scope, when the element has a stable one */ + dslReference?: string; + parent?: ResolvedElement; +} + +const ERODE_ID_PROPERTY = 'erode.id'; +const DSL_IDENTIFIER_PROPERTY = 'structurizr.dsl.identifier'; +// The DSL parser registers anonymous elements under a random UUID, which changes on every export +const UUID_SEGMENT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** + * The `structurizr.dsl.identifier` property, if it can be referenced from DSL. + * Flat mode stores a bare name, hierarchical mode the dotted path; both resolve at model scope. + */ +function readDslReference(element: StructurizrElement): string | undefined { + const value = element.properties?.[DSL_IDENTIFIER_PROPERTY]; + if (!value) return undefined; + const segments = value.split('.'); + const stable = segments.every( + (s) => exportedDslIdentifierPattern.test(s) && !UUID_SEGMENT.test(s) + ); + return stable ? value : undefined; +} + +function slugify(name: string): string { + return name + .normalize('NFKD') + .replace(/\p{M}+/gu, '') + .replace(/(\p{Ll})(\p{Lu})/gu, '$1_$2') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '_') + .replace(/^_+|_+$/g, ''); +} + +function describe(entry: Pick): string { + const name = entry.element.name ?? '(unnamed)'; + const path = entry.parent ? ` in ${describe(entry.parent)}` : ''; + const jsonId = entry.element.id ? ` (JSON id ${entry.element.id})` : ''; + return `${entry.kind} "${name}"${jsonId}${path}`; +} + +function fallbackId( + element: StructurizrElement, + kind: StructurizrElementKind, + parent: ResolvedElement | undefined +): string { + const slug = slugify(element.name ?? ''); + if (!slug) { + const label = describe({ element, kind, parent }); + throw new AdapterError( + `Cannot derive an id for ${label}`, + ErrorCode.MODEL_LOAD_FAILED, + 'structurizr', + `Cannot derive an id for ${label}: it has no DSL identifier and its name has no letters or digits.`, + { element: label }, + ['Assign a DSL identifier to the element, or set an "erode.id" property on it'] + ); + } + return parent ? `${parent.id}.${slug}` : slug; +} + +function duplicateIdError(id: string, first: ResolvedElement, second: ResolvedElement) { + const a = describe(first); + const b = describe(second); + return new AdapterError( + `Duplicate element id "${id}": ${a} and ${b}`, + ErrorCode.MODEL_LOAD_FAILED, + 'structurizr', + `Two elements resolve to the same id "${id}": ${a} and ${b}.`, + { id, first: a, second: b }, + [ + 'Give one of the elements a distinct "erode.id" property or DSL identifier', + 'Element ids come from "erode.id", then the DSL identifier, then the element name', + ] + ); +} + +/** + * Resolves every element's id: `erode.id`, then a stable DSL identifier, then the + * parent's id plus a slug of the name. Duplicates fail the load instead of being + * suffixed, since a suffix would depend on declaration order. + */ +export function resolveElements(model: StructurizrWorkspace['model']): ResolvedElement[] { + const resolved: ResolvedElement[] = []; + const byId = new Map(); + + const add = ( + element: StructurizrElement, + kind: StructurizrElementKind, + parent?: ResolvedElement + ): ResolvedElement => { + const dslReference = readDslReference(element); + const erodeId = element.properties?.[ERODE_ID_PROPERTY]; + const id = + (erodeId === '' ? undefined : erodeId) ?? dslReference ?? fallbackId(element, kind, parent); + const entry: ResolvedElement = { + element, + kind, + id, + key: element.id ?? id, + dslReference, + parent, + }; + const clash = byId.get(id); + if (clash) throw duplicateIdError(id, clash, entry); + byId.set(id, entry); + resolved.push(entry); + return entry; + }; + + for (const person of model?.people ?? []) add(person, 'person'); + for (const system of model?.softwareSystems ?? []) { + const systemEntry = add(system, 'softwareSystem'); + for (const container of system.containers ?? []) { + const containerEntry = add(container, 'container', systemEntry); + for (const component of container.components ?? []) { + add(component, 'component', containerEntry); + } + } + } + + return resolved; +} diff --git a/packages/core/src/adapters/structurizr/patcher.ts b/packages/core/src/adapters/structurizr/patcher.ts index 7b7f27ee..debc2ebc 100644 --- a/packages/core/src/adapters/structurizr/patcher.ts +++ b/packages/core/src/adapters/structurizr/patcher.ts @@ -1,10 +1,11 @@ import { readdirSync, statSync } from 'fs'; import { join, resolve } from 'path'; import { BasePatcher } from '../base-patcher.js'; +import { dslIdentifierPattern } from '../../schemas/common.schema.js'; import { validateStructurizrDsl } from './dsl-validator.js'; import type { StructuredRelationship, NewComponent } from '../../analysis/analysis-types.js'; -import type { ModelRelationship } from '../architecture-types.js'; -import type { DslValidationResult } from '../model-patcher.js'; +import type { ModelRelationship, ComponentIndex } from '../architecture-types.js'; +import type { DslValidationResult, ModelPatchOptions, PatchResult } from '../model-patcher.js'; /** * Escaping of `"` inside Structurizr strings is not documented, so quotes become `'` @@ -26,14 +27,67 @@ export class StructurizrPatcher extends BasePatcher { // Structurizr strings use double quotes only, so an apostrophe in a `#` comment opens nothing protected override readonly scanOptions = { quotes: ['"'], hashComments: true }; + // Pending components are written under their erode id, so only valid DSL identifiers can be declared + protected override filterNewComponents( + components: NewComponent[], + skipped: PatchResult['skipped'] + ): NewComponent[] { + return components.filter((comp) => { + if (dslIdentifierPattern.test(comp.id)) return true; + skipped.push({ + source: comp.id, + target: comp.id, + reason: `New component "${comp.id}" is not a valid DSL identifier (letters, digits, underscores and hyphens, starting with a letter), so it was not added`, + }); + return false; + }); + } + + // Element ids are erode's, not DSL references; a relationship is only written when both ends resolve + protected override validateRelationships( + relationships: StructuredRelationship[], + componentIndex: ComponentIndex, + skipped: PatchResult['skipped'], + pendingComponentIds?: Set, + context?: ModelPatchOptions + ): StructuredRelationship[] { + const known = super.validateRelationships( + relationships, + componentIndex, + skipped, + pendingComponentIds, + context + ); + const references = context?.dslReferences; + if (!references) return known; + + const hasReference = (id: string): boolean => + references.has(id) || !!pendingComponentIds?.has(id); + + return known.filter((rel) => { + const missing = [rel.source, rel.target].find((id) => !hasReference(id)); + if (missing === undefined) return true; + skipped.push({ + source: rel.source, + target: rel.target, + reason: `No DSL identifier for ${missing}: assign one in the DSL so the relationship can reference it`, + }); + return false; + }); + } + protected generateDslLines( unique: StructuredRelationship[], - _existing: ModelRelationship[] + _existing: ModelRelationship[], + context?: ModelPatchOptions ): string[] { + const references = context?.dslReferences; return unique.map((rel) => { const desc = dslString(rel.description); const technology = rel.kind ? ` "${dslString(rel.kind)}"` : ''; - return ` ${rel.source} -> ${rel.target} "${desc}"${technology}`; + const source = references?.get(rel.source) ?? rel.source; + const target = references?.get(rel.target) ?? rel.target; + return ` ${source} -> ${target} "${desc}"${technology}`; }); } diff --git a/packages/core/src/pipelines/analyze.ts b/packages/core/src/pipelines/analyze.ts index e0985a0b..bbcf96fb 100644 --- a/packages/core/src/pipelines/analyze.ts +++ b/packages/core/src/pipelines/analyze.ts @@ -290,6 +290,7 @@ export async function runAnalyze( newComponents: ctx.analysisResult.modelUpdates?.newComponents, validationBaseline: adapter.getValidationBaseline?.(), elementSourceFiles: adapter.getElementSourceFiles?.(), + dslReferences: adapter.getDslReferences?.(), }); if (ctx.patchResult) { const relCount = ctx.patchResult.insertedLines.length; diff --git a/packages/core/src/schemas/common.schema.ts b/packages/core/src/schemas/common.schema.ts index 24a2b013..0d91c06a 100644 --- a/packages/core/src/schemas/common.schema.ts +++ b/packages/core/src/schemas/common.schema.ts @@ -20,8 +20,17 @@ export const ViolationSchema = z /** Only alphanumeric, dots, underscores, and hyphens (valid component IDs). */ const componentIdPattern = /^[a-zA-Z0-9._-]+$/; -/** Valid DSL identifier: starts with a letter, then alphanumeric, underscores, or hyphens. */ -const dslIdentifierPattern = /^[a-zA-Z][a-zA-Z0-9_-]*$/; +/** + * DSL identifier erode will write: starts with a letter, then alphanumeric, underscores, or hyphens. + * Use this for anything the patcher emits. + */ +export const dslIdentifierPattern = /^[a-zA-Z][a-zA-Z0-9_-]*$/; +/** + * Identifier segment accepted when reading a Structurizr export. Wider than + * `dslIdentifierPattern` because the DSL parser also allows a leading digit or underscore + * in identifiers that already exist in a model. + */ +export const exportedDslIdentifierPattern = /^\w[\w-]*$/; /** Single-line printable characters, no DSL delimiters (quotes, braces, brackets, angle brackets, pipes). */ const safeDslTextPattern = /^[^\n\r'"{}[\]`\\<>|]+$/; diff --git a/packages/web/src/content/docs/docs/contributing/adrs/003-architecture-model-adapter-system.md b/packages/web/src/content/docs/docs/contributing/adrs/003-architecture-model-adapter-system.md index d34a0aa7..e34370b9 100644 --- a/packages/web/src/content/docs/docs/contributing/adrs/003-architecture-model-adapter-system.md +++ b/packages/web/src/content/docs/docs/contributing/adrs/003-architecture-model-adapter-system.md @@ -46,6 +46,7 @@ The adapter pattern decouples the pipeline from model format details. Adding a n - **2026-11-17:** `ModelRelationship` and `ComponentRelationship` gain optional `technology`, `description` and `tags`. The LikeC4 adapter fills them and the drift prompt renders them; the Structurizr adapter leaves them unset because it already maps description to `title` and technology to `kind`. - **2026-11-17:** `ModelRelationship` gains an optional `bidirectional` flag. Adapters set it when one declared relationship permits both directions (LikeC4 `a <-> b`). The LikeC4 adapter indexes both directions for dependency checks; formats without the concept leave it unset. - **2026-11-17:** `ArchitectureModelAdapter` gains an optional `getElementSourceFiles()` (element ID to declaring file), and `ModelPatchOptions` an optional `elementSourceFiles`. The patcher uses them to pick the file to patch and falls back to its own file scan when they are absent. Only the LikeC4 adapter implements it. +- **2026-11-17:** Structurizr element IDs come from the `erode.id` property, then the `structurizr.dsl.identifier` property the DSL parser writes into the workspace JSON, then the parent ID plus a snake_case name. Numeric JSON IDs only resolve relationship endpoints and are never exposed. Identifiers containing a UUID segment (anonymous elements) are ignored, because the parser regenerates them on each export. Element types come from the JSON array an element sits in. Duplicate IDs fail the load with an `AdapterError` naming both elements, rather than being suffixed, since suffixes would depend on declaration order. `ArchitectureModelAdapter` gains an optional `getDslReferences()` (element ID to DSL identifier) and `ModelPatchOptions` an optional `dslReferences`. When it is set, the Structurizr patcher writes relationships with DSL identifiers and skips relationships to elements without one. ## Related commits diff --git a/packages/web/src/content/docs/docs/models/structurizr.md b/packages/web/src/content/docs/docs/models/structurizr.md index 0b7d42cf..2d9bc39e 100644 --- a/packages/web/src/content/docs/docs/models/structurizr.md +++ b/packages/web/src/content/docs/docs/models/structurizr.md @@ -124,13 +124,22 @@ The more accurately the model reflects the dependencies that matter, the better ## ID resolution -Erode resolves element IDs using the following priority: +A workspace JSON gives every element a numeric `id` ("1", "5", ...). Erode uses these only to resolve relationships. It resolves the element IDs it shows and reports in this order: -1. **`erode.id` property**: if an element has a `properties` block with `erode.id`, that value is used directly -2. **DSL identifier**: the variable name assigned to the element (e.g., `backend` in `backend = container "Backend API"`) -3. **snake_case name**: the element name converted to snake_case (e.g., `"Backend API"` becomes `backend_api`) +1. **`erode.id` property**: if an element has a `properties` block with `erode.id`, that value is used as is. +2. **DSL identifier**: the identifier assigned in the DSL (e.g., `backend` in `backend = container "Backend API"`). The DSL parser stores it in the exported JSON as the `structurizr.dsl.identifier` property. With the default flat identifiers it is the bare name (`backend`); with `!identifiers hierarchical` it is the dotted path (`softwareSystem.backend`). +3. **Name fallback**: for elements without an identifier, the parent's ID plus the element name converted to snake_case (e.g., a container `"Backend API"` in `softwareSystem` becomes `softwareSystem.backend_api`). The slug is ASCII: accents are stripped (`Betalningstjänst` becomes `betalningstjanst`) and any other character becomes `_`. If nothing remains, loading fails; set `erode.id` or a DSL identifier. -IDs are hierarchical: a container inside a software system gets a dotted path like `my_system.backend`. +Every resolved ID must be unique. If two elements resolve to the same ID (for example two `erode.id` values, or the names `"Payment Service"` and `"Payment-Service"` under the same parent), loading fails with an error that names both elements. Give one of them an `erode.id` or a DSL identifier. + +### Model patches + +When Erode adds a relationship to the DSL, it writes the elements' DSL identifiers, not their Erode IDs. A relationship to an element without a DSL identifier is skipped and listed with the reason. To let Erode patch relationships for an element, assign it an identifier in the DSL. + +### Upgrading + +- Element IDs are now DSL identifiers (or `erode.id`), not the numeric JSON ids. Update any stored references to the old IDs. +- Two elements that resolve to the same ID now fail the load instead of being suffixed. ## Version requirements From f82642dd556e3c626e7c146224fd2e8c4a851f72 Mon Sep 17 00:00:00 2001 From: Anders Hassis Date: Tue, 17 Nov 2026 18:55:11 +0100 Subject: [PATCH 2/2] fix(core): report skip reasons when no model patch remains Callers can pass a skipped array in the patch options; analyze prints the reasons when every relationship was skipped, so users see why, for example that an element needs a DSL identifier. --- packages/core/src/adapters/base-patcher.ts | 2 +- packages/core/src/adapters/model-patcher.ts | 2 ++ .../structurizr/__tests__/patcher-dsl-references.test.ts | 5 ++++- packages/core/src/pipelines/analyze.ts | 5 +++++ 4 files changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/core/src/adapters/base-patcher.ts b/packages/core/src/adapters/base-patcher.ts index f42bf6f7..07e23c5e 100644 --- a/packages/core/src/adapters/base-patcher.ts +++ b/packages/core/src/adapters/base-patcher.ts @@ -97,7 +97,7 @@ export abstract class BasePatcher implements ModelPatcher { async patch(options: ModelPatchOptions): Promise { const { modelPath, relationships, existingRelationships, componentIndex, provider } = options; - const skipped: PatchResult['skipped'] = []; + const skipped: PatchResult['skipped'] = options.skipped ?? []; this.debugLog('Input relationships', relationships); diff --git a/packages/core/src/adapters/model-patcher.ts b/packages/core/src/adapters/model-patcher.ts index 0e525aa9..a46d1195 100644 --- a/packages/core/src/adapters/model-patcher.ts +++ b/packages/core/src/adapters/model-patcher.ts @@ -63,6 +63,8 @@ export interface ModelPatchOptions { elementSourceFiles?: ReadonlyMap; /** Element ID to its DSL reference; when set, relationships to elements without one are skipped */ dslReferences?: ReadonlyMap; + /** When given, skip reasons are also recorded here, so callers see them when no patch remains */ + skipped?: PatchResult['skipped']; } export interface ModelPatcher { diff --git a/packages/core/src/adapters/structurizr/__tests__/patcher-dsl-references.test.ts b/packages/core/src/adapters/structurizr/__tests__/patcher-dsl-references.test.ts index 4774b2fc..634c9000 100644 --- a/packages/core/src/adapters/structurizr/__tests__/patcher-dsl-references.test.ts +++ b/packages/core/src/adapters/structurizr/__tests__/patcher-dsl-references.test.ts @@ -87,13 +87,16 @@ describe('StructurizrPatcher - DSL references', () => { expect(result?.skipped[0]?.reason).toContain('No DSL identifier for orders.payment_adapter'); }); - it('returns no patch when every relationship lacks a DSL identifier', async () => { + it('returns no patch when every relationship lacks a DSL identifier, keeping the reasons', async () => { + const skipped: NonNullable = []; const result = await new StructurizrPatcher().patch({ ...options, + skipped, relationships: [{ source: 'orders.payment_adapter', target: 'shop', description: 'x' }], }); expect(result).toBeNull(); + expect(skipped[0]?.reason).toContain('No DSL identifier for orders.payment_adapter'); }); it('writes the reference, not the erode.id, when they differ', async () => { diff --git a/packages/core/src/pipelines/analyze.ts b/packages/core/src/pipelines/analyze.ts index bbcf96fb..529c6181 100644 --- a/packages/core/src/pipelines/analyze.ts +++ b/packages/core/src/pipelines/analyze.ts @@ -281,7 +281,9 @@ export async function runAnalyze( } p.start('Generating model patch'); const patcher = createModelPatcher(adapter.metadata.id); + const patchSkipped: PatchResult['skipped'] = []; ctx.patchResult = await patcher.patch({ + skipped: patchSkipped, modelPath: effectiveModelPath, relationships: ctx.analysisResult.modelUpdates?.relationships ?? [], existingRelationships: adapter.getAllRelationships(), @@ -317,6 +319,9 @@ export async function runAnalyze( } } else { p.info('All relationships already exist or were invalid, no new components to add'); + for (const { source, target, reason } of patchSkipped) { + p.info(` Skipped ${source} -> ${target}: ${reason}`); + } } } else if (shouldPatch) { p.info('No model update relationships or new components from analysis');