@webpieces/nx-webpieces-rules 0.4.700 → 0.4.702
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/package.json +6 -6
- package/src/executors/generate/executor.js +5 -1
- package/src/executors/generate/executor.js.map +1 -1
- package/src/executors/validate-runtime-architecture/executor.d.ts +10 -4
- package/src/executors/validate-runtime-architecture/executor.js +46 -35
- package/src/executors/validate-runtime-architecture/executor.js.map +1 -1
- package/src/lib/api-usage/api-ast.d.ts +1 -16
- package/src/lib/api-usage/api-ast.js +1 -42
- package/src/lib/api-usage/api-ast.js.map +1 -1
- package/src/lib/api-usage/api-relations.d.ts +1 -17
- package/src/lib/api-usage/api-relations.js +10 -2
- package/src/lib/api-usage/api-relations.js.map +1 -1
- package/src/lib/api-usage/api-scanner.d.ts +1 -1
- package/src/lib/api-usage/api-scanner.js +1 -10
- package/src/lib/api-usage/api-scanner.js.map +1 -1
- package/src/lib/cut-legacy-cycle-resolver.d.ts +47 -0
- package/src/lib/cut-legacy-cycle-resolver.js +68 -0
- package/src/lib/cut-legacy-cycle-resolver.js.map +1 -0
- package/src/lib/graph-loader.js +3 -0
- package/src/lib/graph-loader.js.map +1 -1
- package/src/lib/graph-metadata.js +10 -0
- package/src/lib/graph-metadata.js.map +1 -1
- package/src/lib/graph-sorter.d.ts +8 -1
- package/src/lib/graph-sorter.js.map +1 -1
- package/src/lib/runtime-config.d.ts +0 -7
- package/src/lib/runtime-config.js +0 -5
- package/src/lib/runtime-config.js.map +1 -1
- package/src/lib/runtime-cycles.d.ts +10 -12
- package/src/lib/runtime-cycles.js +11 -14
- package/src/lib/runtime-cycles.js.map +1 -1
- package/src/lib/runtime-graph-levels.d.ts +52 -6
- package/src/lib/runtime-graph-levels.js +118 -19
- package/src/lib/runtime-graph-levels.js.map +1 -1
- package/src/lib/runtime-graph-model.d.ts +8 -1
- package/src/lib/runtime-graph-model.js.map +1 -1
- package/src/lib/runtime-graph.d.ts +1 -1
- package/src/lib/runtime-graph.js +10 -41
- package/src/lib/runtime-graph.js.map +1 -1
- package/src/lib/runtime-visualizer.js +7 -3
- package/src/lib/runtime-visualizer.js.map +1 -1
- package/src/lib/runtime-viz-theme.d.ts +7 -0
- package/src/lib/runtime-viz-theme.js +8 -1
- package/src/lib/runtime-viz-theme.js.map +1 -1
- package/src/lib/service-name-resolver.d.ts +1 -1
- package/src/lib/service-name-resolver.js +1 -1
- package/src/lib/service-name-resolver.js.map +1 -1
- package/src/lib/runtime-host-nodes.d.ts +0 -10
- package/src/lib/runtime-host-nodes.js +0 -15
- package/src/lib/runtime-host-nodes.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph-metadata.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/graph-metadata.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAmCH,gDAOC;AAOD,kCAuCC;AAuFD,8DAwBC;AAgBD,4DAuBC;;AA5OD,+CAAyB;AACzB,mDAA6B;AAC7B,uCAAqD;AAErD,iDAA6C;AAC7C,6DAAwD;AACxD,mDAA8C;AAC9C,qEAA8D;AAC9D,iFAA2E;AAC3E,mEAA8G;AAC9G,yDAAuF;AACvF,wCAAqC;AAExB,QAAA,0BAA0B,GAAG,qBAAqB,CAAC;AAEhE;;;;GAIG;AACH,MAAa,uBAAwB,SAAQ,KAAK;IAClB;IAA5B,YAA4B,QAAkB;QAC1C,KAAK,CACD,4CAA4C,QAAQ,CAAC,MAAM,iBAAiB;YACxE,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAe,EAAE,EAAE,CAAC,OAAO,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CACrE,CAAC;QAJsB,aAAQ,GAAR,QAAQ,CAAU;QAK1C,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IAC1C,CAAC;CACJ;AARD,0DAQC;AAED;;GAEG;AACI,KAAK,UAAU,kBA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AAI,CAAC,GAAG,IAAI,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC,CAAC;QACjD,OAAO;IACX,CAAC;IACD,KAAK,CAAC,gBAAgB,GAAG,OAAO,CAAC;AACrC,CAAC;AAED;;;GAGG;AACH,SAAS,cAAc,CAAC,WAAmB,EAAE,QAAgB;IACzD,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACrF,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAS,kBAAkB,CAAC,aAAqB,EAAE,WAAmB;IAClE,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC;IACxE,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC;QAAE,OAAO,KAAK,CAAC;IAC7C,8DAA8D;IAC9D,IAAI,CAAC;QACD,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC;QAChE,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;IACtE,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,OAAO,CAAC,IAAI,CAAC,4BAA4B,UAAU,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACzE,OAAO,KAAK,CAAC;IACjB,CAAC;AACL,CAAC","sourcesContent":["/**\n * Graph Metadata Enrichment\n *\n * Fills the AI-oriented fields on each architecture/dependencies.json entry:\n * framework — from `framework:<x>` nx tag or package.json inference\n * serviceName — from project.json metadata.webpieces.serviceName; the\n * name clients address this app by at runtime\n * shortDescription — first paragraph of the project's responsibilities.md\n * responsibilitiesFile — repo-relative path to the required responsibilities.md\n * designFile — repo-relative path to the generated DI design.json\n *\n * Validation is aggregated: ALL problems across ALL projects are collected and\n * thrown as one MetadataValidationError so a repo adopting this sees the full\n * seeding list in a single run. Callers must enrich BEFORE writing any file so\n * a failed run never clobbers dependencies.json.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { createProjectGraphAsync } from '@nx/devkit';\nimport type { EnhancedGraph, GraphEntry } from './graph-sorter';\nimport { ProjectInfo } from './project-info';\nimport { resolveFramework } from './framework-resolver';\nimport { resolveRole } from './role-resolver';\nimport { resolveDrawOnGraph } from './draw-on-graph-resolver';\nimport { resolveRuntimeParticipant } from './runtime-participant-resolver';\nimport { resolveCallsService, resolveServiceName, validateUniqueServiceNames } from './service-name-resolver';\nimport { extractShortDescription, validateShortDescription } from './responsibilities';\nimport { toError } from '../toError';\n\nexport const RESPONSIBILITIES_FILE_NAME = 'responsibilities.md';\n\n/**\n * Thrown when one or more projects fail metadata validation (missing/invalid\n * responsibilities.md, bad framework tags, ...). Executors catch this to point\n * AI at the webpieces.responsibilities.md instructions template.\n */\nexport class MetadataValidationError extends Error {\n constructor(public readonly problems: string[]) {\n super(\n `Architecture metadata validation failed (${problems.length} problem(s)):\\n` +\n problems.map((problem: string) => ` - ${problem}`).join('\\n')\n );\n this.name = 'MetadataValidationError';\n }\n}\n\n/**\n * Read per-project root + tags from nx's project graph.\n */\nexport async function collectProjectInfo(): Promise<Map<string, ProjectInfo>> {\n const projectGraph = await createProjectGraphAsync();\n const infos = new Map<string, ProjectInfo>();\n for (const [name, node] of Object.entries(projectGraph.nodes)) {\n infos.set(name, new ProjectInfo(name, node.data.root, node.data.tags ?? []));\n }\n return infos;\n}\n\n/**\n * Enrich every graph entry in place with framework, shortDescription,\n * responsibilitiesFile and designFile. Throws MetadataValidationError listing\n * every problem when any project fails validation.\n */\nexport function enrichGraph(\n graph: EnhancedGraph,\n infos: Map<string, ProjectInfo>,\n workspaceRoot: string\n): void {\n const problems: string[] = [];\n // project -> declared serviceName, collected so duplicates can be reported across the workspace.\n const serviceNames = new Map<string, string>();\n\n for (const [projectName, entry] of Object.entries(graph)) {\n const info = infos.get(projectName);\n if (!info) {\n problems.push(`${projectName}: not found in nx project graph`);\n continue;\n }\n\n enrichDeclarations(entry, info, workspaceRoot, problems);\n enrichClientNames(entry, info, workspaceRoot, projectName, serviceNames, problems);\n enrichResponsibilities(entry, info, workspaceRoot, problems);\n\n // Set designFile ONLY when the project has a REAL generated design (a\n // non-empty `designs[]`), i.e. it has a @DocumentDesign root. A project\n // without one has NO design.json at all (di-graph-generate stopped writing\n // empty ones and reaps stale ones), and legacy repos may still carry an\n // empty `{ designs: [] }` until their next build — both must read the same\n // way, and neither gets a \"View Design\" item on its node menu in the arch\n // viz (designLinks keys off designFile). See graph-visualizer.ts.\n if (hasGeneratedDesign(workspaceRoot, info.root)) {\n entry.designFile = toRepoRelative(info.root, 'design.json');\n }\n }\n\n validateUniqueServiceNames(serviceNames, problems);\n validateLibraryTypesMatch(graph, problems);\n validateRoleDependencies(graph, problems);\n\n if (problems.length > 0) {\n throw new MetadataValidationError(problems);\n }\n}\n\n/**\n * The fields a project DECLARES about itself — its framework env set and role (nx tags), the\n * webpieces runtime packages it depends on (package.json), and whether it opts out of the drawings\n * (nx tag). Grouped because they share a shape: resolve, record the problem, or write the field.\n *\n * Distinct from enrichResponsibilities/designFile, which read generated or hand-written FILES.\n */\n// webpieces-disable no-function-outside-class -- enrichGraph step helper, matching enrichClientNames/enrichResponsibilities in this file\nfunction enrichDeclarations(\n entry: GraphEntry,\n info: ProjectInfo,\n workspaceRoot: string,\n problems: string[]\n): void {\n const resolution = resolveFramework(info, workspaceRoot);\n if (resolution.problem !== null) {\n problems.push(resolution.problem);\n } else if (resolution.frameworks !== null) {\n entry.framework = resolution.frameworks;\n }\n\n const roleResolution = resolveRole(info);\n if (roleResolution.problem !== null) {\n problems.push(roleResolution.problem);\n } else if (roleResolution.role !== null) {\n entry.role = roleResolution.role;\n }\n\n // Only persist when the project declares at least one — a repo full of\n // \"webpiecesRuntime\": [] lines would be noise, and absence already means \"declares none\".\n const participantResolution = resolveRuntimeParticipant(info, workspaceRoot);\n if (participantResolution.problem !== null) {\n problems.push(participantResolution.problem);\n } else if (participantResolution.markers !== null && participantResolution.markers.length > 0) {\n entry.webpiecesRuntime = participantResolution.markers;\n }\n\n // Only persist the field when hidden (false); drawn projects (the\n // default) stay clean in dependencies.json with no drawOnGraph line.\n const drawResolution = resolveDrawOnGraph(info);\n if (drawResolution.problem !== null) {\n problems.push(drawResolution.problem);\n } else if (drawResolution.drawOnGraph === false) {\n entry.drawOnGraph = false;\n }\n}\n\n/**\n * Roles that are terminal APPS — nothing may depend on them. A server, a\n * non-HTTP `app`, or a client is a top-level runnable; being depended upon means\n * it is really a library and should be retagged `role:lib`/`role:designed-lib`.\n */\nexport const APP_ROLES: ReadonlyArray<string> = ['server', 'app', 'client'];\n\n/**\n * Compatibility lattice — the \"up-set\" of each atomic env is the env itself\n * PLUS every ancestor it can legally consume code from (specialization edges\n * child → parent: react → browser, angular → browser, express → node). A\n * consumer promising env `c` can be satisfied by any dependency env in `up(c)`.\n */\nexport const ENV_UP_SETS: Readonly<Record<string, ReadonlyArray<string>>> = {\n react: ['react', 'browser'],\n angular: ['angular', 'browser'],\n browser: ['browser'],\n express: ['express', 'node'],\n node: ['node'],\n};\n\n/** The up-set of an env (env itself + ancestors); unknown envs map to just themselves. */\nfunction upSet(env: string): ReadonlyArray<string> {\n return ENV_UP_SETS[env] ?? [env];\n}\n\n/**\n * `library-types-match-client` rule.\n *\n * A project's `framework` field is its libType — the SET of runtime\n * environments it is validated to run in (browser | react | angular | node |\n * express). For a dependency edge Consumer C → Library L, the edge is LEGAL iff\n * for EVERY env `c` in C's set, up(c) ∩ L's set ≠ ∅ — i.e. every environment\n * the consumer promises to run in can be satisfied by the dependency. This keeps\n * an express app from depending on a browser-only lib, and lets a `browser+node`\n * lib be consumed by both react and express projects. Every violation is\n * appended to `problems` so `arch:generate` fails with the full list.\n */\nexport function validateLibraryTypesMatch(graph: EnhancedGraph, problems: string[]): void {\n for (const [projectName, entry] of Object.entries(graph)) {\n const fromSet = entry.framework;\n if (fromSet === undefined) continue; // framework resolution already flagged this project\n\n for (const dep of entry.dependsOn) {\n const depEntry = graph[dep];\n const toSet = depEntry?.framework;\n if (toSet === undefined) continue;\n\n const unsatisfied = fromSet.filter(\n (env: string) => !upSet(env).some((up: string) => toSet.includes(up))\n );\n if (unsatisfied.length === 0) continue;\n\n problems.push(\n `library-types-match-client: '${projectName}' [${fromSet.join(', ')}] must not depend on ` +\n `'${dep}' [${toSet.join(', ')}] — the consumer env(s) ${unsatisfied.join(', ')} cannot be ` +\n `satisfied by the dependency (each consumer env must resolve to itself or an ancestor it ` +\n `consumes from: react/angular→browser, express→node). Widen '${dep}' framework tags or ` +\n `remove the dependency.`\n );\n }\n }\n}\n\n/**\n * `role-dependency` rule.\n *\n * A project's `role` is its function (server | designed-lib | lib | client).\n * Apps are terminal — libraries and clients consume them, never the reverse:\n * - a `client` is fully terminal: NOTHING may depend on it.\n * - a `server` may only be depended upon by another `server` — the one\n * legitimate case is a server-side orchestrator/e2e harness that boots\n * other servers. A `lib`/`designed-lib`/`client` depending on a `server`\n * inverts the dependency direction and is a violation.\n * - a `bundle` is the one role permitted to depend on ANY app: it aggregates\n * several apps into one distributable (e.g. an nx plugin re-exposing multiple\n * tooling apps), so a `bundle → app` edge is legitimate, not inverted.\n */\nexport function validateRoleDependencies(graph: EnhancedGraph, problems: string[]): void {\n for (const [projectName, entry] of Object.entries(graph)) {\n const fromRole = entry.role;\n for (const dep of entry.dependsOn) {\n const toRole = graph[dep]?.role;\n if (toRole === undefined) continue; // role resolution already flagged this project\n if (!APP_ROLES.includes(toRole)) continue;\n // A server may orchestrate/boot other servers (e.g. an e2e harness).\n if (toRole === 'server' && fromRole === 'server') continue;\n // A bundle aggregates apps — it may depend on any app role.\n if (fromRole === 'bundle') continue;\n\n const why =\n toRole === 'client'\n ? `a 'client' app is terminal and may never be depended upon`\n : `a 'server' may only be depended upon by another 'server' (an orchestrator/e2e harness)`;\n problems.push(\n `role-dependency: '${projectName}' (role:${fromRole ?? 'none'}) must not depend on ` +\n `'${dep}' (role:${toRole}) — ${why}. Retag '${dep}' role:lib/role:designed-lib if it ` +\n `is actually a library, or remove the dependency.`\n );\n }\n }\n}\n\n/**\n * Fill the two symmetric client-addressing fields — `serviceName` (the name clients address THIS app\n * by) and `callsService` (the name THIS app's clients call when no literal ClientConfig sits at the\n * call site). Both are declared in project.json, never derived (see service-name-resolver.ts).\n */\n// webpieces-disable no-function-outside-class -- pure enrichment helper, mirrors enrichResponsibilities\nfunction enrichClientNames(\n entry: EnhancedGraph[string],\n info: ProjectInfo,\n workspaceRoot: string,\n projectName: string,\n serviceNames: Map<string, string>,\n problems: string[]\n): void {\n const serviceResolution = resolveServiceName(info, workspaceRoot);\n if (serviceResolution.problem !== null) {\n problems.push(serviceResolution.problem);\n } else if (serviceResolution.serviceName !== null) {\n entry.serviceName = serviceResolution.serviceName;\n serviceNames.set(projectName, serviceResolution.serviceName);\n }\n\n // Consumed by the runtime graph's target resolution (runtime-graph.ts), between the call-site\n // literal and the fan-out fallback.\n const callsResolution = resolveCallsService(info, workspaceRoot);\n if (callsResolution.problem !== null) {\n problems.push(callsResolution.problem);\n } else if (callsResolution.callsService !== null) {\n entry.callsService = callsResolution.callsService;\n }\n}\n\nfunction enrichResponsibilities(\n entry: EnhancedGraph[string],\n info: ProjectInfo,\n workspaceRoot: string,\n problems: string[]\n): void {\n const responsibilitiesFile = toRepoRelative(info.root, RESPONSIBILITIES_FILE_NAME);\n entry.responsibilitiesFile = responsibilitiesFile;\n\n const absolutePath = path.join(workspaceRoot, info.root, RESPONSIBILITIES_FILE_NAME);\n if (!fs.existsSync(absolutePath)) {\n problems.push(\n `${info.name}: missing required ${responsibilitiesFile} — create it with a heading, ` +\n `one short summary paragraph, then the full responsibilities of the module`\n );\n return;\n }\n\n const summary = extractShortDescription(fs.readFileSync(absolutePath, 'utf-8'));\n const summaryProblem = validateShortDescription(summary, responsibilitiesFile);\n if (summaryProblem !== null) {\n problems.push(`${info.name}: ${summaryProblem}`);\n return;\n }\n entry.shortDescription = summary;\n}\n\n/**\n * Repo-relative path with forward slashes (stable across platforms in the\n * committed JSON).\n */\nfunction toRepoRelative(projectRoot: string, fileName: string): string {\n return [projectRoot.replace(/\\\\/g, '/').replace(/\\/+$/, ''), fileName].join('/');\n}\n\n/**\n * True when the project has a REAL generated DI design — a committed design.json\n * whose `designs[]` is non-empty (i.e. it has ≥1 @DocumentDesign root).\n *\n * MISSING, empty-`designs[]`, and unparseable all read as \"no design\", and that\n * equivalence is load-bearing rather than incidental: di-graph-generate writes NO\n * file for a project without a design root (and reaps a stale one), so \"absent\"\n * is now the normal state for every plain lib and legacy service. Repos that have\n * not rebuilt since still carry `{ designs: [] }` files. Either way the box's node\n * menu must offer no \"View Design\" item. See design-file-emission.spec.ts.\n */\nfunction hasGeneratedDesign(workspaceRoot: string, projectRoot: string): boolean {\n const designPath = path.join(workspaceRoot, projectRoot, 'design.json');\n if (!fs.existsSync(designPath)) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed = JSON.parse(fs.readFileSync(designPath, 'utf-8'));\n return Array.isArray(parsed.designs) && parsed.designs.length > 0;\n } catch (err: unknown) {\n const error = toError(err);\n console.warn(`⚠️ Skipping unparseable ${designPath}: ${error.message}`);\n return false;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"graph-metadata.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/graph-metadata.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAoCH,gDAOC;AAOD,kCAuCC;AAgGD,8DAwBC;AAgBD,4DAuBC;;AAtPD,+CAAyB;AACzB,mDAA6B;AAC7B,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AG,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACrF,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAS,kBAAkB,CAAC,aAAqB,EAAE,WAAmB;IAClE,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC;IACxE,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC;QAAE,OAAO,KAAK,CAAC;IAC7C,8DAA8D;IAC9D,IAAI,CAAC;QACD,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC;QAChE,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;IACtE,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,OAAO,CAAC,IAAI,CAAC,4BAA4B,UAAU,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACzE,OAAO,KAAK,CAAC;IACjB,CAAC;AACL,CAAC","sourcesContent":["/**\n * Graph Metadata Enrichment\n *\n * Fills the AI-oriented fields on each architecture/dependencies.json entry:\n * framework — from `framework:<x>` nx tag or package.json inference\n * serviceName — from project.json metadata.webpieces.serviceName; the\n * name clients address this app by at runtime\n * shortDescription — first paragraph of the project's responsibilities.md\n * responsibilitiesFile — repo-relative path to the required responsibilities.md\n * designFile — repo-relative path to the generated DI design.json\n *\n * Validation is aggregated: ALL problems across ALL projects are collected and\n * thrown as one MetadataValidationError so a repo adopting this sees the full\n * seeding list in a single run. Callers must enrich BEFORE writing any file so\n * a failed run never clobbers dependencies.json.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { createProjectGraphAsync } from '@nx/devkit';\nimport type { EnhancedGraph, GraphEntry } from './graph-sorter';\nimport { ProjectInfo } from './project-info';\nimport { resolveFramework } from './framework-resolver';\nimport { resolveRole } from './role-resolver';\nimport { resolveDrawOnGraph } from './draw-on-graph-resolver';\nimport { resolveCutLegacyCycles } from './cut-legacy-cycle-resolver';\nimport { resolveRuntimeParticipant } from './runtime-participant-resolver';\nimport { resolveCallsService, resolveServiceName, validateUniqueServiceNames } from './service-name-resolver';\nimport { extractShortDescription, validateShortDescription } from './responsibilities';\nimport { toError } from '../toError';\n\nexport const RESPONSIBILITIES_FILE_NAME = 'responsibilities.md';\n\n/**\n * Thrown when one or more projects fail metadata validation (missing/invalid\n * responsibilities.md, bad framework tags, ...). Executors catch this to point\n * AI at the webpieces.responsibilities.md instructions template.\n */\nexport class MetadataValidationError extends Error {\n constructor(public readonly problems: string[]) {\n super(\n `Architecture metadata validation failed (${problems.length} problem(s)):\\n` +\n problems.map((problem: string) => ` - ${problem}`).join('\\n')\n );\n this.name = 'MetadataValidationError';\n }\n}\n\n/**\n * Read per-project root + tags from nx's project graph.\n */\nexport async function collectProjectInfo(): Promise<Map<string, ProjectInfo>> {\n const projectGraph = await createProjectGraphAsync();\n const infos = new Map<string, ProjectInfo>();\n for (const [name, node] of Object.entries(projectGraph.nodes)) {\n infos.set(name, new ProjectInfo(name, node.data.root, node.data.tags ?? []));\n }\n return infos;\n}\n\n/**\n * Enrich every graph entry in place with framework, shortDescription,\n * responsibilitiesFile and designFile. Throws MetadataValidationError listing\n * every problem when any project fails validation.\n */\nexport function enrichGraph(\n graph: EnhancedGraph,\n infos: Map<string, ProjectInfo>,\n workspaceRoot: string\n): void {\n const problems: string[] = [];\n // project -> declared serviceName, collected so duplicates can be reported across the workspace.\n const serviceNames = new Map<string, string>();\n\n for (const [projectName, entry] of Object.entries(graph)) {\n const info = infos.get(projectName);\n if (!info) {\n problems.push(`${projectName}: not found in nx project graph`);\n continue;\n }\n\n enrichDeclarations(entry, info, workspaceRoot, problems);\n enrichClientNames(entry, info, workspaceRoot, projectName, serviceNames, problems);\n enrichResponsibilities(entry, info, workspaceRoot, problems);\n\n // Set designFile ONLY when the project has a REAL generated design (a\n // non-empty `designs[]`), i.e. it has a @DocumentDesign root. A project\n // without one has NO design.json at all (di-graph-generate stopped writing\n // empty ones and reaps stale ones), and legacy repos may still carry an\n // empty `{ designs: [] }` until their next build — both must read the same\n // way, and neither gets a \"View Design\" item on its node menu in the arch\n // viz (designLinks keys off designFile). See graph-visualizer.ts.\n if (hasGeneratedDesign(workspaceRoot, info.root)) {\n entry.designFile = toRepoRelative(info.root, 'design.json');\n }\n }\n\n validateUniqueServiceNames(serviceNames, problems);\n validateLibraryTypesMatch(graph, problems);\n validateRoleDependencies(graph, problems);\n\n if (problems.length > 0) {\n throw new MetadataValidationError(problems);\n }\n}\n\n/**\n * The fields a project DECLARES about itself — its framework env set and role (nx tags), the\n * webpieces runtime packages it depends on (package.json), and whether it opts out of the drawings\n * (nx tag). Grouped because they share a shape: resolve, record the problem, or write the field.\n *\n * Distinct from enrichResponsibilities/designFile, which read generated or hand-written FILES.\n */\n// webpieces-disable no-function-outside-class -- enrichGraph step helper, matching enrichClientNames/enrichResponsibilities in this file\nfunction enrichDeclarations(\n entry: GraphEntry,\n info: ProjectInfo,\n workspaceRoot: string,\n problems: string[]\n): void {\n const resolution = resolveFramework(info, workspaceRoot);\n if (resolution.problem !== null) {\n problems.push(resolution.problem);\n } else if (resolution.frameworks !== null) {\n entry.framework = resolution.frameworks;\n }\n\n const roleResolution = resolveRole(info);\n if (roleResolution.problem !== null) {\n problems.push(roleResolution.problem);\n } else if (roleResolution.role !== null) {\n entry.role = roleResolution.role;\n }\n\n // Only persist when the project declares at least one — a repo full of\n // \"webpiecesRuntime\": [] lines would be noise, and absence already means \"declares none\".\n const participantResolution = resolveRuntimeParticipant(info, workspaceRoot);\n if (participantResolution.problem !== null) {\n problems.push(participantResolution.problem);\n } else if (participantResolution.markers !== null && participantResolution.markers.length > 0) {\n entry.webpiecesRuntime = participantResolution.markers;\n }\n\n // Only persist the field when hidden (false); drawn projects (the\n // default) stay clean in dependencies.json with no drawOnGraph line.\n const drawResolution = resolveDrawOnGraph(info);\n if (drawResolution.problem !== null) {\n problems.push(drawResolution.problem);\n } else if (drawResolution.drawOnGraph === false) {\n entry.drawOnGraph = false;\n }\n\n // Only persist when the project actually cuts an edge — absence is the normal state, and a repo\n // full of \"cutLegacyCycle\": [] lines would bury the ones that mean something.\n const cutResolution = resolveCutLegacyCycles(info);\n if (cutResolution.problem !== null) {\n problems.push(cutResolution.problem);\n } else if (cutResolution.targets !== null && cutResolution.targets.length > 0) {\n entry.cutLegacyCycle = cutResolution.targets;\n }\n}\n\n/**\n * Roles that are terminal APPS — nothing may depend on them. A server, a\n * non-HTTP `app`, or a client is a top-level runnable; being depended upon means\n * it is really a library and should be retagged `role:lib`/`role:designed-lib`.\n */\nexport const APP_ROLES: ReadonlyArray<string> = ['server', 'app', 'client'];\n\n/**\n * Compatibility lattice — the \"up-set\" of each atomic env is the env itself\n * PLUS every ancestor it can legally consume code from (specialization edges\n * child → parent: react → browser, angular → browser, express → node). A\n * consumer promising env `c` can be satisfied by any dependency env in `up(c)`.\n */\nexport const ENV_UP_SETS: Readonly<Record<string, ReadonlyArray<string>>> = {\n react: ['react', 'browser'],\n angular: ['angular', 'browser'],\n browser: ['browser'],\n express: ['express', 'node'],\n node: ['node'],\n};\n\n/** The up-set of an env (env itself + ancestors); unknown envs map to just themselves. */\nfunction upSet(env: string): ReadonlyArray<string> {\n return ENV_UP_SETS[env] ?? [env];\n}\n\n/**\n * `library-types-match-client` rule.\n *\n * A project's `framework` field is its libType — the SET of runtime\n * environments it is validated to run in (browser | react | angular | node |\n * express). For a dependency edge Consumer C → Library L, the edge is LEGAL iff\n * for EVERY env `c` in C's set, up(c) ∩ L's set ≠ ∅ — i.e. every environment\n * the consumer promises to run in can be satisfied by the dependency. This keeps\n * an express app from depending on a browser-only lib, and lets a `browser+node`\n * lib be consumed by both react and express projects. Every violation is\n * appended to `problems` so `arch:generate` fails with the full list.\n */\nexport function validateLibraryTypesMatch(graph: EnhancedGraph, problems: string[]): void {\n for (const [projectName, entry] of Object.entries(graph)) {\n const fromSet = entry.framework;\n if (fromSet === undefined) continue; // framework resolution already flagged this project\n\n for (const dep of entry.dependsOn) {\n const depEntry = graph[dep];\n const toSet = depEntry?.framework;\n if (toSet === undefined) continue;\n\n const unsatisfied = fromSet.filter(\n (env: string) => !upSet(env).some((up: string) => toSet.includes(up))\n );\n if (unsatisfied.length === 0) continue;\n\n problems.push(\n `library-types-match-client: '${projectName}' [${fromSet.join(', ')}] must not depend on ` +\n `'${dep}' [${toSet.join(', ')}] — the consumer env(s) ${unsatisfied.join(', ')} cannot be ` +\n `satisfied by the dependency (each consumer env must resolve to itself or an ancestor it ` +\n `consumes from: react/angular→browser, express→node). Widen '${dep}' framework tags or ` +\n `remove the dependency.`\n );\n }\n }\n}\n\n/**\n * `role-dependency` rule.\n *\n * A project's `role` is its function (server | designed-lib | lib | client).\n * Apps are terminal — libraries and clients consume them, never the reverse:\n * - a `client` is fully terminal: NOTHING may depend on it.\n * - a `server` may only be depended upon by another `server` — the one\n * legitimate case is a server-side orchestrator/e2e harness that boots\n * other servers. A `lib`/`designed-lib`/`client` depending on a `server`\n * inverts the dependency direction and is a violation.\n * - a `bundle` is the one role permitted to depend on ANY app: it aggregates\n * several apps into one distributable (e.g. an nx plugin re-exposing multiple\n * tooling apps), so a `bundle → app` edge is legitimate, not inverted.\n */\nexport function validateRoleDependencies(graph: EnhancedGraph, problems: string[]): void {\n for (const [projectName, entry] of Object.entries(graph)) {\n const fromRole = entry.role;\n for (const dep of entry.dependsOn) {\n const toRole = graph[dep]?.role;\n if (toRole === undefined) continue; // role resolution already flagged this project\n if (!APP_ROLES.includes(toRole)) continue;\n // A server may orchestrate/boot other servers (e.g. an e2e harness).\n if (toRole === 'server' && fromRole === 'server') continue;\n // A bundle aggregates apps — it may depend on any app role.\n if (fromRole === 'bundle') continue;\n\n const why =\n toRole === 'client'\n ? `a 'client' app is terminal and may never be depended upon`\n : `a 'server' may only be depended upon by another 'server' (an orchestrator/e2e harness)`;\n problems.push(\n `role-dependency: '${projectName}' (role:${fromRole ?? 'none'}) must not depend on ` +\n `'${dep}' (role:${toRole}) — ${why}. Retag '${dep}' role:lib/role:designed-lib if it ` +\n `is actually a library, or remove the dependency.`\n );\n }\n }\n}\n\n/**\n * Fill the two symmetric client-addressing fields — `serviceName` (the name clients address THIS app\n * by) and `callsService` (the name THIS app's clients call when no literal ClientConfig sits at the\n * call site). Both are declared in project.json, never derived (see service-name-resolver.ts).\n */\n// webpieces-disable no-function-outside-class -- pure enrichment helper, mirrors enrichResponsibilities\nfunction enrichClientNames(\n entry: EnhancedGraph[string],\n info: ProjectInfo,\n workspaceRoot: string,\n projectName: string,\n serviceNames: Map<string, string>,\n problems: string[]\n): void {\n const serviceResolution = resolveServiceName(info, workspaceRoot);\n if (serviceResolution.problem !== null) {\n problems.push(serviceResolution.problem);\n } else if (serviceResolution.serviceName !== null) {\n entry.serviceName = serviceResolution.serviceName;\n serviceNames.set(projectName, serviceResolution.serviceName);\n }\n\n // Consumed by the runtime graph's target resolution (runtime-graph.ts), between the call-site\n // literal and the fan-out fallback.\n const callsResolution = resolveCallsService(info, workspaceRoot);\n if (callsResolution.problem !== null) {\n problems.push(callsResolution.problem);\n } else if (callsResolution.callsService !== null) {\n entry.callsService = callsResolution.callsService;\n }\n}\n\nfunction enrichResponsibilities(\n entry: EnhancedGraph[string],\n info: ProjectInfo,\n workspaceRoot: string,\n problems: string[]\n): void {\n const responsibilitiesFile = toRepoRelative(info.root, RESPONSIBILITIES_FILE_NAME);\n entry.responsibilitiesFile = responsibilitiesFile;\n\n const absolutePath = path.join(workspaceRoot, info.root, RESPONSIBILITIES_FILE_NAME);\n if (!fs.existsSync(absolutePath)) {\n problems.push(\n `${info.name}: missing required ${responsibilitiesFile} — create it with a heading, ` +\n `one short summary paragraph, then the full responsibilities of the module`\n );\n return;\n }\n\n const summary = extractShortDescription(fs.readFileSync(absolutePath, 'utf-8'));\n const summaryProblem = validateShortDescription(summary, responsibilitiesFile);\n if (summaryProblem !== null) {\n problems.push(`${info.name}: ${summaryProblem}`);\n return;\n }\n entry.shortDescription = summary;\n}\n\n/**\n * Repo-relative path with forward slashes (stable across platforms in the\n * committed JSON).\n */\nfunction toRepoRelative(projectRoot: string, fileName: string): string {\n return [projectRoot.replace(/\\\\/g, '/').replace(/\\/+$/, ''), fileName].join('/');\n}\n\n/**\n * True when the project has a REAL generated DI design — a committed design.json\n * whose `designs[]` is non-empty (i.e. it has ≥1 @DocumentDesign root).\n *\n * MISSING, empty-`designs[]`, and unparseable all read as \"no design\", and that\n * equivalence is load-bearing rather than incidental: di-graph-generate writes NO\n * file for a project without a design root (and reaps a stale one), so \"absent\"\n * is now the normal state for every plain lib and legacy service. Repos that have\n * not rebuilt since still carry `{ designs: [] }` files. Either way the box's node\n * menu must offer no \"View Design\" item. See design-file-emission.spec.ts.\n */\nfunction hasGeneratedDesign(workspaceRoot: string, projectRoot: string): boolean {\n const designPath = path.join(workspaceRoot, projectRoot, 'design.json');\n if (!fs.existsSync(designPath)) return false;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const parsed = JSON.parse(fs.readFileSync(designPath, 'utf-8'));\n return Array.isArray(parsed.designs) && parsed.designs.length > 0;\n } catch (err: unknown) {\n const error = toError(err);\n console.warn(`⚠️ Skipping unparseable ${designPath}: ${error.message}`);\n return false;\n }\n}\n"]}
|
|
@@ -28,7 +28,7 @@ export interface GraphEntry {
|
|
|
28
28
|
framework?: string[];
|
|
29
29
|
role?: string;
|
|
30
30
|
/**
|
|
31
|
-
* The name CLIENTS address this app by at runtime (`new ClientConfig('helper-fsdb'
|
|
31
|
+
* The name CLIENTS address this app by at runtime (`new ClientConfig('helper-fsdb')`) — its
|
|
32
32
|
* deployed service name, DECLARED in project.json as metadata.webpieces.serviceName. Absent for
|
|
33
33
|
* anything nothing calls by name (libraries, browser apps). See service-name-resolver.ts.
|
|
34
34
|
*/
|
|
@@ -49,6 +49,13 @@ export interface GraphEntry {
|
|
|
49
49
|
* Absent means drawn (the default). From the project's `drawOnGraph:` nx tag.
|
|
50
50
|
*/
|
|
51
51
|
drawOnGraph?: boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Target service names whose RUNTIME edge from this project is cut out of leveling and cycle
|
|
54
|
+
* detection, from this project's `cutLegacyCycle:<target>` nx tags. Per EDGE, not per project.
|
|
55
|
+
* An admission of legacy debt, never an approved pattern — see cut-legacy-cycle-resolver.ts.
|
|
56
|
+
* Absent (the overwhelmingly normal case) means this project cuts nothing.
|
|
57
|
+
*/
|
|
58
|
+
cutLegacyCycle?: string[];
|
|
52
59
|
shortDescription?: string;
|
|
53
60
|
responsibilitiesFile?: string;
|
|
54
61
|
designFile?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph-sorter.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/graph-sorter.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;
|
|
1
|
+
{"version":3,"file":"graph-sorter.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/graph-sorter.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;AAqFH,4DAwCC;AASD,wDAgBC;AAnJD,iDAAsD;AAyEtD;;;;;;;;GAQG;AACH,SAAgB,wBAAwB,CAAC,KAA+B;IACpE,MAAM,MAAM,GAAe,EAAE,CAAC;IAC9B,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU,CAAC;IACpC,MAAM,WAAW,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAEvC,OAAO,SAAS,CAAC,IAAI,GAAG,WAAW,CAAC,MAAM,EAAE,CAAC;QACzC,MAAM,YAAY,GAAa,EAAE,CAAC;QAElC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AAM,MAAM,GAAkB,EAAE,CAAC;IAEjC,+DAA+D;IAC/D,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,UAAU,EAAE,EAAE;QACjC,KAAK,MAAM,OAAO,IAAI,KAAK,EAAE,CAAC;YAC1B,6CAA6C;YAC7C,MAAM,CAAC,OAAO,CAAC,GAAG;gBACd,KAAK,EAAE,UAAU;gBACjB,SAAS,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE;aAC3C,CAAC;QACN,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC","sourcesContent":["/**\n * Graph Sorter\n *\n * Performs topological sorting on the dependency graph to:\n * 1. Detect circular dependencies (fails if cycle found)\n * 2. Assign level numbers to each project (level 0 = no deps, level 1 = depends on level 0, etc.)\n * 3. Group projects into layers for deterministic ordering\n */\n\nimport type { ProjectApiRelations } from './api-usage/api-relations';\nimport { ProjectCycleDetector } from './graph-cycles';\n\n/**\n * Graph entry with level metadata plus AI-oriented metadata filled in by\n * enrichGraph() (lib/graph-metadata.ts) before the graph is saved:\n * - framework: the project's libType — the SET of runtime environments it is\n * validated to run in, drawn from browser | react | angular | node | express\n * (e.g. [\"browser\",\"node\"]); from its `framework:` nx tags (source of truth)\n * or inferred from package.json deps\n * - shortDescription: summary extracted from the project's responsibilities.md\n * - responsibilitiesFile: repo-relative path to the FULL responsibilities doc\n * - designFile: repo-relative path to the generated DI design.json (only for\n * project.json projects)\n * - apiRelations: for each api-lib in `dependsOn`, WHY the edge exists — the\n * APIs this project implements (serves) and/or uses (calls), each with its\n * transport (rpc | pubsub). Derived by scanning source (see api-usage/).\n */\nexport interface GraphEntry {\n level: number;\n dependsOn: string[];\n framework?: string[];\n role?: string;\n /**\n * The name CLIENTS address this app by at runtime (`new ClientConfig('helper-fsdb')`) — its\n * deployed service name, DECLARED in project.json as metadata.webpieces.serviceName. Absent for\n * anything nothing calls by name (libraries, browser apps). See service-name-resolver.ts.\n */\n serviceName?: string;\n /**\n * The service(s) this project's clients call when the call site cannot carry a literal\n * `ClientConfig` — the symmetric half of `serviceName`. DECLARED in project.json as\n * metadata.webpieces.callsService, either a single service name (every untargeted `uses` aims\n * there) or an `{ apiClassName: serviceName }` map (a client that calls several). Absent for a\n * project that never calls anything, or one whose call sites all carry literals.\n * See service-name-resolver.ts.\n */\n callsService?: string | Record<string, string>;\n /**\n * When false, the project is hidden from the rendered architecture graphs\n * (its box AND every edge touching it are omitted from dependencies.html and\n * the runtime graph). It stays in this JSON so the data view is complete.\n * Absent means drawn (the default). From the project's `drawOnGraph:` nx tag.\n */\n drawOnGraph?: boolean;\n /**\n * Target service names whose RUNTIME edge from this project is cut out of leveling and cycle\n * detection, from this project's `cutLegacyCycle:<target>` nx tags. Per EDGE, not per project.\n * An admission of legacy debt, never an approved pattern — see cut-legacy-cycle-resolver.ts.\n * Absent (the overwhelmingly normal case) means this project cuts nothing.\n */\n cutLegacyCycle?: string[];\n shortDescription?: string;\n responsibilitiesFile?: string;\n designFile?: string;\n apiRelations?: ProjectApiRelations;\n /**\n * The @webpieces runtime packages this project's OWN package.json declares — http-routing,\n * http-server, http-client-node, http-client-browser, cloudtasks-client. Omitted when it\n * declares none, so TOTAL absence across the file means the file predates this field and\n * nothing is auto-hidden (see runtime-graph.ts). Core/util/logging packages are deliberately\n * not markers; see runtime-participant-resolver.ts for why.\n *\n * The runtime graph ORs this over a node's library closure: a server whose whole webpieces\n * stack comes from a shared bootstrap lib participates even though it declares nothing itself.\n */\n webpiecesRuntime?: string[];\n}\n\n/**\n * Enhanced graph format with level information\n */\nexport type EnhancedGraph = Record<string, GraphEntry>;\n\n/**\n * Compute topological layers for dependency graph using Kahn's algorithm\n *\n * Projects are grouped into layers where each layer only depends on previous layers.\n * Throws an error if a circular dependency is detected.\n *\n * @param graph - Dependency graph { project: [deps] }\n * @returns Array of layers, each containing sorted project names\n */\nexport function computeTopologicalLayers(graph: Record<string, string[]>): string[][] {\n const layers: string[][] = [];\n const processed = new Set<string>();\n const allProjects = Object.keys(graph);\n\n while (processed.size < allProjects.length) {\n const currentLayer: string[] = [];\n\n for (const project of allProjects) {\n if (processed.has(project)) continue;\n\n const deps = graph[project] || [];\n // Check if all dependencies are in previous layers (already processed)\n const allDepsInPrevLayers = deps.every((dep) => processed.has(dep));\n\n if (allDepsInPrevLayers) {\n currentLayer.push(project);\n }\n }\n\n if (currentLayer.length === 0) {\n // No progress made = circular dependency. ProjectCycleDetector is the ONE cycle\n // implementation in this package — it names every chain, in project keys, with the\n // fix — so this reports through it rather than keeping a second, weaker DFS here.\n new ProjectCycleDetector().assertAcyclic(graph, 'the project graph');\n // Unreachable: Kahn only stalls on a cycle, and the assert above throws on every one.\n const remaining = allProjects.filter((p: string): boolean => !processed.has(p));\n throw new Error(\n `Topological sort stalled with no cycle to report — projects left unlayered: ${remaining.join(', ')}`);\n }\n\n // Sort alphabetically within layer for deterministic output\n currentLayer.sort();\n layers.push(currentLayer);\n\n // Mark as processed\n currentLayer.forEach((p) => processed.add(p));\n }\n\n return layers;\n}\n\n/**\n * Sort graph in topological order with alphabetical sorting within layers\n * Returns enhanced format with level metadata\n *\n * @param graph - Unsorted dependency graph { project: [deps] }\n * @returns Sorted graph with level metadata { project: { level: number, dependsOn: [deps] } }\n */\nexport function sortGraphTopologically(graph: Record<string, string[]>): EnhancedGraph {\n const layers = computeTopologicalLayers(graph);\n const result: EnhancedGraph = {};\n\n // Add projects layer by layer (dependencies before dependents)\n layers.forEach((layer, levelIndex) => {\n for (const project of layer) {\n // Already sorted alphabetically within layer\n result[project] = {\n level: levelIndex,\n dependsOn: (graph[project] || []).sort(),\n };\n }\n });\n\n return result;\n}\n"]}
|
|
@@ -8,23 +8,16 @@
|
|
|
8
8
|
* "mode": "ON", // "OFF" disables the whole feature
|
|
9
9
|
* "turnOffRuleUntilEpoch": 0, // whole-rule punt (epoch seconds)
|
|
10
10
|
* "turnOffRuleWhileOnBranch": null, // whole-rule punt while on a named branch
|
|
11
|
-
* "allowedCycles": [ { "services": ["a","b"], "reason": "...", "until": 1771931925 } ],
|
|
12
11
|
* "showExternalNodes": true, // draw firestore/gmail/... as terminal nodes
|
|
13
12
|
* "externalApiPaths": ["libraries/apis/external/**"] // where those vendor contracts live
|
|
14
13
|
* }
|
|
15
14
|
*/
|
|
16
15
|
import { SkipRuleResult } from '@webpieces/rules-config';
|
|
17
16
|
export declare const RUNTIME_RULE_NAME = "runtime-architecture";
|
|
18
|
-
export interface AllowedCycle {
|
|
19
|
-
services: string[];
|
|
20
|
-
reason?: string;
|
|
21
|
-
until?: number;
|
|
22
|
-
}
|
|
23
17
|
export interface RuntimeRuleConfig {
|
|
24
18
|
off: boolean;
|
|
25
19
|
turnOffRuleUntilEpoch?: number;
|
|
26
20
|
turnOffRuleWhileOnBranch?: string;
|
|
27
|
-
allowedCycles: AllowedCycle[];
|
|
28
21
|
/** Render the dashed external terminal nodes in the runtime viz (default true). */
|
|
29
22
|
showExternalNodes: boolean;
|
|
30
23
|
/**
|
|
@@ -9,7 +9,6 @@
|
|
|
9
9
|
* "mode": "ON", // "OFF" disables the whole feature
|
|
10
10
|
* "turnOffRuleUntilEpoch": 0, // whole-rule punt (epoch seconds)
|
|
11
11
|
* "turnOffRuleWhileOnBranch": null, // whole-rule punt while on a named branch
|
|
12
|
-
* "allowedCycles": [ { "services": ["a","b"], "reason": "...", "until": 1771931925 } ],
|
|
13
12
|
* "showExternalNodes": true, // draw firestore/gmail/... as terminal nodes
|
|
14
13
|
* "externalApiPaths": ["libraries/apis/external/**"] // where those vendor contracts live
|
|
15
14
|
* }
|
|
@@ -22,9 +21,6 @@ exports.isGraceActive = isGraceActive;
|
|
|
22
21
|
exports.epochDate = epochDate;
|
|
23
22
|
const rules_config_1 = require("@webpieces/rules-config");
|
|
24
23
|
exports.RUNTIME_RULE_NAME = 'runtime-architecture';
|
|
25
|
-
function isUsableCycle(cycle) {
|
|
26
|
-
return Array.isArray(cycle.services) && cycle.services.length > 0;
|
|
27
|
-
}
|
|
28
24
|
/** Load the runtime-architecture rule config (with safe defaults). */
|
|
29
25
|
function loadRuntimeConfig(workspaceRoot) {
|
|
30
26
|
const shared = (0, rules_config_1.loadAndValidate)(workspaceRoot).resolved;
|
|
@@ -36,7 +32,6 @@ function loadRuntimeConfig(workspaceRoot) {
|
|
|
36
32
|
// turnOffRuleWhileOnBranch is required-but-NULLABLE in the config ("null" = always on), so a
|
|
37
33
|
// non-string (null) collapses to undefined, which shouldSkipRule treats as "no branch scoping".
|
|
38
34
|
turnOffRuleWhileOnBranch: typeof raw.turnOffRuleWhileOnBranch === 'string' ? raw.turnOffRuleWhileOnBranch : undefined,
|
|
39
|
-
allowedCycles: Array.isArray(raw.allowedCycles) ? raw.allowedCycles.filter(isUsableCycle) : [],
|
|
40
35
|
// Opt-OUT: the external systems are the ones that page you at 3am, so they are drawn unless
|
|
41
36
|
// a repo explicitly says its external surface is too noisy to be useful.
|
|
42
37
|
showExternalNodes: raw.showExternalNodes !== false,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-config.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/runtime-config.ts"],"names":[],"mappings":";AAAA
|
|
1
|
+
{"version":3,"file":"runtime-config.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/runtime-config.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;GAaG;;;AAgCH,8CAqBC;AAQD,8CAEC;AAMD,sCAGC;AAGD,8BAEC;AA3ED,0DAA0F;AAE7E,QAAA,iBAAiB,GAAG,sBAAsB,CAAC;AA2BxD,sEAAsE;AACtE,SAAgB,iBAAiB,CAAC,aAAqB;IACnD,MAAM,MAAM,GAAG,IAAA,8BAAe,EAAC,aAAa,CAAC,CAAC,QAAQ,CAAC;IACvD,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,yBAAiB,CAAC,CAAC;IACj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AE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["/**\n * Runtime Config\n *\n * Loads the `runtime-architecture` rule from webpieces.config.json and exposes\n * typed accessors shared by the generate + validate + visualize executors.\n *\n * \"runtime-architecture\": {\n * \"mode\": \"ON\", // \"OFF\" disables the whole feature\n * \"turnOffRuleUntilEpoch\": 0, // whole-rule punt (epoch seconds)\n * \"turnOffRuleWhileOnBranch\": null, // whole-rule punt while on a named branch\n * \"showExternalNodes\": true, // draw firestore/gmail/... as terminal nodes\n * \"externalApiPaths\": [\"libraries/apis/external/**\"] // where those vendor contracts live\n * }\n */\n\nimport { loadAndValidate, shouldSkipRule, SkipRuleResult } from '@webpieces/rules-config';\n\nexport const RUNTIME_RULE_NAME = 'runtime-architecture';\n\nexport interface RuntimeRuleConfig {\n off: boolean;\n turnOffRuleUntilEpoch?: number;\n turnOffRuleWhileOnBranch?: string;\n /** Render the dashed external terminal nodes in the runtime viz (default true). */\n showExternalNodes: boolean;\n /**\n * Globs of project roots whose exported `*Api` types are contracts for systems OUTSIDE this repo.\n * Empty (the default) means the scan looks for no vendor seams at all.\n */\n externalApiPaths: string[];\n}\n\n/**\n * Typed view of the opaque webpieces.config.json option bag for this rule. The\n * config is trusted (it is the workspace's own file), so we cast once here and\n * defensively narrow arrays/numbers rather than threading `unknown` everywhere.\n */\ninterface RuntimeRuleRaw {\n turnOffRuleUntilEpoch?: number;\n turnOffRuleWhileOnBranch?: string | null;\n showExternalNodes?: boolean;\n externalApiPaths?: string[];\n}\n\n/** Load the runtime-architecture rule config (with safe defaults). */\nexport function loadRuntimeConfig(workspaceRoot: string): RuntimeRuleConfig {\n const shared = loadAndValidate(workspaceRoot).resolved;\n const rule = shared.rules.get(RUNTIME_RULE_NAME);\n const raw = (rule?.options ?? {}) as RuntimeRuleRaw;\n return {\n off: rule?.isOff ?? false,\n turnOffRuleUntilEpoch:\n typeof raw.turnOffRuleUntilEpoch === 'number' ? raw.turnOffRuleUntilEpoch : undefined,\n // turnOffRuleWhileOnBranch is required-but-NULLABLE in the config (\"null\" = always on), so a\n // non-string (null) collapses to undefined, which shouldSkipRule treats as \"no branch scoping\".\n turnOffRuleWhileOnBranch:\n typeof raw.turnOffRuleWhileOnBranch === 'string' ? raw.turnOffRuleWhileOnBranch : undefined,\n // Opt-OUT: the external systems are the ones that page you at 3am, so they are drawn unless\n // a repo explicitly says its external surface is too noisy to be useful.\n showExternalNodes: raw.showExternalNodes !== false,\n // Opt-IN: there is no safe guess for where a repo keeps its vendor wrappers, and guessing\n // wrong would classify ordinary libraries as systems outside the repo.\n externalApiPaths: Array.isArray(raw.externalApiPaths)\n ? raw.externalApiPaths.filter((entry: string) => typeof entry === 'string' && entry.length > 0)\n : [],\n };\n}\n\n/**\n * Whole-rule report-only window honoring BOTH escape hatches: skip while on the\n * named branch (turnOffRuleWhileOnBranch) or until the epoch passes\n * (turnOffRuleUntilEpoch). When `.skip` is true, problems are reported but\n * the build is not failed.\n */\nexport function runtimeReportOnly(config: RuntimeRuleConfig): SkipRuleResult {\n return shouldSkipRule(config.turnOffRuleUntilEpoch, config.turnOffRuleWhileOnBranch);\n}\n\n/**\n * Whole-rule grace window: while now < epoch, failures are reported but do not\n * fail the build (warn). Mirrors the other webpieces rules.\n */\nexport function isGraceActive(epoch: number | undefined): boolean {\n if (epoch === undefined) return false;\n return Date.now() / 1000 < epoch;\n}\n\n/** Format the epoch as an ISO date for log messages. */\nexport function epochDate(epoch: number): string {\n return new Date(epoch * 1000).toISOString().split('T')[0];\n}\n"]}
|
|
@@ -1,26 +1,24 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Runtime Cycles
|
|
3
3
|
*
|
|
4
|
-
* Enumerates ALL cycles in
|
|
5
|
-
*
|
|
6
|
-
* checked against the per-cycle allowlist independently.
|
|
4
|
+
* Enumerates ALL cycles in a directed graph using Tarjan's strongly-connected-components algorithm.
|
|
5
|
+
* Every cycle rather than the first, so one run names everything a reader has to break.
|
|
7
6
|
*
|
|
8
|
-
* This is the ONE SCC implementation in the package
|
|
9
|
-
* calls it for the COMPILE-TIME project graph,
|
|
10
|
-
*
|
|
7
|
+
* This is the ONE SCC implementation in the package. `ProjectCycleDetector` (lib/graph-cycles.ts)
|
|
8
|
+
* calls it for BOTH graphs: the COMPILE-TIME project graph, and — through `assignLevels`
|
|
9
|
+
* (lib/runtime-graph-levels.ts) — the RUNTIME service graph.
|
|
11
10
|
*
|
|
12
11
|
* A cycle is any SCC with more than one node, or a single node with a self-edge.
|
|
13
|
-
*
|
|
14
|
-
*
|
|
12
|
+
*
|
|
13
|
+
* There is no per-cycle allowlist any more. The `allowedCycles` config key that once keyed off a
|
|
14
|
+
* canonical sorted-name string is deleted: a cyclic architecture cannot be deployed in any order, so
|
|
15
|
+
* it fails outright, and the one escape is a per-EDGE `cutLegacyCycle:<targetService>` nx tag that
|
|
16
|
+
* keeps the edge out of the adjacency this ever sees.
|
|
15
17
|
*/
|
|
16
18
|
export interface RuntimeCycle {
|
|
17
19
|
/** Sorted service names participating in the cycle. */
|
|
18
20
|
services: string[];
|
|
19
|
-
/** Canonical key: services sorted then joined with ",". */
|
|
20
|
-
key: string;
|
|
21
21
|
}
|
|
22
|
-
/** Canonical key for a set of service names (order-independent). */
|
|
23
|
-
export declare function cycleKey(services: string[]): string;
|
|
24
22
|
/**
|
|
25
23
|
* Find every cycle in a directed graph via Tarjan's SCC algorithm.
|
|
26
24
|
* `graph[node]` lists the nodes `node` points to.
|
|
@@ -2,25 +2,22 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* Runtime Cycles
|
|
4
4
|
*
|
|
5
|
-
* Enumerates ALL cycles in
|
|
6
|
-
*
|
|
7
|
-
* checked against the per-cycle allowlist independently.
|
|
5
|
+
* Enumerates ALL cycles in a directed graph using Tarjan's strongly-connected-components algorithm.
|
|
6
|
+
* Every cycle rather than the first, so one run names everything a reader has to break.
|
|
8
7
|
*
|
|
9
|
-
* This is the ONE SCC implementation in the package
|
|
10
|
-
* calls it for the COMPILE-TIME project graph,
|
|
11
|
-
*
|
|
8
|
+
* This is the ONE SCC implementation in the package. `ProjectCycleDetector` (lib/graph-cycles.ts)
|
|
9
|
+
* calls it for BOTH graphs: the COMPILE-TIME project graph, and — through `assignLevels`
|
|
10
|
+
* (lib/runtime-graph-levels.ts) — the RUNTIME service graph.
|
|
12
11
|
*
|
|
13
12
|
* A cycle is any SCC with more than one node, or a single node with a self-edge.
|
|
14
|
-
*
|
|
15
|
-
*
|
|
13
|
+
*
|
|
14
|
+
* There is no per-cycle allowlist any more. The `allowedCycles` config key that once keyed off a
|
|
15
|
+
* canonical sorted-name string is deleted: a cyclic architecture cannot be deployed in any order, so
|
|
16
|
+
* it fails outright, and the one escape is a per-EDGE `cutLegacyCycle:<targetService>` nx tag that
|
|
17
|
+
* keeps the edge out of the adjacency this ever sees.
|
|
16
18
|
*/
|
|
17
19
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
-
exports.cycleKey = cycleKey;
|
|
19
20
|
exports.findRuntimeCycles = findRuntimeCycles;
|
|
20
|
-
/** Canonical key for a set of service names (order-independent). */
|
|
21
|
-
function cycleKey(services) {
|
|
22
|
-
return [...services].sort().join(',');
|
|
23
|
-
}
|
|
24
21
|
/**
|
|
25
22
|
* Find every cycle in a directed graph via Tarjan's SCC algorithm.
|
|
26
23
|
* `graph[node]` lists the nodes `node` points to.
|
|
@@ -69,7 +66,7 @@ function findRuntimeCycles(graph) {
|
|
|
69
66
|
const isSelfLoop = component.length === 1 && (graph[component[0]] ?? []).includes(component[0]);
|
|
70
67
|
if (isMultiNode || isSelfLoop) {
|
|
71
68
|
const services = [...component].sort();
|
|
72
|
-
cycles.push({ services
|
|
69
|
+
cycles.push({ services });
|
|
73
70
|
}
|
|
74
71
|
}
|
|
75
72
|
return cycles;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-cycles.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/runtime-cycles.ts"],"names":[],"mappings":";AAAA
|
|
1
|
+
{"version":3,"file":"runtime-cycles.js","sourceRoot":"","sources":["../../../../../../packages/tooling/nx-webpieces-rules/src/lib/runtime-cycles.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;GAgBG;;AAWH,8CAoDC;AAxDD;;;GAGG;AACH,SAAgB,iBAAiB,CAAC,KAA+B;IAC7D,MAAM,OAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC1C,MAAM,OAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC1C,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAClC,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,IAAI,GAAe,EAAE,CAAC;IAC5B,IAAI,OAAO,GAAG,CAAC,CAAC;IAEhB,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAEjC,MAAM,aAAa,GAAG,CAAC,IAAY,EAAQ,EAAE;QACzC,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC3B,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC3B,OAAO,IAAI,CAAC,CAAC;QACb,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACjB,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAElB,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,CAAC;YACnC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;gBACrB,aAAa,CAAC,IAAI,CAAC,CAAC;gBACpB,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAE,EAAE,OAAO,CAAC,GAAG,CAAC,IAAI,CAAE,CAAC,CAAC,CAAC;YACxE,C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AAC;YAC5B,MAAM,QAAQ,GAAG,CAAC,GAAG,SAAS,CAAC,CAAC,IAAI,EAAE,CAAC;YACvC,MAAM,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC9B,CAAC;IACL,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC","sourcesContent":["/**\n * Runtime Cycles\n *\n * Enumerates ALL cycles in a directed graph using Tarjan's strongly-connected-components algorithm.\n * Every cycle rather than the first, so one run names everything a reader has to break.\n *\n * This is the ONE SCC implementation in the package. `ProjectCycleDetector` (lib/graph-cycles.ts)\n * calls it for BOTH graphs: the COMPILE-TIME project graph, and — through `assignLevels`\n * (lib/runtime-graph-levels.ts) — the RUNTIME service graph.\n *\n * A cycle is any SCC with more than one node, or a single node with a self-edge.\n *\n * There is no per-cycle allowlist any more. The `allowedCycles` config key that once keyed off a\n * canonical sorted-name string is deleted: a cyclic architecture cannot be deployed in any order, so\n * it fails outright, and the one escape is a per-EDGE `cutLegacyCycle:<targetService>` nx tag that\n * keeps the edge out of the adjacency this ever sees.\n */\n\nexport interface RuntimeCycle {\n /** Sorted service names participating in the cycle. */\n services: string[];\n}\n\n/**\n * Find every cycle in a directed graph via Tarjan's SCC algorithm.\n * `graph[node]` lists the nodes `node` points to.\n */\nexport function findRuntimeCycles(graph: Record<string, string[]>): RuntimeCycle[] {\n const indexOf = new Map<string, number>();\n const lowLink = new Map<string, number>();\n const onStack = new Set<string>();\n const stack: string[] = [];\n const sccs: string[][] = [];\n let counter = 0;\n\n const nodes = Object.keys(graph);\n\n const strongConnect = (node: string): void => {\n indexOf.set(node, counter);\n lowLink.set(node, counter);\n counter += 1;\n stack.push(node);\n onStack.add(node);\n\n for (const next of graph[node] ?? []) {\n if (!indexOf.has(next)) {\n strongConnect(next);\n lowLink.set(node, Math.min(lowLink.get(node)!, lowLink.get(next)!));\n } else if (onStack.has(next)) {\n lowLink.set(node, Math.min(lowLink.get(node)!, indexOf.get(next)!));\n }\n }\n\n if (lowLink.get(node) === indexOf.get(node)) {\n const component: string[] = [];\n let member = '';\n do {\n member = stack.pop()!;\n onStack.delete(member);\n component.push(member);\n } while (member !== node);\n sccs.push(component);\n }\n };\n\n for (const node of nodes) {\n if (!indexOf.has(node)) strongConnect(node);\n }\n\n const cycles: RuntimeCycle[] = [];\n for (const component of sccs) {\n const isMultiNode = component.length > 1;\n const isSelfLoop = component.length === 1 && (graph[component[0]] ?? []).includes(component[0]);\n if (isMultiNode || isSelfLoop) {\n const services = [...component].sort();\n cycles.push({ services });\n }\n }\n return cycles;\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { EnhancedGraph } from './graph-sorter';
|
|
1
2
|
import type { RuntimeEdge, RuntimeGraph } from './runtime-graph-model';
|
|
2
3
|
/**
|
|
3
4
|
* LEVELS and ADJACENCY for the runtime graph — how deep each service sits, and who calls whom.
|
|
@@ -10,14 +11,59 @@ import type { RuntimeEdge, RuntimeGraph } from './runtime-graph-model';
|
|
|
10
11
|
/**
|
|
11
12
|
* Adjacency (service -> [targets]) used for leveling + cycle checks.
|
|
12
13
|
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
14
|
+
* TWO KINDS OF EDGE ARE EXCLUDED, and the second is modelled on the first:
|
|
15
|
+
*
|
|
16
|
+
* PUBSUB EDGES. A queue is precisely the thing that decouples producer from consumer: the producer
|
|
17
|
+
* returns as soon as the task is enqueued and never waits on the consumer, so a queued hop is not a
|
|
18
|
+
* runtime dependency in the sense levels and cycle detection mean. Counting them would make the
|
|
19
|
+
* common and correct `A → queue → A` (a service deferring its own work) an architecture cycle, and
|
|
20
|
+
* would rank services by an ordering that does not constrain deploy or startup.
|
|
21
|
+
*
|
|
22
|
+
* EDGES STAMPED `cutLegacyCycle`. The calling project carries a `cutLegacyCycle:<target>` nx tag
|
|
23
|
+
* (see cut-legacy-cycle-resolver.ts) ADMITTING that this hop closes a real cycle which is being
|
|
24
|
+
* tolerated as legacy debt. Unlike a queued hop the coupling is real, so the edge is still drawn —
|
|
25
|
+
* it is only kept out of leveling and cycle detection, which are the two things a cycle makes
|
|
26
|
+
* meaningless.
|
|
18
27
|
*/
|
|
19
28
|
export declare function adjacencyFromEdges(serviceNames: string[], edges: RuntimeEdge[]): Record<string, string[]>;
|
|
29
|
+
/**
|
|
30
|
+
* Stamp `cutLegacyCycle` on every runtime edge a project declared a cut for — the DECLARATION
|
|
31
|
+
* (`cutLegacyCycle:<targetService>` nx tags, resolved into `GraphEntry.cutLegacyCycle` and committed
|
|
32
|
+
* to dependencies.json) turned into the mark {@link adjacencyFromEdges} above reads.
|
|
33
|
+
*
|
|
34
|
+
* IT FAILS THE BUILD ON A TAG THAT CUTS NOTHING, in both directions:
|
|
35
|
+
*
|
|
36
|
+
* - the tag names a service no runtime node answers to — a typo or a rename. Silently doing nothing
|
|
37
|
+
* is the worst outcome available: the check would look exempted while no edge was in fact cut, or
|
|
38
|
+
* the tag would keep reading as a live IOU after the service it named was deleted. `serviceName`
|
|
39
|
+
* is validated against real module names for exactly this reason.
|
|
40
|
+
* - the tag resolves, but there is no direct edge to cut. The debt is PAID — delete the tag, so
|
|
41
|
+
* `grep -rn cutLegacyCycle` keeps enumerating only cycles still actually tolerated.
|
|
42
|
+
*
|
|
43
|
+
* Returned as problems (the deriver's `problems` list) rather than thrown, so one run names every
|
|
44
|
+
* bad tag instead of stopping at the first.
|
|
45
|
+
*
|
|
46
|
+
* @param edges the derived runtime edges, mutated in place.
|
|
47
|
+
* @param projects the committed project entries carrying `cutLegacyCycle`.
|
|
48
|
+
* @param nodeByServiceName addressable name -> runtime node, the SAME map that resolves a call
|
|
49
|
+
* target, so a tag may name a module name or a declared serviceName.
|
|
50
|
+
*/
|
|
51
|
+
export declare function applyCycleCuts(edges: RuntimeEdge[], projects: EnhancedGraph, nodeByServiceName: Map<string, string>): string[];
|
|
20
52
|
/** Adjacency (service -> [targets]) from a loaded runtime graph. */
|
|
21
53
|
export declare function runtimeAdjacency(graph: RuntimeGraph): Record<string, string[]>;
|
|
22
|
-
/**
|
|
54
|
+
/**
|
|
55
|
+
* Assign levels via topological sort — and THROW on a cycle rather than levelling one.
|
|
56
|
+
*
|
|
57
|
+
* This used to swallow the cycle and flatten EVERY service to level 0, which was the worst available
|
|
58
|
+
* outcome twice over: one bad edge anywhere silently restratified the whole graph, and the reason
|
|
59
|
+
* was discarded, so the diagram rendered as one legitimate-looking flat row.
|
|
60
|
+
*
|
|
61
|
+
* Cycles are not allowed. CD deploys services in dependency order, and a cyclic architecture has no
|
|
62
|
+
* such order — whichever member rolls out first is calling one that is not up yet — so the graph is
|
|
63
|
+
* not deployable and its level numbers mean nothing.
|
|
64
|
+
*
|
|
65
|
+
* Detection is {@link ProjectCycleDetector}, the ONE cycle detector in this package (it guards the
|
|
66
|
+
* compile-time project graph too); only the audience and the cures differ, so only the message is
|
|
67
|
+
* written here.
|
|
68
|
+
*/
|
|
23
69
|
export declare function assignLevels(adjacency: Record<string, string[]>): Record<string, number>;
|