@naylence/advanced-security 0.3.15 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/LICENSE +1 -1
  2. package/dist/browser/index.cjs +2673 -3
  3. package/dist/browser/index.mjs +2684 -14
  4. package/dist/cjs/advanced-security-isomorphic.js +4 -0
  5. package/dist/cjs/advanced-security-isomorphic.js.map +1 -1
  6. package/dist/cjs/naylence/fame/expr/ast.js +135 -0
  7. package/dist/cjs/naylence/fame/expr/ast.js.map +1 -0
  8. package/dist/cjs/naylence/fame/expr/builtins.js +477 -0
  9. package/dist/cjs/naylence/fame/expr/builtins.js.map +1 -0
  10. package/dist/cjs/naylence/fame/expr/errors.js +88 -0
  11. package/dist/cjs/naylence/fame/expr/errors.js.map +1 -0
  12. package/dist/cjs/naylence/fame/expr/evaluator.js +385 -0
  13. package/dist/cjs/naylence/fame/expr/evaluator.js.map +1 -0
  14. package/dist/cjs/naylence/fame/expr/index.js +21 -0
  15. package/dist/cjs/naylence/fame/expr/index.js.map +1 -0
  16. package/dist/cjs/naylence/fame/expr/limits.js +80 -0
  17. package/dist/cjs/naylence/fame/expr/limits.js.map +1 -0
  18. package/dist/cjs/naylence/fame/expr/parser.js +429 -0
  19. package/dist/cjs/naylence/fame/expr/parser.js.map +1 -0
  20. package/dist/cjs/naylence/fame/expr/tokenizer.js +336 -0
  21. package/dist/cjs/naylence/fame/expr/tokenizer.js.map +1 -0
  22. package/dist/cjs/naylence/fame/factory-manifest.js +2 -0
  23. package/dist/cjs/naylence/fame/factory-manifest.js.map +1 -1
  24. package/dist/cjs/naylence/fame/security/auth/index.js +7 -0
  25. package/dist/cjs/naylence/fame/security/auth/index.js.map +1 -0
  26. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.js +70 -0
  27. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.js.map +1 -0
  28. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy.js +562 -0
  29. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy.js.map +1 -0
  30. package/dist/cjs/naylence/fame/security/auth/policy/expr-builtins.js +129 -0
  31. package/dist/cjs/naylence/fame/security/auth/policy/expr-builtins.js.map +1 -0
  32. package/dist/cjs/naylence/fame/security/auth/policy/index.js +15 -0
  33. package/dist/cjs/naylence/fame/security/auth/policy/index.js.map +1 -0
  34. package/dist/cjs/naylence/fame/security/index.js +2 -0
  35. package/dist/cjs/naylence/fame/security/index.js.map +1 -1
  36. package/dist/cjs/naylence/fame/security/register-advanced-security-factories.js +2 -0
  37. package/dist/cjs/naylence/fame/security/register-advanced-security-factories.js.map +1 -1
  38. package/dist/cjs/naylence/fame/security/strict-overlay-security-profile.js +64 -0
  39. package/dist/cjs/naylence/fame/security/strict-overlay-security-profile.js.map +1 -0
  40. package/dist/cjs/package.json +3 -0
  41. package/dist/cjs/plugin.js +2 -0
  42. package/dist/cjs/plugin.js.map +1 -1
  43. package/dist/cjs/version.js +2 -2
  44. package/dist/cjs/version.js.map +1 -1
  45. package/dist/esm/advanced-security-isomorphic.js +4 -0
  46. package/dist/esm/advanced-security-isomorphic.js.map +1 -1
  47. package/dist/esm/naylence/fame/expr/ast.js +135 -0
  48. package/dist/esm/naylence/fame/expr/ast.js.map +1 -0
  49. package/dist/esm/naylence/fame/expr/builtins.js +477 -0
  50. package/dist/esm/naylence/fame/expr/builtins.js.map +1 -0
  51. package/dist/esm/naylence/fame/expr/errors.js +88 -0
  52. package/dist/esm/naylence/fame/expr/errors.js.map +1 -0
  53. package/dist/esm/naylence/fame/expr/evaluator.js +385 -0
  54. package/dist/esm/naylence/fame/expr/evaluator.js.map +1 -0
  55. package/dist/esm/naylence/fame/expr/index.js +21 -0
  56. package/dist/esm/naylence/fame/expr/index.js.map +1 -0
  57. package/dist/esm/naylence/fame/expr/limits.js +80 -0
  58. package/dist/esm/naylence/fame/expr/limits.js.map +1 -0
  59. package/dist/esm/naylence/fame/expr/parser.js +429 -0
  60. package/dist/esm/naylence/fame/expr/parser.js.map +1 -0
  61. package/dist/esm/naylence/fame/expr/tokenizer.js +336 -0
  62. package/dist/esm/naylence/fame/expr/tokenizer.js.map +1 -0
  63. package/dist/esm/naylence/fame/factory-manifest.js +2 -0
  64. package/dist/esm/naylence/fame/factory-manifest.js.map +1 -1
  65. package/dist/esm/naylence/fame/security/auth/index.js +7 -0
  66. package/dist/esm/naylence/fame/security/auth/index.js.map +1 -0
  67. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.js +70 -0
  68. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.js.map +1 -0
  69. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy.js +562 -0
  70. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy.js.map +1 -0
  71. package/dist/esm/naylence/fame/security/auth/policy/expr-builtins.js +129 -0
  72. package/dist/esm/naylence/fame/security/auth/policy/expr-builtins.js.map +1 -0
  73. package/dist/esm/naylence/fame/security/auth/policy/index.js +15 -0
  74. package/dist/esm/naylence/fame/security/auth/policy/index.js.map +1 -0
  75. package/dist/esm/naylence/fame/security/index.js +2 -0
  76. package/dist/esm/naylence/fame/security/index.js.map +1 -1
  77. package/dist/esm/naylence/fame/security/register-advanced-security-factories.js +2 -0
  78. package/dist/esm/naylence/fame/security/register-advanced-security-factories.js.map +1 -1
  79. package/dist/esm/naylence/fame/security/strict-overlay-security-profile.js +64 -0
  80. package/dist/esm/naylence/fame/security/strict-overlay-security-profile.js.map +1 -0
  81. package/dist/esm/package.json +3 -0
  82. package/dist/esm/plugin.js +2 -0
  83. package/dist/esm/plugin.js.map +1 -1
  84. package/dist/esm/version.js +2 -2
  85. package/dist/esm/version.js.map +1 -1
  86. package/dist/node/index.cjs +2795 -6
  87. package/dist/node/index.mjs +2770 -15
  88. package/dist/node/node.cjs +2819 -3
  89. package/dist/node/node.mjs +2796 -15
  90. package/dist/types/advanced-security-isomorphic.d.ts +2 -0
  91. package/dist/types/advanced-security-isomorphic.d.ts.map +1 -1
  92. package/dist/types/naylence/fame/expr/ast.d.ts +85 -0
  93. package/dist/types/naylence/fame/expr/ast.d.ts.map +1 -0
  94. package/dist/types/naylence/fame/expr/builtins.d.ts +79 -0
  95. package/dist/types/naylence/fame/expr/builtins.d.ts.map +1 -0
  96. package/dist/types/naylence/fame/expr/errors.d.ts +61 -0
  97. package/dist/types/naylence/fame/expr/errors.d.ts.map +1 -0
  98. package/dist/types/naylence/fame/expr/evaluator.d.ts +90 -0
  99. package/dist/types/naylence/fame/expr/evaluator.d.ts.map +1 -0
  100. package/dist/types/naylence/fame/expr/index.d.ts +16 -0
  101. package/dist/types/naylence/fame/expr/index.d.ts.map +1 -0
  102. package/dist/types/naylence/fame/expr/limits.d.ts +65 -0
  103. package/dist/types/naylence/fame/expr/limits.d.ts.map +1 -0
  104. package/dist/types/naylence/fame/expr/parser.d.ts +102 -0
  105. package/dist/types/naylence/fame/expr/parser.d.ts.map +1 -0
  106. package/dist/types/naylence/fame/expr/tokenizer.d.ts +51 -0
  107. package/dist/types/naylence/fame/expr/tokenizer.d.ts.map +1 -0
  108. package/dist/types/naylence/fame/factory-manifest.d.ts +1 -1
  109. package/dist/types/naylence/fame/factory-manifest.d.ts.map +1 -1
  110. package/dist/types/naylence/fame/security/auth/index.d.ts +7 -0
  111. package/dist/types/naylence/fame/security/auth/index.d.ts.map +1 -0
  112. package/dist/types/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.d.ts +47 -0
  113. package/dist/types/naylence/fame/security/auth/policy/advanced-authorization-policy-factory.d.ts.map +1 -0
  114. package/dist/types/naylence/fame/security/auth/policy/advanced-authorization-policy.d.ts +73 -0
  115. package/dist/types/naylence/fame/security/auth/policy/advanced-authorization-policy.d.ts.map +1 -0
  116. package/dist/types/naylence/fame/security/auth/policy/expr-builtins.d.ts +14 -0
  117. package/dist/types/naylence/fame/security/auth/policy/expr-builtins.d.ts.map +1 -0
  118. package/dist/types/naylence/fame/security/auth/policy/index.d.ts +12 -0
  119. package/dist/types/naylence/fame/security/auth/policy/index.d.ts.map +1 -0
  120. package/dist/types/naylence/fame/security/index.d.ts +2 -0
  121. package/dist/types/naylence/fame/security/index.d.ts.map +1 -1
  122. package/dist/types/naylence/fame/security/register-advanced-security-factories.d.ts +1 -0
  123. package/dist/types/naylence/fame/security/register-advanced-security-factories.d.ts.map +1 -1
  124. package/dist/types/naylence/fame/security/strict-overlay-security-profile.d.ts +11 -0
  125. package/dist/types/naylence/fame/security/strict-overlay-security-profile.d.ts.map +1 -0
  126. package/dist/types/plugin.d.ts.map +1 -1
  127. package/dist/types/version.d.ts +1 -1
  128. package/dist/types/version.d.ts.map +1 -1
  129. package/package.json +5 -4
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ var factory = require('@naylence/factory');
3
4
  var runtime = require('@naylence/runtime');
4
5
  var asn1Schema = require('@peculiar/asn1-schema');
5
6
  var asn1Csr = require('@peculiar/asn1-csr');
@@ -7,22 +8,2703 @@ var asn1X509 = require('@peculiar/asn1-x509');
7
8
  var ed25519 = require('@noble/ed25519');
8
9
  var sha2_js = require('@noble/hashes/sha2.js');
9
10
  var core = require('@naylence/core');
11
+ var sha256 = require('@noble/hashes/sha256');
10
12
  var chacha_js = require('@noble/ciphers/chacha.js');
11
13
  var ed25519_js = require('@noble/curves/ed25519.js');
12
14
  var hkdf_js = require('@noble/hashes/hkdf.js');
13
15
  var utils_js = require('@noble/hashes/utils.js');
14
16
  var jose = require('jose');
15
- var factory = require('@naylence/factory');
16
17
  var sha256_js = require('@noble/hashes/sha256.js');
17
18
  var x509 = require('@peculiar/x509');
18
19
 
