@telorun/templating 0.23.0 → 0.25.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 (52) hide show
  1. package/README.md +1 -1
  2. package/dist/builtins.d.ts +8 -0
  3. package/dist/builtins.d.ts.map +1 -1
  4. package/dist/builtins.js +13 -0
  5. package/dist/cel/analyze.d.ts +4 -0
  6. package/dist/cel/analyze.d.ts.map +1 -1
  7. package/dist/cel/analyze.js +9 -0
  8. package/dist/cel/catalog.d.ts.map +1 -1
  9. package/dist/cel/catalog.js +12 -4
  10. package/dist/cel/compile.d.ts +4 -26
  11. package/dist/cel/compile.d.ts.map +1 -1
  12. package/dist/cel/compile.js +3 -88
  13. package/dist/cel/interpolation-holes.d.ts +43 -0
  14. package/dist/cel/interpolation-holes.d.ts.map +1 -0
  15. package/dist/cel/interpolation-holes.js +121 -0
  16. package/dist/cel/walk.d.ts +7 -28
  17. package/dist/cel/walk.d.ts.map +1 -1
  18. package/dist/cel/walk.js +7 -39
  19. package/dist/engine.d.ts +30 -0
  20. package/dist/engine.d.ts.map +1 -1
  21. package/dist/engines/cel.d.ts +7 -0
  22. package/dist/engines/cel.d.ts.map +1 -1
  23. package/dist/engines/cel.js +78 -14
  24. package/dist/engines/hole-analysis.d.ts +23 -0
  25. package/dist/engines/hole-analysis.d.ts.map +1 -0
  26. package/dist/engines/hole-analysis.js +66 -0
  27. package/dist/engines/interpolate.d.ts +13 -0
  28. package/dist/engines/interpolate.d.ts.map +1 -0
  29. package/dist/engines/interpolate.js +123 -0
  30. package/dist/engines/sql.d.ts +3 -3
  31. package/dist/engines/sql.d.ts.map +1 -1
  32. package/dist/engines/sql.js +24 -58
  33. package/dist/index.d.ts +6 -4
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +4 -2
  36. package/dist/sentinel.d.ts +4 -5
  37. package/dist/sentinel.d.ts.map +1 -1
  38. package/dist/sentinel.js +6 -14
  39. package/package.json +2 -2
  40. package/src/builtins.ts +14 -0
  41. package/src/cel/analyze.ts +12 -0
  42. package/src/cel/catalog.ts +14 -4
  43. package/src/cel/compile.ts +4 -92
  44. package/src/cel/interpolation-holes.ts +138 -0
  45. package/src/cel/walk.ts +8 -54
  46. package/src/engine.ts +33 -0
  47. package/src/engines/cel.ts +85 -16
  48. package/src/engines/hole-analysis.ts +96 -0
  49. package/src/engines/interpolate.ts +139 -0
  50. package/src/engines/sql.ts +26 -67
  51. package/src/index.ts +12 -7
  52. package/src/sentinel.ts +6 -14
