@telorun/analyzer 0.66.0 → 0.67.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 (76) hide show
  1. package/dist/analyzer.d.ts.map +1 -1
  2. package/dist/analyzer.js +37 -2
  3. package/dist/builtins.d.ts.map +1 -1
  4. package/dist/builtins.js +67 -16
  5. package/dist/cel-scope.d.ts +8 -0
  6. package/dist/cel-scope.d.ts.map +1 -1
  7. package/dist/cel-scope.js +66 -8
  8. package/dist/definition-registry.d.ts +17 -0
  9. package/dist/definition-registry.d.ts.map +1 -1
  10. package/dist/definition-registry.js +35 -0
  11. package/dist/dependency-graph.d.ts.map +1 -1
  12. package/dist/dependency-graph.js +65 -0
  13. package/dist/flatten-for-analyzer.d.ts +36 -0
  14. package/dist/flatten-for-analyzer.d.ts.map +1 -1
  15. package/dist/flatten-for-analyzer.js +103 -4
  16. package/dist/index.d.ts +4 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +3 -2
  19. package/dist/inline-imports.d.ts.map +1 -1
  20. package/dist/inline-imports.js +1 -0
  21. package/dist/manifest-visitor.d.ts +4 -0
  22. package/dist/manifest-visitor.d.ts.map +1 -1
  23. package/dist/manifest-visitor.js +28 -0
  24. package/dist/precompile.d.ts.map +1 -1
  25. package/dist/precompile.js +8 -0
  26. package/dist/resolve-ref-sentinels.d.ts.map +1 -1
  27. package/dist/resolve-ref-sentinels.js +14 -1
  28. package/dist/resource-input.d.ts +75 -0
  29. package/dist/resource-input.d.ts.map +1 -0
  30. package/dist/resource-input.js +90 -0
  31. package/dist/schema-projection.d.ts +13 -0
  32. package/dist/schema-projection.d.ts.map +1 -1
  33. package/dist/schema-projection.js +7 -0
  34. package/dist/system-kinds.d.ts +7 -2
  35. package/dist/system-kinds.d.ts.map +1 -1
  36. package/dist/system-kinds.js +7 -2
  37. package/dist/telo-version.d.ts +1 -1
  38. package/dist/telo-version.js +1 -1
  39. package/dist/template-body.d.ts +50 -0
  40. package/dist/template-body.d.ts.map +1 -0
  41. package/dist/template-body.js +58 -0
  42. package/dist/validate-cel-context.d.ts.map +1 -1
  43. package/dist/validate-cel-context.js +68 -8
  44. package/dist/validate-identifier-names.d.ts.map +1 -1
  45. package/dist/validate-identifier-names.js +17 -2
  46. package/dist/validate-references.d.ts +17 -0
  47. package/dist/validate-references.d.ts.map +1 -1
  48. package/dist/validate-references.js +68 -16
  49. package/dist/validate-resource-inputs.d.ts +35 -0
  50. package/dist/validate-resource-inputs.d.ts.map +1 -0
  51. package/dist/validate-resource-inputs.js +319 -0
  52. package/dist/validate-template-dispatch.d.ts +27 -0
  53. package/dist/validate-template-dispatch.d.ts.map +1 -0
  54. package/dist/validate-template-dispatch.js +95 -0
  55. package/package.json +3 -3
  56. package/src/analyzer.ts +45 -2
  57. package/src/builtins.ts +69 -16
  58. package/src/cel-scope.ts +90 -14
  59. package/src/definition-registry.ts +36 -0
  60. package/src/dependency-graph.ts +66 -0
  61. package/src/flatten-for-analyzer.ts +116 -3
  62. package/src/index.ts +12 -0
  63. package/src/inline-imports.ts +1 -0
  64. package/src/manifest-visitor.ts +33 -0
  65. package/src/precompile.ts +8 -0
  66. package/src/resolve-ref-sentinels.ts +12 -1
  67. package/src/resource-input.ts +132 -0
  68. package/src/schema-projection.ts +19 -0
  69. package/src/system-kinds.ts +7 -2
  70. package/src/telo-version.ts +1 -1
  71. package/src/template-body.ts +104 -0
  72. package/src/validate-cel-context.ts +67 -7
  73. package/src/validate-identifier-names.ts +18 -3
  74. package/src/validate-references.ts +70 -14
  75. package/src/validate-resource-inputs.ts +367 -0
  76. package/src/validate-template-dispatch.ts +99 -0
