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/index.js CHANGED
@@ -261,6 +261,19 @@ function vclToString(v) {
261
261
  }
262
262
  return String(v);
263
263
  }
264
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
265
+ function isValidUtf8(s) {
266
+ return !LONE_SURROGATE.test(s);
267
+ }
268
+
269
+ class VCLFailure {
270
+ value;
271
+ error;
272
+ constructor(value, error) {
273
+ this.value = value;
274
+ this.error = error;
275
+ }
276
+ }
264
277
  function isNotSet(v) {
265
278
  return v instanceof VCLString && v.isNotSet;
266
279
  }
@@ -966,6 +979,7 @@ var BUILTIN_SIGNATURES = {
966
979
  ],
967
980
  ret: "STRING"
968
981
  },
982
+ "utf8.translate": { args: [["STRING", "STRING", "STRING"]], ret: "STRING" },
969
983
  "uuid.dns": { args: [], ret: "STRING" },
970
984
  "uuid.is_valid": { args: [["STRING"]], ret: "BOOL" },
971
985
  "uuid.is_version3": { args: [["STRING"]], ret: "BOOL" },
@@ -1522,14 +1536,269 @@ function collectCallStatements(statements) {
1522
1536
  return calls;
1523
1537
  }
1524
1538
 
1525
- // src/vcl-strings.ts
1539
+ // src/vcl-regex.ts
1526
1540
  var utf8Encoder = new TextEncoder;
