@telorun/templating 0.20.1 → 0.21.1

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 (40) hide show
  1. package/dist/cel/analyze.d.ts +26 -0
  2. package/dist/cel/analyze.d.ts.map +1 -1
  3. package/dist/cel/analyze.js +114 -8
  4. package/dist/cel/catalog.d.ts.map +1 -1
  5. package/dist/cel/catalog.js +10 -0
  6. package/dist/cel/compile.d.ts +9 -3
  7. package/dist/cel/compile.d.ts.map +1 -1
  8. package/dist/cel/compile.js +52 -11
  9. package/dist/cel/diagnose.d.ts +10 -1
  10. package/dist/cel/diagnose.d.ts.map +1 -1
  11. package/dist/cel/diagnose.js +42 -6
  12. package/dist/cel/environment.d.ts.map +1 -1
  13. package/dist/cel/environment.js +2 -0
  14. package/dist/cel/module-call.d.ts +108 -0
  15. package/dist/cel/module-call.d.ts.map +1 -0
  16. package/dist/cel/module-call.js +245 -0
  17. package/dist/cel/value-identity.d.ts +18 -0
  18. package/dist/cel/value-identity.d.ts.map +1 -0
  19. package/dist/cel/value-identity.js +25 -0
  20. package/dist/engine.d.ts +66 -0
  21. package/dist/engine.d.ts.map +1 -1
  22. package/dist/engines/cel.d.ts.map +1 -1
  23. package/dist/engines/cel.js +87 -6
  24. package/dist/engines/sql.d.ts.map +1 -1
  25. package/dist/engines/sql.js +5 -1
  26. package/dist/index.d.ts +3 -2
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +7 -1
  29. package/package.json +3 -3
  30. package/src/cel/analyze.ts +131 -9
  31. package/src/cel/catalog.ts +10 -0
  32. package/src/cel/compile.ts +59 -12
  33. package/src/cel/diagnose.ts +56 -6
  34. package/src/cel/environment.ts +3 -0
  35. package/src/cel/module-call.ts +369 -0
  36. package/src/cel/value-identity.ts +34 -0
  37. package/src/engine.ts +72 -0
  38. package/src/engines/cel.ts +104 -6
  39. package/src/engines/sql.ts +5 -1
  40. package/src/index.ts +20 -1
@@ -1,6 +1,7 @@
1
- import { extractAccessChains, findNullableAccessIssues, validateChainAgainstSchema, } from "../cel/analyze.js";
1
+ import { extractAccessChains, extractCallResultAccesses, findNullableAccessIssues, INDEX_SEGMENT, moduleCallArgumentChains, validateChainAgainstSchema, } from "../cel/analyze.js";
2
2
  import { compileExpression } from "../cel/compile.js";
3
3
  import { auditCalls, explainUnresolved } from "../cel/diagnose.js";
