@libreflare/worker-runtime 0.10.4 → 0.10.6

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 (100) hide show
  1. package/README.md +101 -44
  2. package/dist/rule-evaluator/access-values.d.ts +42 -27
  3. package/dist/rule-evaluator/access-values.d.ts.map +1 -1
  4. package/dist/rule-evaluator/access-values.js +123 -52
  5. package/dist/rule-evaluator/access-values.js.map +1 -1
  6. package/dist/rule-evaluator/byte-strings.d.ts.map +1 -1
  7. package/dist/rule-evaluator/byte-strings.js +27 -11
  8. package/dist/rule-evaluator/byte-strings.js.map +1 -1
  9. package/dist/rule-evaluator/constants.d.ts +1 -1
  10. package/dist/rule-evaluator/constants.d.ts.map +1 -1
  11. package/dist/rule-evaluator/constants.js +8 -0
  12. package/dist/rule-evaluator/constants.js.map +1 -1
  13. package/dist/rule-evaluator/country-codes.generated.js +1 -1
  14. package/dist/rule-evaluator/diagnostics.d.ts +1 -1
  15. package/dist/rule-evaluator/diagnostics.d.ts.map +1 -1
  16. package/dist/rule-evaluator/diagnostics.js +10 -0
  17. package/dist/rule-evaluator/diagnostics.js.map +1 -1
  18. package/dist/rule-evaluator/edge-field-gaps.d.ts +6 -4
  19. package/dist/rule-evaluator/edge-field-gaps.d.ts.map +1 -1
  20. package/dist/rule-evaluator/edge-field-gaps.js +40 -42
  21. package/dist/rule-evaluator/edge-field-gaps.js.map +1 -1
  22. package/dist/rule-evaluator/edge-record.js +2 -0
  23. package/dist/rule-evaluator/edge-record.js.map +1 -1
  24. package/dist/rule-evaluator/engine-observations.d.ts +4 -4
  25. package/dist/rule-evaluator/engine-observations.d.ts.map +1 -1
  26. package/dist/rule-evaluator/engine-observations.generated.d.ts +533 -3
  27. package/dist/rule-evaluator/engine-observations.generated.d.ts.map +1 -1
  28. package/dist/rule-evaluator/engine-observations.generated.js +406 -248
  29. package/dist/rule-evaluator/engine-observations.generated.js.map +1 -1
  30. package/dist/rule-evaluator/engine-observations.js +1 -0
  31. package/dist/rule-evaluator/engine-observations.js.map +1 -1
  32. package/dist/rule-evaluator/explain.js +12 -9
  33. package/dist/rule-evaluator/explain.js.map +1 -1
  34. package/dist/rule-evaluator/field-availability.d.ts +6 -1
  35. package/dist/rule-evaluator/field-availability.d.ts.map +1 -1
  36. package/dist/rule-evaluator/field-availability.js +16 -4
  37. package/dist/rule-evaluator/field-availability.js.map +1 -1
  38. package/dist/rule-evaluator/field-descriptions.generated.d.ts +147 -5
  39. package/dist/rule-evaluator/field-descriptions.generated.d.ts.map +1 -1
  40. package/dist/rule-evaluator/field-descriptions.generated.js +345 -5
  41. package/dist/rule-evaluator/field-descriptions.generated.js.map +1 -1
  42. package/dist/rule-evaluator/fields.d.ts +0 -1
  43. package/dist/rule-evaluator/fields.d.ts.map +1 -1
  44. package/dist/rule-evaluator/fields.js +67 -8
  45. package/dist/rule-evaluator/fields.js.map +1 -1
  46. package/dist/rule-evaluator/function-availability.d.ts +7 -0
  47. package/dist/rule-evaluator/function-availability.d.ts.map +1 -1
  48. package/dist/rule-evaluator/function-availability.js +38 -0
  49. package/dist/rule-evaluator/function-availability.js.map +1 -1
  50. package/dist/rule-evaluator/function-descriptions.d.ts +12 -2
  51. package/dist/rule-evaluator/function-descriptions.d.ts.map +1 -1
  52. package/dist/rule-evaluator/function-descriptions.generated.d.ts +171 -4
  53. package/dist/rule-evaluator/function-descriptions.generated.d.ts.map +1 -1
  54. package/dist/rule-evaluator/function-descriptions.generated.js +1280 -98
  55. package/dist/rule-evaluator/function-descriptions.generated.js.map +1 -1
  56. package/dist/rule-evaluator/function-descriptions.js +3 -1
  57. package/dist/rule-evaluator/function-descriptions.js.map +1 -1
  58. package/dist/rule-evaluator/function-signature-validation.d.ts +13 -4
  59. package/dist/rule-evaluator/function-signature-validation.d.ts.map +1 -1
  60. package/dist/rule-evaluator/function-signature-validation.js +142 -28
  61. package/dist/rule-evaluator/function-signature-validation.js.map +1 -1
  62. package/dist/rule-evaluator/functions.d.ts +10 -6
  63. package/dist/rule-evaluator/functions.d.ts.map +1 -1
  64. package/dist/rule-evaluator/functions.js +550 -167
  65. package/dist/rule-evaluator/functions.js.map +1 -1
  66. package/dist/rule-evaluator/minifier.d.ts +9 -0
  67. package/dist/rule-evaluator/minifier.d.ts.map +1 -1
  68. package/dist/rule-evaluator/minifier.js +23 -0
  69. package/dist/rule-evaluator/minifier.js.map +1 -1
  70. package/dist/rule-evaluator/operators.d.ts.map +1 -1
  71. package/dist/rule-evaluator/operators.js +15 -6
  72. package/dist/rule-evaluator/operators.js.map +1 -1
  73. package/dist/rule-evaluator/parse-cache.d.ts +3 -1
  74. package/dist/rule-evaluator/parse-cache.d.ts.map +1 -1
  75. package/dist/rule-evaluator/parse-cache.js +4 -0
  76. package/dist/rule-evaluator/parse-cache.js.map +1 -1
  77. package/dist/rule-evaluator/parser.d.ts +7 -1
  78. package/dist/rule-evaluator/parser.d.ts.map +1 -1
  79. package/dist/rule-evaluator/parser.js +14 -0
  80. package/dist/rule-evaluator/parser.js.map +1 -1
  81. package/dist/rule-evaluator/quantifier.d.ts +19 -2
  82. package/dist/rule-evaluator/quantifier.d.ts.map +1 -1
  83. package/dist/rule-evaluator/quantifier.js +104 -12
  84. package/dist/rule-evaluator/quantifier.js.map +1 -1
  85. package/dist/rule-evaluator/replacement.d.ts +37 -0
  86. package/dist/rule-evaluator/replacement.d.ts.map +1 -0
  87. package/dist/rule-evaluator/replacement.js +54 -0
  88. package/dist/rule-evaluator/replacement.js.map +1 -0
  89. package/dist/rule-evaluator/rule-language-types.d.ts.map +1 -1
  90. package/dist/rule-evaluator/rule-language-types.js +5 -0
  91. package/dist/rule-evaluator/rule-language-types.js.map +1 -1
  92. package/dist/rule-evaluator/validation.d.ts +2 -1
  93. package/dist/rule-evaluator/validation.d.ts.map +1 -1
  94. package/dist/rule-evaluator/validation.js +250 -91
  95. package/dist/rule-evaluator/validation.js.map +1 -1
  96. package/dist/rule-evaluator/wildcard.d.ts +6 -3
  97. package/dist/rule-evaluator/wildcard.d.ts.map +1 -1
  98. package/dist/rule-evaluator/wildcard.js +10 -4
  99. package/dist/rule-evaluator/wildcard.js.map +1 -1
  100. package/package.json +1 -1
@@ -1,18 +1,41 @@
1
- import { EQUALITY_ORDERING_OPERATORS, isConditionArgument, isDynamicValueNode, unhandledNode, } from './ast.js';
2
- import { applyRuntimeAccessPath, isUnknownElement, PartialArrayValue, RuleMapValue, } from './access-values.js';
1
+ import { EQUALITY_ORDERING_OPERATORS, isConditionArgument, isDynamicValueNode, isExpressionNode, unhandledNode, } from './ast.js';
2
+ import { applyRuntimeAccessPath, inPlaceOf, isUnknownElement, listedElement, OptionalElement, PartialArrayValue, RuleMapValue, } from './access-values.js';
3
3
  import { byteLength, bytesToText, canonicalText, textToBytes } from './byte-strings.js';