1527
- var utf8Decoder = new TextDecoder;
1541
+ var utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
1542
+ var ASCII = /^[\x00-\x7f]*$/;
1543
+ function toBytes(s) {
1544
+ if (ASCII.test(s))
1545
+ return s;
1546
+ const bytes = utf8Encoder.encode(s);
1547
+ let out = "";
1548
+ for (let i = 0;i < bytes.length; i++)
1549
+ out += String.fromCharCode(bytes[i]);
1550
+ return out;
1551
+ }
1552
+ function fromBytes(s) {
1553
+ if (ASCII.test(s))
1554
+ return s;
1555
+ const bytes = new Uint8Array(s.length);
1556
+ for (let i = 0;i < s.length; i++)
1557
+ bytes[i] = s.charCodeAt(i);
1558
+ return utf8Decoder.decode(bytes);
1559
+ }
1560
+ var DIGIT = [[48, 57]];
1561
+ var UPPER = [[65, 90]];
1562
+ var LOWER = [[97, 122]];
1563
+ var ALPHA = [...UPPER, ...LOWER];
1564
+ var ALNUM = [...DIGIT, ...ALPHA];
1565
+ var WORD = [...ALNUM, [95, 95]];
1566
+ var BLANK = [
1567
+ [9, 9],
1568
+ [32, 32]
1569
+ ];
1570
+ var SPACE = [
1571
+ [9, 13],
1572
+ [32, 32]
1573
+ ];
1574
+ var SETS = {
1575
+ d: DIGIT,
1576
+ w: WORD,
1577
+ s: SPACE,
1578
+ h: [...BLANK, [160, 160]],
1579
+ v: [
1580
+ [10, 13],
1581
+ [133, 133]
1582
+ ]
1583
+ };
1584
+ var POSIX = {
1585
+ alpha: ALPHA,
1586
+ digit: DIGIT,
1587
+ alnum: ALNUM,
1588
+ upper: UPPER,
1589
+ lower: LOWER,
1590
+ space: SPACE,
1591
+ blank: BLANK,
1592
+ punct: [
1593
+ [33, 47],
1594
+ [58, 64],
1595
+ [91, 96],
1596
+ [123, 126]
1597
+ ],
1598
+ xdigit: [...DIGIT, [65, 70], [97, 102]],
1599
+ cntrl: [
1600
+ [0, 31],
1601
+ [127, 127]
1602
+ ],
1603
+ print: [[32, 126]],
1604
+ graph: [[33, 126]],
1605
+ word: WORD,
1606
+ ascii: [[0, 127]]
1607
+ };
1608
+ var ANCHORS = {
1609
+ A: "^",
1610
+ z: "$",
1611
+ Z: "(?=\\n?$)",
1612
+ b: "\\b",
1613
+ B: "\\B",
1614
+ R: "(?:\\r\\n|[\\n\\x0b\\f\\r\\x85])"
1615
+ };
1616
+ var SIMPLE_ESCAPES = {
1617
+ n: 10,
1618
+ r: 13,
1619
+ t: 9,
1620
+ f: 12,
1621
+ e: 27,
1622
+ a: 7,
1623
+ b: 8
1624
+ };
1625
+ function complement(ranges) {
1626
+ const out = [];
1627
+ let next = 0;
1628
+ for (const [lo, hi] of [...ranges].sort((a, b) => a[0] - b[0])) {
1629
+ if (lo > next)
1630
+ out.push([next, lo - 1]);
1631
+ next = Math.max(next, hi + 1);
1632
+ }
1633
+ if (next <= 255)
1634
+ out.push([next, 255]);
1635
+ return out;
1636
+ }
1637
+ function withOtherCase(ranges) {
1638
+ const out = [...ranges];
1639
+ for (const [lo, hi] of ranges) {
1640
+ for (const [a, z, shift] of [
1641
+ [65, 90, 32],
1642
+ [97, 122, -32]
1643
+ ]) {
1644
+ const l = Math.max(lo, a);
1645
+ const h = Math.min(hi, z);
1646
+ if (l <= h)
1647
+ out.push([l + shift, h + shift]);
1648
+ }
1649
+ }
1650
+ return out;
1651
+ }
1652
+ function classSource(ranges, negate, caseless) {
1653
+ const hex = (c) => `\\x${c.toString(16).padStart(2, "0")}`;
1654
+ const body = (caseless ? withOtherCase(ranges) : ranges).map(([lo, hi]) => lo === hi ? hex(lo) : `${hex(lo)}-${hex(hi)}`).join("");
1655
+ return `[${negate ? "^" : ""}${body}]`;
1656
+ }
1657
+ var isSingleChar = (r) => r.length === 1 && r[0][0] === r[0][1];
1658
+ function escapeRanges(p, i) {
1659
+ const c = p[i];
1660
+ const set = SETS[c.toLowerCase()];
1661
+ if (set)
1662
+ return [c === c.toLowerCase() ? set : complement(set), i + 1];
1663
+ let code = SIMPLE_ESCAPES[c];
1664
+ let next = i + 1;
1665
+ const braced = /^x\{([0-9a-fA-F]+)\}/.exec(p.slice(i));
1666
+ if (braced) {
1667
+ code = parseInt(braced[1], 16);
1668
+ next = i + braced[0].length;
1669
+ } else if (c === "x" && p[i + 1] !== "{" || c === "0") {
1670
+ const digits = (c === "x" ? /^[0-9a-f]{0,2}/i : /^[0-7]{0,2}/).exec(p.slice(i + 1))[0];
1671
+ code = digits ? parseInt(digits, c === "x" ? 16 : 8) : 0;
1672
+ next += digits.length;
1673
+ } else if (!/[a-z0-9]/i.test(c)) {
1674
+ code = c.charCodeAt(0);
1675
+ }
1676
+ if (code === undefined || code > 255) {
1677
+ throw new Error(`Unsupported regex escape \\${c}`);
1678
+ }
1679
+ return [[[code, code]], next];
1680
+ }
1681
+ function classItem(p, i) {
1682
+ return p[i] === "\\" ? escapeRanges(p, i + 1) : [[[p.charCodeAt(i), p.charCodeAt(i)]], i + 1];
1683
+ }
1684
+ function classAt(p, i, caseless) {
1685
+ const negate = p[i] === "^";
1686
+ if (negate)
1687
+ i++;
1688
+ const ranges = [];
1689
+ do {
1690
+ if (i >= p.length)
1691
+ throw new Error("Missing ] in regex character class");
1692
+ const posix = /^\[:(\^?)([a-z]+):\]/.exec(p.slice(i));
1693
+ if (posix) {
1694
+ const name = caseless && (posix[2] === "upper" || posix[2] === "lower") ? "alpha" : posix[2];
1695
+ const set = POSIX[name];
1696
+ if (!set)
1697
+ throw new Error(`Unknown POSIX class ${posix[0]}`);
1698
+ ranges.push(...posix[1] ? complement(set) : set);
1699
+ i += posix[0].length;
1700
+ continue;
1701
+ }
1702
+ let item;
1703
+ [item, i] = classItem(p, i);
1704
+ if (p[i] === "-" && p[i + 1] !== "]" && i + 1 < p.length) {
1705
+ const [end, next] = classItem(p, i + 1);
1706
+ if (!isSingleChar(item) || !isSingleChar(end) || item[0][0] > end[0][0]) {
1707
+ throw new Error("Invalid range in regex character class");
1708
+ }
1709
+ item = [[item[0][0], end[0][0]]];
1710
+ i = next;
1711
+ }
1712
+ ranges.push(...item);
1713
+ } while (p[i] !== "]");
1714
+ return [classSource(ranges, negate, caseless), i + 1];
1715
+ }
1716
+ function translate(p) {
1717
+ let out = "";
1718
+ let opts = "";
1719
+ const saved = [];
1720
+ let i = 0;
1721
+ while (i < p.length) {
1722
+ const c = p[i++];
1723
+ let m;
1724
+ if (c === "[") {
1725
+ let cls;
1726
+ [cls, i] = classAt(p, i, opts.includes("i"));
1727
+ out += cls;
1728
+ } else if (c === "(") {
1729
+ saved.push(opts);
1730
+ const rest = p.slice(i);
1731
+ if (m = /^\?#[^)]*\)/.exec(rest)) {
1732
+ saved.pop();
1733
+ } else if (m = /^\?P=(\w+)\)/.exec(rest)) {
1734
+ saved.pop();
1735
+ out += `\\k<${m[1]}>`;
1736
+ } else if (m = /^\?(?:P?<(\w+)>|'(\w+)')/.exec(rest)) {
1737
+ out += `(?<${m[1] ?? m[2]}>`;
1738
+ } else if (m = /^(?:\?[:=!]|\?<[=!]|(?!\?))/.exec(rest)) {
1739
+ out += `(${m[0]}`;
1740
+ } else if (m = /^\?([a-zA-Z]*)(?:-([a-zA-Z]*))?([:)])/.exec(rest)) {
1741
+ const [, on = "", off = "", end] = m;
1742
+ for (const f of on + off) {
1743
+ if (!"ims".includes(f))
1744
+ throw new Error(`Unsupported regex option (?${f})`);
1745
+ }
1746
+ if (end === ")")
1747
+ saved.pop();
1748
+ else
1749
+ out += "(?:";
1750
+ opts = [...opts + on].filter((f) => !off.includes(f)).join("");
1751
+ } else {
1752
+ throw new Error(`Unsupported regex group (${rest.slice(0, 2)}`);
1753
+ }
1754
+ i += m[0].length;
1755
+ } else if (c === ")") {
1756
+ opts = saved.pop() ?? opts;
1757
+ out += ")";
1758
+ } else if (c === ".") {
1759
+ out += opts.includes("s") ? "[\\s\\S]" : "[^\\n]";
1760
+ } else if (c === "^") {
1761
+ out += opts.includes("m") ? "(?:^|(?<=\\n)(?=[\\s\\S]))" : "^";
1762
+ } else if (c === "$") {
1763
+ out += opts.includes("m") ? "(?=\\n|$)" : "(?=\\n?$)";
1764
+ } else if (c !== "\\") {
1765
+ out += opts.includes("i") && /[a-z]/i.test(c) ? `[${c.toLowerCase()}${c.toUpperCase()}]` : c;
1766
+ } else if (p[i] === undefined) {
1767
+ throw new Error("Regex ends with a \\");
1768
+ } else if (ANCHORS[p[i]] !== undefined) {
1769
+ out += ANCHORS[p[i++]];
1770
+ } else if (m = /^(?:[1-9]\d*|k<\w+>)/.exec(p.slice(i))) {
1771
+ out += `(?:\\${m[0]})`;
1772
+ i += m[0].length;
1773
+ } else {
1774
+ let ranges;
1775
+ [ranges, i] = escapeRanges(p, i);
1776
+ out += classSource(ranges, false, opts.includes("i"));
1777
+ }
1778
+ }
1779
+ return out;
1780
+ }
1781
+ var cache = new Map;
1782
+ function compileRegex(pattern, flags = "") {
1783
+ const key = `${flags}/${pattern}`;
1784
+ let re = cache.get(key);
1785
+ if (re === undefined) {
1786
+ re = new RegExp(translate(toBytes(pattern)), flags);
1787
+ if (cache.size >= 1000)
1788
+ cache.clear();
1789
+ cache.set(key, re);
1790
+ }
1791
+ return re;
1792
+ }
1793
+
1794
+ // src/vcl-strings.ts
1795
+ var utf8Encoder2 = new TextEncoder;
1796
+ var utf8Decoder2 = new TextDecoder;
1528
1797
  function utf8Bytes(s) {
1529
- return utf8Encoder.encode(s);
1798
+ return utf8Encoder2.encode(s);
1530
1799
  }