4
+ import { moduleCallNodes, moduleNameBindings, resolveModuleCalls, unresolvedCallReceivers, } from "../cel/module-call.js";
4
5
  /** Statically analyze one CEL expression against the effective context schema:
5
6
  * parse → classify every call → type-check → validate member-access chains →
6
7
  * flag nullable access. Single source of truth shared by the `!cel` engine
@@ -24,7 +25,24 @@ export function analyzeCelExpression(source, env) {
24
25
  calls: [],
25
26
  };
26
27
  }
27
- const audit = auditCalls(source, parsed.ast, env.celEnv);
28
+ // Resolution, before anything reads the tree — the audit, the type check and
29
+ // every chain walk below all see the resolved shape, so none of them has to
30
+ // know a module name from a variable.
31
+ // The walks that read resolved calls below are skipped when there are none.
32
+ const resolvedCalls = resolveModuleCalls(parsed.ast, env.moduleNames, env.moduleCallType).length > 0;
33
+ // A name bound inside the expression can never be read once a module owns it:
34
+ // `Billing.f(x)` under a comprehension variable named `Billing` resolves to
35
+ // the module. Reported rather than silently shadowed, the rule every other
36
+ // name in CEL scope follows.
37
+ for (const name of moduleNameBindings(parsed.ast, env.moduleNames)) {
38
+ out.push({
39
+ code: "BINDING_NAME_RESERVED",
40
+ message: `'${name}' names a module here (an imports: alias, Self, or this module's own name), ` +
41
+ `so a call written '${name}.f(…)' resolves to that module and this binding could never ` +
42
+ `be read. Rename the bound variable.`,
43
+ });
44
+ }
45
+ const audit = auditCalls(source, parsed.ast, env.celEnv, env.moduleCallFlags);
28
46
  // Reported whatever the type-checker concludes. A literal argument a guard
29
47
  // will refuse is a defect the manifest states outright, and leaving it to the
30
48
  // run is the thing static analysis exists to prevent — so it is not gated on
@@ -33,7 +51,10 @@ export function analyzeCelExpression(source, env) {
33
51
  let type;
34
52
  let checkError;
35
53
  try {
36
- const result = env.celEnv.check(source);
54
+ // `parsed.check()`, never `celEnv.check(source)`: the latter RE-PARSES, so
55
+ // it would type a tree in which no module call was ever resolved — every
56
+ // one of them reported as a missing method on an unknown receiver.
57
+ const result = parsed.check();
37
58
  if (result.valid)
38
59
  type = result.type;
39
60
  else if (result.error) {
@@ -83,16 +104,44 @@ export function analyzeCelExpression(source, env) {
83
104
  // Comprehension variables are not roots: `extractAccessChains` drops the
84
105
  // names a `.all(x, …)` binds, so the check never sees them.
85
106
  if (env.rootsDeclared) {
107
+ // A receiver that resolved to no module name AND could be one — the host
108
+ // decides the second half, since a name's level is its naming rule, not
109
+ // this engine's. `Foo.bar()` is an unknown identifier like any other, but
110
+ // its repair is an `imports:` alias rather than a different spelling, so it
111
+ // says so; `dbb.query(1)` is a misspelled value and gets no such advice.
112
+ // Walked only once a root is unknown, which a correct expression never has.
113
+ let callReceivers;
86
114
  const reported = new Set();
87
115
  for (const chain of extractAccessChains(parsed.ast)) {
88
116
  const root = chain[0];
89
117
  if (!root || reported.has(root) || env.celEnv.hasVariable(root))
90
118
  continue;
91
119
  reported.add(root);
120
+ callReceivers ??= unresolvedCallReceivers(parsed.ast, env.moduleNames);
92
121
  out.push({
93
122
  code: "CEL_UNKNOWN_IDENTIFIER",
94
- message: `unknown identifier '${root}' — nothing by that name is in scope here.`,
123
+ message: `unknown identifier '${root}' — nothing by that name is in scope here.` +
124
+ (callReceivers.has(root) && env.couldNameModule?.(root) === true
125
+ ? ` To call a function another module declares, '${root}' must be one of this module's names — an 'imports:' alias, 'Self', or the module's own metadata.name.`
126
+ : ""),
127
+ });
128
+ }
129
+ }
130
+ // A module call's result is typed by the callee's declared `returns`, which the
131
+ // caller resolves: member access on it is checked exactly as a read off the
132
+ // context would be, under the call as written.
133
+ if (resolvedCalls && env.moduleCallResult) {
134
+ for (const access of extractCallResultAccesses(parsed.ast)) {
135
+ const schema = env.moduleCallResult(access.qualified);
136
+ if (!schema)
137
+ continue;
138
+ const label = `${access.qualified}(…)`;
139
+ const err = validateChainAgainstSchema([label, ...access.members], {
140
+ type: "object",
141
+ properties: { [label]: schema },
95
142
  });
143
+ if (err)
144
+ out.push({ code: "CEL_UNKNOWN_FIELD", message: err });
96
145
  }
97
146
  }
98
147
  if (env.contextSchema) {
@@ -112,7 +161,39 @@ export function analyzeCelExpression(source, env) {
112
161
  });
113
162
  }
114
163
  }
115
- return { diagnostics: out, calls: audit.calls, ...(type === undefined ? {} : { type }) };
164
+ return {
165
+ diagnostics: out,
166
+ calls: resolvedCalls ? withCallArguments(audit.calls, parsed.ast) : audit.calls,
167
+ ...(type === undefined ? {} : { type }),
168
+ };
169
+ }
170
+ /** The audited call sites, each module call carrying its arguments as the type
171
+ * check saw them. Matched by position, which is what identifies one call among
172
+ * several of the same name. */
173
+ function withCallArguments(calls, ast) {
174
+ const byStart = new Map();
175
+ for (const { node, call } of moduleCallNodes(ast))
176
+ byStart.set(node.start, call);
177
+ const chainsByStart = new Map();
178
+ for (const [node, chains] of moduleCallArgumentChains(ast))
179
+ chainsByStart.set(node.start, chains);
180
+ return calls.map((site) => {
181
+ const call = site.moduleCall ? byStart.get(site.start) : undefined;
182
+ if (!call)
183
+ return site;
184
+ const chains = chainsByStart.get(site.start);
185
+ return {
186
+ ...site,
187
+ arguments: call.args.map((arg, index) => {
188
+ const type = call.argumentTypes?.[index];
189
+ const chain = chains?.[index] ?? null;
190
+ return {
191
+ ...(type !== undefined ? { type } : {}),
192
+ ...(chain && !chain.includes(INDEX_SEGMENT) ? { chain } : {}),
193
+ };
194
+ }),
195
+ };
196
+ });
116
197
  }