@@ -36,6 +36,15 @@ import type {
36
36
  * explained it, and left `${{ }}` interpolations chain-validated but never
37
37
  * type-checked at all. */
38
38
  export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeResult {
39
+ return analyzeCelWithTree(source, env).result;
40
+ }
41
+
42
+ /** {@link analyzeCelExpression}, with the resolved tree it built — for a tag
43
+ * that asks its own questions of one expression without parsing it again. */
44
+ export function analyzeCelWithTree(
45
+ source: string,
46
+ env: AnalyzeEnv,
47
+ ): { result: AnalyzeResult; ast?: ASTNode } {
39
48
  const out: EngineDiagnostic[] = [];
40
49
 
41
50
  let parsed: ReturnType<typeof env.celEnv.parse>;
@@ -43,10 +52,13 @@ export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeRe
43
52
  parsed = env.celEnv.parse(source);
44
53
  } catch (e) {
45
54
  return {
46
- diagnostics: [{ code: "CEL_SYNTAX_ERROR", message: e instanceof Error ? e.message : String(e) }],
47
- calls: [],
55
+ result: {
56
+ diagnostics: [{ code: "CEL_SYNTAX_ERROR", message: e instanceof Error ? e.message : String(e) }],
57
+ calls: [],
58
+ },
48
59
  };
49
60
  }
61
+ const ast: ASTNode = parsed.ast;
50
62
 
51
63
  // Resolution, before anything reads the tree — the audit, the type check and
52
64
  // every chain walk below all see the resolved shape, so none of them has to
@@ -94,15 +106,18 @@ export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeRe
94
106
  // crash here silently retires static typing for that expression. Report it
95
107
  // instead: degrading is acceptable, degrading invisibly is not.
96
108
  return {
97
- diagnostics: [
98
- {
99
- code: "CEL_TYPE_ERROR",
100
- message: `the CEL type-checker failed on this expression: ${
101
- e instanceof Error ? e.message : String(e)
102
- }`,
103
- },
104
- ],
105
- calls: audit.calls,
109
+ result: {
110
+ diagnostics: [
111
+ {
112
+ code: "CEL_TYPE_ERROR",
113
+ message: `the CEL type-checker failed on this expression: ${
114
+ e instanceof Error ? e.message : String(e)
115
+ }`,
116
+ },
117
+ ],
118
+ calls: audit.calls,
119
+ },
120
+ ast,
106
121
  };
107
122
  }
108
123
 
@@ -113,11 +128,18 @@ export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeRe
113
128
  // not become a hard error on valid CEL. Reporting nothing where cel-js is
114
129
  // happy makes an unknown future macro a silent no-op rather than a manifest
115
130
  // this analyzer refuses and the kernel would run fine.
