@libreflare/worker-runtime 0.5.11 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +120 -22
  2. package/dist/rule-evaluator/accept-encoding.d.ts +2 -1
  3. package/dist/rule-evaluator/accept-encoding.d.ts.map +1 -1
  4. package/dist/rule-evaluator/accept-encoding.js +27 -30
  5. package/dist/rule-evaluator/accept-encoding.js.map +1 -1
  6. package/dist/rule-evaluator/access-values.d.ts +28 -0
  7. package/dist/rule-evaluator/access-values.d.ts.map +1 -0
  8. package/dist/rule-evaluator/access-values.js +60 -0
  9. package/dist/rule-evaluator/access-values.js.map +1 -0
  10. package/dist/rule-evaluator/analysis.d.ts +31 -18
  11. package/dist/rule-evaluator/analysis.d.ts.map +1 -1
  12. package/dist/rule-evaluator/analysis.js +46 -127
  13. package/dist/rule-evaluator/analysis.js.map +1 -1
  14. package/dist/rule-evaluator/ast.d.ts +36 -17
  15. package/dist/rule-evaluator/ast.d.ts.map +1 -1
  16. package/dist/rule-evaluator/ast.js +5 -0
  17. package/dist/rule-evaluator/ast.js.map +1 -1
  18. package/dist/rule-evaluator/comparison.d.ts +16 -0
  19. package/dist/rule-evaluator/comparison.d.ts.map +1 -0
  20. package/dist/rule-evaluator/comparison.js +43 -0
  21. package/dist/rule-evaluator/comparison.js.map +1 -0
  22. package/dist/rule-evaluator/constants.d.ts +7 -3
  23. package/dist/rule-evaluator/constants.d.ts.map +1 -1
  24. package/dist/rule-evaluator/constants.js +7 -1
  25. package/dist/rule-evaluator/constants.js.map +1 -1
  26. package/dist/rule-evaluator/country-codes.generated.js +1 -1
  27. package/dist/rule-evaluator/custom-lists.d.ts +6 -0
  28. package/dist/rule-evaluator/custom-lists.d.ts.map +1 -1
  29. package/dist/rule-evaluator/custom-lists.js +21 -1
  30. package/dist/rule-evaluator/custom-lists.js.map +1 -1
  31. package/dist/rule-evaluator/diagnostics.d.ts +10 -7
  32. package/dist/rule-evaluator/diagnostics.d.ts.map +1 -1
  33. package/dist/rule-evaluator/diagnostics.js +31 -1
  34. package/dist/rule-evaluator/diagnostics.js.map +1 -1
  35. package/dist/rule-evaluator/evaluator.d.ts +10 -3
  36. package/dist/rule-evaluator/evaluator.d.ts.map +1 -1
  37. package/dist/rule-evaluator/evaluator.js +85 -78
  38. package/dist/rule-evaluator/evaluator.js.map +1 -1
  39. package/dist/rule-evaluator/explain.d.ts +11 -2
  40. package/dist/rule-evaluator/explain.d.ts.map +1 -1
  41. package/dist/rule-evaluator/explain.js +217 -121
  42. package/dist/rule-evaluator/explain.js.map +1 -1
  43. package/dist/rule-evaluator/field-availability.d.ts +2 -2
  44. package/dist/rule-evaluator/field-availability.d.ts.map +1 -1
  45. package/dist/rule-evaluator/field-availability.js +9 -3
  46. package/dist/rule-evaluator/field-availability.js.map +1 -1
  47. package/dist/rule-evaluator/field-descriptions.d.ts +1 -1
  48. package/dist/rule-evaluator/field-descriptions.d.ts.map +1 -1
  49. package/dist/rule-evaluator/field-descriptions.generated.d.ts +129 -2
  50. package/dist/rule-evaluator/field-descriptions.generated.d.ts.map +1 -1
  51. package/dist/rule-evaluator/field-descriptions.generated.js +289 -3
  52. package/dist/rule-evaluator/field-descriptions.generated.js.map +1 -1
  53. package/dist/rule-evaluator/fields.d.ts +14 -3
  54. package/dist/rule-evaluator/fields.d.ts.map +1 -1
  55. package/dist/rule-evaluator/fields.js +188 -43
  56. package/dist/rule-evaluator/fields.js.map +1 -1
  57. package/dist/rule-evaluator/function-descriptions.d.ts +2 -0
  58. package/dist/rule-evaluator/function-descriptions.d.ts.map +1 -1
  59. package/dist/rule-evaluator/function-descriptions.generated.d.ts +14 -0
  60. package/dist/rule-evaluator/function-descriptions.generated.d.ts.map +1 -1
  61. package/dist/rule-evaluator/function-descriptions.generated.js +25 -0
  62. package/dist/rule-evaluator/function-descriptions.generated.js.map +1 -1
  63. package/dist/rule-evaluator/function-descriptions.js.map +1 -1
  64. package/dist/rule-evaluator/function-signature-validation.d.ts +1 -1
  65. package/dist/rule-evaluator/function-signature-validation.d.ts.map +1 -1
  66. package/dist/rule-evaluator/function-signature-validation.js +147 -33
  67. package/dist/rule-evaluator/function-signature-validation.js.map +1 -1
  68. package/dist/rule-evaluator/functions.d.ts +18 -5
  69. package/dist/rule-evaluator/functions.d.ts.map +1 -1
  70. package/dist/rule-evaluator/functions.js +281 -183
  71. package/dist/rule-evaluator/functions.js.map +1 -1
  72. package/dist/rule-evaluator/minifier.d.ts +2 -6
  73. package/dist/rule-evaluator/minifier.d.ts.map +1 -1
  74. package/dist/rule-evaluator/minifier.js +9 -9
  75. package/dist/rule-evaluator/minifier.js.map +1 -1
  76. package/dist/rule-evaluator/normalizer.d.ts +2 -6
  77. package/dist/rule-evaluator/normalizer.d.ts.map +1 -1
  78. package/dist/rule-evaluator/normalizer.js +8 -8
  79. package/dist/rule-evaluator/normalizer.js.map +1 -1
  80. package/dist/rule-evaluator/operators.d.ts +21 -2
  81. package/dist/rule-evaluator/operators.d.ts.map +1 -1
  82. package/dist/rule-evaluator/operators.js +162 -104
  83. package/dist/rule-evaluator/operators.js.map +1 -1
  84. package/dist/rule-evaluator/outcome.d.ts +63 -0
  85. package/dist/rule-evaluator/outcome.d.ts.map +1 -0
  86. package/dist/rule-evaluator/outcome.js +78 -0
  87. package/dist/rule-evaluator/outcome.js.map +1 -0
  88. package/dist/rule-evaluator/parser.d.ts +8 -2
  89. package/dist/rule-evaluator/parser.d.ts.map +1 -1
  90. package/dist/rule-evaluator/parser.js +118 -102
  91. package/dist/rule-evaluator/parser.js.map +1 -1
  92. package/dist/rule-evaluator/quantifier.d.ts +2 -2
  93. package/dist/rule-evaluator/quantifier.d.ts.map +1 -1
  94. package/dist/rule-evaluator/rule-language-types.d.ts +46 -12
  95. package/dist/rule-evaluator/rule-language-types.d.ts.map +1 -1
  96. package/dist/rule-evaluator/rule-language-types.js +195 -69
  97. package/dist/rule-evaluator/rule-language-types.js.map +1 -1
  98. package/dist/rule-evaluator/tokenizer.d.ts.map +1 -1
  99. package/dist/rule-evaluator/tokenizer.js +25 -0
  100. package/dist/rule-evaluator/tokenizer.js.map +1 -1
  101. package/dist/rule-evaluator/validation.d.ts +8 -9
  102. package/dist/rule-evaluator/validation.d.ts.map +1 -1
  103. package/dist/rule-evaluator/validation.js +249 -82
  104. package/dist/rule-evaluator/validation.js.map +1 -1
  105. package/dist/rule-evaluator/values.d.ts +26 -0
  106. package/dist/rule-evaluator/values.d.ts.map +1 -0
  107. package/dist/rule-evaluator/values.js +55 -0
  108. package/dist/rule-evaluator/values.js.map +1 -0
  109. package/dist/rule-evaluator.d.ts +4 -4
  110. package/dist/rule-evaluator.d.ts.map +1 -1
  111. package/dist/rule-evaluator.js +1 -1
  112. package/dist/rule-evaluator.js.map +1 -1
  113. package/package.json +2 -2
