fastly.js 0.9.0 → 0.9.2

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.
package/dist/browser.js CHANGED
@@ -271,6 +271,19 @@ function vclToString(v) {
271
271
  }
272
272
  return String(v);
273
273
  }
274
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
275
+ function isValidUtf8(s) {
276
+ return !LONE_SURROGATE.test(s);
277
+ }
278
+
279
+ class VCLFailure {
280
+ value;
281
+ error;
282
+ constructor(value, error) {
283
+ this.value = value;
284
+ this.error = error;
285
+ }
286
+ }
274
287
  function isNotSet(v) {
275
288
  return v instanceof VCLString && v.isNotSet;
276
289
  }
@@ -976,6 +989,7 @@ var BUILTIN_SIGNATURES = {
976
989
  ],
977
990
  ret: "STRING"
978
991
  },
992
+ "utf8.translate": { args: [["STRING", "STRING", "STRING"]], ret: "STRING" },
979
993
  "uuid.dns": { args: [], ret: "STRING" },
980
994
  "uuid.is_valid": { args: [["STRING"]], ret: "BOOL" },
981
995
  "uuid.is_version3": { args: [["STRING"]], ret: "BOOL" },
@@ -1532,14 +1546,269 @@ function collectCallStatements(statements) {
1532
1546
  return calls;
1533
1547
  }
1534
1548
 
1535
- // src/vcl-strings.ts
1549
+ // src/vcl-regex.ts
1536
1550
  var utf8Encoder = new TextEncoder;
