@telorun/analyzer 0.68.0 → 0.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/analysis-registry.d.ts +12 -0
  2. package/dist/analysis-registry.d.ts.map +1 -1
  3. package/dist/analysis-registry.js +26 -0
  4. package/dist/call-graph.d.ts +80 -1
  5. package/dist/call-graph.d.ts.map +1 -1
  6. package/dist/call-graph.js +145 -12
  7. package/dist/canonical-json.d.ts +18 -0
  8. package/dist/canonical-json.d.ts.map +1 -0
  9. package/dist/canonical-json.js +26 -0
  10. package/dist/cel-access-chains.d.ts +14 -0
  11. package/dist/cel-access-chains.d.ts.map +1 -0
  12. package/dist/cel-access-chains.js +45 -0
  13. package/dist/import-resolution-diagnostics.d.ts.map +1 -1
  14. package/dist/import-resolution-diagnostics.js +22 -8
  15. package/dist/index.d.ts +7 -5
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +5 -4
  18. package/dist/loaded-types.d.ts +4 -4
  19. package/dist/loaded-types.d.ts.map +1 -1
  20. package/dist/manifest-analysis.d.ts +19 -0
  21. package/dist/manifest-analysis.d.ts.map +1 -1
  22. package/dist/manifest-analysis.js +27 -0
  23. package/dist/manifest-diff.d.ts +111 -0
  24. package/dist/manifest-diff.d.ts.map +1 -0
  25. package/dist/manifest-diff.js +130 -0
  26. package/dist/manifest-loader.d.ts +3 -4
  27. package/dist/manifest-loader.d.ts.map +1 -1
  28. package/dist/manifest-loader.js +4 -5
  29. package/dist/manifest-schemas.d.ts +2 -0
  30. package/dist/manifest-schemas.d.ts.map +1 -1
  31. package/dist/manifest-schemas.js +4 -0
  32. package/dist/module-graph.d.ts +500 -0
  33. package/dist/module-graph.d.ts.map +1 -0
  34. package/dist/module-graph.js +1389 -0
  35. package/dist/reconcile-module-versions.d.ts.map +1 -1
  36. package/dist/reconcile-module-versions.js +10 -11
  37. package/dist/release/release-plan.d.ts +1 -1
  38. package/dist/resolve-zone-containment.d.ts +9 -1
  39. package/dist/resolve-zone-containment.d.ts.map +1 -1
  40. package/dist/resolve-zone-containment.js +34 -6
  41. package/dist/resolve-zone-requirements.d.ts.map +1 -1
  42. package/dist/resolve-zone-requirements.js +4 -2
  43. package/dist/sources/default-sources.d.ts +6 -6
  44. package/dist/sources/default-sources.d.ts.map +1 -1
  45. package/dist/sources/default-sources.js +7 -8
  46. package/dist/sources/integrity.d.ts +3 -2
  47. package/dist/sources/integrity.d.ts.map +1 -1
  48. package/dist/sources/integrity.js +26 -3
  49. package/dist/sources/versioned-ref.d.ts +17 -12
  50. package/dist/sources/versioned-ref.d.ts.map +1 -1
  51. package/dist/sources/versioned-ref.js +22 -24
  52. package/dist/telo-version.d.ts +1 -1
  53. package/dist/telo-version.js +1 -1
  54. package/package.json +2 -2
  55. package/src/analysis-registry.ts +37 -0
  56. package/src/call-graph.ts +207 -14
  57. package/src/canonical-json.ts +24 -0
  58. package/src/cel-access-chains.ts +47 -0
  59. package/src/import-resolution-diagnostics.ts +24 -7
  60. package/src/index.ts +46 -5
  61. package/src/loaded-types.ts +4 -4
  62. package/src/manifest-analysis.ts +39 -0
  63. package/src/manifest-diff.ts +219 -0
  64. package/src/manifest-loader.ts +4 -5
  65. package/src/manifest-schemas.ts +4 -0
  66. package/src/module-graph.ts +1983 -0
  67. package/src/reconcile-module-versions.ts +10 -11
  68. package/src/release/release-plan.ts +1 -1
  69. package/src/resolve-zone-containment.ts +49 -9
  70. package/src/resolve-zone-requirements.ts +7 -2
  71. package/src/sources/default-sources.ts +7 -8
  72. package/src/sources/integrity.ts +28 -3
  73. package/src/sources/versioned-ref.ts +26 -28
  74. package/src/telo-version.ts +1 -1
  75. package/dist/sources/module-ref.d.ts +0 -21
  76. package/dist/sources/module-ref.d.ts.map +0 -1
  77. package/dist/sources/module-ref.js +0 -36
  78. package/dist/sources/registry-source.d.ts +0 -14
  79. package/dist/sources/registry-source.d.ts.map +0 -1
  80. package/dist/sources/registry-source.js +0 -45
  81. package/src/sources/module-ref.ts +0 -49
  82. package/src/sources/registry-source.ts +0 -52
