@documentation-robotics/cli 0.1.10 → 0.1.12
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.
- package/dist/cli.js +18 -2
- package/dist/cli.js.map +2 -2
- package/dist/commands/repair.js +62 -0
- package/dist/commands/repair.js.map +7 -0
- package/dist/commands/version.js +1 -1
- package/dist/core/attribute-collision-repair.js +73 -0
- package/dist/core/attribute-collision-repair.js.map +7 -0
- package/dist/core/graph-model.js +14 -1
- package/dist/core/graph-model.js.map +2 -2
- package/dist/core/model.js +10 -7
- package/dist/core/model.js.map +2 -2
- package/dist/core/reference-registry.js +11 -5
- package/dist/core/reference-registry.js.map +2 -2
- package/dist/export/plantuml-exporter.js +3 -1
- package/dist/export/plantuml-exporter.js.map +2 -2
- package/dist/telemetry/index.js +1 -1
- package/dist/utils/element-reference-shape.js +12 -0
- package/dist/utils/element-reference-shape.js.map +7 -0
- package/dist/utils/spec-version.js +1 -1
- package/dist/utils/spec-version.js.map +1 -1
- package/package.json +9 -9
package/dist/cli.js
CHANGED
|
@@ -32,6 +32,7 @@ import { reportsCommands } from "./commands/reports.js";
|
|
|
32
32
|
import { auditCommand } from "./commands/audit.js";
|
|
33
33
|
import { auditDiffCommand } from "./commands/audit-diff.js";
|
|
34
34
|
import { auditSnapshotsCommand } from "./commands/audit-snapshots.js";
|
|
35
|
+
import { repairAttributeCollisionCommand } from "./commands/repair.js";
|
|
35
36
|
import { initTelemetry, startActiveSpan, shutdownTelemetry } from "./telemetry/index.js";
|
|
36
37
|
import { installConsoleInterceptor } from "./telemetry/console-interceptor.js";
|
|
37
38
|
import { getErrorMessage } from "./utils/errors.js";
|
|
@@ -47,7 +48,7 @@ async function extractExitCode(error) {
|
|
|
47
48
|
}
|
|
48
49
|
return 1;
|
|
49
50
|
}
|
|
50
|
-
const cliVersion = "0.1.
|
|
51
|
+
const cliVersion = "0.1.12", program = new Command();
|
|
51
52
|
(process.argv.includes("--version") || process.argv.includes("-V")) && (process.argv = ["node", "dr", "version"]), program.name("dr").description("Documentation Robotics CLI - Architecture Model Management").option("-v, --verbose", "Enable verbose output").option("--debug", "Enable debug mode").exitOverride().showSuggestionAfterError().hook("preAction", async (thisCommand) => {
|
|
52
53
|
const options = thisCommand.opts();
|
|
53
54
|
setGlobalOptions({
|
|
@@ -215,7 +216,22 @@ Actions:
|
|
|
215
216
|
Examples:
|
|
216
217
|
$ dr audit:snapshots list
|
|
217
218
|
$ dr audit:snapshots delete --id 20260220-100000
|
|
218
|
-
$ dr audit:snapshots clear`).action((action, options) => auditSnapshotsCommand({ ...options, action }))
|
|
219
|
+
$ dr audit:snapshots clear`).action((action, options) => auditSnapshotsCommand({ ...options, action })), program.command("repair:attribute-collision").description(`Find and best-effort-recover model data lost to a fixed bug where saveLayer() stripped "source"/"x-source-reference" attributes from every element, even when a node type's schema declared one as a real (sometimes required) attribute`).option("--apply", "Restore recoverable values found in changeset history (default: report only)").option("--format <format>", "Output format: text (default), json").option("--output <path>", "Write the report to a file instead of stdout").addHelpText("after", `
|
|
220
|
+
This repairs damage from a fixed bug in Model.saveLayer(): a hardcoded, type-blind "internal
|
|
221
|
+
fields" blocklist unconditionally stripped any attribute literally named "source" or
|
|
222
|
+
"x-source-reference" from every element's attributes before writing YAML, regardless of whether
|
|
223
|
+
the element's own schema declared it as a real domain attribute. 41 of 191 node schemas across 8
|
|
224
|
+
layers do (3 mark it required, meaning affected elements fail validation today).
|
|
225
|
+
|
|
226
|
+
Recovery is best-effort: values can only be restored if they still exist in changeset history
|
|
227
|
+
(committing a changeset does not delete it). Elements with no recoverable value are always
|
|
228
|
+
reported, never fabricated \u2014 you'll need to re-supply those manually with
|
|
229
|
+
"dr update <id> --attributes '{...}'".
|
|
230
|
+
|
|
231
|
+
Examples:
|
|
232
|
+
$ dr repair:attribute-collision # Report only \u2014 no changes made
|
|
233
|
+
$ dr repair:attribute-collision --apply # Restore every recoverable value
|
|
234
|
+
$ dr repair:attribute-collision --format json --output report.json`).action((options) => repairAttributeCollisionCommand(options));
|
|
219
235
|
const relationshipGroup = program.command("relationship").description("Relationship operations");
|
|
220
236
|
relationshipCommands(relationshipGroup);
|
|
221
237
|
const elementGroup = program.command("element").description("Element operations");
|
package/dist/cli.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/cli.ts"],
|
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n\n/**\n * Documentation Robotics CLI - Bun Implementation\n * Entry point for the command-line interface\n *\n * Instrumented with OpenTelemetry to create root spans for command execution.\n * Telemetry is controlled by the TELEMETRY_ENABLED build-time constant.\n */\n\nimport { Command, CommanderError } from \"commander\";\nimport { setGlobalOptions } from \"./utils/globals.js\";\nimport { initCommand } from \"./commands/init.js\";\nimport { addCommand } from \"./commands/add.js\";\nimport { updateCommand } from \"./commands/update.js\";\nimport { deleteCommand } from \"./commands/delete.js\";\nimport { showCommand } from \"./commands/show.js\";\nimport { listCommand } from \"./commands/list.js\";\nimport { searchCommand } from \"./commands/search.js\";\nimport { validateCommand } from \"./commands/validate.js\";\nimport { infoCommand } from \"./commands/info.js\";\nimport { relationshipCommands } from \"./commands/relationship.js\";\nimport { elementCommands } from \"./commands/element.js\";\nimport { schemaCommands } from \"./commands/schema.js\";\nimport { catalogCommands } from \"./commands/catalog.js\";\nimport { docsCommands } from \"./commands/docs.js\";\nimport { traceCommand } from \"./commands/trace.js\";\nimport { exportCommand } from \"./commands/export.js\";\nimport { importCommand } from \"./commands/import.js\";\nimport { chatCommand } from \"./commands/chat.js\";\nimport { upgradeCommand } from \"./commands/upgrade.js\";\nimport { conformanceCommand } from \"./commands/conformance.js\";\nimport { changesetCommands } from \"./commands/changeset.js\";\nimport { claudeCommands } from \"./commands/claude.js\";\nimport { copilotCommands } from \"./commands/copilot.js\";\nimport { analyzerCommands } from \"./commands/analyzer.js\";\nimport { versionCommand } from \"./commands/version.js\";\nimport { statsCommand } from \"./commands/stats.js\";\nimport { reportCommand } from \"./commands/report.js\";\nimport { reportsCommands } from \"./commands/reports.js\";\nimport { auditCommand } from \"./commands/audit.js\";\nimport { auditDiffCommand } from \"./commands/audit-diff.js\";\nimport { auditSnapshotsCommand } from \"./commands/audit-snapshots.js\";\nimport { initTelemetry, startActiveSpan, shutdownTelemetry } from \"./telemetry/index.js\";\nimport { installConsoleInterceptor } from \"./telemetry/console-interceptor.js\";\nimport { getErrorMessage } from \"./utils/errors.js\";\n\n// Declare TELEMETRY_ENABLED as a build-time constant (substituted by esbuild)\n// Provide runtime fallback when not running through esbuild\ndeclare const TELEMETRY_ENABLED: boolean;\nconst isTelemetryEnabled = typeof TELEMETRY_ENABLED !== \"undefined\" ? TELEMETRY_ENABLED : false;\n\n// Commands that require console interceptor for telemetry logging\nconst CONSOLE_LOGGING_COMMANDS = new Set(['chat', 'validate', 'import', 'export']);\n\n/**\n * Extract exit code from an error object.\n * Handles CLIError instances and duck-typed objects with exitCode property.\n */\nasync function extractExitCode(error: unknown): Promise<number> {\n const { CLIError } = await import(\"./utils/errors.js\");\n\n if (error instanceof CLIError) {\n return error.exitCode;\n }\n\n // Commander's own errors (--help, unknown commands, etc.) carry exitCode as\n // expected control flow \u2014 handle them directly without duck-typing.\n if (error instanceof CommanderError) {\n return error.exitCode;\n }\n\n // Fallback for duck-typing (handles bundling/module issues)\n if (error && typeof error === \"object\" && \"exitCode\" in error) {\n const errorObj = error as any;\n if (typeof errorObj.exitCode === \"number\") {\n // Validate this looks like a CLIError before accepting\n if (errorObj.name === \"CLIError\" || errorObj.message) {\n if (process.argv.includes(\"--debug\")) {\n console.warn(\n \"[DEBUG] Using duck-typed error object as fallback - this may indicate a module loading issue\"\n );\n }\n return errorObj.exitCode;\n }\n }\n }\n\n return 1;\n}\n\n// Declare build-time constant (substituted by esbuild)\ndeclare const CLI_VERSION: string;\nconst cliVersion = typeof CLI_VERSION !== \"undefined\" ? CLI_VERSION : \"0.1.3\";\n\nconst program = new Command();\n\n// Handle --version and -V flags by redirecting to version command\n// This ensures they go through the telemetry wrapper\nif (process.argv.includes(\"--version\") || process.argv.includes(\"-V\")) {\n process.argv = [\"node\", \"dr\", \"version\"];\n}\n\nprogram\n .name(\"dr\")\n .description(\"Documentation Robotics CLI - Architecture Model Management\")\n .option(\"-v, --verbose\", \"Enable verbose output\")\n .option(\"--debug\", \"Enable debug mode\")\n .exitOverride() // Prevent Commander from calling process.exit() - we handle exit ourselves\n .showSuggestionAfterError() // \"Did you mean X?\" on unknown commands/options\n .hook(\"preAction\", async (thisCommand) => {\n // Set up global state (verbose/debug flags)\n const options = thisCommand.opts();\n setGlobalOptions({\n verbose: options.verbose as boolean | undefined,\n debug: options.debug as boolean | undefined,\n });\n });\n\n// Model commands\nprogram\n .command(\"init [name]\")\n .description(\"Initialize a new architecture model\")\n .option(\"--name <name>\", \"Model name (overrides positional argument)\")\n .option(\"--author <author>\", \"Model author\")\n .option(\"--description <desc>\", \"Model description\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr init\n $ dr init claudetoreum\n $ dr init \"Enterprise Architecture\" --author \"Team A\"\n $ dr init --name \"My Project\" --description \"13-layer federated model\"`\n )\n .action((name, options) => initCommand({ ...options, name: options.name || name }));\n\nprogram\n .command(\"add <layer> <type> <name>\")\n .description(\"Add an element to a layer\")\n .option(\"--name <name>\", \"Element display name (defaults to the name argument)\")\n .option(\"--description <desc>\", \"Element description\")\n .option(\"--attributes <json>\", \"Element type-specific attributes as JSON object\")\n .option(\"--source-file <path>\", \"Source file path (relative from repository root)\")\n .option(\"--source-symbol <name>\", \"Symbol name (class, function, variable) in source file\")\n .option(\"--source-provenance <type>\", \"Provenance type: extracted, manual, inferred, generated\")\n .option(\"--source-repo-remote <url>\", \"Git remote URL for repository context\")\n .option(\"--source-repo-commit <sha>\", \"Git commit SHA (40 hex characters) for repository context\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr add business service \"Customer Management\"\n $ dr add api operation \"Create Customer\" --attributes '{\"operationId\":\"createCustomer\",\"summary\":\"Create a customer\",\"tags\":\"customers\"}'\n $ dr add application component \"Customer API\" --description \"REST API for customer operations\"\n $ dr add security policy \"Auth Validator\" --source-file \"src/auth/validator.ts\" --source-symbol \"validateToken\" --source-provenance \"extracted\"\n\nNote: Element IDs are generated automatically in format {layer}.{type}.{kebab-name}`\n )\n .action(addCommand);\n\nprogram\n .command(\"update <id>\")\n .description(\"Update an element\")\n .option(\"--name <name>\", \"New element name\")\n .option(\"--description <desc>\", \"New description\")\n .option(\"--type <new-type>\", \"Change element type (must be valid for the element's layer; incompatible attributes must be cleaned up manually)\")\n .option(\"--attributes <json>\", \"Updated type-specific attributes (JSON)\")\n .option(\"--source-file <path>\", \"Source file path (relative from repository root)\")\n .option(\"--source-symbol <name>\", \"Symbol name (class, function, variable) in source file\")\n .option(\"--source-provenance <type>\", \"Provenance type: extracted, manual, inferred, generated\")\n .option(\"--source-repo-remote <url>\", \"Git remote URL for repository context\")\n .option(\"--source-repo-commit <sha>\", \"Git commit SHA (40 hex characters) for repository context\")\n .option(\"--clear-source-reference\", \"Remove source reference from element\")\n .addHelpText(\n \"after\",\n `\nNote: Changes are written immediately to model files.\nTo track changes for review, activate a changeset first:\n $ dr changeset activate my-changeset\n\nExamples:\n $ dr update api-endpoint-create-customer --name \"Create Customer (v2)\"\n $ dr update business-service-order --description \"Updated description\"\n $ dr update application-applicationfunction-process-orders --type applicationservice\n $ dr update security-policy-auth --source-file \"src/auth/policy.ts\" --source-provenance \"extracted\"`\n )\n .action(updateCommand);\n\nprogram\n .command(\"delete <id>\")\n .description(\"Delete an element\")\n .option(\"--force\", \"Skip dependency checks (confirmation is also skipped in non-TTY environments)\")\n .option(\"--cascade\", \"Remove dependent elements automatically\")\n .option(\"--dry-run\", \"Show what would be removed without actually removing\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr delete api-endpoint-old-endpoint\n $ dr delete api-endpoint-old-endpoint --force\n $ dr delete api-endpoint-old-endpoint --cascade\n $ dr delete api-endpoint-old-endpoint --dry-run\n $ dr delete api-endpoint-old-endpoint --cascade --dry-run`\n )\n .action(deleteCommand);\n\nprogram\n .command(\"show <id>\")\n .description(\"Display element details\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr show api-endpoint-create-customer\n $ dr show business-service-order-mgmt`\n )\n .action((id, options) => showCommand(id, options));\n\nprogram\n .command(\"list [layer]\")\n .description(\"List elements in a layer (or all layers if omitted)\")\n .option(\"--type <type>\", \"Filter by element type\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr list\n $ dr list api\n $ dr list business --type businessservice\n $ dr list api --json\n $ dr list --json`\n )\n .action(listCommand);\n\nprogram\n .command(\"search <query>\")\n .description(\"Search for elements by name or ID\")\n .option(\"--layer <layer>\", \"Limit search to specific layer\")\n .option(\"--type <type>\", \"Filter by element type\")\n .option(\n \"--source-file <path>\",\n \"Find elements referencing a source file (takes precedence over pattern matching)\"\n )\n .option(\"--json\", \"Output as JSON\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr search customer\n $ dr search \"order processing\" --layer business\n $ dr search create-* --type endpoint\n $ dr search \"\" --source-file src/api/customer.ts`\n )\n .action(searchCommand);\n\nprogram\n .command(\"validate\")\n .description(\"Validate the architecture model\")\n .option(\"--layers <layers...>\", \"Specific layers to validate\")\n .option(\"--strict\", \"Treat warnings as errors\")\n .option(\"--verbose\", \"Show detailed validation output with relationship breakdown\")\n .option(\"--quiet\", \"Show minimal output\")\n .option(\"--output <path>\", \"Export validation report to file (JSON or Markdown)\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .option(\"--orphans\", \"Show only orphaned elements grouped by layer with relationship suggestions\")\n .option(\"--all\", \"Run all validations (default behavior)\")\n .option(\"--markdown\", \"Validate markdown structure\")\n .option(\"--schemas\", \"Validate JSON schemas\")\n .option(\"--schema\", \"Validate JSON schemas (alias for --schemas)\")\n .option(\"--relationships\", \"Validate relationships\")\n .option(\"--structure\", \"Validate documentation structure\")\n .option(\"--naming\", \"Validate naming conventions\")\n .option(\"--references\", \"Validate cross-layer references\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr validate\n $ dr validate --all --strict\n $ dr validate --verbose\n $ dr validate --quiet\n $ dr validate --output report.json\n $ dr validate --output report.md\n $ dr validate --schemas\n $ dr validate --relationships\n $ dr validate --layers business api\n $ dr validate --orphans\n $ dr validate --orphans --output orphans.json`\n )\n .action(validateCommand);\n\nprogram\n .command(\"export <format>\")\n .description(\"Export the architecture model to various formats\")\n .option(\"--output <path>\", \"Output file path (default: print to stdout)\")\n .option(\"--layers <layers...>\", \"Specific layers to export\")\n .option(\"--model <path>\", \"Path to model root directory or manifest.yaml file\")\n .option(\"--include-sources\", \"Include source file paths in PlantUML diagrams as notes\")\n .addHelpText(\n \"after\",\n `\nSupported formats:\n archimate Export to ArchiMate XML (layers 1, 2, 5, 6)\n openapi Export to OpenAPI 3.0 specification (layer 7)\n jsonschema Export to JSON Schema (layer 8)\n plantuml Export to PlantUML diagram\n graphml Export to GraphML (graph visualization)\n markdown Export to Markdown documentation\n\nExamples:\n $ dr export archimate --output model.xml\n $ dr export openapi --layers api\n $ dr export plantuml --include-sources --output diagram.puml\n $ dr export markdown --output docs/architecture.md`\n )\n .action(async (format, options) => {\n await exportCommand({\n format,\n output: options.output,\n layers: options.layers,\n model: options.model,\n includeSources: options.includeSources,\n });\n });\n\nprogram\n .command(\"import <format>\")\n .description(\"Import architecture model from various formats\")\n .option(\"--input <path>\", \"Input file path (required)\", undefined)\n .option(\"--model <path>\", \"Path to model root directory or manifest.yaml file\")\n .option(\n \"--merge-strategy <strategy>\",\n \"How to handle existing elements: add, update, skip (default: add)\"\n )\n .addHelpText(\n \"after\",\n `\nSupported formats:\n archimate Import from ArchiMate XML (layers 1, 2, 5, 6)\n openapi Import from OpenAPI 3.0 specification (layer 7)\n\nExamples:\n $ dr import archimate --input model.xml\n $ dr import openapi --input api.json --merge-strategy add\n $ dr import archimate --input model.xml --model ./myproject`\n )\n .action(async (format, options) => {\n if (!options.input) {\n console.error(\"Error: --input path is required\");\n process.exit(1);\n }\n await importCommand({\n format,\n input: options.input,\n model: options.model,\n mergeStrategy: options.mergeStrategy as \"add\" | \"update\" | \"skip\" | undefined,\n });\n });\n\nprogram\n .command(\"info\")\n .description(\"Show model information\")\n .option(\"--layer <layer>\", \"Show specific layer details\")\n .option(\"--verbose\", \"Show detailed breakdown by element type\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr info\n $ dr info --layer business\n $ dr info --layer api --verbose`\n )\n .action(infoCommand);\n\nprogram\n .command(\"stats\")\n .description(\"Display model statistics and health metrics\")\n .option(\"--model <path>\", \"Path to the model directory\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown, compact\")\n .option(\"--output <path>\", \"Output file path (auto-detects format from extension)\")\n .option(\"--compact\", \"Show compact one-line summary\")\n .option(\"--verbose\", \"Show detailed information\")\n .addHelpText(\n \"after\",\n `\nOutput formats:\n text Full formatted statistics (default)\n json JSON output for automation\n markdown Markdown report format\n compact Single-line summary\n\nExamples:\n $ dr stats # Show full statistics\n $ dr stats --compact # Show one-line summary\n $ dr stats --format json # Output as JSON\n $ dr stats --output stats.md # Save as markdown file\n $ dr stats --output stats.json # Save as JSON file\n $ dr stats --verbose # Show detailed information`\n )\n .action((options) => statsCommand(options));\n\nprogram\n .command(\"report\")\n .description(\"Generate comprehensive architecture reports\")\n .option(\"--model <path>\", \"Path to the model directory\")\n .option(\"--type <type>\", \"Report type: comprehensive (default), statistics, relationships, data-model, quality\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown\")\n .option(\"--output <path>\", \"Output file path (auto-detects format from extension)\")\n .option(\"--verbose\", \"Show detailed information\")\n .option(\"--include-data-model\", \"Include data model analysis (default: true)\")\n .option(\"--include-quality\", \"Include quality metrics (default: true)\")\n .addHelpText(\n \"after\",\n `\nReport types:\n comprehensive Full report with statistics, relationships, and data model (default)\n statistics Statistics and quality metrics\n relationships Relationship analysis and classification\n data-model Layer 8 data model analysis\n quality Quality metrics and recommendations\n\nOutput formats:\n text Full formatted report (default)\n json JSON output for automation\n markdown Markdown report format\n\nExamples:\n $ dr report # Show comprehensive report\n $ dr report --type relationships # Show relationship analysis\n $ dr report --format json # Output as JSON\n $ dr report --output report.md # Save as markdown file\n $ dr report --type data-model --output dm.md # Data model report as markdown\n $ dr report --verbose # Show detailed information`\n )\n .action((options) => reportCommand(options));\n\n// Reports subcommands (managed layer report files)\nconst reportsGroup = program.command(\"reports\").description(\"Manage architecture layer reports\");\nreportsCommands(reportsGroup);\n\n// Audit command - Relationship analysis\nprogram\n .command(\"audit [layer]\")\n .description(\"Analyze relationship coverage, gaps, duplicates, and balance\")\n .option(\"--type <type>\", \"Audit type: relationships (default), nodes, all\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown\")\n .option(\"--output <path>\", \"Output file path (auto-detects format from extension)\")\n .option(\"--verbose\", \"Show detailed analysis\")\n .option(\"--save-snapshot\", \"Save audit report as snapshot for differential analysis\")\n .addHelpText(\n \"after\",\n `\nAudit types:\n relationships Relationship coverage, gaps, duplicates, balance (default)\n nodes Node type usage distribution across model layers\n all Both relationship and node audits\n\nOutput formats:\n text Full formatted audit report (default)\n json JSON output for automation\n markdown Markdown audit report format\n\nExamples:\n $ dr audit # Full relationship audit of all layers\n $ dr audit security # Audit security layer only\n $ dr audit --type nodes # Node type distribution audit\n $ dr audit --type all # Combined relationship + node audit\n $ dr audit --format json # Output as JSON\n $ dr audit --output audit.md # Save as markdown file\n $ dr audit --verbose # Show detailed analysis\n $ dr audit --save-snapshot # Save snapshot for later comparison\n $ dr audit api --output api-audit.json # API layer audit as JSON`\n )\n .action((layer, options) =>\n auditCommand({ ...options, layer, verbose: options.verbose ?? program.opts().verbose }));\n\n// Audit diff command - Compare snapshots\nprogram\n .command(\"audit:diff\")\n .description(\"Compare before/after audit snapshots\")\n .option(\"--before <id>\", \"Before snapshot ID or timestamp\")\n .option(\"--after <id>\", \"After snapshot ID or timestamp\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown\")\n .option(\"--output <path>\", \"Output file path\")\n .option(\"--verbose\", \"Show detailed comparison\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr audit:diff # Compare latest two snapshots\n $ dr audit:diff --before 20260220-100000 --after 20260220-150000\n $ dr audit:diff --format markdown --output diff.md\n $ dr audit:diff --verbose # Show detailed changes`\n )\n .action((options) => auditDiffCommand(options));\n\n// Audit snapshots command - Manage snapshots\nprogram\n .command(\"audit:snapshots <action>\")\n .description(\"Manage audit snapshots (list, delete, clear)\")\n .option(\"--id <id>\", \"Snapshot ID (for delete action)\")\n .addHelpText(\n \"after\",\n `\nActions:\n list List all available snapshots\n delete Delete a specific snapshot (requires --id)\n clear Delete all snapshots\n\nExamples:\n $ dr audit:snapshots list\n $ dr audit:snapshots delete --id 20260220-100000\n $ dr audit:snapshots clear`\n )\n .action((action, options) => auditSnapshotsCommand({ ...options, action }));\n\n// Relationship subcommands\nconst relationshipGroup = program.command(\"relationship\").description(\"Relationship operations\");\nrelationshipCommands(relationshipGroup);\n\n// Element subcommands\nconst elementGroup = program.command(\"element\").description(\"Element operations\");\nelementCommands(elementGroup);\n\n// Schema introspection subcommands\nschemaCommands(program);\n\n// Catalog subcommands (modern relationship catalog)\ncatalogCommands(program);\n\n// Documentation subcommands (schema-driven generation)\ndocsCommands(program);\n\n// Dependency analysis commands\nprogram\n .command(\"trace <elementId>\")\n .description(\"Trace dependencies for an element\")\n .option(\n \"--direction <dir>\",\n \"Trace direction: up (dependencies), down (dependents), both (default)\"\n )\n .option(\"--depth <num>\", \"Maximum traversal depth\")\n .option(\"--metrics\", \"Show graph and element metrics\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr trace api-endpoint-create-customer\n $ dr trace business-service-order --direction down --metrics\n $ dr trace application-component-api --depth 3`\n )\n .action(async (elementId, options) => {\n await traceCommand(elementId, {\n direction: options.direction as \"up\" | \"down\" | \"both\" | undefined,\n depth: options.depth ? parseInt(options.depth) : undefined,\n showMetrics: options.metrics,\n model: options.model,\n });\n });\n\nprogram\n .command(\"visualize\")\n .description(\"Launch visualization server with WebSocket support\")\n .option(\"--port <num>\", \"Server port (default: 8080)\")\n .option(\"--no-browser\", \"Do not auto-open browser\")\n .option(\"--no-auth\", \"Disable authentication (enabled by default)\")\n .option(\"--token <token>\", \"Custom auth token (auto-generated by default)\")\n .option(\"--with-danger\", \"Enable dangerous mode for chat (skip permissions)\")\n .option(\n \"--viewer-path <path>\",\n \"Path to custom viewer build (e.g., ./dist/embedded/dr-viewer-bundle)\"\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr visualize\n $ dr visualize --port 3000\n $ dr visualize --no-browser\n $ dr visualize --no-auth\n $ dr visualize --token my-secret-token\n $ dr visualize --with-danger\n $ dr visualize --viewer-path ./dist/embedded/dr-viewer-bundle\n\nThe --with-danger flag enables dangerous mode for chat functionality:\n - Claude Code: --dangerously-skip-permissions\n - GitHub Copilot: --allow-all-tools\n\nThe --viewer-path option allows loading a local build of the web UI:\n - Point to a directory containing index.html and supporting files\n - Useful for developing custom viewers or using bundled distributions`\n )\n .action(async (options) => {\n const { visualizeCommand } = await import(\"./commands/visualize.js\");\n await visualizeCommand({\n port: options.port,\n noBrowser: options.browser === false, // Commander sets 'browser' to false when --no-browser is used\n noAuth: options.auth === false, // Commander sets 'auth' to false when --no-auth is used\n token: options.token,\n withDanger: options.withDanger,\n viewerPath: options.viewerPath,\n });\n });\n\n// AI Integration command\nprogram\n .command(\"chat [client] [withDanger]\")\n .description(\"Interactive chat with AI about the architecture model\")\n .addHelpText(\n \"after\",\n `\nArguments:\n client Optional AI client to use: \"claude-code\" or \"github-copilot\"\n withDanger Enable dangerous mode: \"with-danger\"\n\nExamples:\n $ dr chat # Auto-detect or use saved preference\n $ dr chat claude-code # Use Claude Code, save as preference\n $ dr chat github-copilot # Use GitHub Copilot, save as preference\n $ dr chat with-danger # Auto-detect with dangerous mode\n $ dr chat claude-code with-danger # Use Claude Code with dangerous mode\n $ dr chat github-copilot with-danger # Use GitHub Copilot with dangerous mode\n\nDangerous mode enables:\n - Claude Code: --dangerously-skip-permissions\n - GitHub Copilot: --allow-all-tools\n\nThis launches an interactive chat interface where you can ask AI questions\nabout your architecture model. Supports Claude Code CLI and GitHub Copilot CLI.\n\nInstall instructions:\n - Claude Code: https://claude.ai\n - GitHub Copilot: gh extension install github/gh-copilot`\n )\n .action(async (client?: string, withDangerArg?: string) => {\n // Parse arguments - handle both \"with-danger\" as first or second arg\n let selectedClient: string | undefined;\n let withDanger = false;\n\n if (client === \"with-danger\") {\n // Format: dr chat with-danger\n withDanger = true;\n selectedClient = undefined;\n } else if (withDangerArg === \"with-danger\") {\n // Format: dr chat <client> with-danger\n withDanger = true;\n selectedClient = client;\n } else {\n // Format: dr chat <client>\n selectedClient = client;\n }\n\n await chatCommand(selectedClient, withDanger);\n });\n\n// Advanced commands\nprogram\n .command(\"version\")\n .description(\"Show CLI and embedded spec version information\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr version`\n )\n .action(async () => {\n await versionCommand();\n });\n\nprogram\n .command(\"upgrade\")\n .description(\"Upgrade spec reference and migrate model to latest versions\")\n .option(\"-y, --yes\", \"Automatically upgrade without prompting\")\n .option(\"--dry-run\", \"Show what would be upgraded without making changes\")\n .option(\"--force\", \"Force all upgrades regardless of current versions; skips migration validation\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr upgrade # Scan, show plan, and prompt for upgrades\n $ dr upgrade --dry-run # Preview available upgrades\n $ dr upgrade --yes # Upgrade without prompting\n $ dr upgrade --force # Force all upgrades, ignoring version checks`\n )\n .action(async (options) => {\n await upgradeCommand({\n yes: options.yes,\n dryRun: options.dryRun,\n force: options.force,\n });\n });\n\nprogram\n .command(\"conformance\")\n .description(\"Check model conformance to layer specifications\")\n .option(\"--layers <layers...>\", \"Specific layers to check\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--verbose\", \"Verbose output\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr conformance\n $ dr conformance --layers business api application\n $ dr conformance --json\n $ dr conformance --verbose`\n )\n .action(async (options) => {\n await conformanceCommand({\n layers: options.layers,\n json: options.json,\n verbose: options.verbose ?? program.opts().verbose,\n });\n });\n\n// Changeset subcommands\nchangesetCommands(program);\n\n// Claude Code integration subcommands\nclaudeCommands(program);\n\n// GitHub Copilot integration subcommands\ncopilotCommands(program);\n\n// Analyzer integration subcommands\nanalyzerCommands(program);\n\n// Execute CLI with proper telemetry span wrapping\n// This creates a root span that all child spans will be linked to\n(async () => {\n let exitCode = 0;\n try {\n if (isTelemetryEnabled) {\n // Initialize telemetry before execution\n await initTelemetry();\n\n // Only install console interceptor for commands that need it\n const commandName = process.argv[2] || \"unknown\";\n if (CONSOLE_LOGGING_COMMANDS.has(commandName)) {\n await installConsoleInterceptor();\n }\n\n const args = process.argv.slice(3).join(\" \");\n\n // Wrap entire CLI execution in active span for proper context propagation\n await startActiveSpan(\n \"cli.execute\",\n async (span) => {\n // Attributes already set via options parameter - no duplicate setAttributes needed\n try {\n // Execute command - all child spans will now link to this root span\n await program.parseAsync(process.argv);\n\n // Set success status\n span.setStatus({ code: 0 }); // SpanStatusCode.OK\n } catch (error) {\n // Record exception and set error status\n // CommanderError with exitCode 0 is help text / unknown subcommand shown \u2014 not a real error\n if (error instanceof CommanderError) {\n if (error.exitCode === 0) {\n span.setStatus({ code: 0 }); // SpanStatusCode.OK\n } else {\n span.recordException(error as Error);\n span.setStatus({\n code: 2, // SpanStatusCode.ERROR\n message: error.message,\n });\n }\n } else {\n span.recordException(error as Error);\n span.setStatus({\n code: 2, // SpanStatusCode.ERROR\n message: getErrorMessage(error),\n });\n }\n\n // Print error message for CLIError instances\n // Skip CommanderError \u2014 Commander already printed its own output (e.g. help text, unknown command)\n const { CLIError } = await import(\"./utils/errors.js\");\n if (error instanceof CommanderError) {\n // Commander handled its own output; nothing to print\n } else if (error instanceof CLIError) {\n console.error(error.format());\n } else if (error instanceof Error) {\n console.error(error.message);\n } else {\n console.error(String(error));\n }\n\n // Extract exit code from CLIError if available\n exitCode = await extractExitCode(error);\n // Don't throw - let telemetry shutdown complete\n }\n },\n {\n \"cli.command\": commandName,\n \"cli.args\": args,\n \"cli.cwd\": process.cwd(),\n \"cli.version\": cliVersion,\n }\n );\n\n // Shutdown telemetry after execution completes\n await shutdownTelemetry();\n\n // Exit with exit code (keepAlive disabled in exporters prevents hanging)\n process.exit(exitCode);\n } else {\n // No telemetry - just parse normally with error handling\n try {\n await program.parseAsync(process.argv);\n } catch (error) {\n // Extract exit code from CLIError if available\n // Skip CommanderError \u2014 Commander already printed its own output (e.g. help text, unknown command)\n const { CLIError } = await import(\"./utils/errors.js\");\n if (error instanceof CommanderError) {\n // Commander handled its own output; nothing to print\n } else if (error instanceof CLIError) {\n console.error(error.format());\n } else {\n // Unexpected exceptions need to be printed\n if (error instanceof Error) {\n console.error(error.message);\n } else {\n console.error(String(error));\n }\n }\n const exitCodeFromError = await extractExitCode(error);\n process.exit(exitCodeFromError);\n }\n }\n } catch (error) {\n // Error during telemetry init or shutdown\n if (!isTelemetryEnabled) {\n // No telemetry - exit immediately with error\n process.exit(1);\n }\n // Telemetry enabled - try to shutdown before exit\n await shutdownTelemetry();\n process.exit(1);\n }\n})();\n"],
|
|
5
|
-
"mappings": ";AAUA,SAAS,SAAS,sBAAsB;AACxC,SAAS,wBAAwB;AACjC,SAAS,mBAAmB;AAC5B,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB;AAC5B,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;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Aa,2BAA2B,EAC/C,OAAO,wBAAwB,6CAA6C,EAC5E,OAAO,qBAAqB,yCAAyC,EACrE,YACC,SACA;;;;;;;;;;;;;;;;;;;+EAmB2E,EAE5E,OAAO,CAAC,YAAY,cAAc,OAAO,CAAC;AAG7C,MAAM,eAAe,QAAQ,QAAQ,SAAS,EAAE,YAAY,mCAAmC;AAC/F,gBAAgB,YAAY,GAG5B,QACG,QAAQ,eAAe,EACvB,YAAY,8DAA8D,EAC1E,OAAO,iBAAiB,iDAAiD,EACzE,OAAO,qBAAqB,+CAA+C,EAC3E,OAAO,mBAAmB,uDAAuD,EACjF,OAAO,aAAa,wBAAwB,EAC5C,OAAO,mBAAmB,yDAAyD,EACnF,YACC,SACA;;;;;;;;;;;;;;;;;;;;oEAoBgE,EAEjE,OAAO,CAAC,OAAO,YACd,aAAa,EAAE,GAAG,SAAS,OAAO,SAAS,QAAQ,WAAW,QAAQ,KAAI,EAAG,QAAO,CAAE,CAAC,GAG3F,QACG,QAAQ,YAAY,EACpB,YAAY,sCAAsC,EAClD,OAAO,iBAAiB,iCAAiC,EACzD,OAAO,gBAAgB,gCAAgC,EACvD,OAAO,qBAAqB,+CAA+C,EAC3E,OAAO,mBAAmB,kBAAkB,EAC5C,OAAO,aAAa,0BAA0B,EAC9C,YACC,SACA;;;;;2EAKuE,EAExE,OAAO,CAAC,YAAY,iBAAiB,OAAO,CAAC,GAGhD,QACG,QAAQ,0BAA0B,EAClC,YAAY,8CAA8C,EAC1D,OAAO,aAAa,iCAAiC,EACrD,YACC,SACA;;;;;;;;;6BASyB,EAE1B,OAAO,CAAC,QAAQ,YAAY,sBAAsB,EAAE,GAAG,SAAS,OAAM,CAAE,CAAC;
|
|
4
|
+
"sourcesContent": ["#!/usr/bin/env node\n\n/**\n * Documentation Robotics CLI - Bun Implementation\n * Entry point for the command-line interface\n *\n * Instrumented with OpenTelemetry to create root spans for command execution.\n * Telemetry is controlled by the TELEMETRY_ENABLED build-time constant.\n */\n\nimport { Command, CommanderError } from \"commander\";\nimport { setGlobalOptions } from \"./utils/globals.js\";\nimport { initCommand } from \"./commands/init.js\";\nimport { addCommand } from \"./commands/add.js\";\nimport { updateCommand } from \"./commands/update.js\";\nimport { deleteCommand } from \"./commands/delete.js\";\nimport { showCommand } from \"./commands/show.js\";\nimport { listCommand } from \"./commands/list.js\";\nimport { searchCommand } from \"./commands/search.js\";\nimport { validateCommand } from \"./commands/validate.js\";\nimport { infoCommand } from \"./commands/info.js\";\nimport { relationshipCommands } from \"./commands/relationship.js\";\nimport { elementCommands } from \"./commands/element.js\";\nimport { schemaCommands } from \"./commands/schema.js\";\nimport { catalogCommands } from \"./commands/catalog.js\";\nimport { docsCommands } from \"./commands/docs.js\";\nimport { traceCommand } from \"./commands/trace.js\";\nimport { exportCommand } from \"./commands/export.js\";\nimport { importCommand } from \"./commands/import.js\";\nimport { chatCommand } from \"./commands/chat.js\";\nimport { upgradeCommand } from \"./commands/upgrade.js\";\nimport { conformanceCommand } from \"./commands/conformance.js\";\nimport { changesetCommands } from \"./commands/changeset.js\";\nimport { claudeCommands } from \"./commands/claude.js\";\nimport { copilotCommands } from \"./commands/copilot.js\";\nimport { analyzerCommands } from \"./commands/analyzer.js\";\nimport { versionCommand } from \"./commands/version.js\";\nimport { statsCommand } from \"./commands/stats.js\";\nimport { reportCommand } from \"./commands/report.js\";\nimport { reportsCommands } from \"./commands/reports.js\";\nimport { auditCommand } from \"./commands/audit.js\";\nimport { auditDiffCommand } from \"./commands/audit-diff.js\";\nimport { auditSnapshotsCommand } from \"./commands/audit-snapshots.js\";\nimport { repairAttributeCollisionCommand } from \"./commands/repair.js\";\nimport { initTelemetry, startActiveSpan, shutdownTelemetry } from \"./telemetry/index.js\";\nimport { installConsoleInterceptor } from \"./telemetry/console-interceptor.js\";\nimport { getErrorMessage } from \"./utils/errors.js\";\n\n// Declare TELEMETRY_ENABLED as a build-time constant (substituted by esbuild)\n// Provide runtime fallback when not running through esbuild\ndeclare const TELEMETRY_ENABLED: boolean;\nconst isTelemetryEnabled = typeof TELEMETRY_ENABLED !== \"undefined\" ? TELEMETRY_ENABLED : false;\n\n// Commands that require console interceptor for telemetry logging\nconst CONSOLE_LOGGING_COMMANDS = new Set(['chat', 'validate', 'import', 'export']);\n\n/**\n * Extract exit code from an error object.\n * Handles CLIError instances and duck-typed objects with exitCode property.\n */\nasync function extractExitCode(error: unknown): Promise<number> {\n const { CLIError } = await import(\"./utils/errors.js\");\n\n if (error instanceof CLIError) {\n return error.exitCode;\n }\n\n // Commander's own errors (--help, unknown commands, etc.) carry exitCode as\n // expected control flow \u2014 handle them directly without duck-typing.\n if (error instanceof CommanderError) {\n return error.exitCode;\n }\n\n // Fallback for duck-typing (handles bundling/module issues)\n if (error && typeof error === \"object\" && \"exitCode\" in error) {\n const errorObj = error as any;\n if (typeof errorObj.exitCode === \"number\") {\n // Validate this looks like a CLIError before accepting\n if (errorObj.name === \"CLIError\" || errorObj.message) {\n if (process.argv.includes(\"--debug\")) {\n console.warn(\n \"[DEBUG] Using duck-typed error object as fallback - this may indicate a module loading issue\"\n );\n }\n return errorObj.exitCode;\n }\n }\n }\n\n return 1;\n}\n\n// Declare build-time constant (substituted by esbuild)\ndeclare const CLI_VERSION: string;\nconst cliVersion = typeof CLI_VERSION !== \"undefined\" ? CLI_VERSION : \"0.1.3\";\n\nconst program = new Command();\n\n// Handle --version and -V flags by redirecting to version command\n// This ensures they go through the telemetry wrapper\nif (process.argv.includes(\"--version\") || process.argv.includes(\"-V\")) {\n process.argv = [\"node\", \"dr\", \"version\"];\n}\n\nprogram\n .name(\"dr\")\n .description(\"Documentation Robotics CLI - Architecture Model Management\")\n .option(\"-v, --verbose\", \"Enable verbose output\")\n .option(\"--debug\", \"Enable debug mode\")\n .exitOverride() // Prevent Commander from calling process.exit() - we handle exit ourselves\n .showSuggestionAfterError() // \"Did you mean X?\" on unknown commands/options\n .hook(\"preAction\", async (thisCommand) => {\n // Set up global state (verbose/debug flags)\n const options = thisCommand.opts();\n setGlobalOptions({\n verbose: options.verbose as boolean | undefined,\n debug: options.debug as boolean | undefined,\n });\n });\n\n// Model commands\nprogram\n .command(\"init [name]\")\n .description(\"Initialize a new architecture model\")\n .option(\"--name <name>\", \"Model name (overrides positional argument)\")\n .option(\"--author <author>\", \"Model author\")\n .option(\"--description <desc>\", \"Model description\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr init\n $ dr init claudetoreum\n $ dr init \"Enterprise Architecture\" --author \"Team A\"\n $ dr init --name \"My Project\" --description \"13-layer federated model\"`\n )\n .action((name, options) => initCommand({ ...options, name: options.name || name }));\n\nprogram\n .command(\"add <layer> <type> <name>\")\n .description(\"Add an element to a layer\")\n .option(\"--name <name>\", \"Element display name (defaults to the name argument)\")\n .option(\"--description <desc>\", \"Element description\")\n .option(\"--attributes <json>\", \"Element type-specific attributes as JSON object\")\n .option(\"--source-file <path>\", \"Source file path (relative from repository root)\")\n .option(\"--source-symbol <name>\", \"Symbol name (class, function, variable) in source file\")\n .option(\"--source-provenance <type>\", \"Provenance type: extracted, manual, inferred, generated\")\n .option(\"--source-repo-remote <url>\", \"Git remote URL for repository context\")\n .option(\"--source-repo-commit <sha>\", \"Git commit SHA (40 hex characters) for repository context\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr add business service \"Customer Management\"\n $ dr add api operation \"Create Customer\" --attributes '{\"operationId\":\"createCustomer\",\"summary\":\"Create a customer\",\"tags\":\"customers\"}'\n $ dr add application component \"Customer API\" --description \"REST API for customer operations\"\n $ dr add security policy \"Auth Validator\" --source-file \"src/auth/validator.ts\" --source-symbol \"validateToken\" --source-provenance \"extracted\"\n\nNote: Element IDs are generated automatically in format {layer}.{type}.{kebab-name}`\n )\n .action(addCommand);\n\nprogram\n .command(\"update <id>\")\n .description(\"Update an element\")\n .option(\"--name <name>\", \"New element name\")\n .option(\"--description <desc>\", \"New description\")\n .option(\"--type <new-type>\", \"Change element type (must be valid for the element's layer; incompatible attributes must be cleaned up manually)\")\n .option(\"--attributes <json>\", \"Updated type-specific attributes (JSON)\")\n .option(\"--source-file <path>\", \"Source file path (relative from repository root)\")\n .option(\"--source-symbol <name>\", \"Symbol name (class, function, variable) in source file\")\n .option(\"--source-provenance <type>\", \"Provenance type: extracted, manual, inferred, generated\")\n .option(\"--source-repo-remote <url>\", \"Git remote URL for repository context\")\n .option(\"--source-repo-commit <sha>\", \"Git commit SHA (40 hex characters) for repository context\")\n .option(\"--clear-source-reference\", \"Remove source reference from element\")\n .addHelpText(\n \"after\",\n `\nNote: Changes are written immediately to model files.\nTo track changes for review, activate a changeset first:\n $ dr changeset activate my-changeset\n\nExamples:\n $ dr update api-endpoint-create-customer --name \"Create Customer (v2)\"\n $ dr update business-service-order --description \"Updated description\"\n $ dr update application-applicationfunction-process-orders --type applicationservice\n $ dr update security-policy-auth --source-file \"src/auth/policy.ts\" --source-provenance \"extracted\"`\n )\n .action(updateCommand);\n\nprogram\n .command(\"delete <id>\")\n .description(\"Delete an element\")\n .option(\"--force\", \"Skip dependency checks (confirmation is also skipped in non-TTY environments)\")\n .option(\"--cascade\", \"Remove dependent elements automatically\")\n .option(\"--dry-run\", \"Show what would be removed without actually removing\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr delete api-endpoint-old-endpoint\n $ dr delete api-endpoint-old-endpoint --force\n $ dr delete api-endpoint-old-endpoint --cascade\n $ dr delete api-endpoint-old-endpoint --dry-run\n $ dr delete api-endpoint-old-endpoint --cascade --dry-run`\n )\n .action(deleteCommand);\n\nprogram\n .command(\"show <id>\")\n .description(\"Display element details\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr show api-endpoint-create-customer\n $ dr show business-service-order-mgmt`\n )\n .action((id, options) => showCommand(id, options));\n\nprogram\n .command(\"list [layer]\")\n .description(\"List elements in a layer (or all layers if omitted)\")\n .option(\"--type <type>\", \"Filter by element type\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr list\n $ dr list api\n $ dr list business --type businessservice\n $ dr list api --json\n $ dr list --json`\n )\n .action(listCommand);\n\nprogram\n .command(\"search <query>\")\n .description(\"Search for elements by name or ID\")\n .option(\"--layer <layer>\", \"Limit search to specific layer\")\n .option(\"--type <type>\", \"Filter by element type\")\n .option(\n \"--source-file <path>\",\n \"Find elements referencing a source file (takes precedence over pattern matching)\"\n )\n .option(\"--json\", \"Output as JSON\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr search customer\n $ dr search \"order processing\" --layer business\n $ dr search create-* --type endpoint\n $ dr search \"\" --source-file src/api/customer.ts`\n )\n .action(searchCommand);\n\nprogram\n .command(\"validate\")\n .description(\"Validate the architecture model\")\n .option(\"--layers <layers...>\", \"Specific layers to validate\")\n .option(\"--strict\", \"Treat warnings as errors\")\n .option(\"--verbose\", \"Show detailed validation output with relationship breakdown\")\n .option(\"--quiet\", \"Show minimal output\")\n .option(\"--output <path>\", \"Export validation report to file (JSON or Markdown)\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .option(\"--orphans\", \"Show only orphaned elements grouped by layer with relationship suggestions\")\n .option(\"--all\", \"Run all validations (default behavior)\")\n .option(\"--markdown\", \"Validate markdown structure\")\n .option(\"--schemas\", \"Validate JSON schemas\")\n .option(\"--schema\", \"Validate JSON schemas (alias for --schemas)\")\n .option(\"--relationships\", \"Validate relationships\")\n .option(\"--structure\", \"Validate documentation structure\")\n .option(\"--naming\", \"Validate naming conventions\")\n .option(\"--references\", \"Validate cross-layer references\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr validate\n $ dr validate --all --strict\n $ dr validate --verbose\n $ dr validate --quiet\n $ dr validate --output report.json\n $ dr validate --output report.md\n $ dr validate --schemas\n $ dr validate --relationships\n $ dr validate --layers business api\n $ dr validate --orphans\n $ dr validate --orphans --output orphans.json`\n )\n .action(validateCommand);\n\nprogram\n .command(\"export <format>\")\n .description(\"Export the architecture model to various formats\")\n .option(\"--output <path>\", \"Output file path (default: print to stdout)\")\n .option(\"--layers <layers...>\", \"Specific layers to export\")\n .option(\"--model <path>\", \"Path to model root directory or manifest.yaml file\")\n .option(\"--include-sources\", \"Include source file paths in PlantUML diagrams as notes\")\n .addHelpText(\n \"after\",\n `\nSupported formats:\n archimate Export to ArchiMate XML (layers 1, 2, 5, 6)\n openapi Export to OpenAPI 3.0 specification (layer 7)\n jsonschema Export to JSON Schema (layer 8)\n plantuml Export to PlantUML diagram\n graphml Export to GraphML (graph visualization)\n markdown Export to Markdown documentation\n\nExamples:\n $ dr export archimate --output model.xml\n $ dr export openapi --layers api\n $ dr export plantuml --include-sources --output diagram.puml\n $ dr export markdown --output docs/architecture.md`\n )\n .action(async (format, options) => {\n await exportCommand({\n format,\n output: options.output,\n layers: options.layers,\n model: options.model,\n includeSources: options.includeSources,\n });\n });\n\nprogram\n .command(\"import <format>\")\n .description(\"Import architecture model from various formats\")\n .option(\"--input <path>\", \"Input file path (required)\", undefined)\n .option(\"--model <path>\", \"Path to model root directory or manifest.yaml file\")\n .option(\n \"--merge-strategy <strategy>\",\n \"How to handle existing elements: add, update, skip (default: add)\"\n )\n .addHelpText(\n \"after\",\n `\nSupported formats:\n archimate Import from ArchiMate XML (layers 1, 2, 5, 6)\n openapi Import from OpenAPI 3.0 specification (layer 7)\n\nExamples:\n $ dr import archimate --input model.xml\n $ dr import openapi --input api.json --merge-strategy add\n $ dr import archimate --input model.xml --model ./myproject`\n )\n .action(async (format, options) => {\n if (!options.input) {\n console.error(\"Error: --input path is required\");\n process.exit(1);\n }\n await importCommand({\n format,\n input: options.input,\n model: options.model,\n mergeStrategy: options.mergeStrategy as \"add\" | \"update\" | \"skip\" | undefined,\n });\n });\n\nprogram\n .command(\"info\")\n .description(\"Show model information\")\n .option(\"--layer <layer>\", \"Show specific layer details\")\n .option(\"--verbose\", \"Show detailed breakdown by element type\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr info\n $ dr info --layer business\n $ dr info --layer api --verbose`\n )\n .action(infoCommand);\n\nprogram\n .command(\"stats\")\n .description(\"Display model statistics and health metrics\")\n .option(\"--model <path>\", \"Path to the model directory\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown, compact\")\n .option(\"--output <path>\", \"Output file path (auto-detects format from extension)\")\n .option(\"--compact\", \"Show compact one-line summary\")\n .option(\"--verbose\", \"Show detailed information\")\n .addHelpText(\n \"after\",\n `\nOutput formats:\n text Full formatted statistics (default)\n json JSON output for automation\n markdown Markdown report format\n compact Single-line summary\n\nExamples:\n $ dr stats # Show full statistics\n $ dr stats --compact # Show one-line summary\n $ dr stats --format json # Output as JSON\n $ dr stats --output stats.md # Save as markdown file\n $ dr stats --output stats.json # Save as JSON file\n $ dr stats --verbose # Show detailed information`\n )\n .action((options) => statsCommand(options));\n\nprogram\n .command(\"report\")\n .description(\"Generate comprehensive architecture reports\")\n .option(\"--model <path>\", \"Path to the model directory\")\n .option(\"--type <type>\", \"Report type: comprehensive (default), statistics, relationships, data-model, quality\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown\")\n .option(\"--output <path>\", \"Output file path (auto-detects format from extension)\")\n .option(\"--verbose\", \"Show detailed information\")\n .option(\"--include-data-model\", \"Include data model analysis (default: true)\")\n .option(\"--include-quality\", \"Include quality metrics (default: true)\")\n .addHelpText(\n \"after\",\n `\nReport types:\n comprehensive Full report with statistics, relationships, and data model (default)\n statistics Statistics and quality metrics\n relationships Relationship analysis and classification\n data-model Layer 8 data model analysis\n quality Quality metrics and recommendations\n\nOutput formats:\n text Full formatted report (default)\n json JSON output for automation\n markdown Markdown report format\n\nExamples:\n $ dr report # Show comprehensive report\n $ dr report --type relationships # Show relationship analysis\n $ dr report --format json # Output as JSON\n $ dr report --output report.md # Save as markdown file\n $ dr report --type data-model --output dm.md # Data model report as markdown\n $ dr report --verbose # Show detailed information`\n )\n .action((options) => reportCommand(options));\n\n// Reports subcommands (managed layer report files)\nconst reportsGroup = program.command(\"reports\").description(\"Manage architecture layer reports\");\nreportsCommands(reportsGroup);\n\n// Audit command - Relationship analysis\nprogram\n .command(\"audit [layer]\")\n .description(\"Analyze relationship coverage, gaps, duplicates, and balance\")\n .option(\"--type <type>\", \"Audit type: relationships (default), nodes, all\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown\")\n .option(\"--output <path>\", \"Output file path (auto-detects format from extension)\")\n .option(\"--verbose\", \"Show detailed analysis\")\n .option(\"--save-snapshot\", \"Save audit report as snapshot for differential analysis\")\n .addHelpText(\n \"after\",\n `\nAudit types:\n relationships Relationship coverage, gaps, duplicates, balance (default)\n nodes Node type usage distribution across model layers\n all Both relationship and node audits\n\nOutput formats:\n text Full formatted audit report (default)\n json JSON output for automation\n markdown Markdown audit report format\n\nExamples:\n $ dr audit # Full relationship audit of all layers\n $ dr audit security # Audit security layer only\n $ dr audit --type nodes # Node type distribution audit\n $ dr audit --type all # Combined relationship + node audit\n $ dr audit --format json # Output as JSON\n $ dr audit --output audit.md # Save as markdown file\n $ dr audit --verbose # Show detailed analysis\n $ dr audit --save-snapshot # Save snapshot for later comparison\n $ dr audit api --output api-audit.json # API layer audit as JSON`\n )\n .action((layer, options) =>\n auditCommand({ ...options, layer, verbose: options.verbose ?? program.opts().verbose }));\n\n// Audit diff command - Compare snapshots\nprogram\n .command(\"audit:diff\")\n .description(\"Compare before/after audit snapshots\")\n .option(\"--before <id>\", \"Before snapshot ID or timestamp\")\n .option(\"--after <id>\", \"After snapshot ID or timestamp\")\n .option(\"--format <format>\", \"Output format: text (default), json, markdown\")\n .option(\"--output <path>\", \"Output file path\")\n .option(\"--verbose\", \"Show detailed comparison\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr audit:diff # Compare latest two snapshots\n $ dr audit:diff --before 20260220-100000 --after 20260220-150000\n $ dr audit:diff --format markdown --output diff.md\n $ dr audit:diff --verbose # Show detailed changes`\n )\n .action((options) => auditDiffCommand(options));\n\n// Audit snapshots command - Manage snapshots\nprogram\n .command(\"audit:snapshots <action>\")\n .description(\"Manage audit snapshots (list, delete, clear)\")\n .option(\"--id <id>\", \"Snapshot ID (for delete action)\")\n .addHelpText(\n \"after\",\n `\nActions:\n list List all available snapshots\n delete Delete a specific snapshot (requires --id)\n clear Delete all snapshots\n\nExamples:\n $ dr audit:snapshots list\n $ dr audit:snapshots delete --id 20260220-100000\n $ dr audit:snapshots clear`\n )\n .action((action, options) => auditSnapshotsCommand({ ...options, action }));\n\n// Repair command - Detect and recover data lost to fixed data-integrity bugs\nprogram\n .command(\"repair:attribute-collision\")\n .description(\n 'Find and best-effort-recover model data lost to a fixed bug where saveLayer() stripped \"source\"/\"x-source-reference\" attributes from every element, even when a node type\\'s schema declared one as a real (sometimes required) attribute'\n )\n .option(\"--apply\", \"Restore recoverable values found in changeset history (default: report only)\")\n .option(\"--format <format>\", \"Output format: text (default), json\")\n .option(\"--output <path>\", \"Write the report to a file instead of stdout\")\n .addHelpText(\n \"after\",\n `\nThis repairs damage from a fixed bug in Model.saveLayer(): a hardcoded, type-blind \"internal\nfields\" blocklist unconditionally stripped any attribute literally named \"source\" or\n\"x-source-reference\" from every element's attributes before writing YAML, regardless of whether\nthe element's own schema declared it as a real domain attribute. 41 of 191 node schemas across 8\nlayers do (3 mark it required, meaning affected elements fail validation today).\n\nRecovery is best-effort: values can only be restored if they still exist in changeset history\n(committing a changeset does not delete it). Elements with no recoverable value are always\nreported, never fabricated \u2014 you'll need to re-supply those manually with\n\"dr update <id> --attributes '{...}'\".\n\nExamples:\n $ dr repair:attribute-collision # Report only \u2014 no changes made\n $ dr repair:attribute-collision --apply # Restore every recoverable value\n $ dr repair:attribute-collision --format json --output report.json`\n )\n .action((options) => repairAttributeCollisionCommand(options));\n\n// Relationship subcommands\nconst relationshipGroup = program.command(\"relationship\").description(\"Relationship operations\");\nrelationshipCommands(relationshipGroup);\n\n// Element subcommands\nconst elementGroup = program.command(\"element\").description(\"Element operations\");\nelementCommands(elementGroup);\n\n// Schema introspection subcommands\nschemaCommands(program);\n\n// Catalog subcommands (modern relationship catalog)\ncatalogCommands(program);\n\n// Documentation subcommands (schema-driven generation)\ndocsCommands(program);\n\n// Dependency analysis commands\nprogram\n .command(\"trace <elementId>\")\n .description(\"Trace dependencies for an element\")\n .option(\n \"--direction <dir>\",\n \"Trace direction: up (dependencies), down (dependents), both (default)\"\n )\n .option(\"--depth <num>\", \"Maximum traversal depth\")\n .option(\"--metrics\", \"Show graph and element metrics\")\n .option(\"--model <path>\", \"Path to model root (contains model/manifest.yaml)\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr trace api-endpoint-create-customer\n $ dr trace business-service-order --direction down --metrics\n $ dr trace application-component-api --depth 3`\n )\n .action(async (elementId, options) => {\n await traceCommand(elementId, {\n direction: options.direction as \"up\" | \"down\" | \"both\" | undefined,\n depth: options.depth ? parseInt(options.depth) : undefined,\n showMetrics: options.metrics,\n model: options.model,\n });\n });\n\nprogram\n .command(\"visualize\")\n .description(\"Launch visualization server with WebSocket support\")\n .option(\"--port <num>\", \"Server port (default: 8080)\")\n .option(\"--no-browser\", \"Do not auto-open browser\")\n .option(\"--no-auth\", \"Disable authentication (enabled by default)\")\n .option(\"--token <token>\", \"Custom auth token (auto-generated by default)\")\n .option(\"--with-danger\", \"Enable dangerous mode for chat (skip permissions)\")\n .option(\n \"--viewer-path <path>\",\n \"Path to custom viewer build (e.g., ./dist/embedded/dr-viewer-bundle)\"\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr visualize\n $ dr visualize --port 3000\n $ dr visualize --no-browser\n $ dr visualize --no-auth\n $ dr visualize --token my-secret-token\n $ dr visualize --with-danger\n $ dr visualize --viewer-path ./dist/embedded/dr-viewer-bundle\n\nThe --with-danger flag enables dangerous mode for chat functionality:\n - Claude Code: --dangerously-skip-permissions\n - GitHub Copilot: --allow-all-tools\n\nThe --viewer-path option allows loading a local build of the web UI:\n - Point to a directory containing index.html and supporting files\n - Useful for developing custom viewers or using bundled distributions`\n )\n .action(async (options) => {\n const { visualizeCommand } = await import(\"./commands/visualize.js\");\n await visualizeCommand({\n port: options.port,\n noBrowser: options.browser === false, // Commander sets 'browser' to false when --no-browser is used\n noAuth: options.auth === false, // Commander sets 'auth' to false when --no-auth is used\n token: options.token,\n withDanger: options.withDanger,\n viewerPath: options.viewerPath,\n });\n });\n\n// AI Integration command\nprogram\n .command(\"chat [client] [withDanger]\")\n .description(\"Interactive chat with AI about the architecture model\")\n .addHelpText(\n \"after\",\n `\nArguments:\n client Optional AI client to use: \"claude-code\" or \"github-copilot\"\n withDanger Enable dangerous mode: \"with-danger\"\n\nExamples:\n $ dr chat # Auto-detect or use saved preference\n $ dr chat claude-code # Use Claude Code, save as preference\n $ dr chat github-copilot # Use GitHub Copilot, save as preference\n $ dr chat with-danger # Auto-detect with dangerous mode\n $ dr chat claude-code with-danger # Use Claude Code with dangerous mode\n $ dr chat github-copilot with-danger # Use GitHub Copilot with dangerous mode\n\nDangerous mode enables:\n - Claude Code: --dangerously-skip-permissions\n - GitHub Copilot: --allow-all-tools\n\nThis launches an interactive chat interface where you can ask AI questions\nabout your architecture model. Supports Claude Code CLI and GitHub Copilot CLI.\n\nInstall instructions:\n - Claude Code: https://claude.ai\n - GitHub Copilot: gh extension install github/gh-copilot`\n )\n .action(async (client?: string, withDangerArg?: string) => {\n // Parse arguments - handle both \"with-danger\" as first or second arg\n let selectedClient: string | undefined;\n let withDanger = false;\n\n if (client === \"with-danger\") {\n // Format: dr chat with-danger\n withDanger = true;\n selectedClient = undefined;\n } else if (withDangerArg === \"with-danger\") {\n // Format: dr chat <client> with-danger\n withDanger = true;\n selectedClient = client;\n } else {\n // Format: dr chat <client>\n selectedClient = client;\n }\n\n await chatCommand(selectedClient, withDanger);\n });\n\n// Advanced commands\nprogram\n .command(\"version\")\n .description(\"Show CLI and embedded spec version information\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr version`\n )\n .action(async () => {\n await versionCommand();\n });\n\nprogram\n .command(\"upgrade\")\n .description(\"Upgrade spec reference and migrate model to latest versions\")\n .option(\"-y, --yes\", \"Automatically upgrade without prompting\")\n .option(\"--dry-run\", \"Show what would be upgraded without making changes\")\n .option(\"--force\", \"Force all upgrades regardless of current versions; skips migration validation\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr upgrade # Scan, show plan, and prompt for upgrades\n $ dr upgrade --dry-run # Preview available upgrades\n $ dr upgrade --yes # Upgrade without prompting\n $ dr upgrade --force # Force all upgrades, ignoring version checks`\n )\n .action(async (options) => {\n await upgradeCommand({\n yes: options.yes,\n dryRun: options.dryRun,\n force: options.force,\n });\n });\n\nprogram\n .command(\"conformance\")\n .description(\"Check model conformance to layer specifications\")\n .option(\"--layers <layers...>\", \"Specific layers to check\")\n .option(\"--json\", \"Output as JSON\")\n .option(\"--verbose\", \"Verbose output\")\n .addHelpText(\n \"after\",\n `\nExamples:\n $ dr conformance\n $ dr conformance --layers business api application\n $ dr conformance --json\n $ dr conformance --verbose`\n )\n .action(async (options) => {\n await conformanceCommand({\n layers: options.layers,\n json: options.json,\n verbose: options.verbose ?? program.opts().verbose,\n });\n });\n\n// Changeset subcommands\nchangesetCommands(program);\n\n// Claude Code integration subcommands\nclaudeCommands(program);\n\n// GitHub Copilot integration subcommands\ncopilotCommands(program);\n\n// Analyzer integration subcommands\nanalyzerCommands(program);\n\n// Execute CLI with proper telemetry span wrapping\n// This creates a root span that all child spans will be linked to\n(async () => {\n let exitCode = 0;\n try {\n if (isTelemetryEnabled) {\n // Initialize telemetry before execution\n await initTelemetry();\n\n // Only install console interceptor for commands that need it\n const commandName = process.argv[2] || \"unknown\";\n if (CONSOLE_LOGGING_COMMANDS.has(commandName)) {\n await installConsoleInterceptor();\n }\n\n const args = process.argv.slice(3).join(\" \");\n\n // Wrap entire CLI execution in active span for proper context propagation\n await startActiveSpan(\n \"cli.execute\",\n async (span) => {\n // Attributes already set via options parameter - no duplicate setAttributes needed\n try {\n // Execute command - all child spans will now link to this root span\n await program.parseAsync(process.argv);\n\n // Set success status\n span.setStatus({ code: 0 }); // SpanStatusCode.OK\n } catch (error) {\n // Record exception and set error status\n // CommanderError with exitCode 0 is help text / unknown subcommand shown \u2014 not a real error\n if (error instanceof CommanderError) {\n if (error.exitCode === 0) {\n span.setStatus({ code: 0 }); // SpanStatusCode.OK\n } else {\n span.recordException(error as Error);\n span.setStatus({\n code: 2, // SpanStatusCode.ERROR\n message: error.message,\n });\n }\n } else {\n span.recordException(error as Error);\n span.setStatus({\n code: 2, // SpanStatusCode.ERROR\n message: getErrorMessage(error),\n });\n }\n\n // Print error message for CLIError instances\n // Skip CommanderError \u2014 Commander already printed its own output (e.g. help text, unknown command)\n const { CLIError } = await import(\"./utils/errors.js\");\n if (error instanceof CommanderError) {\n // Commander handled its own output; nothing to print\n } else if (error instanceof CLIError) {\n console.error(error.format());\n } else if (error instanceof Error) {\n console.error(error.message);\n } else {\n console.error(String(error));\n }\n\n // Extract exit code from CLIError if available\n exitCode = await extractExitCode(error);\n // Don't throw - let telemetry shutdown complete\n }\n },\n {\n \"cli.command\": commandName,\n \"cli.args\": args,\n \"cli.cwd\": process.cwd(),\n \"cli.version\": cliVersion,\n }\n );\n\n // Shutdown telemetry after execution completes\n await shutdownTelemetry();\n\n // Exit with exit code (keepAlive disabled in exporters prevents hanging)\n process.exit(exitCode);\n } else {\n // No telemetry - just parse normally with error handling\n try {\n await program.parseAsync(process.argv);\n } catch (error) {\n // Extract exit code from CLIError if available\n // Skip CommanderError \u2014 Commander already printed its own output (e.g. help text, unknown command)\n const { CLIError } = await import(\"./utils/errors.js\");\n if (error instanceof CommanderError) {\n // Commander handled its own output; nothing to print\n } else if (error instanceof CLIError) {\n console.error(error.format());\n } else {\n // Unexpected exceptions need to be printed\n if (error instanceof Error) {\n console.error(error.message);\n } else {\n console.error(String(error));\n }\n }\n const exitCodeFromError = await extractExitCode(error);\n process.exit(exitCodeFromError);\n }\n }\n } catch (error) {\n // Error during telemetry init or shutdown\n if (!isTelemetryEnabled) {\n // No telemetry - exit immediately with error\n process.exit(1);\n }\n // Telemetry enabled - try to shutdown before exit\n await shutdownTelemetry();\n process.exit(1);\n }\n})();\n"],
|
|
5
|
+
"mappings": ";AAUA,SAAS,SAAS,sBAAsB;AACxC,SAAS,wBAAwB;AACjC,SAAS,mBAAmB;AAC5B,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB;AAC5B,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;AACrC,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB;AAC5B,SAAS,sBAAsB;AAC/B,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAClC,SAAS,sBAAsB;AAC/B,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AACjC,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AACtC,SAAS,uCAAuC;AAChD,SAAS,eAAe,iBAAiB,yBAAyB;AAClE,SAAS,iCAAiC;AAC1C,SAAS,uBAAuB;AAKhC,MAAM,qBAAgE,IAGhE,2BAA2B,oBAAI,IAAI,CAAC,QAAQ,YAAY,UAAU,QAAQ,CAAC;AAMjF,eAAe,gBAAgB,OAAc;AAC3C,QAAM,EAAE,SAAQ,IAAK,MAAM,OAAO,mBAAmB;AAQrD,MANI,iBAAiB,YAMjB,iBAAiB;AACnB,WAAO,MAAM;AAIf,MAAI,SAAS,OAAO,SAAU,YAAY,cAAc,OAAO;AAC7D,UAAM,WAAW;AACjB,QAAI,OA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AO;AAGd,cAAM,EAAE,SAAQ,IAAK,MAAM,OAAO,mBAAmB;AACrD,QAAI,iBAAiB,mBAEV,iBAAiB,WAC1B,QAAQ,MAAM,MAAM,OAAM,CAAE,IAGxB,iBAAiB,QACnB,QAAQ,MAAM,MAAM,OAAO,IAE3B,QAAQ,MAAM,OAAO,KAAK,CAAC;AAG/B,cAAM,oBAAoB,MAAM,gBAAgB,KAAK;AACrD,gBAAQ,KAAK,iBAAiB;MAChC;EAEJ,QAAgB;AAEd,IAAK,sBAEH,QAAQ,KAAK,CAAC,GAGhB,MAAM,kBAAiB,GACvB,QAAQ,KAAK,CAAC;EAChB;AACF,GAAE;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import ansis from "ansis";
|
|
2
|
+
import { Model } from "../core/model.js";
|
|
3
|
+
import { StagedChangesetStorage } from "../core/staged-changeset-storage.js";
|
|
4
|
+
import { scanForAttributeCollisionDamage, attemptRecovery, applyRecovery } from "../core/attribute-collision-repair.js";
|
|
5
|
+
import { ModelNotFoundError, getErrorMessage, handleError } from "../utils/errors.js";
|
|
6
|
+
import { writeFile } from "../utils/file-io.js";
|
|
7
|
+
function printCandidate(c, applied) {
|
|
8
|
+
let note;
|
|
9
|
+
c.recovered ? note = applied ? ansis.green(`restored from changeset "${c.recovered.changesetName}"`) : ansis.green(`recoverable from changeset "${c.recovered.changesetName}"`) : note = ansis.dim("no recoverable value found \u2014 must be re-supplied manually"), console.log(` ${ansis.bold(c.elementRef)} ${ansis.dim(`(${c.specNodeId}.${c.attribute})`)} \u2014 ${note}`);
|
|
10
|
+
}
|
|
11
|
+
async function repairAttributeCollisionCommand(options = {}) {
|
|
12
|
+
try {
|
|
13
|
+
let model;
|
|
14
|
+
try {
|
|
15
|
+
model = await Model.load();
|
|
16
|
+
} catch (error) {
|
|
17
|
+
const message = getErrorMessage(error);
|
|
18
|
+
throw message.includes("No DR project") || message.includes("Model not found") ? new ModelNotFoundError() : error;
|
|
19
|
+
}
|
|
20
|
+
const candidates = scanForAttributeCollisionDamage(model), storage = new StagedChangesetStorage(model.rootPath);
|
|
21
|
+
await attemptRecovery(candidates, storage);
|
|
22
|
+
let repaired = [];
|
|
23
|
+
if (options.apply && candidates.some((c) => c.recovered)) {
|
|
24
|
+
repaired = applyRecovery(model, candidates);
|
|
25
|
+
const affectedLayers = new Set(repaired.map((c) => c.layerName));
|
|
26
|
+
for (const layerName of affectedLayers)
|
|
27
|
+
await model.saveLayer(layerName);
|
|
28
|
+
}
|
|
29
|
+
if ((options.format ?? "text") === "json") {
|
|
30
|
+
const report = {
|
|
31
|
+
totalAffected: candidates.length,
|
|
32
|
+
requiredMissing: candidates.filter((c) => c.required).length,
|
|
33
|
+
optionalMissing: candidates.filter((c) => !c.required).length,
|
|
34
|
+
recoverable: candidates.filter((c) => c.recovered).length,
|
|
35
|
+
repaired: repaired.length,
|
|
36
|
+
applied: !!options.apply,
|
|
37
|
+
candidates
|
|
38
|
+
}, json = JSON.stringify(report, null, 2);
|
|
39
|
+
options.output ? (await writeFile(options.output, json), console.log(ansis.green(`\u2713 Report written to ${options.output}`))) : console.log(json);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (candidates.length === 0) {
|
|
43
|
+
console.log(ansis.green(`
|
|
44
|
+
\u2713 No attribute-collision damage found \u2014 model is clean.
|
|
45
|
+
`));
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
console.log(ansis.bold(`
|
|
49
|
+
Found ${candidates.length} element${candidates.length === 1 ? "" : "s"} missing a schema-declared attribute the fixed persistence bug could have stripped:
|
|
50
|
+
`));
|
|
51
|
+
const required = candidates.filter((c) => c.required), optional = candidates.filter((c) => !c.required);
|
|
52
|
+
required.length > 0 && (console.log(ansis.red(ansis.bold(`REQUIRED \u2014 fails validation today (${required.length}):`))), required.forEach((c) => printCandidate(c, !!options.apply)), console.log()), optional.length > 0 && (console.log(ansis.yellow(ansis.bold(`Optional \u2014 silent, unconfirmed whether ever set (${optional.length}):`))), optional.forEach((c) => printCandidate(c, !!options.apply)), console.log());
|
|
53
|
+
const recoverableCount = candidates.filter((c) => c.recovered).length, unrecoverableCount = candidates.length - recoverableCount;
|
|
54
|
+
options.apply ? (console.log(ansis.green(`\u2713 Restored ${repaired.length} of ${recoverableCount} recoverable value(s) from changeset history.`)), unrecoverableCount > 0 && console.log(ansis.yellow(`\u26A0 ${unrecoverableCount} element(s) have no recoverable value \u2014 re-supply manually with "dr update <id> --attributes '{...}'".`))) : (console.log(ansis.dim(`${recoverableCount} of ${candidates.length} have a recoverable value in changeset history. Run with --apply to restore them.`)), unrecoverableCount > 0 && console.log(ansis.dim(`${unrecoverableCount} have no recoverable value and will need to be manually re-supplied even after --apply.`))), console.log();
|
|
55
|
+
} catch (error) {
|
|
56
|
+
handleError(error);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
export {
|
|
60
|
+
repairAttributeCollisionCommand
|
|
61
|
+
};
|
|
62
|
+
//# sourceMappingURL=repair.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/commands/repair.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Repair command \u2014 detect and best-effort-recover model data lost to a fixed bug in\n * Model.saveLayer() that silently stripped the \"source\"/\"x-source-reference\" attributes from\n * every element on save, even when a node type's own schema declared one as a real (sometimes\n * required) domain attribute. See core/attribute-collision-repair.ts for the full mechanism.\n *\n * This is a detect-and-report tool first, repair second: elements with no recoverable value in\n * changeset history are always reported, never fabricated.\n */\n\nimport ansis from \"ansis\";\nimport { Model } from \"../core/model.js\";\nimport { StagedChangesetStorage } from \"../core/staged-changeset-storage.js\";\nimport {\n scanForAttributeCollisionDamage,\n attemptRecovery,\n applyRecovery,\n type CollisionCandidate,\n} from \"../core/attribute-collision-repair.js\";\nimport { ModelNotFoundError, getErrorMessage, handleError } from \"../utils/errors.js\";\nimport { writeFile } from \"../utils/file-io.js\";\n\nexport interface RepairAttributeCollisionOptions {\n apply?: boolean;\n format?: \"text\" | \"json\";\n output?: string;\n verbose?: boolean;\n}\n\nfunction printCandidate(c: CollisionCandidate, applied: boolean): void {\n let note: string;\n if (c.recovered) {\n note = applied\n ? ansis.green(`restored from changeset \"${c.recovered.changesetName}\"`)\n : ansis.green(`recoverable from changeset \"${c.recovered.changesetName}\"`);\n } else {\n note = ansis.dim(\"no recoverable value found \u2014 must be re-supplied manually\");\n }\n console.log(` ${ansis.bold(c.elementRef)} ${ansis.dim(`(${c.specNodeId}.${c.attribute})`)} \u2014 ${note}`);\n}\n\nexport async function repairAttributeCollisionCommand(\n options: RepairAttributeCollisionOptions = {}\n): Promise<void> {\n try {\n let model: Model;\n try {\n model = await Model.load();\n } catch (error) {\n const message = getErrorMessage(error);\n if (message.includes(\"No DR project\") || message.includes(\"Model not found\")) {\n throw new ModelNotFoundError();\n }\n throw error;\n }\n\n const candidates = scanForAttributeCollisionDamage(model);\n const storage = new StagedChangesetStorage(model.rootPath);\n await attemptRecovery(candidates, storage);\n\n let repaired: CollisionCandidate[] = [];\n if (options.apply && candidates.some((c) => c.recovered)) {\n repaired = applyRecovery(model, candidates);\n const affectedLayers = new Set(repaired.map((c) => c.layerName));\n for (const layerName of affectedLayers) {\n await model.saveLayer(layerName);\n }\n }\n\n const format = options.format ?? \"text\";\n\n if (format === \"json\") {\n const report = {\n totalAffected: candidates.length,\n requiredMissing: candidates.filter((c) => c.required).length,\n optionalMissing: candidates.filter((c) => !c.required).length,\n recoverable: candidates.filter((c) => c.recovered).length,\n repaired: repaired.length,\n applied: !!options.apply,\n candidates,\n };\n const json = JSON.stringify(report, null, 2);\n if (options.output) {\n await writeFile(options.output, json);\n console.log(ansis.green(`\u2713 Report written to ${options.output}`));\n } else {\n console.log(json);\n }\n return;\n }\n\n if (candidates.length === 0) {\n console.log(ansis.green(\"\\n\u2713 No attribute-collision damage found \u2014 model is clean.\\n\"));\n return;\n }\n\n console.log(\n ansis.bold(\n `\\nFound ${candidates.length} element${candidates.length === 1 ? \"\" : \"s\"} missing a ` +\n `schema-declared attribute the fixed persistence bug could have stripped:\\n`\n )\n );\n\n const required = candidates.filter((c) => c.required);\n const optional = candidates.filter((c) => !c.required);\n\n if (required.length > 0) {\n console.log(ansis.red(ansis.bold(`REQUIRED \u2014 fails validation today (${required.length}):`)));\n required.forEach((c) => printCandidate(c, !!options.apply));\n console.log();\n }\n\n if (optional.length > 0) {\n console.log(\n ansis.yellow(ansis.bold(`Optional \u2014 silent, unconfirmed whether ever set (${optional.length}):`))\n );\n optional.forEach((c) => printCandidate(c, !!options.apply));\n console.log();\n }\n\n const recoverableCount = candidates.filter((c) => c.recovered).length;\n const unrecoverableCount = candidates.length - recoverableCount;\n\n if (options.apply) {\n console.log(\n ansis.green(\n `\u2713 Restored ${repaired.length} of ${recoverableCount} recoverable value(s) from changeset history.`\n )\n );\n if (unrecoverableCount > 0) {\n console.log(\n ansis.yellow(\n `\u26A0 ${unrecoverableCount} element(s) have no recoverable value \u2014 re-supply manually ` +\n `with \"dr update <id> --attributes '{...}'\".`\n )\n );\n }\n } else {\n console.log(\n ansis.dim(\n `${recoverableCount} of ${candidates.length} have a recoverable value in changeset history. ` +\n `Run with --apply to restore them.`\n )\n );\n if (unrecoverableCount > 0) {\n console.log(\n ansis.dim(\n `${unrecoverableCount} have no recoverable value and will need to be manually re-supplied ` +\n `even after --apply.`\n )\n );\n }\n }\n console.log();\n } catch (error) {\n handleError(error);\n }\n}\n"],
|
|
5
|
+
"mappings": "AAUA,OAAO,WAAW;AAClB,SAAS,aAAa;AACtB,SAAS,8BAA8B;AACvC,SACE,iCACA,iBACA,qBAEK;AACP,SAAS,oBAAoB,iBAAiB,mBAAmB;AACjE,SAAS,iBAAiB;AAS1B,SAAS,eAAe,GAAuB,SAAgB;AAC7D,MAAI;AACJ,EAAI,EAAE,YACJ,OAAO,UACH,MAAM,MAAM,4BAA4B,EAAE,UAAU,aAAa,GAAG,IAC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EACb,SAAS,OAAO;AACd,gBAAY,KAAK;EACnB;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/commands/version.js
CHANGED
|
@@ -2,7 +2,7 @@ import ansis from "ansis";
|
|
|
2
2
|
import { getCliBundledSpecVersion } from "../utils/spec-version.js";
|
|
3
3
|
import { isTelemetryBuiltIn, isTelemetryConfigured } from "../telemetry/detect.js";
|
|
4
4
|
import { getSpecReferencePath, getModelPath } from "../utils/project-paths.js";
|
|
5
|
-
const gitHash = "
|
|
5
|
+
const gitHash = "d34903f", cliVersion = "0.1.12";
|
|
6
6
|
async function versionCommand() {
|
|
7
7
|
const specVersion = getCliBundledSpecVersion(), telemetryBuiltIn = isTelemetryBuiltIn(), telemetryConfigured = await isTelemetryConfigured();
|
|
8
8
|
let telemetryStatus;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { getNodeType } from "../generated/node-types.js";
|
|
2
|
+
const HISTORICALLY_COLLIDING_ATTRIBUTE_NAMES = ["source", "x-source-reference"];
|
|
3
|
+
function scanForAttributeCollisionDamage(model) {
|
|
4
|
+
const candidates = [];
|
|
5
|
+
for (const layerName of model.getLayerNames()) {
|
|
6
|
+
const layer = model.layers.get(layerName);
|
|
7
|
+
if (layer)
|
|
8
|
+
for (const element of layer.elements.values()) {
|
|
9
|
+
if (!element.spec_node_id)
|
|
10
|
+
continue;
|
|
11
|
+
const nodeType = getNodeType(element.spec_node_id);
|
|
12
|
+
if (nodeType)
|
|
13
|
+
for (const attribute of HISTORICALLY_COLLIDING_ATTRIBUTE_NAMES) {
|
|
14
|
+
const required = nodeType.requiredAttributes.includes(attribute), optional = nodeType.optionalAttributes.includes(attribute);
|
|
15
|
+
!required && !optional || element.attributes != null && Object.prototype.hasOwnProperty.call(element.attributes, attribute) && element.attributes[attribute] !== void 0 || candidates.push({
|
|
16
|
+
elementRef: element.path || element.id,
|
|
17
|
+
elementId: element.id,
|
|
18
|
+
layerName,
|
|
19
|
+
specNodeId: element.spec_node_id,
|
|
20
|
+
attribute,
|
|
21
|
+
required
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return candidates;
|
|
27
|
+
}
|
|
28
|
+
async function attemptRecovery(candidates, storage) {
|
|
29
|
+
if (candidates.length === 0)
|
|
30
|
+
return candidates;
|
|
31
|
+
const changesets = await storage.list();
|
|
32
|
+
changesets.sort((a, b) => (b.modified || "").localeCompare(a.modified || ""));
|
|
33
|
+
for (const candidate of candidates)
|
|
34
|
+
for (const changeset of changesets) {
|
|
35
|
+
const match = [...changeset.changes].sort((a, b) => (b.timestamp || "").localeCompare(a.timestamp || "")).find((change) => {
|
|
36
|
+
if (change.type !== "add" && change.type !== "update" || change.elementId !== candidate.elementRef && change.elementId !== candidate.elementId)
|
|
37
|
+
return !1;
|
|
38
|
+
const afterAttrs = change.after?.attributes;
|
|
39
|
+
return afterAttrs != null && afterAttrs[candidate.attribute] !== void 0;
|
|
40
|
+
});
|
|
41
|
+
if (match) {
|
|
42
|
+
const afterAttrs = match.after.attributes;
|
|
43
|
+
candidate.recovered = {
|
|
44
|
+
value: afterAttrs[candidate.attribute],
|
|
45
|
+
changesetId: changeset.id,
|
|
46
|
+
changesetName: changeset.name,
|
|
47
|
+
changeTimestamp: match.timestamp
|
|
48
|
+
};
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return candidates;
|
|
53
|
+
}
|
|
54
|
+
function applyRecovery(model, candidates) {
|
|
55
|
+
const repaired = [];
|
|
56
|
+
for (const candidate of candidates) {
|
|
57
|
+
if (!candidate.recovered)
|
|
58
|
+
continue;
|
|
59
|
+
const layer = model.layers.get(candidate.layerName);
|
|
60
|
+
if (!layer)
|
|
61
|
+
continue;
|
|
62
|
+
const element = layer.getElement(candidate.elementRef) ?? layer.getElement(candidate.elementId);
|
|
63
|
+
element && (element.attributes = { ...element.attributes, [candidate.attribute]: candidate.recovered.value }, layer.updateElement(element), repaired.push(candidate));
|
|
64
|
+
}
|
|
65
|
+
return repaired;
|
|
66
|
+
}
|
|
67
|
+
export {
|
|
68
|
+
HISTORICALLY_COLLIDING_ATTRIBUTE_NAMES,
|
|
69
|
+
applyRecovery,
|
|
70
|
+
attemptRecovery,
|
|
71
|
+
scanForAttributeCollisionDamage
|
|
72
|
+
};
|
|
73
|
+
//# sourceMappingURL=attribute-collision-repair.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/core/attribute-collision-repair.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Attribute-collision repair \u2014 finds and best-effort-recovers data lost to a fixed bug in\n * Model.saveLayer(): a hardcoded, type-blind \"internal fields\" blocklist unconditionally\n * stripped any attribute literally named \"source\" or \"x-source-reference\" from EVERY element's\n * attributes before writing YAML, regardless of whether the element's own schema declared it as\n * a real domain attribute. 41 of 191 node schemas across 8 layers do (3 mark it required).\n *\n * Once an element was saved under the buggy code, the value is gone from the base model YAML \u2014\n * this module can't un-delete data that was never persisted. What it CAN do:\n *\n * 1. Detect every element that's missing a schema-declared \"source\"/\"x-source-reference\"\n * attribute \u2014 the fingerprint of damage from this bug (as opposed to the attribute simply\n * never having been set, which looks identical for the base model alone).\n * 2. Attempt recovery from changeset history: StagedChangesetStorage writes changes.yaml\n * directly (`yaml.stringify(changeset.changes)`), with NO pass through saveLayer()'s\n * stripping \u2014 so an add/update recorded while this bug was active can still hold the\n * original, un-stripped value, for as long as that changeset file hasn't been deleted\n * (committing a changeset does NOT delete it \u2014 see StagingAreaManager.commit()).\n *\n * Elements with no recoverable value are reported, never fabricated \u2014 this is a best-effort\n * repair, not a guarantee, and the report is only advisory for optional attributes (there's no\n * way to distinguish \"this bug stripped it\" from \"this was never set\" from the base model alone).\n */\n\nimport { Model } from \"./model.js\";\nimport { StagedChangesetStorage } from \"./staged-changeset-storage.js\";\nimport type { Change } from \"./changeset.js\";\nimport { getNodeType } from \"../generated/node-types.js\";\nimport type { SpecNodeId } from \"../generated/node-types.js\";\n\n/** The exact two attribute names the pre-fix INTERNAL_FIELDS blocklist unconditionally\n * stripped, despite being legitimate schema-declared attributes on some node types. Kept as an\n * explicit historical constant, not derived from current code \u2014 the whole point of this module\n * is to find damage from a bug that no longer exists in model.ts, so it can't reconstruct this\n * list by reading the (now-fixed) stripping logic. `__references__`/`__relationships__` are\n * NOT included: those were, and remain, genuinely internal on every node type (zero schema\n * collisions), so their absence is never damage from this bug. */\nexport const HISTORICALLY_COLLIDING_ATTRIBUTE_NAMES = [\"source\", \"x-source-reference\"] as const;\n\nexport interface CollisionCandidate {\n /** Element path (preferred, human-readable) or id if no path is set. */\n elementRef: string;\n elementId: string;\n layerName: string;\n specNodeId: string;\n attribute: (typeof HISTORICALLY_COLLIDING_ATTRIBUTE_NAMES)[number];\n /** Whether the schema marks this attribute required \u2014 a required+missing attribute means the\n * element currently FAILS validation, not just a silent gap. */\n required: boolean;\n recovered?: {\n value: unknown;\n changesetId: string;\n changesetName: string;\n changeTimestamp?: string;\n };\n}\n\n/**\n * Scan every element in the model for one of the two historically-colliding attribute names\n * being declared by its schema but absent from its current, persisted attributes.\n */\nexport function scanForAttributeCollisionDamage(model: Model): CollisionCandidate[] {\n const candidates: CollisionCandidate[] = [];\n\n for (const layerName of model.getLayerNames()) {\n const layer = model.layers.get(layerName);\n if (!layer) continue;\n\n for (const element of layer.elements.values()) {\n if (!element.spec_node_id) continue;\n const nodeType = getNodeType(element.spec_node_id as SpecNodeId);\n if (!nodeType) continue;\n\n for (const attribute of HISTORICALLY_COLLIDING_ATTRIBUTE_NAMES) {\n const required = nodeType.requiredAttributes.includes(attribute);\n const optional = nodeType.optionalAttributes.includes(attribute);\n if (!required && !optional) continue; // Not declared by this type \u2014 nothing to check.\n\n const hasValue =\n element.attributes != null &&\n Object.prototype.hasOwnProperty.call(element.attributes, attribute) &&\n element.attributes[attribute] !== undefined;\n if (hasValue) continue; // Present \u2014 unaffected.\n\n candidates.push({\n elementRef: element.path || element.id,\n elementId: element.id,\n layerName,\n specNodeId: element.spec_node_id,\n attribute,\n required,\n });\n }\n }\n }\n\n return candidates;\n}\n\n/**\n * Attempt to recover each candidate's original value from changeset history. Mutates and\n * returns the same array with `.recovered` filled in where a value was found \u2014 searches every\n * changeset (active, committed, or discarded; committing does not delete the changeset file),\n * newest-first, for the most recent add/update change touching this element that carried a\n * non-empty value for the missing attribute.\n */\nexport async function attemptRecovery(\n candidates: CollisionCandidate[],\n storage: StagedChangesetStorage\n): Promise<CollisionCandidate[]> {\n if (candidates.length === 0) return candidates;\n\n const changesets = await storage.list();\n // Newest-first by last-modified, so the first match found is the most recent one.\n changesets.sort((a, b) => (b.modified || \"\").localeCompare(a.modified || \"\"));\n\n for (const candidate of candidates) {\n for (const changeset of changesets) {\n const changes = [...changeset.changes].sort(\n (a, b) => (b.timestamp || \"\").localeCompare(a.timestamp || \"\")\n );\n\n const match = changes.find((change: Change) => {\n if (change.type !== \"add\" && change.type !== \"update\") return false;\n if (change.elementId !== candidate.elementRef && change.elementId !== candidate.elementId) {\n return false;\n }\n const afterAttrs = (change.after as { attributes?: Record<string, unknown> } | undefined)\n ?.attributes;\n return afterAttrs != null && afterAttrs[candidate.attribute] !== undefined;\n });\n\n if (match) {\n const afterAttrs = (match.after as { attributes: Record<string, unknown> }).attributes;\n candidate.recovered = {\n value: afterAttrs[candidate.attribute],\n changesetId: changeset.id,\n changesetName: changeset.name,\n changeTimestamp: match.timestamp,\n };\n break;\n }\n }\n }\n\n return candidates;\n}\n\n/**\n * Apply recovered values back onto the live model (in memory \u2014 caller is responsible for\n * saving the affected layers). Returns the list of candidates actually repaired.\n */\nexport function applyRecovery(model: Model, candidates: CollisionCandidate[]): CollisionCandidate[] {\n const repaired: CollisionCandidate[] = [];\n\n for (const candidate of candidates) {\n if (!candidate.recovered) continue;\n const layer = model.layers.get(candidate.layerName);\n if (!layer) continue;\n const element = layer.getElement(candidate.elementRef) ?? layer.getElement(candidate.elementId);\n if (!element) continue;\n\n element.attributes = { ...element.attributes, [candidate.attribute]: candidate.recovered.value };\n layer.updateElement(element);\n repaired.push(candidate);\n }\n\n return repaired;\n}\n"],
|
|
5
|
+
"mappings": "AA2BA,SAAS,mBAAmB;AAUrB,MAAM,yCAAyC,CAAC,UAAU,oBAAoB;AAwB/E,SAAU,gCAAgC,OAAY;AAC1D,QAAM,aAAmC,CAAA;AAEzC,aAAW,aAAa,MAAM,cAAa,GAAI;AAC7C,UAAM,QAAQ,MAAM,OAAO,IAAI,SAAS;AACxC,QAAK;AAEL,iBAAW,WAAW,MAAM,SAAS,OAAM,GAAI;AAC7C,YAAI,CAAC,QAAQ;AAAc;AAC3B,cAAM,WAAW,YAAY,QAAQ,YAA0B;AAC/D,YAAK;AAEL,qBAAW,aAAa,wCAAwC;AAC9D,kBAAM,WAAW,SAAS,mBAAmB,SAAS,SAAS,GACzD,WAAW,SAAS,mBAAmB,SAAS,SAAS;AAO/D,YANI,CAAC,YAAY,CAAC,YAGhB,QAAQ,cAAc,QACtB,OAAO,UAAU,eAAe,KAAK,QAAQ,YAAY,SAAS,KAClE,QAAQ,WAAW,SAAS,MAAM,UAGpC,WAAW,KAAK;cACd,YAAY,QAAQ,QAAQ,QAAQ;cACpC,WAAW,QAAQ;cACnB;cACA,YAAY,QAAQ;cACpB;cACA;aACD;UACH;MACF;EACF;AAEA,SAAO;AACT;AASA,eAAsB,gBACpB,YACA,SAA+B;AAE/B,MAAI,WAAW,WAAW;AAAG,WAAO;AAEpC,QAAM,aAAa,MAAM,QAAQ,KAAI;AAErC,aAAW,KAAK,CAAC,GAAG,OAAO,EAAE,YAAY,IAAI,cAAc,EAAE,YAAY,EAAE,CAAC;AAE5E,aAAW,aAAa;AACtB,eAAW,aAAa,YAAY;AAKlC,YAAM,QAJU,CAAC,GAAG,UAAU,OAAO,EAAE,KACrC,CAAC,GAAG,OAAO,EAAE,aAAa,IAAI,cAAc,EAAE,aAAa,EAAE,CAAC,EAG1C,KAAK,CAAC,WAAkB;AAE5C,YADI,OAAO,SAAS,SAAS,OAAO,SAAS,YACzC,OAAO,cAAc,UAAU,cAAc,OAAO,cAAc,UAAU;AAC9E,iBAAO;AAET,cAAM,aAAc,OAAO,OACvB;AACJ,eAAO,cAAc,QAAQ,WAAW,UAAU,SAAS,MAAM;MACnE,CAAC;AAED,UAAI,OAAO;AACT,cAAM,aAAc,MAAM,MAAkD;AAC5E,kBAAU,YAAY;UACpB,OAAO,WAAW,UAAU,SAAS;UACrC,aAAa,UAAU;UACvB,eAAe,UAAU;UACzB,iBAAiB,MAAM;;AAEzB;MACF;IACF;AAGF,SAAO;AACT;AAMM,SAAU,cAAc,OAAc,YAAgC;AAC1E,QAAM,WAAiC,CAAA;AAEvC,aAAW,aAAa,YAAY;AAClC,QAAI,CAAC,UAAU;AAAW;AAC1B,UAAM,QAAQ,MAAM,OAAO,IAAI,UAAU,SAAS;AAClD,QAAI,CAAC;AAAO;AACZ,UAAM,UAAU,MAAM,WAAW,UAAU,UAAU,KAAK,MAAM,WAAW,UAAU,SAAS;AAC9F,IAAK,YAEL,QAAQ,aAAa,EAAE,GAAG,QAAQ,YAAY,CAAC,UAAU,SAAS,GAAG,UAAU,UAAU,MAAK,GAC9F,MAAM,cAAc,OAAO,GAC3B,SAAS,KAAK,SAAS;EACzB;AAEA,SAAO;AACT;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/core/graph-model.js
CHANGED
|
@@ -239,7 +239,20 @@ class GraphModel {
|
|
|
239
239
|
type: element.type,
|
|
240
240
|
name: element.name,
|
|
241
241
|
description: element.description,
|
|
242
|
-
properties
|
|
242
|
+
// `properties` is a SEPARATE COPY of `attributes`, never the same object reference.
|
|
243
|
+
// `Layer`'s node<->Element conversion (layer.ts's constructor/addElement) mutates
|
|
244
|
+
// `node.properties` in place to stash graph-internal bookkeeping keys
|
|
245
|
+
// (__references__/__relationships__/__semanticId__) that have no separate channel
|
|
246
|
+
// on GraphNode. If `properties` and `attributes` aliased the same object (as they
|
|
247
|
+
// did before), those mutations leaked straight into `attributes` too — and
|
|
248
|
+
// `attributes` is exactly what `Model.saveLayer()` persists to YAML and what
|
|
249
|
+
// `Layer.elements`/`getElement()` read back as the element's real domain data.
|
|
250
|
+
// That aliasing is what let `__semanticId__` (added after __references__/
|
|
251
|
+
// __relationships__ were already accounted for elsewhere) slip past
|
|
252
|
+
// model.ts's internal-key filter and get written into persisted YAML. Copying
|
|
253
|
+
// here means a future bookkeeping key added to layer.ts's `nodeProperties` can
|
|
254
|
+
// never repeat that leak, regardless of whether model.ts's filter is kept in sync.
|
|
255
|
+
properties: element.attributes ? { ...element.attributes } : {},
|
|
243
256
|
spec_node_id: element.spec_node_id || void 0,
|
|
244
257
|
layer_id: element.layer_id || void 0,
|
|
245
258
|
attributes: element.attributes && Object.keys(element.attributes).length > 0 ? element.attributes : void 0,
|