@libreflare/worker-runtime 0.8.2 → 0.9.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 (136) hide show
  1. package/README.md +234 -23
  2. package/dist/log-handler.d.ts.map +1 -1
  3. package/dist/log-handler.js +12 -6
  4. package/dist/log-handler.js.map +1 -1
  5. package/dist/rule-evaluator/access-values.d.ts +19 -6
  6. package/dist/rule-evaluator/access-values.d.ts.map +1 -1
  7. package/dist/rule-evaluator/access-values.js +33 -8
  8. package/dist/rule-evaluator/access-values.js.map +1 -1
  9. package/dist/rule-evaluator/analysis.d.ts +63 -11
  10. package/dist/rule-evaluator/analysis.d.ts.map +1 -1
  11. package/dist/rule-evaluator/analysis.js +60 -43
  12. package/dist/rule-evaluator/analysis.js.map +1 -1
  13. package/dist/rule-evaluator/ast.d.ts +31 -18
  14. package/dist/rule-evaluator/ast.d.ts.map +1 -1
  15. package/dist/rule-evaluator/ast.js +3 -4
  16. package/dist/rule-evaluator/ast.js.map +1 -1
  17. package/dist/rule-evaluator/constants.d.ts +1 -1
  18. package/dist/rule-evaluator/constants.d.ts.map +1 -1
  19. package/dist/rule-evaluator/constants.js +3 -0
  20. package/dist/rule-evaluator/constants.js.map +1 -1
  21. package/dist/rule-evaluator/country-codes.generated.js +1 -1
  22. package/dist/rule-evaluator/custom-lists.d.ts +0 -6
  23. package/dist/rule-evaluator/custom-lists.d.ts.map +1 -1
  24. package/dist/rule-evaluator/custom-lists.js +1 -12
  25. package/dist/rule-evaluator/custom-lists.js.map +1 -1
  26. package/dist/rule-evaluator/diagnostics.d.ts +1 -1
  27. package/dist/rule-evaluator/diagnostics.d.ts.map +1 -1
  28. package/dist/rule-evaluator/diagnostics.js +18 -0
  29. package/dist/rule-evaluator/diagnostics.js.map +1 -1
  30. package/dist/rule-evaluator/engine-observations.generated.d.ts +20 -0
  31. package/dist/rule-evaluator/engine-observations.generated.d.ts.map +1 -1
  32. package/dist/rule-evaluator/engine-observations.generated.js +5 -0
  33. package/dist/rule-evaluator/engine-observations.generated.js.map +1 -1
  34. package/dist/rule-evaluator/evaluator.d.ts +4 -2
  35. package/dist/rule-evaluator/evaluator.d.ts.map +1 -1
  36. package/dist/rule-evaluator/evaluator.js +5 -4
  37. package/dist/rule-evaluator/evaluator.js.map +1 -1
  38. package/dist/rule-evaluator/explain.d.ts +2 -1
  39. package/dist/rule-evaluator/explain.d.ts.map +1 -1
  40. package/dist/rule-evaluator/explain.js +49 -7
  41. package/dist/rule-evaluator/explain.js.map +1 -1
  42. package/dist/rule-evaluator/field-descriptions.generated.d.ts +13 -0
  43. package/dist/rule-evaluator/field-descriptions.generated.d.ts.map +1 -1
  44. package/dist/rule-evaluator/field-descriptions.generated.js +33 -0
  45. package/dist/rule-evaluator/field-descriptions.generated.js.map +1 -1
  46. package/dist/rule-evaluator/fields.d.ts +13 -1
  47. package/dist/rule-evaluator/fields.d.ts.map +1 -1
  48. package/dist/rule-evaluator/fields.js +71 -17
  49. package/dist/rule-evaluator/fields.js.map +1 -1
  50. package/dist/rule-evaluator/function-descriptions.d.ts +2 -0
  51. package/dist/rule-evaluator/function-descriptions.d.ts.map +1 -1
  52. package/dist/rule-evaluator/function-descriptions.generated.d.ts +66 -10
  53. package/dist/rule-evaluator/function-descriptions.generated.d.ts.map +1 -1
  54. package/dist/rule-evaluator/function-descriptions.generated.js +129 -11
  55. package/dist/rule-evaluator/function-descriptions.generated.js.map +1 -1
  56. package/dist/rule-evaluator/function-descriptions.js.map +1 -1
  57. package/dist/rule-evaluator/function-signature-validation.d.ts +2 -0
  58. package/dist/rule-evaluator/function-signature-validation.d.ts.map +1 -1
  59. package/dist/rule-evaluator/function-signature-validation.js +169 -19
  60. package/dist/rule-evaluator/function-signature-validation.js.map +1 -1
  61. package/dist/rule-evaluator/functions.d.ts +24 -1
  62. package/dist/rule-evaluator/functions.d.ts.map +1 -1
  63. package/dist/rule-evaluator/functions.js +423 -95
  64. package/dist/rule-evaluator/functions.js.map +1 -1
  65. package/dist/rule-evaluator/ip-literals.d.ts +56 -0
  66. package/dist/rule-evaluator/ip-literals.d.ts.map +1 -0
  67. package/dist/rule-evaluator/ip-literals.js +162 -0
  68. package/dist/rule-evaluator/ip-literals.js.map +1 -0
  69. package/dist/rule-evaluator/log-sample.d.ts.map +1 -1
  70. package/dist/rule-evaluator/log-sample.js +14 -2
  71. package/dist/rule-evaluator/log-sample.js.map +1 -1
  72. package/dist/rule-evaluator/match-chain.d.ts +2 -1
  73. package/dist/rule-evaluator/match-chain.d.ts.map +1 -1
  74. package/dist/rule-evaluator/match-chain.js +12 -17
  75. package/dist/rule-evaluator/match-chain.js.map +1 -1
  76. package/dist/rule-evaluator/minifier.d.ts +1 -1
  77. package/dist/rule-evaluator/minifier.d.ts.map +1 -1
  78. package/dist/rule-evaluator/minifier.js +15 -14
  79. package/dist/rule-evaluator/minifier.js.map +1 -1
  80. package/dist/rule-evaluator/normalizer.d.ts +1 -1
  81. package/dist/rule-evaluator/normalizer.d.ts.map +1 -1
  82. package/dist/rule-evaluator/normalizer.js +4 -5
  83. package/dist/rule-evaluator/normalizer.js.map +1 -1
  84. package/dist/rule-evaluator/operators.d.ts +4 -0
  85. package/dist/rule-evaluator/operators.d.ts.map +1 -1
  86. package/dist/rule-evaluator/operators.js +26 -98
  87. package/dist/rule-evaluator/operators.js.map +1 -1
  88. package/dist/rule-evaluator/outcome.d.ts +2 -0
  89. package/dist/rule-evaluator/outcome.d.ts.map +1 -1
  90. package/dist/rule-evaluator/outcome.js +0 -6
  91. package/dist/rule-evaluator/outcome.js.map +1 -1
  92. package/dist/rule-evaluator/parse-cache.d.ts +9 -2
  93. package/dist/rule-evaluator/parse-cache.d.ts.map +1 -1
  94. package/dist/rule-evaluator/parse-cache.js +10 -4
  95. package/dist/rule-evaluator/parse-cache.js.map +1 -1
  96. package/dist/rule-evaluator/parser.d.ts +181 -21
  97. package/dist/rule-evaluator/parser.d.ts.map +1 -1
  98. package/dist/rule-evaluator/parser.js +561 -93
  99. package/dist/rule-evaluator/parser.js.map +1 -1
  100. package/dist/rule-evaluator/quantifier.d.ts +96 -2
  101. package/dist/rule-evaluator/quantifier.d.ts.map +1 -1
  102. package/dist/rule-evaluator/quantifier.js +263 -22
  103. package/dist/rule-evaluator/quantifier.js.map +1 -1
  104. package/dist/rule-evaluator/query-args.d.ts +23 -0
  105. package/dist/rule-evaluator/query-args.d.ts.map +1 -0
  106. package/dist/rule-evaluator/query-args.js +46 -0
  107. package/dist/rule-evaluator/query-args.js.map +1 -0
  108. package/dist/rule-evaluator/rule-language-types.d.ts +28 -17
  109. package/dist/rule-evaluator/rule-language-types.d.ts.map +1 -1
  110. package/dist/rule-evaluator/rule-language-types.js +117 -42
  111. package/dist/rule-evaluator/rule-language-types.js.map +1 -1
  112. package/dist/rule-evaluator/string-literals.d.ts +20 -0
  113. package/dist/rule-evaluator/string-literals.d.ts.map +1 -0
  114. package/dist/rule-evaluator/string-literals.js +44 -0
  115. package/dist/rule-evaluator/string-literals.js.map +1 -0
  116. package/dist/rule-evaluator/tokenizer.d.ts +34 -5
  117. package/dist/rule-evaluator/tokenizer.d.ts.map +1 -1
  118. package/dist/rule-evaluator/tokenizer.js +320 -74
  119. package/dist/rule-evaluator/tokenizer.js.map +1 -1
  120. package/dist/rule-evaluator/transformation.d.ts +2 -2
  121. package/dist/rule-evaluator/transformation.d.ts.map +1 -1
  122. package/dist/rule-evaluator/transformation.js +4 -5
  123. package/dist/rule-evaluator/transformation.js.map +1 -1
  124. package/dist/rule-evaluator/validation.d.ts.map +1 -1
  125. package/dist/rule-evaluator/validation.js +261 -122
  126. package/dist/rule-evaluator/validation.js.map +1 -1
  127. package/dist/rule-evaluator.d.ts +4 -2
  128. package/dist/rule-evaluator.d.ts.map +1 -1
  129. package/dist/rule-evaluator.js +3 -1
  130. package/dist/rule-evaluator.js.map +1 -1
  131. package/dist/runtime-config.d.ts.map +1 -1
  132. package/dist/runtime-config.js +4 -3
  133. package/dist/runtime-config.js.map +1 -1
  134. package/dist/tools/explain-rule-miss.js +4 -6
  135. package/dist/tools/explain-rule-miss.js.map +1 -1
  136. package/package.json +2 -2