@@ -0,0 +1,1389 @@
1
+ import { isRefSentinel, walkCelExpressions, } from "@telorun/templating";
2
+ import { nodeIdFor, resolveScopedName, resourceId, } from "./call-graph.js";
3
+ import { propertySchemas, resolveLocalRef } from "./manifest-navigation.js";
4
+ import { isStepSlot } from "./step-slot.js";
5
+ import { isInlineResource, resolveFieldEntries } from "./reference-field-map.js";
6
+ import { findZoneProviders } from "./resolve-zone-containment.js";
7
+ import { possibleUses, readRefSlot } from "./ref-slot.js";
8
+ import { canonicalJson } from "./canonical-json.js";
9
+ import { accessChains } from "./cel-access-chains.js";
10
+ /**
11
+ * Rows that are ordered entries of their array.
12
+ *
13
+ * A consumer offering reorder, removal or an index must ask — a declaration
14
+ * written at a dispatch site carries an `index` of 0 and an `array` it shares
15
+ * with its host, both of which are borrowed so it groups into the right branch,
16
+ * and neither of which means what it means on a step.
17
+ */
18
+ export function isOrderedRow(row) {
19
+ return row.kind === "step" || row.kind === "entry" || row.kind === "target";
20
+ }
21
+ /**
22
+ * A hold whose target is ambient infrastructure — the collapse candidate.
23
+ *
24
+ * Stated here rather than in the view because it is the rule the plan fixes,
25
+ * and two hosts applying it differently would disagree about which edges exist:
26
+ * a hold into a shared connection or store is fan-in that swamps a layout and
27
+ * carries no structure, while a hold BETWEEN working resources is the
28
+ * application's spine — a server holding its mounts — and demoting the second
29
+ * with the first is exactly the mistake this replaces.
30
+ */
31
+ /**
32
+ * Is anything reaching this declaration at all?
33
+ *
34
+ * "Declared, referenced by nothing, in no `targets`" — the resource a reader
35
+ * cannot otherwise tell apart from a wired one, since a manifest states no
36
+ * difference between the two. Every incoming edge counts, not only flow: a
37
+ * connection is HELD rather than called, and reading it as unwired would mark
38
+ * every provider in the module. An owned declaration is reached by its owner,
39
+ * and the root is what reaches everything else.
40
+ *
41
+ * A declaration this module did not write is NEVER unwired, however little it
42
+ * is used here. An imported library exports what it exports, and the flatten
43
+ * forwards all of it; "nothing references this" would be a true sentence about
44
+ * an unused export and a useless one, since the reader cannot act on it — the
45
+ * declaration is not theirs to remove.
46
+ */
47
+ export function isUnwired(node, graph) {
48
+ if (node.root || node.external)
49
+ return false;
50
+ if (node.ownership === "inline" || node.ownership === "scoped")
51
+ return false;
52
+ return graph.edgesTo(node.id).length === 0;
53
+ }
54
+ export function isAmbientHold(edge, graph) {
55
+ if (edge.class !== "holds" || !edge.to)
56
+ return false;
57
+ const target = graph.nodeById(edge.to);
58
+ return isAmbientCapability(target?.capability);
59
+ }
60
+ /**
61
+ * Capabilities whose resources are AMBIENT: held and read, never run, and never
62
+ * drawn as the target of a line.
63
+ *
64
+ * Exported because the view partitions on the same fact — which boxes go off
65
+ * the canvas into the drawer — and two spellings of it is how a host ends up
66
+ * collapsing a hold the other still draws an edge for.
67
+ */
68
+ export const AMBIENT_CAPABILITIES = new Set([
69
+ "Telo.Provider",
70
+ "Telo.Type",
71
+ ]);
72
+ /** Is this an ambient declaration — held and read rather than run? */
73
+ export function isAmbientCapability(capability) {
74
+ return !!capability && AMBIENT_CAPABILITIES.has(capability);
75
+ }
76
+ /** Uses that transfer control, so the site is drawn as flow. */
77
+ const FLOW_USES = new Set([
78
+ "call",
79
+ "detached",
80
+ "trigger.inbound",
81
+ "trigger.consumer",
82
+ ]);
83
+ /**
84
+ * The class a site is drawn as.
85
+ *
86
+ * A slot declaring NO use reads as flow, the same conservative direction the
87
+ * call graph takes: the cost of a false "control reaches here" is an edge drawn
88
+ * more prominently than it deserved, while the cost of a false "it never does"
89
+ * is a call the picture denies exists.
90
+ */
91
+ export function edgeClassOf(use) {
92
+ if (use.length === 0)
93
+ return "flow";
94
+ if (use.some((u) => FLOW_USES.has(u)))
95
+ return "flow";
96
+ if (use.includes("dependency"))
97
+ return "holds";
98
+ return "shape";
99
+ }
100
+ /**
101
+ * Documents that declare a TYPE or a module rather than an instance.
102
+ *
103
+ * The flattened analysis carries every imported library's definitions beside
104
+ * its instances, so without this the instance plane fills with the abstracts a
105
+ * dependency happens to declare (`Sql.Connection`, `Codec.Encoder`) — boxes for
106
+ * things that never exist at runtime, drawn among the things that do. They are
107
+ * the kind plane's, which is a separate surface. The module docs are here too:
108
+ * the entry module's is minted as the ROOT, and an imported library's is not an
109
+ * instance at all.
110
+ */
111
+ const DECLARATION_KINDS = new Set([
112
+ "Telo.Definition",
113
+ "Telo.Abstract",
114
+ "Telo.Import",
115
+ "Telo.Application",
116
+ "Telo.Library",
117
+ ]);
118
+ const moduleOf = (manifest) => manifest.metadata?.module;
119
+ /** The canonical id of a resolved kind definition — where it was declared plus
120
+ * what it is called there, which is the one spelling every module agrees on. */
121
+ const canonicalKindOf = (definition) => {
122
+ const metadata = definition?.metadata;
123
+ if (!metadata?.name)
124
+ return undefined;
125
+ return metadata.module ? `${metadata.module}.${metadata.name}` : metadata.name;
126
+ };
127
+ const originOf = (manifest) => manifest.metadata?.xTeloOrigin;
128
+ const isForwardedExport = (manifest) => manifest.metadata?.forwardedExport === true;
129
+ const isInjected = (manifest) => manifest.metadata?.["xTeloInjected"] === true;
130
+ /**
131
+ * A short, stable key over a value's shape.
132
+ *
133
+ * FNV-1a over canonical JSON: what is wanted is that the same written entry
134
+ * keeps the same identity when a sibling is inserted above it, which a hash of
135
+ * the entry's own content gives and an index cannot. Collisions are resolved by
136
+ * declaration order at the call site, so two byte-identical rows stay
137
+ * distinguishable without either one's identity depending on the other's
138
+ * position.
139
+ */
140
+ export function contentKey(value) {
141
+ const json = canonicalJson(value);
142
+ let hash = 0x811c9dc5;
143
+ for (let i = 0; i < json.length; i++) {
144
+ hash ^= json.charCodeAt(i);
145
+ hash = Math.imul(hash, 0x01000193) >>> 0;
146
+ }
147
+ return hash.toString(36);
148
+ }
149
+ /** Mints ids that are unique without being positional: the name where one
150
+ * exists, a content key where none does, and a `~n` suffix only when two
151
+ * siblings are genuinely indistinguishable. */
152
+ class IdMinter {
153
+ used = new Set();
154
+ mint(base) {
155
+ if (!this.used.has(base)) {
156
+ this.used.add(base);
157
+ return base;
158
+ }
159
+ for (let n = 2;; n++) {
160
+ const candidate = `${base}~${n}`;
161
+ if (!this.used.has(candidate)) {
162
+ this.used.add(candidate);
163
+ return candidate;
164
+ }
165
+ }
166
+ }
167
+ }
168
+ /** The schema node at a field-map path, following `[]` into `items` and `{}`
169
+ * into `additionalProperties`, resolving local `$ref`s along the way. */
170
+ function schemaAt(rootSchema, slotPath) {
171
+ if (!rootSchema)
172
+ return undefined;
173
+ let current = rootSchema;
174
+ for (const segment of slotPath.split(".")) {
175
+ if (!current)
176
+ return undefined;
177
+ // A map's key step is its OWN segment (`columns.{}.type`), where an array's
178
+ // rides the field it belongs to (`mounts[].mount`). Reading only the suffix
179
+ // form walked into nothing at the first map, so every slot under one was
180
+ // left with no schema — and a slot with no schema declares no `use`, which
181
+ // classed a column's typed reference as a control transfer.
182
+ if (segment === "{}") {
183
+ current = resolveLocalRef(current.additionalProperties, rootSchema);
184
+ continue;
185
+ }
186
+ const bare = segment.replace(/(\[\]|\{\})+$/g, "");
187
+ let next = propertySchemas(current).find(([k]) => k === bare)?.[1];
188
+ for (const marker of segment.slice(bare.length).match(/\[\]|\{\}/g) ?? []) {
189
+ next = resolveLocalRef(marker === "[]"
190
+ ? next?.items
191
+ : next?.additionalProperties, rootSchema);
192
+ if (!next || typeof next !== "object")
193
+ return undefined;
194
+ }
195
+ current = resolveLocalRef(next, rootSchema);
196
+ }
197
+ return current;
198
+ }
199
+ /**
200
+ * Does this field hold the branch that DISCHARGES a raised error?
201
+ *
202
+ * Two annotations mark one, from two layers, and both are read: the shared CEL
203
+ * one (`x-telo-error-context`, which types the `error` variable inside a
204
+ * `catch:`) and the dispatch outcome vocabulary (`x-telo-outcome-list: catches`,
205
+ * which an HTTP-style router uses to render a code as a response). Neither is a
206
+ * field NAME, so a third-party composer spelling its branch differently is seen
207
+ * as long as it annotates it; recognizing only one would silently mark every
208
+ * route in the standard library as handling nothing.
209
+ */
210
+ function isErrorBranch(schema) {
211
+ return (schema?.["x-telo-error-context"] !== undefined ||
212
+ schema?.["x-telo-outcome-list"] === "catches");
213
+ }
214
+ function entryListsOf(rootSchema) {
215
+ if (!rootSchema)
216
+ return [];
217
+ const out = [];
218
+ for (const [key, propSchema] of propertySchemas(rootSchema)) {
219
+ if (propSchema?.["x-telo-topology-role"] !== "entries")
220
+ continue;
221
+ const items = resolveLocalRef(propSchema.items, rootSchema);
222
+ const matchers = [];
223
+ const handlers = [];
224
+ const errorBranches = [];
225
+ for (const [subKey, subSchema] of propertySchemas(items ?? {})) {
226
+ const role = subSchema?.["x-telo-topology-role"];
227
+ if (role === "matcher")
228
+ matchers.push(subKey);
229
+ else if (role === "handler")
230
+ handlers.push(subKey);
231
+ if (isErrorBranch(subSchema))
232
+ errorBranches.push(subKey);
233
+ }
234
+ out.push({ field: key, matchers, handlers, errorBranches });
235
+ }
236
+ return out;
237
+ }
238
+ /** A value written AT a ref slot that declares a resource rather than naming
239
+ * one — `{kind, …config}` with no `name`. */
240
+ function isInlineDeclaration(value) {
241
+ if (isRefSentinel(value) || !value || typeof value !== "object" || Array.isArray(value)) {
242
+ return false;
243
+ }
244
+ // The shape test itself is the field map's — one reader for "is this a
245
+ // declaration rather than a reference", since the extraction pass keys on the
246
+ // same answer and a second opinion here would decide differently the day the
247
+ // form gains a key.
248
+ return isInlineResource(value);
249
+ }
250
+ /** The referenced name a ref value carries, across both written forms: an
251
+ * unresolved `!ref <name>` sentinel and the `{kind, name}` object
252
+ * `resolveRefSentinels` rewrites it into. */
253
+ function refName(value) {
254
+ if (isRefSentinel(value))
255
+ return value.source;
256
+ if (!value || typeof value !== "object")
257
+ return undefined;
258
+ const name = value.name;
259
+ return typeof name === "string" ? name : undefined;
260
+ }
261
+ /**
262
+ * Fold a manifest set into the module graph.
263
+ *
264
+ * The call graph supplies what calls what — including the scoped nodes and step
265
+ * bodies it already discovers — and this pass adds what a picture needs and a
266
+ * call graph has no reason to carry: declared-but-empty ports, ownership,
267
+ * ordered rows, region membership, and the reduction of six uses to three
268
+ * classes.
269
+ */
270
+ export function buildModuleGraph(resources, callGraph, deps, options = {}) {
271
+ const nodes = [];
272
+ const edges = [];
273
+ const regions = [];
274
+ const byId = new Map();
275
+ const rowIdByPath = new Map();
276
+ /** References found inside inline declarations, resolved once every node
277
+ * exists — a declaration may name a resource declared later in the file. */
278
+ const inlineEdgeSeeds = new Map();
279
+ const add = (node) => {
280
+ nodes.push(node);
281
+ byId.set(node.id, node);
282
+ return node;
283
+ };
284
+ // --- the module root -------------------------------------------------------
285
+ // Not a resource: it owns `targets` and the module's own configuration, and
286
+ // the call graph deliberately skips it. Minting it here is what makes a boot
287
+ // target an ordinary edge rather than a fact a consumer has to fetch from
288
+ // somewhere else.
289
+ let root;
290
+ if (options.root) {
291
+ const name = options.root.metadata?.name ?? "";
292
+ const module = moduleOf(options.root);
293
+ root = add({
294
+ id: resourceId(options.root.kind, name),
295
+ kind: options.root.kind,
296
+ name,
297
+ ownership: "root",
298
+ ...(module ? { module } : {}),
299
+ ports: [],
300
+ rows: [],
301
+ // Boot targets are an ordered list the root always has, empty or not.
302
+ rowArrays: [{ field: "targets", kind: "target" }],
303
+ root: true,
304
+ });
305
+ }
306
+ // --- resource nodes --------------------------------------------------------
307
+ // Minted from the MANIFEST LIST, not from the call graph's node map.
308
+ //
309
+ // The call graph keys a resource by `(kind, name)`, which is unique within one
310
+ // module and not across a flattened set: two libraries each exporting an
311
+ // `Http.Api` named `routes` collapse onto one node there, and a picture built
312
+ // from that map draws one box for two declarations. Minting here from the
313
+ // manifests keeps both, qualified by their declaring module. What is still the
314
+ // call graph's — steps and edges — is translated through `projectedId`, and
315
+ // the collapsed twin's own edges are missing from it; its ports and rows are
316
+ // read from its manifest here, so the box is drawn and wired correctly and
317
+ // only the edges the call graph lost are absent.
318
+ // One id scheme, the call graph's — a resource name is module-scoped, so the
319
+ // module is part of the identity wherever one is stamped. Stating it here a
320
+ // second way is how the two halves would disagree about which box an edge
321
+ // arrives at.
322
+ const idOf = (manifest) => nodeIdFor(manifest);
323
+ const manifestById = new Map();
324
+ for (const manifest of resources) {
325
+ const name = manifest.metadata?.name;
326
+ if (typeof name !== "string" || !manifest.kind || DECLARATION_KINDS.has(manifest.kind))
327
+ continue;
328
+ if (root && manifest === options.root)
329
+ continue;
330
+ const id = idOf(manifest);
331
+ if (byId.has(id))
332
+ continue;
333
+ add(projectResource(id, manifest, deps, options));
334
+ manifestById.set(id, manifest);
335
+ }
336
+ // Call-graph node id → the node it designates here, so a step or an edge the
337
+ // call graph produced lands on the box this pass minted.
338
+ const projectedId = new Map();
339
+ const scopedIdByKey = new Map();
340
+ const scopedByOwner = new Map();
341
+ for (const graphNode of callGraph.nodes.values()) {
342
+ if (graphNode.type !== "resource")
343
+ continue;
344
+ if (DECLARATION_KINDS.has(graphNode.kind))
345
+ continue;
346
+ if (graphNode.scoped) {
347
+ // A `with:`-scoped resource is declared inside another's body, so it is in
348
+ // no manifest list of its own — the call graph is where it exists.
349
+ //
350
+ // One declaration, one box: the call graph keys a scoped node by the
351
+ // scope POINTER, and `x-telo-scope` lists every region a scoped name
352
+ // resolves in (`Run.Sequence` names both `/steps` and `/targets`), so one
353
+ // `with:` entry arrives once per pointer. The pointers say where the name
354
+ // is visible, not where the resource was declared.
355
+ const key = `${graphNode.scopeOwner ?? ""}#scope#${resourceId(graphNode.kind, graphNode.name)}`;
356
+ const already = scopedIdByKey.get(key);
357
+ if (already) {
358
+ projectedId.set(graphNode.id, already);
359
+ continue;
360
+ }
361
+ const node = add(projectResource(graphNode.id, graphNode.manifest, deps, options));
362
+ scopedIdByKey.set(key, node.id);
363
+ node.ownership = "scoped";
364
+ if (graphNode.scopeOwner)
365
+ node.owner = graphNode.scopeOwner;
366
+ if (graphNode.scopeSite)
367
+ node.ownerSite = graphNode.scopeSite;
368
+ manifestById.set(node.id, graphNode.manifest);
369
+ projectedId.set(graphNode.id, node.id);
370
+ const owner = graphNode.scopeOwner;
371
+ if (owner) {
372
+ const sites = scopedByOwner.get(owner) ?? new Map();
373
+ const site = graphNode.scopeSite ?? "";
374
+ sites.set(site, [...(sites.get(site) ?? []), node.id]);
375
+ scopedByOwner.set(owner, sites);
376
+ }
377
+ continue;
378
+ }
379
+ projectedId.set(graphNode.id, idOf(graphNode.manifest));
380
+ }
381
+ // A scoped node's owner is a call-graph id; translate it now that every
382
+ // resource node has one.
383
+ for (const node of nodes) {
384
+ if (node.ownership === "scoped" && node.owner) {
385
+ node.owner = projectedId.get(node.owner) ?? node.owner;
386
+ }
387
+ }
388
+ for (const [owner, sites] of [...scopedByOwner]) {
389
+ const translated = projectedId.get(owner);
390
+ if (translated && translated !== owner) {
391
+ scopedByOwner.delete(owner);
392
+ scopedByOwner.set(translated, sites);
393
+ }
394
+ }
395
+ // Inline children: the extraction stamps the parent and the path it was
396
+ // written at, so ownership is read off the declaration rather than guessed
397
+ // from a name pattern. The stamp names the parent by `(kind, name)`, so it is
398
+ // translated through the same table a call-graph id is.
399
+ const inlineByOwner = new Map();
400
+ for (const node of nodes) {
401
+ if (node.ownership !== "inline" || !node.owner)
402
+ continue;
403
+ node.owner = projectedId.get(node.owner) ?? node.owner;
404
+ const sites = inlineByOwner.get(node.owner) ?? new Map();
405
+ const site = node.ownerSite ?? "";
406
+ sites.set(site, [...(sites.get(site) ?? []), node.id]);
407
+ inlineByOwner.set(node.owner, sites);
408
+ }
409
+ for (const [owner, sites] of inlineByOwner) {
410
+ for (const [site, members] of sites) {
411
+ regions.push({ id: `${owner}#inline:${site}`, kind: "inline", owner, site, members });
412
+ }
413
+ }
414
+ for (const [owner, sites] of scopedByOwner) {
415
+ for (const [site, members] of sites) {
416
+ regions.push({ id: `${owner}#scope:${site}`, kind: "scope", owner, site, members });
417
+ }
418
+ }
419
+ // Execution zones: a region every dispatch inside runs within. Read from the
420
+ // containment walk rather than re-derived, so what the editor draws and what
421
+ // `telo check` enforces are the same region — including one declaring no
422
+ // attributes, which is still a zone.
423
+ for (const zone of findZoneProviders(callGraph, (kind, module) => deps.definition(kind, module))) {
424
+ const owner = projectedId.get(zone.provider.id) ?? zone.provider.id;
425
+ if (!byId.has(owner))
426
+ continue;
427
+ const members = [];
428
+ for (const [id, contained] of zone.contents) {
429
+ // A step is a ROW of its owner here, so a zone reaching one is a zone
430
+ // reaching the resource whose body declares it.
431
+ const memberId = contained.node.type === "step"
432
+ ? (projectedId.get(contained.node.owner) ?? contained.node.owner)
433
+ : (projectedId.get(id) ?? id);
434
+ if (memberId !== owner && byId.has(memberId) && !members.includes(memberId)) {
435
+ members.push(memberId);
436
+ }
437
+ }
438
+ const boundaries = zone.boundaries.map((b) => ({
439
+ from: projectedId.get(b.from.id) ?? b.from.id,
440
+ toName: b.edge.toName,
441
+ escaping: b.escaping,
442
+ }));
443
+ regions.push({
444
+ id: `${owner}#zone:${zone.slot}`,
445
+ kind: "zone",
446
+ owner,
447
+ site: zone.slot,
448
+ members,
449
+ attributes: zone.attributes,
450
+ ...(boundaries.length > 0 ? { boundaries } : {}),
451
+ });
452
+ }
453
+ // --- rows ------------------------------------------------------------------
454
+ // Steps come from the call graph, which owns the analyzer's only step-array
455
+ // recursion; entry lists and boot targets are read here, since neither is a
456
+ // step body and neither has a node of its own.
457
+ const callGraphIdByNode = invertProjectedIds(projectedId);
458
+ const callGraphIdOf = (nodeId) => callGraphIdByNode.get(nodeId) ?? nodeId;
459
+ for (const node of nodes) {
460
+ const manifest = node.root ? options.root : manifestById.get(node.id);
461
+ if (!manifest)
462
+ continue;
463
+ const definition = deps.definition(node.kind, node.module);
464
+ const schema = definition?.schema;
465
+ // The root's rows are its BOOT LIST and nothing else. `targets` carries the
466
+ // step grammar, so the call graph mints a step node for every entry that is
467
+ // not a bare `!ref` — and `targetRows` already renders every shape an entry
468
+ // takes, so collecting both listed an inline target twice.
469
+ node.rows = node.root
470
+ ? targetRows(node, manifest, rowIdByPath)
471
+ : [
472
+ ...stepRows(node, callGraph, callGraphIdOf(node.id), rowIdByPath),
473
+ ...entryRows(node, manifest, schema, rowIdByPath),
474
+ ];
475
+ if (!node.root)
476
+ node.rowArrays = declaredRowArrays(schema);
477
+ }
478
+ // --- ports and edges -------------------------------------------------------
479
+ for (const node of nodes) {
480
+ const manifest = node.root ? options.root : manifestById.get(node.id);
481
+ if (!manifest)
482
+ continue;
483
+ const definition = deps.definition(node.kind, node.module);
484
+ const schema = definition?.schema;
485
+ // A slot whose occupancy is DRAWN AS ROWS is not also a port: a route, a
486
+ // boot target and a step are manipulated as the ordered thing they are, and
487
+ // a second rendering of the same occupancy beside it is two controls for
488
+ // one fact. Read off the DECLARED arrays, not the rows: an empty `mounts`
489
+ // would otherwise be row-owned only once it had a mount in it, so a fresh
490
+ // server showed both a port and an add control for the same list.
491
+ const rowArrays = new Set(node.rowArrays.map((a) => a.field));
492
+ node.ports = buildPorts(manifest, deps, schema, rowArrays);
493
+ const throws = deps.throwsOf?.(manifest);
494
+ if (throws && (throws.codes.length > 0 || throws.unbounded))
495
+ node.throws = throws;
496
+ // A declaration written at a dispatch site hangs under the row that
497
+ // declares it — see `inlineRows`. After the ports, because a route's
498
+ // `handler:` is a port slot and its occupancy is what names the site; and
499
+ // woven rather than appended, so the body stays pre-order, which every
500
+ // consumer of `parent` relies on.
501
+ node.rows = weaveInlineRows(node, manifest, callGraph, callGraphIdOf(node.id), deps, rowIdByPath, inlineEdgeSeeds);
502
+ }
503
+ // Alias-qualified names, so a reference across an import boundary resolves.
504
+ // The call graph matches bare names — right for a name declared here, and the
505
+ // reason `!ref Console.writeLine` reached this pass as a dangling edge.
506
+ // Every row is known by now, so the per-owner index the longest-prefix walk
507
+ // needs is built once rather than re-scanned per edge.
508
+ const rowsByOwner = rowsByOwnerOf(rowIdByPath);
509
+ const byQualifiedName = new Map();
510
+ for (const node of nodes) {
511
+ if (!node.module)
512
+ continue;
513
+ for (const alias of deps.aliasesForModule(node.module)) {
514
+ const key = `${alias}.${node.name}`;
515
+ if (!byQualifiedName.has(key))
516
+ byQualifiedName.set(key, node.id);
517
+ }
518
+ }
519
+ // Edges come from the call graph — one per site, already resolved — re-keyed
520
+ // onto the boxes a view draws: a step's edge is attributed to the resource
521
+ // whose body declares it, with the row that declared it named, because a step
522
+ // is a row here rather than a node of its own.
523
+ for (const edge of callGraph.edges) {
524
+ const projected = projectEdge(edge, callGraph, byId, rowIdByPath, rowsByOwner, byQualifiedName, projectedId);
525
+ if (!projected)
526
+ continue;
527
+ // A reference leaving the module root IS a boot target — the root has no
528
+ // other slots — so the flag is stamped here rather than by a second pass
529
+ // over `targets`, which emitted a duplicate edge for every one of them.
530
+ if (root && projected.from === root.id)
531
+ projected.boot = true;
532
+ edges.push(projected);
533
+ }
534
+ // Data edges: one resource reading another's published state in CEL. Parsed,
535
+ // never scanned — `extractAccessChains` reads `resources.db.status.port` as a
536
+ // chain and a name inside a string literal as nothing, which a token scan
537
+ // cannot tell apart.
538
+ // A bare name resolves in the module that WROTE it — the call graph's own
539
+ // rule, shared rather than restated. Keeping a first-wins index here would
540
+ // have put every inline declaration's reference and every CEL state read back
541
+ // on whichever module happened to come first in the flattened list, which is
542
+ // the collision module-scoped identity exists to prevent.
543
+ const nodesByName = new Map();
544
+ for (const node of nodes) {
545
+ if (node.root)
546
+ continue;
547
+ nodesByName.set(node.name, [...(nodesByName.get(node.name) ?? []), node]);
548
+ }
549
+ const resolveName = (name, fromModule) => resolveScopedName(nodesByName.get(name), (node) => node.module, fromModule)?.id;
550
+ // References written INSIDE a declaration. Resolved here rather than where
551
+ // they were found, because a declaration may name a resource declared later
552
+ // in the file — and against the same name index every other edge uses, so a
553
+ // hold reached through an inline declaration counts exactly as one written at
554
+ // a named resource's own slot.
555
+ for (const [from, list] of inlineEdgeSeeds) {
556
+ const fromModule = byId.get(from)?.module;
557
+ for (const seed of list) {
558
+ const to = resolveName(seed.toName, fromModule) ?? byQualifiedName.get(seed.toName);
559
+ const edge = {
560
+ id: `${from}\0${seed.path}`,
561
+ from,
562
+ toName: seed.toName,
563
+ class: edgeClassOf(seed.uses),
564
+ use: seed.uses,
565
+ slot: seed.slot,
566
+ path: seed.path,
567
+ row: seed.rowId,
568
+ };
569
+ if (to)
570
+ edge.to = to;
571
+ edges.push(edge);
572
+ }
573
+ }
574
+ for (const node of nodes) {
575
+ const manifest = node.root ? options.root : manifestById.get(node.id);
576
+ if (!manifest)
577
+ continue;
578
+ edges.push(...dataEdges(node, manifest, node.module, resolveName, rowIdByPath, rowsByOwner));
579
+ }
580
+ // Where each row's call is WRITTEN, and what may fill it — see
581
+ // `GraphRow.dispatch`. Three shapes, because the grammar has three: a step's
582
+ // slot is declared on its item schema and reachable only through the step
583
+ // walk; an entry's is a row-owned port of the array it sits in; a boot target
584
+ // IS its own slot. All three are stated even when nothing fills them, since
585
+ // an empty site is exactly the one an editor has something to offer at.
586
+ for (const node of nodes) {
587
+ const stepSlots = new Map();
588
+ const stepSites = new Map();
589
+ for (const step of callGraph.steps(callGraphIdOf(node.id))) {
590
+ const first = step.refSlots?.[0];
591
+ if (first) {
592
+ stepSlots.set(step.path, {
593
+ path: first.path,
594
+ refs: first.kinds,
595
+ ...(first.inline ? { inline: true } : {}),
596
+ });
597
+ }
598
+ if (step.refSlots?.length) {
599
+ stepSites.set(step.path, step.refSlots.map((slot) => ({ path: slot.path, refs: slot.kinds })));
600
+ }
601
+ }
602
+ // Whether a port-derived site holds a declaration, by its concrete path.
603
+ const inlineAt = new Set(node.ports.flatMap((port) => port.slots.filter((s) => s.inline).map((s) => s.path)));
604
+ const rowOwnedPorts = node.ports.filter((port) => port.rowOwned);
605
+ for (const row of node.rows) {
606
+ if (row.kind === "step") {
607
+ const slot = stepSlots.get(row.path);
608
+ if (slot) {
609
+ row.dispatch = withAlternatives(slot, stepSites.get(row.path) ?? []);
610
+ }
611
+ continue;
612
+ }
613
+ if (row.kind === "target") {
614
+ const port = node.ports.find((p) => p.slot === `${row.array}[]`);
615
+ if (port) {
616
+ row.dispatch = withAlternatives({
617
+ path: row.path,
618
+ refs: port.refs,
619
+ ...(inlineAt.has(row.path) ? { inline: true } : {}),
620
+ },
621
+ // A boot target IS a step, and the step walk is what sees the sites
622
+ // the entry's own grammar declares — the bare reference the port
623
+ // reports is one spelling of one of them.
624
+ stepSites.get(row.path) ?? []);
625
+ }
626
+ continue;
627
+ }
628
+ if (row.kind !== "entry")
629
+ continue;
630
+ // `routes[].handler` → the handler of THIS route, whether or not one is
631
+ // written: the port's own slots list only the routes that have one.
632
+ const port = rowOwnedPorts.find((p) => containerArrayOf(p.slot) === row.array);
633
+ if (port) {
634
+ const path = `${row.path}.${port.slot.slice(port.slot.indexOf("[].") + 3)}`;
635
+ row.dispatch = {
636
+ path,
637
+ refs: port.refs,
638
+ ...(inlineAt.has(path) ? { inline: true } : {}),
639
+ };
640
+ }
641
+ }
642
+ }
643
+ // Back-fill what a row learns from the edge it declares: where its target
644
+ // resolved, and where this call's arguments are written. Both are the edge's
645
+ // to know — a row is read off the manifest, while `inputs` is a POINTER the
646
+ // slot declares and the target is a name the graph resolved — so they are
647
+ // stamped here rather than guessed twice.
648
+ const rowById = new Map();
649
+ for (const node of nodes)
650
+ for (const row of node.rows)
651
+ rowById.set(row.id, row);
652
+ for (const edge of edges) {
653
+ const row = edge.row ? rowById.get(edge.row) : undefined;
654
+ if (!row)
655
+ continue;
656
+ if (edge.to && row.targetNode === undefined)
657
+ row.targetNode = edge.to;
658
+ if (row.target === undefined)
659
+ row.target = edge.toName;
660
+ if (edge.inputs !== undefined && row.inputs === undefined) {
661
+ // The pointer is relative to the object ENCLOSING the slot, which for a
662
+ // step or an entry is the row itself.
663
+ row.inputs = `${row.path}${edge.inputs.replace(/\//g, ".")}`;
664
+ }
665
+ }
666
+ const fromIndex = new Map();
667
+ const toIndex = new Map();
668
+ for (const edge of edges) {
669
+ fromIndex.set(edge.from, [...(fromIndex.get(edge.from) ?? []), edge]);
670
+ if (edge.to)
671
+ toIndex.set(edge.to, [...(toIndex.get(edge.to) ?? []), edge]);
672
+ }
673
+ return {
674
+ root,
675
+ nodes,
676
+ edges,
677
+ regions,
678
+ kinds: buildKindPlane(resources, nodes, deps, options),
679
+ nodeById: (id) => byId.get(id),
680
+ edgesFrom: (id) => fromIndex.get(id) ?? [],
681
+ edgesTo: (id) => toIndex.get(id) ?? [],
682
+ };
683
+ }
684
+ /**
685
+ * The call-graph id a projected node came from — the reverse of `projectedId`.
686
+ *
687
+ * Built ONCE. Inverting the map per lookup was a linear scan inside three
688
+ * per-node loops, so a module of n boxes paid O(n²) three times over on every
689
+ * keystroke.
690
+ */
691
+ function invertProjectedIds(projectedId) {
692
+ const out = new Map();
693
+ for (const [callGraphId, projected] of projectedId) {
694
+ if (!out.has(projected))
695
+ out.set(projected, callGraphId);
696
+ }
697
+ return out;
698
+ }
699
+ function projectResource(id, manifest, deps, options) {
700
+ const module = moduleOf(manifest);
701
+ const kind = manifest.kind;
702
+ const definition = deps.definition(kind, module);
703
+ const origin = originOf(manifest);
704
+ const node = {
705
+ id,
706
+ kind,
707
+ name: manifest.metadata?.name,
708
+ ownership: "named",
709
+ ports: [],
710
+ rows: [],
711
+ rowArrays: [],
712
+ };
713
+ if (definition?.capability)
714
+ node.capability = definition.capability;
715
+ const canonical = canonicalKindOf(definition);
716
+ if (canonical && canonical !== kind)
717
+ node.canonicalKind = canonical;
718
+ if (!definition)
719
+ node.unknownKind = true;
720
+ if (module)
721
+ node.module = module;
722
+ if (origin) {
723
+ node.ownership = "inline";
724
+ node.owner = resourceId(origin.parentKind, origin.parentName);
725
+ node.ownerSite = origin.pathFromParent;
726
+ }
727
+ else if (isInjected(manifest)) {
728
+ node.ownership = "injected";
729
+ }
730
+ else if (isForwardedExport(manifest)) {
731
+ node.ownership = "imported";
732
+ }
733
+ // External is a fact about the DECLARING module, not about the ownership
734
+ // class: a library's own named resource forwarded into an app is `imported`,
735
+ // while a resource the app declares in an included partial is not — both are
736
+ // decided by the module stamp rather than by how the reference reached here.
737
+ if (options.entryModule && module && module !== options.entryModule) {
738
+ node.external = true;
739
+ // The alias the reference is WRITTEN with. Several may point at one module;
740
+ // the first is taken, because a boundary box needs one label and every
741
+ // alias designates the same module.
742
+ const alias = module ? deps.aliasesForModule(module)[0] : undefined;
743
+ if (alias)
744
+ node.alias = alias;
745
+ }
746
+ return node;
747
+ }
748
+ /** Step rows, from the call graph's step nodes. Depth and parent come from the
749
+ * nesting the call graph already recorded; identity is re-anchored on names. */
750
+ function stepRows(node, callGraph, callGraphId, rowIdByPath) {
751
+ const steps = callGraph.steps(callGraphId);
752
+ if (steps.length === 0)
753
+ return [];
754
+ const minter = new IdMinter();
755
+ const idByStepPath = new Map();
756
+ const rows = [];
757
+ for (const step of steps) {
758
+ const parentId = step.parent ? idByStepPath.get(step.parent) : undefined;
759
+ const anchor = parentId ? `${parentId}/` : `${node.id}#step:`;
760
+ const key = step.name ?? `@${contentKey(step.step)}`;
761
+ const id = minter.mint(`${anchor}${key}`);
762
+ idByStepPath.set(step.id, id);
763
+ rowIdByPath.set(`${node.id}\0${step.path}`, id);
764
+ const row = {
765
+ id,
766
+ kind: "step",
767
+ path: step.path,
768
+ array: step.array,
769
+ index: step.index,
770
+ depth: depthOf(step, callGraph, callGraphId),
771
+ ...(step.name !== undefined ? { name: step.name } : {}),
772
+ ...(step.variant !== undefined ? { variant: step.variant } : {}),
773
+ ...(step.variantLabel !== undefined ? { variantLabel: step.variantLabel } : {}),
774
+ ...(step.predicate !== undefined ? { predicate: step.predicate } : {}),
775
+ ...(parentId ? { parent: parentId } : {}),
776
+ };
777
+ rows.push(row);
778
+ }
779
+ return rows;
780
+ }
781
+ /**
782
+ * One dispatch, with the other ways its grammar lets it be written.
783
+ *
784
+ * Deduplicated by CONSTRAINT, not by path: two spellings accepting the same
785
+ * kinds are one site, and which of them to write is a choice a reader should
786
+ * never be asked to make (the primary is the plainer form). A spelling that
787
+ * accepts something the primary cannot is a site of its own, because it is the
788
+ * only address a reference to such a target could be written at.
789
+ */
790
+ function withAlternatives(primary, sites) {
791
+ const key = (refs) => [...refs].sort().join("\u0000");
792
+ const seen = new Set([key(primary.refs)]);
793
+ const alternatives = [];
794
+ for (const site of sites) {
795
+ if (site.path === primary.path || seen.has(key(site.refs)))
796
+ continue;
797
+ seen.add(key(site.refs));
798
+ alternatives.push(site);
799
+ }
800
+ return alternatives.length > 0 ? { ...primary, alternatives } : primary;
801
+ }
802
+ /**
803
+ * The rows and edges a DECLARATION written at a dispatch site contributes.
804
+ *
805
+ * `invoke: { kind: Sql.Command, connection: !ref chatDb }` is a resource the
806
+ * manifest genuinely declares, and until now the graph could see none of it: no
807
+ * node, no edge, and a step row identical to one that dispatches nothing. The
808
+ * hold was invisible too, so a connection reached only from inside inline
809
+ * declarations was reported as referenced by nothing.
810
+ *
811
+ * What is emitted is one row for the declaration — named by its kind, addressed
812
+ * at the site, so it can be opened and edited where it was written — and one row
813
+ * per reference it fills, each carrying a real edge. That is what puts the hold
814
+ * back on the graph, and it is why these are rows rather than a label: a
815
+ * reference needs somewhere for its line to leave from.
816
+ *
817
+ * Recursive, because a declaration may hold another; bounded by the manifest,
818
+ * which cannot contain itself.
819
+ */
820
+ function inlineRows(node, site, host, deps, rowIdByPath, out) {
821
+ const kind = site.value.kind;
822
+ const declared = deps.definition(kind, node.module);
823
+ const id = `${host.rowId}/${lastPathSegment(site.path)}`;
824
+ const row = {
825
+ id,
826
+ kind: "inline",
827
+ path: site.path,
828
+ array: host.array,
829
+ index: 0,
830
+ depth: host.depth + 1,
831
+ parent: host.rowId,
832
+ declares: kind,
833
+ ...(declared ? {} : { unknownKind: true }),
834
+ };
835
+ out.rows.push(row);
836
+ rowIdByPath.set(`${node.id}\0${site.path}`, id);
837
+ // The declaration's own reference slots, read through its kind's field map —
838
+ // the same map a named resource's ports come from, so an inline declaration
839
+ // and an extracted one describe themselves identically.
840
+ const asManifest = { ...site.value, metadata: { name: id } };
841
+ const declaredSchema = declared?.schema;
842
+ for (const field of deps.refFields(asManifest)) {
843
+ for (const entry of resolveFieldEntries(asManifest, field.path)) {
844
+ const path = `${site.path}.${entry.path}`;
845
+ if (isInlineDeclaration(entry.value)) {
846
+ inlineRows(node, { path, value: entry.value }, { rowId: id, array: host.array, depth: row.depth, slot: `${host.slot}.${field.path}` }, deps, rowIdByPath, out);
847
+ continue;
848
+ }
849
+ const target = refName(entry.value);
850
+ if (target === undefined)
851
+ continue;
852
+ const refId = `${id}/${lastPathSegment(entry.path)}`;
853
+ out.rows.push({
854
+ id: refId,
855
+ kind: "reference",
856
+ name: lastPathSegment(field.path),
857
+ path,
858
+ array: host.array,
859
+ index: 0,
860
+ depth: row.depth + 1,
861
+ parent: id,
862
+ target,
863
+ });
864
+ rowIdByPath.set(`${node.id}\0${path}`, refId);
865
+ out.edges.push({
866
+ rowId: refId,
867
+ toName: target,
868
+ // The slot the OWNER declares, so the branch this edge leaves is the
869
+ // host's own property — what decides whether it is drawn at all.
870
+ slot: `${host.slot}.${field.path}`,
871
+ path,
872
+ // Read off the DECLARED kind's own schema, exactly as a port's is —
873
+ // `use` is a property of the slot, and the slot belongs to the kind
874
+ // written here rather than to the resource hosting it.
875
+ uses: readUses(schemaAt(declaredSchema, field.path)),
876
+ });
877
+ }
878
+ }
879
+ }
880
+ /**
881
+ * The body with each declaration's rows woven in beneath the row that declares
882
+ * it, keeping the whole list pre-order.
883
+ *
884
+ * Pre-order is not a nicety: every consumer of `parent` — the tree's visibility
885
+ * walk, the geometry, the renderer — settles a parent's verdict before it asks
886
+ * about a child, and appending these at the end would silently break all three.
887
+ *
888
+ * Sites come from two places and neither is optional. A STEP's dispatch slot is
889
+ * recorded by the call graph, which is the only walk that reaches a step's item
890
+ * schema; every other slot — a route's `handler:`, a `mounts[].mount` — is an
891
+ * ordinary field-map entry and is found here.
892
+ */
893
+ function weaveInlineRows(node, manifest, callGraph, callGraphId, deps, rowIdByPath, seeds) {
894
+ /**
895
+ * Sites keyed by their concrete path, because the two walks OVERLAP: a step's
896
+ * `invoke:` is both a step dispatch slot and a row-owned port slot, so
897
+ * collecting them into a list emitted every declaration under a step twice —
898
+ * two rows sharing one id, and two copies of every edge inside it.
899
+ */
900
+ // This node's rows as they stand before any declaration is woven in — which
901
+ // is what a site can be hosted BY. Scoped to the node rather than scanning
902
+ // every row in the module, and taken once because the weave only ADDS rows
903
+ // below the ones a site could already have named.
904
+ const ownRows = rowsByOwnerOf(rowIdByPath).get(node.id) ?? [];
905
+ const sites = new Map();
906
+ const record = (rowId, path, value, slot) => {
907
+ if (!rowId || sites.has(path) || !isInlineDeclaration(value))
908
+ return;
909
+ sites.set(path, { rowId, path, value: value, slot });
910
+ };
911
+ for (const step of callGraph.steps(callGraphId)) {
912
+ for (const site of (step.refSlots ?? []).filter((slot) => slot.inline)) {
913
+ const rowId = rowIdByPath.get(`${node.id}\0${step.path}`);
914
+ if (!rowId)
915
+ continue;
916
+ record(rowId, site.path, step.step[site.key], `${step.array}[].${site.key}`);
917
+ }
918
+ }
919
+ for (const port of node.ports) {
920
+ if (!port.slots.some((slot) => slot.inline))
921
+ continue;
922
+ for (const entry of resolveFieldEntries(manifest, port.slot)) {
923
+ // A site on a slot no row owns — a plain `connection:` on a resource — is
924
+ // left to the port, which already draws it. Only a ROW can host a subtree.
925
+ const rowId = rowIdByPath.get(`${node.id}\0${entry.path}`) ??
926
+ rowAt(new Map([[node.id, ownRows]]), node.id, entry.path);
927
+ if (!rowId)
928
+ continue;
929
+ record(rowId, entry.path, entry.value, port.slot);
930
+ }
931
+ }
932
+ if (sites.size === 0)
933
+ return node.rows;
934
+ const byRow = new Map();
935
+ for (const site of sites.values()) {
936
+ byRow.set(site.rowId, [...(byRow.get(site.rowId) ?? []), site]);
937
+ }
938
+ const out = [];
939
+ for (const row of node.rows) {
940
+ out.push(row);
941
+ for (const site of byRow.get(row.id) ?? []) {
942
+ const collected = { rows: [], edges: [] };
943
+ inlineRows(node, { path: site.path, value: site.value }, { rowId: row.id, array: row.array, depth: row.depth, slot: site.slot }, deps, rowIdByPath, collected);
944
+ out.push(...collected.rows);
945
+ if (collected.edges.length > 0) {
946
+ seeds.set(node.id, [...(seeds.get(node.id) ?? []), ...collected.edges]);
947
+ }
948
+ }
949
+ }
950
+ return out;
951
+ }
952
+ /** `steps[0].invoke.connection` → `connection`; `routes[1]` → `routes`. */
953
+ function lastPathSegment(path) {
954
+ const last = path.split(".").pop() ?? path;
955
+ return last.replace(/\[\d+\]$/, "").replace(/\[\]$|\{\}$/, "");
956
+ }
957
+ /** Nesting depth of a step: how many step parents stand above it. */
958
+ function depthOf(step, callGraph, ownerId) {
959
+ let depth = 0;
960
+ let current = step;
961
+ const byId = new Map(callGraph.steps(ownerId).map((s) => [s.id, s]));
962
+ while (current?.parent) {
963
+ depth++;
964
+ current = byId.get(current.parent);
965
+ }
966
+ return depth;
967
+ }
968
+ /** Entry rows: one per item of an `x-telo-topology-role: entries` array. The
969
+ * matcher fields are what identifies an entry to a reader, so they are also
970
+ * what its identity is derived from — a route keeps its identity when a route
971
+ * is inserted above it, and loses it only when its own path or method change,
972
+ * which is what makes it a different route. */
973
+ function entryRows(node, manifest, schema, rowIdByPath) {
974
+ const rows = [];
975
+ for (const spec of entryListsOf(schema)) {
976
+ const value = manifest[spec.field];
977
+ if (!Array.isArray(value))
978
+ continue;
979
+ const minter = new IdMinter();
980
+ value.forEach((item, index) => {
981
+ const entry = (item ?? {});
982
+ // What IDENTIFIES an entry to a reader is the scalars its matcher holds —
983
+ // a path and a method — not the whole matcher, which for an HTTP route
984
+ // also carries the request schema. Taking the schema would put a row's
985
+ // identity at the mercy of an edit to a property it does not show, so a
986
+ // reader loses their selection by editing something else entirely.
987
+ const match = scalarLeaves(Object.fromEntries(spec.matchers.filter((m) => entry[m] !== undefined).map((m) => [m, entry[m]])));
988
+ const key = Object.keys(match).length > 0 ? contentKey(match) : contentKey(entry);
989
+ const path = `${spec.field}[${index}]`;
990
+ const id = minter.mint(`${node.id}#entry:${spec.field}/${key}`);
991
+ rowIdByPath.set(`${node.id}\0${path}`, id);
992
+ const handlerField = spec.handlers.find((h) => entry[h] !== undefined);
993
+ const target = handlerField ? refName(entry[handlerField]) : undefined;
994
+ const catches = spec.errorBranches.some((b) => {
995
+ const value = entry[b];
996
+ return Array.isArray(value) ? value.length > 0 : value !== undefined;
997
+ });
998
+ rows.push({
999
+ id,
1000
+ kind: "entry",
1001
+ path,
1002
+ array: spec.field,
1003
+ index,
1004
+ depth: 0,
1005
+ ...(Object.keys(match).length > 0 ? { match } : {}),
1006
+ ...(target !== undefined ? { target } : {}),
1007
+ ...(catches ? { catches: true } : {}),
1008
+ });
1009
+ });
1010
+ }
1011
+ return rows;
1012
+ }
1013
+ /**
1014
+ * The scalar leaves of a value, flattened to one map, to a bounded depth.
1015
+ *
1016
+ * A matcher is whatever the kind declared it to be: a flat `path` / `method`
1017
+ * pair on one router, a nested `request:` object on another. Reading the scalars
1018
+ * out of it works for both without naming either — and stopping at scalars is
1019
+ * what keeps a nested JSON Schema (which is an object all the way down) out of
1020
+ * something a reader is meant to recognize the row by.
1021
+ */
1022
+ function scalarLeaves(value, depth = 0) {
1023
+ const out = {};
1024
+ if (depth > 2 || !value || typeof value !== "object" || Array.isArray(value))
1025
+ return out;
1026
+ for (const [key, child] of Object.entries(value)) {
1027
+ if (child === null)
1028
+ continue;
1029
+ if (typeof child !== "object")
1030
+ out[key] = child;
1031
+ else
1032
+ Object.assign(out, scalarLeaves(child, depth + 1));
1033
+ }
1034
+ return out;
1035
+ }
1036
+ /**
1037
+ * The ordered arrays a kind declares — its entry lists and its step bodies.
1038
+ *
1039
+ * Both are found by annotation (`x-telo-topology-role: entries`, and the shared
1040
+ * step-body stamp), so a third-party composer's list is offered the same
1041
+ * affordances as `Http.Api`'s routes with no editor change.
1042
+ */
1043
+ function declaredRowArrays(schema) {
1044
+ const out = [];
1045
+ for (const spec of entryListsOf(schema))
1046
+ out.push({ field: spec.field, kind: "entry" });
1047
+ for (const [key, propSchema] of propertySchemas(schema ?? {})) {
1048
+ if (isStepSlot(propSchema))
1049
+ out.push({ field: key, kind: "step" });
1050
+ }
1051
+ return out;
1052
+ }
1053
+ /** Boot rows: the root's `targets`, which is an ordered step list — a later
1054
+ * target reads an earlier one's result — so it is rows, not a set. */
1055
+ function targetRows(node, manifest, rowIdByPath) {
1056
+ const targets = manifest.targets;
1057
+ if (!Array.isArray(targets))
1058
+ return [];
1059
+ const minter = new IdMinter();
1060
+ return targets.map((entry, index) => {
1061
+ const record = (entry ?? {});
1062
+ const target = refName(entry) ?? refName(record.ref) ?? refName(record.invoke) ?? undefined;
1063
+ const name = typeof record.name === "string" ? record.name : undefined;
1064
+ const key = name ?? target ?? `@${contentKey(entry)}`;
1065
+ const path = `targets[${index}]`;
1066
+ const id = minter.mint(`${node.id}#target:${key}`);
1067
+ rowIdByPath.set(`${node.id}\0${path}`, id);
1068
+ return {
1069
+ id,
1070
+ kind: "target",
1071
+ path,
1072
+ array: "targets",
1073
+ index,
1074
+ depth: 0,
1075
+ ...(name !== undefined ? { name } : {}),
1076
+ ...(target !== undefined ? { target } : {}),
1077
+ // A boot target's shapes carry no branch titles, so there is no variant
1078
+ // to report — but a GATED one is the same fact a step's `when:` is, and
1079
+ // a target drawn without its guard says it always runs.
1080
+ ...(guardOf(record) !== undefined ? { predicate: guardOf(record) } : {}),
1081
+ };
1082
+ });
1083
+ }
1084
+ /** The `when:` guard on a boot target, as written. */
1085
+ function guardOf(entry) {
1086
+ const written = entry.when;
1087
+ if (typeof written === "string")
1088
+ return written;
1089
+ if (written && typeof written === "object") {
1090
+ const source = written.source;
1091
+ if (typeof source === "string")
1092
+ return source;
1093
+ }
1094
+ return undefined;
1095
+ }
1096
+ /** Every declared reference slot as a port, with its occupancy read off the
1097
+ * manifest — so an empty slot is a port with no filled sites rather than an
1098
+ * absence a view has to infer. */
1099
+ function buildPorts(manifest, deps, schema, rowArrays) {
1100
+ const fields = deps.refFields(manifest);
1101
+ // The `anyOf` sub-shapes of one array-of-refs are ONE slot, not three. A boot
1102
+ // target may be written bare, as `{ref, when}` or as an inline invoke step, so
1103
+ // the field map lists `targets[]`, `targets[].ref` and `targets[].invoke` —
1104
+ // rendering each as its own port offers three sockets for one position and
1105
+ // says the module has slots it does not have.
1106
+ const arrayRefBases = new Set(fields.filter((f) => isArrayOfRefs(f.path)).map((f) => arrayBaseOf(f.path)));
1107
+ const ports = [];
1108
+ for (const field of fields) {
1109
+ if ([...arrayRefBases].some((base) => field.path.startsWith(`${base}[].`)))
1110
+ continue;
1111
+ const slotSchema = schemaAt(schema, field.path);
1112
+ const uses = readUses(slotSchema);
1113
+ const slots = [];
1114
+ for (const { value, path } of resolveFieldEntries(manifest, field.path)) {
1115
+ const target = refName(value);
1116
+ const slot = { path };
1117
+ if (target !== undefined)
1118
+ slot.target = target;
1119
+ // A slot holding a declaration rather than a reference is FILLED, and a
1120
+ // view that reads only `target` would draw it as an empty socket — the
1121
+ // one reading that is wrong in both directions, since it invites filling
1122
+ // a slot that is already occupied.
1123
+ else if (isInlineDeclaration(value))
1124
+ slot.inline = true;
1125
+ slots.push(slot);
1126
+ }
1127
+ // **An unwritten slot still has a write site.** Resolving the manifest for
1128
+ // `notFoundHandler.invoke` on a server that declares no `notFoundHandler`
1129
+ // yields nothing, so the port had no path at all — it rendered as an empty
1130
+ // socket that could not be filled, which is worse than not drawing it: it
1131
+ // offers an affordance and then refuses. The path IS the site for a slot in
1132
+ // no array, so it is synthesized here rather than left to every consumer to
1133
+ // reconstruct.
1134
+ if (slots.length === 0 && !field.path.includes("[]") && !field.path.includes("{}")) {
1135
+ slots.push({ path: field.path });
1136
+ }
1137
+ const port = {
1138
+ slot: field.path,
1139
+ refs: field.refs,
1140
+ capabilities: field.capabilities,
1141
+ array: field.isArray,
1142
+ class: edgeClassOf(uses),
1143
+ slots,
1144
+ };
1145
+ const append = appendPathFor(field.path, manifest);
1146
+ if (append)
1147
+ port.addPath = append;
1148
+ if (rowArrays.has(containerArrayOf(field.path)))
1149
+ port.rowOwned = true;
1150
+ ports.push(port);
1151
+ }
1152
+ return ports;
1153
+ }
1154
+ /** A top-level array of direct refs (`targets[]`): the trailing `[]` is the
1155
+ * path's only marker. */
1156
+ function isArrayOfRefs(path) {
1157
+ return path.endsWith("[]") && !path.slice(0, -2).match(/\[\]|\{\}/);
1158
+ }
1159
+ /** `targets[]` → `targets`. */
1160
+ function arrayBaseOf(path) {
1161
+ return path.slice(0, -2);
1162
+ }
1163
+ /**
1164
+ * Where a NEW occupancy of this slot would be written.
1165
+ *
1166
+ * Both array shapes reach here: a direct array of refs (`targets[]` →
1167
+ * `targets[2]`) and a ref inside an array of objects (`mounts[].mount` →
1168
+ * `mounts[2].mount`). The second was missing, so an `Http.Server` with no mounts
1169
+ * offered no way to add one — the port drew an empty rail and the drag had
1170
+ * nowhere to land. Undefined for a slot in no array, and for one nested past a
1171
+ * single array, where the index of the outer item is not determined by the slot
1172
+ * alone.
1173
+ */
1174
+ function appendPathFor(path, manifest) {
1175
+ const marker = path.indexOf("[]");
1176
+ if (marker === -1)
1177
+ return undefined;
1178
+ const array = path.slice(0, marker);
1179
+ const suffix = path.slice(marker + 2);
1180
+ if (array.includes("{}") || suffix.includes("[]") || suffix.includes("{}"))
1181
+ return undefined;
1182
+ const existing = manifest[array];
1183
+ return `${array}[${Array.isArray(existing) ? existing.length : 0}]${suffix}`;
1184
+ }
1185
+ /** The array a slot's occupancy sits in (`routes[].handler` → `routes`,
1186
+ * `targets[]` → `targets`), or the path itself when it is in no array. */
1187
+ function containerArrayOf(path) {
1188
+ const marker = path.indexOf("[]");
1189
+ return marker === -1 ? path : path.slice(0, marker);
1190
+ }
1191
+ /**
1192
+ * Declared uses at a slot, through the annotation's ONE reader.
1193
+ *
1194
+ * It used to hand-parse `slotSchema["x-telo-ref"]`, which sees nothing when the
1195
+ * annotation sits in a `oneOf` branch — the sanctioned shape for a slot that
1196
+ * unions a value with a reference. A column's `type:` is exactly that, so its
1197
+ * `use: schema` read as no declared use at all and the slot was classed (and
1198
+ * drawn) as a control transfer. `readRefSlot` unions the branches; `possibleUses`
1199
+ * folds a case map's arms in, which is what a PORT wants: the port describes the
1200
+ * slot, and which arm holds is decided per site by the call graph.
1201
+ */
1202
+ function readUses(slotSchema) {
1203
+ const slot = readRefSlot(slotSchema);
1204
+ return slot ? possibleUses(slot) : [];
1205
+ }
1206
+ /** Re-key one call-graph edge onto the boxes a view draws. A step's edge is
1207
+ * attributed to the resource whose body declares it — a step is a row here,
1208
+ * not a node — with the row named so the edge can dock onto it. */
1209
+ function projectEdge(edge, callGraph, byId, rowIdByPath, rowsByOwner, byQualifiedName, projectedId) {
1210
+ const source = callGraph.nodes.get(edge.from);
1211
+ const rawFrom = source?.type === "step" ? source.owner : edge.from;
1212
+ const fromId = projectedId.get(rawFrom) ?? rawFrom;
1213
+ if (!byId.has(fromId))
1214
+ return undefined;
1215
+ const projected = {
1216
+ id: `${fromId}\0${edge.slot}\0${edge.path}`,
1217
+ from: fromId,
1218
+ toName: edge.toName,
1219
+ class: edgeClassOf(edge.use),
1220
+ use: edge.use,
1221
+ slot: edge.slot,
1222
+ path: edge.path,
1223
+ };
1224
+ const to = edge.to ? (projectedId.get(edge.to) ?? edge.to) : undefined;
1225
+ if (to && byId.has(to))
1226
+ projected.to = to;
1227
+ else {
1228
+ const qualified = byQualifiedName.get(edge.toName);
1229
+ if (qualified)
1230
+ projected.to = qualified;
1231
+ }
1232
+ if (edge.inputs !== undefined)
1233
+ projected.inputs = edge.inputs;
1234
+ if (edge.scoped)
1235
+ projected.scoped = true;
1236
+ // The row an edge leaves from: the step that declares it, or the entry whose
1237
+ // handler slot holds it. Longest-prefix on the concrete path, so a site
1238
+ // nested inside a branch docks onto the row that actually declares it.
1239
+ const row = rowIdByPath.get(`${fromId}\0${edge.path}`) ?? rowAt(rowsByOwner, fromId, edge.path);
1240
+ if (row)
1241
+ projected.row = row;
1242
+ return projected;
1243
+ }
1244
+ /** The row whose path is the longest prefix of a site's path. */
1245
+ function rowAt(rowsByOwner, ownerId, path) {
1246
+ let best;
1247
+ let bestLength = -1;
1248
+ for (const row of rowsByOwner.get(ownerId) ?? []) {
1249
+ const inside = path.startsWith(`${row.path}.`) || path.startsWith(`${row.path}[`);
1250
+ if (inside && row.path.length > bestLength) {
1251
+ best = row.id;
1252
+ bestLength = row.path.length;
1253
+ }
1254
+ }
1255
+ return best;
1256
+ }
1257
+ /**
1258
+ * The rows each box owns, by owner — so finding the row a nested site sits in
1259
+ * is a scan of one box's rows rather than of every row in the module.
1260
+ *
1261
+ * The flat `<owner>\0<path>` map is the right shape for an exact hit and the
1262
+ * wrong one for the longest-prefix walk, which is the COMMON case: a step's ref
1263
+ * is nested inside the step, so the exact lookup misses and the fallback ran
1264
+ * over every row of every box, for every edge and every CEL chain.
1265
+ */
1266
+ function rowsByOwnerOf(rowIdByPath) {
1267
+ const out = new Map();
1268
+ for (const [key, id] of rowIdByPath) {
1269
+ // The LAST separator: a node id contains NULs of its own (`kind\0name`, and
1270
+ // `module\0kind\0name` across a boundary) while a concrete path contains
1271
+ // none, so splitting at the first one takes the kind for the owner and
1272
+ // leaves the name glued to the path — an index that matches nothing.
1273
+ const marker = key.lastIndexOf("\0");
1274
+ if (marker === -1)
1275
+ continue;
1276
+ const owner = key.slice(0, marker);
1277
+ out.set(owner, [...(out.get(owner) ?? []), { path: key.slice(marker + 1), id }]);
1278
+ }
1279
+ return out;
1280
+ }
1281
+ /** Kinds a definition body declares — the marks of a template rather than a
1282
+ * controller-backed kind. */
1283
+ const TEMPLATE_FIELDS = ["resources", "invoke", "run", "provide"];
1284
+ /**
1285
+ * The kind plane: every `Telo.Definition` / `Telo.Abstract` in scope, with its
1286
+ * lineage and the instances that were declared of it.
1287
+ *
1288
+ * Built from the same manifest list the instance plane skips them from, so a
1289
+ * kind-only library — one whose whole content is declarations — has a plane to
1290
+ * render rather than an empty canvas.
1291
+ */
1292
+ function buildKindPlane(resources, nodes, deps, options) {
1293
+ const exportedKinds = new Set((options.root?.exports?.kinds ?? []).filter((k) => typeof k === "string"));
1294
+ // Keyed on the CANONICAL kind, because that is what a kind's own id is: an
1295
+ // instance a library declared as `kind: Self.WriteLine` belongs to
1296
+ // `console.WriteLine`, and keying on the written spelling gave every such kind
1297
+ // an empty instance list.
1298
+ const instancesByKind = new Map();
1299
+ for (const node of nodes) {
1300
+ if (node.root)
1301
+ continue;
1302
+ const key = node.canonicalKind ?? node.kind;
1303
+ instancesByKind.set(key, [...(instancesByKind.get(key) ?? []), node.id]);
1304
+ }
1305
+ const out = [];
1306
+ for (const manifest of resources) {
1307
+ const docKind = manifest.kind;
1308
+ if (docKind !== "Telo.Definition" && docKind !== "Telo.Abstract")
1309
+ continue;
1310
+ const name = manifest.metadata?.name;
1311
+ if (!name)
1312
+ continue;
1313
+ const module = moduleOf(manifest);
1314
+ const id = module ? `${module}.${name}` : name;
1315
+ const record = manifest;
1316
+ const extendsName = typeof record.extends === "string" ? record.extends : undefined;
1317
+ const parent = extendsName ? deps.definition(extendsName, module) : undefined;
1318
+ const parentModule = parent ? moduleOf(parent) : undefined;
1319
+ const parentName = parent?.metadata?.name;
1320
+ const kind = {
1321
+ id,
1322
+ name,
1323
+ abstract: docKind === "Telo.Abstract",
1324
+ instances: instancesByKind.get(id) ?? [],
1325
+ template: TEMPLATE_FIELDS.some((f) => record[f] !== undefined),
1326
+ own: !!options.entryModule && module === options.entryModule,
1327
+ };
1328
+ if (module)
1329
+ kind.module = module;
1330
+ if (typeof record.capability === "string")
1331
+ kind.capability = record.capability;
1332
+ if (extendsName)
1333
+ kind.extendsName = extendsName;
1334
+ if (parent && parentName)
1335
+ kind.extendsId = parentModule ? `${parentModule}.${parentName}` : parentName;
1336
+ // Only the entry module's gate is in hand — an imported library's
1337
+ // `exports.kinds` is stamped on the import, not on the definition, so a
1338
+ // claim about it here would be a guess.
1339
+ if (kind.own)
1340
+ kind.exported = exportedKinds.has(name);
1341
+ out.push(kind);
1342
+ }
1343
+ return out;
1344
+ }
1345
+ /**
1346
+ * Every `resources.<name>…` read in one resource's CEL, as an edge.
1347
+ *
1348
+ * This is the dependency a manifest states without a slot: a config provider
1349
+ * read by five resources has five edges the reference graph cannot show, and an
1350
+ * observed-state read is the same shape one level in. Deduplicated per
1351
+ * (target, chain), since the same read at two sites is one fact about the pair.
1352
+ */
1353
+ function dataEdges(node, manifest, fromModule, resolveName, rowIdByPath, rowsByOwner) {
1354
+ const out = [];
1355
+ const seen = new Set();
1356
+ walkCelExpressions(manifest, "", (source, path) => {
1357
+ for (const chain of accessChains(source)) {
1358
+ if (chain[0] !== "resources" || chain.length < 2)
1359
+ continue;
1360
+ const targetName = chain[1];
1361
+ // `resources.<name>` is a bare name written in THIS module's scope, so it
1362
+ // resolves the way every other bare name does.
1363
+ const to = resolveName(targetName, fromModule);
1364
+ if (!to || to === node.id)
1365
+ continue;
1366
+ const read = chain.join(".");
1367
+ const key = `${to}\0${read}`;
1368
+ if (seen.has(key))
1369
+ continue;
1370
+ seen.add(key);
1371
+ const edge = {
1372
+ id: `${node.id}\0data\0${path}\0${read}`,
1373
+ from: node.id,
1374
+ to,
1375
+ toName: targetName,
1376
+ class: "data",
1377
+ use: [],
1378
+ slot: "cel",
1379
+ path,
1380
+ read,
1381
+ };
1382
+ const row = rowIdByPath.get(`${node.id}\0${path}`) ?? rowAt(rowsByOwner, node.id, path);
1383
+ if (row)
1384
+ edge.row = row;
1385
+ out.push(edge);
1386
+ }
1387
+ });
1388
+ return out;
1389
+ }