@@ -18,11 +18,53 @@ import type { DefinitionRegistry } from "./definition-registry.js";
18
18
  const SOURCE = "telo-analyzer";
19
19
 
20
20
  /**
21
- * Checks whether `kind` satisfies the ref constraint in `entry`.
22
- * Returns an empty array when valid, or mismatch error strings when not.
23
- * Returns an empty array immediately when the ref identity is not registered
24
- * (partial contextskip check rather than false-positive).
21
+ * Liskov substitutability at a kind constraint: is `resolved` (a canonical
22
+ * `<module>.<Kind>`) accepted where `targetKind` is required?
23
+ *
24
+ * THE one implementation `checkKind` below builds a MESSAGE from it and adds
25
+ * nothing to the rule, so a resource input's injection site and an ordinary ref
26
+ * slot cannot come to disagree about what satisfies a constraint.
27
+ *
28
+ * A value satisfies the slot when it transitively extends the target kind, or —
29
+ * for a CONCRETE target — IS that kind; `getByExtends` is the same transitive
30
+ * subtype index for both, and an abstract is satisfied only by an implementer,
31
+ * never by the abstract itself (which is non-instantiable). Accepts a constraint
32
+ * that resolves to nothing, and an abstract with no loaded implementations:
33
+ * partial context, where a rejection would be a guess.
25
34
  */