@@ -1,26 +1,30 @@
1
1
  import { ruleExpressionDiagnostic, } from './diagnostics.js';
2
- import { EQUALITY_ORDERING_OPERATORS, isBooleanLiteralName, isConditionArgument, isDynamicValueNode, isEmptyArgument, isExpressionNode, isUncertainArgument, mayHaveFewerArguments, unhandledNode, validSetElements, } from './ast.js';
2
+ import { EQUALITY_ORDERING_OPERATORS, isBooleanLiteralName, isConditionArgument, isDynamicValueNode, isEmptyArgument, isExpressionNode, isUncertainArgument, mayHaveFewerArguments, mayHaveMoreArguments, unhandledNode, validSetElements, } from './ast.js';
3
3
  import { RULE_EXPRESSION_MATCH_ALL_EXPRESSION } from './constants.js';
4
4
  import { isRuleExpressionFunctionAvailable, isRuleExpressionOperatorAvailable } from './function-availability.js';
5
5
  import { getUnreliableRuleExpressionFunctionReason } from './functions.js';
6
- import { bindArguments, validateFunctionSignature, } from './function-signature-validation.js';
6
+ import { bindArguments, PREDICATE_SHAPE_TYPES, validateFunctionSignature, } from './function-signature-validation.js';
7
7
  import { minifyRuleExpression } from './minifier.js';
8
8
  import { parseExpression } from './parse-cache.js';
9
+ import { trimRuleExpression } from './tokenizer.js';
9
10
  import { hasRuleExpressionSyntaxErrors } from './transformation.js';
10
11
  import { isKnownRuleExpressionFieldName, isRuleExpressionFieldAvailable, resolveRuleExpressionFieldAvailability, } from './field-availability.js';
11
- import { deprecatedFieldReplacement, KNOWN_DEPRECATED_FIELDS, REQUEST_HEADER_ARRAYS, REQUEST_HEADER_MAPS } from './fields.js';
12
+ import { deprecatedFieldReplacement, KNOWN_DEPRECATED_FIELDS, REQUEST_HEADER_ARRAYS, REQUEST_HEADER_MAPS, } from './fields.js';
12
13
  import { isRuleExpressionCountryCode } from './country-codes.js';
13
14
  import { getRuleExpressionFieldValueDomain } from './field-value-domains.js';
14
15
  import { customList, isRuleExpressionIpListItem, isRuleExpressionListName, } from './custom-lists.js';