19
- // This file is auto-generated during build - do not edit manually
20
- // Generated from package.json version: 0.3.15
20
+ // This file is auto-generated during build - do not edit manually
21
+ // Generated from package.json version: 0.4.1
22
+ /**
23
+ * The package version, injected at build time.
24
+ * @internal
25
+ */
26
+ const VERSION = '0.4.1';
27
+
28
+ /**
29
+ * Abstract Syntax Tree (AST) node types for the expression language.
30
+ *
31
+ * The AST is produced by the parser and consumed by the evaluator.
32
+ */
33
+ // ============================================================
34
+ // AST Utilities
35
+ // ============================================================
36
+ /**
37
+ * Counts the total number of nodes in an AST.
38
+ */
39
+ function countAstNodes(node) {
40
+ let count = 1;
41
+ switch (node.type) {
42
+ case "StringLiteral":
43
+ case "NumberLiteral":
44
+ case "BooleanLiteral":
45
+ case "NullLiteral":
46
+ case "Identifier":
47
+ return count;
48
+ case "ArrayLiteral":
49
+ for (const element of node.elements) {
50
+ count += countAstNodes(element);
51
+ }
52
+ return count;
53
+ case "MemberAccess":
54
+ return count + countAstNodes(node.object);
55
+ case "IndexAccess":
56
+ return count + countAstNodes(node.object) + countAstNodes(node.index);
57
+ case "FunctionCall":
58
+ for (const arg of node.args) {
59
+ count += countAstNodes(arg);
60
+ }
61
+ return count;
62
+ case "UnaryOp":
63
+ return count + countAstNodes(node.operand);
64
+ case "BinaryOp":
65
+ return count + countAstNodes(node.left) + countAstNodes(node.right);
66
+ case "TernaryOp":
67
+ return (count +
68
+ countAstNodes(node.condition) +
69
+ countAstNodes(node.consequent) +
70
+ countAstNodes(node.alternate));
71
+ }
72
+ }
73
+ /**
74
+ * Calculates the maximum depth of an AST.
75
+ */
76
+ function calculateAstDepth(node) {
77
+ switch (node.type) {
78
+ case "StringLiteral":
79
+ case "NumberLiteral":
80
+ case "BooleanLiteral":
81
+ case "NullLiteral":
82
+ case "Identifier":
83
+ return 1;
84
+ case "ArrayLiteral": {
85
+ let maxChildDepth = 0;
86
+ for (const element of node.elements) {
87
+ maxChildDepth = Math.max(maxChildDepth, calculateAstDepth(element));
88
+ }
89
+ return 1 + maxChildDepth;
90
+ }
91
+ case "MemberAccess":
92
+ return 1 + calculateAstDepth(node.object);
93
+ case "IndexAccess":
94
+ return (1 +
95
+ Math.max(calculateAstDepth(node.object), calculateAstDepth(node.index)));
96
+ case "FunctionCall": {
97
+ let maxArgDepth = 0;
98
+ for (const arg of node.args) {
99
+ maxArgDepth = Math.max(maxArgDepth, calculateAstDepth(arg));
100
+ }
101
+ return 1 + maxArgDepth;
102
+ }
103
+ case "UnaryOp":
104
+ return 1 + calculateAstDepth(node.operand);
105
+ case "BinaryOp":
106
+ return (1 +
107
+ Math.max(calculateAstDepth(node.left), calculateAstDepth(node.right)));
108
+ case "TernaryOp":
109
+ return (1 +
110
+ Math.max(calculateAstDepth(node.condition), calculateAstDepth(node.consequent), calculateAstDepth(node.alternate)));
111
+ }
112
+ }
113
+ /**
114
+ * Returns a human-readable representation of an AST node for debugging.
115
+ */
116
+ function astToString(node, indent = 0) {
117
+ const prefix = " ".repeat(indent);
118
+ switch (node.type) {
119
+ case "StringLiteral":
120
+ return `${prefix}String: "${node.value}"`;
121
+ case "NumberLiteral":
122
+ return `${prefix}Number: ${node.value}`;
123
+ case "BooleanLiteral":
124
+ return `${prefix}Boolean: ${node.value}`;
125
+ case "NullLiteral":
126
+ return `${prefix}Null`;
127
+ case "ArrayLiteral":
128
+ return (`${prefix}Array:\n` +
129
+ node.elements.map((e) => astToString(e, indent + 1)).join("\n"));
130
+ case "Identifier":
131
+ return `${prefix}Identifier: ${node.name}`;
132
+ case "MemberAccess":
133
+ return (`${prefix}MemberAccess: .${node.property}\n` +
134
+ astToString(node.object, indent + 1));
135
+ case "IndexAccess":
136
+ return (`${prefix}IndexAccess:\n` +
137
+ `${prefix} object:\n` +
138
+ astToString(node.object, indent + 2) +
139
+ `\n${prefix} index:\n` +
140
+ astToString(node.index, indent + 2));
141
+ case "FunctionCall":
142
+ return (`${prefix}FunctionCall: ${node.name}\n` +
143
+ node.args.map((a) => astToString(a, indent + 1)).join("\n"));
144
+ case "UnaryOp":
145
+ return (`${prefix}UnaryOp: ${node.operator}\n` +
146
+ astToString(node.operand, indent + 1));
147
+ case "BinaryOp":
148
+ return (`${prefix}BinaryOp: ${node.operator}\n` +
149
+ astToString(node.left, indent + 1) +
150
+ "\n" +
151
+ astToString(node.right, indent + 1));
152
+ case "TernaryOp":
153
+ return (`${prefix}TernaryOp:\n` +
154
+ `${prefix} condition:\n` +
155
+ astToString(node.condition, indent + 2) +
156
+ `\n${prefix} consequent:\n` +
157
+ astToString(node.consequent, indent + 2) +
158
+ `\n${prefix} alternate:\n` +
159
+ astToString(node.alternate, indent + 2));
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Error types for the expression evaluation engine.
165
+ *
166
+ * All expression errors extend ExpressionError for consistent handling.
167
+ */
168
+ /**
169
+ * Base error class for all expression-related errors.
170
+ */
171
+ class ExpressionError extends Error {
172
+ constructor(message, position, expression) {
173
+ super(message);
174
+ this.name = "ExpressionError";
175
+ this.position = position;
176
+ this.expression = expression;
177
+ }
178
+ /**
179
+ * Returns a formatted error message with position context.
180
+ */
181
+ formatWithContext() {
182
+ if (this.expression === undefined || this.position === undefined) {
183
+ return this.message;
184
+ }
185
+ const pointer = " ".repeat(this.position) + "^";
186
+ return `${this.message}\n ${this.expression}\n ${pointer}`;
187
+ }
188
+ }
189
+ /**
190
+ * Error thrown during tokenization (lexical analysis).
191
+ */
192
+ class TokenizerError extends ExpressionError {
193
+ constructor(message, position, expression) {
194
+ super(message, position, expression);
195
+ this.name = "TokenizerError";
196
+ }
197
+ }
198
+ /**
199
+ * Error thrown during parsing (syntax analysis).
200
+ */
201
+ class ParseError extends ExpressionError {
202
+ constructor(message, position, expression) {
203
+ super(message, position, expression);
204
+ this.name = "ParseError";
205
+ }
206
+ }
207
+ /**
208
+ * Error thrown during evaluation (runtime error).
209
+ */
210
+ class EvaluationError extends ExpressionError {
211
+ constructor(message, position, expression, path) {
212
+ super(message, position, expression);
213
+ this.name = "EvaluationError";
214
+ this.path = path;
215
+ }
216
+ }
217
+ /**
218
+ * Error thrown for type mismatches during evaluation.
219
+ */
220
+ class TypeError extends EvaluationError {
221
+ constructor(expected, actual, position, expression) {
222
+ super(`Type error: expected ${expected}, got ${actual}`, position, expression);
223
+ this.name = "TypeError";
224
+ this.expected = expected;
225
+ this.actual = actual;
226
+ }
227
+ }
228
+ /**
229
+ * Error thrown when expression limits are exceeded.
230
+ */
231
+ class LimitExceededError extends ExpressionError {
232
+ constructor(limitName, limit, actual) {
233
+ super(`Limit exceeded: ${limitName} (limit: ${limit}, actual: ${actual})`);
234
+ this.name = "LimitExceededError";
235
+ this.limitName = limitName;
236
+ this.limit = limit;
237
+ this.actual = actual;
238
+ }
239
+ }
240
+ /**
241
+ * Error thrown when a built-in function encounters an error.
242
+ */
243
+ class BuiltinError extends EvaluationError {
244
+ constructor(functionName, message, position, expression) {
245
+ super(`${functionName}: ${message}`, position, expression);
246
+ this.name = "BuiltinError";
247
+ this.functionName = functionName;
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Resource limits for expression parsing and evaluation.
253
+ *
254
+ * These limits protect against resource exhaustion attacks and
255
+ * overly complex expressions.
256
+ */
257
+ /**
258
+ * Default expression limits.
259
+ *
260
+ * These values are chosen to allow reasonable expressions while
261
+ * preventing resource exhaustion.
262
+ */
263
+ const DEFAULT_EXPRESSION_LIMITS = {
264
+ maxExpressionLength: 4096,
265
+ maxAstDepth: 32,
266
+ maxAstNodes: 256,
267
+ maxRegexPatternLength: 256,
268
+ maxGlobPatternLength: 256,
269
+ maxStringLength: 1024,
270
+ maxArrayLength: 64,
271
+ maxFunctionArgs: 16,
272
+ maxMemberAccessDepth: 16,
273
+ };
274
+ /**
275
+ * Validates that expression length is within limits.
276
+ */
277
+ function checkExpressionLength(expression, limits = DEFAULT_EXPRESSION_LIMITS) {
278
+ if (expression.length > limits.maxExpressionLength) {
279
+ throw new Error(`Expression length ${expression.length} exceeds limit of ${limits.maxExpressionLength}`);
280
+ }
281
+ }
282
+ /**
283
+ * Validates AST depth during parsing.
284
+ */
285
+ function checkAstDepth(depth, limits = DEFAULT_EXPRESSION_LIMITS) {
286
+ if (depth > limits.maxAstDepth) {
287
+ throw new Error(`AST depth ${depth} exceeds limit of ${limits.maxAstDepth}`);
288
+ }
289
+ }
290
+ /**
291
+ * Validates AST node count during parsing.
292
+ */
293
+ function checkAstNodeCount(count, limits = DEFAULT_EXPRESSION_LIMITS) {
294
+ if (count > limits.maxAstNodes) {
295
+ throw new Error(`AST node count ${count} exceeds limit of ${limits.maxAstNodes}`);
296
+ }
297
+ }
298
+ /**
299
+ * Validates regex pattern length before compilation.
300
+ */
301
+ function checkRegexPatternLength(pattern, limits = DEFAULT_EXPRESSION_LIMITS) {
302
+ if (pattern.length > limits.maxRegexPatternLength) {
303
+ throw new Error(`Regex pattern length ${pattern.length} exceeds limit of ${limits.maxRegexPatternLength}`);
304
+ }
305
+ }
306
+ /**
307
+ * Validates glob pattern length before compilation.
308
+ */
309
+ function checkGlobPatternLength(pattern, limits = DEFAULT_EXPRESSION_LIMITS) {
310
+ if (pattern.length > limits.maxGlobPatternLength) {
311
+ throw new Error(`Glob pattern length ${pattern.length} exceeds limit of ${limits.maxGlobPatternLength}`);
312
+ }
313
+ }
314
+ /**
315
+ * Validates array length during evaluation.
316
+ */
317
+ function checkArrayLength(length, limits = DEFAULT_EXPRESSION_LIMITS) {
318
+ if (length > limits.maxArrayLength) {
319
+ throw new Error(`Array length ${length} exceeds limit of ${limits.maxArrayLength}`);
320
+ }
321
+ }
322
+ /**
323
+ * Validates function argument count.
324
+ */
325
+ function checkFunctionArgCount(count, limits = DEFAULT_EXPRESSION_LIMITS) {
326
+ if (count > limits.maxFunctionArgs) {
327
+ throw new Error(`Function argument count ${count} exceeds limit of ${limits.maxFunctionArgs}`);
328
+ }
329
+ }
330
+
331
+ /**
332
+ * Tokenizer (lexer) for the expression language.
333
+ *
334
+ * Converts expression strings into a stream of tokens for the parser.
335
+ */
336
+ /**
337
+ * Keywords recognized by the tokenizer.
338
+ */
339
+ const KEYWORDS = new Map([
340
+ ["true", "TRUE"],
341
+ ["false", "FALSE"],
342
+ ["null", "NULL"],
343
+ ["in", "IN"],
344
+ ["not", "NOT"],
345
+ ]);
346
+ /**
347
+ * Checks if a character is a digit.
348
+ */
349
+ function isDigit(ch) {
350
+ return ch >= "0" && ch <= "9";
351
+ }
352
+ /**
353
+ * Checks if a character can start an identifier.
354
+ */
355
+ function isIdentifierStart(ch) {
356
+ return ((ch >= "a" && ch <= "z") ||
357
+ (ch >= "A" && ch <= "Z") ||
358
+ ch === "_");
359
+ }
360
+ /**
361
+ * Checks if a character can continue an identifier.
362
+ */
363
+ function isIdentifierPart(ch) {
364
+ return isIdentifierStart(ch) || isDigit(ch);
365
+ }
366
+ /**
367
+ * Checks if a character is whitespace.
368
+ */
369
+ function isWhitespace(ch) {
370
+ return ch === " " || ch === "\t" || ch === "\n" || ch === "\r";
371
+ }
372
+ /**
373
+ * Tokenizer for expression strings.
374
+ */
375
+ class Tokenizer {
376
+ constructor(source, limits) {
377
+ this.position = 0;
378
+ this.tokens = [];
379
+ this.source = source;
380
+ this.limits = limits;
381
+ }
382
+ /**
383
+ * Tokenizes the source expression and returns all tokens.
384
+ */
385
+ tokenize() {
386
+ checkExpressionLength(this.source, this.limits);
387
+ while (!this.isAtEnd()) {
388
+ this.scanToken();
389
+ }
390
+ this.tokens.push({
391
+ type: "EOF",
392
+ value: "",
393
+ position: this.position,
394
+ });
395
+ return this.tokens;
396
+ }
397
+ isAtEnd() {
398
+ return this.position >= this.source.length;
399
+ }
400
+ peek() {
401
+ if (this.isAtEnd())
402
+ return "\0";
403
+ return this.source[this.position];
404
+ }
405
+ peekNext() {
406
+ if (this.position + 1 >= this.source.length)
407
+ return "\0";
408
+ return this.source[this.position + 1];
409
+ }
410
+ advance() {
411
+ return this.source[this.position++];
412
+ }
413
+ addToken(type, value, position) {
414
+ this.tokens.push({ type, value, position });
415
+ }
416
+ scanToken() {
417
+ const ch = this.advance();
418
+ const startPosition = this.position - 1;
419
+ // Skip whitespace
420
+ if (isWhitespace(ch)) {
421
+ return;
422
+ }
423
+ // Single-character tokens
424
+ switch (ch) {
425
+ case "(":
426
+ this.addToken("LPAREN", "(", startPosition);
427
+ return;
428
+ case ")":
429
+ this.addToken("RPAREN", ")", startPosition);
430
+ return;
431
+ case "[":
432
+ this.addToken("LBRACKET", "[", startPosition);
433
+ return;
434
+ case "]":
435
+ this.addToken("RBRACKET", "]", startPosition);
436
+ return;
437
+ case ".":
438
+ this.addToken("DOT", ".", startPosition);
439
+ return;
440
+ case ",":
441
+ this.addToken("COMMA", ",", startPosition);
442
+ return;
443
+ case "+":
444
+ this.addToken("PLUS", "+", startPosition);
445
+ return;
446
+ case "-":
447
+ this.addToken("MINUS", "-", startPosition);
448
+ return;
449
+ case "*":
450
+ this.addToken("STAR", "*", startPosition);
451
+ return;
452
+ case "/":
453
+ this.addToken("SLASH", "/", startPosition);
454
+ return;
455
+ case "%":
456
+ this.addToken("PERCENT", "%", startPosition);
457
+ return;
458
+ case "?":
459
+ this.addToken("QUESTION", "?", startPosition);
460
+ return;
461
+ case ":":
462
+ this.addToken("COLON", ":", startPosition);
463
+ return;
464
+ }
465
+ // Two-character operators
466
+ if (ch === "<") {
467
+ if (this.peek() === "=") {
468
+ this.advance();
469
+ this.addToken("LE", "<=", startPosition);
470
+ }
471
+ else {
472
+ this.addToken("LT", "<", startPosition);
473
+ }
474
+ return;
475
+ }
476
+ if (ch === ">") {
477
+ if (this.peek() === "=") {
478
+ this.advance();
479
+ this.addToken("GE", ">=", startPosition);
480
+ }
481
+ else {
482
+ this.addToken("GT", ">", startPosition);
483
+ }
484
+ return;
485
+ }
486
+ if (ch === "=") {
487
+ if (this.peek() === "=") {
488
+ this.advance();
489
+ this.addToken("EQ", "==", startPosition);
490
+ return;
491
+ }
492
+ throw new TokenizerError("Unexpected '='. Did you mean '=='?", startPosition, this.source);
493
+ }
494
+ if (ch === "!") {
495
+ if (this.peek() === "=") {
496
+ this.advance();
497
+ this.addToken("NE", "!=", startPosition);
498
+ }
499
+ else {
500
+ this.addToken("NOT", "!", startPosition);
501
+ }
502
+ return;
503
+ }
504
+ if (ch === "&") {
505
+ if (this.peek() === "&") {
506
+ this.advance();
507
+ this.addToken("AND", "&&", startPosition);
508
+ return;
509
+ }
510
+ throw new TokenizerError("Unexpected '&'. Did you mean '&&'?", startPosition, this.source);
511
+ }
512
+ if (ch === "|") {
513
+ if (this.peek() === "|") {
514
+ this.advance();
515
+ this.addToken("OR", "||", startPosition);
516
+ return;
517
+ }
518
+ throw new TokenizerError("Unexpected '|'. Did you mean '||'?", startPosition, this.source);
519
+ }
520
+ // String literals
521
+ if (ch === '"' || ch === "'") {
522
+ this.scanString(ch, startPosition);
523
+ return;
524
+ }
525
+ // Number literals
526
+ if (isDigit(ch)) {
527
+ this.scanNumber(startPosition);
528
+ return;
529
+ }
530
+ // Identifiers and keywords
531
+ if (isIdentifierStart(ch)) {
532
+ this.scanIdentifier(startPosition);
533
+ return;
534
+ }
535
+ throw new TokenizerError(`Unexpected character: '${ch}'`, startPosition, this.source);
536
+ }
537
+ scanString(quote, startPosition) {
538
+ let value = "";
539
+ while (!this.isAtEnd() && this.peek() !== quote) {
540
+ const ch = this.advance();
541
+ if (ch === "\\") {
542
+ // Escape sequence
543
+ if (this.isAtEnd()) {
544
+ throw new TokenizerError("Unterminated string", startPosition, this.source);
545
+ }
546
+ const escaped = this.advance();
547
+ switch (escaped) {
548
+ case "n":
549
+ value += "\n";
550
+ break;
551
+ case "r":
552
+ value += "\r";
553
+ break;
554
+ case "t":
555
+ value += "\t";
556
+ break;
557
+ case "\\":
558
+ value += "\\";
559
+ break;
560
+ case '"':
561
+ value += '"';
562
+ break;
563
+ case "'":
564
+ value += "'";
565
+ break;
566
+ default:
567
+ throw new TokenizerError(`Invalid escape sequence: \\${escaped}`, this.position - 2, this.source);
568
+ }
569
+ }
570
+ else if (ch === "\n" || ch === "\r") {
571
+ throw new TokenizerError("Unterminated string (newline in string literal)", startPosition, this.source);
572
+ }
573
+ else {
574
+ value += ch;
575
+ }
576
+ }
577
+ if (this.isAtEnd()) {
578
+ throw new TokenizerError("Unterminated string", startPosition, this.source);
579
+ }
580
+ // Consume closing quote
581
+ this.advance();
582
+ this.addToken("STRING", value, startPosition);
583
+ }
584
+ scanNumber(startPosition) {
585
+ // Back up to include the first digit
586
+ this.position--;
587
+ let value = "";
588
+ // Integer part
589
+ while (isDigit(this.peek())) {
590
+ value += this.advance();
591
+ }
592
+ // Fractional part
593
+ if (this.peek() === "." && isDigit(this.peekNext())) {
594
+ value += this.advance(); // consume '.'
595
+ while (isDigit(this.peek())) {
596
+ value += this.advance();
597
+ }
598
+ }
599
+ // Exponent part
600
+ if (this.peek() === "e" || this.peek() === "E") {
601
+ value += this.advance();
602
+ if (this.peek() === "+" || this.peek() === "-") {
603
+ value += this.advance();
604
+ }
605
+ if (!isDigit(this.peek())) {
606
+ throw new TokenizerError("Invalid number: expected exponent digits", startPosition, this.source);
607
+ }
608
+ while (isDigit(this.peek())) {
609
+ value += this.advance();
610
+ }
611
+ }
612
+ this.addToken("NUMBER", value, startPosition);
613
+ }
614
+ scanIdentifier(startPosition) {
615
+ // Back up to include the first character
616
+ this.position--;
617
+ let value = "";
618
+ while (isIdentifierPart(this.peek())) {
619
+ value += this.advance();
620
+ }
621
+ // Check for "not in" compound keyword
622
+ const valueLower = value.toLowerCase();
623
+ if (valueLower === "not") {
624
+ // Check if followed by whitespace and "in"
625
+ const savedPosition = this.position;
626
+ // Skip whitespace
627
+ while (isWhitespace(this.peek())) {
628
+ this.advance();
629
+ }
630
+ // Check for "in"
631
+ if (this.peek() === "i" &&
632
+ this.peekNext() === "n" &&
633
+ !isIdentifierPart(this.source[this.position + 2] ?? "\0")) {
634
+ this.advance(); // consume 'i'
635
+ this.advance(); // consume 'n'
636
+ this.addToken("NOT_IN", "not in", startPosition);
637
+ return;
638
+ }
639
+ // Not "not in", restore position
640
+ this.position = savedPosition;
641
+ }
642
+ // Check for keyword
643
+ const keywordType = KEYWORDS.get(valueLower);
644
+ if (keywordType) {
645
+ this.addToken(keywordType, value, startPosition);
646
+ }
647
+ else {
648
+ this.addToken("IDENTIFIER", value, startPosition);
649
+ }
650
+ }
651
+ }
652
+ /**
653
+ * Tokenizes an expression string into tokens.
654
+ *
655
+ * @param source - The expression string to tokenize
656
+ * @param limits - Optional expression limits
657
+ * @returns Array of tokens
658
+ * @throws TokenizerError if the expression contains invalid tokens
659
+ */
660
+ function tokenize(source, limits) {
661
+ const tokenizer = new Tokenizer(source, limits);
662
+ return tokenizer.tokenize();
663
+ }
664
+
665
+ /**
666
+ * Parser for the expression language.
667
+ *
668
+ * Parses a stream of tokens into an Abstract Syntax Tree (AST).
669
+ * Uses recursive descent parsing with operator precedence.
670
+ *
671
+ * Precedence (lowest to highest):
672
+ * 1. Ternary: ? :
673
+ * 2. Logical OR: ||
674
+ * 3. Logical AND: &&
675
+ * 4. Membership: in, not in
676
+ * 5. Equality: ==, !=
677
+ * 6. Comparison: <, <=, >, >=
678
+ * 7. Additive: +, -
679
+ * 8. Multiplicative: *, /, %
680
+ * 9. Unary: !, -
681
+ * 10. Postfix: . [] ()
682
+ * 11. Primary: literals, identifiers, parentheses
683
+ */
684
+ /**
685
+ * Parser for expression strings.
686
+ */
687
+ class Parser {
688
+ constructor(tokens, source, limits = DEFAULT_EXPRESSION_LIMITS) {
689
+ this.current = 0;
690
+ this.tokens = tokens;
691
+ this.source = source;
692
+ this.limits = limits;
693
+ }
694
+ /**
695
+ * Parses the token stream into an AST.
696
+ */
697
+ parse() {
698
+ const ast = this.parseTernary();
699
+ if (!this.isAtEnd()) {
700
+ const token = this.peek();
701
+ throw new ParseError(`Unexpected token: ${token.value || token.type}`, token.position, this.source);
702
+ }
703
+ // Validate AST limits
704
+ const nodeCount = countAstNodes(ast);
705
+ checkAstNodeCount(nodeCount, this.limits);
706
+ const depth = calculateAstDepth(ast);
707
+ checkAstDepth(depth, this.limits);
708
+ return ast;
709
+ }
710
+ // ============================================================
711
+ // Token Helpers
712
+ // ============================================================
713
+ isAtEnd() {
714
+ return this.peek().type === "EOF";
715
+ }
716
+ peek() {
717
+ return this.tokens[this.current];
718
+ }
719
+ previous() {
720
+ return this.tokens[this.current - 1];
721
+ }
722
+ advance() {
723
+ if (!this.isAtEnd()) {
724
+ this.current++;
725
+ }
726
+ return this.previous();
727
+ }
728
+ check(type) {
729
+ if (this.isAtEnd())
730
+ return false;
731
+ return this.peek().type === type;
732
+ }
733
+ match(...types) {
734
+ for (const type of types) {
735
+ if (this.check(type)) {
736
+ this.advance();
737
+ return true;
738
+ }
739
+ }
740
+ return false;
741
+ }
742
+ consume(type, message) {
743
+ if (this.check(type)) {
744
+ return this.advance();
745
+ }
746
+ const token = this.peek();
747
+ throw new ParseError(message, token.position, this.source);
748
+ }
749
+ // ============================================================
750
+ // Expression Parsing (by precedence, lowest to highest)
751
+ // ============================================================
752
+ /**
753
+ * Parses ternary expressions: condition ? consequent : alternate
754
+ */
755
+ parseTernary() {
756
+ const position = this.peek().position;
757
+ let node = this.parseOr();
758
+ if (this.match("QUESTION")) {
759
+ const consequent = this.parseTernary();
760
+ this.consume("COLON", "Expected ':' in ternary expression");
761
+ const alternate = this.parseTernary();
762
+ node = {
763
+ type: "TernaryOp",
764
+ position,
765
+ condition: node,
766
+ consequent,
767
+ alternate,
768
+ };
769
+ }
770
+ return node;
771
+ }
772
+ /**
773
+ * Parses logical OR: ||
774
+ */
775
+ parseOr() {
776
+ let node = this.parseAnd();
777
+ while (this.match("OR")) {
778
+ const position = this.previous().position;
779
+ const right = this.parseAnd();
780
+ node = {
781
+ type: "BinaryOp",
782
+ position,
783
+ operator: "||",
784
+ left: node,
785
+ right,
786
+ };
787
+ }
788
+ return node;
789
+ }
790
+ /**
791
+ * Parses logical AND: &&
792
+ */
793
+ parseAnd() {
794
+ let node = this.parseEquality();
795
+ while (this.match("AND")) {
796
+ const position = this.previous().position;
797
+ const right = this.parseEquality();
798
+ node = {
799
+ type: "BinaryOp",
800
+ position,
801
+ operator: "&&",
802
+ left: node,
803
+ right,
804
+ };
805
+ }
806
+ return node;
807
+ }
808
+ /**
809
+ * Parses equality: ==, !=
810
+ */
811
+ parseEquality() {
812
+ let node = this.parseMembership();
813
+ while (this.match("EQ", "NE")) {
814
+ const operator = this.previous().type === "EQ" ? "==" : "!=";
815
+ const position = this.previous().position;
816
+ const right = this.parseMembership();
817
+ node = {
818
+ type: "BinaryOp",
819
+ position,
820
+ operator: operator,
821
+ left: node,
822
+ right,
823
+ };
824
+ }
825
+ return node;
826
+ }
827
+ /**
828
+ * Parses membership: in, not in
829
+ */
830
+ parseMembership() {
831
+ let node = this.parseComparison();
832
+ while (this.match("IN", "NOT_IN")) {
833
+ const operator = this.previous().type === "IN" ? "in" : "not in";
834
+ const position = this.previous().position;
835
+ const right = this.parseComparison();
836
+ node = {
837
+ type: "BinaryOp",
838
+ position,
839
+ operator: operator,
840
+ left: node,
841
+ right,
842
+ };
843
+ }
844
+ return node;
845
+ }
846
+ /**
847
+ * Parses comparison: <, <=, >, >=
848
+ */
849
+ parseComparison() {
850
+ let node = this.parseAdditive();
851
+ while (this.match("LT", "LE", "GT", "GE")) {
852
+ const token = this.previous();
853
+ let operator;
854
+ switch (token.type) {
855
+ case "LT":
856
+ operator = "<";
857
+ break;
858
+ case "LE":
859
+ operator = "<=";
860
+ break;
861
+ case "GT":
862
+ operator = ">";
863
+ break;
864
+ case "GE":
865
+ operator = ">=";
866
+ break;
867
+ default:
868
+ throw new ParseError(`Unexpected token: ${token.type}`, token.position, this.source);
869
+ }
870
+ const position = token.position;
871
+ const right = this.parseAdditive();
872
+ node = {
873
+ type: "BinaryOp",
874
+ position,
875
+ operator,
876
+ left: node,
877
+ right,
878
+ };
879
+ }
880
+ return node;
881
+ }
882
+ /**
883
+ * Parses additive: +, -
884
+ */
885
+ parseAdditive() {
886
+ let node = this.parseMultiplicative();
887
+ while (this.match("PLUS", "MINUS")) {
888
+ const operator = this.previous().type === "PLUS" ? "+" : "-";
889
+ const position = this.previous().position;
890
+ const right = this.parseMultiplicative();
891
+ node = {
892
+ type: "BinaryOp",
893
+ position,
894
+ operator: operator,
895
+ left: node,
896
+ right,
897
+ };
898
+ }
899
+ return node;
900
+ }
901
+ /**
902
+ * Parses multiplicative: *, /, %
903
+ */
904
+ parseMultiplicative() {
905
+ let node = this.parseUnary();
906
+ while (this.match("STAR", "SLASH", "PERCENT")) {
907
+ const token = this.previous();
908
+ let operator;
909
+ switch (token.type) {
910
+ case "STAR":
911
+ operator = "*";
912
+ break;
913
+ case "SLASH":
914
+ operator = "/";
915
+ break;
916
+ case "PERCENT":
917
+ operator = "%";
918
+ break;
919
+ default:
920
+ throw new ParseError(`Unexpected token: ${token.type}`, token.position, this.source);
921
+ }
922
+ const position = token.position;
923
+ const right = this.parseUnary();
924
+ node = {
925
+ type: "BinaryOp",
926
+ position,
927
+ operator,
928
+ left: node,
929
+ right,
930
+ };
931
+ }
932
+ return node;
933
+ }
934
+ /**
935
+ * Parses unary: !, -
936
+ */
937
+ parseUnary() {
938
+ if (this.match("NOT", "MINUS")) {
939
+ const token = this.previous();
940
+ const operator = token.type === "NOT" ? "!" : "-";
941
+ const position = token.position;
942
+ const operand = this.parseUnary();
943
+ return {
944
+ type: "UnaryOp",
945
+ position,
946
+ operator,
947
+ operand,
948
+ };
949
+ }
950
+ return this.parsePostfix();
951
+ }
952
+ /**
953
+ * Parses postfix: . [] ()
954
+ */
955
+ parsePostfix() {
956
+ let node = this.parsePrimary();
957
+ while (true) {
958
+ if (this.match("DOT")) {
959
+ const position = this.previous().position;
960
+ const propToken = this.consume("IDENTIFIER", "Expected property name after '.'");
961
+ node = {
962
+ type: "MemberAccess",
963
+ position,
964
+ object: node,
965
+ property: propToken.value,
966
+ };
967
+ }
968
+ else if (this.match("LBRACKET")) {
969
+ const position = this.previous().position;
970
+ const index = this.parseTernary();
971
+ this.consume("RBRACKET", "Expected ']' after index");
972
+ node = {
973
+ type: "IndexAccess",
974
+ position,
975
+ object: node,
976
+ index,
977
+ };
978
+ }
979
+ else if (this.match("LPAREN")) {
980
+ // Function call - node must be an identifier
981
+ if (node.type !== "Identifier") {
982
+ throw new ParseError("Only named functions can be called", node.position, this.source);
983
+ }
984
+ const position = this.previous().position;
985
+ const args = this.parseArgumentList();
986
+ checkFunctionArgCount(args.length, this.limits);
987
+ node = {
988
+ type: "FunctionCall",
989
+ position,
990
+ name: node.name,
991
+ args,
992
+ };
993
+ }
994
+ else {
995
+ break;
996
+ }
997
+ }
998
+ return node;
999
+ }
1000
+ /**
1001
+ * Parses function argument list (already consumed opening paren).
1002
+ */
1003
+ parseArgumentList() {
1004
+ const args = [];
1005
+ if (!this.check("RPAREN")) {
1006
+ do {
1007
+ args.push(this.parseTernary());
1008
+ } while (this.match("COMMA"));
1009
+ }
1010
+ this.consume("RPAREN", "Expected ')' after function arguments");
1011
+ return args;
1012
+ }
1013
+ /**
1014
+ * Parses primary expressions: literals, identifiers, parentheses, arrays.
1015
+ */
1016
+ parsePrimary() {
1017
+ const token = this.peek();
1018
+ const position = token.position;
1019
+ // Boolean literals
1020
+ if (this.match("TRUE")) {
1021
+ return { type: "BooleanLiteral", position, value: true };
1022
+ }
1023
+ if (this.match("FALSE")) {
1024
+ return { type: "BooleanLiteral", position, value: false };
1025
+ }
1026
+ // Null literal
1027
+ if (this.match("NULL")) {
1028
+ return { type: "NullLiteral", position };
1029
+ }
1030
+ // String literal
1031
+ if (this.match("STRING")) {
1032
+ return {
1033
+ type: "StringLiteral",
1034
+ position,
1035
+ value: this.previous().value,
1036
+ };
1037
+ }
1038
+ // Number literal
1039
+ if (this.match("NUMBER")) {
1040
+ const value = parseFloat(this.previous().value);
1041
+ if (!Number.isFinite(value)) {
1042
+ throw new ParseError("Invalid number", position, this.source);
1043
+ }
1044
+ return { type: "NumberLiteral", position, value };
1045
+ }
1046
+ // Identifier
1047
+ if (this.match("IDENTIFIER")) {
1048
+ return {
1049
+ type: "Identifier",
1050
+ position,
1051
+ name: this.previous().value,
1052
+ };
1053
+ }
1054
+ // Parenthesized expression
1055
+ if (this.match("LPAREN")) {
1056
+ const expr = this.parseTernary();
1057
+ this.consume("RPAREN", "Expected ')' after expression");
1058
+ return expr;
1059
+ }
1060
+ // Array literal
1061
+ if (this.match("LBRACKET")) {
1062
+ const elements = [];
1063
+ if (!this.check("RBRACKET")) {
1064
+ do {
1065
+ elements.push(this.parseTernary());
1066
+ } while (this.match("COMMA"));
1067
+ }
1068
+ this.consume("RBRACKET", "Expected ']' after array elements");
1069
+ checkArrayLength(elements.length, this.limits);
1070
+ return { type: "ArrayLiteral", position, elements };
1071
+ }
1072
+ throw new ParseError(`Unexpected token: ${token.value || token.type}`, position, this.source);
1073
+ }
1074
+ }
1075
+ /**
1076
+ * Parses an expression string into an AST.
1077
+ *
1078
+ * @param source - The expression string to parse
1079
+ * @param limits - Optional expression limits
1080
+ * @returns The parsed AST
1081
+ * @throws TokenizerError if tokenization fails
1082
+ * @throws ParseError if parsing fails
1083
+ */
1084
+ function parse(source, limits = DEFAULT_EXPRESSION_LIMITS) {
1085
+ const tokens = tokenize(source, limits);
1086
+ const parser = new Parser(tokens, source, limits);
1087
+ return parser.parse();
1088
+ }
1089
+
1090
+ /**
1091
+ * Built-in functions for the expression language.
1092
+ *
1093
+ * All built-in functions are pure and deterministic.
1094
+ *
1095
+ * Null handling semantics:
1096
+ * - `undefined` is normalized to `null` throughout the expression value model.
1097
+ * - Predicate-style builtins (starts_with, ends_with, contains, glob_match,
1098
+ * regex_match, etc.) return `false` when passed `null` for required args
1099
+ * instead of throwing an error.
1100
+ * - Wrong non-null types still raise BuiltinError to surface real bugs.
1101
+ * - Non-predicate operations (arithmetic, comparisons) remain strict.
1102
+ */
1103
+ /**
1104
+ * Normalizes a JavaScript value to an ExprValue.
1105
+ *
1106
+ * Rules:
1107
+ * - `undefined` -> `null`
1108
+ * - `null` -> `null`
1109
+ * - boolean/number/string -> returned as-is
1110
+ * - array -> elements are recursively normalized
1111
+ * - object -> returned as-is (reads will normalize on access)
1112
+ * - other types (function, symbol, etc.) -> `null`
1113
+ *
1114
+ * This ensures `undefined` never leaks into the expression value model.
1115
+ */
1116
+ function normalizeJsValue(value) {
1117
+ if (value === undefined || value === null) {
1118
+ return null;
1119
+ }
1120
+ if (typeof value === "boolean" || typeof value === "number") {
1121
+ return value;
1122
+ }
1123
+ if (typeof value === "string") {
1124
+ return value;
1125
+ }
1126
+ if (Array.isArray(value)) {
1127
+ return value.map((element) => normalizeJsValue(element));
1128
+ }
1129
+ if (typeof value === "object") {
1130
+ // Return the object as-is; reads will normalize on access
1131
+ return value;
1132
+ }
1133
+ // Function, symbol, bigint, etc. -> null
1134
+ return null;
1135
+ }
1136
+ /**
1137
+ * Gets the type name of a value for error messages.
1138
+ */
1139
+ function getTypeName(value) {
1140
+ if (value === null)
1141
+ return "null";
1142
+ if (Array.isArray(value))
1143
+ return "array";
1144
+ return typeof value;
1145
+ }
1146
+ /**
1147
+ * Asserts that a value is a string.
1148
+ */
1149
+ function assertString$1(value, argName, functionName) {
1150
+ if (typeof value !== "string") {
1151
+ throw new BuiltinError(functionName, `${argName} must be a string, got ${getTypeName(value)}`);
1152
+ }
1153
+ }
1154
+ /**
1155
+ * Checks if a value is null (for null-tolerant predicates).
1156
+ */
1157
+ function isNull$1(value) {
1158
+ return value === null;
1159
+ }
1160
+ /**
1161
+ * Asserts that a non-null value is a string (for null-tolerant predicates).
1162
+ * Returns false if the value is null (indicating predicate should return false).
1163
+ * Throws BuiltinError if the value is non-null but not a string.
1164
+ */
1165
+ function assertStringOrNull$1(value, argName, functionName) {
1166
+ if (isNull$1(value)) {
1167
+ return false;
1168
+ }
1169
+ if (typeof value !== "string") {
1170
+ throw new BuiltinError(functionName, `${argName} must be a string, got ${getTypeName(value)}`);
1171
+ }
1172
+ return true;
1173
+ }
1174
+ /**
1175
+ * Gets an argument by index, throwing if not present.
1176
+ */
1177
+ function getArg$1(args, index, functionName) {
1178
+ const value = args[index];
1179
+ if (value === undefined) {
1180
+ throw new BuiltinError(functionName, `missing argument at index ${index}`);
1181
+ }
1182
+ return value;
1183
+ }
1184
+ /**
1185
+ * Asserts argument count.
1186
+ */
1187
+ function assertArgCount$1(args, expected, functionName) {
1188
+ if (args.length !== expected) {
1189
+ throw new BuiltinError(functionName, `expected ${expected} argument(s), got ${args.length}`);
1190
+ }
1191
+ }
1192
+ /**
1193
+ * Asserts argument count range.
1194
+ */
1195
+ function assertArgCountRange(args, min, max, functionName) {
1196
+ if (args.length < min || args.length > max) {
1197
+ throw new BuiltinError(functionName, `expected ${min}-${max} argument(s), got ${args.length}`);
1198
+ }
1199
+ }
1200
+ // ============================================================
1201
+ // String Helpers
1202
+ // ============================================================
1203
+ /**
1204
+ * lower(s: string) -> string
1205
+ *
1206
+ * Returns the lowercase version of the string.
1207
+ */
1208
+ const lower = (args) => {
1209
+ assertArgCount$1(args, 1, "lower");
1210
+ const s = getArg$1(args, 0, "lower");
1211
+ assertString$1(s, "s", "lower");
1212
+ return s.toLowerCase();
1213
+ };
1214
+ /**
1215
+ * upper(s: string) -> string
1216
+ *
1217
+ * Returns the uppercase version of the string.
1218
+ */
1219
+ const upper = (args) => {
1220
+ assertArgCount$1(args, 1, "upper");
1221
+ const s = getArg$1(args, 0, "upper");
1222
+ assertString$1(s, "s", "upper");
1223
+ return s.toUpperCase();
1224
+ };
1225
+ /**
1226
+ * starts_with(s: string, prefix: string) -> bool
1227
+ *
1228
+ * Returns true if the string starts with the prefix.
1229
+ * Null-tolerant: returns false if either argument is null.
1230
+ */
1231
+ const starts_with = (args) => {
1232
+ assertArgCount$1(args, 2, "starts_with");
1233
+ const s = getArg$1(args, 0, "starts_with");
1234
+ const prefix = getArg$1(args, 1, "starts_with");
1235
+ // Null-tolerant: return false if either arg is null
1236
+ if (!assertStringOrNull$1(s, "s", "starts_with"))
1237
+ return false;
1238
+ if (!assertStringOrNull$1(prefix, "prefix", "starts_with"))
1239
+ return false;
1240
+ return s.startsWith(prefix);
1241
+ };
1242
+ /**
1243
+ * ends_with(s: string, suffix: string) -> bool
1244
+ *
1245
+ * Returns true if the string ends with the suffix.
1246
+ * Null-tolerant: returns false if either argument is null.
1247
+ */
1248
+ const ends_with = (args) => {
1249
+ assertArgCount$1(args, 2, "ends_with");
1250
+ const s = getArg$1(args, 0, "ends_with");
1251
+ const suffix = getArg$1(args, 1, "ends_with");
1252
+ // Null-tolerant: return false if either arg is null
1253
+ if (!assertStringOrNull$1(s, "s", "ends_with"))
1254
+ return false;
1255
+ if (!assertStringOrNull$1(suffix, "suffix", "ends_with"))
1256
+ return false;
1257
+ return s.endsWith(suffix);
1258
+ };
1259
+ /**
1260
+ * contains(s: string, substring: string) -> bool
1261
+ *
1262
+ * Returns true if the string contains the substring.
1263
+ * Null-tolerant: returns false if either argument is null.
1264
+ */
1265
+ const contains = (args) => {
1266
+ assertArgCount$1(args, 2, "contains");
1267
+ const s = getArg$1(args, 0, "contains");
1268
+ const substring = getArg$1(args, 1, "contains");
1269
+ // Null-tolerant: return false if either arg is null
1270
+ if (!assertStringOrNull$1(s, "s", "contains"))
1271
+ return false;
1272
+ if (!assertStringOrNull$1(substring, "substring", "contains"))
1273
+ return false;
1274
+ return s.includes(substring);
1275
+ };
1276
+ /**
1277
+ * split(s: string, separator: string) -> string[]
1278
+ *
1279
+ * Splits the string by the separator.
1280
+ */
1281
+ const split = (args) => {
1282
+ assertArgCountRange(args, 1, 2, "split");
1283
+ const s = getArg$1(args, 0, "split");
1284
+ assertString$1(s, "s", "split");
1285
+ const separator = args.length >= 2 ? getArg$1(args, 1, "split") : " ";
1286
+ assertString$1(separator, "separator", "split");
1287
+ return s.split(separator);
1288
+ };
1289
+ // ============================================================
1290
+ // Collection Helpers
1291
+ // ============================================================
1292
+ /**
1293
+ * len(x: string | array) -> number
1294
+ *
1295
+ * Returns the length of a string or array.
1296
+ */
1297
+ const len = (args) => {
1298
+ assertArgCount$1(args, 1, "len");
1299
+ const x = getArg$1(args, 0, "len");
1300
+ if (typeof x === "string") {
1301
+ return x.length;
1302
+ }
1303
+ if (Array.isArray(x)) {
1304
+ return x.length;
1305
+ }
1306
+ throw new BuiltinError("len", `expected string or array, got ${getTypeName(x)}`);
1307
+ };
1308
+ // ============================================================
1309
+ // Generic Helpers
1310
+ // ============================================================
1311
+ /**
1312
+ * exists(x: any) -> bool
1313
+ *
1314
+ * Returns true if the value is not null.
1315
+ * Missing bindings and missing properties evaluate to null, so this
1316
+ * can be used to check for presence.
1317
+ */
1318
+ const exists = (args) => {
1319
+ assertArgCount$1(args, 1, "exists");
1320
+ const x = getArg$1(args, 0, "exists");
1321
+ return x !== null;
1322
+ };
1323
+ /**
1324
+ * coalesce(a: any, b: any) -> any
1325
+ *
1326
+ * Returns `a` if it is not null, otherwise returns `b`.
1327
+ * This is useful for providing default values.
1328
+ */
1329
+ const coalesce = (args) => {
1330
+ assertArgCount$1(args, 2, "coalesce");
1331
+ const a = getArg$1(args, 0, "coalesce");
1332
+ const b = getArg$1(args, 1, "coalesce");
1333
+ return a !== null ? a : b;
1334
+ };
1335
+ /**
1336
+ * trim(s: string) -> string
1337
+ *
1338
+ * Trims whitespace from both ends of a string.
1339
+ * Returns an empty string if `s` is null (for convenient composition).
1340
+ * Throws BuiltinError if `s` is non-null but not a string.
1341
+ */
1342
+ const trim = (args) => {
1343
+ assertArgCount$1(args, 1, "trim");
1344
+ const s = getArg$1(args, 0, "trim");
1345
+ // Null-friendly: return empty string for null
1346
+ if (s === null) {
1347
+ return "";
1348
+ }
1349
+ // Strict type check for non-null values
1350
+ if (typeof s !== "string") {
1351
+ throw new BuiltinError("trim", `s must be a string, got ${getTypeName(s)}`);
1352
+ }
1353
+ return s.trim();
1354
+ };
1355
+ /**
1356
+ * secure_hash(input_str: string, length: number) -> string
1357
+ *
1358
+ * Generates a deterministic secure hash/fingerprint of the input string.
1359
+ * Uses SHA-256 hashing to create a stable identifier of the specified length.
1360
+ * Returns base62-encoded string (alphanumeric, case-sensitive).
1361
+ * Automatically rehashes if result contains blacklisted words.
1362
+ * Returns empty string if input_str is null (for convenient composition).
1363
+ * Throws BuiltinError if input_str is non-null but not a string, or if length is invalid.
1364
+ */
1365
+ const secure_hash = (args) => {
1366
+ assertArgCount$1(args, 2, "secure_hash");
1367
+ const input_str = getArg$1(args, 0, "secure_hash");
1368
+ const length = getArg$1(args, 1, "secure_hash");
1369
+ // Null-friendly: return empty string for null input
1370
+ if (input_str === null) {
1371
+ return "";
1372
+ }
1373
+ // Strict type check for input_str
1374
+ if (typeof input_str !== "string") {
1375
+ throw new BuiltinError("secure_hash", `input_str must be a string, got ${getTypeName(input_str)}`);
1376
+ }
1377
+ // Strict type check for length
1378
+ if (typeof length !== "number") {
1379
+ throw new BuiltinError("secure_hash", `length must be a number, got ${getTypeName(length)}`);
1380
+ }
1381
+ // Validate length is a positive integer
1382
+ if (!Number.isInteger(length) || length <= 0) {
1383
+ throw new BuiltinError("secure_hash", `length must be a positive integer, got ${length}`);
1384
+ }
1385
+ // Use generateFingerprintSync from @naylence/core
1386
+ // This provides SHA-256 hashing, base62 encoding, and profanity filtering
1387
+ return core.generateFingerprintSync(input_str, length, sha256.sha256);
1388
+ };
1389
+ // ============================================================
1390
+ // Pattern Helpers (BSL-only)
1391
+ // ============================================================
1392
+ /**
1393
+ * Escapes special regex characters in a string.
1394
+ */
1395
+ function escapeRegex(str) {
1396
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1397
+ }
1398
+ /**
1399
+ * Converts a glob pattern to a regex pattern.
1400
+ */
1401
+ function globToRegex(glob) {
1402
+ const parts = [];
1403
+ let i = 0;
1404
+ while (i < glob.length) {
1405
+ const ch = glob[i];
1406
+ if (ch === "*") {
1407
+ if (glob[i + 1] === "*") {
1408
+ // `**` matches any characters
1409
+ parts.push(".*");
1410
+ i += 2;
1411
+ }
1412
+ else {
1413
+ // `*` matches any characters except dots
1414
+ parts.push("[^.]*");
1415
+ i += 1;
1416
+ }
1417
+ }
1418
+ else if (ch === "?") {
1419
+ // `?` matches a single character
1420
+ parts.push("[^.]");
1421
+ i += 1;
1422
+ }
1423
+ else {
1424
+ parts.push(escapeRegex(ch));
1425
+ i += 1;
1426
+ }
1427
+ }
1428
+ return parts.join("");
1429
+ }
1430
+ /**
1431
+ * glob_match(value: string, pattern: string) -> bool
1432
+ *
1433
+ * Returns true if the value matches the glob pattern.
1434
+ * Glob syntax: * (single segment), ** (any depth), ? (single char)
1435
+ * Null-tolerant: returns false if either argument is null.
1436
+ */
1437
+ const glob_match = (args, context) => {
1438
+ assertArgCount$1(args, 2, "glob_match");
1439
+ const value = getArg$1(args, 0, "glob_match");
1440
+ const pattern = getArg$1(args, 1, "glob_match");
1441
+ // Null-tolerant: return false if either arg is null
1442
+ if (!assertStringOrNull$1(value, "value", "glob_match"))
1443
+ return false;
1444
+ if (!assertStringOrNull$1(pattern, "pattern", "glob_match"))
1445
+ return false;
1446
+ // Validate pattern length
1447
+ checkGlobPatternLength(pattern, context.limits);
1448
+ // Convert glob to regex
1449
+ const regexPattern = `^${globToRegex(pattern)}$`;
1450
+ try {
1451
+ const regex = new RegExp(regexPattern);
1452
+ return regex.test(value);
1453
+ }
1454
+ catch {
1455
+ throw new BuiltinError("glob_match", `invalid glob pattern: ${pattern}`);
1456
+ }
1457
+ };
1458
+ /**
1459
+ * Detects potentially catastrophic regex patterns.
1460
+ *
1461
+ * This is a best-effort heuristic check for common ReDoS patterns.
1462
+ */
1463
+ function isSafeRegex(pattern) {
1464
+ // Check for obvious catastrophic patterns:
1465
+ // - Nested quantifiers: (a+)+, (a*)*
1466
+ // - Overlapping alternation with quantifiers: (a|a)+
1467
+ // Simple heuristic: reject patterns with nested quantifiers
1468
+ const nestedQuantifiers = /([+*?]|\{\d+,?\d*\})\s*\)\s*([+*?]|\{\d+,?\d*\})/;
1469
+ if (nestedQuantifiers.test(pattern)) {
1470
+ return false;
1471
+ }
1472
+ // Reject patterns with excessive backtracking potential
1473
+ const excessiveBacktracking = /(\.\*){3,}|(\.\+){3,}/;
1474
+ if (excessiveBacktracking.test(pattern)) {
1475
+ return false;
1476
+ }
1477
+ return true;
1478
+ }
1479
+ /**
1480
+ * regex_match(value: string, pattern: string) -> bool
1481
+ *
1482
+ * Returns true if the value matches the regex pattern.
1483
+ * The pattern is anchored (full match).
1484
+ * Null-tolerant: returns false if either argument is null.
1485
+ */
1486
+ const regex_match = (args, context) => {
1487
+ assertArgCount$1(args, 2, "regex_match");
1488
+ const value = getArg$1(args, 0, "regex_match");
1489
+ const pattern = getArg$1(args, 1, "regex_match");
1490
+ // Null-tolerant: return false if either arg is null
1491
+ if (!assertStringOrNull$1(value, "value", "regex_match"))
1492
+ return false;
1493
+ if (!assertStringOrNull$1(pattern, "pattern", "regex_match"))
1494
+ return false;
1495
+ // Validate pattern length
1496
+ checkRegexPatternLength(pattern, context.limits);
1497
+ // Check for potentially unsafe patterns
1498
+ if (!isSafeRegex(pattern)) {
1499
+ throw new BuiltinError("regex_match", `pattern may cause excessive backtracking: ${pattern}`);
1500
+ }
1501
+ // Anchor the pattern for full match
1502
+ const anchoredPattern = pattern.startsWith("^")
1503
+ ? pattern
1504
+ : pattern.endsWith("$")
1505
+ ? pattern
1506
+ : `^(?:${pattern})$`;
1507
+ try {
1508
+ const regex = new RegExp(anchoredPattern);
1509
+ return regex.test(value);
1510
+ }
1511
+ catch (error) {
1512
+ throw new BuiltinError("regex_match", `invalid regex pattern: ${pattern} - ${error instanceof Error ? error.message : String(error)}`);
1513
+ }
1514
+ };
1515
+ // ============================================================
1516
+ // Registry
1517
+ // ============================================================
1518
+ /**
1519
+ * Registry of all built-in functions.
1520
+ */
1521
+ const BUILTIN_FUNCTIONS = new Map([
1522
+ // String helpers
1523
+ ["lower", lower],
1524
+ ["upper", upper],
1525
+ ["starts_with", starts_with],
1526
+ ["ends_with", ends_with],
1527
+ ["contains", contains],
1528
+ ["split", split],
1529
+ ["trim", trim],
1530
+ // Collection helpers
1531
+ ["len", len],
1532
+ // Generic helpers
1533
+ ["exists", exists],
1534
+ ["coalesce", coalesce],
1535
+ ["secure_hash", secure_hash],
1536
+ // Pattern helpers
1537
+ ["glob_match", glob_match],
1538
+ ["regex_match", regex_match],
1539
+ ]);
1540
+ /**
1541
+ * Calls a built-in function by name.
1542
+ *
1543
+ * @param name - The function name
1544
+ * @param args - The function arguments
1545
+ * @param context - The evaluation context
1546
+ * @returns The function result
1547
+ * @throws BuiltinError if the function doesn't exist or fails
1548
+ */
1549
+ function callBuiltin(name, args, context, functions = BUILTIN_FUNCTIONS) {
1550
+ const fn = functions.get(name);
1551
+ if (!fn) {
1552
+ throw new EvaluationError(`Unknown function: ${name}`, context.position, context.source);
1553
+ }
1554
+ return fn(args, context);
1555
+ }
1556
+ /**
1557
+ * Checks if a name is a built-in function.
1558
+ */
1559
+ function isBuiltinFunction(name, functions = BUILTIN_FUNCTIONS) {
1560
+ return functions.has(name);
1561
+ }
1562
+
1563
+ /**
1564
+ * Expression evaluator.
1565
+ *
1566
+ * Evaluates an AST against a set of variable bindings and returns a value.
1567
+ *
1568
+ * Null handling semantics:
1569
+ * - `undefined` values are normalized to `null` throughout evaluation.
1570
+ * - Missing identifiers evaluate to `null`.
1571
+ * - Member access on `null` or non-object returns `null`.
1572
+ * - Missing properties return `null` (including properties set to `undefined`).
1573
+ */
1574
+ /**
1575
+ * Evaluates an AST node and returns the result.
1576
+ */
1577
+ class Evaluator {
1578
+ constructor(context) {
1579
+ this.memberAccessDepth = 0;
1580
+ this.context = context;
1581
+ this.limits = context.limits ?? DEFAULT_EXPRESSION_LIMITS;
1582
+ this.source = context.source ?? "";
1583
+ this.functions = context.functions ?? BUILTIN_FUNCTIONS;
1584
+ }
1585
+ /**
1586
+ * Evaluates an AST node and returns the value.
1587
+ */
1588
+ evaluate(node) {
1589
+ switch (node.type) {
1590
+ case "StringLiteral":
1591
+ return node.value;
1592
+ case "NumberLiteral":
1593
+ return node.value;
1594
+ case "BooleanLiteral":
1595
+ return node.value;
1596
+ case "NullLiteral":
1597
+ return null;
1598
+ case "ArrayLiteral":
1599
+ return node.elements.map((e) => this.evaluate(e));
1600
+ case "Identifier":
1601
+ return this.evaluateIdentifier(node.name, node.position);
1602
+ case "MemberAccess":
1603
+ return this.evaluateMemberAccess(node);
1604
+ case "IndexAccess":
1605
+ return this.evaluateIndexAccess(node);
1606
+ case "FunctionCall":
1607
+ return this.evaluateFunctionCall(node);
1608
+ case "UnaryOp":
1609
+ return this.evaluateUnaryOp(node.operator, node.operand, node.position);
1610
+ case "BinaryOp":
1611
+ return this.evaluateBinaryOp(node.operator, node.left, node.right, node.position);
1612
+ case "TernaryOp":
1613
+ return this.evaluateTernaryOp(node.condition, node.consequent, node.alternate, node.position);
1614
+ }
1615
+ }
1616
+ /**
1617
+ * Evaluates as boolean with strict type checking.
1618
+ */
1619
+ evaluateAsBoolean(node) {
1620
+ const value = this.evaluate(node);
1621
+ if (typeof value !== "boolean") {
1622
+ throw new TypeError("boolean", getTypeName(value), node.position, this.source);
1623
+ }
1624
+ return value;
1625
+ }
1626
+ evaluateIdentifier(name, _position) {
1627
+ // Check if it's a top-level binding
1628
+ if (name in this.context.bindings) {
1629
+ // Normalize the value to ensure undefined becomes null
1630
+ return normalizeJsValue(this.context.bindings[name]);
1631
+ }
1632
+ // Unknown identifier evaluates to null (missing field)
1633
+ return null;
1634
+ }
1635
+ evaluateMemberAccess(node) {
1636
+ // Check member access depth
1637
+ this.memberAccessDepth++;
1638
+ if (this.memberAccessDepth > this.limits.maxMemberAccessDepth) {
1639
+ throw new EvaluationError(`Member access depth ${this.memberAccessDepth} exceeds limit of ${this.limits.maxMemberAccessDepth}`, node.position, this.source);
1640
+ }
1641
+ try {
1642
+ const obj = this.evaluate(node.object);
1643
+ // Null-safe member access: null.foo -> null
1644
+ if (obj === null) {
1645
+ return null;
1646
+ }
1647
+ // Must be an object (not primitive, not array)
1648
+ if (typeof obj !== "object" || Array.isArray(obj)) {
1649
+ // Type mismatch during access returns null (not error)
1650
+ return null;
1651
+ }
1652
+ const record = obj;
1653
+ if (node.property in record) {
1654
+ // Normalize the value to ensure undefined becomes null
1655
+ return normalizeJsValue(record[node.property]);
1656
+ }
1657
+ // Missing property evaluates to null
1658
+ return null;
1659
+ }
1660
+ finally {
1661
+ this.memberAccessDepth--;
1662
+ }
1663
+ }
1664
+ evaluateIndexAccess(node) {
1665
+ const obj = this.evaluate(node.object);
1666
+ const index = this.evaluate(node.index);
1667
+ // Null-safe index access: null[0] -> null
1668
+ if (obj === null) {
1669
+ return null;
1670
+ }
1671
+ // Array access with numeric index
1672
+ if (Array.isArray(obj)) {
1673
+ if (typeof index !== "number") {
1674
+ throw new TypeError("number", getTypeName(index), node.position, this.source);
1675
+ }
1676
+ const intIndex = Math.floor(index);
1677
+ if (intIndex < 0 || intIndex >= obj.length) {
1678
+ // Out of bounds evaluates to null
1679
+ return null;
1680
+ }
1681
+ // Normalize array element to ensure undefined becomes null
1682
+ return normalizeJsValue(obj[intIndex]);
1683
+ }
1684
+ // Object access with string key
1685
+ if (typeof obj === "object") {
1686
+ if (typeof index !== "string") {
1687
+ throw new TypeError("string", getTypeName(index), node.position, this.source);
1688
+ }
1689
+ const record = obj;
1690
+ if (index in record) {
1691
+ // Normalize the value to ensure undefined becomes null
1692
+ return normalizeJsValue(record[index]);
1693
+ }
1694
+ // Missing key evaluates to null
1695
+ return null;
1696
+ }
1697
+ // Type mismatch during access returns null
1698
+ return null;
1699
+ }
1700
+ evaluateFunctionCall(node) {
1701
+ // Evaluate arguments
1702
+ const args = node.args.map((arg) => this.evaluate(arg));
1703
+ const builtinContext = {
1704
+ limits: this.limits,
1705
+ position: node.position,
1706
+ source: this.source,
1707
+ };
1708
+ return callBuiltin(node.name, args, builtinContext, this.functions);
1709
+ }
1710
+ evaluateUnaryOp(operator, operand, position) {
1711
+ const value = this.evaluate(operand);
1712
+ switch (operator) {
1713
+ case "!":
1714
+ if (typeof value !== "boolean") {
1715
+ throw new TypeError("boolean", getTypeName(value), position, this.source);
1716
+ }
1717
+ return !value;
1718
+ case "-":
1719
+ if (typeof value !== "number") {
1720
+ throw new TypeError("number", getTypeName(value), position, this.source);
1721
+ }
1722
+ return -value;
1723
+ }
1724
+ }
1725
+ evaluateBinaryOp(operator, left, right, position) {
1726
+ // Short-circuit evaluation for logical operators
1727
+ if (operator === "&&") {
1728
+ const leftValue = this.evaluate(left);
1729
+ if (typeof leftValue !== "boolean") {
1730
+ throw new TypeError("boolean", getTypeName(leftValue), left.position, this.source);
1731
+ }
1732
+ if (!leftValue)
1733
+ return false;
1734
+ const rightValue = this.evaluate(right);
1735
+ if (typeof rightValue !== "boolean") {
1736
+ throw new TypeError("boolean", getTypeName(rightValue), right.position, this.source);
1737
+ }
1738
+ return rightValue;
1739
+ }
1740
+ if (operator === "||") {
1741
+ const leftValue = this.evaluate(left);
1742
+ if (typeof leftValue !== "boolean") {
1743
+ throw new TypeError("boolean", getTypeName(leftValue), left.position, this.source);
1744
+ }
1745
+ if (leftValue)
1746
+ return true;
1747
+ const rightValue = this.evaluate(right);
1748
+ if (typeof rightValue !== "boolean") {
1749
+ throw new TypeError("boolean", getTypeName(rightValue), right.position, this.source);
1750
+ }
1751
+ return rightValue;
1752
+ }
1753
+ // Eager evaluation for other operators
1754
+ const leftValue = this.evaluate(left);
1755
+ const rightValue = this.evaluate(right);
1756
+ switch (operator) {
1757
+ // Arithmetic
1758
+ case "+":
1759
+ if (typeof leftValue === "string" && typeof rightValue === "string") {
1760
+ return leftValue + rightValue;
1761
+ }
1762
+ if (typeof leftValue === "number" && typeof rightValue === "number") {
1763
+ return leftValue + rightValue;
1764
+ }
1765
+ throw new EvaluationError(`Cannot add ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
1766
+ case "-":
1767
+ if (typeof leftValue !== "number" || typeof rightValue !== "number") {
1768
+ throw new EvaluationError(`Cannot subtract ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
1769
+ }
1770
+ return leftValue - rightValue;
1771
+ case "*":
1772
+ if (typeof leftValue !== "number" || typeof rightValue !== "number") {
1773
+ throw new EvaluationError(`Cannot multiply ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
1774
+ }
1775
+ return leftValue * rightValue;
1776
+ case "/":
1777
+ if (typeof leftValue !== "number" || typeof rightValue !== "number") {
1778
+ throw new EvaluationError(`Cannot divide ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
1779
+ }
1780
+ if (rightValue === 0) {
1781
+ throw new EvaluationError("Division by zero", position, this.source);
1782
+ }
1783
+ return leftValue / rightValue;
1784
+ case "%":
1785
+ if (typeof leftValue !== "number" || typeof rightValue !== "number") {
1786
+ throw new EvaluationError(`Cannot compute modulo of ${getTypeName(leftValue)} and ${getTypeName(rightValue)}`, position, this.source);
1787
+ }
1788
+ if (rightValue === 0) {
1789
+ throw new EvaluationError("Modulo by zero", position, this.source);
1790
+ }
1791
+ return leftValue % rightValue;
1792
+ // Comparison
1793
+ case "<":
1794
+ case "<=":
1795
+ case ">":
1796
+ case ">=":
1797
+ return this.evaluateComparison(operator, leftValue, rightValue, position);
1798
+ // Equality
1799
+ case "==":
1800
+ return this.valuesEqual(leftValue, rightValue);
1801
+ case "!=":
1802
+ return !this.valuesEqual(leftValue, rightValue);
1803
+ // Membership
1804
+ case "in":
1805
+ return this.evaluateIn(leftValue, rightValue, position);
1806
+ case "not in":
1807
+ return !this.evaluateIn(leftValue, rightValue, position);
1808
+ }
1809
+ }
1810
+ evaluateComparison(operator, left, right, position) {
1811
+ // Numbers
1812
+ if (typeof left === "number" && typeof right === "number") {
1813
+ switch (operator) {
1814
+ case "<":
1815
+ return left < right;
1816
+ case "<=":
1817
+ return left <= right;
1818
+ case ">":
1819
+ return left > right;
1820
+ case ">=":
1821
+ return left >= right;
1822
+ }
1823
+ }
1824
+ // Strings
1825
+ if (typeof left === "string" && typeof right === "string") {
1826
+ switch (operator) {
1827
+ case "<":
1828
+ return left < right;
1829
+ case "<=":
1830
+ return left <= right;
1831
+ case ">":
1832
+ return left > right;
1833
+ case ">=":
1834
+ return left >= right;
1835
+ }
1836
+ }
1837
+ throw new EvaluationError(`Cannot compare ${getTypeName(left)} and ${getTypeName(right)} with ${operator}`, position, this.source);
1838
+ }
1839
+ evaluateIn(left, right, position) {
1840
+ // String in string (substring check)
1841
+ if (typeof left === "string" && typeof right === "string") {
1842
+ return right.includes(left);
1843
+ }
1844
+ // Value in array
1845
+ if (Array.isArray(right)) {
1846
+ return right.some((item) => this.valuesEqual(left, item));
1847
+ }
1848
+ // Key in object
1849
+ if (typeof right === "object" && right !== null && !Array.isArray(right)) {
1850
+ if (typeof left !== "string") {
1851
+ throw new EvaluationError(`Cannot check if ${getTypeName(left)} is a key in object (expected string)`, position, this.source);
1852
+ }
1853
+ return left in right;
1854
+ }
1855
+ throw new EvaluationError(`Cannot check membership: ${getTypeName(left)} in ${getTypeName(right)}`, position, this.source);
1856
+ }
1857
+ evaluateTernaryOp(condition, consequent, alternate, _position) {
1858
+ const condValue = this.evaluate(condition);
1859
+ if (typeof condValue !== "boolean") {
1860
+ throw new TypeError("boolean", getTypeName(condValue), condition.position, this.source);
1861
+ }
1862
+ return condValue ? this.evaluate(consequent) : this.evaluate(alternate);
1863
+ }
1864
+ /**
1865
+ * Deep equality check for expression values.
1866
+ */
1867
+ valuesEqual(a, b) {
1868
+ // Identical primitives or same reference
1869
+ if (a === b)
1870
+ return true;
1871
+ // Type mismatch
1872
+ if (typeof a !== typeof b)
1873
+ return false;
1874
+ // null check (both must be null if one is)
1875
+ if (a === null || b === null)
1876
+ return false;
1877
+ // Arrays
1878
+ if (Array.isArray(a) && Array.isArray(b)) {
1879
+ if (a.length !== b.length)
1880
+ return false;
1881
+ for (let i = 0; i < a.length; i++) {
1882
+ if (!this.valuesEqual(a[i], b[i])) {
1883
+ return false;
1884
+ }
1885
+ }
1886
+ return true;
1887
+ }
1888
+ // Objects
1889
+ if (typeof a === "object" && typeof b === "object") {
1890
+ const aKeys = Object.keys(a);
1891
+ const bKeys = Object.keys(b);
1892
+ if (aKeys.length !== bKeys.length)
1893
+ return false;
1894
+ for (const key of aKeys) {
1895
+ if (!Object.prototype.hasOwnProperty.call(b, key))
1896
+ return false;
1897
+ const aRecord = a;
1898
+ const bRecord = b;
1899
+ if (!this.valuesEqual(aRecord[key], bRecord[key])) {
1900
+ return false;
1901
+ }
1902
+ }
1903
+ return true;
1904
+ }
1905
+ return false;
1906
+ }
1907
+ }
1908
+ /**
1909
+ * Evaluates an AST against a context and returns the result.
1910
+ *
1911
+ * @param ast - The AST to evaluate
1912
+ * @param context - The evaluation context with bindings
1913
+ * @returns The evaluation result
1914
+ */
1915
+ function evaluate(ast, context) {
1916
+ try {
1917
+ const evaluator = new Evaluator(context);
1918
+ const value = evaluator.evaluate(ast);
1919
+ return { value, success: true };
1920
+ }
1921
+ catch (error) {
1922
+ const message = error instanceof Error ? error.message : String(error);
1923
+ return { value: null, success: false, error: message };
1924
+ }
1925
+ }
1926
+ /**
1927
+ * Evaluates an AST as a boolean condition.
1928
+ *
1929
+ * @param ast - The AST to evaluate
1930
+ * @param context - The evaluation context with bindings
1931
+ * @returns true if the condition is met, false otherwise (including errors)
1932
+ */
1933
+ function evaluateAsBoolean(ast, context) {
1934
+ try {
1935
+ const evaluator = new Evaluator(context);
1936
+ const value = evaluator.evaluateAsBoolean(ast);
1937
+ return { value };
1938
+ }
1939
+ catch (error) {
1940
+ const message = error instanceof Error ? error.message : String(error);
1941
+ return { value: false, error: message };
1942
+ }
1943
+ }
1944
+
1945
+ /**
1946
+ * Authorization-specific expression built-ins.
1947
+ *
1948
+ * Null handling semantics:
1949
+ * - Scope predicate builtins (has_scope, has_any_scope, has_all_scopes)
1950
+ * return `false` when passed `null` for required args.
1951
+ * - Wrong non-null types still raise BuiltinError to surface real bugs.
1952
+ */
1953
+ /**
1954
+ * Checks if a value is null.
1955
+ */
1956
+ function isNull(value) {
1957
+ return value === null;
1958
+ }
1959
+ /**
1960
+ * Creates a function registry with auth helpers installed.
1961
+ */
1962
+ function createAuthFunctionRegistry(grantedScopes = []) {
1963
+ const scopes = grantedScopes ?? [];
1964
+ /**
1965
+ * Checks if any granted scope matches a pattern (using glob syntax).
1966
+ */
1967
+ const matchesScope = (scope) => {
1968
+ // Exact match for now; safe and deterministic.
1969
+ return scopes.includes(scope);
1970
+ };
1971
+ /**
1972
+ * has_scope(scope: string) -> bool
1973
+ *
1974
+ * Returns true if the scope is in the granted scopes.
1975
+ * Null-tolerant: returns false if scope is null.
1976
+ */
1977
+ const has_scope = (args) => {
1978
+ assertArgCount(args, 1, "has_scope");
1979
+ const scope = getArg(args, 0, "has_scope");
1980
+ // Null-tolerant: return false if scope is null
1981
+ if (!assertStringOrNull(scope, "scope", "has_scope"))
1982
+ return false;
1983
+ return matchesScope(scope);
1984
+ };
1985
+ /**
1986
+ * has_any_scope(scopes: string[]) -> bool
1987
+ *
1988
+ * Returns true if any scope in the array is in the granted scopes.
1989
+ * Null-tolerant: returns false if scopes is null.
1990
+ */
1991
+ const has_any_scope = (args) => {
1992
+ assertArgCount(args, 1, "has_any_scope");
1993
+ const values = getArg(args, 0, "has_any_scope");
1994
+ // Null-tolerant: return false if scopes is null
1995
+ if (!assertStringArrayOrNull(values, "scopes", "has_any_scope"))
1996
+ return false;
1997
+ if (values.length === 0) {
1998
+ return false;
1999
+ }
2000
+ return values.some((scope) => matchesScope(scope));
2001
+ };
2002
+ /**
2003
+ * has_all_scopes(scopes: string[]) -> bool
2004
+ *
2005
+ * Returns true if all scopes in the array are in the granted scopes.
2006
+ * Null-tolerant: returns false if scopes is null.
2007
+ */
2008
+ const has_all_scopes = (args) => {
2009
+ assertArgCount(args, 1, "has_all_scopes");
2010
+ const values = getArg(args, 0, "has_all_scopes");
2011
+ // Null-tolerant: return false if scopes is null
2012
+ if (!assertStringArrayOrNull(values, "scopes", "has_all_scopes"))
2013
+ return false;
2014
+ if (values.length === 0) {
2015
+ return true;
2016
+ }
2017
+ return values.every((scope) => matchesScope(scope));
2018
+ };
2019
+ return new Map([
2020
+ ...BUILTIN_FUNCTIONS,
2021
+ ["has_scope", has_scope],
2022
+ ["has_any_scope", has_any_scope],
2023
+ ["has_all_scopes", has_all_scopes],
2024
+ ]);
2025
+ }
2026
+ /**
2027
+ * Asserts that a non-null value is a string (for null-tolerant predicates).
2028
+ * Returns false if the value is null (indicating predicate should return false).
2029
+ * Throws BuiltinError if the value is non-null but not a string.
2030
+ */
2031
+ function assertStringOrNull(value, argName, functionName) {
2032
+ if (isNull(value)) {
2033
+ return false;
2034
+ }
2035
+ if (typeof value !== "string") {
2036
+ throw new BuiltinError(functionName, `${argName} must be a string, got ${getTypeName(value)}`);
2037
+ }
2038
+ return true;
2039
+ }
2040
+ /**
2041
+ * Asserts that a non-null value is an array of strings (for null-tolerant predicates).
2042
+ * Returns false if the value is null (indicating predicate should return false).
2043
+ * Throws BuiltinError if the value is non-null but not a string array.
2044
+ */
2045
+ function assertStringArrayOrNull(value, argName, functionName) {
2046
+ if (isNull(value)) {
2047
+ return false;
2048
+ }
2049
+ if (!Array.isArray(value)) {
2050
+ throw new BuiltinError(functionName, `${argName} must be an array of strings, got ${getTypeName(value)}`);
2051
+ }
2052
+ for (let i = 0; i < value.length; i++) {
2053
+ if (typeof value[i] !== "string") {
2054
+ throw new BuiltinError(functionName, `${argName}[${i}] must be a string, got ${getTypeName(value[i])}`);
2055
+ }
2056
+ }
2057
+ return true;
2058
+ }
2059
+ function getArg(args, index, functionName) {
2060
+ const value = args[index];
2061
+ if (value === undefined) {
2062
+ throw new BuiltinError(functionName, `missing argument at index ${index}`);
2063
+ }
2064
+ return value;
2065
+ }
2066
+ function assertArgCount(args, expected, functionName) {
2067
+ if (args.length !== expected) {
2068
+ throw new BuiltinError(functionName, `expected ${expected} argument(s), got ${args.length}`);
2069
+ }
2070
+ }
2071
+
21
2072
  /**
22
- * The package version, injected at build time.
23
- * @internal
2073
+ * Expression-based authorization policy implementation.
2074
+ *
2075
+ * Extends the basic policy with support for `when` expression evaluation.
2076
+ * This is part of the BSL-licensed Advanced Security package.
2077
+ */
2078
+ /**
2079
+ * Simple console logger implementation.
2080
+ */
2081
+ const defaultLogger = {
2082
+ debug: () => { },
2083
+ warning: (event, data) => {
2084
+ console.warn(`[naylence.security.auth.policy.expression] ${event}`, data);
2085
+ },
2086
+ };
2087
+ /**
2088
+ * Extracts the target address string from the envelope.
2089
+ */
2090
+ function extractAddress(envelope) {
2091
+ const to = envelope.to;
2092
+ if (!to) {
2093
+ return undefined;
2094
+ }
2095
+ if (typeof to === "string") {
2096
+ return to;
2097
+ }
2098
+ if (typeof to === "object" && "toString" in to) {
2099
+ return to.toString();
2100
+ }
2101
+ return undefined;
2102
+ }
2103
+ /**
2104
+ * Extracts granted scopes from the authorization context.
2105
+ */
2106
+ function extractGrantedScopes(context) {
2107
+ const authContext = context?.security?.authorization;
2108
+ if (!authContext) {
2109
+ return [];
2110
+ }
2111
+ if (Array.isArray(authContext.grantedScopes)) {
2112
+ return authContext.grantedScopes;
2113
+ }
2114
+ const claims = authContext.claims;
2115
+ if (claims) {
2116
+ const scopeClaim = claims.scope ?? claims.scopes ?? claims.scp;
2117
+ if (typeof scopeClaim === "string") {
2118
+ return scopeClaim.split(/\s+/).filter((s) => s.length > 0);
2119
+ }
2120
+ if (Array.isArray(scopeClaim)) {
2121
+ return scopeClaim.filter((s) => typeof s === "string");
2122
+ }
2123
+ }
2124
+ return [];
2125
+ }
2126
+ /**
2127
+ * Extracts claims from the authorization context.
2128
+ */
2129
+ function extractClaims(context) {
2130
+ const authContext = context?.security?.authorization;
2131
+ if (!authContext?.claims) {
2132
+ return {};
2133
+ }
2134
+ return authContext.claims;
2135
+ }
2136
+ /**
2137
+ * Creates a safe envelope subset for expression bindings.
2138
+ */
2139
+ function createEnvelopeBindings(envelope) {
2140
+ const frame = envelope.frame;
2141
+ const envelopeRecord = envelope;
2142
+ return {
2143
+ id: envelope.id ?? null,
2144
+ traceId: envelopeRecord.traceId ?? null,
2145
+ corrId: envelopeRecord.corrId ?? null,
2146
+ flowId: envelopeRecord.flowId ?? null,
2147
+ to: extractAddress(envelope) ?? null,
2148
+ frame: frame
2149
+ ? { type: frame.type ?? null }
2150
+ : { type: null },
2151
+ };
2152
+ }
2153
+ /**
2154
+ * Creates delivery context bindings for expression evaluation.
2155
+ */
2156
+ function createDeliveryBindings(context, action) {
2157
+ return {
2158
+ origin_type: context?.originType ?? null,
2159
+ routing_action: action,
2160
+ };
2161
+ }
2162
+ /**
2163
+ * Expression-based authorization policy that evaluates rules with `when` expressions.
2164
+ *
2165
+ * Features:
2166
+ * - All features of BasicAuthorizationPolicy
2167
+ * - Expression evaluation for `when` clauses
2168
+ * - Deterministic, side-effect-free evaluation
2169
+ * - Missing fields evaluate to null (not error)
2170
+ * - Parse/evaluation errors cause rule to not match
2171
+ */
2172
+ class AdvancedAuthorizationPolicy {
2173
+ constructor(options) {
2174
+ const { policyDefinition, warnOnUnknownFields = true, expressionLimits = DEFAULT_EXPRESSION_LIMITS, logger = defaultLogger, } = options;
2175
+ this.expressionLimits = expressionLimits;
2176
+ this.logger = logger;
2177
+ // Validate and extract default effect
2178
+ this.defaultEffect = this.validateDefaultEffect(policyDefinition.default_effect);
2179
+ // Warn about unknown policy fields
2180
+ if (warnOnUnknownFields) {
2181
+ this.warnUnknownPolicyFields(policyDefinition);
2182
+ }
2183
+ // Compile rules for efficient evaluation
2184
+ this.compiledRules = this.compileRules(policyDefinition.rules, warnOnUnknownFields);
2185
+ this.logger.debug("expression_policy_compiled", {
2186
+ defaultEffect: this.defaultEffect,
2187
+ ruleCount: this.compiledRules.length,
2188
+ rulesWithWhen: this.compiledRules.filter((r) => r.whenAst).length,
2189
+ });
2190
+ }
2191
+ /**
2192
+ * Evaluates the policy against a request.
2193
+ */
2194
+ async evaluateRequest(_node, envelope, context, action) {
2195
+ const resolvedAction = action ?? "*";
2196
+ const resolvedActionNormalized = this.normalizeActionToken(resolvedAction) ?? resolvedAction;
2197
+ const address = extractAddress(envelope);
2198
+ const grantedScopes = extractGrantedScopes(context);
2199
+ const rawFrameType = envelope.frame
2200
+ ?.type;
2201
+ const frameTypeNormalized = typeof rawFrameType === "string" && rawFrameType.trim().length > 0
2202
+ ? rawFrameType.trim().toLowerCase()
2203
+ : "";
2204
+ const rawOriginType = context?.originType;
2205
+ const originTypeNormalized = typeof rawOriginType === "string"
2206
+ ? this.normalizeOriginTypeToken(rawOriginType) ?? undefined
2207
+ : undefined;
2208
+ // Prepare expression bindings (lazy)
2209
+ let expressionBindings = null;
2210
+ let functionRegistry = null;
2211
+ const evaluationTrace = [];
2212
+ // Evaluate rules in order (first match wins)
2213
+ for (const rule of this.compiledRules) {
2214
+ const step = {
2215
+ ruleId: rule.id,
2216
+ result: false,
2217
+ };
2218
+ // Check frame type match
2219
+ if (rule.frameTypes) {
2220
+ if (!frameTypeNormalized) {
2221
+ step.expression = "frame_type: missing";
2222
+ step.result = false;
2223
+ evaluationTrace.push(step);
2224
+ continue;
2225
+ }
2226
+ if (!rule.frameTypes.has(frameTypeNormalized)) {
2227
+ step.expression = `frame_type: ${rawFrameType ?? "unknown"} not in rule set`;
2228
+ step.result = false;
2229
+ evaluationTrace.push(step);
2230
+ continue;
2231
+ }
2232
+ }
2233
+ // Check origin type match
2234
+ if (rule.originTypes) {
2235
+ if (originTypeNormalized === undefined) {
2236
+ step.expression = "origin_type: missing (rule requires origin)";
2237
+ step.result = false;
2238
+ evaluationTrace.push(step);
2239
+ continue;
2240
+ }
2241
+ if (!rule.originTypes.has(originTypeNormalized)) {
2242
+ step.expression = `origin_type: ${rawOriginType ?? "unknown"} not in [${Array.from(rule.originTypes).join(", ")}]`;
2243
+ step.result = false;
2244
+ evaluationTrace.push(step);
2245
+ continue;
2246
+ }
2247
+ }
2248
+ // Check action match
2249
+ if (!rule.actions.has("*") && !rule.actions.has(resolvedActionNormalized)) {
2250
+ step.expression = `action: ${resolvedActionNormalized} not in [${Array.from(rule.actions).join(", ")}]`;
2251
+ step.result = false;
2252
+ evaluationTrace.push(step);
2253
+ continue;
2254
+ }
2255
+ // Check address match
2256
+ if (rule.addressPatterns) {
2257
+ if (!address) {
2258
+ step.expression = "address: pattern requires address, but none provided";
2259
+ step.result = false;
2260
+ evaluationTrace.push(step);
2261
+ continue;
2262
+ }
2263
+ const matched = rule.addressPatterns.some((p) => p.match(address));
2264
+ if (!matched) {
2265
+ const patterns = rule.addressPatterns.map((p) => p.source).join(", ");
2266
+ step.expression = `address: none of [${patterns}] matched ${address}`;
2267
+ step.result = false;
2268
+ evaluationTrace.push(step);
2269
+ continue;
2270
+ }
2271
+ }
2272
+ // Check scope match
2273
+ if (rule.scopeMatcher) {
2274
+ if (!rule.scopeMatcher(grantedScopes)) {
2275
+ step.expression = "scope: requirement not satisfied";
2276
+ step.boundValues = { grantedScopes: [...grantedScopes] };
2277
+ step.result = false;
2278
+ evaluationTrace.push(step);
2279
+ continue;
2280
+ }
2281
+ }
2282
+ // Check when expression
2283
+ if (rule.whenParseError) {
2284
+ // Parse error - rule does not match
2285
+ step.expression = `when: parse error - ${rule.whenParseError}`;
2286
+ step.result = false;
2287
+ evaluationTrace.push(step);
2288
+ continue;
2289
+ }
2290
+ if (rule.whenAst) {
2291
+ // Lazy initialization of expression bindings
2292
+ if (!expressionBindings) {
2293
+ expressionBindings = {
2294
+ claims: extractClaims(context),
2295
+ envelope: createEnvelopeBindings(envelope),
2296
+ delivery: createDeliveryBindings(context, resolvedAction),
2297
+ time: {
2298
+ now_ms: Date.now(),
2299
+ now_iso: new Date().toISOString(),
2300
+ },
2301
+ };
2302
+ }
2303
+ const functions = functionRegistry ?? createAuthFunctionRegistry(grantedScopes);
2304
+ functionRegistry = functions;
2305
+ const evalContext = {
2306
+ bindings: expressionBindings,
2307
+ limits: this.expressionLimits,
2308
+ source: rule.whenSource,
2309
+ functions,
2310
+ };
2311
+ const whenResult = evaluateAsBoolean(rule.whenAst, evalContext);
2312
+ if (whenResult.error) {
2313
+ // Evaluation error - rule does not match
2314
+ step.expression = `when: evaluation error - ${whenResult.error}`;
2315
+ step.result = false;
2316
+ evaluationTrace.push(step);
2317
+ continue;
2318
+ }
2319
+ if (!whenResult.value) {
2320
+ // Expression evaluated to false
2321
+ step.expression = `when: expression evaluated to false`;
2322
+ step.boundValues = {
2323
+ whenExpression: rule.whenSource,
2324
+ };
2325
+ step.result = false;
2326
+ evaluationTrace.push(step);
2327
+ continue;
2328
+ }
2329
+ // Expression evaluated to true
2330
+ step.expression = `when: expression evaluated to true`;
2331
+ }
2332
+ // Rule matched
2333
+ step.result = true;
2334
+ if (!step.expression) {
2335
+ step.expression = "all conditions matched";
2336
+ }
2337
+ step.boundValues = {
2338
+ action: resolvedAction,
2339
+ address,
2340
+ grantedScopes: [...grantedScopes],
2341
+ ...(rule.whenSource ? { whenExpression: rule.whenSource } : {}),
2342
+ };
2343
+ evaluationTrace.push(step);
2344
+ this.logger.debug("rule_matched", {
2345
+ ruleId: rule.id,
2346
+ effect: rule.effect,
2347
+ action: resolvedAction,
2348
+ address,
2349
+ hadWhenClause: Boolean(rule.whenAst),
2350
+ });
2351
+ return {
2352
+ effect: rule.effect,
2353
+ reason: rule.description ?? `Matched rule: ${rule.id}`,
2354
+ matchedRule: rule.id,
2355
+ evaluationTrace,
2356
+ };
2357
+ }
2358
+ // No rule matched, apply default effect
2359
+ this.logger.debug("no_rule_matched", {
2360
+ defaultEffect: this.defaultEffect,
2361
+ action: resolvedAction,
2362
+ address,
2363
+ });
2364
+ return {
2365
+ effect: this.defaultEffect,
2366
+ reason: `No rule matched, applying default effect: ${this.defaultEffect}`,
2367
+ evaluationTrace,
2368
+ };
2369
+ }
2370
+ validateDefaultEffect(effect) {
2371
+ if (effect === undefined || effect === null) {
2372
+ return "deny";
2373
+ }
2374
+ if (effect !== "allow" && effect !== "deny") {
2375
+ throw new Error(`Invalid default_effect: "${String(effect)}". Must be "allow" or "deny"`);
2376
+ }
2377
+ return effect;
2378
+ }
2379
+ warnUnknownPolicyFields(definition) {
2380
+ for (const key of Object.keys(definition)) {
2381
+ if (!runtime.KNOWN_POLICY_FIELDS.has(key)) {
2382
+ this.logger.warning("unknown_policy_field", { field: key });
2383
+ }
2384
+ }
2385
+ }
2386
+ compileRules(rules, warnOnUnknown) {
2387
+ return rules.map((rule, index) => this.compileRule(rule, index, warnOnUnknown));
2388
+ }
2389
+ compileRule(rule, index, warnOnUnknown) {
2390
+ const id = rule.id ?? `rule_${index}`;
2391
+ // Validate effect
2392
+ if (!runtime.VALID_EFFECTS.includes(rule.effect)) {
2393
+ throw new Error(`Invalid effect in rule "${id}": "${String(rule.effect)}". Must be "allow" or "deny"`);
2394
+ }
2395
+ // Compile action(s)
2396
+ const actions = this.compileActions(rule.action, id);
2397
+ // Compile address patterns
2398
+ const addressPatterns = this.compileAddress(rule.address, id);
2399
+ // Compile frame type gating
2400
+ const frameTypes = this.compileFrameTypes(rule.frame_type, id);
2401
+ // Compile origin type gating
2402
+ const originTypes = this.compileOriginTypes(rule.origin_type, id);
2403
+ // Compile scope matcher
2404
+ let scopeMatcher;
2405
+ if (rule.scope !== undefined) {
2406
+ try {
2407
+ const compiled = runtime.compileGlobOnlyScopeRequirement(rule.scope, id);
2408
+ scopeMatcher = (scopes) => compiled.evaluate(scopes);
2409
+ }
2410
+ catch (error) {
2411
+ throw new Error(`Invalid scope requirement in rule "${id}": ${error instanceof Error ? error.message : String(error)}`);
2412
+ }
2413
+ }
2414
+ // Compile when expression
2415
+ let whenAst;
2416
+ let whenSource;
2417
+ let whenParseError;
2418
+ if (typeof rule.when === "string" && rule.when.trim().length > 0) {
2419
+ whenSource = rule.when.trim();
2420
+ try {
2421
+ whenAst = parse(whenSource, this.expressionLimits);
2422
+ }
2423
+ catch (error) {
2424
+ // Parse error - store for evaluation time
2425
+ whenParseError =
2426
+ error instanceof Error ? error.message : String(error);
2427
+ this.logger.warning("when_parse_error", {
2428
+ ruleId: id,
2429
+ expression: whenSource,
2430
+ error: whenParseError,
2431
+ });
2432
+ }
2433
+ }
2434
+ // Warn about unknown fields
2435
+ if (warnOnUnknown) {
2436
+ for (const key of Object.keys(rule)) {
2437
+ if (!runtime.KNOWN_RULE_FIELDS.has(key)) {
2438
+ this.logger.warning("unknown_rule_field", { ruleId: id, field: key });
2439
+ }
2440
+ }
2441
+ }
2442
+ return {
2443
+ id,
2444
+ description: rule.description,
2445
+ effect: rule.effect,
2446
+ actions,
2447
+ frameTypes,
2448
+ originTypes,
2449
+ addressPatterns,
2450
+ scopeMatcher,
2451
+ whenAst,
2452
+ whenSource,
2453
+ whenParseError,
2454
+ };
2455
+ }
2456
+ compileActions(action, ruleId) {
2457
+ if (action === undefined) {
2458
+ return new Set(["*"]);
2459
+ }
2460
+ if (typeof action === "string") {
2461
+ const normalized = this.normalizeActionToken(action);
2462
+ if (!normalized) {
2463
+ throw new Error(`Invalid action in rule "${ruleId}": "${action}". Must be one of: ${runtime.VALID_ACTIONS.join(", ")}`);
2464
+ }
2465
+ return new Set([normalized]);
2466
+ }
2467
+ if (!Array.isArray(action)) {
2468
+ throw new Error(`Invalid action in rule "${ruleId}": must be a string or array of strings`);
2469
+ }
2470
+ if (action.length === 0) {
2471
+ throw new Error(`Invalid action in rule "${ruleId}": array must not be empty`);
2472
+ }
2473
+ const actions = new Set();
2474
+ for (const a of action) {
2475
+ if (typeof a !== "string") {
2476
+ throw new Error(`Invalid action in rule "${ruleId}": all values must be strings`);
2477
+ }
2478
+ const normalized = this.normalizeActionToken(a);
2479
+ if (!normalized) {
2480
+ throw new Error(`Invalid action in rule "${ruleId}": "${a}". Must be one of: ${runtime.VALID_ACTIONS.join(", ")}`);
2481
+ }
2482
+ actions.add(normalized);
2483
+ }
2484
+ return actions;
2485
+ }
2486
+ compileAddress(address, ruleId) {
2487
+ if (address === undefined) {
2488
+ return undefined;
2489
+ }
2490
+ const context = `address in rule "${ruleId}"`;
2491
+ if (typeof address === "string") {
2492
+ const trimmed = address.trim();
2493
+ if (!trimmed) {
2494
+ throw new Error(`Invalid address in rule "${ruleId}": value must not be empty`);
2495
+ }
2496
+ try {
2497
+ return [runtime.compileGlobPattern(trimmed, context)];
2498
+ }
2499
+ catch (error) {
2500
+ throw new Error(`Invalid address in rule "${ruleId}": ${error instanceof Error ? error.message : String(error)}`);
2501
+ }
2502
+ }
2503
+ if (!Array.isArray(address)) {
2504
+ throw new Error(`Invalid address in rule "${ruleId}": must be a string or array of strings`);
2505
+ }
2506
+ if (address.length === 0) {
2507
+ throw new Error(`Invalid address in rule "${ruleId}": array must not be empty`);
2508
+ }
2509
+ const patterns = [];
2510
+ for (const addr of address) {
2511
+ if (typeof addr !== "string") {
2512
+ throw new Error(`Invalid address in rule "${ruleId}": all values must be strings`);
2513
+ }
2514
+ const trimmed = addr.trim();
2515
+ if (!trimmed) {
2516
+ throw new Error(`Invalid address in rule "${ruleId}": values must not be empty`);
2517
+ }
2518
+ try {
2519
+ patterns.push(runtime.compileGlobPattern(trimmed, context));
2520
+ }
2521
+ catch (error) {
2522
+ throw new Error(`Invalid address in rule "${ruleId}": ${error instanceof Error ? error.message : String(error)}`);
2523
+ }
2524
+ }
2525
+ return patterns;
2526
+ }
2527
+ compileFrameTypes(frameType, ruleId) {
2528
+ if (frameType === undefined) {
2529
+ return undefined;
2530
+ }
2531
+ if (typeof frameType === "string") {
2532
+ const normalized = frameType.trim().toLowerCase();
2533
+ if (!normalized) {
2534
+ throw new Error(`Invalid frame_type in rule "${ruleId}": value must not be empty`);
2535
+ }
2536
+ return new Set([normalized]);
2537
+ }
2538
+ if (!Array.isArray(frameType)) {
2539
+ throw new Error(`Invalid frame_type in rule "${ruleId}": must be a string or array of strings`);
2540
+ }
2541
+ if (frameType.length === 0) {
2542
+ throw new Error(`Invalid frame_type in rule "${ruleId}": array must not be empty`);
2543
+ }
2544
+ const frameTypes = new Set();
2545
+ for (const ft of frameType) {
2546
+ if (typeof ft !== "string") {
2547
+ throw new Error(`Invalid frame_type in rule "${ruleId}": all values must be strings`);
2548
+ }
2549
+ const normalized = ft.trim().toLowerCase();
2550
+ if (!normalized) {
2551
+ throw new Error(`Invalid frame_type in rule "${ruleId}": values must not be empty`);
2552
+ }
2553
+ frameTypes.add(normalized);
2554
+ }
2555
+ return frameTypes;
2556
+ }
2557
+ compileOriginTypes(originType, ruleId) {
2558
+ if (originType === undefined) {
2559
+ return undefined;
2560
+ }
2561
+ if (typeof originType === "string") {
2562
+ const trimmed = originType.trim();
2563
+ if (!trimmed) {
2564
+ throw new Error(`Invalid origin_type in rule "${ruleId}": value must not be empty`);
2565
+ }
2566
+ const normalized = this.normalizeOriginTypeToken(trimmed);
2567
+ if (!normalized) {
2568
+ throw new Error(`Invalid origin_type in rule "${ruleId}": "${originType}". Must be one of: ${runtime.VALID_ORIGIN_TYPES.join(", ")}`);
2569
+ }
2570
+ return new Set([normalized]);
2571
+ }
2572
+ if (!Array.isArray(originType)) {
2573
+ throw new Error(`Invalid origin_type in rule "${ruleId}": must be a string or array of strings`);
2574
+ }
2575
+ if (originType.length === 0) {
2576
+ throw new Error(`Invalid origin_type in rule "${ruleId}": array must not be empty`);
2577
+ }
2578
+ const originTypes = new Set();
2579
+ for (const ot of originType) {
2580
+ if (typeof ot !== "string") {
2581
+ throw new Error(`Invalid origin_type in rule "${ruleId}": all values must be strings`);
2582
+ }
2583
+ const trimmed = ot.trim();
2584
+ if (!trimmed) {
2585
+ throw new Error(`Invalid origin_type in rule "${ruleId}": values must not be empty`);
2586
+ }
2587
+ const normalized = this.normalizeOriginTypeToken(trimmed);
2588
+ if (!normalized) {
2589
+ throw new Error(`Invalid origin_type in rule "${ruleId}": "${ot}". Must be one of: ${runtime.VALID_ORIGIN_TYPES.join(", ")}`);
2590
+ }
2591
+ originTypes.add(normalized);
2592
+ }
2593
+ return originTypes;
2594
+ }
2595
+ normalizeActionToken(value) {
2596
+ const trimmed = value.trim();
2597
+ if (!trimmed) {
2598
+ return null;
2599
+ }
2600
+ if (trimmed === "*") {
2601
+ return "*";
2602
+ }
2603
+ const normalized = trimmed.replace(/[\s_-]+/g, "").toLowerCase();
2604
+ const map = {
2605
+ connect: "Connect",
2606
+ forwardupstream: "ForwardUpstream",
2607
+ forwarddownstream: "ForwardDownstream",
2608
+ forwardpeer: "ForwardPeer",
2609
+ deliverlocal: "DeliverLocal",
2610
+ };
2611
+ return map[normalized] ?? null;
2612
+ }
2613
+ normalizeOriginTypeToken(value) {
2614
+ const trimmed = value.trim();
2615
+ if (!trimmed) {
2616
+ return null;
2617
+ }
2618
+ const normalized = trimmed.replace(/[\s_-]+/g, "").toLowerCase();
2619
+ const map = {
2620
+ downstream: "downstream",
2621
+ upstream: "upstream",
2622
+ peer: "peer",
2623
+ local: "local",
2624
+ };
2625
+ return map[normalized] ?? null;
2626
+ }
2627
+ }
2628
+
2629
+ var advancedAuthorizationPolicy = /*#__PURE__*/Object.freeze({
2630
+ __proto__: null,
2631
+ AdvancedAuthorizationPolicy: AdvancedAuthorizationPolicy
2632
+ });
2633
+
2634
+ /**
2635
+ * Factory for creating AdvancedAuthorizationPolicy instances.
2636
+ */
2637
+ let modulePromise = null;
2638
+ function getModule() {
2639
+ if (!modulePromise) {
2640
+ modulePromise = Promise.resolve().then(function () { return advancedAuthorizationPolicy; });
2641
+ }
2642
+ return modulePromise;
2643
+ }
2644
+ function normalizeConfig$5(config) {
2645
+ if (!config) {
2646
+ throw new Error("AdvancedAuthorizationPolicyFactory requires a configuration with a policyDefinition");
2647
+ }
2648
+ const candidate = config;
2649
+ // Support both camelCase and snake_case for policyDefinition
2650
+ const policyDefinition = (candidate.policyDefinition ??
2651
+ candidate.policy_definition);
2652
+ if (!policyDefinition || typeof policyDefinition !== "object") {
2653
+ throw new Error("AdvancedAuthorizationPolicyConfig requires a policyDefinition object");
2654
+ }
2655
+ // Support both camelCase and snake_case for warnOnUnknownFields
2656
+ const warnOnUnknownFields = candidate.warnOnUnknownFields ?? candidate.warn_on_unknown_fields;
2657
+ if (warnOnUnknownFields !== undefined &&
2658
+ typeof warnOnUnknownFields !== "boolean") {
2659
+ throw new Error("warnOnUnknownFields must be a boolean");
2660
+ }
2661
+ // Support both camelCase and snake_case for expressionLimits
2662
+ const expressionLimits = (candidate.expressionLimits ??
2663
+ candidate.expression_limits);
2664
+ return {
2665
+ policyDefinition,
2666
+ warnOnUnknownFields: warnOnUnknownFields ?? true,
2667
+ expressionLimits,
2668
+ };
2669
+ }
2670
+ /**
2671
+ * Factory metadata for registration.
2672
+ */
2673
+ const FACTORY_META$e = {
2674
+ base: runtime.AUTHORIZATION_POLICY_FACTORY_BASE_TYPE,
2675
+ key: "AdvancedAuthorizationPolicy",
2676
+ };
2677
+ /**
2678
+ * Factory for creating AdvancedAuthorizationPolicy instances.
24
2679
  */
25
- const VERSION = '0.3.15';
2680
+ class AdvancedAuthorizationPolicyFactory extends runtime.AuthorizationPolicyFactory {
2681
+ constructor() {
2682
+ super(...arguments);
2683
+ this.type = "AdvancedAuthorizationPolicy";
2684
+ }
2685
+ /**
2686
+ * Creates an AdvancedAuthorizationPolicy from the given configuration.
2687
+ *
2688
+ * @param config - Configuration with policyDefinition
2689
+ * @returns The created authorization policy
2690
+ */
2691
+ async create(config) {
2692
+ const normalized = normalizeConfig$5(config);
2693
+ const { AdvancedAuthorizationPolicy } = await getModule();
2694
+ return new AdvancedAuthorizationPolicy({
2695
+ policyDefinition: normalized.policyDefinition,
2696
+ warnOnUnknownFields: normalized.warnOnUnknownFields,
2697
+ expressionLimits: normalized.expressionLimits,
2698
+ });
2699
+ }
2700
+ }
2701
+
2702
+ var advancedAuthorizationPolicyFactory = /*#__PURE__*/Object.freeze({
2703
+ __proto__: null,
2704
+ AdvancedAuthorizationPolicyFactory: AdvancedAuthorizationPolicyFactory,
2705
+ FACTORY_META: FACTORY_META$e,
2706
+ default: AdvancedAuthorizationPolicyFactory
2707
+ });
26
2708
 
27
2709
  const logger$h = runtime.getLogger("naylence.fame.security.cert.util");
28
2710
  const CACHE_LIMIT = 512;
@@ -6071,6 +8753,7 @@ var advancedWelcomeServiceFactory = /*#__PURE__*/Object.freeze({
6071
8753
  * Provides the list of advanced security factory modules for registration.
6072
8754
  */
6073
8755
  const MODULES = [
8756
+ "./security/auth/policy/advanced-authorization-policy-factory.js",
6074
8757
  "./security/cert/default-ca-service-factory.js",
6075
8758
  "./security/cert/default-certificate-manager-factory.js",
6076
8759
  "./security/cert/trust-store/browser-trust-store-provider-factory.js",
@@ -6087,6 +8770,7 @@ const MODULES = [
6087
8770
  "./welcome/advanced-welcome-service-factory.js"
6088
8771
  ];
6089
8772
  const MODULE_LOADERS = {
8773
+ "./security/auth/policy/advanced-authorization-policy-factory.js": () => Promise.resolve().then(function () { return advancedAuthorizationPolicyFactory; }),
6090
8774
  "./security/cert/default-ca-service-factory.js": () => Promise.resolve().then(function () { return defaultCaServiceFactory; }),
6091
8775
  "./security/cert/default-certificate-manager-factory.js": () => Promise.resolve().then(function () { return defaultCertificateManagerFactory; }),
6092
8776
  "./security/cert/trust-store/browser-trust-store-provider-factory.js": () => Promise.resolve().then(function () { return browserTrustStoreProviderFactory; }),
@@ -6103,6 +8787,75 @@ const MODULE_LOADERS = {
6103
8787
  "./welcome/advanced-welcome-service-factory.js": () => Promise.resolve().then(function () { return advancedWelcomeServiceFactory; }),
6104
8788
  };
6105
8789
 
8790
+ /**
8791
+ * Strict Overlay Security Profile
8792
+ *
8793
+ * Provides the strict-overlay security profile for advanced security scenarios.
8794
+ * This profile requires X.509 certificate-based signing and supports both
8795
+ * channel and sealed encryption modes.
8796
+ */
8797
+ const ENV_VAR_DEFAULT_ENCRYPTION_LEVEL = "FAME_DEFAULT_ENCRYPTION_LEVEL";
8798
+ const ENV_VAR_AUTHORIZATION_PROFILE = "FAME_AUTHORIZATION_PROFILE";
8799
+ const PROFILE_NAME_STRICT_OVERLAY = "strict-overlay";
8800
+ const STRICT_OVERLAY_PROFILE = {
8801
+ type: "DefaultSecurityManager",
8802
+ security_policy: {
8803
+ type: "DefaultSecurityPolicy",
8804
+ signing: {
8805
+ signing_material: "x509-chain",
8806
+ require_cert_sid_match: true,
8807
+ inbound: {
8808
+ signature_policy: "required",
8809
+ unsigned_violation_action: "nack",
8810
+ invalid_signature_action: "nack",
8811
+ },
8812
+ response: {
8813
+ mirror_request_signing: true,
8814
+ always_sign_responses: false,
8815
+ sign_error_responses: true,
8816
+ },
8817
+ outbound: {
8818
+ default_signing: true,
8819
+ sign_sensitive_operations: true,
8820
+ sign_if_recipient_expects: true,
8821
+ },
8822
+ },
8823
+ encryption: {
8824
+ inbound: {
8825
+ allow_plaintext: true,
8826
+ allow_channel: true,
8827
+ allow_sealed: true,
8828
+ plaintext_violation_action: "nack",
8829
+ channel_violation_action: "nack",
8830
+ sealed_violation_action: "nack",
8831
+ },
8832
+ response: {
8833
+ mirror_request_level: true,
8834
+ minimum_response_level: "plaintext",
8835
+ escalate_sealed_responses: false,
8836
+ },
8837
+ outbound: {
8838
+ default_level: factory.Expressions.env(ENV_VAR_DEFAULT_ENCRYPTION_LEVEL, "channel"),
8839
+ escalate_if_peer_supports: false,
8840
+ prefer_sealed_for_sensitive: false,
8841
+ },
8842
+ },
8843
+ },
8844
+ authorizer: {
8845
+ type: "AuthorizationProfile",
8846
+ profile: factory.Expressions.env(ENV_VAR_AUTHORIZATION_PROFILE, "jwt"),
8847
+ },
8848
+ };
8849
+ // Register the strict-overlay profile
8850
+ runtime.registerProfile(runtime.SECURITY_MANAGER_FACTORY_BASE_TYPE, PROFILE_NAME_STRICT_OVERLAY, STRICT_OVERLAY_PROFILE, { source: "advanced-security:strict-overlay-security-profile", allowOverride: true });
8851
+
8852
+ var strictOverlaySecurityProfile = /*#__PURE__*/Object.freeze({
8853
+ __proto__: null,
8854
+ ENV_VAR_AUTHORIZATION_PROFILE: ENV_VAR_AUTHORIZATION_PROFILE,
8855
+ ENV_VAR_DEFAULT_ENCRYPTION_LEVEL: ENV_VAR_DEFAULT_ENCRYPTION_LEVEL,
8856
+ PROFILE_NAME_STRICT_OVERLAY: PROFILE_NAME_STRICT_OVERLAY
8857
+ });
8858
+
6106
8859
  const SECURITY_PREFIX = "./security/";
6107
8860
  const SECURITY_MODULES = MODULES.filter((spec) => spec.startsWith(SECURITY_PREFIX));
6108
8861
  const EXTRA_MODULES = MODULES.filter((spec) => !spec.startsWith(SECURITY_PREFIX));
@@ -9839,6 +12592,8 @@ const advancedSecurityPlugin = {
9839
12592
  try {
9840
12593
  // console.log('[naylence:advanced-security] registering advanced security factories...');
9841
12594
  await registerAdvancedSecurityPluginFactories();
12595
+ // Import modules with side-effect registrations (not in manifest)
12596
+ await Promise.resolve().then(function () { return strictOverlaySecurityProfile; });
9842
12597
  // console.log('[naylence:advanced-security] advanced security factories registered');
9843
12598
  initialized = true;
9844
12599
  }
@@ -9858,6 +12613,7 @@ var plugin = /*#__PURE__*/Object.freeze({
9858
12613
  registerAdvancedSecurityPluginFactories: registerAdvancedSecurityPluginFactories
9859
12614
  });
9860
12615
 
12616
+ exports.ADVANCED_AUTHORIZATION_POLICY_FACTORY_META = FACTORY_META$e;
9861
12617
  exports.ADVANCED_EDDSA_ENVELOPE_SIGNER_FACTORY_META = FACTORY_META$9;
9862
12618
  exports.ADVANCED_EDDSA_ENVELOPE_VERIFIER_FACTORY_META = FACTORY_META$8;
9863
12619
  exports.ADVANCED_WELCOME_FACTORY_META = FACTORY_META$4;
@@ -9868,47 +12624,80 @@ exports.AFTReplicaStickinessManager = AFTReplicaStickinessManager;
9868
12624
  exports.AFTReplicaStickinessManagerFactory = AFTReplicaStickinessManagerFactory;
9869
12625
  exports.AFT_LOAD_BALANCER_FACTORY_META = FACTORY_META$6;
9870
12626
  exports.AFT_REPLICA_FACTORY_META = FACTORY_META$5;
12627
+ exports.AdvancedAuthorizationPolicy = AdvancedAuthorizationPolicy;
12628
+ exports.AdvancedAuthorizationPolicyFactory = AdvancedAuthorizationPolicyFactory;
9871
12629
  exports.AdvancedEdDSAEnvelopeSignerFactory = AdvancedEdDSAEnvelopeSignerFactory;
9872
12630
  exports.AdvancedEdDSAEnvelopeVerifierFactory = AdvancedEdDSAEnvelopeVerifierFactory;
9873
12631
  exports.AdvancedWelcomeService = AdvancedWelcomeService;
9874
12632
  exports.AdvancedWelcomeServiceFactory = AdvancedWelcomeServiceFactory;
12633
+ exports.BUILTIN_FUNCTIONS = BUILTIN_FUNCTIONS;
12634
+ exports.BuiltinError = BuiltinError;
9875
12635
  exports.CAServiceClient = CAServiceClient;
9876
12636
  exports.CompositeEncryptionManager = CompositeEncryptionManager;
9877
12637
  exports.CompositeEncryptionManagerFactory = CompositeEncryptionManagerFactory;
12638
+ exports.DEFAULT_EXPRESSION_LIMITS = DEFAULT_EXPRESSION_LIMITS;
9878
12639
  exports.DEFAULT_SECURE_CHANNEL_MANAGER_FACTORY_META = FACTORY_META$b;
9879
12640
  exports.DEFAULT_STICKINESS_SECURITY_LEVEL = DEFAULT_STICKINESS_SECURITY_LEVEL;
9880
12641
  exports.DefaultSecureChannelManager = DefaultSecureChannelManager;
9881
12642
  exports.DefaultSecureChannelManagerFactory = DefaultSecureChannelManagerFactory;
9882
12643
  exports.ENV_VAR_FAME_CA_SERVICE_URL = ENV_VAR_FAME_CA_SERVICE_URL;
9883
12644
  exports.EdDSAEnvelopeVerifier = EdDSAEnvelopeVerifier;
12645
+ exports.EvaluationError = EvaluationError;
12646
+ exports.Evaluator = Evaluator;
12647
+ exports.ExpressionError = ExpressionError;
9884
12648
  exports.GRANT_PURPOSE_CA_SIGN = GRANT_PURPOSE_CA_SIGN;
12649
+ exports.LimitExceededError = LimitExceededError;
9885
12650
  exports.NoAFTSigner = NoAFTSigner;
12651
+ exports.ParseError = ParseError;
12652
+ exports.Parser = Parser;
9886
12653
  exports.SidOnlyAFTVerifier = SidOnlyAFTVerifier;
9887
12654
  exports.SignedAFTSigner = SignedAFTSigner;
9888
12655
  exports.SignedOptionalAFTVerifier = SignedOptionalAFTVerifier;
9889
12656
  exports.StrictAFTVerifier = StrictAFTVerifier;
12657
+ exports.Tokenizer = Tokenizer;
12658
+ exports.TokenizerError = TokenizerError;
12659
+ exports.TypeError = TypeError;
9890
12660
  exports.UnsignedAFTSigner = UnsignedAFTSigner;
9891
12661
  exports.VERSION = VERSION;
9892
12662
  exports.X5CKeyManager = X5CKeyManager;
9893
12663
  exports.X5CKeyManagerFactory = X5CKeyManagerFactory;
9894
12664
  exports.X5C_KEY_MANAGER_FACTORY_META = FACTORY_META$7;
9895
12665
  exports.__advancedSecurityPluginLoader = __advancedSecurityPluginLoader;
12666
+ exports.astToString = astToString;
9896
12667
  exports.base64UrlDecode = base64UrlDecode;
9897
12668
  exports.base64UrlEncode = base64UrlEncode;
12669
+ exports.calculateAstDepth = calculateAstDepth;
12670
+ exports.callBuiltin = callBuiltin;
9898
12671
  exports.channelEncryption = index;
12672
+ exports.checkArrayLength = checkArrayLength;
12673
+ exports.checkAstDepth = checkAstDepth;
12674
+ exports.checkAstNodeCount = checkAstNodeCount;
12675
+ exports.checkExpressionLength = checkExpressionLength;
12676
+ exports.checkFunctionArgCount = checkFunctionArgCount;
12677
+ exports.checkGlobPatternLength = checkGlobPatternLength;
12678
+ exports.checkRegexPatternLength = checkRegexPatternLength;
12679
+ exports.countAstNodes = countAstNodes;
9899
12680
  exports.createAftHelper = createAftHelper;
9900
12681
  exports.createAftPayload = createAftPayload;
9901
12682
  exports.createAftReplicaStickinessManager = createAftReplicaStickinessManager;
9902
12683
  exports.createAftSigner = createAftSigner;
9903
12684
  exports.createAftVerifier = createAftVerifier;
12685
+ exports.createAuthFunctionRegistry = createAuthFunctionRegistry;
9904
12686
  exports.createEd25519Csr = createEd25519Csr;
12687
+ exports.evaluate = evaluate;
12688
+ exports.evaluateAsBoolean = evaluateAsBoolean;
9905
12689
  exports.extractCertificateInfo = extractCertificateInfo;
9906
12690
  exports.formatCertificateInfo = formatCertificateInfo;
12691
+ exports.getTypeName = getTypeName;
12692
+ exports.isBuiltinFunction = isBuiltinFunction;
12693
+ exports.normalizeJsValue = normalizeJsValue;
9907
12694
  exports.normalizeStickinessMode = normalizeStickinessMode;
12695
+ exports.parse = parse;
9908
12696
  exports.publicKeyFromX5c = publicKeyFromX5c;
9909
12697
  exports.registerAdvancedSecurityFactories = registerAdvancedSecurityFactories;
9910
12698
  exports.sealedEncryption = index$1;
9911
12699
  exports.serializeAftClaims = serializeAftClaims;
9912
12700
  exports.serializeAftHeader = serializeAftHeader;
12701
+ exports.tokenize = tokenize;
9913
12702
  exports.utf8Decode = utf8Decode;
9914
12703
  exports.validateJwkX5cCertificate = validateJwkX5cCertificate;