1531
1800
  function decodeBytes(bytes) {
1532
- return utf8Decoder.decode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
1801
+ return utf8Decoder2.decode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
1533
1802
  }
1534
1803
  function isAlnumByte(b) {
1535
1804
  return b >= 65 && b <= 90 || b >= 97 && b <= 122 || b >= 48 && b <= 57;
@@ -1824,10 +2093,9 @@ var JSON_ESCAPE_MAP = new Map([
1824
2093
  [12, "\\f"],
1825
2094
  [13, "\\r"]
1826
2095
  ]);
1827
- var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
1828
2096
  function json_escape(str) {
1829
2097
  const s = String(str);
1830
- if (LONE_SURROGATE.test(s))
2098
+ if (!isValidUtf8(s))
1831
2099
  return "";
1832
2100
  let out = "";
1833
2101
  for (const ch of s) {
@@ -1905,33 +2173,34 @@ function expandReplacement(_input, replacement, match) {
1905
2173
  }
1906
2174
  function regsub(str, pattern, replacement) {
1907
2175
  try {
1908
- const s = String(str);
1909
- const re = new RegExp(pattern);
1910
- const match = re.exec(s);
2176
+ const s = toBytes(String(str));
2177
+ const match = compileRegex(String(pattern)).exec(s);
1911
2178
  if (!match)
1912
- return s;
1913
- return s.slice(0, match.index) + expandReplacement(s, replacement, match) + s.slice(match.index + match[0].length);
2179
+ return String(str);
2180
+ return fromBytes(s.slice(0, match.index) + expandReplacement(s, toBytes(String(replacement)), match) + s.slice(match.index + match[0].length));
1914
2181
  } catch {
1915
2182
  return str;
1916
2183
  }
1917
2184
  }
1918
2185
  function regsuball(str, pattern, replacement) {
1919
2186
  try {
1920
- const s = String(str);
1921
- const re = new RegExp(pattern, "g");
2187
+ const s = toBytes(String(str));
2188
+ const re = compileRegex(String(pattern), "g");
2189
+ re.lastIndex = 0;
2190
+ const sub = toBytes(String(replacement));
1922
2191
  let result = "";
1923
2192
  let lastEnd = 0;
1924
2193
  let match;
1925
2194
  while ((match = re.exec(s)) !== null) {
1926
2195
  result += s.slice(lastEnd, match.index);
1927
- result += expandReplacement(s, replacement, match);
2196
+ result += expandReplacement(s, sub, match);
1928
2197
  lastEnd = match.index + match[0].length;
1929
2198
  if (match[0].length === 0) {
1930
2199
  re.lastIndex++;
1931
2200
  }
1932
2201
  }
1933
2202
  result += s.slice(lastEnd);
1934
- return result;
2203
+ return fromBytes(result);
1935
2204
  } catch {
1936
2205
  return str;
1937
2206
  }
@@ -2015,6 +2284,9 @@ function strstr(haystack, needle) {
2015
2284
  }
2016
2285
  function strpad(s, width, pad) {
2017
2286
  const str = String(s);
2287
+ if (!Number.isFinite(width) || width <= -Number.MAX_SAFE_INTEGER) {
2288
+ return new VCLFailure("", "EDOM");
2289
+ }
2018
2290
  const w = Math.abs(Math.trunc(width));
2019
2291
  const sLen = utf8Bytes(str).length;
2020
2292
  if (sLen >= w)
@@ -3251,6 +3523,21 @@ function fastlyHash(key, seed, from, to) {
3251
3523
  return null;
3252
3524
  }
3253
3525
  var MAX_RTIME_SECONDS = 9223372036.854776;
3526
+ function urlComponents(url) {
3527
+ const pathEnd = url.search(/[?#]/);
3528
+ const path = pathEnd < 0 ? url : url.substring(0, pathEnd);
3529
+ const qs = url[pathEnd] === "?" ? url.substring(pathEnd + 1).split("#")[0] : "";
3530
+ const lastSlash = path.lastIndexOf("/");
3531
+ const basename2 = path.substring(lastSlash + 1);
3532
+ const dot = basename2.lastIndexOf(".");
3533
+ return {
3534
+ path,
3535
+ qs,
3536
+ dirname: lastSlash > 0 ? path.substring(0, lastSlash) : "/",
3537
+ basename: basename2,
3538
+ ext: dot >= 0 ? basename2.substring(dot + 1) : ""
3539
+ };
3540
+ }
3254
3541
  function serializeHeaders(headers) {
3255
3542
  if (!headers)
3256
3543
  return "";
@@ -4344,6 +4631,11 @@ class VCLCompiler {
4344
4631
  }
4345
4632
  evaluateFunctionCall(expression, context) {
4346
4633
  const result = this.evaluateFunctionCallInner(expression, context);
4634
+ if (result instanceof VCLFailure) {
4635
+ if (context.fastly)
4636
+ context.fastly.error = result.error;
4637
+ return coerceBuiltinReturn(expression.name, result.value);
4638
+ }
4347
4639
  const rule = NULL_RESULT_RULES[expression.name];
4348
4640
  if (rule && (result === null || result === undefined)) {
4349
4641
  if (context.fastly)
@@ -4738,11 +5030,7 @@ class VCLCompiler {
4738
5030
  return raw === undefined ? VCLString.notset() : firstHeaderFragment(raw);
4739
5031
  }
4740
5032
  if (parts.length === 3 && idPart0 === "re" && idPart1 === "group") {
4741
- const groupNumber = parseInt(idPart2, 10);
4742
- if (!Number.isNaN(groupNumber) && context.re?.groups?.[groupNumber] !== undefined) {
4743
- return context.re.groups[groupNumber];
4744
- }
4745
- return VCLString.notset();
5033
+ return context.re?.groups?.[idPart2] ?? VCLString.notset();
4746
5034
  }
4747
5035
  if (parts.length >= 2 && idPart0 === "var") {
4748
5036
  const varName = parts.slice(1).join(".");
@@ -4766,35 +5054,16 @@ class VCLCompiler {
4766
5054
  return context.obj.response ?? "";
4767
5055
  if (name === "req.url")
4768
5056
  return context.req.url;
4769
- if (name === "req.url.path") {
4770
- const url = context.req.url || "";
4771
- const qIdx = url.indexOf("?");
4772
- return qIdx >= 0 ? url.substring(0, qIdx) : url;
4773
- }
4774
- if (name === "req.url.qs") {
4775
- const url = context.req.url || "";
4776
- const qIdx = url.indexOf("?");
4777
- return qIdx >= 0 ? url.substring(qIdx + 1) : "";
4778
- }
4779
- if (name === "req.url.basename") {
4780
- const path = this.resolveVariable("req.url.path", context);
4781
- if (path === "")
4782
- return ".";
4783
- const lastSlash = path.lastIndexOf("/");
4784
- return lastSlash >= 0 ? path.substring(lastSlash + 1) : path;
4785
- }
4786
- if (name === "req.url.dirname") {
4787
- const path = this.resolveVariable("req.url.path", context);
4788
- if (path === "")
4789
- return ".";
4790
- const lastSlash = path.lastIndexOf("/");
4791
- return lastSlash >= 0 ? path.substring(0, lastSlash + 1) : "/";
4792
- }
4793
- if (name === "req.url.ext") {
4794
- const basename2 = this.resolveVariable("req.url.basename", context);
4795
- const dotIdx = basename2.lastIndexOf(".");
4796
- return dotIdx >= 0 ? basename2.substring(dotIdx + 1) : "";
4797
- }
5057
+ if (name === "req.url.path")
5058
+ return urlComponents(context.req.url).path;
5059
+ if (name === "req.url.qs")
5060
+ return urlComponents(context.req.url).qs;
5061
+ if (name === "req.url.basename")
5062
+ return urlComponents(context.req.url).basename;
5063
+ if (name === "req.url.dirname")
5064
+ return urlComponents(context.req.url).dirname;
5065
+ if (name === "req.url.ext")
5066
+ return urlComponents(context.req.url).ext;
4798
5067
  if (name === "req.method" || name === "req.request")
4799
5068
  return context.req.method;
4800
5069
  if (name === "req.backend")
@@ -4902,35 +5171,16 @@ class VCLCompiler {
4902
5171
  return context.bereq.method;
4903
5172
  if (name === "bereq.proto")
4904
5173
  return ctx.bereq?.proto || "HTTP/1.1";
4905
- if (name === "bereq.url.path") {
4906
- const url = context.bereq.url || "";
4907
- const qIdx = url.indexOf("?");
4908
- return qIdx >= 0 ? url.substring(0, qIdx) : url;
4909
- }
4910
- if (name === "bereq.url.qs") {
4911
- const url = context.bereq.url || "";
4912
- const qIdx = url.indexOf("?");
4913
- return qIdx >= 0 ? url.substring(qIdx + 1) : "";
4914
- }
4915
- if (name === "bereq.url.basename") {
4916
- const path = this.resolveVariable("bereq.url.path", context);
4917
- if (path === "")
4918
- return ".";
4919
- const lastSlash = path.lastIndexOf("/");
4920
- return lastSlash >= 0 ? path.substring(lastSlash + 1) : path;
4921
- }
4922
- if (name === "bereq.url.dirname") {
4923
- const path = this.resolveVariable("bereq.url.path", context);
4924
- if (path === "")
4925
- return ".";
4926
- const lastSlash = path.lastIndexOf("/");
4927
- return lastSlash >= 0 ? path.substring(0, lastSlash + 1) : "/";
4928
- }
4929
- if (name === "bereq.url.ext") {
4930
- const basename2 = this.resolveVariable("bereq.url.basename", context);
4931
- const dotIdx = basename2.lastIndexOf(".");
4932
- return dotIdx >= 0 ? basename2.substring(dotIdx + 1) : "";
4933
- }
5174
+ if (name === "bereq.url.path")
5175
+ return urlComponents(context.bereq.url).path;
5176
+ if (name === "bereq.url.qs")
5177
+ return urlComponents(context.bereq.url).qs;
5178
+ if (name === "bereq.url.basename")
5179
+ return urlComponents(context.bereq.url).basename;
5180
+ if (name === "bereq.url.dirname")
5181
+ return urlComponents(context.bereq.url).dirname;
5182
+ if (name === "bereq.url.ext")
5183
+ return urlComponents(context.bereq.url).ext;
4934
5184
  if (name === "bereq.headers")
4935
5185
  return serializeHeaders(context.bereq.http);
4936
5186
  if (name === "bereq.max_reuse_idle_time")
@@ -5503,13 +5753,20 @@ class VCLCompiler {
5503
5753
  }
5504
5754
  regexMatch(left, right, context, negate) {
5505
5755
  try {
5506
- const regex = right instanceof RegExp ? right : new RegExp(String(right));
5507
- const match = String(left).match(regex);
5756
+ const regex = right instanceof RegExp ? right : compileRegex(String(right));
5757
+ const match = regex.exec(toBytes(String(left)));
5758
+ context.re = undefined;
5508
5759
  if (match) {
5509
- const groups = {};
5760
+ const groups = Object.create(null);
5510
5761
  match.forEach((val, i) => {
5511
- groups[i] = val ?? "";
5762
+ if (val !== undefined)
5763
+ groups[i] = fromBytes(val);
5512
5764
  });
5765
+ for (const name in match.groups) {
5766
+ const val = match.groups[name];
5767
+ if (val !== undefined)
5768
+ groups[name] = fromBytes(val);
5769
+ }
5513
5770
  context.re = { groups };
5514
5771
  return !negate;
5515
5772
  }
@@ -6213,6 +6470,112 @@ function createMathModule() {
6213
6470
  };
6214
6471
  }
6215
6472
 
6473
+ // src/vcl-utf8.ts
6474
+ function isNullArg(value) {
6475
+ return value === null || value === undefined || isNotSet(value);
6476
+ }
6477
+ var lastSets = null;
6478
+ var lastTable = new Map;
6479
+ function translationTable(set1, set2) {
6480
+ const key = `${set1}\x00${set2}`;
6481
+ if (key === lastSets)
6482
+ return lastTable;
6483
+ const from = [...set1];
6484
+ const to = [...set2];
6485
+ const table = new Map;
6486
+ for (let i = 0;i < from.length; i++) {
6487
+ const character = from[i];
6488
+ if (!table.has(character))
6489
+ table.set(character, to[Math.min(i, to.length - 1)]);
6490
+ }
6491
+ lastSets = key;
6492
+ lastTable = table;
6493
+ return table;
6494
+ }
6495
+ function translateSetsError(set1, set2) {
6496
+ const count1 = [...set1].length;
6497
+ const count2 = [...set2].length;
6498
+ if (count1 === 0)
6499
+ return "Characters required in set1";
6500
+ if (count2 === 0)
6501
+ return "Characters required in set2";
6502
+ if (count2 > count1) {
6503
+ return `Excess characters in set2: Expected ${count1} or fewer, got ${count2}`;
6504
+ }
6505
+ return null;
6506
+ }
6507
+ var UTF8Module = {
6508
+ is_valid: (s) => !isNullArg(s) && isValidUtf8(toRawString(s)),
6509
+ codepoint_count: (s) => {
6510
+ const str = toRawString(s);
6511
+ return isValidUtf8(str) ? [...str].length : 0;
6512
+ },
6513
+ substr: (s, offset, length) => {
6514
+ if (isNullArg(s))
6515
+ return null;
6516
+ const str = toRawString(s);
6517
+ if (!isValidUtf8(str))
6518
+ return null;
6519
+ const runes = [...str];
6520
+ const count = runes.length;
6521
+ let start = Math.trunc(Number(offset));
6522
+ if (!Number.isFinite(start))
6523
+ return null;
6524
+ if (start < 0)
6525
+ start += count;
6526
+ if (start < 0 || start > count)
6527
+ return null;
6528
+ let len;
6529
+ if (length === undefined) {
6530
+ len = count - start;
6531
+ } else {
6532
+ len = Math.trunc(Number(length));
6533
+ if (!Number.isFinite(len))
6534
+ return null;
6535
+ if (len < 0)
6536
+ len += count - start;
6537
+ }
6538
+ if (len < 0)
6539
+ len = 0;
6540
+ return runes.slice(start, start + len).join("");
6541
+ },
6542
+ strpad: (s, width, pad) => {
6543
+ const str = toRawString(s);
6544
+ const padStr = toRawString(pad);
6545
+ if (padStr === "")
6546
+ return str;
6547
+ const w = Math.trunc(Number(width));
6548
+ if (!Number.isFinite(w) || w <= -Number.MAX_SAFE_INTEGER)
6549
+ return new VCLFailure("", "EDOM");
6550
+ if (!isValidUtf8(padStr) || !isValidUtf8(str))
6551
+ return new VCLFailure(null, "EUTF8");
6552
+ const runes = [...str];
6553
+ const padRunes = [...padStr];
6554
+ const paddedCount = Math.abs(w);
6555
+ if (runes.length >= paddedCount)
6556
+ return str;
6557
+ const paddingCount = paddedCount - runes.length;
6558
+ const padding = [];
6559
+ for (let i = 0;i < paddingCount; i++)
6560
+ padding.push(padRunes[i % padRunes.length]);
6561
+ return w < 0 ? str + padding.join("") : padding.join("") + str;
6562
+ },
6563
+ translate: (input, set1, set2) => {
6564
+ const str = toRawString(input);
6565
+ if (!isValidUtf8(str))
6566
+ return new VCLFailure(null, "EUTF8");
6567
+ const from = toRawString(set1);
6568
+ const to = toRawString(set2);
6569
+ if (from === "" || to === "")
6570
+ return str;
6571
+ const table = translationTable(from, to);
6572
+ let out = "";
6573
+ for (const rune of str)
6574
+ out += table.get(rune) ?? rune;
6575
+ return out;
6576
+ }
6577
+ };
6578
+
6216
6579
  // src/vcl-parser-impl.ts
6217
6580
  var INT64_MAX = 2n ** 63n - 1n;
6218
6581
  var INT64_MIN_MAGNITUDE = 2n ** 63n;
@@ -6262,6 +6625,20 @@ var RETURN_ACTIONS = new Set([
6262
6625
  "hit_for_pass",
6263
6626
  "upgrade"
6264
6627
  ]);
6628
+ function constantString(expression) {
6629
+ if (expression.type === "StringLiteral")
6630
+ return expression.value;
6631
+ if (expression.type === "BinaryExpression") {
6632
+ if (expression.operator !== "+" && expression.operator !== " ")
6633
+ return null;
6634
+ const left = constantString(expression.left);
6635
+ if (left === null)
6636
+ return null;
6637
+ const right = constantString(expression.right);
6638
+ return right === null ? null : left + right;
6639
+ }
6640
+ return null;
6641
+ }
6265
6642
 
6266
6643
  class VCLParser {
6267
6644
  tokens = [];
@@ -7800,9 +8177,9 @@ class VCLParser {
7800
8177
  previous() {
7801
8178
  return this.tokens[this.current - 1];
7802
8179
  }
7803
- error(message) {
7804
- const token = this.peek();
7805
- throw new Error(`${message} at line ${token.line}, column ${token.column}`);
8180
+ error(message, at) {
8181
+ const where = at?.location ?? this.peek();
8182
+ throw new Error(`${message} at line ${where.line}, column ${where.column}`);
7806
8183
  }
7807
8184
  parseFunctionCall(token) {
7808
8185
  const name = token.value;
@@ -7814,6 +8191,9 @@ class VCLParser {
7814
8191
  } while (this.match("PUNCTUATION" /* PUNCTUATION */, ","));
7815
8192
  }
7816
8193
  this.consume("PUNCTUATION" /* PUNCTUATION */, "Expected ')' after function arguments");
8194
+ if (name === "utf8.translate" && args.length === 3) {
8195
+ this.checkTranslateSets(args[1], args[2]);
8196
+ }
7817
8197
  let result = {
7818
8198
  type: "FunctionCall",
7819
8199
  name,
@@ -7838,11 +8218,23 @@ class VCLParser {
7838
8218
  }
7839
8219
  return result;
7840
8220
  }
8221
+ checkTranslateSets(set1Expression, set2Expression) {
8222
+ const set1 = constantString(set1Expression);
8223
+ if (set1 === null)
8224
+ this.error("Expected a constant string for set1", set1Expression);
8225
+ const set2 = constantString(set2Expression);
8226
+ if (set2 === null)
8227
+ this.error("Expected a constant string for set2", set2Expression);
8228
+ const problem = translateSetsError(set1, set2);
8229
+ if (problem !== null) {
8230
+ this.error(problem, problem.includes("set1") ? set1Expression : set2Expression);
8231
+ }
8232
+ }
7841
8233
  }
7842
8234
 
7843
8235
  // src/vcl-parser.ts
7844
8236
  var UTF8_ENCODER = new TextEncoder;
7845
- var UTF8_STRICT_DECODER = new TextDecoder("utf-8", { fatal: true });
8237
+ var UTF8_STRICT_DECODER = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
7846
8238
  var LONG_STRING_OPEN_RE = /\{([A-Za-z0-9_]*)"/y;
7847
8239
  var RTIME_UNITS = new Set(["ms", "s", "m", "h", "d", "w", "y"]);
7848
8240
  var UNIT_BOUNDARY = /[a-zA-Z0-9_.:-]/;
@@ -8080,14 +8472,8 @@ class VCLLexer {
8080
8472
  const raw = this.input.substring(this.position, rawEnd);
8081
8473
  let content;
8082
8474
  if (!raw.includes("%")) {
8083
- for (const ch of raw) {
8084
- if (ch === `
8085
- `) {
8086
- this.line++;
8087
- this.column = 1;
8088
- }
8089
- this.advance();
8090
- }
8475
+ while (this.position < rawEnd)
8476
+ this.advanceTrackingLine();
8091
8477
  if (this.position < this.input.length)
8092
8478
  this.advance();
8093
8479
  content = raw;
@@ -8409,23 +8795,6 @@ function bytesToString(bytes) {
8409
8795
  }
8410
8796
  return out;
8411
8797
  }
8412
- function isValidUtf8(s) {
8413
- for (let i = 0;i < s.length; i++) {
8414
- const cu = s.charCodeAt(i);
8415
- if (cu >= 55296 && cu <= 56319) {
8416
- const lo = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
8417
- if (lo >= 56320 && lo <= 57343) {
8418
- i++;
8419
- continue;
8420
- }
8421
- return false;
8422
- }
8423
- if (cu >= 56320 && cu <= 57343) {
8424
- return false;
8425
- }
8426
- }
8427
- return true;
8428
- }
8429
8798
  function percentUnescape(s, plusAsSpace) {
8430
8799
  const bytes = stringToBytes(s);
8431
8800
  const out = [];
@@ -8638,13 +9007,13 @@ function globToRegExp(pattern) {
8638
9007
  var MATCHER_CACHE_MAX = 1000;
8639
9008
  var GLOB_MATCHER_CACHE = new Map;
8640
9009
  var REGEX_MATCHER_CACHE = new Map;
8641
- function cached(cache, pattern, build) {
8642
- let fn = cache.get(pattern);
9010
+ function cached(cache2, pattern, build) {
9011
+ let fn = cache2.get(pattern);
8643
9012
  if (fn === undefined) {
8644
9013
  fn = build(pattern);
8645
- if (cache.size >= MATCHER_CACHE_MAX)
8646
- cache.clear();
8647
- cache.set(pattern, fn);
9014
+ if (cache2.size >= MATCHER_CACHE_MAX)
9015
+ cache2.clear();
9016
+ cache2.set(pattern, fn);
8648
9017
  }
8649
9018
  return fn;
8650
9019
  }
@@ -8657,30 +9026,11 @@ function globMatcher(pattern) {
8657
9026
  return re.test(name);
8658
9027
  };
8659
9028
  }
8660
- function pcreToRegExp(pattern) {
8661
- let p = String(pattern);
8662
- let flags = "";
8663
- for (;; ) {
8664
- const m = /^\(\?([a-zA-Z]+)\)/.exec(p);
8665
- if (!m)
8666
- break;
8667
- for (const ch of m[1]) {
8668
- if (ch === "i" || ch === "m" || ch === "s") {
8669
- if (!flags.includes(ch))
8670
- flags += ch;
8671
- } else {
8672
- throw new Error(`Unsupported inline regex flag: ${ch}`);
8673
- }
8674
- }
8675
- p = p.substring(m[0].length);
8676
- }
8677
- return new RegExp(p, `${flags}g`);
8678
- }
8679
9029
  function regexMatcher(pattern) {
8680
- const re = pcreToRegExp(pattern);
9030
+ const re = compileRegex(pattern, "g");
8681
9031
  return (name) => {
8682
9032
  re.lastIndex = 0;
8683
- for (const m of name.matchAll(re)) {
9033
+ for (const m of toBytes(name).matchAll(re)) {
8684
9034
  if (m[0].length > 0)
8685
9035
  return true;
8686
9036
  }
@@ -9123,7 +9473,7 @@ function createTableModule() {
9123
9473
  if (value === undefined)
9124
9474
  return null;
9125
9475
  try {
9126
- return new RegExp(String(value));
9476
+ return compileRegex(String(value));
9127
9477
  } catch {
9128
9478
  return null;
9129
9479
  }
@@ -9134,103 +9484,6 @@ function createTableModule() {
9134
9484
  };
9135
9485
  }
9136
9486
 
9137
- // src/vcl-utf8.ts
9138
- var UTF8Module = {
9139
- is_valid: (s) => {
9140
- try {
9141
- const buf = Buffer.from(String(s), "utf-8");
9142
- return buf.toString("utf-8") === String(s);
9143
- } catch {
9144
- return false;
9145
- }
9146
- },
9147
- codepoint_count: (s) => {
9148
- const str = String(s);
9149
- try {
9150
- const buf = Buffer.from(str, "utf-8");
9151
- if (buf.toString("utf-8") !== str)
9152
- return 0;
9153
- } catch {
9154
- return 0;
9155
- }
9156
- return [...str].length;
9157
- },
9158
- substr: (s, offset, length) => {
9159
- const str = String(s);
9160
- try {
9161
- const buf = Buffer.from(str, "utf-8");
9162
- if (buf.toString("utf-8") !== str)
9163
- return null;
9164
- } catch {
9165
- return null;
9166
- }
9167
- const input = [...str];
9168
- const off = Math.trunc(Number(offset));
9169
- let start;
9170
- if (off < 0) {
9171
- start = input.length + off;
9172
- if (start < 0)
9173
- return "";
9174
- } else {
9175
- start = off;
9176
- }
9177
- let end;
9178
- if (length === undefined || length === null) {
9179
- end = input.length;
9180
- } else {
9181
- const len = Math.trunc(Number(length));
9182
- if (len < 0) {
9183
- end = input.length + len;
9184
- } else {
9185
- end = start + len;
9186
- if (end < 0)
9187
- return "";
9188
- }
9189
- }
9190
- if (end > input.length)
9191
- end = input.length;
9192
- if (start > input.length)
9193
- return "";
9194
- if (end <= start)
9195
- return "";
9196
- return input.slice(start, end).join("");
9197
- },
9198
- strpad: (s, width, pad) => {
9199
- const str = String(s);
9200
- const padStr = String(pad);
9201
- if (padStr === "")
9202
- return str;
9203
- const w = Math.trunc(Number(width));
9204
- if (!Number.isFinite(w) || w <= -Number.MAX_SAFE_INTEGER)
9205
- return "";
9206
- try {
9207
- const buf1 = Buffer.from(padStr, "utf-8");
9208
- if (buf1.toString("utf-8") !== padStr)
9209
- return null;
9210
- const buf2 = Buffer.from(str, "utf-8");
9211
- if (buf2.toString("utf-8") !== str)
9212
- return null;
9213
- } catch {
9214
- return null;
9215
- }
9216
- const origRunes = [...str];
9217
- const padRunes = [...padStr];
9218
- const origCount = origRunes.length;
9219
- const paddedCount = Math.abs(w);
9220
- if (origCount >= paddedCount)
9221
- return str;
9222
- const paddingCount = paddedCount - origCount;
9223
- const padding = [];
9224
- for (let i = 0;i < paddingCount; i++) {
9225
- padding.push(padRunes[i % padRunes.length]);
9226
- }
9227
- if (w < 0) {
9228
- return str + padding.join("");
9229
- }
9230
- return padding.join("") + str;
9231
- }
9232
- };
9233
-
9234
9487
  // src/vcl-uuid.ts
9235
9488
  import {
9236
9489
  parse,
@@ -9552,22 +9805,8 @@ function createVCLContext(platform = getPlatform()) {
9552
9805
  suffixof: (str, suffix) => String(str).endsWith(String(suffix)),
9553
9806
  replace: (str, search, replacement) => String(str).replace(String(search), String(replacement)),
9554
9807
  replaceall: (str, search, replacement) => String(str).split(String(search)).join(String(replacement)),
9555
- regsub: (str, regex, replacement) => {
9556
- try {
9557
- return String(str).replace(new RegExp(regex), replacement);
9558
- } catch (e) {
9559
- logError(`Invalid regex: ${regex}`, e);
9560
- return str;
9561
- }
9562
- },
9563
- regsuball: (str, regex, replacement) => {
9564
- try {
9565
- return String(str).replace(new RegExp(regex, "g"), replacement);
9566
- } catch (e) {
9567
- logError(`Invalid regex: ${regex}`, e);
9568
- return str;
9569
- }
9570
- },
9808
+ regsub,
9809
+ regsuball,
9571
9810
  integer: (value) => parseInt(String(value), 10) || 0,
9572
9811
  real: (value) => parseFloat(String(value)) || 0,
9573
9812
  math: {
@@ -9981,7 +10220,7 @@ Connection: close\r
9981
10220
  },
9982
10221
  lookup_regex: (tableName, key, defaultValue = "") => {
9983
10222
  const table = context.tables[tableName];
9984
- const defaultRegex = () => defaultValue ? new RegExp(defaultValue) : /(?:)/;
10223
+ const defaultRegex = () => defaultValue ? compileRegex(defaultValue) : /(?:)/;
9985
10224
  if (!table || !(key in table.entries))
9986
10225
  return defaultRegex();
9987
10226
  const value = table.entries[key];
@@ -9989,7 +10228,7 @@ Connection: close\r
9989
10228
  return value;
9990
10229
  if (typeof value === "string") {
9991
10230
  try {
9992
- return new RegExp(value);
10231
+ return compileRegex(value);
9993
10232
  } catch (e) {
9994
10233
  logError(`Invalid regex pattern: ${value}`, e);
9995
10234
  return defaultRegex();
@@ -10055,7 +10294,8 @@ Connection: close\r
10055
10294
  is_valid: UTF8Module.is_valid,
10056
10295
  codepoint_count: UTF8Module.codepoint_count,
10057
10296
  substr: UTF8Module.substr,
10058
- strpad: UTF8Module.strpad
10297
+ strpad: UTF8Module.strpad,
10298
+ translate: UTF8Module.translate
10059
10299
  };
10060
10300
  context.uuid = createUUIDModule(platform);
10061
10301
  const simpleHash = (str) => {
@@ -10213,7 +10453,7 @@ function loadVCL(filePath) {
10213
10453
  var DEFAULT_TTL = 300;
10214
10454
  var DEFAULT_GRACE = 3600;
10215
10455
  var DEFAULT_STALE_WHILE_REVALIDATE = 10;
10216
- function toBytes(body) {
10456
+ function toBytes2(body) {
10217
10457
  if (typeof body === "string")
10218
10458
  return new TextEncoder().encode(body);
10219
10459
  if (body instanceof ArrayBuffer)
@@ -10223,13 +10463,51 @@ function toBytes(body) {
10223
10463
  function computeCacheKey(context) {
10224
10464
  return context.hashData && context.hashData.length > 0 ? context.hashData.join(":") : `${context.req.url}:${context.req.http.host || ""}`;
10225
10465
  }
10466
+ var DROPPED_ON_PASS = new Set([
10467
+ "alt-svc",
10468
+ "connection",
10469
+ "fastly-dsr-request",
10470
+ "fastly-shield-rp",
10471
+ "keep-alive",
10472
+ "te",
10473
+ "trailer",
10474
+ "upgrade"
10475
+ ]);
10476
+ var DROPPED_ON_POST_MISS = new Set([
10477
+ ...DROPPED_ON_PASS,
10478
+ "accept-ranges",
10479
+ "cache-control",
10480
+ "cdn-cache-control",
10481
+ "content-range",
10482
+ "fastly-cache-control",
10483
+ "proxy-authenticate",
10484
+ "proxy-authorization",
10485
+ "range"
10486
+ ]);
10487
+ var DROPPED_ON_MISS = new Set([
10488
+ ...DROPPED_ON_POST_MISS,
10489
+ "content-length",
10490
+ "if-modified-since",
10491
+ "if-none-match",
10492
+ "if-range",
10493
+ "transfer-encoding"
10494
+ ]);
10495
+ function initBackendRequest(context, mode) {
10496
+ const post = context.req.method === "POST";
10497
+ const dropped = mode === "pass" ? DROPPED_ON_PASS : post ? DROPPED_ON_POST_MISS : DROPPED_ON_MISS;
10498
+ context.bereq = {
10499
+ url: context.req.url,
10500
+ method: mode === "miss" && !post ? "GET" : context.req.method,
10501
+ http: Object.fromEntries(Object.entries(context.req.http).filter(([name]) => !dropped.has(name.toLowerCase())))
10502
+ };
10503
+ }
10226
10504
  function errorResult(context, key, restarts) {
10227
10505
  return {
10228
10506
  response: {
10229
10507
  status: context.obj.status || 500,
10230
10508
  statusText: "",
10231
10509
  headers: { ...context.obj.http },
10232
- body: toBytes(context.obj.response ?? "")
10510
+ body: toBytes2(context.obj.response ?? "")
10233
10511
  },
10234
10512
  action: "error",
10235
10513
  restarts,
@@ -10252,7 +10530,7 @@ async function runPipeline(opts) {
10252
10530
  }
10253
10531
  }
10254
10532
  async function runPass(opts) {
10255
- const { subroutines, context, cache, getBackendResponse } = opts;
10533
+ const { subroutines, context, cache: cache2, getBackendResponse } = opts;
10256
10534
  const now = () => context.platform.now();
10257
10535
  context.hashData = [];
10258
10536
  context.beresp.backend = undefined;
@@ -10286,7 +10564,7 @@ async function runPass(opts) {
10286
10564
  if (action === "lookup") {
10287
10565
  executeVCL(subroutines, "vcl_hash", context);
10288
10566
  key = computeCacheKey(context);
10289
- const cached2 = cache.get(key);
10567
+ const cached2 = cache2.get(key);
10290
10568
  if (cached2) {
10291
10569
  const at = now();
10292
10570
  const isFresh = at < cached2.expires;
@@ -10307,7 +10585,7 @@ async function runPass(opts) {
10307
10585
  return "restart";
10308
10586
  executeVCL(subroutines, "vcl_log", context);
10309
10587
  if (isStale)
10310
- cache.delete(key);
10588
+ cache2.delete(key);
10311
10589
  return {
10312
10590
  response: {
10313
10591
  status: context.resp.status,
@@ -10321,15 +10599,22 @@ async function runPass(opts) {
10321
10599
  };
10322
10600
  }
10323
10601
  } else {
10324
- cache.delete(key);
10602
+ cache2.delete(key);
10603
+ initBackendRequest(context, "miss");
10325
10604
  action = executeVCL(subroutines, "vcl_miss", context) || "fetch";
10326
10605
  }
10327
10606
  } else {
10607
+ initBackendRequest(context, "miss");
10328
10608
  action = executeVCL(subroutines, "vcl_miss", context) || "fetch";
10329
10609
  }
10330
- } else if (action === "pass") {
10610
+ }
10611
+ if (action === "pass") {
10612
+ key = "";
10613
+ initBackendRequest(context, "pass");
10331
10614
  action = executeVCL(subroutines, "vcl_pass", context) || "fetch";
10332
10615
  }
10616
+ if (action === "error")
10617
+ return errorResult(context, key, restarts);
10333
10618
  const passing = key === "";
10334
10619
  let backendResponse;
10335
10620
  try {
@@ -10374,7 +10659,7 @@ async function runPass(opts) {
10374
10659
  context.beresp.grace = DEFAULT_GRACE;
10375
10660
  context.beresp.stale_while_revalidate = DEFAULT_STALE_WHILE_REVALIDATE;
10376
10661
  }
10377
- const body = toBytes(backendResponse.body);
10662
+ const body = toBytes2(backendResponse.body);
10378
10663
  context.resp.status = context.beresp.status;
10379
10664
  context.resp.statusText = context.beresp.statusText;
10380
10665
  context.resp.http = { ...context.beresp.http };
@@ -10387,7 +10672,7 @@ async function runPass(opts) {
10387
10672
  const ttlMs = context.beresp.ttl * 1000;
10388
10673
  const graceMs = (context.beresp.grace || 0) * 1000;
10389
10674
  const swrMs = (context.beresp.stale_while_revalidate || 0) * 1000;
10390
- cache.set(key, {
10675
+ cache2.set(key, {
10391
10676
  resp: {
10392
10677
  status: context.resp.status,
10393
10678
  statusText: context.resp.statusText,