15
- import { fieldDataType, formatRuleExpressionDataType, isArrayExpandedNode, isBooleanType, isConcreteComparisonFamily, isFieldNode, isFuncNode, inferFunctionInvocation, inferRuleExpressionArgument, isIpAddressValueType, isLiteralNode, isStringLiteral, isUnknownRuleExpressionDataType, ruleExpressionComparisonTypeFamily, ruleExpressionValueTypes, singleValueType, } from './rule-language-types.js';
16
- import { extractQuantifierComparison, extractQuantifierPredicate } from './quantifier.js';
17
- import { stringLiteralSource } from './tokenizer.js';
16
+ import { collectionElementDataType, conditionShape, fieldDataType, formatRuleExpressionDataType, isArrayConditionArgument, isArrayExpandedNode, isBooleanArrayType, isBooleanType, isConcreteComparisonFamily, isFieldNode, isFuncNode, inferFunctionInvocation, inferRuleExpressionArgument, isIpAddressValueType, isLiteralNode, isStringLiteral, isUnknownRuleExpressionDataType, ruleExpressionComparisonTypeFamily, ruleExpressionValueTypes, singleValueType, } from './rule-language-types.js';
17
+ import { conditionArray, isArrayCall, isArrayComparison, isArrayCondition, predicateArrays, quantifierPredicateConditions, readQuantifierPredicate, readsWholeArray, unalignedArray, unwrapMappedCalls, } from './quantifier.js';
18
+ import { renderRuleExpressionStringLiteral } from './string-literals.js';
18
19
  export const MAX_CLOUDFLARE_RULE_EXPRESSION_LENGTH = 4096;
19
20
  export const RULE_EXPRESSION_VALIDATION_PRESETS = [
20
21
  'url-rewrite-filter',
21
22
  'url-rewrite-target',
22
23
  'logging-source-key',
23
24
  ];
25
+ function isArgumentPosition(position) {
26
+ return position === 'argument' || position === 'boolean-argument' || position === 'array-argument';
27
+ }
24
28
  /** Functions Cloudflare accepts at most once in any expression. */
25
29
  const SINGLE_USE_FUNCTIONS = new Set(['hash_in_range']);
26
30
  /** Functions the URL rewrite phase accepts at most once in a filter or a rewrite target. */
