Repository navigation
Expand file tree
/
Copy pathcel-engine.ts
More file actions
2386 lines (2282 loc) · 116 KB
/
Copy pathcel-engine.ts
File metadata and controls
2386 lines (2282 loc) · 116 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* CEL dialect engine — wraps `@marcbachmann/cel-js` with the ObjectStack
* stdlib, bounded execution limits, and result coercion.
*
* Why a thin wrapper:
*
* - cel-js returns `BigInt` for ints. The kernel and CRM expect plain
* numbers, so we coerce at the boundary.
* - cel-js parses dotted names as receiver-typed methods; we register
* `now()`, `today()`, `daysFromNow()` as bare functions and let `os.*`
* refer to context data only (see {@link buildScope}).
* - Bounds (`maxAstNodes`, `maxDepth`, …) are enforced spec-wide so
* third-party plugins can't ship runaway predicates.
*/
import { Environment, EvaluationError, ParseError, TypeError as CelTypeError, serialize } from '@marcbachmann/cel-js';
import type { ASTNode } from '@marcbachmann/cel-js';
import type { Expression } from '@objectstack/spec';
import { buildScope, registerBoundStdLib, registerNumericCoercions, registerStdLib } from './stdlib';
import type { PermissionBinding, StdLibBinding } from './stdlib';
import type { DialectEngine, EvalContext, EvalResult } from './types';
import type { CelRootsRefusalCode, ExpressionRefusal } from './expression-refusal';
/**
* Default execution bounds. Picked conservatively — every metadata-authored
* expression we've seen is well under these. If you hit them, the expression
* is too complex for a CEL formula and should move to a hook/action body
* (`ScriptBody { language: 'js' }`, the L2 sandboxed surface).
*/
export const DEFAULT_LIMITS = {
maxAstNodes: 256,
maxDepth: 32,
maxListElements: 64,
maxMapEntries: 64,
maxCallArguments: 16,
} as const;
/**
* The `Environment` options EVERY ObjectStack CEL evaluation is built with.
*
* Named rather than inlined so the stdlib drift pin
* (`cel-stdlib-drift.test.ts`) can construct the *same* environment it
* measures. A pin that hand-rebuilt a lookalike would keep passing after these
* options changed underneath it — measuring an environment nothing evaluates
* in, which is the exact failure mode the pin exists to prevent.
*
* Not re-exported from `index.ts`: package-internal seam, not public API.
*/
export const CEL_ENV_OPTIONS = {
unlistedVariablesAreDyn: true,
enableOptionalTypes: true,
limits: DEFAULT_LIMITS,
} as const;
/**
* Build the evaluation `Environment` — cel-js's own global registrations plus
* {@link registerStdLib} and {@link registerNumericCoercions}.
*
* Exported (package-internal; NOT in `index.ts`) so the stdlib drift pin reads
* the authoritative environment through the same constructor the engine uses
* ({@link buildEnvReading}, which also builds the shared evaluation environment).
*
* `permissionBinding` is the acting subject plus its effective object
* permissions and held system capabilities, pinned for this one evaluation
* (see `PermissionBinding`). Every caller that is not evaluating —
* `compile()`, the drift pin, the function-existence oracle — omits it, and
* that is exactly right: it changes what `can` / `hasCapability` ANSWER, never
* whether they EXIST, so the set of registered
* names is identical with and without it and a publish-time verdict can never
* disagree with the runtime about which names resolve.
*/
export function buildEnv(
now: () => Date,
timezone = 'UTC',
permissionBinding?: PermissionBinding,
): Environment {
const pinned: StdLibBinding = { now, timezone, permissionBinding };
return buildEnvReading(() => pinned);
}
/**
* The one constructor behind {@link buildEnv} and the shared evaluation
* environment: the same options and the same registrations, with the stdlib
* reading its `now`, timezone, permission binding and option labels through
* `read`.
*/
function buildEnvReading(read: () => StdLibBinding): Environment {
const env = new Environment(CEL_ENV_OPTIONS);
return registerNumericCoercions(registerBoundStdLib(env, read));
}
/**
* What the shared evaluation environment's stdlib answers from outside any
* evaluation: no permission binding, so `can` / `hasCapability` refuse exactly
* as an environment built without one does. No function of that environment
* runs outside `celEngine.evaluate`, which always sets its own binding.
*/
const UNBOUND: StdLibBinding = { now: () => new Date(), timezone: 'UTC', permissionBinding: undefined };
/**
* The binding of the evaluation now running on {@link evaluationEnv}, or
* {@link UNBOUND} when none is.
*
* `celEngine.evaluate` saves it, sets its own and restores the saved one in a
* `finally`, so a nested evaluation and a thrown one both leave the outer
* binding exactly as it was, and no binding outlives its evaluation.
*
* Every evaluation runs to completion inside `evaluate`: cel-js goes
* asynchronous only for a function registered as async, and this environment
* registers none. A Promise-valued scope value is refused (`Unsupported type:
* Promise`, a `runtime` fault), so no continuation ever reads the slot later.
*/
let activeBinding: StdLibBinding = UNBOUND;
/**
* The evaluation environment, built once and reused by every
* `celEngine.evaluate` (#24536). Building the stdlib per evaluation was most
* of an evaluation's cost.
*
* Sharing it is sound because a cel-js `Environment` keeps no per-evaluation
* state: each evaluation gets its own `RootContext`, the parser resets its
* input and limit counters at the start of every parse, and what the registry
* caches (type declarations, overload resolution) is keyed on types, never on
* values. What did vary per evaluation, the stdlib's `now`, timezone,
* permission binding and option labels, is read from {@link activeBinding}.
*/
let evaluationEnv: Environment | undefined;
/**
* Programs parsed on {@link evaluationEnv}, keyed on the source `env.parse` was
* handed (#24536).
*
* With the environment built once, parsing and type-checking were most of what
* an evaluation still cost, and one source is evaluated once per row. A cel-js
* program is the parse-once, evaluate-many form of `env.evaluate`.
*
* ⚠️ A program is NOT free of evaluation state. cel-js keeps per-run state on
* the AST itself:
* - a comprehension (`exists`, `all`, `exists_one`, `map`, `filter`) keeps
* its iteration context on the AST (`args.iterCtx`), and `cel.bind` keeps
* its binding context there too (`bindCtx`). Each run re-parents that
* overlay to its own scope (`OverlayContext.reuse`), and every variable the
* step reads goes through that parent;
* - a function call writes its arguments' RUNTIME types into the AST's
* `argTypes` on every call, and then reads them back to pick an overload.
*
* In sequential use each of these is overwritten before it is read, so a
* cached program answers exactly as a fresh parse would. Two runs of ONE AST
* at once do not: a run re-entered from inside its own comprehension (a scope
* getter that evaluates the same source for another subject) would re-parent
* the outer run's overlay, and the outer run would read the inner run's
* `current_user` and `record`. So a program serves one run at a time
* ({@link runningPrograms}). A cached program also keeps its last
* evaluation's scope (the `RootContext` its overlays point at, and their
* `iterValue` / `accuValue`) reachable until the next evaluation of that
* source, bounded by the cache's size.
*
* The key is the source AFTER the rewrites (`rewriteTemporalEquality`,
* `rewriteNullableTernary`, the overload retry's `rewriteFaultedOperands`), so a
* rewrite that depends on the row's values is part of the key, never applied
* from another row. Nothing invalidates an entry: every entry belongs to the
* one environment, whose registrations never change after it is built. Bounded
* like `temporalRewriteCache`, oldest entry out first. A source that does
* not parse is never stored; it is reparsed, and refused, every time.
*/
const evaluationPrograms = new Map<string, ReturnType<Environment['parse']>>();
const EVALUATION_PROGRAM_CACHE_MAX = 500;
/**
* The programs with a run in progress. A run that finds its source's cached
* program here, which is a nested evaluation of the same source, parses a
* private one instead, so no AST is ever run twice at once. Runs are
* synchronous (see {@link activeBinding}), so a run is over when the program
* returns or throws.
*/
const runningPrograms = new Set<ReturnType<Environment['parse']>>();
/** Evaluate `source` on {@link evaluationEnv} through its cached program. */
function runProgram(env: Environment, source: string, scope: Record<string, unknown>): unknown {
let program = evaluationPrograms.get(source);
if (program === undefined) {
program = env.parse(source);
if (evaluationPrograms.size >= EVALUATION_PROGRAM_CACHE_MAX) {
const first = evaluationPrograms.keys().next().value;
if (first !== undefined) evaluationPrograms.delete(first);
}
evaluationPrograms.set(source, program);
} else if (runningPrograms.has(program)) {
return env.parse(source)(scope);
}
runningPrograms.add(program);
try {
return program(scope);
} finally {
runningPrograms.delete(program);
}
}
/**
* The "never faults" BASELINE: the namespace roots the strict check env
* declares, so that a `record`-scoped CEL site is never faulted for merely
* NAMING one. ⛔ It is NOT any surface's accept set — membership here is not a
* claim that a surface BINDS the root, and a root this list declares can be
* unbound, and so unresolvable, at any individual evaluation site.
*
* The PER-SURFACE verdict lives in `@objectstack/lint`, never here:
* `fieldRuleRootIssue` answers "may THIS surface reference this root?" for the
* field-level `*When` surface, against that surface's own closed set
* `FIELD_RULE_BOUND_ROOTS` (`record` / `previous` / `parent`). Ask that pair
* whenever the question names a surface. A root this list declares and that
* surface does not bind — `data` is the standing example (#17409) — is the two
* answers doing their separate jobs, ⛔ not a disagreement to repair by editing
* this list.
*
* Declared so that member access (`record.foo`) and any arithmetic/comparison on
* a root both defer to runtime — the strict env faults ONLY on an *undeclared*
* top-level identifier, i.e. a bare field reference. Generous on purpose: an
* unknown root is a missed catch, a missing root is a false positive that would
* break the build, so we err toward declaring more.
*
* ⚠️ The CEL type each env declares them AS is not uniform, and the difference is
* load-bearing rather than incidental. {@link buildScopedEnv} — the declaredness
* oracle — declares them `dyn`, because only `dyn` delivers BOTH halves of the
* sentence above; `map` delivered member access and faulted the comparison, and
* #16412 measured what that cost (see {@link firstUndeclaredReference}). The
* type-soundness envs keep them `map`: there a root is a container the check
* deliberately declines to reason through, and the typed struct on
* `record`/`previous`/`input` is what carries the field types.
*
* ## Why this list is PUBLISHED (#6713)
*
* Exported for the same reason as {@link collectCelRootIdentifiers} and
* {@link firstUndeclaredReference}: a surface that binds a CLOSED set of roots
* has to name the roots it does NOT bind, and that complement is
* `SCOPE_ROOTS` minus its own allowlist. `@objectstack/lint`'s field-level
* `*When` gate is exactly such a surface — it binds `record` / `previous` /
* `parent` and nothing else — and it used to carry a hand-written DENYLIST of
* three roots instead. A denylist structurally cannot track this list: every
* root added here (`current_user` arrived in commit e9b526597) is silently unreported at
* that surface until somebody remembers to copy it over, and #6713 measured 21
* roots sitting in that gap.
*
* Consuming the list is NOT the same as consuming {@link firstUndeclaredReference}
* and the difference is load-bearing. The strict env also declares CEL's own
* TYPE names (`int`, `string`, `bool`, `type`, `map`, …), so
* `type(record.x) == string` reports `string` as a root that "resolves" —
* legitimate CEL a declaredness oracle cannot tell apart from an unbound
* namespace. Membership of THIS list can.
*/
export const SCOPE_ROOTS = [
'record', 'previous', 'input', 'output', 'os', 'vars', 'variables',
'automation', 'context', 'args', 'item', 'env', 'user', 'step', 'result',
'trigger', 'event', 'payload', 'data', 'params', 'config', 'settings',
// UI action / predicate context (ActionEngine, renderers): the current
// record plus ambient globals exposed to `visible`/`disabled` predicates.
'ctx', 'features',
// Master-detail inline grids inject the header record as `parent` for a
// child field's `readonlyWhen`/`requiredWhen` predicate (ADR-0036, #1581).
'parent',
// Approval-node `expression` approvers (#3447 P2): the record's LIVE state
// at node entry — bound only in that evaluation site, alongside `trigger`
// (the submit-time snapshot) and `vars`. Declared here so the strict lint
// env doesn't misread `current.x` as a bare field reference.
'current',
// ADR-0068 D1's CANONICAL user root, and the last one this list was missing
// (commit e9b526597). `buildScope` mounts the same `EvalUser` object under
// `current_user` / `user` / `ctx.user` / `os.user` whenever the evaluation
// carries a user, and this package already told the rest of the platform so:
// `introspectScope` lists `current_user` among the roots it hands an author,
// and `checkRoleCatalog`'s four position-membership regexes all lead with it.
// Only this list disagreed — so the one spelling ADR-0068 calls canonical was
// the one spelling the strict env read as a BARE FIELD, while its two aliases
// (`user`, `ctx`) passed. One package, two accounts of the same root.
'current_user',
] as const;
/*
* Why widening this list is the safe direction, and where the narrow verdict
* lives instead (commit e9b526597).
*
* This list is a "never faults" BASELINE, not a per-surface contract —
* `SCOPE_ROOTS`'s own doc-comment opens by saying exactly that, and every entry
* is generous by construction. A
* surface that binds a CLOSED set of roots does not express that by hoping the
* baseline omits the others; it says so at the surface, through
* `collectCelRootIdentifiers` (that helper reads the AST and is completely
* independent of this list — see the approval-node approvers in #3447 P2, and
* `@objectstack/lint`'s field-level `*When` gate for `current_user`).
*
* That matters here because field- and section-level `visibleWhen` genuinely do
* NOT bind `current_user` (#6146, measured at both ends: `evalFieldPredicate`
* binds `record` + `previous` + `parent` and nothing else). Before commit e9b526597 that
* surface's rejection came out of this list's omission as a SIDE EFFECT, and it
* showed: the diagnostic was the generic bare-field one, so it prescribed
* "Write `record.current_user`" — a shape that binds on no layer at all. A
* verdict that belongs to one surface now reads as that surface's own rule,
* with that surface's own prescription.
*/
/**
* A `record`-scoped environment (`unlistedVariablesAreDyn: false`) for detecting
* bare field references. It reuses the real stdlib so function calls don't fault;
* only undeclared *variables* do. Built once — `parse`/`check` do not mutate it.
*/
function buildScopedEnv(knownFields: readonly string[]): Environment {
const env = new Environment({
unlistedVariablesAreDyn: false,
enableOptionalTypes: true,
limits: DEFAULT_LIMITS,
});
registerStdLib(env, () => new Date(0));
// Roots are `dyn`, NOT `map`, for exactly the reason `knownFields` are (below)
// and the doc-comment on {@link SCOPE_ROOTS} already claims: member access,
// arithmetic and comparison on a root must all defer to runtime, so that the
// ONLY thing this env faults on is an undeclared top-level identifier.
//
// `map` delivered the member half and not the other two (#16412): `map` has no
// `==` / `<` / `+` overload, so `data == 'x'` — a root, or an object field
// sharing a root's name, in an ordinary comparison — faulted `no such
// overload` HERE while compiling clean in the permissive env, where the same
// names are `dyn`. Because cel-js's checker reports exactly ONE error, that
// fault took the first slot and every undeclared reference behind it in the
// same source went unjudged: `firstUndeclaredReference` answered `null`, the
// value that also means "every reference is rooted", and four consuming rules
// published the source clean. The two environments now agree about these
// names, so the class cannot arise rather than being compensated for
// downstream.
//
// ⛔ This does NOT weaken the check: `dyn` is undeclared-identifier-neutral —
// it changes what is legal ON a declared root, never whether an UNdeclared
// name faults. The `knownFields` loop below has always relied on that.
for (const root of SCOPE_ROOTS) {
try { env.registerVariable(root, 'dyn'); } catch { /* duplicate — ignore */ }
}
// `knownFields` are declared as `dyn` so they (and member/arith/compare on
// them) never fault — only a genuinely-undeclared top-level identifier does.
// Empty for a record-scope site (any bare field is a bug); the trigger
// object's fields for a flattened flow condition (only a NON-field bare ref —
// a typo or flow variable — is then interesting).
for (const field of knownFields) {
try { env.registerVariable(field, 'dyn'); } catch { /* duplicate / reserved — ignore */ }
}
return env;
}
// Roots-only env reused for the common record-scope check (no per-call rebuild).
let recordScopeEnv: Environment | undefined;
/**
* In a `record`-scoped CEL site — a `Field.formula` or an object validation
* predicate — the evaluation scope binds only the `record`/`previous`/… *namespaces*
* (no field flattening). A bare top-level identifier like `amount` or `status`
* therefore resolves to nothing and the expression silently evaluates to `null`
* / never fires (#1928, the class behind #1927's broken formulas). Returns the
* first such bare reference, or `null`.
*
* Acts ONLY on cel-js's `Unknown variable: X` fault, so it cannot false-positive
* on arithmetic/comparison overloads — and it must NOT be applied to flow /
* automation conditions, where the record's fields ARE flattened to top-level
* and bare references are correct.
*
* ## The false-NEGATIVE side of that narrowing (#16412)
*
* The paragraph above states which error this helper cannot make. It does not
* state that it makes neither, and it does not: cel-js's checker hands back
* exactly ONE error, so when the FIRST one is of another class every undeclared
* reference behind it in the same source goes unjudged and the answer is
* `null` -- the same value that means "every reference is rooted". A `null`
* here is "nothing was reported", never "the source is clean", and a caller
* that needs the stronger reading does not get it from this helper.
*
* The masking is POSITIONAL, not name-keyed: the masked name is not the one
* that triggered the first error, so excluding the trigger's own name does not
* reach it.
*
* ⚠️ {@link celEngine.compile} is not a gate against this, so a caller that
* only reaches here on a clean compile is not protected by that gate. `compile`
* type-checks in the PERMISSIVE env ({@link CEL_ENV_OPTIONS},
* `unlistedVariablesAreDyn: true`), so a source can compile clean and still
* fault HERE.
*
* ## What is CLOSED, and what is still open (#16412)
*
* ⭐ CLOSED — the {@link SCOPE_ROOTS} class. It was by far the wider of the two
* reachable ones: a root, or an object field sharing a root's name (`data`,
* `config`, `result`, `item`, `event`, `input`, `user`, …), used as the operand
* of an operator with no `map` overload. {@link buildScopedEnv} declared those
* roots `map` while the permissive env left them `dyn`, and that DISAGREEMENT
* was the whole mechanism; the roots are now `dyn` in both, so the class cannot
* arise. Measured on this env, before → after:
*
* data == 'x' && status == 'q' null -> "status" the class, closed
* status == 'q' && data == 'x' "status" unchanged, the control
*
* ⛔ STILL OPEN — every OTHER first-error class, and the mechanism above is
* untouched for them. Two are reachable from authored input:
*
* - a CEL TYPE name (`type`, `string`, `int`, …) in that same position. CEL
* itself declares those names, so no declaration this package controls can
* move them; `type == 'grid' && status == 'q'` still answers `null`. Pinned
* per NAME by `@objectstack/lint`'s `visibility-bare-identifier` suite, while
* the masking it causes is source-wide.
* - `has()` handed a non-select argument (`has(status) && other == 'x'`), which
* faults `has() invalid argument`. `@objectstack/lint`'s
* `validate-visibility-predicates` masks `has(…)` spans at its own call site
* (#16118) and that mask stays load-bearing; no other consumer has one.
* The page/view door now REPORTS the argument itself, under
* `visibility-predicate-has-argument` (#25281); on every other surface
* `validateExpression`'s compile pass refuses it. Neither changes what this
* helper answers: a `has()` first error still masks the references behind
* it here. A select whose receiver is an index or a call (`has(a[0].b)`) is
* NOT in this class: the spec admits it, and {@link rewriteIndexedHas}
* lowers it before this check runs (#25267).
*
* ⇒ A `null` from this helper is still "nothing was reported", never "the
* source is clean". ⛔ Do not close the remaining classes by widening the regex
* onto the overload message: that false positive is precisely what the
* narrowing buys off (`type(record.x) == string` is legitimate CEL). Reporting
* past the first error needs a re-check loop over a neutralised source, or a
* checker entry that returns more than one error -- cel-js 8.0.0 has none, its
* `TypeCheckResult` carries a single `error` -- and either one changes what
* every consuming rule reports. That is a design decision, not a patch.
*/
export function firstUndeclaredReference(
source: string,
knownFields: readonly string[] = [],
): string | null {
if (typeof source !== 'string' || !source.trim()) return null;
try {
const env = knownFields.length === 0
? (recordScopeEnv ??= buildScopedEnv([]))
: buildScopedEnv(knownFields);
// #25267 — judged in the form the engine checks, so an indexed `has()`
// receiver is not a first error that masks every reference behind it.
const result = env.parse(rewriteIndexedHas(source)).check?.() as
| { valid: boolean; error?: { message?: string } }
| undefined;
if (result && result.valid === false) {
const m = /Unknown variable:\s*([A-Za-z_$][\w$]*)/.exec(result.error?.message ?? '');
if (m) return m[1];
}
} catch {
// Parse/other faults are the syntax checker's job (celEngine.compile); this
// helper only reports the undeclared-variable case.
}
return null;
}
/**
* The distinct top-level identifiers (namespace roots) a CEL expression
* references — `current.x + vars.step.y` → `['current', 'vars']`, a bare
* `amount > 100` → `['amount']`. Member names and function names are not
* identifiers and are never reported.
*
* Built for evaluation sites that expose a CLOSED set of roots (#3447 P2:
* approval-node `expression` approvers allow only `current`/`trigger`/`vars`).
* Such a site must reject any other root BEFORE evaluating: the runtime env is
* `unlistedVariablesAreDyn: true`, so an out-of-contract root (`record.x`, a
* bare field) would otherwise evaluate to `null` and silently produce an empty
* result instead of an error. Both the lint rule and the runtime pre-check
* consume this one helper so the two can never drift.
*
* Returns `{ ok: false }` with the classifier's message when the source does
* not parse — callers surface that as a config error, not an empty root set.
* The failure also carries a refusal `code` and its `params`
* (`expression-refusal.ts`), for a consumer that renders its own words
* instead of the English `error`.
*/
export function collectCelRootIdentifiers(source: string): CelRootIdentifiersResult {
if (typeof source !== 'string' || !source.trim()) {
return { ok: false, error: 'expression is empty', code: 'empty-expression', params: {} };
}
try {
// Same nullable-ternary rewrite as compile/evaluate so "what parses" agrees
// across build, lint, and runtime (#3306).
const compiled = buildEnv(() => new Date(0)).parse(rewriteNullableTernary(source));
const roots = new Set<string>();
const walk = (node: unknown): void => {
if (Array.isArray(node)) { for (const child of node) walk(child); return; }
if (!isCelNode(node)) return; // member/function-name strings, literals
if (node.op === 'id' && typeof node.args === 'string') { roots.add(node.args); return; }
// Member access: only the receiver can hold identifiers — `args[1]` is the
// member NAME, which must not be reported as a root.
if (node.op === '.' && Array.isArray(node.args)) { walk(node.args[0]); return; }
walk(node.args);
};
walk(compiled.ast);
return { ok: true, roots: [...roots] };
} catch (err) {
const classified = classifyError(err);
const detail = classified.ok === false ? classified.error.message : String(err);
return { ok: false, error: detail, code: 'cel-parse-failed', params: { detail } };
}
}
/**
* What {@link collectCelRootIdentifiers} answers: the roots, or a refusal
* whose `error` is the English reason and whose `code` / `params` say the
* same thing for a consumer that renders its own words.
*/
export type CelRootIdentifiersResult =
| { ok: true; roots: string[] }
| ({ ok: false; error: string } & ExpressionRefusal<CelRootsRefusalCode>);
/**
* A parsed CEL AST node, re-exported so a consumer can name the type this
* package already hands it without importing `@marcbachmann/cel-js` itself.
*
* The alias is not cosmetic. {@link lowerCelAst} has always *taken* a cel-js
* `ASTNode` while the type stayed unexported, so every caller that wanted to
* hold an AST had to reach past this package to the parser — which is precisely
* how a second, differently-configured parse entry gets built (#4812). Prefixed
* `Cel` to match the package's other CEL-domain public names
* (`CelFilterCompileResult`, `collectCelRootIdentifiers`, `isPushdownableCel`);
* bare `ASTNode` would be ambiguous in a package that also owns the cron and
* template dialects.
*/
export type CelAstNode = ASTNode;
/**
* The canonical parse env, shared with {@link celEngine.compile} (#24536) —
* {@link buildEnv}'s `unlistedVariablesAreDyn`, `enableOptionalTypes`,
* {@link DEFAULT_LIMITS} and stdlib — and built once because `parse` neither mutates the environment nor depends on the
* `now()` it was given (the same reasoning `recordScopeEnv` already relies on).
* The parity suite pins the equivalence against a freshly-built env, so this
* memo cannot silently drift away from `compile`.
*/
let canonicalParseEnv: Environment | undefined;
/**
* Parse a CEL source to its AST through the **canonical** front end — the one
* answer in this repo to "what parses" (#4812).
*
* Every other entry point in this package (`compile`, `evaluate`,
* {@link collectCelRootIdentifiers}) reaches the parser through the same three
* things, and so does this one:
*
* 1. {@link rewriteNullableTernary} — the #3306 `cond ? value : null` rewrite,
* so the AST a consumer analyses is the AST the runtime will execute, not
* the shape the author happened to type;
* 2. {@link DEFAULT_LIMITS} — the platform's bounds. A source over
* `maxAstNodes` / `maxDepth` / `maxListElements` does **not** parse here,
* because it does not parse anywhere else on the platform either;
* 3. the registered stdlib and `unlistedVariablesAreDyn: true` env.
*
* A consumer that built its own `new Environment(...)` instead got a different
* answer to (2) in particular — it would happily parse, and then reason about,
* a predicate `compile()` rejects outright. That is not a hypothetical: it is
* what `@objectstack/lint`'s null-guard pass did until #4812.
*
* Returns `null` — never throws — when the source is empty or does not parse,
* so a caller whose job is *not* to adjudicate syntax can skip it in one line
* and leave the verdict to the gate that owns it (`validateExpression`, which
* reports both the syntax fault and the bounds fault with a message written for
* self-correction).
*
* This is `parse` only, deliberately **not** `parse + check`: `compile()` is the
* entry that also type-checks. A caller that wants the AST of an expression
* which parses but does not type-check (a great many predicates over `dyn`
* operands) must not be denied it, and a caller that wants the type verdict
* should ask `compile()` for it. The parity suite pins both halves of that
* asymmetry so neither side drifts.
*/
export function parseCelToAst(source: string): CelAstNode | null {
const parsed = parseCelToAstWithReason(source);
return parsed.ok ? parsed.ast : null;
}
/**
* The inverse of {@link parseCelToAst}: print a CEL AST back to surface syntax.
*
* This is the lossless half of the #15811 migration. Every EVALUATED expression
* slot in the spec now composes `EvaluatedExpressionInputSchema`, so an
* `{ dialect: 'cel', ast }` envelope carrying no `source` is refused at the
* door — and the author of such an envelope needs a `source` back. For CEL the
* platform HAS a printer (cel-js `serialize`, which this package already uses
* for its own scope rewrites), so that recovery is mechanical rather than a
* re-authoring job. `cron` and `template` have no AST at all, so the question
* does not arise for them; ADR-0087's structured TODO covers every case this
* function answers `null` to.
*
* ⚠️ Lossless is claimed about MEANING, not bytes. `serialize` re-renders from
* the parse tree, so it normalises what the grammar does not distinguish —
* measured: single-quoted string literals come back double-quoted
* (`record.p == 'x'` → `record.p == "x"`), and redundant parentheses that the
* parser dropped do not come back. A caller that needs the author's original
* bytes cannot get them from an AST; a caller that needs a `source` the engine
* evaluates identically can.
*
* Returns `null` — never throws — on anything that is not a CEL AST this
* platform can round-trip, so a caller can fall back to the hand-migration path
* in one line. Three ways to earn that `null`, and the third is the one that
* matters: `serialize` refuses the value (it throws `Unknown AST operation` on
* a non-AST, which is how an opaque `ast` an author hand-wrote is caught); the
* printed text is blank; or the printed text does not parse back through
* {@link parseCelToAst} — the platform's own bounded parser, the same one every
* other entry point in this package reaches. That last check is what makes
* "lossless" a reading rather than a claim: a source this platform cannot parse
* is not a source it can evaluate, whatever the printer produced.
*/
export function printCelAst(ast: unknown): string | null {
if (ast === null || typeof ast !== 'object') return null;
let printed: unknown;
try {
printed = serialize(ast as Parameters<typeof serialize>[0]);
} catch {
return null;
}
if (typeof printed !== 'string' || printed.trim().length === 0) return null;
return parseCelToAst(printed) === null ? null : printed;
}
// ---------------------------------------------------------------------------
// The reason-carrying sister entrance (#6132)
// ---------------------------------------------------------------------------
/** A key of {@link DEFAULT_LIMITS} — the platform bounds a source can overrun. */
export type CelLimitKey = keyof typeof DEFAULT_LIMITS;
const CEL_LIMIT_KEYS = Object.keys(DEFAULT_LIMITS) as readonly CelLimitKey[];
/** How far past a {@link DEFAULT_LIMITS} bound a source actually reaches. */
export interface CelBoundsOverrun {
/**
* WHICH bound was exceeded — `maxAstNodes` / `maxDepth` / `maxListElements` / …
* `null` only if cel-js reports a limit fault this package cannot name (see
* {@link limitKeyOf}); a guessed key would send the author to shorten the
* wrong axis, so the honest answer is "we know it was a bound, not which".
*/
limit: CelLimitKey | null;
/** The platform's value for that bound, i.e. what the source had to stay under. */
limitValue: number | null;
/**
* What the source itself measures on that axis: the smallest value of
* `limits[limit]` under which it parses, every OTHER bound lifted, so the
* number is cel-js's own accounting rather than a second implementation of
* it. `null` when the measurement was capped (see {@link CEL_BOUNDS_MEASURE_CAP_FACTOR})
* or is not being taken — a bounds *refusal* never measures, because
* measuring means re-parsing a source we have just decided is too big.
*/
measured: number | null;
/**
* cel-js's own one-line summary — `Exceeded maxAstNodes (256)`. Taken from
* `ParseError#summary`, NOT `#message`: the latter is
* `formatErrorWithHighlight`'s rendering, which interpolates the author's own
* source line (the #6223 hazard).
*/
summary: string;
}
/**
* The verdict {@link parseCelToAstWithReason} returns — the same three-way
* answer {@link classifyCelFault} already grades a thrown fault into, made
* available to a caller that has to ACT differently on `bounds` than on
* `parse`, rather than collapsing both to `null`.
*/
export type CelParseResult =
| { ok: true; ast: CelAstNode }
/** Empty / whitespace-only source. Not a fault — "no expression". */
| { ok: false; kind: 'empty'; message: string }
/** A syntax fault. `message` is cel-js's rendered message, verbatim. */
| { ok: false; kind: 'parse'; message: string }
| {
ok: false;
kind: 'bounds';
/** cel-js's rendered message, verbatim — same string `parse` carries. */
message: string;
/** WHICH bound, and by how much. */
overrun: CelBoundsOverrun;
/**
* The AST an otherwise-identical but **unbounded** parse yields, when the
* caller asked for it (`{ admitOverLimit: true }`) — the 17.0.0-rc.x
* grace window's input, and nothing else's. `null` otherwise.
*/
unboundedAst: CelAstNode | null;
};
export interface ParseCelToAstOptions {
/**
* Also perform the unbounded parse and hand back its AST + the measured
* overrun. **Only** the 17.0.0-rc.x pushdown grace window sets this (see
* `cel-pushdown-limits.ts`); it is what lets that window keep compiling a
* predicate the platform's bounds refuse, while still naming the bound. It
* disappears with the grace window at v17 GA.
*
* Off by default, deliberately: an unbounded parse of a source we have just
* measured as over-budget is work proportional to the source, so a caller
* that only wants the verdict must not pay for it.
*/
admitOverLimit?: boolean;
}
/**
* How far above the exceeded bound {@link measureOverrun} will search before it
* gives up and reports `measured: null`. Bounds the diagnostic's own cost:
* without a cap, describing a pathological source means parsing it at whatever
* size it happens to be.
*/
export const CEL_BOUNDS_MEASURE_CAP_FACTOR = 64;
/**
* The canonical env with ONE bound lifted, used only to measure an overrun.
* Configured identically to {@link canonicalParseEnv} in every other respect —
* same stdlib, same `unlistedVariablesAreDyn`, same `enableOptionalTypes` — so
* "the smallest bound this source parses under" is a fact about the source and
* not about a second, differently-shaped front end.
*/
function buildProbeEnv(limits: Record<string, number>): Environment {
const env = new Environment({
unlistedVariablesAreDyn: true,
enableOptionalTypes: true,
limits: limits as unknown as typeof DEFAULT_LIMITS,
});
return registerNumericCoercions(registerStdLib(env, () => new Date(0), 'UTC'));
}
/** Every bound lifted out of the way except `key`, which is set to `value`. */
function probeLimits(key: CelLimitKey, value: number): Record<string, number> {
const limits: Record<string, number> = {};
for (const k of CEL_LIMIT_KEYS) limits[k] = Number.MAX_SAFE_INTEGER;
limits[key] = value;
return limits;
}
function parsesUnder(source: string, key: CelLimitKey, value: number): boolean {
try {
buildProbeEnv(probeLimits(key, value)).parse(source);
return true;
} catch {
return false;
}
}
/**
* The smallest `limits[key]` under which `source` parses — i.e. what the source
* measures on that axis, in cel-js's own units.
*
* Measured rather than computed. cel-js decrements each counter at its own call
* sites (`Parser#node` for `maxAstNodes`, three separate recursion points for
* `maxDepth`, …), and `maxDepth` in particular counts parenthesised recursion
* that leaves no AST node behind — so a node-walk over the parsed tree would
* report `3` for a 60-deep parenthesis nest. Asking the parser is the only way
* the number in the WARN means what it says.
*
* Exponential probe from the exceeded bound, then binary search: `O(log n)`
* parses, capped at {@link CEL_BOUNDS_MEASURE_CAP_FACTOR}× the bound.
*/
function measureOverrun(source: string, key: CelLimitKey, limitValue: number): number | null {
const cap = limitValue * CEL_BOUNDS_MEASURE_CAP_FACTOR;
let hi = limitValue * 2;
while (hi <= cap && !parsesUnder(source, key, hi)) hi *= 2;
if (hi > cap) return null;
// It parses at `hi` and (by construction) not at `lo`. Narrow to the boundary.
let lo = hi / 2;
while (hi - lo > 1) {
const mid = Math.floor((lo + hi) / 2);
if (parsesUnder(source, key, mid)) hi = mid;
else lo = mid;
}
return hi;
}
/** Read the exceeded bound's key out of cel-js's structured limit fault. */
function limitKeyOf(err: ParseError): CelLimitKey | null {
// `summary` is `Exceeded ${limitKey} (${limit})`, built by `Parser#limitExceeded`
// from a fixed set of keys — the author's source never reaches it (that is
// `message`, via `formatErrorWithHighlight`). We still validate the capture
// against `DEFAULT_LIMITS` rather than trusting the shape, so a cel-js that
// rephrases the sentence degrades to "we know it was a bounds fault, not which
// bound" instead of inventing a limit name.
const key = /^Exceeded (\w+) /.exec(err.summary ?? '')?.[1];
return key && (CEL_LIMIT_KEYS as readonly string[]).includes(key) ? (key as CelLimitKey) : null;
}
/**
* {@link parseCelToAst}, but it says WHY it refused (#6132).
*
* `parseCelToAst` collapses "this is not valid CEL" and "this is valid CEL that
* is over the platform's budget" into the same `null`, which is right for a
* caller whose job is not to adjudicate syntax. It is wrong for a caller whose
* job is to *report* the refusal: the RLS / sharing pushdown path fails closed
* on a refusal, and "your policy was rejected: parse error" for a predicate
* that is perfectly well-formed but 431 AST nodes long sends the author
* hunting for a typo that does not exist. This entrance names the bound
* (`maxAstNodes` / `maxDepth` / `maxListElements` / …), the platform's value
* for it, and what their source actually measures.
*
* The verdict is graded by the SAME {@link classifyCelFault} the engine's
* `compile` / `evaluate` use — error class plus structured `code`, never prose
* (#6223). A `bounds` verdict here and a `bounds` verdict from
* `celEngine.compile()` are therefore the same judgement of the same fault,
* which is the property `cel-parse-reason.test.ts` pins.
*/
export function parseCelToAstWithReason(
source: string,
opts: ParseCelToAstOptions = {},
): CelParseResult {
if (typeof source !== 'string' || !source.trim()) {
return { ok: false, kind: 'empty', message: 'empty expression' };
}
// The #3306 rewrite is part of the canonical front end, so it happens before
// the parse whose verdict we are reporting — and the measurement below probes
// the SAME rewritten source, so the number describes what actually parsed.
const rewritten = rewriteNullableTernary(source);
try {
// A wall-clock-free `now()` — the stdlib is registered for parse-time shape
// only and is never called on this path.
canonicalParseEnv ??= buildEnv(() => new Date(0));
return { ok: true, ast: canonicalParseEnv.parse(rewritten).ast };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (classifyCelFault(err) !== 'bounds') return { ok: false, kind: 'parse', message };
const parseErr = err as ParseError;
const limit = limitKeyOf(parseErr);
const summary = parseErr.summary ?? message.split('\n')[0];
if (!limit) {
// A bounds fault we cannot NAME — unreachable on cel-js 8.0.0, where
// `Parser#limitExceeded` always phrases it `Exceeded <key> (<n>)`, but a
// rephrasing upstream has to degrade honestly. Still reported as `bounds`
// (the class is not in doubt) and never as a syntax fault, which is the
// exact mislabel this entrance exists to stop — but with `limit: null`
// rather than a guessed key, and with no AST to admit, so the pushdown
// path fails closed on it in either position of the switch.
return {
ok: false,
kind: 'bounds',
message,
overrun: { limit: null, limitValue: null, measured: null, summary },
unboundedAst: null,
};
}
const limitValue = DEFAULT_LIMITS[limit];
let unboundedAst: CelAstNode | null = null;
let measured: number | null = null;
if (opts.admitOverLimit) {
try {
unboundedAst = buildProbeEnv(probeLimits(limit, Number.MAX_SAFE_INTEGER)).parse(rewritten).ast;
measured = measureOverrun(rewritten, limit, limitValue);
} catch {
// Unbounded still refuses ⇒ a second, non-`limit` bound or a fault the
// bounded parse never got far enough to raise. No AST to admit.
unboundedAst = null;
}
}
return { ok: false, kind: 'bounds', message, overrun: { limit, limitValue, measured, summary }, unboundedAst };
}
}
/**
* The result type cel-js's type-checker infers for a `value`/`predicate`
* expression — its raw CEL type name (`'int'`, `'double'`, `'string'`, `'bool'`,
* `'google.protobuf.Timestamp'`, `'dyn'`, …) — or `null` when the expression does
* not type-check. Reuses the SAME record-scoped, stdlib-registered env as
* {@link firstUndeclaredReference}: namespace roots (`record`, `previous`, …) and
* `knownFields` are both declared `dyn`, so both `record.<field>` and bare
* `<field>` references resolve while every stdlib call carries its declared
* return type.
*
* Deliberately conservative. A member access (`record.amount`) or a bare field is
* `dyn`, and an operator over two `dyn` operands stays `dyn` (cel-js cannot prove
* it numeric), so `record.a + record.b` — which could be string concatenation —
* infers `dyn`, not a number. A typed literal or a stdlib return DOES pin the
* type, so the common computed-number formulas resolve concretely:
* `daysBetween(start_date, end_date) + 1` → `int`, `amount * 0.1` → `double`. A
* caller keying off a concrete numeric type therefore never mis-classifies an
* ambiguous formula.
*/
export function inferCelType(source: string, knownFields: readonly string[] = []): string | null {
if (typeof source !== 'string' || !source.trim()) return null;
try {
const env = knownFields.length === 0
? (recordScopeEnv ??= buildScopedEnv([]))
: buildScopedEnv(knownFields);
// #25267 — typed in the form the engine checks (an indexed `has()` is `bool`).
const result = env.parse(rewriteIndexedHas(source)).check?.() as
| { valid?: boolean; type?: unknown }
| undefined;
if (!result || result.valid === false) return null;
return typeof result.type === 'string' ? result.type : null;
} catch {
// Parse/other faults mean we cannot prove a type — the conservative `null`.
return null;
}
}
/** @deprecated use {@link firstUndeclaredReference} with no fields. */
export function detectBareReference(source: string): string | null {
return firstUndeclaredReference(source);
}
/**
* The CEL type a field is declared as for the Tier-4 type-soundness check
* (#1928). Deliberately coarse: only genuinely-scalar fields whose *misuse
* always faults the runtime* are pinned to a concrete type; everything the
* runtime rescues stays `dyn` and can therefore never fault.
* - `string`/`bool` — text/boolean fields; arithmetic/ordering against a number
* faults (unless a text value happens to be numeric) → advisory warning.
* - `timestamp` — `date`/`datetime` fields; ARITHMETIC against a number always
* nulls at runtime (`date − date + 1`, `today() + 30`, #3306) → hard error.
* Ordering/equality/concatenation of a date field is runtime-tolerated and
* is never flagged (see {@link firstTypeMismatch}).
* See {@link firstTypeMismatch}.
*/
export type FieldCelType = 'string' | 'bool' | 'timestamp' | 'dyn';
/** The cel-js type name a {@link FieldCelType} declares in a typed env. */
function celTypeName(t: FieldCelType): string {
return t === 'timestamp' ? 'google.protobuf.Timestamp' : t;
}
/** CEL types produced by date subtraction / temporal fns — arith on these nulls. */
const DATE_CEL_TYPES = new Set(['google.protobuf.Timestamp', 'google.protobuf.Duration']);
/** Numeric CEL types — the RHS that turns date arithmetic into a runtime fault. */
const NUMERIC_CEL_TYPES = new Set(['int', 'uint', 'double']);
/** Arithmetic operators (excludes ordering `< > <= >=`, which dates tolerate). */
const ARITH_OPS = new Set(['+', '-', '*', '/', '%']);
/** Concrete types the soundness env pins — each needs a `== null` overload below. */
const NULL_GUARD_TYPES = ['string', 'bool', 'google.protobuf.Timestamp', 'google.protobuf.Duration'];
/**
* cel-js has no `<scalar/message> == null` overload, so a `record.<field> != null`
* guard faults the typed check for any pinned field — and because `check()` reports
* only its FIRST error, that fault MASKS a real arithmetic fault later in the same
* expression (the ubiquitous `guard ? <date arith> : null` shape, #3306). Register
* no-op `== null` overloads (this env is check-only, never evaluated; `!=` desugars
* to `==`) so the guard type-checks and the real fault surfaces. `==`/`!=` are never
* flagged themselves ({@link UNSOUND_OVERLOAD_RE} excludes them), so this only
* unmasks — it can never introduce a false positive.
*/
function registerNullComparisons(env: Environment): void {
for (const t of NULL_GUARD_TYPES) {
try { env.registerOperator(`${t} == null`, () => false); } catch { /* already/invalid — ignore */ }
try { env.registerOperator(`null == ${t}`, () => false); } catch { /* already/invalid — ignore */ }
}
}
/**
* A `no such overload` fault for an ARITHMETIC (`+ - * / %`) or ORDERING
* (`< > <= >=`) operator, with the two operand types captured. Equality
* (`==` / `!=`) is intentionally excluded: cel-js's checker faults on a
* heterogeneous equality (`string == int`) but the runtime evaluates it
* cleanly to `false` — so a fault there is NOT a runtime failure and must not
* warn. Linear (no nested quantifiers) — no ReDoS. Operand types are `[\w.]+`
* (e.g. `string`, `int`, `google.protobuf.Timestamp`); the operator token is
* punctuation, so the two never overlap.
*/
const UNSOUND_OVERLOAD_RE = /no such overload:\s*([\w.]+)\s*(<=|>=|<|>|\+|-|\*|\/|%)\s*([\w.]+)/;
/**
* A typed environment for the soundness check. Each field carries a concrete
* CEL type (`string`/`bool`) or `dyn`, so cel-js's checker faults an
* arithmetic/ordering operator applied across incompatible types. The `scope`
* mirrors how the authoring site binds fields:
* - `'record'` → `record.<field>` member access, via a typed struct on the
* `record`/`previous`/`input` namespaces (formula fields,
* validations, action/hook/sharing predicates).
* - `'flattened'` → bare `<field>` top-level variables (flow / automation
* conditions). Unlisted identifiers stay `dyn`
* (`unlistedVariablesAreDyn: true`) so a flow variable never
* faults — only a typed field misused does.
* Built per call — cheap, and only used at build time.
*/
function buildTypedEnv(
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
scope: 'record' | 'flattened',
temporalAsText = false,
/**
* [#29959] Flattened scope only: the field types to type `record.<field>` /
* `previous.<field>` with. Absent, those roots stay `map` (dyn members). It
* is a map of its own, not `fieldCelTypes`, because a bare name a flow
* variable holds is left out of the bare typing while `record.<name>` still
* reads the field.
*/
recordRootTypes?: Readonly<Record<string, FieldCelType>>,
): Environment {
// `temporalAsText` declares a `date`/`datetime` field as the text the runtime
// holds ({@link DATE_TEXT_CEL_TYPE}) instead of a Timestamp — see
// {@link firstDateTextVerdict}.
const typeName = (t: FieldCelType): string =>
temporalAsText && t === 'timestamp' ? DATE_TEXT_CEL_TYPE : celTypeName(t);
if (scope === 'flattened') {
const env = new Environment({
unlistedVariablesAreDyn: true,
enableOptionalTypes: true,
limits: DEFAULT_LIMITS,
});
registerStdLib(env, () => new Date(0));
registerNullComparisons(env);
if (temporalAsText) registerDateTextOverloads(env);
if (recordRootTypes) {
// [#29959] A flow run binds the record it was handed as `record` too
// (`seedRunVariables`), beside the flattened bare names, so
// `record.<field>` is the same value as the bare `<field>` and is typed
// the same: the `record`-scope struct, on `record` and `previous`.
const fields: Record<string, string> = {};
for (const [name, t] of Object.entries(recordRootTypes)) fields[name] = typeName(t);
try { env.registerType('OsRecordScope', { fields }); } catch { /* invalid field name — ignore */ }
for (const root of ['record', 'previous']) {