1537
- var utf8Decoder = new TextDecoder;
1551
+ var utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
1552
+ var ASCII = /^[\x00-\x7f]*$/;
1553
+ function toBytes(s) {
1554
+ if (ASCII.test(s))
1555
+ return s;
1556
+ const bytes = utf8Encoder.encode(s);
1557
+ let out = "";
1558
+ for (let i = 0;i < bytes.length; i++)
1559
+ out += String.fromCharCode(bytes[i]);
1560
+ return out;
1561
+ }
1562
+ function fromBytes(s) {
1563
+ if (ASCII.test(s))
1564
+ return s;
1565
+ const bytes = new Uint8Array(s.length);
1566
+ for (let i = 0;i < s.length; i++)
1567
+ bytes[i] = s.charCodeAt(i);
1568
+ return utf8Decoder.decode(bytes);
1569
+ }
1570
+ var DIGIT = [[48, 57]];
1571
+ var UPPER = [[65, 90]];
1572
+ var LOWER = [[97, 122]];
1573
+ var ALPHA = [...UPPER, ...LOWER];
1574
+ var ALNUM = [...DIGIT, ...ALPHA];
1575
+ var WORD = [...ALNUM, [95, 95]];
1576
+ var BLANK = [
1577
+ [9, 9],
1578
+ [32, 32]
1579
+ ];
1580
+ var SPACE = [
1581
+ [9, 13],
1582
+ [32, 32]
1583
+ ];
1584
+ var SETS = {
1585
+ d: DIGIT,
1586
+ w: WORD,
1587
+ s: SPACE,
1588
+ h: [...BLANK, [160, 160]],
1589
+ v: [
1590
+ [10, 13],
1591
+ [133, 133]
1592
+ ]
1593
+ };
1594
+ var POSIX = {
1595
+ alpha: ALPHA,
1596
+ digit: DIGIT,
1597
+ alnum: ALNUM,
1598
+ upper: UPPER,
1599
+ lower: LOWER,
1600
+ space: SPACE,
1601
+ blank: BLANK,
1602
+ punct: [
1603
+ [33, 47],
1604
+ [58, 64],
1605
+ [91, 96],
1606
+ [123, 126]
1607
+ ],
1608
+ xdigit: [...DIGIT, [65, 70], [97, 102]],
1609
+ cntrl: [
1610
+ [0, 31],
1611
+ [127, 127]
1612
+ ],
1613
+ print: [[32, 126]],
1614
+ graph: [[33, 126]],
1615
+ word: WORD,
1616
+ ascii: [[0, 127]]
1617
+ };
1618
+ var ANCHORS = {
1619
+ A: "^",
1620
+ z: "$",
1621
+ Z: "(?=\\n?$)",
1622
+ b: "\\b",
1623
+ B: "\\B",
1624
+ R: "(?:\\r\\n|[\\n\\x0b\\f\\r\\x85])"
1625
+ };
1626
+ var SIMPLE_ESCAPES = {
1627
+ n: 10,
1628
+ r: 13,
1629
+ t: 9,
1630
+ f: 12,
1631
+ e: 27,
1632
+ a: 7,
1633
+ b: 8
1634
+ };
1635
+ function complement(ranges) {
1636
+ const out = [];
1637
+ let next = 0;
1638
+ for (const [lo, hi] of [...ranges].sort((a, b) => a[0] - b[0])) {
1639
+ if (lo > next)
1640
+ out.push([next, lo - 1]);
1641
+ next = Math.max(next, hi + 1);
1642
+ }
1643
+ if (next <= 255)
1644
+ out.push([next, 255]);
1645
+ return out;
1646
+ }
1647
+ function withOtherCase(ranges) {
1648
+ const out = [...ranges];
1649
+ for (const [lo, hi] of ranges) {
1650
+ for (const [a, z, shift] of [
1651
+ [65, 90, 32],
1652
+ [97, 122, -32]
1653
+ ]) {
1654
+ const l = Math.max(lo, a);
1655
+ const h = Math.min(hi, z);
1656
+ if (l <= h)
1657
+ out.push([l + shift, h + shift]);
1658
+ }
1659
+ }
1660
+ return out;
1661
+ }
1662
+ function classSource(ranges, negate, caseless) {
1663
+ const hex = (c) => `\\x${c.toString(16).padStart(2, "0")}`;
1664
+ const body = (caseless ? withOtherCase(ranges) : ranges).map(([lo, hi]) => lo === hi ? hex(lo) : `${hex(lo)}-${hex(hi)}`).join("");
1665
+ return `[${negate ? "^" : ""}${body}]`;
1666
+ }
1667
+ var isSingleChar = (r) => r.length === 1 && r[0][0] === r[0][1];
1668
+ function escapeRanges(p, i) {
1669
+ const c = p[i];
1670
+ const set = SETS[c.toLowerCase()];
1671
+ if (set)
1672
+ return [c === c.toLowerCase() ? set : complement(set), i + 1];
1673
+ let code = SIMPLE_ESCAPES[c];
1674
+ let next = i + 1;
1675
+ const braced = /^x\{([0-9a-fA-F]+)\}/.exec(p.slice(i));
1676
+ if (braced) {
1677
+ code = parseInt(braced[1], 16);
1678
+ next = i + braced[0].length;
1679
+ } else if (c === "x" && p[i + 1] !== "{" || c === "0") {
1680
+ const digits = (c === "x" ? /^[0-9a-f]{0,2}/i : /^[0-7]{0,2}/).exec(p.slice(i + 1))[0];
1681
+ code = digits ? parseInt(digits, c === "x" ? 16 : 8) : 0;
1682
+ next += digits.length;
1683
+ } else if (!/[a-z0-9]/i.test(c)) {
1684
+ code = c.charCodeAt(0);
1685
+ }
1686
+ if (code === undefined || code > 255) {
1687
+ throw new Error(`Unsupported regex escape \\${c}`);
1688
+ }
1689
+ return [[[code, code]], next];
1690
+ }
1691
+ function classItem(p, i) {
1692
+ return p[i] === "\\" ? escapeRanges(p, i + 1) : [[[p.charCodeAt(i), p.charCodeAt(i)]], i + 1];
1693
+ }
1694
+ function classAt(p, i, caseless) {
1695
+ const negate = p[i] === "^";
1696
+ if (negate)
1697
+ i++;
1698
+ const ranges = [];
1699
+ do {
1700
+ if (i >= p.length)
1701
+ throw new Error("Missing ] in regex character class");
1702
+ const posix = /^\[:(\^?)([a-z]+):\]/.exec(p.slice(i));
1703
+ if (posix) {
1704
+ const name = caseless && (posix[2] === "upper" || posix[2] === "lower") ? "alpha" : posix[2];
1705
+ const set = POSIX[name];
1706
+ if (!set)
1707
+ throw new Error(`Unknown POSIX class ${posix[0]}`);
1708
+ ranges.push(...posix[1] ? complement(set) : set);
1709
+ i += posix[0].length;
1710
+ continue;
1711
+ }
1712
+ let item;
1713
+ [item, i] = classItem(p, i);
1714
+ if (p[i] === "-" && p[i + 1] !== "]" && i + 1 < p.length) {
1715
+ const [end, next] = classItem(p, i + 1);
1716
+ if (!isSingleChar(item) || !isSingleChar(end) || item[0][0] > end[0][0]) {
1717
+ throw new Error("Invalid range in regex character class");
1718
+ }
1719
+ item = [[item[0][0], end[0][0]]];
1720
+ i = next;
1721
+ }
1722
+ ranges.push(...item);
1723
+ } while (p[i] !== "]");
1724
+ return [classSource(ranges, negate, caseless), i + 1];
1725
+ }
1726
+ function translate(p) {
1727
+ let out = "";
1728
+ let opts = "";
1729
+ const saved = [];
1730
+ let i = 0;
1731
+ while (i < p.length) {
1732
+ const c = p[i++];
1733
+ let m;
1734
+ if (c === "[") {
1735
+ let cls;
1736
+ [cls, i] = classAt(p, i, opts.includes("i"));
1737
+ out += cls;
1738
+ } else if (c === "(") {
1739
+ saved.push(opts);
1740
+ const rest = p.slice(i);
1741
+ if (m = /^\?#[^)]*\)/.exec(rest)) {
1742
+ saved.pop();
1743
+ } else if (m = /^\?P=(\w+)\)/.exec(rest)) {
1744
+ saved.pop();
1745
+ out += `\\k<${m[1]}>`;
1746
+ } else if (m = /^\?(?:P?<(\w+)>|'(\w+)')/.exec(rest)) {
1747
+ out += `(?<${m[1] ?? m[2]}>`;
1748
+ } else if (m = /^(?:\?[:=!]|\?<[=!]|(?!\?))/.exec(rest)) {
1749
+ out += `(${m[0]}`;
1750
+ } else if (m = /^\?([a-zA-Z]*)(?:-([a-zA-Z]*))?([:)])/.exec(rest)) {
1751
+ const [, on = "", off = "", end] = m;
1752
+ for (const f of on + off) {
1753
+ if (!"ims".includes(f))
1754
+ throw new Error(`Unsupported regex option (?${f})`);
1755
+ }
1756
+ if (end === ")")
1757
+ saved.pop();
1758
+ else
1759
+ out += "(?:";
1760
+ opts = [...opts + on].filter((f) => !off.includes(f)).join("");
1761
+ } else {
1762
+ throw new Error(`Unsupported regex group (${rest.slice(0, 2)}`);
1763
+ }
1764
+ i += m[0].length;
1765
+ } else if (c === ")") {
1766
+ opts = saved.pop() ?? opts;
1767
+ out += ")";
1768
+ } else if (c === ".") {
1769
+ out += opts.includes("s") ? "[\\s\\S]" : "[^\\n]";
1770
+ } else if (c === "^") {
1771
+ out += opts.includes("m") ? "(?:^|(?<=\\n)(?=[\\s\\S]))" : "^";
1772
+ } else if (c === "$") {
1773
+ out += opts.includes("m") ? "(?=\\n|$)" : "(?=\\n?$)";
1774
+ } else if (c !== "\\") {
1775
+ out += opts.includes("i") && /[a-z]/i.test(c) ? `[${c.toLowerCase()}${c.toUpperCase()}]` : c;
1776
+ } else if (p[i] === undefined) {
1777
+ throw new Error("Regex ends with a \\");
1778
+ } else if (ANCHORS[p[i]] !== undefined) {
1779
+ out += ANCHORS[p[i++]];
1780
+ } else if (m = /^(?:[1-9]\d*|k<\w+>)/.exec(p.slice(i))) {
1781
+ out += `(?:\\${m[0]})`;
1782
+ i += m[0].length;
1783
+ } else {
1784
+ let ranges;
1785
+ [ranges, i] = escapeRanges(p, i);
1786
+ out += classSource(ranges, false, opts.includes("i"));
1787
+ }
1788
+ }
1789
+ return out;
1790
+ }
1791
+ var cache = new Map;
1792
+ function compileRegex(pattern, flags = "") {
1793
+ const key = `${flags}/${pattern}`;
1794
+ let re = cache.get(key);
1795
+ if (re === undefined) {
1796
+ re = new RegExp(translate(toBytes(pattern)), flags);
1797
+ if (cache.size >= 1000)
1798
+ cache.clear();
1799
+ cache.set(key, re);
1800
+ }
1801
+ return re;
1802
+ }
1803
+
1804
+ // src/vcl-strings.ts
1805
+ var utf8Encoder2 = new TextEncoder;
1806
+ var utf8Decoder2 = new TextDecoder;
1538
1807
  function utf8Bytes(s) {
1539
- return utf8Encoder.encode(s);
1808
+ return utf8Encoder2.encode(s);
1540
1809
  }