@@ -33,7 +37,7 @@ export function validateRuleExpressionSyntax(source, config = {}) {
33
37
  const maxLength = config?.maxLength ?? MAX_CLOUDFLARE_RULE_EXPRESSION_LENGTH;
34
38
  const parseOptions = config.comments ? { comments: config.comments } : {};
35
39
  const preset = config.preset ?? 'url-rewrite-filter';
36
- const expression = source.trim();
40
+ const expression = trimRuleExpression(source);
37
41
  const errors = [];
38
42
  const diagnostics = [];
39
43
  const semanticContext = {
@@ -66,7 +70,9 @@ export function validateRuleExpressionSyntax(source, config = {}) {
66
70
  collectValidationDiagnostics(errors, diagnostics, parseDiagnostics, 'expression');
67
71
  if (parsedExpression)
68
72
  collectSemanticValidationDiagnostics(errors, diagnostics, parsedExpression, expression, semanticContext);
69
- collectValidationDiagnostics(errors, diagnostics, minifiedParseDiagnostics, 'minifiedExpression');
73
+ // The minified parse checks that minifying kept the expression valid. Its warnings repeat the expression's,
74
+ // as the minifier keeps literals as written.
75
+ collectValidationDiagnostics(errors, diagnostics, minifiedParseDiagnostics.filter(diagnostic => diagnostic.severity === 'error'), 'minifiedExpression');
70
76
  if ((config.enforceMaxLength ?? true) && lengthCheckedExpression.length > maxLength) {
71
77
  const expressionLabel = minify ? 'minified rule expression' : 'rule expression';
72
78
  const limitLabel = maxLength === MAX_CLOUDFLARE_RULE_EXPRESSION_LENGTH ? 'Cloudflare limit' : 'configured limit';
@@ -251,33 +257,39 @@ function collectSemanticValidationDiagnostics(errors, diagnostics, node, express
251
257
  validateFunctionUsage(node, context, errors, diagnostics);
252
258
  }
253
259
  function validateSemanticNode(node, guardedHeaders, errors, diagnostics, expression, context, position) {
260
+ // The conditions an argument combines are arguments' conditions too, with the first one's type.
261
+ let operandPosition = 'predicate';
262
+ if (position === 'boolean-argument' || position === 'array-argument')
263
+ operandPosition = position;
264
+ else if (position === 'argument')
265
+ operandPosition = combinedArgumentPosition(node);
254
266
  switch (node.kind) {
255
267
  case 'And': {
256
268
  const andGuards = unionHeaderGuards(guardedHeaders, collectHeaderPresenceGuards(node));
257
269
  for (const operand of node.operands) {
258
- validateSemanticNode(operand, andGuards, errors, diagnostics, expression, context, 'predicate');
270
+ validateSemanticNode(operand, andGuards, errors, diagnostics, expression, context, operandPosition);
259
271
  }
260
272
  return;
261
273
  }
262
274
  case 'Or':
263
275
  case 'Xor':
264
276
  for (const operand of node.operands) {
265
- validateSemanticNode(operand, guardedHeaders, errors, diagnostics, expression, context, 'predicate');
277
+ validateSemanticNode(operand, guardedHeaders, errors, diagnostics, expression, context, operandPosition);
266
278
  }
267
279
  return;
268
280
  case 'Not':
269
- validateSemanticNode(node.operand, guardedHeaders, errors, diagnostics, expression, context, 'predicate');
281
+ validateSemanticNode(node.operand, guardedHeaders, errors, diagnostics, expression, context, isArgumentPosition(position) ? position : 'predicate');
270
282
  return;
271
283
  case 'Comparison':
272
284
  validateFieldOrFunc(node.left, guardedHeaders, errors, diagnostics, expression, context);
273
285
  if (isDynamicValueNode(node.right)) {
274
286
  validateFieldOrFunc(node.right, guardedHeaders, errors, diagnostics, expression, context);
275
287
  }
276
- validateComparisonRequirements(node, errors, diagnostics, context);
288
+ validateComparisonRequirements(node, errors, diagnostics, context, isArgumentPosition(position));
277
289
  return;
278
290
  case 'Func': {
279
- if (position === 'predicate')
280
- validateFunctionPredicateResult(node, errors, diagnostics);
291
+ if (position !== 'value' && position !== 'counted')
292
+ validateFunctionPredicateResult(node, position, errors, diagnostics);
281
293
  validateFunctionAvailability(node, errors, diagnostics, context);
282
294
  validateAccessPath(node, errors, diagnostics);
283
295
  validateFunctionSupport(node, diagnostics);
@@ -289,16 +301,22 @@ function validateSemanticNode(node, guardedHeaders, errors, diagnostics, express
289
301
  validateHeaderOrderReads(node, diagnostics, expression);
290
302
  if (node.name === 'coalesce')
291
303
  validateCoalesceFallbacks(node, binding, diagnostics);
304
+ const errorCount = errors.length;
305
+ // Whether len() only counts the arrays the call's arguments give.
306
+ const counted = node.name === 'len' || position === 'counted';
292
307
  if (node.name === 'any' || node.name === 'all') {
293
308
  validateQuantifierPredicateArgs(node, guardedHeaders, errors, diagnostics, expression, context);
294
309
  }
295
310
  else {
296
- validateFuncArgs(node, guardedHeaders, errors, diagnostics, expression, context);
311
+ validateFuncArgs(node, guardedHeaders, errors, diagnostics, expression, context, counted);
297
312
  }
313
+ // A pairing warning on conditions any check rejects would only add to their errors.
314
+ if (argumentsValid && errors.length === errorCount)
315
+ validateConditionPairing(node, diagnostics, expression, counted);
298
316
  return;
299
317
  }
300
318
  case 'BoolField':
301
- validateBoolFieldNode(node, errors, diagnostics, expression, context);
319
+ validateBoolFieldNode(node, position, errors, diagnostics, expression, context);
302
320
  return;
303
321
  case 'Invalid':
304
322
  // A field or call that recovery cut short gets its own checks, but is not judged as a condition.
@@ -309,16 +327,37 @@ function validateSemanticNode(node, guardedHeaders, errors, diagnostics, express
309
327
  unhandledNode(node);
310
328
  }
311
329
  }
312
- function validateFunctionPredicateResult(node, errors, diagnostics) {
330
+ /**
331
+ * Reports a call whose result is no condition. A Boolean in any() or all() has
332
+ * its own error, as it has no result for each element, and an argument takes
333
+ * an array of Booleans too.
334
+ */
335
+ function validateFunctionPredicateResult(node, position, errors, diagnostics) {
313
336
  const type = conditionResultType(node);
314
337
  if (!type || isUnknownRuleExpressionDataType(type) || isBooleanType(type))
315
338
  return;
339
+ if (isArgumentPosition(position) && isBooleanArrayType(type))
340
+ return;
316
341
  const actualType = formatRuleExpressionDataType(type);
317
- pushFuncError(node, `function '${node.name}' result must be Boolean in predicate position; received ${actualType}`, errors, diagnostics, {
342
+ const expectedType = predicateType(position);
343
+ pushFuncError(node, `function '${node.name}' result must be ${expectedType} in predicate position; received ${actualType}`, errors, diagnostics, {
318
344
  id: 'function.result_type_mismatch',
319
- params: { functionName: node.name, expectedType: 'Boolean', actualType },
345
+ params: { functionName: node.name, expectedType, actualType },
320
346
  });
321
347
  }
348
+ /** The type a condition must have where it is. */
349
+ function predicateType(position) {
350
+ return PREDICATE_SHAPE_TYPES[position === 'array-predicate' || position === 'array-argument' ? 'array' : 'scalar'];
351
+ }
352
+ /** Where the conditions an argument combines are: they must have the first one's type. */
353
+ function combinedArgumentPosition(node) {
354
+ if (node.kind !== 'And' && node.kind !== 'Or' && node.kind !== 'Xor')
355
+ return 'argument';
356
+ const shape = conditionShape(inferRuleExpressionArgument(node.operands[0]));
357
+ if (shape === 'array')
358
+ return 'array-argument';
359
+ return shape === 'scalar' ? 'boolean-argument' : 'argument';
360
+ }
322
361
  /**
323
362
  * The type a call's result has as a condition, or null when it is invalid.
324
363
  * Where only whether the call maps is unknown, the type of one invocation
@@ -332,10 +371,16 @@ function conditionResultType(node) {
332
371
  const type = singleValueType(node);
333
372
  return type && !isBooleanType(type) ? type : null;
334
373
  }
335
- function validateComparisonRequirements(node, errors, diagnostics, context) {
374
+ /**
375
+ * Checks a comparison. One whose left side `[*]` expands compares each
376
+ * element, which only a function argument can: elsewhere, a condition needs
377
+ * a single result, and any() and all() check their own comparisons.
378
+ */
379
+ function validateComparisonRequirements(node, errors, diagnostics, context, elementwise) {
336
380
  let invalidArrayComparison = false;
337
381
  const leftInfo = inferRuleExpressionArgument(node.left);
338
- const leftExpanded = !leftInfo.invalid && leftInfo.expanded;
382
+ // Where each element is not compared, a left side that `[*]` expands is an error.
383
+ const leftExpanded = !elementwise && !leftInfo.invalid && leftInfo.expanded;
339
384
  if (isFieldNode(node.left) && leftExpanded) {
340
385
  pushComparisonError(node.left, '[*] cannot be used directly with comparison operators; wrap the comparison in any() or all()', errors, diagnostics, { id: 'array_expansion.direct_comparison' });
341
386
  invalidArrayComparison = true;
@@ -419,7 +464,10 @@ function validateComparisonTypeCompatibility(node, right, errors, diagnostics) {
419
464
  const leftInfo = inferRuleExpressionArgument(node.left);
420
465
  if (leftInfo.invalid)
421
466
  return;
422
- const leftType = leftInfo.type;
467
+ // A left side that `[*]` expands compares each element.
468
+ const leftType = leftInfo.expanded ? collectionElementDataType(leftInfo.type) : leftInfo.type;
469
+ if (!leftType)
470
+ return;
423
471
  const leftFamily = ruleExpressionComparisonTypeFamily(leftType);
424
472
  if (leftFamily === 'unsupported') {
425
473
  const leftTypeLabel = formatRuleExpressionDataType(leftType);
@@ -591,16 +639,23 @@ function reportSingleUseFunction(functionName, usage, errors, diagnostics) {
591
639
  }
592
640
  }
593
641
  /**
594
- * Whether an argument is a Boolean field or a call used as a condition, such
595
- * as `(ssl)` or `(has_value(...))`, which Cloudflare evaluates with its IsTrue
596
- * operator. Other conditions use their own operators, and so do quantifiers.
597
- * One that recovery cut short may be a comparison instead, and is invalid;
598
- * see InvalidNode.operand.
642
+ * Whether a condition is a Boolean field or a call other than a quantifier,
643
+ * which Cloudflare evaluates with its IsTrue operator, as it does `ssl` in
644
+ * `not ssl`. Other conditions use their own operators, and so do quantifiers.
645
+ */
646
+ function isTruthTest(condition) {
647
+ if (condition.kind === 'Func')
648
+ return condition.name !== 'any' && condition.name !== 'all';
649
+ return condition.kind === 'BoolField';
650
+ }
651
+ /**
652
+ * Whether an argument is a truth test (see isTruthTest()) used as a
653
+ * condition, such as `(ssl)` or `(has_value(...))`; a call on its own is a
654
+ * value. One that recovery cut short may be a comparison instead, and is
655
+ * invalid; see InvalidNode.operand.
599
656
  */
600
657
  function isTruthTestArgument(arg) {
601
- if (arg.kind === 'Func')
602
- return arg.condition === true && arg.name !== 'any' && arg.name !== 'all';
603
- return arg.kind === 'BoolField';
658
+ return isTruthTest(arg) && (arg.kind === 'BoolField' || arg.condition === true);
604
659
  }
605
660
  /** Collects every function call, nested replacement, and operator in an expression. */
606
661
  function collectFunctionUsage(node, replacementFunctionStack, usage) {
@@ -631,11 +686,11 @@ function collectFunctionUsage(node, replacementFunctionStack, usage) {
631
686
  case 'Xor':
632
687
  usage.operators?.push({ operator: node.kind.toLowerCase(), node });
633
688
  for (const operand of node.operands)
634
- collectFunctionUsage(operand, replacementFunctionStack, usage);
689
+ collectConditionUsage(operand, replacementFunctionStack, usage);
635
690
  return;
636
691
  case 'Not':
637
692
  usage.operators?.push({ operator: 'not', node });
638
- collectFunctionUsage(node.operand, replacementFunctionStack, usage);
693
+ collectConditionUsage(node.operand, replacementFunctionStack, usage);
639
694
  return;
640
695
  case 'Comparison':
641
696
  usage.operators?.push({ operator: node.op, node });
@@ -660,20 +715,14 @@ function collectFunctionUsage(node, replacementFunctionStack, usage) {
660
715
  unhandledNode(node);
661
716
  }
662
717
  }
718
+ /** Collects what a condition uses, with the IsTrue operator of a truth test; see isTruthTest(). */
719
+ function collectConditionUsage(condition, replacementFunctionStack, usage) {
720
+ if (isTruthTest(condition))
721
+ usage.operators?.push({ operator: 'is_true', node: condition });
722
+ collectFunctionUsage(condition, replacementFunctionStack, usage);
723
+ }
663
724
  function validateListRef(node, left, op, errors, diagnostics, context) {
664
- const validName = validateListRefName(node, errors, diagnostics);
665
- if (context.rejectListReferences) {
666
- pushValueError(node, `list reference '$${node.name}' is not allowed`, errors, diagnostics, {
667
- id: 'list.reference_not_allowed',
668
- params: { listName: node.name },
669
- });
670
- }
671
- if (context.customLists !== undefined && validName && !Object.hasOwn(context.customLists, node.name)) {
672
- pushValueError(node, `list reference '$${node.name}' is not configured`, errors, diagnostics, {
673
- id: 'list.reference_not_configured',
674
- params: { listName: node.name },
675
- });
676
- }
725
+ validateListReference(node, errors, diagnostics, context);
677
726
  if (op !== 'in') {
678
727
  pushValueError(node, `list '$${node.name}' can only be used with the in operator`, errors, diagnostics, {
679
728
  id: 'list.reference_requires_in_operator',
@@ -683,7 +732,8 @@ function validateListRef(node, left, op, errors, diagnostics, context) {
683
732
  }
684
733
  validateKnownListRefValueType(node, left, errors, diagnostics, context);
685
734
  }
686
- function validateFunctionListRefArg(node, arg, errors, diagnostics, context) {
735
+ /** Checks a list reference wherever it is: its name, and whether the context allows and configures it. */
736
+ function validateListReference(arg, errors, diagnostics, context) {
687
737
  const validName = validateListRefName(arg, errors, diagnostics);
688
738
  if (context.rejectListReferences) {
689
739
  pushValueError(arg, `list reference '$${arg.name}' is not allowed`, errors, diagnostics, {
@@ -697,17 +747,6 @@ function validateFunctionListRefArg(node, arg, errors, diagnostics, context) {
697
747
  params: { listName: arg.name },
698
748
  });
699
749
  }
700
- const quantifier = extractQuantifierPredicate(node);
701
- if (quantifier?.value === arg) {
702
- if (quantifier.op === 'in') {
703
- validateKnownListRefValueType(arg, quantifier.source, errors, diagnostics, context);
704
- return;
705
- }
706
- pushValueError(arg, `list '$${arg.name}' can only be used with the in operator`, errors, diagnostics, {
707
- id: 'list.reference_requires_in_operator',
708
- params: { listName: arg.name, operator: quantifier.op },
709
- });
710
- }
711
750
  }
712
751
  function validateKnownListRefValueType(node, left, errors, diagnostics, context) {
713
752
  const listKind = customList(context.customLists, node.name)?.kind ?? SUPPORTED_LIST_KIND;
@@ -800,8 +839,8 @@ function pushFuncError(node, requirement, errors, diagnostics, metadata) {
800
839
  diagnostics.push({
801
840
  ...metadata,
802
841
  severity: 'error',
803
- pos: node.pos ?? null,
804
- length: node.length ?? 0,
842
+ pos: node.pos,
843
+ length: node.length,
805
844
  source: 'expression',
806
845
  });
807
846
  }
@@ -869,6 +908,10 @@ function validateHeaderOrderReads(node, diagnostics, expression) {
869
908
  * on none, as validateSemanticNode() skips its own order reads.
870
909
  */
871
910
  function orderedHeaderFields(node, first) {
911
+ // A condition's results for each element keep the order of the arrays it reads; a call's are its value.
912
+ if (node && node.kind !== 'Func' && isArrayConditionArgument(node)) {
913
+ return predicateArrays(node).flatMap(array => orderedHeaderFields(array, true));
914
+ }
872
915
  if (isFieldNode(node)) {
873
916
  const whole = node.accessPath.length === 0 || (first && readsWholeArray(node.accessPath));
874
917
  return isRebuiltHeaderArray(node.name) && whole ? [node] : [];
@@ -900,10 +943,13 @@ function isRebuiltHeaderArray(name) {
900
943
  }
901
944
  /**
902
945
  * Warns about a read of the request header names or values in order, which
903
- * a challenge solve may get wrong. any(), all(), has_value() and len() do not
904
- * depend on it.
946
+ * a challenge solve may get wrong. has_value(), len(), and any() and all()
947
+ * over arrays that line up do not depend on it; see validateConditionPairing().
905
948
  */
906
949
  function pushHeaderOrderWarning(node, diagnostics, expression) {
950
+ // Reads can reach a field more than once, as an index on a call and the pairing of its arguments do.
951
+ if (diagnostics.some(diagnostic => diagnostic.id === 'field.header_order_unreliable' && diagnostic.pos === node.pos))
952
+ return;
907
953
  diagnostics.push({
908
954
  id: 'field.header_order_unreliable',
909
955
  params: { fieldExpression: expressionForNode(node, expression) },
@@ -954,38 +1000,103 @@ function validateFieldOrFunc(node, guardedHeaders, errors, diagnostics, expressi
954
1000
  }
955
1001
  validateSemanticNode(node, guardedHeaders, errors, diagnostics, expression, context, 'value');
956
1002
  }
957
- function validateFuncArgs(node, guardedHeaders, errors, diagnostics, expression, context) {
958
- for (const arg of node.args) {
1003
+ function validateFuncArgs(node, guardedHeaders, errors, diagnostics, expression, context, counted = false) {
1004
+ for (let index = 0; index < node.args.length; index++) {
1005
+ const arg = node.args[index];
959
1006
  if (isFieldNode(arg)) {
960
1007
  validateFieldNode(arg, guardedHeaders, errors, diagnostics, expression, context);
961
1008
  }
962
1009
  else if (isExpressionNode(arg)) {
963
- const position = isConditionArgument(arg) ? 'predicate' : 'value';
964
- validateSemanticNode(arg, guardedHeaders, errors, diagnostics, expression, context, position);
1010
+ validateSemanticNode(arg, guardedHeaders, errors, diagnostics, expression, context, argumentPosition(node, index, counted));
965
1011
  }
966
1012
  else if (arg.kind === 'ListRef') {
967
- validateFunctionListRefArg(node, arg, errors, diagnostics, context);
1013
+ validateListReference(arg, errors, diagnostics, context);
968
1014
  }
969
1015
  }
970
1016
  }
1017
+ /** Where a call's argument is, where `counted` says that len() only counts the arrays its arguments give. */
1018
+ function argumentPosition(node, index, counted) {
1019
+ const arg = node.args[index];
1020
+ if (isConditionArgument(arg))
1021
+ return 'argument';
1022
+ // len() takes one argument.
1023
+ if (!counted || (node.name === 'len' && index > 0))
1024
+ return 'value';
1025
+ return isFuncNode(arg) && (arg.name === 'coalesce' || arg.name === 'concat') && arg.accessPath.length === 0 ? 'counted' : 'value';
1026
+ }
971
1027
  function validateQuantifierPredicateArgs(node, guardedHeaders, errors, diagnostics, expression, context) {
972
- const quantifier = extractQuantifierPredicate(node);
973
- if (!quantifier) {
974
- const comparison = extractQuantifierComparison(node);
975
- if (comparison && !comparison.comparison.right) {
976
- validateFieldOrFunc(comparison.source, guardedHeaders, errors, diagnostics, expression, context);
1028
+ const reading = readQuantifierPredicate(node);
1029
+ switch (reading?.kind) {
1030
+ case 'conditions':
1031
+ // A comparison over each element is checked as the quantifier's own, a call with a result for each
1032
+ // element as a value, and any other condition as one that needs such results.
1033
+ for (const { node: condition } of quantifierPredicateConditions(reading.predicate)) {
1034
+ if (isArrayComparison(condition)) {
1035
+ validateQuantifierComparisonOperands(condition, guardedHeaders, errors, diagnostics, expression, context);
1036
+ }
1037
+ else if (isArrayCall(condition)) {
1038
+ validateFieldOrFunc(condition, guardedHeaders, errors, diagnostics, expression, context);
1039
+ }
1040
+ else {
1041
+ validateSemanticNode(condition, guardedHeaders, errors, diagnostics, expression, context, 'array-predicate');
1042
+ }
1043
+ }
977
1044
  return;
978
- }
979
- validateFuncArgs(node, guardedHeaders, errors, diagnostics, expression, context);
980
- return;
1045
+ case 'comparison':
1046
+ validateQuantifierComparisonOperands(reading.comparison, guardedHeaders, errors, diagnostics, expression, context);
1047
+ return;
1048
+ default:
1049
+ // A call read as a value is checked as any argument is.
1050
+ validateFuncArgs(node, guardedHeaders, errors, diagnostics, expression, context);
981
1051
  }
982
- validateFieldOrFunc(quantifier.source, guardedHeaders, errors, diagnostics, expression, context);
983
- if (isDynamicValueNode(quantifier.value)) {
984
- validateFieldOrFunc(quantifier.value, guardedHeaders, errors, diagnostics, expression, context);
1052
+ }
1053
+ /** Checks the operands of a comparison over each element of a quantifier's collection. */
1054
+ function validateQuantifierComparisonOperands(comparison, guardedHeaders, errors, diagnostics, expression, context) {
1055
+ validateFieldOrFunc(comparison.left, guardedHeaders, errors, diagnostics, expression, context);
1056
+ const value = comparison.right;
1057
+ if (isDynamicValueNode(value))
1058
+ validateFieldOrFunc(value, guardedHeaders, errors, diagnostics, expression, context);
1059
+ if (value?.kind === 'ListRef')
1060
+ validateListRef(value, comparison.left, comparison.op, errors, diagnostics, context);
1061
+ }
1062
+ /**
1063
+ * Warns when a call's conditions pair arrays whose elements may not line up:
1064
+ * a quantifier's predicate, or an argument read as a condition with a result
1065
+ * for each element. Cloudflare pairs them by index and stops at the shorter
1066
+ * one, so conditions on arrays from different lists rarely mean what they
1067
+ * say. Such pairs also depend on the order of each array, so the request
1068
+ * header names and values among them get the order warning, unless
1069
+ * `counted` says that len() only counts the results.
1070
+ */
1071
+ function validateConditionPairing(node, diagnostics, expression, counted) {
1072
+ for (const conditions of pairingConditions(node)) {
1073
+ const arrays = predicateArrays(conditions);
1074
+ const unaligned = unalignedArray(arrays);
1075
+ if (!unaligned)
1076
+ continue;
1077
+ diagnostics.push({
1078
+ id: 'array_expansion.unaligned_arrays',
1079
+ params: { functionName: node.name },
1080
+ severity: 'warning',
1081
+ pos: typeof unaligned.pos === 'number' ? unaligned.pos : null,
1082
+ length: typeof unaligned.length === 'number' ? unaligned.length : 0,
1083
+ source: 'expression',
1084
+ });
1085
+ if (counted)
1086
+ continue;
1087
+ for (const array of arrays) {
1088
+ for (const field of orderedHeaderFields(array, true))
1089
+ pushHeaderOrderWarning(field, diagnostics, expression);
1090
+ }
985
1091
  }
986
- if (quantifier.value.kind === 'ListRef') {
987
- validateFunctionListRefArg(node, quantifier.value, errors, diagnostics, context);
1092
+ }
1093
+ /** A call's conditions with a result for each element: a quantifier's predicate read as conditions, or such arguments. */
1094
+ function pairingConditions(node) {
1095
+ if (node.name === 'any' || node.name === 'all') {
1096
+ const reading = readQuantifierPredicate(node);
1097
+ return reading?.kind === 'conditions' && !isUncertainArgument(node, 0) ? [reading.predicate] : [];
988
1098
  }
1099
+ return node.args.filter((arg, index) => isArrayConditionArgument(arg) && !isUncertainArgument(node, index));
989
1100
  }
990
1101
  /** Reports arguments the function's signature rejects, and returns whether there were none. */
991
1102
  function validateFunctionArgRequirements(node, binding, errors, diagnostics) {
@@ -1042,7 +1153,7 @@ function validateFieldNode(node, guardedHeaders, errors, diagnostics, expression
1042
1153
  const fieldExpression = expression.slice(node.pos, node.pos + node.length);
1043
1154
  // has_key() looks the key up exactly, so it quotes the key as the access reads it. The map's keys are
1044
1155
  // lowercase, so it finds the header however the client spelled its name.
1045
- const guardExpression = `has_key(${node.name}, ${stringLiteralSource(mapKey.key)})`;
1156
+ const guardExpression = `has_key(${node.name}, ${renderRuleExpressionStringLiteral(mapKey.key)})`;
1046
1157
  diagnostics.push({
1047
1158
  id: 'field.header_index_requires_guard',
1048
1159
  params: { fieldExpression, guardExpression, headerName },
@@ -1104,7 +1215,7 @@ function validateMapKeyCase(node, errors, diagnostics) {
1104
1215
  });
1105
1216
  return false;
1106
1217
  }
1107
- function validateBoolFieldNode(node, errors, diagnostics, expression, context) {
1218
+ function validateBoolFieldNode(node, position, errors, diagnostics, expression, context) {
1108
1219
  // validateBooleanLiterals() reports `true` and `false`.
1109
1220
  if (isBooleanLiteralName(node.name))
1110
1221
  return;
@@ -1113,14 +1224,16 @@ function validateBoolFieldNode(node, errors, diagnostics, expression, context) {
1113
1224
  if (!isKnownFieldName(node.name))
1114
1225
  return;
1115
1226
  const type = fieldDataType(node.name);
1227
+ // A Boolean in any() or all() has its own error, as it has no result for each element.
1116
1228
  if (isUnknownRuleExpressionDataType(type) || isBooleanType(type))
1117
1229
  return;
1118
1230
  const actualType = formatRuleExpressionDataType(type);
1119
- const message = `field '${node.name}' must be Boolean in predicate position; received ${actualType}`;
1231
+ const expectedType = predicateType(position);
1232
+ const message = `field '${node.name}' must be ${expectedType} in predicate position; received ${actualType}`;
1120
1233
  errors.push(message);
1121
1234
  diagnostics.push({
1122
1235
  id: 'field.predicate_type_mismatch',
1123
- params: { fieldName: node.name, expectedType: 'Boolean', actualType },
1236
+ params: { fieldName: node.name, expectedType, actualType },
1124
1237
  severity: 'error',
1125
1238
  pos: typeof node.pos === 'number' ? node.pos : null,
1126
1239
  length: typeof node.length === 'number' ? node.length : 0,
@@ -1283,6 +1396,8 @@ function getHeaderPresenceGuardNames(node) {
1283
1396
  if (validateFunctionSignature(node, bindArguments(node)).length > 0)
1284
1397
  return new Set();
1285
1398
  switch (node.name) {
1399
+ case 'all':
1400
+ return getAllHeaderGuardNames(node);
1286
1401
  case 'any':
1287
1402
  return getQuantifierHeaderGuardNames(node);
1288
1403
  case 'has_key':
@@ -1294,26 +1409,63 @@ function getHeaderPresenceGuardNames(node) {
1294
1409
  }
1295
1410
  }
1296
1411
  function getQuantifierHeaderGuardNames(node) {
1297
- // Recovery from a syntax error may have cut the predicate short; see FuncNode.uncertainFrom.
1298
- if (isUncertainArgument(node, 0))
1299
- return new Set();
1300
- const comparison = extractQuantifierComparison(node);
1301
- if (!comparison)
1412
+ const predicate = node.args[0];
1413
+ if (!isExpressionNode(predicate))
1302
1414
  return new Set();
1303
- const collection = headerCollection(comparison.source);
1304
- // A value that meets the comparison, negated or not, whatever it compares with, proves the header has one.
1305
- if (collection?.kind === 'values')
1306
- return new Set([collection.header]);
1307
- if (collection?.kind !== 'names')
1415
+ // Recovery from a syntax error may have cut the predicate short, and without its `)`, more may follow;
1416
+ // see FuncNode.uncertainFrom. One read whole that joins conditions with `and` but without the parentheses
1417
+ // they need may end after its first condition instead, which guards in either reading, as the quantifier
1418
+ // then joins what follows with `and`. A comparison operator skipped before a first condition that is a
1419
+ // comparison lost no left side, as comparisons do not chain, and one that is not guards nothing.
1420
+ const uncertain = isUncertainArgument(node, 0);
1421
+ if (uncertain && (mayHaveMoreArguments(node) || predicate.kind !== 'And'))
1308
1422
  return new Set();
1309
- const value = comparison.comparison.right;
1310
- if (!value || comparison.negated)
1311
- return new Set();
1312
- if (comparison.op === 'eq' && value.kind === 'StringLiteral')
1313
- return new Set([guardHeaderName(value.value)]);
1314
- if (comparison.op === 'in' && value.kind === 'SetLiteral')
1315
- return new Set(stringLiteralValues(value).map(guardHeaderName));
1316
- return new Set();
1423
+ const conditions = quantifierPredicateConditions(predicate);
1424
+ const guards = new Set();
1425
+ for (const { node: condition, required } of uncertain ? conditions.slice(0, 1) : conditions) {
1426
+ if (!isArrayCondition(condition))
1427
+ continue;
1428
+ // any() is true only where every array in its predicate has an element, so a value of a header's own
1429
+ // proves it present, negated or not, whatever the condition makes of it.
1430
+ const collection = headerCollection(conditionArray(condition));
1431
+ const header = valuesGuardName(collection);
1432
+ if (header !== undefined)
1433
+ guards.add(header);
1434
+ else if (collection?.kind === 'names' && condition.kind === 'Comparison') {
1435
+ for (const name of nameComparisonGuardNames(condition, required))
1436
+ guards.add(name);
1437
+ }
1438
+ }
1439
+ return guards;
1440
+ }
1441
+ /**
1442
+ * The header all() proves present: the one whose own values a call read as a
1443
+ * value maps over, as all() is false where that call gives nil; see
1444
+ * QuantifierPredicateReading. Over conditions, all() holds where the header
1445
+ * is missing.
1446
+ */
1447
+ function getAllHeaderGuardNames(node) {
1448
+ // Recovery from a syntax error may have cut the argument short, so that the call is not all of it.
1449
+ const reading = isUncertainArgument(node, 0) ? null : readQuantifierPredicate(node);
1450
+ const header = reading?.kind === 'value' ? valuesGuardName(headerCollection(reading.predicate)) : undefined;
1451
+ return new Set(header === undefined ? [] : [header]);
1452
+ }
1453
+ /**
1454
+ * The header a comparison of the header names in an any() predicate proves
1455
+ * present: the one it equals, where the predicate holds only if the
1456
+ * comparison does.
1457
+ */
1458
+ function nameComparisonGuardNames(comparison, required) {
1459
+ if (!required)
1460
+ return [];
1461
+ const value = comparison.right;
1462
+ if (comparison.op === 'eq' && value?.kind === 'StringLiteral')
1463
+ return [guardHeaderName(value.value)];
1464
+ if (comparison.op !== 'in' || value?.kind !== 'SetLiteral')
1465
+ return [];
1466
+ // A set proves only that one of its names is present.
1467
+ const names = new Set(stringLiteralValues(value).map(guardHeaderName));
1468
+ return names.size === 1 ? [...names] : [];
1317
1469
  }
1318
1470
  /**
1319
1471
  * The header `has_key(http.request.headers, "x")` checks for, normalized by
@@ -1339,14 +1491,19 @@ function getHasValueHeaderGuardNames(node) {
1339
1491
  if (isUncertainArgument(node, 0))
1340
1492
  return new Set();
1341
1493
  const [collectionArgument, value] = node.args;
1342
- const collection = headerCollection(collectionArgument);
1343
1494
  // Whatever value is found among a header's values proves the header present, so only the names read it.
1344
- if (collection?.kind === 'values')
1345
- return new Set([collection.header]);
1495
+ const collection = headerCollection(collectionArgument);
1496
+ const header = valuesGuardName(collection);
1497
+ if (header !== undefined)
1498
+ return new Set([header]);
1346
1499
  if (collection?.kind !== 'names' || isUncertainArgument(node, 1) || !isStringLiteral(value))
1347
1500
  return new Set();
1348
1501
  return new Set([guardHeaderName(value.value)]);
1349
1502
  }
1503
+ /** The header whose own values a collection is (see headerCollection()), which an element of it proves present. */
1504
+ function valuesGuardName(collection) {
1505
+ return collection?.kind === 'values' ? collection.header : undefined;
1506
+ }
1350
1507
  /**
1351
1508
  * The request header collection a guard reads: one header's values, as
1352
1509
  * `http.request.headers["x"]` or `["x"][*]`, directly or through calls that
@@ -1372,24 +1529,6 @@ function headerCollection(node) {
1372
1529
  const [key, ...rest] = values.accessPath;
1373
1530
  return key?.kind === 'MapKeyAccess' && readsWholeArray(rest) ? { kind: 'values', header: guardHeaderName(key.key) } : null;
1374
1531
  }
1375
- /**
1376
- * The value under the calls that map over it and that `unwraps` accepts by
1377
- * name; null when one of them reads its result other than whole, as
1378
- * `lower(...)[0]` or an access that failed to parse does.
1379
- */
1380
- function unwrapMappedCalls(node, unwraps) {
1381
- let value = node;
1382
- while (isFuncNode(value) && unwraps(value.name) && inferFunctionInvocation(value).mapping === 'mapped') {
1383
- if (!readsWholeArray(value.accessPath))
1384
- return null;
1385
- value = value.args[0];
1386
- }
1387
- return value;
1388
- }
1389
- /** Whether an access path reads a whole array: no access, or `[*]`. */
1390
- function readsWholeArray(accessPath) {
1391
- return accessPath.length === 0 || (accessPath.length === 1 && accessPath[0].kind === 'ArrayWildcardAccess');
1392
- }
1393
1532
  /**
1394
1533
  * A header name as guards and the indexed accesses they guard compare it:
1395
1534
  * lowercased, as names keep the client's spelling and map keys are lowercase.