117
198
  /** `dyn` in a checker message means an operand whose type is unknown here —
118
199
  * almost always a step result whose invoked resource declares no
@@ -129,7 +210,7 @@ export const celEngine = {
129
210
  name: "cel",
130
211
  language: "cel",
131
212
  compile(source, env) {
132
- return compileExpression(source, env.celEnv);
213
+ return compileExpression(source, env.celEnv, env.moduleNames);
133
214
  },
134
215
  analyze(source, env) {
135
216
  return analyzeCelExpression(source, env);
@@ -1 +1 @@
1
- {"version":3,"file":"sql.d.ts","sourceRoot":"","sources":["../../src/engines/sql.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAsB,KAAK,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAG7F,OAAO,KAAK,EAIV,gBAAgB,EACjB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,kBAAkB,EAAE,KAAK,gBAAgB,EAAE,CAAC;AAErD;;;;;kFAKkF;AAClF,eAAO,MAAM,SAAS,EAAE,gBA4CvB,CAAC"}
1
+ {"version":3,"file":"sql.d.ts","sourceRoot":"","sources":["../../src/engines/sql.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAsB,KAAK,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAG7F,OAAO,KAAK,EAIV,gBAAgB,EACjB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,kBAAkB,EAAE,KAAK,gBAAgB,EAAE,CAAC;AAErD;;;;;kFAKkF;AAClF,eAAO,MAAM,SAAS,EAAE,gBAgDvB,CAAC"}
@@ -12,10 +12,14 @@ export const sqlEngine = {
12
12
  name: "sql",
13
13
  language: "sql",
14
14
  compile(source, env) {
15
- const inner = compileString(source, env.celEnv);
15
+ const inner = compileString(source, env.celEnv, env.moduleNames);
16
16
  return {
17
17
  __compiled: true,
18
18
  source,
19
+ // The qualified module calls of every interpolation, for the reason
20
+ // `refs` are carried: a consumer asking what an expression CALLS cannot
21
+ // re-derive it from the text without the declaring module's names.
22
+ calls: typeof inner === "string" ? [] : (inner.calls ?? []),
19
23
  // The AST-derived root identifiers of every interpolation, carried through
20
24
  // rather than dropped. `compileString` has already computed them one line
21
25
  // above, and a consumer that asks a compiled value what it READS —
package/dist/index.d.ts CHANGED
@@ -2,7 +2,8 @@ export { buildCelEnvironment, celBuiltinFunctions, deriveSignatures, type CelHan
2
2
  export { celFunctionCatalog, CEL_FUNCTIONS, type CelFunctionInfo, type CelFunctionDoc, type CelFunctionCategory, } from "./cel/catalog.js";
3
3
  export { compileExpression, compileString, toParameterized, TEMPLATE_REGEX, EXACT_TEMPLATE_REGEX, } from "./cel/compile.js";
4
4
  export { extractAccessChains, findNullableAccessIssues, INDEX_SEGMENT, validateChainAgainstSchema, } from "./cel/analyze.js";
5
- export { auditCalls, explainUnresolved, functionIndex, type CallAudit } from "./cel/diagnose.js";
5
+ export { auditCalls, explainUnresolved, functionIndex, type CallAudit, type ModuleCallFlags, } from "./cel/diagnose.js";
6
+ export { MODULE_CALL_DISPATCH_KEY, moduleCallOf, resolveModuleCalls, type ModuleCallDispatch, type ModuleCallTypeResolver, } from "./cel/module-call.js";
6
7
  export { walkCelExpressions, type CelSurface } from "./cel/walk.js";
7
8
  export { celEngine } from "./engines/cel.js";
8
9
  export { includeBytesEngine, includeTextEngine, normalizeIncludePath, type NormalizedIncludePath, } from "./engines/include.js";
@@ -11,7 +12,7 @@ export { refEngine } from "./engines/ref.js";
11
12
  export { sqlEngine, isParameterizedSql, type ParameterizedSql } from "./engines/sql.js";
12
13
  export { TemplatingEngineRegistry } from "./registry.js";
13
14
  export { builtinEngines, createDefaultRegistry, defaultRegistry, producedTypeOf, } from "./builtins.js";
14
- export type { AnalyzeEnv, AnalyzeResult, CallSite, CompileEnv, DiagnosticFix, EngineDiagnostic, EngineFileClaim, TemplatingEngine, } from "./engine.js";
15
+ export type { AnalyzeEnv, AnalyzeResult, CallArgument, CallSite, CompileEnv, DiagnosticFix, EngineDiagnostic, EngineFileClaim, TemplatingEngine, } from "./engine.js";
15
16
  export { CEL_ENGINE, INCLUDE_BYTES_ENGINE, INCLUDE_ENGINE_NAMES, INCLUDE_TEXT_ENGINE, isIncludeSentinel, isRefSentinel, isTaggedSentinel, makeTaggedSentinel, plainChainOf, type TaggedSentinel, } from "./sentinel.js";
16
17
  export { buildCustomTags, defaultCustomTags } from "./yaml-tags.js";
17
18
  //# sourceMappingURL=index.d.ts.map
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AE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAExF,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EACL,cAAc,EACd,qBAAqB,EACrB,eAAe,EACf,cAAc,GACf,MAAM,eAAe,CAAC;AACvB,YAAY,EACV,UAAU,EACV,aAAa,EACb,YAAY,EACZ,QAAQ,EACR,UAAU,EACV,aAAa,EACb,gBAAgB,EAChB,eAAe,EACf,gBAAgB,GACjB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,UAAU,EACV,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,EACjB,aAAa,EACb,gBAAgB,EAChB,kBAAkB,EAClB,YAAY,EACZ,KAAK,cAAc,GACpB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC"}
package/dist/index.js CHANGED
@@ -2,7 +2,13 @@ export { buildCelEnvironment, celBuiltinFunctions, deriveSignatures, } from "./c
2
2
  export { celFunctionCatalog, CEL_FUNCTIONS, } from "./cel/catalog.js";
3
3
  export { compileExpression, compileString, toParameterized, TEMPLATE_REGEX, EXACT_TEMPLATE_REGEX, } from "./cel/compile.js";
4
4
  export { extractAccessChains, findNullableAccessIssues, INDEX_SEGMENT, validateChainAgainstSchema, } from "./cel/analyze.js";
5
- export { auditCalls, explainUnresolved, functionIndex } from "./cel/diagnose.js";
5
+ export { auditCalls, explainUnresolved, functionIndex, } from "./cel/diagnose.js";
6
+ // The rewrite, its reader, and the activation key the kernel binds a scope's
7
+ // dispatch table under. The unbound message and the receiver and bound-name
8
+ // walks are read inside this package only.
9
+ // `ModuleCallTypeResolver` is here because `AnalyzeEnv` names it: an exported
10
+ // interface whose field type cannot be named is not usable from outside.
11
+ export { MODULE_CALL_DISPATCH_KEY, moduleCallOf, resolveModuleCalls, } from "./cel/module-call.js";
6
12
  export { walkCelExpressions } from "./cel/walk.js";
7
13
  export { celEngine } from "./engines/cel.js";
8
14
  export { includeBytesEngine, includeTextEngine, normalizeIncludePath, } from "./engines/include.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telorun/templating",
3
- "version": "0.20.1",
3
+ "version": "0.21.1",
4
4
  "description": "Telo Templating - Engine registry and shared CEL core for Telo manifests.",
5
5
  "keywords": [
6
6
  "telo",
@@ -35,7 +35,7 @@
35
35
  "src/**"
36
36
  ],
37
37
  "dependencies": {
38
- "@marcbachmann/cel-js": "^7.6.1",
38
+ "@marcbachmann/cel-js": "7.6.1",
39
39
  "d3-format": "3.1.2",
40
40
  "re2js": "^2.8.3",
41
41
  "uuid": "^14.0.1",
@@ -46,7 +46,7 @@
46
46
  "@types/node": "^20.0.0",
47
47
  "typescript": "^5.0.0",
48
48
  "vitest": "^2.1.8",
49
- "@telorun/sdk": "0.90.0"
49
+ "@telorun/sdk": "0.97.0"
50
50
  },
51
51
  "peerDependencies": {
52
52
  "@telorun/sdk": "*"
@@ -1,11 +1,19 @@
1
1
  import type { ASTNode } from "@marcbachmann/cel-js";
2
2
  import { isLiveSlot } from "@telorun/sdk";
3
+ import { moduleCallOf } from "./module-call.js";
3
4
 
4
5
  /**
5
6
  * Extract all member-access chains from a CEL AST.
6
7
  * Returns arrays like ["request", "query", "name"] for `request.query.name`.
7
8
  * Chains that start with a call or non-identifier root are ignored.
8
9
  * Bound variables in comprehension macros (filter, map, exists, all, exists_one) are excluded.
10
+ *
11
+ * A RESOLVED module call contributes no chain for its receiver: `Billing` in
12
+ * `Billing.format(x)` names a module, not a value, so reading it as a root
13
+ * would invent a dependency, an undeclared identifier and a `resources` read
14
+ * that the expression never states. Resolution is `resolveModuleCalls`, on the
15
+ * tree, before this walk — an unresolved tree still reports the receiver, which
16
+ * is the right answer for a caller that supplied no module names.
9
17
  */
