@telorun/templating 0.107.0 → 0.108.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 (60) hide show
  1. package/dist/builtins.d.ts +2 -2
  2. package/dist/builtins.d.ts.map +1 -1
  3. package/dist/cel/analyze.d.ts +6 -6
  4. package/dist/cel/analyze.d.ts.map +1 -1
  5. package/dist/cel/analyze.js +138 -183
  6. package/dist/cel/compile.d.ts +47 -17
  7. package/dist/cel/compile.d.ts.map +1 -1
  8. package/dist/cel/compile.js +135 -83
  9. package/dist/cel/diagnose.d.ts +52 -57
  10. package/dist/cel/diagnose.d.ts.map +1 -1
  11. package/dist/cel/diagnose.js +69 -291
  12. package/dist/cel/environment.d.ts +33 -37
  13. package/dist/cel/environment.d.ts.map +1 -1
  14. package/dist/cel/environment.js +54 -86
  15. package/dist/cel/module-call.d.ts +68 -79
  16. package/dist/cel/module-call.d.ts.map +1 -1
  17. package/dist/cel/module-call.js +118 -194
  18. package/dist/cel/value-brands.d.ts +14 -12
  19. package/dist/cel/value-brands.d.ts.map +1 -1
  20. package/dist/cel/value-brands.js +26 -24
  21. package/dist/cel/verdict-codes.d.ts +13 -2
  22. package/dist/cel/verdict-codes.d.ts.map +1 -1
  23. package/dist/cel/verdict-codes.js +20 -1
  24. package/dist/engine.d.ts +4 -4
  25. package/dist/engine.d.ts.map +1 -1
  26. package/dist/engines/cel.d.ts +2 -2
  27. package/dist/engines/cel.d.ts.map +1 -1
  28. package/dist/engines/cel.js +53 -81
  29. package/dist/engines/hole-analysis.d.ts +3 -3
  30. package/dist/engines/hole-analysis.d.ts.map +1 -1
  31. package/dist/engines/interpolate.js +11 -8
  32. package/dist/index.d.ts +4 -5
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +8 -5
  35. package/package.json +4 -4
  36. package/src/builtins.ts +2 -2
  37. package/src/cel/analyze.ts +152 -193
  38. package/src/cel/compile.ts +160 -77
  39. package/src/cel/diagnose.ts +115 -370
  40. package/src/cel/environment.ts +64 -87
  41. package/src/cel/module-call.ts +129 -292
  42. package/src/cel/value-brands.ts +26 -25
  43. package/src/cel/verdict-codes.ts +20 -1
  44. package/src/engine.ts +4 -4
  45. package/src/engines/cel.ts +52 -84
  46. package/src/engines/hole-analysis.ts +3 -3
  47. package/src/engines/interpolate.ts +16 -13
  48. package/src/index.ts +8 -11
  49. package/dist/cel/catalog.d.ts +0 -70
  50. package/dist/cel/catalog.d.ts.map +0 -1
  51. package/dist/cel/catalog.js +0 -1320
  52. package/dist/cel/json-prefix-scan.d.ts +0 -17
  53. package/dist/cel/json-prefix-scan.d.ts.map +0 -1
  54. package/dist/cel/json-prefix-scan.js +0 -160
  55. package/dist/cel/value-identity.d.ts +0 -18
  56. package/dist/cel/value-identity.d.ts.map +0 -1
  57. package/dist/cel/value-identity.js +0 -25
  58. package/src/cel/catalog.ts +0 -1455
  59. package/src/cel/json-prefix-scan.ts +0 -152
  60. package/src/cel/value-identity.ts +0 -34