35
+ export function kindSatisfies(
36
+ resolved: string,
37
+ targetKind: string,
38
+ registry: DefinitionRegistry,
39
+ ): boolean {
40
+ const canonical = registry.resolveRef(targetKind) ?? targetKind;
41
+ const targetDef = registry.resolve(canonical);
42
+ if (!targetDef) return true;
43
+ if (targetDef.kind !== "Telo.Abstract" && resolved === canonical) return true;
44
+ const subtypes = registry.getByExtends(canonical);
45
+ if (subtypes.some((d) => `${d.metadata.module}.${d.metadata.name}` === resolved)) return true;
46
+ // Leniency is about the CANDIDATE, not about the population, and it is the
47
+ // same question for an abstract target and a concrete one. Accepting whenever
48
+ // no subtype happened to be loaded silenced the check exactly where it was
49
+ // needed: an app whose imports declare no `Telo.Runnable` is an app whose boot
50
+ // targets are all wrong, and every one of them passed.
51
+ //
52
+ // An UNREGISTERED candidate is not partial context, and the distinction is
53
+ // load-bearing: a kind nobody declared is an unknown kind or an unimported
54
+ // alias prefix (`NotAnAlias.Script`), which is precisely what this check
55
+ // exists to report. Only a kind that IS declared, whose ancestry reaches
56
+ // something this analysis never saw, is undecidable — there the missing hop is
57
+ // where the target it appears not to reach could have been declared.
58
+ // A candidate the registry never saw cannot be judged on what it implements —
59
+ // the analysis simply does not hold it. Whether its NAME is resolvable is a
60
+ // different question, asked of the alias scope by the caller.
61
+ if (!registry.resolve(resolved)) return true;
62
+ return !registry.ancestryResolved(resolved);
63
+ }
64
+
65
+ /** {@link kindSatisfies} at every kind a slot accepts, rendered as messages.
66
+ * The acceptance rule is not restated here — only what to say when it fails,
67
+ * which needs the slot's alternatives and the target's flavour. */
26
68
  function checkKind(
27
69
  kind: string,
28
70
  entry: RefFieldEntry,
@@ -30,23 +72,30 @@ function checkKind(
30
72
  aliases: AliasResolver,
31
73
  ): string[] {
32
74
  const resolved = aliases.resolveKind(kind) ?? kind;
75
+ // A qualified kind whose prefix names no import in this scope is a bad NAME
76
+ // rather than a bad type — `{kind: NotAnAlias.Script}` where only `Lib` is
77
+ // imported — and this check is the only place it surfaces, so it is never
78
+ // waved through as partial context. Asked of the resolver, which reports
79
+ // `unknown` for exactly that case: a kind reached through a DECLARED alias
80
+ // resolves (`ok`) even when the target's definitions are not loaded, and a
81
+ // gated one says so separately.
82
+ const unknownAlias =
83
+ kind.includes(".") &&
84
+ aliases.resolveKindResult(kind).status === "unknown" &&
85
+ // …and the registry does not hold it under the name as written either. A
86
+ // manifest may carry a canonical `<module>.<Kind>`, which no alias resolves
87
+ // and which is nonetheless perfectly identified.
88
+ registry.resolve(resolved) === undefined;
33
89
  const errors: string[] = [];
34
90
  for (const refStr of entry.refs) {
35
91
  const targetKind = registry.resolveRef(refStr);
36
92
  if (!targetKind) return [];
37
93
  const targetDef = registry.resolve(targetKind);
38
94
  if (!targetDef) return [];
39
- // Liskov substitutability: a value satisfies the slot when it transitively
40
- // extends the target kind, or — for a CONCRETE target — IS that kind.
41
- // `getByExtends` is the same transitive subtype index for abstract and
42
- // concrete targets alike; an abstract is satisfied only by an implementer,
43
- // never by the abstract kind itself (which is non-instantiable).
44
- if (targetDef.kind !== "Telo.Abstract" && resolved === targetKind) return [];
95
+ if (!unknownAlias && kindSatisfies(resolved, targetKind, registry)) return [];
45
96
  const subtypes = registry.getByExtends(targetKind);
46
97
  const subtypeKinds = new Set(subtypes.map((d) => `${d.metadata.module}.${d.metadata.name}`));
47
- if (subtypeKinds.has(resolved)) return [];
48
98
  if (targetDef.kind === "Telo.Abstract") {
49
- if (subtypes.length === 0) return []; // partial context — no implementations loaded yet
50
99
  // Suggest only what an author can actually wire: with abstract-extends-
51
100
  // abstract real (Telo.Executable over Invocable/Runnable), the transitive
52
101
  // subtype list contains abstracts, which are non-instantiable and would
@@ -54,9 +103,16 @@ function checkKind(
54
103
  const concrete = subtypes
55
104
  .filter((d) => d.kind !== "Telo.Abstract")
56
105
  .map((d) => `${d.metadata.module}.${d.metadata.name}`);
57
- const options = (concrete.length > 0 ? concrete : [...subtypeKinds]).join(", ");
106
+ const options = concrete.length > 0 ? concrete : [...subtypeKinds];
107
+ // With nothing loaded that implements the target there is no list to
108
+ // offer, so the message says what this kind IS instead — which is the
109
+ // half the author can act on ("it declares 'Telo.Invocable'" points
110
+ // straight at a boot target that should have been an invoke step).
111
+ const declared = registry.resolve(resolved)?.capability;
58
112
  errors.push(
59
- `'${kind}' does not implement '${targetKind}' (known implementations: ${options})`,
113
+ options.length > 0
114
+ ? `'${kind}' does not implement '${targetKind}' (known implementations: ${options.join(", ")})`
115
+ : `'${kind}' does not implement '${targetKind}'${declared ? ` — it declares '${declared}'` : ""}`,
60
116
  );
61
117
  } else {
62
118
  const options = subtypeKinds.size > 0 ? ` or a subtype (${[...subtypeKinds].join(", ")})` : "";
@@ -0,0 +1,367 @@
1
+ import type { ResourceManifest } from "@telorun/sdk";
2
+ import { isRefSentinel } from "@telorun/templating";
3
+ import type { AliasResolver } from "./alias-resolver.js";
4
+ import type { DefinitionRegistry } from "./definition-registry.js";
5
+ import { findDynamicLeaf } from "./resource-rule.js";
6
+ import { readResourceInputs, readSuppliedResources } from "./resource-input.js";
7
+ import { type AnalysisDiagnostic, DiagnosticSeverity } from "./types.js";
8
+
9
+ const SOURCE = "telo-analyzer";
10
+
11
+ /** A target library's declared `resources:` block, canonicalized in that
12
+ * library's own alias scope and stamped onto the `Telo.Import` by
13
+ * `stampRequiredResources`: entry name → canonical kind. */
14
+ type RequiredResources = Record<string, string>;
15
+
16
+ /**
17
+ * The strict half of {@link readResourceInputs} — the `validate-ref-slots.ts`
18
+ * split applied to the resource-input boundary, and not optional for the same
19
+ * reason: the two sides fail in OPPOSITE directions. An unreadable DECLARATION
20
+ * leaves the library referencing a name nothing stands behind; an unchecked
21
+ * INJECTION hands a library an instance of a kind it never asked for, which
22
+ * surfaces as a method-missing failure inside someone else's module.
23
+ *
24
+ * Two surfaces, scoped the same way every other declaration check is — to the
25
+ * entry's own modules, since a published dependency's block is not the
26
+ * consumer's to fix:
27
+ *
28
+ * - **The library's own declaration.** Each entry's alias-qualified `kind:` must
29
+ * resolve in the DECLARING module's scope (`RESOURCE_INPUT_KIND_UNRESOLVED`).
30
+ * A constraint that resolves to nothing accepts anything, which is the same
31
+ * hole `X_TELO_REF_UNRESOLVED` exists to close one level down.
32
+ * - **The injection site.** Every declared entry must be supplied
33
+ * (`RESOURCE_INPUT_MISSING` — the same failure as a missing required
34
+ * variable), nothing beyond them may be (`RESOURCE_INPUT_UNKNOWN`), the value
35
+ * must name a resource that exists (`RESOURCE_INPUT_UNRESOLVED`), and its
36
+ * kind must satisfy the declared constraint transitively
37
+ * (`RESOURCE_INPUT_KIND_MISMATCH`).
38
+ *
39
+ * Browser-safe.
40
+ */
41
+ export function validateResourceInputs(
42
+ manifests: ResourceManifest[],
43
+ registry: DefinitionRegistry,
44
+ aliases: AliasResolver,
45
+ rootModules: Set<string>,
46
+ /** Kind acceptance, transitively — the `checkKind` rule `validate-references`
47
+ * applies at an ordinary ref slot, passed in rather than re-derived so the
48
+ * two cannot disagree about what satisfies a constraint. */
49
+ acceptsKind: (suppliedKind: string, requiredKind: string) => boolean,
50
+ ): AnalysisDiagnostic[] {
51
+ const out: AnalysisDiagnostic[] = [];
52
+
53
+ const isOwn = (module: string | undefined): boolean => !module || rootModules.has(module);
54
+
55
+ // --- the library's own declaration -------------------------------------
56
+ for (const m of manifests) {
57
+ if (m.kind !== "Telo.Library") continue;
58
+ const moduleName = m.metadata?.name as string | undefined;
59
+ // Only the entry's own modules, so the declaring scope is always the root
60
+ // alias table — a library analyzed here IS a root module.
61
+ if (!isOwn(moduleName)) continue;
62
+ const scope = aliases;
63
+ const exported = new Set(
64
+ (((m as Record<string, any>).exports?.resources ?? []) as unknown[]).filter(
65
+ (e): e is string => typeof e === "string",
66
+ ),
67
+ );
68
+ for (const input of readResourceInputs(m)) {
69
+ // An input is the IMPORTER's instance, borrowed. Exporting it back out
70
+ // would forward a kind-only stand-in into the consumer's flattened set as
71
+ // a resource this library declares — a phantom the consumer can `!ref`
72
+ // and whose kind constraint is all there is behind it. Handing an
73
+ // instance straight back to whoever supplied it is also a relation
74
+ // nothing needs; if it ever does, it should be a decision rather than a
75
+ // name collision nobody noticed.
76
+ if (exported.has(input.name)) {
77
+ out.push({
78
+ severity: DiagnosticSeverity.Error,
79
+ code: "RESOURCE_INPUT_EXPORTED",
80
+ source: SOURCE,
81
+ message:
82
+ `Resource input '${input.name}' is also listed in 'exports.resources'. An input is ` +
83
+ `an instance the importer supplies, not one this library declares, so there is ` +
84
+ `nothing to export — remove it from 'exports.resources', or rename the input.`,
85
+ data: {
86
+ resource: { kind: m.kind, name: moduleName as string },
87
+ filePath: (m.metadata as { source?: string } | undefined)?.source,
88
+ path: `resources.${input.name}`,
89
+ },
90
+ });
91
+ }
92
+ if (registry.resolve(input.kind) ?? registry.resolve(scope.resolveKind(input.kind) ?? "")) {
93
+ continue;
94
+ }
95
+ out.push({
96
+ severity: DiagnosticSeverity.Error,
97
+ code: "RESOURCE_INPUT_KIND_UNRESOLVED",
98
+ source: SOURCE,
99
+ message:
100
+ `Resource input '${input.name}' is constrained to kind '${input.kind}', which does not ` +
101
+ `resolve in this library's scope. Write it alias-qualified — '<Alias>.<Kind>' for an ` +
102
+ `import declared in this file, 'Self.<Kind>' for a kind this library owns, or ` +
103
+ `'Telo.<Kind>' for a built-in. An unresolvable constraint accepts anything.`,
104
+ data: {
105
+ resource: { kind: m.kind, name: moduleName as string },
106
+ filePath: (m.metadata as { source?: string } | undefined)?.source,
107
+ path: `resources.${input.name}.kind`,
108
+ },
109
+ });
110
+ }
111
+ }
112
+
113
+ // --- the injection site --------------------------------------------------
114
+ for (const m of manifests) {
115
+ if (m.kind !== "Telo.Import") continue;
116
+ const meta = m.metadata as
117
+ | {
118
+ name?: string;
119
+ module?: string;
120
+ source?: string;
121
+ resolvedModuleName?: string;
122
+ requiredResources?: RequiredResources;
123
+ sharedLibrary?: boolean;
124
+ resolvedSource?: string;
125
+ }
126
+ | undefined;
127
+ const alias = meta?.name;
128
+ if (!alias || !isOwn(meta?.module)) continue;
129
+ // An import whose target identity was never established registers nothing —
130
+ // reporting a missing input against it would blame the author for a
131
+ // dependency the loader has already said it could not obtain.
132
+ if (!meta?.resolvedModuleName) continue;
133
+
134
+ // A singleton has no room for a per-import override: `logging:` scopes a
135
+ // subtree that is no longer this import's subtree, and `runtime:` selects a
136
+ // controller backend for a library that is instantiated once. Whichever
137
+ // import happened to be created first would decide, so the field is
138
+ // rejected rather than silently applied to everyone or silently dropped.
139
+ if (meta.sharedLibrary === true) {
140
+ for (const field of ["logging", "runtime"] as const) {
141
+ if ((m as Record<string, unknown>)[field] === undefined) continue;
142
+ out.push({
143
+ severity: DiagnosticSeverity.Error,
144
+ code: "SHARED_LIBRARY_OVERRIDE",
145
+ source: SOURCE,
146
+ message:
147
+ `Import '${alias}' declares '${field}:', but module ` +
148
+ `'${meta.resolvedModuleName}' is 'lifecycle: shared' — one instantiation for the ` +
149
+ `whole application, so a per-import override cannot apply to it. Remove it, or ` +
150
+ `make the library 'lifecycle: isolated'.`,
151
+ data: {
152
+ resource: { kind: m.kind, name: alias },
153
+ filePath: meta.source,
154
+ path: field,
155
+ },
156
+ });
157
+ }
158
+ }
159
+
160
+ const required = Object.entries(meta.requiredResources ?? {});
161
+ const supplied = readSuppliedResources(m);
162
+ const declared = new Map(required);
163
+ const resource = { kind: m.kind, name: alias };
164
+ const filePath = meta.source;
165
+
166
+ for (const [entryName, entryKind] of required) {
167
+ if (entryName in supplied) continue;
168
+ out.push({
169
+ severity: DiagnosticSeverity.Error,
170
+ code: "RESOURCE_INPUT_MISSING",
171
+ source: SOURCE,
172
+ message:
173
+ `Import '${alias}' does not supply the resource input '${entryName}', which module ` +
174
+ `'${meta.resolvedModuleName}' requires (kind '${entryKind}'). Add ` +
175
+ `\`resources: { ${entryName}: !ref <name> }\` to the import.`,
176
+ data: { resource, filePath, path: "resources" },
177
+ });
178
+ }
179
+
180
+ for (const [name, value] of Object.entries(supplied)) {
181
+ const path = `resources.${name}`;
182
+ const entry = declared.get(name);
183
+ if (!entry) {
184
+ const known = required.map(([n]) => n).join(", ") || "(none)";
185
+ out.push({
186
+ severity: DiagnosticSeverity.Error,
187
+ code: "RESOURCE_INPUT_UNKNOWN",
188
+ source: SOURCE,
189
+ message:
190
+ `Import '${alias}' supplies a resource input '${name}', which module ` +
191
+ `'${meta.resolvedModuleName}' does not declare. Declared inputs: ${known}.`,
192
+ data: { resource, filePath, path },
193
+ });
194
+ continue;
195
+ }
196
+ // Phase 2.5 rewrote a resolvable `!ref` to `{kind, name}`; a sentinel that
197
+ // survived names nothing the importer can reach.
198
+ if (isRefSentinel(value)) {
199
+ out.push({
200
+ severity: DiagnosticSeverity.Error,
201
+ code: "RESOURCE_INPUT_UNRESOLVED",
202
+ source: SOURCE,
203
+ message: `Import '${alias}': resource input '${name}' → resource '${value.source}' not found`,
204
+ data: { resource, filePath, path },
205
+ });
206
+ continue;
207
+ }
208
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
209
+ out.push({
210
+ severity: DiagnosticSeverity.Error,
211
+ code: "RESOURCE_INPUT_UNRESOLVED",
212
+ source: SOURCE,
213
+ message:
214
+ `Import '${alias}': resource input '${name}' must be a '!ref' to a resource this ` +
215
+ `module declares.`,
216
+ data: { resource, filePath, path },
217
+ });
218
+ continue;
219
+ }
220
+ const suppliedKind = (value as { kind?: unknown }).kind;
221
+ if (typeof suppliedKind !== "string") continue;
222
+ const canonical = aliases.resolveKind(suppliedKind) ?? suppliedKind;
223
+ if (acceptsKind(canonical, entry)) continue;
224
+ out.push({
225
+ severity: DiagnosticSeverity.Error,
226
+ code: "RESOURCE_INPUT_KIND_MISMATCH",
227
+ source: SOURCE,
228
+ message:
229
+ `Import '${alias}': resource input '${name}' is '${suppliedKind}' (resolved: ` +
230
+ `'${canonical}'), which does not satisfy the declared constraint '${entry}'.`,
231
+ data: { resource, filePath, path },
232
+ });
233
+ }
234
+ }
235
+
236
+ out.push(...sharedLibraryConflicts(manifests, isOwn));
237
+
238
+ return out;
239
+ }
240
+
241
+ /** One import's supplied configuration, as the conflict check compares it. */
242
+ interface SuppliedConfig {
243
+ readonly alias: string;
244
+ readonly module: string | undefined;
245
+ readonly filePath: string | undefined;
246
+ readonly blocks: ReadonlyMap<string, Record<string, unknown>>;
247
+ }
248
+
249
+ const SUPPLIED_BLOCKS = ["variables", "secrets", "resources"] as const;
250
+
251
+ /**
252
+ * Two imports of ONE `lifecycle: shared` library supplying different values.
253
+ *
254
+ * The runtime half (`ERR_SHARED_LIBRARY_CONFLICT`) is authoritative — it holds
255
+ * resolved values and live instances, and a library reached through a
256
+ * programmatic load never passed `telo check`. But the overwhelmingly common
257
+ * shape is two literal scalars in one flattened manifest set, which is decidable
258
+ * here, and a conflict is a hard BOOT failure: finding it at `telo check` is the
259
+ * difference between a squiggle and a deployment that will not start.
260
+ *
261
+ * Only what is DECIDABLE is compared, and the two ways it is not are skipped
262
+ * rather than guessed:
263
+ *
264
+ * - A value holding a `!cel` (at any depth) is known only at load. Two
265
+ * different expressions may evaluate equal, and identical text in two
266
+ * different modules may not.
267
+ * - A `resources:` entry names a resource by name, which means the same
268
+ * instance only when both imports were DECLARED in the same module — so a
269
+ * cross-module pair is left to the runtime.
270
+ *
271
+ * Grouped by the target's RESOLVED SOURCE, the identity the kernel keys its
272
+ * singleton registry on; `resolvedModuleName` would collapse two versions of one
273
+ * module, which are two libraries.
274
+ */
275
+ function sharedLibraryConflicts(
276
+ manifests: ResourceManifest[],
277
+ isOwn: (module: string | undefined) => boolean,
278
+ ): AnalysisDiagnostic[] {
279
+ const out: AnalysisDiagnostic[] = [];
280
+ const byTarget = new Map<string, SuppliedConfig[]>();
281
+
282
+ for (const m of manifests) {
283
+ if (m.kind !== "Telo.Import") continue;
284
+ const meta = m.metadata as
285
+ | { name?: string; module?: string; source?: string; sharedLibrary?: boolean; resolvedSource?: string }
286
+ | undefined;
287
+ if (meta?.sharedLibrary !== true || !meta.name || !meta.resolvedSource) continue;
288
+ const blocks = new Map<string, Record<string, unknown>>();
289
+ for (const block of SUPPLIED_BLOCKS) {
290
+ const value = (m as Record<string, unknown>)[block];
291
+ blocks.set(
292
+ block,
293
+ value && typeof value === "object" && !Array.isArray(value)
294
+ ? (value as Record<string, unknown>)
295
+ : {},
296
+ );
297
+ }
298
+ const bucket = byTarget.get(meta.resolvedSource);
299
+ const entry: SuppliedConfig = {
300
+ alias: meta.name,
301
+ module: meta.module,
302
+ filePath: meta.source,
303
+ blocks,
304
+ };
305
+ if (bucket) bucket.push(entry);
306
+ else byTarget.set(meta.resolvedSource, [entry]);
307
+ }
308
+
309
+ for (const group of byTarget.values()) {
310
+ if (group.length < 2) continue;
311
+ const [first, ...rest] = group;
312
+ for (const later of rest) {
313
+ for (const block of SUPPLIED_BLOCKS) {
314
+ // A reference means the same instance only within one module's scope.
315
+ if (block === "resources" && first!.module !== later.module) continue;
316
+ const a = first!.blocks.get(block)!;
317
+ const b = later.blocks.get(block)!;
318
+ for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
319
+ if (findDynamicLeaf(a[key]) || findDynamicLeaf(b[key])) continue;
320
+ if (sameSuppliedValue(a[key], b[key])) continue;
321
+ out.push({
322
+ severity: DiagnosticSeverity.Error,
323
+ code: "SHARED_LIBRARY_CONFLICT",
324
+ source: SOURCE,
325
+ message:
326
+ `Import '${later.alias}' and import '${first!.alias}' both reach a ` +
327
+ `'lifecycle: shared' library — one instantiation for the whole application — but ` +
328
+ `they supply different values for ${block}.${key}. Make the two imports agree, or ` +
329
+ `make the library 'lifecycle: isolated'.`,
330
+ data: isOwn(later.module)
331
+ ? {
332
+ resource: { kind: "Telo.Import", name: later.alias },
333
+ filePath: later.filePath,
334
+ path: `${block}.${key}`,
335
+ }
336
+ : {
337
+ resource: { kind: "Telo.Import", name: first!.alias },
338
+ filePath: first!.filePath,
339
+ path: `${block}.${key}`,
340
+ },
341
+ });
342
+ }
343
+ }
344
+ }
345
+ }
346
+
347
+ return out;
348
+ }
349
+
350
+ /** Structural equality, key-order insensitive — the analyzer's half of the rule
351
+ * the kernel applies to resolved values. A secret's VALUE is compared but never
352
+ * printed: the key is what the author has to look at. */
353
+ function sameSuppliedValue(a: unknown, b: unknown): boolean {
354
+ if (a === b) return true;
355
+ if (a === undefined || b === undefined || a === null || b === null) return false;
356
+ if (Array.isArray(a) || Array.isArray(b)) {
357
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
358
+ return a.every((item, i) => sameSuppliedValue(item, b[i]));
359
+ }
360
+ if (typeof a === "object" && typeof b === "object") {
361
+ const left = a as Record<string, unknown>;
362
+ const right = b as Record<string, unknown>;
363
+ const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
364
+ return [...keys].every((key) => sameSuppliedValue(left[key], right[key]));
365
+ }
366
+ return false;
367
+ }
@@ -0,0 +1,99 @@
1
+ import type { ResourceManifest } from "@telorun/sdk";
2
+ import { isRefSentinel } from "@telorun/templating";
3
+ import { distance } from "./levenshtein.js";
4
+ import { DiagnosticSeverity, type AnalysisDiagnostic } from "./types.js";
5
+
6
+ const SOURCE = "telo-analyzer";
7
+
8
+ /** The four slots a `Telo.Definition` names its dispatch target in. Each takes
9
+ * the same grammar; which one is legal for a given capability is
10
+ * `validate-provider-coherence`'s question, not this one's. */
11
+ const DISPATCH_FIELDS = ["invoke", "run", "provide", "mount"] as const;
12
+
13
+ /**
14
+ * A `!ref` at a definition's dispatch slot must name a sibling `resources:`
15
+ * entry.
16
+ *
17
+ * `!ref` is the one spelling an author — and the editor's rename, completion and
18
+ * go-to-definition — expects to be RESOLVED. But a `Telo.Definition` is in both
19
+ * `REF_VALIDATION_SKIP_KINDS` and `REF_RESOLUTION_SKIP_KINDS`, and the dispatch
20
+ * slots carry no `x-telo-ref` (the accepted targets are the definition's own
21
+ * template-internal entries, not resources of any module), so no reference pass
22
+ * reaches them. Introducing the tag at a slot nothing resolves would be worse
23
+ * than the string form it replaces: a typo that used to be an obvious runtime
24
+ * miss becomes a typo in a construct that advertises static resolution.
25
+ *
26
+ * Decidable only when every sibling name is LITERAL. A template routinely names
27
+ * its entries with CEL (`name: !cel "self.name + '-query'"`), and an expression
28
+ * could expand to the referenced name — so one dynamic sibling switches the
29
+ * check off for that definition rather than inventing a miss.
30
+ *
31
+ * Entry-module-scoped, like every other declaration check: a published
32
+ * dependency's template body is not the consumer's to fix.
33
+ *
34
+ * Browser-safe.
35
+ */
36
+ export function validateTemplateDispatch(
37
+ manifests: ResourceManifest[],
38
+ rootModules: ReadonlySet<string>,
39
+ ): AnalysisDiagnostic[] {
40
+ const out: AnalysisDiagnostic[] = [];
41
+
42
+ for (const m of manifests) {
43
+ if (m.kind !== "Telo.Definition") continue;
44
+ const meta = m.metadata as { name?: string; module?: string; source?: string } | undefined;
45
+ const name = meta?.name;
46
+ if (!name) continue;
47
+ if (meta?.module && !rootModules.has(meta.module)) continue;
48
+
49
+ const bodies = (m as Record<string, unknown>).resources;
50
+ if (!Array.isArray(bodies)) continue;
51
+
52
+ const siblings: string[] = [];
53
+ let anyDynamic = false;
54
+ for (const entry of bodies) {
55
+ const entryName = (entry as { metadata?: { name?: unknown } } | undefined)?.metadata?.name;
56
+ if (typeof entryName === "string" && !entryName.includes("${{")) siblings.push(entryName);
57
+ else if (entryName !== undefined) anyDynamic = true;
58
+ }
59
+ if (anyDynamic) continue;
60
+
61
+ for (const field of DISPATCH_FIELDS) {
62
+ const value = (m as Record<string, unknown>)[field];
63
+ if (!isRefSentinel(value)) continue;
64
+ const source = value.source;
65
+ const target = source.startsWith("Self.") ? source.slice("Self.".length) : source;
66
+ if (siblings.includes(target)) continue;
67
+ const suggestion = nearest(target, siblings);
68
+ out.push({
69
+ severity: DiagnosticSeverity.Error,
70
+ code: "TEMPLATE_DISPATCH_UNKNOWN",
71
+ source: SOURCE,
72
+ message:
73
+ `${m.kind}/${name}: '${field}: !ref ${source}' names no entry in 'resources:'. ` +
74
+ `Available: ${siblings.join(", ") || "(none)"}.` +
75
+ (suggestion ? ` Did you mean '${suggestion}'?` : ""),
76
+ data: {
77
+ resource: { kind: m.kind, name },
78
+ filePath: meta?.source,
79
+ path: field,
80
+ ...(suggestion ? { fix: { replacement: suggestion } } : {}),
81
+ },
82
+ });
83
+ }
84
+ }
85
+
86
+ return out;
87
+ }
88
+
89
+ /** The closest sibling name, when one is close enough to be a typo rather than a
90
+ * different name. */
91
+ function nearest(target: string, candidates: readonly string[]): string | undefined {
92
+ let best: { name: string; d: number } | undefined;
93
+ for (const candidate of candidates) {
94
+ const d = distance(target, candidate);
95
+ if (!best || d < best.d) best = { name: candidate, d };
96
+ }
97
+ const limit = Math.max(1, Math.floor(target.length / 3));
98
+ return best && best.d <= limit ? best.name : undefined;
99
+ }