10
18
  export function extractAccessChains(node: ASTNode): string[][] {
11
19
  const chains: string[][] = [];
@@ -13,6 +21,29 @@ export function extractAccessChains(node: ASTNode): string[][] {
13
21
  return chains;
14
22
  }
15
23
 
24
+ /**
25
+ * Each resolved module call's arguments as plain member chains, keyed by the
26
+ * call's node — `null` for an argument that is not one, or that is rooted at a
27
+ * name the expression itself binds (`xs.map(item, Billing.total(item))`), which
28
+ * no context schema describes.
29
+ */
30
+ export function moduleCallArgumentChains(node: ASTNode): Map<ASTNode, Array<string[] | null>> {
31
+ const out = new Map<ASTNode, Array<string[] | null>>();
32
+ visitNode(node, [], new Set(), (call, callNode, boundVars) => {
33
+ out.set(
34
+ callNode,
35
+ call.args.map((arg) => extractChain(arg, boundVars)),
36
+ );
37
+ });
38
+ return out;
39
+ }
40
+
41
+ type ModuleCallVisitor = (
42
+ call: NonNullable<ReturnType<typeof moduleCallOf>>,
43
+ node: ASTNode,
44
+ boundVars: ReadonlySet<string>,
45
+ ) => void;
46
+
16
47
  const COMPREHENSION_METHODS = new Set(["filter", "map", "exists", "all", "exists_one"]);
17
48
 
18
49
  /** `cel.bind(name, init, body)` — CEL's only binding form, and the one the
@@ -34,19 +65,31 @@ function bindCall(node: ASTNode): { name: string; init: ASTNode; body: ASTNode }
34
65
  return { name: nameNode.args as string, init, body };
35
66
  }
36
67
 
37
- function visitNode(node: ASTNode, chains: string[][], boundVars: Set<string>): void {
68
+ function visitNode(
69
+ node: ASTNode,
70
+ chains: string[][],
71
+ boundVars: Set<string>,
72
+ onModuleCall?: ModuleCallVisitor,
73
+ ): void {
38
74
  const chain = extractChain(node, boundVars);
39
75
  if (chain !== null) {
40
76
  chains.push(chain);
41
77
  return;
42
78
  }
43
79
 
80
+ const moduleCall = moduleCallOf(node);
81
+ if (moduleCall) {
82
+ onModuleCall?.(moduleCall, node, boundVars);
83
+ for (const arg of moduleCall.args) visitNode(arg, chains, boundVars, onModuleCall);
84
+ return;
85
+ }
86
+
44
87
  // The bound name is in scope for the body ONLY; `init` is evaluated in the
45
88
  // enclosing scope, so a name used there still has to resolve there.
46
89
  const bind = bindCall(node);
47
90
  if (bind) {
48
- visitNode(bind.init, chains, boundVars);
49
- visitNode(bind.body, chains, new Set(boundVars).add(bind.name));
91
+ visitNode(bind.init, chains, boundVars, onModuleCall);
92
+ visitNode(bind.body, chains, new Set(boundVars).add(bind.name), onModuleCall);
50
93
  return;
51
94
  }
52
95
 
@@ -58,7 +101,7 @@ function visitNode(node: ASTNode, chains: string[][], boundVars: Set<string>): v
58
101
  ) {
59
102
  const receiver = node.args[1];
60
103
  const comprehensionArgs = node.args[2];
61
- if (isASTNode(receiver)) visitNode(receiver, chains, boundVars);
104
+ if (isASTNode(receiver)) visitNode(receiver, chains, boundVars, onModuleCall);
62
105
  if (
63
106
  Array.isArray(comprehensionArgs) &&
64
107
  comprehensionArgs.length >= 2 &&
@@ -69,7 +112,7 @@ function visitNode(node: ASTNode, chains: string[][], boundVars: Set<string>): v
69
112
  newBoundVars.add((comprehensionArgs[0] as ASTNode).args as string);
70
113
  for (let i = 1; i < comprehensionArgs.length; i++) {
71
114
  const arg = comprehensionArgs[i];
72
- if (isASTNode(arg)) visitNode(arg as ASTNode, chains, newBoundVars);
115
+ if (isASTNode(arg)) visitNode(arg as ASTNode, chains, newBoundVars, onModuleCall);
73
116
  }
74
117
  }
75
118
  return;
@@ -79,17 +122,17 @@ function visitNode(node: ASTNode, chains: string[][], boundVars: Set<string>): v
79
122
  if (Array.isArray(args)) {
80
123
  for (const arg of args) {
81
124
  if (isASTNode(arg)) {
82
- visitNode(arg, chains, boundVars);
125
+ visitNode(arg, chains, boundVars, onModuleCall);
83
126
  } else if (Array.isArray(arg)) {
84
127
  for (const item of arg) {
85
- if (isASTNode(item)) visitNode(item, chains, boundVars);
128
+ if (isASTNode(item)) visitNode(item, chains, boundVars, onModuleCall);
86
129
  }
87
130
  }
88
131
  }
89
132
  } else if (isASTNode(args)) {
90
133
  // Unary operators (`!_`, `-_`) carry their operand as a single node
91
134
  // rather than a one-element array, so descend into it directly.
92
- visitNode(args, chains, boundVars);
135
+ visitNode(args, chains, boundVars, onModuleCall);
93
136
  }
94
137
  }
95
138
 
@@ -102,7 +145,7 @@ function isASTNode(v: unknown): v is ASTNode {
102
145
  * chains to declared names treat this as "unknown member". */
103
146
  export const INDEX_SEGMENT = "[*]";
104
147
 
105
- function extractChain(node: ASTNode, boundVars: Set<string>): string[] | null {
148
+ function extractChain(node: ASTNode, boundVars: ReadonlySet<string>): string[] | null {
106
149
  if (node.op === "id") {
107
150
  const name = node.args as string;
108
151
  if (boundVars.has(name)) return null;
@@ -121,6 +164,59 @@ function extractChain(node: ASTNode, boundVars: Set<string>): string[] | null {
121
164
  return null;
122
165
  }
123
166
 
167
+ /** A member access on a module call's result: the call, and the members read
168
+ * off it in order (`Billing.total(xs).amount` → `amount`). */
169
+ export interface CallResultAccess {
170
+ readonly qualified: string;
171
+ readonly members: readonly string[];
172
+ }
173
+
174
+ /**
175
+ * Every member access whose base is a module call, longest first — the chains
176
+ * {@link extractAccessChains} deliberately skips, since their root is a value
177
+ * no context schema describes. The caller supplies the call's result schema.
178
+ */
179
+ export function extractCallResultAccesses(node: ASTNode): CallResultAccess[] {
180
+ const out: CallResultAccess[] = [];
181
+ visitAccess(node, out);
182
+ return out;
183
+ }
184
+
185
+ function visitAccess(node: ASTNode, out: CallResultAccess[]): void {
186
+ if (node.op === "." || node.op === "[]") {
187
+ const members: string[] = [];
188
+ let base: ASTNode = node;
189
+ while (base.op === "." || base.op === "[]") {
190
+ const [obj, field] = base.args as [ASTNode, unknown];
191
+ members.unshift(base.op === "." ? String(field) : INDEX_SEGMENT);
192
+ if (base.op === "[]" && isASTNode(field)) visitAccess(field, out);
193
+ base = obj;
194
+ }
195
+ const call = moduleCallOf(base);
196
+ if (call) {
197
+ out.push({ qualified: call.qualified, members });
198
+ for (const arg of call.args) visitAccess(arg, out);
199
+ return;
200
+ }
201
+ visitAccess(base, out);
202
+ return;
203
+ }
204
+ const moduleCall = moduleCallOf(node);
205
+ if (moduleCall) {
206
+ for (const arg of moduleCall.args) visitAccess(arg, out);
207
+ return;
208
+ }
209
+ const args = node.args;
210
+ if (Array.isArray(args)) {
211
+ for (const arg of args) {
212
+ if (isASTNode(arg)) visitAccess(arg, out);
213
+ else if (Array.isArray(arg)) for (const item of arg) if (isASTNode(item)) visitAccess(item, out);
214
+ }
215
+ } else if (isASTNode(args)) {
216
+ visitAccess(args, out);
217
+ }
218
+ }
219
+
124
220
  interface NullableIssue {
125
221
  /** Dotted path of the nullable value being dereferenced (e.g. "error"). */
126
222
  path: string;
@@ -274,6 +370,14 @@ function walkNullable(
274
370
  return;
275
371
  }
276
372
 
373
+ // A module call's receiver is a module name, not a value; mirror
374
+ // extractAccessChains so it is never read as a nullable context field.
375
+ const moduleCall = moduleCallOf(node);
376
+ if (moduleCall) {
377
+ for (const arg of moduleCall.args) walkNullable(arg, nonNull, boundVars, issues, schema);
378
+ return;
379
+ }
380
+
277
381
  // `cel.bind` binds a name for its body; mirror extractAccessChains so a bound
278
382
  // name is never read as a nullable context field.
279
383
  const bind = bindCall(node);
@@ -341,6 +445,24 @@ export function validateChainAgainstSchema(
341
445
  for (let i = 0; i < chain.length; i++) {
342
446
  const key = chain[i]!;
343
447
  if (!current || typeof current !== "object") return null;
448
+ // An index reads an ELEMENT: an array's `items`, or a map's value schema. What
449
+ // is below it is checked like any member access, which is what reaches a
450
+ // typo inside a list of records (`items[0].amont`). An object that also
451
+ // declares `properties` may be indexed by one of those names, which the
452
+ // chain does not record, so nothing below it is judged.
453
+ if (key === INDEX_SEGMENT) {
454
+ const element =
455
+ current.items && typeof current.items === "object" && !Array.isArray(current.items)
456
+ ? current.items
457
+ : !current.properties &&
458
+ current.additionalProperties &&
459
+ typeof current.additionalProperties === "object"
460
+ ? current.additionalProperties
461
+ : undefined;
462
+ if (!element) return null;
463
+ current = element;
464
+ continue;
465
+ }
344
466
  const props: Record<string, any> | undefined = current.properties;
345
467
  if (!props) return null;
346
468
  if (key in props) {
@@ -1030,6 +1030,16 @@ export const CEL_FUNCTIONS: readonly CelFunctionDoc[] = [
1030
1030
  },
1031
1031
  // Time (non-deterministic). `nowIso`/`today` take an optional IANA timezone
1032
1032
  // (default "UTC"); epoch values are absolute and take none.
1033
+ {
1034
+ name: "now",
1035
+ signature: "now(): timestamp",
1036
+ register: ["now(): google.protobuf.Timestamp"],
1037
+ category: "time",
1038
+ summary: "Current instant as a native timestamp, for comparison and duration arithmetic.",
1039
+ deterministic: false,
1040
+ hostBacked: false,
1041
+ build: () => () => new Date(),
1042
+ },
1033
1043
  {
1034
1044
  name: "nowIso",
1035
1045
  signature: "nowIso(string?): string",
@@ -1,6 +1,8 @@
1
1
  import { isCompiledValue, type CompiledValue } from "@telorun/sdk";
2
- import type { Environment } from "@marcbachmann/cel-js";
2
+ import type { ASTNode, Environment } from "@marcbachmann/cel-js";
3
3
  import { extractAccessChains } from "./analyze.js";
4
+ import { CEL_FUNCTIONS } from "./catalog.js";
5
+ import { resolveModuleCalls } from "./module-call.js";
4
6
 
5
7
  export const TEMPLATE_REGEX = /\$\{\{\s*([^}]+?)\s*\}\}/g;
6
8
  export const EXACT_TEMPLATE_REGEX = /^\s*\$\{\{\s*([^}]+?)\s*\}\}\s*$/;
@@ -9,25 +11,59 @@ export const EXACT_TEMPLATE_REGEX = /^\s*\$\{\{\s*([^}]+?)\s*\}\}\s*$/;
9
11
  * first element of every member-access chain (`self.table` → `self`). Returns
10
12
  * undefined when the parse result carries no AST so consumers can tell "no
11
13
  * refs" from "unknown". */
12
- function rootRefs(parsed: unknown): readonly string[] | undefined {
13
- const ast = (parsed as { ast?: unknown }).ast;
14
- if (!ast) return undefined;
14
+ function rootRefs(ast: ASTNode): readonly string[] {
15
15
  const roots = new Set<string>();
16
- for (const chain of extractAccessChains(ast as never)) {
16
+ for (const chain of extractAccessChains(ast)) {
17
17
  if (chain.length > 0) roots.add(chain[0]!);
18
18
  }
19
19
  return [...roots];
20
20
  }
21
21
 
22
+ const NON_DETERMINISTIC = new Set(
23
+ CEL_FUNCTIONS.filter((f) => !f.deterministic).map((f) => f.name),
24
+ );
25
+
26
+ /** True when the expression calls a catalog function whose result differs per
27
+ * call (`uuidv4()`, `nowMillis()`), so evaluating it once and reusing the value
28
+ * would change what it means. */
29
+ function callsNonDeterministic(root: ASTNode): boolean {
30
+ const visit = (node: unknown): boolean => {
31
+ if (Array.isArray(node)) return node.some(visit);
32
+ if (!node || typeof node !== "object" || !("op" in node)) return false;
33
+ const n = node as ASTNode;
34
+ if ((n.op === "call" || n.op === "rcall") && Array.isArray(n.args)) {
35
+ const name = (n.args as unknown[])[0];
36
+ if (typeof name === "string" && NON_DETERMINISTIC.has(name)) return true;
37
+ }
38
+ const args = n.args as unknown;
39
+ return Array.isArray(args) ? args.some(visit) : visit(args);
40
+ };
41
+ return visit(root);
42
+ }
43
+
22
44
  /** Compile a single CEL expression (no `${{ }}` wrapping) into a CompiledValue.
23
45
  * Throws on syntax errors. Used by the `!cel` engine where the entire tagged
24
- * scalar is treated as one expression. */
25
- export function compileExpression(expr: string, env: Environment): CompiledValue {
46
+ * scalar is treated as one expression.
47
+ *
48
+ * `moduleNames` are the declaring module's own names; a call whose receiver is
49
+ * one of them resolves to a late-bound module call HERE, on the parsed tree, so
50
+ * every later reader — the root references below, the analyzer's passes, the
51
+ * kernel's dependency walk — sees the resolved shape rather than re-deriving
52
+ * it from the source text. */
53
+ export function compileExpression(
54
+ expr: string,
55
+ env: Environment,
56
+ moduleNames?: ReadonlySet<string>,
57
+ ): CompiledValue {
26
58
  const fn = env.parse(expr);
59
+ const ast: ASTNode = fn.ast;
60
+ const calls = resolveModuleCalls(ast, moduleNames);
27
61
  return {
28
62
  __compiled: true,
29
63
  source: expr,
30
- refs: rootRefs(fn),
64
+ refs: rootRefs(ast),
65
+ calls,
66
+ ...(callsNonDeterministic(ast) ? { volatile: true as const } : {}),
31
67
  call: (ctx: Record<string, unknown>) => fn(ctx),
32
68
  };
33
69
  }
@@ -37,26 +73,35 @@ export function compileExpression(expr: string, env: Environment): CompiledValue
37
73
  * contains interpolations, returns a CompiledValue that joins literal parts
38
74
  * with stringified expression results. If no expressions are present, returns
39
75
  * the input string unchanged. Throws on CEL syntax errors. */
40
- export function compileString(s: string, env: Environment): unknown {
76
+ export function compileString(
77
+ s: string,
78
+ env: Environment,
79
+ moduleNames?: ReadonlySet<string>,
80
+ ): unknown {
41
81
  if (!s.includes("${{")) return s;
42
82
 
43
83
  const exact = s.match(EXACT_TEMPLATE_REGEX);
44
84
  if (exact) {
45
- return compileExpression(exact[1].trim(), env);
85
+ return compileExpression(exact[1].trim(), env, moduleNames);
46
86
  }
47
87
 
48
88
  const parts: Array<string | CompiledValue> = [];
49
89
  let last = 0;
50
90
  for (const m of s.matchAll(TEMPLATE_REGEX)) {
51
91
  if (m.index! > last) parts.push(s.slice(last, m.index));
52
- parts.push(compileExpression(m[1].trim(), env));
92
+ parts.push(compileExpression(m[1].trim(), env, moduleNames));
53
93
  last = m.index! + m[0].length;
54
94
  }
55
95
  if (last < s.length) parts.push(s.slice(last));
56
96
 
57
97
  const refs = new Set<string>();
98
+ const calls = new Set<string>();
99
+ let volatile = false;
58
100
  for (const p of parts) {
59
- if (typeof p !== "string" && p.refs) for (const r of p.refs) refs.add(r);
101
+ if (typeof p === "string") continue;
102
+ if (p.refs) for (const r of p.refs) refs.add(r);
103
+ if (p.calls) for (const c of p.calls) calls.add(c);
104
+ if (p.volatile) volatile = true;
60
105
  }
61
106
 
62
107
  return {
@@ -64,6 +109,8 @@ export function compileString(s: string, env: Environment): unknown {
64
109
  source: s,
65
110
  parts,
66
111
  refs: [...refs],
112
+ calls: [...calls],
113
+ ...(volatile ? { volatile: true as const } : {}),
67
114
  call: (ctx: Record<string, unknown>) =>
68
115
  parts.map((p) => (typeof p === "string" ? p : String(p.call(ctx) ?? ""))).join(""),
69
116
  } satisfies CompiledValue;