@@ -1,1320 +0,0 @@
1
- import { formatLocale } from "d3-format";
2
- import { RE2JS, RE2JSSyntaxException } from "re2js";
3
- import { v1, v3, v4, v5, v6, v7, validate as uuidValidate, version as uuidVersion } from "uuid";
4
- import { PLAIN_ENCODINGS } from "@telorun/sdk";
5
- import { scanJsonPrefix } from "./json-prefix-scan.js";
6
- /** RE2 regex engine for the CEL `regex*` functions — `re2js`, a pure-JS port of
7
- * Google's RE2. The dialect is RE2 (linear-time, no backtracking, ReDoS-safe) —
8
- * never JS `RegExp` — so a manifest's regex behaves the same across runtimes.
9
- * Flags map a trailing option string to RE2 flags; inline `(?s)` etc. work in
10
- * the pattern too.
11
- *
12
- * Why pure-JS and not a native RE2:
13
- * - The Rust `regex` crate via napi (N-API) is faster, but shipping it means a
14
- * cross-platform prebuild matrix + per-triple npm packages — a whole release
15
- * subsystem for one function family.
16
- * - The `re2` npm package (Google's C++ RE2) is simpler to depend on, but it's a
17
- * nan/V8 addon and **does not load under Bun** (incomplete V8 C++ ABI →
18
- * `undefined symbol`). Telo's CLI and test suite run on Bun, so that's a
19
- * non-starter.
20
- * `re2js` is pure JS: zero native addons, runs identically on Node, Bun, and the
21
- * browser (keeps this package — and the analyzer — browser-safe), and needs no
22
- * prebuilds. The cost is throughput vs. native, which is irrelevant for the
23
- * small strings CEL manifests run regex over. */
24
- const RE2_FLAG = {
25
- i: RE2JS.CASE_INSENSITIVE,
26
- m: RE2JS.MULTILINE,
27
- s: RE2JS.DOTALL,
28
- };
29
- /** RE2's parse-error kinds, in RE2's own words — the closed vocabulary an
30
- * invalid-pattern refusal ends with, so every engine words one identically. */
31
- export const RE2_PATTERN_ERROR_KINDS = [
32
- "missing closing )",
33
- "missing closing ]",
34
- "unexpected )",
35
- "trailing backslash at end of expression",
36
- "invalid escape sequence",
37
- "invalid character class range",
38
- "invalid named capture",
39
- "duplicate capture group name",
40
- "invalid or unsupported Perl syntax",
41
- "missing argument to repetition operator",
42
- "invalid nested repetition operator",
43
- "invalid repeat count",
44
- "expression nests too deeply",
45
- "expression too large",
46
- ];
47
- /** A refusal a catalog function makes of its arguments — the one failure a
48
- * literal guard reports. It reads as a plain `Error` wherever it is printed. */
49
- class CatalogRefusal extends Error {
50
- }
51
- Object.defineProperty(CatalogRefusal, "name", { value: "Error" });
52
- const re2Flags = (fn, flags) => {
53
- let bits = 0;
54
- for (const c of flags ?? "") {
55
- if (c === "g")
56
- continue; // global is implicit in replaceAll / find-loop
57
- const bit = RE2_FLAG[c];
58
- if (bit === undefined)
59
- throw new CatalogRefusal(`${fn}: unknown regex flag '${c}' (supported: i, m, s)`);
60
- bits |= bit;
61
- }
62
- return bits;
63
- };
64
- /** The refusal is Telo's: the library's `error parsing regexp:` prefix and the
65
- * fragment it quotes never reach it. A failure outside the vocabulary is a
66
- * defect here, raised as one with the library's error as its cause. */
67
- const re2Pattern = (fn, pattern, bits) => {
68
- try {
69
- return RE2JS.compile(pattern, bits);
70
- }
71
- catch (e) {
72
- const kind = e instanceof RE2JSSyntaxException ? e.error : undefined;
73
- if (kind === undefined || !RE2_PATTERN_ERROR_KINDS.includes(kind)) {
74
- throw new Error(`${fn}: the RE2 compiler failed on pattern ${JSON.stringify(pattern)} with an error outside Telo's parse-error vocabulary`, { cause: e });
75
- }
76
- throw new CatalogRefusal(`${fn}: invalid RE2 pattern ${JSON.stringify(pattern)}: ${kind}`);
77
- }
78
- };
79
- const compileRe2 = (fn, pattern, flags) => re2Pattern(fn, pattern, re2Flags(fn, flags));
80
- /** Run a runtime guard for its refusal, so a `checkArgs` never restates one.
81
- * Anything else it throws is the engine failing, not the argument. */
82
- const literalGuard = (run) => {
83
- try {
84
- run();
85
- return undefined;
86
- }
87
- catch (e) {
88
- if (e instanceof CatalogRefusal)
89
- return e.message;
90
- throw e;
91
- }
92
- };
93
- /** A regex function's literal guard: the flags and the pattern, each judged
94
- * only when written as a literal, by the compile the runtime runs. */
95
- const regexLiteralGuard = (fn, patternAt, flagsAt) => (literals) => literalGuard(() => {
96
- const pattern = literals[patternAt];
97
- const flags = literals[flagsAt];
98
- const bits = typeof flags === "string" ? re2Flags(fn, flags) : 0;
99
- if (typeof pattern === "string")
100
- re2Pattern(fn, pattern, bits);
101
- });
102
- /** The host parser's verdict stands; Telo's scan only words its refusal. The
103
- * scan reading as JSON a text the host refused is a defect here. */
104
- const parseJsonText = (text) => {
105
- try {
106
- return JSON.parse(text);
107
- }
108
- catch (hostRefusal) {
109
- const refusal = scanJsonPrefix(text);
110
- if (refusal === undefined) {
111
- throw new Error("parseJson: the host JSON parser refused a text Telo's scan reads as valid JSON", {
112
- cause: hostRefusal,
113
- });
114
- }
115
- throw new Error(`parseJson: invalid JSON at offset ${refusal.offset}${refusal.endOfInput ? " (unexpected end of input)" : ""}`);
116
- }
117
- };
118
- const num = (x) => Number(x);
119
- const minMax = (list, isMin) => {
120
- if (!Array.isArray(list) || list.length === 0)
121
- return null;
122
- let best = list[0];
123
- let bestN = num(best);
124
- for (const x of list) {
125
- const n = num(x);
126
- if (isMin ? n < bestN : n > bestN) {
127
- best = x;
128
- bestN = n;
129
- }
130
- }
131
- return best;
132
- };
133
- const sortList = (list) => [...list].sort((a, b) => {
134
- if (typeof a === "number" || typeof a === "bigint") {
135
- const d = num(a) - num(b);
136
- return d < 0 ? -1 : d > 0 ? 1 : 0;
137
- }
138
- return String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
139
- });
140
- /** The number-formatting locale, pinned rather than defaulted.
141
- *
142
- * d3-format's default locale renders a negative with U+2212 MINUS SIGN, so
143
- * `format(-1.5, '.2f')` is `"−1.50"` and not `"-1.50"` — a string that no
144
- * downstream parser, comparison or diff treats as the number it looks like.
145
- * Every field here is fixed to its ASCII form for the same reason the layer is
146
- * locale-free at all: the same manifest must render the same bytes on every
147
- * runtime, and a second engine implementing the specifier grammar has to be
148
- * able to reproduce these exactly. */
149
- const FORMAT_LOCALE = formatLocale({
150
- decimal: ".",
151
- thousands: ",",
152
- grouping: [3],
153
- currency: ["$", ""],
154
- minus: "-",
155
- percent: "%",
156
- nan: "NaN",
157
- });
158
- /** Largest integer a double represents exactly. */
159
- const MAX_EXACT_INT = 9007199254740991n;
160
- /** A CEL `int` is a BigInt in this runtime and `d3-format` throws on one
161
- * outright, so a formattable argument is converted here. Past 2^53 a double
162
- * stops representing every integer, and silently emitting a number that is not
163
- * the one the author computed is the defect class this family exists to close —
164
- * so that case raises instead. */
165
- const formattable = (fn, x) => {
166
- if (typeof x === "bigint") {
167
- if (x > MAX_EXACT_INT || x < -MAX_EXACT_INT) {
168
- throw new CatalogRefusal(`${fn}: integer ${x} exceeds 2^53-1 and cannot be formatted exactly as a double`);
169
- }
170
- return Number(x);
171
- }
172
- const n = Number(x);
173
- // The runtime backstop behind the typed registrations. A value that is not a
174
- // number formats as the string "NaN", which is the failure this family exists
175
- // to remove: it looks like an answer and prints into a document. Named here
176
- // rather than coerced, the way an instant argument is.
177
- if (!Number.isFinite(n)) {
178
- throw new CatalogRefusal(`${fn}: expected a finite number, got ${JSON.stringify(x)}`);
179
- }
180
- return n;
181
- };
182
- /** Specifier type characters d3 implements. An unknown one PARSES — `.2q`
183
- * yields `"1"` rather than throwing — so a typo would silently format against
184
- * the default type. The set is checked here so a bad specifier is refused
185
- * rather than quietly answered. */
186
- const FORMAT_TYPES = new Set([..."efgrs%pbodxXcn"]);
187
- /** A specifier is a CEL value, so it can be request-derived — an `Http.Server`
188
- * evaluating `format(x, request.query.spec)` would otherwise grow this map for
189
- * the life of the process, and it is module-global, so every in-process kernel
190
- * shares it. Cleared wholesale at the cap rather than evicted one at a time: a
191
- * manifest's real specifier set is a handful of constants that repopulate
192
- * immediately, and an LRU is machinery for a hit rate nothing here needs. */
193
- const FORMATTER_CACHE_MAX = 256;
194
- const formatterCache = new Map();
195
- const formatter = (fn, spec) => {
196
- const text = String(spec);
197
- const cached = formatterCache.get(text);
198
- if (cached)
199
- return cached;
200
- const type = text.slice(-1);
201
- if (text !== "" && /[a-zA-Z%]/.test(type) && !FORMAT_TYPES.has(type)) {
202
- throw new CatalogRefusal(`${fn}: unknown format type '${type}' (one of ${[...FORMAT_TYPES].join("")})`);
203
- }
204
- // The `.precision` group — width is the digits BEFORE the dot, so this is the
205
- // only `.`-digits sequence the grammar admits.
206
- const precision = /\.(\d+)/.exec(text);
207
- if (precision)
208
- digitCount(fn, precision[1]);
209
- let built;
210
- try {
211
- built = FORMAT_LOCALE.format(text);
212
- }
213
- catch {
214
- throw new CatalogRefusal(`${fn}: invalid format specifier ${JSON.stringify(text)}`);
215
- }
216
- if (formatterCache.size >= FORMATTER_CACHE_MAX)
217
- formatterCache.clear();
218
- formatterCache.set(text, built);
219
- return built;
220
- };
221
- /** Decimal places, bounded. The ceiling is well below what `toFixed` accepts
222
- * because past it the digits are an artefact of the binary representation
223
- * rather than of the value.
224
- *
225
- * ONE rule, enforced wherever a precision is written: `formatter` applies it to
226
- * a specifier's `.precision` group too. Bounding only this spelling let an
227
- * author route around the guard by writing `format(x, '.11f')` instead of
228
- * `fixed(x, 11)` — the family giving two answers to one question. It is not the
229
- * grammar subsetting the "full d3 surface" decision refuses: every specifier
230
- * type and flag stays available, and only the digit count is capped. */
231
- const MAX_DECIMALS = 10;
232
- const digitCount = (fn, digits) => {
233
- const n = Number(digits);
234
- if (!Number.isInteger(n) || n < 0 || n > MAX_DECIMALS) {
235
- throw new CatalogRefusal(`${fn}: decimal places must be an integer 0-${MAX_DECIMALS}, got ${String(digits)}`);
236
- }
237
- return n;
238
- };
239
- /** Render a minute count against a declared day length. The day is a policy
240
- * argument, never an assumption — see the catalog entry's summary. */
241
- const durationText = (minutes, minutesPerDay) => {
242
- const perDay = Math.round(formattable("formatDuration", minutesPerDay));
243
- if (!Number.isFinite(perDay) || perDay <= 0) {
244
- throw new CatalogRefusal(`formatDuration: minutesPerDay must be a positive number, got ${perDay}`);
245
- }
246
- const total = Math.round(formattable("formatDuration", minutes));
247
- if (!Number.isFinite(total)) {
248
- throw new CatalogRefusal(`formatDuration: minutes must be a finite number`);
249
- }
250
- const magnitude = Math.abs(total);
251
- const days = Math.floor(magnitude / perDay);
252
- const withinDay = magnitude % perDay;
253
- const hours = Math.floor(withinDay / 60);
254
- const mins = withinDay % 60;
255
- const parts = [];
256
- if (days)
257
- parts.push(`${days}d`);
258
- if (hours)
259
- parts.push(`${hours}h`);
260
- if (mins)
261
- parts.push(`${mins}m`);
262
- if (parts.length === 0)
263
- parts.push("0m");
264
- return `${total < 0 ? "-" : ""}${parts.join(" ")}`;
265
- };
266
- /** Refuse an unknown zone in this family's own voice. Left to `Intl`, the
267
- * failure is a raw `RangeError` naming neither the function nor what was
268
- * wrong with the argument — the only refusal here that did not read
269
- * `<fn>: <what is wrong>`, and whose wording belongs to the JS engine rather
270
- * than to Telo. Also the guard `checkArgs` runs at analysis time, so a literal
271
- * zone is checked once and answered identically in both places. */
272
- const assertZone = (fn, tz) => {
273
- try {
274
- new Intl.DateTimeFormat("en-US", { timeZone: tz });
275
- }
276
- catch {
277
- throw new CatalogRefusal(`${fn}: unknown IANA time zone ${JSON.stringify(tz)}`);
278
- }
279
- return tz;
280
- };
281
- /** `Intl.DateTimeFormat` is an ECMA-402 global in Node (full ICU) and browsers,
282
- * so timezone handling needs no Node-only API and stays browser-safe. */
283
- const zoneParts = (date, tz, opts) => {
284
- const parts = {};
285
- for (const p of new Intl.DateTimeFormat("en-US", { timeZone: tz, ...opts }).formatToParts(date)) {
286
- parts[p.type] = p.value;
287
- }
288
- return parts;
289
- };
290
- /** Current instant as ISO-8601 in `tz`: UTC `…Z` for "UTC", else the zone's
291
- * offset (e.g. `2026-06-06T18:30:00.000-05:00`). Uses only standard Intl
292
- * fields and derives the offset arithmetically, so it needs no newer Intl
293
- * type-lib features and stays portable. */
294
- const isoInZone = (now, tz) => {
295
- if (tz === "UTC" || tz === "Z")
296
- return now.toISOString();
297
- const p = zoneParts(now, tz, {
298
- hourCycle: "h23",
299
- year: "numeric",
300
- month: "2-digit",
301
- day: "2-digit",
302
- hour: "2-digit",
303
- minute: "2-digit",
304
- second: "2-digit",
305
- });
306
- // Sub-second is timezone-independent; read it off the instant directly.
307
- const ms = String(now.getUTCMilliseconds()).padStart(3, "0");
308
- // Offset = the zone's wall-clock read as UTC, minus the real instant.
309
- const asUtc = Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +p.second);
310
- const offsetMin = Math.round((asUtc - now.getTime()) / 60000);
311
- const offset = offsetMin === 0
312
- ? "Z"
313
- : `${offsetMin > 0 ? "+" : "-"}${String(Math.floor(Math.abs(offsetMin) / 60)).padStart(2, "0")}:${String(Math.abs(offsetMin) % 60).padStart(2, "0")}`;
314
- return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}:${p.second}.${ms}${offset}`;
315
- };
316
- /** Calendar date (`YYYY-MM-DD`) of an instant in `tz`. */
317
- const dateInZone = (now, tz) => {
318
- if (tz === "UTC" || tz === "Z")
319
- return now.toISOString().slice(0, 10);
320
- const p = zoneParts(now, tz, { year: "numeric", month: "2-digit", day: "2-digit" });
321
- return `${p.year}-${p.month}-${p.day}`;
322
- };
323
- const zonedFields = (date, tz) => {
324
- const p = zoneParts(date, tz, {
325
- hourCycle: "h23",
326
- year: "numeric",
327
- month: "2-digit",
328
- day: "2-digit",
329
- hour: "2-digit",
330
- minute: "2-digit",
331
- second: "2-digit",
332
- });
333
- return {
334
- year: +p.year,
335
- month: +p.month,
336
- day: +p.day,
337
- hour: +p.hour,
338
- minute: +p.minute,
339
- second: +p.second,
340
- };
341
- };
342
- /** The zone's offset at `date`, in milliseconds — its wall clock read as UTC,
343
- * minus the real instant. The same arithmetic `isoInZone` does. */
344
- const zoneOffsetMs = (date, tz) => {
345
- const f = zonedFields(date, tz);
346
- return Date.UTC(f.year, f.month - 1, f.day, f.hour, f.minute, f.second) - date.getTime();
347
- };
348
- const sameWallClock = (a, b) => a.year === b.year &&
349
- a.month === b.month &&
350
- a.day === b.day &&
351
- a.hour === b.hour &&
352
- a.minute === b.minute &&
353
- a.second === b.second;
354
- /** The instant whose wall clock in `tz` is the given fields.
355
- *
356
- * The offset depends on the instant being solved for, so this takes the offset
357
- * at the UTC reading, corrects, and then CHECKS by reading the result back.
358
- * That check is the whole point: a plain fixpoint settles on an instant whose
359
- * wall clock is not the one asked for whenever the requested time does not
360
- * exist, and it settles BACKWARDS — which silently moves the calendar day, the
361
- * one thing `addMonths` and `startOfMonth` exist to control. Chile jumps
362
- * 00:00 → 01:00 on 2026-09-06 and Cuba on 2026-03-08, so "the 6th at midnight"
363
- * there is not a time; a fixpoint answered "the 5th at 23:00".
364
- *
365
- * Resolution follows Java's `ZonedDateTime` and Temporal's `compatible`:
366
- * a wall clock that exists twice (a fall-back) takes the EARLIER instant, and
367
- * one that does not exist (a spring-forward gap) shifts FORWARD out of the gap,
368
- * which keeps the requested day. */
369
- const instantOfZoned = (f, tz) => {
370
- const asUtc = Date.UTC(f.year, f.month - 1, f.day, f.hour, f.minute, f.second);
371
- const offsetA = zoneOffsetMs(new Date(asUtc), tz);
372
- const candidateA = asUtc - offsetA;
373
- const offsetB = zoneOffsetMs(new Date(candidateA), tz);
374
- if (offsetA === offsetB)
375
- return new Date(candidateA);
376
- const candidateB = asUtc - offsetB;
377
- const aHolds = sameWallClock(zonedFields(new Date(candidateA), tz), f);
378
- const bHolds = sameWallClock(zonedFields(new Date(candidateB), tz), f);
379
- if (aHolds && bHolds)
380
- return new Date(Math.min(candidateA, candidateB));
381
- if (aHolds)
382
- return new Date(candidateA);
383
- if (bHolds)
384
- return new Date(candidateB);
385
- return new Date(Math.max(candidateA, candidateB));
386
- };
387
- /** `Date.UTC` maps years 0-99 to 1900-1999, so the year is set explicitly. */
388
- const daysInMonth = (year, month) => {
389
- const d = new Date(Date.UTC(2000, month, 0));
390
- d.setUTCFullYear(year, month, 0);
391
- return d.getUTCDate();
392
- };
393
- /** An instant argument arrives as a `Date`; anything else is a caller error the
394
- * type-checker did not catch (a `dyn` slot), so it is named rather than
395
- * coerced into an Invalid Date that formats as `NaN`. */
396
- const instantArg = (fn, v) => {
397
- if (v instanceof Date && Number.isFinite(v.getTime()))
398
- return v;
399
- throw new Error(`${fn}: expected a timestamp`);
400
- };
401
- /** Drop entries whose value is null or the empty string. Nothing else: an empty
402
- * list or map is a value someone deliberately built. CEL hands a map over as a
403
- * plain object or a `Map` depending on how it was produced, so both are read. */
404
- const compactValue = (v) => {
405
- const keep = (x) => x !== null && x !== undefined && x !== "";
406
- if (Array.isArray(v))
407
- return v.filter(keep);
408
- if (v instanceof Map) {
409
- return new Map([...v.entries()].filter(([, value]) => keep(value)));
410
- }
411
- // A PLAIN object only. Rebuilding an arbitrary object from its entries is how
412
- // a byte buffer becomes `{"0":137,…}` and an instant becomes `{}` — silently,
413
- // and looking like a value. The same rule the compile walker follows, and the
414
- // same "name it rather than coerce it" the instant argument follows.
415
- if (v !== null && typeof v === "object") {
416
- const proto = Object.getPrototypeOf(v);
417
- if (proto !== Object.prototype && proto !== null) {
418
- throw new Error(`compact: expected a map or a list, got ${v.constructor?.name ?? "an object"}`);
419
- }
420
- return Object.fromEntries(Object.entries(v).filter(([, value]) => keep(value)));
421
- }
422
- throw new Error(`compact: expected a map or a list, got ${JSON.stringify(v)}`);
423
- };
424
- /** A CEL map as entries. Read the way `compact` reads one — a map arrives as a
425
- * plain object or a `Map` depending on how it was produced — and refusing
426
- * anything that is not one, since rebuilding an arbitrary object from its
427
- * entries is how a byte buffer becomes `{"0":137,…}` silently. A LIST is named
428
- * rather than coerced: CEL's `+` already concatenates lists, so a list here is
429
- * a mistake with a spelling that works, not a case to support. */
430
- const mapEntries = (fn, v) => {
431
- if (v instanceof Map)
432
- return [...v.entries()];
433
- if (Array.isArray(v))
434
- throw new Error(`${fn}: expected a map, got a list — use '+' to join lists`);
435
- if (v !== null && typeof v === "object") {
436
- const proto = Object.getPrototypeOf(v);
437
- if (proto !== Object.prototype && proto !== null) {
438
- throw new Error(`${fn}: expected a map, got ${v.constructor?.name ?? "an object"}`);
439
- }
440
- return Object.entries(v);
441
- }
442
- throw new Error(`${fn}: expected a map, got ${JSON.stringify(v)}`);
443
- };
444
- /** Right-hand precedence, so `merge(defaults, overrides)` reads as it looks.
445
- *
446
- * The map case is the one with no spelling at all — `+` joins lists and
447
- * strings and refuses maps — so a child kind inheriting a map-valued field
448
- * could only REPLACE it. That turns a default the parent set for a reason into
449
- * something every consumer must restate, and a consumer who restates it
450
- * incompletely gets a system that works until the omitted entry matters.
451
- *
452
- * Follows the LEFT argument's shape: this extends that map, so what comes back
453
- * is what was extended. */
454
- const mergeMaps = (a, b) => {
455
- const entries = [...mapEntries("merge", a), ...mapEntries("merge", b)];
456
- return a instanceof Map ? new Map(entries) : Object.fromEntries(entries);
457
- };
458
- const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
459
- /** Base64 → bytes, written out rather than delegated: `Buffer` is not browser-
460
- * safe and `atob` round-trips through a string, which is the corruption this
461
- * pair exists to avoid. Accepts the URL-safe alphabet and tolerates missing
462
- * padding, both of which appear in real API payloads; a character outside the
463
- * alphabet is a hard error rather than a silently dropped byte. */
464
- function decodeBase64ToBytes(input) {
465
- const clean = input.replace(/[\r\n\t ]/g, "").replace(/-/g, "+").replace(/_/g, "/").replace(/=+$/, "");
466
- // A remainder of 1 cannot come from any byte sequence: base64 encodes 3 bytes
467
- // as 4 characters, so the valid remainders are 0, 2 and 3. Left to the loop it
468
- // would leave 6 bits unwritten and return a SHORT buffer — the silently dropped
469
- // byte this function refuses for a bad character.
470
- if (clean.length % 4 === 1) {
471
- throw new Error("bytesFromBase64: input length is not valid base64");
472
- }
473
- const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
474
- let bits = 0;
475
- let acc = 0;
476
- let written = 0;
477
- for (const ch of clean) {
478
- const value = BASE64_ALPHABET.indexOf(ch);
479
- if (value < 0)
480
- throw new Error(`bytesFromBase64: '${ch}' is not a base64 character`);
481
- acc = (acc << 6) | value;
482
- bits += 6;
483
- if (bits >= 8) {
484
- bits -= 8;
485
- out[written++] = (acc >> bits) & 0xff;
486
- }
487
- }
488
- return out.subarray(0, written);
489
- }
490
- function encodeBytesToBase64(input) {
491
- let out = "";
492
- for (let i = 0; i < input.length; i += 3) {
493
- const a = input[i];
494
- const b = i + 1 < input.length ? input[i + 1] : undefined;
495
- const c = i + 2 < input.length ? input[i + 2] : undefined;
496
- out += BASE64_ALPHABET[a >> 2];
497
- out += BASE64_ALPHABET[((a & 0x03) << 4) | ((b ?? 0) >> 4)];
498
- out += b === undefined ? "=" : BASE64_ALPHABET[((b & 0x0f) << 2) | ((c ?? 0) >> 6)];
499
- out += c === undefined ? "=" : BASE64_ALPHABET[c & 0x3f];
500
- }
501
- return out;
502
- }
503
- export const CEL_FUNCTIONS = [
504
- // Collections
505
- {
506
- name: "join",
507
- signature: "join(list, string): string",
508
- category: "collection",
509
- summary: "Join list elements into a string with a separator.",
510
- deterministic: true,
511
- hostBacked: false,
512
- build: () => (list, sep) => list.map(String).join(sep),
513
- },
514
- {
515
- name: "keys",
516
- signature: "keys(map): list",
517
- category: "collection",
518
- summary: "List a map's keys.",
519
- deterministic: true,
520
- hostBacked: false,
521
- build: () => (map) => map instanceof Map ? [...map.keys()] : Object.keys(map),
522
- },
523
- {
524
- name: "values",
525
- signature: "values(map): list",
526
- category: "collection",
527
- summary: "List a map's values.",
528
- deterministic: true,
529
- hostBacked: false,
530
- build: () => (map) => map instanceof Map ? [...map.values()] : Object.values(map),
531
- },
532
- {
533
- name: "distinct",
534
- signature: "distinct(list): list",
535
- category: "collection",
536
- summary: "Remove duplicate elements, preserving order.",
537
- deterministic: true,
538
- hostBacked: false,
539
- build: () => (list) => [...new Set(list)],
540
- },
541
- {
542
- name: "reverse",
543
- signature: "reverse(list): list",
544
- category: "collection",
545
- summary: "Reverse a list (copy; never mutates the input).",
546
- deterministic: true,
547
- hostBacked: false,
548
- build: () => (list) => [...list].reverse(),
549
- },
550
- {
551
- name: "flatten",
552
- signature: "flatten(list): list",
553
- category: "collection",
554
- summary: "Flatten one level of nested lists.",
555
- deterministic: true,
556
- hostBacked: false,
557
- build: () => (list) => list.flat(),
558
- },
559
- {
560
- name: "sort",
561
- signature: "sort(list): list",
562
- category: "collection",
563
- summary: "Sort a list numerically (numbers) or lexicographically; copy.",
564
- deterministic: true,
565
- hostBacked: false,
566
- build: () => (list) => sortList(list),
567
- },
568
- {
569
- name: "range",
570
- signature: "range(int): list<int>",
571
- category: "collection",
572
- summary: "Integers [0, n-1] (empty for n <= 0); materializes indices for an unknown-length list.",
573
- deterministic: true,
574
- hostBacked: false,
575
- build: () => (n) => Array.from({ length: Math.max(0, Math.trunc(num(n))) }, (_unused, i) => BigInt(i)),
576
- },
577
- {
578
- name: "enumerate",
579
- signature: "enumerate(list): list",
580
- category: "collection",
581
- summary: "Pair each element with its zero-based position as {index, value}.",
582
- deterministic: true,
583
- hostBacked: false,
584
- build: () => (list) => list.map((value, i) => ({ index: BigInt(i), value })),
585
- },
586
- // Strings
587
- {
588
- name: "lower",
589
- signature: "lower(string): string",
590
- category: "string",
591
- summary: "Lowercase a string.",
592
- deterministic: true,
593
- hostBacked: false,
594
- build: () => (s) => s.toLowerCase(),
595
- },
596
- {
597
- name: "upper",
598
- signature: "upper(string): string",
599
- category: "string",
600
- summary: "Uppercase a string.",
601
- deterministic: true,
602
- hostBacked: false,
603
- build: () => (s) => s.toUpperCase(),
604
- },
605
- {
606
- name: "trim",
607
- signature: "trim(string): string",
608
- category: "string",
609
- summary: "Strip leading/trailing whitespace.",
610
- deterministic: true,
611
- hostBacked: false,
612
- build: () => (s) => s.trim(),
613
- },
614
- {
615
- name: "replace",
616
- signature: "replace(string, string, string): string",
617
- category: "string",
618
- summary: "Replace all occurrences of a substring.",
619
- deterministic: true,
620
- hostBacked: false,
621
- build: () => (s, a, b) => s.split(a).join(b),
622
- },
623
- {
624
- name: "split",
625
- signature: "split(string, string): list",
626
- category: "string",
627
- summary: "Split a string on a separator into a list.",
628
- deterministic: true,
629
- hostBacked: false,
630
- build: () => (s, sep) => s.split(sep),
631
- },
632
- {
633
- name: "regexReplace",
634
- signature: "regexReplace(string, string, string, string?): string",
635
- category: "string",
636
- summary: "Replace every regex match (RE2 syntax) with a replacement ($1 backrefs); flags like 'i', 'm', 's'.",
637
- deterministic: true,
638
- hostBacked: false,
639
- checkArgs: regexLiteralGuard("regexReplace", 1, 3),
640
- build: () => (s, pattern, replacement, flags) => compileRe2("regexReplace", pattern, flags).matcher(s).replaceAll(replacement),
641
- },
642
- {
643
- name: "regexExtract",
644
- signature: "regexExtract(string, string, string?): string",
645
- category: "string",
646
- summary: "First whole match of a regex (RE2 syntax), or '' when there is none.",
647
- deterministic: true,
648
- hostBacked: false,
649
- checkArgs: regexLiteralGuard("regexExtract", 1, 2),
650
- build: () => (s, pattern, flags) => {
651
- const m = compileRe2("regexExtract", pattern, flags).matcher(s);
652
- return m.find() ? (m.group() ?? "") : "";
653
- },
654
- },
655
- {
656
- name: "regexExtractAll",
657
- signature: "regexExtractAll(string, string, string?): list<string>",
658
- category: "string",
659
- summary: "Every whole match of a regex (RE2 syntax), in order.",
660
- deterministic: true,
661
- hostBacked: false,
662
- checkArgs: regexLiteralGuard("regexExtractAll", 1, 2),
663
- build: () => (s, pattern, flags) => {
664
- const m = compileRe2("regexExtractAll", pattern, flags).matcher(s);
665
- const out = [];
666
- while (m.find())
667
- out.push(m.group() ?? "");
668
- return out;
669
- },
670
- },
671
- {
672
- name: "regexGroups",
673
- signature: "regexGroups(string, string, string?): list<string>",
674
- category: "string",
675
- summary: "Capture groups of the first regex match (RE2 syntax); empty list when there is no match.",
676
- deterministic: true,
677
- hostBacked: false,
678
- checkArgs: regexLiteralGuard("regexGroups", 1, 2),
679
- build: () => (s, pattern, flags) => {
680
- const m = compileRe2("regexGroups", pattern, flags).matcher(s);
681
- if (!m.find())
682
- return [];
683
- return Array.from({ length: m.groupCount() }, (_unused, i) => m.group(i + 1) ?? "");
684
- },
685
- },
686
- {
687
- name: "trimPrefix",
688
- signature: "trimPrefix(string, string): string",
689
- category: "string",
690
- summary: "Strip a leading prefix if present.",
691
- deterministic: true,
692
- hostBacked: false,
693
- build: () => (s, prefix) => (s.startsWith(prefix) ? s.slice(prefix.length) : s),
694
- },
695
- {
696
- name: "trimSuffix",
697
- signature: "trimSuffix(string, string): string",
698
- category: "string",
699
- summary: "Strip a trailing suffix if present.",
700
- deterministic: true,
701
- hostBacked: false,
702
- build: () => (s, suffix) => suffix && s.endsWith(suffix) ? s.slice(0, s.length - suffix.length) : s,
703
- },
704
- // One `slice` over the three sequence types rather than three names: CEL
705
- // already treats `size()` that way, and the alternative teaches an author that
706
- // slicing bytes is a different operation from slicing a string.
707
- //
708
- // OVERLOADED BY PARAMETER TYPE, so a wrong receiver is rejected — `slice(42, 0,
709
- // 1)` matches nothing. What cannot ALSO be registered is a `dyn` parameter
710
- // variant: cel-js refuses overloads that overlap, and a `dyn` first parameter
711
- // overlaps all three. That is why the RETURN is `dyn` rather than the input's
712
- // own type. A step result whose producer declares no output type is `dyn`, and
713
- // with concrete returns the checker resolves such a call to whichever overload
714
- // was registered first and pins the result to it — so slicing an untyped byte
715
- // buffer came back typed `string`, and a byte consumer downstream reported a
716
- // mismatch against perfectly valid CEL. Precision on the way out would be lost
717
- // at the CEL boundary anyway, where type arguments are erased; being wrong
718
- // about an untyped receiver would not be.
719
- {
720
- name: "slice",
721
- signature: "slice(dyn, int, int): dyn",
722
- register: [
723
- "slice(bytes, int, int): dyn",
724
- "slice(string, int, int): dyn",
725
- "slice(list, int, int): dyn",
726
- ],
727
- // Not "string": it is the one function over strings, bytes AND lists, and the
728
- // category is what groups it in the generated reference — filing it under
729
- // strings hides it from the byte and list readers who need it most.
730
- category: "collection",
731
- summary: "Take the half-open range [start, end) of a string, bytes or list.",
732
- deterministic: true,
733
- hostBacked: false,
734
- // Indices arrive as BigInt (a CEL int is int64), and both `String.slice` and
735
- // `TypedArray.subarray` reject one. `subarray` rather than `slice` for bytes:
736
- // a view costs no copy, and every consumer treats the result as read-only.
737
- build: () => (value, start, end) => {
738
- const from = Number(start);
739
- const to = Number(end);
740
- return value instanceof Uint8Array ? value.subarray(from, to) : value.slice(from, to);
741
- },
742
- },
743
- // Math
744
- {
745
- name: "abs",
746
- signature: "abs(dyn): double",
747
- category: "math",
748
- summary: "Absolute value.",
749
- deterministic: true,
750
- hostBacked: false,
751
- build: () => (x) => Math.abs(num(x)),
752
- },
753
- {
754
- name: "floor",
755
- signature: "floor(dyn): double",
756
- category: "math",
757
- summary: "Round down to an integer.",
758
- deterministic: true,
759
- hostBacked: false,
760
- build: () => (x) => Math.floor(num(x)),
761
- },
762
- {
763
- name: "ceil",
764
- signature: "ceil(dyn): double",
765
- category: "math",
766
- summary: "Round up to an integer.",
767
- deterministic: true,
768
- hostBacked: false,
769
- build: () => (x) => Math.ceil(num(x)),
770
- },
771
- {
772
- name: "round",
773
- signature: "round(dyn, int?): double",
774
- register: [
775
- "round(double): double",
776
- "round(int): double",
777
- "round(double, int): double",
778
- "round(int, int): double",
779
- ],
780
- category: "math",
781
- summary: "Round to the nearest integer, or to the given number of decimal places (0–10). The two-argument form shares the formatter's rounding rule, so a rounded value and the cell rendered beside it agree at the boundary. An integer past 2^53 is refused rather than rounded to a neighbour.",
782
- deterministic: true,
783
- hostBacked: false,
784
- // Both arities go through `formattable`, so the 2^53 refusal does not depend
785
- // on which one the author wrote. Guarding only the two-argument form left
786
- // `round(x)` silently answering with a neighbouring integer — the defect
787
- // this family exists to close, reachable by writing one fewer argument.
788
- build: () => (x, digits) => digits === undefined
789
- ? Math.round(formattable("round", x))
790
- : Number(formattable("round", x).toFixed(digitCount("round", digits))),
791
- checkArgs: (lit) => literalGuard(() => {
792
- if (lit[1] !== undefined)
793
- digitCount("round", lit[1]);
794
- if (typeof lit[0] === "bigint")
795
- formattable("round", lit[0]);
796
- }),
797
- },
798
- {
799
- name: "min",
800
- signature: "min(list): dyn",
801
- category: "math",
802
- summary: "Smallest element (by numeric value); null for an empty list.",
803
- deterministic: true,
804
- hostBacked: false,
805
- build: () => (list) => minMax(list, true),
806
- },
807
- {
808
- name: "max",
809
- signature: "max(list): dyn",
810
- category: "math",
811
- summary: "Largest element (by numeric value); null for an empty list.",
812
- deterministic: true,
813
- hostBacked: false,
814
- build: () => (list) => minMax(list, false),
815
- },
816
- {
817
- name: "sum",
818
- signature: "sum(list): double",
819
- category: "math",
820
- summary: "Sum of a list's numeric elements; 0 for an empty list.",
821
- deterministic: true,
822
- hostBacked: false,
823
- build: () => (list) => Array.isArray(list) ? list.reduce((acc, x) => acc + num(x), 0) : 0,
824
- },
825
- {
826
- name: "avg",
827
- signature: "avg(list): dyn",
828
- category: "math",
829
- summary: "Arithmetic mean of a list's numeric elements; null for an empty list.",
830
- deterministic: true,
831
- hostBacked: false,
832
- build: () => (list) => Array.isArray(list) && list.length > 0
833
- ? list.reduce((acc, x) => acc + num(x), 0) / list.length
834
- : null,
835
- },
836
- // JSON
837
- {
838
- name: "json",
839
- signature: "json(dyn): string",
840
- category: "json",
841
- summary: "Serialize any value to a JSON string.",
842
- deterministic: true,
843
- hostBacked: true,
844
- build: (h) => (value) => h.json(value),
845
- },
846
- {
847
- name: "parseJson",
848
- signature: "parseJson(string): dyn",
849
- category: "json",
850
- summary: "Parse a JSON string into a value (numbers come back as doubles).",
851
- deterministic: true,
852
- hostBacked: false,
853
- build: () => (s) => parseJsonText(s),
854
- },
855
- // Paths. The one way to extend a host path: `variables.dataDir.joinPath('reports')`
856
- // keeps it a `Telo.HostPath` (the analyzer types that overload), where `+`
857
- // would make it a plain string. Host-backed because what a separator IS
858
- // belongs to the machine running it.
859
- {
860
- name: "joinPath",
861
- signature: "string.joinPath(string): string",
862
- register: ["string.joinPath(string): string"],
863
- category: "string",
864
- summary: "Join a relative path onto a path with the host's separator (`\\` on Windows). On a host path it yields a host path; an absolute argument is refused.",
865
- deterministic: true,
866
- hostBacked: true,
867
- build: (h) => (base, relative) => h.joinPath(base, relative),
868
- },
869
- // Encoding
870
- {
871
- name: "base64Encode",
872
- signature: "base64Encode(string): string",
873
- category: "encoding",
874
- summary: "Encode a UTF-8 string as base64.",
875
- deterministic: true,
876
- hostBacked: true,
877
- build: (h) => (s) => h.base64Encode(s),
878
- },
879
- {
880
- name: "base64Decode",
881
- signature: "base64Decode(string): string",
882
- category: "encoding",
883
- summary: "Decode a base64 string to UTF-8.",
884
- deterministic: true,
885
- hostBacked: true,
886
- build: (h) => (s) => h.base64Decode(s),
887
- },
888
- // Base64 <-> BYTES, as distinct from the two above, which are UTF-8
889
- // string<->string and silently corrupt anything that is not text. Those keep
890
- // their meaning (changing it would change what shipped manifests mean); these
891
- // are the correct path for binary, and the pair a byte-typed slot needs.
892
- // Pure-JS on purpose: `Buffer` is what made the string pair host-backed, and
893
- // this package has to stay browser-safe.
894
- {
895
- name: "bytesFromBase64",
896
- signature: "bytesFromBase64(string): bytes",
897
- category: "encoding",
898
- summary: "Decode a base64 string to raw bytes.",
899
- deterministic: true,
900
- hostBacked: false,
901
- build: () => (s) => decodeBase64ToBytes(s),
902
- },
903
- {
904
- name: "bytesToBase64",
905
- signature: "bytesToBase64(bytes): string",
906
- category: "encoding",
907
- summary: "Encode raw bytes as a base64 string.",
908
- deterministic: true,
909
- hostBacked: false,
910
- build: () => (b) => encodeBytesToBase64(b),
911
- },
912
- {
913
- name: "urlEncode",
914
- signature: "urlEncode(string): string",
915
- category: "encoding",
916
- summary: "Percent-encode a URI component.",
917
- deterministic: true,
918
- hostBacked: false,
919
- build: () => (s) => encodeURIComponent(s),
920
- },
921
- {
922
- name: "urlDecode",
923
- signature: "urlDecode(string): string",
924
- category: "encoding",
925
- summary: "Decode a percent-encoded URI component.",
926
- deterministic: true,
927
- hostBacked: false,
928
- build: () => (s) => decodeURIComponent(s),
929
- },
930
- // Hashing
931
- {
932
- name: "sha256",
933
- signature: "sha256(string): string",
934
- category: "hashing",
935
- summary: "SHA-256 hash, hex-encoded.",
936
- deterministic: true,
937
- hostBacked: true,
938
- build: (h) => (s) => h.sha256(s),
939
- },
940
- {
941
- name: "md5",
942
- signature: "md5(string): string",
943
- category: "hashing",
944
- summary: "MD5 hash, hex-encoded.",
945
- deterministic: true,
946
- hostBacked: true,
947
- build: (h) => (s) => h.md5(s),
948
- },
949
- {
950
- name: "sha1",
951
- signature: "sha1(string): string",
952
- category: "hashing",
953
- summary: "SHA-1 hash, hex-encoded.",
954
- deterministic: true,
955
- hostBacked: true,
956
- build: (h) => (s) => h.sha1(s),
957
- },
958
- {
959
- name: "sha512",
960
- signature: "sha512(string): string",
961
- category: "hashing",
962
- summary: "SHA-512 hash, hex-encoded.",
963
- deterministic: true,
964
- hostBacked: true,
965
- build: (h) => (s) => h.sha512(s),
966
- },
967
- {
968
- name: "hmac",
969
- signature: "hmac(string, string, string): string",
970
- category: "hashing",
971
- summary: "HMAC of message under key for an algorithm (e.g. 'sha256'), hex.",
972
- deterministic: true,
973
- hostBacked: true,
974
- build: (h) => (algo, key, msg) => h.hmac(algo, key, msg),
975
- },
976
- // Null handling
977
- {
978
- name: "default",
979
- signature: "default(dyn, dyn): dyn",
980
- category: "null",
981
- summary: "Return the value, or the fallback when it is null.",
982
- deterministic: true,
983
- hostBacked: false,
984
- build: () => (v, fallback) => v === null || v === undefined ? fallback : v,
985
- },
986
- {
987
- name: "coalesce",
988
- signature: "coalesce(list): dyn",
989
- category: "null",
990
- summary: "First non-null element of a list, or null.",
991
- deterministic: true,
992
- hostBacked: false,
993
- build: () => (list) => {
994
- const found = list.find((x) => x !== null && x !== undefined);
995
- return found === undefined ? null : found;
996
- },
997
- },
998
- // Time (non-deterministic). `nowIso`/`today` take an optional IANA timezone
999
- // (default "UTC"); epoch values are absolute and take none.
1000
- {
1001
- name: "now",
1002
- signature: "now(): timestamp",
1003
- register: ["now(): google.protobuf.Timestamp"],
1004
- category: "time",
1005
- summary: "Current instant as a native timestamp, for comparison and duration arithmetic.",
1006
- deterministic: false,
1007
- hostBacked: false,
1008
- build: () => () => new Date(),
1009
- },
1010
- {
1011
- name: "nowIso",
1012
- signature: "nowIso(string?): string",
1013
- category: "time",
1014
- summary: "Current time as ISO-8601; UTC by default, or in the given IANA timezone.",
1015
- deterministic: false,
1016
- hostBacked: false,
1017
- build: () => (tz) => isoInZone(new Date(), tz ?? "UTC"),
1018
- },
1019
- {
1020
- name: "today",
1021
- signature: "today(string?): string",
1022
- category: "time",
1023
- summary: "Current calendar date (YYYY-MM-DD); UTC by default, or in the given IANA timezone.",
1024
- deterministic: false,
1025
- hostBacked: false,
1026
- build: () => (tz) => dateInZone(new Date(), tz ?? "UTC"),
1027
- },
1028
- {
1029
- name: "nowMillis",
1030
- signature: "nowMillis(): int",
1031
- category: "time",
1032
- summary: "Current time as epoch milliseconds (absolute; timezone-independent).",
1033
- deterministic: false,
1034
- hostBacked: false,
1035
- build: () => () => BigInt(Date.now()),
1036
- },
1037
- {
1038
- name: "nowSeconds",
1039
- signature: "nowSeconds(): int",
1040
- category: "time",
1041
- summary: "Current time as epoch seconds (absolute; timezone-independent).",
1042
- deterministic: false,
1043
- hostBacked: false,
1044
- build: () => () => BigInt(Math.floor(Date.now() / 1000)),
1045
- },
1046
- // Timestamp conversions. cel-go's standard library defines both and cel-js
1047
- // ships neither, which is what made an instant a one-way door: timestamp
1048
- // arithmetic and the `getFullYear` / `getHours` family already work, but
1049
- // nothing converted the result back into a value a manifest field accepts,
1050
- // so an expiry could be computed and not stored. Semantics follow cel-go
1051
- // exactly — RFC 3339 and epoch SECONDS — so `int(timestamp)` and
1052
- // `timestamp(int)` round-trip in one unit.
1053
- //
1054
- // `string(duration)` is cel-spec's too, and cel-js omits it: seconds with a
1055
- // trimmed fraction, the `Telo.Duration` plain encoding, so a duration renders
1056
- // one way whether it is interpolated or serialized.
1057
- {
1058
- name: "string",
1059
- signature: "string(timestamp | duration): string",
1060
- register: [
1061
- "string(google.protobuf.Timestamp): string",
1062
- "string(google.protobuf.Duration): string",
1063
- ],
1064
- category: "conversion",
1065
- summary: "Format an instant as RFC 3339 (ISO-8601, UTC), or a duration as seconds with a trimmed fraction (`5400s`, `1.5s`).",
1066
- deterministic: true,
1067
- hostBacked: false,
1068
- build: () => (value) => value instanceof Date ? value.toISOString() : PLAIN_ENCODINGS["cel-duration"].encode(value),
1069
- },
1070
- {
1071
- name: "int",
1072
- signature: "int(timestamp): int",
1073
- register: ["int(google.protobuf.Timestamp): int"],
1074
- category: "conversion",
1075
- summary: "Epoch seconds of an instant (the unit `timestamp(int)` reads back).",
1076
- deterministic: true,
1077
- hostBacked: false,
1078
- build: () => (t) => BigInt(Math.floor(t.getTime() / 1000)),
1079
- },
1080
- // Formatting. The number surface is the d3-format specifier grammar in full,
1081
- // `[[fill]align][sign][symbol][0][width][,][.precision][~][type]`, so a chart
1082
- // axis label and the table cell beside it cannot round the same value two
1083
- // ways. Rounding is therefore d3's: `f` rounds the double at the decimal
1084
- // place, so `.2f` of 1.005 is "1.00" — 1.005 is not representable and the
1085
- // nearest double sits below the half.
1086
- {
1087
- name: "format",
1088
- signature: "format(dyn, string): string",
1089
- // Registered per numeric type rather than as `dyn`. A `dyn` first parameter
1090
- // accepted a string and answered "NaN" — a value that looks like an answer
1091
- // and prints into a document. A genuinely dynamic expression still passes,
1092
- // because cel-js matches `dyn` against any declared parameter type; what
1093
- // this rejects is a STATICALLY known wrong type, at `telo check`.
1094
- register: ["format(double, string): string", "format(int, string): string"],
1095
- category: "formatting",
1096
- summary: "Format a number with a d3-format specifier (`.2f`, `,.2f`, `.1%`, `.2s`).",
1097
- deterministic: true,
1098
- hostBacked: false,
1099
- build: () => (x, spec) => formatter("format", spec)(formattable("format", x)),
1100
- checkArgs: (lit) => literalGuard(() => {
1101
- if (lit[1] !== undefined)
1102
- formatter("format", lit[1]);
1103
- if (typeof lit[0] === "bigint")
1104
- formattable("format", lit[0]);
1105
- }),
1106
- },
1107
- {
1108
- name: "fixed",
1109
- signature: "fixed(dyn, int): string",
1110
- register: ["fixed(double, int): string", "fixed(int, int): string"],
1111
- category: "formatting",
1112
- summary: "Fixed-decimal string with the given number of places (0–10).",
1113
- deterministic: true,
1114
- hostBacked: false,
1115
- build: () => (x, digits) => formatter("fixed", `.${digitCount("fixed", digits)}f`)(formattable("fixed", x)),
1116
- checkArgs: (lit) => literalGuard(() => {
1117
- if (lit[1] !== undefined)
1118
- digitCount("fixed", lit[1]);
1119
- if (typeof lit[0] === "bigint")
1120
- formattable("fixed", lit[0]);
1121
- }),
1122
- },
1123
- {
1124
- name: "formatDuration",
1125
- signature: "formatDuration(dyn, int): string",
1126
- register: [
1127
- "formatDuration(double, int): string",
1128
- "formatDuration(int, int): string",
1129
- ],
1130
- category: "formatting",
1131
- summary: "Render a minute count against a declared day length: `formatDuration(510, 480)` is `1d 30m`. The day length is an argument because it is a policy, not arithmetic. The result is a rendering for a reader, not a duration literal — its `d` is the declared day, so it must not be fed back into a field that parses a duration.",
1132
- deterministic: true,
1133
- hostBacked: false,
1134
- build: () => (minutes, minutesPerDay) => durationText(minutes, minutesPerDay),
1135
- checkArgs: (lit) => literalGuard(() => {
1136
- if (lit[1] !== undefined)
1137
- durationText(lit[0] ?? 0, lit[1]);
1138
- }),
1139
- },
1140
- {
1141
- name: "dateIn",
1142
- signature: "dateIn(timestamp, string?): string",
1143
- register: [
1144
- "dateIn(google.protobuf.Timestamp): string",
1145
- "dateIn(google.protobuf.Timestamp, string): string",
1146
- ],
1147
- category: "time",
1148
- summary: "Calendar date (`YYYY-MM-DD`) of an instant, in an IANA zone (UTC by default).",
1149
- deterministic: true,
1150
- hostBacked: false,
1151
- build: () => (t, tz) => dateInZone(instantArg("dateIn", t), assertZone("dateIn", tz ?? "UTC")),
1152
- checkArgs: (lit) => literalGuard(() => {
1153
- if (typeof lit[1] === "string")
1154
- assertZone("dateIn", lit[1]);
1155
- }),
1156
- },
1157
- {
1158
- name: "isoIn",
1159
- signature: "isoIn(timestamp, string?): string",
1160
- register: [
1161
- "isoIn(google.protobuf.Timestamp): string",
1162
- "isoIn(google.protobuf.Timestamp, string): string",
1163
- ],
1164
- category: "time",
1165
- summary: "ISO-8601 rendering of an instant, in an IANA zone (UTC by default).",
1166
- deterministic: true,
1167
- hostBacked: false,
1168
- build: () => (t, tz) => isoInZone(instantArg("isoIn", t), assertZone("isoIn", tz ?? "UTC")),
1169
- checkArgs: (lit) => literalGuard(() => {
1170
- if (typeof lit[1] === "string")
1171
- assertZone("isoIn", lit[1]);
1172
- }),
1173
- },
1174
- {
1175
- name: "startOfMonth",
1176
- signature: "startOfMonth(timestamp, string?): timestamp",
1177
- register: [
1178
- "startOfMonth(google.protobuf.Timestamp): google.protobuf.Timestamp",
1179
- "startOfMonth(google.protobuf.Timestamp, string): google.protobuf.Timestamp",
1180
- ],
1181
- category: "time",
1182
- summary: "Midnight on the 1st of the instant's month, in an IANA zone (UTC by default).",
1183
- deterministic: true,
1184
- hostBacked: false,
1185
- checkArgs: (lit) => literalGuard(() => {
1186
- if (typeof lit[1] === "string")
1187
- assertZone("startOfMonth", lit[1]);
1188
- }),
1189
- build: () => (t, tz) => {
1190
- const zone = assertZone("startOfMonth", tz ?? "UTC");
1191
- const f = zonedFields(instantArg("startOfMonth", t), zone);
1192
- return instantOfZoned({ year: f.year, month: f.month, day: 1, hour: 0, minute: 0, second: 0 }, zone);
1193
- },
1194
- },
1195
- {
1196
- name: "addMonths",
1197
- signature: "addMonths(timestamp, int, string?): timestamp",
1198
- register: [
1199
- "addMonths(google.protobuf.Timestamp, int): google.protobuf.Timestamp",
1200
- "addMonths(google.protobuf.Timestamp, int, string): google.protobuf.Timestamp",
1201
- ],
1202
- category: "time",
1203
- summary: "Shift an instant by whole months in an IANA zone, clamping the day of month (Jan 31 + 1 month is Feb 28).",
1204
- deterministic: true,
1205
- hostBacked: false,
1206
- checkArgs: (lit) => literalGuard(() => {
1207
- if (typeof lit[2] === "string")
1208
- assertZone("addMonths", lit[2]);
1209
- }),
1210
- build: () => (t, months, tz) => {
1211
- const zone = assertZone("addMonths", tz ?? "UTC");
1212
- const f = zonedFields(instantArg("addMonths", t), zone);
1213
- const shifted = f.year * 12 + (f.month - 1) + Number(months);
1214
- // `%` takes the dividend's sign in JS, so a negative total would yield
1215
- // month 0. Unreachable for realistic dates and wrong for free otherwise.
1216
- const year = Math.floor(shifted / 12);
1217
- const month = (((shifted % 12) + 12) % 12) + 1;
1218
- return instantOfZoned({ ...f, year, month, day: Math.min(f.day, daysInMonth(year, month)) }, zone);
1219
- },
1220
- },
1221
- {
1222
- name: "compact",
1223
- signature: "compact(dyn): dyn",
1224
- // A `dyn` parameter accepted an instant (yielding `{}`) and a byte buffer
1225
- // (yielding `{"0":137,…}`), both silently and both passing `telo check`.
1226
- register: ["compact(list): list", "compact(map): map"],
1227
- category: "collection",
1228
- summary: "Drop entries whose value is null or the empty string, from a map or a list.",
1229
- deterministic: true,
1230
- hostBacked: false,
1231
- build: () => (v) => compactValue(v),
1232
- },
1233
- {
1234
- name: "merge",
1235
- signature: "merge(map, map): map",
1236
- register: ["merge(map, map): map"],
1237
- category: "collection",
1238
- summary: "Combine two maps, with the right-hand map winning on a shared key. Use it to add to a map rather than replace it — `merge(defaults, overrides)`.",
1239
- deterministic: true,
1240
- hostBacked: false,
1241
- build: () => (a, b) => mergeMaps(a, b),
1242
- },
1243
- // UUID
1244
- {
1245
- name: "uuidv1",
1246
- signature: "uuidv1(): string",
1247
- category: "uuid",
1248
- summary: "Time-based UUID (v1).",
1249
- deterministic: false,
1250
- hostBacked: false,
1251
- build: () => () => v1(),
1252
- },
1253
- {
1254
- name: "uuidv4",
1255
- signature: "uuidv4(): string",
1256
- category: "uuid",
1257
- summary: "Random UUID (v4).",
1258
- deterministic: false,
1259
- hostBacked: false,
1260
- build: () => () => v4(),
1261
- },
1262
- {
1263
- name: "uuidv6",
1264
- signature: "uuidv6(): string",
1265
- category: "uuid",
1266
- summary: "Time-ordered UUID (v6).",
1267
- deterministic: false,
1268
- hostBacked: false,
1269
- build: () => () => v6(),
1270
- },
1271
- {
1272
- name: "uuidv7",
1273
- signature: "uuidv7(): string",
1274
- category: "uuid",
1275
- summary: "Time-ordered UUID (v7).",
1276
- deterministic: false,
1277
- hostBacked: false,
1278
- build: () => () => v7(),
1279
- },
1280
- {
1281
- name: "uuidv3",
1282
- signature: "uuidv3(string, string): string",
1283
- category: "uuid",
1284
- summary: "Name-based UUID (v3, MD5) under a namespace UUID.",
1285
- deterministic: true,
1286
- hostBacked: false,
1287
- build: () => (name, ns) => v3(name, ns),
1288
- },
1289
- {
1290
- name: "uuidv5",
1291
- signature: "uuidv5(string, string): string",
1292
- category: "uuid",
1293
- summary: "Name-based UUID (v5, SHA-1) under a namespace UUID.",
1294
- deterministic: true,
1295
- hostBacked: false,
1296
- build: () => (name, ns) => v5(name, ns),
1297
- },
1298
- {
1299
- name: "uuidValidate",
1300
- signature: "uuidValidate(string): bool",
1301
- category: "uuid",
1302
- summary: "True if the string is a valid UUID.",
1303
- deterministic: true,
1304
- hostBacked: false,
1305
- build: () => (s) => uuidValidate(s),
1306
- },
1307
- {
1308
- name: "uuidVersion",
1309
- signature: "uuidVersion(string): int",
1310
- category: "uuid",
1311
- summary: "The version number of a UUID.",
1312
- deterministic: true,
1313
- hostBacked: false,
1314
- build: () => (s) => BigInt(uuidVersion(s)),
1315
- },
1316
- ];
1317
- /** Build-free catalog for the CLI / docs (`telo cel functions`). */
1318
- export function celFunctionCatalog() {
1319
- return CEL_FUNCTIONS.map(({ build: _build, ...info }) => info);
1320
- }