1541
1810
  function decodeBytes(bytes) {
1542
- return utf8Decoder.decode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
1811
+ return utf8Decoder2.decode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
1543
1812
  }
1544
1813
  function isAlnumByte(b) {
1545
1814
  return b >= 65 && b <= 90 || b >= 97 && b <= 122 || b >= 48 && b <= 57;
@@ -1834,10 +2103,9 @@ var JSON_ESCAPE_MAP = new Map([
1834
2103
  [12, "\\f"],
1835
2104
  [13, "\\r"]
1836
2105
  ]);
1837
- var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
1838
2106
  function json_escape(str) {
1839
2107
  const s = String(str);
1840
- if (LONE_SURROGATE.test(s))
2108
+ if (!isValidUtf8(s))
1841
2109
  return "";
1842
2110
  let out = "";
1843
2111
  for (const ch of s) {
@@ -1915,33 +2183,34 @@ function expandReplacement(_input, replacement, match) {
1915
2183
  }
1916
2184
  function regsub(str, pattern, replacement) {
1917
2185
  try {
1918
- const s = String(str);
1919
- const re = new RegExp(pattern);
1920
- const match = re.exec(s);
2186
+ const s = toBytes(String(str));
2187
+ const match = compileRegex(String(pattern)).exec(s);
1921
2188
  if (!match)
1922
- return s;
1923
- return s.slice(0, match.index) + expandReplacement(s, replacement, match) + s.slice(match.index + match[0].length);
2189
+ return String(str);
2190
+ return fromBytes(s.slice(0, match.index) + expandReplacement(s, toBytes(String(replacement)), match) + s.slice(match.index + match[0].length));
1924
2191
  } catch {
1925
2192
  return str;
1926
2193
  }
1927
2194
  }
1928
2195
  function regsuball(str, pattern, replacement) {
1929
2196
  try {
1930
- const s = String(str);
1931
- const re = new RegExp(pattern, "g");
2197
+ const s = toBytes(String(str));
2198
+ const re = compileRegex(String(pattern), "g");
2199
+ re.lastIndex = 0;
2200
+ const sub = toBytes(String(replacement));
1932
2201
  let result = "";
1933
2202
  let lastEnd = 0;
1934
2203
  let match;
1935
2204
  while ((match = re.exec(s)) !== null) {
1936
2205
  result += s.slice(lastEnd, match.index);
1937
- result += expandReplacement(s, replacement, match);
2206
+ result += expandReplacement(s, sub, match);
1938
2207
  lastEnd = match.index + match[0].length;
1939
2208
  if (match[0].length === 0) {
1940
2209
  re.lastIndex++;
1941
2210
  }
1942
2211
  }
1943
2212
  result += s.slice(lastEnd);
1944
- return result;
2213
+ return fromBytes(result);
1945
2214
  } catch {
1946
2215
  return str;
1947
2216
  }
@@ -2025,6 +2294,9 @@ function strstr(haystack, needle) {
2025
2294
  }
2026
2295
  function strpad(s, width, pad) {
2027
2296
  const str = String(s);
2297
+ if (!Number.isFinite(width) || width <= -Number.MAX_SAFE_INTEGER) {
2298
+ return new VCLFailure("", "EDOM");
2299
+ }
2028
2300
  const w = Math.abs(Math.trunc(width));
2029
2301
  const sLen = utf8Bytes(str).length;
2030
2302
  if (sLen >= w)
@@ -3261,6 +3533,21 @@ function fastlyHash(key, seed, from, to) {
3261
3533
  return null;
3262
3534
  }
3263
3535
  var MAX_RTIME_SECONDS = 9223372036.854776;
3536
+ function urlComponents(url) {
3537
+ const pathEnd = url.search(/[?#]/);
3538
+ const path = pathEnd < 0 ? url : url.substring(0, pathEnd);
3539
+ const qs = url[pathEnd] === "?" ? url.substring(pathEnd + 1).split("#")[0] : "";
3540
+ const lastSlash = path.lastIndexOf("/");
3541
+ const basename2 = path.substring(lastSlash + 1);
3542
+ const dot = basename2.lastIndexOf(".");
3543
+ return {
3544
+ path,
3545
+ qs,
3546
+ dirname: lastSlash > 0 ? path.substring(0, lastSlash) : "/",
3547
+ basename: basename2,
3548
+ ext: dot >= 0 ? basename2.substring(dot + 1) : ""
3549
+ };
3550
+ }
3264
3551
  function serializeHeaders(headers) {
3265
3552
  if (!headers)
3266
3553
  return "";
@@ -4354,6 +4641,11 @@ class VCLCompiler {
4354
4641
  }
4355
4642
  evaluateFunctionCall(expression, context) {
4356
4643
  const result = this.evaluateFunctionCallInner(expression, context);
4644
+ if (result instanceof VCLFailure) {
4645
+ if (context.fastly)
4646
+ context.fastly.error = result.error;
4647
+ return coerceBuiltinReturn(expression.name, result.value);
4648
+ }
4357
4649
  const rule = NULL_RESULT_RULES[expression.name];
4358
4650
  if (rule && (result === null || result === undefined)) {
4359
4651
  if (context.fastly)
@@ -4748,11 +5040,7 @@ class VCLCompiler {
4748
5040
  return raw === undefined ? VCLString.notset() : firstHeaderFragment(raw);
4749
5041
  }
4750
5042
  if (parts.length === 3 && idPart0 === "re" && idPart1 === "group") {
4751
- const groupNumber = parseInt(idPart2, 10);
4752
- if (!Number.isNaN(groupNumber) && context.re?.groups?.[groupNumber] !== undefined) {
4753
- return context.re.groups[groupNumber];
4754
- }
4755
- return VCLString.notset();
5043
+ return context.re?.groups?.[idPart2] ?? VCLString.notset();
4756
5044
  }
4757
5045
  if (parts.length >= 2 && idPart0 === "var") {
4758
5046
  const varName = parts.slice(1).join(".");
@@ -4776,35 +5064,16 @@ class VCLCompiler {
4776
5064
  return context.obj.response ?? "";
4777
5065
  if (name === "req.url")
4778
5066
  return context.req.url;
4779
- if (name === "req.url.path") {
4780
- const url = context.req.url || "";
4781
- const qIdx = url.indexOf("?");
4782
- return qIdx >= 0 ? url.substring(0, qIdx) : url;
4783
- }
4784
- if (name === "req.url.qs") {
4785
- const url = context.req.url || "";
4786
- const qIdx = url.indexOf("?");
4787
- return qIdx >= 0 ? url.substring(qIdx + 1) : "";
4788
- }
4789
- if (name === "req.url.basename") {
4790
- const path = this.resolveVariable("req.url.path", context);
4791
- if (path === "")
4792
- return ".";
4793
- const lastSlash = path.lastIndexOf("/");
4794
- return lastSlash >= 0 ? path.substring(lastSlash + 1) : path;
4795
- }
4796
- if (name === "req.url.dirname") {
4797
- const path = this.resolveVariable("req.url.path", context);
4798
- if (path === "")
4799
- return ".";
4800
- const lastSlash = path.lastIndexOf("/");
4801
- return lastSlash >= 0 ? path.substring(0, lastSlash + 1) : "/";
4802
- }
4803
- if (name === "req.url.ext") {
4804
- const basename2 = this.resolveVariable("req.url.basename", context);
4805
- const dotIdx = basename2.lastIndexOf(".");
4806
- return dotIdx >= 0 ? basename2.substring(dotIdx + 1) : "";
4807
- }
5067
+ if (name === "req.url.path")
5068
+ return urlComponents(context.req.url).path;
5069
+ if (name === "req.url.qs")
5070
+ return urlComponents(context.req.url).qs;
5071
+ if (name === "req.url.basename")
5072
+ return urlComponents(context.req.url).basename;
5073
+ if (name === "req.url.dirname")
5074
+ return urlComponents(context.req.url).dirname;
5075
+ if (name === "req.url.ext")
5076
+ return urlComponents(context.req.url).ext;
4808
5077
  if (name === "req.method" || name === "req.request")
4809
5078
  return context.req.method;
4810
5079
  if (name === "req.backend")
@@ -4912,35 +5181,16 @@ class VCLCompiler {
4912
5181
  return context.bereq.method;
4913
5182
  if (name === "bereq.proto")
4914
5183
  return ctx.bereq?.proto || "HTTP/1.1";
4915
- if (name === "bereq.url.path") {
4916
- const url = context.bereq.url || "";
4917
- const qIdx = url.indexOf("?");
4918
- return qIdx >= 0 ? url.substring(0, qIdx) : url;
4919
- }
4920
- if (name === "bereq.url.qs") {
4921
- const url = context.bereq.url || "";
4922
- const qIdx = url.indexOf("?");
4923
- return qIdx >= 0 ? url.substring(qIdx + 1) : "";
4924
- }
4925
- if (name === "bereq.url.basename") {
4926
- const path = this.resolveVariable("bereq.url.path", context);
4927
- if (path === "")
4928
- return ".";
4929
- const lastSlash = path.lastIndexOf("/");
4930
- return lastSlash >= 0 ? path.substring(lastSlash + 1) : path;
4931
- }
4932
- if (name === "bereq.url.dirname") {
4933
- const path = this.resolveVariable("bereq.url.path", context);
4934
- if (path === "")
4935
- return ".";
4936
- const lastSlash = path.lastIndexOf("/");
4937
- return lastSlash >= 0 ? path.substring(0, lastSlash + 1) : "/";
4938
- }
4939
- if (name === "bereq.url.ext") {
4940
- const basename2 = this.resolveVariable("bereq.url.basename", context);
4941
- const dotIdx = basename2.lastIndexOf(".");
4942
- return dotIdx >= 0 ? basename2.substring(dotIdx + 1) : "";
4943
- }
5184
+ if (name === "bereq.url.path")
5185
+ return urlComponents(context.bereq.url).path;
5186
+ if (name === "bereq.url.qs")
5187
+ return urlComponents(context.bereq.url).qs;
5188
+ if (name === "bereq.url.basename")
5189
+ return urlComponents(context.bereq.url).basename;
5190
+ if (name === "bereq.url.dirname")
5191
+ return urlComponents(context.bereq.url).dirname;
5192
+ if (name === "bereq.url.ext")
5193
+ return urlComponents(context.bereq.url).ext;
4944
5194
  if (name === "bereq.headers")
4945
5195
  return serializeHeaders(context.bereq.http);
4946
5196
  if (name === "bereq.max_reuse_idle_time")
@@ -5513,13 +5763,20 @@ class VCLCompiler {
5513
5763
  }
5514
5764
  regexMatch(left, right, context, negate) {
5515
5765
  try {
5516
- const regex = right instanceof RegExp ? right : new RegExp(String(right));
5517
- const match = String(left).match(regex);
5766
+ const regex = right instanceof RegExp ? right : compileRegex(String(right));
5767
+ const match = regex.exec(toBytes(String(left)));
5768
+ context.re = undefined;
5518
5769
  if (match) {
5519
- const groups = {};
5770
+ const groups = Object.create(null);
5520
5771
  match.forEach((val, i) => {
5521
- groups[i] = val ?? "";
5772
+ if (val !== undefined)
5773
+ groups[i] = fromBytes(val);
5522
5774
  });
5775
+ for (const name in match.groups) {
5776
+ const val = match.groups[name];
5777
+ if (val !== undefined)
5778
+ groups[name] = fromBytes(val);
5779
+ }
5523
5780
  context.re = { groups };
5524
5781
  return !negate;
5525
5782
  }
@@ -6223,6 +6480,112 @@ function createMathModule() {
6223
6480
  };
6224
6481
  }
6225
6482
 
6483
+ // src/vcl-utf8.ts
6484
+ function isNullArg(value) {
6485
+ return value === null || value === undefined || isNotSet(value);
6486
+ }
6487
+ var lastSets = null;
6488
+ var lastTable = new Map;
6489
+ function translationTable(set1, set2) {
6490
+ const key = `${set1}\x00${set2}`;
6491
+ if (key === lastSets)
6492
+ return lastTable;
6493
+ const from = [...set1];
6494
+ const to = [...set2];
6495
+ const table = new Map;
6496
+ for (let i = 0;i < from.length; i++) {
6497
+ const character = from[i];
6498
+ if (!table.has(character))
6499
+ table.set(character, to[Math.min(i, to.length - 1)]);
6500
+ }
6501
+ lastSets = key;
6502
+ lastTable = table;
6503
+ return table;
6504
+ }
6505
+ function translateSetsError(set1, set2) {
6506
+ const count1 = [...set1].length;
6507
+ const count2 = [...set2].length;
6508
+ if (count1 === 0)
6509
+ return "Characters required in set1";
6510
+ if (count2 === 0)
6511
+ return "Characters required in set2";
6512
+ if (count2 > count1) {
6513
+ return `Excess characters in set2: Expected ${count1} or fewer, got ${count2}`;
6514
+ }
6515
+ return null;
6516
+ }
6517
+ var UTF8Module = {
6518
+ is_valid: (s) => !isNullArg(s) && isValidUtf8(toRawString(s)),
6519
+ codepoint_count: (s) => {
6520
+ const str = toRawString(s);
6521
+ return isValidUtf8(str) ? [...str].length : 0;
6522
+ },
6523
+ substr: (s, offset, length) => {
6524
+ if (isNullArg(s))
6525
+ return null;
6526
+ const str = toRawString(s);
6527
+ if (!isValidUtf8(str))
6528
+ return null;
6529
+ const runes = [...str];
6530
+ const count = runes.length;
6531
+ let start = Math.trunc(Number(offset));
6532
+ if (!Number.isFinite(start))
6533
+ return null;
6534
+ if (start < 0)
6535
+ start += count;
6536
+ if (start < 0 || start > count)
6537
+ return null;
6538
+ let len;
6539
+ if (length === undefined) {
6540
+ len = count - start;
6541
+ } else {
6542
+ len = Math.trunc(Number(length));
6543
+ if (!Number.isFinite(len))
6544
+ return null;
6545
+ if (len < 0)
6546
+ len += count - start;
6547
+ }
6548
+ if (len < 0)
6549
+ len = 0;
6550
+ return runes.slice(start, start + len).join("");
6551
+ },
6552
+ strpad: (s, width, pad) => {
6553
+ const str = toRawString(s);
6554
+ const padStr = toRawString(pad);
6555
+ if (padStr === "")
6556
+ return str;
6557
+ const w = Math.trunc(Number(width));
6558
+ if (!Number.isFinite(w) || w <= -Number.MAX_SAFE_INTEGER)
6559
+ return new VCLFailure("", "EDOM");
6560
+ if (!isValidUtf8(padStr) || !isValidUtf8(str))
6561
+ return new VCLFailure(null, "EUTF8");
6562
+ const runes = [...str];
6563
+ const padRunes = [...padStr];
6564
+ const paddedCount = Math.abs(w);
6565
+ if (runes.length >= paddedCount)
6566
+ return str;
6567
+ const paddingCount = paddedCount - runes.length;
6568
+ const padding = [];
6569
+ for (let i = 0;i < paddingCount; i++)
6570
+ padding.push(padRunes[i % padRunes.length]);
6571
+ return w < 0 ? str + padding.join("") : padding.join("") + str;
6572
+ },
6573
+ translate: (input, set1, set2) => {
6574
+ const str = toRawString(input);
6575
+ if (!isValidUtf8(str))
6576
+ return new VCLFailure(null, "EUTF8");
6577
+ const from = toRawString(set1);
6578
+ const to = toRawString(set2);
6579
+ if (from === "" || to === "")
6580
+ return str;
6581
+ const table = translationTable(from, to);
6582
+ let out = "";
6583
+ for (const rune of str)
6584
+ out += table.get(rune) ?? rune;
6585
+ return out;
6586
+ }
6587
+ };
6588
+
6226
6589
  // src/vcl-parser-impl.ts
6227
6590
  var INT64_MAX = 2n ** 63n - 1n;
6228
6591
  var INT64_MIN_MAGNITUDE = 2n ** 63n;
@@ -6272,6 +6635,20 @@ var RETURN_ACTIONS = new Set([
6272
6635
  "hit_for_pass",
6273
6636
  "upgrade"
6274
6637
  ]);
6638
+ function constantString(expression) {
6639
+ if (expression.type === "StringLiteral")
6640
+ return expression.value;
6641
+ if (expression.type === "BinaryExpression") {
6642
+ if (expression.operator !== "+" && expression.operator !== " ")
6643
+ return null;
6644
+ const left = constantString(expression.left);
6645
+ if (left === null)
6646
+ return null;
6647
+ const right = constantString(expression.right);
6648
+ return right === null ? null : left + right;
6649
+ }
6650
+ return null;
6651
+ }
6275
6652
 
6276
6653
  class VCLParser {
6277
6654
  tokens = [];
@@ -7810,9 +8187,9 @@ class VCLParser {
7810
8187
  previous() {
7811
8188
  return this.tokens[this.current - 1];
7812
8189
  }
7813
- error(message) {
7814
- const token = this.peek();
7815
- throw new Error(`${message} at line ${token.line}, column ${token.column}`);
8190
+ error(message, at) {
8191
+ const where = at?.location ?? this.peek();
8192
+ throw new Error(`${message} at line ${where.line}, column ${where.column}`);
7816
8193
  }
7817
8194
  parseFunctionCall(token) {
7818
8195
  const name = token.value;
@@ -7824,6 +8201,9 @@ class VCLParser {
7824
8201
  } while (this.match("PUNCTUATION" /* PUNCTUATION */, ","));
7825
8202
  }
7826
8203
  this.consume("PUNCTUATION" /* PUNCTUATION */, "Expected ')' after function arguments");
8204
+ if (name === "utf8.translate" && args.length === 3) {
8205
+ this.checkTranslateSets(args[1], args[2]);
8206
+ }
7827
8207
  let result = {
7828
8208
  type: "FunctionCall",
7829
8209
  name,
@@ -7848,11 +8228,23 @@ class VCLParser {
7848
8228
  }
7849
8229
  return result;
7850
8230
  }
8231
+ checkTranslateSets(set1Expression, set2Expression) {
8232
+ const set1 = constantString(set1Expression);
8233
+ if (set1 === null)
8234
+ this.error("Expected a constant string for set1", set1Expression);
8235
+ const set2 = constantString(set2Expression);
8236
+ if (set2 === null)
8237
+ this.error("Expected a constant string for set2", set2Expression);
8238
+ const problem = translateSetsError(set1, set2);
8239
+ if (problem !== null) {
8240
+ this.error(problem, problem.includes("set1") ? set1Expression : set2Expression);
8241
+ }
8242
+ }
7851
8243
  }
7852
8244
 
7853
8245
  // src/vcl-parser.ts
7854
8246
  var UTF8_ENCODER = new TextEncoder;
7855
- var UTF8_STRICT_DECODER = new TextDecoder("utf-8", { fatal: true });
8247
+ var UTF8_STRICT_DECODER = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
7856
8248
  var LONG_STRING_OPEN_RE = /\{([A-Za-z0-9_]*)"/y;
7857
8249
  var RTIME_UNITS = new Set(["ms", "s", "m", "h", "d", "w", "y"]);
7858
8250
  var UNIT_BOUNDARY = /[a-zA-Z0-9_.:-]/;
@@ -8090,14 +8482,8 @@ class VCLLexer {
8090
8482
  const raw = this.input.substring(this.position, rawEnd);
8091
8483
  let content;
8092
8484
  if (!raw.includes("%")) {
8093
- for (const ch of raw) {
8094
- if (ch === `
8095
- `) {
8096
- this.line++;
8097
- this.column = 1;
8098
- }
8099
- this.advance();
8100
- }
8485
+ while (this.position < rawEnd)
8486
+ this.advanceTrackingLine();
8101
8487
  if (this.position < this.input.length)
8102
8488
  this.advance();
8103
8489
  content = raw;
@@ -8419,23 +8805,6 @@ function bytesToString(bytes) {
8419
8805
  }
8420
8806
  return out;
8421
8807
  }
8422
- function isValidUtf8(s) {
8423
- for (let i = 0;i < s.length; i++) {
8424
- const cu = s.charCodeAt(i);
8425
- if (cu >= 55296 && cu <= 56319) {
8426
- const lo = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
8427
- if (lo >= 56320 && lo <= 57343) {
8428
- i++;
8429
- continue;
8430
- }
8431
- return false;
8432
- }
8433
- if (cu >= 56320 && cu <= 57343) {
8434
- return false;
8435
- }
8436
- }
8437
- return true;
8438
- }
8439
8808
  function percentUnescape(s, plusAsSpace) {
8440
8809
  const bytes = stringToBytes(s);
8441
8810
  const out = [];
@@ -8648,13 +9017,13 @@ function globToRegExp(pattern) {
8648
9017
  var MATCHER_CACHE_MAX = 1000;
8649
9018
  var GLOB_MATCHER_CACHE = new Map;
8650
9019
  var REGEX_MATCHER_CACHE = new Map;
8651
- function cached(cache, pattern, build) {
8652
- let fn = cache.get(pattern);
9020
+ function cached(cache2, pattern, build) {
9021
+ let fn = cache2.get(pattern);
8653
9022
  if (fn === undefined) {
8654
9023
  fn = build(pattern);
8655
- if (cache.size >= MATCHER_CACHE_MAX)
8656
- cache.clear();
8657
- cache.set(pattern, fn);
9024
+ if (cache2.size >= MATCHER_CACHE_MAX)
9025
+ cache2.clear();
9026
+ cache2.set(pattern, fn);
8658
9027
  }
8659
9028
  return fn;
8660
9029
  }
@@ -8667,30 +9036,11 @@ function globMatcher(pattern) {
8667
9036
  return re.test(name);
8668
9037
  };
8669
9038
  }
8670
- function pcreToRegExp(pattern) {
8671
- let p = String(pattern);
8672
- let flags = "";
8673
- for (;; ) {
8674
- const m = /^\(\?([a-zA-Z]+)\)/.exec(p);
8675
- if (!m)
8676
- break;
8677
- for (const ch of m[1]) {
8678
- if (ch === "i" || ch === "m" || ch === "s") {
8679
- if (!flags.includes(ch))
8680
- flags += ch;
8681
- } else {
8682
- throw new Error(`Unsupported inline regex flag: ${ch}`);
8683
- }
8684
- }
8685
- p = p.substring(m[0].length);
8686
- }
8687
- return new RegExp(p, `${flags}g`);
8688
- }
8689
9039
  function regexMatcher(pattern) {
8690
- const re = pcreToRegExp(pattern);
9040
+ const re = compileRegex(pattern, "g");
8691
9041
  return (name) => {
8692
9042
  re.lastIndex = 0;
8693
- for (const m of name.matchAll(re)) {
9043
+ for (const m of toBytes(name).matchAll(re)) {
8694
9044
  if (m[0].length > 0)
8695
9045
  return true;
8696
9046
  }
@@ -9133,7 +9483,7 @@ function createTableModule() {
9133
9483
  if (value === undefined)
9134
9484
  return null;
9135
9485
  try {
9136
- return new RegExp(String(value));
9486
+ return compileRegex(String(value));
9137
9487
  } catch {
9138
9488
  return null;
9139
9489
  }
@@ -9144,103 +9494,6 @@ function createTableModule() {
9144
9494
  };
9145
9495
  }
9146
9496
 
9147
- // src/vcl-utf8.ts
9148
- var UTF8Module = {
9149
- is_valid: (s) => {
9150
- try {
9151
- const buf = Buffer.from(String(s), "utf-8");
9152
- return buf.toString("utf-8") === String(s);
9153
- } catch {
9154
- return false;
9155
- }
9156
- },
9157
- codepoint_count: (s) => {
9158
- const str = String(s);
9159
- try {
9160
- const buf = Buffer.from(str, "utf-8");
9161
- if (buf.toString("utf-8") !== str)
9162
- return 0;
9163
- } catch {
9164
- return 0;
9165
- }
9166
- return [...str].length;
9167
- },
9168
- substr: (s, offset, length) => {
9169
- const str = String(s);
9170
- try {
9171
- const buf = Buffer.from(str, "utf-8");
9172
- if (buf.toString("utf-8") !== str)
9173
- return null;
9174
- } catch {
9175
- return null;
9176
- }
9177
- const input = [...str];
9178
- const off = Math.trunc(Number(offset));
9179
- let start;
9180
- if (off < 0) {
9181
- start = input.length + off;
9182
- if (start < 0)
9183
- return "";
9184
- } else {
9185
- start = off;
9186
- }
9187
- let end;
9188
- if (length === undefined || length === null) {
9189
- end = input.length;
9190
- } else {
9191
- const len = Math.trunc(Number(length));
9192
- if (len < 0) {
9193
- end = input.length + len;
9194
- } else {
9195
- end = start + len;
9196
- if (end < 0)
9197
- return "";
9198
- }
9199
- }
9200
- if (end > input.length)
9201
- end = input.length;
9202
- if (start > input.length)
9203
- return "";
9204
- if (end <= start)
9205
- return "";
9206
- return input.slice(start, end).join("");
9207
- },
9208
- strpad: (s, width, pad) => {
9209
- const str = String(s);
9210
- const padStr = String(pad);
9211
- if (padStr === "")
9212
- return str;
9213
- const w = Math.trunc(Number(width));
9214
- if (!Number.isFinite(w) || w <= -Number.MAX_SAFE_INTEGER)
9215
- return "";
9216
- try {
9217
- const buf1 = Buffer.from(padStr, "utf-8");
9218
- if (buf1.toString("utf-8") !== padStr)
9219
- return null;
9220
- const buf2 = Buffer.from(str, "utf-8");
9221
- if (buf2.toString("utf-8") !== str)
9222
- return null;
9223
- } catch {
9224
- return null;
9225
- }
9226
- const origRunes = [...str];
9227
- const padRunes = [...padStr];
9228
- const origCount = origRunes.length;
9229
- const paddedCount = Math.abs(w);
9230
- if (origCount >= paddedCount)
9231
- return str;
9232
- const paddingCount = paddedCount - origCount;
9233
- const padding = [];
9234
- for (let i = 0;i < paddingCount; i++) {
9235
- padding.push(padRunes[i % padRunes.length]);
9236
- }
9237
- if (w < 0) {
9238
- return str + padding.join("");
9239
- }
9240
- return padding.join("") + str;
9241
- }
9242
- };
9243
-
9244
9497
  // src/vcl-uuid.ts
9245
9498
  import {
9246
9499
  parse,
@@ -9562,22 +9815,8 @@ function createVCLContext(platform = getPlatform()) {
9562
9815
  suffixof: (str, suffix) => String(str).endsWith(String(suffix)),
9563
9816
  replace: (str, search, replacement) => String(str).replace(String(search), String(replacement)),
9564
9817
  replaceall: (str, search, replacement) => String(str).split(String(search)).join(String(replacement)),
9565
- regsub: (str, regex, replacement) => {
9566
- try {
9567
- return String(str).replace(new RegExp(regex), replacement);
9568
- } catch (e) {
9569
- logError(`Invalid regex: ${regex}`, e);
9570
- return str;
9571
- }
9572
- },
9573
- regsuball: (str, regex, replacement) => {
9574
- try {
9575
- return String(str).replace(new RegExp(regex, "g"), replacement);
9576
- } catch (e) {
9577
- logError(`Invalid regex: ${regex}`, e);
9578
- return str;
9579
- }
9580
- },
9818
+ regsub,
9819
+ regsuball,
9581
9820
  integer: (value) => parseInt(String(value), 10) || 0,
9582
9821
  real: (value) => parseFloat(String(value)) || 0,
9583
9822
  math: {
@@ -9991,7 +10230,7 @@ Connection: close\r
9991
10230
  },
9992
10231
  lookup_regex: (tableName, key, defaultValue = "") => {
9993
10232
  const table = context.tables[tableName];
9994
- const defaultRegex = () => defaultValue ? new RegExp(defaultValue) : /(?:)/;
10233
+ const defaultRegex = () => defaultValue ? compileRegex(defaultValue) : /(?:)/;
9995
10234
  if (!table || !(key in table.entries))
9996
10235
  return defaultRegex();
9997
10236
  const value = table.entries[key];
@@ -9999,7 +10238,7 @@ Connection: close\r
9999
10238
  return value;
10000
10239
  if (typeof value === "string") {
10001
10240
  try {
10002
- return new RegExp(value);
10241
+ return compileRegex(value);
10003
10242
  } catch (e) {
10004
10243
  logError(`Invalid regex pattern: ${value}`, e);
10005
10244
  return defaultRegex();
@@ -10065,7 +10304,8 @@ Connection: close\r
10065
10304
  is_valid: UTF8Module.is_valid,
10066
10305
  codepoint_count: UTF8Module.codepoint_count,
10067
10306
  substr: UTF8Module.substr,
10068
- strpad: UTF8Module.strpad
10307
+ strpad: UTF8Module.strpad,
10308
+ translate: UTF8Module.translate
10069
10309
  };
10070
10310
  context.uuid = createUUIDModule(platform);
10071
10311
  const simpleHash = (str) => {
@@ -10215,7 +10455,7 @@ function executeVCL(subroutines, subroutineName, context) {
10215
10455
  var DEFAULT_TTL = 300;
10216
10456
  var DEFAULT_GRACE = 3600;
10217
10457
  var DEFAULT_STALE_WHILE_REVALIDATE = 10;
10218
- function toBytes(body) {
10458
+ function toBytes2(body) {
10219
10459
  if (typeof body === "string")
10220
10460
  return new TextEncoder().encode(body);
10221
10461
  if (body instanceof ArrayBuffer)
@@ -10225,13 +10465,51 @@ function toBytes(body) {
10225
10465
  function computeCacheKey(context) {
10226
10466
  return context.hashData && context.hashData.length > 0 ? context.hashData.join(":") : `${context.req.url}:${context.req.http.host || ""}`;
10227
10467
  }
10468
+ var DROPPED_ON_PASS = new Set([
10469
+ "alt-svc",
10470
+ "connection",
10471
+ "fastly-dsr-request",
10472
+ "fastly-shield-rp",
10473
+ "keep-alive",
10474
+ "te",
10475
+ "trailer",
10476
+ "upgrade"
10477
+ ]);
10478
+ var DROPPED_ON_POST_MISS = new Set([
10479
+ ...DROPPED_ON_PASS,
10480
+ "accept-ranges",
10481
+ "cache-control",
10482
+ "cdn-cache-control",
10483
+ "content-range",
10484
+ "fastly-cache-control",
10485
+ "proxy-authenticate",
10486
+ "proxy-authorization",
10487
+ "range"
10488
+ ]);
10489
+ var DROPPED_ON_MISS = new Set([
10490
+ ...DROPPED_ON_POST_MISS,
10491
+ "content-length",
10492
+ "if-modified-since",
10493
+ "if-none-match",
10494
+ "if-range",
10495
+ "transfer-encoding"
10496
+ ]);
10497
+ function initBackendRequest(context, mode) {
10498
+ const post = context.req.method === "POST";
10499
+ const dropped = mode === "pass" ? DROPPED_ON_PASS : post ? DROPPED_ON_POST_MISS : DROPPED_ON_MISS;
10500
+ context.bereq = {
10501
+ url: context.req.url,
10502
+ method: mode === "miss" && !post ? "GET" : context.req.method,
10503
+ http: Object.fromEntries(Object.entries(context.req.http).filter(([name]) => !dropped.has(name.toLowerCase())))
10504
+ };
10505
+ }
10228
10506
  function errorResult(context, key, restarts) {
10229
10507
  return {
10230
10508
  response: {
10231
10509
  status: context.obj.status || 500,
10232
10510
  statusText: "",
10233
10511
  headers: { ...context.obj.http },
10234
- body: toBytes(context.obj.response ?? "")
10512
+ body: toBytes2(context.obj.response ?? "")
10235
10513
  },
10236
10514
  action: "error",
10237
10515
  restarts,
@@ -10254,7 +10532,7 @@ async function runPipeline(opts) {
10254
10532
  }
10255
10533
  }
10256
10534
  async function runPass(opts) {
10257
- const { subroutines, context, cache, getBackendResponse } = opts;
10535
+ const { subroutines, context, cache: cache2, getBackendResponse } = opts;
10258
10536
  const now = () => context.platform.now();
10259
10537
  context.hashData = [];
10260
10538
  context.beresp.backend = undefined;
@@ -10288,7 +10566,7 @@ async function runPass(opts) {
10288
10566
  if (action === "lookup") {
10289
10567
  executeVCL(subroutines, "vcl_hash", context);
10290
10568
  key = computeCacheKey(context);
10291
- const cached2 = cache.get(key);
10569
+ const cached2 = cache2.get(key);
10292
10570
  if (cached2) {
10293
10571
  const at = now();
10294
10572
  const isFresh = at < cached2.expires;
@@ -10309,7 +10587,7 @@ async function runPass(opts) {
10309
10587
  return "restart";
10310
10588
  executeVCL(subroutines, "vcl_log", context);
10311
10589
  if (isStale)
10312
- cache.delete(key);
10590
+ cache2.delete(key);
10313
10591
  return {
10314
10592
  response: {
10315
10593
  status: context.resp.status,
@@ -10323,15 +10601,22 @@ async function runPass(opts) {
10323
10601
  };
10324
10602
  }
10325
10603
  } else {
10326
- cache.delete(key);
10604
+ cache2.delete(key);
10605
+ initBackendRequest(context, "miss");
10327
10606
  action = executeVCL(subroutines, "vcl_miss", context) || "fetch";
10328
10607
  }
10329
10608
  } else {
10609
+ initBackendRequest(context, "miss");
10330
10610
  action = executeVCL(subroutines, "vcl_miss", context) || "fetch";
10331
10611
  }
10332
- } else if (action === "pass") {
10612
+ }
10613
+ if (action === "pass") {
10614
+ key = "";
10615
+ initBackendRequest(context, "pass");
10333
10616
  action = executeVCL(subroutines, "vcl_pass", context) || "fetch";
10334
10617
  }
10618
+ if (action === "error")
10619
+ return errorResult(context, key, restarts);
10335
10620
  const passing = key === "";
10336
10621
  let backendResponse;
10337
10622
  try {
@@ -10376,7 +10661,7 @@ async function runPass(opts) {
10376
10661
  context.beresp.grace = DEFAULT_GRACE;
10377
10662
  context.beresp.stale_while_revalidate = DEFAULT_STALE_WHILE_REVALIDATE;
10378
10663
  }
10379
- const body = toBytes(backendResponse.body);
10664
+ const body = toBytes2(backendResponse.body);
10380
10665
  context.resp.status = context.beresp.status;
10381
10666
  context.resp.statusText = context.beresp.statusText;
10382
10667
  context.resp.http = { ...context.beresp.http };
@@ -10389,7 +10674,7 @@ async function runPass(opts) {
10389
10674
  const ttlMs = context.beresp.ttl * 1000;
10390
10675
  const graceMs = (context.beresp.grace || 0) * 1000;
10391
10676
  const swrMs = (context.beresp.stale_while_revalidate || 0) * 1000;
10392
- cache.set(key, {
10677
+ cache2.set(key, {
10393
10678
  resp: {
10394
10679
  status: context.resp.status,
10395
10680
  statusText: context.resp.statusText,