@@ -1,5 +1,6 @@
1
- import { pushDiagnostic, } from './diagnostics.js';
2
- import { pushWarning, } from './ast.js';
1
+ import { pushDiagnostic, ruleExpressionDiagnostic, } from './diagnostics.js';
2
+ import { EQUALITY_ORDERING_OPERATORS, isDynamicValueNode, pushWarning, } from './ast.js';
3
+ import { RULE_EXPRESSION_MATCH_ALL_EXPRESSION } from './constants.js';
3
4
  import { getUnreliableRuleExpressionFunctionReason } from './functions.js';
4
5
  import { validateFunctionSignature } from './function-signature-validation.js';
5
6
  import { minifyRuleExpression } from './minifier.js';
@@ -8,8 +9,8 @@ import { isKnownRuleExpressionFieldName, isRuleExpressionFieldAvailable, resolve
8
9
  import { DEPRECATED_FIELD_REPLACEMENTS, KNOWN_DEPRECATED_FIELDS, } from './fields.js';
9
10
  import { isRuleExpressionCountryCode } from './country-codes.js';
10
11
  import { getRuleExpressionFieldValueDomain } from './field-value-domains.js';
11
- import { isRuleExpressionIpListItem, isRuleExpressionListName, } from './custom-lists.js';
12
- import { baseFunctionName, classifyInlineSetValue, formatRuleExpressionDataType, isConcreteComparisonFamily, isExpressionNode, isFieldNode, isFuncNode, inferRuleExpressionArgument, isIpAddressValueType, ruleExpressionComparisonTypeFamily, ruleExpressionValueTypes, } from './rule-language-types.js';
12
+ import { customList, isRuleExpressionIpListItem, isRuleExpressionListName, } from './custom-lists.js';
13
+ import { formatRuleExpressionDataType, isArrayExpandedNode, isConcreteComparisonFamily, isExpressionNode, isFieldNode, isFuncNode, inferRuleExpressionArgument, isIpAddressValueType, isLiteralNode, isUnknownRuleExpressionDataType, ruleExpressionComparisonTypeFamily, ruleExpressionValueTypes, } from './rule-language-types.js';
13
14
  import { extractQuantifierComparison, extractQuantifierPredicate } from './quantifier.js';
14
15
  export const MAX_CLOUDFLARE_RULE_EXPRESSION_LENGTH = 4096;
15
16
  export const RULE_EXPRESSION_VALIDATION_PRESETS = [
@@ -42,7 +43,6 @@ export function validateRuleExpressionSyntax(source, config = {}) {
42
43
  pushDiagnostic(diagnostics, {
43
44
  id: 'rule_expression.required',
44
45
  severity: 'error',
45
- message,
46
46
  pos: null,
47
47
  length: 0,
48
48
  source: 'expression',
@@ -51,19 +51,20 @@ export function validateRuleExpressionSyntax(source, config = {}) {
51
51
  const parseWarnings = [];
52
52
  const parseDiagnostics = [];
53
53
  const parsedExpression = expression ? parseExpression(expression, parseWarnings, parseDiagnostics, parseOptions) : null;
54
- const minified = minify ? minifyRuleExpression(expression, parseOptions) : { expression, warnings: [], diagnostics: [] };
54
+ const minified = minify ? minifyRuleExpression(expression, parseOptions) : { expression, diagnostics: [] };
55
55
  const minifiedParseWarnings = [];
56
56
  const minifiedParseDiagnostics = [];
57
- const minificationFailed = (minified.diagnostics ?? []).some(diagnostic => diagnostic.severity === 'error');
57
+ const minificationFailed = minified.diagnostics.some(diagnostic => diagnostic.severity === 'error');
58
58
  if (minify && minified.expression && !minificationFailed) {
59
59
  parseExpression(minified.expression, minifiedParseWarnings, minifiedParseDiagnostics);
60
60
  }
61
61
  const lengthCheckedExpression = minify ? minified.expression : expression;
62
- collectValidationDiagnostics(errors, warnings, diagnostics, parseWarnings, parseDiagnostics, 'expression');
62
+ collectValidationDiagnostics(errors, warnings, diagnostics, parseDiagnostics, 'expression');
63
63
  if (parsedExpression)
64
64
  collectSemanticValidationDiagnostics(errors, warnings, diagnostics, parsedExpression, expression, semanticContext);
65
- collectValidationDiagnostics(errors, warnings, diagnostics, minified.warnings, minified.diagnostics ?? [], 'expression');
66
- collectValidationDiagnostics(errors, warnings, diagnostics, minifiedParseWarnings, minifiedParseDiagnostics, 'minifiedExpression');
65
+ for (const diagnostic of minified.diagnostics)
66
+ pushDiagnostic(diagnostics, { ...diagnostic, source: 'expression' });
67
+ collectValidationDiagnostics(errors, warnings, diagnostics, minifiedParseDiagnostics, 'minifiedExpression');
67
68
  if ((config.enforceMaxLength ?? true) && lengthCheckedExpression.length > maxLength) {
68
69
  const expressionLabel = minify ? 'minified rule expression' : 'rule expression';
69
70
  const limitLabel = maxLength === MAX_CLOUDFLARE_RULE_EXPRESSION_LENGTH ? 'Cloudflare limit' : 'configured limit';
@@ -78,19 +79,16 @@ export function validateRuleExpressionSyntax(source, config = {}) {
78
79
  limitKind: maxLength === MAX_CLOUDFLARE_RULE_EXPRESSION_LENGTH ? 'cloudflare' : 'configured',
79
80
  },
80
81
  severity: 'error',
81
- message,
82
82
  pos: null,
83
83
  length: 0,
84
84
  source: minify ? 'minifiedExpression' : 'expression',
85
85
  });
86
86
  }
87
87
  const validation = {
88
- ok: errors.length === 0,
88
+ ok: !diagnostics.some(diagnostic => diagnostic.severity === 'error'),
89
89
  expression,
90
90
  length: expression.length,
91
91
  maxLength,
92
- errors: [...new Set(errors)],
93
- warnings: [...new Set(warnings)],
94
92
  diagnostics,
95
93
  };
96
94
  if (!minify)
@@ -114,6 +112,33 @@ export function validateLoggingSourceKeyRuleExpressionSyntax(source) {
114
112
  rejectListReferences: true,
115
113
  });
116
114
  }
115
+ const evaluationErrors = new WeakMap();
116
+ /**
117
+ * Returns the errors that make Cloudflare reject a predicate expression in any
118
+ * rule: syntax, operator and type, function signature, and list usage errors.
119
+ * Field availability, length limits, and list contents are not checked. The
120
+ * result is cached with the parsed expression.
121
+ */
122
+ export function ruleExpressionEvaluationErrors(expression) {
123
+ const parseWarnings = [];
124
+ const parseDiagnostics = [];
125
+ const node = parseExpression(expression, parseWarnings, parseDiagnostics);
126
+ const cached = evaluationErrors.get(node);
127
+ if (cached)
128
+ return cached;
129
+ const errors = [];
130
+ const diagnostics = [];
131
+ collectValidationDiagnostics(errors, [], diagnostics, parseDiagnostics, 'expression');
132
+ collectSemanticValidationDiagnostics(errors, [], diagnostics, node, expression, {
133
+ preset: 'url-rewrite-filter',
134
+ fieldAvailability: null,
135
+ rejectListReferences: false,
136
+ deprecationNotices: false,
137
+ });
138
+ const result = [...new Set(errors)];
139
+ evaluationErrors.set(node, result);
140
+ return result;
141
+ }
117
142
  function fieldAvailabilityRules(preset, config, errors, diagnostics) {
118
143
  return resolveRuleExpressionFieldAvailability(preset, config, {
119
144
  onUnknownField: (configPath, field) => {
@@ -206,38 +231,15 @@ function pushValidationConfigError(message, errors, diagnostics, metadata) {
206
231
  pushDiagnostic(diagnostics, {
207
232
  ...metadata,
208
233
  severity: 'error',
209
- message,
210
234
  pos: null,
211
235
  length: 0,
212
236
  source: 'expression',
213
237
  });
214
238
  }
215
- function collectValidationDiagnostics(errors, warnings, diagnostics, messages, messageDiagnostics, source) {
216
- const detailedMessages = new Set();
239
+ function collectValidationDiagnostics(errors, warnings, diagnostics, messageDiagnostics, source) {
217
240
  for (const diagnostic of messageDiagnostics) {
218
- detailedMessages.add(diagnostic.message);
219
241
  pushValidationMessage(errors, warnings, diagnostic.message, diagnostic.severity);
220
- pushDiagnostic(diagnostics, {
221
- ...(diagnostic.id ? { id: diagnostic.id } : {}),
222
- ...(diagnostic.params ? { params: diagnostic.params } : {}),
223
- severity: diagnostic.severity,
224
- message: diagnostic.message,
225
- pos: diagnostic.pos ?? null,
226
- length: diagnostic.length,
227
- source,
228
- });
229
- }
230
- for (const message of messages) {
231
- if (detailedMessages.has(message))
232
- continue;
233
- pushValidationMessage(errors, warnings, message, 'warning');
234
- pushDiagnostic(diagnostics, {
235
- severity: 'warning',
236
- message,
237
- pos: null,
238
- length: 0,
239
- source,
240
- });
242
+ pushDiagnostic(diagnostics, ruleExpressionDiagnostic(diagnostic, source));
241
243
  }
242
244
  }
243
245
  function pushValidationMessage(errors, warnings, message, severity) {
@@ -247,35 +249,45 @@ function pushValidationMessage(errors, warnings, message, severity) {
247
249
  warnings.push(message);
248
250
  }
249
251
  function collectSemanticValidationDiagnostics(errors, warnings, diagnostics, node, expression, context) {
250
- validateSemanticNode(node, new Set(), errors, warnings, diagnostics, expression, context);
252
+ const rootPosition = context.preset === 'url-rewrite-target' ? 'value' : 'predicate';
253
+ validateBooleanLiterals(node, errors, diagnostics);
254
+ validateSemanticNode(node, new Set(), errors, warnings, diagnostics, expression, context, rootPosition);
251
255
  if (context.preset === 'url-rewrite-target')
252
256
  validateRewriteTargetFunctionUsage(node, errors, diagnostics);
253
257
  }
254
- function validateSemanticNode(node, guardedHeaders, errors, warnings, diagnostics, expression, context) {
258
+ function validateSemanticNode(node, guardedHeaders, errors, warnings, diagnostics, expression, context, position) {
255
259
  switch (node.kind) {
256
260
  case 'And': {
257
261
  const andGuards = unionHeaderGuards(guardedHeaders, collectHeaderPresenceGuards(node));
258
262
  for (const operand of node.operands) {
259
- validateSemanticNode(operand, andGuards, errors, warnings, diagnostics, expression, context);
263
+ validateSemanticNode(operand, andGuards, errors, warnings, diagnostics, expression, context, 'predicate');
260
264
  }
261
265
  return;
262
266
  }
263
267
  case 'Or':
264
268
  case 'Xor':
265
269
  for (const operand of node.operands) {
266
- validateSemanticNode(operand, guardedHeaders, errors, warnings, diagnostics, expression, context);
270
+ validateSemanticNode(operand, guardedHeaders, errors, warnings, diagnostics, expression, context, 'predicate');
267
271
  }
268
272
  return;
269
273
  case 'Not':
270
- validateSemanticNode(node.operand, guardedHeaders, errors, warnings, diagnostics, expression, context);
274
+ validateSemanticNode(node.operand, guardedHeaders, errors, warnings, diagnostics, expression, context, 'predicate');
271
275
  return;
272
276
  case 'Comparison':
273
277
  validateFieldOrFunc(node.left, guardedHeaders, errors, warnings, diagnostics, expression, context);
278
+ if (isDynamicValueNode(node.right)) {
279
+ validateFieldOrFunc(node.right, guardedHeaders, errors, warnings, diagnostics, expression, context);
280
+ }
274
281
  validateComparisonRequirements(node, errors, diagnostics, context);
275
282
  return;
276
283
  case 'Func':
284
+ if (position === 'predicate')
285
+ validateFunctionPredicateResult(node, errors, diagnostics);
286
+ validateAccessPath(node, errors, diagnostics);
277
287
  validateFunctionSupport(node, warnings, diagnostics);
278
288
  validateFunctionArgRequirements(node, errors, diagnostics);
289
+ if (node.name === 'coalesce')
290
+ validateCoalesceFallbacks(node, warnings, diagnostics);
279
291
  if (node.name === 'any' || node.name === 'all') {
280
292
  validateQuantifierPredicateArgs(node, guardedHeaders, errors, warnings, diagnostics, expression, context);
281
293
  }
@@ -288,18 +300,47 @@ function validateSemanticNode(node, guardedHeaders, errors, warnings, diagnostic
288
300
  return;
289
301
  }
290
302
  }
303
+ function validateFunctionPredicateResult(node, errors, diagnostics) {
304
+ const result = inferRuleExpressionArgument(node);
305
+ if (result.accessIssues.length > 0 || isUnknownRuleExpressionDataType(result.type))
306
+ return;
307
+ if (result.type.kind === 'scalar' && result.type.name === 'Boolean')
308
+ return;
309
+ const actualType = formatRuleExpressionDataType(result.type);
310
+ pushFuncError(node, `function '${node.name}' result must be Boolean in predicate position; received ${actualType}`, errors, diagnostics, {
311
+ id: 'function.result_type_mismatch',
312
+ params: { functionName: node.name, expectedType: 'Boolean', actualType },
313
+ });
314
+ }
291
315
  function validateComparisonRequirements(node, errors, diagnostics, context) {
292
316
  let invalidArrayComparison = false;
293
- if (node.left.kind === 'ArrayField') {
317
+ const leftInfo = inferRuleExpressionArgument(node.left);
318
+ if (isFieldNode(node.left) && leftInfo.expanded && leftInfo.accessIssues.length === 0) {
294
319
  pushComparisonError(node.left, '[*] cannot be used directly with comparison operators; wrap the comparison in any() or all()', errors, diagnostics, { id: 'array_expansion.direct_comparison' });
295
320
  invalidArrayComparison = true;
296
321
  }
297
- if (node.left.kind === 'Func' && node.left.name.endsWith('_array')) {
322
+ if (node.left.kind === 'Func' && leftInfo.expanded && leftInfo.accessIssues.length === 0) {
298
323
  pushFuncError(node.left, '[*] cannot be used directly with comparison operators; wrap the comparison in any() or all()', errors, diagnostics, { id: 'array_expansion.direct_comparison' });
299
324
  invalidArrayComparison = true;
300
325
  }
326
+ const rightInfo = isDynamicValueNode(node.right) ? inferRuleExpressionArgument(node.right) : null;
327
+ if (isDynamicValueNode(node.right) && rightInfo?.expanded && rightInfo.accessIssues.length === 0) {
328
+ pushValueError(node.right, '[*] cannot be used directly with comparison operators; wrap the comparison in any() or all()', errors, diagnostics, { id: 'array_expansion.direct_comparison' });
329
+ invalidArrayComparison = true;
330
+ }
301
331
  if (!node.right)
302
332
  return;
333
+ // Only equality and ordering operators compare dynamic values; `in` reports its own list requirement.
334
+ if (isDynamicValueNode(node.right) && node.op !== 'in' && !EQUALITY_ORDERING_OPERATORS.has(node.op)) {
335
+ pushValueError(node.right, `operator '${node.op}' requires a literal value on the right side`, errors, diagnostics, { id: 'operator.requires_literal_value', params: { operator: node.op } });
336
+ return;
337
+ }
338
+ if (node.right.kind === 'SetLiteral' && node.op !== 'in') {
339
+ pushValueError(node.right, 'inline lists can only be used with the in operator', errors, diagnostics, {
340
+ id: 'inline_list.requires_in_operator',
341
+ });
342
+ return;
343
+ }
303
344
  if (node.right?.kind === 'ListRef') {
304
345
  validateListRef(node.right, node.left, node.op, errors, diagnostics, context);
305
346
  }
@@ -310,8 +351,9 @@ function validateComparisonRequirements(node, errors, diagnostics, context) {
310
351
  validateWildcardPattern(node.right, errors, diagnostics);
311
352
  }
312
353
  validateComparisonValueDomain(node, errors, diagnostics);
313
- if (!invalidArrayComparison)
354
+ if (!invalidArrayComparison && leftInfo.accessIssues.length === 0 && (rightInfo?.accessIssues.length ?? 0) === 0) {
314
355
  validateComparisonTypeCompatibility(node, errors, diagnostics);
356
+ }
315
357
  }
316
358
  function validateComparisonValueDomain(node, errors, diagnostics) {
317
359
  if (!isFieldNode(node.left) || (node.op !== 'eq' && node.op !== 'ne' && node.op !== 'in'))
@@ -319,12 +361,7 @@ function validateComparisonValueDomain(node, errors, diagnostics) {
319
361
  if (getRuleExpressionFieldValueDomain(node.left.name) !== 'country-code')
320
362
  return;
321
363
  const right = node.right;
322
- const values = right?.kind === 'StringLiteral'
323
- ? [right.value]
324
- : right?.kind === 'SetLiteral'
325
- ? right.values.filter((value) => typeof value === 'string')
326
- : [];
327
- for (const value of values) {
364
+ for (const value of stringLiteralValues(right)) {
328
365
  if (isRuleExpressionCountryCode(value))
329
366
  continue;
330
367
  const message = `'${value}' is not a valid country code for field '${node.left.name}'`;
@@ -334,6 +371,14 @@ function validateComparisonValueDomain(node, errors, diagnostics) {
334
371
  });
335
372
  }
336
373
  }
374
+ /** The quoted String values of a literal or inline list. */
375
+ function stringLiteralValues(node) {
376
+ if (node?.kind === 'StringLiteral')
377
+ return [node.value];
378
+ if (node?.kind !== 'SetLiteral')
379
+ return [];
380
+ return node.elements.flatMap(element => element.type === 'string' ? [element.value] : []);
381
+ }
337
382
  function validateComparisonTypeCompatibility(node, errors, diagnostics) {
338
383
  if (node.op === 'in') {
339
384
  if (node.right?.kind === 'ListRef')
@@ -357,6 +402,14 @@ function validateComparisonTypeCompatibility(node, errors, diagnostics) {
357
402
  });
358
403
  return;
359
404
  }
405
+ if (rightFamily === 'unsupported') {
406
+ const rightTypeLabel = formatRuleExpressionDataType(rightType);
407
+ pushComparisonTypeError(node.right, `operator '${node.op}' does not support ${rightTypeLabel} values`, errors, diagnostics, {
408
+ id: 'operator.unsupported_type',
409
+ params: { operator: node.op, side: 'right', valueType: rightTypeLabel },
410
+ });
411
+ return;
412
+ }
360
413
  if (!isConcreteComparisonFamily(leftFamily) || !isConcreteComparisonFamily(rightFamily))
361
414
  return;
362
415
  const leftLabel = comparisonFamilyLabel(leftFamily);
@@ -473,7 +526,7 @@ function validateRewriteTargetFunctionUsage(node, errors, diagnostics) {
473
526
  function collectRewriteTargetFunctions(node, replacementFunctionStack, functions, errors, diagnostics) {
474
527
  switch (node.kind) {
475
528
  case 'Func': {
476
- const functionName = baseFunctionName(node.name);
529
+ const functionName = node.name;
477
530
  if (URL_REWRITE_TARGET_SINGLE_USE_FUNCTIONS.has(functionName)) {
478
531
  functions.set(functionName, [...(functions.get(functionName) ?? []), node]);
479
532
  }
@@ -503,10 +556,11 @@ function collectRewriteTargetFunctions(node, replacementFunctionStack, functions
503
556
  return;
504
557
  case 'Comparison':
505
558
  collectRewriteTargetFunctions(node.left, replacementFunctionStack, functions, errors, diagnostics);
559
+ if (isDynamicValueNode(node.right)) {
560
+ collectRewriteTargetFunctions(node.right, replacementFunctionStack, functions, errors, diagnostics);
561
+ }
506
562
  return;
507
563
  case 'Field':
508
- case 'ArrayField':
509
- case 'MapField':
510
564
  case 'BoolField':
511
565
  case 'StringLiteral':
512
566
  case 'NumberLiteral':
@@ -567,7 +621,7 @@ function validateFunctionListRefArg(node, arg, errors, diagnostics, context) {
567
621
  }
568
622
  }
569
623
  function validateKnownListRefValueType(node, left, errors, diagnostics, context) {
570
- const listKind = context.customLists?.[node.name]?.kind ?? SUPPORTED_LIST_KIND;
624
+ const listKind = customList(context.customLists, node.name)?.kind ?? SUPPORTED_LIST_KIND;
571
625
  const valueTypes = ruleExpressionValueTypes(left);
572
626
  if (valueTypes.length === 0 || valueTypes.some(valueType => listKindAcceptsValueType(listKind, valueType)))
573
627
  return;
@@ -603,7 +657,7 @@ function isRecord(value) {
603
657
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
604
658
  }
605
659
  function validateInlineSetLiteral(node, errors, diagnostics) {
606
- const valueTypes = new Set(node.values.map(classifyInlineSetValue));
660
+ const valueTypes = new Set(node.elements.map(element => element.type));
607
661
  if (valueTypes.size <= 1)
608
662
  return;
609
663
  pushValueError(node, 'inline list elements must all have the same data type', errors, diagnostics, {
@@ -645,7 +699,6 @@ function pushComparisonError(node, requirement, errors, diagnostics, metadata) {
645
699
  pushDiagnostic(diagnostics, {
646
700
  ...metadata,
647
701
  severity: 'error',
648
- message,
649
702
  pos: node.pos,
650
703
  length: node.length,
651
704
  source: 'expression',
@@ -657,7 +710,6 @@ function pushFuncError(node, requirement, errors, diagnostics, metadata) {
657
710
  pushDiagnostic(diagnostics, {
658
711
  ...metadata,
659
712
  severity: 'error',
660
- message,
661
713
  pos: node.pos ?? null,
662
714
  length: node.length ?? 0,
663
715
  source: 'expression',
@@ -669,14 +721,13 @@ function pushValueError(node, message, errors, diagnostics, metadata) {
669
721
  pushDiagnostic(diagnostics, {
670
722
  ...metadata,
671
723
  severity: 'error',
672
- message,
673
724
  pos: span.pos,
674
725
  length: span.length,
675
726
  source: 'expression',
676
727
  });
677
728
  }
678
729
  function validateFunctionSupport(node, warnings, diagnostics) {
679
- const functionName = node.name.endsWith('_array') ? node.name.slice(0, -'_array'.length) : node.name;
730
+ const functionName = node.name;
680
731
  const reason = getUnreliableRuleExpressionFunctionReason(functionName);
681
732
  if (!reason)
682
733
  return;
@@ -686,18 +737,42 @@ function validateFunctionSupport(node, warnings, diagnostics) {
686
737
  id: 'function.unreliable',
687
738
  params: { functionName, reason },
688
739
  severity: 'warning',
689
- message,
690
740
  pos: null,
691
741
  length: 0,
692
742
  source: 'expression',
693
743
  });
694
744
  }
745
+ /**
746
+ * Warns when a coalesce() argument before the last can never be nil, which
747
+ * makes every argument after it unused. Only literals and fields without
748
+ * access are certain: Cloudflare produces nil from map keys, array indexes,
749
+ * and functions, never from a field itself.
750
+ */
751
+ function validateCoalesceFallbacks(node, warnings, diagnostics) {
752
+ const index = node.args.slice(0, -1).findIndex(arg => (isLiteralNode(arg) && arg.kind !== 'SetLiteral' && arg.kind !== 'ListRef') ||
753
+ (isFieldNode(arg) && arg.accessPath.length === 0));
754
+ if (index < 0)
755
+ return;
756
+ const parameterName = `value${index + 1}`;
757
+ const unusedArgumentCount = node.args.length - index - 1;
758
+ const message = `function 'coalesce' parameter '${parameterName}' is never nil, so the arguments after it are never used`;
759
+ const span = argSpan(node.args[index]);
760
+ pushWarning(warnings, message);
761
+ pushDiagnostic(diagnostics, {
762
+ id: 'function.coalesce.never_nil_argument',
763
+ params: { functionName: 'coalesce', parameterName, unusedArgumentCount },
764
+ severity: 'warning',
765
+ pos: span.pos,
766
+ length: span.length,
767
+ source: 'expression',
768
+ });
769
+ }
695
770
  function validateFieldOrFunc(node, guardedHeaders, errors, warnings, diagnostics, expression, context) {
696
771
  if (isFieldNode(node)) {
697
772
  validateFieldNode(node, guardedHeaders, errors, warnings, diagnostics, expression, context);
698
773
  return;
699
774
  }
700
- validateSemanticNode(node, guardedHeaders, errors, warnings, diagnostics, expression, context);
775
+ validateSemanticNode(node, guardedHeaders, errors, warnings, diagnostics, expression, context, 'value');
701
776
  }
702
777
  function validateFuncArgs(node, guardedHeaders, errors, warnings, diagnostics, expression, context) {
703
778
  for (const arg of node.args) {
@@ -705,7 +780,7 @@ function validateFuncArgs(node, guardedHeaders, errors, warnings, diagnostics, e
705
780
  validateFieldNode(arg, guardedHeaders, errors, warnings, diagnostics, expression, context);
706
781
  }
707
782
  else if (isExpressionNode(arg)) {
708
- validateSemanticNode(arg, guardedHeaders, errors, warnings, diagnostics, expression, context);
783
+ validateSemanticNode(arg, guardedHeaders, errors, warnings, diagnostics, expression, context, 'value');
709
784
  }
710
785
  else if (arg.kind === 'ListRef') {
711
786
  validateFunctionListRefArg(node, arg, errors, diagnostics, context);
@@ -724,6 +799,9 @@ function validateQuantifierPredicateArgs(node, guardedHeaders, errors, warnings,
724
799
  return;
725
800
  }
726
801
  validateFieldOrFunc(quantifier.source, guardedHeaders, errors, warnings, diagnostics, expression, context);
802
+ if (isDynamicValueNode(quantifier.value)) {
803
+ validateFieldOrFunc(quantifier.value, guardedHeaders, errors, warnings, diagnostics, expression, context);
804
+ }
727
805
  if (quantifier.value.kind === 'ListRef') {
728
806
  validateFunctionListRefArg(node, quantifier.value, errors, diagnostics, context);
729
807
  }
@@ -740,7 +818,6 @@ function pushFunctionSignatureError(signatureError, errors, diagnostics) {
740
818
  id: signatureError.id,
741
819
  ...(signatureError.params ? { params: signatureError.params } : {}),
742
820
  severity: 'error',
743
- message: signatureError.message,
744
821
  pos: span.pos,
745
822
  length: span.length,
746
823
  source: 'expression',
@@ -758,11 +835,16 @@ function argSpan(arg) {
758
835
  return { pos: null, length: 0 };
759
836
  }
760
837
  function validateFieldNode(node, guardedHeaders, errors, warnings, diagnostics, expression, context) {
838
+ validateAccessPath(node, errors, diagnostics);
761
839
  validateFieldAvailability(node, errors, diagnostics, expression, context);
762
840
  validateDeprecatedField(node, warnings, diagnostics, expression, context);
763
- if (node.kind !== 'MapField' || node.name !== 'http.request.headers' || node.index === undefined)
841
+ if (node.name !== 'http.request.headers')
842
+ return;
843
+ const mapKey = node.accessPath.find(access => access.kind === 'MapKeyAccess');
844
+ const arrayIndex = node.accessPath.find(access => access.kind === 'ArrayIndexAccess');
845
+ if (!mapKey || !arrayIndex)
764
846
  return;
765
- const headerName = node.key.toLowerCase();
847
+ const headerName = mapKey.key.toLowerCase();
766
848
  if (guardedHeaders.has(headerName))
767
849
  return;
768
850
  const fieldExpression = expression.slice(node.pos, node.pos + node.length);
@@ -773,17 +855,103 @@ function validateFieldNode(node, guardedHeaders, errors, warnings, diagnostics,
773
855
  id: 'field.header_index_requires_guard',
774
856
  params: { fieldExpression, guardExpression, headerName },
775
857
  severity: 'warning',
776
- message,
777
858
  pos: node.pos,
778
859
  length: node.length,
779
860
  source: 'expression',
780
861
  });
781
862
  }
863
+ function validateAccessPath(node, errors, diagnostics) {
864
+ for (const issue of inferRuleExpressionArgument(node).accessIssues) {
865
+ const accessLabel = issue.accessKind === 'map-key'
866
+ ? 'map key'
867
+ : issue.accessKind === 'array-index' ? 'array index' : 'array wildcard';
868
+ const actualType = formatRuleExpressionDataType(issue.actualType);
869
+ const expectedArticle = issue.expectedType === 'Array' ? 'an' : 'a';
870
+ const message = `${accessLabel} access requires ${expectedArticle} ${issue.expectedType} value; received ${actualType}`;
871
+ errors.push(message);
872
+ pushDiagnostic(diagnostics, {
873
+ id: 'access.type_mismatch',
874
+ params: {
875
+ accessKind: issue.accessKind,
876
+ actualType,
877
+ expectedType: issue.expectedType,
878
+ },
879
+ severity: 'error',
880
+ pos: issue.access.pos ?? null,
881
+ length: issue.access.length ?? 0,
882
+ source: 'expression',
883
+ });
884
+ }
885
+ }
782
886
  function validateBoolFieldNode(node, errors, warnings, diagnostics, expression, context) {
887
+ // validateBooleanLiterals() reports `true` and `false`.
783
888
  if (node.name === 'true' || node.name === 'false')
784
889
  return;
785
890
  validateFieldAvailability(node, errors, diagnostics, expression, context);
786
891
  validateDeprecatedField(node, warnings, diagnostics, expression, context);
892
+ if (!isKnownFieldName(node.name))
893
+ return;
894
+ const type = inferRuleExpressionArgument({ kind: 'Field', name: node.name, accessPath: [], pos: node.pos ?? 0, length: node.length ?? 0 }).type;
895
+ if (isUnknownRuleExpressionDataType(type) || (type.kind === 'scalar' && type.name === 'Boolean'))
896
+ return;
897
+ const actualType = formatRuleExpressionDataType(type);
898
+ const message = `field '${node.name}' must be Boolean in predicate position; received ${actualType}`;
899
+ errors.push(message);
900
+ pushDiagnostic(diagnostics, {
901
+ id: 'field.predicate_type_mismatch',
902
+ params: { fieldName: node.name, expectedType: 'Boolean', actualType },
903
+ severity: 'error',
904
+ pos: typeof node.pos === 'number' ? node.pos : null,
905
+ length: typeof node.length === 'number' ? node.length : 0,
906
+ source: 'expression',
907
+ });
908
+ }
909
+ /**
910
+ * Cloudflare has no Boolean literals. It accepts `true` only as an entire
911
+ * expression, which matches every request.
912
+ */
913
+ function validateBooleanLiterals(root, errors, diagnostics) {
914
+ if (root.kind === 'BoolField' && root.name === RULE_EXPRESSION_MATCH_ALL_EXPRESSION)
915
+ return;
916
+ const visit = (node) => {
917
+ switch (node?.kind) {
918
+ case 'BoolField':
919
+ if (node.name === 'true' || node.name === 'false')
920
+ pushBooleanLiteralError(node, node.name, errors, diagnostics);
921
+ return;
922
+ case 'BoolLiteral':
923
+ pushBooleanLiteralError(node, String(node.value), errors, diagnostics);
924
+ return;
925
+ case 'Comparison':
926
+ visit(node.left);
927
+ visit(node.right);
928
+ return;
929
+ case 'Func':
930
+ node.args.forEach(visit);
931
+ return;
932
+ case 'Not':
933
+ visit(node.operand);
934
+ return;
935
+ case 'And':
936
+ case 'Or':
937
+ case 'Xor':
938
+ node.operands.forEach(visit);
939
+ return;
940
+ }
941
+ };
942
+ visit(root);
943
+ }
944
+ function pushBooleanLiteralError(node, literal, errors, diagnostics) {
945
+ const message = `'${literal}' is not a value; Cloudflare accepts 'true' only as the entire expression`;
946
+ errors.push(message);
947
+ pushDiagnostic(diagnostics, {
948
+ id: 'rule_expression.boolean_literal',
949
+ params: { literal },
950
+ severity: 'error',
951
+ pos: typeof node.pos === 'number' ? node.pos : null,
952
+ length: typeof node.length === 'number' ? node.length : 0,
953
+ source: 'expression',
954
+ });
787
955
  }
788
956
  function validateDeprecatedField(node, warnings, diagnostics, expression, context) {
789
957
  if (!context.deprecationNotices || !KNOWN_DEPRECATED_FIELDS.has(node.name))
@@ -800,21 +968,22 @@ function validateDeprecatedField(node, warnings, diagnostics, expression, contex
800
968
  ? { fieldExpression, replacement }
801
969
  : { fieldExpression },
802
970
  severity: 'notice',
803
- message,
804
971
  pos: typeof node.pos === 'number' ? node.pos : null,
805
972
  length: typeof node.length === 'number' ? node.length : 0,
806
973
  source: 'expression',
807
974
  });
808
975
  }
809
976
  function validateFieldAvailability(node, errors, diagnostics, expression, context) {
810
- const rules = context.fieldAvailability;
811
- if (!rules)
812
- return;
977
+ // Unknown fields are invalid in every product, whatever its field availability.
813
978
  if (!isKnownFieldName(node.name)) {
814
979
  pushUnknownFieldError(node, errors, diagnostics, expression);
815
980
  return;
816
981
  }
817
- if (isRuleExpressionFieldAvailable({ name: node.name, map: node.kind === 'MapField' }, rules))
982
+ const rules = context.fieldAvailability;
983
+ if (!rules)
984
+ return;
985
+ const map = isFieldNode(node) && node.accessPath.some(access => access.kind === 'MapKeyAccess');
986
+ if (isRuleExpressionFieldAvailable({ name: node.name, map }, rules))
818
987
  return;
819
988
  const fieldExpression = expressionForNode(node, expression);
820
989
  const message = `field '${fieldExpression}' is not available for ${rules.preset} expressions`;
@@ -823,7 +992,6 @@ function validateFieldAvailability(node, errors, diagnostics, expression, contex
823
992
  id: 'field.unavailable',
824
993
  params: { fieldExpression, fieldName: node.name, preset: rules.preset },
825
994
  severity: 'error',
826
- message,
827
995
  pos: typeof node.pos === 'number' ? node.pos : null,
828
996
  length: typeof node.length === 'number' ? node.length : 0,
829
997
  source: 'expression',
@@ -837,7 +1005,6 @@ function pushUnknownFieldError(node, errors, diagnostics, expression) {
837
1005
  id: 'field.unknown',
838
1006
  params: { fieldExpression, fieldName: node.name },
839
1007
  severity: 'error',
840
- message,
841
1008
  pos: typeof node.pos === 'number' ? node.pos : null,
842
1009
  length: typeof node.length === 'number' ? node.length : 0,
843
1010
  source: 'expression',
@@ -878,20 +1045,20 @@ function getHeaderPresenceGuardNames(node) {
878
1045
  names.add(quantifier.value.value.toLowerCase());
879
1046
  }
880
1047
  if (quantifier.op === 'in' && quantifier.value.kind === 'SetLiteral') {
881
- for (const value of quantifier.value.values) {
882
- if (typeof value === 'string')
883
- names.add(value.toLowerCase());
1048
+ for (const element of quantifier.value.elements) {
1049
+ if (element.type === 'string')
1050
+ names.add(element.value.toLowerCase());
884
1051
  }
885
1052
  }
886
1053
  return names;
887
1054
  }
888
1055
  function isHeaderNamesCollection(node) {
889
1056
  if (isFieldNode(node)) {
890
- return node.kind === 'ArrayField' && node.name === 'http.request.headers.names';
1057
+ return isArrayExpandedNode(node) && node.name === 'http.request.headers.names';
891
1058
  }
892
- if (isFuncNode(node) && node.name === 'lower_array') {
1059
+ if (isFuncNode(node) && node.name === 'lower' && isArrayExpandedNode(node)) {
893
1060
  const arg = node.args[0];
894
- return isFieldNode(arg) && arg.kind === 'ArrayField' && arg.name === 'http.request.headers.names';
1061
+ return isFieldNode(arg) && isArrayExpandedNode(arg) && arg.name === 'http.request.headers.names';
895
1062
  }
896
1063
  return false;
897
1064
  }