131
+ // What explaining a rejection already reported, so the context's own chain
132
+ // check below does not report it twice.
133
+ const explained = new Set<string>();
116
134
  if (checkError !== undefined) {
117
135
  // `check()` stops at its first problem; the audit enumerates every bad call,
118
136
  // which is the whole reason it exists as more than a message rewriter.
119
137
  out.push(...audit.diagnostics);
120
- if (audit.diagnostics.length === 0) {
138
+ const unknownFields =
139
+ audit.diagnostics.length === 0 ? explainUnknownFields(parsed.ast, env) : [];
140
+ out.push(...unknownFields);
141
+ for (const d of unknownFields) explained.add(d.message);
142
+ if (audit.diagnostics.length === 0 && unknownFields.length === 0) {
121
143
  out.push({
122
144
  code: "CEL_TYPE_ERROR",
123
145
  message: checkError + explainUnresolved(audit.unresolved, env.celEnv) + DYN_HINT(checkError),
@@ -178,7 +200,7 @@ export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeRe
178
200
  const contextSchema = env.contextSchema as Record<string, any>;
179
201
  for (const chain of extractAccessChains(parsed.ast)) {
180
202
  const err = validateChainAgainstSchema(chain, contextSchema);
181
- if (err) out.push({ code: "CEL_UNKNOWN_FIELD", message: err });
203
+ if (err && !explained.has(err)) out.push({ code: "CEL_UNKNOWN_FIELD", message: err });
182
204
  }
183
205
 
184
206
  for (const issue of findNullableAccessIssues(parsed.ast, contextSchema)) {
@@ -193,12 +215,55 @@ export function analyzeCelExpression(source: string, env: AnalyzeEnv): AnalyzeRe
193
215
  }
194
216
 
195
217
  return {
196
- diagnostics: out,
197
- calls: resolvedCalls ? withCallArguments(audit.calls, parsed.ast) : audit.calls,
198
- ...(type === undefined ? {} : { type }),
218
+ result: {
219
+ diagnostics: out,
220
+ calls: resolvedCalls ? withCallArguments(audit.calls, parsed.ast) : audit.calls,
221
+ ...(type === undefined ? {} : { type }),
222
+ ...(ast.op === "value" && typeof ast.args === "string" ? { stringLiteral: ast.args } : {}),
223
+ ...(checkError === undefined ? {} : { readTypes: chainTypes(parsed.ast, env) }),
224
+ },
225
+ ast,
199
226
  };
200
227
  }
201
228
 
229
+ /** Every chain naming a field the site's names do not declare, as the host's
230
+ * explain schema reads them — the readable half of a rejection the checker
231
+ * reported in its own words. The explain schema is not the checker's
232
+ * environment, so a chain is reported only when the checker rejects it too;
233
+ * otherwise the rejection was about something else and keeps its own words. */
234
+ function explainUnknownFields(ast: ASTNode, env: AnalyzeEnv): EngineDiagnostic[] {
235
+ const schema = env.explainSchema?.();
236
+ if (!schema) return [];
237
+ const out: EngineDiagnostic[] = [];
238
+ const reported = new Set<string>();
239
+ for (const chain of extractAccessChains(ast)) {
240
+ const message = validateChainAgainstSchema(chain, schema as Record<string, any>);
241
+ if (message && !reported.has(message) && checkerRejects(chain, env)) {
242
+ reported.add(message);
243
+ out.push({ code: "CEL_UNKNOWN_FIELD", message });
244
+ }
245
+ }
246
+ return out;
247
+ }
248
+
249
+ /** The checked type of each distinct plain chain the expression reads. */
250
+ function chainTypes(ast: ASTNode, env: AnalyzeEnv): string[] {
251
+ const types = new Set<string>();
252
+ for (const chain of extractAccessChains(ast)) {
253
+ if (chain.includes(INDEX_SEGMENT)) continue;
254
+ const result = env.celEnv.check(chain.join("."));
255
+ if (result.valid && result.type !== undefined) types.add(result.type);
256
+ }
257
+ return [...types];
258
+ }
259
+
260
+ /** Does the checker reject the chain's named prefix (up to its first index)? */
261
+ function checkerRejects(chain: readonly string[], env: AnalyzeEnv): boolean {
262
+ const end = chain.indexOf(INDEX_SEGMENT);
263
+ const named = end === -1 ? chain : chain.slice(0, end);
264
+ return !env.celEnv.check(named.join(".")).valid;
265
+ }
266
+
202
267
  /** The audited call sites, each module call carrying its arguments as the type
203
268
  * check saw them. Matched by position, which is what identifies one call among
204
269
  * several of the same name. */
@@ -248,4 +313,8 @@ export const celEngine: TemplatingEngine = {
248
313
  analyze(source, env) {
249
314
  return analyzeCelExpression(source, env);
250
315
  },
316
+
317
+ expressionRegions(source) {
318
+ return [{ start: 0, end: source.length }];
319
+ },
251
320
  };
@@ -0,0 +1,96 @@
1
+ import type { ASTNode } from "@marcbachmann/cel-js";
2
+ import type { CompiledValue } from "@telorun/sdk";
3
+ import { compileExpression } from "../cel/compile.js";
4
+ import {
5
+ readInterpolationHoles,
6
+ type InterpolationHole,
7
+ } from "../cel/interpolation-holes.js";
8
+ import type {
9
+ AnalyzeEnv,
10
+ AnalyzeResult,
11
+ CallSite,
12
+ CompileEnv,
13
+ DiagnosticFix,
14
+ EngineDiagnostic,
15
+ ExpressionRegion,
16
+ } from "../engine.js";
17
+ import { analyzeCelWithTree } from "./cel.js";
18
+
19
+ /** The holes of a scalar a hole-bearing tag compiles, or a thrown error naming
20
+ * where the reading failed — a tag's scalar that cannot be read is not a value. */
21
+ export function requireHoles(tag: string, source: string): readonly InterpolationHole[] {
22
+ const reading = readInterpolationHoles(source);
23
+ if (!reading.ok) throw new Error(`!${tag}: ${reading.message}`);
24
+ return reading.holes;
25
+ }
26
+
27
+ /** Every hole compiled as its own CEL expression, with the roots, module calls
28
+ * and volatility of all of them carried together. */
29
+ export function compileHoles(
30
+ holes: readonly InterpolationHole[],
31
+ env: CompileEnv,
32
+ ): {
33
+ readonly compiled: readonly CompiledValue[];
34
+ readonly refs: readonly string[];
35
+ readonly calls: readonly string[];
36
+ readonly volatile: boolean;
37
+ } {
38
+ const compiled = holes.map((h) => compileExpression(h.expr, env.celEnv, env.moduleNames));
39
+ const refs = new Set<string>();
40
+ const calls = new Set<string>();
41
+ let volatile = false;
42
+ for (const c of compiled) {
43
+ for (const r of c.refs ?? []) refs.add(r);
44
+ for (const q of c.calls ?? []) calls.add(q);
45
+ if (c.volatile) volatile = true;
46
+ }
47
+ return { compiled, refs: [...refs], calls: [...calls], volatile };
48
+ }
49
+
50
+ /** Analyze each hole with the shared CEL analysis, so diagnostics read exactly
51
+ * as they do under `!cel`; a fix computed against one hole's expression is
52
+ * re-anchored onto the whole scalar, and call offsets onto the scalar too.
53
+ * `perHole` adds a tag's own verdict on a hole that analyzed clean. */
54
+ export function analyzeHoles(
55
+ source: string,
56
+ env: AnalyzeEnv,
57
+ perHole?: (
58
+ hole: InterpolationHole,
59
+ result: AnalyzeResult,
60
+ ast: ASTNode | undefined,
61
+ ) => readonly EngineDiagnostic[],
62
+ ): AnalyzeResult {
63
+ const reading = readInterpolationHoles(source);
64
+ if (!reading.ok) {
65
+ return { diagnostics: [{ code: "CEL_SYNTAX_ERROR", message: reading.message }], calls: [] };
66
+ }
67
+ const diagnostics: EngineDiagnostic[] = [];
68
+ const calls: CallSite[] = [];
69
+ for (const hole of reading.holes) {
70
+ const { result, ast } = analyzeCelWithTree(hole.expr, env);
71
+ for (const d of result.diagnostics) {
72
+ diagnostics.push(d.fix ? { ...d, fix: reanchor(source, hole, d.fix) } : d);
73
+ }
74
+ for (const c of result.calls) {
75
+ calls.push({ ...c, start: hole.exprStart + c.start, end: hole.exprStart + c.end });
76
+ }
77
+ if (perHole && result.diagnostics.length === 0) diagnostics.push(...perHole(hole, result, ast));
78
+ }
79
+ return { diagnostics, calls };
80
+ }
81
+
82
+ /** The CEL expressions of a hole-bearing scalar, by offset. */
83
+ export function holeRegions(source: string): readonly ExpressionRegion[] {
84
+ const reading = readInterpolationHoles(source);
85
+ if (!reading.ok) return [];
86
+ return reading.holes.map((h) => ({ start: h.exprStart, end: h.exprStart + h.expr.length }));
87
+ }
88
+
89
+ function reanchor(source: string, hole: InterpolationHole, fix: DiagnosticFix): DiagnosticFix {
90
+ return {
91
+ replacement:
92
+ source.slice(0, hole.exprStart) +
93
+ fix.replacement +
94
+ source.slice(hole.exprStart + hole.expr.length),
95
+ };
96
+ }
@@ -0,0 +1,139 @@
1
+ import { Environment, EvaluationError, type ASTNode } from "@marcbachmann/cel-js";
2
+ import { RuntimeError, type CompiledValue } from "@telorun/sdk";
3
+ import { nullableValueChain } from "../cel/analyze.js";
4
+ import { literalFragments, type InterpolationHole } from "../cel/interpolation-holes.js";
5
+ import type { AnalyzeEnv, AnalyzeResult, EngineDiagnostic, TemplatingEngine } from "../engine.js";
6
+ import { analyzeHoles, compileHoles, holeRegions, requireHoles } from "./hole-analysis.js";
7
+
8
+ const INTERPOLATE_ENGINE = "interpolate";
9
+
10
+ /**
11
+ * The `!interpolate` engine: literal text with `${{ expr }}` holes, always a
12
+ * string. Its meaning is exactly the CEL expression that joins the text with
13
+ * `string(<hole>)` for each hole — every hole converts through CEL's own
14
+ * `string()` overloads (RFC 3339 for a timestamp, `5400s` for a duration, UTF-8
15
+ * for bytes), never the host language's conversion, so any CEL engine renders
16
+ * the same text. A hole whose type has no `string()` overload is refused
17
+ * statically, and a `dyn` hole that turns out null, a list or a map is refused
18
+ * at runtime with the hole it came from.
19
+ */
20
+ export const interpolateEngine: TemplatingEngine = {
21
+ name: INTERPOLATE_ENGINE,
22
+ language: "cel",
23
+
24
+ compile(source, env) {
25
+ const holes = requireHoles(INTERPOLATE_ENGINE, source);
26
+ const fragments = literalFragments(source, holes);
27
+ const { compiled, refs, calls, volatile } = compileHoles(holes, env);
28
+ const convert = stringConversion(env.celEnv);
29
+ return {
30
+ __compiled: true,
31
+ source,
32
+ refs,
33
+ calls,
34
+ ...(volatile ? { volatile: true as const } : {}),
35
+ call: (ctx: Record<string, unknown>): string => {
36
+ let out = fragments[0]!;
37
+ for (let i = 0; i < holes.length; i++) {
38
+ out += convert(compiled[i]!.call(ctx), holes[i]!, source) + fragments[i + 1]!;
39
+ }
40
+ return out;
41
+ },
42
+ } satisfies CompiledValue;
43
+ },
44
+
45
+ analyze(source, env) {
46
+ return analyzeHoles(source, env, (hole, result, ast) => holeVerdict(hole, result, ast, env));
47
+ },
48
+
49
+ producedType() {
50
+ return { type: "string" };
51
+ },
52
+
53
+ expressionRegions(source) {
54
+ return holeRegions(source);
55
+ },
56
+ };
57
+
58
+ /** A clean hole's own checks, over the tree its analysis already built:
59
+ * whether it may be null, and whether CEL can turn its type into text at all. */
60
+ function holeVerdict(
61
+ hole: InterpolationHole,
62
+ result: AnalyzeResult,
63
+ ast: ASTNode | undefined,
64
+ env: AnalyzeEnv,
65
+ ): readonly EngineDiagnostic[] {
66
+ if (ast && env.contextSchema) {
67
+ const chain = nullableValueChain(ast, env.contextSchema as Record<string, any>);
68
+ if (chain !== null) {
69
+ return [
70
+ {
71
+ code: "CEL_NULLABLE_ACCESS",
72
+ message:
73
+ `'${chain}' may be null, and a null has no text — guard it in the hole ` +
74
+ `(e.g. '\${{ ${chain} != null ? ${chain} : "" }}').`,
75
+ },
76
+ ];
77
+ }
78
+ }
79
+ if (result.type === undefined || convertibleTypes(env.celEnv).has(result.type)) return [];
80
+ return [
81
+ {
82
+ code: "INTERPOLATION_HOLE_NOT_CONVERTIBLE",
83
+ message:
84
+ `the hole '\${{ ${hole.expr} }}' is ${result.type}, which CEL's string() cannot convert to text. ` +
85
+ `Convert it inside the hole (e.g. join a list, or read the field you meant), or write the whole value as !cel.`,
86
+ },
87
+ ];
88
+ }
89
+
90
+ const CONVERTIBLE = new WeakMap<Environment, ReadonlySet<string>>();
91
+
92
+ /** The types a `string()` overload of `env` accepts, `dyn` among them — read
93
+ * off the registered overloads, so the check is the one evaluation applies. */
94
+ function convertibleTypes(env: Environment): ReadonlySet<string> {
95
+ const cached = CONVERTIBLE.get(env);
96
+ if (cached) return cached;
97
+ const types = new Set<string>(["dyn"]);
98
+ for (const fn of env.getDefinitions().functions) {
99
+ if (fn.name === "string" && fn.receiverType === null && fn.params?.length === 1) {
100
+ types.add(fn.params[0]!.type);
101
+ }
102
+ }
103
+ CONVERTIBLE.set(env, types);
104
+ return types;
105
+ }
106
+
107
+ type Conversion = (value: unknown, hole: InterpolationHole, source: string) => string;
108
+
109
+ const CONVERSIONS = new WeakMap<Environment, Conversion>();
110
+
111
+ /** CEL's `string(v)` in `env`, with every overload the environment registers. */
112
+ function stringConversion(env: Environment): Conversion {
113
+ const cached = CONVERSIONS.get(env);
114
+ if (cached) return cached;
115
+ const program = env.parse("string(value)") as (ctx: { value: unknown }) => unknown;
116
+ const conversion: Conversion = (value, hole, source) => {
117
+ if (typeof value === "string") return value;
118
+ try {
119
+ return program({ value }) as string;
120
+ } catch (error) {
121
+ if (!(error instanceof EvaluationError)) throw error;
122
+ throw new RuntimeError(
123
+ "ERR_INTERPOLATION_HOLE_NOT_CONVERTIBLE",
124
+ `the hole '\${{ ${hole.expr} }}' at offset ${hole.start} of !interpolate ${JSON.stringify(source)} ` +
125
+ `evaluated to ${runtimeTypeOf(value)}, which CEL's string() cannot convert to text. ` +
126
+ `Declare outputType on the resource producing it so the check sees its type, or guard it inside the hole.`,
127
+ );
128
+ }
129
+ };
130
+ CONVERSIONS.set(env, conversion);
131
+ return conversion;
132
+ }
133
+
134
+ function runtimeTypeOf(value: unknown): string {
135
+ if (value === null || value === undefined) return "null";
136
+ if (Array.isArray(value)) return "a list";
137
+ if (value instanceof Map || Object.getPrototypeOf(value) === Object.prototype) return "a map";
138
+ return `a value of type ${(value as object).constructor?.name ?? typeof value}`;
139
+ }
@@ -1,19 +1,14 @@
1
1
  import { isParameterizedSql, type CompiledValue, type ParameterizedSql } from "@telorun/sdk";
2
- import { analyzeCelExpression } from "./cel.js";
3
- import { compileString, toParameterized, TEMPLATE_REGEX } from "../cel/compile.js";
4
- import type {
5
- CallSite,
6
- DiagnosticFix,
7
- EngineDiagnostic,
8
- TemplatingEngine,
9
- } from "../engine.js";
2
+ import { literalFragments } from "../cel/interpolation-holes.js";
3
+ import type { TemplatingEngine } from "../engine.js";
4
+ import { analyzeHoles, compileHoles, holeRegions, requireHoles } from "./hole-analysis.js";
10
5
 
11
6
  export { isParameterizedSql, type ParameterizedSql };
12
7
 
13
8
  /** The `!sql` engine. Treats the tagged scalar as a SQL string with `${{ }}`
14
- * interpolations whose values are *bound*, not spliced. Unlike `!cel` (one bare
15
- * expression) it keeps the literal text and each interpolation separate: at
16
- * runtime `call()` returns a {@link ParameterizedSql} the consumer turns into a
9
+ * holes whose values are *bound*, not spliced. Unlike `!cel` (one bare
10
+ * expression) it keeps the literal text and each hole separate: at runtime
11
+ * `call()` returns a {@link ParameterizedSql} the consumer turns into a
17
12
  * parameterized query. Generic expansion passes that object through untouched
18
13
  * (it is the `call()` result), so it survives the step-level input expansion. */
19
14
  export const sqlEngine: TemplatingEngine = {
@@ -21,69 +16,33 @@ export const sqlEngine: TemplatingEngine = {
21
16
  language: "sql",
22
17
 
23
18
  compile(source, env) {
24
- const inner = compileString(source, env.celEnv, env.moduleNames);
19
+ const holes = requireHoles("sql", source);
20
+ const fragments = literalFragments(source, holes);
21
+ const { compiled, refs, calls, volatile } = compileHoles(holes, env);
25
22
  return {
26
23
  __compiled: true,
27
24
  source,
28
- // The qualified module calls of every interpolation, for the reason
29
- // `refs` are carried: a consumer asking what an expression CALLS cannot
30
- // re-derive it from the text without the declaring module's names.
31
- calls: typeof inner === "string" ? [] : ((inner as CompiledValue).calls ?? []),
32
- // The AST-derived root identifiers of every interpolation, carried through
33
- // rather than dropped. `compileString` has already computed them one line
34
- // above, and a consumer that asks a compiled value what it READS —
35
- // a template body deciding which nodes survive its `init()` — otherwise
36
- // falls back to scanning the source text, which cannot tell an identifier
37
- // from a word inside a SQL string literal.
38
- refs: typeof inner === "string" ? [] : (inner as CompiledValue).refs,
39
- call: (ctx: Record<string, unknown>): ParameterizedSql => {
40
- const { fragments, values } = toParameterized(inner, ctx);
41
- return { __teloParameterized: true, fragments, values };
42
- },
25
+ // Carried for the reason `!cel` carries them: a consumer asking what an
26
+ // expression READS or CALLS cannot re-derive it from SQL text, which
27
+ // cannot tell an identifier from a word inside a string literal.
28
+ refs,
29
+ calls,
30
+ ...(volatile ? { volatile: true as const } : {}),
31
+ call: (ctx: Record<string, unknown>): ParameterizedSql => ({
32
+ __teloParameterized: true,
33
+ fragments: fragments.slice(),
34
+ values: compiled.map((c) => c.call(ctx)),
35
+ }),
43
36
  } satisfies CompiledValue;
44
37
  },
45
38
 
46
39
  analyze(source, env) {
47
- // Each `${{ }}` interpolation is its own CEL expression; reuse the shared
48
- // per-expression analyzer so diagnostics match the `!cel` engine exactly.
49
- // Each interpolation's offset is kept so a fix computed against the bare
50
- // expression is re-anchored to the whole SQL scalar — the only thing that
51
- // ever made `!sql` fix-less was dropping it here.
52
- const diagnostics: EngineDiagnostic[] = [];
53
- const calls: CallSite[] = [];
54
- for (const { expr, start } of expressionsOf(source)) {
55
- const result = analyzeCelExpression(expr, env);
56
- for (const d of result.diagnostics) {
57
- diagnostics.push(d.fix ? { ...d, fix: reanchor(source, expr, start, d.fix) } : d);
58
- }
59
- for (const c of result.calls) {
60
- calls.push({ ...c, start: start + c.start, end: start + c.end });
61
- }
62
- }
63
- // No `type`: a SQL template is a string built from many expressions, so
40
+ // No `type`: a SQL template is a query built from many expressions, so
64
41
  // there is no single checked type to report.
65
- return { diagnostics, calls };
42
+ return analyzeHoles(source, env);
66
43
  },
67
- };
68
-
69
- /** Re-anchor a fix computed against one interpolation onto the full source. */
70
- function reanchor(source: string, expr: string, start: number, fix: DiagnosticFix): DiagnosticFix {
71
- return {
72
- replacement: source.slice(0, start) + fix.replacement + source.slice(start + expr.length),
73
- };
74
- }
75
-
76
- /** Each `${{ expr }}` body in a `!sql` template, with the body's offset in the
77
- * source. The offset is derived from the opening delimiter and the leading
78
- * whitespace the capture group already trims, never by searching for the
79
- * body text — which a body appearing twice would defeat. */
80
- function expressionsOf(source: string): { expr: string; start: number }[] {
81
- const out: { expr: string; start: number }[] = [];
82
- for (const m of source.matchAll(TEMPLATE_REGEX)) {
83
- const lead = /^\s*/.exec(m[0]!.slice(OPEN.length))![0]!.length;
84
- out.push({ expr: m[1]!, start: m.index! + OPEN.length + lead });
85
- }
86
- return out;
87
- }
88
44
 
89
- const OPEN = "${{";
45
+ expressionRegions(source) {
46
+ return holeRegions(source);
47
+ },
48
+ };
package/src/index.ts CHANGED
@@ -11,13 +11,15 @@ export {
11
11
  type CelFunctionDoc,
12
12
  type CelFunctionCategory,
13
13
  } from "./cel/catalog.js";
14
+ export { compileExpression } from "./cel/compile.js";
14
15
  export {
15
- compileExpression,
16
- compileString,
17
- toParameterized,
18
- TEMPLATE_REGEX,
19
- EXACT_TEMPLATE_REGEX,
20
- } from "./cel/compile.js";
16
+ interpolationShape,
17
+ literalFragments,
18
+ readInterpolationHoles,
19
+ type HoleReading,
20
+ type InterpolationHole,
21
+ type InterpolationShape,
22
+ } from "./cel/interpolation-holes.js";
21
23
  export {
22
24
  extractAccessChains,
23
25
  findNullableAccessIssues,
@@ -43,7 +45,7 @@ export {
43
45
  type ModuleCallDispatch,
44
46
  type ModuleCallTypeResolver,
45
47
  } from "./cel/module-call.js";
46
- export { walkCelExpressions, type CelSurface } from "./cel/walk.js";
48
+ export { walkCelExpressions } from "./cel/walk.js";
47
49
 
48
50
  export { celEngine } from "./engines/cel.js";
49
51
  export {
@@ -53,6 +55,7 @@ export {
53
55
  normalizeModulePath,
54
56
  type NormalizedIncludePath,
55
57
  } from "./engines/include.js";
58
+ export { interpolateEngine } from "./engines/interpolate.js";
56
59
  export { literalEngine } from "./engines/literal.js";
57
60
  export { modulePathEngine } from "./engines/module-path.js";
58
61
  export { refEngine } from "./engines/ref.js";
@@ -61,6 +64,7 @@ export { sqlEngine, isParameterizedSql, type ParameterizedSql } from "./engines/
61
64
  export { TemplatingEngineRegistry } from "./registry.js";
62
65
  export {
63
66
  builtinEngines,
67
+ celExpressionsOf,
64
68
  createDefaultRegistry,
65
69
  defaultRegistry,
66
70
  producedTypeOf,
@@ -74,6 +78,7 @@ export type {
74
78
  DiagnosticFix,
75
79
  EngineDiagnostic,
76
80
  EngineFileClaim,
81
+ ExpressionRegion,
77
82
  TemplatingEngine,
78
83
  } from "./engine.js";
79
84
 
package/src/sentinel.ts CHANGED
@@ -51,26 +51,18 @@ export const MODULE_PATH_ENGINE = "module-path";
51
51
  /**
52
52
  * The dotted chain a value names, or undefined.
53
53
  *
54
- * Only a PLAIN CHAIN — `steps.encode.result.output` — in either spelling a
55
- * manifest may carry it: a `!cel` sentinel or the `${{ }}` string form. An
56
- * expression that COMPUTES rather than names has no schema to read off a context,
57
- * so a caller that navigates one gets nothing and reports nothing: silence where
58
- * the analyzer knows least is the conservative direction.
54
+ * Only a PLAIN CHAIN written as a `!cel` value — `steps.encode.result.output`.
55
+ * An expression that COMPUTES rather than names has no schema to read off a
56
+ * context, so a caller that navigates one gets nothing and reports nothing:
57
+ * silence where the analyzer knows least is the conservative direction.
59
58
  *
60
59
  * Here rather than in each caller because "is this expression a plain chain" is
61
60
  * one question, and two copies of the answer would eventually disagree about a
62
61
  * shape like `a.b[0]`.
63
62
  */
64
63
  export function plainChainOf(value: unknown): string | undefined {
65
- const source = isTaggedSentinel(value)
66
- ? value.engine === CEL_ENGINE
67
- ? value.source
68
- : undefined
69
- : typeof value === "string"
70
- ? /^\s*\$\{\{(.+)\}\}\s*$/.exec(value)?.[1]
71
- : undefined;
72
- if (typeof source !== "string") return undefined;
73
- const trimmed = source.trim();
64
+ if (!isTaggedSentinel(value) || value.engine !== CEL_ENGINE) return undefined;
65
+ const trimmed = value.source.trim();
74
66
  return /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(trimmed)
75
67
  ? trimmed
76
68
  : undefined;