@promptctl/go-template-js 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -78,6 +78,9 @@ var ArgCountError = class extends EvalError {
78
78
  this.got = got;
79
79
  }
80
80
  };
81
+ function isStackOverflow(e) {
82
+ return (e instanceof RangeError || e instanceof Error && e.name === "InternalError") && (e.message.includes("call stack") || e.message.includes("too much recursion"));
83
+ }
81
84
  var TypeMismatchError = class extends EvalError {
82
85
  name = "TypeMismatchError";
83
86
  kind = "TypeMismatchError";
@@ -87,7 +90,7 @@ var TypeMismatchError = class extends EvalError {
87
90
  expected;
88
91
  receivedSummary;
89
92
  constructor(funcName, argIndex, expected, receivedSummary, pos, ctx = {}) {
90
- super(`function ${JSON.stringify(funcName)} arg ${argIndex}: expected ${expected}, but a ${receivedSummary} flowed in. Pass it through \`unstyled\` (or your engine's flatten function) to convert.`, pos, ctx);
93
+ super(`function ${JSON.stringify(funcName)} arg ${argIndex}: expected ${expected}, but a value of type ${receivedSummary} flowed in. Pass it through \`unstyled\` (or your engine's flatten function) to convert.`, pos, ctx);
91
94
  this.funcName = funcName;
92
95
  this.argIndex = argIndex;
93
96
  this.expected = expected;
@@ -599,7 +602,7 @@ function isIdentPart(c) {
599
602
  /**
600
603
  * The named sub-templates a template can invoke: the ones its own source
601
604
  * declared plus, transitively, the ones it inherited at parse. Opaque: only
602
- * `has` and the `EMPTY` identity are public, so a consumer can neither build
605
+ * `has`, `names` and the `EMPTY` identity are public, so a consumer can neither build
603
606
  * one by hand (the parser is the single enforcer of the redefinition invariant
604
607
  * below) nor reach the AST inside — the entry lookup is `lookupDefine`, a
605
608
  * module export index.ts never re-exports.
@@ -635,10 +638,26 @@ var Defines = class Defines {
635
638
  has(name) {
636
639
  return readDefine(this, name) !== void 0;
637
640
  }
641
+ /**
642
+ * Every name this set can render, own and inherited, sorted — what a
643
+ * consumer reads after `evaluateDefine` reports a name as not defined.
644
+ * The parser forbids redeclaring an inherited name, so the chain repeats
645
+ * none; the Set keeps the listing duplicate-free without leaning on that.
646
+ */
647
+ names() {
648
+ const names = /* @__PURE__ */ new Set();
649
+ for (let d = this; d; d = d.#parent) for (const name of d.#own.keys()) names.add(name);
650
+ return [...names].sort();
651
+ }
638
652
  };
639
653
  function parse(source, delims, inherit = Defines.EMPTY) {
640
654
  return new Parser(source, delims, inherit).parseTemplate();
641
655
  }
656
+ const PIPELINE_CONTEXT = {
657
+ If: "if",
658
+ Range: "range",
659
+ With: "with"
660
+ };
642
661
  var Parser = class {
643
662
  lex;
644
663
  buf = [];
@@ -760,7 +779,7 @@ var Parser = class {
760
779
  return null;
761
780
  case "RightDelim": throw this.errAt(head, "empty action", { expected: "pipeline" });
762
781
  default: {
763
- const pipe = this.parsePipeline();
782
+ const pipe = this.parsePipeline("command");
764
783
  const right = this.expect("RightDelim", "`}}`");
765
784
  return {
766
785
  type: "Action",
@@ -775,7 +794,7 @@ var Parser = class {
775
794
  }
776
795
  }
777
796
  parseBranch(kind, startPos, trimLeft) {
778
- const pipe = this.parsePipeline();
797
+ const pipe = this.parsePipeline(PIPELINE_CONTEXT[kind]);
779
798
  this.expect("RightDelim", "`}}`");
780
799
  if (kind === "Range") this.rangeDepth += 1;
781
800
  const list = this.parseList();
@@ -873,7 +892,7 @@ var Parser = class {
873
892
  }
874
893
  parseTemplateInvocation(startPos, trimLeft) {
875
894
  const name = this.parseQuotedName();
876
- const pipe = this.peek().type === "RightDelim" ? void 0 : this.parsePipeline();
895
+ const pipe = this.peek().type === "RightDelim" ? void 0 : this.parsePipeline("template clause");
877
896
  const trim = {
878
897
  trimLeft,
879
898
  trimRight: this.expect("RightDelim", "`}}`").trimRight === true
@@ -893,7 +912,7 @@ var Parser = class {
893
912
  }
894
913
  parseBlock(startPos, trimLeft) {
895
914
  const name = this.parseQuotedName();
896
- const pipe = this.peek().type === "RightDelim" ? void 0 : this.parsePipeline();
915
+ const pipe = this.parsePipeline("block clause");
897
916
  this.expect("RightDelim", "`}}`");
898
917
  const savedDepth = this.rangeDepth;
899
918
  this.rangeDepth = 0;
@@ -907,19 +926,13 @@ var Parser = class {
907
926
  list,
908
927
  source: this.source
909
928
  });
910
- return pipe ? {
929
+ return {
911
930
  type: "Block",
912
931
  pos: startPos,
913
932
  name,
914
933
  pipe,
915
934
  list,
916
935
  trim
917
- } : {
918
- type: "Block",
919
- pos: startPos,
920
- name,
921
- list,
922
- trim
923
936
  };
924
937
  }
925
938
  parseDefine(_startPos, _trimLeft) {
@@ -944,9 +957,11 @@ var Parser = class {
944
957
  });
945
958
  return decodeStringLiteral(t.value, t.pos, this.source);
946
959
  }
947
- parsePipeline() {
960
+ parsePipeline(context) {
948
961
  const startPos = this.peek().pos;
949
- const decls = this.tryParseDecls();
962
+ const decls = this.tryParseDecls(context);
963
+ const end = this.peek();
964
+ if (end.type === "RightDelim" || end.type === "RightParen") throw this.errAt(end, `missing value for ${context}`, { expected: "command" });
950
965
  const cmds = [this.parseCommand()];
951
966
  while (this.peek().type === "Pipe") {
952
967
  this.next();
@@ -965,18 +980,19 @@ var Parser = class {
965
980
  cmds
966
981
  };
967
982
  }
968
- tryParseDecls() {
969
- if (this.peek().type !== "Variable") return void 0;
983
+ tryParseDecls(context) {
984
+ if (!isDeclTarget(this.peek())) return void 0;
970
985
  let n = 1;
971
986
  while (this.peek(n).type === "Comma") {
972
- if (this.peek(n + 1).type !== "Variable") return void 0;
987
+ if (!isDeclTarget(this.peek(n + 1))) return void 0;
973
988
  n += 2;
974
989
  }
975
990
  const opType = this.peek(n).type;
976
991
  if (opType !== "Declare" && opType !== "Assign") return void 0;
977
992
  const vars = [varFromToken(this.next())];
978
993
  while (this.peek().type === "Comma") {
979
- this.next();
994
+ const comma = this.next();
995
+ if (vars.length === (context === "range" ? 2 : 1)) throw this.errAt(comma, `too many declarations in ${context}`);
980
996
  vars.push(varFromToken(this.expect("Variable", "$variable")));
981
997
  }
982
998
  return {
@@ -1037,7 +1053,7 @@ var Parser = class {
1037
1053
  }
1038
1054
  }
1039
1055
  parseChainOrPipe(startPos) {
1040
- const inner = this.parsePipeline();
1056
+ const inner = this.parsePipeline("parenthesized pipeline");
1041
1057
  const rparen = this.expect("RightParen", "`)`");
1042
1058
  const fields = [];
1043
1059
  const expectedNextOffset = rparen.pos.offset + 1;
@@ -1087,6 +1103,9 @@ function canStartPrimary(t) {
1087
1103
  default: return false;
1088
1104
  }
1089
1105
  }
1106
+ function isDeclTarget(t) {
1107
+ return t.type === "Variable" && !t.value.includes(".");
1108
+ }
1090
1109
  function varFromToken(t) {
1091
1110
  return {
1092
1111
  type: "Variable",
@@ -1303,7 +1322,7 @@ function children(node) {
1303
1322
  node.elseList
1304
1323
  ] : [node.pipe, node.list];
1305
1324
  case "Template": return node.pipe ? [node.pipe] : [];
1306
- case "Block": return node.pipe ? [node.pipe, node.list] : [node.list];
1325
+ case "Block": return [node.pipe, node.list];
1307
1326
  default: return assertNever(node);
1308
1327
  }
1309
1328
  }
@@ -1494,13 +1513,13 @@ function eagerBuiltins(toString, isT) {
1494
1513
  arity: { kind: "variadic" }
1495
1514
  },
1496
1515
  print: {
1497
- fn: (...args) => goPrint(args, toString),
1516
+ fn: (...args) => goPrint(args, toString, isT),
1498
1517
  argTypes: ["stringifiable"],
1499
1518
  arity: { kind: "variadic" },
1500
1519
  returnType: "string"
1501
1520
  },
1502
1521
  println: {
1503
- fn: (...args) => `${goPrint(args, toString)}\n`,
1522
+ fn: (...args) => `${goPrintln(args, toString, isT)}\n`,
1504
1523
  argTypes: ["stringifiable"],
1505
1524
  arity: { kind: "variadic" },
1506
1525
  returnType: "string"
@@ -1525,22 +1544,23 @@ function eagerBuiltins(toString, isT) {
1525
1544
  call: {
1526
1545
  fn: (fn, ...args) => fn(...args),
1527
1546
  argTypes: ["callable", "value"],
1528
- arity: { kind: "variadic" }
1547
+ arity: { kind: "variadic" },
1548
+ writes: true
1529
1549
  },
1530
1550
  html: {
1531
- fn: (...args) => htmlEscape(goPrint(args, toString)),
1551
+ fn: (...args) => htmlEscape(goPrint(args, toString, isT)),
1532
1552
  argTypes: ["stringifiable"],
1533
1553
  arity: { kind: "variadic" },
1534
1554
  returnType: "string"
1535
1555
  },
1536
1556
  js: {
1537
- fn: (...args) => jsEscape(goPrint(args, toString)),
1557
+ fn: (...args) => jsEscape(goPrint(args, toString, isT)),
1538
1558
  argTypes: ["stringifiable"],
1539
1559
  arity: { kind: "variadic" },
1540
1560
  returnType: "string"
1541
1561
  },
1542
1562
  urlquery: {
1543
- fn: (...args) => urlQueryEscape(goPrint(args, toString)),
1563
+ fn: (...args) => urlQueryEscape(goPrint(args, toString, isT)),
1544
1564
  argTypes: ["stringifiable"],
1545
1565
  arity: { kind: "variadic" },
1546
1566
  returnType: "string"
@@ -1662,22 +1682,20 @@ function goPrintfType(v) {
1662
1682
  if (v instanceof Map || typeof v === "object") return "map[string]interface {}";
1663
1683
  return typeof v;
1664
1684
  }
1665
- function goPrint(args, toString) {
1685
+ function goPrint(args, toString, isT) {
1666
1686
  let out = "";
1667
1687
  let prevIsString = false;
1668
1688
  for (let i = 0; i < args.length; i++) {
1669
1689
  const arg = args[i];
1670
1690
  const isString = typeof arg === "string";
1671
1691
  if (i > 0 && !prevIsString && !isString) out += " ";
1672
- out += stringifyForPrint(arg, toString);
1692
+ out += formatV(arg, toString, isT);
1673
1693
  prevIsString = isString;
1674
1694
  }
1675
1695
  return out;
1676
1696
  }
1677
- function stringifyForPrint(value, toString) {
1678
- if (value === null || value === void 0) return "<nil>";
1679
- if (typeof value === "string") return value;
1680
- return toString(value);
1697
+ function goPrintln(args, toString, isT) {
1698
+ return args.map((arg) => formatV(arg, toString, isT)).join(" ");
1681
1699
  }
1682
1700
  const HTML_ESCAPE_TABLE = {
1683
1701
  "\0": "�",
@@ -1751,26 +1769,34 @@ function sprintf(format, args, toString, isT) {
1751
1769
  }
1752
1770
  const verb = format[j];
1753
1771
  const spec = format.slice(i + 1, j);
1772
+ const missing = argIdx >= args.length;
1754
1773
  const arg = args[argIdx++];
1755
- out += formatVerb(verb ?? "", spec, arg, toString, isT);
1774
+ out += missing ? `%!${verb ?? ""}(MISSING)` : formatVerb(verb ?? "", spec, arg, toString, isT);
1756
1775
  i = j + 1;
1757
1776
  }
1758
1777
  return out;
1759
1778
  }
1760
1779
  function formatVerb(verb, spec, arg, toString, isT) {
1780
+ if (arg instanceof Uint8Array && (verb === "s" || verb === "q")) return formatLeafVerb(verb, spec, new TextDecoder().decode(arg), toString, isT);
1781
+ if (arg instanceof Uint8Array && verb === "x") return applyWidth(spec, Array.from(arg, (b) => b.toString(16).padStart(2, "0")).join(""));
1782
+ return formatWalk(arg, (leaf) => formatLeafVerb(verb, spec, leaf, toString, isT), toString, isT);
1783
+ }
1784
+ function formatLeafVerb(verb, spec, arg, toString, isT) {
1761
1785
  switch (verb) {
1762
- case "s": return typeof arg === "string" ? applyWidth(spec, arg) : applyWidth(spec, stringifyForPrint(arg, toString));
1786
+ case "s": return applyWidth(spec, formatLeafV(arg, toString, isT));
1763
1787
  case "d":
1764
- if (typeof arg !== "number" && typeof arg !== "bigint") return `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;
1788
+ if (typeof arg !== "number" && typeof arg !== "bigint") return badVerb(verb, arg, toString, isT);
1765
1789
  return applyWidth(spec, String(typeof arg === "bigint" ? arg : Math.trunc(arg)));
1766
- case "v": return applyWidth(spec, formatV(arg, toString, isT));
1767
- case "q": return applyWidth(spec, JSON.stringify(stringifyForPrint(arg, toString)));
1790
+ case "v": return applyWidth(spec, formatLeafV(arg, toString, isT));
1791
+ case "q": return applyWidth(spec, JSON.stringify(formatLeafV(arg, toString, isT)));
1768
1792
  case "f": {
1769
- if (typeof arg !== "number" && typeof arg !== "bigint") return `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;
1793
+ if (typeof arg !== "number" && typeof arg !== "bigint") return badVerb(verb, arg, toString, isT);
1770
1794
  const precision = spec.includes(".") ? Number(spec.split(".")[1]) : 6;
1771
1795
  return applyWidth(spec, Number(arg).toFixed(precision));
1772
1796
  }
1773
- case "t": return applyWidth(spec, isTruthy(arg) ? "true" : "false");
1797
+ case "t":
1798
+ if (typeof arg !== "boolean") return badVerb(verb, arg, toString, isT);
1799
+ return applyWidth(spec, String(arg));
1774
1800
  case "x":
1775
1801
  if (typeof arg === "string") {
1776
1802
  const bytes = new TextEncoder().encode(arg);
@@ -1778,12 +1804,16 @@ function formatVerb(verb, spec, arg, toString, isT) {
1778
1804
  for (const b of bytes) hex += b.toString(16).padStart(2, "0");
1779
1805
  return applyWidth(spec, hex);
1780
1806
  }
1781
- if (typeof arg !== "number" && typeof arg !== "bigint") return `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;
1807
+ if (typeof arg !== "number" && typeof arg !== "bigint") return badVerb(verb, arg, toString, isT);
1782
1808
  if (typeof arg === "bigint") return applyWidth(spec, arg.toString(16));
1783
1809
  return applyWidth(spec, Math.trunc(arg).toString(16));
1784
- default: return `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;
1810
+ default: return badVerb(verb, arg, toString, isT);
1785
1811
  }
1786
1812
  }
1813
+ function badVerb(verb, arg, toString, isT) {
1814
+ if (arg === null || arg === void 0) return `%!${verb}(<nil>)`;
1815
+ return `%!${verb}(${goPrintfType(arg)}=${formatLeafV(arg, toString, isT)})`;
1816
+ }
1787
1817
  function applyWidth(spec, body) {
1788
1818
  const flag = spec.match(/^([+\-# 0]*)/)?.[1] ?? "";
1789
1819
  const widthMatch = spec.slice(flag.length).match(/^(\d+)/);
@@ -1794,70 +1824,248 @@ function applyWidth(spec, body) {
1794
1824
  return flag.includes("-") ? body + pad : pad + body;
1795
1825
  }
1796
1826
  function formatV(value, toString, isT) {
1827
+ try {
1828
+ return formatWalk(value, (leaf) => formatLeafV(leaf, toString, isT), toString, isT);
1829
+ } catch (err) {
1830
+ if (err instanceof UnprintableError) throw new UnprintableError(err.leaf, err.cause, value);
1831
+ throw err;
1832
+ }
1833
+ }
1834
+ function formatWalk(value, leaf, toString, isT) {
1835
+ if (isT(value)) return leaf(value);
1836
+ const walk = (v) => formatWalk(v, leaf, toString, isT);
1837
+ if (Array.isArray(value)) return `[${value.map(walk).join(" ")}]`;
1838
+ if (ArrayBuffer.isView(value) && !(value instanceof DataView)) return `[${Array.from(value, walk).join(" ")}]`;
1839
+ if (value instanceof Map) return formatEntries([...value.entries()], walk, toString, isT);
1840
+ if (isPlainObject(value)) return formatEntries(Object.entries(value), walk, toString, isT);
1841
+ if (isStruct(value)) return `{${Object.values(value).map(walk).join(" ")}}`;
1842
+ return leaf(value);
1843
+ }
1844
+ function isStruct(value) {
1845
+ return typeof value === "object" && value !== null && !(value instanceof Set) && !hasOwnString(value);
1846
+ }
1847
+ function formatLeafV(value, toString, isT) {
1797
1848
  if (value === null || value === void 0) return "<nil>";
1798
1849
  if (typeof value === "string") return value;
1799
- if (isT(value)) return toString(value);
1800
- if (Array.isArray(value)) return `[${value.map((v) => formatV(v, toString, isT)).join(" ")}]`;
1801
- if (value instanceof Map) return formatEntries([...value.entries()], toString, isT);
1802
- if (isPlainObject(value)) return formatEntries(Object.entries(value), toString, isT);
1803
- return String(value);
1804
- }
1805
- function formatEntries(entries, toString, isT) {
1806
- const fmt = (v) => formatV(v, toString, isT);
1850
+ if (isT(value)) return flattenT(value, toString);
1851
+ if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return String(value);
1852
+ if (typeof value === "object" && hasOwnString(value)) return stringerText(value);
1853
+ throw new UnprintableError(value);
1854
+ }
1855
+ function flattenT(value, toString) {
1856
+ try {
1857
+ return toString(value);
1858
+ } catch (err) {
1859
+ if (isStackOverflow(err)) throw err;
1860
+ throw new UnprintableError(value, err);
1861
+ }
1862
+ }
1863
+ function stringerText(value) {
1864
+ try {
1865
+ return String(value);
1866
+ } catch (err) {
1867
+ if (isStackOverflow(err)) throw err;
1868
+ throw new UnprintableError(value, err);
1869
+ }
1870
+ }
1871
+ function hasOwnString(value) {
1872
+ let root = value;
1873
+ for (let p = Object.getPrototypeOf(root); p !== null; p = Object.getPrototypeOf(p)) root = p;
1874
+ const own = value.toString;
1875
+ return typeof own === "function" && own !== root.toString;
1876
+ }
1877
+ /** A value Go's `%v` has no text form for: a Set, a function, a symbol, or
1878
+ * a T the engine's `toString` cannot flatten. The action and the call that
1879
+ * met it report it at their position. */
1880
+ var UnprintableError = class extends Error {
1881
+ name = "UnprintableError";
1882
+ /** What cannot print, named from the printed value: the leaf alone, or
1883
+ * the value holding it. */
1884
+ summary;
1885
+ constructor(leaf, cause, root = leaf) {
1886
+ const summary = root === leaf ? typeNameOf(leaf) : `${typeNameOf(root)} holding ${typeNameOf(leaf)}`;
1887
+ const why = cause instanceof TypeMismatchError ? `expected ${cause.expected}` : "it has no text form";
1888
+ super(`cannot print a value of type ${summary}: ${why}`, { cause });
1889
+ this.leaf = leaf;
1890
+ this.summary = summary;
1891
+ }
1892
+ };
1893
+ function typeNameOf(value) {
1894
+ if (value === null) return "null";
1895
+ if (Array.isArray(value)) return "array";
1896
+ if (typeof value !== "object") return typeof value;
1897
+ if (isPlainObject(value)) return "object";
1898
+ for (let p = Object.getPrototypeOf(value); p !== null; p = Object.getPrototypeOf(p)) {
1899
+ const name = p.constructor?.name;
1900
+ if (typeof name === "string" && name !== "") return name === "Object" ? "object" : name;
1901
+ }
1902
+ return "object";
1903
+ }
1904
+ function formatEntries(entries, walk, toString, isT) {
1807
1905
  const isNumeric = (k) => typeof k === "number" || typeof k === "bigint";
1808
- const byKey = ([a], [b]) => {
1809
- if (isNumeric(a) && isNumeric(b)) return a < b ? -1 : a > b ? 1 : 0;
1810
- if (isNumeric(a) !== isNumeric(b)) return isNumeric(a) ? -1 : 1;
1811
- const [as, bs] = [fmt(a), fmt(b)];
1812
- return as < bs ? -1 : as > bs ? 1 : 0;
1906
+ const byKey = (a, b) => {
1907
+ if (isNumeric(a.k) && isNumeric(b.k)) return a.k < b.k ? -1 : a.k > b.k ? 1 : 0;
1908
+ if (isNumeric(a.k) !== isNumeric(b.k)) return isNumeric(a.k) ? -1 : 1;
1909
+ return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;
1813
1910
  };
1814
- return `map[${[...entries].sort(byKey).map(([k, v]) => `${fmt(k)}:${fmt(v)}`).join(" ")}]`;
1911
+ return `map[${entries.map(([k, v]) => ({
1912
+ k,
1913
+ v,
1914
+ text: formatV(k, toString, isT)
1915
+ })).sort(byKey).map(({ k, v }) => `${walk(k)}:${walk(v)}`).join(" ")}]`;
1815
1916
  }
1816
1917
  function isPlainObject(value) {
1817
1918
  if (value === null || typeof value !== "object") return false;
1818
1919
  if (Array.isArray(value)) return false;
1819
1920
  if (value instanceof Map || value instanceof Set) return false;
1820
1921
  const proto = Object.getPrototypeOf(value);
1821
- return proto === null || proto === Object.prototype;
1922
+ return proto === null || Object.getPrototypeOf(proto) === null;
1923
+ }
1924
+ //#endregion
1925
+ //#region src/evaluator/include.ts
1926
+ const render = () => {
1927
+ throw new Error("include was called outside the evaluator's dispatch");
1928
+ };
1929
+ /** Helm's `include(name string, data interface{}) (string, error)`. */
1930
+ const include = {
1931
+ fn: render,
1932
+ argTypes: ["string", "value"],
1933
+ arity: { kind: "exact" },
1934
+ returnType: "string"
1935
+ };
1936
+ /** True iff `fn` is `include`, under whatever name or copy it was registered. */
1937
+ function isInclude(fn) {
1938
+ return fn.fn === render;
1939
+ }
1940
+ //#endregion
1941
+ //#region src/evaluator/marks.ts
1942
+ const NO_MARKS = /* @__PURE__ */ new Set();
1943
+ let createMarked;
1944
+ let openMarked;
1945
+ let readCarrier;
1946
+ /**
1947
+ * A func's return value together with the marks of the call that
1948
+ * produced it. Opaque: build one with {@link marked}; only the engine
1949
+ * reads it.
1950
+ */
1951
+ var Marked = class Marked {
1952
+ #value;
1953
+ #marks;
1954
+ constructor(value, marks) {
1955
+ this.#value = value;
1956
+ this.#marks = marks;
1957
+ }
1958
+ static {
1959
+ createMarked = (value, marks) => value instanceof Marked ? new Marked(value.#value, [...value.#marks, ...marks]) : new Marked(value, marks);
1960
+ openMarked = (result) => result instanceof Marked ? {
1961
+ value: result.#value,
1962
+ marks: result.#marks
1963
+ } : {
1964
+ value: result,
1965
+ marks: []
1966
+ };
1967
+ readCarrier = (result, into) => {
1968
+ if (!(result instanceof Marked)) return result;
1969
+ for (const mark of result.#marks) into.add(mark);
1970
+ return result.#value;
1971
+ };
1972
+ }
1973
+ };
1974
+ /**
1975
+ * Return this from a registered func to mark the call: every emission
1976
+ * and control decision that depends on the call's result reports
1977
+ * `marks`. The template sees `value`, exactly as if it had been returned
1978
+ * directly.
1979
+ */
1980
+ function marked(value, ...marks) {
1981
+ return createMarked(value, marks);
1982
+ }
1983
+ /**
1984
+ * A func's return read apart: its value and the marks it carries (none
1985
+ * for a plain value). For JS code that builds on a marking func outside a
1986
+ * template — `const { value, marks } = unmarked(tween.fn(...))`, then
1987
+ * `return marked(Math.min(1, value as number), ...marks)`.
1988
+ */
1989
+ function unmarked(result) {
1990
+ return openMarked(result);
1991
+ }
1992
+ /** `a ∪ b`, sharing an operand when the other is empty. */
1993
+ function unionMarks(a, b) {
1994
+ if (b.size === 0) return a;
1995
+ if (a.size === 0) return b;
1996
+ return new Set([...a, ...b]);
1822
1997
  }
1823
1998
  //#endregion
1824
1999
  //#region src/evaluator/scope.ts
1825
- function rootScope(value) {
2000
+ /**
2001
+ * Lexical scope chain for the evaluator.
2002
+ *
2003
+ * [LAW:dataflow-not-control-flow] A `Scope` is a `dot`, a parent
2004
+ * pointer and the variables declared in it. Entering a construct or an
2005
+ * iteration *constructs* a frame and leaving it drops the frame, so
2006
+ * nothing is ever undone: iterations of `{{range}}` cannot see each
2007
+ * other's `:=` declarations — the data shape itself prevents the bug.
2008
+ *
2009
+ * Only a frame's variables change. A lookup walks the parent chain.
2010
+ * Assignment via `=` searches the chain and overwrites the binding in
2011
+ * the frame that declared it; declaration via `:=` always creates the
2012
+ * binding in the current leaf frame.
2013
+ *
2014
+ * `$` is an ordinary variable declared in a chain's root frame, as in
2015
+ * Go, where it is `vars[0]`: so `$ = v` assigns it, and a `template` /
2016
+ * `block` invocation starts a fresh chain whose only variable is `$`.
2017
+ */
2018
+ /** The frame a template body starts in: `.` and `$` are both `dot`. */
2019
+ function rootScope(dot) {
1826
2020
  return {
1827
- dot: value,
1828
- root: value,
2021
+ dot,
1829
2022
  parent: void 0,
1830
- vars: /* @__PURE__ */ new Map()
2023
+ vars: new Map([["$", dot]])
1831
2024
  };
1832
2025
  }
1833
2026
  function pushScope(parent, dot) {
1834
2027
  return {
1835
2028
  dot,
1836
- root: parent.root,
1837
2029
  parent,
1838
2030
  vars: /* @__PURE__ */ new Map()
1839
2031
  };
1840
2032
  }
2033
+ function findFrame(scope, name) {
2034
+ let cur = scope;
2035
+ while (cur !== void 0 && !cur.vars.has(name)) cur = cur.parent;
2036
+ return cur;
2037
+ }
1841
2038
  /**
1842
2039
  * Look up a `$var` binding, walking the parent chain.
1843
- * Returns `{ found: true, value }` on hit and `{ found: false }` on miss
1844
- * — explicit shape rather than `undefined` so callers can disambiguate
1845
- * "not declared" from "declared but undefined".
2040
+ * Returns the binding on hit and `undefined` on miss — a `Binding` is a
2041
+ * record, so a variable declared as `undefined` is still a hit.
1846
2042
  */
1847
2043
  function lookupVar(scope, name) {
1848
- let cur = scope;
1849
- while (cur !== void 0) {
1850
- if (cur.vars.has(name)) return {
1851
- found: true,
1852
- value: cur.vars.get(name)
1853
- };
1854
- cur = cur.parent;
1855
- }
1856
- return { found: false };
2044
+ return findFrame(scope, name)?.vars.get(name);
1857
2045
  }
1858
2046
  /** Declare a new variable in the leaf scope (for `:=`). */
1859
- function declareVar(scope, name, value) {
1860
- scope.vars.set(name, value);
2047
+ function declareVar(scope, name, binding) {
2048
+ scope.vars.set(name, binding);
2049
+ }
2050
+ /**
2051
+ * Overwrite the nearest frame's binding of `name` (for `=`), as Go's
2052
+ * text/template exec.go walks its variable stack. Returns whether any
2053
+ * frame declared it; the caller owns the "undefined variable" error,
2054
+ * which needs a position this module does not have.
2055
+ */
2056
+ function assignVar(scope, name, binding) {
2057
+ const frame = findFrame(scope, name);
2058
+ frame?.vars.set(name, binding);
2059
+ return frame !== void 0;
2060
+ }
2061
+ /** Add `marks` to what `name`'s binding depends on, if any frame declared it. */
2062
+ function markVar(scope, name, marks) {
2063
+ const binding = lookupVar(scope, name);
2064
+ if (binding === void 0) return;
2065
+ assignVar(scope, name, {
2066
+ value: binding.value,
2067
+ marks: unionMarks(binding.marks, marks)
2068
+ });
1861
2069
  }
1862
2070
  //#endregion
1863
2071
  //#region src/evaluator/evaluator.ts
@@ -1966,6 +2174,7 @@ function validateArgSpecs(funcs) {
1966
2174
  const BREAK_SIGNAL = Object.freeze({ kind: "break" });
1967
2175
  const CONTINUE_SIGNAL = Object.freeze({ kind: "continue" });
1968
2176
  const NO_PIPE = { kind: "none" };
2177
+ const notDefined = (name) => `template ${JSON.stringify(name)} is not defined`;
1969
2178
  /**
1970
2179
  * A parsed template bound to its parent engine.
1971
2180
  *
@@ -1982,18 +2191,20 @@ let internalCreateTemplate;
1982
2191
  var Template = class Template {
1983
2192
  source;
1984
2193
  _evaluate;
2194
+ _evaluateDefine;
1985
2195
  _defines;
1986
2196
  _referencedFunctions;
1987
2197
  _referencedCalls;
1988
- constructor(source, evaluate, defines, referencedFunctions, referencedCalls) {
2198
+ constructor(source, evaluate, evaluateDefine, defines, referencedFunctions, referencedCalls) {
1989
2199
  this.source = source;
1990
2200
  this._evaluate = evaluate;
2201
+ this._evaluateDefine = evaluateDefine;
1991
2202
  this._defines = defines;
1992
2203
  this._referencedFunctions = referencedFunctions;
1993
2204
  this._referencedCalls = referencedCalls;
1994
2205
  }
1995
2206
  static {
1996
- internalCreateTemplate = (source, evaluate, defines, referencedFunctions, referencedCalls) => new Template(source, evaluate, defines, referencedFunctions, referencedCalls);
2207
+ internalCreateTemplate = (source, evaluate, evaluateDefine, defines, referencedFunctions, referencedCalls) => new Template(source, evaluate, evaluateDefine, defines, referencedFunctions, referencedCalls);
1997
2208
  }
1998
2209
  /**
1999
2210
  * The named sub-templates this template can invoke — its own `{{define}}`s
@@ -2011,6 +2222,15 @@ var Template = class Template {
2011
2222
  return this._evaluate(scope);
2012
2223
  }
2013
2224
  /**
2225
+ * Render one named sub-template — any `{{ define }}` in {@link defines}, its
2226
+ * own or inherited — with `scope` as its dot and `$`, as Go's
2227
+ * `ExecuteTemplate` does. The output is the same `T[]` a whole-template
2228
+ * {@link evaluate} produces, through the same `emitted` / `decided` hooks.
2229
+ */
2230
+ evaluateDefine(name, scope) {
2231
+ return this._evaluateDefine(name, scope);
2232
+ }
2233
+ /**
2014
2234
  * The FuncMap function names this template references — every identifier that
2015
2235
  * names a function in this parse: the template body and its own `{{ define }}`
2016
2236
  * blocks. A set inherited at parse (see {@link Template.defines}) is described
@@ -2126,13 +2346,17 @@ var Engine = class {
2126
2346
  funcs;
2127
2347
  missingKey;
2128
2348
  delims;
2349
+ emitted;
2350
+ decided;
2129
2351
  constructor(config) {
2130
2352
  this.fromString = config.fromString;
2131
2353
  const userToString = Object.hasOwn(config, "toString") ? config.toString : void 0;
2132
2354
  this.toString = userToString ?? defaultToString;
2133
- this.isT = config.isT ?? DEFAULT_IS_T;
2134
2355
  this.missingKey = validateMissingKey(config.missingKey);
2135
2356
  this.delims = validateDelims(config.delims);
2357
+ this.isT = config.isT ?? DEFAULT_IS_T;
2358
+ this.emitted = config.emitted ?? ((value) => value);
2359
+ this.decided = config.decided ?? (() => {});
2136
2360
  this.funcs = validateArgSpecs({
2137
2361
  ...defaultBuiltins(this.toString, this.isT),
2138
2362
  ...config.funcs ?? {}
@@ -2147,7 +2371,14 @@ var Engine = class {
2147
2371
  */
2148
2372
  parse(source, inherit) {
2149
2373
  const parsed = parse(source, this.delims, inherit);
2150
- return internalCreateTemplate(parsed.source, (scope) => this.evalParsed(parsed, scope), parsed.defines, collectReferencedFunctions(parsed), collectReferencedCalls(parsed));
2374
+ return internalCreateTemplate(parsed.source, (scope) => this.evalParsed(parsed, scope, (root, ctx) => this.evalList(parsed.root, root, ctx)), (name, scope) => {
2375
+ const entry = lookupDefine(parsed.defines, name);
2376
+ if (!entry) throw new Error(notDefined(name));
2377
+ return this.evalParsed(parsed, scope, (root, ctx) => this.renderDefine(name, entry, root.dot, entry.list.pos, {
2378
+ ...ctx,
2379
+ source: entry.source
2380
+ }));
2381
+ }, parsed.defines, collectReferencedFunctions(parsed), collectReferencedCalls(parsed));
2151
2382
  }
2152
2383
  /**
2153
2384
  * Convenience sugar for `parse(src).evaluate.bind(template)`.
@@ -2168,15 +2399,19 @@ var Engine = class {
2168
2399
  evaluate(template, scope) {
2169
2400
  return template.evaluate(scope);
2170
2401
  }
2171
- evalParsed(parsed, scope) {
2402
+ evalParsed(parsed, scope, body) {
2172
2403
  const out = [];
2173
- const root = rootScope(scope);
2174
- const ctx = {
2175
- out,
2404
+ body(rootScope({
2405
+ value: scope,
2406
+ marks: NO_MARKS
2407
+ }), {
2408
+ emit: (value, marks) => out.push(this.emitted(value, marks)),
2409
+ decided: this.decided,
2176
2410
  defines: parsed.defines,
2177
- source: parsed.source
2178
- };
2179
- this.evalList(parsed.root, root, ctx);
2411
+ source: parsed.source,
2412
+ marks: NO_MARKS,
2413
+ depth: 0
2414
+ });
2180
2415
  return out;
2181
2416
  }
2182
2417
  evalList(node, scope, ctx) {
@@ -2185,14 +2420,15 @@ var Engine = class {
2185
2420
  evalNode(node, scope, ctx) {
2186
2421
  switch (node.type) {
2187
2422
  case "Text":
2188
- ctx.out.push(this.fromString(node.text));
2423
+ ctx.emit(this.fromString(node.text), ctx.marks);
2189
2424
  return;
2190
2425
  case "Comment": return;
2191
- case "Action": {
2192
- const value = this.evalAction(node, scope, ctx);
2193
- if (node.pipe.decls.length === 0) this.emitFromValue(value, ctx);
2426
+ case "Action":
2427
+ this.read(ctx, (reads) => {
2428
+ const value = this.evalPipe(node.pipe, scope, ctx, reads);
2429
+ if (node.pipe.decls.length === 0) ctx.emit(this.lift(value, node.pos, ctx.source), unionMarks(reads, ctx.marks));
2430
+ });
2194
2431
  return;
2195
- }
2196
2432
  case "List":
2197
2433
  this.evalList(node, scope, ctx);
2198
2434
  return;
@@ -2228,36 +2464,47 @@ var Engine = class {
2228
2464
  }
2229
2465
  }
2230
2466
  evalIf(node, scope, ctx) {
2231
- if (isTruthy(this.evalPipe(node.pipe, scope, ctx))) this.evalList(node.list, scope, ctx);
2232
- else if (node.elseList) this.evalList(node.elseList, scope, ctx);
2467
+ const frame = constructFrame(scope);
2468
+ const { value: cond, reads } = this.read(ctx, (r) => this.evalPipe(node.pipe, frame, ctx, r));
2469
+ const arm = this.decide(reads, ctx, frame, node);
2470
+ if (isTruthy(cond)) this.evalList(node.list, frame, arm);
2471
+ else if (node.elseList) this.evalList(node.elseList, frame, arm);
2233
2472
  }
2234
2473
  evalWith(node, scope, ctx) {
2235
- const value = this.evalPipe(node.pipe, scope, ctx);
2236
- if (isTruthy(value)) {
2237
- const child = pushScope(scope, value);
2238
- this.evalList(node.list, child, ctx);
2239
- } else if (node.elseList) this.evalList(node.elseList, scope, ctx);
2474
+ const frame = constructFrame(scope);
2475
+ const { value, reads } = this.read(ctx, (r) => this.evalPipe(node.pipe, frame, ctx, r));
2476
+ const arm = this.decide(reads, ctx, frame, node);
2477
+ if (isTruthy(value)) this.evalList(node.list, pushScope(frame, {
2478
+ value,
2479
+ marks: arm.marks
2480
+ }), arm);
2481
+ else if (node.elseList) this.evalList(node.elseList, frame, arm);
2240
2482
  }
2241
2483
  evalRange(node, scope, ctx) {
2242
- const value = this.evalPipeWithoutDecls(node.pipe, scope, ctx);
2243
- const decls = node.pipe.decls;
2484
+ const rangeScope = constructFrame(scope);
2485
+ const { value, reads } = this.read(ctx, (r) => this.evalPipe(node.pipe, rangeScope, ctx, r));
2486
+ const arm = this.decide(reads, ctx, rangeScope, node);
2487
+ const { decls, isAssign } = node.pipe;
2244
2488
  const entries = enumerateForRange(value);
2245
2489
  try {
2246
2490
  if (entries.length === 0) {
2247
- if (node.elseList) this.evalList(node.elseList, scope, ctx);
2491
+ if (node.elseList) this.evalList(node.elseList, rangeScope, arm);
2248
2492
  return;
2249
2493
  }
2250
2494
  for (const [key, item] of entries) {
2251
- const child = pushScope(scope, item);
2252
- if (decls.length === 1) declareVar(child, decls[0]?.idents[0] ?? "$", item);
2253
- else if (decls.length >= 2) {
2254
- const k = decls[0]?.idents[0] ?? "$";
2255
- const v = decls[1]?.idents[0] ?? "$";
2256
- declareVar(child, k, key);
2257
- declareVar(child, v, item);
2258
- }
2495
+ decls.forEach((decl, i) => {
2496
+ const binding = {
2497
+ value: i === decls.length - 1 ? item : key,
2498
+ marks: arm.marks
2499
+ };
2500
+ this.bind(rangeScope, decl, isAssign, binding, ctx);
2501
+ });
2502
+ const child = pushScope(rangeScope, {
2503
+ value: item,
2504
+ marks: arm.marks
2505
+ });
2259
2506
  try {
2260
- this.evalList(node.list, child, ctx);
2507
+ this.evalList(node.list, child, arm);
2261
2508
  } catch (e) {
2262
2509
  if (e === CONTINUE_SIGNAL) continue;
2263
2510
  throw e;
@@ -2269,59 +2516,143 @@ var Engine = class {
2269
2516
  }
2270
2517
  }
2271
2518
  evalTemplateInvoke(node, scope, ctx) {
2272
- const entry = lookupDefine(ctx.defines, node.name);
2273
- if (!entry) throw new EvalError(`template ${JSON.stringify(node.name)} is not defined`, node.pos, { source: ctx.source });
2274
- const child = pushScope(scope, node.pipe ? this.evalPipe(node.pipe, scope, ctx) : scope.dot);
2275
- this.evalList(entry.list, child, {
2276
- out: ctx.out,
2277
- defines: ctx.defines,
2278
- source: entry.source
2279
- });
2519
+ const entry = this.definedEntry(node.name, node.pos, ctx);
2520
+ const dot = this.invocationDot(node.pipe, scope, ctx);
2521
+ this.renderDefine(node.name, entry, dot, node.pos, ctx);
2522
+ }
2523
+ definedEntry(name, pos, ctx) {
2524
+ const entry = lookupDefine(ctx.defines, name);
2525
+ if (!entry) throw new EvalError(notDefined(name), pos, { source: ctx.source });
2526
+ return entry;
2527
+ }
2528
+ renderDefine(name, body, dot, pos, ctx) {
2529
+ try {
2530
+ this.evalList(body.list, rootScope(dot), {
2531
+ ...ctx,
2532
+ source: body.source,
2533
+ depth: ctx.depth + 1
2534
+ });
2535
+ } catch (e) {
2536
+ if (!isStackOverflow(e)) throw e;
2537
+ throw new EvalError(`template ${JSON.stringify(name)}: nesting depth ${ctx.depth + 1} exceeds the host's stack`, pos, {
2538
+ source: ctx.source,
2539
+ cause: e
2540
+ });
2541
+ }
2542
+ }
2543
+ include(registered, name, data, pos, ctx, reads) {
2544
+ const entry = this.definedEntry(name, pos, ctx);
2545
+ const parts = [];
2546
+ const emit = (value, marks) => {
2547
+ parts.push(this.toString(value));
2548
+ for (const mark of marks) reads.add(mark);
2549
+ };
2550
+ const decided = (marks) => {
2551
+ ctx.decided(marks);
2552
+ for (const mark of marks) reads.add(mark);
2553
+ };
2554
+ const dot = {
2555
+ value: data,
2556
+ marks: new Set([...reads, ...ctx.marks])
2557
+ };
2558
+ try {
2559
+ this.renderDefine(name, entry, dot, pos, {
2560
+ ...ctx,
2561
+ emit,
2562
+ decided
2563
+ });
2564
+ } catch (e) {
2565
+ if (!(e instanceof TemplateError)) throw e;
2566
+ const root = innermost(e);
2567
+ throw new (root instanceof FailError ? FailError : EvalError)(`error calling ${registered} ${JSON.stringify(name)}: ${root.message}`, pos, {
2568
+ source: ctx.source,
2569
+ cause: e
2570
+ });
2571
+ }
2572
+ return parts.join("");
2280
2573
  }
2281
2574
  evalBlock(node, scope, ctx) {
2282
- const child = pushScope(scope, node.pipe ? this.evalPipe(node.pipe, scope, ctx) : scope.dot);
2575
+ const dot = this.invocationDot(node.pipe, scope, ctx);
2283
2576
  const entry = lookupDefine(ctx.defines, node.name) ?? {
2284
2577
  list: node.list,
2285
2578
  source: ctx.source
2286
2579
  };
2287
- this.evalList(entry.list, child, {
2288
- out: ctx.out,
2289
- defines: ctx.defines,
2290
- source: entry.source
2291
- });
2580
+ this.renderDefine(node.name, entry, dot, node.pos, ctx);
2581
+ }
2582
+ decide(reads, ctx, frame, arms) {
2583
+ const marks = unionMarks(ctx.marks, reads);
2584
+ ctx.decided(marks);
2585
+ for (const name of this.assignedIn(arms)) markVar(frame, name, marks);
2586
+ return {
2587
+ ...ctx,
2588
+ marks
2589
+ };
2292
2590
  }
2293
- evalAction(node, scope, ctx) {
2294
- return this.evalPipe(node.pipe, scope, ctx);
2591
+ assigned = /* @__PURE__ */ new WeakMap();
2592
+ assignedIn(arms) {
2593
+ const cached = this.assigned.get(arms.list);
2594
+ if (cached !== void 0) return cached;
2595
+ const names = /* @__PURE__ */ new Set();
2596
+ const collect = (n) => {
2597
+ if (n.type === "Pipe" && n.isAssign) for (const d of n.decls) names.add(d.idents[0] ?? "$");
2598
+ };
2599
+ for (const list of [arms.list, arms.elseList]) if (list) walk(list, collect);
2600
+ const found = [...names];
2601
+ this.assigned.set(arms.list, found);
2602
+ return found;
2295
2603
  }
2296
- evalPipe(pipe, scope, ctx) {
2604
+ invocationDot(pipe, scope, ctx) {
2605
+ const { value, reads } = this.read(ctx, (r) => pipe ? this.evalPipe(pipe, scope, ctx, r) : null);
2606
+ return {
2607
+ value,
2608
+ marks: unionMarks(reads, ctx.marks)
2609
+ };
2610
+ }
2611
+ read(ctx, evaluate) {
2612
+ const reads = /* @__PURE__ */ new Set();
2613
+ try {
2614
+ return {
2615
+ value: evaluate(reads),
2616
+ reads
2617
+ };
2618
+ } catch (e) {
2619
+ ctx.decided(unionMarks(reads, ctx.marks));
2620
+ throw e;
2621
+ }
2622
+ }
2623
+ evalPipe(pipe, scope, ctx, reads) {
2297
2624
  if (pipe.cmds.length === 0) throw new EvalError("empty pipeline", pipe.pos, { source: ctx.source });
2298
- let value = this.evalCommand(pipe.cmds[0], scope, ctx, NO_PIPE);
2299
- for (let i = 1; i < pipe.cmds.length; i++) {
2300
- const next = pipe.cmds[i];
2301
- value = this.evalCommand(next, scope, ctx, {
2302
- kind: "value",
2303
- value
2304
- });
2625
+ const inputs = /* @__PURE__ */ new Set();
2626
+ let value;
2627
+ try {
2628
+ value = this.evalCommand(pipe.cmds[0], scope, ctx, NO_PIPE, inputs);
2629
+ for (let i = 1; i < pipe.cmds.length; i++) {
2630
+ const next = pipe.cmds[i];
2631
+ value = this.evalCommand(next, scope, ctx, {
2632
+ kind: "value",
2633
+ value
2634
+ }, inputs);
2635
+ }
2636
+ } finally {
2637
+ for (const mark of inputs) reads.add(mark);
2305
2638
  }
2306
- if (pipe.decls.length > 0) for (const decl of pipe.decls) declareVar(scope, decl.idents[0] ?? "$", value);
2639
+ for (const decl of pipe.decls) this.bind(scope, decl, pipe.isAssign, {
2640
+ value,
2641
+ marks: unionMarks(inputs, ctx.marks)
2642
+ }, ctx);
2307
2643
  return value;
2308
2644
  }
2309
- evalPipeWithoutDecls(pipe, scope, ctx) {
2310
- const stripped = {
2311
- type: "Pipe",
2312
- pos: pipe.pos,
2313
- decls: [],
2314
- isAssign: false,
2315
- cmds: pipe.cmds
2316
- };
2317
- return this.evalPipe(stripped, scope, ctx);
2645
+ bind(scope, decl, isAssign, binding, ctx) {
2646
+ const name = decl.idents[0] ?? "$";
2647
+ if (!isAssign) declareVar(scope, name, binding);
2648
+ else if (!assignVar(scope, name, binding)) throw undefinedVariable(name, decl.pos, ctx);
2318
2649
  }
2319
- evalCommand(cmd, scope, ctx, piped) {
2650
+ evalCommand(cmd, scope, ctx, piped, reads) {
2320
2651
  if (cmd.args.length === 0) throw new EvalError("empty command", cmd.pos, { source: ctx.source });
2321
2652
  const head = cmd.args[0];
2322
2653
  if (head.type !== "Identifier") {
2323
2654
  if (cmd.args.length > 1) throw new EvalError(`cannot apply arguments to a ${head.type} primary; only functions take arguments`, cmd.pos, { source: ctx.source });
2324
- return this.evalPrimary(head, scope, ctx);
2655
+ return this.evalPrimary(head, scope, ctx, reads);
2325
2656
  }
2326
2657
  const fn = this.funcs[head.ident];
2327
2658
  if (!fn) throw new FuncNotFoundError(head.ident, head.pos, {
@@ -2330,46 +2661,66 @@ var Engine = class {
2330
2661
  });
2331
2662
  const argNodes = cmd.args.slice(1);
2332
2663
  const lazy = isLazy(fn);
2333
- const args = argNodes.map((n) => lazy ? () => this.evalPrimary(n, scope, ctx) : this.evalPrimary(n, scope, ctx));
2664
+ const args = argNodes.map((n) => lazy ? () => this.evalPrimary(n, scope, ctx, reads) : this.evalPrimary(n, scope, ctx, reads));
2334
2665
  if (piped.kind === "value") {
2335
2666
  const v = piped.value;
2336
2667
  args.push(lazy ? () => v : v);
2337
2668
  }
2338
- return this.invoke(head.ident, fn, args, cmd.pos, ctx);
2669
+ return this.invoke(head.ident, fn, args, cmd.pos, ctx, reads);
2339
2670
  }
2340
- invoke(name, fn, args, pos, ctx) {
2341
- enforceArgTypes(name, fn, args, pos, ctx.source, this.toString, this.fromString, this.isT);
2671
+ invoke(name, fn, args, pos, ctx, reads) {
2342
2672
  try {
2343
- return fn.fn(...args);
2673
+ enforceArgTypes(name, fn, args, pos, ctx.source, this.toString, this.fromString, this.isT);
2344
2674
  } catch (e) {
2675
+ if (e instanceof TemplateError) throw e;
2676
+ throw new EvalError(`error calling ${name}: ${errorText(e)}`, pos, {
2677
+ source: ctx.source,
2678
+ cause: e
2679
+ });
2680
+ }
2681
+ let result;
2682
+ try {
2683
+ result = readCarrier(isInclude(fn) ? this.include(name, args[0], args[1], pos, ctx, reads) : fn.fn(...args), reads);
2684
+ } catch (thrown) {
2685
+ const e = readCarrier(thrown, reads);
2345
2686
  if (e instanceof TypeMismatchError) throw new TypeMismatchError(e.funcName, e.argIndex, e.expected, e.receivedSummary, pos, { source: ctx.source });
2346
- if (e instanceof FailError) throw new FailError(e.message, pos, { source: ctx.source });
2687
+ if (e instanceof FailError) throw new FailError(e.message, pos, {
2688
+ source: ctx.source,
2689
+ cause: e.cause
2690
+ });
2347
2691
  if (e instanceof TemplateError) throw e;
2348
2692
  throw new EvalError(`error calling ${name}: ${errorText(e)}`, pos, {
2349
2693
  source: ctx.source,
2350
2694
  cause: e
2351
2695
  });
2352
2696
  }
2697
+ if (fn.writes === true) ctx.decided(new Set([...reads, ...ctx.marks]));
2698
+ return result;
2699
+ }
2700
+ evalPrimary(node, scope, ctx, reads) {
2701
+ const value = this.evalOperand(node, scope, ctx, reads);
2702
+ if (value instanceof Marked) throw new EvalError("a marked() value reached the template from inside a func's return; return marked(...) itself, not a structure containing one", node.pos, { source: ctx.source });
2703
+ return value;
2353
2704
  }
2354
- evalPrimary(node, scope, ctx) {
2705
+ evalOperand(node, scope, ctx, reads) {
2355
2706
  switch (node.type) {
2356
- case "Dot": return scope.dot;
2707
+ case "Dot": return this.readDot(scope, reads);
2357
2708
  case "Nil": return null;
2358
2709
  case "Bool": return node.value;
2359
2710
  case "Number": return numberValue(node);
2360
2711
  case "String": return node.value;
2361
- case "Field": return this.resolveFieldChain(scope.dot, node.idents, node.pos, ctx);
2362
- case "Variable": return this.resolveVariable(node.idents, scope, node.pos, ctx);
2712
+ case "Field": return this.resolveFieldChain(this.readDot(scope, reads), node.idents, node.pos, ctx);
2713
+ case "Variable": return this.resolveVariable(node.idents, scope, node.pos, ctx, reads);
2363
2714
  case "Identifier": {
2364
2715
  const fn = this.funcs[node.ident];
2365
2716
  if (!fn) throw new FuncNotFoundError(node.ident, node.pos, {
2366
2717
  source: ctx.source,
2367
2718
  available: Object.keys(this.funcs)
2368
2719
  });
2369
- return this.invoke(node.ident, fn, [], node.pos, ctx);
2720
+ return this.invoke(node.ident, fn, [], node.pos, ctx, reads);
2370
2721
  }
2371
- case "Chain": return this.resolveFieldChain(this.evalPrimary(node.node, scope, ctx), node.fields, node.pos, ctx);
2372
- case "Pipe": return this.evalPipe(node, scope, ctx);
2722
+ case "Chain": return this.resolveFieldChain(this.evalPrimary(node.node, scope, ctx, reads), node.fields, node.pos, ctx);
2723
+ case "Pipe": return this.evalPipe(node, scope, ctx, reads);
2373
2724
  default: throw new EvalError(`cannot evaluate ${node.type} as a value`, node.pos, { source: ctx.source });
2374
2725
  }
2375
2726
  }
@@ -2378,38 +2729,34 @@ var Engine = class {
2378
2729
  if (result !== MISSING) return result;
2379
2730
  if (this.missingKey === "error") throw new MissingFieldError(idents, pos, { source: ctx.source });
2380
2731
  }
2381
- resolveVariable(idents, scope, pos, ctx) {
2732
+ resolveVariable(idents, scope, pos, ctx, reads) {
2382
2733
  const head = idents[0] ?? "$";
2383
- if (head === "$") {
2384
- const tail = idents.slice(1);
2385
- return tail.length === 0 ? scope.root : this.resolveFieldChain(scope.root, tail, pos, ctx);
2386
- }
2387
- const lookup = lookupVar(scope, head);
2388
- if (!lookup.found) throw new EvalError(`undefined variable ${head}`, pos, { source: ctx.source });
2734
+ const binding = lookupVar(scope, head);
2735
+ if (binding === void 0) throw undefinedVariable(head, pos, ctx);
2736
+ for (const mark of binding.marks) reads.add(mark);
2389
2737
  const tail = idents.slice(1);
2390
- return tail.length === 0 ? lookup.value : this.resolveFieldChain(lookup.value, tail, pos, ctx);
2738
+ return tail.length === 0 ? binding.value : this.resolveFieldChain(binding.value, tail, pos, ctx);
2391
2739
  }
2392
- emitFromValue(value, ctx) {
2393
- if (value === null || value === void 0) {
2394
- ctx.out.push(this.fromString("<no value>"));
2395
- return;
2396
- }
2397
- if (typeof value === "string") {
2398
- ctx.out.push(this.fromString(value));
2399
- return;
2400
- }
2401
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
2402
- ctx.out.push(this.fromString(String(value)));
2403
- return;
2404
- }
2405
- if (this.isT(value)) {
2406
- ctx.out.push(value);
2407
- return;
2740
+ readDot(scope, reads) {
2741
+ for (const mark of scope.dot.marks) reads.add(mark);
2742
+ return scope.dot.value;
2743
+ }
2744
+ lift(value, pos, source) {
2745
+ if (value === null || value === void 0) return this.fromString("<no value>");
2746
+ if (typeof value === "string") return this.fromString(value);
2747
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return this.fromString(String(value));
2748
+ if (this.isT(value)) return value;
2749
+ try {
2750
+ return this.fromString(formatV(value, this.toString, this.isT));
2751
+ } catch (err) {
2752
+ throw new EvalError(err instanceof UnprintableError ? err.message : `cannot print: ${errorText(err)}`, pos, {
2753
+ source,
2754
+ cause: err
2755
+ });
2408
2756
  }
2409
- ctx.out.push(this.fromString(formatV(value, this.toString, this.isT)));
2410
2757
  }
2411
2758
  };
2412
- const DEFAULT_IS_T = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Map);
2759
+ const DEFAULT_IS_T = (v) => typeof v === "string";
2413
2760
  function createEngine(config) {
2414
2761
  return new Engine(config);
2415
2762
  }
@@ -2423,20 +2770,21 @@ function enforceArgTypes(funcName, spec, values, pos, src, toString = defaultToS
2423
2770
  for (let i = 0; i < values.length; i++) {
2424
2771
  const declared = lookup(i);
2425
2772
  const value = values[i];
2426
- if (!matchesArgType(declared, value, toString, isT)) {
2773
+ const refusal = refusalOf(declared, value, toString, isT);
2774
+ if (refusal !== void 0) {
2427
2775
  if ((declared === "int" || declared === "truncating-int") && (typeof value === "number" || typeof value === "bigint")) throw new NotIntegerError(funcName, i + 1, value, pos, { source: src });
2428
- throw new TypeMismatchError(funcName, i + 1, humanArgType(declared), describeValue(value), pos, { source: src });
2776
+ throw new TypeMismatchError(funcName, i + 1, humanArgType(declared), refusal, pos, { source: src });
2429
2777
  }
2430
2778
  if (declared === "liftable" && typeof value === "string") values[i] = fromString(value);
2431
2779
  if (declared === "truncating-int") values[i] = Math.trunc(Number(value));
2432
2780
  else if (declared === "int" || declared === "float") values[i] = Number(value);
2433
2781
  if (declared === "ordered") {
2434
2782
  if (firstOrdered === -1) firstOrdered = i;
2435
- else if (!sameOrderedKind(values[firstOrdered], value)) throw new TypeMismatchError(funcName, i + 1, `${humanArgType("ordered")} of the same kind as ${describeValue(values[firstOrdered])}`, describeValue(value), pos, { source: src });
2783
+ else if (!sameOrderedKind(values[firstOrdered], value)) throw new TypeMismatchError(funcName, i + 1, `${humanArgType("ordered")} of the same kind as ${typeNameOf(values[firstOrdered])}`, typeNameOf(value), pos, { source: src });
2436
2784
  }
2437
2785
  if (declared === "comparable") {
2438
2786
  if (firstComparable === -1) firstComparable = i;
2439
- else if (!sameComparableKind(values[firstComparable], value)) throw new TypeMismatchError(funcName, i + 1, `${humanArgType("comparable")} of the same kind as ${describeValue(values[firstComparable])}`, describeValue(value), pos, { source: src });
2787
+ else if (!sameComparableKind(values[firstComparable], value)) throw new TypeMismatchError(funcName, i + 1, `${humanArgType("comparable")} of the same kind as ${typeNameOf(values[firstComparable])}`, typeNameOf(value), pos, { source: src });
2440
2788
  }
2441
2789
  }
2442
2790
  }
@@ -2464,7 +2812,7 @@ function makeSlotLookup(argTypes, arity) {
2464
2812
  case "alternating": return (i) => argTypes[i % len];
2465
2813
  }
2466
2814
  }
2467
- function matchesArgType(declared, value, toString, isT) {
2815
+ function matchesArgType(declared, value, isT) {
2468
2816
  switch (declared) {
2469
2817
  case "truthy":
2470
2818
  case "reflective":
@@ -2484,14 +2832,6 @@ function matchesArgType(declared, value, toString, isT) {
2484
2832
  case "collection": return typeof value === "string" || Array.isArray(value) || value instanceof Map || isPlainObject(value);
2485
2833
  case "index-key": return typeof value === "string" || typeof value === "number" || typeof value === "bigint";
2486
2834
  case "sliceable": return typeof value === "string" || Array.isArray(value);
2487
- case "stringifiable":
2488
- if (typeof value === "string") return true;
2489
- try {
2490
- toString(value);
2491
- return true;
2492
- } catch {
2493
- return false;
2494
- }
2495
2835
  case "liftable": return typeof value === "string" || isT(value);
2496
2836
  case "serializable": return isJsonSerializable(value);
2497
2837
  default: throw new Error(`invalid ArgType: ${String(declared)}`);
@@ -2504,7 +2844,7 @@ function defaultToString(value) {
2504
2844
  if (typeof value === "string") return value;
2505
2845
  if (value === null || value === void 0) return "<nil>";
2506
2846
  if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return String(value);
2507
- throw new TypeMismatchError("<engine.toString>", 1, "string (or a consumer-supplied toString that flattens T)", describeValue(value), {
2847
+ throw new TypeMismatchError("<engine.toString>", 1, "string (or a consumer-supplied toString that flattens T)", typeNameOf(value), {
2508
2848
  line: 0,
2509
2849
  column: 0,
2510
2850
  offset: 0
@@ -2544,13 +2884,13 @@ function humanArgType(t) {
2544
2884
  case "int": return "integer (safe-integer number or bigint)";
2545
2885
  case "truncating-int": return "integer (finite number, truncated toward zero, or safe-integer bigint)";
2546
2886
  case "float": return "float (number, including NaN/Infinity, or finite-convertible bigint)";
2547
- case "T": return "T (consumer-defined fragment)";
2887
+ case "T": return "T (a value the engine's isT accepts)";
2548
2888
  case "ordered": return "orderable primitive";
2549
2889
  case "list": return "list";
2550
2890
  case "dict": return "dict (plain object)";
2551
2891
  case "sized": return "sized value (string, list, map, set, or dict)";
2552
2892
  case "comparable": return "comparable value (orderable primitive, nil, list, dict, Map, or Set)";
2553
- case "stringifiable": return "stringifiable value (string or convertible via the engine's toString)";
2893
+ case "stringifiable": return "stringifiable value (string, nil, scalar, a T the engine's toString flattens, an object with its own toString, a class instance, or a list/map of those; not a Set, function or symbol)";
2554
2894
  case "liftable": return "liftable value (T or string, the latter lifted via the engine's fromString)";
2555
2895
  case "callable": return "callable (function value)";
2556
2896
  case "collection": return "collection (string, array, Map, or dict)";
@@ -2565,15 +2905,30 @@ function humanArgType(t) {
2565
2905
  default: throw new Error(`invalid ArgType: ${String(t)}`);
2566
2906
  }
2567
2907
  }
2908
+ function constructFrame(scope) {
2909
+ return pushScope(scope, scope.dot);
2910
+ }
2911
+ function undefinedVariable(name, pos, ctx) {
2912
+ return new EvalError(`undefined variable: ${name}`, pos, { source: ctx.source });
2913
+ }
2914
+ function innermost(e) {
2915
+ return e.cause instanceof TemplateError ? innermost(e.cause) : e;
2916
+ }
2568
2917
  function errorText(e) {
2569
2918
  return e instanceof Error ? e.message : String(e);
2570
2919
  }
2571
- function describeValue(value) {
2572
- if (value === null) return "null";
2573
- if (value === void 0) return "undefined";
2574
- if (Array.isArray(value)) return "array";
2575
- if (value instanceof Map) return "Map";
2576
- return typeof value;
2920
+ function refusalOf(declared, value, toString, isT) {
2921
+ if (declared === "stringifiable") return printRefusal(value, toString, isT)?.summary;
2922
+ return matchesArgType(declared, value, isT) ? void 0 : typeNameOf(value);
2923
+ }
2924
+ function printRefusal(value, toString, isT) {
2925
+ try {
2926
+ formatV(value, toString, isT);
2927
+ return;
2928
+ } catch (err) {
2929
+ if (err instanceof UnprintableError) return err;
2930
+ throw err;
2931
+ }
2577
2932
  }
2578
2933
  /**
2579
2934
  * Produce [key, value] entries for a `range` operand.
@@ -3035,33 +3390,41 @@ function pad3(n) {
3035
3390
  function spacePad2(n) {
3036
3391
  return n < 10 ? ` ${n}` : String(n);
3037
3392
  }
3393
+ function offsetParts(offsetSeconds) {
3394
+ const minutes = Math.trunc(offsetSeconds / 60);
3395
+ const abs = Math.abs(minutes);
3396
+ return {
3397
+ sign: minutes < 0 ? "-" : "+",
3398
+ hh: pad2(Math.floor(abs / 60)),
3399
+ mm: pad2(abs % 60)
3400
+ };
3401
+ }
3038
3402
  /** ±hhmm (no colon). E.g. "+0500", "-0500", "+0000". */
3039
- function fmtOffset(offsetMinutes) {
3040
- const sign = offsetMinutes >= 0 ? "+" : "-";
3041
- const abs = Math.abs(offsetMinutes);
3042
- return `${sign}${pad2(Math.floor(abs / 60))}${pad2(abs % 60)}`;
3403
+ function fmtOffset(offsetSeconds) {
3404
+ const { sign, hh, mm } = offsetParts(offsetSeconds);
3405
+ return `${sign}${hh}${mm}`;
3043
3406
  }
3044
3407
  /** ±hh:mm (with colon). E.g. "+05:00", "-05:00", "+00:00". */
3045
- function fmtOffsetColon(offsetMinutes) {
3046
- const sign = offsetMinutes >= 0 ? "+" : "-";
3047
- const abs = Math.abs(offsetMinutes);
3048
- return `${sign}${pad2(Math.floor(abs / 60))}:${pad2(abs % 60)}`;
3408
+ function fmtOffsetColon(offsetSeconds) {
3409
+ const { sign, hh, mm } = offsetParts(offsetSeconds);
3410
+ return `${sign}${hh}:${mm}`;
3049
3411
  }
3050
3412
  /** ±hh only. */
3051
- function fmtOffsetHour(offsetMinutes) {
3052
- return `${offsetMinutes >= 0 ? "+" : "-"}${pad2(Math.floor(Math.abs(offsetMinutes) / 60))}`;
3413
+ function fmtOffsetHour(offsetSeconds) {
3414
+ const { sign, hh } = offsetParts(offsetSeconds);
3415
+ return `${sign}${hh}`;
3053
3416
  }
3054
3417
  /** Z or ±hhmm. */
3055
- function fmtOffsetZ(offsetMinutes) {
3056
- return offsetMinutes === 0 ? "Z" : fmtOffset(offsetMinutes);
3418
+ function fmtOffsetZ(offsetSeconds) {
3419
+ return offsetSeconds === 0 ? "Z" : fmtOffset(offsetSeconds);
3057
3420
  }
3058
3421
  /** Z or ±hh:mm. */
3059
- function fmtOffsetColonZ(offsetMinutes) {
3060
- return offsetMinutes === 0 ? "Z" : fmtOffsetColon(offsetMinutes);
3422
+ function fmtOffsetColonZ(offsetSeconds) {
3423
+ return offsetSeconds === 0 ? "Z" : fmtOffsetColon(offsetSeconds);
3061
3424
  }
3062
3425
  /** Z or ±hh. */
3063
- function fmtOffsetHourZ(offsetMinutes) {
3064
- return offsetMinutes === 0 ? "Z" : fmtOffsetHour(offsetMinutes);
3426
+ function fmtOffsetHourZ(offsetSeconds) {
3427
+ return offsetSeconds === 0 ? "Z" : fmtOffsetHour(offsetSeconds);
3065
3428
  }
3066
3429
  function fmtFrac(ms, width, trimTrailing) {
3067
3430
  const nanosTotal = ms * 1e6;
@@ -3087,16 +3450,16 @@ const TOKENS$1 = [
3087
3450
  }],
3088
3451
  ["January", (z) => MONTHS_LONG$1[z.month - 1] ?? "January"],
3089
3452
  ["Monday", (z) => WEEKDAYS_LONG[z.weekday] ?? "Monday"],
3090
- ["Z07:00", (z) => fmtOffsetColonZ(z.offsetMinutes)],
3091
- ["-07:00", (z) => fmtOffsetColon(z.offsetMinutes)],
3092
- ["Z0700", (z) => fmtOffsetZ(z.offsetMinutes)],
3093
- ["-0700", (z) => fmtOffset(z.offsetMinutes)],
3094
- ["2006", (z) => String(z.year)],
3453
+ ["Z07:00", (z) => fmtOffsetColonZ(z.offsetSeconds)],
3454
+ ["-07:00", (z) => fmtOffsetColon(z.offsetSeconds)],
3455
+ ["Z0700", (z) => fmtOffsetZ(z.offsetSeconds)],
3456
+ ["-0700", (z) => fmtOffset(z.offsetSeconds)],
3457
+ ["2006", (z) => `${z.year < 0 ? "-" : ""}${String(Math.abs(z.year)).padStart(4, "0")}`],
3095
3458
  ["Jan", (z) => MONTHS_SHORT$1[z.month - 1] ?? "Jan"],
3096
3459
  ["Mon", (z) => WEEKDAYS_SHORT[z.weekday] ?? "Mon"],
3097
3460
  ["MST", (z) => z.tzAbbr],
3098
- ["-07", (z) => fmtOffsetHour(z.offsetMinutes)],
3099
- ["Z07", (z) => fmtOffsetHourZ(z.offsetMinutes)],
3461
+ ["-07", (z) => fmtOffsetHour(z.offsetSeconds)],
3462
+ ["Z07", (z) => fmtOffsetHourZ(z.offsetSeconds)],
3100
3463
  ["15", (z) => pad2(z.hour)],
3101
3464
  ["01", (z) => pad2(z.month)],
3102
3465
  ["02", (z) => pad2(z.day)],
@@ -3104,7 +3467,7 @@ const TOKENS$1 = [
3104
3467
  ["03", (z) => pad2(z.hour12)],
3105
3468
  ["04", (z) => pad2(z.minute)],
3106
3469
  ["05", (z) => pad2(z.second)],
3107
- ["06", (z) => pad2(z.year % 100)],
3470
+ ["06", (z) => pad2(Math.abs(z.year) % 100)],
3108
3471
  ["PM", (z) => z.hour >= 12 ? "PM" : "AM"],
3109
3472
  ["pm", (z) => z.hour >= 12 ? "pm" : "am"],
3110
3473
  ["1", (z) => String(z.month)],
@@ -3135,6 +3498,7 @@ function formatGoLayout(layout, z) {
3135
3498
  //#endregion
3136
3499
  //#region src/sprig/datetime/_zone.ts
3137
3500
  const INTL_OPTS = {
3501
+ era: "short",
3138
3502
  year: "numeric",
3139
3503
  month: "2-digit",
3140
3504
  day: "2-digit",
@@ -3142,13 +3506,9 @@ const INTL_OPTS = {
3142
3506
  hour: "2-digit",
3143
3507
  minute: "2-digit",
3144
3508
  second: "2-digit",
3145
- hour12: false
3509
+ hour12: false,
3510
+ timeZoneName: "short"
3146
3511
  };
3147
- function indexParts(parts) {
3148
- const out = /* @__PURE__ */ new Map();
3149
- for (const p of parts) out.set(p.type, p.value);
3150
- return out;
3151
- }
3152
3512
  const WEEKDAY_NAMES = [
3153
3513
  "Sunday",
3154
3514
  "Monday",
@@ -3158,56 +3518,87 @@ const WEEKDAY_NAMES = [
3158
3518
  "Friday",
3159
3519
  "Saturday"
3160
3520
  ];
3161
- /** Extract date parts in the requested IANA timezone. Falls back to "UTC" on invalid zone, mirroring Go sprig. */
3162
- function getZoneParts(date, tzInput) {
3163
- let tz;
3521
+ function readParts(fmt, date) {
3522
+ const parts = /* @__PURE__ */ new Map();
3523
+ for (const p of fmt.formatToParts(date)) parts.set(p.type, p.value);
3524
+ return (type) => {
3525
+ const value = parts.get(type);
3526
+ if (value === void 0) throw new Error(`Intl.DateTimeFormat omitted the ${type} part`);
3527
+ return value;
3528
+ };
3529
+ }
3530
+ function buildFormatter(timeZone) {
3531
+ return new Intl.DateTimeFormat("en-US", {
3532
+ ...INTL_OPTS,
3533
+ timeZone
3534
+ });
3535
+ }
3536
+ const OFFSET_ZONE = /^[+-]/;
3537
+ const formattersByZone = /* @__PURE__ */ new Map();
3538
+ function zoneFormatter(name) {
3539
+ const key = name.replace(/[A-Z]/g, (c) => c.toLowerCase());
3540
+ const cached = formattersByZone.get(key);
3541
+ if (cached !== void 0) return cached;
3542
+ const loaded = OFFSET_ZONE.test(name) ? void 0 : buildOrUnknown(name);
3543
+ if (loaded === void 0) return zoneFormatter("UTC");
3544
+ formattersByZone.set(key, loaded);
3545
+ return loaded;
3546
+ }
3547
+ function buildOrUnknown(name) {
3548
+ if (name === "UTC") return buildFormatter(name);
3164
3549
  try {
3165
- new Intl.DateTimeFormat("en-US", { timeZone: tzInput });
3166
- tz = tzInput;
3167
- } catch {
3168
- tz = "UTC";
3550
+ return buildFormatter(name);
3551
+ } catch (e) {
3552
+ if (e instanceof RangeError) return void 0;
3553
+ throw e;
3169
3554
  }
3170
- const p = indexParts(new Intl.DateTimeFormat("en-US", {
3171
- ...INTL_OPTS,
3172
- timeZone: tz
3173
- }).formatToParts(date));
3174
- const hour = parseInt(p.get("hour") ?? "0", 10) % 24;
3175
- const tzAbbr = indexParts(new Intl.DateTimeFormat("en-US", {
3176
- timeZone: tz,
3177
- timeZoneName: "short"
3178
- }).formatToParts(date)).get("timeZoneName") ?? tz;
3179
- const offsetMinutes = parseGMTOffset(indexParts(new Intl.DateTimeFormat("en-US", {
3180
- timeZone: tz,
3181
- timeZoneName: "shortOffset"
3182
- }).formatToParts(date)).get("timeZoneName") ?? "GMT");
3183
- const weekday = WEEKDAY_NAMES.indexOf(p.get("weekday") ?? "Sunday");
3555
+ }
3556
+ /** Extract date parts in the requested IANA timezone. Falls back to "UTC" on invalid zone, mirroring Go sprig. */
3557
+ function getZoneParts(date, zone) {
3558
+ const part = readParts(zoneFormatter(zone), date);
3559
+ const eraYear = parseInt(part("year"), 10);
3560
+ const year = part("era") === "BC" ? 1 - eraYear : eraYear;
3561
+ const month = parseInt(part("month"), 10);
3562
+ const day = parseInt(part("day"), 10);
3563
+ const hour = parseInt(part("hour"), 10) % 24;
3564
+ const minute = parseInt(part("minute"), 10);
3565
+ const second = parseInt(part("second"), 10);
3566
+ const ms = date.getUTCMilliseconds();
3567
+ const offsetSeconds = (daysFromCivil(year, month, day) * 864e5 + ((hour * 60 + minute) * 60 + second) * 1e3 + ms - date.getTime()) / 1e3;
3568
+ const weekdayName = part("weekday");
3569
+ const weekday = WEEKDAY_NAMES.indexOf(weekdayName);
3570
+ if (weekday === -1) throw new Error(`Intl.DateTimeFormat gave an unknown weekday ${weekdayName}`);
3184
3571
  return {
3185
- year: parseInt(p.get("year") ?? "2000", 10),
3186
- month: parseInt(p.get("month") ?? "1", 10),
3187
- day: parseInt(p.get("day") ?? "1", 10),
3188
- weekday: weekday === -1 ? 0 : weekday,
3572
+ year,
3573
+ month,
3574
+ day,
3575
+ weekday,
3189
3576
  hour,
3190
3577
  hour12: hour % 12 || 12,
3191
- minute: parseInt(p.get("minute") ?? "0", 10),
3192
- second: parseInt(p.get("second") ?? "0", 10),
3193
- ms: date.getUTCMilliseconds(),
3194
- tzAbbr,
3195
- offsetMinutes
3578
+ minute,
3579
+ second,
3580
+ ms,
3581
+ tzAbbr: part("timeZoneName"),
3582
+ offsetSeconds
3196
3583
  };
3197
3584
  }
3198
- /** Parse "GMT", "GMT+5", "GMT+5:30", "GMT-4" → offset in minutes. */
3199
- function parseGMTOffset(s) {
3200
- if (s === "GMT" || s === "UTC") return 0;
3201
- const m = s.match(/^GMT([+-])(\d{1,2})(?::(\d{2}))?$/);
3202
- if (!m) return 0;
3203
- const sign = m[1] === "+" ? 1 : -1;
3204
- const h = parseInt(m[2] ?? "0", 10);
3205
- const min = parseInt(m[3] ?? "0", 10);
3206
- return sign * (h * 60 + min);
3585
+ function daysFromCivil(year, month, day) {
3586
+ const y = month <= 2 ? year - 1 : year;
3587
+ const era = Math.floor(y / 400);
3588
+ const yearOfEra = y - era * 400;
3589
+ const dayOfYear = Math.floor((153 * ((month + 9) % 12) + 2) / 5) + day - 1;
3590
+ const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
3591
+ return era * 146097 + dayOfEra - 719468;
3207
3592
  }
3593
+ let hostZone;
3208
3594
  /** Host timezone name (IANA string). */
3209
3595
  function localTz() {
3210
- return Intl.DateTimeFormat().resolvedOptions().timeZone;
3596
+ const key = `${globalThis.process?.env.TZ}|${(/* @__PURE__ */ new Date()).getTimezoneOffset()}`;
3597
+ if (hostZone?.key !== key) hostZone = {
3598
+ key,
3599
+ zone: Intl.DateTimeFormat().resolvedOptions().timeZone
3600
+ };
3601
+ return hostZone.zone;
3211
3602
  }
3212
3603
  //#endregion
3213
3604
  //#region src/sprig/datetime/date.ts
@@ -3292,15 +3683,13 @@ function durationRound(d) {
3292
3683
  //#region src/sprig/datetime/htmlDate.ts
3293
3684
  /** `htmlDate t` — YYYY-MM-DD in the host timezone. */
3294
3685
  function htmlDate(t) {
3295
- const z = getZoneParts(resolveDate(t), localTz());
3296
- return `${z.year}-${String(z.month).padStart(2, "0")}-${String(z.day).padStart(2, "0")}`;
3686
+ return formatGoLayout("2006-01-02", getZoneParts(resolveDate(t), localTz()));
3297
3687
  }
3298
3688
  //#endregion
3299
3689
  //#region src/sprig/datetime/htmlDateInZone.ts
3300
3690
  /** `htmlDateInZone t zone` — YYYY-MM-DD in the named timezone. */
3301
3691
  function htmlDateInZone(t, zone) {
3302
- const z = getZoneParts(resolveDate(t), zone);
3303
- return `${z.year}-${String(z.month).padStart(2, "0")}-${String(z.day).padStart(2, "0")}`;
3692
+ return formatGoLayout("2006-01-02", getZoneParts(resolveDate(t), zone));
3304
3693
  }
3305
3694
  //#endregion
3306
3695
  //#region src/sprig/datetime/now.ts
@@ -4123,12 +4512,14 @@ function sprigDicts() {
4123
4512
  "string",
4124
4513
  "value"
4125
4514
  ],
4126
- arity: { kind: "exact" }
4515
+ arity: { kind: "exact" },
4516
+ writes: true
4127
4517
  },
4128
4518
  unset: {
4129
4519
  fn: (d, k) => unset(d, k),
4130
4520
  argTypes: ["dict", "string"],
4131
- arity: { kind: "exact" }
4521
+ arity: { kind: "exact" },
4522
+ writes: true
4132
4523
  },
4133
4524
  keys: {
4134
4525
  fn: (d) => keys(d),
@@ -4482,8 +4873,8 @@ function dig(...args) {
4482
4873
  const dict = args[args.length - 1];
4483
4874
  const def = args[args.length - 2];
4484
4875
  const keys = args.slice(0, -2);
4485
- if (!isPlainDict(dict)) throw bodyTypeMismatch("dig", args.length - 1, "dict", describeKind(dict));
4486
- for (let i = 0; i < keys.length; i++) if (typeof keys[i] !== "string") throw bodyTypeMismatch("dig", i, "string", describeKind(keys[i]));
4876
+ if (!isPlainDict(dict)) throw bodyTypeMismatch("dig", args.length - 1, "dict", typeNameOf(dict));
4877
+ for (let i = 0; i < keys.length; i++) if (typeof keys[i] !== "string") throw bodyTypeMismatch("dig", i, "string", typeNameOf(keys[i]));
4487
4878
  return digFromDict(dict, def, keys, args.length);
4488
4879
  }
4489
4880
  function digFromDict(d, def, ks, argCount) {
@@ -4491,19 +4882,12 @@ function digFromDict(d, def, ks, argCount) {
4491
4882
  if (!Object.hasOwn(d, k)) return def;
4492
4883
  const step = d[k];
4493
4884
  if (ks.length === 1) return step;
4494
- if (!isPlainDict(step)) throw bodyTypeMismatch("dig", argCount - 1, "dict at intermediate key", describeKind(step));
4885
+ if (!isPlainDict(step)) throw bodyTypeMismatch("dig", argCount - 1, "dict at intermediate key", typeNameOf(step));
4495
4886
  return digFromDict(step, def, ks.slice(1), argCount);
4496
4887
  }
4497
4888
  function isPlainDict(v) {
4498
4889
  return v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Map) && !(v instanceof Set);
4499
4890
  }
4500
- function describeKind(v) {
4501
- if (v === null) return "null";
4502
- if (Array.isArray(v)) return "array";
4503
- if (v instanceof Map) return "Map";
4504
- if (v instanceof Set) return "Set";
4505
- return typeof v;
4506
- }
4507
4891
  //#endregion
4508
4892
  //#region src/sprig/lists/first.ts
4509
4893
  function first(list) {
@@ -5518,38 +5902,60 @@ function sprigSemver() {
5518
5902
  };
5519
5903
  }
5520
5904
  //#endregion
5905
+ //#region src/sprig/strings/abbreviateFull.ts
5906
+ /**
5907
+ * goutils.AbbreviateFull (Masterminds/goutils@v1.1.1 stringutils.go), the
5908
+ * function behind both sprig `abbrev` and `abbrevboth`: keep at most
5909
+ * `maxWidth` characters of `cps`, starting near `offset`, marking each cut
5910
+ * end with `...`.
5911
+ *
5912
+ * [LAW:one-source-of-truth] Ported whole, step for step in Go's order, so
5913
+ * both sprig wrappers share Go's one control flow instead of each
5914
+ * reconstructing the branch it noticed. Indexed by code point where Go
5915
+ * indexes by byte — see `runes.js`.
5916
+ *
5917
+ * Go returns an error at its two minimum-width checks; both sprig wrappers
5918
+ * guard against reaching them, so here they throw rather than model sprig's
5919
+ * swallowed error.
5920
+ */
5921
+ function abbreviateFull(cps, offset, maxWidth) {
5922
+ if (cps.length === 0) return "";
5923
+ if (maxWidth < 4) throw new Error("stringutils illegal argument: Minimum abbreviation width is 4");
5924
+ if (cps.length <= maxWidth) return cps.join("");
5925
+ const start = Math.min(offset, cps.length - (maxWidth - 3));
5926
+ if (start <= 4) return `${cps.slice(0, maxWidth - 3).join("")}...`;
5927
+ if (maxWidth < 7) throw new Error("stringutils illegal argument: Minimum abbreviation width with offset is 7");
5928
+ if (start + maxWidth - 3 < cps.length) return `...${abbreviateFull(cps.slice(start), 0, maxWidth - 3)}`;
5929
+ return `...${cps.slice(cps.length - (maxWidth - 3)).join("")}`;
5930
+ }
5931
+ //#endregion
5521
5932
  //#region src/sprig/strings/abbrev.ts
5522
5933
  /**
5523
5934
  * `abbrev width s` — truncate `s` to `width` chars, replacing the tail
5524
- * with `...` when truncation occurs. Width must be at least 4 to fit
5525
- * the ellipsis; smaller widths return `s` unchanged (Go sprig
5526
- * behavior).
5935
+ * with `...` when truncation occurs: sprig's guard around
5936
+ * goutils.Abbreviate, which is AbbreviateFull at offset 0. Widths below 4
5937
+ * cannot fit the ellipsis and return `s` unchanged.
5527
5938
  *
5528
5939
  * `width` counts code points, so the cut never splits an astral
5529
5940
  * character — see `runes.js` for why that differs from Go's bytes.
5530
5941
  */
5531
5942
  function abbrev(width, s) {
5532
- const cps = runes(s);
5533
- if (cps.length <= width) return s;
5534
5943
  if (width < 4) return s;
5535
- return `${cps.slice(0, width - 3).join("")}...`;
5944
+ return abbreviateFull(runes(s), 0, width);
5536
5945
  }
5537
5946
  //#endregion
5538
5947
  //#region src/sprig/strings/abbrevboth.ts
5539
5948
  /**
5540
- * `abbrevboth left right s` — abbreviate from both ends, leaving `...`
5541
- * around the visible window. Mirrors Go sprig's abbrevboth semantics:
5542
- * left/right specify offsets (0-indexed); the result has `...` around
5543
- * a slice taken between them.
5949
+ * `abbrevboth left right s` — sprig's guard around goutils.AbbreviateFull
5950
+ * with `left` as the offset and `right` as the maximum width: a window of
5951
+ * `s` near `left`, with `...` at each end that was cut.
5544
5952
  *
5545
5953
  * Offsets count code points, so the window never splits an astral
5546
5954
  * character — see `runes.js` for why that differs from Go's bytes.
5547
5955
  */
5548
5956
  function abbrevboth(left, right, s) {
5549
- const cps = runes(s);
5550
- if (right < 7 || cps.length < right) return s;
5551
- if (left < 0 || left > cps.length - right + 1) return s;
5552
- return `...${cps.slice(left, left + right - 6).join("")}...`;
5957
+ if (right < 4 || left > 0 && right < 7) return s;
5958
+ return abbreviateFull(runes(s), left, right);
5553
5959
  }
5554
5960
  //#endregion
5555
5961
  //#region src/sprig/strings/caseUtils.ts
@@ -5905,17 +6311,11 @@ function initials(s) {
5905
6311
  function join(sep, list) {
5906
6312
  const parts = [];
5907
6313
  for (const v of list) {
5908
- if (v !== null && v !== void 0 && typeof v === "object") throw bodyTypeMismatch("join", 2, "list of strings/primitives", `list element of type ${describe(v)}`);
6314
+ if (v !== null && v !== void 0 && typeof v === "object") throw bodyTypeMismatch("join", 2, "list of strings/primitives", `list element of type ${typeNameOf(v)}`);
5909
6315
  parts.push(String(v));
5910
6316
  }
5911
6317
  return parts.join(sep);
5912
6318
  }
5913
- function describe(v) {
5914
- if (Array.isArray(v)) return "array";
5915
- if (v instanceof Map) return "Map";
5916
- if (v instanceof Set) return "Set";
5917
- return "object";
5918
- }
5919
6319
  //#endregion
5920
6320
  //#region src/sprig/strings/kebabcase.ts
5921
6321
  /**
@@ -6535,6 +6935,6 @@ function sprigTypes() {
6535
6935
  };
6536
6936
  }
6537
6937
  //#endregion
6538
- export { ArgCountError, Defines, Engine, EvalError, FailError, FuncNotFoundError, MissingFieldError, NotIntegerError, ParseError, Template, TemplateError, TypeMismatchError, createEngine, sprigConversions, sprigDatetime, sprigDefaults, sprigDicts, sprigFlow, sprigHash, sprigLists, sprigMath, sprigRandom, sprigRegex, sprigSemver, sprigStrings, sprigTypes, staticDictEntries };
6938
+ export { ArgCountError, Defines, Engine, EvalError, FailError, FuncNotFoundError, MissingFieldError, NotIntegerError, ParseError, Template, TemplateError, TypeMismatchError, createEngine, include, marked, sprigConversions, sprigDatetime, sprigDefaults, sprigDicts, sprigFlow, sprigHash, sprigLists, sprigMath, sprigRandom, sprigRegex, sprigSemver, sprigStrings, sprigTypes, staticDictEntries, unmarked };
6539
6939
 
6540
6940
  //# sourceMappingURL=index.js.map