4
4
  import { formatIpAddress, ipAddressOctets } from './custom-lists.js';
5
5
  import { resolveBoolField, resolveFieldNode } from './fields.js';
6
6
  import { hashInRange } from './hash-in-range.js';
7
7
  import { applyOp, compareOperands, findMatchingSetMember, literalValue, reachableSetMembers } from './operators.js';
8
8
  import { andOutcome, incomparable, isUnknown, known, negateOutcome, orOutcome, outcomeValue, unavailable, valueOutcome, xorOutcome, } from './outcome.js';
9
- import { conditionArray, extractQuantifierPredicate, givesNilForNilArgument, keepsPlacesWhenMapped, quantifierPredicateConditions, readQuantifierPredicate, unalignedArray, } from './quantifier.js';
9
+ import { conditionArray, extractQuantifierPredicate, givesNilForNilArgument, keepsPlacesWhenMapped, pairedArgumentArrays, quantifierPredicateConditions, readQuantifierPredicate, unalignedArray, } from './quantifier.js';
10
10
  import { removeQueryArgs } from './query-args.js';
11
+ import { expandReplacement, MAX_REPLACEMENT_REFERENCES, measureReplacement } from './replacement.js';
11
12
  import { urlDecode } from './url-decode.js';
12
13
  import { compileWildcard, wildcardCaptures } from './wildcard.js';
13
14
  import { collectionElementDataType, compareRuleExpressionDataTypes, formatRuleExpressionDataType, evaluatedValueType, inferFunctionInvocation, isArrayConditionArgument, } from './rule-language-types.js';
15
+ /**
16
+ * The most a call's result holds, over all its elements when it maps; see
17
+ * elementSize(). A request's URL and headers fit, while join(), replacements
18
+ * and a mapped concat() can make many megabytes of them, which Cloudflare
19
+ * gives whole. An array keeps the elements that fit, and the others are
20
+ * unknown. It bounds memory rather than accounting for it: what a call holds
21
+ * while it runs can be a few times as much.
22
+ */
23
+ const MAX_RESULT_SIZE = 512 * 1024;
24
+ /** The fewest characters an array element counts as: even an empty one takes memory, and an unknown one more. */
25
+ const MIN_ELEMENT_SIZE = 8;
26
+ /** The most elements concat() of arrays joins, whatever they hold, as its result shares their text. */
27
+ const MAX_CONCAT_ELEMENTS = MAX_RESULT_SIZE / MIN_ELEMENT_SIZE;
28
+ const RESULT_SIZE_REASON = `its result holds more than ${MAX_RESULT_SIZE} characters, counting each array element as at least ${MIN_ELEMENT_SIZE}`;
29
+ /** A result that holds more, which is not built; see tooLargeResult(). */
30
+ const TOO_LARGE = Symbol('too large');
31
+ /** How much the pieces of a result may hold where joining them can unite their bytes; see surelyTooLarge(). */
32
+ const MAX_JOINED_SIZE = MAX_RESULT_SIZE * 3;
14
33
  const UNRELIABLE_FUNCTION_REASONS = {
15
34
  bit_slice: 'packet bit slicing is not available in Worker request context',
35
+ hmac_md5: 'synchronous HMAC-MD5 is not available in this evaluator',
36
+ hmac_sha1: 'synchronous HMAC-SHA-1 is not available in this evaluator',
37
+ hmac_sha256: 'synchronous HMAC-SHA-256 is not available in this evaluator',
38
+ hmac_sha512: 'synchronous HMAC-SHA-512 is not available in this evaluator',
16
39
  is_jwt_present: 'Cloudflare API JWT token configurations are not available in Worker request context',
17
40
  is_jwt_valid: 'Cloudflare API JWT token configurations are not available in Worker request context',
18
41
  is_timed_hmac_valid_v0: 'synchronous HMAC validation is not available in this evaluator',
@@ -20,6 +43,7 @@ const UNRELIABLE_FUNCTION_REASONS = {
20
43
  sha1: 'synchronous SHA-1 hashing is not available in this evaluator',
21
44
  sha256: 'synchronous SHA-256 hashing is not available in this evaluator',
22
45
  sha512: 'synchronous SHA-512 hashing is not available in this evaluator',
46
+ sign_sigv4_hmac_sha256: 'synchronous SigV4 signing is not available in this evaluator',
23
47
  uuidv4: 'Cloudflare uuidv4() derives randomness from the source bytes and cannot be reproduced exactly here',
24
48
  };
25
49
  export function getUnreliableRuleExpressionFunctionReason(name) {
@@ -39,8 +63,8 @@ function evaluateRuntimeOperand(node, ctx) {
39
63
  * Narrows a value to a rule-language value. Only coalesce(), has_key(), and
40
64
  * postfix access read maps, and validation rejects maps anywhere else, so a
41
65
  * map here is unknown. So is a partly known array, which only any(), all(),
42
- * has_value(), len(), concat(), mapped functions and postfix access read in
43
- * part.
66
+ * has_value(), len(), concat(), filter(), mapped functions and postfix access
67
+ * read in part.
44
68
  */
45
69
  function ruleValue(evaluated) {
46
70
  if (isUnknown(evaluated))
@@ -95,15 +119,21 @@ export function evaluateComparison(node, ctx) {
95
119
  */
96
120
  export function evaluateCollection(fieldArg, ctx) {
97
121
  const evaluated = evaluateRuntimeOperand(fieldArg, ctx);
98
- const array = isUnknown(evaluated) ? evaluated : arrayElements(evaluated.value);
122
+ const array = isUnknown(evaluated) ? evaluated : arrayValue(evaluated.value);
99
123
  if (isUnknown(array))
100
124
  return array;
101
- const { elements, more } = array.value;
102
- const values = elements.flatMap(element => !isUnknownElement(element) && isCollectionValue(element.value) ? [element.value] : []);
103
- const unknown = elements.find(isUnknownElement) ?? more;
104
- if (!unknown)
105
- return known({ values });
106
- return known(elements.length === 0 ? { values, unknown, mayBeEmpty: true } : { values, unknown });
125
+ if (!(array.value instanceof PartialArrayValue))
126
+ return known({ values: array.value.filter(isCollectionValue) });
127
+ const { elements, more, shortest } = array.value;
128
+ const values = array.value.knownValues();
129
+ const optional = elements.flatMap(listed => listed instanceof OptionalElement && !isUnknownElement(listed.element) ? [listed.element.value] : []);
130
+ return known({
131
+ values: values.filter(isCollectionValue),
132
+ unknown: array.value.firstUnknown(),
133
+ optional: optional.filter(isCollectionValue),
134
+ mayHoldUnknown: more !== undefined || values.length + optional.length < elements.length,
135
+ mayBeEmpty: shortest === 0,
136
+ });
107
137
  }
108
138
  function isCollectionValue(value) {
109
139
  return typeof value === 'string' || typeof value === 'number';
@@ -195,30 +225,31 @@ function evaluateQuantifier(node, ctx) {
195
225
  const reading = readQuantifierPredicate(node);
196
226
  return reading ? evaluatePairedQuantifier(node, reading, ctx).outcome : false;
197
227
  }
198
- /** A value's elements, read as an array: nil has none, a scalar is one, and a map's are unknown. */
199
- function arrayElements(value) {
228
+ /** A value read as an array: nil has no elements, a scalar is one, and a map's are unknown. */
229
+ function arrayValue(value) {
200
230
  if (value instanceof RuleMapValue)
201
231
  return unavailable('a map value');
202
- if (value instanceof PartialArrayValue)
203
- return known({ elements: value.elements, more: value.more });
204
232
  if (value === null)
205
- return known({ elements: [] });
206
- return known({ elements: (Array.isArray(value) ? value : [value]).map(element => known(element)) });
233
+ return known([]);
234
+ return known(value instanceof PartialArrayValue || Array.isArray(value) ? value : [value]);
207
235
  }
208
- const NO_PAIRS = { arrays: new Map(), certain: 0, end: 0 };
236
+ const NO_PAIRS = { arrays: new Map(), end: 0, tailFrom: 0 };
209
237
  /**
210
238
  * Evaluates the collections of a predicate's conditions; see PairedArrays.
211
239
  * An empty one leaves no pairs, whatever the others hold, so the ones after
212
240
  * it are not read. `valueCall` is a quantifier's predicate read as a value,
213
- * which is no array when it gives nil.
241
+ * which is no array when it gives nil. `source` is an array that pairs with
242
+ * them.
214
243
  */
215
- function pairArrays(owner, predicate, ctx, valueCall) {
244
+ function pairArrays(owner, predicate, ctx, valueCall, source) {
245
+ const paired = source?.array;
246
+ if (paired && paired.length === 0 && !paired.more)
247
+ return NO_PAIRS;
216
248
  const arrays = new Map();
217
- let certain = Infinity;
218
- let end = Infinity;
219
- let longest = 0;
220
- let firstMore;
221
- let shortestMore;
249
+ let end = paired && !paired.more ? paired.length : Infinity;
250
+ let longest = paired ? paired.length : 0;
251
+ let shortest = paired;
252
+ let partial = paired?.unknownLength !== undefined;
222
253
  for (const { node: condition } of quantifierPredicateConditions(predicate)) {
223
254
  // Conditions that validation accepts have a result for each element at each comparison and call (see
224
255
  // isArrayCondition()), so their kind tells them.
@@ -230,35 +261,48 @@ function pairArrays(owner, predicate, ctx, valueCall) {
230
261
  giveWarnings(ctx, warnings);
231
262
  return { ...NO_PAIRS, nilCall: valueCall };
232
263
  }
233
- const array = pairedArray(owner, condition, evaluated, warnings, ctx);
264
+ const compare = condition.kind === 'Comparison' ? comparatorFor(owner, condition, ctx) : isTrueValue;
265
+ const array = pairedArray(evaluated, warnings, compare, ctx);
234
266
  if (array.length === 0 && !array.more)
235
267
  return NO_PAIRS;
236
268
  arrays.set(condition, array);
237
- if (array.length < certain) {
238
- certain = array.length;
239
- shortestMore = array.more;
240
- }
269
+ if (!shortest || array.shortest < shortest.shortest)
270
+ shortest = array;
241
271
  longest = Math.max(longest, array.length);
242
- if (array.more)
243
- firstMore ??= array.more;
244
- else
272
+ partial ||= array.unknownLength !== undefined;
273
+ if (!array.more)
245
274
  end = Math.min(end, array.length);
246
275
  }
247
276
  // Validation rejects a predicate that compares no collection.
248
- if (arrays.size === 0)
277
+ if (!shortest || arrays.size === 0)
249
278
  return NO_PAIRS;
250
- const tail = end === Infinity ? firstMore : undefined;
279
+ if (!partial)
280
+ return { arrays, end, tailFrom: end };
281
+ const all = paired ? [paired, ...arrays.values()] : [...arrays.values()];
282
+ const tail = end === Infinity ? all[0].more : undefined;
251
283
  if (end === Infinity)
252
284
  end = longest;
253
- // A collection that may hold more has its known elements at positions it cannot tell, unless every
254
- // collection describes the same items.
255
- if (firstMore && !describeSameItems(arrays, certain)) {
256
- for (const array of arrays.values()) {
257
- if (array.more)
258
- array.elements = Array(array.length).fill(array.more);
259
- }
285
+ if (describeSameItems(arrays, source)) {
286
+ // Each index pairs the elements of one item, which the collections have or lack together.
287
+ const [{ elements, length, shortest: certain }] = all;
288
+ const missing = certain < length ? (index) => missingReason(elements[index]) : undefined;
289
+ return { arrays, end, missing, tail, tailFrom: Math.min(...all.map(array => array.moreFrom ?? array.length)) };
290
+ }
291
+ // Past its leading elements, a collection that may lack or hold others has its elements at positions it cannot
292
+ // tell, but for the last, which is the only one that can be at the last position when it lists them all.
293
+ for (const array of all) {
294
+ const { leading = array.length, more, unknownLength } = array;
295
+ if (!unknownLength)
296
+ continue;
297
+ const last = more ? -1 : array.length - 1;
298
+ array.elements = array.elements.map((listed, index) => index < leading || index === last ? listed : unknownLength);
260
299
  }
261
- return { arrays, certain, end, shortestMore, tail };
300
+ const { shortest: certain, unknownLength } = shortest;
301
+ return { arrays, end, missing: index => index < certain ? undefined : unknownLength, tail, tailFrom: end };
302
+ }
303
+ /** Why an array may lack an element it lists, when it may. */
304
+ function missingReason(listed) {
305
+ return listed instanceof OptionalElement ? listed.reason : undefined;
262
306
  }
263
307
  /**
264
308
  * Evaluates any() or all() as Cloudflare does, over the pairs of its
@@ -268,12 +312,12 @@ function pairArrays(owner, predicate, ctx, valueCall) {
268
312
  export function evaluatePairedQuantifier(node, reading, ctx) {
269
313
  const settling = node.name === 'any';
270
314
  const { predicate } = reading;
271
- const { arrays, certain, end, shortestMore, tail, nilCall } = pairArrays(node, predicate, ctx, reading.kind === 'value' ? reading.predicate : undefined);
315
+ const { arrays, end, missing, tail, nilCall } = pairArrays(node, predicate, ctx, reading.kind === 'value' ? reading.predicate : undefined);
272
316
  // A call read as a value that gives nil is no array, which neither any() nor all() holds for; see
273
317
  // QuantifierPredicateReading.
274
318
  if (nilCall)
275
319
  return { outcome: false, paired: 0, mayLackSome: false, mayHaveMore: false, nilCall };
276
- const result = (outcome) => ({ outcome, paired: end, mayLackSome: end > certain, mayHaveMore: tail !== undefined });
320
+ const result = (outcome) => ({ outcome, paired: end, mayLackSome: firstMissing(end, missing) !== undefined, mayHaveMore: tail !== undefined });
277
321
  // The unknown outcomes of known elements, from every position, and the first outcome that reads an unknown
278
322
  // element, which is combined after them, so that an unknown comparison value, which applies at every
279
323
  // element, names the cause before one element does.
@@ -281,14 +325,12 @@ export function evaluatePairedQuantifier(node, reading, ctx) {
281
325
  let pending;
282
326
  for (let index = 0; index < end; index++) {
283
327
  let outcome = pairedOutcome(predicate, index, arrays);
284
- if (index >= certain) {
285
- // The shortest collection may end before this position, so it may hold no pair. It may hold more, or
286
- // the pairs would end at `certain`. One that settles the result settles it only if the pair is there.
287
- if (outcome === settling)
288
- outcome = shortestMore;
289
- }
290
- else if (outcome === settling) {
291
- return result(outcome);
328
+ if (outcome === settling) {
329
+ // One that may be missing settles the result only if it is there.
330
+ const reason = missing?.(index);
331
+ if (!reason)
332
+ return result(outcome);
333
+ outcome = reason;
292
334
  }
293
335
  if (typeof outcome === 'function')
294
336
  pending ??= outcome;
@@ -306,71 +348,108 @@ export function evaluatePairedQuantifier(node, reading, ctx) {
306
348
  /**
307
349
  * Evaluates a function argument read as a condition with a result for each
308
350
  * element: the array of its results, at the pairs of its collections (see
309
- * PairedArrays), with none over nil. An unknown result keeps its place, and
310
- * when the shortest collection may hold more, so may the array, which lists
311
- * the results that may follow when it knows them all.
351
+ * PairedArrays), with none over nil. An unknown result keeps its place.
312
352
  */
313
353
  function evaluateConditionArray(node, ctx) {
314
- const pairing = pairArrays(node, node, ctx);
315
- const { arrays, certain, end, tail } = pairing;
316
- // Past `certain`, the shortest collection may end at any position, so a result there may be missing, and
317
- // unless more may follow `end`, those are the only results that may follow.
318
- const count = tail ? certain : end;
319
- const results = [];
320
- for (let index = 0; index < count; index++)
321
- results.push(resultElement(node, index, arrays, ctx));
322
- return known(PartialArrayValue.from(results.slice(0, certain), moreResults(pairing), tail ? undefined : results.slice(certain)));
354
+ const { arrays, end, missing, tail, tailFrom } = pairArrays(node, node, ctx);
355
+ const results = resultElements(node, end, arrays, ctx);
356
+ return known(PartialArrayValue.from(missing ? results.map((result, index) => optionalElement(result, missing(index))) : results, tail, tailFrom));
357
+ }
358
+ /** An element that the array may lack for a reason, when there is one. */
359
+ function optionalElement(element, reason) {
360
+ return reason ? new OptionalElement(element, reason) : element;
323
361
  }
324
362
  /** The number of results evaluateConditionArray() gives, which reads none of them. */
325
363
  function countConditionResults(node, ctx) {
326
- const pairing = pairArrays(node, node, ctx);
327
- return moreResults(pairing)?.() ?? known(pairing.certain);
364
+ const { end, missing, tail } = pairArrays(node, node, ctx);
365
+ return (firstMissing(end, missing) ?? tail)?.() ?? known(end);
328
366
  }
329
- /** Why a condition argument may have more results than `certain`: the shortest collection may hold more. */
330
- function moreResults({ certain, end, shortestMore, tail }) {
331
- return certain < end || tail ? shortestMore : undefined;
367
+ /** Why the first pair that may be missing may be, when one may. */
368
+ function firstMissing(end, missing) {
369
+ if (!missing)
370
+ return undefined;
371
+ for (let index = 0; index < end; index++) {
372
+ const reason = missing(index);
373
+ if (reason)
374
+ return reason;
375
+ }
376
+ return undefined;
332
377
  }
333
378
  /**
334
- * The result at an index as an element of the array of results. One that is
335
- * not known settles nothing, and tells why only when read, as an unknown
336
- * element does.
379
+ * The results at the first `count` indexes as elements of the array of
380
+ * results. One that is not known settles nothing, and tells why only when
381
+ * read, as an unknown element does. Results unknown for one cause, as where
382
+ * they compare with an unknown value, share an element, as there can be
383
+ * thousands.
337
384
  */
338
- function resultElement(node, index, arrays, ctx) {
339
- const { result: outcome, warnings } = collectWarnings(ctx, () => pairedOutcome(node, index, arrays));
340
- if (typeof outcome !== 'boolean') {
341
- return deferWarnings(ctx, warnings, () => outcomeValue(typeof outcome === 'function' ? outcome() : outcome));
385
+ function resultElements(node, count, arrays, ctx) {
386
+ const results = [];
387
+ let last;
388
+ for (let index = 0; index < count; index++) {
389
+ const { result: outcome, warnings } = collectWarnings(ctx, () => pairedOutcome(node, index, arrays));
390
+ if (typeof outcome === 'boolean') {
391
+ giveWarnings(ctx, warnings);
392
+ results.push(known(outcome));
393
+ continue;
394
+ }
395
+ const cause = typeof outcome === 'function' ? outcome : outcome.cause;
396
+ if (last?.cause !== cause || !sameWarnings(last.warnings, warnings)) {
397
+ const read = () => outcomeValue(typeof outcome === 'function' ? outcome() : outcome);
398
+ last = { cause, warnings, element: deferWarnings(ctx, warnings, read) };
399
+ }
400
+ results.push(last.element);
342
401
  }
343
- giveWarnings(ctx, warnings);
344
- return known(outcome);
402
+ return results;
403
+ }
404
+ function sameWarnings(left, right) {
405
+ return left.length === right.length && left.every((warning, index) => warning === right[index]);
345
406
  }
346
407
  /**
347
408
  * Whether a predicate's collections describe the same item at each index:
348
- * they come from one list (see pairedArrayList()), and each holds `length`
349
- * elements. An element dropped, as a mapped call's nil result, or added, as
350
- * a Set-Cookie value repeated past a cut header list, changes the length.
409
+ * they come from one list (see pairedArrayList()), and list as many elements,
410
+ * and may lack the same ones. An element dropped, as a mapped call's nil
411
+ * result, or added, as a Set-Cookie value repeated past a cut header list,
412
+ * changes how many there are.
351
413
  */
352
- function describeSameItems(arrays, length) {
353
- for (const array of arrays.values()) {
354
- if (array.length !== length)
414
+ function describeSameItems(arrays, source) {
415
+ if (arrays.size === 1 && !source)
416
+ return true;
417
+ const nodes = [...arrays.keys()].map(conditionArray);
418
+ const all = [...arrays.values()];
419
+ if (source) {
420
+ nodes.push(...pairedArgumentArrays(source.node));
421
+ all.push(source.array);
422
+ }
423
+ const [first] = all;
424
+ for (const { elements, length, shortest } of all) {
425
+ if (length !== first.length || shortest !== first.shortest)
426
+ return false;
427
+ if (shortest === length)
428
+ continue;
429
+ if (elements.some((listed, index) => (listed instanceof OptionalElement) !== (first.elements[index] instanceof OptionalElement)))
355
430
  return false;
356
431
  }
357
- return !unalignedArray([...arrays.keys()].map(conditionArray));
358
- }
359
- /** A condition's array, from its evaluated collection and the warnings evaluating it gave. */
360
- function pairedArray(owner, condition, evaluated, warnings, ctx) {
361
- // A call's result holds at an element where it is true.
362
- const compare = condition.kind === 'Comparison' ? comparatorFor(owner, condition, ctx) : (value) => value === true;
363
- if (!isUnknown(evaluated) && Array.isArray(evaluated.value)) {
364
- giveWarnings(ctx, warnings);
365
- return { values: evaluated.value, elements: [], length: evaluated.value.length, compare };
432
+ return !unalignedArray(nodes);
433
+ }
434
+ /** Whether a call's result holds at an element: where it is true. */
435
+ function isTrueValue(value) {
436
+ return value === true;
437
+ }
438
+ /** A condition's array, or a PairedSource's, from its evaluated collection and the warnings evaluating it gave. */
439
+ function pairedArray(evaluated, warnings, compare, ctx) {
440
+ const array = isUnknown(evaluated) ? evaluated : arrayValue(evaluated.value);
441
+ if (isUnknown(array)) {
442
+ // A collection unknown whole tells why only when read, since the other collections may settle the result.
443
+ const more = deferWarnings(ctx, warnings, () => array);
444
+ return { values: undefined, elements: [], length: 0, shortest: 0, more, unknownLength: more, compare };
366
445
  }
367
- const array = isUnknown(evaluated) ? evaluated : arrayElements(evaluated.value);
368
- // A collection unknown whole tells why only when read, since the other collections may settle the result.
369
- if (isUnknown(array))
370
- return { values: undefined, elements: [], length: 0, more: deferWarnings(ctx, warnings, () => array), compare };
371
446
  giveWarnings(ctx, warnings);
372
- const { elements, more } = array.value;
373
- return { values: undefined, elements, length: elements.length, more, compare };
447
+ if (!(array.value instanceof PartialArrayValue)) {
448
+ const { length } = array.value;
449
+ return { values: array.value, elements: [], length, shortest: length, compare };
450
+ }
451
+ const { elements, shortest, more, moreFrom, leading, unknownLength } = array.value;
452
+ return { values: undefined, elements, length: elements.length, shortest, more, moreFrom, leading, unknownLength, compare };
374
453
  }
375
454
  /**
376
455
  * Runs `compute` with warnings of its own, to give when its result is read:
@@ -392,6 +471,16 @@ function giveWarnings(ctx, warnings) {
392
471
  for (const warning of warnings)
393
472
  ctx.warnings.add(warning);
394
473
  }
474
+ /** Takes from ctx, into `into`, the warnings it was given after its first `given`. */
475
+ function takeWarnings(ctx, given, into) {
476
+ let index = 0;
477
+ for (const warning of ctx.warnings) {
478
+ if (index++ < given)
479
+ continue;
480
+ into.add(warning);
481
+ ctx.warnings.delete(warning);
482
+ }
483
+ }
395
484
  /** An unknown value that gives its warnings only when read, as an unknown element does. */
396
485
  function deferWarnings(ctx, warnings, read) {
397
486
  return () => {
@@ -428,9 +517,13 @@ function elementOutcome(array, index) {
428
517
  // A collection known whole holds no more, so it reaches every position read.
429
518
  if (array.values)
430
519
  return array.compare(array.values[index]);
431
- const element = array.elements[index] ?? array.more;
520
+ const element = elementAt(array, index);
432
521
  return isUnknownElement(element) ? element : array.compare(element.value);
433
522
  }
523
+ /** The element at an index of a collection known in part, unknown where it lists none. */
524
+ function elementAt(array, index) {
525
+ return index < array.length ? listedElement(array.elements[index]) : array.more;
526
+ }
434
527
  /** Combines operands at an index, stopping at the first known one that decides the result, if any does. */
435
528
  function combinePairedOutcomes(operands, deciding, combine, index, arrays) {
436
529
  const outcomes = [];
@@ -496,10 +589,41 @@ export function evaluateFuncValue(node, ctx) {
496
589
  const evaluated = invocation.mapping === 'mapped'
497
590
  ? evaluateFuncArray(node, ctx, invocation)
498
591
  : evaluateDirectFuncValue(node, ctx, invocation);
592
+ if (evaluated === TOO_LARGE)
593
+ return tooLargeResult(ctx, node.name);
499
594
  if (isUnknown(evaluated))
500
595
  return evaluated;
596
+ // Only concat() and mapped calls can make an array too large, and they count it as they get its elements.
597
+ if (typeof evaluated.value === 'string' && evaluated.value.length > MAX_RESULT_SIZE)
598
+ return tooLargeResult(ctx, node.name);
501
599
  return applyRuntimeAccessPath(evaluated.value, node.accessPath);
502
600
  }
601
+ /** How many characters an array element counts as. An unknown one is not read, as reading it warns. */
602
+ function elementSize(element) {
603
+ return isUnknownElement(element) ? MIN_ELEMENT_SIZE : valueSize(element.value);
604
+ }
605
+ function valueSize(value) {
606
+ let size = 0;
607
+ if (typeof value === 'string')
608
+ size = value.length;
609
+ else if (Array.isArray(value))
610
+ for (const element of value)
611
+ size += valueSize(element);
612
+ return Math.max(size, MIN_ELEMENT_SIZE);
613
+ }
614
+ /**
615
+ * Whether a result joined from pieces that hold `size` characters in all is
616
+ * surely too large. Joining text can unite bytes into characters, which leaves
617
+ * a third of their number at least, so where a piece is text with such bytes,
618
+ * only a result past MAX_JOINED_SIZE surely is.
619
+ */
620
+ function surelyTooLarge(size, ...pieces) {
621
+ if (size <= MAX_RESULT_SIZE)
622
+ return false;
623
+ if (size > MAX_JOINED_SIZE)
624
+ return true;
625
+ return !pieces.some(list => list.some(piece => typeof piece === 'string' && !piece.isWellFormed()));
626
+ }
503
627
  /**
504
628
  * Evaluates a call on its arguments, or one that maps on one element:
505
629
  * `element` is then its first argument, and `later` keeps the arguments
@@ -520,16 +644,12 @@ function evaluateDirectFuncValue(node, ctx, invocation, later, element = null) {
520
644
  case 'any':
521
645
  return outcomeValue(evaluateQuantifier(node, ctx));
522
646
  case 'concat': {
523
- const parts = [];
524
- for (let index = 0; index < args.length; index++) {
525
- const part = runtimeArgument(index);
526
- if (isUnknown(part))
527
- return part;
528
- parts.push(part.value);
529
- }
647
+ const parts = readConcatArguments(args.length, runtimeArgument, read, () => tooLargeResult(ctx, name));
648
+ if (parts === TOO_LARGE || isUnknown(parts))
649
+ return parts;
530
650
  // An array known in part keeps its known elements, as any() and all() read them.
531
- if (parts.some(part => part instanceof PartialArrayValue))
532
- return concatElements(parts, invocation.argumentTypes);
651
+ if (parts.value.some(part => part instanceof PartialArrayValue))
652
+ return concatElements(parts.value, invocation.argumentTypes);
533
653
  break;
534
654
  }
535
655
  case 'coalesce':
@@ -540,6 +660,8 @@ function evaluateDirectFuncValue(node, ctx, invocation, later, element = null) {
540
660
  return value;
541
661
  }
542
662
  return known(null);
663
+ case 'filter':
664
+ return later ? filterValues(element, argument(1)) : evaluateFilter(node, ctx);
543
665
  case 'has_key': {
544
666
  // A nil key gives nil without reading the map, as Cloudflare documents.
545
667
  const key = argument(1);
@@ -558,7 +680,7 @@ function evaluateDirectFuncValue(node, ctx, invocation, later, element = null) {
558
680
  return collection;
559
681
  // A partly known array's known elements can settle it, as they do any().
560
682
  const partial = collection.value instanceof PartialArrayValue ? collection.value : undefined;
561
- const values = partial ? known(partial.knownValues().values) : ruleValue(collection);
683
+ const values = partial ? known(partial.knownValues()) : ruleValue(collection);
562
684
  if (isUnknown(values))
563
685
  return values;
564
686
  const value = argument(1);
@@ -578,9 +700,9 @@ function evaluateDirectFuncValue(node, ctx, invocation, later, element = null) {
578
700
  const source = runtimeArgument(0);
579
701
  if (isUnknown(source))
580
702
  return source;
581
- // Unknown elements keep their places, so only more that may follow leaves the length unknown.
703
+ // Unknown elements keep their places, so only elements it may lack or not list leave the length unknown.
582
704
  if (source.value instanceof PartialArrayValue)
583
- return source.value.more?.() ?? known(source.value.elements.length);
705
+ return source.value.unknownLength?.() ?? known(source.value.elements.length);
584
706
  const value = ruleValue(source);
585
707
  return isUnknown(value) ? value : known(lengthOfValue(value.value));
586
708
  }
@@ -588,6 +710,18 @@ function evaluateDirectFuncValue(node, ctx, invocation, later, element = null) {
588
710
  return lookupJsonValue('integer', args.length, argument);
589
711
  case 'lookup_json_string':
590
712
  return lookupJsonValue('string', args.length, argument);
713
+ case 'hmac_md5':
714
+ case 'hmac_sha1':
715
+ case 'hmac_sha256':
716
+ case 'hmac_sha512': {
717
+ // A nil message or key gives nil, as Cloudflare documents, so the other one's warnings do not apply.
718
+ const { result: values, warnings } = collectWarnings(ctx, () => [argument(0), argument(1)]);
719
+ const nil = values.find(value => !isUnknown(value) && value.value === null);
720
+ if (nil)
721
+ return nil;
722
+ giveWarnings(ctx, warnings);
723
+ return unreliableFunction(ctx, name);
724
+ }
591
725
  case 'bit_slice':
592
726
  case 'is_jwt_present':
593
727
  case 'is_jwt_valid':
@@ -596,6 +730,7 @@ function evaluateDirectFuncValue(node, ctx, invocation, later, element = null) {
596
730
  case 'sha1':
597
731
  case 'sha256':
598
732
  case 'sha512':
733
+ case 'sign_sigv4_hmac_sha256':
599
734
  case 'uuidv4':
600
735
  return unreliableFunction(ctx, name);
601
736
  }
@@ -608,7 +743,9 @@ function evaluateDirectFuncValue(node, ctx, invocation, later, element = null) {
608
743
  values.push(value.value);
609
744
  }
610
745
  const value = functionResult(name, values, invocation);
611
- return value === undefined ? unavailable(functionSource(name)) : known(canonicalResult(value));
746
+ if (value === undefined)
747
+ return unavailable(functionSource(name));
748
+ return value === TOO_LARGE ? value : known(canonicalResult(value));
612
749
  }
613
750
  /**
614
751
  * Puts each string of a result in the one form byte-strings.ts gives its
@@ -647,9 +784,13 @@ function functionResult(name, values, invocation) {
647
784
  return decodeBase64Value(at(0));
648
785
  case 'encode_base64':
649
786
  return encodeBase64Value(at(0), at(1));
787
+ case 'encode_hex':
788
+ return encodeHexValue(at(0));
650
789
  case 'ends_with':
651
790
  case 'starts_with':
652
791
  return matchesAffix(name, at(0), at(1));
792
+ case 'format_date':
793
+ return formatDate(at(0), at(1));
653
794
  case 'join':
654
795
  return joinValues(at(0), at(1));
655
796
  case 'lower':
@@ -686,10 +827,13 @@ function evaluateFuncArray(node, ctx, invocation) {
686
827
  // Over nil, such as a missing header's values, the call gives nil, not an empty array.
687
828
  if (!isUnknown(source) && source.value === null)
688
829
  return source;
689
- const array = isUnknown(source) ? source : arrayElements(source.value);
830
+ const array = isUnknown(source) ? source : arrayValue(source.value);
690
831
  if (isUnknown(array))
691
832
  return array;
692
- const { elements, more } = array.value;
833
+ const { value } = array;
834
+ const { elements, more, moreFrom } = value instanceof PartialArrayValue
835
+ ? value
836
+ : { elements: value.map(element => known(element)), more: undefined, moreFrom: value.length };
693
837
  const later = [];
694
838
  // A nil later argument gives every element nil, unknown ones too, so the call gives an empty array.
695
839
  if ((elements.length > 0 || more) && givesNilForNilArgument(node.name)) {
@@ -702,26 +846,75 @@ function evaluateFuncArray(node, ctx, invocation) {
702
846
  }
703
847
  }
704
848
  let keepsPlaces = keepsPlacesWhenMapped(node.name);
849
+ const tooLarge = () => tooLargeResult(ctx, node.name);
850
+ const evaluate = (element) => {
851
+ const direct = evaluateDirectFuncValue(node, ctx, invocation, later, element);
852
+ return direct === TOO_LARGE ? direct : ruleValue(direct);
853
+ };
854
+ // Elements it may lack leave the others their whole budget. Those, and unknown results kept in place, warn only
855
+ // when read. The first may have read a later argument for all, so they share their warnings.
856
+ let size = 0;
857
+ let optionalSize = 0;
858
+ let deferredWarnings;
859
+ let resultsFrom = 0;
705
860
  const results = [];
706
- for (const element of elements) {
861
+ for (let index = 0; index < elements.length; index++) {
862
+ const listed = elements[index];
863
+ const optional = listed instanceof OptionalElement;
864
+ const element = listedElement(listed);
865
+ // The results that fit can still settle what reads them, so the ones past them are unknown elements.
866
+ let result = tooLarge;
707
867
  if (isUnknownElement(element)) {
708
- results.push(element);
709
- continue;
868
+ result = element;
710
869
  }
711
- const result = ruleValue(evaluateDirectFuncValue(node, ctx, invocation, later, element.value));
712
- if (isUnknown(result))
713
- return result;
714
- if (result.value !== null)
715
- results.push(result);
716
- // A listed function that gives nil after all may for an unknown element too.
717
- else
718
- keepsPlaces = false;
870
+ else if ((optional ? optionalSize : size) <= MAX_RESULT_SIZE) {
871
+ let evaluated;
872
+ if (optional) {
873
+ const collected = collectWarnings(ctx, () => evaluate(element.value));
874
+ evaluated = collected.result;
875
+ deferredWarnings ??= new Set();
876
+ for (const warning of collected.warnings)
877
+ deferredWarnings.add(warning);
878
+ }
879
+ else {
880
+ const given = ctx.warnings.size;
881
+ evaluated = evaluate(element.value);
882
+ if (keepsPlaces && evaluated !== TOO_LARGE && isUnknown(evaluated))
883
+ takeWarnings(ctx, given, (deferredWarnings ??= new Set()));
884
+ }
885
+ if (evaluated !== TOO_LARGE) {
886
+ if (isUnknown(evaluated)) {
887
+ const unknown = evaluated;
888
+ result = deferWarnings(ctx, deferredWarnings ?? [], () => unknown);
889
+ // A function that gives every element a result keeps an unknown one in place; otherwise the call is unknown.
890
+ if (!optional && !keepsPlaces)
891
+ return result();
892
+ }
893
+ else if (evaluated.value === null) {
894
+ // A listed function that gives nil after all may for an unknown element too.
895
+ keepsPlaces = false;
896
+ continue;
897
+ }
898
+ else {
899
+ result = evaluated;
900
+ }
901
+ }
902
+ }
903
+ const total = optional ? (optionalSize += elementSize(result)) : (size += elementSize(result));
904
+ if (total > MAX_RESULT_SIZE)
905
+ result = tooLarge;
906
+ results.push(inPlaceOf(listed, result));
907
+ if (index < moreFrom)
908
+ resultsFrom = results.length;
719
909
  }
720
910
  if (keepsPlaces)
721
- return known(PartialArrayValue.from(results, more));
722
- // An unknown element may give nil, which drops it, so it leaves its place and the later ones unknown.
723
- const knownResults = results.filter(result => !isUnknownElement(result));
724
- return known(PartialArrayValue.from(knownResults, results.find(isUnknownElement) ?? more));
911
+ return known(PartialArrayValue.from(results, more, resultsFrom));
912
+ // An unknown element may give nil, which drops it.
913
+ const droppable = results.map(listed => {
914
+ const element = listedElement(listed);
915
+ return isUnknownElement(element) ? new OptionalElement(element, element) : listed;
916
+ });
917
+ return known(PartialArrayValue.from(droppable, more, resultsFrom));
725
918
  }
726
919
  function evaluateArgValue(arg, ctx) {
727
920
  // An omitted optional argument is null, which functions treat as absent.
@@ -797,6 +990,47 @@ function nonValueArgumentSource(arg) {
797
990
  return `list '$${arg.name}'`;
798
991
  return 'an inline list';
799
992
  }
993
+ /**
994
+ * Evaluates filter(): its array's elements at the positions where its
995
+ * conditions hold, as Cloudflare pairs them by index and stops at the shorter
996
+ * array. An unknown condition may keep its element or not, so the result may
997
+ * lack it, as it may one whose position an array may lack. Validation rejects
998
+ * arguments that may be nil.
999
+ */
1000
+ function evaluateFilter(node, ctx) {
1001
+ const [arrayNode, predicate] = node.args;
1002
+ // No field is an array of Booleans, so only a condition or a call gives one.
1003
+ if (!isExpressionNode(predicate))
1004
+ return unavailable(functionSource(node.name));
1005
+ const { result: evaluated, warnings } = collectWarnings(ctx, () => evaluateArgValue(arrayNode, ctx));
1006
+ const array = pairedArray(evaluated, warnings, isTrueValue, ctx);
1007
+ const { arrays, end, missing, tail, tailFrom } = pairArrays(predicate, predicate, ctx, undefined, { node: arrayNode, array });
1008
+ const kept = [];
1009
+ let keptFrom = 0;
1010
+ resultElements(predicate, end, arrays, ctx).forEach((result, index) => {
1011
+ const unknown = isUnknownElement(result);
1012
+ if (!unknown && result.value !== true)
1013
+ return;
1014
+ const element = array.values ? known(array.values[index]) : elementAt(array, index);
1015
+ kept.push(optionalElement(element, unknown ? result : missing?.(index)));
1016
+ if (index < tailFrom)
1017
+ keptFrom = kept.length;
1018
+ });
1019
+ return known(PartialArrayValue.from(kept, tail, keptFrom));
1020
+ }
1021
+ /**
1022
+ * Evaluates filter() on one element of the arrays it maps over. An unknown
1023
+ * condition leaves the whole call unknown, its length too, as an unknown later
1024
+ * argument leaves any call that maps, even where the element does not reach
1025
+ * it: no list lines up with each of the arrays, so such a call gets a warning
1026
+ * anyway.
1027
+ */
1028
+ function filterValues(array, conditions) {
1029
+ if (isUnknown(conditions))
1030
+ return conditions;
1031
+ const { value } = conditions;
1032
+ return known(Array.isArray(array) && Array.isArray(value) ? array.filter((_, index) => value[index] === true) : []);
1033
+ }
800
1034
  /** Returns nil (null) for a nil collection or value, as Cloudflare documents. */
801
1035
  function evaluateHasValue(collection, value) {
802
1036
  if (collection === null || value === null)
@@ -813,6 +1047,63 @@ function matchesAffix(name, value, affix) {
813
1047
  ? String(value).startsWith(String(affix))
814
1048
  : String(value).endsWith(String(affix));
815
1049
  }
1050
+ /**
1051
+ * Reads the arguments of concat() until one is unknown, or the result is
1052
+ * surely too large; arrays end after the elements that fit. Those that arrays
1053
+ * may lack have a budget of their own, as sharing the others' would make the
1054
+ * result depend on the order of the arguments, and arrays do not list those
1055
+ * past it: the result can do without. `read`, which keeps the arguments, loses
1056
+ * them too.
1057
+ */
1058
+ function readConcatArguments(count, argument, read, tooLarge) {
1059
+ const parts = [];
1060
+ let size = 0;
1061
+ let limit = MAX_RESULT_SIZE;
1062
+ let elementCount = 0;
1063
+ let optionalCount = 0;
1064
+ for (let index = 0; index < count; index++) {
1065
+ const part = argument(index);
1066
+ if (isUnknown(part))
1067
+ return part;
1068
+ let { value } = part;
1069
+ if (value instanceof PartialArrayValue) {
1070
+ optionalCount += value.elements.length - value.shortest;
1071
+ if (optionalCount > MAX_CONCAT_ELEMENTS) {
1072
+ value = value.withoutOptional();
1073
+ read[index] = known(value);
1074
+ }
1075
+ }
1076
+ if (Array.isArray(value) || value instanceof PartialArrayValue) {
1077
+ const room = MAX_CONCAT_ELEMENTS - elementCount;
1078
+ elementCount += value instanceof PartialArrayValue ? value.shortest : value.length;
1079
+ if (elementCount > MAX_CONCAT_ELEMENTS) {
1080
+ // The elements that fit can still settle any() and has_value().
1081
+ parts.push(firstElements(value, room, tooLarge));
1082
+ return known(parts);
1083
+ }
1084
+ }
1085
+ parts.push(value);
1086
+ if (typeof value === 'string')
1087
+ size += value.length;
1088
+ if (size <= limit)
1089
+ continue;
1090
+ if (surelyTooLarge(size, parts))
1091
+ return TOO_LARGE;
1092
+ // A part has bytes that can unite, so the parts are not scanned again.
1093
+ limit = MAX_JOINED_SIZE;
1094
+ }
1095
+ return known(parts);
1096
+ }
1097
+ /** An array up to its first `count` elements, of those it surely has, as one that `more` says holds more. */
1098
+ function firstElements(array, count, more) {
1099
+ if (Array.isArray(array))
1100
+ return PartialArrayValue.from(array.slice(0, count).map(value => known(value)), more, count);
1101
+ let end = 0;
1102
+ for (let left = count; left > 0; end++)
1103
+ if (!(array.elements[end] instanceof OptionalElement))
1104
+ left--;
1105
+ return PartialArrayValue.from(array.elements.slice(0, end), more, Math.min(array.moreFrom, end));
1106
+ }
816
1107
  function concatValues(values, argumentTypes) {
817
1108
  if (values.length < 2 || concatTypesDiffer(argumentTypes))
818
1109
  return null;
@@ -836,30 +1127,25 @@ function concatTypesDiffer(argumentTypes) {
836
1127
  }
837
1128
  /**
838
1129
  * concat() over arrays some of which are known only in part: the result
839
- * holds each one's elements, an unknown one in its place, and may hold more
840
- * where one may, which leaves every position unknown, as PartialArrayValue
841
- * says. What more it may be carries over where each such part lists it. A
842
- * value that is no array gives nil, as in concatValues(); a map is unknown,
843
- * as in ruleValue().
1130
+ * lists each one's elements in turn, and may lack or hold others where one
1131
+ * may. A value that is no array gives nil, as in concatValues(); a map is
1132
+ * unknown, as in ruleValue().
844
1133
  */
845
1134
  function concatElements(parts, argumentTypes) {
846
- if (parts.length < 2 || concatTypesDiffer(argumentTypes))
1135
+ if (argumentTypes.length < 2 || concatTypesDiffer(argumentTypes))
847
1136
  return known(null);
848
1137
  const elements = [];
849
1138
  let more;
850
- let optional = [];
1139
+ let moreFrom = 0;
851
1140
  for (const part of parts) {
852
1141
  if (part instanceof RuleMapValue)
853
1142
  return unavailable('a map value');
854
1143
  if (part instanceof PartialArrayValue) {
855
- elements.push(...part.elements);
856
- if (!part.more)
857
- continue;
1144
+ if (!more)
1145
+ moreFrom = elements.length + part.moreFrom;
1146
+ for (const element of part.elements)
1147
+ elements.push(element);
858
1148
  more ??= part.more;
859
- if (part.optional)
860
- optional?.push(...part.optional);
861
- else
862
- optional = undefined;
863
1149
  }
864
1150
  else if (Array.isArray(part)) {
865
1151
  for (const value of part)
@@ -869,7 +1155,7 @@ function concatElements(parts, argumentTypes) {
869
1155
  return known(null);
870
1156
  }
871
1157
  }
872
- return known(PartialArrayValue.from(elements, more, optional));
1158
+ return known(PartialArrayValue.from(elements, more, moreFrom));
873
1159
  }
874
1160
  /** Cloudflare counts the bytes of a string. */
875
1161
  function lengthOfValue(value) {
@@ -897,13 +1183,100 @@ function encodeBase64Value(value, flagsValue) {
897
1183
  if (value === null)
898
1184
  return null;
899
1185
  const flags = flagsValue === null ? '' : String(flagsValue);
900
- let encoded = bytesToBase64(textToBytes(String(value)));
1186
+ const bytes = bytesToEncode(String(value), 4 / 3);
1187
+ if (bytes === TOO_LARGE)
1188
+ return bytes;
1189
+ let encoded = bytesToBase64(bytes);
901
1190
  if (flags.includes('u'))
902
1191
  encoded = encoded.replaceAll('+', '-').replaceAll('/', '_');
903
1192
  if (!flags.includes('p'))
904
1193
  encoded = encoded.replace(/=+$/, '');
905
1194
  return encoded;
906
1195
  }
1196
+ /** The bytes of a text, unless an encoding that writes `ratio` characters for each would hold too much. */
1197
+ function bytesToEncode(text, ratio) {
1198
+ // Each character is at least one byte.
1199
+ if (text.length * ratio > MAX_RESULT_SIZE)
1200
+ return TOO_LARGE;
1201
+ const bytes = textToBytes(text);
1202
+ return Math.ceil(bytes.length * ratio) > MAX_RESULT_SIZE ? TOO_LARGE : bytes;
1203
+ }
1204
+ const HEX_DIGITS = new TextEncoder().encode('0123456789abcdef');
1205
+ /** Writes each byte as two lowercase hex digits. */
1206
+ function encodeHexValue(value) {
1207
+ if (value === null)
1208
+ return null;
1209
+ const bytes = bytesToEncode(String(value), 2);
1210
+ if (bytes === TOO_LARGE)
1211
+ return bytes;
1212
+ const digits = new Uint8Array(bytes.length * 2);
1213
+ for (let index = 0; index < bytes.length; index++) {
1214
+ digits[index * 2] = HEX_DIGITS[bytes[index] >> 4];
1215
+ digits[index * 2 + 1] = HEX_DIGITS[bytes[index] & 15];
1216
+ }
1217
+ return bytesToText(digits);
1218
+ }
1219
+ const SECONDS_PER_DAY = 86400;
1220
+ /** The first and last seconds of the years format_date() formats, -999999 to 999999; it gives nil outside them. */
1221
+ const MIN_DATE_TIMESTAMP = daysFromCivil(-999999, 1, 1) * SECONDS_PER_DAY;
1222
+ const MAX_DATE_TIMESTAMP = daysFromCivil(1000000, 1, 1) * SECONDS_PER_DAY - 1;
1223
+ /**
1224
+ * Formats Unix seconds as UTC text in the proleptic Gregorian calendar. A
1225
+ * year outside 0 to 9999 has a sign, and every year has at least four digits.
1226
+ * Validation leaves only the directives Cloudflare supports.
1227
+ */
1228
+ function formatDate(timestampValue, formatValue) {
1229
+ if (typeof timestampValue !== 'number' || typeof formatValue !== 'string')
1230
+ return null;
1231
+ if (timestampValue < MIN_DATE_TIMESTAMP || timestampValue > MAX_DATE_TIMESTAMP)
1232
+ return null;
1233
+ const days = Math.floor(timestampValue / SECONDS_PER_DAY);
1234
+ const seconds = timestampValue - days * SECONDS_PER_DAY;
1235
+ const [year, month, day] = civilFromDays(days);
1236
+ const twoDigits = (value) => String(value).padStart(2, '0');
1237
+ const yearText = year >= 0 && year <= 9999
1238
+ ? String(year).padStart(4, '0')
1239
+ : `${year < 0 ? '-' : '+'}${String(Math.abs(year)).padStart(4, '0')}`;
1240
+ return formatValue.replace(/%([YmdHMS%])/g, (_directive, letter) => {
1241
+ switch (letter) {
1242
+ case 'Y':
1243
+ return yearText;
1244
+ case 'm':
1245
+ return twoDigits(month);
1246
+ case 'd':
1247
+ return twoDigits(day);
1248
+ case 'H':
1249
+ return twoDigits(Math.floor(seconds / 3600));
1250
+ case 'M':
1251
+ return twoDigits(Math.floor(seconds / 60) % 60);
1252
+ case 'S':
1253
+ return twoDigits(seconds % 60);
1254
+ default:
1255
+ return '%';
1256
+ }
1257
+ });
1258
+ }
1259
+ /** The days from 1970-01-01 to a date; see https://howardhinnant.github.io/date_algorithms.html. */
1260
+ function daysFromCivil(year, month, day) {
1261
+ const shiftedYear = month <= 2 ? year - 1 : year;
1262
+ const era = Math.floor(shiftedYear / 400);
1263
+ const yearOfEra = shiftedYear - era * 400;
1264
+ const dayOfYear = Math.floor((153 * (month > 2 ? month - 3 : month + 9) + 2) / 5) + day - 1;
1265
+ const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
1266
+ return era * 146097 + dayOfEra - 719468;
1267
+ }
1268
+ /** The year, month and day of a count of days from 1970-01-01; the inverse of daysFromCivil(). */
1269
+ function civilFromDays(days) {
1270
+ const shifted = days + 719468;
1271
+ const era = Math.floor(shifted / 146097);
1272
+ const dayOfEra = shifted - era * 146097;
1273
+ const yearOfEra = Math.floor((dayOfEra - Math.floor(dayOfEra / 1460) + Math.floor(dayOfEra / 36524) - Math.floor(dayOfEra / 146096)) / 365);
1274
+ const dayOfYear = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
1275
+ const monthIndex = Math.floor((5 * dayOfYear + 2) / 153);
1276
+ const day = dayOfYear - Math.floor((153 * monthIndex + 2) / 5) + 1;
1277
+ const month = monthIndex < 10 ? monthIndex + 3 : monthIndex - 9;
1278
+ return [yearOfEra + era * 400 + (month <= 2 ? 1 : 0), month, day];
1279
+ }
907
1280
  /**
908
1281
  * Decodes standard Base64 as Cloudflare does, observed with live requests: it
909
1282
  * skips whitespace and takes input with or without padding. Other input is
@@ -932,10 +1305,15 @@ function bytesToBase64(bytes) {
932
1305
  binary += String.fromCharCode(byte);
933
1306
  return globalThis.btoa(binary);
934
1307
  }
935
- function joinValues(items, separator) {
936
- if (!Array.isArray(items) || separator === null)
1308
+ function joinValues(items, separatorValue) {
1309
+ if (!Array.isArray(items) || separatorValue === null)
937
1310
  return null;
938
- return items.map(item => String(item)).join(String(separator));
1311
+ const texts = items.map(item => String(item));
1312
+ const separator = String(separatorValue);
1313
+ let size = separator.length * Math.max(texts.length - 1, 0);
1314
+ for (const text of texts)
1315
+ size += text.length;
1316
+ return surelyTooLarge(size, texts, [separator]) ? TOO_LARGE : texts.join(separator);
939
1317
  }
940
1318
  /**
941
1319
  * Cloudflare accepts one seed, and a nil seed gives nil. The bounds are integer
@@ -1039,16 +1417,27 @@ function jsonMember(container, key) {
1039
1417
  function regexReplace(sourceValue, patternValue, replacementValue) {
1040
1418
  if (sourceValue === null || patternValue === null || replacementValue === null)
1041
1419
  return null;
1420
+ const source = String(sourceValue);
1421
+ let match;
1042
1422
  try {
1043
- const regex = new RegExp(String(patternValue));
1044
- return String(sourceValue).replace(regex, (...matchParts) => {
1045
- const captures = matchParts.slice(1, -2);
1046
- return replaceRuleCaptureReferences(String(replacementValue), captures);
1047
- });
1423
+ match = new RegExp(String(patternValue)).exec(source);
1048
1424
  }
1049
1425
  catch {
1050
- return String(sourceValue);
1426
+ return source;
1051
1427
  }
1428
+ return match ? replaceMatch(source, match.index, match, String(replacementValue)) : source;
1429
+ }
1430
+ /** Writes a replacement in place of a source's match, which is the first of the captures. */
1431
+ function replaceMatch(source, start, captures, replacement) {
1432
+ const before = source.slice(0, start);
1433
+ const after = source.slice(start + (captures[0]?.length ?? 0));
1434
+ // The size is counted only where it could be too large.
1435
+ if (replacement.length + source.length * (MAX_REPLACEMENT_REFERENCES + 1) > MAX_RESULT_SIZE) {
1436
+ const { length, written } = measureReplacement(replacement, captures);
1437
+ if (surelyTooLarge(before.length + length + after.length, [before, replacement, after], written))
1438
+ return TOO_LARGE;
1439
+ }
1440
+ return before + expandReplacement(replacement, captures) + after;
1052
1441
  }
1053
1442
  /** Removes each listed byte wherever it appears, as Cloudflare does, so a result can split a character. */
1054
1443
  function removeBytes(sourceValue, removeValue) {
@@ -1125,16 +1514,7 @@ function wildcardReplaceValue(sourceValue, patternValue, replacementValue, flags
1125
1514
  function wildcardReplace(source, pattern, replacement, flags) {
1126
1515
  const compiled = compileWildcard(pattern, flags.includes('s'));
1127
1516
  const captures = compiled && wildcardCaptures(compiled, source);
1128
- if (!captures)
1129
- return source;
1130
- return replaceRuleCaptureReferences(replacement, captures);
1131
- }
1132
- function replaceRuleCaptureReferences(replacement, captures) {
1133
- return replacement.replace(/\$\$|\$\{([1-8])\}/g, (full, index) => {
1134
- if (full === '$$')
1135
- return '$';
1136
- return captures[Number.parseInt(index ?? '0', 10) - 1]?.toString() ?? '';
1137
- });
1517
+ return captures ? replaceMatch(source, 0, captures, replacement) : source;
1138
1518
  }
1139
1519
  /** Returns the network address, printed as Cloudflare prints IP addresses. */
1140
1520
  function evaluateCidr(addressValue, ipv4BitsValue, ipv6BitsValue) {
@@ -1154,6 +1534,9 @@ function evaluateCidr(addressValue, ipv4BitsValue, ipv6BitsValue) {
1154
1534
  }
1155
1535
  return formatIpAddress(octets);
1156
1536
  }
1537
+ function tooLargeResult(ctx, name) {
1538
+ return unreliableFunction(ctx, name, RESULT_SIZE_REASON);
1539
+ }
1157
1540
  /** A function result this evaluator cannot reproduce is unknown. */
1158
1541
  function unreliableFunction(ctx, name, reason = getUnreliableRuleExpressionFunctionReason(name)) {
1159
1542
  if (reason)