@promptctl/go-template-js 0.12.0 → 0.13.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/README.md +22 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +70 -32
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#own","#parent","#value","#marks","parseSource","_exhaustive","MONTHS_LONG","MONTHS_SHORT","TOKENS","_enc","_dec","_enc","isUpper"],"sources":["../src/errors.ts","../src/parser/ast.ts","../src/parser/lexer.ts","../src/parser/parser.ts","../src/parser/walk.ts","../src/evaluator/access.ts","../src/sprig/types/deepEqual.ts","../src/evaluator/lazy.ts","../src/evaluator/truthy.ts","../src/evaluator/builtins.ts","../src/evaluator/include.ts","../src/evaluator/marks.ts","../src/evaluator/scope.ts","../src/evaluator/evaluator.ts","../src/sprig/conversions/atoi.ts","../src/sprig/conversions/float64.ts","../src/sprig/conversions/parseBase0.ts","../src/sprig/conversions/int.ts","../src/sprig/conversions/int64.ts","../src/sprig/conversions/toDecimal.ts","../src/sprig/conversions/toRawJson.ts","../src/sprig/conversions/index.ts","../src/sprig/datetime/_duration.ts","../src/sprig/datetime/_resolve.ts","../src/sprig/datetime/ago.ts","../src/sprig/datetime/_format.ts","../src/sprig/datetime/_zone.ts","../src/sprig/datetime/date.ts","../src/sprig/datetime/dateInZone.ts","../src/sprig/datetime/dateModify.ts","../src/sprig/datetime/duration.ts","../src/sprig/datetime/durationRound.ts","../src/sprig/datetime/htmlDate.ts","../src/sprig/datetime/htmlDateInZone.ts","../src/sprig/datetime/now.ts","../src/sprig/datetime/_parse.ts","../src/sprig/datetime/toDate.ts","../src/sprig/datetime/unixEpoch.ts","../src/sprig/datetime/index.ts","../src/sprig/defaults/empty.ts","../src/sprig/defaults/coalesce.ts","../src/sprig/defaults/default.ts","../src/sprig/defaults/fromJson.ts","../src/sprig/defaults/ternary.ts","../src/sprig/defaults/toJson.ts","../src/sprig/defaults/toPrettyJson.ts","../src/sprig/defaults/index.ts","../src/sprig/dicts/dict.ts","../src/sprig/dicts/get.ts","../src/sprig/dicts/hasKey.ts","../src/sprig/dicts/keys.ts","../src/sprig/dicts/merge.ts","../src/sprig/dicts/mergeOverwrite.ts","../src/sprig/dicts/omit.ts","../src/sprig/dicts/pick.ts","../src/sprig/dicts/pluck.ts","../src/sprig/dicts/set.ts","../src/sprig/dicts/unset.ts","../src/sprig/dicts/values.ts","../src/sprig/dicts/index.ts","../src/sprig/flow/fail.ts","../src/sprig/flow/index.ts","../src/sprig/hash/adler32sum.ts","../src/sprig/hash/_b32.ts","../src/sprig/hash/b32dec.ts","../src/sprig/hash/b32enc.ts","../src/sprig/hash/b64dec.ts","../src/sprig/hash/b64enc.ts","../src/sprig/hash/sha1sum.ts","../src/sprig/hash/sha256sum.ts","../src/sprig/hash/sha512sum.ts","../src/sprig/hash/uuidv4.ts","../src/sprig/hash/index.ts","../src/sprig/lists/all.ts","../src/sprig/lists/any.ts","../src/sprig/lists/append.ts","../src/sprig/lists/chunk.ts","../src/sprig/lists/compact.ts","../src/sprig/lists/concat.ts","../src/evaluator/errors.ts","../src/sprig/lists/dig.ts","../src/sprig/lists/first.ts","../src/sprig/lists/has.ts","../src/sprig/lists/initial.ts","../src/sprig/lists/last.ts","../src/sprig/lists/len.ts","../src/sprig/lists/list.ts","../src/sprig/lists/prepend.ts","../src/sprig/lists/rest.ts","../src/sprig/lists/reverse.ts","../src/sprig/lists/slice.ts","../src/sprig/lists/sortAlpha.ts","../src/sprig/lists/uniq.ts","../src/sprig/lists/without.ts","../src/sprig/lists/index.ts","../src/sprig/math/add.ts","../src/sprig/math/add1.ts","../src/sprig/math/add1f.ts","../src/sprig/math/addf.ts","../src/sprig/math/ceil.ts","../src/sprig/math/div.ts","../src/sprig/math/divf.ts","../src/sprig/math/floor.ts","../src/sprig/math/max.ts","../src/sprig/math/maxf.ts","../src/sprig/math/min.ts","../src/sprig/math/minf.ts","../src/sprig/math/mod.ts","../src/sprig/math/mul.ts","../src/sprig/math/mulf.ts","../src/sprig/math/round.ts","../src/sprig/math/untilStep.ts","../src/sprig/math/seq.ts","../src/sprig/math/sub.ts","../src/sprig/math/subf.ts","../src/sprig/math/until.ts","../src/sprig/math/index.ts","../src/sprig/random/_prng.ts","../src/sprig/random/randAlpha.ts","../src/sprig/random/randAlphaNum.ts","../src/sprig/random/randAscii.ts","../src/sprig/random/randInt.ts","../src/sprig/random/randNumeric.ts","../src/sprig/strings/runes.ts","../src/sprig/random/shuffle.ts","../src/sprig/random/index.ts","../src/sprig/regex/regexFind.ts","../src/sprig/regex/regexFindAll.ts","../src/sprig/regex/regexMatch.ts","../src/sprig/regex/regexReplaceAll.ts","../src/sprig/regex/regexReplaceAllLiteral.ts","../src/sprig/regex/regexSplit.ts","../src/sprig/regex/index.ts","../src/sprig/semver/parse.ts","../src/sprig/semver/semver.ts","../src/sprig/semver/constraint.ts","../src/sprig/semver/semverCompare.ts","../src/sprig/semver/index.ts","../src/sprig/strings/abbreviateFull.ts","../src/sprig/strings/abbrev.ts","../src/sprig/strings/abbrevboth.ts","../src/sprig/strings/caseUtils.ts","../src/sprig/strings/camelcase.ts","../src/sprig/strings/cat.ts","../src/sprig/strings/contains.ts","../src/sprig/strings/hasPrefix.ts","../src/sprig/strings/hasSuffix.ts","../src/sprig/strings/indent.ts","../src/sprig/strings/initials.ts","../src/sprig/strings/join.ts","../src/sprig/strings/kebabcase.ts","../src/sprig/strings/lower.ts","../src/sprig/strings/nindent.ts","../src/sprig/strings/nospace.ts","../src/sprig/strings/plural.ts","../src/sprig/strings/quote.ts","../src/sprig/strings/regexQuoteMeta.ts","../src/sprig/strings/repeat.ts","../src/sprig/strings/replace.ts","../src/sprig/strings/snakecase.ts","../src/sprig/strings/split.ts","../src/sprig/strings/splitList.ts","../src/sprig/strings/splitn.ts","../src/sprig/strings/squote.ts","../src/sprig/strings/substr.ts","../src/sprig/strings/swapcase.ts","../src/sprig/strings/title.ts","../src/sprig/strings/trim.ts","../src/sprig/strings/trimAll.ts","../src/sprig/strings/trimPrefix.ts","../src/sprig/strings/trimSuffix.ts","../src/sprig/strings/trunc.ts","../src/sprig/strings/untitle.ts","../src/sprig/strings/upper.ts","../src/sprig/strings/wrap.ts","../src/sprig/strings/wrapWith.ts","../src/sprig/strings/index.ts","../src/sprig/types/deepCopy.ts","../src/sprig/types/kindOf.ts","../src/sprig/types/kindIs.ts","../src/sprig/types/typeOf.ts","../src/sprig/types/typeIs.ts","../src/sprig/types/typeIsLike.ts","../src/sprig/types/index.ts"],"sourcesContent":["/**\n * Unified error hierarchy for go-template-js.\n *\n * [LAW:single-enforcer] One module owns the error class hierarchy.\n * Both parser and evaluator import from here — no duplicate or\n * parallel definitions.\n *\n * TemplateError (base)\n * ├── ParseError\n * └── EvalError\n * ├── FuncNotFoundError\n * ├── ArgCountError\n * ├── TypeMismatchError\n * └── MissingFieldError\n *\n * Every error carries `pos` and `kind` (a discriminator string for\n * machine inspection). Subclasses add structured fields specific to\n * their failure mode. `.toString()` produces a multi-line presentation\n * with source snippet when `source` was supplied.\n */\n\nimport type { Pos } from \"./parser/pos.js\";\n\nexport type ErrorKind =\n | \"ParseError\"\n | \"EvalError\"\n | \"FuncNotFoundError\"\n | \"ArgCountError\"\n | \"TypeMismatchError\"\n | \"MissingFieldError\"\n | \"FailError\";\n\nexport interface TemplateErrorContext {\n readonly source?: string | undefined;\n /** The error a function body threw, when this one reports it at the call site. */\n readonly cause?: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Base.\n// ---------------------------------------------------------------------------\n\nexport class TemplateError extends Error {\n override readonly name: string = \"TemplateError\";\n readonly kind: ErrorKind = \"EvalError\";\n readonly pos: Pos;\n readonly source: string | undefined;\n\n constructor(message: string, pos: Pos, ctx: TemplateErrorContext = {}) {\n super(message, { cause: ctx.cause });\n this.pos = pos;\n this.source = ctx.source;\n }\n\n /** 3-line excerpt of the source around the error with caret. */\n get sourceSnippet(): string {\n return this.source ? buildSnippet(this.source, this.pos) : \"\";\n }\n\n override toString(): string {\n const head = `${this.name}: ${this.message}\\n at line ${this.pos.line}, column ${this.pos.column}`;\n const snippet = this.sourceSnippet;\n return snippet ? `${head}\\n\\n${snippet}` : head;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Parser error.\n// ---------------------------------------------------------------------------\n\nexport interface ParseErrorContext extends TemplateErrorContext {\n readonly expected?: string;\n readonly found?: string;\n}\n\nexport class ParseError extends TemplateError {\n override readonly name = \"ParseError\";\n override readonly kind: ErrorKind = \"ParseError\";\n readonly expected: string | undefined;\n readonly found: string | undefined;\n\n constructor(message: string, pos: Pos, ctx: ParseErrorContext = {}) {\n super(message, pos, ctx);\n this.expected = ctx.expected;\n this.found = ctx.found;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Eval errors.\n// ---------------------------------------------------------------------------\n\nexport class EvalError extends TemplateError {\n override readonly name: string = \"EvalError\";\n override readonly kind: ErrorKind = \"EvalError\";\n}\n\n/**\n * Thrown when a template references a function the engine's FuncMap\n * has no entry for. Includes a list of nearest-matching registered\n * names by edit distance — most useful when the failure is a typo.\n */\nexport class FuncNotFoundError extends EvalError {\n override readonly name = \"FuncNotFoundError\";\n override readonly kind: ErrorKind = \"FuncNotFoundError\";\n readonly funcName: string;\n readonly suggestions: readonly string[];\n\n constructor(\n funcName: string,\n pos: Pos,\n ctx: TemplateErrorContext & { available?: readonly string[] } = {},\n ) {\n const suggestions = nearestMatches(funcName, ctx.available ?? []);\n const tail = suggestions.length === 0 ? \"\" : ` (did you mean: ${suggestions.join(\", \")}?)`;\n super(`function ${JSON.stringify(funcName)} is not registered${tail}`, pos, ctx);\n this.funcName = funcName;\n this.suggestions = suggestions;\n }\n}\n\n/**\n * The argument counts a func accepts — a closed interval, with\n * `maximum: Infinity` for the variadic and alternating kinds.\n *\n * [LAW:one-source-of-truth] Nothing declares these numbers. They are\n * derived from `TemplateFunc.arity` and `argTypes.length` by\n * `acceptedArgCount` in the evaluator, which is the only producer; a\n * registration that stored its own minimum would be a second copy of a\n * number the declaration already carries.\n */\nexport interface ArgCount {\n readonly minimum: number;\n readonly maximum: number;\n}\n\n/**\n * Thrown when a func is called with a number of arguments its declared\n * arity does not accept — `{{ upper \"a\" \"b\" }}`, `{{ min }}`.\n *\n * The message mirrors Go's `text/template`, which reports a fixed-arity\n * signature as `want N` and a variadic one as `want at least N`. That\n * distinction is read off `accepted`, not passed in, so the two phrasings\n * cannot disagree about which one a given func gets.\n */\nexport class ArgCountError extends EvalError {\n override readonly name = \"ArgCountError\";\n override readonly kind: ErrorKind = \"ArgCountError\";\n readonly funcName: string;\n readonly accepted: ArgCount;\n readonly got: number;\n\n constructor(\n funcName: string,\n accepted: ArgCount,\n got: number,\n pos: Pos,\n ctx: TemplateErrorContext = {},\n ) {\n const want =\n accepted.minimum === accepted.maximum\n ? `${accepted.minimum}`\n : `at least ${accepted.minimum}`;\n super(`wrong number of args for ${funcName}: want ${want} got ${got}`, pos, ctx);\n this.funcName = funcName;\n this.accepted = accepted;\n this.got = got;\n }\n}\n\n// A template error never matches, whatever its text: a func that overflowed\n// was already reported at its own call, as `error calling <func>`.\n// No regex: V8 compiles one on first use, which at the deepest frame\n// overflows into a SyntaxError that is no longer recognised.\nexport function isStackOverflow(e: unknown): boolean {\n return (\n (e instanceof RangeError || (e instanceof Error && e.name === \"InternalError\")) &&\n (e.message.includes(\"call stack\") || e.message.includes(\"too much recursion\"))\n );\n}\n\nexport class TypeMismatchError extends EvalError {\n override readonly name = \"TypeMismatchError\";\n override readonly kind: ErrorKind = \"TypeMismatchError\";\n readonly funcName: string;\n /** 1-based argument index for human-readable messages. */\n readonly argIndex: number;\n readonly expected: string;\n readonly receivedSummary: string;\n\n constructor(\n funcName: string,\n argIndex: number,\n expected: string,\n receivedSummary: string,\n pos: Pos,\n ctx: TemplateErrorContext = {},\n ) {\n super(\n `function ${JSON.stringify(funcName)} arg ${argIndex}: expected ${expected}, ` +\n `but a value of type ${receivedSummary} flowed in. Pass it through \\`unstyled\\` (or your ` +\n `engine's flatten function) to convert.`,\n pos,\n ctx,\n );\n this.funcName = funcName;\n this.argIndex = argIndex;\n this.expected = expected;\n this.receivedSummary = receivedSummary;\n }\n}\n\n/**\n * An integer slot refused a number that is not a safe integer. Still a\n * `TypeMismatchError` (the slot's type refused the value), but worded\n * with the value and the reason: a fractional is Go's own refusal,\n * `expected integer; found 2.7`, and an integer past 2^53 is\n * `integer out of range: <n>`, since JS cannot carry it exactly. The\n * generic wording would say a number was expected and a number arrived,\n * and suggest flattening a styled value that was never there.\n */\nexport class NotIntegerError extends TypeMismatchError {\n constructor(\n funcName: string,\n argIndex: number,\n value: number | bigint,\n pos: Pos,\n ctx: TemplateErrorContext = {},\n ) {\n super(funcName, argIndex, \"integer\", String(value), pos, ctx);\n this.message = Number.isInteger(Number(value))\n ? `integer out of range: ${String(value)}`\n : `expected integer; found ${String(value)}`;\n }\n}\n\nexport class MissingFieldError extends EvalError {\n override readonly name = \"MissingFieldError\";\n override readonly kind: ErrorKind = \"MissingFieldError\";\n readonly path: readonly string[];\n\n constructor(path: readonly string[], pos: Pos, ctx: TemplateErrorContext = {}) {\n super(`field \"${path.join(\".\")}\" not found on receiver`, pos, ctx);\n this.path = path;\n }\n}\n\n// ---------------------------------------------------------------------------\n// FailError — thrown by the sprig `fail` function.\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a template calls `fail \"message\"`. Consumers can catch\n * this specifically to distinguish intentional template failures from\n * engine bugs. The message comes from the template author.\n *\n * [LAW:single-enforcer] One class, one place. The `fail` sprig function\n * is the only producer; catch `FailError` to handle it distinctly from\n * TypeMismatchError or other eval errors.\n */\nexport class FailError extends EvalError {\n override readonly name = \"FailError\";\n override readonly kind: ErrorKind = \"FailError\";\n\n constructor(\n message: string,\n pos: Pos = { line: 0, column: 0, offset: 0 },\n ctx: TemplateErrorContext = {},\n ) {\n super(message, pos, ctx);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Snippet builder — pure helper.\n// ---------------------------------------------------------------------------\n\nfunction buildSnippet(source: string, pos: Pos): string {\n const lines = source.split(\"\\n\");\n const lineIdx = pos.line - 1;\n\n const display: { num: number; text: string }[] = [];\n if (lineIdx - 1 >= 0 && lineIdx - 1 < lines.length) {\n display.push({ num: lineIdx, text: lines[lineIdx - 1] ?? \"\" });\n }\n if (lineIdx >= 0 && lineIdx < lines.length) {\n display.push({ num: lineIdx + 1, text: lines[lineIdx] ?? \"\" });\n }\n if (lineIdx + 1 < lines.length) {\n display.push({ num: lineIdx + 2, text: lines[lineIdx + 1] ?? \"\" });\n }\n if (display.length === 0) return \"\";\n\n const numWidth = String(display[display.length - 1]?.num ?? 1).length;\n const out: string[] = [];\n for (const d of display) {\n out.push(` ${String(d.num).padStart(numWidth, \" \")} | ${d.text}`);\n if (d.num === pos.line) {\n const gutter = ` ${\" \".repeat(numWidth)} | `;\n const caretPad = \" \".repeat(Math.max(0, pos.column - 1));\n out.push(`${gutter}${caretPad}^`);\n }\n }\n return out.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Edit-distance suggestions for FuncNotFoundError.\n// ---------------------------------------------------------------------------\n\nfunction nearestMatches(target: string, candidates: readonly string[]): string[] {\n if (candidates.length === 0) return [];\n const ranked = candidates\n .map((c) => ({ name: c, dist: editDistance(target, c) }))\n .sort((a, b) => a.dist - b.dist);\n // Heuristic: top 3, but only when the closest is within length/2\n // edits — avoid wildly unrelated suggestions when the user typed\n // something nothing like any registered name.\n const cutoff = Math.max(2, Math.floor(target.length / 2));\n return ranked\n .filter((r) => r.dist <= cutoff)\n .slice(0, 3)\n .map((r) => r.name);\n}\n\nfunction editDistance(a: string, b: string): number {\n if (a === b) return 0;\n const m = a.length;\n const n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n const prev = new Array<number>(n + 1);\n const cur = new Array<number>(n + 1);\n for (let j = 0; j <= n; j++) prev[j] = j;\n for (let i = 1; i <= m; i++) {\n cur[0] = i;\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n cur[j] = Math.min((cur[j - 1] ?? 0) + 1, (prev[j] ?? 0) + 1, (prev[j - 1] ?? 0) + cost);\n }\n for (let j = 0; j <= n; j++) prev[j] = cur[j] ?? 0;\n }\n return prev[n] ?? 0;\n}\n","/**\n * AST node types for go-template-js.\n *\n * Mirrors `text/template/parse` (https://pkg.go.dev/text/template/parse) so\n * an eventual Go port shares the same shape.\n *\n * [LAW:dataflow-not-control-flow] Every node has a single string literal\n * `type` discriminator. Downstream code (evaluator, walker, stringifier) is\n * one exhaustive switch over `Node[\"type\"]` — no class hierarchies, no\n * instanceof checks. Variability lives in the data (the discriminator\n * value), not in scattered conditionals.\n *\n * [LAW:one-source-of-truth] Every node carries `pos: Pos` from a single\n * canonical Pos type. No node grows its own ad-hoc position fields.\n */\n\nimport type { Pos } from \"./pos.js\";\n\n// ---------------------------------------------------------------------------\n// Trim markers — the `{{- ... -}}` whitespace-stripping syntax.\n// ---------------------------------------------------------------------------\n\nexport interface TrimMarkers {\n readonly trimLeft: boolean;\n readonly trimRight: boolean;\n}\n\nexport const NO_TRIM: TrimMarkers = { trimLeft: false, trimRight: false };\n\n// ---------------------------------------------------------------------------\n// Node base — type discriminator + position.\n// ---------------------------------------------------------------------------\n\ninterface NodeBase<T extends string> {\n readonly type: T;\n readonly pos: Pos;\n}\n\n// ---------------------------------------------------------------------------\n// Leaves.\n// ---------------------------------------------------------------------------\n\nexport interface TextNode extends NodeBase<\"Text\"> {\n readonly text: string;\n}\n\nexport interface CommentNode extends NodeBase<\"Comment\"> {\n /** The comment body, without the surrounding `{{/*` `*\\/}}`. */\n readonly text: string;\n readonly trim: TrimMarkers;\n}\n\nexport type DotNode = NodeBase<\"Dot\">;\nexport type NilNode = NodeBase<\"Nil\">;\n\nexport interface BoolNode extends NodeBase<\"Bool\"> {\n readonly value: boolean;\n}\n\n/**\n * Numeric literal. Go's parser admits ints, floats, complex, and untyped\n * constants in several bases. We preserve the original source `text` and\n * tag the parsed flavors so the evaluator can pick the right runtime\n * representation without re-lexing.\n */\nexport interface NumberNode extends NodeBase<\"Number\"> {\n /** Original source text (e.g. `0x10`, `1.5e3`, `0o17`, `42i`). */\n readonly text: string;\n readonly isInt: boolean;\n readonly isUint: boolean;\n readonly isFloat: boolean;\n readonly isComplex: boolean;\n /** Present iff `isInt || isUint`. Use bigint for safe full-range ints. */\n readonly intValue?: bigint;\n /** Present iff `isFloat`. */\n readonly floatValue?: number;\n /** Present iff `isComplex` — [real, imag]. */\n readonly complexValue?: readonly [number, number];\n}\n\nexport interface StringNode extends NodeBase<\"String\"> {\n /** Source-as-written including surrounding quotes (e.g. `\"hi\"` or `` `raw` ``). */\n readonly raw: string;\n /** Decoded string value (escapes processed). */\n readonly value: string;\n}\n\nexport interface IdentifierNode extends NodeBase<\"Identifier\"> {\n readonly ident: string;\n}\n\n/**\n * Field chain like `.x.y.z`.\n * `idents` excludes the leading dot — `.x.y` → `[\"x\", \"y\"]`.\n */\nexport interface FieldNode extends NodeBase<\"Field\"> {\n readonly idents: readonly string[];\n}\n\n/**\n * Variable reference like `$var` or `$var.x.y`.\n * `idents[0]` is the variable's name *with* its leading `$` (`\"$var\"`),\n * matching Go's parse package convention. Subsequent entries are field\n * accesses.\n */\nexport interface VariableNode extends NodeBase<\"Variable\"> {\n readonly idents: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// Composites.\n// ---------------------------------------------------------------------------\n\n/** A sequence of nodes — the body of a template, branch, or block. */\nexport interface ListNode extends NodeBase<\"List\"> {\n readonly nodes: readonly Node[];\n}\n\n/**\n * A field access on a parenthesised pipeline result, e.g. `(pipe).x.y`.\n * `node` is the inner expression (typically a PipeNode or another\n * primary).\n */\nexport interface ChainNode extends NodeBase<\"Chain\"> {\n readonly node: Node;\n readonly fields: readonly string[];\n}\n\n/** A single command in a pipeline: head + arguments. */\nexport interface CommandNode extends NodeBase<\"Command\"> {\n readonly args: readonly Node[];\n}\n\n/**\n * A pipeline — `cmd1 a b | cmd2 c | cmd3`.\n *\n * `decls` carries left-hand variable declarations for assignment forms:\n * `{{ $a := pipe }}` → decls = [$a], isAssign = false\n * `{{ $a = pipe }}` → decls = [$a], isAssign = true\n * `{{ pipe }}` → decls = [], isAssign = false\n */\nexport interface PipeNode extends NodeBase<\"Pipe\"> {\n readonly decls: readonly VariableNode[];\n readonly isAssign: boolean;\n readonly cmds: readonly CommandNode[];\n}\n\n/** `{{ pipeline }}` — produces output from a pipeline value. */\nexport interface ActionNode extends NodeBase<\"Action\"> {\n readonly pipe: PipeNode;\n readonly trim: TrimMarkers;\n}\n\n// ---------------------------------------------------------------------------\n// Branch nodes — if / range / with all share the same shape conceptually.\n// We keep them as separate types so the discriminator lets the evaluator\n// switch exhaustively, matching Go's parse package which emits IfNode,\n// RangeNode, WithNode as distinct concrete types.\n// ---------------------------------------------------------------------------\n\ninterface BranchFields {\n readonly pipe: PipeNode;\n readonly list: ListNode;\n /** Absent when there's no `{{else}}` clause. */\n readonly elseList?: ListNode;\n readonly trim: TrimMarkers;\n}\n\nexport interface IfNode extends NodeBase<\"If\">, BranchFields {}\nexport interface RangeNode extends NodeBase<\"Range\">, BranchFields {}\nexport interface WithNode extends NodeBase<\"With\">, BranchFields {}\n\n// ---------------------------------------------------------------------------\n// Range-body control-flow leaves — `{{break}}` and `{{continue}}`.\n//\n// [LAW:types-are-the-program] Break/continue carry no pipeline and no\n// body. They are leaves whose only purpose is the discriminator: the\n// evaluator's range loop switches on `type` to know which control-flow\n// transition to perform. Encoding them as leaves (instead of, say, an\n// ActionNode with a magic identifier) is the strongest theorem about\n// them — the type forbids \"{{break .foo}}\" by construction, so no body\n// has to guard against a stray pipeline.\n//\n// Their legality is *lexical*: only valid inside a `{{range}}` body\n// (not inside a `{{define}}`/`{{block}}` body, even if those are\n// lexically nested inside a range — those bodies are independent\n// parse contexts in Go's text/template, and we match that here).\n// The parser enforces this via a rangeDepth counter that is saved /\n// restored around sub-template bodies.\n// ---------------------------------------------------------------------------\n\nexport interface BreakNode extends NodeBase<\"Break\"> {\n readonly trim: TrimMarkers;\n}\n\nexport interface ContinueNode extends NodeBase<\"Continue\"> {\n readonly trim: TrimMarkers;\n}\n\n// ---------------------------------------------------------------------------\n// Sub-template nodes.\n// ---------------------------------------------------------------------------\n\n/** `{{template \"name\" pipe?}}` — invokes a named template. */\nexport interface TemplateNode extends NodeBase<\"Template\"> {\n readonly name: string;\n /** Optional argument expression. Absent when no pipe is supplied. */\n readonly pipe?: PipeNode;\n readonly trim: TrimMarkers;\n}\n\n/** `{{block \"name\" pipe}} list {{end}}` — define + invoke in one form. */\nexport interface BlockNode extends NodeBase<\"Block\"> {\n readonly name: string;\n readonly pipe: PipeNode;\n readonly list: ListNode;\n readonly trim: TrimMarkers;\n}\n\n// ---------------------------------------------------------------------------\n// The discriminated union.\n// ---------------------------------------------------------------------------\n\nexport type Node =\n | TextNode\n | CommentNode\n | DotNode\n | NilNode\n | BoolNode\n | NumberNode\n | StringNode\n | IdentifierNode\n | FieldNode\n | VariableNode\n | ListNode\n | ChainNode\n | CommandNode\n | PipeNode\n | ActionNode\n | IfNode\n | RangeNode\n | WithNode\n | BreakNode\n | ContinueNode\n | TemplateNode\n | BlockNode;\n\nexport type NodeType = Node[\"type\"];\n\nexport type NodeOf<T extends NodeType> = Extract<Node, { type: T }>;\n\n// ---------------------------------------------------------------------------\n// Type-level exhaustiveness helper.\n//\n// [LAW:dataflow-not-control-flow] Use `assertNever` in switches over Node\n// to make adding a new node kind a compile error at every dispatch site,\n// not a silent fallthrough.\n// ---------------------------------------------------------------------------\n\nexport function assertNever(value: never): never {\n throw new Error(`unhandled node kind: ${JSON.stringify(value)}`);\n}\n","/**\n * Lexer for Go-template syntax.\n *\n * Mirrors the tokens that text/template/parse/lex.go produces. The lexer\n * is a pull-style state machine — call `next()` to consume the next\n * token, `peek()` to look without consuming. EOF is emitted explicitly\n * as a terminal token.\n *\n * [LAW:dataflow-not-control-flow] The state of the lexer is captured in\n * a single `mode` discriminator (`text` | `action` | `done`), and the\n * `next()` method dispatches on that mode in one switch. Variability\n * lives in the data (current offset, current mode), not in scattered\n * conditional code paths around side effects.\n *\n * [LAW:single-enforcer] All position tracking happens through `advance`.\n * Callers never adjust `offset`, `line`, or `column` directly — that\n * would let line/column drift from offset.\n */\n\nimport { ParseError } from \"./errors.js\";\nimport type { Pos } from \"./pos.js\";\n\n// ---------------------------------------------------------------------------\n// Tokens.\n// ---------------------------------------------------------------------------\n\nexport type TokenType =\n | \"Text\"\n | \"LeftDelim\"\n | \"RightDelim\"\n | \"Comment\"\n | \"Identifier\"\n | \"Field\"\n | \"Variable\"\n | \"String\"\n | \"Number\"\n | \"Char\"\n | \"Bool\"\n | \"Nil\"\n | \"Dot\"\n | \"LeftParen\"\n | \"RightParen\"\n | \"Pipe\"\n | \"Assign\"\n | \"Declare\"\n | \"Comma\"\n | \"If\"\n | \"Else\"\n | \"End\"\n | \"Range\"\n | \"With\"\n | \"Break\"\n | \"Continue\"\n | \"Define\"\n | \"Template\"\n | \"Block\"\n | \"EOF\";\n\nexport interface Token {\n readonly type: TokenType;\n /** Original source text covered by the token (raw — quotes/dots/etc preserved). */\n readonly value: string;\n readonly pos: Pos;\n /** Set on LeftDelim when the source had `{{-`. */\n readonly trimLeft?: boolean;\n /** Set on RightDelim when the source had `-}}`. */\n readonly trimRight?: boolean;\n}\n\nconst KEYWORDS = new Map<string, TokenType>([\n [\"if\", \"If\"],\n [\"else\", \"Else\"],\n [\"end\", \"End\"],\n [\"range\", \"Range\"],\n [\"with\", \"With\"],\n [\"break\", \"Break\"],\n [\"continue\", \"Continue\"],\n [\"define\", \"Define\"],\n [\"template\", \"Template\"],\n [\"block\", \"Block\"],\n [\"true\", \"Bool\"],\n [\"false\", \"Bool\"],\n [\"nil\", \"Nil\"],\n]);\n\n/**\n * Action delimiters. Default is Go's `{{` / `}}`. Trim-marker forms are\n * derived mechanically: `<left>-` opens with-trim and `-<right>` closes\n * with-trim, matching Go's `text/template`.\n *\n * [LAW:types-are-the-program] Both sides are required if specified —\n * neither may be empty. This is a stronger theorem than Go's API\n * (which lets one side default while the other is set) and forbids\n * the half-configured state that would otherwise have to be defended\n * against at every internal use site.\n */\nexport interface Delims {\n readonly left: string;\n readonly right: string;\n}\n\nexport const DEFAULT_DELIMS: Delims = { left: \"{{\", right: \"}}\" };\n\nconst COMMENT_OPEN = \"/*\";\nconst COMMENT_CLOSE = \"*/\";\n\n// ---------------------------------------------------------------------------\n// Lexer.\n// ---------------------------------------------------------------------------\n\ntype Mode = \"text\" | \"action\" | \"done\";\n\nexport class Lexer {\n private readonly src: string;\n // [LAW:dataflow-not-control-flow] Delims are data, not modes. Lifting\n // them from module-level constants to instance fields adds no\n // branches — the existing state machine reads its delimiter strings\n // from these fields instead of from compile-time constants.\n private readonly leftDelim: string;\n private readonly rightDelim: string;\n private offset = 0;\n private line = 1;\n private column = 1;\n private mode: Mode = \"text\";\n private pending: Token | undefined;\n\n constructor(src: string, delims: Delims = DEFAULT_DELIMS) {\n this.src = src;\n this.leftDelim = delims.left;\n this.rightDelim = delims.right;\n }\n\n /** Position of the next byte to consume. */\n pos(): Pos {\n return { line: this.line, column: this.column, offset: this.offset };\n }\n\n /**\n * Build a ParseError that always carries the source for snippet\n * extraction. Lexer call sites use this exclusively.\n */\n private err(\n message: string,\n pos: Pos,\n extra: { expected?: string; found?: string } = {},\n ): ParseError {\n return new ParseError(message, pos, { ...extra, source: this.src });\n }\n\n next(): Token {\n if (this.pending) {\n const t = this.pending;\n this.pending = undefined;\n return t;\n }\n return this.read();\n }\n\n peek(): Token {\n if (!this.pending) this.pending = this.read();\n return this.pending;\n }\n\n private read(): Token {\n switch (this.mode) {\n case \"text\":\n return this.readText();\n case \"action\":\n return this.readAction();\n case \"done\":\n return this.makeToken(\"EOF\", \"\", this.pos());\n }\n }\n\n // ---------------------------------------------------------------------\n // TEXT mode — accumulate characters until a `{{` or EOF.\n //\n // Trim markers complicate this: a `{{-` token instructs the *previous*\n // text token to drop trailing whitespace. We resolve this by peeking\n // for `-` after the opening delimiter and trimming the captured text\n // before emitting it.\n // ---------------------------------------------------------------------\n private readText(): Token {\n if (this.offset >= this.src.length) {\n this.mode = \"done\";\n return this.makeToken(\"EOF\", \"\", this.pos());\n }\n const startPos = this.pos();\n\n // Find next `<leftDelim>` or EOF.\n let end = this.offset;\n while (end < this.src.length && !this.src.startsWith(this.leftDelim, end)) {\n end += 1;\n }\n\n // Detect trim marker on the upcoming delim.\n const sawDelim = end < this.src.length;\n const trimLeft = sawDelim && this.src[end + this.leftDelim.length] === \"-\";\n\n // If `{{-`, strip trailing ASCII whitespace from the captured text.\n let textEnd = end;\n if (trimLeft) {\n while (textEnd > this.offset && isSpace(this.src[textEnd - 1] ?? \"\")) {\n textEnd -= 1;\n }\n }\n\n if (textEnd > this.offset) {\n const value = this.src.slice(this.offset, textEnd);\n this.advanceTo(textEnd);\n return this.makeToken(\"Text\", value, startPos);\n }\n\n // No text content — there may still be whitespace between us and\n // the delim (already trimmed away from the previous Text token).\n // Skip it before emitting the delim so position bookkeeping stays\n // synchronised.\n this.advanceTo(end);\n return this.emitLeftDelim(trimLeft);\n }\n\n private emitLeftDelim(trimLeft: boolean): Token {\n const start = this.pos();\n this.advanceBy(this.leftDelim.length);\n if (trimLeft) {\n // skip the `-`\n this.advanceBy(1);\n // skip the whitespace right after `<left>-` per Go's spec\n while (isSpace(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n }\n this.mode = \"action\";\n\n // Comment handling: if the next chars are `/*`, consume until `*/<right>`\n // and emit a Comment token instead of a LeftDelim.\n if (this.src.startsWith(COMMENT_OPEN, this.offset)) {\n return this.readComment(start, trimLeft);\n }\n\n return this.makeToken(\n \"LeftDelim\",\n trimLeft ? `${this.leftDelim}-` : this.leftDelim,\n start,\n trimLeft ? { trimLeft: true } : {},\n );\n }\n\n private readComment(startDelim: Pos, trimLeft: boolean): Token {\n this.advanceBy(COMMENT_OPEN.length);\n const bodyStart = this.offset;\n const closeIdx = this.src.indexOf(COMMENT_CLOSE, this.offset);\n if (closeIdx === -1) {\n throw this.err(\"unclosed comment\", startDelim, {\n expected: `*/${this.rightDelim}`,\n found: \"end of input\",\n });\n }\n // Advance through body\n this.advanceTo(closeIdx);\n const body = this.src.slice(bodyStart, closeIdx).trim();\n this.advanceBy(COMMENT_CLOSE.length);\n\n // Optional whitespace between `*/` and the closing `<right>` / `-<right>`.\n // Go's spec says `-<right>` requires *adjacent* whitespace; we accept\n // either `*/ -<right>`, `*/-<right>`, `*/ <right>`, or `*/<right>` for\n // forgiveness.\n while (isSpace(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n let trimRight = false;\n if (this.src[this.offset] === \"-\") {\n trimRight = true;\n this.advanceBy(1);\n }\n if (!this.src.startsWith(this.rightDelim, this.offset)) {\n throw this.err(`expected \\`${this.rightDelim}\\` to close comment`, this.pos(), {\n expected: this.rightDelim,\n found: this.src[this.offset] ?? \"end of input\",\n });\n }\n this.advanceBy(this.rightDelim.length);\n // After comment body close, drop trailing whitespace from upcoming\n // text if `-}}` was used. Implement by skipping forward in text now.\n if (trimRight) {\n while (isSpace(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n }\n this.mode = \"text\";\n\n // Comment carries its own trim flags so the parser can preserve\n // them in the AST. Omit unset flags entirely (per\n // exactOptionalPropertyTypes).\n return this.makeToken(\"Comment\", body, startDelim, {\n ...(trimLeft ? { trimLeft: true } : {}),\n ...(trimRight ? { trimRight: true } : {}),\n });\n }\n\n // ---------------------------------------------------------------------\n // ACTION mode — operators, identifiers, literals.\n // ---------------------------------------------------------------------\n private readAction(): Token {\n this.skipActionSpaces();\n\n // Right delim? Check `-<right>` *first* — otherwise a delim like\n // `}}` would match the bare form before the trim-form is considered.\n if (this.src.startsWith(`-${this.rightDelim}`, this.offset)) {\n const start = this.pos();\n this.advanceBy(1 + this.rightDelim.length);\n this.mode = \"text\";\n // strip leading whitespace from upcoming text\n while (isSpace(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n return this.makeToken(\"RightDelim\", `-${this.rightDelim}`, start, { trimRight: true });\n }\n if (this.src.startsWith(this.rightDelim, this.offset)) {\n const start = this.pos();\n this.advanceBy(this.rightDelim.length);\n this.mode = \"text\";\n return this.makeToken(\"RightDelim\", this.rightDelim, start);\n }\n\n if (this.offset >= this.src.length) {\n throw this.err(\"unclosed action\", this.pos(), {\n expected: this.rightDelim,\n found: \"end of input\",\n });\n }\n\n const ch = this.src[this.offset];\n const start = this.pos();\n\n // Punctuation.\n switch (ch) {\n case \"(\":\n this.advanceBy(1);\n return this.makeToken(\"LeftParen\", \"(\", start);\n case \")\":\n this.advanceBy(1);\n return this.makeToken(\"RightParen\", \")\", start);\n case \"|\":\n this.advanceBy(1);\n return this.makeToken(\"Pipe\", \"|\", start);\n case \",\":\n this.advanceBy(1);\n return this.makeToken(\"Comma\", \",\", start);\n case \":\":\n if (this.src[this.offset + 1] === \"=\") {\n this.advanceBy(2);\n return this.makeToken(\"Declare\", \":=\", start);\n }\n throw this.err(\"expected `:=`\", start, { expected: \":=\", found: \":\" });\n case \"=\":\n this.advanceBy(1);\n return this.makeToken(\"Assign\", \"=\", start);\n case '\"':\n return this.readQuotedString(start);\n case \"`\":\n return this.readRawString(start);\n case \"'\":\n return this.readChar(start);\n }\n\n // Variable: $name or $ alone.\n if (ch === \"$\") {\n return this.readVariable(start);\n }\n\n // Number — possibly signed. Go template numbers can begin with +/-.\n if (\n ch !== undefined &&\n (isDigit(ch) ||\n (isSign(ch) && isDigit(this.src[this.offset + 1] ?? \"\")) ||\n (ch === \".\" && isDigit(this.src[this.offset + 1] ?? \"\")))\n ) {\n return this.readNumber(start);\n }\n\n // Field: `.name` or bare `.`\n if (ch === \".\") {\n return this.readDotOrField(start);\n }\n\n // Identifier / keyword.\n if (ch !== undefined && isIdentStart(ch)) {\n return this.readIdentifier(start);\n }\n\n throw this.err(`unexpected character ${JSON.stringify(ch)}`, start, {\n found: ch ?? \"end of input\",\n });\n }\n\n // ---------------------------------------------------------------------\n // Literals + identifiers.\n // ---------------------------------------------------------------------\n\n private readQuotedString(start: Pos): Token {\n const startOffset = this.offset;\n this.advanceBy(1);\n while (this.offset < this.src.length) {\n const c = this.src[this.offset];\n if (c === \"\\\\\") {\n // Skip escape sequence (consume the next char, no decoding here).\n this.advanceBy(1);\n if (this.offset < this.src.length) this.advanceBy(1);\n continue;\n }\n if (c === \"\\n\") {\n throw this.err(\"newline in interpreted string\", start, {\n found: \"\\\\n\",\n });\n }\n if (c === '\"') {\n this.advanceBy(1);\n return this.makeToken(\"String\", this.src.slice(startOffset, this.offset), start);\n }\n this.advanceBy(1);\n }\n throw this.err(\"unterminated string literal\", start, {\n expected: '\"',\n found: \"end of input\",\n });\n }\n\n private readRawString(start: Pos): Token {\n const startOffset = this.offset;\n this.advanceBy(1);\n while (this.offset < this.src.length) {\n if (this.src[this.offset] === \"`\") {\n this.advanceBy(1);\n return this.makeToken(\"String\", this.src.slice(startOffset, this.offset), start);\n }\n this.advanceBy(1);\n }\n throw this.err(\"unterminated raw string literal\", start, {\n expected: \"`\",\n found: \"end of input\",\n });\n }\n\n private readChar(start: Pos): Token {\n const startOffset = this.offset;\n this.advanceBy(1);\n while (this.offset < this.src.length) {\n const c = this.src[this.offset];\n if (c === \"\\\\\") {\n this.advanceBy(1);\n if (this.offset < this.src.length) this.advanceBy(1);\n continue;\n }\n if (c === \"\\n\") {\n throw this.err(\"newline in rune literal\", start, { found: \"\\\\n\" });\n }\n if (c === \"'\") {\n this.advanceBy(1);\n return this.makeToken(\"Char\", this.src.slice(startOffset, this.offset), start);\n }\n this.advanceBy(1);\n }\n throw this.err(\"unterminated rune literal\", start, {\n expected: \"'\",\n found: \"end of input\",\n });\n }\n\n private readNumber(start: Pos): Token {\n const startOffset = this.offset;\n // Optional sign.\n if (isSign(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n // Detect base prefix.\n if (this.src[this.offset] === \"0\" && this.offset + 1 < this.src.length) {\n const next = this.src[this.offset + 1];\n if (next === \"x\" || next === \"X\") {\n this.advanceBy(2);\n while (isHex(this.src[this.offset] ?? \"\") || this.src[this.offset] === \"_\") {\n this.advanceBy(1);\n }\n // hex float (1.0p1) — Go supports it; we accept the form lazily\n if (\n this.src[this.offset] === \".\" ||\n this.src[this.offset] === \"p\" ||\n this.src[this.offset] === \"P\"\n ) {\n while (this.isHexFloatTail(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n }\n return this.finishNumber(startOffset, start);\n }\n if (next === \"o\" || next === \"O\") {\n this.advanceBy(2);\n while (isOctal(this.src[this.offset] ?? \"\") || this.src[this.offset] === \"_\")\n this.advanceBy(1);\n return this.finishNumber(startOffset, start);\n }\n if (next === \"b\" || next === \"B\") {\n this.advanceBy(2);\n while (isBinary(this.src[this.offset] ?? \"\") || this.src[this.offset] === \"_\")\n this.advanceBy(1);\n return this.finishNumber(startOffset, start);\n }\n }\n\n // Decimal / float.\n while (isDigit(this.src[this.offset] ?? \"\") || this.src[this.offset] === \"_\") this.advanceBy(1);\n if (this.src[this.offset] === \".\") {\n this.advanceBy(1);\n while (isDigit(this.src[this.offset] ?? \"\") || this.src[this.offset] === \"_\")\n this.advanceBy(1);\n }\n if (this.src[this.offset] === \"e\" || this.src[this.offset] === \"E\") {\n this.advanceBy(1);\n if (isSign(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n while (isDigit(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n }\n // Imaginary suffix.\n if (this.src[this.offset] === \"i\") this.advanceBy(1);\n return this.finishNumber(startOffset, start);\n }\n\n private isHexFloatTail(c: string): boolean {\n return isHex(c) || c === \".\" || c === \"p\" || c === \"P\" || c === \"+\" || c === \"-\" || c === \"_\";\n }\n\n private finishNumber(startOffset: number, start: Pos): Token {\n if (this.offset === startOffset) {\n throw this.err(\"expected number\", start, { expected: \"digit\" });\n }\n return this.makeToken(\"Number\", this.src.slice(startOffset, this.offset), start);\n }\n\n private readVariable(start: Pos): Token {\n const startOffset = this.offset;\n this.advanceBy(1); // $\n while (isIdentPart(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n // Field accesses appended to a variable form a Variable token whose\n // value is the full `$name.x.y` chain. The parser splits this back\n // into VariableNode.idents.\n while (this.src[this.offset] === \".\" && isIdentStart(this.src[this.offset + 1] ?? \"\")) {\n this.advanceBy(1); // .\n while (isIdentPart(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n }\n return this.makeToken(\"Variable\", this.src.slice(startOffset, this.offset), start);\n }\n\n private readDotOrField(start: Pos): Token {\n const startOffset = this.offset;\n this.advanceBy(1); // .\n if (!isIdentStart(this.src[this.offset] ?? \"\")) {\n return this.makeToken(\"Dot\", \".\", start);\n }\n while (isIdentPart(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n while (this.src[this.offset] === \".\" && isIdentStart(this.src[this.offset + 1] ?? \"\")) {\n this.advanceBy(1); // .\n while (isIdentPart(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n }\n return this.makeToken(\"Field\", this.src.slice(startOffset, this.offset), start);\n }\n\n private readIdentifier(start: Pos): Token {\n const startOffset = this.offset;\n while (isIdentPart(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n const text = this.src.slice(startOffset, this.offset);\n const kw = KEYWORDS.get(text);\n if (kw) {\n return this.makeToken(kw, text, start);\n }\n return this.makeToken(\"Identifier\", text, start);\n }\n\n // ---------------------------------------------------------------------\n // Position and dispatch helpers.\n // ---------------------------------------------------------------------\n\n private skipActionSpaces(): void {\n while (this.offset < this.src.length) {\n const c = this.src[this.offset];\n if (c === \" \" || c === \"\\t\" || c === \"\\r\" || c === \"\\n\") {\n this.advanceBy(1);\n } else {\n return;\n }\n }\n }\n\n private advanceBy(n: number): void {\n for (let i = 0; i < n; i++) {\n const c = this.src[this.offset];\n this.offset += 1;\n if (c === \"\\n\") {\n this.line += 1;\n this.column = 1;\n } else {\n this.column += 1;\n }\n }\n }\n\n private advanceTo(target: number): void {\n while (this.offset < target) this.advanceBy(1);\n }\n\n private makeToken(\n type: TokenType,\n value: string,\n pos: Pos,\n extra: { trimLeft?: boolean; trimRight?: boolean } = {},\n ): Token {\n return Object.freeze({\n type,\n value,\n pos,\n ...(extra.trimLeft !== undefined ? { trimLeft: extra.trimLeft } : {}),\n ...(extra.trimRight !== undefined ? { trimRight: extra.trimRight } : {}),\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Character class predicates — small + inlinable.\n// ---------------------------------------------------------------------------\n\nfunction isSpace(c: string): boolean {\n return c === \" \" || c === \"\\t\" || c === \"\\r\" || c === \"\\n\";\n}\n\nfunction isSign(c: string): boolean {\n return c === \"+\" || c === \"-\";\n}\n\nfunction isDigit(c: string): boolean {\n return c >= \"0\" && c <= \"9\";\n}\n\nfunction isHex(c: string): boolean {\n return isDigit(c) || (c >= \"a\" && c <= \"f\") || (c >= \"A\" && c <= \"F\");\n}\n\nfunction isOctal(c: string): boolean {\n return c >= \"0\" && c <= \"7\";\n}\n\nfunction isBinary(c: string): boolean {\n return c === \"0\" || c === \"1\";\n}\n\nfunction isLetter(c: string): boolean {\n return (c >= \"a\" && c <= \"z\") || (c >= \"A\" && c <= \"Z\");\n}\n\nfunction isIdentStart(c: string): boolean {\n return isLetter(c) || c === \"_\";\n}\n\nfunction isIdentPart(c: string): boolean {\n return isIdentStart(c) || isDigit(c);\n}\n\n// ---------------------------------------------------------------------------\n// Convenience: tokenize an entire source.\n// ---------------------------------------------------------------------------\n\nexport function tokenize(src: string, delims?: Delims): readonly Token[] {\n const lex = delims ? new Lexer(src, delims) : new Lexer(src);\n const out: Token[] = [];\n while (true) {\n const t = lex.next();\n out.push(t);\n if (t.type === \"EOF\") return out;\n }\n}\n","/**\n * Recursive-descent parser for Go-template syntax.\n *\n * [LAW:dataflow-not-control-flow] The parser is a single class whose\n * methods read the token stream and emit AST nodes. There are no\n * conditional code paths that produce *different program structure* —\n * every grammar production is one method whose shape is fixed; the\n * variability is in the token values it observes.\n *\n * [LAW:single-enforcer] All token consumption goes through `next` /\n * `peek` / `expect`. No grammar production reaches into the lexer\n * directly — that would let two productions disagree about position\n * tracking or lookahead state.\n */\n\nimport type {\n ActionNode,\n BlockNode,\n BoolNode,\n BreakNode,\n ChainNode,\n CommandNode,\n CommentNode,\n ContinueNode,\n DotNode,\n FieldNode,\n IdentifierNode,\n IfNode,\n ListNode,\n NilNode,\n Node,\n NumberNode,\n PipeNode,\n RangeNode,\n StringNode,\n TemplateNode,\n TextNode,\n TrimMarkers,\n VariableNode,\n WithNode,\n} from \"./ast.js\";\nimport { ParseError } from \"./errors.js\";\nimport { type Delims, Lexer, type Token, type TokenType } from \"./lexer.js\";\nimport type { Pos } from \"./pos.js\";\n\n// ---------------------------------------------------------------------------\n// Public API.\n// ---------------------------------------------------------------------------\n\n/**\n * A named sub-template body together with the source it was parsed from.\n * A body invoked through an inherited `Defines` runs far from the template\n * that invoked it, so an error inside it must snippet against ITS source,\n * not the invoker's.\n */\nexport interface DefineEntry {\n readonly list: ListNode;\n readonly source: string;\n}\n\n/**\n * The named sub-templates a template can invoke: the ones its own source\n * declared plus, transitively, the ones it inherited at parse. Opaque: only\n * `has`, `names` and the `EMPTY` identity are public, so a consumer can neither build\n * one by hand (the parser is the single enforcer of the redefinition invariant\n * below) nor reach the AST inside — the entry lookup is `lookupDefine`, a\n * module export index.ts never re-exports.\n *\n * [LAW:one-source-of-truth] Inheritance is a parent LINK, never a copy. N\n * templates parsed against one shared preamble hold one preamble AST among\n * them — the alternative (prepending the preamble's source to each parse)\n * multiplies the preamble's AST by N, which is how a 2 KB helper block became\n * hundreds of megabytes in a long-lived process.\n *\n * Lookup is nearest-first, but the parser forbids a template from declaring a\n * name its inherited set already holds (the same `redefinition` error as two\n * declarations in one source), so nearest-first never actually shadows.\n */\n// [LAW:one-source-of-truth] The parser is the only place a Defines is built\n// and the evaluator the only reader of its entries — both captured from the\n// static block below, the same way Engine reaches Template's private\n// constructor — so the public surface carries neither a constructor nor an\n// AST-returning method.\nlet chainDefines: (own: ReadonlyMap<string, DefineEntry>, parent: Defines) => Defines;\nlet readDefine: (defines: Defines, name: string) => DefineEntry | undefined;\n\n/** Nearest-first entry lookup through the inheritance chain. Package-internal. */\nexport function lookupDefine(defines: Defines, name: string): DefineEntry | undefined {\n return readDefine(defines, name);\n}\n\nexport class Defines {\n static readonly EMPTY = new Defines(new Map(), undefined);\n readonly #own: ReadonlyMap<string, DefineEntry>;\n readonly #parent: Defines | undefined;\n\n private constructor(own: ReadonlyMap<string, DefineEntry>, parent: Defines | undefined) {\n this.#own = own;\n this.#parent = parent;\n }\n\n static {\n chainDefines = (own, parent) => new Defines(own, parent);\n readDefine = (d, name) => d.#own.get(name) ?? (d.#parent && readDefine(d.#parent, name));\n }\n\n has(name: string): boolean {\n return readDefine(this, name) !== undefined;\n }\n\n /**\n * Every name this set can render, own and inherited, sorted — what a\n * consumer reads after `evaluateDefine` reports a name as not defined.\n * The parser forbids redeclaring an inherited name, so the chain repeats\n * none; the Set keeps the listing duplicate-free without leaning on that.\n */\n names(): string[] {\n const names = new Set<string>();\n for (let d: Defines | undefined = this; d; d = d.#parent) {\n for (const name of d.#own.keys()) names.add(name);\n }\n return [...names].sort();\n }\n}\n\nexport interface ParseResult {\n /** The body of the unnamed/root template. */\n readonly root: ListNode;\n /**\n * Templates this parse can invoke: its own (`ownDefines`) chained onto the\n * inherited set it was parsed against.\n */\n readonly defines: Defines;\n /**\n * The sub-templates this source itself declared, by `{{define \"name\"}}` /\n * `{{block}}` — what static introspection describes; the inherited set is\n * described by the parse that declared it.\n */\n readonly ownDefines: ReadonlyMap<string, DefineEntry>;\n /** Original source text — preserved for error snippets and Template.source. */\n readonly source: string;\n}\n\nexport function parse(\n source: string,\n delims?: Delims,\n inherit: Defines = Defines.EMPTY,\n): ParseResult {\n const parser = new Parser(source, delims, inherit);\n return parser.parseTemplate();\n}\n\n// ---------------------------------------------------------------------------\n// Internals.\n// ---------------------------------------------------------------------------\n\n// Go's text/template/parse names the pipeline it is parsing in its\n// errors (\"too many declarations in command\").\ntype PipelineContext =\n | \"command\"\n | \"if\"\n | \"range\"\n | \"with\"\n | \"template clause\"\n | \"block clause\"\n | \"parenthesized pipeline\";\n\nconst PIPELINE_CONTEXT = { If: \"if\", Range: \"range\", With: \"with\" } as const satisfies Record<\n \"If\" | \"Range\" | \"With\",\n PipelineContext\n>;\n\nclass Parser {\n private readonly lex: Lexer;\n private readonly buf: Token[] = [];\n private readonly defines = new Map<string, DefineEntry>();\n private readonly inherit: Defines;\n private readonly source: string;\n // [LAW:types-are-the-program] Lexical-only counter: how many enclosing\n // `{{range}}` bodies surround the current parse position. `{{break}}`\n // and `{{continue}}` are legal iff this is > 0. Mirrors Go's\n // text/template/parse `Tree.rangeDepth`. Saved/restored around\n // sub-template bodies (`{{define}}` / `{{block}}`) because those\n // bodies are independent parse contexts in Go — a break lexically\n // inside a range but inside a nested define is still an error.\n private rangeDepth = 0;\n\n constructor(source: string, delims: Delims | undefined, inherit: Defines) {\n this.source = source;\n this.inherit = inherit;\n this.lex = delims ? new Lexer(source, delims) : new Lexer(source);\n }\n\n // -------------------------------------------------------------------\n // Token stream helpers.\n // -------------------------------------------------------------------\n\n private peek(n = 0): Token {\n while (this.buf.length <= n) {\n this.buf.push(this.lex.next());\n }\n // [LAW:no-defensive-null-guards] We just filled the buffer to n+1\n // entries, so buf[n] is non-undefined by construction. Cast rather\n // than guard — the alternative throw would be unreachable.\n return this.buf[n] as Token;\n }\n\n private next(): Token {\n if (this.buf.length > 0) return this.buf.shift() as Token;\n return this.lex.next();\n }\n\n private expect(type: TokenType, what: string): Token {\n const t = this.next();\n if (t.type !== type) {\n throw this.errAt(t, `expected ${what}`, { expected: what, found: tokenLabel(t) });\n }\n return t;\n }\n\n private errAt(\n t: Token,\n message: string,\n extra: { expected?: string; found?: string } = {},\n ): ParseError {\n return new ParseError(message, t.pos, {\n ...extra,\n source: this.source,\n });\n }\n\n // -------------------------------------------------------------------\n // Top-level.\n // -------------------------------------------------------------------\n\n parseTemplate(): ParseResult {\n const root = this.parseList();\n if (this.peek().type !== \"EOF\") {\n const left = this.peek();\n // We only stop in parseList for stray `{{else}}` or `{{end}}`.\n // Surface that as a curated message rather than the generic\n // \"unexpected `{{`\" we'd otherwise emit.\n const inside = this.peek(1);\n if (left.type === \"LeftDelim\" && (inside.type === \"Else\" || inside.type === \"End\")) {\n const keyword = inside.type === \"Else\" ? \"else\" : \"end\";\n throw this.errAt(\n left,\n `unexpected \\`{{${keyword}}}\\` outside of \\`if\\`, \\`range\\`, \\`with\\`, or \\`block\\``,\n { found: `{{${keyword}}}` },\n );\n }\n throw this.errAt(left, `unexpected ${tokenLabel(left)}`, { found: tokenLabel(left) });\n }\n return {\n root,\n defines: chainDefines(this.defines, this.inherit),\n ownDefines: this.defines,\n source: this.source,\n };\n }\n\n // -------------------------------------------------------------------\n // List body — runs until EOF or a branch terminator (else/end).\n // -------------------------------------------------------------------\n\n private parseList(): ListNode {\n const startPos = this.peek().pos;\n const nodes: Node[] = [];\n while (true) {\n const t = this.peek();\n if (t.type === \"EOF\") break;\n if (t.type === \"Text\") {\n this.next();\n nodes.push({ type: \"Text\", pos: t.pos, text: t.value } satisfies TextNode);\n continue;\n }\n if (t.type === \"Comment\") {\n this.next();\n const trim = trimFromToken(t);\n nodes.push({ type: \"Comment\", pos: t.pos, text: t.value, trim } satisfies CommentNode);\n continue;\n }\n if (t.type === \"LeftDelim\") {\n // Branch terminators stop the list without consuming the delim.\n const inside = this.peek(1).type;\n if (inside === \"Else\" || inside === \"End\") return finishList(startPos, nodes);\n const action = this.parseAction();\n if (action !== null) nodes.push(action);\n continue;\n }\n throw this.errAt(t, `unexpected ${tokenLabel(t)} at top level`, {\n found: tokenLabel(t),\n });\n }\n return finishList(startPos, nodes);\n }\n\n // -------------------------------------------------------------------\n // Action body — dispatched on the keyword right after `{{`.\n //\n // Returns null when the action consumed is a `{{define}}` block, since\n // defines are stashed in the parser's defines map rather than added to\n // the surrounding list.\n // -------------------------------------------------------------------\n\n private parseAction(): Node | null {\n const left = this.expect(\"LeftDelim\", \"`{{`\");\n const trimLeft = left.trimLeft === true;\n const head = this.peek();\n\n switch (head.type) {\n case \"If\":\n this.next();\n return this.parseBranch(\"If\", left.pos, trimLeft);\n case \"Range\":\n this.next();\n return this.parseBranch(\"Range\", left.pos, trimLeft);\n case \"With\":\n this.next();\n return this.parseBranch(\"With\", left.pos, trimLeft);\n case \"Break\":\n this.next();\n return this.parseBreakOrContinue(\"Break\", left.pos, trimLeft);\n case \"Continue\":\n this.next();\n return this.parseBreakOrContinue(\"Continue\", left.pos, trimLeft);\n case \"Template\":\n this.next();\n return this.parseTemplateInvocation(left.pos, trimLeft);\n case \"Block\":\n this.next();\n return this.parseBlock(left.pos, trimLeft);\n case \"Define\":\n this.next();\n this.parseDefine(left.pos, trimLeft);\n return null;\n case \"RightDelim\":\n // Empty action `{{}}` is illegal in Go's parser.\n throw this.errAt(head, \"empty action\", { expected: \"pipeline\" });\n default: {\n // A plain pipeline action: `{{ pipeline }}`.\n const pipe = this.parsePipeline(\"command\");\n const right = this.expect(\"RightDelim\", \"`}}`\");\n return {\n type: \"Action\",\n pos: left.pos,\n pipe,\n trim: { trimLeft, trimRight: right.trimRight === true },\n } satisfies ActionNode;\n }\n }\n }\n\n // -------------------------------------------------------------------\n // Branches: if / range / with.\n //\n // Shape: `{{if PIPE}} list ({{else if PIPE}} list)* ({{else}} list)? {{end}}`.\n // The `else if` chain is desugared into nested IfNodes inside the\n // outer if's elseList, matching Go's parse package.\n // -------------------------------------------------------------------\n\n private parseBranch(\n kind: \"If\" | \"Range\" | \"With\",\n startPos: Pos,\n trimLeft: boolean,\n ): IfNode | RangeNode | WithNode {\n const pipe = this.parsePipeline(PIPELINE_CONTEXT[kind]);\n this.expect(\"RightDelim\", \"`}}`\");\n // [LAW:types-are-the-program] `rangeDepth` counts the enclosing\n // ranges that can absorb a `{{break}}` / `{{continue}}` at the\n // current parse position. A range's body contributes 1; a range's\n // else clause contributes 0 — the else only runs on empty input\n // and is structurally outside the iteration, so it cannot be the\n // *target* of a break aimed at its own range. Another enclosing\n // range is required for the signal to be catchable.\n //\n // Decrementing *before* parsing the else (not after parseElsePart)\n // matches Go's text/template parser exactly — see\n // text/template/parse/parse.go:540-547 — so a top-level\n // `{{range}}{{else}}{{break}}{{end}}` errors at parse time with\n // the same \"{{break}} outside {{range}}\" message Go emits.\n if (kind === \"Range\") this.rangeDepth += 1;\n const list = this.parseList();\n if (kind === \"Range\") this.rangeDepth -= 1;\n const elsePart = this.parseElsePart();\n const endRight = elsePart.endConsumed ? elsePart.endRight : this.consumeEnd();\n const trim: TrimMarkers = { trimLeft, trimRight: endRight };\n\n const base = elsePart.list\n ? { pipe, list, elseList: elsePart.list, trim }\n : { pipe, list, trim };\n switch (kind) {\n case \"If\":\n return { type: \"If\", pos: startPos, ...base } satisfies IfNode;\n case \"Range\":\n return { type: \"Range\", pos: startPos, ...base } satisfies RangeNode;\n case \"With\":\n return { type: \"With\", pos: startPos, ...base } satisfies WithNode;\n }\n }\n\n // -------------------------------------------------------------------\n // {{break}} / {{continue}} — range-body control flow.\n //\n // [LAW:types-are-the-program] Both are leaves with only a position +\n // trim markers. The strongest theorem about them is that they carry\n // no value, no body, no pipeline — encode that in the type so the\n // body of every visitor is forced to treat them as leaves.\n //\n // [LAW:single-enforcer] The \"must be inside a `{{range}}`\" rule\n // lives here at the gate. Once the AST is built, the evaluator\n // trusts the lexical guarantee — no runtime guard re-checks.\n // -------------------------------------------------------------------\n private parseBreakOrContinue(\n kind: \"Break\" | \"Continue\",\n startPos: Pos,\n trimLeft: boolean,\n ): BreakNode | ContinueNode {\n if (this.rangeDepth === 0) {\n const keyword = kind === \"Break\" ? \"break\" : \"continue\";\n throw new ParseError(`{{${keyword}}} outside of {{range}}`, startPos, {\n source: this.source,\n });\n }\n const right = this.expect(\"RightDelim\", \"`}}`\");\n const trim: TrimMarkers = { trimLeft, trimRight: right.trimRight === true };\n return kind === \"Break\"\n ? ({ type: \"Break\", pos: startPos, trim } satisfies BreakNode)\n : ({ type: \"Continue\", pos: startPos, trim } satisfies ContinueNode);\n }\n\n /**\n * Parse the `{{else}}` / `{{else if PIPE}}` segment, if any.\n *\n * `else if` is desugared into a nested IfNode wrapped in the elseList.\n * The recursive parseBranch consumes the chain's single closing\n * `{{end}}`, so the outer caller must NOT consume another — hence the\n * `endConsumed` flag we propagate back.\n */\n private parseElsePart(): {\n list: ListNode | undefined;\n endRight: boolean;\n endConsumed: boolean;\n } {\n if (this.peek().type !== \"LeftDelim\" || this.peek(1).type !== \"Else\") {\n return { list: undefined, endRight: false, endConsumed: false };\n }\n const left = this.next(); // {{\n this.next(); // else\n if (this.peek().type === \"If\") {\n this.next(); // if\n const innerIf = this.parseBranch(\"If\", left.pos, left.trimLeft === true);\n return {\n list: { type: \"List\", pos: left.pos, nodes: [innerIf] },\n endRight: innerIf.trim.trimRight,\n endConsumed: true,\n };\n }\n this.expect(\"RightDelim\", \"`}}`\");\n const list = this.parseList();\n return { list, endRight: false, endConsumed: false };\n }\n\n /** Consume the closing `{{end}}` and return whether it was a `-}}`. */\n private consumeEnd(): boolean {\n this.expect(\"LeftDelim\", \"`{{end}}`\");\n this.expect(\"End\", \"`end`\");\n const right = this.expect(\"RightDelim\", \"`}}`\");\n return right.trimRight === true;\n }\n\n // -------------------------------------------------------------------\n // Sub-templates: template / block / define.\n // -------------------------------------------------------------------\n\n private parseTemplateInvocation(startPos: Pos, trimLeft: boolean): TemplateNode {\n const name = this.parseQuotedName();\n const pipe =\n this.peek().type === \"RightDelim\" ? undefined : this.parsePipeline(\"template clause\");\n const right = this.expect(\"RightDelim\", \"`}}`\");\n const trim: TrimMarkers = { trimLeft, trimRight: right.trimRight === true };\n return pipe\n ? ({ type: \"Template\", pos: startPos, name, pipe, trim } satisfies TemplateNode)\n : ({ type: \"Template\", pos: startPos, name, trim } satisfies TemplateNode);\n }\n\n private parseBlock(startPos: Pos, trimLeft: boolean): BlockNode {\n const name = this.parseQuotedName();\n const pipe = this.parsePipeline(\"block clause\");\n this.expect(\"RightDelim\", \"`}}`\");\n // [LAW:types-are-the-program] A `{{block}}` body is invoked via the\n // sub-template machinery: a separate parse context in Go's\n // text/template. Save and reset rangeDepth so a `{{break}}` inside\n // a block body — even when the block is lexically nested in an\n // outer range — is correctly rejected at parse time.\n const savedDepth = this.rangeDepth;\n this.rangeDepth = 0;\n const list = this.parseList();\n this.rangeDepth = savedDepth;\n const endRight = this.consumeEnd();\n const trim: TrimMarkers = { trimLeft, trimRight: endRight };\n // Block both registers a default body under `name` AND invokes it.\n // A preceding `{{define}}` for the same name — in this source or in the\n // inherited set — takes precedence: the block body is the fallback, not\n // the override.\n if (!this.defines.has(name) && !this.inherit.has(name)) {\n this.defines.set(name, { list, source: this.source });\n }\n return { type: \"Block\", pos: startPos, name, pipe, list, trim } satisfies BlockNode;\n }\n\n private parseDefine(_startPos: Pos, _trimLeft: boolean): void {\n const name = this.parseQuotedName();\n this.expect(\"RightDelim\", \"`}}`\");\n // [LAW:types-are-the-program] Defines are independent parse\n // contexts in Go's text/template — `{{break}}` inside a `{{define}}`\n // body is illegal even when the define is lexically nested inside\n // a range. Save and reset rangeDepth so the depth tracked here\n // reflects only ranges that lexically enclose this body.\n const savedDepth = this.rangeDepth;\n this.rangeDepth = 0;\n const list = this.parseList();\n this.rangeDepth = savedDepth;\n this.consumeEnd();\n if (this.defines.has(name) || this.inherit.has(name)) {\n throw new ParseError(`redefinition of template ${JSON.stringify(name)}`, list.pos, {\n source: this.source,\n });\n }\n this.defines.set(name, { list, source: this.source });\n }\n\n private parseQuotedName(): string {\n const t = this.next();\n if (t.type !== \"String\") {\n throw this.errAt(t, \"expected template name (quoted string)\", {\n expected: \"string\",\n found: tokenLabel(t),\n });\n }\n return decodeStringLiteral(t.value, t.pos, this.source);\n }\n\n // -------------------------------------------------------------------\n // Pipelines.\n //\n // pipeline := decls? command (`|` command)*\n // decls := variable (`,` variable)? (`:=` | `=`)\n //\n // The second variable is legal only in a `range` pipeline.\n // -------------------------------------------------------------------\n\n private parsePipeline(context: PipelineContext): PipeNode {\n const startPos = this.peek().pos;\n const decls = this.tryParseDecls(context);\n const end = this.peek();\n if (end.type === \"RightDelim\" || end.type === \"RightParen\") {\n throw this.errAt(end, `missing value for ${context}`, { expected: \"command\" });\n }\n const cmds: CommandNode[] = [this.parseCommand()];\n while (this.peek().type === \"Pipe\") {\n this.next();\n const next = this.peek();\n if (!canStartPrimary(next.type)) {\n throw this.errAt(next, \"missing command after `|`\", {\n expected: \"command\",\n found: tokenLabel(next),\n });\n }\n cmds.push(this.parseCommand());\n }\n return {\n type: \"Pipe\",\n pos: startPos,\n decls: decls?.vars ?? [],\n isAssign: decls?.isAssign ?? false,\n cmds,\n };\n }\n\n private tryParseDecls(\n context: PipelineContext,\n ): { vars: VariableNode[]; isAssign: boolean } | undefined {\n if (!isDeclTarget(this.peek())) return undefined;\n // We have to be conservative here — `$x` could be the start of a\n // declaration *or* a plain pipeline whose first command is just a\n // variable reference. Distinguish by scanning ahead for `:=` / `=`\n // (possibly through `, $y` chains).\n let n = 1;\n while (this.peek(n).type === \"Comma\") {\n if (!isDeclTarget(this.peek(n + 1))) return undefined;\n n += 2;\n }\n const opType = this.peek(n).type;\n if (opType !== \"Declare\" && opType !== \"Assign\") return undefined;\n\n const vars: VariableNode[] = [varFromToken(this.next() as Token)];\n while (this.peek().type === \"Comma\") {\n const comma = this.next();\n if (vars.length === (context === \"range\" ? 2 : 1)) {\n throw this.errAt(comma, `too many declarations in ${context}`);\n }\n vars.push(varFromToken(this.expect(\"Variable\", \"$variable\")));\n }\n const op = this.next();\n return { vars, isAssign: op.type === \"Assign\" };\n }\n\n // -------------------------------------------------------------------\n // Commands and primaries.\n //\n // command := primary+\n // primary := dot | field | variable | identifier | string | number\n // | char | bool | nil | `(` pipeline `)` (`.field`)*\n // -------------------------------------------------------------------\n\n private parseCommand(): CommandNode {\n const startPos = this.peek().pos;\n const args: Node[] = [this.parsePrimary()];\n while (canStartPrimary(this.peek().type)) {\n args.push(this.parsePrimary());\n }\n return { type: \"Command\", pos: startPos, args };\n }\n\n private parsePrimary(): Node {\n const t = this.next();\n switch (t.type) {\n case \"Dot\":\n return { type: \"Dot\", pos: t.pos } satisfies DotNode;\n case \"Field\":\n return {\n type: \"Field\",\n pos: t.pos,\n idents: t.value.slice(1).split(\".\"),\n } satisfies FieldNode;\n case \"Variable\":\n return varFromToken(t);\n case \"Identifier\":\n return { type: \"Identifier\", pos: t.pos, ident: t.value } satisfies IdentifierNode;\n case \"String\":\n return {\n type: \"String\",\n pos: t.pos,\n raw: t.value,\n value: decodeStringLiteral(t.value, t.pos, this.source),\n } satisfies StringNode;\n case \"Number\":\n return numberFromToken(t);\n case \"Char\":\n // Treat runes as numbers — Go's parser does the same; the rune\n // value is the integer code point. We synthesize a NumberNode\n // with the original char-literal text preserved.\n return runeNumberFromToken(t, this.source);\n case \"Bool\":\n return { type: \"Bool\", pos: t.pos, value: t.value === \"true\" } satisfies BoolNode;\n case \"Nil\":\n return { type: \"Nil\", pos: t.pos } satisfies NilNode;\n case \"LeftParen\":\n return this.parseChainOrPipe(t.pos);\n default:\n throw this.errAt(t, `expected command argument, found ${tokenLabel(t)}`, {\n expected: \"command argument\",\n found: tokenLabel(t),\n });\n }\n }\n\n private parseChainOrPipe(startPos: Pos): Node {\n const inner = this.parsePipeline(\"parenthesized pipeline\");\n const rparen = this.expect(\"RightParen\", \"`)`\");\n // Field chain on `(pipe).field` requires the `.` to be immediately\n // adjacent to `)` — otherwise it's a separate command argument.\n // The lexer's Field tokens carry source positions; if there was\n // whitespace between `)` and the next Field, their positions\n // won't be consecutive.\n const fields: string[] = [];\n const expectedNextOffset = rparen.pos.offset + 1;\n const t = this.peek();\n if (t.type === \"Field\" && t.pos.offset === expectedNextOffset) {\n this.next();\n fields.push(...t.value.slice(1).split(\".\"));\n }\n if (fields.length === 0) return inner;\n return { type: \"Chain\", pos: startPos, node: inner, fields } satisfies ChainNode;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers — pure data-in / data-out, no parser state.\n// ---------------------------------------------------------------------------\n\nfunction finishList(pos: Pos, nodes: Node[]): ListNode {\n return { type: \"List\", pos, nodes };\n}\n\nfunction trimFromToken(t: Token): TrimMarkers {\n return {\n trimLeft: t.trimLeft === true,\n trimRight: t.trimRight === true,\n };\n}\n\nfunction tokenLabel(t: Token): string {\n if (t.type === \"EOF\") return \"end of input\";\n return t.value || t.type;\n}\n\nfunction canStartPrimary(t: TokenType): boolean {\n switch (t) {\n case \"Dot\":\n case \"Field\":\n case \"Variable\":\n case \"Identifier\":\n case \"String\":\n case \"Number\":\n case \"Char\":\n case \"Bool\":\n case \"Nil\":\n case \"LeftParen\":\n return true;\n default:\n return false;\n }\n}\n\n// A declaration names a bare variable: Go lexes `$x.y` as `$x` and a\n// field, so `$x.y := v` is no declaration and fails as a pipeline.\nfunction isDeclTarget(t: Token): boolean {\n return t.type === \"Variable\" && !t.value.includes(\".\");\n}\n\nfunction varFromToken(t: Token): VariableNode {\n return {\n type: \"Variable\",\n pos: t.pos,\n idents: splitVariableIdents(t.value),\n };\n}\n\nfunction splitVariableIdents(value: string): string[] {\n // `$name.x.y` → [\"$name\", \"x\", \"y\"]; `$` → [\"$\"]\n const dotIdx = value.indexOf(\".\");\n if (dotIdx === -1) return [value];\n return [value.slice(0, dotIdx), ...value.slice(dotIdx + 1).split(\".\")];\n}\n\nfunction numberFromToken(t: Token): NumberNode {\n const text = t.value;\n // Strip underscore separators per Go syntax.\n const cleaned = text.replace(/_/g, \"\");\n const lower = cleaned.toLowerCase();\n const isComplex = lower.endsWith(\"i\");\n const body = isComplex ? cleaned.slice(0, -1) : cleaned;\n const isFloat =\n !isComplex &&\n (body.includes(\".\") ||\n (!body.startsWith(\"0x\") && !body.startsWith(\"0X\") && /[eE]/.test(body)) ||\n ((body.startsWith(\"0x\") || body.startsWith(\"0X\")) && /[pP]/.test(body)));\n const isInt = !isComplex && !isFloat;\n\n const base: NumberNode = {\n type: \"Number\",\n pos: t.pos,\n text,\n isInt,\n isUint: false,\n isFloat,\n isComplex,\n };\n\n if (isInt) {\n const intValue = parseIntegerLiteral(body);\n return { ...base, intValue };\n }\n if (isFloat) {\n const floatValue = parseFloatLiteral(body);\n return { ...base, floatValue };\n }\n // complex\n const im = parseFloatLiteral(body);\n return { ...base, complexValue: [0, im] };\n}\n\nfunction runeNumberFromToken(t: Token, source: string): NumberNode {\n const inner = decodeRuneLiteral(t.value, t.pos, source);\n return {\n type: \"Number\",\n pos: t.pos,\n text: t.value,\n isInt: true,\n isUint: false,\n isFloat: false,\n isComplex: false,\n intValue: BigInt(inner),\n };\n}\n\nfunction parseIntegerLiteral(text: string): bigint {\n // Handle leading sign explicitly because BigInt() accepts \"+123\" but\n // not all base-prefixed signed forms uniformly.\n let sign = 1n;\n let body = text;\n if (body.startsWith(\"+\")) body = body.slice(1);\n else if (body.startsWith(\"-\")) {\n sign = -1n;\n body = body.slice(1);\n }\n return sign * BigInt(body);\n}\n\nfunction parseFloatLiteral(text: string): number {\n return Number(text);\n}\n\nfunction decodeStringLiteral(raw: string, pos: Pos, source: string): string {\n if (raw.startsWith(\"`\")) {\n return raw.slice(1, -1);\n }\n // Interpreted string: process escapes.\n let out = \"\";\n for (let i = 1; i < raw.length - 1; i++) {\n const c = raw[i];\n if (c !== \"\\\\\") {\n out += c;\n continue;\n }\n const next = raw[++i];\n switch (next) {\n case \"n\":\n out += \"\\n\";\n break;\n case \"t\":\n out += \"\\t\";\n break;\n case \"r\":\n out += \"\\r\";\n break;\n case \"\\\\\":\n out += \"\\\\\";\n break;\n case '\"':\n out += '\"';\n break;\n case \"'\":\n out += \"'\";\n break;\n case \"a\":\n out += \"\\x07\";\n break;\n case \"b\":\n out += \"\\b\";\n break;\n case \"f\":\n out += \"\\f\";\n break;\n case \"v\":\n out += \"\\v\";\n break;\n case \"0\":\n case \"1\":\n case \"2\":\n case \"3\":\n case \"4\":\n case \"5\":\n case \"6\":\n case \"7\": {\n // Octal — 3 digits total including the `next`.\n const digits = next + (raw[i + 1] ?? \"\") + (raw[i + 2] ?? \"\");\n i += 2;\n out += String.fromCodePoint(Number.parseInt(digits, 8));\n break;\n }\n case \"x\": {\n const digits = (raw[i + 1] ?? \"\") + (raw[i + 2] ?? \"\");\n i += 2;\n out += String.fromCodePoint(Number.parseInt(digits, 16));\n break;\n }\n case \"u\": {\n const digits = raw.slice(i + 1, i + 5);\n i += 4;\n out += String.fromCodePoint(Number.parseInt(digits, 16));\n break;\n }\n case \"U\": {\n const digits = raw.slice(i + 1, i + 9);\n i += 8;\n out += String.fromCodePoint(Number.parseInt(digits, 16));\n break;\n }\n default:\n throw new ParseError(`bad escape sequence \\\\${next}`, pos, {\n expected: \"valid escape sequence\",\n found: `\\\\${next}`,\n source,\n });\n }\n }\n return out;\n}\n\nfunction decodeRuneLiteral(raw: string, pos: Pos, source: string): number {\n // raw is `'x'` — slice the inner content and reuse the string decoder\n // by wrapping in double quotes (after escaping a literal `\"`).\n const inner = raw.slice(1, -1);\n const escaped = inner.replace(/\"/g, '\\\\\"');\n const decoded = decodeStringLiteral(`\"${escaped}\"`, pos, source);\n if (decoded.length === 0) {\n throw new ParseError(\"empty rune literal\", pos, { source });\n }\n return decoded.codePointAt(0) ?? 0;\n}\n","/**\n * AST traversal helpers.\n *\n * [LAW:dataflow-not-control-flow] `children()` is one exhaustive switch on\n * the node's `type` discriminator that always returns a (possibly empty)\n * array of children. Walkers do not skip operations — they always call\n * `visit(n)` on every reachable node, then recurse into whatever children\n * the data-driven `children()` exposes.\n *\n * [LAW:single-enforcer] All AST traversal goes through `walk` /\n * `children`. Any caller who reinvents traversal will diverge — fix the\n * helper, not the callsite.\n */\n\nimport { assertNever, type Node, type NodeType } from \"./ast.js\";\n\n/**\n * Visitor callback. Receives every node in preorder. Return `false` to\n * stop descending into the current node's children; any other return\n * value (including `undefined`) means \"continue\".\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: void return is idiomatic for callback APIs where the caller may simply not return anything; switching to `undefined` would force every caller to write `return undefined` for no semantic gain.\nexport type Visitor = (node: Node) => boolean | void;\n\n/**\n * Walk an AST in preorder. The visitor sees a node before its children.\n */\nexport function walk(node: Node, visit: Visitor): void {\n const descend = visit(node);\n if (descend === false) return;\n for (const child of children(node)) {\n walk(child, visit);\n }\n}\n\n/**\n * The direct children of a node, in source order. Empty for leaves.\n *\n * Returning a fresh array each call keeps the contract simple — callers\n * may iterate or splat without aliasing surprises. The cost is trivial\n * for AST traversal.\n */\nexport function children(node: Node): readonly Node[] {\n switch (node.type) {\n case \"Text\":\n case \"Comment\":\n case \"Dot\":\n case \"Nil\":\n case \"Bool\":\n case \"Number\":\n case \"String\":\n case \"Identifier\":\n case \"Field\":\n case \"Variable\":\n case \"Break\":\n case \"Continue\":\n return [];\n case \"List\":\n return node.nodes;\n case \"Chain\":\n return [node.node];\n case \"Command\":\n return node.args;\n case \"Pipe\":\n return [...node.decls, ...node.cmds];\n case \"Action\":\n return [node.pipe];\n case \"If\":\n case \"Range\":\n case \"With\":\n return node.elseList ? [node.pipe, node.list, node.elseList] : [node.pipe, node.list];\n case \"Template\":\n return node.pipe ? [node.pipe] : [];\n case \"Block\":\n return [node.pipe, node.list];\n default:\n return assertNever(node);\n }\n}\n\n/**\n * Collect every node in preorder. Convenience for tests + tooling.\n */\nexport function flatten(node: Node): readonly Node[] {\n const out: Node[] = [];\n walk(node, (n) => {\n out.push(n);\n });\n return out;\n}\n\n/**\n * Count nodes of each kind. Useful for tests and diagnostics.\n */\nexport function tally(node: Node): Readonly<Record<NodeType, number>> {\n const counts = emptyTally();\n walk(node, (n) => {\n counts[n.type] += 1;\n });\n return counts;\n}\n\nfunction emptyTally(): Record<NodeType, number> {\n return {\n Text: 0,\n Comment: 0,\n Dot: 0,\n Nil: 0,\n Bool: 0,\n Number: 0,\n String: 0,\n Identifier: 0,\n Field: 0,\n Variable: 0,\n List: 0,\n Chain: 0,\n Command: 0,\n Pipe: 0,\n Action: 0,\n If: 0,\n Range: 0,\n With: 0,\n Break: 0,\n Continue: 0,\n Template: 0,\n Block: 0,\n };\n}\n","/**\n * Field / index access for evaluator primaries.\n *\n * Mirrors Go's `text/template` semantics where applicable:\n * - Plain JS objects: own + prototype-chain properties.\n * - Maps: `.get(key)`.\n * - Arrays: numeric `[i]` (string-indexed access not supported — that's\n * Go's behavior for slices/arrays).\n * - Methods/functions are returned as-is for the caller to invoke when\n * the AST shape demands a function call.\n *\n * Missing-key handling: a genuinely absent field returns the `MISSING`\n * sentinel, which the caller (`Engine.resolveFieldChain`) interprets per\n * the configured `missingKey` policy — `\"default\"`/`\"zero\"` produce\n * `undefined` (Go-default `<no value>` when emitted), `\"error\"` throws\n * `MissingFieldError`. The receiver-is-nullish case at the top of\n * `getField` is the trust-boundary exception documented inline below.\n *\n * [LAW:single-enforcer] This module returns the `MISSING` discriminator\n * unconditionally; the policy decision lives at exactly one site.\n */\n\n/** Sentinel returned by `getField` when a field is genuinely absent. */\nexport const MISSING: unique symbol = Symbol(\"go-template-js.MISSING\");\nexport type Missing = typeof MISSING;\n\nexport function getField(value: unknown, name: string): unknown | Missing {\n // [LAW:no-defensive-null-guards] exception: trust boundary — the\n // receiver is consumer-supplied scope data, so a nullish value is\n // valid input that must collapse to the same MISSING signal an absent\n // field produces. The `else` branch is the real work; this is not a\n // skip-the-operation guard.\n if (value === null || value === undefined) return MISSING;\n if (value instanceof Map) {\n return value.has(name) ? value.get(name) : MISSING;\n }\n if (Array.isArray(value)) {\n // Per Go, accessing a named field on a slice is a missing-field\n // error — no `length` magic. The numeric `index` builtin handles\n // positional access in a separate ticket.\n return MISSING;\n }\n if (typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n if (name in obj) return obj[name];\n return MISSING;\n }\n return MISSING;\n}\n\n/**\n * Walk a chain of field names left-to-right. Returns `MISSING` as soon\n * as any link is missing. The caller decides how to surface the error\n * (typically via EvalError pointing at the AST node's position).\n */\nexport function walkFieldChain(value: unknown, idents: readonly string[]): unknown | Missing {\n let cur: unknown = value;\n for (const id of idents) {\n if (cur === MISSING) return MISSING;\n cur = getField(cur, id);\n }\n return cur;\n}\n","/**\n * `deepEqual a b` — recursive structural equality.\n *\n * Mirrors Go sprig's intent. Implementation handles primitives,\n * arrays, plain objects, Maps, and Sets. NaN is treated as equal to\n * itself (matches `Object.is`).\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (a === null || b === null || a === undefined || b === undefined) return false;\n if (typeof a !== typeof b) return false;\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((v, i) => deepEqual(v, b[i]));\n }\n if (a instanceof Map && b instanceof Map) {\n if (a.size !== b.size) return false;\n for (const [k, v] of a) if (!b.has(k) || !deepEqual(v, b.get(k))) return false;\n return true;\n }\n if (a instanceof Set && b instanceof Set) {\n if (a.size !== b.size) return false;\n for (const v of a) if (!b.has(v)) return false;\n return true;\n }\n if (typeof a === \"object\" && typeof b === \"object\") {\n const ak = Object.keys(a as object);\n const bk = Object.keys(b as object);\n if (ak.length !== bk.length) return false;\n return ak.every((k) =>\n deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n );\n }\n return false;\n}\n","/**\n * Internal lazy-func registry.\n *\n * `and` / `or` short-circuit by receiving thunks instead of values. The\n * dispatcher needs to know which funcs want thunks, but the public\n * `TemplateFunc` interface must not advertise (or admit) a way for\n * consumer code to opt in — only the builtins module does that.\n *\n * [LAW:single-enforcer] One side-channel — a module-private WeakSet —\n * holds the set of lazy funcs. `markLazy` is the only writer (called by\n * `defaultBuiltins`); `isLazy` is the only reader (called by the\n * dispatcher). The brand never appears on the func object, so it\n * cannot leak into the published `.d.ts` and it is not reachable via\n * any public symbol or string key.\n *\n * Lives in its own leaf module so both `evaluator.ts` and `builtins.ts`\n * can import it without forming a runtime import cycle.\n */\n\nimport type { TemplateFunc } from \"./evaluator.js\";\n\nconst LAZY_FUNCS = new WeakSet<TemplateFunc>();\n\n/** Mark a func as wanting thunks. Internal — only `defaultBuiltins` calls this. */\nexport function markLazy<F extends TemplateFunc>(fn: F): F {\n LAZY_FUNCS.add(fn);\n return fn;\n}\n\n/** True iff the func was registered via `markLazy`. */\nexport function isLazy(fn: TemplateFunc): boolean {\n return LAZY_FUNCS.has(fn);\n}\n","/**\n * Go-template truthiness, used by `if`, `with`, and `range`-empty.\n *\n * Per https://pkg.go.dev/text/template#hdr-Actions, \"the empty values\n * are false, 0, any nil pointer or interface value, and any array,\n * slice, map, or string of length zero.\" Strings of length zero are\n * also empty.\n */\n\nexport function isTruthy(value: unknown): boolean {\n if (value === null || value === undefined) return false;\n if (value === false) return false;\n if (typeof value === \"number\") return value !== 0 && !Number.isNaN(value);\n if (typeof value === \"bigint\") return value !== 0n;\n if (typeof value === \"string\") return value.length > 0;\n if (Array.isArray(value)) return value.length > 0;\n if (value instanceof Map) return value.size > 0;\n if (value instanceof Set) return value.size > 0;\n // Plain object — empty iff it has no own enumerable string keys.\n if (typeof value === \"object\") {\n return Object.keys(value).length > 0;\n }\n return Boolean(value);\n}\n","/**\n * Go template's built-in functions.\n *\n * https://pkg.go.dev/text/template#hdr-Functions\n *\n * Categories:\n * - Eager (most): args evaluated normally, value-in / value-out.\n * - Lazy (and/or): take thunks instead of values so evaluation can\n * short-circuit. Registered via `markLazy` — see lazy.ts.\n *\n * [LAW:single-enforcer] Built-ins live in *one* exported FuncMap.\n * Consumers merge with their own funcs; user-supplied entries with\n * matching names override the built-in (intentional — gives\n * consumers an escape hatch).\n */\n\nimport { isStackOverflow, TypeMismatchError } from \"../errors.js\";\nimport { deepEqual } from \"../sprig/types/deepEqual.js\";\nimport type { FuncMap } from \"./evaluator.js\";\nimport { markLazy } from \"./lazy.js\";\nimport { isTruthy } from \"./truthy.js\";\n\n// ---------------------------------------------------------------------------\n// Eager built-ins.\n//\n// [LAW:single-enforcer] The print/printf family flattens through\n// `formatV` over the engine's `toString`/`isT` — the same function the\n// gate's \"stringifiable\" probe runs (`printRefusal` in src/evaluator/evaluator.ts).\n// Two callsites (probe at the gate, flatten in the body) — one source of truth.\n// ---------------------------------------------------------------------------\n\nfunction eagerBuiltins(toString: (v: unknown) => string, isT: IsT): FuncMap {\n return {\n // Comparison — Go template promotes numeric types and compares\n // strings/bools by value. We match that by leaning on JS `<`/`===`\n // which already does the right thing for primitives.\n // [LAW:single-enforcer] `argTypes: [\"comparable\"]` puts the kind\n // check + cross-slot same-kind rule (with number↔bigint bridged and\n // nil-wildcarded) at the gate. The body trusts kinds and routes\n // structural compares through `deepEqual`. Variadic per Go: `eq a\n // b c` is true if any of b, c equals a.\n eq: {\n fn: (a: unknown, ...rest: unknown[]) => rest.some((r) => goEqPair(a, r)),\n // Go: `eq(arg1 reflect.Value, arg2 ...reflect.Value)` — two\n // parameters, so Go's gate requires one. Go's own body separately\n // rejects a lone argument with `errNoComparison`; this body does\n // neither yet and returns false (template-conformance-3ds).\n argTypes: [\"comparable\", \"comparable\"],\n arity: { kind: \"variadic\" },\n },\n ne: {\n fn: (a: unknown, b: unknown) => !goEqPair(a, b),\n argTypes: [\"comparable\", \"comparable\"],\n arity: { kind: \"exact\" },\n },\n // [LAW:single-enforcer] `argTypes: [\"ordered\", \"ordered\"]` routes\n // both per-slot kind validation and the cross-slot same-kind rule\n // through `enforceArgTypes`. By the time `compare` runs, the args\n // are guaranteed orderable and same-kinded, so it can be a thin\n // numeric/lexicographic body — no defensive cross-type check.\n lt: {\n fn: (a: unknown, b: unknown) => compare(a, b) < 0,\n argTypes: [\"ordered\", \"ordered\"],\n arity: { kind: \"exact\" },\n },\n le: {\n fn: (a: unknown, b: unknown) => compare(a, b) <= 0,\n argTypes: [\"ordered\", \"ordered\"],\n arity: { kind: \"exact\" },\n },\n gt: {\n fn: (a: unknown, b: unknown) => compare(a, b) > 0,\n argTypes: [\"ordered\", \"ordered\"],\n arity: { kind: \"exact\" },\n },\n ge: {\n fn: (a: unknown, b: unknown) => compare(a, b) >= 0,\n argTypes: [\"ordered\", \"ordered\"],\n arity: { kind: \"exact\" },\n },\n\n // [LAW:single-enforcer] `len` declares \"sized\" so the gate rejects\n // numbers/booleans/nil once with TypeMismatchError. The body trusts\n // the kind and only fans out the per-kind size readout.\n len: { fn: (v: unknown) => goLen(v), argTypes: [\"sized\"], arity: { kind: \"exact\" } },\n\n // [LAW:single-enforcer] `index x i j` walks i, then j. The first\n // slot is \"collection\" (string | array | Map | dict); every key\n // slot is \"index-key\" (string | number | bigint). The body trusts\n // the gate — nil/Set/class-instance receivers are rejected before\n // it runs. Closes audit finding B5: typed-T keys no longer\n // silently `String(key)`-flatten on object collections.\n index: {\n fn: (collection: unknown, ...keys: unknown[]) => {\n let cur: unknown = collection;\n for (const k of keys) cur = goIndex(cur, k);\n return cur;\n },\n argTypes: [\"collection\", \"index-key\"],\n arity: { kind: \"variadic\" },\n },\n\n // [LAW:single-enforcer] `slice x i j` — array/slice/string slicing.\n // First slot declares \"sliceable\" (string|array) so the gate\n // rejects non-sliceable receivers once; index slots declare \"int\"\n // (Go refuses a non-integer index) so the gate normalizes\n // `number|bigint` to an integer `number` carrier before the body\n // runs; the body checks the bounds Go checks (`goSlice`).\n slice: {\n fn: (collection: string | readonly unknown[], ...indices: number[]) =>\n goSlice(collection, indices),\n argTypes: [\"sliceable\", \"int\"],\n arity: { kind: \"variadic\" },\n },\n\n // [LAW:single-enforcer] Formatted printers declare \"stringifiable\"\n // so the gate probes each non-string arg through `formatV`, the\n // flatten the bodies perform — a T through `engine.toString`, any\n // other value as Go's `%v`. Closes audit findings B1–B4: nothing\n // silently `String(v)`-flattens to \"[object Object]\".\n print: {\n fn: (...args: unknown[]) => goPrint(args, toString, isT),\n argTypes: [\"stringifiable\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n println: {\n fn: (...args: unknown[]) => `${goPrintln(args, toString, isT)}\\n`,\n argTypes: [\"stringifiable\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n printf: {\n fn: (format: string, ...args: unknown[]) => sprintf(format, args, toString, isT),\n argTypes: [\"string\", \"stringifiable\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n // Sprig's `toString`/`toStrings` are Go's `%v` — built here, beside\n // `printf`, because that is where the engine's `toString`/`isT` are.\n // `as const`: a property key named `toString` shadows\n // `Object.prototype.toString` in TS's contextual typing of the literal.\n toString: {\n fn: (v: unknown) => formatV(v, toString, isT),\n argTypes: [\"value\"] as const,\n arity: { kind: \"exact\" } as const,\n returnType: \"string\" as const,\n },\n toStrings: {\n fn: (list: unknown[]) => list.map((v) => formatV(v, toString, isT)),\n argTypes: [\"list\"],\n arity: { kind: \"exact\" },\n },\n\n // [LAW:single-enforcer] `call` declares \"callable\" for the first\n // slot — the gate rejects non-functions once with TypeMismatchError;\n // the body trusts the kind. Trailing slot is \"value\": pass-through\n // arguments to the callable, intent-documented as heterogeneous.\n call: {\n fn: (fn: unknown, ...args: unknown[]) => (fn as (...a: unknown[]) => unknown)(...args),\n argTypes: [\"callable\", \"value\"],\n arity: { kind: \"variadic\" },\n // The function comes from the data and has no registration to say\n // whether it writes, so `call` says it for every function it runs.\n writes: true,\n },\n\n // [LAW:single-enforcer + LAW:one-source-of-truth] `html` mirrors Go's\n // `text/template.HTMLEscaper`: flatten args via the print pipeline,\n // then escape the six HTML-significant characters. Sharing the\n // `\"stringifiable\"` gate + `goPrint` body with print/printf keeps\n // the no-silent-flatten contract uniform across every builtin that\n // produces a string from heterogeneous arg values.\n html: {\n fn: (...args: unknown[]) => htmlEscape(goPrint(args, toString, isT)),\n argTypes: [\"stringifiable\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n\n // [LAW:single-enforcer + LAW:one-source-of-truth] `js` mirrors Go's\n // `text/template.JSEscaper`: same flatten-then-escape shape as `html`,\n // differing only in the escape table. The shared `\"stringifiable\"`\n // gate keeps the no-silent-flatten contract uniform.\n js: {\n fn: (...args: unknown[]) => jsEscape(goPrint(args, toString, isT)),\n argTypes: [\"stringifiable\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n\n // [LAW:single-enforcer + LAW:one-source-of-truth] `urlquery` mirrors\n // Go's `text/template.URLQueryEscaper`: flatten via fmt.Sprint, then\n // `url.QueryEscape`. Same shape as html/js — only the escape function\n // differs. Built on the UTF-8 byte stream (not the JS code-unit\n // stream) so multi-byte runes percent-encode to the same bytes Go\n // emits.\n urlquery: {\n fn: (...args: unknown[]) => urlQueryEscape(goPrint(args, toString, isT)),\n argTypes: [\"stringifiable\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n\n // `not` is also lazy in spirit, but with a single argument it's\n // semantically equivalent to eager evaluation. Keep it eager.\n // Slot declares \"truthy\": isTruthy() runs against any value.\n not: { fn: (v: unknown) => !isTruthy(v), argTypes: [\"truthy\"], arity: { kind: \"exact\" } },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Lazy short-circuiting forms.\n//\n// `and a b c …` returns the first falsy argument, or the last argument\n// if all are truthy. `or` is the dual. Registered via `markLazy` so the\n// dispatcher hands them thunks instead of values; their declared\n// `argTypes: [\"truthy\"]` makes the gate a no-op against thunks (the\n// matcher is permissive-by-intent) while documenting that each arg is\n// consulted for truthiness.\n// ---------------------------------------------------------------------------\n\nfunction lazyBuiltins(): FuncMap {\n return {\n and: markLazy({\n argTypes: [\"truthy\", \"truthy\"],\n arity: { kind: \"variadic\" },\n fn: (...thunks: unknown[]) => {\n let last: unknown = true;\n for (const t of thunks) {\n last = (t as () => unknown)();\n if (!isTruthy(last)) return last;\n }\n return last;\n },\n }),\n or: markLazy({\n argTypes: [\"truthy\", \"truthy\"],\n arity: { kind: \"variadic\" },\n fn: (...thunks: unknown[]) => {\n let last: unknown = false;\n for (const t of thunks) {\n last = (t as () => unknown)();\n if (isTruthy(last)) return last;\n }\n return last;\n },\n }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public default registry.\n// ---------------------------------------------------------------------------\n\nexport function defaultBuiltins(toString: (v: unknown) => string, isT: IsT): FuncMap {\n return { ...eagerBuiltins(toString, isT), ...lazyBuiltins() };\n}\n\n// ---------------------------------------------------------------------------\n// Comparison + length + index helpers (Go-template semantics).\n// ---------------------------------------------------------------------------\n\nfunction goEqPair(a: unknown, b: unknown): boolean {\n // Go-template `eq` semantics: numeric kinds bridge (1 == 1n), and\n // structural values (arrays, plain objects, Maps, Sets) compare by\n // deep equality. The gate already enforces same-kind for the slots,\n // so this only needs to compute equality — never reject.\n if (typeof a === \"number\" && typeof b === \"bigint\") return BigInt(a) === b;\n if (typeof a === \"bigint\" && typeof b === \"number\") return a === BigInt(b);\n return deepEqual(a, b);\n}\n\nfunction compare(a: unknown, b: unknown): number {\n // [LAW:single-enforcer] Same-kind invariant is enforced by\n // `enforceArgTypes` ahead of this call (via `argTypes: [\"ordered\",\n // \"ordered\"]`). Here we only compute the ordering — no cross-type\n // defensive logic needed.\n if (typeof a === \"bigint\" && typeof b === \"bigint\") {\n return a === b ? 0 : a < b ? -1 : 1;\n }\n if (typeof a === \"bigint\" || typeof b === \"bigint\") {\n const an = typeof a === \"bigint\" ? a : BigInt(Math.trunc(Number(a)));\n const bn = typeof b === \"bigint\" ? b : BigInt(Math.trunc(Number(b)));\n return an === bn ? 0 : an < bn ? -1 : 1;\n }\n // a and b are guaranteed same-kind (string/number/boolean) at this\n // point, so the ordering is a direct primitive compare.\n const x = a as string | number | boolean;\n const y = b as string | number | boolean;\n return x === y ? 0 : x < y ? -1 : 1;\n}\n\nfunction goLen(value: unknown): number {\n // [LAW:single-enforcer] Kind already validated by `enforceArgTypes`\n // against argTypes: [\"sized\"]. Body picks the per-kind size readout;\n // no defensive nil / non-sized throws here — the gate caught those.\n if (typeof value === \"string\") return value.length;\n if (Array.isArray(value)) return value.length;\n if (value instanceof Map) return value.size;\n if (value instanceof Set) return value.size;\n return Object.keys(value as Record<string, unknown>).length;\n}\n\nfunction goIndex(collection: unknown, key: unknown): unknown {\n // [LAW:single-enforcer] The gate validates the *initial* collection\n // and key shapes. Mid-walk, `collection` is whatever the previous\n // step returned — so the body keeps a \"cannot index\" defense for\n // intermediate non-collection values (e.g., a leaf number). The nil\n // case is folded into that catch-all.\n if (Array.isArray(collection) || typeof collection === \"string\") {\n const i = indexArg(key, collection.length);\n if (i === collection.length) throw new Error(`index out of range: ${i}`);\n return collection[i];\n }\n if (collection instanceof Map) {\n return collection.get(key);\n }\n if (collection !== null && typeof collection === \"object\") {\n // Closes B5: no silent `String(key)`. Object access requires a\n // string key; numeric/bigint keys for an object collection are a\n // body-level kind error (the gate's per-slot rule can't express\n // \"key kind depends on receiver kind\" without cross-slot logic).\n if (typeof key !== \"string\") {\n throw new Error(`index: object index must be string, got ${describeType(key)}`);\n }\n return (collection as Record<string, unknown>)[key];\n }\n throw new Error(`index: cannot index ${describeType(collection)}`);\n}\n\n// [LAW:one-source-of-truth] Go's `indexArg`: the one rule `index` and\n// `slice` share for a position into a string, slice, or array — an\n// integer in `0..cap`, refused in Go's words otherwise. `cap` itself is\n// admitted because a slice bound may equal the length; `index` refuses\n// it on its own.\nfunction indexArg(key: unknown, cap: number): number {\n const x = typeof key === \"bigint\" ? Number(key) : key;\n if (typeof x !== \"number\" || !Number.isInteger(x)) {\n throw new Error(`cannot index slice/array with type ${goPrintfType(key)}`);\n }\n if (x < 0 || x > cap) throw new Error(`index out of range: ${String(key)}`);\n return x;\n}\n\n// Go's builtin `slice x i j k`: up to three bounds, each checked by\n// `indexArg` and ordered `i <= j <= k`; a string takes at most two.\nfunction goSlice(collection: string | readonly unknown[], indices: readonly number[]): unknown {\n if (indices.length > 3) throw new Error(`too many slice indexes: ${indices.length}`);\n if (typeof collection === \"string\" && indices.length > 2) {\n throw new Error(\"cannot 3-index slice a string\");\n }\n const cap = collection.length;\n const bounds = [0, cap, cap];\n indices.forEach((ix, n) => {\n bounds[n] = indexArg(ix, cap);\n });\n const [i, j, k] = bounds as [number, number, number];\n if (i > j) throw new Error(`invalid slice index: ${i} > ${j}`);\n if (j > k) throw new Error(`invalid slice index: ${j} > ${k}`);\n return collection.slice(i, j);\n}\n\nfunction describeType(v: unknown): string {\n if (v === null) return \"null\";\n if (v === undefined) return \"undefined\";\n if (Array.isArray(v)) return \"array\";\n if (v instanceof Map) return \"Map\";\n return typeof v;\n}\n\n// Go-style type name for `%!<verb>(<type>=<value>)` printf diagnostics.\n// Mirrors what Go's fmt prints for the common scalar types we accept.\nfunction goPrintfType(v: unknown): string {\n if (v === null || v === undefined) return \"<nil>\";\n if (typeof v === \"string\") return \"string\";\n if (typeof v === \"boolean\") return \"bool\";\n if (typeof v === \"bigint\") return \"int64\";\n if (typeof v === \"number\") return Number.isInteger(v) ? \"int\" : \"float64\";\n if (Array.isArray(v)) return \"[]interface {}\";\n if (v instanceof Map || typeof v === \"object\") return \"map[string]interface {}\";\n return typeof v;\n}\n\n// ---------------------------------------------------------------------------\n// Print + sprintf.\n//\n// We support %s, %d, %v, %q, %f, %t, %x — the verbs explicitly listed\n// in the parser-evaluator-cgm epic. Unknown verbs pass through as\n// `%!<verb>(<arg>)` matching Go's diagnostic style.\n// ---------------------------------------------------------------------------\n\nfunction goPrint(args: readonly unknown[], toString: ToString, isT: IsT): string {\n // Go's `fmt.Sprint`: emits a space between adjacent operands when\n // *neither* of the two flanking values is a string. So `x` `1` is\n // joined as `x1` (string adjacent), but `1` `true` is joined as\n // `1 true` (neither is a string).\n let out = \"\";\n let prevIsString = false;\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n const isString = typeof arg === \"string\";\n if (i > 0 && !prevIsString && !isString) out += \" \";\n out += formatV(arg, toString, isT);\n prevIsString = isString;\n }\n return out;\n}\n\n// Go's `fmt.Sprintln`: unlike Sprint, a space between every two operands.\nfunction goPrintln(args: readonly unknown[], toString: ToString, isT: IsT): string {\n return args.map((arg) => formatV(arg, toString, isT)).join(\" \");\n}\n\n// ---------------------------------------------------------------------------\n// HTML escaping.\n//\n// Mirrors Go's `text/template.HTMLEscape` byte-for-byte: NUL becomes the\n// Unicode replacement character, the five HTML-significant characters\n// become their shortest numeric / named entities (Go picks `"` over\n// `"` and `'` over `'` for brevity — match that).\n// ---------------------------------------------------------------------------\n\nconst HTML_ESCAPE_TABLE: Readonly<Record<string, string>> = {\n \"\\0\": \"�\",\n '\"': \""\",\n \"'\": \"'\",\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n};\n\nfunction htmlEscape(s: string): string {\n return s.replace(/[\\0\"'&<>]/g, (c) => HTML_ESCAPE_TABLE[c] ?? c);\n}\n\n// ---------------------------------------------------------------------------\n// JS escaping.\n//\n// Mirrors Go's `text/template.JSEscape` rune-for-rune. The fixed set\n// `\\ ' \" < > & =` map to specific replacements; ASCII control chars\n// (< 0x20) emit `\\u00XX`; non-ASCII (>= 0x80) that aren't `unicode.IsPrint`\n// also emit `\\u%04X`. Everything else passes through. Go's `unicode.IsPrint`\n// for non-ASCII is L/M/N/P/S — anything in C or Z (including U+00A0,\n// U+2028, U+2029, zero-width formats, private use) is non-printable.\n// ---------------------------------------------------------------------------\n\nconst JS_FIXED_ESCAPES: Readonly<Record<string, string>> = {\n \"\\\\\": \"\\\\\\\\\",\n \"'\": \"\\\\'\",\n '\"': '\\\\\"',\n \"<\": \"\\\\u003C\",\n \">\": \"\\\\u003E\",\n \"&\": \"\\\\u0026\",\n \"=\": \"\\\\u003D\",\n};\n\nconst JS_NON_ASCII_PRINTABLE = /^[\\p{L}\\p{M}\\p{N}\\p{P}\\p{S}]$/u;\n\nfunction jsEscape(s: string): string {\n let out = \"\";\n for (const ch of s) {\n const fixed = JS_FIXED_ESCAPES[ch];\n if (fixed !== undefined) {\n out += fixed;\n continue;\n }\n const cp = ch.codePointAt(0) as number;\n if (cp < 0x20 || (cp >= 0x80 && !JS_NON_ASCII_PRINTABLE.test(ch))) {\n out += `\\\\u${cp.toString(16).toUpperCase().padStart(4, \"0\")}`;\n continue;\n }\n out += ch;\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// URL-query escaping.\n//\n// Mirrors Go's `net/url.QueryEscape` (which `text/template.URLQueryEscaper`\n// delegates to) byte-for-byte: the unreserved set [A-Za-z0-9-._~] passes\n// through, space becomes `+`, every other byte becomes `%XX` uppercase hex.\n// Operates on UTF-8 bytes — multi-byte runes encode to the same percent\n// sequences Go emits (e.g. \"α\" → \"%CE%B1\"). Diverges from JS's\n// `encodeURIComponent` which uses `%20` for space and leaves `!*'()` raw.\n// ---------------------------------------------------------------------------\n\nconst URL_QUERY_ENCODER = new TextEncoder();\n\nfunction urlQueryEscape(s: string): string {\n let out = \"\";\n const bytes = URL_QUERY_ENCODER.encode(s);\n for (const b of bytes) {\n const unreserved =\n (b >= 0x30 && b <= 0x39) || // 0-9\n (b >= 0x41 && b <= 0x5a) || // A-Z\n (b >= 0x61 && b <= 0x7a) || // a-z\n b === 0x2d || // -\n b === 0x2e || // .\n b === 0x5f || // _\n b === 0x7e; // ~\n if (unreserved) {\n out += String.fromCharCode(b);\n } else if (b === 0x20) {\n out += \"+\";\n } else {\n out += `%${b.toString(16).toUpperCase().padStart(2, \"0\")}`;\n }\n }\n return out;\n}\n\nfunction sprintf(\n format: string,\n args: readonly unknown[],\n toString: (v: unknown) => string,\n isT: IsT,\n): string {\n let out = \"\";\n let argIdx = 0;\n let i = 0;\n while (i < format.length) {\n const ch = format[i];\n if (ch !== \"%\") {\n out += ch;\n i += 1;\n continue;\n }\n if (format[i + 1] === \"%\") {\n out += \"%\";\n i += 2;\n continue;\n }\n // Read optional flags + width + precision before the verb.\n let j = i + 1;\n while (j < format.length && \"+-# 0\".includes(format[j] ?? \"\")) j += 1;\n while (j < format.length && format[j] !== undefined && /[0-9]/.test(format[j] as string))\n j += 1;\n if (format[j] === \".\") {\n j += 1;\n while (j < format.length && format[j] !== undefined && /[0-9]/.test(format[j] as string))\n j += 1;\n }\n const verb = format[j];\n const spec = format.slice(i + 1, j);\n const missing = argIdx >= args.length;\n const arg = args[argIdx++];\n out += missing ? `%!${verb ?? \"\"}(MISSING)` : formatVerb(verb ?? \"\", spec, arg, toString, isT);\n i = j + 1;\n }\n return out;\n}\n\n// Go's fmt applies a verb to each element of a slice or map, keys\n// included — `%d` of `[1 2]` is `[1 2]`, `%q` of `{k: \"v\"}` is\n// `map[\"k\":\"v\"]` — so the verb formats the leaves of the one `%v` walk.\nfunction formatVerb(\n verb: string,\n spec: string,\n arg: unknown,\n toString: (v: unknown) => string,\n isT: IsT,\n): string {\n // A Uint8Array is Go's []byte, which %s and %q print as text and %x as\n // the bytes' hex; every other verb walks it as a slice.\n if (arg instanceof Uint8Array && (verb === \"s\" || verb === \"q\")) {\n return formatLeafVerb(verb, spec, new TextDecoder().decode(arg), toString, isT);\n }\n if (arg instanceof Uint8Array && verb === \"x\") {\n return applyWidth(spec, Array.from(arg, (b) => b.toString(16).padStart(2, \"0\")).join(\"\"));\n }\n return formatWalk(arg, (leaf) => formatLeafVerb(verb, spec, leaf, toString, isT), toString, isT);\n}\n\nfunction formatLeafVerb(\n verb: string,\n spec: string,\n arg: unknown,\n toString: (v: unknown) => string,\n isT: IsT,\n): string {\n switch (verb) {\n case \"s\":\n return applyWidth(spec, formatLeafV(arg, toString, isT));\n case \"d\": {\n // [LAW:single-enforcer] Non-numeric primitives route to the same\n // diagnostic format as the `default:` arm — no silent NaN.\n if (typeof arg !== \"number\" && typeof arg !== \"bigint\") {\n return badVerb(verb, arg, toString, isT);\n }\n const n = typeof arg === \"bigint\" ? arg : Math.trunc(arg);\n return applyWidth(spec, String(n));\n }\n case \"v\":\n return applyWidth(spec, formatLeafV(arg, toString, isT));\n case \"q\":\n return applyWidth(spec, JSON.stringify(formatLeafV(arg, toString, isT)));\n case \"f\": {\n // [LAW:single-enforcer] See %d.\n if (typeof arg !== \"number\" && typeof arg !== \"bigint\") {\n return badVerb(verb, arg, toString, isT);\n }\n const precision = spec.includes(\".\") ? Number(spec.split(\".\")[1]) : 6;\n const n = Number(arg);\n return applyWidth(spec, n.toFixed(precision));\n }\n case \"t\":\n // [LAW:single-enforcer] Go's %t takes a bool; see %d.\n if (typeof arg !== \"boolean\") {\n return badVerb(verb, arg, toString, isT);\n }\n return applyWidth(spec, String(arg));\n case \"x\": {\n // Go's %x on a string emits the hex of its UTF-8 bytes.\n if (typeof arg === \"string\") {\n const bytes = new TextEncoder().encode(arg);\n let hex = \"\";\n for (const b of bytes) hex += b.toString(16).padStart(2, \"0\");\n return applyWidth(spec, hex);\n }\n // [LAW:single-enforcer] See %d.\n if (typeof arg !== \"number\" && typeof arg !== \"bigint\") {\n return badVerb(verb, arg, toString, isT);\n }\n if (typeof arg === \"bigint\") return applyWidth(spec, arg.toString(16));\n const n = Math.trunc(arg);\n return applyWidth(spec, n.toString(16));\n }\n default:\n return badVerb(verb, arg, toString, isT);\n }\n}\n\n// [LAW:single-enforcer] Go's one diagnostic for a verb its operand does not\n// take: `%!d(string=a)`, and `%!d(<nil>)` for nil.\nfunction badVerb(verb: string, arg: unknown, toString: ToString, isT: IsT): string {\n if (arg === null || arg === undefined) return `%!${verb}(<nil>)`;\n return `%!${verb}(${goPrintfType(arg)}=${formatLeafV(arg, toString, isT)})`;\n}\n\nfunction applyWidth(spec: string, body: string): string {\n // Parse width and the `-` (left-align) flag from the spec — anything\n // before a `.` and not in the flag set is the width.\n const flag = spec.match(/^([+\\-# 0]*)/)?.[1] ?? \"\";\n const widthMatch = spec.slice(flag.length).match(/^(\\d+)/);\n if (!widthMatch) return body;\n const width = Number(widthMatch[1]);\n if (body.length >= width) return body;\n const pad = \" \".repeat(width - body.length);\n return flag.includes(\"-\") ? body + pad : pad + body;\n}\n\n// Is this value a T — opaque, printed by its own String — or not? The\n// engine's one predicate, threaded to every place that prints a value.\nexport type IsT = (value: unknown) => boolean;\n\n// [LAW:one-source-of-truth] The one Go-`%v` formatter: the output stream,\n// printf's `%v` verb, and sprig's `toString`/`toStrings` all print through\n// it, so a bare `{{ .doc }}` and `{{ printf \"%v\" .doc }}` cannot disagree.\n// A T flattens through the engine's `toString`, the same function `%s`\n// and `print` use. Of the non-T values, only the shapes Go walks are\n// walked — an array, a Map, a plain object (printed as Go prints a map:\n// `map[k:v …]`, keys sorted the way fmt orders them).\nexport function formatV(value: unknown, toString: ToString, isT: IsT): string {\n try {\n return formatWalk(value, (leaf) => formatLeafV(leaf, toString, isT), toString, isT);\n } catch (err) {\n // The leaf that refused knows only itself; the walk's root is named\n // here, once, so every reporter describes the refusal the same way.\n if (err instanceof UnprintableError) throw new UnprintableError(err.leaf, err.cause, value);\n throw err;\n }\n}\n\n// [LAW:single-enforcer] The one structural walk every verb shares; the\n// verb decides only how a leaf prints.\nfunction formatWalk(\n value: unknown,\n leaf: (v: unknown) => string,\n toString: ToString,\n isT: IsT,\n): string {\n if (isT(value)) return leaf(value);\n const walk = (v: unknown): string => formatWalk(v, leaf, toString, isT);\n if (Array.isArray(value)) return `[${value.map(walk).join(\" \")}]`;\n if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {\n return `[${Array.from(value as unknown as ArrayLike<unknown>, walk).join(\" \")}]`;\n }\n if (value instanceof Map) return formatEntries([...value.entries()], walk, toString, isT);\n if (isPlainObject(value)) return formatEntries(Object.entries(value), walk, toString, isT);\n // A class instance is Go's struct: `%v` prints its field values in\n // order, `{alice 30}`, unless it is a Stringer.\n if (isStruct(value)) return `{${Object.values(value).map(walk).join(\" \")}}`;\n return leaf(value);\n}\n\nfunction isStruct(value: unknown): value is object {\n return (\n typeof value === \"object\" && value !== null && !(value instanceof Set) && !hasOwnString(value)\n );\n}\n\n// A leaf has a `%v` text form when it is nil, a scalar, a T the engine's\n// `toString` flattens, or an object with its own String — a Date, a\n// RegExp, a class that defines `toString`, Go's Stringer. A Set, a\n// function or a symbol has none: printing it would be the silent\n// \"[object Set]\" flatten, so it is refused, and a `toString` that cannot\n// flatten a T is a refusal too.\nfunction formatLeafV(value: unknown, toString: ToString, isT: IsT): string {\n if (value === null || value === undefined) return \"<nil>\";\n if (typeof value === \"string\") return value;\n if (isT(value)) return flattenT(value, toString);\n if (typeof value === \"number\" || typeof value === \"bigint\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (typeof value === \"object\" && hasOwnString(value)) return stringerText(value);\n throw new UnprintableError(value);\n}\n\nfunction flattenT(value: unknown, toString: ToString): string {\n try {\n return toString(value);\n } catch (err) {\n if (isStackOverflow(err)) throw err;\n throw new UnprintableError(value, err);\n }\n}\n\n// A Stringer whose text form throws is refused as a T is: the same\n// UnprintableError, so every print refusal has one type.\nfunction stringerText(value: object): string {\n try {\n return String(value);\n } catch (err) {\n if (isStackOverflow(err)) throw err;\n throw new UnprintableError(value, err);\n }\n}\n\n// Go's Stringer: a callable `toString` other than the `[object …]`\n// default, which is the one on the root of the prototype chain — read\n// there, not off this realm's `Object.prototype`, so an object from a\n// vm context or an iframe is judged the same.\nfunction hasOwnString(value: object): boolean {\n let root: object = value;\n for (let p = Object.getPrototypeOf(root); p !== null; p = Object.getPrototypeOf(p)) root = p;\n const own = (value as { toString?: unknown }).toString;\n return typeof own === \"function\" && own !== (root as { toString?: unknown }).toString;\n}\n\n/** A value Go's `%v` has no text form for: a Set, a function, a symbol, or\n * a T the engine's `toString` cannot flatten. The action and the call that\n * met it report it at their position. */\nexport class UnprintableError extends Error {\n override readonly name = \"UnprintableError\";\n /** What cannot print, named from the printed value: the leaf alone, or\n * the value holding it. */\n readonly summary: string;\n constructor(\n readonly leaf: unknown,\n cause?: unknown,\n root: unknown = leaf,\n ) {\n const summary =\n root === leaf ? typeNameOf(leaf) : `${typeNameOf(root)} holding ${typeNameOf(leaf)}`;\n // A flattener that names what it expected says why; any other refusal\n // is a value with no text form.\n const why =\n cause instanceof TypeMismatchError ? `expected ${cause.expected}` : \"it has no text form\";\n super(`cannot print a value of type ${summary}: ${why}`, { cause });\n this.summary = summary;\n }\n}\n\n// [LAW:one-source-of-truth] The one name every error gives a value's type. A\n// JS constructor name, not Go's %T: `Rich`, not `*main.Rich`. Not `kindOf`\n// in src/sprig/types/kindOf.ts, the template-visible kind, which answers a\n// different question.\n// the typeof of a primitive, `array` and `object` for the shapes Go walks\n// as slice and map, and otherwise the nearest named constructor — so an\n// anonymous `class extends Set` is still a Set.\nexport function typeNameOf(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n if (typeof value !== \"object\") return typeof value;\n if (isPlainObject(value)) return \"object\";\n for (let p = Object.getPrototypeOf(value); p !== null; p = Object.getPrototypeOf(p)) {\n const name = (p as { constructor?: { name?: unknown } }).constructor?.name;\n // `Object.create({})` is a plain object too: its chain ends in `Object`.\n if (typeof name === \"string\" && name !== \"\") return name === \"Object\" ? \"object\" : name;\n }\n return \"object\";\n}\n\ntype ToString = (value: unknown) => string;\n\n// [LAW:single-enforcer] The one ordering a Map and a plain object print in:\n// numeric keys numerically and first, every other key by its formatted text.\nfunction formatEntries(\n entries: readonly (readonly [unknown, unknown])[],\n walk: (v: unknown) => string,\n toString: ToString,\n isT: IsT,\n): string {\n const isNumeric = (k: unknown): k is number | bigint =>\n typeof k === \"number\" || typeof k === \"bigint\";\n type Keyed = { readonly k: unknown; readonly v: unknown; readonly text: string };\n const byKey = (a: Keyed, b: Keyed): number => {\n if (isNumeric(a.k) && isNumeric(b.k)) return a.k < b.k ? -1 : a.k > b.k ? 1 : 0;\n if (isNumeric(a.k) !== isNumeric(b.k)) return isNumeric(a.k) ? -1 : 1;\n return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;\n };\n return `map[${entries\n .map(([k, v]): Keyed => ({ k, v, text: formatV(k, toString, isT) }))\n .sort(byKey)\n .map(({ k, v }) => `${walk(k)}:${walk(v)}`)\n .join(\" \")}]`;\n}\n\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n if (Array.isArray(value)) return false;\n if (value instanceof Map || value instanceof Set) return false;\n // Reject typed arrays, Dates, RegExps, class instances and other\n // built-ins by requiring a null prototype or one whose own prototype is\n // null — any realm's `Object.prototype`.\n const proto = Object.getPrototypeOf(value);\n return proto === null || Object.getPrototypeOf(proto) === null;\n}\n","/**\n * `include` — Helm's function for rendering a `{{ define }}` by name and\n * returning its text, so a sub-template's output can be piped, tested,\n * defaulted or bound like any other value. `{{ template }}` renders the same\n * define but writes straight to the output, where none of that can reach it.\n *\n * Opt-in: Go's `text/template` has no `include`, so it is not a builtin.\n * Register it like a sprig group — `funcs: { ...sprigStrings(), include }` —\n * under any name.\n *\n * [LAW:single-enforcer] Rendering a define needs the evaluator's context,\n * which no `TemplateFunc` body receives. The evaluator recognizes `include`\n * by its module-private `fn` and runs the render in its place. A consumer\n * cannot forge that function, and it follows the registration through any\n * name and any copy (`{ ...include }`).\n *\n * Leaf module so `evaluator.ts` and `index.ts` import it without a cycle.\n */\n\nimport type { TemplateFunc } from \"./evaluator.js\";\n\n// Never called: the evaluator dispatches on this reference to its own\n// render. Reaching this body means that dispatch was bypassed.\nconst render = (): never => {\n throw new Error(\"include was called outside the evaluator's dispatch\");\n};\n\n/** Helm's `include(name string, data interface{}) (string, error)`. */\nexport const include: TemplateFunc = {\n fn: render,\n argTypes: [\"string\", \"value\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n};\n\n/** True iff `fn` is `include`, under whatever name or copy it was registered. */\nexport function isInclude(fn: TemplateFunc): boolean {\n return fn.fn === render;\n}\n","/**\n * Evaluation provenance: which marked calls a value depends on.\n *\n * A registered func marks the call it is in by returning\n * `marked(value, ...tokens)`. The engine unwraps the carrier at its one\n * dispatch site and the tokens travel beside the value — through every\n * variable and dot it is bound into, onto every action that reads it —\n * until a hook reports them (`EngineConfig.emitted` / `decided`).\n *\n * [LAW:types-are-the-program] Provenance rides beside values, never on\n * them: a number or a string cannot carry a fact, and a wrapper that\n * reached a template value would change what every slot matcher sees.\n * So the carrier exists only between a func body's return and `invoke`;\n * nothing downstream of `invoke` can be handed one.\n */\n\n/** The set of marks a value or an emission depends on. */\nexport type Marks = ReadonlySet<unknown>;\n\nexport const NO_MARKS: Marks = new Set();\n\n// Declared before the class: its static block assigns them as the class\n// is defined, and a `let` read or written before its line is in the TDZ.\nlet createMarked: (value: unknown, marks: readonly unknown[]) => Marked;\nlet openMarked: (result: unknown) => {\n readonly value: unknown;\n readonly marks: readonly unknown[];\n};\n\n// [LAW:single-enforcer] The one reader of a carrier, called only by the\n// engine's dispatch site: the marks join the reading pipe's set and the\n// plain value continues as the call's result.\nexport let readCarrier: (result: unknown, into: Set<unknown>) => unknown;\n\n/**\n * A func's return value together with the marks of the call that\n * produced it. Opaque: build one with {@link marked}; only the engine\n * reads it.\n */\nexport class Marked {\n readonly #value: unknown;\n readonly #marks: readonly unknown[];\n\n private constructor(value: unknown, marks: readonly unknown[]) {\n this.#value = value;\n this.#marks = marks;\n }\n\n static {\n createMarked = (value, marks) =>\n // `marked(marked(v, a), b)` is one carrier with both marks, so a\n // func that wraps another func's result never hides the inner mark.\n value instanceof Marked\n ? new Marked(value.#value, [...value.#marks, ...marks])\n : new Marked(value, marks);\n openMarked = (result) =>\n result instanceof Marked\n ? { value: result.#value, marks: result.#marks }\n : { value: result, marks: [] };\n readCarrier = (result, into) => {\n if (!(result instanceof Marked)) return result;\n for (const mark of result.#marks) into.add(mark);\n return result.#value;\n };\n }\n}\n\n/**\n * Return this from a registered func to mark the call: every emission\n * and control decision that depends on the call's result reports\n * `marks`. The template sees `value`, exactly as if it had been returned\n * directly.\n */\nexport function marked(value: unknown, ...marks: unknown[]): Marked {\n return createMarked(value, marks);\n}\n\n/**\n * A func's return read apart: its value and the marks it carries (none\n * for a plain value). For JS code that builds on a marking func outside a\n * template — `const { value, marks } = unmarked(tween.fn(...))`, then\n * `return marked(Math.min(1, value as number), ...marks)`.\n */\nexport function unmarked(result: unknown): {\n readonly value: unknown;\n readonly marks: readonly unknown[];\n} {\n return openMarked(result);\n}\n\n/** `a ∪ b`, sharing an operand when the other is empty. */\nexport function unionMarks(a: Marks, b: Marks): Marks {\n if (b.size === 0) return a;\n if (a.size === 0) return b;\n return new Set([...a, ...b]);\n}\n","/**\n * Lexical scope chain for the evaluator.\n *\n * [LAW:dataflow-not-control-flow] A `Scope` is a `dot`, a parent\n * pointer and the variables declared in it. Entering a construct or an\n * iteration *constructs* a frame and leaving it drops the frame, so\n * nothing is ever undone: iterations of `{{range}}` cannot see each\n * other's `:=` declarations — the data shape itself prevents the bug.\n *\n * Only a frame's variables change. A lookup walks the parent chain.\n * Assignment via `=` searches the chain and overwrites the binding in\n * the frame that declared it; declaration via `:=` always creates the\n * binding in the current leaf frame.\n *\n * `$` is an ordinary variable declared in a chain's root frame, as in\n * Go, where it is `vars[0]`: so `$ = v` assigns it, and a `template` /\n * `block` invocation starts a fresh chain whose only variable is `$`.\n */\n\nimport { type Marks, unionMarks } from \"./marks.js\";\n\n/**\n * A bound value and the marks it depends on.\n *\n * [LAW:types-are-the-program] One record, so no binding can be made\n * without saying what it depends on: a variable or a dot that forgot\n * its marks would report them late, which is the one failure\n * provenance exists to rule out.\n */\nexport interface Binding {\n readonly value: unknown;\n readonly marks: Marks;\n}\n\nexport interface Scope {\n /** Current dot value — what `.` resolves to. */\n readonly dot: Binding;\n /** Parent scope, or undefined for a chain's root frame. */\n readonly parent: Scope | undefined;\n /** Variables declared in *this* frame. */\n readonly vars: Map<string, Binding>;\n}\n\n/** The frame a template body starts in: `.` and `$` are both `dot`. */\nexport function rootScope(dot: Binding): Scope {\n return { dot, parent: undefined, vars: new Map([[\"$\", dot]]) };\n}\n\nexport function pushScope(parent: Scope, dot: Binding): Scope {\n return { dot, parent, vars: new Map() };\n}\n\n// [LAW:single-enforcer] The one walk that decides which frame a name\n// resolves to, so a read and an assignment can never disagree.\nfunction findFrame(scope: Scope, name: string): Scope | undefined {\n let cur: Scope | undefined = scope;\n while (cur !== undefined && !cur.vars.has(name)) cur = cur.parent;\n return cur;\n}\n\n/**\n * Look up a `$var` binding, walking the parent chain.\n * Returns the binding on hit and `undefined` on miss — a `Binding` is a\n * record, so a variable declared as `undefined` is still a hit.\n */\nexport function lookupVar(scope: Scope, name: string): Binding | undefined {\n return findFrame(scope, name)?.vars.get(name);\n}\n\n/** Declare a new variable in the leaf scope (for `:=`). */\nexport function declareVar(scope: Scope, name: string, binding: Binding): void {\n scope.vars.set(name, binding);\n}\n\n/**\n * Overwrite the nearest frame's binding of `name` (for `=`), as Go's\n * text/template exec.go walks its variable stack. Returns whether any\n * frame declared it; the caller owns the \"undefined variable\" error,\n * which needs a position this module does not have.\n */\nexport function assignVar(scope: Scope, name: string, binding: Binding): boolean {\n const frame = findFrame(scope, name);\n frame?.vars.set(name, binding);\n return frame !== undefined;\n}\n\n/** Add `marks` to what `name`'s binding depends on, if any frame declared it. */\nexport function markVar(scope: Scope, name: string, marks: Marks): void {\n const binding = lookupVar(scope, name);\n if (binding === undefined) return;\n assignVar(scope, name, { value: binding.value, marks: unionMarks(binding.marks, marks) });\n}\n","/**\n * Engine<T> — generic-over-T template evaluator.\n *\n * [LAW:dataflow-not-control-flow] Evaluation is one switch on the AST\n * node's type. Every node kind has exactly one production rule; the\n * shape of work is fixed by the data, not by scattered branching.\n *\n * [LAW:single-enforcer] All `string → T` conversion goes through\n * `fromString`. There is exactly one place text becomes T. Function\n * returns of `string` are routed through the same converter on their\n * way to the output stream — the asymmetry between \"string in / T out\"\n * is encoded as a single function call, not duplicated at every site.\n *\n * State is threaded as a single `EvalContext` per `evaluate()` call —\n * no instance mutation, so the same Engine handles concurrent evaluate\n * calls (tested through the parse-once-eval-many invariant).\n */\n\nimport {\n type ArgCount,\n ArgCountError,\n EvalError,\n FailError,\n FuncNotFoundError,\n isStackOverflow,\n MissingFieldError,\n NotIntegerError,\n TemplateError,\n TypeMismatchError,\n} from \"../errors.js\";\nimport {\n assertNever,\n type CommandNode,\n type ListNode,\n type Node,\n type PipeNode,\n type VariableNode,\n} from \"../parser/ast.js\";\nimport type { Delims } from \"../parser/lexer.js\";\nimport {\n type DefineEntry,\n type Defines,\n lookupDefine,\n type ParseResult,\n parse as parseSource,\n} from \"../parser/parser.js\";\nimport type { Pos } from \"../parser/pos.js\";\nimport { walk } from \"../parser/walk.js\";\nimport { MISSING, walkFieldChain } from \"./access.js\";\nimport {\n defaultBuiltins,\n formatV,\n type IsT,\n isPlainObject,\n typeNameOf,\n UnprintableError,\n} from \"./builtins.js\";\nimport { isInclude } from \"./include.js\";\nimport { isLazy } from \"./lazy.js\";\nimport { Marked, type Marks, NO_MARKS, readCarrier, unionMarks } from \"./marks.js\";\nimport {\n assignVar,\n type Binding,\n declareVar,\n lookupVar,\n markVar,\n pushScope,\n rootScope,\n type Scope,\n} from \"./scope.js\";\nimport { isTruthy } from \"./truthy.js\";\n\n// ---------------------------------------------------------------------------\n// Public API.\n// ---------------------------------------------------------------------------\n\n/**\n * Every kind a slot may declare.\n *\n * [LAW:one-source-of-truth] The kinds are a *list* first and a type\n * second. `validateArgSpecs` must reject a declaration naming a kind\n * that does not exist, and a runtime check needs a runtime list; writing\n * that list out beside a hand-maintained union would be the second\n * clock. So the array is authoritative and `ArgType` is derived from it\n * — one edit adds a kind to the type, to the construct-time check, and\n * to the two exhaustive switches that must then grow an arm.\n *\n * The per-kind semantics live on `ArgType` below, where a consumer\n * hovering the exported name finds them.\n */\nconst ARG_TYPES = [\n \"string\",\n // [LAW:types-are-the-program] \"int\", \"truncating-int\" and \"float\" are\n // validate-AND-parse numeric carriers. The matcher's membership\n // predicate IS the body's contract. Go has two integer semantics, and\n // each gets its own kind so a slot declares which one it has:\n // - \"int\" is a Go `int` parameter (`repeat`, `substr`, `until`, the\n // built-in `slice`'s indices …): Go refuses a fractional there\n // (\"expected integer; found 2.7\"), so the matcher admits only\n // safe integers, in either carrier. NaN, Infinity, fractionals,\n // and integers past 2^53 are rejected at the gate.\n // - \"truncating-int\" is the numeric half of sprig's `interface{}`\n // parameter read through `cast.ToInt64` (`add`, `sub`, `max` …):\n // Go truncates a fractional toward zero, so the matcher admits any\n // finite number and the gate truncates it. The cast's string, bool\n // and nil conversions are refused, as every slot here refuses a\n // kind it would have to flatten.\n // - \"float\" admits any number (NaN/Infinity are legitimate IEEE\n // 754 floats; Go's float64 has them too) and bigints whose\n // `Number()` is finite. The only rejected bigint is one whose\n // conversion overflows to Infinity.\n // After membership is proven the gate mutates `values[i]` to a\n // `number` carrier (\"int\"/\"float\": `Number(v)`; \"truncating-int\":\n // `Math.trunc(Number(v))`). Mirrors the \"liftable\" precedent: the\n // slot is both the membership rule and the parse step.\n \"int\",\n \"truncating-int\",\n \"float\",\n \"bool\",\n \"T\",\n \"ordered\",\n \"list\",\n \"dict\",\n \"sized\",\n \"comparable\",\n \"stringifiable\",\n \"liftable\",\n \"callable\",\n \"collection\",\n \"index-key\",\n \"sliceable\",\n \"truthy\",\n \"reflective\",\n \"value\",\n \"serializable\",\n] as const;\n\n/**\n * Declared parameter type for a registered template function. Used by\n * the no-silent-flatten guard to detect unsafe T-into-string flows.\n *\n * - \"string\" — must be a JS string. Non-string values raise\n * TypeMismatchError. This is the **architectural commitment**: T\n * never silently flattens into a string parameter.\n * - \"int\" — validate-AND-parse integer carrier: a Go `int`\n * parameter. Accepts any safe-integer `number` and any `bigint`\n * whose `Number()` is safe-integer-representable; rejects\n * fractionals, `NaN`, `±Infinity`, and integers past 2^53, as\n * Go refuses `repeat 2.7 \"x\"`. The gate normalizes `values[i]` to\n * `Number(v)` so bodies see `number`. Used by every slot Go declares\n * `int`: the built-in `slice`'s indices, `repeat`, `substr`, `trunc`,\n * `until`, `seq`, `chunk`, `splitn`, `round`'s precision ….\n * - \"truncating-int\" — the numeric half of sprig's `cast.ToInt64` read\n * of an `interface{}` parameter. Accepts what \"int\" accepts plus any\n * finite fractional `number`, which the gate truncates toward zero\n * (`max 1.5 2.5` is `2` in Go); refuses the strings, bools and nil\n * the cast would convert. Used by `add`, `add1`, `sub`, `mul`, `div`, `mod`,\n * `max`, `min`, `biggest`, and sprig's list `slice`.\n * - \"float\" — validate-AND-parse float carrier. Accepts any `number`\n * (including `NaN`/`±Infinity` — legitimate IEEE-754 floats) and any\n * `bigint` whose `Number()` is finite (overflow-to-Infinity rejected\n * as a magnitude failure). The gate normalizes to `Number(v)` so\n * bodies see `number`. Used by `addf`, `subf`, `mulf`, `divf`,\n * `maxf`, `minf`. Added by epic template-variance-num-carrier-hfv.\n * - \"bool\" — must be `typeof \"boolean\"`.\n * - \"T\" — a T: membership is exactly the engine's `isT` (see\n * `EngineConfig.isT`).\n * - \"ordered\" — orderable primitive (string, number, bigint, boolean).\n * When two or more \"ordered\" slots appear in the same call, all of\n * them must share a kind, with `number` and `bigint` bridged. Used\n * by `lt`/`le`/`gt`/`ge` to match Go's `text/template` rule that\n * ordering operands have the same type.\n *\n * Precise kinds (added template-laws-3gt.1, consumed in .2–.7):\n * - \"list\" — array. Excludes string (Go-parity: string is not a list).\n * - \"dict\" — plain object (not Map; Maps are handled separately).\n * - \"sized\" — has a meaningful `len`: string | array | Map | Set | object.\n * - \"comparable\" — accepted by `eq`/`ne`: any JSON-shaped value\n * (ordered primitive, nil, array, plain object, Map, or Set).\n * Functions and symbols are excluded. When two or more \"comparable\"\n * slots appear in the same call, all of them must share a kind, with\n * `number`↔`bigint` bridged and `nil` acting as a wildcard. Object\n * equality routes through `deepEqual` in `eq`/`ne` bodies.\n * - \"stringifiable\" — a value Go's `%v` can print: a string, nil, a\n * scalar, a T the engine's `toString` flattens, an object with its own\n * toString, a class instance (Go's struct), or a list/map of those; a\n * Set, function or symbol has no text form. The matcher *probes* `formatV`;\n * downstream func bodies call it again to actually print.\n * - \"callable\" — `typeof v === \"function\"`.\n * - \"collection\" — string | array | Map | plain object. The receiver\n * shape `index` accepts. Sets and primitives are rejected. Nil is\n * rejected by the gate; the body trusts a non-nil collection.\n * (Added template-laws-3gt.7 alongside the index migration.)\n * - \"index-key\" — string | number | bigint. The key shape `index`\n * accepts. The body decides which collection kind a given key fits\n * (arrays want integer; objects want string).\n * - \"sliceable\" — string | array. Receiver shape for `slice`. Folded\n * into template-laws-3gt.8 alongside the intent-named migration so\n * .9 could delete `\"any\"` from the union.\n *\n * Intent-named kinds (added template-laws-3gt.1, consumed in .8) —\n * the labels carry intent for readers; runtime behavior is documented\n * pass-through except where noted:\n * - \"truthy\" — anything (truthiness context).\n * - \"reflective\" — anything (type-inspection context).\n * - \"value\" — anything (genuinely heterogeneous: constructors,\n * structural ops). Documents intent.\n * - \"serializable\" — anything JSON-encodable. Runtime-validated:\n * functions, symbols, and circular refs fail the gate.\n *\n * [LAW:make-it-impossible] `\"any\"` is intentionally absent from this\n * union. Every slot must engage with the type system. If a slot is\n * genuinely heterogeneous, use the kind that documents the reason\n * (`\"truthy\"`, `\"reflective\"`, `\"serializable\"`, `\"value\"`,\n * `\"callable\"`). The history for this decision lives in epic\n * template-laws-3gt.\n */\nexport type ArgType = (typeof ARG_TYPES)[number];\n\n/**\n * How many arguments a func accepts, and how `argTypes` covers them.\n *\n * [LAW:types-are-the-program] Argument *count* used to live only in the\n * JS signature, where the gate could not see it: `enforceArgTypes`\n * iterated the supplied values, so a missing or surplus argument was\n * not a state it could represent, let alone reject. Declaring arity\n * alongside `argTypes` makes the count a fact the gate reads —\n * `acceptedArgCount` projects this union into the counts a declaration\n * admits and rejects the rest before the slot loop.\n *\n * [LAW:one-source-of-truth] No kind carries a count that `argTypes`\n * already holds. `\"exact\"` means exactly `argTypes.length`, and\n * `\"variadic\"` means at least `argTypes.length - 1` — which is Go's\n * gate for a variadic signature, always, since its fixed parameters are\n * every one but the last. A `minimum` field on either would be a second\n * copy of a number the array carries, and the copy is what drifts:\n * `minimum` survives here only on `\"alternating\"`, where `argTypes` is\n * a cycle length rather than a parameter count and the two are\n * genuinely unrelated.\n *\n * [LAW:one-type-per-behavior] The three kinds are exactly the three\n * slot-lookup rules, so `makeSlotLookup` switches on this union and\n * nothing else. Folding the former `argTypePattern` field in here is\n * what makes \"exact yet alternating\" unrepresentable rather than merely\n * unused.\n *\n * There is deliberately no `between`/optional-trailing kind: Go's own\n * `text/template` and `sprig` have no notion of an optional parameter,\n * so every signature is fixed-arity or variadic. That every declaration\n * here matches the Go function it mirrors is not a claim — it is\n * checked by `go-arity.test.ts` against `go-arity.fixture.json`, which\n * `conformance/gen/arity` extracts from Go. Do not add a fourth kind\n * without a Go signature that demands it.\n */\nexport type Arity =\n /** Exactly `argTypes.length` arguments; each slot is declared once. */\n | { readonly kind: \"exact\" }\n /**\n * At least `argTypes.length - 1` arguments — Go's own gate for a\n * variadic signature, whose fixed parameters are every one but the\n * last. The trailing `argTypes` entry is that last, repeating\n * parameter, so every argument past the declared ones validates\n * against `argTypes[argTypes.length - 1]`.\n *\n * Declare one slot per Go parameter, the repeating one last: `eq` is\n * `func(reflect.Value, ...reflect.Value)`, so it declares two\n * `\"comparable\"` slots and requires one. Collapsing those to a single\n * slot would render the same verdicts today and quietly lose the\n * minimum.\n */\n | { readonly kind: \"variadic\" }\n /**\n * At least `minimum` arguments — the one kind that needs the number,\n * because `argTypes` below is a cycle length, not a parameter count.\n * With `argTypes` read as a *cycle*:\n * the slot for argument `i` is `argTypes[i % argTypes.length]`. Used\n * by `dict`'s `string, value, string, value, …` kv pairing — without\n * it the gate cannot distinguish even-index keys (must be string)\n * from odd-index values (anything), and the body would re-validate\n * per key, splitting `[LAW:single-enforcer]` across two layers.\n */\n | { readonly kind: \"alternating\"; readonly minimum: number };\n\nexport interface TemplateFunc {\n /**\n * The function body. Parameter types are *contravariant-bottom*\n * (`never[]`) so any concrete signature is assignable here — write\n * `fn: (s: string, n: number) => …` if that's what the func wants,\n * and rely on `argTypes` + `enforceArgTypes` to validate at runtime.\n *\n * [LAW:single-enforcer] Param-type validation lives at the dispatch\n * site (`enforceArgTypes`). The compile-time signature does not\n * duplicate that gate — it stays out of the way so consumer\n * implementations can declare the precise types they expect.\n *\n * The signature is *not* a source of arity: `fn.length` stops at the\n * first rest parameter and lies about several registrations (`min`,\n * `max`, `mul` and friends report 0 while Go requires 1). Arity comes\n * from `arity`, never from here.\n *\n * Return `marked(value, ...tokens)` to mark the call; the template sees\n * `value`, and the tokens reach `EngineConfig.emitted` / `decided`\n * wherever the output depends on it.\n */\n readonly fn: (...args: never[]) => unknown;\n /**\n * Declared positional parameter types. Required.\n *\n * How the slots cover the supplied arguments is `arity`'s job: an\n * `\"exact\"` func declares one entry per parameter, a `\"variadic\"` one\n * declares the repeating slot last, and an `\"alternating\"` one\n * declares the cycle.\n *\n * The pipe-fed last argument is appended to the positional list\n * before validation, so it is checked against the slot its final\n * position selects.\n */\n readonly argTypes: readonly ArgType[];\n readonly returnType?: ArgType;\n /**\n * Argument count. Required — a func whose arity is undeclared is a\n * func the gate cannot check, and defaulting to a permissive value\n * would hide exactly the registrations that most need the\n * declaration.\n *\n * Minimums mirror Go's *arity gate*, which is not always the same as\n * the function body's own requirement; see `eq` and `dig`.\n */\n readonly arity: Arity;\n /**\n * `true` when the body stores anything it was handed — in place in an\n * argument, as sprig `set` and `unset` do, or in a closure or module\n * variable a later call returns — or runs code it was handed, which may\n * store (`call`). Omitted: it does neither, which is true of nearly\n * every func.\n *\n * [LAW:types-are-the-program] Whether a call writes is a fact about the\n * func, so it is declared rather than assumed of every call. Where a\n * write lands is beyond what the engine can follow (an object read\n * later, a fragment already emitted, the host's data for the next\n * evaluation), so each call of a writing func reports its inputs'\n * marks through `EngineConfig.decided` as it runs. A body that writes\n * without declaring it reports late.\n */\n readonly writes?: true;\n}\n\nexport type FuncMap = Record<string, TemplateFunc>;\n\n/**\n * Everything the argument gate reads off a registration.\n *\n * [LAW:types-are-the-program] `argTypes` and `arity` answer one\n * question between them — which arguments are legal — and neither\n * answers it alone: `argTypes` says what each slot holds, `arity` says\n * how many slots there are and how they cover the supplied values.\n * Passing them as one value is what makes \"types without their arity\"\n * unrepresentable at the gate; when they were two positional\n * parameters, the second one defaulted and the count check could be\n * skipped by omission.\n */\nexport type ArgSpec = Pick<TemplateFunc, \"argTypes\" | \"arity\">;\n\n/**\n * Policy for missing field/map-key access — mirrors Go's\n * `text/template` `Option(\"missingkey=...\")`:\n *\n * - `\"default\"` (Go's `missingkey=default` / `missingkey=invalid`):\n * missing access yields `undefined`; emitted output is `<no value>`.\n * This is the engine default, matching Go's `text/template` default.\n * - `\"zero\"` (Go's `missingkey=zero`): in Go, returns the zero value of\n * the map's element type. JavaScript has no static value-type info,\n * so the runtime cannot synthesize a typed zero — the option is\n * accepted for API parity and behaves identically to `\"default\"`.\n * Use sprig `default` (`{{ .x | default \"\" }}`) when you want a\n * typed-zero substitute at the use site.\n * - `\"error\"` (Go's `missingkey=error`): missing access throws\n * `MissingFieldError`. Use this in environments where a missing key\n * indicates a scope-construction bug that should fail loud.\n */\nexport type MissingKeyOption = \"default\" | \"zero\" | \"error\";\n\n// [LAW:one-source-of-truth] The valid-set lives next to the type it\n// validates. The `Engine` constructor's boundary check consumes this;\n// no other site decides what counts as a valid policy value.\nconst VALID_MISSING_KEYS: ReadonlySet<MissingKeyOption> = new Set([\"default\", \"zero\", \"error\"]);\n\n// [LAW:types-are-the-program] The TS union forbids invalid values at\n// compile time; this is the JS-boundary mirror of the same theorem so\n// a typo from a JS caller (or an `as`-cast TS caller) fails loud at\n// construct time instead of silently disabling the policy.\nfunction validateMissingKey(value: MissingKeyOption | undefined): MissingKeyOption {\n if (value === undefined) return \"default\";\n if (VALID_MISSING_KEYS.has(value)) return value;\n throw new Error(\n `EngineConfig.missingKey: expected \"default\" | \"zero\" | \"error\", got ${describeBoundaryValue(value)}`,\n );\n}\n\n// [LAW:one-type-per-behavior] Shared safe formatter for boundary\n// diagnostics — every validator that rejects an out-of-shape JS value\n// uses this to describe what was actually passed. `JSON.stringify`\n// would have thrown on bigint or cyclic inputs, swapping the intended\n// diagnostic for an unrelated TypeError; the diagnostic must survive\n// any value the caller might mis-pass.\nfunction describeBoundaryValue(value: unknown): string {\n if (typeof value === \"string\") return JSON.stringify(value);\n if (value === null) return \"null\";\n if (value === undefined) return \"undefined\";\n if (typeof value === \"bigint\") return `${value}n`;\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n if (typeof value === \"symbol\") return value.toString();\n if (typeof value === \"function\") return \"[Function]\";\n return `[${typeof value}]`;\n}\n\n// [LAW:one-source-of-truth] `Delims` is canonical in `parser/lexer.ts`\n// (the lowest layer that consumes it). Re-exported here so consumers\n// reaching `EngineConfig` see the type in the same module without\n// needing to import from internal paths.\nexport type { Delims };\n\n// [LAW:types-are-the-program] The TS interface is the canonical shape;\n// this is the JS-boundary mirror — a typo'd or partially-set object\n// from a JS caller (or an `as`-cast TS caller) fails loud at construct\n// time instead of producing pathological tokenization later. Returns\n// `undefined` for \"no override\" so the parser falls back to its own\n// default and we never need a separate \"are delims set\" boolean.\nfunction validateDelims(value: Delims | undefined): Delims | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"object\" || value === null) {\n throw new Error(\n `EngineConfig.delims: expected { left, right } object, got ${describeBoundaryValue(value)}`,\n );\n }\n if (typeof value.left !== \"string\" || value.left.length === 0) {\n throw new Error(\n `EngineConfig.delims.left: expected non-empty string, got ${describeBoundaryValue(value.left)}`,\n );\n }\n if (typeof value.right !== \"string\" || value.right.length === 0) {\n throw new Error(\n `EngineConfig.delims.right: expected non-empty string, got ${describeBoundaryValue(value.right)}`,\n );\n }\n return { left: value.left, right: value.right };\n}\n\n// [LAW:types-are-the-program] The strongest theorem the gate needs is\n// that every registration's declared arity actually covers its declared\n// slots. TypeScript carries most of it — `arity` is required, and the\n// three kinds are a closed union — but not this last correlation: only\n// `\"exact\"` may declare zero slots. `\"variadic\"` reads its repeating\n// slot off the end of `argTypes`, so with none declared its minimum\n// derives to -1 and the gate accepts any count; `\"alternating\"` indexes\n// `i % argTypes.length`, so with none declared every slot lookup is\n// NaN. Both silently disable the gate for that func rather than failing\n// — [LAW:no-silent-failure] — which is why this is a construct-time\n// error and not a permissive fallback.\n//\n// Expressing it in the type would mean splitting `TemplateFunc` into a\n// union discriminated on `arity.kind`, with the variadic arm requiring\n// a non-empty `argTypes` tuple. That correlation does not survive the\n// `Pick` the gate takes (`ArgSpec`), so it would buy a compile-time\n// check for registrations and lose one at the gate. This is the same\n// JS-boundary mirror `validateMissingKey` and `validateDelims` are.\n//\n// The predicate is a returning switch rather than `kind !== \"exact\"` so\n// that adding a fourth `Arity` kind fails to compile until someone says\n// which side of this line it falls on.\nfunction readsSlotsFromArgTypes(arity: Arity): boolean {\n switch (arity.kind) {\n case \"exact\":\n return false;\n case \"variadic\":\n return true;\n case \"alternating\":\n return true;\n }\n}\n\n// [LAW:parse-dont-validate] The one checkpoint for a declaration. It\n// runs at construct time, which is the only moment at which a malformed\n// `TemplateFunc` can be reported against the line that wrote it, and it\n// fails loudly — so the gate downstream may assume every `ArgSpec` it\n// reads is well-formed and never re-checks one.\n//\n// `argTypes` membership is checked here rather than at the gate for the\n// same reason arity well-formedness is (template-arity-n2j.7ve). A\n// declaration that casts past `ArgType` (`[\"number\" as ArgType]`, a\n// stale registration, a JS caller with no compile-time guard) used to\n// construct cleanly and then raw-throw `Error(\"invalid ArgType: number\")`\n// out of `matchesArgType` mid-render: outside the TemplateError\n// hierarchy, with no position, no caret, and no func name — from inside\n// the gate, which is exactly the failure shape this epic exists to\n// remove. The kind a slot declares is a fact about the *declaration*,\n// knowable before any template is parsed, so this is where it is known.\n//\n// The `default` arms in `matchesArgType` and `humanArgType` stay: their\n// `never` assignment is the compile-time guardrail that forces an arm\n// per kind, and their throw is now unreachable by construction rather\n// than a live path a consumer can reach.\nfunction validateArgSpecs(funcs: FuncMap): FuncMap {\n const legal: ReadonlySet<string> = new Set(ARG_TYPES);\n for (const [name, fn] of Object.entries(funcs)) {\n fn.argTypes.forEach((declared, slot) => {\n if (!legal.has(declared)) {\n throw new Error(\n `EngineConfig.funcs.${name}: argTypes[${slot}] is ${JSON.stringify(declared)}, ` +\n `which is not an ArgType; declare one of ${ARG_TYPES.join(\", \")}`,\n );\n }\n });\n if (readsSlotsFromArgTypes(fn.arity) && fn.argTypes.length === 0) {\n throw new Error(\n `EngineConfig.funcs.${name}: arity ${JSON.stringify(fn.arity.kind)} needs at ` +\n `least one declared argType (it reads its repeating slot from the end of ` +\n `argTypes); declare the slots the Go signature has, or use { kind: \"exact\" }`,\n );\n }\n if (\n fn.arity.kind === \"alternating\" &&\n (!Number.isSafeInteger(fn.arity.minimum) || fn.arity.minimum < 0)\n ) {\n throw new Error(\n `EngineConfig.funcs.${name}: arity \"alternating\" needs a non-negative integer ` +\n `minimum, got ${String(fn.arity.minimum)}; the gate rejects every count below ` +\n `it, so a negative or non-finite minimum would disable the lower bound`,\n );\n }\n }\n return funcs;\n}\n\n// [LAW:types-are-the-program] `isT` may be left at its string default only\n// when T is a string; any other T — an object, or `string | Frag` whose\n// funcs return fragments — must name its fragments, or they print as\n// `map[…]` text. The compiler is the one enforcer.\nexport type EngineConfig<T> = EngineConfigFields<T> &\n ([T] extends [string] ? unknown : { readonly isT: (value: unknown) => value is T });\n\ninterface EngineConfigFields<T> {\n /** Convert a text literal (or string-returning function result) into T. */\n readonly fromString: (s: string) => T;\n /**\n * Flatten a T (or other engine-managed value) into a string.\n *\n * [LAW:single-enforcer] Dual of `fromString`: one place owns the\n * string→T direction, this owns the T→string direction. Built-ins\n * registered against the `\"stringifiable\"` ArgType call this for each\n * T they print, nested ones included; every non-T value prints as Go's\n * `%v` and never reaches it.\n *\n * Default behaviour: passes through any value that is already a\n * `typeof \"string\"` and throws `TypeMismatchError` for everything\n * else. That makes the `T = string` case (consumer set\n * `fromString: (s) => s`) work out of the box, while a non-string T\n * configured without a `toString` errors loudly the first time a\n * `\"stringifiable\"` slot encounters a T value — never silently.\n */\n readonly toString?: (value: T) => string;\n /**\n * Is this value a T? At the output stream a T is pushed as itself and\n * anything else is printed as Go prints it (`[a b]`, `map[k:v …]`, a\n * Date's own String); at a call, a `\"T\"` ArgType slot accepts exactly\n * what this says.\n *\n * [LAW:single-enforcer] The one predicate for what is a T. At the output\n * stream a string, number, boolean or nil is lifted through `fromString`\n * before it is asked, so it decides only for structured values.\n * Default: a string — the T the default `fromString`/`toString` pair\n * supports — so a plain object prints `map[k:v …]` as Go's `%v` does.\n * Required by the type whenever T is not a string, e.g.\n * `isT: (v) => v instanceof RichText`.\n */\n readonly isT?: (value: unknown) => value is T;\n /**\n * PRNG source for `sprigRandom` functions. Defaults to `Math.random`.\n * Supply a seeded generator for reproducible templates.\n *\n * [LAW:single-enforcer] One config field owns the randomness source;\n * pass this to `sprigRandom(config.random)` when composing a full\n * sprig engine so the seam is wired once, not per-function.\n */\n readonly random?: () => number;\n /**\n * Clock source for `sprigDatetime` functions. Defaults to\n * `() => new Date()`. Supply a frozen clock for deterministic test\n * output.\n *\n * [LAW:single-enforcer] One config field owns the time source; pass\n * this to `sprigDatetime(config.clock)` when composing a full sprig\n * engine so the seam is wired once, not per-function.\n */\n readonly clock?: () => Date;\n /**\n * Policy for missing field / map-key access. Defaults to `\"default\"`\n * (matching Go's `text/template` default — silent `<no value>`). See\n * `MissingKeyOption` for the full enum semantics.\n *\n * [LAW:single-enforcer] One config field owns the policy; the\n * `resolveFieldChain` gate is the only site that consults it.\n * [LAW:dataflow-not-control-flow] The policy is data flowing into a\n * fixed gate, not a branch sprinkled across accessors.\n */\n readonly missingKey?: MissingKeyOption;\n /**\n * Optional override for the template action delimiters. Mirrors\n * Go's `text/template.Template.Delims(left, right)`. Both sides\n * are required if specified — neither may be empty.\n *\n * [LAW:single-enforcer] Validated once at construct time and\n * threaded into the parser as immutable data; no re-validation\n * along the call chain.\n * [LAW:dataflow-not-control-flow] The delim pair is data flowing\n * into the fixed lexer state machine — no new modes, no new\n * branches, just different constant values seeded at construction.\n */\n readonly delims?: Delims;\n /** Optional registry of named functions usable in pipelines. */\n readonly funcs?: FuncMap;\n /**\n * Every `T` the template emits passes through here with the marks it\n * depends on (see `marked`), and the return is what reaches the output.\n * The marks are those of every value the emitting action read and of\n * every `if`/`with`/`range` arm it sits in; a mark is reported early,\n * never late, and a mark bound somewhere nobody reads is not reported.\n * Called for every emission, an empty set included. Default: returns\n * `value` unchanged.\n */\n readonly emitted?: (value: T, marks: ReadonlySet<unknown>) => T;\n /**\n * Called once each time an `if`/`with`/`range` pipe is evaluated,\n * before either arm runs — so a decision whose taken arm emits nothing\n * (or which has no arm to take) still says what it depended on. Also\n * called for each call of a func that declares `writes` (the output may\n * show that write later with no cell to say it on), and for each action\n * or control pipe that throws. Every call carries the marks of the\n * values read and of every `if`/`with`/`range` arm it sits in.\n * Default: does nothing.\n */\n readonly decided?: (marks: ReadonlySet<unknown>) => void;\n}\n\n// Per-evaluate context. Threaded through every internal method.\n// The bodies a control construct chooses among.\ninterface Arms {\n readonly list: ListNode;\n readonly elseList?: ListNode;\n}\n\ninterface EvalContext<T> {\n // Where a fragment goes once produced. The root evaluation's sink\n // pushes through `emitted` onto the output; `include`'s sink captures\n // the fragment instead, because a captured fragment never reaches the\n // output — the string it becomes does.\n readonly emit: (value: T, marks: Marks) => void;\n // Where a decision's marks go. The root's sink is the engine's `decided`;\n // `include`'s also joins them to its result, which hangs on every\n // decision its body made, an arm that emitted nothing included.\n readonly decided: (marks: Marks) => void;\n readonly defines: Defines;\n readonly source: string | undefined;\n // The control-pipe marks of every arm being evaluated: an emission\n // here depends on the branches that led to it.\n readonly marks: Marks;\n // How many define bodies enclose this one, for the error that names a\n // recursion too deep for the host's stack.\n readonly depth: number;\n}\n\n// [LAW:types-are-the-program] Internal control-flow sentinels for\n// `{{break}}` / `{{continue}}`. They are NOT user-facing errors —\n// `TemplateError` deliberately is not their base — and they never\n// escape `evalRange`: the parser guarantees (via rangeDepth) that\n// every Break/Continue node is lexically inside a Range body, and\n// the range body is the only thrower-and-catcher of these. A\n// reference-identity check at the catch site is the strongest\n// possible discriminator: no string matching, no error-message\n// drift, no risk of swallowing user errors. See [LAW:single-enforcer]\n// — these constants are the one source of truth for the signal.\nconst BREAK_SIGNAL = Object.freeze({ kind: \"break\" as const });\nconst CONTINUE_SIGNAL = Object.freeze({ kind: \"continue\" as const });\n\n// [LAW:dataflow-not-control-flow] Pipeline-fed value, structurally\n// distinguished from absence. Replaces an earlier `unknown` parameter\n// where `undefined` was overloaded to mean both \"no pipe\" and \"pipe of\n// undefined\" — a sentinel collision that produced arity-mismatched\n// calls when a function legitimately returned `undefined`. The\n// discriminator now drives the append decision; the value (including\n// `undefined`) flows through unchanged.\ntype Piped = { readonly kind: \"none\" } | { readonly kind: \"value\"; readonly value: unknown };\n\nconst NO_PIPE: Piped = { kind: \"none\" };\n\n// The one wording for a by-name render whose name nothing defines, whether\n// a template or the host asked.\nconst notDefined = (name: string): string => `template ${JSON.stringify(name)} is not defined`;\n\n/**\n * A parsed template bound to its parent engine.\n *\n * Template instances are immutable — `evaluate(scope)` may be called\n * any number of times with different scopes, matching the\n * \"parse-once-eval-many\" invariant from the epic spec. The `source`\n * property exposes the original template text for debugging /\n * diagnostics.\n *\n * Construct via `engine.parse(src)`. The constructor is private so\n * the public type surface need not reference internal AST shapes.\n */\n// [LAW:one-source-of-truth] `internalCreateTemplate` is the *only*\n// callable factory for Template. Captured from the static block below\n// so that Engine (and only Engine) can construct Templates without\n// exposing the parsed AST shape on the public type surface.\nlet internalCreateTemplate: <U>(\n source: string,\n evaluate: (scope: unknown) => U[],\n evaluateDefine: (name: string, scope: unknown) => U[],\n defines: Defines,\n referencedFunctions: ReadonlySet<string>,\n referencedCalls: readonly ReferencedCall[],\n) => Template<U>;\n\n// [LAW:types-are-the-program] One command-head call site projected to the facts\n// a static consumer can act on: the callee name and its positional arguments,\n// with each LITERAL string argument decoded and every non-literal argument\n// (field, pipeline, bool, number, …) reported as `null` so positions are\n// preserved. This is the argument-aware companion to `referencedFunctions`:\n// where that answers \"is X called?\", this answers \"with what literal strings?\".\nexport interface ReferencedCall {\n /** The function name at the head of the command. */\n readonly name: string;\n /**\n * The positional arguments after the head. A literal string argument is its\n * decoded value; any non-string-literal argument is `null` (its value is only\n * known at evaluation time). Indices match the call site, so `args[0]` is the\n * first argument regardless of the kinds in between.\n *\n * [LAW:one-source-of-truth] A derived view of {@link argExprs} — the\n * string-literal projection kept for consumers that only read literal\n * string slots. `args[i]` is `argExprs[i].value` when that is a literal\n * string, `null` otherwise.\n */\n readonly args: readonly (string | null)[];\n /**\n * The positional arguments after the head, each statically projected to a\n * {@link ReferencedArg}. Indices match the call site (`argExprs[0]` is the\n * first argument), and `argExprs.length === args.length`.\n */\n readonly argExprs: readonly ReferencedArg[];\n}\n\n/**\n * A scalar value statically decodable from a literal argument node. Numbers\n * carry the same JS value evaluation would produce (safe ints as `number`,\n * larger ints as `bigint`); `null` is the projection of the `nil` literal.\n */\nexport type ReferencedLiteral = string | number | bigint | boolean | null;\n\n// [LAW:types-are-the-program] The total static projection of one call\n// argument. Three shapes cover the whole grammar: a literal scalar whose\n// value is known at parse time; a nested call `(f a b …)` projected\n// recursively so a consumer can read e.g. `(dict \"k\" \"v\")` option args\n// without evaluating; and `dynamic` for everything whose value only exists\n// at eval time (fields, variables, pipelines, function-valued idents, …).\n// A value is never guessed: anything not provably literal is `dynamic`\n// [LAW:no-silent-failure].\nexport type ReferencedArg =\n | { readonly kind: \"literal\"; readonly value: ReferencedLiteral }\n | { readonly kind: \"call\"; readonly name: string; readonly args: readonly ReferencedArg[] }\n | { readonly kind: \"dynamic\" };\n\nexport class Template<T> {\n readonly source: string;\n private readonly _evaluate: (scope: unknown) => T[];\n private readonly _evaluateDefine: (name: string, scope: unknown) => T[];\n private readonly _defines: Defines;\n // [LAW:types-are-the-program] The set of FuncMap names this template\n // references, computed ONCE from the parsed AST at construction. A name here\n // is a function the template *can* call (it is the head of some command, or\n // appears as a function-valued argument); whether a given evaluation reaches\n // it is a runtime question this static fact does not answer. Frozen so the\n // exposed set cannot be mutated by a caller.\n private readonly _referencedFunctions: ReadonlySet<string>;\n // [LAW:types-are-the-program] Every command-head call with its literal string\n // args, computed ONCE from the same parsed AST. A superset of the information\n // in `_referencedFunctions` (every call's name is also a referenced function),\n // exposed separately so the cheaper name-only query stays a `Set`.\n private readonly _referencedCalls: readonly ReferencedCall[];\n\n private constructor(\n source: string,\n evaluate: (scope: unknown) => T[],\n evaluateDefine: (name: string, scope: unknown) => T[],\n defines: Defines,\n referencedFunctions: ReadonlySet<string>,\n referencedCalls: readonly ReferencedCall[],\n ) {\n this.source = source;\n this._evaluate = evaluate;\n this._evaluateDefine = evaluateDefine;\n this._defines = defines;\n this._referencedFunctions = referencedFunctions;\n this._referencedCalls = referencedCalls;\n }\n\n static {\n internalCreateTemplate = <U>(\n source: string,\n evaluate: (scope: unknown) => U[],\n evaluateDefine: (name: string, scope: unknown) => U[],\n defines: Defines,\n referencedFunctions: ReadonlySet<string>,\n referencedCalls: readonly ReferencedCall[],\n ) =>\n new Template(source, evaluate, evaluateDefine, defines, referencedFunctions, referencedCalls);\n }\n\n /**\n * The named sub-templates this template can invoke — its own `{{define}}`s\n * chained onto whatever it inherited at parse. Pass it to `engine.parse` as\n * `inherit` to let another template invoke the same set without re-parsing\n * (and re-allocating) it: the idiom for a shared helper preamble is\n * `const helpers = engine.parse(preamble).defines()` once, then\n * `engine.parse(src, helpers)` per template. Opaque: the AST inside is not\n * part of the public surface.\n */\n defines(): Defines {\n return this._defines;\n }\n\n evaluate(scope: unknown): T[] {\n return this._evaluate(scope);\n }\n\n /**\n * Render one named sub-template — any `{{ define }}` in {@link defines}, its\n * own or inherited — with `scope` as its dot and `$`, as Go's\n * `ExecuteTemplate` does. The output is the same `T[]` a whole-template\n * {@link evaluate} produces, through the same `emitted` / `decided` hooks.\n */\n evaluateDefine(name: string, scope: unknown): T[] {\n return this._evaluateDefine(name, scope);\n }\n\n /**\n * The FuncMap function names this template references — every identifier that\n * names a function in this parse: the template body and its own `{{ define }}`\n * blocks. A set inherited at parse (see {@link Template.defines}) is described\n * by the template that parsed it, not here.\n *\n * This is a STATIC fact derived from the parsed AST, not an execution trace:\n * a name in the set is a function the template *can* invoke; a name absent\n * from the set is one it provably never invokes. Use it to ask \"does this\n * template use helper X?\" without evaluating it (e.g. to discover which\n * templates depend on a feature func) — robust where a source-text scan is\n * not, because it sees through whitespace, pipelines, and field/string\n * lookalikes.\n *\n * Built-in operators registered for every engine (`and`, `eq`, `index`,\n * `printf`, …) are reported the same as consumer funcs — a referenced name is\n * a referenced name regardless of who registered it.\n */\n referencedFunctions(): ReadonlySet<string> {\n return this._referencedFunctions;\n }\n\n /**\n * Every command-head call in this parse — the template body and its own\n * `{{ define }}` blocks, never an inherited set — in preorder, each paired with its positional arguments projected to literal\n * strings (a non-string-literal argument is reported as `null`, preserving\n * argument positions).\n *\n * Like {@link referencedFunctions} this is a STATIC fact from the parsed AST,\n * not an execution trace. Use it when \"is X called?\" is not enough and you\n * need the literal arguments a call was written with — e.g. to discover that a\n * template contains `{{ menu \"applyTheme\" \"themePage\" }}` and read its first\n * argument without evaluating the template. Each call's `argExprs` carries the\n * full {@link ReferencedArg} projection (scalar literals, nested literal calls\n * like `(dict \"k\" \"v\")`, `dynamic` for eval-time values); `args` is its\n * string-literal-only view. Calls whose head is not a bare function\n * identifier (e.g. a field invoked via `call`) are not reported here; their\n * names still appear in {@link referencedFunctions}.\n */\n referencedCalls(): readonly ReferencedCall[] {\n return this._referencedCalls;\n }\n}\n\n// [LAW:single-enforcer] The one place \"which functions does this AST reference\"\n// is computed — a single preorder walk (the shared traversal helper) over the\n// root body and every `{{ define }}` body. In go-template's grammar every\n// IdentifierNode names a function (bare `true`/`nil`/numbers parse to their own\n// node kinds), whether it is a command head (`{{ f x }}`) or a function-valued\n// argument (`{{ call .x f }}`), so collecting every Identifier is exactly the\n// set of referenced functions — no positional special-casing.\nfunction collectReferencedFunctions(parsed: ParseResult): ReadonlySet<string> {\n const names = new Set<string>();\n const collect = (root: Node): void => {\n walk(root, (node) => {\n if (node.type === \"Identifier\") names.add(node.ident);\n });\n };\n collect(parsed.root);\n for (const entry of parsed.ownDefines.values()) collect(entry.list);\n return names;\n}\n\nconst DYNAMIC_ARG: ReferencedArg = { kind: \"dynamic\" };\n\n// [LAW:single-enforcer] The one place an argument node becomes a\n// ReferencedArg. Literal leaves decode to the SAME JS value evaluation\n// produces — strings/bools directly, numbers via the shared `numberValue`\n// (complex literals have no scalar carrier, so they stay `dynamic` rather\n// than invent one), `nil` as `null`. A parenthesised argument parses as a\n// PipeNode; only the trivial pipe — no declarations, exactly one command,\n// an Identifier head — is a statically readable nested call `(f a b …)`,\n// projected recursively. Every other shape is an eval-time value: `dynamic`.\nfunction projectArg(node: Node): ReferencedArg {\n switch (node.type) {\n case \"String\":\n return { kind: \"literal\", value: node.value };\n case \"Bool\":\n return { kind: \"literal\", value: node.value };\n case \"Nil\":\n return { kind: \"literal\", value: null };\n case \"Number\": {\n const value = numberValue(node);\n return typeof value === \"number\" || typeof value === \"bigint\"\n ? { kind: \"literal\", value }\n : DYNAMIC_ARG;\n }\n case \"Pipe\": {\n if (node.decls.length !== 0 || node.cmds.length !== 1) return DYNAMIC_ARG;\n const cmd = node.cmds[0];\n if (cmd === undefined) return DYNAMIC_ARG;\n const head = cmd.args[0];\n if (head === undefined || head.type !== \"Identifier\") return DYNAMIC_ARG;\n return { kind: \"call\", name: head.ident, args: cmd.args.slice(1).map(projectArg) };\n }\n default:\n return DYNAMIC_ARG;\n }\n}\n\n// [LAW:single-enforcer] The one place \"which command-head calls, with what\n// literal args\" is computed — the same preorder walk as\n// `collectReferencedFunctions`, over the root body and every `{{ define }}`. A\n// CommandNode whose first arg is an Identifier is a call of that function; the\n// remaining args are projected via `projectArg`, preserving positions, and the\n// legacy string-only `args` view is derived from that projection\n// [LAW:one-source-of-truth]. Pipeline stages (`{{ x | f }}`) parse as Commands\n// too, so `f` is reported with the args written at its own stage (the piped\n// value is prepended at eval and is not an AST argument) — consistent with how\n// the head/args split is defined here.\nfunction collectReferencedCalls(parsed: ParseResult): readonly ReferencedCall[] {\n const calls: ReferencedCall[] = [];\n const collect = (root: Node): void => {\n walk(root, (node) => {\n if (node.type !== \"Command\") return;\n const head = node.args[0];\n if (head === undefined || head.type !== \"Identifier\") return;\n const argExprs = node.args.slice(1).map(projectArg);\n calls.push({\n name: head.ident,\n args: argExprs.map((arg) =>\n arg.kind === \"literal\" && typeof arg.value === \"string\" ? arg.value : null,\n ),\n argExprs,\n });\n });\n };\n collect(parsed.root);\n for (const entry of parsed.ownDefines.values()) collect(entry.list);\n return calls;\n}\n\nexport class Engine<T> {\n private readonly fromString: (s: string) => T;\n // [LAW:single-enforcer] Stored alongside `fromString` so the engine\n // owns both halves of the text↔T boundary. Threaded into\n // `enforceArgTypes` so `\"stringifiable\"` slots probe with the same\n // function that downstream func bodies will re-use to flatten.\n private readonly toString: (value: unknown) => string;\n private readonly isT: IsT;\n private readonly funcs: FuncMap;\n // [LAW:single-enforcer] One field, consulted only at `resolveFieldChain`.\n // [LAW:one-source-of-truth] Default is `\"default\"` so the engine\n // matches Go's `text/template` default (\"missingkey=default\" /\n // \"invalid\"). The conformance corpus is generated by Go's reference\n // implementation under that default; aligning the JS default keeps\n // byte-parity for any fixture exercising missing keys.\n private readonly missingKey: MissingKeyOption;\n // [LAW:single-enforcer] One field, threaded into the parser as\n // immutable data. `undefined` means \"use parser's defaults\" — we\n // never store a synthesized default here, so the engine can't\n // accidentally diverge from whatever the parser considers default.\n private readonly delims: Delims | undefined;\n // [LAW:dataflow-not-control-flow] Always called; an unconfigured hook is\n // the identity / no-op, so provenance is one path whether or not anyone\n // listens.\n private readonly emitted: (value: T, marks: Marks) => T;\n private readonly decided: (marks: Marks) => void;\n\n constructor(config: EngineConfig<T>) {\n this.fromString = config.fromString;\n // `toString` collides with `Object.prototype.toString`, so a plain\n // `config.toString ?? default` would silently bind the prototype\n // method when the consumer didn't pass anything. Check for an own\n // property explicitly so the fallback only fires for unconfigured\n // engines.\n const userToString = Object.hasOwn(config, \"toString\") ? config.toString : undefined;\n this.toString = (userToString ?? defaultToString) as (value: unknown) => string;\n // [LAW:no-defensive-null-guards] exception: trust boundary — the\n // EngineConfig flows in from JS callers (no compile-time guard) and\n // TS callers using `as` casts. A typo like `\"erro\"` would silently\n // degrade to default semantics and disable the strict policy a\n // caller asked for. Validate at construct time so the bad value\n // fails loud at the only place it can be detected.\n this.missingKey = validateMissingKey(config.missingKey);\n // [LAW:no-defensive-null-guards] exception: trust boundary. Same\n // rationale as `missingKey`: a typo'd or partially-set delims\n // object from a JS caller would otherwise produce baffling\n // tokenization at parse time. Fail loud at the only place the\n // mistake can be detected.\n this.delims = validateDelims(config.delims);\n this.isT = config.isT ?? DEFAULT_IS_T;\n this.emitted = config.emitted ?? ((value) => value);\n this.decided = config.decided ?? (() => {});\n // [LAW:single-enforcer] Built-ins live in one registry; consumer\n // funcs override on a per-name basis (this gives consumers an\n // escape hatch — desired).\n //\n // [LAW:parse-dont-validate] Arity well-formedness is checked once,\n // here, on the merged map — after overrides, so a consumer cannot\n // shadow a built-in with a malformed declaration. The gate then\n // derives counts from these declarations without re-checking them.\n this.funcs = validateArgSpecs({\n ...defaultBuiltins(this.toString, this.isT),\n ...(config.funcs ?? {}),\n });\n }\n\n /**\n * Parse a template source into a reusable Template handle.\n *\n * The returned Template is immutable; calling `evaluate(scope)` on\n * it any number of times with different scopes is safe and avoids\n * re-parsing.\n */\n parse(source: string, inherit?: Defines): Template<T> {\n const parsed = parseSource(source, this.delims, inherit);\n return internalCreateTemplate(\n parsed.source,\n (scope) =>\n this.evalParsed(parsed, scope, (root, ctx) => this.evalList(parsed.root, root, ctx)),\n (name, scope) => {\n // The call is the host's, at no place in any source. A name it\n // cannot find is the host's mistake, as Go's ExecuteTemplate returns\n // a plain error; the define itself runs as if called from its own\n // body, in the source that declared it.\n const entry = lookupDefine(parsed.defines, name);\n if (!entry) throw new Error(notDefined(name));\n return this.evalParsed(parsed, scope, (root, ctx) =>\n this.renderDefine(name, entry, root.dot, entry.list.pos, {\n ...ctx,\n source: entry.source,\n }),\n );\n },\n parsed.defines,\n collectReferencedFunctions(parsed),\n collectReferencedCalls(parsed),\n );\n }\n\n /**\n * Convenience sugar for `parse(src).evaluate.bind(template)`.\n *\n * Returns a closure that takes a scope and produces T[]. Useful when\n * the template is parsed once at module load and called many times.\n */\n compile(source: string): (scope: unknown) => T[] {\n const template = this.parse(source);\n return (scope: unknown) => template.evaluate(scope);\n }\n\n /**\n * Evaluate a parsed template against a scope value, producing T[].\n *\n * Accepts only Templates produced by `engine.parse(src)` so the\n * public type surface stays clear of internal AST shapes.\n */\n evaluate(template: Template<T>, scope: unknown): T[] {\n return template.evaluate(scope);\n }\n\n // [LAW:single-enforcer] All evaluation flows through here; the\n // Template closure built in `parse()` calls back into this method.\n private evalParsed(\n parsed: ParseResult,\n scope: unknown,\n body: (root: Scope, ctx: EvalContext<T>) => void,\n ): T[] {\n const out: T[] = [];\n const root = rootScope({ value: scope, marks: NO_MARKS });\n const ctx: EvalContext<T> = {\n emit: (value, marks) => out.push(this.emitted(value, marks)),\n decided: this.decided,\n defines: parsed.defines,\n source: parsed.source,\n marks: NO_MARKS,\n depth: 0,\n };\n body(root, ctx);\n return out;\n }\n\n // -------------------------------------------------------------------\n // Statement-level dispatch (output-producing nodes).\n // -------------------------------------------------------------------\n\n private evalList(node: ListNode, scope: Scope, ctx: EvalContext<T>): void {\n for (const child of node.nodes) {\n this.evalNode(child, scope, ctx);\n }\n }\n\n private evalNode(node: Node, scope: Scope, ctx: EvalContext<T>): void {\n switch (node.type) {\n case \"Text\":\n ctx.emit(this.fromString(node.text), ctx.marks);\n return;\n case \"Comment\":\n return;\n case \"Action\":\n // The whole action — pipe, lift, `emitted` — is one read, so a throw\n // anywhere in it reports what it had consumed.\n this.read(ctx, (reads) => {\n const value = this.evalPipe(node.pipe, scope, ctx, reads);\n // Per Go's spec, actions whose pipeline declares variables\n // (`{{ $x := pipe }}`) contribute no output — they're pure\n // assignment statements. Only assignment-free actions emit.\n if (node.pipe.decls.length === 0) {\n ctx.emit(this.lift(value, node.pos, ctx.source), unionMarks(reads, ctx.marks));\n }\n });\n return;\n case \"List\":\n this.evalList(node, scope, ctx);\n return;\n case \"If\":\n this.evalIf(node, scope, ctx);\n return;\n case \"Range\":\n this.evalRange(node, scope, ctx);\n return;\n case \"With\":\n this.evalWith(node, scope, ctx);\n return;\n case \"Break\":\n // [LAW:single-enforcer] The signal is the *only* mechanism;\n // the parser already guarantees we're lexically inside a\n // range, and `evalRange` is the only catcher.\n throw BREAK_SIGNAL;\n case \"Continue\":\n throw CONTINUE_SIGNAL;\n case \"Template\":\n this.evalTemplateInvoke(node, scope, ctx);\n return;\n case \"Block\":\n this.evalBlock(node, scope, ctx);\n return;\n case \"Pipe\":\n case \"Command\":\n case \"Identifier\":\n case \"Field\":\n case \"Variable\":\n case \"Chain\":\n case \"Dot\":\n case \"Nil\":\n case \"Bool\":\n case \"Number\":\n case \"String\":\n // These are *expression* nodes — they should never appear as\n // statements at list level. If one does, the AST is malformed.\n throw new EvalError(`unexpected ${node.type} at statement position`, node.pos, {\n source: ctx.source,\n });\n default:\n assertNever(node);\n }\n }\n\n // -------------------------------------------------------------------\n // Control flow.\n // -------------------------------------------------------------------\n\n private evalIf(\n node: { pipe: PipeNode; list: ListNode; elseList?: ListNode },\n scope: Scope,\n ctx: EvalContext<T>,\n ): void {\n const frame = constructFrame(scope);\n const { value: cond, reads } = this.read(ctx, (r) => this.evalPipe(node.pipe, frame, ctx, r));\n const arm = this.decide(reads, ctx, frame, node);\n if (isTruthy(cond)) {\n this.evalList(node.list, frame, arm);\n } else if (node.elseList) {\n this.evalList(node.elseList, frame, arm);\n }\n }\n\n private evalWith(\n node: { pipe: PipeNode; list: ListNode; elseList?: ListNode },\n scope: Scope,\n ctx: EvalContext<T>,\n ): void {\n const frame = constructFrame(scope);\n const { value, reads } = this.read(ctx, (r) => this.evalPipe(node.pipe, frame, ctx, r));\n const arm = this.decide(reads, ctx, frame, node);\n if (isTruthy(value)) {\n this.evalList(node.list, pushScope(frame, { value, marks: arm.marks }), arm);\n } else if (node.elseList) {\n this.evalList(node.elseList, frame, arm);\n }\n }\n\n private evalRange(\n node: { pipe: PipeNode; list: ListNode; elseList?: ListNode; pos: Pos },\n scope: Scope,\n ctx: EvalContext<T>,\n ): void {\n // The pipe's decls first bind to the ranged value as a whole (`=`\n // assigns the enclosing variables instead); each iteration then\n // rebinds them to its key and element, as Go's exec.go does.\n const rangeScope = constructFrame(scope);\n const { value, reads } = this.read(ctx, (r) => this.evalPipe(node.pipe, rangeScope, ctx, r));\n const arm = this.decide(reads, ctx, rangeScope, node);\n const { decls, isAssign } = node.pipe;\n\n const entries = enumerateForRange(value);\n // [LAW:single-enforcer] Two catch boundaries, exactly mirroring\n // Go's text/template `walkRange` (exec.go: two `defer recover`s\n // around the function and around `oneIteration`):\n //\n // - The *outer* try catches BREAK_SIGNAL only. It scopes both\n // the body-iteration loop *and* the `else` clause — so a\n // break inside a range's else (legal only when there is an\n // outer range, by the parser's `rangeDepth` rule) terminates\n // this range, not the outer one.\n //\n // - The *inner* per-iteration try catches CONTINUE_SIGNAL only.\n // Continue inside the body advances to the next iteration;\n // continue inside the else propagates up, because the outer\n // try doesn't catch it (matches Go: walkContinue is not\n // caught by walkRange's outer recover).\n //\n // Reference-identity catches — no message-string matching, so\n // unrelated user errors with similar shapes are never swallowed.\n try {\n if (entries.length === 0) {\n if (node.elseList) this.evalList(node.elseList, rangeScope, arm);\n return;\n }\n for (const [key, item] of entries) {\n // Every item, key and decl came out of the ranged value, so each\n // depends on what the range pipe read.\n // The last decl takes the element; a first of two takes the key.\n decls.forEach((decl, i) => {\n const binding = { value: i === decls.length - 1 ? item : key, marks: arm.marks };\n this.bind(rangeScope, decl, isAssign, binding, ctx);\n });\n const child = pushScope(rangeScope, { value: item, marks: arm.marks });\n try {\n this.evalList(node.list, child, arm);\n } catch (e) {\n if (e === CONTINUE_SIGNAL) continue;\n throw e;\n }\n }\n } catch (e) {\n if (e === BREAK_SIGNAL) return;\n throw e;\n }\n }\n\n private evalTemplateInvoke(\n node: { name: string; pipe?: PipeNode; pos: Pos },\n scope: Scope,\n ctx: EvalContext<T>,\n ): void {\n const entry = this.definedEntry(node.name, node.pos, ctx);\n const dot = this.invocationDot(node.pipe, scope, ctx);\n this.renderDefine(node.name, entry, dot, node.pos, ctx);\n }\n\n // [LAW:single-enforcer] The one lookup a by-name render inside a template\n // (`{{ template }}`, `include`) goes through, and so the one \"is not\n // defined\" error at a place in a source.\n private definedEntry(name: string, pos: Pos, ctx: EvalContext<T>): DefineEntry {\n const entry = lookupDefine(ctx.defines, name);\n if (!entry) {\n throw new EvalError(notDefined(name), pos, {\n source: ctx.source,\n });\n }\n return entry;\n }\n\n // [LAW:single-enforcer] Every define body runs here: `{{ template }}`,\n // `{{ block }}` and `include`.\n private renderDefine(\n name: string,\n body: { readonly list: ListNode; readonly source: string | undefined },\n dot: Binding,\n pos: Pos,\n ctx: EvalContext<T>,\n ): void {\n // A template body sees only its own `$`, never the caller's variables.\n // Its errors snippet against the source that declared it, which for an\n // inherited define is not this template's source.\n try {\n this.evalList(body.list, rootScope(dot), {\n ...ctx,\n source: body.source,\n depth: ctx.depth + 1,\n });\n } catch (e) {\n // Go caps nesting at 100000, deeper than any JS host's stack. The\n // recursion runs as deep as the host allows; the overflow becomes one\n // error naming the define, at the innermost frame that can build it,\n // and every frame above passes that `TemplateError` through.\n if (!isStackOverflow(e)) throw e;\n throw new EvalError(\n `template ${JSON.stringify(name)}: nesting depth ${ctx.depth + 1} exceeds the host's stack`,\n pos,\n { source: ctx.source, cause: e },\n );\n }\n }\n\n // Helm's `include`: the define renders into a capture instead of the\n // output, and its text is the call's value. What the body's fragments\n // depend on is what that value depends on, so their marks join `reads`.\n private include(\n registered: string,\n name: string,\n data: unknown,\n pos: Pos,\n ctx: EvalContext<T>,\n reads: Set<unknown>,\n ): string {\n const entry = this.definedEntry(name, pos, ctx);\n const parts: string[] = [];\n const emit = (value: T, marks: Marks): void => {\n // [LAW:single-enforcer] T→string is the engine's `toString`, here as\n // everywhere; a non-string T with none configured fails loudly.\n parts.push(this.toString(value));\n for (const mark of marks) reads.add(mark);\n };\n const decided = (marks: Marks): void => {\n ctx.decided(marks);\n for (const mark of marks) reads.add(mark);\n };\n // The dot depends on everything the call has read so far, its data\n // argument included: a mark is reported early, never late. A snapshot:\n // `reads` keeps growing as the body emits.\n const dot = { value: data, marks: new Set([...reads, ...ctx.marks]) };\n try {\n this.renderDefine(name, entry, dot, pos, { ...ctx, emit, decided });\n } catch (e) {\n // `error calling <registered name>` at the call, with the body's own error —\n // its class, position and source — as the cause. The text is the\n // innermost error's, not every level's again: a chain of includes\n // otherwise repeats itself once per level. A `fail` stays a\n // `FailError`, so the template's own refusal is told apart from the\n // engine's however many includes it passed through.\n if (!(e instanceof TemplateError)) throw e;\n const root = innermost(e);\n const Wrap = root instanceof FailError ? FailError : EvalError;\n throw new Wrap(`error calling ${registered} ${JSON.stringify(name)}: ${root.message}`, pos, {\n source: ctx.source,\n cause: e,\n });\n }\n return parts.join(\"\");\n }\n\n private evalBlock(\n node: { name: string; pipe: PipeNode; list: ListNode; pos: Pos },\n scope: Scope,\n ctx: EvalContext<T>,\n ): void {\n // A block invokes the same-named template if one is registered (or\n // that registration came from the block itself at parse time).\n // The dot for the block body is the pipe's value when present.\n const dot = this.invocationDot(node.pipe, scope, ctx);\n const entry = lookupDefine(ctx.defines, node.name) ?? { list: node.list, source: ctx.source };\n this.renderDefine(node.name, entry, dot, node.pos, ctx);\n }\n\n // [LAW:single-enforcer] The one place a control pipe's marks are\n // reported, and the one place they join what depends on the decision:\n // whichever arm runs — an empty one, or none — the decision has already\n // said what it read, and every variable an arm may `=`-assign carries it,\n // since its value after the construct hangs on which arm ran.\n private decide(reads: Marks, ctx: EvalContext<T>, frame: Scope, arms: Arms): EvalContext<T> {\n const marks = unionMarks(ctx.marks, reads);\n ctx.decided(marks);\n for (const name of this.assignedIn(arms)) markVar(frame, name, marks);\n return { ...ctx, marks };\n }\n\n // The names any `=` in a construct's arms assigns, nested constructs\n // included; fixed by the AST, so found once per construct.\n private readonly assigned = new WeakMap<ListNode, readonly string[]>();\n private assignedIn(arms: Arms): readonly string[] {\n const cached = this.assigned.get(arms.list);\n if (cached !== undefined) return cached;\n const names = new Set<string>();\n const collect = (n: Node): void => {\n if (n.type === \"Pipe\" && n.isAssign) for (const d of n.decls) names.add(d.idents[0] ?? \"$\");\n };\n for (const list of [arms.list, arms.elseList]) if (list) walk(list, collect);\n const found = [...names];\n this.assigned.set(arms.list, found);\n return found;\n }\n\n // The dot a `template`/`block` invocation pushes: the pipe's value with\n // what it depends on, or, with no pipe, Go's nil data.\n private invocationDot(pipe: PipeNode | undefined, scope: Scope, ctx: EvalContext<T>): Binding {\n const { value, reads } = this.read(ctx, (r) =>\n pipe ? this.evalPipe(pipe, scope, ctx, r) : null,\n );\n return { value, marks: unionMarks(reads, ctx.marks) };\n }\n\n // [LAW:single-enforcer] Every set of reads starts here, and so does the\n // one guarantee for a pipe that throws: the error the host shows\n // instead of output may clear when a mark it read changes, and with no\n // output there is no cell to say so on, so its reads go to `decided`.\n private read(\n ctx: EvalContext<T>,\n evaluate: (reads: Set<unknown>) => unknown,\n ): { readonly value: unknown; readonly reads: Marks } {\n const reads = new Set<unknown>();\n try {\n return { value: evaluate(reads), reads };\n } catch (e) {\n ctx.decided(unionMarks(reads, ctx.marks));\n throw e;\n }\n }\n\n // -------------------------------------------------------------------\n // Expression-level dispatch (value-producing).\n // -------------------------------------------------------------------\n\n // `reads` receives the pipe's provenance: the marks its value depends\n // on. The pipe collects its own inputs — each command's arguments, the\n // value piped into it, the carrier its call returns — so a call's writes\n // depend on what its pipe consumed up to that call, not on what an\n // enclosing pipe read beside it.\n private evalPipe(\n pipe: PipeNode,\n scope: Scope,\n ctx: EvalContext<T>,\n reads: Set<unknown>,\n ): unknown {\n if (pipe.cmds.length === 0) {\n throw new EvalError(\"empty pipeline\", pipe.pos, { source: ctx.source });\n }\n const inputs = new Set<unknown>();\n let value: unknown;\n // The merge runs on every path, so a pipe that throws still hands\n // `read` what it had consumed when it failed.\n try {\n value = this.evalCommand(pipe.cmds[0] as CommandNode, scope, ctx, NO_PIPE, inputs);\n for (let i = 1; i < pipe.cmds.length; i++) {\n const next = pipe.cmds[i] as CommandNode;\n value = this.evalCommand(next, scope, ctx, { kind: \"value\", value }, inputs);\n }\n } finally {\n for (const mark of inputs) reads.add(mark);\n }\n\n // Apply variable declarations / assignments after the pipe is\n // fully evaluated; `evalRange` rebinds them per iteration.\n for (const decl of pipe.decls) {\n this.bind(scope, decl, pipe.isAssign, { value, marks: unionMarks(inputs, ctx.marks) }, ctx);\n }\n return value;\n }\n\n // [LAW:single-enforcer] The one place a decl binds: `:=` declares in\n // `scope`'s own frame, `=` overwrites the nearest frame that declared\n // the name and refuses a name no frame declared.\n private bind(\n scope: Scope,\n decl: VariableNode,\n isAssign: boolean,\n binding: Binding,\n ctx: EvalContext<T>,\n ): void {\n const name = decl.idents[0] ?? \"$\";\n if (!isAssign) {\n declareVar(scope, name, binding);\n } else if (!assignVar(scope, name, binding)) {\n throw undefinedVariable(name, decl.pos, ctx);\n }\n }\n\n private evalCommand(\n cmd: CommandNode,\n scope: Scope,\n ctx: EvalContext<T>,\n piped: Piped,\n reads: Set<unknown>,\n ): unknown {\n if (cmd.args.length === 0) {\n throw new EvalError(\"empty command\", cmd.pos, { source: ctx.source });\n }\n const head = cmd.args[0] as Node;\n\n if (head.type !== \"Identifier\") {\n if (cmd.args.length > 1) {\n throw new EvalError(\n `cannot apply arguments to a ${head.type} primary; only functions take arguments`,\n cmd.pos,\n { source: ctx.source },\n );\n }\n return this.evalPrimary(head, scope, ctx, reads);\n }\n\n const fn = this.funcs[head.ident];\n if (!fn)\n throw new FuncNotFoundError(head.ident, head.pos, {\n source: ctx.source,\n available: Object.keys(this.funcs),\n });\n\n const argNodes = cmd.args.slice(1);\n\n // [LAW:dataflow-not-control-flow] One dispatch path. Lazy funcs\n // receive thunks (so they can short-circuit), eager funcs receive\n // values — that's the only difference, and it's encoded in the\n // shape of `args`, not in whether `enforceArgTypes` runs. Lazy\n // funcs declare permissive slots (e.g. `\"truthy\"`) so the\n // validation is a no-op against thunks.\n const lazy = isLazy(fn);\n const args: unknown[] = argNodes.map((n) =>\n lazy ? () => this.evalPrimary(n, scope, ctx, reads) : this.evalPrimary(n, scope, ctx, reads),\n );\n // [LAW:dataflow-not-control-flow] The discriminator drives whether\n // the pipe value is appended; `undefined` flows through as a real\n // value when present, instead of colliding with \"no pipe\".\n if (piped.kind === \"value\") {\n const v = piped.value;\n args.push(lazy ? () => v : v);\n }\n\n return this.invoke(head.ident, fn, args, cmd.pos, ctx, reads);\n }\n\n // [LAW:single-enforcer] Every call of a registered function — a command\n // head or a bare identifier operand — crosses the gate and has its body's\n // error reported at the call site here, and nowhere else.\n private invoke(\n name: string,\n fn: TemplateFunc,\n args: unknown[],\n pos: Pos,\n ctx: EvalContext<T>,\n reads: Set<unknown>,\n ): unknown {\n try {\n enforceArgTypes(\n name,\n fn,\n args,\n pos,\n ctx.source,\n this.toString,\n this.fromString as (s: string) => unknown,\n this.isT,\n );\n } catch (e) {\n // The gate's own errors are positioned already; a failure it meets\n // while probing (a cyclic structure) is reported at the call as Go\n // reports a function's error.\n if (e instanceof TemplateError) throw e;\n throw new EvalError(`error calling ${name}: ${errorText(e)}`, pos, {\n source: ctx.source,\n cause: e,\n });\n }\n // [LAW:single-enforcer] One cast at the dispatch site. `TemplateFunc.fn`\n // declares `(...args: never[]) => unknown` so consumer impls can narrow\n // their parameter types; we erase that here, having already validated\n // the runtime types via `enforceArgTypes`.\n let result: unknown;\n try {\n // [LAW:single-enforcer] A `marked` carrier is unwrapped here and only\n // here — returned or thrown — so no template value is ever one.\n // [LAW:dataflow-not-control-flow] The gate and the error path below\n // are the same for every call; `include` differs only in which body\n // runs, because its body is a render the evaluator owns.\n result = readCarrier(\n isInclude(fn)\n ? this.include(name, args[0] as string, args[1], pos, ctx, reads)\n : (fn.fn as (...a: unknown[]) => unknown)(...args),\n reads,\n );\n } catch (thrown) {\n // A func whose failure depends on a marked value throws\n // `marked(error, …)`: the error may clear when the mark changes, and\n // the enclosing `read` reports it.\n const e = readCarrier(thrown, reads);\n // [LAW:single-enforcer] The dispatch site is the *one* place that\n // owns call-site context (pos, source). Funcs that validate nested\n // structure (e.g. list elements, alternating variadic positions)\n // throw TypeMismatchError without pos info; we re-emit with the\n // call-site pos so the snippet points at the failing call.\n if (e instanceof TypeMismatchError) {\n throw new TypeMismatchError(e.funcName, e.argIndex, e.expected, e.receivedSummary, pos, {\n source: ctx.source,\n });\n }\n if (e instanceof FailError) {\n throw new FailError(e.message, pos, { source: ctx.source, cause: e.cause });\n }\n if (e instanceof TemplateError) throw e;\n // Go reports a function's own error as `error calling <name>: <err>`\n // at the call site; the body's error rides along as the cause.\n throw new EvalError(`error calling ${name}: ${errorText(e)}`, pos, {\n source: ctx.source,\n cause: e,\n });\n }\n // Where a write lands escapes the engine — into an object read later,\n // into a fragment already emitted, into the host's data for the next\n // evaluation — so the marks it stored are reported now, on the channel\n // that needs no cell.\n // A snapshot: the command's set keeps growing after this call.\n if (fn.writes === true) ctx.decided(new Set([...reads, ...ctx.marks]));\n return result;\n }\n\n // A carrier is unwrapped only as a func's own return. One nested inside\n // a returned value is not read there; a func that later returns it alone\n // (`index`, `get`) reads it with its marks, so its value never reaches\n // output without them. Where a template operand reaches one directly\n // (`(box).c`) the likely mistake is named rather than printed.\n private evalPrimary(node: Node, scope: Scope, ctx: EvalContext<T>, reads: Set<unknown>): unknown {\n const value = this.evalOperand(node, scope, ctx, reads);\n if (value instanceof Marked) {\n throw new EvalError(\n \"a marked() value reached the template from inside a func's return; \" +\n \"return marked(...) itself, not a structure containing one\",\n node.pos,\n { source: ctx.source },\n );\n }\n return value;\n }\n\n private evalOperand(node: Node, scope: Scope, ctx: EvalContext<T>, reads: Set<unknown>): unknown {\n switch (node.type) {\n case \"Dot\":\n return this.readDot(scope, reads);\n case \"Nil\":\n return null;\n case \"Bool\":\n return node.value;\n case \"Number\":\n return numberValue(node);\n case \"String\":\n return node.value;\n case \"Field\":\n return this.resolveFieldChain(this.readDot(scope, reads), node.idents, node.pos, ctx);\n case \"Variable\":\n return this.resolveVariable(node.idents, scope, node.pos, ctx, reads);\n case \"Identifier\": {\n const fn = this.funcs[node.ident];\n if (!fn)\n throw new FuncNotFoundError(node.ident, node.pos, {\n source: ctx.source,\n available: Object.keys(this.funcs),\n });\n return this.invoke(node.ident, fn, [], node.pos, ctx, reads);\n }\n case \"Chain\":\n return this.resolveFieldChain(\n this.evalPrimary(node.node, scope, ctx, reads),\n node.fields,\n node.pos,\n ctx,\n );\n case \"Pipe\":\n return this.evalPipe(node, scope, ctx, reads);\n default:\n throw new EvalError(`cannot evaluate ${node.type} as a value`, node.pos, {\n source: ctx.source,\n });\n }\n }\n\n // -------------------------------------------------------------------\n // Field chains and variables.\n // -------------------------------------------------------------------\n\n private resolveFieldChain(\n receiver: unknown,\n idents: readonly string[],\n pos: Pos,\n ctx: EvalContext<T>,\n ): unknown {\n const result = walkFieldChain(receiver, idents);\n if (result !== MISSING) return result;\n // [LAW:dataflow-not-control-flow] Single gate, three productions.\n // The policy value (a discriminator already validated by the\n // EngineConfig type) drives which production runs — no checks\n // scattered across accessors. `\"default\"` and `\"zero\"` collapse to\n // the same JS-observable behavior because JS lacks the static\n // value-type info Go's `reflect.New(elemType).Elem()` consumes; the\n // option is accepted for API parity (see MissingKeyOption JSDoc).\n if (this.missingKey === \"error\") {\n throw new MissingFieldError(idents, pos, { source: ctx.source });\n }\n return undefined;\n }\n\n private resolveVariable(\n idents: readonly string[],\n scope: Scope,\n pos: Pos,\n ctx: EvalContext<T>,\n reads: Set<unknown>,\n ): unknown {\n const head = idents[0] ?? \"$\";\n const binding = lookupVar(scope, head);\n if (binding === undefined) throw undefinedVariable(head, pos, ctx);\n for (const mark of binding.marks) reads.add(mark);\n const tail = idents.slice(1);\n return tail.length === 0\n ? binding.value\n : this.resolveFieldChain(binding.value, tail, pos, ctx);\n }\n\n private readDot(scope: Scope, reads: Set<unknown>): unknown {\n for (const mark of scope.dot.marks) reads.add(mark);\n return scope.dot.value;\n }\n\n // -------------------------------------------------------------------\n // Output stream.\n // -------------------------------------------------------------------\n\n // The fragment an action's value becomes on the output stream.\n private lift(value: unknown, pos: Pos, source: string | undefined): T {\n // Matches Go's text/template, which prints `<no value>` for a nil\n // pipeline rather than skipping the emit.\n if (value === null || value === undefined) return this.fromString(\"<no value>\");\n if (typeof value === \"string\") return this.fromString(value);\n if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n return this.fromString(String(value));\n }\n // A T is pushed as itself; anything else prints as Go's\n // `fmt.Sprintf(\"%v\", v)` would (`[a b c]`, `map[k:v]`), which keeps the\n // conformance corpus byte-equal.\n if (this.isT(value)) return value as T;\n try {\n return this.fromString(formatV(value, this.toString, this.isT));\n } catch (err) {\n // Every failure to print — a refusal, a T with no flattener, a\n // cyclic structure — is reported at the action.\n const message =\n err instanceof UnprintableError ? err.message : `cannot print: ${errorText(err)}`;\n throw new EvalError(message, pos, { source, cause: err });\n }\n }\n}\n\n// [LAW:one-source-of-truth] The engine's default `isT`, shared by the\n// constructor and the standalone `enforceArgTypes`, so the output stream and\n// the `\"T\"` ArgType gate cannot disagree about what a T is by default.\nexport const DEFAULT_IS_T: IsT = (v) => typeof v === \"string\";\n\n// ---------------------------------------------------------------------------\n// Convenience constructor matching the future public-API shape (.api.1).\n// ---------------------------------------------------------------------------\n\nexport function createEngine<T>(config: EngineConfig<T>): Engine<T> {\n return new Engine(config);\n}\n\n// ---------------------------------------------------------------------------\n// No-silent-flatten guard.\n//\n// [LAW:single-enforcer] This is the *one* place where argument types\n// are validated against runtime values. Every function call routes\n// through here.\n// ---------------------------------------------------------------------------\n\n// Exported for the deep-import universal-property harness (see\n// `test/conformance/no-silent-flatten-universal.test.ts`). Not part of\n// the public stability surface — `src/index.ts` does not re-export it.\n//\n// `toString` is optional so the harness (and any other deep-import\n// caller) keeps compiling unchanged. When omitted, the default\n// stringifier is used; that only affects `\"stringifiable\"` slots, where\n// a T then follows `defaultToString` — a string flattens, any other T is\n// refused. The print family and the escapers declare those slots, so a\n// deep-import caller passing no `toString` is probing a stricter engine\n// than one a consumer configured with its own.\nexport function enforceArgTypes(\n funcName: string,\n spec: ArgSpec,\n values: unknown[],\n pos: Pos,\n src: string | undefined,\n toString: (value: unknown) => string = defaultToString,\n fromString: (s: string) => unknown = defaultFromString,\n isT: IsT = DEFAULT_IS_T,\n): void {\n const { argTypes, arity } = spec;\n // [LAW:parse-dont-validate] The count check is the first leg of this\n // checkpoint and it fails loudly: a call whose argument count the\n // declared arity does not accept never reaches the slot loop, and\n // never reaches the body. Everything below this line — and every\n // func body downstream of it — may assume `values.length` is one the\n // signature admits, so nothing inland counts arguments again.\n //\n // It runs *before* the slot loop deliberately. Too few arguments\n // shifts the remaining ones into the wrong slots, so checking types\n // first reports a missing argument as a type error: `substr \"a\"`\n // used to complain that a string flowed into an integer slot, which\n // is confidently wrong about which mistake the author made.\n const accepted = acceptedArgCount(argTypes, arity);\n if (values.length < accepted.minimum || values.length > accepted.maximum) {\n throw new ArgCountError(funcName, accepted, values.length, pos, { source: src });\n }\n // [LAW:dataflow-not-control-flow] No short-circuit. The shape of work\n // is fixed: validate every positional value against its declared\n // type. Variability lives in `argTypes` (use intent-named kinds like\n // `\"value\"` for genuinely heterogeneous slots), never in whether\n // validation runs.\n //\n // [LAW:single-enforcer] Slot lookup is a single function — the\n // variadic-overflow rule (trailing-repeat, modulo cycle when the\n // arity is `\"alternating\"`) lives here once, not duplicated at the\n // loop body. See template-laws-3gt.3 for the alternation motivation\n // (`dict`'s string/value kv pairing).\n const lookup = makeSlotLookup(argTypes, arity);\n let firstOrdered = -1;\n let firstComparable = -1;\n for (let i = 0; i < values.length; i++) {\n const declared = lookup(i);\n const value = values[i];\n const refusal = refusalOf(declared, value, toString, isT);\n if (refusal !== undefined) {\n // An integer slot refusing a number is Go's `expected integer`\n // refusal, and says so with the value; every other refusal is a\n // kind mismatch.\n if (\n (declared === \"int\" || declared === \"truncating-int\") &&\n (typeof value === \"number\" || typeof value === \"bigint\")\n ) {\n throw new NotIntegerError(funcName, i + 1, value, pos, { source: src });\n }\n throw new TypeMismatchError(funcName, i + 1, humanArgType(declared), refusal, pos, {\n source: src,\n });\n }\n // [LAW:single-enforcer] The lift lives at the gate, never in func\n // bodies — bodies of \"liftable\" slots see T, full stop. Mirrors the\n // T→string direction owned by `engine.toString` (used by\n // `\"stringifiable\"`); this is the string→T direction owned by\n // `engine.fromString`. Probe-only matchers stay pure; this gate\n // mutation is the one place a typed boundary actually rewrites.\n if (declared === \"liftable\" && typeof value === \"string\") {\n values[i] = fromString(value);\n }\n // [LAW:single-enforcer] Numeric carrier normalization lives at the\n // gate so bodies receive `number`, never `number | bigint`. Mirrors\n // the \"liftable\" lift above: matcher proves membership, gate\n // mutates to the canonical carrier. Bodies of \"int\"/\"float\" slots\n // can rely on `typeof value === \"number\"`. Added by epic\n // template-variance-num-carrier-hfv.1; consumers migrated in .2/.3;\n // the transitional \"number\" kind was retired in .4 so this gate is\n // the only normalization site.\n if (declared === \"truncating-int\") {\n values[i] = Math.trunc(Number(value));\n } else if (declared === \"int\" || declared === \"float\") {\n values[i] = Number(value);\n }\n // [LAW:single-enforcer] The cross-slot ordering rule lives here,\n // alongside the per-slot type rule, so \"what counts as a valid\n // comparison\" has a single enforcer. Each \"ordered\" slot must\n // share a kind with the first \"ordered\" slot in the same call,\n // with number↔bigint bridged.\n if (declared === \"ordered\") {\n if (firstOrdered === -1) {\n firstOrdered = i;\n } else if (!sameOrderedKind(values[firstOrdered], value)) {\n throw new TypeMismatchError(\n funcName,\n i + 1,\n `${humanArgType(\"ordered\")} of the same kind as ${typeNameOf(values[firstOrdered])}`,\n typeNameOf(value),\n pos,\n { source: src },\n );\n }\n }\n // [LAW:single-enforcer] Same-kind rule for \"comparable\" — Go's\n // `text/template` errors on `eq \"foo\" 1`. number↔bigint bridged;\n // nil acts as a wildcard so `eq .field nil` works regardless of\n // .field's kind.\n if (declared === \"comparable\") {\n if (firstComparable === -1) {\n firstComparable = i;\n } else if (!sameComparableKind(values[firstComparable], value)) {\n throw new TypeMismatchError(\n funcName,\n i + 1,\n `${humanArgType(\"comparable\")} of the same kind as ${typeNameOf(values[firstComparable])}`,\n typeNameOf(value),\n pos,\n { source: src },\n );\n }\n }\n }\n}\n\n// The counts a declaration accepts. Sibling projection to\n// `makeSlotLookup` below: both read the same `Arity` union, this one\n// for how many arguments are legal, that one for what each is. Neither\n// duplicates the other's rule.\n//\n// [LAW:one-source-of-truth] Every number here is derived. `\"exact\"`\n// accepts exactly as many arguments as it declares slots; `\"variadic\"`\n// requires all but the repeating one, which is Go's own gate for a\n// variadic signature; only `\"alternating\"` supplies a number, because\n// there `argTypes` is a cycle length and carries no count. Storing a\n// minimum on the other two kinds would be a second copy of\n// `argTypes.length`, and the copy is what drifts.\n//\n// No `Math.max(0, …)` floor is needed for the `\"variadic\"` subtraction:\n// a variadic registration declaring no slots is rejected at construct\n// time by `validateArgSpecs`, so `argTypes.length` is at least 1 here.\nfunction acceptedArgCount(argTypes: readonly ArgType[], arity: Arity): ArgCount {\n switch (arity.kind) {\n case \"exact\":\n return { minimum: argTypes.length, maximum: argTypes.length };\n case \"variadic\":\n return { minimum: argTypes.length - 1, maximum: Infinity };\n case \"alternating\":\n return { minimum: arity.minimum, maximum: Infinity };\n }\n}\n\n// [LAW:dataflow-not-control-flow] The overflow rule is picked once per\n// call as an index→slot map, so the loop in `enforceArgTypes` has the\n// same shape for every func — no per-iteration branch on the kind, and\n// none inside an arm either: `\"variadic\"` clamps to its trailing slot\n// rather than testing for the end of the declared ones.\n//\n// [LAW:one-type-per-behavior] One arm per `Arity` kind, because the\n// three kinds *are* the three slot-lookup rules.\n//\n// Every read is total on an upstream guarantee, which is why none is\n// guarded here: `\"exact\"` is never asked for a slot past the end, since\n// the count check in `enforceArgTypes` pinned `values.length ===\n// argTypes.length`; `\"variadic\"` and `\"alternating\"` always have a slot\n// to index, since `validateArgSpecs` rejects either kind with none.\nfunction makeSlotLookup(argTypes: readonly ArgType[], arity: Arity): (i: number) => ArgType {\n const len = argTypes.length;\n switch (arity.kind) {\n case \"exact\":\n return (i) => argTypes[i] as ArgType;\n case \"variadic\":\n return (i) => argTypes[Math.min(i, len - 1)] as ArgType;\n case \"alternating\":\n return (i) => argTypes[i % len] as ArgType;\n }\n}\n\nfunction matchesArgType(\n declared: Exclude<ArgType, \"stringifiable\">,\n value: unknown,\n isT: IsT,\n): boolean {\n switch (declared) {\n case \"truthy\":\n case \"reflective\":\n case \"value\":\n // [LAW:dataflow-not-control-flow] Permissive matcher; the\n // *label* carries reader-facing intent so a future grep can\n // distinguish \"we accept anything because we inspect the type\"\n // from \"we accept anything because we run truthiness\"\n // from \"any escape-hatch leftover\". Migration target for .8.\n return true;\n case \"string\":\n return typeof value === \"string\";\n case \"int\":\n // [LAW:types-are-the-program] Strongest true theorem for an \"int\"\n // slot: the value is a safe integer, whichever carrier holds it.\n // `Number.isSafeInteger` refuses NaN, Infinity, fractionals, and\n // integers past 2^53 in one predicate — the same bound the bigint\n // arm holds, since past it `Number()` silently corrupts the value.\n return (\n (typeof value === \"number\" && Number.isSafeInteger(value)) ||\n (typeof value === \"bigint\" && Number.isSafeInteger(Number(value)))\n );\n case \"truncating-int\":\n // [LAW:types-are-the-program] sprig's cast admits a fractional and\n // truncates it, so this slot admits every finite number; NaN and\n // Infinity have no integer interpretation (`Math.trunc(NaN)` is\n // NaN) and are refused like \"int\" refuses them.\n return (\n (typeof value === \"number\" && Number.isFinite(value)) ||\n (typeof value === \"bigint\" && Number.isSafeInteger(Number(value)))\n );\n case \"float\":\n // [LAW:types-are-the-program] \"float\" mirrors IEEE 754: NaN and\n // ±Infinity are legitimate float values (Go's float64 has them\n // too), so the matcher accepts them — they survive gate\n // normalization unchanged. The only rejected bigint shape is one\n // whose `Number()` conversion overflows to Infinity, because\n // that's a magnitude failure, not a float-precision tradeoff.\n // Bigints in the merely-precision-losing range (e.g. 2n**100n)\n // are accepted; float never promised exact preservation.\n return (\n typeof value === \"number\" || (typeof value === \"bigint\" && Number.isFinite(Number(value)))\n );\n case \"bool\":\n return typeof value === \"boolean\";\n case \"ordered\":\n return (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n );\n case \"T\":\n // [LAW:single-enforcer] What the engine's output stream calls a T.\n return isT(value);\n case \"list\":\n // Go-parity: a string is not a list to sprig, even though it is\n // iterable. Excluding string here forces consumers to spell out\n // string-vs-list intent at the slot.\n return Array.isArray(value);\n case \"dict\":\n // Plain object only. Maps, arrays, Sets, class instances, and\n // null are not \"dicts\" — the dict slot expects bag-of-keys\n // semantics with `Object.keys` / `Record<string, unknown>` shape.\n return isPlainObject(value);\n case \"sized\":\n return (\n typeof value === \"string\" ||\n Array.isArray(value) ||\n value instanceof Map ||\n value instanceof Set ||\n isPlainObject(value)\n );\n case \"comparable\":\n // [LAW:one-source-of-truth] Membership is \"anything JSON-shaped\":\n // ordered primitives, nil, arrays, Maps, Sets, plain objects.\n // Functions and symbols are rejected. The cross-slot same-kind\n // rule (with nil-as-wildcard) is enforced in `enforceArgTypes`\n // alongside the per-slot match.\n return (\n value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\" ||\n Array.isArray(value) ||\n value instanceof Map ||\n value instanceof Set ||\n isPlainObject(value)\n );\n case \"callable\":\n return typeof value === \"function\";\n case \"collection\":\n // Receiver shape for `index`. Sets and class instances are\n // rejected (Sets aren't keyed; class instances aren't sprig\n // dicts). Nil is rejected so the body never has to defend.\n return (\n typeof value === \"string\" ||\n Array.isArray(value) ||\n value instanceof Map ||\n isPlainObject(value)\n );\n case \"index-key\":\n // Key shape for `index`. The body decides which collection kind\n // a key actually fits (array wants integer; object wants string;\n // Map's get accepts the key as-is for whatever it stores).\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"bigint\";\n case \"sliceable\":\n // Receiver shape for `slice`: string or array. Maps/dicts/Sets\n // are not sliceable in Go's `text/template`.\n return typeof value === \"string\" || Array.isArray(value);\n case \"liftable\":\n // Mirror of \"stringifiable\" in the opposite direction: a T, or a\n // string `enforceArgTypes` lifts once through `engine.fromString`.\n // [LAW:single-enforcer] The T half is the same predicate the \"T\" slot reads.\n return typeof value === \"string\" || isT(value);\n case \"serializable\":\n // Runtime-validate JSON encodability. `JSON.stringify` returns\n // `undefined` for functions/symbols and throws on circular refs;\n // either result fails the gate.\n return isJsonSerializable(value);\n default: {\n // [LAW:types-are-the-program] Explicit exhaustiveness check.\n // The `never` assignment is what makes adding a future ArgType\n // — or, equivalently, reintroducing the retired `\"number\"` —\n // a tsc error: a fresh union member is no longer assignable to\n // `never`, so the editor sees the missed case at compile time.\n // The `throw` is unreachable from an engine: a declaration that\n // casts past `ArgType` is rejected at construct time by\n // `validateArgSpecs`, so no template can drive an unknown kind\n // here (template-arity-n2j.7ve moved that check off the render\n // path, where it escaped as a raw, positionless `Error`). It\n // stays as the runtime floor for a direct deep-import caller,\n // which is the only remaining way in.\n const _exhaustive: never = declared;\n throw new Error(`invalid ArgType: ${String(_exhaustive)}`);\n }\n }\n}\n\n// Default lifter, used only when `enforceArgTypes` is called outside\n// the engine's dispatch path (e.g. tests exercising the gate\n// directly). Real engine calls always thread `this.fromString` from\n// `EngineConfig`, which is mandatory in the public API. Identity\n// keeps the gate honest in the synthetic case: a string literally\n// flows through unchanged, so `T = string` engines never need to\n// know about `\"liftable\"` for the gate to behave correctly.\nfunction defaultFromString(s: string): unknown {\n return s;\n}\n\n// Default flattener for engines that don't supply `toString`. It sees\n// only values `isT` claims: a string flows through unchanged (the\n// `T = string` happy path), a scalar or nil an `isT` claimed gets its\n// natural form, and any other T is the \"typed-T without consumer\n// flattener\" case the README contract is about, and throws a\n// TypeMismatchError. `evalCommand` wraps and re-emits with\n// the proper call-site pos (see [LAW:single-enforcer] above).\nfunction defaultToString(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined) return \"<nil>\";\n if (typeof value === \"number\" || typeof value === \"bigint\" || typeof value === \"boolean\") {\n return String(value);\n }\n throw new TypeMismatchError(\n \"<engine.toString>\",\n 1,\n \"string (or a consumer-supplied toString that flattens T)\",\n typeNameOf(value),\n { line: 0, column: 0, offset: 0 },\n );\n}\n\nfunction isJsonSerializable(value: unknown): boolean {\n try {\n const encoded = JSON.stringify(value);\n // `JSON.stringify` returns `undefined` for top-level functions /\n // symbols / undefined; treat that as \"not serializable\".\n return encoded !== undefined;\n } catch {\n // Circular references or BigInt land here.\n return false;\n }\n}\n\n// Same-kind check for two values declared `ordered`. Number and bigint\n// are bridged because compare() handles them as one numeric kind.\nfunction sameOrderedKind(a: unknown, b: unknown): boolean {\n if (typeof a === typeof b) return true;\n if (typeof a === \"number\" && typeof b === \"bigint\") return true;\n if (typeof a === \"bigint\" && typeof b === \"number\") return true;\n return false;\n}\n\n// Same-kind check for two \"comparable\" slots. Kinds: nil | string |\n// number (number/bigint bridged) | boolean | array | map | set |\n// object. nil is a wildcard, matching any kind.\nfunction sameComparableKind(a: unknown, b: unknown): boolean {\n const ka = comparableKind(a);\n const kb = comparableKind(b);\n if (ka === \"nil\" || kb === \"nil\") return true;\n return ka === kb;\n}\n\nfunction comparableKind(v: unknown): string {\n if (v === null || v === undefined) return \"nil\";\n if (typeof v === \"string\") return \"string\";\n if (typeof v === \"number\" || typeof v === \"bigint\") return \"number\";\n if (typeof v === \"boolean\") return \"boolean\";\n if (Array.isArray(v)) return \"array\";\n if (v instanceof Map) return \"map\";\n if (v instanceof Set) return \"set\";\n return \"object\";\n}\n\nfunction humanArgType(t: ArgType): string {\n switch (t) {\n case \"int\":\n return \"integer (safe-integer number or bigint)\";\n case \"truncating-int\":\n return \"integer (finite number, truncated toward zero, or safe-integer bigint)\";\n case \"float\":\n return \"float (number, including NaN/Infinity, or finite-convertible bigint)\";\n case \"T\":\n return \"T (a value the engine's isT accepts)\";\n case \"ordered\":\n return \"orderable primitive\";\n case \"list\":\n return \"list\";\n case \"dict\":\n return \"dict (plain object)\";\n case \"sized\":\n return \"sized value (string, list, map, set, or dict)\";\n case \"comparable\":\n return \"comparable value (orderable primitive, nil, list, dict, Map, or Set)\";\n case \"stringifiable\":\n 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)\";\n case \"liftable\":\n return \"liftable value (T or string, the latter lifted via the engine's fromString)\";\n case \"callable\":\n return \"callable (function value)\";\n case \"collection\":\n return \"collection (string, array, Map, or dict)\";\n case \"index-key\":\n return \"index key (number, bigint, or string)\";\n case \"sliceable\":\n return \"sliceable value (string or array)\";\n case \"serializable\":\n return \"JSON-serializable value\";\n case \"truthy\":\n case \"reflective\":\n case \"value\":\n case \"string\":\n case \"bool\":\n return t;\n default: {\n // [LAW:types-are-the-program] Same explicit exhaustiveness arm\n // as `matchesArgType` — see the rationale there. Mirrors it\n // here so the retirement-of-\"number\" guardrail is symmetric:\n // both the gate's membership predicate and its human-readable\n // labeller refuse to silently handle an unknown kind.\n const _exhaustive: never = t;\n throw new Error(`invalid ArgType: ${String(_exhaustive)}`);\n }\n }\n}\n\n// [LAW:single-enforcer] The frame every `if`, `with` and `range` opens,\n// spanning its pipe, its body and its else, so a `:=` anywhere in the\n// construct ends with it, as Go marks and pops its variable stack.\nfunction constructFrame(scope: Scope): Scope {\n return pushScope(scope, scope.dot);\n}\n\n// [LAW:single-enforcer] Reading and assigning an undeclared variable\n// fail alike, with Go's text/template exec.go message.\nfunction undefinedVariable(name: string, pos: Pos, ctx: { source: string | undefined }): EvalError {\n return new EvalError(`undefined variable: ${name}`, pos, { source: ctx.source });\n}\n\n// The template error a chain of `cause`s started from: where it went wrong.\nfunction innermost(e: TemplateError): TemplateError {\n return e.cause instanceof TemplateError ? innermost(e.cause) : e;\n}\n\n// The host ran out of stack in the template's own frames: V8 and JSC throw\n// a RangeError, SpiderMonkey an InternalError, each naming the condition.\n// A body may throw anything; Go's `%v` of an error is its message.\nfunction errorText(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n// What a refused argument is, as the gate's TypeMismatchError names it, or\n// undefined when the argument is accepted. A \"stringifiable\" refusal names\n// what `formatV` could not print — the argument, or the argument holding\n// it — from the one probe that decided it, so `toString` runs once. Every\n// other refusal names the argument's type.\nfunction refusalOf(\n declared: ArgType,\n value: unknown,\n toString: (value: unknown) => string,\n isT: IsT,\n): string | undefined {\n if (declared === \"stringifiable\") return printRefusal(value, toString, isT)?.summary;\n return matchesArgType(declared, value, isT) ? undefined : typeNameOf(value);\n}\n\n// The flatten the \"stringifiable\" bodies perform — `formatV`, Go's `%v`,\n// which hands every T (nested included) to `engine.toString` — returning its\n// refusal. Only a refusal to print is an answer; anything else, a stack\n// overflow on a cyclic structure, surfaces as itself.\nfunction printRefusal(\n value: unknown,\n toString: (value: unknown) => string,\n isT: IsT,\n): UnprintableError | undefined {\n try {\n formatV(value, toString, isT);\n return undefined;\n } catch (err) {\n if (err instanceof UnprintableError) return err;\n throw err;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Range support — iteration helpers.\n// ---------------------------------------------------------------------------\n\n/**\n * Produce [key, value] entries for a `range` operand.\n *\n * - Arrays / typed arrays / strings: numeric index → element\n * - Maps and plain objects: entries sorted by key. Matches Go's\n * `text/template`, which sorts map keys via `internal/fmtsort`\n * before iterating — same input always produces the same byte\n * output. Strings sort lexically; numbers numerically.\n * - Sets: index → element (Go ranges over channels but we map to Set\n * for symmetry with arrays/iteration)\n * - null/undefined: empty\n */\nfunction enumerateForRange(value: unknown): readonly (readonly [unknown, unknown])[] {\n if (value === null || value === undefined) return [];\n if (Array.isArray(value)) return value.map((v, i) => [i, v] as const);\n if (typeof value === \"string\") return [...value].map((c, i) => [i, c] as const);\n if (value instanceof Map) return sortMapEntries([...value.entries()]);\n if (value instanceof Set) return [...value.values()].map((v, i) => [i, v] as const);\n if (typeof value === \"object\") {\n return sortMapEntries(Object.entries(value as Record<string, unknown>));\n }\n return [];\n}\n\n// Sort map / object entries by key to match Go's text/template\n// `fmtsort` ordering. Numbers compare numerically, strings lexically,\n// mixed kinds fall back to string-ordering of the key. The compare is\n// stable enough for byte-equality conformance against Go.\nfunction sortMapEntries(\n entries: readonly (readonly [unknown, unknown])[],\n): readonly (readonly [unknown, unknown])[] {\n return [...entries].sort((a, b) => compareMapKeys(a[0], b[0]));\n}\n\nfunction compareMapKeys(a: unknown, b: unknown): number {\n const an = typeof a === \"number\" || typeof a === \"bigint\";\n const bn = typeof b === \"number\" || typeof b === \"bigint\";\n if (an && bn) {\n const ax = typeof a === \"bigint\" ? Number(a) : (a as number);\n const bx = typeof b === \"bigint\" ? Number(b) : (b as number);\n return ax === bx ? 0 : ax < bx ? -1 : 1;\n }\n const as = String(a);\n const bs = String(b);\n return as === bs ? 0 : as < bs ? -1 : 1;\n}\n\n// ---------------------------------------------------------------------------\n// Numeric-literal helper.\n// ---------------------------------------------------------------------------\n\nfunction numberValue(n: {\n readonly intValue?: bigint;\n readonly floatValue?: number;\n readonly complexValue?: readonly [number, number];\n}): unknown {\n if (n.intValue !== undefined) {\n const bi = n.intValue;\n if (bi >= BigInt(Number.MIN_SAFE_INTEGER) && bi <= BigInt(Number.MAX_SAFE_INTEGER)) {\n return Number(bi);\n }\n return bi;\n }\n if (n.floatValue !== undefined) return n.floatValue;\n if (n.complexValue !== undefined) return n.complexValue;\n // [LAW:one-source-of-truth] The AST contract guarantees one of\n // intValue/floatValue/complexValue is set on a NumberNode. Reaching\n // here means the parser produced a NumberNode missing all three —\n // an internal invariant break, not a runtime input we should\n // silently coerce to undefined.\n throw new Error(\n \"internal: NumberNode has none of intValue/floatValue/complexValue — parser invariant violated\",\n );\n}\n","/**\n * `atoi s` — parse a base-10 integer string. Returns 0 for any\n * non-parseable input, matching Go sprig (`strconv.Atoi(s)` with the\n * error discarded). Hex/octal prefixes are *not* accepted — that's\n * what `toDecimal` is for.\n */\n\n// [LAW:single-enforcer] The `\"string\"` gate validates the kind once;\n// the body trusts it. Parse failure → 0 (Go-parity: `strconv.Atoi`\n// errors, sprig discards).\n//\n// The `Number.isSafeInteger` guard is this converter's own\n// *output-precision policy*, not a mirror of Go's int64 boundary or\n// the gate's matcher predicate:\n// - Go's `strconv.Atoi` admits decimals up to int64 max\n// (9223372036854775807). JS doubles lose integer precision past\n// `Number.MAX_SAFE_INTEGER` (2^53 - 1), so values in\n// [MAX_SAFE_INTEGER+1, int64-max] are *valid in Go* but would\n// round on the way through JS — returning them would silently\n// hand the caller a different integer than the string named.\n// Collapsing the whole range to 0 is the precision-safe choice.\n// - The \"int\" ArgType matcher holds the same safe-integer bound at\n// the gate; this guard applies it at the parse step, because\n// atoi's input is a string the gate cannot see as a number.\n// Runaway-to-Infinity collapse falls out of the same predicate as a\n// free side effect.\nexport function atoi(s: string): number {\n if (!/^[+-]?\\d+$/.test(s)) return 0;\n const n = Number.parseInt(s, 10);\n return Number.isSafeInteger(n) ? n : 0;\n}\n","/**\n * `float64 v` — coerce to a JS number. Strings parse via\n * `Number.parseFloat` (Go: `strconv.ParseFloat(s, 64)`); non-numeric\n * input collapses to 0.\n */\n\n// [LAW:dataflow-not-control-flow] Per-kind dispatch lives here once;\n// callers don't repeat the shape check.\nexport function float64(v: unknown): number {\n if (typeof v === \"number\") return v;\n if (typeof v === \"bigint\") return Number(v);\n if (typeof v === \"string\") {\n const n = Number.parseFloat(v);\n return Number.isNaN(n) ? 0 : n;\n }\n if (typeof v === \"boolean\") return v ? 1 : 0;\n return 0;\n}\n","/**\n * Internal helper — Go's `strconv.ParseInt(s, 0, 64)` auto-detect rule.\n *\n * `0x`/`0X` → hex, `0b`/`0B` → binary, `0o`/`0O` → octal,\n * leading `0` → octal, otherwise decimal.\n *\n * Returns the parsed integer string-keyed (so callers can decide\n * `Number` vs `BigInt`), or `null` for unparseable input. Empty\n * string and lone `+`/`-` are unparseable.\n */\n// [LAW:one-source-of-truth] The base-detect rule lives in one place.\n// `int` and `int64` both route through here so their string-parse\n// behavior cannot drift from each other or from Go.\nexport function parseBase0(\n s: string,\n): { sign: 1 | -1; digits: string; base: 2 | 8 | 10 | 16 } | null {\n if (s === \"\") return null;\n let sign: 1 | -1 = 1;\n let body = s;\n if (body[0] === \"+\") body = body.slice(1);\n else if (body[0] === \"-\") {\n sign = -1;\n body = body.slice(1);\n }\n if (body === \"\") return null;\n\n if (/^0x[0-9a-fA-F]+$/i.test(body)) return { sign, digits: body.slice(2), base: 16 };\n if (/^0b[01]+$/i.test(body)) return { sign, digits: body.slice(2), base: 2 };\n if (/^0o[0-7]+$/i.test(body)) return { sign, digits: body.slice(2), base: 8 };\n if (body === \"0\") return { sign, digits: \"0\", base: 10 };\n if (body[0] === \"0\") {\n // Leading 0 + more chars → octal mode. Out-of-range digit fails;\n // we mirror Go (which errors) by returning null instead of\n // silently falling back to decimal.\n if (!/^0[0-7]+$/.test(body)) return null;\n return { sign, digits: body.slice(1), base: 8 };\n }\n if (!/^[0-9]+$/.test(body)) return null;\n return { sign, digits: body, base: 10 };\n}\n","import { parseBase0 } from \"./parseBase0.js\";\n\n/**\n * `int v` — coerce to integer, truncating toward zero. Strings parse\n * with Go's `strconv.ParseInt(s, 0, 64)` rule (base auto-detect: hex\n * `0x`, octal `0`/`0o`, binary `0b`, decimal default). Anything not\n * parseable → 0.\n */\n\n// [LAW:dataflow-not-control-flow] Variability lives in *values*; the\n// shape of the dispatch (one branch per JS kind) mirrors the JS type\n// system's discriminator, not an external mode flag.\n//\n// `Number.isSafeInteger` is this converter's *output-precision\n// policy*, not the gate's input predicate (the `\"int\"` ArgType\n// matcher happens to hold the same bound on its inputs). This\n// converter accepts heterogeneous input (`\"value\"` slot — number,\n// bigint, string, boolean, anything) and produces a number, so it\n// owns precision at the output edge: a returned value is guaranteed\n// to round-trip without loss. Sources of unsafe results — finite\n// `Math.trunc(2**60)`, `Number(2n**1024n)` → Infinity,\n// `Number.parseInt` of a long-enough digit string — all collapse to\n// 0 under one predicate. Stricter than Go-sprig's int64 boundary,\n// stricter than the gate's number-branch predicate, but stricter\n// in the precision-safe direction.\nexport function int(v: unknown): number {\n if (typeof v === \"number\") {\n const n = Math.trunc(v);\n return Number.isSafeInteger(n) ? n : 0;\n }\n if (typeof v === \"bigint\") {\n const n = Number(v);\n return Number.isSafeInteger(n) ? n : 0;\n }\n if (typeof v === \"string\") {\n const parsed = parseBase0(v);\n if (parsed === null) return 0;\n const n = parsed.sign * Number.parseInt(parsed.digits, parsed.base);\n return Number.isSafeInteger(n) ? n : 0;\n }\n if (typeof v === \"boolean\") return v ? 1 : 0;\n return 0;\n}\n","import { parseBase0 } from \"./parseBase0.js\";\n\n/**\n * `int64 v` — coerce to a 64-bit integer. Returns `bigint` so the\n * full Go-`int64` precision survives the round-trip (a JS `number`\n * loses precision past 2^53).\n *\n * Shares `parseBase0`'s base-detect + sign rules with `int`, so the\n * input shape (what string forms are recognized) is the same. The\n * **carrier** differs — `int` returns a JS `number` and applies a\n * `Number.isSafeInteger` clamp on output so the returned value\n * round-trips without precision loss; `int64`'s `bigint` carrier\n * holds the full int64 range, so no clamp is needed and string\n * forms like `\"9007199254740993\"` (past 2^53) survive unchanged.\n * The divergence is intentional: the carrier *forces* the precision\n * policy at this boundary, not the other way around.\n */\n\n// [LAW:types-are-the-program] Carrier choice (number vs bigint)\n// drives the policy split. Input parsing is shared (`parseBase0`) so\n// the string-form contract cannot drift; output handling diverges\n// only at the precision boundary the carrier itself defines.\nexport function int64(v: unknown): bigint {\n if (typeof v === \"bigint\") return v;\n if (typeof v === \"number\") return BigInt(Math.trunc(v));\n if (typeof v === \"string\") {\n const parsed = parseBase0(v);\n if (parsed === null) return 0n;\n // BigInt accepts \"0x\"/\"0b\"/\"0o\" literal forms directly; rebuild\n // a literal we can hand to BigInt() to avoid re-implementing\n // arbitrary-precision parsing per base.\n const prefix =\n parsed.base === 16 ? \"0x\" : parsed.base === 2 ? \"0b\" : parsed.base === 8 ? \"0o\" : \"\";\n const n = BigInt(prefix + parsed.digits);\n return parsed.sign === -1 ? -n : n;\n }\n if (typeof v === \"boolean\") return v ? 1n : 0n;\n return 0n;\n}\n","/**\n * `toDecimal s` — parse `s` as base-8 (octal) and return the decimal\n * value. Despite the name, sprig hard-codes base 8 — see Masterminds\n * `toDecimal`: `strconv.ParseInt(fmt.Sprintf(\"%v\", v), 8, 64)`.\n *\n * Prefixes are *not* accepted (only base-8 explicit means no `0o`/`0x`\n * detection). Non-octal digits or non-string-parseable input → 0.\n *\n * Examples:\n * toDecimal \"0755\" → 493 (the \"convert octal-string to decimal\" use case)\n * toDecimal \"08\" → 0 (8 is not an octal digit; Go errors)\n * toDecimal \"0xff\" → 0 (no prefix detection at base 8)\n */\n// [LAW:one-source-of-truth] Behavior is \"parse base-8\" full stop.\n// Anyone who wants base-detect uses `int` instead; that's where the\n// auto-detect rule lives (`parseBase0`).\n//\n// The `Number.isSafeInteger` guard is this converter's\n// *output-precision policy* (same shape as `atoi.ts` — see that file\n// for the full rationale). Two distinct boundaries collapse into\n// one predicate:\n// - Octal strings whose decimal value lands in\n// [MAX_SAFE_INTEGER+1, int64-max] are valid under Go's\n// `strconv.ParseInt(..., 8, 64)` but round under JS doubles.\n// Returning them silently would hand the caller a different\n// integer than the string named — collapsed to 0 instead.\n// - Octal strings long enough to overflow `Number.parseInt` to JS\n// Infinity (which Go *would* also reject) fall out of the same\n// predicate as a free side effect.\nexport function toDecimal(s: string): number {\n if (!/^[+-]?[0-7]+$/.test(s)) return 0;\n const sign = s[0] === \"-\" ? -1 : 1;\n const body = s[0] === \"+\" || s[0] === \"-\" ? s.slice(1) : s;\n const n = sign * Number.parseInt(body, 8);\n return Number.isSafeInteger(n) ? n : 0;\n}\n","/**\n * `toRawJson v` — JSON-encode without HTML escaping. Go uses a json\n * encoder with `SetEscapeHTML(false)`; JS `JSON.stringify` does not\n * HTML-escape by default, so the function is a direct mapping.\n *\n * The undefined→\"null\" coercion matches Go's `encoding/json` (which\n * encodes untyped-nil as `null`); JS would otherwise return\n * `undefined` and break callers expecting a string.\n */\n// [LAW:single-enforcer] The \"serializable\" gate already rejects\n// functions/symbols/circular refs upstream, so the body trusts the\n// kind and only routes the encoding step.\nexport function toRawJson(value: unknown): string {\n return JSON.stringify(value) ?? \"null\";\n}\n","/**\n * Sprig conversion utilities — pair-files per epic spec.\n *\n * [LAW:single-enforcer] One module owns FuncMap registration for this\n * category. Consumers either import individual functions or spread\n * the whole map via `sprigConversions()` into their EngineConfig.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { atoi } from \"./atoi.js\";\nimport { float64 } from \"./float64.js\";\nimport { int } from \"./int.js\";\nimport { int64 } from \"./int64.js\";\nimport { toDecimal } from \"./toDecimal.js\";\nimport { toRawJson } from \"./toRawJson.js\";\n\nexport { atoi, float64, int, int64, toDecimal, toRawJson };\n\nexport function sprigConversions(): FuncMap {\n // [LAW:one-source-of-truth] Slot kinds come straight from the epic\n // spec (template-sprig-ctz.1):\n // - \"string\" — atoi/toDecimal: parse-from-string\n // - \"value\" — int/int64/float64: heterogeneous-by-\n // intent; the body is the per-kind dispatch\n // [LAW:dataflow-not-control-flow]\n // - \"serializable\" — toRawJson: gate rejects functions/symbols/\n // circular refs so the body never silently\n // emits \"null\"\n const map: FuncMap = {\n atoi: {\n fn: (s) => atoi(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"int\",\n },\n int: { fn: (v) => int(v), argTypes: [\"value\"], arity: { kind: \"exact\" }, returnType: \"int\" },\n int64: { fn: (v) => int64(v), argTypes: [\"value\"], arity: { kind: \"exact\" } },\n float64: {\n fn: (v) => float64(v),\n argTypes: [\"value\"],\n arity: { kind: \"exact\" },\n returnType: \"float\",\n },\n toDecimal: {\n fn: (s) => toDecimal(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"int\",\n },\n toRawJson: {\n fn: (v) => toRawJson(v),\n argTypes: [\"serializable\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n };\n return map;\n}\n","/**\n * Go-style duration: parsing and formatting.\n *\n * Go's `time.ParseDuration` grammar:\n * duration = [-] component+\n * component = decimal unit\n * unit = ns | us | µs | ms | s | m | h\n *\n * Values are nanoseconds internally (same as Go's time.Duration).\n *\n * [LAW:one-source-of-truth] All duration string ↔ nanoseconds\n * conversions live here. No other file does this math.\n */\n\nconst NS_PER = {\n h: 3_600_000_000_000,\n m: 60_000_000_000,\n s: 1_000_000_000,\n ms: 1_000_000,\n us: 1_000,\n µs: 1_000,\n ns: 1,\n} as const;\n\ntype Unit = keyof typeof NS_PER;\n\n/**\n * Parse a Go duration string to nanoseconds (as a float for sub-ms\n * precision). Returns `NaN` on parse failure.\n *\n * Accepts: \"0\", \"300ms\", \"1.5h\", \"2h45m\", \"-1h30m\", \"100µs\".\n */\nexport function parseDurationNs(s: string): number {\n if (s === \"0\") return 0;\n\n let negative = false;\n let rest = s;\n if (rest.startsWith(\"-\")) {\n negative = true;\n rest = rest.slice(1);\n } else if (rest.startsWith(\"+\")) {\n rest = rest.slice(1);\n }\n\n if (!rest) return NaN;\n\n let total = 0;\n // Match: decimal (possibly with `.`) followed by unit name.\n // Units sorted longest-first to avoid \"m\" matching before \"ms\".\n const UNIT_RE = /^(\\d+(?:\\.\\d+)?)(ns|µs|us|ms|[smh])/;\n while (rest.length > 0) {\n const m = UNIT_RE.exec(rest);\n if (!m) return NaN;\n const value = parseFloat(m[1] ?? \"0\");\n const unit = m[2] as Unit;\n total += value * NS_PER[unit];\n rest = rest.slice(m[0].length);\n }\n\n return negative ? -total : total;\n}\n\n/**\n * Format nanoseconds as Go's `time.Duration.String()`.\n *\n * Go's algorithm mirrors time/time.go Duration.String():\n * - Values < 1µs: \"Xns\"\n * - Values < 1ms: \"X.YYYµs\" (trailing zeros trimmed)\n * - Values < 1s: \"X.YYYms\" (trailing zeros trimmed)\n * - Values >= 1s: \"XhYmZ.WWWs\" (hours/minutes shown when non-zero;\n * intermediate zero units always shown once hours or\n * minutes appear; e.g. \"1h0m0s\", \"1m0s\")\n */\nexport function formatDurationNs(ns: number): string {\n if (ns === 0) return \"0s\";\n\n let negative = false;\n let abs = ns;\n if (abs < 0) {\n negative = true;\n abs = -abs;\n }\n\n let out: string;\n if (abs < NS_PER.us) {\n out = `${Math.floor(abs)}ns`;\n } else if (abs < NS_PER.ms) {\n out = fmtSubUnit(abs, NS_PER.us, 3, \"µs\");\n } else if (abs < NS_PER.s) {\n out = fmtSubUnit(abs, NS_PER.ms, 6, \"ms\");\n } else {\n out = fmtGeqSecond(abs);\n }\n\n return negative ? `-${out}` : out;\n}\n\n/** Format sub-second values in a given unit (µs, ms). */\nfunction fmtSubUnit(abs: number, unit: number, fracDigits: number, suffix: string): string {\n const whole = Math.floor(abs / unit);\n const frac = Math.round(abs % unit);\n if (frac === 0) return `${whole}${suffix}`;\n const fracStr = String(frac).padStart(fracDigits, \"0\").replace(/0+$/, \"\");\n return `${whole}.${fracStr}${suffix}`;\n}\n\n/** Format durations >= 1 second as Go does. */\nfunction fmtGeqSecond(abs: number): string {\n const h = Math.floor(abs / NS_PER.h);\n abs -= h * NS_PER.h;\n const m = Math.floor(abs / NS_PER.m);\n abs -= m * NS_PER.m;\n // abs is now nanoseconds in the current second slot (0..59_999_999_999)\n const s = Math.floor(abs / NS_PER.s);\n const nsFrac = abs - s * NS_PER.s;\n\n // Format seconds, optionally with nanosecond fraction.\n const secStr =\n nsFrac === 0\n ? `${s}s`\n : `${s}.${String(Math.round(nsFrac)).padStart(9, \"0\").replace(/0+$/, \"\")}s`;\n\n if (h > 0) return `${h}h${m}m${secStr}`;\n if (m > 0) return `${m}m${secStr}`;\n return secStr;\n}\n\n/** Format nanoseconds as a duration, rounding to the largest non-zero unit. */\nexport function roundDurationNs(ns: number): string {\n const abs = Math.abs(ns);\n\n // Round to the appropriate precision level.\n let rounded: number;\n if (abs >= NS_PER.h) {\n rounded = Math.round(ns / NS_PER.h) * NS_PER.h;\n } else if (abs >= NS_PER.m) {\n rounded = Math.round(ns / NS_PER.m) * NS_PER.m;\n } else if (abs >= NS_PER.s) {\n rounded = Math.round(ns / NS_PER.s) * NS_PER.s;\n } else if (abs >= NS_PER.ms) {\n rounded = Math.round(ns / NS_PER.ms) * NS_PER.ms;\n } else if (abs >= NS_PER.us) {\n rounded = Math.round(ns / NS_PER.us) * NS_PER.us;\n } else {\n rounded = ns;\n }\n\n return formatDurationNs(rounded);\n}\n\n/** Convert integer seconds to nanoseconds. */\nexport function secondsToNs(s: number): number {\n return s * NS_PER.s;\n}\n","/**\n * Normalise the heterogeneous `t` argument accepted by date functions.\n *\n * Go sprig's `dateInZone` accepts: `time.Time`, `int64`, `int`, `int32`.\n * JS side: `Date`, `number` (Unix seconds), `bigint` (Unix seconds),\n * `string` (ISO / Go-layout string).\n *\n * When `t` is already a `Date`, it is returned unchanged.\n * When `t` is a number or bigint, it is treated as Unix seconds (matching\n * Go's `time.Unix(n, 0)` — NOT milliseconds).\n * When `t` is a string, it is parsed by `Date.parse` as a fallback.\n *\n * [LAW:single-enforcer] One place owns `t → Date` normalisation.\n * All date functions call this; none duplicate the logic.\n */\nexport function resolveDate(t: unknown): Date {\n if (t instanceof Date) return t;\n if (typeof t === \"bigint\") return new Date(Number(t) * 1000);\n if (typeof t === \"number\") return new Date(t * 1000);\n if (typeof t === \"string\") {\n const parsed = new Date(t);\n if (!Number.isNaN(parsed.getTime())) return parsed;\n throw new Error(`sprig: cannot parse date value ${JSON.stringify(t)}`);\n }\n throw new Error(`sprig: unsupported date type: ${typeof t}`);\n}\n","import type { Clock } from \"./_clock.js\";\nimport { formatDurationNs } from \"./_duration.js\";\nimport { resolveDate } from \"./_resolve.js\";\n\n/**\n * `ago t` — Go-style duration since `t`.\n * Mirrors Go sprig: `time.Since(t).Round(time.Second).String()`.\n */\nexport function ago(t: unknown, clock: Clock): string {\n const ms = clock().getTime() - resolveDate(t).getTime();\n // Round to nearest second then format.\n const ns = Math.round(ms / 1000) * 1_000_000_000;\n return formatDurationNs(ns);\n}\n","/**\n * Go reference-time layout tokenizer and formatter.\n *\n * Go's reference time: `Mon Jan 2 15:04:05 MST 2006`\n * Each component uses a unique value so the tokenizer can identify it\n * positionally without ambiguity markers.\n *\n * Strategy: greedy left-to-right scan — try each known token at the\n * current position (longest first); pass literal characters through.\n * Round-trips Go's exact output for every tested layout.\n *\n * [LAW:one-source-of-truth] Format-token definitions live here only;\n * the parser in `_parse.ts` imports the same token list inverted.\n */\n\nimport type { ZoneParts } from \"./_zone.js\";\n\n// ---------------------------------------------------------------------------\n// Constant tables\n// ---------------------------------------------------------------------------\n\nconst MONTHS_LONG = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\nconst MONTHS_SHORT = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n];\n\nconst WEEKDAYS_LONG = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n];\n\nconst WEEKDAYS_SHORT = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n\n// ---------------------------------------------------------------------------\n// Formatting helpers\n// ---------------------------------------------------------------------------\n\nfunction pad2(n: number): string {\n return n < 10 ? `0${n}` : String(n);\n}\n\nfunction pad3(n: number): string {\n return n < 10 ? `00${n}` : n < 100 ? `0${n}` : String(n);\n}\n\nfunction spacePad2(n: number): string {\n return n < 10 ? ` ${n}` : String(n);\n}\n\n// Go prints an offset in whole minutes truncated toward zero, signed by\n// those minutes (so -30s prints \"+0000\"), and writes \"Z\" only when the exact\n// offset in seconds is zero.\nfunction offsetParts(offsetSeconds: number): { sign: string; hh: string; mm: string } {\n const minutes = Math.trunc(offsetSeconds / 60);\n const abs = Math.abs(minutes);\n return {\n sign: minutes < 0 ? \"-\" : \"+\",\n hh: pad2(Math.floor(abs / 60)),\n mm: pad2(abs % 60),\n };\n}\n\n/** ±hhmm (no colon). E.g. \"+0500\", \"-0500\", \"+0000\". */\nfunction fmtOffset(offsetSeconds: number): string {\n const { sign, hh, mm } = offsetParts(offsetSeconds);\n return `${sign}${hh}${mm}`;\n}\n\n/** ±hh:mm (with colon). E.g. \"+05:00\", \"-05:00\", \"+00:00\". */\nfunction fmtOffsetColon(offsetSeconds: number): string {\n const { sign, hh, mm } = offsetParts(offsetSeconds);\n return `${sign}${hh}:${mm}`;\n}\n\n/** ±hh only. */\nfunction fmtOffsetHour(offsetSeconds: number): string {\n const { sign, hh } = offsetParts(offsetSeconds);\n return `${sign}${hh}`;\n}\n\n/** Z or ±hhmm. */\nfunction fmtOffsetZ(offsetSeconds: number): string {\n return offsetSeconds === 0 ? \"Z\" : fmtOffset(offsetSeconds);\n}\n\n/** Z or ±hh:mm. */\nfunction fmtOffsetColonZ(offsetSeconds: number): string {\n return offsetSeconds === 0 ? \"Z\" : fmtOffsetColon(offsetSeconds);\n}\n\n/** Z or ±hh. */\nfunction fmtOffsetHourZ(offsetSeconds: number): string {\n return offsetSeconds === 0 ? \"Z\" : fmtOffsetHour(offsetSeconds);\n}\n\n// Fractional second helper: pad/trim to `width` digits.\nfunction fmtFrac(ms: number, width: number, trimTrailing: boolean): string {\n // ms is 0–999; expand to full nanosecond-width by multiplying\n const nanosTotal = ms * 1_000_000; // ms → ns\n const full = String(nanosTotal).padStart(9, \"0\");\n const s = full.slice(0, width);\n if (trimTrailing) return s.replace(/0+$/, \"\");\n return s;\n}\n\n// ---------------------------------------------------------------------------\n// Token table — ordered longest-first so greedy matching is correct.\n// ---------------------------------------------------------------------------\n\ntype Replacer = (z: ZoneParts) => string;\n\n// Each entry: [tokenString, replacer].\n// Order MUST be stable and longest-first within the same starting character.\nconst TOKENS: [string, Replacer][] = [\n // 9-digit fractional seconds\n [\".000000000\", (z) => `.${fmtFrac(z.ms, 9, false)}`],\n [\n \".999999999\",\n (z) => {\n const s = fmtFrac(z.ms, 9, true);\n return s ? `.${s}` : \"\";\n },\n ],\n // 6-digit fractional seconds\n [\".000000\", (z) => `.${fmtFrac(z.ms, 6, false)}`],\n [\n \".999999\",\n (z) => {\n const s = fmtFrac(z.ms, 6, true);\n return s ? `.${s}` : \"\";\n },\n ],\n // 3-digit fractional seconds\n [\".000\", (z) => `.${pad3(z.ms)}`],\n [\n \".999\",\n (z) => {\n const s = pad3(z.ms).replace(/0+$/, \"\");\n return s ? `.${s}` : \"\";\n },\n ],\n // 7-char\n [\"January\", (z) => MONTHS_LONG[z.month - 1] ?? \"January\"],\n // 6-char\n [\"Monday\", (z) => WEEKDAYS_LONG[z.weekday] ?? \"Monday\"],\n [\"Z07:00\", (z) => fmtOffsetColonZ(z.offsetSeconds)],\n [\"-07:00\", (z) => fmtOffsetColon(z.offsetSeconds)],\n // 5-char\n [\"Z0700\", (z) => fmtOffsetZ(z.offsetSeconds)],\n [\"-0700\", (z) => fmtOffset(z.offsetSeconds)],\n // 4-char\n // Go: sign, then the magnitude padded to four digits (-5 → \"-0005\").\n [\"2006\", (z) => `${z.year < 0 ? \"-\" : \"\"}${String(Math.abs(z.year)).padStart(4, \"0\")}`],\n // 3-char\n [\"Jan\", (z) => MONTHS_SHORT[z.month - 1] ?? \"Jan\"],\n [\"Mon\", (z) => WEEKDAYS_SHORT[z.weekday] ?? \"Mon\"],\n [\"MST\", (z) => z.tzAbbr],\n [\"-07\", (z) => fmtOffsetHour(z.offsetSeconds)],\n [\"Z07\", (z) => fmtOffsetHourZ(z.offsetSeconds)],\n // 2-char\n [\"15\", (z) => pad2(z.hour)],\n [\"01\", (z) => pad2(z.month)],\n [\"02\", (z) => pad2(z.day)],\n // Space-padded day: `_2` is underscore+2 in the format string.\n [\"_2\", (z) => spacePad2(z.day)],\n [\"03\", (z) => pad2(z.hour12)],\n [\"04\", (z) => pad2(z.minute)],\n [\"05\", (z) => pad2(z.second)],\n [\"06\", (z) => pad2(Math.abs(z.year) % 100)],\n [\"PM\", (z) => (z.hour >= 12 ? \"PM\" : \"AM\")],\n [\"pm\", (z) => (z.hour >= 12 ? \"pm\" : \"am\")],\n // 1-char\n [\"1\", (z) => String(z.month)],\n [\"2\", (z) => String(z.day)],\n [\"3\", (z) => String(z.hour12)],\n [\"4\", (z) => String(z.minute)],\n [\"5\", (z) => String(z.second)],\n];\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Format `zoneParts` according to Go's reference-time layout string.\n * Literal characters pass through unchanged.\n */\nexport function formatGoLayout(layout: string, z: ZoneParts): string {\n let result = \"\";\n let i = 0;\n while (i < layout.length) {\n let matched = false;\n for (const [token, replacer] of TOKENS) {\n if (layout.startsWith(token, i)) {\n result += replacer(z);\n i += token.length;\n matched = true;\n break;\n }\n }\n if (!matched) {\n result += layout[i++];\n }\n }\n return result;\n}\n","/**\n * Timezone-aware date parts extraction via Intl.DateTimeFormat.\n *\n * No third-party deps. All modern runtimes (Node ≥ 14, Bun, Deno,\n * browsers) ship Intl with IANA tz database support.\n *\n * [LAW:single-enforcer] All timezone arithmetic routes through\n * `getZoneParts` — never through `date.getHours()` (host-tz) or manual\n * offset computation at callsites.\n */\n\nexport interface ZoneParts {\n year: number; // astronomical: 1 BC is 0\n month: number; // 1–12\n day: number; // 1–31\n weekday: number; // 0 = Sun, 1 = Mon, …, 6 = Sat\n hour: number; // 0–23\n hour12: number; // 1–12 (Go's `3` token)\n minute: number;\n second: number;\n ms: number; // milliseconds 0–999 (from UTC epoch)\n tzAbbr: string; // \"UTC\", \"EST\", \"EDT\", etc.\n offsetSeconds: number; // UTC offset, exact (e.g. -18000 for EST, -17762 for New York LMT)\n}\n\n// `era` lets BCE years be told from CE: Intl numbers 1 BC as year \"1\".\n// `timeZoneName` adds the short abbreviation as a part.\nconst INTL_OPTS: Intl.DateTimeFormatOptions = {\n era: \"short\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n weekday: \"long\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n timeZoneName: \"short\",\n};\n\nconst WEEKDAY_NAMES = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n];\n\n// INTL_OPTS requests every part read here, so a missing one is a runtime\n// that broke the contract, not a value to default past.\nfunction readParts(fmt: Intl.DateTimeFormat, date: Date) {\n const parts = new Map<string, string>();\n for (const p of fmt.formatToParts(date)) parts.set(p.type, p.value);\n return (type: Intl.DateTimeFormatPartTypes): string => {\n const value = parts.get(type);\n if (value === undefined) throw new Error(`Intl.DateTimeFormat omitted the ${type} part`);\n return value;\n };\n}\n\nfunction buildFormatter(timeZone: string): Intl.DateTimeFormat {\n return new Intl.DateTimeFormat(\"en-US\", { ...INTL_OPTS, timeZone });\n}\n\n// Go's time.LoadLocation rejects UTC offset names (\"+05:30\"), which Intl\n// accepts as zones.\nconst OFFSET_ZONE = /^[+-]/;\n\n// [LAW:no-shared-mutable-globals] Owned by `zoneFormatter` alone, the only\n// reader and writer. Invariant: each entry is a pure function of the key\n// (locale and options are fixed), so memoising leaves every result unchanged\n// and nothing is ever evicted. Only zones that load are stored, keyed\n// ASCII-case-insensitively as ECMA-402 matches them, so the map is bounded by\n// the IANA identifiers however a template spells them. Construction costs\n// tens of µs; formatting with a warm formatter, a few.\nconst formattersByZone = new Map<string, Intl.DateTimeFormat>();\n\n// Mirror Go sprig: a zone that does not load falls back to UTC. Intl rejects\n// an unknown zone with a RangeError. The UTC formatter is built outside the\n// `try`, so a runtime that cannot honour INTL_OPTS at all fails loudly.\nfunction zoneFormatter(name: string): Intl.DateTimeFormat {\n const key = name.replace(/[A-Z]/g, (c) => c.toLowerCase());\n const cached = formattersByZone.get(key);\n if (cached !== undefined) return cached;\n const loaded = OFFSET_ZONE.test(name) ? undefined : buildOrUnknown(name);\n if (loaded === undefined) return zoneFormatter(\"UTC\");\n formattersByZone.set(key, loaded);\n return loaded;\n}\n\nfunction buildOrUnknown(name: string): Intl.DateTimeFormat | undefined {\n if (name === \"UTC\") return buildFormatter(name);\n try {\n return buildFormatter(name);\n } catch (e) {\n if (e instanceof RangeError) return undefined;\n throw e;\n }\n}\n\n/** Extract date parts in the requested IANA timezone. Falls back to \"UTC\" on invalid zone, mirroring Go sprig. */\nexport function getZoneParts(date: Date, zone: string): ZoneParts {\n const part = readParts(zoneFormatter(zone), date);\n\n const eraYear = parseInt(part(\"year\"), 10);\n const year = part(\"era\") === \"BC\" ? 1 - eraYear : eraYear;\n const month = parseInt(part(\"month\"), 10);\n const day = parseInt(part(\"day\"), 10);\n // hour12: false returns \"24\" for midnight in some runtimes — normalise.\n const hour = parseInt(part(\"hour\"), 10) % 24;\n const minute = parseInt(part(\"minute\"), 10);\n const second = parseInt(part(\"second\"), 10);\n const ms = date.getUTCMilliseconds();\n\n // The UTC offset is the wall clock read as if it were UTC, minus the\n // instant: exact to the second, so local mean time offsets such as New\n // York's -4:56:02 before 1883 survive. Plain arithmetic, not a Date,\n // because the wall clock may lie past Date's ±8.64e15 ms range.\n const wallMs =\n daysFromCivil(year, month, day) * 86_400_000 + ((hour * 60 + minute) * 60 + second) * 1000 + ms;\n const offsetSeconds = (wallMs - date.getTime()) / 1000;\n\n const weekdayName = part(\"weekday\");\n const weekday = WEEKDAY_NAMES.indexOf(weekdayName);\n if (weekday === -1) throw new Error(`Intl.DateTimeFormat gave an unknown weekday ${weekdayName}`);\n\n return {\n year,\n month,\n day,\n weekday,\n hour,\n hour12: hour % 12 || 12,\n minute,\n second,\n ms,\n tzAbbr: part(\"timeZoneName\"),\n offsetSeconds,\n };\n}\n\n// Days from 1970-01-01 to a proleptic Gregorian date, for any integer year.\n// Howard Hinnant's days_from_civil: count in 400-year eras from 0000-03-01.\nfunction daysFromCivil(year: number, month: number, day: number): number {\n const y = month <= 2 ? year - 1 : year;\n const era = Math.floor(y / 400);\n const yearOfEra = y - era * 400;\n const dayOfYear = Math.floor((153 * ((month + 9) % 12) + 2) / 5) + day - 1;\n const dayOfEra =\n yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;\n return era * 146_097 + dayOfEra - 719_468;\n}\n\n// [LAW:no-shared-mutable-globals] Owned by `localTz` alone. Go fixes\n// `time.Local` before `main`, but in JS the host zone moves at runtime: Node\n// re-resolves it when `process.env.TZ` is assigned, a browser when the OS\n// zone changes. The memo is keyed on both signals (the offset stands in for\n// the OS zone where there is no `process`), so it resolves afresh, at the\n// cost of one formatter, only when one of them moves.\nlet hostZone: { key: string; zone: string } | undefined;\n\n/** Host timezone name (IANA string). */\nexport function localTz(): string {\n const key = `${globalThis.process?.env.TZ}|${new Date().getTimezoneOffset()}`;\n if (hostZone?.key !== key) {\n hostZone = { key, zone: Intl.DateTimeFormat().resolvedOptions().timeZone };\n }\n return hostZone.zone;\n}\n","import { formatGoLayout } from \"./_format.js\";\nimport { resolveDate } from \"./_resolve.js\";\nimport { getZoneParts, localTz } from \"./_zone.js\";\n\n/**\n * `date format t` — format `t` using Go's reference-time layout,\n * in the host timezone (mirrors Go's `date` which uses `time.Local`).\n */\nexport function date(format: string, t: unknown): string {\n const d = resolveDate(t);\n return formatGoLayout(format, getZoneParts(d, localTz()));\n}\n","import { formatGoLayout } from \"./_format.js\";\nimport { resolveDate } from \"./_resolve.js\";\nimport { getZoneParts } from \"./_zone.js\";\n\n/**\n * `dateInZone format t zone` — format `t` using Go's reference-time\n * layout, displayed in the named IANA timezone.\n */\nexport function dateInZone(format: string, t: unknown, zone: string): string {\n const d = resolveDate(t);\n return formatGoLayout(format, getZoneParts(d, zone));\n}\n","import { parseDurationNs } from \"./_duration.js\";\nimport { resolveDate } from \"./_resolve.js\";\n\n/**\n * `dateModify duration t` — add or subtract a Go duration from `t`.\n * `duration` is a Go duration string: \"1h30m\", \"-24h\", \"300ms\".\n */\nexport function dateModify(duration: string, t: unknown): Date {\n const d = resolveDate(t);\n const ns = parseDurationNs(duration);\n // Mirror Go sprig: return the original date unchanged on parse error.\n if (Number.isNaN(ns)) return d;\n return new Date(d.getTime() + ns / 1_000_000);\n}\n","import { formatDurationNs, secondsToNs } from \"./_duration.js\";\n\n/**\n * `duration sec` — seconds → Go-style duration string.\n * Mirrors Go sprig: accepts a string (parsed as decimal integer seconds)\n * or a number/bigint.\n *\n * `duration(\"3600\")` → `\"1h0m0s\"`, `duration(\"5\")` → `\"5s\"`.\n *\n * Note: Go sprig only handles `string` and `int64` inputs; `int` (the type\n * of a Go template integer literal) falls to a default-zero branch. To\n * maintain portable templates, always pass seconds as a string.\n */\nexport function duration(sec: unknown): string {\n if (typeof sec === \"string\") {\n const n = parseInt(sec, 10);\n return Number.isNaN(n) ? \"0s\" : formatDurationNs(secondsToNs(n));\n }\n if (typeof sec === \"bigint\") return formatDurationNs(secondsToNs(Number(sec)));\n if (typeof sec === \"number\") return formatDurationNs(secondsToNs(sec));\n return \"0s\";\n}\n","import { parseDurationNs } from \"./_duration.js\";\n\n// Mirror Go sprig's constants (nanoseconds). Comparisons are strict (>).\nconst YEAR = 3_600_000_000_000 * 24 * 365;\nconst MONTH = 3_600_000_000_000 * 24 * 30;\nconst DAY = 3_600_000_000_000 * 24;\nconst HOUR = 3_600_000_000_000;\nconst MINUTE = 60_000_000_000;\nconst SECOND = 1_000_000_000;\n\n/**\n * `durationRound d` — parse a Go duration string and truncate to the\n * largest unit. Mirrors Go sprig's `durationRound` which uses integer\n * division (NOT rounding) and custom single-unit suffixes.\n *\n * Examples: \"1h30m\" → \"1h\", \"90s\" → \"1m\", \"1h\" → \"60m\" (strict >).\n */\nexport function durationRound(d: unknown): string {\n const s = String(d);\n const ns = parseDurationNs(s);\n if (Number.isNaN(ns)) return \"0s\";\n\n const u = Math.abs(ns);\n if (u > YEAR) return `${Math.floor(u / YEAR)}y`;\n if (u > MONTH) return `${Math.floor(u / MONTH)}mo`;\n if (u > DAY) return `${Math.floor(u / DAY)}d`;\n if (u > HOUR) return `${Math.floor(u / HOUR)}h`;\n if (u > MINUTE) return `${Math.floor(u / MINUTE)}m`;\n if (u > SECOND) return `${Math.floor(u / SECOND)}s`;\n return \"0s\";\n}\n","import { formatGoLayout } from \"./_format.js\";\nimport { resolveDate } from \"./_resolve.js\";\nimport { getZoneParts, localTz } from \"./_zone.js\";\n\n/** `htmlDate t` — YYYY-MM-DD in the host timezone. */\nexport function htmlDate(t: unknown): string {\n return formatGoLayout(\"2006-01-02\", getZoneParts(resolveDate(t), localTz()));\n}\n","import { formatGoLayout } from \"./_format.js\";\nimport { resolveDate } from \"./_resolve.js\";\nimport { getZoneParts } from \"./_zone.js\";\n\n/** `htmlDateInZone t zone` — YYYY-MM-DD in the named timezone. */\nexport function htmlDateInZone(t: unknown, zone: string): string {\n return formatGoLayout(\"2006-01-02\", getZoneParts(resolveDate(t), zone));\n}\n","import type { Clock } from \"./_clock.js\";\n\n/** `now` — current instant. Routed through the clock seam. */\nexport function now(clock: Clock): Date {\n return clock();\n}\n","/**\n * Parse a date string according to Go's reference-time layout.\n *\n * Mirrors `time.ParseInLocation` with UTC as the default location\n * (when the layout contains no timezone token, the result is UTC).\n *\n * Strategy: tokenise the layout the same way the formatter does —\n * greedy longest-match — but instead of replacing tokens with values,\n * consume the corresponding characters from the value string.\n */\n\nconst MONTHS_LONG = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\nconst MONTHS_SHORT = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n];\n\n// ---------------------------------------------------------------------------\n// Parse state\n// ---------------------------------------------------------------------------\n\ninterface ParseState {\n year: number;\n month: number; // 1–12\n day: number; // 1–31\n hour: number; // 0–23\n minute: number;\n second: number;\n ms: number;\n offsetMinutes: number; // UTC offset; NaN means \"not set\" → default to UTC\n isPM: boolean;\n hour12: boolean; // did layout use 12h token?\n}\n\nfunction defaultState(): ParseState {\n return {\n year: 2000,\n month: 1,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n ms: 0,\n offsetMinutes: 0,\n isPM: false,\n hour12: false,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Value-string consumers\n// ---------------------------------------------------------------------------\n\nfunction consumeFixed(val: string, pos: number, n: number): [string, number] {\n return [val.slice(pos, pos + n), pos + n];\n}\n\nfunction consumeDigits(val: string, pos: number, min: number, max: number): [number, number] {\n let end = pos;\n while (\n end < val.length &&\n end - pos < max &&\n val.charCodeAt(end) >= 48 &&\n val.charCodeAt(end) <= 57\n )\n end++;\n if (end - pos < min) throw new Error(`sprig toDate: expected ${min}-${max} digits at pos ${pos}`);\n return [parseInt(val.slice(pos, end), 10), end];\n}\n\nfunction consumeMonthLong(val: string, pos: number): [number, number] {\n for (const [i, m] of MONTHS_LONG.entries()) {\n if (val.startsWith(m, pos)) return [i + 1, pos + m.length];\n }\n throw new Error(`sprig toDate: expected month name at pos ${pos}`);\n}\n\nfunction consumeMonthShort(val: string, pos: number): [number, number] {\n for (const [i, m] of MONTHS_SHORT.entries()) {\n if (val.startsWith(m, pos)) return [i + 1, pos + m.length];\n }\n throw new Error(`sprig toDate: expected short month name at pos ${pos}`);\n}\n\nfunction consumeWeekdayLong(val: string, pos: number): number {\n const days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\n for (const d of days) if (val.startsWith(d, pos)) return pos + d.length;\n throw new Error(`sprig toDate: expected weekday name at pos ${pos}`);\n}\n\nfunction consumeWeekdayShort(val: string, pos: number): number {\n const days = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n for (const d of days) if (val.startsWith(d, pos)) return pos + d.length;\n throw new Error(`sprig toDate: expected short weekday name at pos ${pos}`);\n}\n\nfunction consumeSpacePaddedDay(val: string, pos: number): [number, number] {\n // Leading space or digit for space-padded day (`_2` token).\n if (val[pos] === \" \") {\n const [n, end] = consumeDigits(val, pos + 1, 1, 1);\n return [n, end];\n }\n return consumeDigits(val, pos, 1, 2);\n}\n\n/** Parse offset like \"+0500\", \"-0500\", \"+05:00\", \"-05:00\", \"+05\", \"-05\". Returns minutes. */\nfunction consumeOffset(val: string, pos: number, withColon: boolean): [number, number] {\n const sign = val[pos] === \"+\" ? 1 : val[pos] === \"-\" ? -1 : 0;\n if (sign === 0) throw new Error(`sprig toDate: expected +/- at pos ${pos}`);\n let p = pos + 1;\n const [h, p2] = consumeDigits(val, p, 2, 2);\n p = p2;\n let m = 0;\n if (withColon && val[p] === \":\") {\n const [m2, p3] = consumeDigits(val, p + 1, 2, 2);\n m = m2;\n p = p3;\n } else if (!withColon) {\n const [m2, p3] = consumeDigits(val, p, 2, 2);\n m = m2;\n p = p3;\n }\n return [sign * (h * 60 + m), p];\n}\n\n/** Parse \"Z\" or an offset. withColon controls +05:00 vs +0500 form. Returns [offsetMinutes, newPos]. */\nfunction consumeZOrOffset(\n val: string,\n pos: number,\n withColon: boolean,\n hourOnly: boolean,\n): [number, number] {\n if (val[pos] === \"Z\") return [0, pos + 1];\n if (hourOnly) {\n const sign = val[pos] === \"+\" ? 1 : val[pos] === \"-\" ? -1 : 0;\n if (sign === 0) throw new Error(`sprig toDate: expected Z or +/- at pos ${pos}`);\n const [h, p2] = consumeDigits(val, pos + 1, 2, 2);\n return [sign * h * 60, p2];\n }\n return consumeOffset(val, pos, withColon);\n}\n\n/** Parse timezone abbreviation (e.g. \"UTC\", \"EST\"). Returns new pos. */\nfunction consumeTzAbbr(val: string, pos: number): number {\n // TZ abbreviation is a run of uppercase letters.\n let end = pos;\n while (end < val.length && val.charCodeAt(end) >= 65 && val.charCodeAt(end) <= 90) end++;\n if (end === pos) throw new Error(`sprig toDate: expected timezone abbreviation at pos ${pos}`);\n return end;\n}\n\n/** Parse fractional seconds (like \".000\", \".999\", etc.) starting AFTER the dot. */\nfunction consumeFrac(val: string, pos: number, width: number): [number, number] {\n const [raw, end] = consumeFixed(val, pos, width);\n const ns = parseInt(raw.padEnd(9, \"0\"), 10);\n return [Math.round(ns / 1_000_000), end]; // → ms\n}\n\n// ---------------------------------------------------------------------------\n// Token dispatch\n// ---------------------------------------------------------------------------\n\n// Returns [newValPos, modified state], consuming both layout and value tokens.\nfunction dispatchToken(\n token: string,\n val: string,\n vp: number,\n st: ParseState,\n): [number, ParseState] {\n const s = { ...st };\n switch (token) {\n case \"January\": {\n const [m, p2] = consumeMonthLong(val, vp);\n s.month = m;\n return [p2, s];\n }\n case \"Monday\": {\n const p2 = consumeWeekdayLong(val, vp);\n return [p2, s];\n }\n case \"Jan\": {\n const [m, p2] = consumeMonthShort(val, vp);\n s.month = m;\n return [p2, s];\n }\n case \"Mon\": {\n const p2 = consumeWeekdayShort(val, vp);\n return [p2, s];\n }\n case \"2006\": {\n const [y, p2] = consumeDigits(val, vp, 4, 4);\n s.year = y;\n return [p2, s];\n }\n case \"06\": {\n const [y, p2] = consumeDigits(val, vp, 2, 2);\n s.year = y < 70 ? 2000 + y : 1900 + y;\n return [p2, s];\n }\n case \"01\": {\n const [m, p2] = consumeDigits(val, vp, 2, 2);\n s.month = m;\n return [p2, s];\n }\n case \"1\": {\n const [m, p2] = consumeDigits(val, vp, 1, 2);\n s.month = m;\n return [p2, s];\n }\n case \"_2\": {\n const [d, p2] = consumeSpacePaddedDay(val, vp);\n s.day = d;\n return [p2, s];\n }\n case \"02\": {\n const [d, p2] = consumeDigits(val, vp, 2, 2);\n s.day = d;\n return [p2, s];\n }\n case \"2\": {\n const [d, p2] = consumeDigits(val, vp, 1, 2);\n s.day = d;\n return [p2, s];\n }\n case \"15\": {\n const [h, p2] = consumeDigits(val, vp, 2, 2);\n s.hour = h;\n return [p2, s];\n }\n case \"03\": {\n const [h, p2] = consumeDigits(val, vp, 2, 2);\n s.hour = h;\n s.hour12 = true;\n return [p2, s];\n }\n case \"3\": {\n const [h, p2] = consumeDigits(val, vp, 1, 2);\n s.hour = h;\n s.hour12 = true;\n return [p2, s];\n }\n case \"04\": {\n const [m, p2] = consumeDigits(val, vp, 2, 2);\n s.minute = m;\n return [p2, s];\n }\n case \"4\": {\n const [m, p2] = consumeDigits(val, vp, 1, 2);\n s.minute = m;\n return [p2, s];\n }\n case \"05\": {\n const [sec, p2] = consumeDigits(val, vp, 2, 2);\n s.second = sec;\n return [p2, s];\n }\n case \"5\": {\n const [sec, p2] = consumeDigits(val, vp, 1, 2);\n s.second = sec;\n return [p2, s];\n }\n case \"PM\":\n case \"pm\": {\n const ampm = val.slice(vp, vp + 2).toLowerCase();\n if (ampm !== \"am\" && ampm !== \"pm\")\n throw new Error(\n `sprig toDate: expected AM/PM at pos ${vp}, got ${JSON.stringify(val.slice(vp, vp + 2))}`,\n );\n s.isPM = ampm === \"pm\";\n s.hour12 = true;\n return [vp + 2, s];\n }\n case \"MST\": {\n const p2 = consumeTzAbbr(val, vp);\n // We don't map abbreviation → offset (ambiguous); keep current offset.\n return [p2, s];\n }\n case \"-0700\": {\n const [off, p2] = consumeOffset(val, vp, false);\n s.offsetMinutes = off;\n return [p2, s];\n }\n case \"-07:00\": {\n const [off, p2] = consumeOffset(val, vp, true);\n s.offsetMinutes = off;\n return [p2, s];\n }\n case \"-07\": {\n const sign = val[vp] === \"+\" ? 1 : val[vp] === \"-\" ? -1 : 0;\n if (sign === 0) throw new Error(`sprig toDate: expected +/- at pos ${vp}`);\n const [h, p2] = consumeDigits(val, vp + 1, 2, 2);\n s.offsetMinutes = sign * h * 60;\n return [p2, s];\n }\n case \"Z0700\": {\n const [off, p2] = consumeZOrOffset(val, vp, false, false);\n s.offsetMinutes = off;\n return [p2, s];\n }\n case \"Z07:00\": {\n const [off, p2] = consumeZOrOffset(val, vp, true, false);\n s.offsetMinutes = off;\n return [p2, s];\n }\n case \"Z07\": {\n const [off, p2] = consumeZOrOffset(val, vp, false, true);\n s.offsetMinutes = off;\n return [p2, s];\n }\n case \".000000000\": {\n // consume dot + 9 digits (dot is required)\n if (val[vp] !== \".\") throw new Error(`sprig toDate: expected . at pos ${vp}`);\n const [ms, p3] = consumeFrac(val, vp + 1, 9);\n s.ms = ms;\n return [p3, s];\n }\n case \".999999999\": {\n // optional: if val has a dot here, consume; otherwise skip\n if (val[vp] !== \".\") return [vp, s];\n const end = vp + 1;\n let e2 = end;\n while (e2 < val.length && val.charCodeAt(e2) >= 48 && val.charCodeAt(e2) <= 57) e2++;\n const frac = val.slice(end, e2).padEnd(9, \"0\");\n s.ms = Math.round(parseInt(frac, 10) / 1_000_000);\n return [e2, s];\n }\n case \".000000\": {\n // dot is required\n if (val[vp] !== \".\") throw new Error(`sprig toDate: expected . at pos ${vp}`);\n const [ms, p3] = consumeFrac(val, vp + 1, 6);\n s.ms = ms;\n return [p3, s];\n }\n case \".999999\": {\n if (val[vp] !== \".\") return [vp, s];\n const end = vp + 1;\n let e2 = end;\n while (e2 < val.length && val.charCodeAt(e2) >= 48 && val.charCodeAt(e2) <= 57) e2++;\n const frac = val.slice(end, e2).padEnd(9, \"0\");\n s.ms = Math.round(parseInt(frac, 10) / 1_000_000);\n return [e2, s];\n }\n case \".000\": {\n // dot is required\n if (val[vp] !== \".\") throw new Error(`sprig toDate: expected . at pos ${vp}`);\n const [ms, p3] = consumeFrac(val, vp + 1, 3);\n s.ms = ms;\n return [p3, s];\n }\n case \".999\": {\n if (val[vp] !== \".\") return [vp, s];\n const end = vp + 1;\n let e2 = end;\n while (e2 < val.length && val.charCodeAt(e2) >= 48 && val.charCodeAt(e2) <= 57) e2++;\n const frac = val.slice(end, e2).padEnd(3, \"0\");\n s.ms = parseInt(frac, 10);\n return [e2, s];\n }\n }\n throw new Error(`sprig toDate: unhandled token ${token}`);\n}\n\n// Token list in the same order as _format.ts (longest first).\nconst TOKENS: string[] = [\n \".000000000\",\n \".999999999\",\n \".000000\",\n \".999999\",\n \".000\",\n \".999\",\n \"January\",\n \"Monday\",\n \"Z07:00\",\n \"-07:00\",\n \"Z0700\",\n \"-0700\",\n \"2006\",\n \"Jan\",\n \"Mon\",\n \"MST\",\n \"-07\",\n \"Z07\",\n \"15\",\n \"01\",\n \"02\",\n \"_2\",\n \"03\",\n \"04\",\n \"05\",\n \"06\",\n \"PM\",\n \"pm\",\n \"1\",\n \"2\",\n \"3\",\n \"4\",\n \"5\",\n];\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Parse `value` according to Go's reference-time `layout`.\n * Returns a UTC-based `Date` whose wall time corresponds to the parsed\n * components adjusted for the parsed timezone offset.\n */\nexport function parseGoLayout(layout: string, value: string): Date {\n let lp = 0;\n let vp = 0;\n let st = defaultState();\n\n while (lp < layout.length) {\n let matched = false;\n for (const token of TOKENS) {\n if (layout.startsWith(token, lp)) {\n const [newVp, newSt] = dispatchToken(token, value, vp, st);\n vp = newVp;\n st = newSt;\n lp += token.length;\n matched = true;\n break;\n }\n }\n if (!matched) {\n // Literal character: must match in value.\n const lc = layout.charAt(lp);\n if (value[vp] !== lc) {\n throw new Error(\n `sprig toDate: expected ${JSON.stringify(lc)} at pos ${vp}, got ${JSON.stringify(value[vp])}`,\n );\n }\n lp++;\n vp++;\n }\n }\n\n // Verify the entire value string was consumed.\n if (vp !== value.length) {\n throw new Error(\n `sprig toDate: extra characters at pos ${vp}: ${JSON.stringify(value.slice(vp))}`,\n );\n }\n\n // Adjust 12-hour clock.\n if (st.hour12) {\n const h12 = st.hour % 12;\n st.hour = st.isPM ? h12 + 12 : h12;\n }\n\n // Build UTC timestamp from components + offset.\n const utcMs =\n Date.UTC(st.year, st.month - 1, st.day, st.hour, st.minute, st.second, st.ms) -\n st.offsetMinutes * 60 * 1000;\n return new Date(utcMs);\n}\n","import { parseGoLayout } from \"./_parse.js\";\n\n/**\n * `toDate format value` — parse `value` string using Go's reference-time\n * layout. Returns a `Date`. Mirrors Go sprig's `toDate`.\n */\nexport function toDate(format: string, value: string): Date {\n return parseGoLayout(format, value);\n}\n","import { resolveDate } from \"./_resolve.js\";\n\n/** `unixEpoch t` — seconds since Unix epoch as a decimal string. */\nexport function unixEpoch(t: unknown): string {\n return String(Math.floor(resolveDate(t).getTime() / 1000));\n}\n","/**\n * Sprig date/time functions — `now`, `date`, `dateInZone`, `dateModify`,\n * `htmlDate`, `htmlDateInZone`, `duration`, `durationRound`, `toDate`,\n * `ago`, `unixEpoch`.\n *\n * All \"current time\" reads go through the `clock` seam so tests can\n * freeze time deterministically. [LAW:single-enforcer]\n *\n * Go format-string support: the full reference-time token set including\n * fractional seconds, all timezone forms, and both 12h and 24h clocks.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport type { Clock } from \"./_clock.js\";\nimport { ago } from \"./ago.js\";\nimport { date } from \"./date.js\";\nimport { dateInZone } from \"./dateInZone.js\";\nimport { dateModify } from \"./dateModify.js\";\nimport { duration } from \"./duration.js\";\nimport { durationRound } from \"./durationRound.js\";\nimport { htmlDate } from \"./htmlDate.js\";\nimport { htmlDateInZone } from \"./htmlDateInZone.js\";\nimport { now } from \"./now.js\";\nimport { toDate } from \"./toDate.js\";\nimport { unixEpoch } from \"./unixEpoch.js\";\n\nexport {\n ago,\n date,\n dateInZone,\n dateModify,\n duration,\n durationRound,\n htmlDate,\n htmlDateInZone,\n now,\n toDate,\n unixEpoch,\n};\n\n/**\n * Build the sprig date/time FuncMap.\n *\n * @param clock - Source of \"current time\". Defaults to `() => new Date()`.\n * Pass a frozen clock for deterministic test output (mirrors\n * `EngineConfig.clock`).\n */\nexport function sprigDatetime(clock: Clock = () => new Date()): FuncMap {\n return {\n now: {\n fn: () => now(clock),\n argTypes: [],\n arity: { kind: \"exact\" },\n },\n date: {\n fn: (format, t) => date(format as string, t),\n argTypes: [\"string\", \"value\"],\n arity: { kind: \"exact\" },\n },\n dateInZone: {\n fn: (format, t, zone) => dateInZone(format as string, t, zone as string),\n argTypes: [\"string\", \"value\", \"string\"],\n arity: { kind: \"exact\" },\n },\n dateModify: {\n fn: (dur, t) => dateModify(dur as string, t),\n argTypes: [\"string\", \"value\"],\n arity: { kind: \"exact\" },\n },\n htmlDate: {\n fn: (t) => htmlDate(t),\n argTypes: [\"value\"],\n arity: { kind: \"exact\" },\n },\n htmlDateInZone: {\n fn: (t, zone) => htmlDateInZone(t, zone as string),\n argTypes: [\"value\", \"string\"],\n arity: { kind: \"exact\" },\n },\n duration: {\n fn: (sec) => duration(sec),\n argTypes: [\"value\"],\n arity: { kind: \"exact\" },\n },\n durationRound: {\n fn: (d) => durationRound(d),\n argTypes: [\"value\"],\n arity: { kind: \"exact\" },\n },\n toDate: {\n fn: (format, s) => toDate(format as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n ago: {\n fn: (t) => ago(t, clock),\n argTypes: [\"value\"],\n arity: { kind: \"exact\" },\n },\n unixEpoch: {\n fn: (t) => unixEpoch(t),\n argTypes: [\"value\"],\n arity: { kind: \"exact\" },\n },\n };\n}\n","/**\n * `empty val` — true if `val` is \"empty\" per Go sprig's rules:\n * nil, false, 0, 0.0, \"\", empty array/Map/object.\n *\n * Note: `empty 0` is true (this surprises newcomers — Go sprig matches\n * Go's reflect-IsZero semantics).\n */\n\nexport function empty(value: unknown): boolean {\n if (value === null || value === undefined) return true;\n if (value === false) return true;\n if (typeof value === \"number\") return value === 0 || Number.isNaN(value);\n if (typeof value === \"bigint\") return value === 0n;\n if (typeof value === \"string\") return value.length === 0;\n if (Array.isArray(value)) return value.length === 0;\n if (value instanceof Map) return value.size === 0;\n if (value instanceof Set) return value.size === 0;\n if (typeof value === \"object\") return Object.keys(value as object).length === 0;\n return false;\n}\n","/**\n * `coalesce a b c …` — returns the first non-empty argument, or\n * undefined if none are non-empty.\n */\n\nimport { empty } from \"./empty.js\";\n\nexport function coalesce(...values: readonly unknown[]): unknown {\n for (const v of values) {\n if (!empty(v)) return v;\n }\n return undefined;\n}\n","/**\n * `default defaultVal val` — returns `val` if non-empty (per `empty`),\n * else `defaultVal`.\n *\n * Argument order matches Go sprig: the *default* comes first, the\n * value comes second. Pipelines feed the trailing arg, so\n * `{{ .name | default \"anonymous\" }}` evaluates default(\"anonymous\", .name).\n */\n\nimport { empty } from \"./empty.js\";\n\nexport function defaultFn(defaultVal: unknown, value: unknown): unknown {\n return empty(value) ? defaultVal : value;\n}\n","/**\n * `fromJson s` — parses a JSON string into a value.\n *\n * Returns the parsed value. Throws if the input is not valid JSON,\n * matching Go sprig's behaviour (Go sprig propagates the parse error).\n */\n\nexport function fromJson(input: string): unknown {\n return JSON.parse(input);\n}\n","/**\n * `ternary trueVal falseVal cond` — returns `trueVal` if `cond` is\n * truthy, else `falseVal`.\n *\n * Note: argument order matches Go sprig and surprises newcomers.\n * Pipelines feed cond as the trailing arg, e.g.\n * `{{ .ok | ternary \"YES\" \"NO\" }}` → ternary(\"YES\", \"NO\", .ok)\n */\n\nimport { isTruthy } from \"../../evaluator/truthy.js\";\n\nexport function ternary(trueVal: unknown, falseVal: unknown, cond: unknown): unknown {\n return isTruthy(cond) ? trueVal : falseVal;\n}\n","/**\n * `toJson val` — serializes a value to compact JSON.\n *\n * Matches Go sprig in spirit but uses JS `JSON.stringify`. Note that\n * `JSON.stringify(undefined)` is undefined; we coerce that to \"null\"\n * for byte-equivalence with Go's encoding/json (which encodes\n * untyped-nil as null).\n */\n\nexport function toJson(value: unknown): string {\n return JSON.stringify(value) ?? \"null\";\n}\n","/**\n * `toPrettyJson val` — JSON with 2-space indentation, matching Go\n * sprig's output exactly.\n */\n\nexport function toPrettyJson(value: unknown): string {\n return JSON.stringify(value, null, 2) ?? \"null\";\n}\n","/**\n * Sprig defaults — `default`, `empty`, `coalesce`, `ternary`, JSON.\n *\n * [LAW:single-enforcer] One module owns the FuncMap registration for\n * this category. Consumers either import individual functions or\n * spread the whole map via `sprigDefaults()` into their EngineConfig.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { coalesce } from \"./coalesce.js\";\nimport { defaultFn } from \"./default.js\";\nimport { empty } from \"./empty.js\";\nimport { fromJson } from \"./fromJson.js\";\nimport { ternary } from \"./ternary.js\";\nimport { toJson } from \"./toJson.js\";\nimport { toPrettyJson } from \"./toPrettyJson.js\";\n\nexport { coalesce, defaultFn, empty, fromJson, ternary, toJson, toPrettyJson };\n\nexport function sprigDefaults(): FuncMap {\n // [LAW:one-source-of-truth] Intent-named slots replace \"any\" so the\n // label tells the reader why each slot accepts anything:\n // - \"value\" — heterogeneous slot (constructor / pass-through)\n // - \"truthy\" — value is consulted for emptiness/truthiness\n // - \"serializable\" — value is about to be JSON-encoded; the gate\n // rejects functions, symbols, and circular refs\n // so toJson/toPrettyJson never silently emit\n // \"null\" or throw deep inside the body.\n return {\n // Go: `dfault(d interface{}, given ...interface{})` — the value to\n // test is variadic, so `default \"fallback\"` with nothing to test is\n // a legal call that yields the fallback.\n default: {\n fn: (a, b) => defaultFn(a, b),\n argTypes: [\"value\", \"truthy\"],\n arity: { kind: \"variadic\" },\n },\n empty: { fn: (v) => empty(v), argTypes: [\"truthy\"], arity: { kind: \"exact\" } },\n coalesce: {\n fn: (...vs) => coalesce(...vs),\n argTypes: [\"truthy\"],\n arity: { kind: \"variadic\" },\n },\n ternary: {\n fn: (a, b, c) => ternary(a, b, c),\n argTypes: [\"value\", \"value\", \"truthy\"],\n arity: { kind: \"exact\" },\n },\n fromJson: { fn: (s) => fromJson(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n toJson: {\n fn: (v) => toJson(v),\n argTypes: [\"serializable\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n toPrettyJson: {\n fn: (v) => toPrettyJson(v),\n argTypes: [\"serializable\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n };\n}\n","/**\n * `dict k1 v1 k2 v2 …` — builds a record from alternating key/value pairs.\n *\n * [LAW:single-enforcer] The boundary gate (`enforceArgTypes`) validates\n * the kv cycle via `arity: { kind: \"alternating\" }` against\n * `argTypes: [\"string\", \"value\"]`, so every key position is a string by\n * the time the body runs. The body trusts the gate; no per-key probe.\n *\n * Odd-length call (`dict \"a\"`) leaves the last value `undefined` —\n * matches Go sprig.\n */\n\nimport type { ReferencedArg, ReferencedLiteral } from \"../../evaluator/evaluator.js\";\n\nexport function dict(...kvs: unknown[]): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (let i = 0; i < kvs.length; i += 2) {\n out[kvs[i] as string] = kvs[i + 1];\n }\n return out;\n}\n\n/**\n * Statically read a `(dict k1 v1 …)` call argument's key/value pairs from a\n * {@link ReferencedArg} projection (see `Template.referencedCalls`).\n *\n * Returns the entries only when the argument is provably a literal dict: a\n * nested call named `dict` whose args are ALL literals, string-typed at every\n * key position, in complete pairs. Anything else — a non-`dict` call, a\n * dynamic entry (`(dict \"k\" .x)`), a non-string key (which would fail the\n * runtime arg gate anyway), an odd-length pair list — returns `null`: the\n * value is not statically readable, and a value is never guessed\n * [LAW:no-silent-failure].\n *\n * [LAW:one-source-of-truth] Lives beside — and folds through — the runtime\n * `dict` above, so the static reading and the evaluated value share one\n * pairing semantics (including later-wins on duplicate keys).\n */\nexport function staticDictEntries(arg: ReferencedArg): Record<string, ReferencedLiteral> | null {\n if (arg.kind !== \"call\" || arg.name !== \"dict\" || arg.args.length % 2 !== 0) return null;\n const values: ReferencedLiteral[] = [];\n for (const [i, entry] of arg.args.entries()) {\n if (entry.kind !== \"literal\") return null;\n if (i % 2 === 0 && typeof entry.value !== \"string\") return null;\n values.push(entry.value);\n }\n // Every value is a ReferencedLiteral and every key slot a string, in\n // complete pairs — the runtime fold cannot introduce `unknown` or\n // `undefined`, so the cast only restates what the loop established.\n return dict(...values) as Record<string, ReferencedLiteral>;\n}\n","/**\n * `get d key` — returns d[key] or undefined.\n *\n * [LAW:single-enforcer] The gate validates `d` is a plain object\n * (`\"dict\"`); the body trusts the receiver type. The Map case lives in\n * template-laws-3gt.7 (where the slot widens with an explicit Map-key\n * carve-out per audit B5/B6) — until then, Maps are rejected at the\n * gate.\n */\nexport function get(d: Record<string, unknown>, key: string): unknown {\n return d[key];\n}\n","/**\n * `hasKey d key` — true when `key` is a own-property of `d`.\n *\n * Note: sprig's name is `hasKey` though docs sometimes say `haskey`.\n * [LAW:single-enforcer] Receiver type validated at the gate.\n */\nexport function hasKey(d: Record<string, unknown>, key: string): boolean {\n return key in d;\n}\n","/**\n * `keys d` — list of own enumerable string keys.\n *\n * [LAW:single-enforcer] Receiver type validated at the gate (`\"dict\"`);\n * the body trusts the parameter. Maps are rejected by the dict gate —\n * closes audit finding B6 (no silent `String(key)` flattening of\n * typed-T Map keys, because Maps never reach this body).\n */\nexport function keys(d: Record<string, unknown>): string[] {\n return Object.keys(d);\n}\n","/**\n * `merge dst src1 src2 …` — copies missing keys from sources into dst,\n * leaving dst's existing keys untouched. Returns a new dict.\n *\n * [LAW:single-enforcer] Every dict slot is gated as `\"dict\"` (variadic\n * trailing-repeat), so dst and every source are plain objects by the\n * time the body runs.\n */\nexport function merge(\n dst: Record<string, unknown>,\n ...sources: Record<string, unknown>[]\n): Record<string, unknown> {\n const out: Record<string, unknown> = { ...dst };\n for (const s of sources) {\n for (const [k, v] of Object.entries(s)) {\n if (!(k in out)) out[k] = v;\n }\n }\n return out;\n}\n","/**\n * `mergeOverwrite dst src1 src2 …` — like `merge` but later sources\n * overwrite earlier values.\n *\n * [LAW:single-enforcer] Every dict slot is gated as `\"dict\"`.\n */\nexport function mergeOverwrite(\n dst: Record<string, unknown>,\n ...sources: Record<string, unknown>[]\n): Record<string, unknown> {\n const out: Record<string, unknown> = { ...dst };\n for (const s of sources) {\n Object.assign(out, s);\n }\n return out;\n}\n","/**\n * `omit d k1 k2 …` — sub-dict with the listed keys removed.\n *\n * [LAW:single-enforcer] Receiver type validated at the gate.\n */\nexport function omit(d: Record<string, unknown>, ...drop: string[]): Record<string, unknown> {\n const set = new Set(drop);\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(d)) {\n if (!set.has(k)) out[k] = v;\n }\n return out;\n}\n","/**\n * `pick d k1 k2 …` — sub-dict with only the listed keys.\n *\n * [LAW:single-enforcer] Receiver type validated at the gate.\n */\nexport function pick(d: Record<string, unknown>, ...wanted: string[]): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of wanted) {\n if (key in d) out[key] = d[key];\n }\n return out;\n}\n","/**\n * `pluck key d1 d2 …` — collect d[key] from each dict that has it.\n *\n * [LAW:single-enforcer] Every dict slot is gated as `\"dict\"`; the body\n * trusts each receiver and skips entries that lack the key.\n */\nexport function pluck(key: string, ...dicts: Record<string, unknown>[]): unknown[] {\n const out: unknown[] = [];\n for (const d of dicts) {\n if (key in d) out.push(d[key]);\n }\n return out;\n}\n","/**\n * `set d key value` — mutates the receiver to bind `key=value` and\n * returns it. Matches Go sprig: the receiver and the returned value\n * are the same dict.\n *\n * [LAW:single-enforcer] Non-dict receivers are rejected at the gate\n * (`argTypes: [\"dict\", \"string\", \"value\"]`); the body trusts the\n * receiver type. The previous body-level `bodyTypeMismatch` (working-\n * tree fix in template-laws-703.10) became dead code once the slot\n * declared `\"dict\"` and was deleted in template-laws-3gt.3.\n */\nexport function set(\n d: Record<string, unknown>,\n key: string,\n value: unknown,\n): Record<string, unknown> {\n d[key] = value;\n return d;\n}\n","/**\n * `unset d key` — mutates the receiver to drop `key` and returns it.\n * Matches Go sprig: the receiver and the returned value are the same\n * dict.\n *\n * [LAW:single-enforcer] Non-dict receivers are rejected at the gate;\n * see `set.ts` for the rationale.\n */\nexport function unset(d: Record<string, unknown>, key: string): Record<string, unknown> {\n delete d[key];\n return d;\n}\n","/**\n * `values d` — list of own enumerable values.\n *\n * [LAW:single-enforcer] Receiver type validated at the gate.\n */\nexport function values(d: Record<string, unknown>): unknown[] {\n return Object.values(d);\n}\n","/** Sprig dict utilities — pair-files per epic spec. */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { dict, staticDictEntries } from \"./dict.js\";\nimport { get } from \"./get.js\";\nimport { hasKey } from \"./hasKey.js\";\nimport { keys } from \"./keys.js\";\nimport { merge } from \"./merge.js\";\nimport { mergeOverwrite } from \"./mergeOverwrite.js\";\nimport { omit } from \"./omit.js\";\nimport { pick } from \"./pick.js\";\nimport { pluck } from \"./pluck.js\";\nimport { set } from \"./set.js\";\nimport { unset } from \"./unset.js\";\nimport { values } from \"./values.js\";\n\nexport {\n dict,\n get,\n hasKey,\n keys,\n merge,\n mergeOverwrite,\n omit,\n pick,\n pluck,\n set,\n staticDictEntries,\n unset,\n values,\n};\n\nexport function sprigDicts(): FuncMap {\n // [LAW:single-enforcer] Dict slots declare \"dict\" so the gate enforces\n // plain-object-ness once. Bodies trust the param type and drop the\n // `(d && typeof d === \"object\" && !(d instanceof Map))` guards that\n // previously duplicated the check across 11 funcs.\n //\n // `dict` (constructor) uses arity: { kind: \"alternating\" } so the\n // gate validates the kv cycle (string at every even index, value at\n // every odd index) — otherwise the body would re-validate every key\n // beyond the first, splitting [LAW:single-enforcer] in two.\n //\n // Receivers are typed `Record<string, unknown>` in the bodies; the\n // `as unknown[]` casts at registration are erased once the gate has\n // narrowed the runtime type.\n return {\n dict: {\n fn: (...kv) => dict(...kv),\n argTypes: [\"string\", \"value\"],\n // Go: `dict(v ...interface{})` — no required arguments; `{{ dict }}`\n // is an empty dict. The cycle pairs even-index keys with\n // odd-index values.\n arity: { kind: \"alternating\", minimum: 0 },\n },\n get: {\n fn: (d, k) => get(d as Record<string, unknown>, k as string),\n argTypes: [\"dict\", \"string\"],\n arity: { kind: \"exact\" },\n },\n set: {\n fn: (d, k, v) => set(d as Record<string, unknown>, k as string, v),\n argTypes: [\"dict\", \"string\", \"value\"],\n arity: { kind: \"exact\" },\n // Go's `set` writes into the dict it is handed and returns it.\n writes: true,\n },\n unset: {\n fn: (d, k) => unset(d as Record<string, unknown>, k as string),\n argTypes: [\"dict\", \"string\"],\n arity: { kind: \"exact\" },\n writes: true,\n },\n // Go: `keys(dicts ...map[string]interface{})` — variadic, so no\n // argument is required and every dict past the first contributes\n // its keys too. `arity` declares Go's gate, not what this body\n // currently consumes: the body reads one dict, ignores the rest,\n // and throws on none where Go returns `[]`. Narrowing the arity to\n // match the body would paper over that gap and invent a divergence\n // the gate would then enforce; the gap is tracked on the\n // conformance epic instead.\n keys: {\n fn: (d) => keys(d as Record<string, unknown>),\n argTypes: [\"dict\"],\n arity: { kind: \"variadic\" },\n },\n values: {\n fn: (d) => values(d as Record<string, unknown>),\n argTypes: [\"dict\"],\n arity: { kind: \"exact\" },\n },\n pluck: {\n fn: (k, ...d) => pluck(k as string, ...(d as Record<string, unknown>[])),\n argTypes: [\"string\", \"dict\"],\n arity: { kind: \"variadic\" },\n },\n pick: {\n fn: (d, ...k) => pick(d as Record<string, unknown>, ...(k as string[])),\n argTypes: [\"dict\", \"string\"],\n arity: { kind: \"variadic\" },\n },\n omit: {\n fn: (d, ...k) => omit(d as Record<string, unknown>, ...(k as string[])),\n argTypes: [\"dict\", \"string\"],\n arity: { kind: \"variadic\" },\n },\n hasKey: {\n fn: (d, k) => hasKey(d as Record<string, unknown>, k as string),\n argTypes: [\"dict\", \"string\"],\n arity: { kind: \"exact\" },\n },\n merge: {\n fn: (d, ...s) => merge(d as Record<string, unknown>, ...(s as Record<string, unknown>[])),\n argTypes: [\"dict\", \"dict\"],\n arity: { kind: \"variadic\" },\n },\n mergeOverwrite: {\n fn: (d, ...s) =>\n mergeOverwrite(d as Record<string, unknown>, ...(s as Record<string, unknown>[])),\n argTypes: [\"dict\", \"dict\"],\n arity: { kind: \"variadic\" },\n },\n };\n}\n","/**\n * `fail msg` — unconditionally abort template evaluation with `msg`.\n *\n * Mirrors Go sprig's `fail`, which returns `(string, error)` and causes\n * text/template to stop execution. Throws `FailError` so consumers can\n * catch it specifically and distinguish it from engine errors.\n *\n * [LAW:types-are-the-program] Return type `never` encodes the invariant\n * that this function never returns — the type system enforces what a\n * comment would only suggest.\n */\n\nimport { FailError } from \"../../errors.js\";\n\nexport function fail(msg: string): never {\n throw new FailError(msg);\n}\n","/**\n * Sprig flow-control functions — `fail`.\n *\n * [LAW:single-enforcer] One module owns the FuncMap registration.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { fail } from \"./fail.js\";\n\nexport { fail };\n\nexport function sprigFlow(): FuncMap {\n return {\n fail: { fn: (msg) => fail(msg as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n };\n}\n","const _enc = new TextEncoder();\nconst MOD_ADLER = 65521;\n\n/**\n * `adler32sum s` — Adler-32 checksum of `s` as a decimal string.\n *\n * Matches Go's `hash/adler32.Checksum([]byte(s))` formatted with `%d`.\n * Uses unsigned 32-bit arithmetic via `>>> 0` to mirror Go's uint32 result.\n */\nexport function adler32sum(s: string): string {\n const bytes = _enc.encode(s);\n let a = 1;\n let b = 0;\n for (const byte of bytes) {\n a = (a + byte) % MOD_ADLER;\n b = (b + a) % MOD_ADLER;\n }\n return String((b * 65536 + a) >>> 0);\n}\n","/**\n * [LAW:one-source-of-truth] RFC 4648 base32 alphabet and decode table —\n * shared by b32enc and b32dec.\n */\n\nexport const ALPHA32 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n\n/** Reverse lookup: character → 5-bit value. */\nexport const DECODE32: ReadonlyMap<string, number> = new Map(\n Array.from(ALPHA32).map((c, i) => [c, i] as [string, number]),\n);\n","import { DECODE32 } from \"./_b32.js\";\n\nconst _dec = new TextDecoder();\n\n/** `b32dec s` — RFC 4648 base32 decoded back to a UTF-8 string. */\nexport function b32dec(s: string): string {\n const stripped = s.replace(/=+$/, \"\").toUpperCase();\n const bytes: number[] = [];\n let bits = 0;\n let value = 0;\n for (const c of stripped) {\n const v = DECODE32.get(c);\n if (v === undefined) throw new Error(`b32dec: invalid character '${c}'`);\n value = (value << 5) | v;\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n bytes.push((value >> bits) & 0xff);\n }\n }\n return _dec.decode(new Uint8Array(bytes));\n}\n","import { ALPHA32 } from \"./_b32.js\";\n\nconst _enc = new TextEncoder();\n\n/** `b32enc s` — UTF-8 bytes of `s` encoded as RFC 4648 base32. */\nexport function b32enc(s: string): string {\n const bytes = _enc.encode(s);\n let result = \"\";\n let bits = 0;\n let value = 0;\n for (const byte of bytes) {\n value = (value << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n result += ALPHA32[(value >> bits) & 31];\n }\n }\n if (bits > 0) result += ALPHA32[(value << (5 - bits)) & 31];\n while (result.length % 8 !== 0) result += \"=\";\n return result;\n}\n","const _dec = new TextDecoder();\n\n/** `b64dec s` — standard base64 decoded back to a UTF-8 string. */\nexport function b64dec(s: string): string {\n const binary = atob(s);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return _dec.decode(bytes);\n}\n","const _enc = new TextEncoder();\n\n/** `b64enc s` — UTF-8 bytes of `s` encoded as standard base64. */\nexport function b64enc(s: string): string {\n const bytes = _enc.encode(s);\n const chars = [];\n for (const b of bytes) chars.push(String.fromCharCode(b));\n return btoa(chars.join(\"\"));\n}\n","import { sha1 } from \"@noble/hashes/legacy.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\n\n/** `sha1sum s` — hex-encoded SHA-1 digest of `s` (UTF-8). */\nexport function sha1sum(s: string): string {\n return bytesToHex(sha1(utf8ToBytes(s)));\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\n\n/** `sha256sum s` — hex-encoded SHA-256 digest of `s` (UTF-8). */\nexport function sha256sum(s: string): string {\n return bytesToHex(sha256(utf8ToBytes(s)));\n}\n","import { sha512 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\n\n/** `sha512sum s` — hex-encoded SHA-512 digest of `s` (UTF-8). */\nexport function sha512sum(s: string): string {\n return bytesToHex(sha512(utf8ToBytes(s)));\n}\n","/**\n * `uuidv4` — RFC 4122 v4 UUID via `globalThis.crypto.randomUUID()`.\n *\n * Available in Node >= 20.19 (package minimum), Bun, Deno, and all modern browsers.\n * Throws if the runtime lacks `crypto.randomUUID` — this should never\n * happen in the supported environment set.\n */\nexport function uuidv4(): string {\n // [LAW:no-defensive-null-guards] We assert availability rather than silently\n // falling back: a missing crypto.randomUUID is a configuration problem that\n // should surface loudly, not be papered over with a Math.random fallback.\n if (typeof globalThis.crypto?.randomUUID !== \"function\") {\n throw new Error(\"uuidv4: globalThis.crypto.randomUUID is not available\");\n }\n return globalThis.crypto.randomUUID();\n}\n","/**\n * Sprig hash, encoding, and UUID functions — `b64enc`, `b64dec`, `b32enc`,\n * `b32dec`, `sha1sum`, `sha256sum`, `sha512sum`, `adler32sum`, `uuidv4`.\n *\n * All functions are pure and synchronous. SHA-* use @noble/hashes (audited,\n * zero-dep, ~5 KB gzipped per family); encoding is hand-rolled per RFC 4648;\n * UUID uses globalThis.crypto.randomUUID.\n *\n * [LAW:single-enforcer] FuncMap registration is the only place that maps\n * sprig template names to implementations.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { adler32sum } from \"./adler32sum.js\";\nimport { b32dec } from \"./b32dec.js\";\nimport { b32enc } from \"./b32enc.js\";\nimport { b64dec } from \"./b64dec.js\";\nimport { b64enc } from \"./b64enc.js\";\nimport { sha1sum } from \"./sha1sum.js\";\nimport { sha256sum } from \"./sha256sum.js\";\nimport { sha512sum } from \"./sha512sum.js\";\nimport { uuidv4 } from \"./uuidv4.js\";\n\nexport { adler32sum, b32dec, b32enc, b64dec, b64enc, sha1sum, sha256sum, sha512sum, uuidv4 };\n\n/** Build the sprig hash/encoding FuncMap. */\nexport function sprigHash(): FuncMap {\n return {\n b64enc: { fn: (s) => b64enc(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n b64dec: { fn: (s) => b64dec(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n b32enc: { fn: (s) => b32enc(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n b32dec: { fn: (s) => b32dec(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n sha1sum: { fn: (s) => sha1sum(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n sha256sum: {\n fn: (s) => sha256sum(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n },\n sha512sum: {\n fn: (s) => sha512sum(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n },\n adler32sum: {\n fn: (s) => adler32sum(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n },\n uuidv4: { fn: () => uuidv4(), argTypes: [], arity: { kind: \"exact\" } },\n };\n}\n","/**\n * `all v1 v2 …` — true iff `empty(x)` is false for every argument.\n * An empty argument list returns true (Go sprig: vacuous truth).\n *\n * [LAW:one-source-of-truth] Truthiness uses the same `empty()` helper\n * the rest of the sprig surface (default, coalesce, empty) routes\n * through, so \"is this empty?\" has exactly one answer.\n */\n\nimport { empty } from \"../defaults/empty.js\";\n\nexport function all(...values: readonly unknown[]): boolean {\n for (const v of values) {\n if (empty(v)) return false;\n }\n return true;\n}\n","/**\n * `any v1 v2 …` — true iff `empty(x)` is false for at least one\n * argument. An empty argument list returns false.\n *\n * [LAW:one-source-of-truth] Truthiness uses the same `empty()` helper\n * the rest of the sprig surface (default, coalesce, empty) routes\n * through, so \"is this empty?\" has exactly one answer.\n */\n\nimport { empty } from \"../defaults/empty.js\";\n\nexport function any(...values: readonly unknown[]): boolean {\n for (const v of values) {\n if (!empty(v)) return true;\n }\n return false;\n}\n","/** `append list item` — add item at the end. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function append(list: unknown[], item: unknown): unknown[] {\n return [...list, item];\n}\n","/** `chunk size list` — split list into sub-lists of `size`. */\n// [LAW:single-enforcer] The \"int\" gate admits only an integer `size`\n// (Go declares it `int`); the \"list\" gate validates array-ness. Body clamps the lower\n// bound to 1 (domain rule: chunks of <1 are nonsensical).\nexport function chunk(size: number, list: unknown[]): unknown[][] {\n const n = Math.max(1, size);\n const out: unknown[][] = [];\n for (let i = 0; i < list.length; i += n) {\n out.push(list.slice(i, i + n));\n }\n return out;\n}\n","import { empty } from \"../defaults/empty.js\";\n\n/** `compact list` — drop empty values per sprig's `empty` rules. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function compact(list: unknown[]): unknown[] {\n return list.filter((v) => !empty(v));\n}\n","/** `concat a b c …` — flat-concat lists. */\n// [LAW:single-enforcer] The variadic \"list\" slot validates array-ness\n// for every argument; this body trusts the param type and skips the\n// per-element Array.isArray guard.\nexport function concat(...lists: unknown[][]): unknown[] {\n const out: unknown[] = [];\n for (const l of lists) {\n out.push(...l);\n }\n return out;\n}\n","/**\n * Re-exports from the unified error module, plus a small helper for\n * constructing `TypeMismatchError` from inside sprig func bodies.\n *\n * Historical location — code that imported from this path keeps\n * working. New code should import directly from `src/errors.ts`.\n */\n\nimport { TypeMismatchError } from \"../errors.js\";\n\nexport {\n type ArgCount,\n ArgCountError,\n EvalError,\n FuncNotFoundError,\n MissingFieldError,\n TemplateError,\n TypeMismatchError,\n} from \"../errors.js\";\n\nconst NO_POS = { line: 0, column: 0, offset: 0 } as const;\n\n/**\n * Construct a TypeMismatchError from inside a registered func body,\n * where the call-site `pos` is unavailable. The dispatch site\n * (`evalCommand`) catches this and re-emits with the correct pos —\n * see [LAW:single-enforcer] in evaluator.ts.\n *\n * Use when the gate cannot validate (nested elements, alternating\n * variadic positions). For first-class arg validation, declare the\n * type in `argTypes` so `enforceArgTypes` catches it at the boundary.\n */\nexport function bodyTypeMismatch(\n funcName: string,\n argIndex: number,\n expected: string,\n receivedSummary: string,\n): TypeMismatchError {\n return new TypeMismatchError(funcName, argIndex, expected, receivedSummary, NO_POS);\n}\n","/**\n * `dig key1 key2 … default dict` — walks nested dict by string keys,\n * returning the deepest value found, or `default` when a key along\n * the path is missing.\n *\n * The argument shape is *positional from the end*:\n *\n * dig \"a\" \"b\" \"c\" <default> <dict>\n *\n * — last arg is the dict, the one before it is the default, every\n * preceding arg is a string key. This shape comes straight from Go\n * sprig and is unintuitive but documented.\n *\n * [LAW:single-enforcer] exception: `argTypes: [\"value\"]` (variadic\n * trailing slot) — the from-the-end positional shape cannot be\n * expressed by the gate's positional-from-the-start + trailing-repeat\n * model. We accept body-side validation here and use\n * `bodyTypeMismatch` so failures still surface as TypeMismatchError\n * with the correct call-site pos.\n */\n\nimport { typeNameOf } from \"../../evaluator/builtins.js\";\nimport { bodyTypeMismatch } from \"../../evaluator/errors.js\";\n\nexport function dig(...args: unknown[]): unknown {\n if (args.length < 3) {\n // Match Go's `panic(\"dig needs at least three arguments\")`.\n throw bodyTypeMismatch(\n \"dig\",\n 0,\n \"at least 3 arguments (...keys, default, dict)\",\n `${args.length} argument${args.length === 1 ? \"\" : \"s\"}`,\n );\n }\n const dict = args[args.length - 1];\n const def = args[args.length - 2];\n const keys = args.slice(0, -2);\n\n if (!isPlainDict(dict)) {\n throw bodyTypeMismatch(\"dig\", args.length - 1, \"dict\", typeNameOf(dict));\n }\n for (let i = 0; i < keys.length; i++) {\n if (typeof keys[i] !== \"string\") {\n throw bodyTypeMismatch(\"dig\", i, \"string\", typeNameOf(keys[i]));\n }\n }\n\n return digFromDict(dict as Record<string, unknown>, def, keys as string[], args.length);\n}\n\nfunction digFromDict(\n d: Record<string, unknown>,\n def: unknown,\n ks: readonly string[],\n argCount: number,\n): unknown {\n const k = ks[0] as string;\n if (!Object.hasOwn(d, k)) return def;\n const step = d[k];\n if (ks.length === 1) return step;\n // Go would `step.(map[string]interface{})` here, panicking on a\n // non-map intermediate. Mirror that — surface it as a typed error\n // rather than letting JS coerce silently.\n if (!isPlainDict(step)) {\n // Attribute to dict arg (last arg position).\n throw bodyTypeMismatch(\"dig\", argCount - 1, \"dict at intermediate key\", typeNameOf(step));\n }\n return digFromDict(step as Record<string, unknown>, def, ks.slice(1), argCount);\n}\n\nfunction isPlainDict(v: unknown): v is Record<string, unknown> {\n return (\n v !== null &&\n typeof v === \"object\" &&\n !Array.isArray(v) &&\n !(v instanceof Map) &&\n !(v instanceof Set)\n );\n}\n","// [LAW:single-enforcer] The \"list\" gate validates array-ness; this\n// body trusts the param type. Per Go sprig, `first` accepts lists only\n// — strings are not lists, so the previous string fallback is gone.\nexport function first(list: unknown[]): unknown {\n return list[0];\n}\n","import { deepEqual } from \"../types/deepEqual.js\";\n\n/** `has item list` — true iff `item` ∈ `list`. Note arg order matches Go sprig. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\n// [LAW:one-source-of-truth] Element equality routes through `deepEqual`,\n// matching Go sprig's `reflect.DeepEqual` (closes audit G4).\nexport function has(item: unknown, list: unknown[]): boolean {\n return list.some((e) => deepEqual(e, item));\n}\n","/** All elements except the last. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function initial(list: unknown[]): unknown[] {\n return list.slice(0, -1);\n}\n","// [LAW:single-enforcer] The \"list\" gate validates array-ness; this\n// body trusts the param type. Per Go sprig, `last` accepts lists only\n// — strings are not lists, so the previous string fallback is gone.\nexport function last(list: unknown[]): unknown {\n return list[list.length - 1];\n}\n","/**\n * Sprig `len` — same shape as the evaluator's built-in `len`. Re-exposed\n * here so the sprig category is self-contained per the epic's required\n * layout.\n *\n * [LAW:single-enforcer] Sized-kind validation lives at the gate via\n * argTypes: [\"sized\"]. The body picks the per-kind readout; nil and\n * non-sized values are rejected once by `enforceArgTypes`, never here.\n */\nexport function len(value: unknown): number {\n if (Array.isArray(value)) return value.length;\n if (typeof value === \"string\") return value.length;\n if (value instanceof Map) return value.size;\n if (value instanceof Set) return value.size;\n return Object.keys(value as object).length;\n}\n","/** `list a b c …` — constructs a list from the given items. */\nexport function list(...items: unknown[]): unknown[] {\n return items;\n}\n","/** `prepend list item` — add item at the front. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function prepend(list: unknown[], item: unknown): unknown[] {\n return [item, ...list];\n}\n","/** All elements except the first. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function rest(list: unknown[]): unknown[] {\n return list.slice(1);\n}\n","// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function reverse(list: unknown[]): unknown[] {\n return [...list].reverse();\n}\n","/** `slice list [i [j]]` — Array.prototype.slice. */\n// [LAW:single-enforcer] The \"list\" and \"truncating-int\" gates validate\n// array-ness and hand over indices truncated toward zero (sprig's cast);\n// missing trailing args remain undefined (the gate loops only over\n// present values), so i/j stay optional but never null.\nexport function slice(list: unknown[], i?: number, j?: number): unknown[] {\n const start = i === undefined ? 0 : i;\n const end = j === undefined ? list.length : j;\n return list.slice(start, end);\n}\n","/**\n * `sortAlpha list` — stringify each element, sort lexicographically.\n * Returns `string[]`.\n *\n * Mirrors Go sprig's `sortAlpha`, which calls `strslice` (skips nil\n * entries, stringifies the rest via `strval`) then `sort.StringSlice`.\n * `String(v)` lines up with Go's `%v` for primitives; non-ASCII byte\n * ordering is identical to Go's `sort.StringSlice` for ASCII input\n * (the only kind the conformance fixtures exercise).\n */\n\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function sortAlpha(list: readonly unknown[]): string[] {\n const out: string[] = [];\n for (const v of list) {\n // Go's `strslice` skips nil entries — match.\n if (v === null || v === undefined) continue;\n out.push(String(v));\n }\n return out.sort();\n}\n","import { deepEqual } from \"../types/deepEqual.js\";\n\n/** Unique values, preserving first-occurrence order. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\n// [LAW:one-source-of-truth] Element equality routes through `deepEqual`,\n// matching Go sprig's `reflect.DeepEqual` (closes audit G4).\nexport function uniq(list: unknown[]): unknown[] {\n const out: unknown[] = [];\n for (const v of list) if (!out.some((e) => deepEqual(e, v))) out.push(v);\n return out;\n}\n","import { deepEqual } from \"../types/deepEqual.js\";\n\n/** `without list a b c …` — drop any of a/b/c… from list. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\n// [LAW:one-source-of-truth] Element equality routes through `deepEqual`,\n// matching Go sprig's `reflect.DeepEqual` (closes audit G4).\nexport function without(list: unknown[], ...exclude: unknown[]): unknown[] {\n return list.filter((v) => !exclude.some((e) => deepEqual(e, v)));\n}\n","/** Sprig list utilities — pair-files per epic spec. */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { all } from \"./all.js\";\nimport { any } from \"./any.js\";\nimport { append } from \"./append.js\";\nimport { chunk } from \"./chunk.js\";\nimport { compact } from \"./compact.js\";\nimport { concat } from \"./concat.js\";\nimport { dig } from \"./dig.js\";\nimport { first } from \"./first.js\";\nimport { has } from \"./has.js\";\nimport { initial } from \"./initial.js\";\nimport { last } from \"./last.js\";\nimport { len } from \"./len.js\";\nimport { list } from \"./list.js\";\nimport { prepend } from \"./prepend.js\";\nimport { rest } from \"./rest.js\";\nimport { reverse } from \"./reverse.js\";\nimport { slice } from \"./slice.js\";\nimport { sortAlpha } from \"./sortAlpha.js\";\nimport { uniq } from \"./uniq.js\";\nimport { without } from \"./without.js\";\n\nexport {\n all,\n any,\n append,\n chunk,\n compact,\n concat,\n dig,\n first,\n has,\n initial,\n last,\n len,\n list,\n prepend,\n rest,\n reverse,\n slice,\n sortAlpha,\n uniq,\n without,\n};\n\nexport function sprigLists(): FuncMap {\n // [LAW:single-enforcer] List slots declare \"list\" so the gate enforces\n // array-ness once. Bodies trust the param type and drop the defensive\n // `Array.isArray` guards that previously duplicated the check 14 times.\n // Item slots that are genuinely heterogeneous use \"value\" — they still\n // accept anything, but the label documents intent (per template-laws-3gt.1).\n // `len` declares \"sized\" (template-laws-3gt.4) — the body trusts the\n // gate. `list` (constructor) declares \"value\" (template-laws-3gt.8)\n // — heterogeneous-by-intent.\n return {\n list: {\n fn: (...a) => list(...a),\n argTypes: [\"value\"],\n arity: { kind: \"variadic\" },\n },\n first: { fn: (l) => first(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n last: { fn: (l) => last(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n rest: { fn: (l) => rest(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n initial: { fn: (l) => initial(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n len: { fn: (l) => len(l), argTypes: [\"sized\"], arity: { kind: \"exact\" } },\n reverse: { fn: (l) => reverse(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n uniq: { fn: (l) => uniq(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n without: {\n fn: (l, ...e) => without(l as unknown[], ...e),\n argTypes: [\"list\", \"value\"],\n arity: { kind: \"variadic\" },\n },\n has: {\n fn: (i, l) => has(i, l as unknown[]),\n argTypes: [\"value\", \"list\"],\n arity: { kind: \"exact\" },\n },\n compact: { fn: (l) => compact(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n // Go: `slice(list interface{}, indices ...interface{})` — one\n // required list and any number of indices, so `slice .l 1` and\n // `slice .l` are both legal. Declaring three fixed slots would make\n // the gate reject them, inventing a divergence. The repeating\n // \"truncating-int\" slot covers both indices: sprig reads them through\n // `cast.ToInt`, which truncates a fractional.\n slice: {\n fn: (l, i, j) => slice(l as unknown[], i as number | undefined, j as number | undefined),\n argTypes: [\"list\", \"truncating-int\"],\n arity: { kind: \"variadic\" },\n },\n concat: {\n fn: (...l) => concat(...(l as unknown[][])),\n argTypes: [\"list\"],\n arity: { kind: \"variadic\" },\n },\n chunk: {\n fn: (s, l) => chunk(s as number, l as unknown[]),\n argTypes: [\"int\", \"list\"],\n arity: { kind: \"exact\" },\n },\n prepend: {\n fn: (l, i) => prepend(l as unknown[], i),\n argTypes: [\"list\", \"value\"],\n arity: { kind: \"exact\" },\n },\n append: {\n fn: (l, i) => append(l as unknown[], i),\n argTypes: [\"list\", \"value\"],\n arity: { kind: \"exact\" },\n },\n sortAlpha: {\n fn: (l) => sortAlpha(l as unknown[]),\n argTypes: [\"list\"],\n arity: { kind: \"exact\" },\n returnType: \"list\",\n },\n // [LAW:one-source-of-truth] `push` is Go sprig's deprecated alias for\n // `append`. Registered directly against the same closure so divergence\n // is impossible — same pattern as `biggest`→`max` in sprigMath.\n push: {\n fn: (l, i) => append(l as unknown[], i),\n argTypes: [\"list\", \"value\"],\n arity: { kind: \"exact\" },\n },\n // [LAW:one-source-of-truth] `tuple` is Go sprig's alias for `list`.\n tuple: {\n fn: (...a) => list(...a),\n argTypes: [\"value\"],\n arity: { kind: \"variadic\" },\n },\n // [LAW:single-enforcer] exception: `dig`'s \"...keys, default, dict\"\n // shape is positional from the *end* — the gate's positional-from-the-\n // start + trailing-repeat model can't express it. Body-side validation\n // surfaces failures via `bodyTypeMismatch` so call-site pos is preserved.\n // Go: `dig(ps ...interface{})` — the arity gate requires nothing.\n // Sprig's own \"dig needs at least three arguments\" is a body-side\n // panic, not an arity error, and `dig`'s body already reproduces it.\n // Declaring a minimum of 3 here would move that failure to the gate\n // and change its message away from Go's.\n dig: {\n fn: (...a) => dig(...a),\n argTypes: [\"value\"],\n arity: { kind: \"variadic\" },\n },\n all: {\n fn: (...a) => all(...a),\n argTypes: [\"truthy\"],\n arity: { kind: \"variadic\" },\n returnType: \"bool\",\n },\n any: {\n fn: (...a) => any(...a),\n argTypes: [\"truthy\"],\n arity: { kind: \"variadic\" },\n returnType: \"bool\",\n },\n };\n}\n","/** `add a b c …` — variadic integer sum. */\nexport function add(...args: number[]): number {\n return args.reduce((acc, v) => acc + v, 0);\n}\n","/** `add1 n` — integer increment. Mirrors Go sprig's `add1(i interface{}) int64`. */\nexport function add1(n: number): number {\n return n + 1;\n}\n","/** `add1f n` — float increment. Mirrors Go sprig's `add1f(i interface{}) float64`. */\nexport function add1f(n: number): number {\n return n + 1;\n}\n","export function addf(...args: number[]): number {\n return args.reduce((acc, v) => acc + v, 0);\n}\n","export function ceil(a: number): number {\n return Math.ceil(a);\n}\n","/** `div a b` — integer division (Go semantics: truncate toward zero). */\nexport function div(a: number, b: number): number {\n return Math.trunc(a / b);\n}\n","export function divf(a: number, ...rest: number[]): number {\n return rest.reduce((acc, v) => acc / v, a);\n}\n","export function floor(a: number): number {\n return Math.floor(a);\n}\n","/** `max a b c …` — variadic maximum (Go int64 semantics; args arrive truncated). */\nexport function max(...args: number[]): number {\n return args.reduce((m, v) => (v > m ? v : m), Number.NEGATIVE_INFINITY);\n}\n","/**\n * `maxf a b c …` — variadic float-typed maximum. Mirrors Go sprig's\n * `maxf` (float64, no truncation). Distinct from `max` (int64-truncated).\n */\nexport function maxf(...args: number[]): number {\n return args.reduce((m, v) => Math.max(m, v), -Infinity);\n}\n","/** `min a b c …` — variadic minimum (Go int64 semantics; args arrive truncated). */\nexport function min(...args: number[]): number {\n return args.reduce((m, v) => (v < m ? v : m), Number.POSITIVE_INFINITY);\n}\n","/** `minf a b c …` — variadic float-typed minimum. Float counterpart of `min` (int64-truncated). */\nexport function minf(...args: number[]): number {\n return args.reduce((m, v) => Math.min(m, v), Infinity);\n}\n","/** `mod a b` — modulo. JS `%` matches Go's: sign follows the dividend. */\nexport function mod(a: number, b: number): number {\n return a % b;\n}\n","/** `mul a b c …` — variadic integer product. */\nexport function mul(...args: number[]): number {\n return args.reduce((acc, v) => acc * v, 1);\n}\n","export function mulf(...args: number[]): number {\n return args.reduce((acc, v) => acc * v, 1);\n}\n","/** `round a [precision=0]` — round half-away-from-zero, matching Go sprig. */\nexport function round(a: number, precision: number = 0): number {\n const factor = 10 ** precision;\n return (Math.sign(a) * Math.round(Math.abs(a) * factor)) / factor;\n}\n","/**\n * `untilStep start stop step` — Python-`range`-shaped integer slice.\n * Mirrors Go sprig's `untilStep(start, stop, step int) []int`. Step\n * direction must agree with the start→stop direction; mismatched signs\n * (e.g. `start < stop` with `step <= 0`) yield an empty slice rather\n * than looping forever.\n */\n\nexport function untilStep(start: number, stop: number, step: number): number[] {\n const v: number[] = [];\n if (stop < start) {\n if (step >= 0) return v;\n for (let i = start; i > stop; i += step) v.push(i);\n return v;\n }\n if (step <= 0) return v;\n for (let i = start; i < stop; i += step) v.push(i);\n return v;\n}\n","/**\n * `seq …` — space-joined integer sequence. Mirrors Go sprig's `seq`,\n * which dispatches on arity and is **inclusive** of the end value:\n *\n * seq() → \"\"\n * seq(end) → 1..end (descending if end<1)\n * seq(start, end) → start..end (step ±1 by direction)\n * seq(start, step, end) → stepped, end inclusive when reached\n * 4+ args → \"\"\n *\n * Inclusivity is implemented the same way Go does it — by passing\n * `end + increment` (or `end + step` for the 2-arg case) into the\n * exclusive `untilStep`. The 3-arg form returns \"\" when the bounds\n * descend (`end < start`) but the caller passes a positive step —\n * matching Go's early-return at `if step > 0 { return \"\" }`.\n *\n * Output is the int slice joined with \" \", so `{{ seq 5 }}` emits\n * `1 2 3 4 5`. Result type is `string`, **not** `number[]`.\n */\n\nimport { untilStep } from \"./untilStep.js\";\n\nexport function seq(...params: number[]): string {\n let increment = 1;\n switch (params.length) {\n case 0:\n return \"\";\n case 1: {\n const start = 1;\n const end = params[0] as number;\n if (end < start) increment = -1;\n return untilStep(start, end + increment, increment).join(\" \");\n }\n case 2: {\n const start = params[0] as number;\n const end = params[1] as number;\n const step = end < start ? -1 : 1;\n return untilStep(start, end + step, step).join(\" \");\n }\n case 3: {\n const start = params[0] as number;\n const step = params[1] as number;\n const end = params[2] as number;\n if (end < start) {\n increment = -1;\n if (step > 0) return \"\";\n }\n return untilStep(start, end + increment, step).join(\" \");\n }\n default:\n return \"\";\n }\n}\n","export function sub(a: number, b: number): number {\n return a - b;\n}\n","export function subf(a: number, ...rest: number[]): number {\n return rest.reduce((acc, v) => acc - v, a);\n}\n","/**\n * `until count` — `[0, 1, …, count-1]` for positive counts, or\n * `[0, -1, …, count+1]` for negative counts. Mirrors Go sprig's\n * `until`, which derives step direction from the sign of `count`\n * and delegates to `untilStep`.\n */\n\nimport { untilStep } from \"./untilStep.js\";\n\nexport function until(count: number): number[] {\n return untilStep(0, count, count < 0 ? -1 : 1);\n}\n","/** Sprig math utilities — int and float arithmetic. */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { add } from \"./add.js\";\nimport { add1 } from \"./add1.js\";\nimport { add1f } from \"./add1f.js\";\nimport { addf } from \"./addf.js\";\nimport { ceil } from \"./ceil.js\";\nimport { div } from \"./div.js\";\nimport { divf } from \"./divf.js\";\nimport { floor } from \"./floor.js\";\nimport { max } from \"./max.js\";\nimport { maxf } from \"./maxf.js\";\nimport { min } from \"./min.js\";\nimport { minf } from \"./minf.js\";\nimport { mod } from \"./mod.js\";\nimport { mul } from \"./mul.js\";\nimport { mulf } from \"./mulf.js\";\nimport { round } from \"./round.js\";\nimport { seq } from \"./seq.js\";\nimport { sub } from \"./sub.js\";\nimport { subf } from \"./subf.js\";\nimport { until } from \"./until.js\";\nimport { untilStep } from \"./untilStep.js\";\n\nexport {\n add,\n add1,\n add1f,\n addf,\n ceil,\n div,\n divf,\n floor,\n max,\n maxf,\n min,\n minf,\n mod,\n mul,\n mulf,\n round,\n seq,\n sub,\n subf,\n until,\n untilStep,\n};\n\nexport function sprigMath(): FuncMap {\n // [LAW:single-enforcer] enforceArgTypes normalizes numeric slots to\n // plain `number` before dispatch. Sprig reads its `interface{}` math\n // arguments through `cast.ToInt64`, so those slots are\n // \"truncating-int\" (`max 1.5 2.5` is 2); `seq`/`until`/`untilStep` and\n // `round`'s precision are Go `int` parameters, so they are \"int\" and\n // refuse a fractional. \"float\" arrives coerced (IEEE-754 semantics).\n // Bodies receive `number`, never `bigint`.\n return {\n add: {\n fn: (...a) => add(...(a as number[])),\n argTypes: [\"truncating-int\"],\n arity: { kind: \"variadic\" },\n },\n sub: {\n fn: (a, b) => sub(a as number, b as number),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"exact\" },\n },\n mul: {\n fn: (...a) => mul(...(a as number[])),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"variadic\" },\n },\n div: {\n fn: (a, b) => div(a as number, b as number),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"exact\" },\n },\n mod: {\n fn: (a, b) => mod(a as number, b as number),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"exact\" },\n },\n min: {\n fn: (...a) => min(...(a as number[])),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"variadic\" },\n },\n max: {\n fn: (...a) => max(...(a as number[])),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"variadic\" },\n },\n floor: { fn: (a) => floor(a as number), argTypes: [\"float\"], arity: { kind: \"exact\" } },\n ceil: { fn: (a) => ceil(a as number), argTypes: [\"float\"], arity: { kind: \"exact\" } },\n // Go: `round(a interface{}, p int, rOpt ...float64)` — the\n // precision is a *required* parameter and only the rounding\n // threshold is variadic, so Go rejects `round 3.7`. `arity`\n // declares that gate; the body's `precision = 0` default and its\n // silent drop of `rOpt` are body-side gaps tracked on the\n // conformance epic, not reasons to widen the declaration.\n round: {\n fn: (a, p) => round(a as number, p as number),\n argTypes: [\"float\", \"int\", \"float\"],\n arity: { kind: \"variadic\" },\n },\n addf: {\n fn: (...a) => addf(...(a as number[])),\n argTypes: [\"float\"],\n arity: { kind: \"variadic\" },\n },\n // Go: `subf(a interface{}, v ...interface{})` — folds over every\n // argument, unlike the integer `sub`, which Go declares with two\n // fixed parameters.\n subf: {\n fn: (a, ...rest) => subf(a as number, ...(rest as number[])),\n argTypes: [\"float\", \"float\"],\n arity: { kind: \"variadic\" },\n },\n mulf: {\n fn: (...a) => mulf(...(a as number[])),\n argTypes: [\"float\", \"float\"],\n arity: { kind: \"variadic\" },\n },\n // Go: `divf(a interface{}, v ...interface{})` — folds over every\n // argument, unlike the integer `div`.\n divf: {\n fn: (a, ...rest) => divf(a as number, ...(rest as number[])),\n argTypes: [\"float\", \"float\"],\n arity: { kind: \"variadic\" },\n },\n add1: { fn: (n) => add1(n as number), argTypes: [\"truncating-int\"], arity: { kind: \"exact\" } },\n add1f: { fn: (n) => add1f(n as number), argTypes: [\"float\"], arity: { kind: \"exact\" } },\n maxf: {\n fn: (...a) => maxf(...(a as number[])),\n argTypes: [\"float\", \"float\"],\n arity: { kind: \"variadic\" },\n },\n minf: {\n fn: (...a) => minf(...(a as number[])),\n argTypes: [\"float\", \"float\"],\n arity: { kind: \"variadic\" },\n },\n // `biggest` is Go sprig's deprecated alias for `max`. Registered\n // directly against the same function so divergence is impossible.\n biggest: {\n fn: (...a) => max(...(a as number[])),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"variadic\" },\n },\n seq: {\n fn: (...a) => seq(...(a as number[])),\n argTypes: [\"int\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n until: {\n fn: (n) => until(n as number),\n argTypes: [\"int\"],\n arity: { kind: \"exact\" },\n returnType: \"list\",\n },\n untilStep: {\n fn: (a, b, c) => untilStep(a as number, b as number, c as number),\n argTypes: [\"int\", \"int\", \"int\"],\n arity: { kind: \"exact\" },\n returnType: \"list\",\n },\n };\n}\n","/**\n * Internal PRNG seam for sprig random functions.\n *\n * [LAW:single-enforcer] All randomness in this module routes through\n * the `random` parameter — never through `Math.random` directly. The\n * caller supplies the source; these helpers consume it.\n */\n\nexport class RandIntRangeError extends Error {\n constructor(min: number, max: number) {\n super(`randIntFromRange: max must be greater than min (max=${max}, min=${min})`);\n this.name = \"RandIntRangeError\";\n }\n}\n\n/** Clamp PRNG output to [0, 1) to defend against out-of-range injected sources. */\nexport function clampRandom(value: number): number {\n // [LAW:no-defensive-null-guards] Non-finite check is valid here: `random`\n // is caller-supplied (trust boundary), and NaN/Infinity are out-of-range.\n if (!Number.isFinite(value)) return 0;\n return Math.max(0, Math.min(value, 0.9999999999999999));\n}\n\nexport const ALPHA = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nexport const ALPHANUM = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\nexport const NUMERIC = \"0123456789\";\n// ASCII printable range 32–126 inclusive (matches Go sprig: Intn(95)+32).\nexport const ASCII = Array.from({ length: 95 }, (_, i) => String.fromCharCode(i + 32)).join(\"\");\n\nexport function randString(n: number, charset: string, random: () => number): string {\n const chars = [];\n for (let i = 0; i < n; i++) {\n chars.push(charset.charAt(Math.floor(clampRandom(random()) * charset.length)));\n }\n return chars.join(\"\");\n}\n\n/** Inclusive `min`, exclusive `max` — mirrors Go `rand.Intn(max-min)+min`. */\nexport function randIntFromRange(min: number, max: number, random: () => number): number {\n if (max <= min) throw new RandIntRangeError(min, max);\n return Math.floor(clampRandom(random()) * (max - min)) + min;\n}\n","import { ALPHA, randString } from \"./_prng.js\";\n\n/** `randAlpha n` — `n` random letters [A-Za-z]. */\nexport function randAlpha(n: number, random: () => number): string {\n return randString(n, ALPHA, random);\n}\n","import { ALPHANUM, randString } from \"./_prng.js\";\n\n/** `randAlphaNum n` — `n` random alphanumeric characters [A-Za-z0-9]. */\nexport function randAlphaNum(n: number, random: () => number): string {\n return randString(n, ALPHANUM, random);\n}\n","import { ASCII, randString } from \"./_prng.js\";\n\n/** `randAscii n` — `n` random printable ASCII characters (0x20–0x7E). */\nexport function randAscii(n: number, random: () => number): string {\n return randString(n, ASCII, random);\n}\n","import { bodyTypeMismatch } from \"../../evaluator/errors.js\";\nimport { RandIntRangeError, randIntFromRange } from \"./_prng.js\";\n\n/** `randInt min max` — random integer in [min, max). Mirrors Go sprig. */\nexport function randInt(min: number, max: number, random: () => number): number {\n try {\n return randIntFromRange(min, max, random);\n } catch (e) {\n if (e instanceof RandIntRangeError) {\n throw bodyTypeMismatch(\n \"randInt\",\n 2,\n \"max > min\",\n `constraint violated (max=${max}, min=${min})`,\n );\n }\n throw e;\n }\n}\n","import { NUMERIC, randString } from \"./_prng.js\";\n\n/** `randNumeric n` — `n` random decimal digits [0-9]. */\nexport function randNumeric(n: number, random: () => number): string {\n return randString(n, NUMERIC, random);\n}\n","/**\n * The rune-level string seam: the operations Go gets for free on its\n * strings and JS does not.\n *\n * [LAW:parse-dont-validate] Go walks a string as runes; JS strings are\n * UTF-16, so a character-position operation done on the raw string\n * (`s.slice(0, 1)`, `s[i]`, `s.length`, `s.split(\"\")`) splits an astral\n * character in half and yields a lone surrogate — `trunc 1 \"𐍈x\"`\n * returned \"\\ud800\", for which `isWellFormed()` is false. Decoding once,\n * up front, is the checkpoint: every element of the returned array is a\n * whole character, so an index into the middle of one is unrepresentable\n * and no slice of it can produce a lone surrogate. Callers re-encode\n * with `.join(\"\")`.\n *\n * Code points deliberately — not UTF-16 units, and not grapheme\n * clusters. Grapheme clustering would hold `\"é\"` together, a third\n * behaviour matching neither Go nor this engine.\n *\n * For splitting this buys exact Go parity. For slicing it buys\n * well-formedness instead: Go slices `trunc`/`substr`/`abbrev` by BYTE,\n * so `trunc 1 \"𐍈x\"` is the single invalid byte `\\xf0` there and the\n * whole `𐍈` here. That residual divergence is intended and tracked\n * separately; a rune is the closest well-formed unit to Go's byte.\n */\n\n/**\n * Decode `s` to its code points. The array is freshly built per call,\n * so callers may permute it in place (`shuffle` does).\n */\nexport function runes(s: string): string[] {\n return Array.from(s);\n}\n\n/**\n * `strings.Split(s, sep)` — an empty separator splits between runes,\n * where JS's `s.split(\"\")` splits between UTF-16 units and shears\n * astral characters into lone surrogates.\n *\n * [LAW:single-enforcer] `split`, `splitList`, `splitn`, and `replace`\n * all reach for Go's split; the empty-separator rule lives here so the\n * four cannot drift on it.\n */\nexport function goSplit(sep: string, s: string): string[] {\n return sep === \"\" ? runes(s) : s.split(sep);\n}\n","import { runes } from \"../strings/runes.js\";\nimport { clampRandom } from \"./_prng.js\";\n\n/**\n * `shuffle s` — returns a randomly permuted copy of `s`.\n *\n * Operates on Unicode code points (matching Go sprig's rune-level Fisher-Yates).\n */\nexport function shuffle(s: string, random: () => number): string {\n const cps = runes(s);\n for (let i = cps.length - 1; i > 0; i--) {\n const j = Math.floor(clampRandom(random()) * (i + 1));\n const tmp = cps[i] as string;\n cps[i] = cps[j] as string;\n cps[j] = tmp;\n }\n return cps.join(\"\");\n}\n","/**\n * Sprig random functions — `randInt`, `randAlpha`, `randAlphaNum`,\n * `randNumeric`, `randAscii`, `shuffle`.\n *\n * [LAW:single-enforcer] The `random` parameter is the *only* source of\n * randomness in this module. All six functions receive it from the\n * factory closure so there is one seam, not six.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { randAlpha } from \"./randAlpha.js\";\nimport { randAlphaNum } from \"./randAlphaNum.js\";\nimport { randAscii } from \"./randAscii.js\";\nimport { randInt } from \"./randInt.js\";\nimport { randNumeric } from \"./randNumeric.js\";\nimport { shuffle } from \"./shuffle.js\";\n\nexport { randAlpha, randAlphaNum, randAscii, randInt, randNumeric, shuffle };\n\n/**\n * Build the sprig random FuncMap.\n *\n * @param random - PRNG source. Defaults to `Math.random`. Pass a seeded\n * generator for reproducible templates (matches `EngineConfig.random`).\n */\nexport function sprigRandom(random: () => number = Math.random): FuncMap {\n return {\n randInt: {\n fn: (min, max) => randInt(min as number, max as number, random),\n argTypes: [\"int\", \"int\"],\n arity: { kind: \"exact\" },\n },\n randAlpha: {\n fn: (n) => randAlpha(n as number, random),\n argTypes: [\"int\"],\n arity: { kind: \"exact\" },\n },\n randAlphaNum: {\n fn: (n) => randAlphaNum(n as number, random),\n argTypes: [\"int\"],\n arity: { kind: \"exact\" },\n },\n randNumeric: {\n fn: (n) => randNumeric(n as number, random),\n argTypes: [\"int\"],\n arity: { kind: \"exact\" },\n },\n randAscii: {\n fn: (n) => randAscii(n as number, random),\n argTypes: [\"int\"],\n arity: { kind: \"exact\" },\n },\n shuffle: {\n fn: (s) => shuffle(s as string, random),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n },\n };\n}\n","/** `regexFind pattern s` — first match, or \"\" when no match. */\nexport function regexFind(pattern: string, s: string): string {\n const m = new RegExp(pattern).exec(s);\n return m ? m[0] : \"\";\n}\n","/**\n * `regexFindAll pattern s n` — first `n` matches (or all if n<0).\n * Mirrors Go sprig's signature: pattern, s, then optional n.\n */\nexport function regexFindAll(pattern: string, s: string, n: number = -1): string[] {\n const re = new RegExp(pattern, \"g\");\n const out: string[] = [];\n for (const m of s.matchAll(re)) {\n // Check before push so n=0 returns [] (Go regexp.FindAllString parity:\n // a non-negative n means *at most* n matches; n=0 means zero).\n if (n >= 0 && out.length >= n) break;\n out.push(m[0]);\n }\n return out;\n}\n","/** `regexMatch pattern s` — true iff JS regex matches anywhere in s. */\nexport function regexMatch(pattern: string, s: string): boolean {\n return new RegExp(pattern).test(s);\n}\n","/**\n * `regexReplaceAll pattern s repl` — replace ALL pattern matches with\n * the replacement string. Replacement supports JS's $1/$2/$<name>\n * backreference syntax.\n */\nexport function regexReplaceAll(pattern: string, s: string, repl: string): string {\n return s.replace(new RegExp(pattern, \"g\"), repl);\n}\n","/**\n * `regexReplaceAllLiteral` — like regexReplaceAll but the replacement\n * string is treated literally ($1/$2 are not expanded).\n */\nexport function regexReplaceAllLiteral(pattern: string, s: string, repl: string): string {\n // Escape `$` so JS's String.prototype.replace doesn't interpret it.\n const literal = repl.replace(/\\$/g, \"$$$$\");\n return s.replace(new RegExp(pattern, \"g\"), literal);\n}\n","/** `regexSplit pattern s n` — split by regex, optional max count. */\nexport function regexSplit(pattern: string, s: string, n: number = -1): string[] {\n const re = new RegExp(pattern);\n if (n < 0) return s.split(re);\n return s.split(re).slice(0, n);\n}\n","/**\n * Sprig regex utilities.\n *\n * Important divergence from Go sprig: these use **JS regex semantics**\n * (ECMAScript), not Go's RE2. Most patterns work identically; the\n * notable differences are lookbehind syntax and Unicode property\n * escapes. Document the divergence in the README when it lands.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { regexFind } from \"./regexFind.js\";\nimport { regexFindAll } from \"./regexFindAll.js\";\nimport { regexMatch } from \"./regexMatch.js\";\nimport { regexReplaceAll } from \"./regexReplaceAll.js\";\nimport { regexReplaceAllLiteral } from \"./regexReplaceAllLiteral.js\";\nimport { regexSplit } from \"./regexSplit.js\";\n\nexport { regexFind, regexFindAll, regexMatch, regexReplaceAll, regexReplaceAllLiteral, regexSplit };\n\nexport function sprigRegex(): FuncMap {\n // [LAW:single-enforcer] argTypes is the *one* contract describing\n // what each func accepts. enforceArgTypes catches T flowing into a\n // string slot at the boundary, so the bodies trust their declared\n // types and no longer call `String(.)`.\n return {\n regexMatch: {\n fn: (p, s) => regexMatch(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n regexFind: {\n fn: (p, s) => regexFind(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n regexFindAll: {\n fn: (p, s, n) => regexFindAll(p as string, s as string, n as number),\n argTypes: [\"string\", \"string\", \"int\"],\n arity: { kind: \"exact\" },\n },\n regexReplaceAll: {\n fn: (p, s, r) => regexReplaceAll(p as string, s as string, r as string),\n argTypes: [\"string\", \"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n regexReplaceAllLiteral: {\n fn: (p, s, r) => regexReplaceAllLiteral(p as string, s as string, r as string),\n argTypes: [\"string\", \"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n regexSplit: {\n fn: (p, s, n) => regexSplit(p as string, s as string, n as number),\n argTypes: [\"string\", \"string\", \"int\"],\n arity: { kind: \"exact\" },\n },\n };\n}\n","/**\n * SemVer parsing and comparison utilities.\n *\n * Mirrors Masterminds/semver v3 semantics used by Go sprig:\n * - Optional v prefix; missing minor/patch default to 0\n * - Standard semver 2.0.0 ordering: major.minor.patch then pre-release\n * - Release (no pre-release) > pre-release of same version\n *\n * [LAW:one-source-of-truth] One parser, one comparator. Constraint\n * evaluation imports from here rather than re-implementing comparison.\n */\n\n// Matches: v?major[.minor[.patch]][-prerelease][+metadata]\n// Groups: 1=major, 2=minor, 3=patch, 4=prerelease, 5=metadata\n// SemVer 2.0.0: prerelease/metadata use [0-9A-Za-z-] with . separators.\nconst VERSION_RE =\n /^v?(\\d+)(?:\\.(\\d+)(?:\\.(\\d+))?)?(?:-([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$/;\n\n// [LAW:types-are-the-program] SemVer mirrors the fields Go sprig exposes\n// from Masterminds/semver v3's Version struct. Template access `.Major`\n// etc. maps directly to these keys via the engine's field accessor.\nexport interface SemVer {\n readonly Major: number;\n readonly Minor: number;\n readonly Patch: number;\n readonly Prerelease: string;\n readonly Metadata: string;\n readonly Original: string;\n}\n\nexport function parseSemVer(s: string): SemVer {\n const input = s.trim();\n const m = VERSION_RE.exec(input);\n if (!m) throw new Error(`invalid semver: ${JSON.stringify(s)}`);\n return {\n Major: parseInt(m[1] ?? \"0\", 10),\n Minor: m[2] !== undefined ? parseInt(m[2], 10) : 0,\n Patch: m[3] !== undefined ? parseInt(m[3], 10) : 0,\n Prerelease: m[4] ?? \"\",\n Metadata: m[5] ?? \"\",\n Original: input,\n };\n}\n\n/** Returns negative if a < b, 0 if equal, positive if a > b. */\nexport function compareSemVer(a: SemVer, b: SemVer): number {\n const d = a.Major - b.Major || a.Minor - b.Minor || a.Patch - b.Patch;\n if (d !== 0) return d;\n return comparePrerelease(a.Prerelease, b.Prerelease);\n}\n\nfunction comparePrerelease(a: string, b: string): number {\n if (a === b) return 0;\n if (a === \"\") return 1; // release > pre-release\n if (b === \"\") return -1; // pre-release < release\n\n const aParts = a.split(\".\");\n const bParts = b.split(\".\");\n for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {\n const ap = aParts[i];\n const bp = bParts[i];\n if (ap === undefined) return -1; // fewer identifiers = smaller\n if (bp === undefined) return 1;\n const an = /^\\d+$/.test(ap) ? parseInt(ap, 10) : null;\n const bn = /^\\d+$/.test(bp) ? parseInt(bp, 10) : null;\n if (an !== null && bn !== null) {\n if (an !== bn) return an - bn;\n } else if (an !== null) {\n return -1; // numeric < alphanumeric per semver spec\n } else if (bn !== null) {\n return 1;\n } else {\n if (ap < bp) return -1;\n if (ap > bp) return 1;\n }\n }\n return 0;\n}\n","/**\n * `semver s` — parse a semver string into a struct with Major, Minor,\n * Patch, Prerelease, Metadata, Original fields.\n *\n * Mirrors Go sprig's `semver` which wraps Masterminds/semver v3's\n * `NewVersion`. Template field access (`.Major`, `.Prerelease`, etc.)\n * maps to the same-named keys on the returned object.\n *\n * Throws on invalid input — matches Go's behaviour where `semver` returns\n * (Version, error) and sprig panics on error.\n */\n\nimport { parseSemVer, type SemVer } from \"./parse.js\";\n\nexport type { SemVer };\n\nexport function semver(s: string): SemVer {\n return parseSemVer(s);\n}\n","/**\n * Masterminds/semver v3-compatible constraint parsing and evaluation.\n *\n * Supports operators: =, !=, >, >=, <, <=, ~ (tilde), ^ (caret), \"\" (=).\n * AND groups: comma- or whitespace-separated.\n * OR groups: || separated.\n *\n * [LAW:types-are-the-program] A constraint IS a predicate function —\n * parsing produces (v: SemVer) => boolean directly. No intermediate\n * structural representation is needed at the call site.\n */\n\nimport { compareSemVer, parseSemVer, type SemVer } from \"./parse.js\";\n\ntype Predicate = (v: SemVer) => boolean;\n\n// Tokenizes individual constraint items: optional op + version string.\n// Version portion allows partial versions (1, 1.2, 1.2.3) and alphanumeric\n// pre-release/metadata suffixes. Commas are separators (skipped by \\d match).\n// Operators: =, !=, >, >=, <, <=, ~, ^ (longest-first for greedy matching).\nconst TOKEN_RE = /(!=|>=|<=|>|<|~|\\^|=)?\\s*(v?\\d[^\\s,]*)/g;\n\nexport function parseConstraintExpr(s: string): Predicate {\n const orGroups = s\n .split(/\\|\\|/)\n .map((p) => p.trim())\n .filter(Boolean);\n if (orGroups.length === 0) throw new Error(`empty constraint: ${JSON.stringify(s)}`);\n const preds = orGroups.map(parseAndGroup);\n return (v) => preds.some((p) => p(v));\n}\n\nfunction parseAndGroup(s: string): Predicate {\n const preds: Predicate[] = [];\n let consumed = 0;\n for (const m of s.matchAll(TOKEN_RE)) {\n // Validate gap between previous consumed position and this match is only separators.\n const gap = s.slice(consumed, m.index);\n if (gap.length > 0 && !/^[,\\s]*$/.test(gap))\n throw new Error(`unexpected characters in constraint: ${JSON.stringify(gap)}`);\n preds.push(buildSingle(m[1] ?? \"\", m[2] ?? \"\"));\n consumed = (m.index ?? 0) + m[0].length;\n }\n if (preds.length === 0) throw new Error(`no constraint tokens in: ${JSON.stringify(s)}`);\n // Validate entire string was consumed (allowing trailing whitespace)\n const remaining = s.slice(consumed).trim();\n if (remaining.length > 0)\n throw new Error(`unexpected characters in constraint: ${JSON.stringify(remaining)}`);\n return (v) => preds.every((p) => p(v));\n}\n\n// Counts explicitly-given version components (1 = major only, 2 = major.minor, 3 = all).\n// Needed for tilde/caret semantics where partial specs have different bounds.\nfunction countComponents(vstr: string): number {\n const core = vstr.replace(/^v/, \"\").replace(/[-+].*$/, \"\");\n return Math.min(core.split(\".\").length, 3);\n}\n\nfunction makeSemVer(major: number, minor: number, patch: number, pre: string): SemVer {\n const vstr = pre ? `${major}.${minor}.${patch}-${pre}` : `${major}.${minor}.${patch}`;\n return {\n Major: major,\n Minor: minor,\n Patch: patch,\n Prerelease: pre,\n Metadata: \"\",\n Original: vstr,\n };\n}\n\n// Masterminds/semver v3 pre-release exclusion rule: a version with a\n// pre-release is excluded from a non-pre-release constraint unless the\n// constraint has a pre-release at the exact same major.minor.patch.\nfunction preReleaseCheck(v: SemVer, constraint: SemVer): boolean {\n if (v.Prerelease === \"\") return true;\n if (constraint.Prerelease !== \"\") {\n return (\n v.Major === constraint.Major && v.Minor === constraint.Minor && v.Patch === constraint.Patch\n );\n }\n return false;\n}\n\nfunction buildSingle(op: string, vstr: string): Predicate {\n const cv = parseSemVer(vstr);\n const components = countComponents(vstr);\n const minorDirty = components < 2;\n const patchDirty = components < 3;\n\n switch (op) {\n case \"\":\n case \"=\":\n return (v) => compareSemVer(v, cv) === 0;\n case \"!=\":\n return (v) => compareSemVer(v, cv) !== 0;\n case \">\":\n return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) > 0;\n case \">=\":\n return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) >= 0;\n case \"<\":\n return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) < 0;\n case \"<=\":\n return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) <= 0;\n case \"~\":\n return buildTilde(cv, minorDirty);\n case \"^\":\n return buildCaret(cv, minorDirty, patchDirty);\n default:\n throw new Error(`unknown constraint operator: ${JSON.stringify(op)}`);\n }\n}\n\n// Tilde: locks major (and minor if given). Allows patch-level changes.\n// ~X.Y.Z or ~X.Y → >=X.Y.Z, <X.(Y+1).0\n// ~X → >=X.0.0, <(X+1).0.0\nfunction buildTilde(cv: SemVer, minorDirty: boolean): Predicate {\n if (minorDirty) {\n const lower = makeSemVer(cv.Major, 0, 0, cv.Prerelease);\n const upper = makeSemVer(cv.Major + 1, 0, 0, \"\");\n return (v) =>\n preReleaseCheck(v, lower) && compareSemVer(v, lower) >= 0 && compareSemVer(v, upper) < 0;\n }\n const upper = makeSemVer(cv.Major, cv.Minor + 1, 0, \"\");\n return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) >= 0 && compareSemVer(v, upper) < 0;\n}\n\n// Caret: locks the left-most non-zero element.\n// ^X.Y.Z or ^X.Y where X>0 → >=X.Y.Z, <(X+1).0.0\n// ^0.Y.Z or ^0.Y where Y>0 → >=0.Y.Z, <0.(Y+1).0\n// ^0.0.Z (patch explicit) → >=0.0.Z, <0.0.(Z+1)\n// ^0.0 (patch dirty) → >=0.0.0, <0.1.0\n// ^0 or ^X (minor dirty) → >=X.0.0, <(X+1).0.0\nfunction buildCaret(cv: SemVer, minorDirty: boolean, patchDirty: boolean): Predicate {\n let upper: SemVer;\n if (minorDirty) {\n upper = makeSemVer(cv.Major + 1, 0, 0, \"\");\n } else if (cv.Major > 0) {\n upper = makeSemVer(cv.Major + 1, 0, 0, \"\");\n } else if (cv.Minor > 0) {\n upper = makeSemVer(0, cv.Minor + 1, 0, \"\");\n } else if (patchDirty) {\n // ^0.0 (minor explicit 0, patch not given) → <0.1.0\n upper = makeSemVer(0, 1, 0, \"\");\n } else {\n // ^0.0.Z (patch explicit) → <0.0.(Z+1)\n upper = makeSemVer(0, 0, cv.Patch + 1, \"\");\n }\n return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) >= 0 && compareSemVer(v, upper) < 0;\n}\n","/**\n * `semverCompare constraint version` — returns true iff `version`\n * satisfies `constraint`.\n *\n * Constraint syntax follows Masterminds/semver v3 (Go sprig's semver\n * library): =, !=, >, >=, <, <=, ~ (tilde), ^ (caret), || for OR,\n * comma/space for AND.\n *\n * Note: Go sprig's argument order is (constraint, version) — the\n * constraint comes first.\n */\n\nimport { parseConstraintExpr } from \"./constraint.js\";\nimport { parseSemVer } from \"./parse.js\";\n\nexport function semverCompare(constraint: string, version: string): boolean {\n const predicate = parseConstraintExpr(constraint);\n const v = parseSemVer(version);\n return predicate(v);\n}\n","/**\n * Sprig semver functions — `semver`, `semverCompare`.\n *\n * [LAW:single-enforcer] One module owns the FuncMap registration.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { type SemVer, semver } from \"./semver.js\";\nimport { semverCompare } from \"./semverCompare.js\";\n\nexport { type SemVer, semver, semverCompare };\n\nexport function sprigSemver(): FuncMap {\n return {\n // [LAW:types-are-the-program] Returns a plain object whose keys mirror\n // Masterminds/semver v3's method names so Go template field access\n // (`.Major`, `.Prerelease`, etc.) works without an adapter.\n semver: { fn: (s) => semver(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n semverCompare: {\n fn: (constraint, version) => semverCompare(constraint as string, version as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n returnType: \"bool\",\n },\n };\n}\n","/**\n * goutils.AbbreviateFull (Masterminds/goutils@v1.1.1 stringutils.go), the\n * function behind both sprig `abbrev` and `abbrevboth`: keep at most\n * `maxWidth` characters of `cps`, starting near `offset`, marking each cut\n * end with `...`.\n *\n * [LAW:one-source-of-truth] Ported whole, step for step in Go's order, so\n * both sprig wrappers share Go's one control flow instead of each\n * reconstructing the branch it noticed. Indexed by code point where Go\n * indexes by byte — see `runes.js`.\n *\n * Go returns an error at its two minimum-width checks; both sprig wrappers\n * guard against reaching them, so here they throw rather than model sprig's\n * swallowed error.\n */\nexport function abbreviateFull(cps: readonly string[], offset: number, maxWidth: number): string {\n if (cps.length === 0) return \"\";\n if (maxWidth < 4) {\n throw new Error(\"stringutils illegal argument: Minimum abbreviation width is 4\");\n }\n if (cps.length <= maxWidth) return cps.join(\"\");\n // Go's two offset clamps, to the length and then so that maxWidth-3\n // characters remain; past the check above the second is always tighter.\n const start = Math.min(offset, cps.length - (maxWidth - 3));\n if (start <= 4) return `${cps.slice(0, maxWidth - 3).join(\"\")}...`;\n if (maxWidth < 7) {\n throw new Error(\"stringutils illegal argument: Minimum abbreviation width with offset is 7\");\n }\n if (start + maxWidth - 3 < cps.length) {\n return `...${abbreviateFull(cps.slice(start), 0, maxWidth - 3)}`;\n }\n return `...${cps.slice(cps.length - (maxWidth - 3)).join(\"\")}`;\n}\n","import { abbreviateFull } from \"./abbreviateFull.js\";\nimport { runes } from \"./runes.js\";\n\n/**\n * `abbrev width s` — truncate `s` to `width` chars, replacing the tail\n * with `...` when truncation occurs: sprig's guard around\n * goutils.Abbreviate, which is AbbreviateFull at offset 0. Widths below 4\n * cannot fit the ellipsis and return `s` unchanged.\n *\n * `width` counts code points, so the cut never splits an astral\n * character — see `runes.js` for why that differs from Go's bytes.\n */\nexport function abbrev(width: number, s: string): string {\n if (width < 4) return s;\n return abbreviateFull(runes(s), 0, width);\n}\n","import { abbreviateFull } from \"./abbreviateFull.js\";\nimport { runes } from \"./runes.js\";\n\n/**\n * `abbrevboth left right s` — sprig's guard around goutils.AbbreviateFull\n * with `left` as the offset and `right` as the maximum width: a window of\n * `s` near `left`, with `...` at each end that was cut.\n *\n * Offsets count code points, so the window never splits an astral\n * character — see `runes.js` for why that differs from Go's bytes.\n */\nexport function abbrevboth(left: number, right: number, s: string): string {\n if (right < 4 || (left > 0 && right < 7)) return s;\n return abbreviateFull(runes(s), left, right);\n}\n","/**\n * Word-classifying state machine ported from huandu/xstrings v1.3.3\n * (https://github.com/huandu/xstrings/blob/v1.3.3/convert.go), which\n * Go sprig delegates to for `snakecase`, `camelcase`, and `kebabcase`.\n *\n * [LAW:one-source-of-truth] Three sprig funcs target the same\n * algorithm with two different connector chars (`_`, `-`) plus a\n * separate camel walk. The state machine lives once in this module;\n * the per-func files are thin specializations.\n *\n * ## Port notes\n *\n * Go iterates UTF-8 bytes via `utf8.DecodeRuneInString`. The `runes`\n * seam yields code points the same way Go yields runes, so the\n * rune-level logic carries over. We intentionally do NOT attempt to\n * mirror xstrings' `isAlphabet` CJK-exclusion table — for ASCII/Latin\n * templates, which are what real users feed sprig, the simpler\n * `isLetter` test matches Go's output. The fixture suite pins the\n * cases consumers actually exercise.\n *\n * `unicode.ToTitle` from Go has no JS equivalent for ASCII letters\n * (Title and Upper coincide for code points without a separate Title\n * mapping), so we use `String.toUpperCase()` everywhere xstrings would\n * have used either.\n */\n\nimport { runes } from \"./runes.js\";\n\n// [LAW:types-are-the-program] WordType is the discriminator the\n// state machine routes on. Object-frozen literal keeps the same\n// runtime shape as a const enum without the bundler/isolatedModules\n// pitfalls biome flags.\nconst WordType = {\n Invalid: 0,\n Number: 1,\n UpperCase: 2,\n Alphabet: 3,\n Connector: 4,\n Punct: 5,\n Other: 6,\n} as const;\ntype WordType = (typeof WordType)[keyof typeof WordType];\n\ninterface Word {\n readonly wt: WordType;\n readonly text: string;\n}\n\nconst isConnectorRe = /^[-_\\s]$/;\nconst isPunctRe = /^\\p{P}$/u;\nconst isLetterRe = /^\\p{L}$/u;\nconst isUpperRe = /^\\p{Lu}$/u;\nconst isNumberRe = /^\\p{N}$/u;\n\n// All classifiers accept `undefined` as a no-op false. The caller\n// shape is \"is the next code point in class X\" — out-of-bounds is\n// trivially \"no\", which keeps the loop conditions readable without\n// duplicating an `i < cps.length` guard at every call site.\nfunction isConnector(ch: string | undefined): boolean {\n return ch !== undefined && isConnectorRe.test(ch);\n}\n\nfunction isAlphabet(ch: string | undefined): boolean {\n return ch !== undefined && isLetterRe.test(ch);\n}\n\nfunction isUpper(ch: string | undefined): boolean {\n return ch !== undefined && isUpperRe.test(ch);\n}\n\nfunction isNumber(ch: string | undefined): boolean {\n return ch !== undefined && isNumberRe.test(ch);\n}\n\nfunction isPunct(ch: string | undefined): boolean {\n return ch !== undefined && isPunctRe.test(ch);\n}\n\n/**\n * Pull the next word off `cps` starting at `i`. Returns the word's\n * type + text and the index of the first code point after the word.\n *\n * Mirrors xstrings.nextWord: classifies the first rune, then extends\n * the word as long as the next rune fits the same class — with a\n * special \"HTTPStatus\" carve-out where an upper-run followed by a\n * lower letter releases the last upper into the next word.\n */\nfunction nextWord(cps: readonly string[], start: number): { word: Word; next: number } {\n if (start >= cps.length) {\n return { word: { wt: WordType.Invalid, text: \"\" }, next: start };\n }\n // Bounds checked above; the cast trades a redundant runtime check\n // for the same nullability shape used elsewhere in this module\n // (e.g. `split.ts` has `parts[i] as string`).\n const r = cps[start] as string;\n let i = start + 1;\n\n if (isConnector(r)) {\n while (i < cps.length && isConnector(cps[i])) i++;\n return { word: { wt: WordType.Connector, text: cps.slice(start, i).join(\"\") }, next: i };\n }\n if (isPunct(r)) {\n while (i < cps.length && isPunct(cps[i])) i++;\n return { word: { wt: WordType.Punct, text: cps.slice(start, i).join(\"\") }, next: i };\n }\n if (isUpper(r)) {\n if (i >= cps.length) {\n return { word: { wt: WordType.UpperCase, text: r }, next: i };\n }\n if (isUpper(cps[i])) {\n // Run of uppers. Walk until non-upper.\n let endOfRun = i;\n while (endOfRun < cps.length && isUpper(cps[endOfRun])) endOfRun++;\n // \"HTTPStatus\" carve-out: when the run is followed by a letter\n // (which must be lower since the run already ended), the LAST\n // upper of the run is released into the next word so it can\n // become \"HTTP\" + \"Status\" rather than \"HTTPS\" + \"tatus\".\n if (endOfRun < cps.length && isAlphabet(cps[endOfRun])) {\n return {\n word: { wt: WordType.UpperCase, text: cps.slice(start, endOfRun - 1).join(\"\") },\n next: endOfRun - 1,\n };\n }\n return {\n word: { wt: WordType.UpperCase, text: cps.slice(start, endOfRun).join(\"\") },\n next: endOfRun,\n };\n }\n if (isAlphabet(cps[i])) {\n // Single upper followed by lower-run: e.g. \"FirstName\" -> \"First\".\n let end = i + 1;\n while (end < cps.length && isAlphabet(cps[end]) && !isUpper(cps[end])) end++;\n return {\n word: { wt: WordType.UpperCase, text: cps.slice(start, end).join(\"\") },\n next: end,\n };\n }\n // Single upper followed by non-letter (digit, connector, etc.).\n return { word: { wt: WordType.UpperCase, text: r }, next: i };\n }\n if (isAlphabet(r)) {\n while (i < cps.length && isAlphabet(cps[i]) && !isUpper(cps[i])) i++;\n return { word: { wt: WordType.Alphabet, text: cps.slice(start, i).join(\"\") }, next: i };\n }\n if (isNumber(r)) {\n while (i < cps.length && isNumber(cps[i])) i++;\n return { word: { wt: WordType.Number, text: cps.slice(start, i).join(\"\") }, next: i };\n }\n while (\n i < cps.length &&\n !isConnector(cps[i]) &&\n !isAlphabet(cps[i]) &&\n !isNumber(cps[i]) &&\n !isPunct(cps[i])\n ) {\n i++;\n }\n return { word: { wt: WordType.Other, text: cps.slice(start, i).join(\"\") }, next: i };\n}\n\n/**\n * Lowercase a word's text into the output buffer. Connector words\n * have their internal connector chars rewritten to the target\n * connector; all other words are lowered character-by-character.\n */\nfunction pushLowered(buf: string[], word: Word, connector: string): void {\n if (word.wt !== WordType.UpperCase && word.wt !== WordType.Connector) {\n buf.push(word.text);\n return;\n }\n for (const ch of word.text) {\n if (isConnector(ch)) {\n buf.push(connector);\n } else if (isUpper(ch)) {\n buf.push(ch.toLowerCase());\n } else {\n buf.push(ch);\n }\n }\n}\n\n/**\n * Port of xstrings.camelCaseToLowerCase. Walks word-by-word and\n * inserts `connector` at the right transitions to produce snake/kebab\n * output.\n */\nexport function camelCaseToLowerCase(s: string, connector: string): string {\n if (s.length === 0) return \"\";\n const cps = runes(s);\n const buf: string[] = [];\n\n let { word, next: i } = nextWord(cps, 0);\n\n while (i < cps.length) {\n if (word.wt !== WordType.Connector) {\n pushLowered(buf, word, connector);\n }\n const prev = word;\n const last = word;\n ({ word, next: i } = nextWord(cps, i));\n\n if (prev.wt === WordType.Number) {\n while (word.wt === WordType.Alphabet || word.wt === WordType.Number) {\n pushLowered(buf, word, connector);\n ({ word, next: i } = nextWord(cps, i));\n }\n if (\n word.wt !== WordType.Invalid &&\n word.wt !== WordType.Punct &&\n word.wt !== WordType.Connector\n ) {\n buf.push(connector);\n }\n continue;\n }\n if (prev.wt === WordType.Connector) {\n pushLowered(buf, last, connector);\n continue;\n }\n if (prev.wt === WordType.Punct) {\n // nothing\n continue;\n }\n // default: prev is alphabet/upper/other\n if (word.wt !== WordType.Number) {\n if (word.wt !== WordType.Connector && word.wt !== WordType.Punct) {\n buf.push(connector);\n }\n continue;\n }\n // word is a Number — special handling per xstrings.\n if (i >= cps.length) {\n // No following word; let the loop tail emit `word`.\n continue;\n }\n const numberWord = word;\n ({ word, next: i } = nextWord(cps, i));\n // If after the number isn't an alphabet, treat the number as its\n // own word (e.g. \"Duration2m3s\" → \"duration_2m3s\").\n if (word.wt !== WordType.Alphabet) {\n pushLowered(buf, numberWord, connector);\n if (word.wt !== WordType.Connector && word.wt !== WordType.Punct) {\n buf.push(connector);\n }\n continue;\n }\n // Lowercase letters follow the number, so the number is its own\n // word with a leading connector: e.g. \"HTTP2xx\" → \"http_2xx\".\n buf.push(connector);\n pushLowered(buf, numberWord, connector);\n while (word.wt === WordType.Alphabet || word.wt === WordType.Number) {\n pushLowered(buf, word, connector);\n ({ word, next: i } = nextWord(cps, i));\n }\n if (\n word.wt !== WordType.Invalid &&\n word.wt !== WordType.Connector &&\n word.wt !== WordType.Punct\n ) {\n buf.push(connector);\n }\n }\n pushLowered(buf, word, connector);\n return buf.join(\"\").toLowerCase();\n}\n\n/**\n * Port of xstrings.ToCamelCase. Two-phase walk:\n * - Phase 1 preserves leading connectors verbatim, capitalizes the\n * first non-connector rune.\n * - Phase 2 walks `(prev, curr)` rune pairs, collapsing connector→\n * non-connector to a single uppered rune, preserving runs of\n * adjacent connectors, and lowercasing other runes.\n */\nexport function camelCase(s: string): string {\n if (s.length === 0) return \"\";\n const cps = runes(s);\n const buf: string[] = [];\n\n let i = 0;\n let r0 = \"\";\n\n while (i < cps.length) {\n r0 = cps[i] as string;\n i++;\n if (!isConnector(r0)) {\n r0 = r0.toUpperCase();\n break;\n }\n buf.push(r0);\n }\n\n if (i >= cps.length) {\n if (cps.length > 0) buf.push(r0);\n return buf.join(\"\");\n }\n\n while (i < cps.length) {\n const r1 = r0;\n r0 = cps[i] as string;\n i++;\n\n if (isConnector(r0) && isConnector(r1)) {\n buf.push(r1);\n continue;\n }\n if (isConnector(r1)) {\n r0 = r0.toUpperCase();\n } else {\n r0 = r0.toLowerCase();\n buf.push(r1);\n }\n }\n buf.push(r0);\n return buf.join(\"\");\n}\n","/**\n * `camelcase s` — port of `xstrings.ToCamelCase`. Note: despite the\n * name, Go sprig's `camelcase` is **PascalCase** — the first letter\n * is uppercased, not lowercased. This is a documented Go-sprig\n * quirk and we preserve it byte-for-byte.\n *\n * Examples (matching the xstrings docstring):\n * \"some_words\" -> \"SomeWords\"\n * \"http_server\" -> \"HttpServer\"\n * \"_complex__case_\" -> \"_Complex_Case_\"\n */\n\n// [LAW:one-source-of-truth] The walk lives in caseUtils alongside\n// the snake/kebab algorithm.\nimport { camelCase } from \"./caseUtils.js\";\n\nexport function camelcase(s: string): string {\n return camelCase(s);\n}\n","/** `cat a b c` — concatenates with spaces, like Go sprig. */\nexport function cat(...args: string[]): string {\n return args.join(\" \");\n}\n","export function contains(substr: string, s: string): boolean {\n return s.includes(substr);\n}\n","export function hasPrefix(prefix: string, s: string): boolean {\n return s.startsWith(prefix);\n}\n","export function hasSuffix(suffix: string, s: string): boolean {\n return s.endsWith(suffix);\n}\n","/** `indent n s` — prefix every line of `s` with `n` spaces. */\nexport function indent(n: number, s: string): string {\n const pad = \" \".repeat(Math.max(0, n));\n return s\n .split(\"\\n\")\n .map((line) => pad + line)\n .join(\"\\n\");\n}\n","/**\n * `initials s` — port of `goutils.Initials` (what Go sprig's `initials`\n * delegates to): the first character of each whitespace-separated word,\n * case preserved — `\"Ada Lovelace\"` -> `\"AL\"`, `\"foo bar baz\"` -> `\"fbb\"`.\n *\n * Byte-faithful: goutils indexes the word's first BYTE, so a multi-byte\n * leading character yields that byte as a code point — `\"Ölga\"` -> `\"Ã\"`,\n * `\"𐍈foo\"` -> `\"ð\"` (both verified against the Go conformance generator),\n * never the full glyph.\n */\nexport function initials(s: string): string {\n const enc = new TextEncoder();\n return (\n s\n .split(/\\s+/)\n .filter((w) => w.length > 0)\n // [LAW:dataflow-not-control-flow] spread of the 1-byte slice: an (impossible)\n // empty word contributes \"\" naturally instead of a guarded fallback value.\n .map((w) => String.fromCharCode(...enc.encode(w).slice(0, 1)))\n .join(\"\")\n );\n}\n","import { typeNameOf } from \"../../evaluator/builtins.js\";\nimport { bodyTypeMismatch } from \"../../evaluator/errors.js\";\n\n/**\n * `join sep list` — joins a list with the separator.\n *\n * [LAW:single-enforcer] The list-shape gate is `argTypes: [\"string\",\n * \"list\"]` — non-arrays raise TypeMismatchError before this body runs.\n * The body validates each *element* because the no-silent-flatten\n * commitment (\"typed values never become strings without an explicit\n * conversion\") applies inside lists too: primitives stringify\n * naturally; non-primitive (typed-T) elements throw, and `evalCommand`\n * re-emits with the call-site pos.\n */\nexport function join(sep: string, list: readonly unknown[]): string {\n const parts: string[] = [];\n for (const v of list) {\n if (v !== null && v !== undefined && typeof v === \"object\") {\n throw bodyTypeMismatch(\n \"join\",\n 2,\n \"list of strings/primitives\",\n `list element of type ${typeNameOf(v)}`,\n );\n }\n parts.push(String(v));\n }\n return parts.join(sep);\n}\n","/**\n * `kebabcase s` — port of `xstrings.ToKebabCase`. Identical to\n * `snakecase` except the connector is `-`.\n */\n\n// [LAW:one-source-of-truth] The state machine lives in caseUtils;\n// kebabcase is the `-` specialization.\nimport { camelCaseToLowerCase } from \"./caseUtils.js\";\n\nexport function kebabcase(s: string): string {\n return camelCaseToLowerCase(s, \"-\");\n}\n","export function lower(s: string): string {\n return s.toLowerCase();\n}\n","/** `nindent n s` — `indent` with a leading newline. */\nimport { indent } from \"./indent.js\";\n\nexport function nindent(n: number, s: string): string {\n return `\\n${indent(n, s)}`;\n}\n","/**\n * `nospace s` — strip whitespace from `s`. Mirrors Go sprig's\n * `goutils.DeleteWhiteSpace`, which iterates bytes and drops anything\n * `unicode.IsSpace` returns true for. ECMAScript `\\s` covers the same\n * ASCII whitespace set (space, tab, CR, LF, VT, FF) — the goutils\n * implementation is byte-indexed so multi-byte Unicode whitespace\n * already escapes its filter, leaving ASCII as the de-facto contract.\n */\n\n// [LAW:single-enforcer] The `\"string\"` gate validates the kind once\n// at dispatch; the body trusts it.\nexport function nospace(s: string): string {\n return s.replace(/\\s+/g, \"\");\n}\n","/**\n * `plural one many n` — return `one` if `n == 1`, else `many`.\n * Mirrors Go sprig's `plural(one, many string, count int) string`.\n */\n\n// [LAW:single-enforcer] Slot kinds (`[\"string\", \"string\", \"int\"]`) are\n// validated and normalized at the dispatch gate; the body receives a\n// finite `number`. Safe-integer bigints (|n| ≤ 2^53) normalize through\n// the gate to plain `number`; bigints outside that range are rejected\n// at the gate (precision-loss is a magnitude failure, not a tradeoff).\n// Either way, no body-side bigint comparison is needed.\nexport function plural(one: string, many: string, n: number): string {\n return n === 1 ? one : many;\n}\n","/** `quote a b c` — wraps each arg in double quotes, joined by spaces. */\nexport function quote(...args: string[]): string {\n return args.map((a) => `\"${a}\"`).join(\" \");\n}\n","/**\n * `regexQuoteMeta s` — escape regex metacharacters in `s` so it can be\n * embedded literally in a regex. Mirrors Go's `regexp.QuoteMeta`,\n * which backslash-escapes the set `\\.+*?()|[]{}^$`.\n *\n * ECMAScript regex shares the same metacharacter set, so the escape\n * list is identical.\n */\n\n// [LAW:single-enforcer] Kind validated at the dispatch gate; the body\n// just rewrites.\nexport function regexQuoteMeta(s: string): string {\n return s.replace(/[\\\\.+*?()|[\\]{}^$]/g, \"\\\\$&\");\n}\n","export function repeat(n: number, s: string): string {\n return s.repeat(Math.max(0, n));\n}\n","import { goSplit } from \"./runes.js\";\n\n/**\n * Replaces ALL occurrences of `old` with `nw` in `s` (Go's strings.Replace n=-1).\n *\n * An empty `old` splits between runes rather than UTF-16 units, so the\n * replacement is never inserted inside an astral character. Where Go\n * additionally inserts `nw` at both ends (`-a-b-c-` to this port's\n * `a-b-c`) it still differs — a separate, non-Unicode divergence.\n */\nexport function replace(old: string, nw: string, s: string): string {\n return goSplit(old, s).join(nw);\n}\n","/**\n * `snakecase s` — port of `xstrings.ToSnakeCase`. Inserts `_` between\n * camelCase/PascalCase word boundaries and rewrites any space, dash,\n * or underscore run into a single `_`. Runs of upper-case letters\n * release their last character into the next word, so `HTTPServer`\n * becomes `http_server`, not `https_erver`.\n */\n\n// [LAW:one-source-of-truth] The state machine lives in caseUtils;\n// snakecase is the `_` specialization.\nimport { camelCaseToLowerCase } from \"./caseUtils.js\";\n\nexport function snakecase(s: string): string {\n return camelCaseToLowerCase(s, \"_\");\n}\n","import { goSplit } from \"./runes.js\";\n\n/**\n * `split sep s` — Go sprig oddity: returns a DICT keyed by `_<index>`,\n * not a list. Use `splitList` for the list form.\n * split \"/\" \"a/b/c\" → { _0: \"a\", _1: \"b\", _2: \"c\" }\n */\nexport function split(sep: string, s: string): Record<string, string> {\n const parts = goSplit(sep, s);\n const out: Record<string, string> = {};\n for (let i = 0; i < parts.length; i++) {\n out[`_${i}`] = parts[i] as string;\n }\n return out;\n}\n","import { goSplit } from \"./runes.js\";\n\nexport function splitList(sep: string, s: string): string[] {\n return goSplit(sep, s);\n}\n","/**\n * `splitn sep n s` — split `s` on `sep` into at most `n` parts and\n * return a `{_0, _1, …}` map. Mirrors Go sprig:\n *\n * parts := strings.SplitN(orig, sep, n)\n * for i, v := range parts {\n * res[\"_\" + strconv.Itoa(i)] = v\n * }\n *\n * The `{_0, _1}` shape (rather than a list) is idiosyncratic to Go\n * sprig. Preserve it byte-for-byte — consumers index into the result\n * by name, e.g. `(splitn \":\" 2 \"a:b:c\")._1` → `\"b:c\"`.\n *\n * `strings.SplitN` semantics that JS `String.split(sep, n)` does *not*\n * match: when there are more parts than `n`, the last slot holds the\n * **unsplit remainder**, not a truncated prefix. JS `split` would\n * drop \"b:c\" entirely; Go keeps it. The body re-joins the tail\n * explicitly to recover the Go behavior.\n */\n\nimport { goSplit } from \"./runes.js\";\n\n// [LAW:single-enforcer] Slot kinds (`[\"string\", \"int\", \"string\"]`)\n// validate and normalize the inputs at the dispatch gate — `n` arrives\n// as a safe-integer `number`. Safe-integer bigints (|n| ≤ 2^53) are\n// accepted and normalized via `Number(v)`; fractionals, NaN, ±Infinity,\n// and integers outside that range are rejected at the gate.\n// The body owns the SplitN→map shape transform.\nexport function splitn(sep: string, n: number, s: string): Record<string, string> {\n const parts = goSplitN(s, sep, n);\n const res: Record<string, string> = {};\n for (let i = 0; i < parts.length; i++) {\n res[`_${i}`] = parts[i] ?? \"\";\n }\n return res;\n}\n\n// Go's strings.SplitN(s, sep, n):\n// n > 0 → at most n substrings; last is unsplit remainder\n// n == 0 → empty list\n// n < 0 → all substrings (== Split)\nfunction goSplitN(s: string, sep: string, n: number): string[] {\n if (n === 0) return [];\n const all = goSplit(sep, s);\n if (n < 0 || all.length <= n) return all;\n const head = all.slice(0, n - 1);\n const tail = all.slice(n - 1).join(sep);\n return [...head, tail];\n}\n","/** `squote a b c` — like `quote` but single quotes. */\nexport function squote(...args: string[]): string {\n return args.map((a) => `'${a}'`).join(\" \");\n}\n","import { runes } from \"./runes.js\";\n\n/**\n * `substr i j s` — substring [i, j) with out-of-range clamping.\n * Matches Go sprig's behavior of clamping rather than throwing:\n * negative `end` (and any `end` past the last char) clamps to the\n * string's length; `start` clamps to `[0, end]`.\n *\n * Offsets count code points, so a window never splits an astral\n * character — see `runes.js` for why that differs from Go's bytes.\n */\nexport function substr(start: number, end: number, s: string): string {\n const cps = runes(s);\n const j = end < 0 || end > cps.length ? cps.length : end;\n const i = Math.min(Math.max(0, start), j);\n return cps.slice(i, j).join(\"\");\n}\n","/**\n * `swapcase s` — flip case per code point. Mirrors Go sprig's\n * `goutils.SwapCase` for ASCII and Latin-1 inputs.\n *\n * Go's `goutils.SwapCase` carries a \"preceded by whitespace\" flag and\n * uses `unicode.ToTitle` instead of `ToUpper` for the first lowercase\n * letter of each word. For ASCII letters Title and Upper coincide, so\n * the flag has no observable effect on output and is omitted here —\n * keeping it would be load-bearing complexity that the type system\n * cannot constrain. Non-ASCII ligatures (e.g. German `ß` whose JS\n * `toUpperCase` returns `SS` while Go's `ToTitle` returns `ẞ`) diverge,\n * matching the README's existing Go/Unicode divergence statements.\n */\n\n// [LAW:single-enforcer] The \"string\" gate validates the kind once at\n// dispatch; the body trusts it.\n//\n// [LAW:dataflow-not-control-flow] Each iteration unconditionally\n// emits one transformed code point. The category check selects the\n// transformation; it never gates whether the emit happens.\nexport function swapcase(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (isUpper(ch)) {\n out += ch.toLowerCase();\n } else if (isLower(ch)) {\n out += ch.toUpperCase();\n } else {\n out += ch;\n }\n }\n return out;\n}\n\nfunction isUpper(ch: string): boolean {\n return ch !== ch.toLowerCase() && ch === ch.toUpperCase();\n}\n\nfunction isLower(ch: string): boolean {\n return ch !== ch.toUpperCase() && ch === ch.toLowerCase();\n}\n","/** Capitalize the first letter of each whitespace-separated word. */\nexport function title(s: string): string {\n return s.replace(/\\b([a-zA-Z])/g, (m) => m.toUpperCase());\n}\n","export function trim(s: string): string {\n return s.trim();\n}\n","import { runes } from \"./runes.js\";\n\n/**\n * `trimAll cutset s` — strip leading + trailing chars in `cutset`.\n *\n * Both sides are compared as code points, matching Go's `strings.Trim`,\n * which decodes the cutset as runes. Scanning `s` by UTF-16 unit\n * compared half an astral character against whole ones, so an astral\n * cutset char never matched and the string came back untrimmed.\n */\nexport function trimAll(cutset: string, s: string): string {\n if (cutset.length === 0) return s;\n const set = new Set(runes(cutset));\n const cps = runes(s);\n let start = 0;\n while (start < cps.length && set.has(cps[start] as string)) start += 1;\n let end = cps.length;\n while (end > start && set.has(cps[end - 1] as string)) end -= 1;\n return cps.slice(start, end).join(\"\");\n}\n","export function trimPrefix(prefix: string, s: string): string {\n return s.startsWith(prefix) ? s.slice(prefix.length) : s;\n}\n","export function trimSuffix(suffix: string, s: string): string {\n return s.endsWith(suffix) ? s.slice(0, s.length - suffix.length) : s;\n}\n","import { runes } from \"./runes.js\";\n\n/**\n * `trunc n s` — first `n` chars when n>=0; last |n| chars when n<0.\n * Strings shorter than |n| are returned unchanged. Matches Go sprig.\n *\n * `n` counts code points, so truncating never splits an astral\n * character — see `runes.js` for why that differs from Go's bytes.\n */\nexport function trunc(n: number, s: string): string {\n const cps = runes(s);\n if (n < 0) {\n const k = -n;\n return k >= cps.length ? s : cps.slice(cps.length - k).join(\"\");\n }\n return n >= cps.length ? s : cps.slice(0, n).join(\"\");\n}\n","/** Lowercase the first letter of each whitespace-separated word. */\nexport function untitle(s: string): string {\n return s.replace(/\\b([A-Z])/g, (m) => m.toLowerCase());\n}\n","export function upper(s: string): string {\n return s.toUpperCase();\n}\n","/**\n * `wrap width s` — soft-wrap `s` to `width` columns at word boundaries.\n * Lines longer than width that contain no spaces are emitted as-is.\n */\nexport function wrap(width: number, s: string): string {\n return wrapWithSeparator(width, \"\\n\", s);\n}\n\nexport function wrapWithSeparator(width: number, sep: string, s: string): string {\n if (width <= 0) return s;\n const out: string[] = [];\n for (const para of s.split(\"\\n\")) {\n let line = \"\";\n for (const word of para.split(/\\s+/)) {\n if (word.length === 0) continue;\n if (line.length === 0) {\n line = word;\n } else if (line.length + 1 + word.length <= width) {\n line += ` ${word}`;\n } else {\n out.push(line);\n line = word;\n }\n }\n if (line.length > 0) out.push(line);\n }\n return out.join(sep);\n}\n","import { wrapWithSeparator } from \"./wrap.js\";\n\n/** `wrapWith width sep s` — wrap to width using `sep` instead of \\n. */\nexport function wrapWith(width: number, sep: string, s: string): string {\n return wrapWithSeparator(width, sep, s);\n}\n","/**\n * Sprig string utilities.\n *\n * Each function lives in its own file with a co-located unit test.\n * `sprigStrings()` bundles them as a FuncMap for one-line consumer\n * registration on the engine.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { abbrev } from \"./abbrev.js\";\nimport { abbrevboth } from \"./abbrevboth.js\";\nimport { camelcase } from \"./camelcase.js\";\nimport { cat } from \"./cat.js\";\nimport { contains } from \"./contains.js\";\nimport { hasPrefix } from \"./hasPrefix.js\";\nimport { hasSuffix } from \"./hasSuffix.js\";\nimport { indent } from \"./indent.js\";\nimport { initials } from \"./initials.js\";\nimport { join } from \"./join.js\";\nimport { kebabcase } from \"./kebabcase.js\";\nimport { lower } from \"./lower.js\";\nimport { nindent } from \"./nindent.js\";\nimport { nospace } from \"./nospace.js\";\nimport { plural } from \"./plural.js\";\nimport { quote } from \"./quote.js\";\nimport { regexQuoteMeta } from \"./regexQuoteMeta.js\";\nimport { repeat } from \"./repeat.js\";\nimport { replace } from \"./replace.js\";\nimport { snakecase } from \"./snakecase.js\";\nimport { split } from \"./split.js\";\nimport { splitList } from \"./splitList.js\";\nimport { splitn } from \"./splitn.js\";\nimport { squote } from \"./squote.js\";\nimport { substr } from \"./substr.js\";\nimport { swapcase } from \"./swapcase.js\";\nimport { title } from \"./title.js\";\nimport { trim } from \"./trim.js\";\nimport { trimAll } from \"./trimAll.js\";\nimport { trimPrefix } from \"./trimPrefix.js\";\nimport { trimSuffix } from \"./trimSuffix.js\";\nimport { trunc } from \"./trunc.js\";\nimport { untitle } from \"./untitle.js\";\nimport { upper } from \"./upper.js\";\nimport { wrap } from \"./wrap.js\";\nimport { wrapWith } from \"./wrapWith.js\";\n\nexport {\n abbrev,\n abbrevboth,\n camelcase,\n cat,\n contains,\n hasPrefix,\n hasSuffix,\n indent,\n initials,\n join,\n kebabcase,\n lower,\n nindent,\n nospace,\n plural,\n quote,\n regexQuoteMeta,\n repeat,\n replace,\n snakecase,\n split,\n splitList,\n splitn,\n squote,\n substr,\n swapcase,\n title,\n trim,\n trimAll,\n trimPrefix,\n trimSuffix,\n trunc,\n untitle,\n upper,\n wrap,\n wrapWith,\n};\n\nexport function sprigStrings(): FuncMap {\n // [LAW:single-enforcer] argTypes is the contract describing what each\n // func accepts; enforceArgTypes runs at the boundary, so the `as`\n // casts below are provably-safe — the runtime types match the\n // declared argTypes. Numeric slots use \"int\" (Go declares every one\n // of them `int`): the gate accepts integer-valued `number` and\n // safe-integer `bigint` (|n| ≤ 2^53), normalizes both to a `number`,\n // and rejects fractionals, out-of-range bigints, NaN, and ±Infinity\n // at the boundary. Bodies receive plain `number` and\n // drop the body-side `Number(v)` coercions that used to re-do the\n // gate's work. See template-variance-num-carrier-hfv.3.\n return {\n abbrev: {\n fn: (w, s) => abbrev(w as number, s as string),\n argTypes: [\"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n abbrevboth: {\n fn: (l, r, s) => abbrevboth(l as number, r as number, s as string),\n argTypes: [\"int\", \"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n camelcase: {\n fn: (s) => camelcase(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n cat: {\n fn: (...a) => cat(...(a as string[])),\n argTypes: [\"string\"],\n arity: { kind: \"variadic\" },\n },\n contains: {\n fn: (sub, s) => contains(sub as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n hasPrefix: {\n fn: (p, s) => hasPrefix(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n hasSuffix: {\n fn: (sf, s) => hasSuffix(sf as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n indent: {\n fn: (n, s) => indent(n as number, s as string),\n argTypes: [\"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n initials: { fn: (s) => initials(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n join: {\n fn: (sep, list) => join(sep as string, list as unknown[]),\n argTypes: [\"string\", \"list\"],\n arity: { kind: \"exact\" },\n },\n kebabcase: {\n fn: (s) => kebabcase(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n lower: { fn: (s) => lower(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n nindent: {\n fn: (n, s) => nindent(n as number, s as string),\n argTypes: [\"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n nospace: {\n fn: (s) => nospace(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n plural: {\n fn: (one, many, n) => plural(one as string, many as string, n as number),\n argTypes: [\"string\", \"string\", \"int\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n quote: {\n fn: (...a) => quote(...(a as string[])),\n argTypes: [\"string\"],\n arity: { kind: \"variadic\" },\n },\n regexQuoteMeta: {\n fn: (s) => regexQuoteMeta(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n repeat: {\n fn: (n, s) => repeat(n as number, s as string),\n argTypes: [\"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n replace: {\n fn: (o, n, s) => replace(o as string, n as string, s as string),\n argTypes: [\"string\", \"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n snakecase: {\n fn: (s) => snakecase(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n split: {\n fn: (sep, s) => split(sep as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n splitList: {\n fn: (sep, s) => splitList(sep as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n splitn: {\n fn: (sep, n, s) => splitn(sep as string, n as number, s as string),\n argTypes: [\"string\", \"int\", \"string\"],\n arity: { kind: \"exact\" },\n returnType: \"dict\",\n },\n squote: {\n fn: (...a) => squote(...(a as string[])),\n argTypes: [\"string\"],\n arity: { kind: \"variadic\" },\n },\n substr: {\n fn: (i, j, s) => substr(i as number, j as number, s as string),\n argTypes: [\"int\", \"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n swapcase: {\n fn: (s) => swapcase(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n title: { fn: (s) => title(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n trim: { fn: (s) => trim(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n trimAll: {\n fn: (cs, s) => trimAll(cs as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n trimPrefix: {\n fn: (p, s) => trimPrefix(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n trimSuffix: {\n fn: (sf, s) => trimSuffix(sf as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n trunc: {\n fn: (n, s) => trunc(n as number, s as string),\n argTypes: [\"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n untitle: { fn: (s) => untitle(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n upper: { fn: (s) => upper(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n wrap: {\n fn: (w, s) => wrap(w as number, s as string),\n argTypes: [\"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n wrapWith: {\n fn: (w, sep, s) => wrapWith(w as number, sep as string, s as string),\n argTypes: [\"int\", \"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n };\n}\n","/**\n * `deepCopy v` — recursive structural clone.\n *\n * Uses `structuredClone` when available; falls back to a JSON\n * round-trip for older targets. The fallback drops functions and\n * symbols — same caveat as JSON.stringify.\n */\nexport function deepCopy<T>(value: T): T {\n if (typeof globalThis.structuredClone === \"function\") {\n return globalThis.structuredClone(value);\n }\n return JSON.parse(JSON.stringify(value)) as T;\n}\n","/**\n * `kindOf v` — JS-flavoured equivalent of Go's `reflect.Kind`.\n *\n * Go: int / float64 / string / bool / slice / map / struct / ptr / …\n * JS: number / string / boolean / array / map / object / null / undefined / function / bigint / symbol\n *\n * We return the JS-native kind. Consumers porting templates from Go\n * sprig should test against the JS-native names.\n */\nexport function kindOf(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n if (value instanceof Map) return \"map\";\n if (value instanceof Set) return \"set\";\n return typeof value;\n}\n","import { kindOf } from \"./kindOf.js\";\n\nexport function kindIs(kind: string, value: unknown): boolean {\n return kindOf(value) === kind;\n}\n","import { kindOf } from \"./kindOf.js\";\n\n/**\n * `typeOf v` — for JS, essentially the same as kindOf, with the\n * caveat that \"object\" is the catch-all for plain dicts and class\n * instances. Go's reflect.Type would distinguish struct names; we\n * don't have that info at runtime.\n */\nexport function typeOf(value: unknown): string {\n return kindOf(value);\n}\n","import { typeOf } from \"./typeOf.js\";\n\nexport function typeIs(type: string, value: unknown): boolean {\n return typeOf(value) === type;\n}\n","import { typeIs } from \"./typeIs.js\";\n\n/**\n * `typeIsLike type v` — Go sprig's \"like\" matches both value and\n * pointer-to-value. JS doesn't have pointers so this collapses to\n * `typeIs`.\n */\nexport function typeIsLike(type: string, value: unknown): boolean {\n return typeIs(type, value);\n}\n","/** Sprig type/reflection utilities. */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { deepCopy } from \"./deepCopy.js\";\nimport { deepEqual } from \"./deepEqual.js\";\nimport { kindIs } from \"./kindIs.js\";\nimport { kindOf } from \"./kindOf.js\";\nimport { typeIs } from \"./typeIs.js\";\nimport { typeIsLike } from \"./typeIsLike.js\";\nimport { typeOf } from \"./typeOf.js\";\n\nexport { deepCopy, deepEqual, kindIs, kindOf, typeIs, typeIsLike, typeOf };\n\nexport function sprigTypes(): FuncMap {\n // [LAW:one-source-of-truth] Reflection slots declare \"reflective\"\n // (intent: type-inspection context); structural-clone/compare slots\n // declare \"value\" (intent: genuinely heterogeneous). The *kind/type\n // name* arguments stay \"string\" — they exist to be compared against\n // typeOf's string output.\n return {\n kindOf: { fn: (v) => kindOf(v), argTypes: [\"reflective\"], arity: { kind: \"exact\" } },\n kindIs: {\n fn: (k, v) => kindIs(k as string, v),\n argTypes: [\"string\", \"reflective\"],\n arity: { kind: \"exact\" },\n },\n typeOf: { fn: (v) => typeOf(v), argTypes: [\"reflective\"], arity: { kind: \"exact\" } },\n typeIs: {\n fn: (t, v) => typeIs(t as string, v),\n argTypes: [\"string\", \"reflective\"],\n arity: { kind: \"exact\" },\n },\n typeIsLike: {\n fn: (t, v) => typeIsLike(t as string, v),\n argTypes: [\"string\", \"reflective\"],\n arity: { kind: \"exact\" },\n },\n deepEqual: {\n fn: (a, b) => deepEqual(a, b),\n argTypes: [\"value\", \"value\"],\n arity: { kind: \"exact\" },\n },\n deepCopy: { fn: (v) => deepCopy(v), argTypes: [\"value\"], arity: { kind: \"exact\" } },\n };\n}\n"],"mappings":";;;;AA0CA,IAAa,gBAAb,cAAmC,MAAM;CACvC,OAAiC;CACjC,OAA2B;CAC3B;CACA;CAEA,YAAY,SAAiB,KAAU,MAA4B,EAAE,EAAE;AACrE,QAAM,SAAS,EAAE,OAAO,IAAI,OAAO,CAAC;AACpC,OAAK,MAAM;AACX,OAAK,SAAS,IAAI;;;CAIpB,IAAI,gBAAwB;AAC1B,SAAO,KAAK,SAAS,aAAa,KAAK,QAAQ,KAAK,IAAI,GAAG;;CAG7D,WAA4B;EAC1B,MAAM,OAAO,GAAG,KAAK,KAAK,IAAI,KAAK,QAAQ,cAAc,KAAK,IAAI,KAAK,WAAW,KAAK,IAAI;EAC3F,MAAM,UAAU,KAAK;AACrB,SAAO,UAAU,GAAG,KAAK,MAAM,YAAY;;;AAa/C,IAAa,aAAb,cAAgC,cAAc;CAC5C,OAAyB;CACzB,OAAoC;CACpC;CACA;CAEA,YAAY,SAAiB,KAAU,MAAyB,EAAE,EAAE;AAClE,QAAM,SAAS,KAAK,IAAI;AACxB,OAAK,WAAW,IAAI;AACpB,OAAK,QAAQ,IAAI;;;AAQrB,IAAa,YAAb,cAA+B,cAAc;CAC3C,OAAiC;CACjC,OAAoC;;;;;;;AAQtC,IAAa,oBAAb,cAAuC,UAAU;CAC/C,OAAyB;CACzB,OAAoC;CACpC;CACA;CAEA,YACE,UACA,KACA,MAAgE,EAAE,EAClE;EACA,MAAM,cAAc,eAAe,UAAU,IAAI,aAAa,EAAE,CAAC;EACjE,MAAM,OAAO,YAAY,WAAW,IAAI,KAAK,mBAA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WAAW;GACT,KAAK,GAAG,MAAM,UAAU,GAAG,EAAE;GAC7B,UAAU,CAAC,SAAS,QAAQ;GAC5B,OAAO,EAAE,MAAM,SAAS;GACzB;EACD,UAAU;GAAE,KAAK,MAAM,SAAS,EAAE;GAAE,UAAU,CAAC,QAAQ;GAAE,OAAO,EAAE,MAAM,SAAS;GAAE;EACpF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#own","#parent","#text","#value","#marks","parseSource","_exhaustive","MONTHS_LONG","MONTHS_SHORT","TOKENS","_enc","_dec","_enc","isUpper"],"sources":["../src/errors.ts","../src/parser/ast.ts","../src/parser/lexer.ts","../src/parser/parser.ts","../src/parser/walk.ts","../src/evaluator/access.ts","../src/sprig/types/deepEqual.ts","../src/evaluator/lazy.ts","../src/evaluator/include.ts","../src/evaluator/truthy.ts","../src/evaluator/builtins.ts","../src/evaluator/marks.ts","../src/evaluator/scope.ts","../src/evaluator/evaluator.ts","../src/sprig/conversions/atoi.ts","../src/sprig/conversions/float64.ts","../src/sprig/conversions/parseBase0.ts","../src/sprig/conversions/int.ts","../src/sprig/conversions/int64.ts","../src/sprig/conversions/toDecimal.ts","../src/sprig/conversions/toRawJson.ts","../src/sprig/conversions/index.ts","../src/sprig/datetime/_duration.ts","../src/sprig/datetime/_resolve.ts","../src/sprig/datetime/ago.ts","../src/sprig/datetime/_format.ts","../src/sprig/datetime/_zone.ts","../src/sprig/datetime/date.ts","../src/sprig/datetime/dateInZone.ts","../src/sprig/datetime/dateModify.ts","../src/sprig/datetime/duration.ts","../src/sprig/datetime/durationRound.ts","../src/sprig/datetime/htmlDate.ts","../src/sprig/datetime/htmlDateInZone.ts","../src/sprig/datetime/now.ts","../src/sprig/datetime/_parse.ts","../src/sprig/datetime/toDate.ts","../src/sprig/datetime/unixEpoch.ts","../src/sprig/datetime/index.ts","../src/sprig/defaults/empty.ts","../src/sprig/defaults/coalesce.ts","../src/sprig/defaults/default.ts","../src/sprig/defaults/fromJson.ts","../src/sprig/defaults/ternary.ts","../src/sprig/defaults/toJson.ts","../src/sprig/defaults/toPrettyJson.ts","../src/sprig/defaults/index.ts","../src/sprig/dicts/dict.ts","../src/sprig/dicts/get.ts","../src/sprig/dicts/hasKey.ts","../src/sprig/dicts/keys.ts","../src/sprig/dicts/merge.ts","../src/sprig/dicts/mergeOverwrite.ts","../src/sprig/dicts/omit.ts","../src/sprig/dicts/pick.ts","../src/sprig/dicts/pluck.ts","../src/sprig/dicts/set.ts","../src/sprig/dicts/unset.ts","../src/sprig/dicts/values.ts","../src/sprig/dicts/index.ts","../src/sprig/flow/fail.ts","../src/sprig/flow/index.ts","../src/sprig/hash/adler32sum.ts","../src/sprig/hash/_b32.ts","../src/sprig/hash/b32dec.ts","../src/sprig/hash/b32enc.ts","../src/sprig/hash/b64dec.ts","../src/sprig/hash/b64enc.ts","../src/sprig/hash/sha1sum.ts","../src/sprig/hash/sha256sum.ts","../src/sprig/hash/sha512sum.ts","../src/sprig/hash/uuidv4.ts","../src/sprig/hash/index.ts","../src/sprig/lists/all.ts","../src/sprig/lists/any.ts","../src/sprig/lists/append.ts","../src/sprig/lists/chunk.ts","../src/sprig/lists/compact.ts","../src/sprig/lists/concat.ts","../src/evaluator/errors.ts","../src/sprig/lists/dig.ts","../src/sprig/lists/first.ts","../src/sprig/lists/has.ts","../src/sprig/lists/initial.ts","../src/sprig/lists/last.ts","../src/sprig/lists/len.ts","../src/sprig/lists/list.ts","../src/sprig/lists/prepend.ts","../src/sprig/lists/rest.ts","../src/sprig/lists/reverse.ts","../src/sprig/lists/slice.ts","../src/sprig/lists/sortAlpha.ts","../src/sprig/lists/uniq.ts","../src/sprig/lists/without.ts","../src/sprig/lists/index.ts","../src/sprig/math/add.ts","../src/sprig/math/add1.ts","../src/sprig/math/add1f.ts","../src/sprig/math/addf.ts","../src/sprig/math/ceil.ts","../src/sprig/math/div.ts","../src/sprig/math/divf.ts","../src/sprig/math/floor.ts","../src/sprig/math/max.ts","../src/sprig/math/maxf.ts","../src/sprig/math/min.ts","../src/sprig/math/minf.ts","../src/sprig/math/mod.ts","../src/sprig/math/mul.ts","../src/sprig/math/mulf.ts","../src/sprig/math/round.ts","../src/sprig/math/untilStep.ts","../src/sprig/math/seq.ts","../src/sprig/math/sub.ts","../src/sprig/math/subf.ts","../src/sprig/math/until.ts","../src/sprig/math/index.ts","../src/sprig/random/_prng.ts","../src/sprig/random/randAlpha.ts","../src/sprig/random/randAlphaNum.ts","../src/sprig/random/randAscii.ts","../src/sprig/random/randInt.ts","../src/sprig/random/randNumeric.ts","../src/sprig/strings/runes.ts","../src/sprig/random/shuffle.ts","../src/sprig/random/index.ts","../src/sprig/regex/regexFind.ts","../src/sprig/regex/regexFindAll.ts","../src/sprig/regex/regexMatch.ts","../src/sprig/regex/regexReplaceAll.ts","../src/sprig/regex/regexReplaceAllLiteral.ts","../src/sprig/regex/regexSplit.ts","../src/sprig/regex/index.ts","../src/sprig/semver/parse.ts","../src/sprig/semver/semver.ts","../src/sprig/semver/constraint.ts","../src/sprig/semver/semverCompare.ts","../src/sprig/semver/index.ts","../src/sprig/strings/abbreviateFull.ts","../src/sprig/strings/abbrev.ts","../src/sprig/strings/abbrevboth.ts","../src/sprig/strings/caseUtils.ts","../src/sprig/strings/camelcase.ts","../src/sprig/strings/cat.ts","../src/sprig/strings/contains.ts","../src/sprig/strings/hasPrefix.ts","../src/sprig/strings/hasSuffix.ts","../src/sprig/strings/indent.ts","../src/sprig/strings/initials.ts","../src/sprig/strings/join.ts","../src/sprig/strings/kebabcase.ts","../src/sprig/strings/lower.ts","../src/sprig/strings/nindent.ts","../src/sprig/strings/nospace.ts","../src/sprig/strings/plural.ts","../src/sprig/strings/quote.ts","../src/sprig/strings/regexQuoteMeta.ts","../src/sprig/strings/repeat.ts","../src/sprig/strings/replace.ts","../src/sprig/strings/snakecase.ts","../src/sprig/strings/split.ts","../src/sprig/strings/splitList.ts","../src/sprig/strings/splitn.ts","../src/sprig/strings/squote.ts","../src/sprig/strings/substr.ts","../src/sprig/strings/swapcase.ts","../src/sprig/strings/title.ts","../src/sprig/strings/trim.ts","../src/sprig/strings/trimAll.ts","../src/sprig/strings/trimPrefix.ts","../src/sprig/strings/trimSuffix.ts","../src/sprig/strings/trunc.ts","../src/sprig/strings/untitle.ts","../src/sprig/strings/upper.ts","../src/sprig/strings/wrap.ts","../src/sprig/strings/wrapWith.ts","../src/sprig/strings/index.ts","../src/sprig/types/deepCopy.ts","../src/sprig/types/kindOf.ts","../src/sprig/types/kindIs.ts","../src/sprig/types/typeOf.ts","../src/sprig/types/typeIs.ts","../src/sprig/types/typeIsLike.ts","../src/sprig/types/index.ts"],"sourcesContent":["/**\n * Unified error hierarchy for go-template-js.\n *\n * [LAW:single-enforcer] One module owns the error class hierarchy.\n * Both parser and evaluator import from here — no duplicate or\n * parallel definitions.\n *\n * TemplateError (base)\n * ├── ParseError\n * └── EvalError\n * ├── FuncNotFoundError\n * ├── ArgCountError\n * ├── TypeMismatchError\n * └── MissingFieldError\n *\n * Every error carries `pos` and `kind` (a discriminator string for\n * machine inspection). Subclasses add structured fields specific to\n * their failure mode. `.toString()` produces a multi-line presentation\n * with source snippet when `source` was supplied.\n */\n\nimport type { Pos } from \"./parser/pos.js\";\n\nexport type ErrorKind =\n | \"ParseError\"\n | \"EvalError\"\n | \"FuncNotFoundError\"\n | \"ArgCountError\"\n | \"TypeMismatchError\"\n | \"MissingFieldError\"\n | \"FailError\";\n\nexport interface TemplateErrorContext {\n readonly source?: string | undefined;\n /** The error a function body threw, when this one reports it at the call site. */\n readonly cause?: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Base.\n// ---------------------------------------------------------------------------\n\nexport class TemplateError extends Error {\n override readonly name: string = \"TemplateError\";\n readonly kind: ErrorKind = \"EvalError\";\n readonly pos: Pos;\n readonly source: string | undefined;\n\n constructor(message: string, pos: Pos, ctx: TemplateErrorContext = {}) {\n super(message, { cause: ctx.cause });\n this.pos = pos;\n this.source = ctx.source;\n }\n\n /** 3-line excerpt of the source around the error with caret. */\n get sourceSnippet(): string {\n return this.source ? buildSnippet(this.source, this.pos) : \"\";\n }\n\n override toString(): string {\n const head = `${this.name}: ${this.message}\\n at line ${this.pos.line}, column ${this.pos.column}`;\n const snippet = this.sourceSnippet;\n return snippet ? `${head}\\n\\n${snippet}` : head;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Parser error.\n// ---------------------------------------------------------------------------\n\nexport interface ParseErrorContext extends TemplateErrorContext {\n readonly expected?: string;\n readonly found?: string;\n}\n\nexport class ParseError extends TemplateError {\n override readonly name = \"ParseError\";\n override readonly kind: ErrorKind = \"ParseError\";\n readonly expected: string | undefined;\n readonly found: string | undefined;\n\n constructor(message: string, pos: Pos, ctx: ParseErrorContext = {}) {\n super(message, pos, ctx);\n this.expected = ctx.expected;\n this.found = ctx.found;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Eval errors.\n// ---------------------------------------------------------------------------\n\nexport class EvalError extends TemplateError {\n override readonly name: string = \"EvalError\";\n override readonly kind: ErrorKind = \"EvalError\";\n}\n\n/**\n * Thrown when a template references a function the engine's FuncMap\n * has no entry for. Includes a list of nearest-matching registered\n * names by edit distance — most useful when the failure is a typo.\n */\nexport class FuncNotFoundError extends EvalError {\n override readonly name = \"FuncNotFoundError\";\n override readonly kind: ErrorKind = \"FuncNotFoundError\";\n readonly funcName: string;\n readonly suggestions: readonly string[];\n\n constructor(\n funcName: string,\n pos: Pos,\n ctx: TemplateErrorContext & { available?: readonly string[] } = {},\n ) {\n const suggestions = nearestMatches(funcName, ctx.available ?? []);\n const tail = suggestions.length === 0 ? \"\" : ` (did you mean: ${suggestions.join(\", \")}?)`;\n super(`function ${JSON.stringify(funcName)} is not registered${tail}`, pos, ctx);\n this.funcName = funcName;\n this.suggestions = suggestions;\n }\n}\n\n/**\n * The argument counts a func accepts — a closed interval, with\n * `maximum: Infinity` for the variadic and alternating kinds.\n *\n * [LAW:one-source-of-truth] Nothing declares these numbers. They are\n * derived from `TemplateFunc.arity` and `argTypes.length` by\n * `acceptedArgCount` in the evaluator, which is the only producer; a\n * registration that stored its own minimum would be a second copy of a\n * number the declaration already carries.\n */\nexport interface ArgCount {\n readonly minimum: number;\n readonly maximum: number;\n}\n\n/**\n * Thrown when a func is called with a number of arguments its declared\n * arity does not accept — `{{ upper \"a\" \"b\" }}`, `{{ min }}`.\n *\n * The message mirrors Go's `text/template`, which reports a fixed-arity\n * signature as `want N` and a variadic one as `want at least N`. That\n * distinction is read off `accepted`, not passed in, so the two phrasings\n * cannot disagree about which one a given func gets.\n */\nexport class ArgCountError extends EvalError {\n override readonly name = \"ArgCountError\";\n override readonly kind: ErrorKind = \"ArgCountError\";\n readonly funcName: string;\n readonly accepted: ArgCount;\n readonly got: number;\n\n constructor(\n funcName: string,\n accepted: ArgCount,\n got: number,\n pos: Pos,\n ctx: TemplateErrorContext = {},\n ) {\n const want =\n accepted.minimum === accepted.maximum\n ? `${accepted.minimum}`\n : `at least ${accepted.minimum}`;\n super(`wrong number of args for ${funcName}: want ${want} got ${got}`, pos, ctx);\n this.funcName = funcName;\n this.accepted = accepted;\n this.got = got;\n }\n}\n\n// A template error never matches, whatever its text: a func that overflowed\n// was already reported at its own call, as `error calling <func>`.\n// No regex: V8 compiles one on first use, which at the deepest frame\n// overflows into a SyntaxError that is no longer recognised.\nexport function isStackOverflow(e: unknown): boolean {\n return (\n (e instanceof RangeError || (e instanceof Error && e.name === \"InternalError\")) &&\n (e.message.includes(\"call stack\") || e.message.includes(\"too much recursion\"))\n );\n}\n\nexport class TypeMismatchError extends EvalError {\n override readonly name = \"TypeMismatchError\";\n override readonly kind: ErrorKind = \"TypeMismatchError\";\n readonly funcName: string;\n /** 1-based argument index for human-readable messages. */\n readonly argIndex: number;\n readonly expected: string;\n readonly receivedSummary: string;\n\n constructor(\n funcName: string,\n argIndex: number,\n expected: string,\n receivedSummary: string,\n pos: Pos,\n ctx: TemplateErrorContext = {},\n ) {\n super(\n `function ${JSON.stringify(funcName)} arg ${argIndex}: expected ${expected}, ` +\n `but a value of type ${receivedSummary} flowed in. Pass it through \\`unstyled\\` (or your ` +\n `engine's flatten function) to convert.`,\n pos,\n ctx,\n );\n this.funcName = funcName;\n this.argIndex = argIndex;\n this.expected = expected;\n this.receivedSummary = receivedSummary;\n }\n}\n\n/**\n * An integer slot refused a number that is not a safe integer. Still a\n * `TypeMismatchError` (the slot's type refused the value), but worded\n * with the value and the reason: a fractional is Go's own refusal,\n * `expected integer; found 2.7`, and an integer past 2^53 is\n * `integer out of range: <n>`, since JS cannot carry it exactly. The\n * generic wording would say a number was expected and a number arrived,\n * and suggest flattening a styled value that was never there.\n */\nexport class NotIntegerError extends TypeMismatchError {\n constructor(\n funcName: string,\n argIndex: number,\n value: number | bigint,\n pos: Pos,\n ctx: TemplateErrorContext = {},\n ) {\n super(funcName, argIndex, \"integer\", String(value), pos, ctx);\n this.message = Number.isInteger(Number(value))\n ? `integer out of range: ${String(value)}`\n : `expected integer; found ${String(value)}`;\n }\n}\n\nexport class MissingFieldError extends EvalError {\n override readonly name = \"MissingFieldError\";\n override readonly kind: ErrorKind = \"MissingFieldError\";\n readonly path: readonly string[];\n\n constructor(path: readonly string[], pos: Pos, ctx: TemplateErrorContext = {}) {\n super(`field \"${path.join(\".\")}\" not found on receiver`, pos, ctx);\n this.path = path;\n }\n}\n\n// ---------------------------------------------------------------------------\n// FailError — thrown by the sprig `fail` function.\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a template calls `fail \"message\"`. Consumers can catch\n * this specifically to distinguish intentional template failures from\n * engine bugs. The message comes from the template author.\n *\n * [LAW:single-enforcer] One class, one place. The `fail` sprig function\n * is the only producer; catch `FailError` to handle it distinctly from\n * TypeMismatchError or other eval errors.\n */\nexport class FailError extends EvalError {\n override readonly name = \"FailError\";\n override readonly kind: ErrorKind = \"FailError\";\n\n constructor(\n message: string,\n pos: Pos = { line: 0, column: 0, offset: 0 },\n ctx: TemplateErrorContext = {},\n ) {\n super(message, pos, ctx);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Snippet builder — pure helper.\n// ---------------------------------------------------------------------------\n\nfunction buildSnippet(source: string, pos: Pos): string {\n const lines = source.split(\"\\n\");\n const lineIdx = pos.line - 1;\n\n const display: { num: number; text: string }[] = [];\n if (lineIdx - 1 >= 0 && lineIdx - 1 < lines.length) {\n display.push({ num: lineIdx, text: lines[lineIdx - 1] ?? \"\" });\n }\n if (lineIdx >= 0 && lineIdx < lines.length) {\n display.push({ num: lineIdx + 1, text: lines[lineIdx] ?? \"\" });\n }\n if (lineIdx + 1 < lines.length) {\n display.push({ num: lineIdx + 2, text: lines[lineIdx + 1] ?? \"\" });\n }\n if (display.length === 0) return \"\";\n\n const numWidth = String(display[display.length - 1]?.num ?? 1).length;\n const out: string[] = [];\n for (const d of display) {\n out.push(` ${String(d.num).padStart(numWidth, \" \")} | ${d.text}`);\n if (d.num === pos.line) {\n const gutter = ` ${\" \".repeat(numWidth)} | `;\n const caretPad = \" \".repeat(Math.max(0, pos.column - 1));\n out.push(`${gutter}${caretPad}^`);\n }\n }\n return out.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Edit-distance suggestions for FuncNotFoundError.\n// ---------------------------------------------------------------------------\n\nfunction nearestMatches(target: string, candidates: readonly string[]): string[] {\n if (candidates.length === 0) return [];\n const ranked = candidates\n .map((c) => ({ name: c, dist: editDistance(target, c) }))\n .sort((a, b) => a.dist - b.dist);\n // Heuristic: top 3, but only when the closest is within length/2\n // edits — avoid wildly unrelated suggestions when the user typed\n // something nothing like any registered name.\n const cutoff = Math.max(2, Math.floor(target.length / 2));\n return ranked\n .filter((r) => r.dist <= cutoff)\n .slice(0, 3)\n .map((r) => r.name);\n}\n\nfunction editDistance(a: string, b: string): number {\n if (a === b) return 0;\n const m = a.length;\n const n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n const prev = new Array<number>(n + 1);\n const cur = new Array<number>(n + 1);\n for (let j = 0; j <= n; j++) prev[j] = j;\n for (let i = 1; i <= m; i++) {\n cur[0] = i;\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n cur[j] = Math.min((cur[j - 1] ?? 0) + 1, (prev[j] ?? 0) + 1, (prev[j - 1] ?? 0) + cost);\n }\n for (let j = 0; j <= n; j++) prev[j] = cur[j] ?? 0;\n }\n return prev[n] ?? 0;\n}\n","/**\n * AST node types for go-template-js.\n *\n * Mirrors `text/template/parse` (https://pkg.go.dev/text/template/parse) so\n * an eventual Go port shares the same shape.\n *\n * [LAW:dataflow-not-control-flow] Every node has a single string literal\n * `type` discriminator. Downstream code (evaluator, walker, stringifier) is\n * one exhaustive switch over `Node[\"type\"]` — no class hierarchies, no\n * instanceof checks. Variability lives in the data (the discriminator\n * value), not in scattered conditionals.\n *\n * [LAW:one-source-of-truth] Every node carries `pos: Pos` from a single\n * canonical Pos type. No node grows its own ad-hoc position fields.\n */\n\nimport type { Pos } from \"./pos.js\";\n\n// ---------------------------------------------------------------------------\n// Trim markers — the `{{- ... -}}` whitespace-stripping syntax.\n// ---------------------------------------------------------------------------\n\nexport interface TrimMarkers {\n readonly trimLeft: boolean;\n readonly trimRight: boolean;\n}\n\nexport const NO_TRIM: TrimMarkers = { trimLeft: false, trimRight: false };\n\n// ---------------------------------------------------------------------------\n// Node base — type discriminator + position.\n// ---------------------------------------------------------------------------\n\ninterface NodeBase<T extends string> {\n readonly type: T;\n readonly pos: Pos;\n}\n\n// ---------------------------------------------------------------------------\n// Leaves.\n// ---------------------------------------------------------------------------\n\nexport interface TextNode extends NodeBase<\"Text\"> {\n readonly text: string;\n}\n\nexport interface CommentNode extends NodeBase<\"Comment\"> {\n /** The comment body, without the surrounding `{{/*` `*\\/}}`. */\n readonly text: string;\n readonly trim: TrimMarkers;\n}\n\nexport type DotNode = NodeBase<\"Dot\">;\nexport type NilNode = NodeBase<\"Nil\">;\n\nexport interface BoolNode extends NodeBase<\"Bool\"> {\n readonly value: boolean;\n}\n\n/**\n * Numeric literal. Go's parser admits ints, floats, complex, and untyped\n * constants in several bases. We preserve the original source `text` and\n * tag the parsed flavors so the evaluator can pick the right runtime\n * representation without re-lexing.\n */\nexport interface NumberNode extends NodeBase<\"Number\"> {\n /** Original source text (e.g. `0x10`, `1.5e3`, `0o17`, `42i`). */\n readonly text: string;\n readonly isInt: boolean;\n readonly isUint: boolean;\n readonly isFloat: boolean;\n readonly isComplex: boolean;\n /** Present iff `isInt || isUint`. Use bigint for safe full-range ints. */\n readonly intValue?: bigint;\n /** Present iff `isFloat`. */\n readonly floatValue?: number;\n /** Present iff `isComplex` — [real, imag]. */\n readonly complexValue?: readonly [number, number];\n}\n\nexport interface StringNode extends NodeBase<\"String\"> {\n /** Source-as-written including surrounding quotes (e.g. `\"hi\"` or `` `raw` ``). */\n readonly raw: string;\n /** Decoded string value (escapes processed). */\n readonly value: string;\n}\n\nexport interface IdentifierNode extends NodeBase<\"Identifier\"> {\n readonly ident: string;\n}\n\n/**\n * Field chain like `.x.y.z`.\n * `idents` excludes the leading dot — `.x.y` → `[\"x\", \"y\"]`.\n */\nexport interface FieldNode extends NodeBase<\"Field\"> {\n readonly idents: readonly string[];\n}\n\n/**\n * Variable reference like `$var` or `$var.x.y`.\n * `idents[0]` is the variable's name *with* its leading `$` (`\"$var\"`),\n * matching Go's parse package convention. Subsequent entries are field\n * accesses.\n */\nexport interface VariableNode extends NodeBase<\"Variable\"> {\n readonly idents: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// Composites.\n// ---------------------------------------------------------------------------\n\n/** A sequence of nodes — the body of a template, branch, or block. */\nexport interface ListNode extends NodeBase<\"List\"> {\n readonly nodes: readonly Node[];\n}\n\n/**\n * A field access on a parenthesised pipeline result, e.g. `(pipe).x.y`.\n * `node` is the inner expression (typically a PipeNode or another\n * primary).\n */\nexport interface ChainNode extends NodeBase<\"Chain\"> {\n readonly node: Node;\n readonly fields: readonly string[];\n}\n\n/** A single command in a pipeline: head + arguments. */\nexport interface CommandNode extends NodeBase<\"Command\"> {\n readonly args: readonly Node[];\n}\n\n/**\n * A pipeline — `cmd1 a b | cmd2 c | cmd3`.\n *\n * `decls` carries left-hand variable declarations for assignment forms:\n * `{{ $a := pipe }}` → decls = [$a], isAssign = false\n * `{{ $a = pipe }}` → decls = [$a], isAssign = true\n * `{{ pipe }}` → decls = [], isAssign = false\n */\nexport interface PipeNode extends NodeBase<\"Pipe\"> {\n readonly decls: readonly VariableNode[];\n readonly isAssign: boolean;\n readonly cmds: readonly CommandNode[];\n}\n\n/** `{{ pipeline }}` — produces output from a pipeline value. */\nexport interface ActionNode extends NodeBase<\"Action\"> {\n readonly pipe: PipeNode;\n readonly trim: TrimMarkers;\n}\n\n// ---------------------------------------------------------------------------\n// Branch nodes — if / range / with all share the same shape conceptually.\n// We keep them as separate types so the discriminator lets the evaluator\n// switch exhaustively, matching Go's parse package which emits IfNode,\n// RangeNode, WithNode as distinct concrete types.\n// ---------------------------------------------------------------------------\n\ninterface BranchFields {\n readonly pipe: PipeNode;\n readonly list: ListNode;\n /** Absent when there's no `{{else}}` clause. */\n readonly elseList?: ListNode;\n readonly trim: TrimMarkers;\n}\n\nexport interface IfNode extends NodeBase<\"If\">, BranchFields {}\nexport interface RangeNode extends NodeBase<\"Range\">, BranchFields {}\nexport interface WithNode extends NodeBase<\"With\">, BranchFields {}\n\n// ---------------------------------------------------------------------------\n// Range-body control-flow leaves — `{{break}}` and `{{continue}}`.\n//\n// [LAW:types-are-the-program] Break/continue carry no pipeline and no\n// body. They are leaves whose only purpose is the discriminator: the\n// evaluator's range loop switches on `type` to know which control-flow\n// transition to perform. Encoding them as leaves (instead of, say, an\n// ActionNode with a magic identifier) is the strongest theorem about\n// them — the type forbids \"{{break .foo}}\" by construction, so no body\n// has to guard against a stray pipeline.\n//\n// Their legality is *lexical*: only valid inside a `{{range}}` body\n// (not inside a `{{define}}`/`{{block}}` body, even if those are\n// lexically nested inside a range — those bodies are independent\n// parse contexts in Go's text/template, and we match that here).\n// The parser enforces this via a rangeDepth counter that is saved /\n// restored around sub-template bodies.\n// ---------------------------------------------------------------------------\n\nexport interface BreakNode extends NodeBase<\"Break\"> {\n readonly trim: TrimMarkers;\n}\n\nexport interface ContinueNode extends NodeBase<\"Continue\"> {\n readonly trim: TrimMarkers;\n}\n\n// ---------------------------------------------------------------------------\n// Sub-template nodes.\n// ---------------------------------------------------------------------------\n\n/** `{{template \"name\" pipe?}}` — invokes a named template. */\nexport interface TemplateNode extends NodeBase<\"Template\"> {\n readonly name: string;\n /** Optional argument expression. Absent when no pipe is supplied. */\n readonly pipe?: PipeNode;\n readonly trim: TrimMarkers;\n}\n\n/** `{{block \"name\" pipe}} list {{end}}` — define + invoke in one form. */\nexport interface BlockNode extends NodeBase<\"Block\"> {\n readonly name: string;\n readonly pipe: PipeNode;\n readonly list: ListNode;\n readonly trim: TrimMarkers;\n}\n\n// ---------------------------------------------------------------------------\n// The discriminated union.\n// ---------------------------------------------------------------------------\n\nexport type Node =\n | TextNode\n | CommentNode\n | DotNode\n | NilNode\n | BoolNode\n | NumberNode\n | StringNode\n | IdentifierNode\n | FieldNode\n | VariableNode\n | ListNode\n | ChainNode\n | CommandNode\n | PipeNode\n | ActionNode\n | IfNode\n | RangeNode\n | WithNode\n | BreakNode\n | ContinueNode\n | TemplateNode\n | BlockNode;\n\nexport type NodeType = Node[\"type\"];\n\nexport type NodeOf<T extends NodeType> = Extract<Node, { type: T }>;\n\n// ---------------------------------------------------------------------------\n// Type-level exhaustiveness helper.\n//\n// [LAW:dataflow-not-control-flow] Use `assertNever` in switches over Node\n// to make adding a new node kind a compile error at every dispatch site,\n// not a silent fallthrough.\n// ---------------------------------------------------------------------------\n\nexport function assertNever(value: never): never {\n throw new Error(`unhandled node kind: ${JSON.stringify(value)}`);\n}\n","/**\n * Lexer for Go-template syntax.\n *\n * Mirrors the tokens that text/template/parse/lex.go produces. The lexer\n * is a pull-style state machine — call `next()` to consume the next\n * token, `peek()` to look without consuming. EOF is emitted explicitly\n * as a terminal token.\n *\n * [LAW:dataflow-not-control-flow] The state of the lexer is captured in\n * a single `mode` discriminator (`text` | `action` | `done`), and the\n * `next()` method dispatches on that mode in one switch. Variability\n * lives in the data (current offset, current mode), not in scattered\n * conditional code paths around side effects.\n *\n * [LAW:single-enforcer] All position tracking happens through `advance`.\n * Callers never adjust `offset`, `line`, or `column` directly — that\n * would let line/column drift from offset.\n */\n\nimport { ParseError } from \"./errors.js\";\nimport type { Pos } from \"./pos.js\";\n\n// ---------------------------------------------------------------------------\n// Tokens.\n// ---------------------------------------------------------------------------\n\nexport type TokenType =\n | \"Text\"\n | \"LeftDelim\"\n | \"RightDelim\"\n | \"Comment\"\n | \"Identifier\"\n | \"Field\"\n | \"Variable\"\n | \"String\"\n | \"Number\"\n | \"Char\"\n | \"Bool\"\n | \"Nil\"\n | \"Dot\"\n | \"LeftParen\"\n | \"RightParen\"\n | \"Pipe\"\n | \"Assign\"\n | \"Declare\"\n | \"Comma\"\n | \"If\"\n | \"Else\"\n | \"End\"\n | \"Range\"\n | \"With\"\n | \"Break\"\n | \"Continue\"\n | \"Define\"\n | \"Template\"\n | \"Block\"\n | \"EOF\";\n\nexport interface Token {\n readonly type: TokenType;\n /** Original source text covered by the token (raw — quotes/dots/etc preserved). */\n readonly value: string;\n readonly pos: Pos;\n /** Set on LeftDelim when the source had `{{-`. */\n readonly trimLeft?: boolean;\n /** Set on RightDelim when the source had `-}}`. */\n readonly trimRight?: boolean;\n}\n\nconst KEYWORDS = new Map<string, TokenType>([\n [\"if\", \"If\"],\n [\"else\", \"Else\"],\n [\"end\", \"End\"],\n [\"range\", \"Range\"],\n [\"with\", \"With\"],\n [\"break\", \"Break\"],\n [\"continue\", \"Continue\"],\n [\"define\", \"Define\"],\n [\"template\", \"Template\"],\n [\"block\", \"Block\"],\n [\"true\", \"Bool\"],\n [\"false\", \"Bool\"],\n [\"nil\", \"Nil\"],\n]);\n\n/**\n * Action delimiters. Default is Go's `{{` / `}}`. Trim-marker forms are\n * derived mechanically: `<left>-` opens with-trim and `-<right>` closes\n * with-trim, matching Go's `text/template`.\n *\n * [LAW:types-are-the-program] Both sides are required if specified —\n * neither may be empty. This is a stronger theorem than Go's API\n * (which lets one side default while the other is set) and forbids\n * the half-configured state that would otherwise have to be defended\n * against at every internal use site.\n */\nexport interface Delims {\n readonly left: string;\n readonly right: string;\n}\n\nexport const DEFAULT_DELIMS: Delims = { left: \"{{\", right: \"}}\" };\n\nconst COMMENT_OPEN = \"/*\";\nconst COMMENT_CLOSE = \"*/\";\n\n// ---------------------------------------------------------------------------\n// Lexer.\n// ---------------------------------------------------------------------------\n\ntype Mode = \"text\" | \"action\" | \"done\";\n\nexport class Lexer {\n private readonly src: string;\n // [LAW:dataflow-not-control-flow] Delims are data, not modes. Lifting\n // them from module-level constants to instance fields adds no\n // branches — the existing state machine reads its delimiter strings\n // from these fields instead of from compile-time constants.\n private readonly leftDelim: string;\n private readonly rightDelim: string;\n private offset = 0;\n private line = 1;\n private column = 1;\n private mode: Mode = \"text\";\n private pending: Token | undefined;\n\n constructor(src: string, delims: Delims = DEFAULT_DELIMS) {\n this.src = src;\n this.leftDelim = delims.left;\n this.rightDelim = delims.right;\n }\n\n /** Position of the next byte to consume. */\n pos(): Pos {\n return { line: this.line, column: this.column, offset: this.offset };\n }\n\n /**\n * Build a ParseError that always carries the source for snippet\n * extraction. Lexer call sites use this exclusively.\n */\n private err(\n message: string,\n pos: Pos,\n extra: { expected?: string; found?: string } = {},\n ): ParseError {\n return new ParseError(message, pos, { ...extra, source: this.src });\n }\n\n next(): Token {\n if (this.pending) {\n const t = this.pending;\n this.pending = undefined;\n return t;\n }\n return this.read();\n }\n\n peek(): Token {\n if (!this.pending) this.pending = this.read();\n return this.pending;\n }\n\n private read(): Token {\n switch (this.mode) {\n case \"text\":\n return this.readText();\n case \"action\":\n return this.readAction();\n case \"done\":\n return this.makeToken(\"EOF\", \"\", this.pos());\n }\n }\n\n // ---------------------------------------------------------------------\n // TEXT mode — accumulate characters until a `{{` or EOF.\n //\n // Trim markers complicate this: a `{{-` token instructs the *previous*\n // text token to drop trailing whitespace. We resolve this by peeking\n // for `-` after the opening delimiter and trimming the captured text\n // before emitting it.\n // ---------------------------------------------------------------------\n private readText(): Token {\n if (this.offset >= this.src.length) {\n this.mode = \"done\";\n return this.makeToken(\"EOF\", \"\", this.pos());\n }\n const startPos = this.pos();\n\n // Find next `<leftDelim>` or EOF.\n let end = this.offset;\n while (end < this.src.length && !this.src.startsWith(this.leftDelim, end)) {\n end += 1;\n }\n\n // Detect trim marker on the upcoming delim.\n const sawDelim = end < this.src.length;\n const trimLeft = sawDelim && this.src[end + this.leftDelim.length] === \"-\";\n\n // If `{{-`, strip trailing ASCII whitespace from the captured text.\n let textEnd = end;\n if (trimLeft) {\n while (textEnd > this.offset && isSpace(this.src[textEnd - 1] ?? \"\")) {\n textEnd -= 1;\n }\n }\n\n if (textEnd > this.offset) {\n const value = this.src.slice(this.offset, textEnd);\n this.advanceTo(textEnd);\n return this.makeToken(\"Text\", value, startPos);\n }\n\n // No text content — there may still be whitespace between us and\n // the delim (already trimmed away from the previous Text token).\n // Skip it before emitting the delim so position bookkeeping stays\n // synchronised.\n this.advanceTo(end);\n return this.emitLeftDelim(trimLeft);\n }\n\n private emitLeftDelim(trimLeft: boolean): Token {\n const start = this.pos();\n this.advanceBy(this.leftDelim.length);\n if (trimLeft) {\n // skip the `-`\n this.advanceBy(1);\n // skip the whitespace right after `<left>-` per Go's spec\n while (isSpace(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n }\n this.mode = \"action\";\n\n // Comment handling: if the next chars are `/*`, consume until `*/<right>`\n // and emit a Comment token instead of a LeftDelim.\n if (this.src.startsWith(COMMENT_OPEN, this.offset)) {\n return this.readComment(start, trimLeft);\n }\n\n return this.makeToken(\n \"LeftDelim\",\n trimLeft ? `${this.leftDelim}-` : this.leftDelim,\n start,\n trimLeft ? { trimLeft: true } : {},\n );\n }\n\n private readComment(startDelim: Pos, trimLeft: boolean): Token {\n this.advanceBy(COMMENT_OPEN.length);\n const bodyStart = this.offset;\n const closeIdx = this.src.indexOf(COMMENT_CLOSE, this.offset);\n if (closeIdx === -1) {\n throw this.err(\"unclosed comment\", startDelim, {\n expected: `*/${this.rightDelim}`,\n found: \"end of input\",\n });\n }\n // Advance through body\n this.advanceTo(closeIdx);\n const body = this.src.slice(bodyStart, closeIdx).trim();\n this.advanceBy(COMMENT_CLOSE.length);\n\n // Optional whitespace between `*/` and the closing `<right>` / `-<right>`.\n // Go's spec says `-<right>` requires *adjacent* whitespace; we accept\n // either `*/ -<right>`, `*/-<right>`, `*/ <right>`, or `*/<right>` for\n // forgiveness.\n while (isSpace(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n let trimRight = false;\n if (this.src[this.offset] === \"-\") {\n trimRight = true;\n this.advanceBy(1);\n }\n if (!this.src.startsWith(this.rightDelim, this.offset)) {\n throw this.err(`expected \\`${this.rightDelim}\\` to close comment`, this.pos(), {\n expected: this.rightDelim,\n found: this.src[this.offset] ?? \"end of input\",\n });\n }\n this.advanceBy(this.rightDelim.length);\n // After comment body close, drop trailing whitespace from upcoming\n // text if `-}}` was used. Implement by skipping forward in text now.\n if (trimRight) {\n while (isSpace(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n }\n this.mode = \"text\";\n\n // Comment carries its own trim flags so the parser can preserve\n // them in the AST. Omit unset flags entirely (per\n // exactOptionalPropertyTypes).\n return this.makeToken(\"Comment\", body, startDelim, {\n ...(trimLeft ? { trimLeft: true } : {}),\n ...(trimRight ? { trimRight: true } : {}),\n });\n }\n\n // ---------------------------------------------------------------------\n // ACTION mode — operators, identifiers, literals.\n // ---------------------------------------------------------------------\n private readAction(): Token {\n this.skipActionSpaces();\n\n // Right delim? Check `-<right>` *first* — otherwise a delim like\n // `}}` would match the bare form before the trim-form is considered.\n if (this.src.startsWith(`-${this.rightDelim}`, this.offset)) {\n const start = this.pos();\n this.advanceBy(1 + this.rightDelim.length);\n this.mode = \"text\";\n // strip leading whitespace from upcoming text\n while (isSpace(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n return this.makeToken(\"RightDelim\", `-${this.rightDelim}`, start, { trimRight: true });\n }\n if (this.src.startsWith(this.rightDelim, this.offset)) {\n const start = this.pos();\n this.advanceBy(this.rightDelim.length);\n this.mode = \"text\";\n return this.makeToken(\"RightDelim\", this.rightDelim, start);\n }\n\n if (this.offset >= this.src.length) {\n throw this.err(\"unclosed action\", this.pos(), {\n expected: this.rightDelim,\n found: \"end of input\",\n });\n }\n\n const ch = this.src[this.offset];\n const start = this.pos();\n\n // Punctuation.\n switch (ch) {\n case \"(\":\n this.advanceBy(1);\n return this.makeToken(\"LeftParen\", \"(\", start);\n case \")\":\n this.advanceBy(1);\n return this.makeToken(\"RightParen\", \")\", start);\n case \"|\":\n this.advanceBy(1);\n return this.makeToken(\"Pipe\", \"|\", start);\n case \",\":\n this.advanceBy(1);\n return this.makeToken(\"Comma\", \",\", start);\n case \":\":\n if (this.src[this.offset + 1] === \"=\") {\n this.advanceBy(2);\n return this.makeToken(\"Declare\", \":=\", start);\n }\n throw this.err(\"expected `:=`\", start, { expected: \":=\", found: \":\" });\n case \"=\":\n this.advanceBy(1);\n return this.makeToken(\"Assign\", \"=\", start);\n case '\"':\n return this.readQuotedString(start);\n case \"`\":\n return this.readRawString(start);\n case \"'\":\n return this.readChar(start);\n }\n\n // Variable: $name or $ alone.\n if (ch === \"$\") {\n return this.readVariable(start);\n }\n\n // Number — possibly signed. Go template numbers can begin with +/-.\n if (\n ch !== undefined &&\n (isDigit(ch) ||\n (isSign(ch) && isDigit(this.src[this.offset + 1] ?? \"\")) ||\n (ch === \".\" && isDigit(this.src[this.offset + 1] ?? \"\")))\n ) {\n return this.readNumber(start);\n }\n\n // Field: `.name` or bare `.`\n if (ch === \".\") {\n return this.readDotOrField(start);\n }\n\n // Identifier / keyword.\n if (ch !== undefined && isIdentStart(ch)) {\n return this.readIdentifier(start);\n }\n\n throw this.err(`unexpected character ${JSON.stringify(ch)}`, start, {\n found: ch ?? \"end of input\",\n });\n }\n\n // ---------------------------------------------------------------------\n // Literals + identifiers.\n // ---------------------------------------------------------------------\n\n private readQuotedString(start: Pos): Token {\n const startOffset = this.offset;\n this.advanceBy(1);\n while (this.offset < this.src.length) {\n const c = this.src[this.offset];\n if (c === \"\\\\\") {\n // Skip escape sequence (consume the next char, no decoding here).\n this.advanceBy(1);\n if (this.offset < this.src.length) this.advanceBy(1);\n continue;\n }\n if (c === \"\\n\") {\n throw this.err(\"newline in interpreted string\", start, {\n found: \"\\\\n\",\n });\n }\n if (c === '\"') {\n this.advanceBy(1);\n return this.makeToken(\"String\", this.src.slice(startOffset, this.offset), start);\n }\n this.advanceBy(1);\n }\n throw this.err(\"unterminated string literal\", start, {\n expected: '\"',\n found: \"end of input\",\n });\n }\n\n private readRawString(start: Pos): Token {\n const startOffset = this.offset;\n this.advanceBy(1);\n while (this.offset < this.src.length) {\n if (this.src[this.offset] === \"`\") {\n this.advanceBy(1);\n return this.makeToken(\"String\", this.src.slice(startOffset, this.offset), start);\n }\n this.advanceBy(1);\n }\n throw this.err(\"unterminated raw string literal\", start, {\n expected: \"`\",\n found: \"end of input\",\n });\n }\n\n private readChar(start: Pos): Token {\n const startOffset = this.offset;\n this.advanceBy(1);\n while (this.offset < this.src.length) {\n const c = this.src[this.offset];\n if (c === \"\\\\\") {\n this.advanceBy(1);\n if (this.offset < this.src.length) this.advanceBy(1);\n continue;\n }\n if (c === \"\\n\") {\n throw this.err(\"newline in rune literal\", start, { found: \"\\\\n\" });\n }\n if (c === \"'\") {\n this.advanceBy(1);\n return this.makeToken(\"Char\", this.src.slice(startOffset, this.offset), start);\n }\n this.advanceBy(1);\n }\n throw this.err(\"unterminated rune literal\", start, {\n expected: \"'\",\n found: \"end of input\",\n });\n }\n\n private readNumber(start: Pos): Token {\n const startOffset = this.offset;\n // Optional sign.\n if (isSign(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n // Detect base prefix.\n if (this.src[this.offset] === \"0\" && this.offset + 1 < this.src.length) {\n const next = this.src[this.offset + 1];\n if (next === \"x\" || next === \"X\") {\n this.advanceBy(2);\n while (isHex(this.src[this.offset] ?? \"\") || this.src[this.offset] === \"_\") {\n this.advanceBy(1);\n }\n // hex float (1.0p1) — Go supports it; we accept the form lazily\n if (\n this.src[this.offset] === \".\" ||\n this.src[this.offset] === \"p\" ||\n this.src[this.offset] === \"P\"\n ) {\n while (this.isHexFloatTail(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n }\n return this.finishNumber(startOffset, start);\n }\n if (next === \"o\" || next === \"O\") {\n this.advanceBy(2);\n while (isOctal(this.src[this.offset] ?? \"\") || this.src[this.offset] === \"_\")\n this.advanceBy(1);\n return this.finishNumber(startOffset, start);\n }\n if (next === \"b\" || next === \"B\") {\n this.advanceBy(2);\n while (isBinary(this.src[this.offset] ?? \"\") || this.src[this.offset] === \"_\")\n this.advanceBy(1);\n return this.finishNumber(startOffset, start);\n }\n }\n\n // Decimal / float.\n while (isDigit(this.src[this.offset] ?? \"\") || this.src[this.offset] === \"_\") this.advanceBy(1);\n if (this.src[this.offset] === \".\") {\n this.advanceBy(1);\n while (isDigit(this.src[this.offset] ?? \"\") || this.src[this.offset] === \"_\")\n this.advanceBy(1);\n }\n if (this.src[this.offset] === \"e\" || this.src[this.offset] === \"E\") {\n this.advanceBy(1);\n if (isSign(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n while (isDigit(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n }\n // Imaginary suffix.\n if (this.src[this.offset] === \"i\") this.advanceBy(1);\n return this.finishNumber(startOffset, start);\n }\n\n private isHexFloatTail(c: string): boolean {\n return isHex(c) || c === \".\" || c === \"p\" || c === \"P\" || c === \"+\" || c === \"-\" || c === \"_\";\n }\n\n private finishNumber(startOffset: number, start: Pos): Token {\n if (this.offset === startOffset) {\n throw this.err(\"expected number\", start, { expected: \"digit\" });\n }\n return this.makeToken(\"Number\", this.src.slice(startOffset, this.offset), start);\n }\n\n private readVariable(start: Pos): Token {\n const startOffset = this.offset;\n this.advanceBy(1); // $\n while (isIdentPart(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n // Field accesses appended to a variable form a Variable token whose\n // value is the full `$name.x.y` chain. The parser splits this back\n // into VariableNode.idents.\n while (this.src[this.offset] === \".\" && isIdentStart(this.src[this.offset + 1] ?? \"\")) {\n this.advanceBy(1); // .\n while (isIdentPart(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n }\n return this.makeToken(\"Variable\", this.src.slice(startOffset, this.offset), start);\n }\n\n private readDotOrField(start: Pos): Token {\n const startOffset = this.offset;\n this.advanceBy(1); // .\n if (!isIdentStart(this.src[this.offset] ?? \"\")) {\n return this.makeToken(\"Dot\", \".\", start);\n }\n while (isIdentPart(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n while (this.src[this.offset] === \".\" && isIdentStart(this.src[this.offset + 1] ?? \"\")) {\n this.advanceBy(1); // .\n while (isIdentPart(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n }\n return this.makeToken(\"Field\", this.src.slice(startOffset, this.offset), start);\n }\n\n private readIdentifier(start: Pos): Token {\n const startOffset = this.offset;\n while (isIdentPart(this.src[this.offset] ?? \"\")) this.advanceBy(1);\n const text = this.src.slice(startOffset, this.offset);\n const kw = KEYWORDS.get(text);\n if (kw) {\n return this.makeToken(kw, text, start);\n }\n return this.makeToken(\"Identifier\", text, start);\n }\n\n // ---------------------------------------------------------------------\n // Position and dispatch helpers.\n // ---------------------------------------------------------------------\n\n private skipActionSpaces(): void {\n while (this.offset < this.src.length) {\n const c = this.src[this.offset];\n if (c === \" \" || c === \"\\t\" || c === \"\\r\" || c === \"\\n\") {\n this.advanceBy(1);\n } else {\n return;\n }\n }\n }\n\n private advanceBy(n: number): void {\n for (let i = 0; i < n; i++) {\n const c = this.src[this.offset];\n this.offset += 1;\n if (c === \"\\n\") {\n this.line += 1;\n this.column = 1;\n } else {\n this.column += 1;\n }\n }\n }\n\n private advanceTo(target: number): void {\n while (this.offset < target) this.advanceBy(1);\n }\n\n private makeToken(\n type: TokenType,\n value: string,\n pos: Pos,\n extra: { trimLeft?: boolean; trimRight?: boolean } = {},\n ): Token {\n return Object.freeze({\n type,\n value,\n pos,\n ...(extra.trimLeft !== undefined ? { trimLeft: extra.trimLeft } : {}),\n ...(extra.trimRight !== undefined ? { trimRight: extra.trimRight } : {}),\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Character class predicates — small + inlinable.\n// ---------------------------------------------------------------------------\n\nfunction isSpace(c: string): boolean {\n return c === \" \" || c === \"\\t\" || c === \"\\r\" || c === \"\\n\";\n}\n\nfunction isSign(c: string): boolean {\n return c === \"+\" || c === \"-\";\n}\n\nfunction isDigit(c: string): boolean {\n return c >= \"0\" && c <= \"9\";\n}\n\nfunction isHex(c: string): boolean {\n return isDigit(c) || (c >= \"a\" && c <= \"f\") || (c >= \"A\" && c <= \"F\");\n}\n\nfunction isOctal(c: string): boolean {\n return c >= \"0\" && c <= \"7\";\n}\n\nfunction isBinary(c: string): boolean {\n return c === \"0\" || c === \"1\";\n}\n\nfunction isLetter(c: string): boolean {\n return (c >= \"a\" && c <= \"z\") || (c >= \"A\" && c <= \"Z\");\n}\n\nfunction isIdentStart(c: string): boolean {\n return isLetter(c) || c === \"_\";\n}\n\nfunction isIdentPart(c: string): boolean {\n return isIdentStart(c) || isDigit(c);\n}\n\n// ---------------------------------------------------------------------------\n// Convenience: tokenize an entire source.\n// ---------------------------------------------------------------------------\n\nexport function tokenize(src: string, delims?: Delims): readonly Token[] {\n const lex = delims ? new Lexer(src, delims) : new Lexer(src);\n const out: Token[] = [];\n while (true) {\n const t = lex.next();\n out.push(t);\n if (t.type === \"EOF\") return out;\n }\n}\n","/**\n * Recursive-descent parser for Go-template syntax.\n *\n * [LAW:dataflow-not-control-flow] The parser is a single class whose\n * methods read the token stream and emit AST nodes. There are no\n * conditional code paths that produce *different program structure* —\n * every grammar production is one method whose shape is fixed; the\n * variability is in the token values it observes.\n *\n * [LAW:single-enforcer] All token consumption goes through `next` /\n * `peek` / `expect`. No grammar production reaches into the lexer\n * directly — that would let two productions disagree about position\n * tracking or lookahead state.\n */\n\nimport type {\n ActionNode,\n BlockNode,\n BoolNode,\n BreakNode,\n ChainNode,\n CommandNode,\n CommentNode,\n ContinueNode,\n DotNode,\n FieldNode,\n IdentifierNode,\n IfNode,\n ListNode,\n NilNode,\n Node,\n NumberNode,\n PipeNode,\n RangeNode,\n StringNode,\n TemplateNode,\n TextNode,\n TrimMarkers,\n VariableNode,\n WithNode,\n} from \"./ast.js\";\nimport { ParseError } from \"./errors.js\";\nimport { type Delims, Lexer, type Token, type TokenType } from \"./lexer.js\";\nimport type { Pos } from \"./pos.js\";\n\n// ---------------------------------------------------------------------------\n// Public API.\n// ---------------------------------------------------------------------------\n\n/**\n * A named sub-template body together with the source it was parsed from.\n * A body invoked through an inherited `Defines` runs far from the template\n * that invoked it, so an error inside it must snippet against ITS source,\n * not the invoker's.\n */\nexport interface DefineEntry {\n readonly list: ListNode;\n readonly source: string;\n}\n\n/**\n * The named sub-templates a template can invoke: the ones its own source\n * declared plus, transitively, the ones it inherited at parse. Opaque: only\n * `has`, `names` and the `EMPTY` identity are public, so a consumer can neither build\n * one by hand (the parser is the single enforcer of the redefinition invariant\n * below) nor reach the AST inside — the entry lookup is `lookupDefine`, a\n * module export index.ts never re-exports.\n *\n * [LAW:one-source-of-truth] Inheritance is a parent LINK, never a copy. N\n * templates parsed against one shared preamble hold one preamble AST among\n * them — the alternative (prepending the preamble's source to each parse)\n * multiplies the preamble's AST by N, which is how a 2 KB helper block became\n * hundreds of megabytes in a long-lived process.\n *\n * Lookup is nearest-first, but the parser forbids a template from declaring a\n * name its inherited set already holds (the same `redefinition` error as two\n * declarations in one source), so nearest-first never actually shadows.\n */\n// [LAW:one-source-of-truth] The parser is the only place a Defines is built\n// and the evaluator the only reader of its entries — both captured from the\n// static block below, the same way Engine reaches Template's private\n// constructor — so the public surface carries neither a constructor nor an\n// AST-returning method.\nlet chainDefines: (own: ReadonlyMap<string, DefineEntry>, parent: Defines) => Defines;\nlet readDefine: (defines: Defines, name: string) => DefineEntry | undefined;\n\n/** Nearest-first entry lookup through the inheritance chain. Package-internal. */\nexport function lookupDefine(defines: Defines, name: string): DefineEntry | undefined {\n return readDefine(defines, name);\n}\n\nexport class Defines {\n static readonly EMPTY = new Defines(new Map(), undefined);\n readonly #own: ReadonlyMap<string, DefineEntry>;\n readonly #parent: Defines | undefined;\n\n private constructor(own: ReadonlyMap<string, DefineEntry>, parent: Defines | undefined) {\n this.#own = own;\n this.#parent = parent;\n }\n\n static {\n chainDefines = (own, parent) => new Defines(own, parent);\n readDefine = (d, name) => d.#own.get(name) ?? (d.#parent && readDefine(d.#parent, name));\n }\n\n has(name: string): boolean {\n return readDefine(this, name) !== undefined;\n }\n\n /**\n * Every name this set can render, own and inherited, sorted — what a\n * consumer reads after `evaluateDefine` reports a name as not defined.\n * The parser forbids redeclaring an inherited name, so the chain repeats\n * none; the Set keeps the listing duplicate-free without leaning on that.\n */\n names(): string[] {\n const names = new Set<string>();\n for (let d: Defines | undefined = this; d; d = d.#parent) {\n for (const name of d.#own.keys()) names.add(name);\n }\n return [...names].sort();\n }\n}\n\nexport interface ParseResult {\n /** The body of the unnamed/root template. */\n readonly root: ListNode;\n /**\n * Templates this parse can invoke: its own (`ownDefines`) chained onto the\n * inherited set it was parsed against.\n */\n readonly defines: Defines;\n /**\n * The sub-templates this source itself declared, by `{{define \"name\"}}` /\n * `{{block}}` — what static introspection describes; the inherited set is\n * described by the parse that declared it.\n */\n readonly ownDefines: ReadonlyMap<string, DefineEntry>;\n /** Original source text — preserved for error snippets and Template.source. */\n readonly source: string;\n}\n\nexport function parse(\n source: string,\n delims?: Delims,\n inherit: Defines = Defines.EMPTY,\n): ParseResult {\n const parser = new Parser(source, delims, inherit);\n return parser.parseTemplate();\n}\n\n// ---------------------------------------------------------------------------\n// Internals.\n// ---------------------------------------------------------------------------\n\n// Go's text/template/parse names the pipeline it is parsing in its\n// errors (\"too many declarations in command\").\ntype PipelineContext =\n | \"command\"\n | \"if\"\n | \"range\"\n | \"with\"\n | \"template clause\"\n | \"block clause\"\n | \"parenthesized pipeline\";\n\nconst PIPELINE_CONTEXT = { If: \"if\", Range: \"range\", With: \"with\" } as const satisfies Record<\n \"If\" | \"Range\" | \"With\",\n PipelineContext\n>;\n\nclass Parser {\n private readonly lex: Lexer;\n private readonly buf: Token[] = [];\n private readonly defines = new Map<string, DefineEntry>();\n private readonly inherit: Defines;\n private readonly source: string;\n // [LAW:types-are-the-program] Lexical-only counter: how many enclosing\n // `{{range}}` bodies surround the current parse position. `{{break}}`\n // and `{{continue}}` are legal iff this is > 0. Mirrors Go's\n // text/template/parse `Tree.rangeDepth`. Saved/restored around\n // sub-template bodies (`{{define}}` / `{{block}}`) because those\n // bodies are independent parse contexts in Go — a break lexically\n // inside a range but inside a nested define is still an error.\n private rangeDepth = 0;\n\n constructor(source: string, delims: Delims | undefined, inherit: Defines) {\n this.source = source;\n this.inherit = inherit;\n this.lex = delims ? new Lexer(source, delims) : new Lexer(source);\n }\n\n // -------------------------------------------------------------------\n // Token stream helpers.\n // -------------------------------------------------------------------\n\n private peek(n = 0): Token {\n while (this.buf.length <= n) {\n this.buf.push(this.lex.next());\n }\n // [LAW:no-defensive-null-guards] We just filled the buffer to n+1\n // entries, so buf[n] is non-undefined by construction. Cast rather\n // than guard — the alternative throw would be unreachable.\n return this.buf[n] as Token;\n }\n\n private next(): Token {\n if (this.buf.length > 0) return this.buf.shift() as Token;\n return this.lex.next();\n }\n\n private expect(type: TokenType, what: string): Token {\n const t = this.next();\n if (t.type !== type) {\n throw this.errAt(t, `expected ${what}`, { expected: what, found: tokenLabel(t) });\n }\n return t;\n }\n\n private errAt(\n t: Token,\n message: string,\n extra: { expected?: string; found?: string } = {},\n ): ParseError {\n return new ParseError(message, t.pos, {\n ...extra,\n source: this.source,\n });\n }\n\n // -------------------------------------------------------------------\n // Top-level.\n // -------------------------------------------------------------------\n\n parseTemplate(): ParseResult {\n const root = this.parseList();\n if (this.peek().type !== \"EOF\") {\n const left = this.peek();\n // We only stop in parseList for stray `{{else}}` or `{{end}}`.\n // Surface that as a curated message rather than the generic\n // \"unexpected `{{`\" we'd otherwise emit.\n const inside = this.peek(1);\n if (left.type === \"LeftDelim\" && (inside.type === \"Else\" || inside.type === \"End\")) {\n const keyword = inside.type === \"Else\" ? \"else\" : \"end\";\n throw this.errAt(\n left,\n `unexpected \\`{{${keyword}}}\\` outside of \\`if\\`, \\`range\\`, \\`with\\`, or \\`block\\``,\n { found: `{{${keyword}}}` },\n );\n }\n throw this.errAt(left, `unexpected ${tokenLabel(left)}`, { found: tokenLabel(left) });\n }\n return {\n root,\n defines: chainDefines(this.defines, this.inherit),\n ownDefines: this.defines,\n source: this.source,\n };\n }\n\n // -------------------------------------------------------------------\n // List body — runs until EOF or a branch terminator (else/end).\n // -------------------------------------------------------------------\n\n private parseList(): ListNode {\n const startPos = this.peek().pos;\n const nodes: Node[] = [];\n while (true) {\n const t = this.peek();\n if (t.type === \"EOF\") break;\n if (t.type === \"Text\") {\n this.next();\n nodes.push({ type: \"Text\", pos: t.pos, text: t.value } satisfies TextNode);\n continue;\n }\n if (t.type === \"Comment\") {\n this.next();\n const trim = trimFromToken(t);\n nodes.push({ type: \"Comment\", pos: t.pos, text: t.value, trim } satisfies CommentNode);\n continue;\n }\n if (t.type === \"LeftDelim\") {\n // Branch terminators stop the list without consuming the delim.\n const inside = this.peek(1).type;\n if (inside === \"Else\" || inside === \"End\") return finishList(startPos, nodes);\n const action = this.parseAction();\n if (action !== null) nodes.push(action);\n continue;\n }\n throw this.errAt(t, `unexpected ${tokenLabel(t)} at top level`, {\n found: tokenLabel(t),\n });\n }\n return finishList(startPos, nodes);\n }\n\n // -------------------------------------------------------------------\n // Action body — dispatched on the keyword right after `{{`.\n //\n // Returns null when the action consumed is a `{{define}}` block, since\n // defines are stashed in the parser's defines map rather than added to\n // the surrounding list.\n // -------------------------------------------------------------------\n\n private parseAction(): Node | null {\n const left = this.expect(\"LeftDelim\", \"`{{`\");\n const trimLeft = left.trimLeft === true;\n const head = this.peek();\n\n switch (head.type) {\n case \"If\":\n this.next();\n return this.parseBranch(\"If\", left.pos, trimLeft);\n case \"Range\":\n this.next();\n return this.parseBranch(\"Range\", left.pos, trimLeft);\n case \"With\":\n this.next();\n return this.parseBranch(\"With\", left.pos, trimLeft);\n case \"Break\":\n this.next();\n return this.parseBreakOrContinue(\"Break\", left.pos, trimLeft);\n case \"Continue\":\n this.next();\n return this.parseBreakOrContinue(\"Continue\", left.pos, trimLeft);\n case \"Template\":\n this.next();\n return this.parseTemplateInvocation(left.pos, trimLeft);\n case \"Block\":\n this.next();\n return this.parseBlock(left.pos, trimLeft);\n case \"Define\":\n this.next();\n this.parseDefine(left.pos, trimLeft);\n return null;\n case \"RightDelim\":\n // Empty action `{{}}` is illegal in Go's parser.\n throw this.errAt(head, \"empty action\", { expected: \"pipeline\" });\n default: {\n // A plain pipeline action: `{{ pipeline }}`.\n const pipe = this.parsePipeline(\"command\");\n const right = this.expect(\"RightDelim\", \"`}}`\");\n return {\n type: \"Action\",\n pos: left.pos,\n pipe,\n trim: { trimLeft, trimRight: right.trimRight === true },\n } satisfies ActionNode;\n }\n }\n }\n\n // -------------------------------------------------------------------\n // Branches: if / range / with.\n //\n // Shape: `{{if PIPE}} list ({{else if PIPE}} list)* ({{else}} list)? {{end}}`.\n // The `else if` chain is desugared into nested IfNodes inside the\n // outer if's elseList, matching Go's parse package.\n // -------------------------------------------------------------------\n\n private parseBranch(\n kind: \"If\" | \"Range\" | \"With\",\n startPos: Pos,\n trimLeft: boolean,\n ): IfNode | RangeNode | WithNode {\n const pipe = this.parsePipeline(PIPELINE_CONTEXT[kind]);\n this.expect(\"RightDelim\", \"`}}`\");\n // [LAW:types-are-the-program] `rangeDepth` counts the enclosing\n // ranges that can absorb a `{{break}}` / `{{continue}}` at the\n // current parse position. A range's body contributes 1; a range's\n // else clause contributes 0 — the else only runs on empty input\n // and is structurally outside the iteration, so it cannot be the\n // *target* of a break aimed at its own range. Another enclosing\n // range is required for the signal to be catchable.\n //\n // Decrementing *before* parsing the else (not after parseElsePart)\n // matches Go's text/template parser exactly — see\n // text/template/parse/parse.go:540-547 — so a top-level\n // `{{range}}{{else}}{{break}}{{end}}` errors at parse time with\n // the same \"{{break}} outside {{range}}\" message Go emits.\n if (kind === \"Range\") this.rangeDepth += 1;\n const list = this.parseList();\n if (kind === \"Range\") this.rangeDepth -= 1;\n const elsePart = this.parseElsePart();\n const endRight = elsePart.endConsumed ? elsePart.endRight : this.consumeEnd();\n const trim: TrimMarkers = { trimLeft, trimRight: endRight };\n\n const base = elsePart.list\n ? { pipe, list, elseList: elsePart.list, trim }\n : { pipe, list, trim };\n switch (kind) {\n case \"If\":\n return { type: \"If\", pos: startPos, ...base } satisfies IfNode;\n case \"Range\":\n return { type: \"Range\", pos: startPos, ...base } satisfies RangeNode;\n case \"With\":\n return { type: \"With\", pos: startPos, ...base } satisfies WithNode;\n }\n }\n\n // -------------------------------------------------------------------\n // {{break}} / {{continue}} — range-body control flow.\n //\n // [LAW:types-are-the-program] Both are leaves with only a position +\n // trim markers. The strongest theorem about them is that they carry\n // no value, no body, no pipeline — encode that in the type so the\n // body of every visitor is forced to treat them as leaves.\n //\n // [LAW:single-enforcer] The \"must be inside a `{{range}}`\" rule\n // lives here at the gate. Once the AST is built, the evaluator\n // trusts the lexical guarantee — no runtime guard re-checks.\n // -------------------------------------------------------------------\n private parseBreakOrContinue(\n kind: \"Break\" | \"Continue\",\n startPos: Pos,\n trimLeft: boolean,\n ): BreakNode | ContinueNode {\n if (this.rangeDepth === 0) {\n const keyword = kind === \"Break\" ? \"break\" : \"continue\";\n throw new ParseError(`{{${keyword}}} outside of {{range}}`, startPos, {\n source: this.source,\n });\n }\n const right = this.expect(\"RightDelim\", \"`}}`\");\n const trim: TrimMarkers = { trimLeft, trimRight: right.trimRight === true };\n return kind === \"Break\"\n ? ({ type: \"Break\", pos: startPos, trim } satisfies BreakNode)\n : ({ type: \"Continue\", pos: startPos, trim } satisfies ContinueNode);\n }\n\n /**\n * Parse the `{{else}}` / `{{else if PIPE}}` segment, if any.\n *\n * `else if` is desugared into a nested IfNode wrapped in the elseList.\n * The recursive parseBranch consumes the chain's single closing\n * `{{end}}`, so the outer caller must NOT consume another — hence the\n * `endConsumed` flag we propagate back.\n */\n private parseElsePart(): {\n list: ListNode | undefined;\n endRight: boolean;\n endConsumed: boolean;\n } {\n if (this.peek().type !== \"LeftDelim\" || this.peek(1).type !== \"Else\") {\n return { list: undefined, endRight: false, endConsumed: false };\n }\n const left = this.next(); // {{\n this.next(); // else\n if (this.peek().type === \"If\") {\n this.next(); // if\n const innerIf = this.parseBranch(\"If\", left.pos, left.trimLeft === true);\n return {\n list: { type: \"List\", pos: left.pos, nodes: [innerIf] },\n endRight: innerIf.trim.trimRight,\n endConsumed: true,\n };\n }\n this.expect(\"RightDelim\", \"`}}`\");\n const list = this.parseList();\n return { list, endRight: false, endConsumed: false };\n }\n\n /** Consume the closing `{{end}}` and return whether it was a `-}}`. */\n private consumeEnd(): boolean {\n this.expect(\"LeftDelim\", \"`{{end}}`\");\n this.expect(\"End\", \"`end`\");\n const right = this.expect(\"RightDelim\", \"`}}`\");\n return right.trimRight === true;\n }\n\n // -------------------------------------------------------------------\n // Sub-templates: template / block / define.\n // -------------------------------------------------------------------\n\n private parseTemplateInvocation(startPos: Pos, trimLeft: boolean): TemplateNode {\n const name = this.parseQuotedName();\n const pipe =\n this.peek().type === \"RightDelim\" ? undefined : this.parsePipeline(\"template clause\");\n const right = this.expect(\"RightDelim\", \"`}}`\");\n const trim: TrimMarkers = { trimLeft, trimRight: right.trimRight === true };\n return pipe\n ? ({ type: \"Template\", pos: startPos, name, pipe, trim } satisfies TemplateNode)\n : ({ type: \"Template\", pos: startPos, name, trim } satisfies TemplateNode);\n }\n\n private parseBlock(startPos: Pos, trimLeft: boolean): BlockNode {\n const name = this.parseQuotedName();\n const pipe = this.parsePipeline(\"block clause\");\n this.expect(\"RightDelim\", \"`}}`\");\n // [LAW:types-are-the-program] A `{{block}}` body is invoked via the\n // sub-template machinery: a separate parse context in Go's\n // text/template. Save and reset rangeDepth so a `{{break}}` inside\n // a block body — even when the block is lexically nested in an\n // outer range — is correctly rejected at parse time.\n const savedDepth = this.rangeDepth;\n this.rangeDepth = 0;\n const list = this.parseList();\n this.rangeDepth = savedDepth;\n const endRight = this.consumeEnd();\n const trim: TrimMarkers = { trimLeft, trimRight: endRight };\n // Block both registers a default body under `name` AND invokes it.\n // A preceding `{{define}}` for the same name — in this source or in the\n // inherited set — takes precedence: the block body is the fallback, not\n // the override.\n if (!this.defines.has(name) && !this.inherit.has(name)) {\n this.defines.set(name, { list, source: this.source });\n }\n return { type: \"Block\", pos: startPos, name, pipe, list, trim } satisfies BlockNode;\n }\n\n private parseDefine(_startPos: Pos, _trimLeft: boolean): void {\n const name = this.parseQuotedName();\n this.expect(\"RightDelim\", \"`}}`\");\n // [LAW:types-are-the-program] Defines are independent parse\n // contexts in Go's text/template — `{{break}}` inside a `{{define}}`\n // body is illegal even when the define is lexically nested inside\n // a range. Save and reset rangeDepth so the depth tracked here\n // reflects only ranges that lexically enclose this body.\n const savedDepth = this.rangeDepth;\n this.rangeDepth = 0;\n const list = this.parseList();\n this.rangeDepth = savedDepth;\n this.consumeEnd();\n if (this.defines.has(name) || this.inherit.has(name)) {\n throw new ParseError(`redefinition of template ${JSON.stringify(name)}`, list.pos, {\n source: this.source,\n });\n }\n this.defines.set(name, { list, source: this.source });\n }\n\n private parseQuotedName(): string {\n const t = this.next();\n if (t.type !== \"String\") {\n throw this.errAt(t, \"expected template name (quoted string)\", {\n expected: \"string\",\n found: tokenLabel(t),\n });\n }\n return decodeStringLiteral(t.value, t.pos, this.source);\n }\n\n // -------------------------------------------------------------------\n // Pipelines.\n //\n // pipeline := decls? command (`|` command)*\n // decls := variable (`,` variable)? (`:=` | `=`)\n //\n // The second variable is legal only in a `range` pipeline.\n // -------------------------------------------------------------------\n\n private parsePipeline(context: PipelineContext): PipeNode {\n const startPos = this.peek().pos;\n const decls = this.tryParseDecls(context);\n const end = this.peek();\n if (end.type === \"RightDelim\" || end.type === \"RightParen\") {\n throw this.errAt(end, `missing value for ${context}`, { expected: \"command\" });\n }\n const cmds: CommandNode[] = [this.parseCommand()];\n while (this.peek().type === \"Pipe\") {\n this.next();\n const next = this.peek();\n if (!canStartPrimary(next.type)) {\n throw this.errAt(next, \"missing command after `|`\", {\n expected: \"command\",\n found: tokenLabel(next),\n });\n }\n cmds.push(this.parseCommand());\n }\n return {\n type: \"Pipe\",\n pos: startPos,\n decls: decls?.vars ?? [],\n isAssign: decls?.isAssign ?? false,\n cmds,\n };\n }\n\n private tryParseDecls(\n context: PipelineContext,\n ): { vars: VariableNode[]; isAssign: boolean } | undefined {\n if (!isDeclTarget(this.peek())) return undefined;\n // We have to be conservative here — `$x` could be the start of a\n // declaration *or* a plain pipeline whose first command is just a\n // variable reference. Distinguish by scanning ahead for `:=` / `=`\n // (possibly through `, $y` chains).\n let n = 1;\n while (this.peek(n).type === \"Comma\") {\n if (!isDeclTarget(this.peek(n + 1))) return undefined;\n n += 2;\n }\n const opType = this.peek(n).type;\n if (opType !== \"Declare\" && opType !== \"Assign\") return undefined;\n\n const vars: VariableNode[] = [varFromToken(this.next() as Token)];\n while (this.peek().type === \"Comma\") {\n const comma = this.next();\n if (vars.length === (context === \"range\" ? 2 : 1)) {\n throw this.errAt(comma, `too many declarations in ${context}`);\n }\n vars.push(varFromToken(this.expect(\"Variable\", \"$variable\")));\n }\n const op = this.next();\n return { vars, isAssign: op.type === \"Assign\" };\n }\n\n // -------------------------------------------------------------------\n // Commands and primaries.\n //\n // command := primary+\n // primary := dot | field | variable | identifier | string | number\n // | char | bool | nil | `(` pipeline `)` (`.field`)*\n // -------------------------------------------------------------------\n\n private parseCommand(): CommandNode {\n const startPos = this.peek().pos;\n const args: Node[] = [this.parsePrimary()];\n while (canStartPrimary(this.peek().type)) {\n args.push(this.parsePrimary());\n }\n return { type: \"Command\", pos: startPos, args };\n }\n\n private parsePrimary(): Node {\n const t = this.next();\n switch (t.type) {\n case \"Dot\":\n return { type: \"Dot\", pos: t.pos } satisfies DotNode;\n case \"Field\":\n return {\n type: \"Field\",\n pos: t.pos,\n idents: t.value.slice(1).split(\".\"),\n } satisfies FieldNode;\n case \"Variable\":\n return varFromToken(t);\n case \"Identifier\":\n return { type: \"Identifier\", pos: t.pos, ident: t.value } satisfies IdentifierNode;\n case \"String\":\n return {\n type: \"String\",\n pos: t.pos,\n raw: t.value,\n value: decodeStringLiteral(t.value, t.pos, this.source),\n } satisfies StringNode;\n case \"Number\":\n return numberFromToken(t);\n case \"Char\":\n // Treat runes as numbers — Go's parser does the same; the rune\n // value is the integer code point. We synthesize a NumberNode\n // with the original char-literal text preserved.\n return runeNumberFromToken(t, this.source);\n case \"Bool\":\n return { type: \"Bool\", pos: t.pos, value: t.value === \"true\" } satisfies BoolNode;\n case \"Nil\":\n return { type: \"Nil\", pos: t.pos } satisfies NilNode;\n case \"LeftParen\":\n return this.parseChainOrPipe(t.pos);\n default:\n throw this.errAt(t, `expected command argument, found ${tokenLabel(t)}`, {\n expected: \"command argument\",\n found: tokenLabel(t),\n });\n }\n }\n\n private parseChainOrPipe(startPos: Pos): Node {\n const inner = this.parsePipeline(\"parenthesized pipeline\");\n const rparen = this.expect(\"RightParen\", \"`)`\");\n // Field chain on `(pipe).field` requires the `.` to be immediately\n // adjacent to `)` — otherwise it's a separate command argument.\n // The lexer's Field tokens carry source positions; if there was\n // whitespace between `)` and the next Field, their positions\n // won't be consecutive.\n const fields: string[] = [];\n const expectedNextOffset = rparen.pos.offset + 1;\n const t = this.peek();\n if (t.type === \"Field\" && t.pos.offset === expectedNextOffset) {\n this.next();\n fields.push(...t.value.slice(1).split(\".\"));\n }\n if (fields.length === 0) return inner;\n return { type: \"Chain\", pos: startPos, node: inner, fields } satisfies ChainNode;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers — pure data-in / data-out, no parser state.\n// ---------------------------------------------------------------------------\n\nfunction finishList(pos: Pos, nodes: Node[]): ListNode {\n return { type: \"List\", pos, nodes };\n}\n\nfunction trimFromToken(t: Token): TrimMarkers {\n return {\n trimLeft: t.trimLeft === true,\n trimRight: t.trimRight === true,\n };\n}\n\nfunction tokenLabel(t: Token): string {\n if (t.type === \"EOF\") return \"end of input\";\n return t.value || t.type;\n}\n\nfunction canStartPrimary(t: TokenType): boolean {\n switch (t) {\n case \"Dot\":\n case \"Field\":\n case \"Variable\":\n case \"Identifier\":\n case \"String\":\n case \"Number\":\n case \"Char\":\n case \"Bool\":\n case \"Nil\":\n case \"LeftParen\":\n return true;\n default:\n return false;\n }\n}\n\n// A declaration names a bare variable: Go lexes `$x.y` as `$x` and a\n// field, so `$x.y := v` is no declaration and fails as a pipeline.\nfunction isDeclTarget(t: Token): boolean {\n return t.type === \"Variable\" && !t.value.includes(\".\");\n}\n\nfunction varFromToken(t: Token): VariableNode {\n return {\n type: \"Variable\",\n pos: t.pos,\n idents: splitVariableIdents(t.value),\n };\n}\n\nfunction splitVariableIdents(value: string): string[] {\n // `$name.x.y` → [\"$name\", \"x\", \"y\"]; `$` → [\"$\"]\n const dotIdx = value.indexOf(\".\");\n if (dotIdx === -1) return [value];\n return [value.slice(0, dotIdx), ...value.slice(dotIdx + 1).split(\".\")];\n}\n\nfunction numberFromToken(t: Token): NumberNode {\n const text = t.value;\n // Strip underscore separators per Go syntax.\n const cleaned = text.replace(/_/g, \"\");\n const lower = cleaned.toLowerCase();\n const isComplex = lower.endsWith(\"i\");\n const body = isComplex ? cleaned.slice(0, -1) : cleaned;\n const isFloat =\n !isComplex &&\n (body.includes(\".\") ||\n (!body.startsWith(\"0x\") && !body.startsWith(\"0X\") && /[eE]/.test(body)) ||\n ((body.startsWith(\"0x\") || body.startsWith(\"0X\")) && /[pP]/.test(body)));\n const isInt = !isComplex && !isFloat;\n\n const base: NumberNode = {\n type: \"Number\",\n pos: t.pos,\n text,\n isInt,\n isUint: false,\n isFloat,\n isComplex,\n };\n\n if (isInt) {\n const intValue = parseIntegerLiteral(body);\n return { ...base, intValue };\n }\n if (isFloat) {\n const floatValue = parseFloatLiteral(body);\n return { ...base, floatValue };\n }\n // complex\n const im = parseFloatLiteral(body);\n return { ...base, complexValue: [0, im] };\n}\n\nfunction runeNumberFromToken(t: Token, source: string): NumberNode {\n const inner = decodeRuneLiteral(t.value, t.pos, source);\n return {\n type: \"Number\",\n pos: t.pos,\n text: t.value,\n isInt: true,\n isUint: false,\n isFloat: false,\n isComplex: false,\n intValue: BigInt(inner),\n };\n}\n\nfunction parseIntegerLiteral(text: string): bigint {\n // Handle leading sign explicitly because BigInt() accepts \"+123\" but\n // not all base-prefixed signed forms uniformly.\n let sign = 1n;\n let body = text;\n if (body.startsWith(\"+\")) body = body.slice(1);\n else if (body.startsWith(\"-\")) {\n sign = -1n;\n body = body.slice(1);\n }\n return sign * BigInt(body);\n}\n\nfunction parseFloatLiteral(text: string): number {\n return Number(text);\n}\n\nfunction decodeStringLiteral(raw: string, pos: Pos, source: string): string {\n if (raw.startsWith(\"`\")) {\n return raw.slice(1, -1);\n }\n // Interpreted string: process escapes.\n let out = \"\";\n for (let i = 1; i < raw.length - 1; i++) {\n const c = raw[i];\n if (c !== \"\\\\\") {\n out += c;\n continue;\n }\n const next = raw[++i];\n switch (next) {\n case \"n\":\n out += \"\\n\";\n break;\n case \"t\":\n out += \"\\t\";\n break;\n case \"r\":\n out += \"\\r\";\n break;\n case \"\\\\\":\n out += \"\\\\\";\n break;\n case '\"':\n out += '\"';\n break;\n case \"'\":\n out += \"'\";\n break;\n case \"a\":\n out += \"\\x07\";\n break;\n case \"b\":\n out += \"\\b\";\n break;\n case \"f\":\n out += \"\\f\";\n break;\n case \"v\":\n out += \"\\v\";\n break;\n case \"0\":\n case \"1\":\n case \"2\":\n case \"3\":\n case \"4\":\n case \"5\":\n case \"6\":\n case \"7\": {\n // Octal — 3 digits total including the `next`.\n const digits = next + (raw[i + 1] ?? \"\") + (raw[i + 2] ?? \"\");\n i += 2;\n out += String.fromCodePoint(Number.parseInt(digits, 8));\n break;\n }\n case \"x\": {\n const digits = (raw[i + 1] ?? \"\") + (raw[i + 2] ?? \"\");\n i += 2;\n out += String.fromCodePoint(Number.parseInt(digits, 16));\n break;\n }\n case \"u\": {\n const digits = raw.slice(i + 1, i + 5);\n i += 4;\n out += String.fromCodePoint(Number.parseInt(digits, 16));\n break;\n }\n case \"U\": {\n const digits = raw.slice(i + 1, i + 9);\n i += 8;\n out += String.fromCodePoint(Number.parseInt(digits, 16));\n break;\n }\n default:\n throw new ParseError(`bad escape sequence \\\\${next}`, pos, {\n expected: \"valid escape sequence\",\n found: `\\\\${next}`,\n source,\n });\n }\n }\n return out;\n}\n\nfunction decodeRuneLiteral(raw: string, pos: Pos, source: string): number {\n // raw is `'x'` — slice the inner content and reuse the string decoder\n // by wrapping in double quotes (after escaping a literal `\"`).\n const inner = raw.slice(1, -1);\n const escaped = inner.replace(/\"/g, '\\\\\"');\n const decoded = decodeStringLiteral(`\"${escaped}\"`, pos, source);\n if (decoded.length === 0) {\n throw new ParseError(\"empty rune literal\", pos, { source });\n }\n return decoded.codePointAt(0) ?? 0;\n}\n","/**\n * AST traversal helpers.\n *\n * [LAW:dataflow-not-control-flow] `children()` is one exhaustive switch on\n * the node's `type` discriminator that always returns a (possibly empty)\n * array of children. Walkers do not skip operations — they always call\n * `visit(n)` on every reachable node, then recurse into whatever children\n * the data-driven `children()` exposes.\n *\n * [LAW:single-enforcer] All AST traversal goes through `walk` /\n * `children`. Any caller who reinvents traversal will diverge — fix the\n * helper, not the callsite.\n */\n\nimport { assertNever, type Node, type NodeType } from \"./ast.js\";\n\n/**\n * Visitor callback. Receives every node in preorder. Return `false` to\n * stop descending into the current node's children; any other return\n * value (including `undefined`) means \"continue\".\n */\n// biome-ignore lint/suspicious/noConfusingVoidType: void return is idiomatic for callback APIs where the caller may simply not return anything; switching to `undefined` would force every caller to write `return undefined` for no semantic gain.\nexport type Visitor = (node: Node) => boolean | void;\n\n/**\n * Walk an AST in preorder. The visitor sees a node before its children.\n */\nexport function walk(node: Node, visit: Visitor): void {\n const descend = visit(node);\n if (descend === false) return;\n for (const child of children(node)) {\n walk(child, visit);\n }\n}\n\n/**\n * The direct children of a node, in source order. Empty for leaves.\n *\n * Returning a fresh array each call keeps the contract simple — callers\n * may iterate or splat without aliasing surprises. The cost is trivial\n * for AST traversal.\n */\nexport function children(node: Node): readonly Node[] {\n switch (node.type) {\n case \"Text\":\n case \"Comment\":\n case \"Dot\":\n case \"Nil\":\n case \"Bool\":\n case \"Number\":\n case \"String\":\n case \"Identifier\":\n case \"Field\":\n case \"Variable\":\n case \"Break\":\n case \"Continue\":\n return [];\n case \"List\":\n return node.nodes;\n case \"Chain\":\n return [node.node];\n case \"Command\":\n return node.args;\n case \"Pipe\":\n return [...node.decls, ...node.cmds];\n case \"Action\":\n return [node.pipe];\n case \"If\":\n case \"Range\":\n case \"With\":\n return node.elseList ? [node.pipe, node.list, node.elseList] : [node.pipe, node.list];\n case \"Template\":\n return node.pipe ? [node.pipe] : [];\n case \"Block\":\n return [node.pipe, node.list];\n default:\n return assertNever(node);\n }\n}\n\n/**\n * Collect every node in preorder. Convenience for tests + tooling.\n */\nexport function flatten(node: Node): readonly Node[] {\n const out: Node[] = [];\n walk(node, (n) => {\n out.push(n);\n });\n return out;\n}\n\n/**\n * Count nodes of each kind. Useful for tests and diagnostics.\n */\nexport function tally(node: Node): Readonly<Record<NodeType, number>> {\n const counts = emptyTally();\n walk(node, (n) => {\n counts[n.type] += 1;\n });\n return counts;\n}\n\nfunction emptyTally(): Record<NodeType, number> {\n return {\n Text: 0,\n Comment: 0,\n Dot: 0,\n Nil: 0,\n Bool: 0,\n Number: 0,\n String: 0,\n Identifier: 0,\n Field: 0,\n Variable: 0,\n List: 0,\n Chain: 0,\n Command: 0,\n Pipe: 0,\n Action: 0,\n If: 0,\n Range: 0,\n With: 0,\n Break: 0,\n Continue: 0,\n Template: 0,\n Block: 0,\n };\n}\n","/**\n * Field / index access for evaluator primaries.\n *\n * Mirrors Go's `text/template` semantics where applicable:\n * - Plain JS objects: own + prototype-chain properties.\n * - Maps: `.get(key)`.\n * - Arrays: numeric `[i]` (string-indexed access not supported — that's\n * Go's behavior for slices/arrays).\n * - Methods/functions are returned as-is for the caller to invoke when\n * the AST shape demands a function call.\n *\n * Missing-key handling: a genuinely absent field returns the `MISSING`\n * sentinel, which the caller (`Engine.resolveFieldChain`) interprets per\n * the configured `missingKey` policy — `\"default\"`/`\"zero\"` produce\n * `undefined` (Go-default `<no value>` when emitted), `\"error\"` throws\n * `MissingFieldError`. The receiver-is-nullish case at the top of\n * `getField` is the trust-boundary exception documented inline below.\n *\n * [LAW:single-enforcer] This module returns the `MISSING` discriminator\n * unconditionally; the policy decision lives at exactly one site.\n */\n\n/** Sentinel returned by `getField` when a field is genuinely absent. */\nexport const MISSING: unique symbol = Symbol(\"go-template-js.MISSING\");\nexport type Missing = typeof MISSING;\n\nexport function getField(value: unknown, name: string): unknown | Missing {\n // [LAW:no-defensive-null-guards] exception: trust boundary — the\n // receiver is consumer-supplied scope data, so a nullish value is\n // valid input that must collapse to the same MISSING signal an absent\n // field produces. The `else` branch is the real work; this is not a\n // skip-the-operation guard.\n if (value === null || value === undefined) return MISSING;\n if (value instanceof Map) {\n return value.has(name) ? value.get(name) : MISSING;\n }\n if (Array.isArray(value)) {\n // Per Go, accessing a named field on a slice is a missing-field\n // error — no `length` magic. The numeric `index` builtin handles\n // positional access in a separate ticket.\n return MISSING;\n }\n if (typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n if (name in obj) return obj[name];\n return MISSING;\n }\n return MISSING;\n}\n\n/**\n * Walk a chain of field names left-to-right. Returns `MISSING` as soon\n * as any link is missing. The caller decides how to surface the error\n * (typically via EvalError pointing at the AST node's position).\n */\nexport function walkFieldChain(value: unknown, idents: readonly string[]): unknown | Missing {\n let cur: unknown = value;\n for (const id of idents) {\n if (cur === MISSING) return MISSING;\n cur = getField(cur, id);\n }\n return cur;\n}\n","/**\n * `deepEqual a b` — recursive structural equality.\n *\n * Mirrors Go sprig's intent. Implementation handles primitives,\n * arrays, plain objects, Maps, and Sets. NaN is treated as equal to\n * itself (matches `Object.is`).\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (a === null || b === null || a === undefined || b === undefined) return false;\n if (typeof a !== typeof b) return false;\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((v, i) => deepEqual(v, b[i]));\n }\n if (a instanceof Map && b instanceof Map) {\n if (a.size !== b.size) return false;\n for (const [k, v] of a) if (!b.has(k) || !deepEqual(v, b.get(k))) return false;\n return true;\n }\n if (a instanceof Set && b instanceof Set) {\n if (a.size !== b.size) return false;\n for (const v of a) if (!b.has(v)) return false;\n return true;\n }\n if (typeof a === \"object\" && typeof b === \"object\") {\n const ak = Object.keys(a as object);\n const bk = Object.keys(b as object);\n if (ak.length !== bk.length) return false;\n return ak.every((k) =>\n deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n );\n }\n return false;\n}\n","/**\n * Internal lazy-func registry.\n *\n * `and` / `or` short-circuit by receiving thunks instead of values. The\n * dispatcher needs to know which funcs want thunks, but the public\n * `TemplateFunc` interface must not advertise (or admit) a way for\n * consumer code to opt in — only the builtins module does that.\n *\n * [LAW:single-enforcer] One side-channel — a module-private WeakSet —\n * holds the set of lazy funcs. `markLazy` is the only writer (called by\n * `defaultBuiltins`); `isLazy` is the only reader (called by the\n * dispatcher). The brand never appears on the func object, so it\n * cannot leak into the published `.d.ts` and it is not reachable via\n * any public symbol or string key.\n *\n * Lives in its own leaf module so both `evaluator.ts` and `builtins.ts`\n * can import it without forming a runtime import cycle.\n */\n\nimport type { TemplateFunc } from \"./evaluator.js\";\n\nconst LAZY_FUNCS = new WeakSet<TemplateFunc>();\n\n/** Mark a func as wanting thunks. Internal — only `defaultBuiltins` calls this. */\nexport function markLazy<F extends TemplateFunc>(fn: F): F {\n LAZY_FUNCS.add(fn);\n return fn;\n}\n\n/** True iff the func was registered via `markLazy`. */\nexport function isLazy(fn: TemplateFunc): boolean {\n return LAZY_FUNCS.has(fn);\n}\n","/**\n * `include` — Helm's function for rendering a `{{ define }}` by name and\n * returning its text, so a sub-template's output can be piped, tested,\n * defaulted or bound like any other value. `{{ template }}` renders the same\n * define but writes straight to the output, where none of that can reach it.\n *\n * Opt-in: Go's `text/template` has no `include`, so it is not a builtin.\n * Register it like a sprig group — `funcs: { ...sprigStrings(), include }` —\n * under any name.\n *\n * [LAW:single-enforcer] Rendering a define needs the evaluator's context,\n * which no `TemplateFunc` body receives. The evaluator recognizes `include`\n * by its module-private `fn` and runs the render in its place. A consumer\n * cannot forge that function, and it follows the registration through any\n * name and any copy (`{ ...include }`).\n *\n * Leaf module so `evaluator.ts` and `index.ts` import it without a cycle.\n */\n\nimport type { TemplateFunc } from \"./evaluator.js\";\n\n// Never called: the evaluator dispatches on this reference to its own\n// render. Reaching this body means that dispatch was bypassed.\nconst render = (): never => {\n throw new Error(\"include was called outside the evaluator's dispatch\");\n};\n\n/** Helm's `include(name string, data interface{}) (string, error)`. */\nexport const include: TemplateFunc = {\n fn: render,\n argTypes: [\"string\", \"value\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n};\n\nconst renderFragments = (): never => {\n throw new Error(\"includeFragments was called outside the evaluator's dispatch\");\n};\n\n/** Capture a define for replay as its original output fragments. */\nexport const includeFragments: TemplateFunc = {\n ...include,\n fn: renderFragments,\n returnType: \"value\",\n};\n\nexport function includeKind(fn: TemplateFunc): \"text\" | \"fragments\" | undefined {\n if (fn.fn === render) return \"text\";\n if (fn.fn === renderFragments) return \"fragments\";\n return undefined;\n}\n\n// [LAW:single-enforcer] A host may load two copies of this package. Both\n// must recognize a capture before asking their own fragment predicate.\nconst captureText = Symbol.for(\"@promptctl/go-template-js/captureText\");\n\nexport function isCapturedText(value: unknown): value is CapturedText {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype !== null && Object.hasOwn(prototype, captureText);\n}\n\n/** A capture's visible label is its Stringer view and determines its truth. */\nexport class CapturedText {\n readonly #text: string;\n\n constructor(text: string) {\n this.#text = text;\n }\n\n get [captureText](): string {\n return this.#text;\n }\n\n toString(): string {\n return this[captureText];\n }\n}\n","/**\n * Go-template truthiness, used by `if`, `with`, and `range`-empty.\n *\n * Per https://pkg.go.dev/text/template#hdr-Actions, \"the empty values\n * are false, 0, any nil pointer or interface value, and any array,\n * slice, map, or string of length zero.\" Strings of length zero are\n * also empty.\n */\n\nimport { isCapturedText } from \"./include.js\";\n\nexport function isTruthy(value: unknown): boolean {\n if (value === null || value === undefined) return false;\n if (value === false) return false;\n if (typeof value === \"number\") return value !== 0 && !Number.isNaN(value);\n if (typeof value === \"bigint\") return value !== 0n;\n if (typeof value === \"string\") return value.length > 0;\n if (isCapturedText(value)) return value.toString().length > 0;\n if (Array.isArray(value)) return value.length > 0;\n if (value instanceof Map) return value.size > 0;\n if (value instanceof Set) return value.size > 0;\n // Plain object — empty iff it has no own enumerable string keys.\n if (typeof value === \"object\") {\n return Object.keys(value).length > 0;\n }\n return Boolean(value);\n}\n","/**\n * Go template's built-in functions.\n *\n * https://pkg.go.dev/text/template#hdr-Functions\n *\n * Categories:\n * - Eager (most): args evaluated normally, value-in / value-out.\n * - Lazy (and/or): take thunks instead of values so evaluation can\n * short-circuit. Registered via `markLazy` — see lazy.ts.\n *\n * [LAW:single-enforcer] Built-ins live in *one* exported FuncMap.\n * Consumers merge with their own funcs; user-supplied entries with\n * matching names override the built-in (intentional — gives\n * consumers an escape hatch).\n */\n\nimport { isStackOverflow, TypeMismatchError } from \"../errors.js\";\nimport { deepEqual } from \"../sprig/types/deepEqual.js\";\nimport type { FuncMap } from \"./evaluator.js\";\nimport { markLazy } from \"./lazy.js\";\nimport { isTruthy } from \"./truthy.js\";\n\n// ---------------------------------------------------------------------------\n// Eager built-ins.\n//\n// [LAW:single-enforcer] The print/printf family flattens through\n// `formatV` over the engine's `toString`/`isT` — the same function the\n// gate's \"stringifiable\" probe runs (`printRefusal` in src/evaluator/evaluator.ts).\n// Two callsites (probe at the gate, flatten in the body) — one source of truth.\n// ---------------------------------------------------------------------------\n\nfunction eagerBuiltins(toString: (v: unknown) => string, isT: IsT): FuncMap {\n return {\n // Comparison — Go template promotes numeric types and compares\n // strings/bools by value. We match that by leaning on JS `<`/`===`\n // which already does the right thing for primitives.\n // [LAW:single-enforcer] `argTypes: [\"comparable\"]` puts the kind\n // check + cross-slot same-kind rule (with number↔bigint bridged and\n // nil-wildcarded) at the gate. The body trusts kinds and routes\n // structural compares through `deepEqual`. Variadic per Go: `eq a\n // b c` is true if any of b, c equals a.\n eq: {\n fn: (a: unknown, ...rest: unknown[]) => rest.some((r) => goEqPair(a, r)),\n // Go: `eq(arg1 reflect.Value, arg2 ...reflect.Value)` — two\n // parameters, so Go's gate requires one. Go's own body separately\n // rejects a lone argument with `errNoComparison`; this body does\n // neither yet and returns false (template-conformance-3ds).\n argTypes: [\"comparable\", \"comparable\"],\n arity: { kind: \"variadic\" },\n },\n ne: {\n fn: (a: unknown, b: unknown) => !goEqPair(a, b),\n argTypes: [\"comparable\", \"comparable\"],\n arity: { kind: \"exact\" },\n },\n // [LAW:single-enforcer] `argTypes: [\"ordered\", \"ordered\"]` routes\n // both per-slot kind validation and the cross-slot same-kind rule\n // through `enforceArgTypes`. By the time `compare` runs, the args\n // are guaranteed orderable and same-kinded, so it can be a thin\n // numeric/lexicographic body — no defensive cross-type check.\n lt: {\n fn: (a: unknown, b: unknown) => compare(a, b) < 0,\n argTypes: [\"ordered\", \"ordered\"],\n arity: { kind: \"exact\" },\n },\n le: {\n fn: (a: unknown, b: unknown) => compare(a, b) <= 0,\n argTypes: [\"ordered\", \"ordered\"],\n arity: { kind: \"exact\" },\n },\n gt: {\n fn: (a: unknown, b: unknown) => compare(a, b) > 0,\n argTypes: [\"ordered\", \"ordered\"],\n arity: { kind: \"exact\" },\n },\n ge: {\n fn: (a: unknown, b: unknown) => compare(a, b) >= 0,\n argTypes: [\"ordered\", \"ordered\"],\n arity: { kind: \"exact\" },\n },\n\n // [LAW:single-enforcer] `len` declares \"sized\" so the gate rejects\n // numbers/booleans/nil once with TypeMismatchError. The body trusts\n // the kind and only fans out the per-kind size readout.\n len: { fn: (v: unknown) => goLen(v), argTypes: [\"sized\"], arity: { kind: \"exact\" } },\n\n // [LAW:single-enforcer] `index x i j` walks i, then j. The first\n // slot is \"collection\" (string | array | Map | dict); every key\n // slot is \"index-key\" (string | number | bigint). The body trusts\n // the gate — nil/Set/class-instance receivers are rejected before\n // it runs. Closes audit finding B5: typed-T keys no longer\n // silently `String(key)`-flatten on object collections.\n index: {\n fn: (collection: unknown, ...keys: unknown[]) => {\n let cur: unknown = collection;\n for (const k of keys) cur = goIndex(cur, k);\n return cur;\n },\n argTypes: [\"collection\", \"index-key\"],\n arity: { kind: \"variadic\" },\n },\n\n // [LAW:single-enforcer] `slice x i j` — array/slice/string slicing.\n // First slot declares \"sliceable\" (string|array) so the gate\n // rejects non-sliceable receivers once; index slots declare \"int\"\n // (Go refuses a non-integer index) so the gate normalizes\n // `number|bigint` to an integer `number` carrier before the body\n // runs; the body checks the bounds Go checks (`goSlice`).\n slice: {\n fn: (collection: string | readonly unknown[], ...indices: number[]) =>\n goSlice(collection, indices),\n argTypes: [\"sliceable\", \"int\"],\n arity: { kind: \"variadic\" },\n },\n\n // [LAW:single-enforcer] Formatted printers declare \"stringifiable\"\n // so the gate probes each non-string arg through `formatV`, the\n // flatten the bodies perform — a T through `engine.toString`, any\n // other value as Go's `%v`. Closes audit findings B1–B4: nothing\n // silently `String(v)`-flattens to \"[object Object]\".\n print: {\n fn: (...args: unknown[]) => goPrint(args, toString, isT),\n argTypes: [\"stringifiable\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n println: {\n fn: (...args: unknown[]) => `${goPrintln(args, toString, isT)}\\n`,\n argTypes: [\"stringifiable\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n printf: {\n fn: (format: string, ...args: unknown[]) => sprintf(format, args, toString, isT),\n argTypes: [\"string\", \"stringifiable\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n // Sprig's `toString`/`toStrings` are Go's `%v` — built here, beside\n // `printf`, because that is where the engine's `toString`/`isT` are.\n // `as const`: a property key named `toString` shadows\n // `Object.prototype.toString` in TS's contextual typing of the literal.\n toString: {\n fn: (v: unknown) => formatV(v, toString, isT),\n argTypes: [\"value\"] as const,\n arity: { kind: \"exact\" } as const,\n returnType: \"string\" as const,\n },\n toStrings: {\n fn: (list: unknown[]) => list.map((v) => formatV(v, toString, isT)),\n argTypes: [\"list\"],\n arity: { kind: \"exact\" },\n },\n\n // [LAW:single-enforcer] `call` declares \"callable\" for the first\n // slot — the gate rejects non-functions once with TypeMismatchError;\n // the body trusts the kind. Trailing slot is \"value\": pass-through\n // arguments to the callable, intent-documented as heterogeneous.\n call: {\n fn: (fn: unknown, ...args: unknown[]) => (fn as (...a: unknown[]) => unknown)(...args),\n argTypes: [\"callable\", \"value\"],\n arity: { kind: \"variadic\" },\n // The function comes from the data and has no registration to say\n // whether it writes, so `call` says it for every function it runs.\n writes: true,\n },\n\n // [LAW:single-enforcer + LAW:one-source-of-truth] `html` mirrors Go's\n // `text/template.HTMLEscaper`: flatten args via the print pipeline,\n // then escape the six HTML-significant characters. Sharing the\n // `\"stringifiable\"` gate + `goPrint` body with print/printf keeps\n // the no-silent-flatten contract uniform across every builtin that\n // produces a string from heterogeneous arg values.\n html: {\n fn: (...args: unknown[]) => htmlEscape(goPrint(args, toString, isT)),\n argTypes: [\"stringifiable\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n\n // [LAW:single-enforcer + LAW:one-source-of-truth] `js` mirrors Go's\n // `text/template.JSEscaper`: same flatten-then-escape shape as `html`,\n // differing only in the escape table. The shared `\"stringifiable\"`\n // gate keeps the no-silent-flatten contract uniform.\n js: {\n fn: (...args: unknown[]) => jsEscape(goPrint(args, toString, isT)),\n argTypes: [\"stringifiable\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n\n // [LAW:single-enforcer + LAW:one-source-of-truth] `urlquery` mirrors\n // Go's `text/template.URLQueryEscaper`: flatten via fmt.Sprint, then\n // `url.QueryEscape`. Same shape as html/js — only the escape function\n // differs. Built on the UTF-8 byte stream (not the JS code-unit\n // stream) so multi-byte runes percent-encode to the same bytes Go\n // emits.\n urlquery: {\n fn: (...args: unknown[]) => urlQueryEscape(goPrint(args, toString, isT)),\n argTypes: [\"stringifiable\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n\n // `not` is also lazy in spirit, but with a single argument it's\n // semantically equivalent to eager evaluation. Keep it eager.\n // Slot declares \"truthy\": isTruthy() runs against any value.\n not: { fn: (v: unknown) => !isTruthy(v), argTypes: [\"truthy\"], arity: { kind: \"exact\" } },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Lazy short-circuiting forms.\n//\n// `and a b c …` returns the first falsy argument, or the last argument\n// if all are truthy. `or` is the dual. Registered via `markLazy` so the\n// dispatcher hands them thunks instead of values; their declared\n// `argTypes: [\"truthy\"]` makes the gate a no-op against thunks (the\n// matcher is permissive-by-intent) while documenting that each arg is\n// consulted for truthiness.\n// ---------------------------------------------------------------------------\n\nfunction lazyBuiltins(): FuncMap {\n return {\n and: markLazy({\n argTypes: [\"truthy\", \"truthy\"],\n arity: { kind: \"variadic\" },\n fn: (...thunks: unknown[]) => {\n let last: unknown = true;\n for (const t of thunks) {\n last = (t as () => unknown)();\n if (!isTruthy(last)) return last;\n }\n return last;\n },\n }),\n or: markLazy({\n argTypes: [\"truthy\", \"truthy\"],\n arity: { kind: \"variadic\" },\n fn: (...thunks: unknown[]) => {\n let last: unknown = false;\n for (const t of thunks) {\n last = (t as () => unknown)();\n if (isTruthy(last)) return last;\n }\n return last;\n },\n }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public default registry.\n// ---------------------------------------------------------------------------\n\nexport function defaultBuiltins(toString: (v: unknown) => string, isT: IsT): FuncMap {\n return { ...eagerBuiltins(toString, isT), ...lazyBuiltins() };\n}\n\n// ---------------------------------------------------------------------------\n// Comparison + length + index helpers (Go-template semantics).\n// ---------------------------------------------------------------------------\n\nfunction goEqPair(a: unknown, b: unknown): boolean {\n // Go-template `eq` semantics: numeric kinds bridge (1 == 1n), and\n // structural values (arrays, plain objects, Maps, Sets) compare by\n // deep equality. The gate already enforces same-kind for the slots,\n // so this only needs to compute equality — never reject.\n if (typeof a === \"number\" && typeof b === \"bigint\") return BigInt(a) === b;\n if (typeof a === \"bigint\" && typeof b === \"number\") return a === BigInt(b);\n return deepEqual(a, b);\n}\n\nfunction compare(a: unknown, b: unknown): number {\n // [LAW:single-enforcer] Same-kind invariant is enforced by\n // `enforceArgTypes` ahead of this call (via `argTypes: [\"ordered\",\n // \"ordered\"]`). Here we only compute the ordering — no cross-type\n // defensive logic needed.\n if (typeof a === \"bigint\" && typeof b === \"bigint\") {\n return a === b ? 0 : a < b ? -1 : 1;\n }\n if (typeof a === \"bigint\" || typeof b === \"bigint\") {\n const an = typeof a === \"bigint\" ? a : BigInt(Math.trunc(Number(a)));\n const bn = typeof b === \"bigint\" ? b : BigInt(Math.trunc(Number(b)));\n return an === bn ? 0 : an < bn ? -1 : 1;\n }\n // a and b are guaranteed same-kind (string/number/boolean) at this\n // point, so the ordering is a direct primitive compare.\n const x = a as string | number | boolean;\n const y = b as string | number | boolean;\n return x === y ? 0 : x < y ? -1 : 1;\n}\n\nfunction goLen(value: unknown): number {\n // [LAW:single-enforcer] Kind already validated by `enforceArgTypes`\n // against argTypes: [\"sized\"]. Body picks the per-kind size readout;\n // no defensive nil / non-sized throws here — the gate caught those.\n if (typeof value === \"string\") return value.length;\n if (Array.isArray(value)) return value.length;\n if (value instanceof Map) return value.size;\n if (value instanceof Set) return value.size;\n return Object.keys(value as Record<string, unknown>).length;\n}\n\nfunction goIndex(collection: unknown, key: unknown): unknown {\n // [LAW:single-enforcer] The gate validates the *initial* collection\n // and key shapes. Mid-walk, `collection` is whatever the previous\n // step returned — so the body keeps a \"cannot index\" defense for\n // intermediate non-collection values (e.g., a leaf number). The nil\n // case is folded into that catch-all.\n if (Array.isArray(collection) || typeof collection === \"string\") {\n const i = indexArg(key, collection.length);\n if (i === collection.length) throw new Error(`index out of range: ${i}`);\n return collection[i];\n }\n if (collection instanceof Map) {\n return collection.get(key);\n }\n if (collection !== null && typeof collection === \"object\") {\n // Closes B5: no silent `String(key)`. Object access requires a\n // string key; numeric/bigint keys for an object collection are a\n // body-level kind error (the gate's per-slot rule can't express\n // \"key kind depends on receiver kind\" without cross-slot logic).\n if (typeof key !== \"string\") {\n throw new Error(`index: object index must be string, got ${describeType(key)}`);\n }\n return (collection as Record<string, unknown>)[key];\n }\n throw new Error(`index: cannot index ${describeType(collection)}`);\n}\n\n// [LAW:one-source-of-truth] Go's `indexArg`: the one rule `index` and\n// `slice` share for a position into a string, slice, or array — an\n// integer in `0..cap`, refused in Go's words otherwise. `cap` itself is\n// admitted because a slice bound may equal the length; `index` refuses\n// it on its own.\nfunction indexArg(key: unknown, cap: number): number {\n const x = typeof key === \"bigint\" ? Number(key) : key;\n if (typeof x !== \"number\" || !Number.isInteger(x)) {\n throw new Error(`cannot index slice/array with type ${goPrintfType(key)}`);\n }\n if (x < 0 || x > cap) throw new Error(`index out of range: ${String(key)}`);\n return x;\n}\n\n// Go's builtin `slice x i j k`: up to three bounds, each checked by\n// `indexArg` and ordered `i <= j <= k`; a string takes at most two.\nfunction goSlice(collection: string | readonly unknown[], indices: readonly number[]): unknown {\n if (indices.length > 3) throw new Error(`too many slice indexes: ${indices.length}`);\n if (typeof collection === \"string\" && indices.length > 2) {\n throw new Error(\"cannot 3-index slice a string\");\n }\n const cap = collection.length;\n const bounds = [0, cap, cap];\n indices.forEach((ix, n) => {\n bounds[n] = indexArg(ix, cap);\n });\n const [i, j, k] = bounds as [number, number, number];\n if (i > j) throw new Error(`invalid slice index: ${i} > ${j}`);\n if (j > k) throw new Error(`invalid slice index: ${j} > ${k}`);\n return collection.slice(i, j);\n}\n\nfunction describeType(v: unknown): string {\n if (v === null) return \"null\";\n if (v === undefined) return \"undefined\";\n if (Array.isArray(v)) return \"array\";\n if (v instanceof Map) return \"Map\";\n return typeof v;\n}\n\n// Go-style type name for `%!<verb>(<type>=<value>)` printf diagnostics.\n// Mirrors what Go's fmt prints for the common scalar types we accept.\nfunction goPrintfType(v: unknown): string {\n if (v === null || v === undefined) return \"<nil>\";\n if (typeof v === \"string\") return \"string\";\n if (typeof v === \"boolean\") return \"bool\";\n if (typeof v === \"bigint\") return \"int64\";\n if (typeof v === \"number\") return Number.isInteger(v) ? \"int\" : \"float64\";\n if (Array.isArray(v)) return \"[]interface {}\";\n if (v instanceof Map || typeof v === \"object\") return \"map[string]interface {}\";\n return typeof v;\n}\n\n// ---------------------------------------------------------------------------\n// Print + sprintf.\n//\n// We support %s, %d, %v, %q, %f, %t, %x — the verbs explicitly listed\n// in the parser-evaluator-cgm epic. Unknown verbs pass through as\n// `%!<verb>(<arg>)` matching Go's diagnostic style.\n// ---------------------------------------------------------------------------\n\nfunction goPrint(args: readonly unknown[], toString: ToString, isT: IsT): string {\n // Go's `fmt.Sprint`: emits a space between adjacent operands when\n // *neither* of the two flanking values is a string. So `x` `1` is\n // joined as `x1` (string adjacent), but `1` `true` is joined as\n // `1 true` (neither is a string).\n let out = \"\";\n let prevIsString = false;\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n const isString = typeof arg === \"string\";\n if (i > 0 && !prevIsString && !isString) out += \" \";\n out += formatV(arg, toString, isT);\n prevIsString = isString;\n }\n return out;\n}\n\n// Go's `fmt.Sprintln`: unlike Sprint, a space between every two operands.\nfunction goPrintln(args: readonly unknown[], toString: ToString, isT: IsT): string {\n return args.map((arg) => formatV(arg, toString, isT)).join(\" \");\n}\n\n// ---------------------------------------------------------------------------\n// HTML escaping.\n//\n// Mirrors Go's `text/template.HTMLEscape` byte-for-byte: NUL becomes the\n// Unicode replacement character, the five HTML-significant characters\n// become their shortest numeric / named entities (Go picks `"` over\n// `"` and `'` over `'` for brevity — match that).\n// ---------------------------------------------------------------------------\n\nconst HTML_ESCAPE_TABLE: Readonly<Record<string, string>> = {\n \"\\0\": \"�\",\n '\"': \""\",\n \"'\": \"'\",\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n};\n\nfunction htmlEscape(s: string): string {\n return s.replace(/[\\0\"'&<>]/g, (c) => HTML_ESCAPE_TABLE[c] ?? c);\n}\n\n// ---------------------------------------------------------------------------\n// JS escaping.\n//\n// Mirrors Go's `text/template.JSEscape` rune-for-rune. The fixed set\n// `\\ ' \" < > & =` map to specific replacements; ASCII control chars\n// (< 0x20) emit `\\u00XX`; non-ASCII (>= 0x80) that aren't `unicode.IsPrint`\n// also emit `\\u%04X`. Everything else passes through. Go's `unicode.IsPrint`\n// for non-ASCII is L/M/N/P/S — anything in C or Z (including U+00A0,\n// U+2028, U+2029, zero-width formats, private use) is non-printable.\n// ---------------------------------------------------------------------------\n\nconst JS_FIXED_ESCAPES: Readonly<Record<string, string>> = {\n \"\\\\\": \"\\\\\\\\\",\n \"'\": \"\\\\'\",\n '\"': '\\\\\"',\n \"<\": \"\\\\u003C\",\n \">\": \"\\\\u003E\",\n \"&\": \"\\\\u0026\",\n \"=\": \"\\\\u003D\",\n};\n\nconst JS_NON_ASCII_PRINTABLE = /^[\\p{L}\\p{M}\\p{N}\\p{P}\\p{S}]$/u;\n\nfunction jsEscape(s: string): string {\n let out = \"\";\n for (const ch of s) {\n const fixed = JS_FIXED_ESCAPES[ch];\n if (fixed !== undefined) {\n out += fixed;\n continue;\n }\n const cp = ch.codePointAt(0) as number;\n if (cp < 0x20 || (cp >= 0x80 && !JS_NON_ASCII_PRINTABLE.test(ch))) {\n out += `\\\\u${cp.toString(16).toUpperCase().padStart(4, \"0\")}`;\n continue;\n }\n out += ch;\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// URL-query escaping.\n//\n// Mirrors Go's `net/url.QueryEscape` (which `text/template.URLQueryEscaper`\n// delegates to) byte-for-byte: the unreserved set [A-Za-z0-9-._~] passes\n// through, space becomes `+`, every other byte becomes `%XX` uppercase hex.\n// Operates on UTF-8 bytes — multi-byte runes encode to the same percent\n// sequences Go emits (e.g. \"α\" → \"%CE%B1\"). Diverges from JS's\n// `encodeURIComponent` which uses `%20` for space and leaves `!*'()` raw.\n// ---------------------------------------------------------------------------\n\nconst URL_QUERY_ENCODER = new TextEncoder();\n\nfunction urlQueryEscape(s: string): string {\n let out = \"\";\n const bytes = URL_QUERY_ENCODER.encode(s);\n for (const b of bytes) {\n const unreserved =\n (b >= 0x30 && b <= 0x39) || // 0-9\n (b >= 0x41 && b <= 0x5a) || // A-Z\n (b >= 0x61 && b <= 0x7a) || // a-z\n b === 0x2d || // -\n b === 0x2e || // .\n b === 0x5f || // _\n b === 0x7e; // ~\n if (unreserved) {\n out += String.fromCharCode(b);\n } else if (b === 0x20) {\n out += \"+\";\n } else {\n out += `%${b.toString(16).toUpperCase().padStart(2, \"0\")}`;\n }\n }\n return out;\n}\n\nfunction sprintf(\n format: string,\n args: readonly unknown[],\n toString: (v: unknown) => string,\n isT: IsT,\n): string {\n let out = \"\";\n let argIdx = 0;\n let i = 0;\n while (i < format.length) {\n const ch = format[i];\n if (ch !== \"%\") {\n out += ch;\n i += 1;\n continue;\n }\n if (format[i + 1] === \"%\") {\n out += \"%\";\n i += 2;\n continue;\n }\n // Read optional flags + width + precision before the verb.\n let j = i + 1;\n while (j < format.length && \"+-# 0\".includes(format[j] ?? \"\")) j += 1;\n while (j < format.length && format[j] !== undefined && /[0-9]/.test(format[j] as string))\n j += 1;\n if (format[j] === \".\") {\n j += 1;\n while (j < format.length && format[j] !== undefined && /[0-9]/.test(format[j] as string))\n j += 1;\n }\n const verb = format[j];\n const spec = format.slice(i + 1, j);\n const missing = argIdx >= args.length;\n const arg = args[argIdx++];\n out += missing ? `%!${verb ?? \"\"}(MISSING)` : formatVerb(verb ?? \"\", spec, arg, toString, isT);\n i = j + 1;\n }\n return out;\n}\n\n// Go's fmt applies a verb to each element of a slice or map, keys\n// included — `%d` of `[1 2]` is `[1 2]`, `%q` of `{k: \"v\"}` is\n// `map[\"k\":\"v\"]` — so the verb formats the leaves of the one `%v` walk.\nfunction formatVerb(\n verb: string,\n spec: string,\n arg: unknown,\n toString: (v: unknown) => string,\n isT: IsT,\n): string {\n // A Uint8Array is Go's []byte, which %s and %q print as text and %x as\n // the bytes' hex; every other verb walks it as a slice.\n if (arg instanceof Uint8Array && (verb === \"s\" || verb === \"q\")) {\n return formatLeafVerb(verb, spec, new TextDecoder().decode(arg), toString, isT);\n }\n if (arg instanceof Uint8Array && verb === \"x\") {\n return applyWidth(spec, Array.from(arg, (b) => b.toString(16).padStart(2, \"0\")).join(\"\"));\n }\n return formatWalk(arg, (leaf) => formatLeafVerb(verb, spec, leaf, toString, isT), toString, isT);\n}\n\nfunction formatLeafVerb(\n verb: string,\n spec: string,\n arg: unknown,\n toString: (v: unknown) => string,\n isT: IsT,\n): string {\n switch (verb) {\n case \"s\":\n return applyWidth(spec, formatLeafV(arg, toString, isT));\n case \"d\": {\n // [LAW:single-enforcer] Non-numeric primitives route to the same\n // diagnostic format as the `default:` arm — no silent NaN.\n if (typeof arg !== \"number\" && typeof arg !== \"bigint\") {\n return badVerb(verb, arg, toString, isT);\n }\n const n = typeof arg === \"bigint\" ? arg : Math.trunc(arg);\n return applyWidth(spec, String(n));\n }\n case \"v\":\n return applyWidth(spec, formatLeafV(arg, toString, isT));\n case \"q\":\n return applyWidth(spec, JSON.stringify(formatLeafV(arg, toString, isT)));\n case \"f\": {\n // [LAW:single-enforcer] See %d.\n if (typeof arg !== \"number\" && typeof arg !== \"bigint\") {\n return badVerb(verb, arg, toString, isT);\n }\n const precision = spec.includes(\".\") ? Number(spec.split(\".\")[1]) : 6;\n const n = Number(arg);\n return applyWidth(spec, n.toFixed(precision));\n }\n case \"t\":\n // [LAW:single-enforcer] Go's %t takes a bool; see %d.\n if (typeof arg !== \"boolean\") {\n return badVerb(verb, arg, toString, isT);\n }\n return applyWidth(spec, String(arg));\n case \"x\": {\n // Go's %x on a string emits the hex of its UTF-8 bytes.\n if (typeof arg === \"string\") {\n const bytes = new TextEncoder().encode(arg);\n let hex = \"\";\n for (const b of bytes) hex += b.toString(16).padStart(2, \"0\");\n return applyWidth(spec, hex);\n }\n // [LAW:single-enforcer] See %d.\n if (typeof arg !== \"number\" && typeof arg !== \"bigint\") {\n return badVerb(verb, arg, toString, isT);\n }\n if (typeof arg === \"bigint\") return applyWidth(spec, arg.toString(16));\n const n = Math.trunc(arg);\n return applyWidth(spec, n.toString(16));\n }\n default:\n return badVerb(verb, arg, toString, isT);\n }\n}\n\n// [LAW:single-enforcer] Go's one diagnostic for a verb its operand does not\n// take: `%!d(string=a)`, and `%!d(<nil>)` for nil.\nfunction badVerb(verb: string, arg: unknown, toString: ToString, isT: IsT): string {\n if (arg === null || arg === undefined) return `%!${verb}(<nil>)`;\n return `%!${verb}(${goPrintfType(arg)}=${formatLeafV(arg, toString, isT)})`;\n}\n\nfunction applyWidth(spec: string, body: string): string {\n // Parse width and the `-` (left-align) flag from the spec — anything\n // before a `.` and not in the flag set is the width.\n const flag = spec.match(/^([+\\-# 0]*)/)?.[1] ?? \"\";\n const widthMatch = spec.slice(flag.length).match(/^(\\d+)/);\n if (!widthMatch) return body;\n const width = Number(widthMatch[1]);\n if (body.length >= width) return body;\n const pad = \" \".repeat(width - body.length);\n return flag.includes(\"-\") ? body + pad : pad + body;\n}\n\n// Is this value a T — opaque, printed by its own String — or not? The\n// engine's one predicate, threaded to every place that prints a value.\nexport type IsT = (value: unknown) => boolean;\n\n// [LAW:one-source-of-truth] The one Go-`%v` formatter: the output stream,\n// printf's `%v` verb, and sprig's `toString`/`toStrings` all print through\n// it, so a bare `{{ .doc }}` and `{{ printf \"%v\" .doc }}` cannot disagree.\n// A T flattens through the engine's `toString`, the same function `%s`\n// and `print` use. Of the non-T values, only the shapes Go walks are\n// walked — an array, a Map, a plain object (printed as Go prints a map:\n// `map[k:v …]`, keys sorted the way fmt orders them).\nexport function formatV(value: unknown, toString: ToString, isT: IsT): string {\n try {\n return formatWalk(value, (leaf) => formatLeafV(leaf, toString, isT), toString, isT);\n } catch (err) {\n // The leaf that refused knows only itself; the walk's root is named\n // here, once, so every reporter describes the refusal the same way.\n if (err instanceof UnprintableError) throw new UnprintableError(err.leaf, err.cause, value);\n throw err;\n }\n}\n\n// [LAW:single-enforcer] The one structural walk every verb shares; the\n// verb decides only how a leaf prints.\nfunction formatWalk(\n value: unknown,\n leaf: (v: unknown) => string,\n toString: ToString,\n isT: IsT,\n): string {\n if (isT(value)) return leaf(value);\n const walk = (v: unknown): string => formatWalk(v, leaf, toString, isT);\n if (Array.isArray(value)) return `[${value.map(walk).join(\" \")}]`;\n if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {\n return `[${Array.from(value as unknown as ArrayLike<unknown>, walk).join(\" \")}]`;\n }\n if (value instanceof Map) return formatEntries([...value.entries()], walk, toString, isT);\n if (isPlainObject(value)) return formatEntries(Object.entries(value), walk, toString, isT);\n // A class instance is Go's struct: `%v` prints its field values in\n // order, `{alice 30}`, unless it is a Stringer.\n if (isStruct(value)) return `{${Object.values(value).map(walk).join(\" \")}}`;\n return leaf(value);\n}\n\nfunction isStruct(value: unknown): value is object {\n return (\n typeof value === \"object\" && value !== null && !(value instanceof Set) && !hasOwnString(value)\n );\n}\n\n// A leaf has a `%v` text form when it is nil, a scalar, a T the engine's\n// `toString` flattens, or an object with its own String — a Date, a\n// RegExp, a class that defines `toString`, Go's Stringer. A Set, a\n// function or a symbol has none: printing it would be the silent\n// \"[object Set]\" flatten, so it is refused, and a `toString` that cannot\n// flatten a T is a refusal too.\nfunction formatLeafV(value: unknown, toString: ToString, isT: IsT): string {\n if (value === null || value === undefined) return \"<nil>\";\n if (typeof value === \"string\") return value;\n if (isT(value)) return flattenT(value, toString);\n if (typeof value === \"number\" || typeof value === \"bigint\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (typeof value === \"object\" && hasOwnString(value)) return stringerText(value);\n throw new UnprintableError(value);\n}\n\nfunction flattenT(value: unknown, toString: ToString): string {\n try {\n return toString(value);\n } catch (err) {\n if (isStackOverflow(err)) throw err;\n throw new UnprintableError(value, err);\n }\n}\n\n// A Stringer whose text form throws is refused as a T is: the same\n// UnprintableError, so every print refusal has one type.\nfunction stringerText(value: object): string {\n try {\n return String(value);\n } catch (err) {\n if (isStackOverflow(err)) throw err;\n throw new UnprintableError(value, err);\n }\n}\n\n// Go's Stringer: a callable `toString` other than the `[object …]`\n// default, which is the one on the root of the prototype chain — read\n// there, not off this realm's `Object.prototype`, so an object from a\n// vm context or an iframe is judged the same.\nfunction hasOwnString(value: object): boolean {\n let root: object = value;\n for (let p = Object.getPrototypeOf(root); p !== null; p = Object.getPrototypeOf(p)) root = p;\n const own = (value as { toString?: unknown }).toString;\n return typeof own === \"function\" && own !== (root as { toString?: unknown }).toString;\n}\n\n/** A value Go's `%v` has no text form for: a Set, a function, a symbol, or\n * a T the engine's `toString` cannot flatten. The action and the call that\n * met it report it at their position. */\nexport class UnprintableError extends Error {\n override readonly name = \"UnprintableError\";\n /** What cannot print, named from the printed value: the leaf alone, or\n * the value holding it. */\n readonly summary: string;\n constructor(\n readonly leaf: unknown,\n cause?: unknown,\n root: unknown = leaf,\n ) {\n const summary =\n root === leaf ? typeNameOf(leaf) : `${typeNameOf(root)} holding ${typeNameOf(leaf)}`;\n // A flattener that names what it expected says why; any other refusal\n // is a value with no text form.\n const why =\n cause instanceof TypeMismatchError ? `expected ${cause.expected}` : \"it has no text form\";\n super(`cannot print a value of type ${summary}: ${why}`, { cause });\n this.summary = summary;\n }\n}\n\n// [LAW:one-source-of-truth] The one name every error gives a value's type. A\n// JS constructor name, not Go's %T: `Rich`, not `*main.Rich`. Not `kindOf`\n// in src/sprig/types/kindOf.ts, the template-visible kind, which answers a\n// different question.\n// the typeof of a primitive, `array` and `object` for the shapes Go walks\n// as slice and map, and otherwise the nearest named constructor — so an\n// anonymous `class extends Set` is still a Set.\nexport function typeNameOf(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n if (typeof value !== \"object\") return typeof value;\n if (isPlainObject(value)) return \"object\";\n for (let p = Object.getPrototypeOf(value); p !== null; p = Object.getPrototypeOf(p)) {\n const name = (p as { constructor?: { name?: unknown } }).constructor?.name;\n // `Object.create({})` is a plain object too: its chain ends in `Object`.\n if (typeof name === \"string\" && name !== \"\") return name === \"Object\" ? \"object\" : name;\n }\n return \"object\";\n}\n\ntype ToString = (value: unknown) => string;\n\n// [LAW:single-enforcer] The one ordering a Map and a plain object print in:\n// numeric keys numerically and first, every other key by its formatted text.\nfunction formatEntries(\n entries: readonly (readonly [unknown, unknown])[],\n walk: (v: unknown) => string,\n toString: ToString,\n isT: IsT,\n): string {\n const isNumeric = (k: unknown): k is number | bigint =>\n typeof k === \"number\" || typeof k === \"bigint\";\n type Keyed = { readonly k: unknown; readonly v: unknown; readonly text: string };\n const byKey = (a: Keyed, b: Keyed): number => {\n if (isNumeric(a.k) && isNumeric(b.k)) return a.k < b.k ? -1 : a.k > b.k ? 1 : 0;\n if (isNumeric(a.k) !== isNumeric(b.k)) return isNumeric(a.k) ? -1 : 1;\n return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;\n };\n return `map[${entries\n .map(([k, v]): Keyed => ({ k, v, text: formatV(k, toString, isT) }))\n .sort(byKey)\n .map(({ k, v }) => `${walk(k)}:${walk(v)}`)\n .join(\" \")}]`;\n}\n\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n if (Array.isArray(value)) return false;\n if (value instanceof Map || value instanceof Set) return false;\n // Reject typed arrays, Dates, RegExps, class instances and other\n // built-ins by requiring a null prototype or one whose own prototype is\n // null — any realm's `Object.prototype`.\n const proto = Object.getPrototypeOf(value);\n return proto === null || Object.getPrototypeOf(proto) === null;\n}\n","/**\n * Evaluation provenance: which marked calls a value depends on.\n *\n * A registered func marks the call it is in by returning\n * `marked(value, ...tokens)`. The engine unwraps the carrier at its one\n * dispatch site and the tokens travel beside the value — through every\n * variable and dot it is bound into, onto every action that reads it —\n * until a hook reports them (`EngineConfig.emitted` / `decided`).\n *\n * [LAW:types-are-the-program] Provenance rides beside values, never on\n * them: a number or a string cannot carry a fact, and a wrapper that\n * reached a template value would change what every slot matcher sees.\n * So the carrier exists only between a func body's return and `invoke`;\n * nothing downstream of `invoke` can be handed one.\n */\n\n/** The set of marks a value or an emission depends on. */\nexport type Marks = ReadonlySet<unknown>;\n\nexport const NO_MARKS: Marks = new Set();\n\n// Declared before the class: its static block assigns them as the class\n// is defined, and a `let` read or written before its line is in the TDZ.\nlet createMarked: (value: unknown, marks: readonly unknown[]) => Marked;\nlet openMarked: (result: unknown) => {\n readonly value: unknown;\n readonly marks: readonly unknown[];\n};\n\n// [LAW:single-enforcer] The one reader of a carrier, called only by the\n// engine's dispatch site: the marks join the reading pipe's set and the\n// plain value continues as the call's result.\nexport let readCarrier: (result: unknown, into: Set<unknown>) => unknown;\n\n/**\n * A func's return value together with the marks of the call that\n * produced it. Opaque: build one with {@link marked}; only the engine\n * reads it.\n */\nexport class Marked {\n readonly #value: unknown;\n readonly #marks: readonly unknown[];\n\n private constructor(value: unknown, marks: readonly unknown[]) {\n this.#value = value;\n this.#marks = marks;\n }\n\n static {\n createMarked = (value, marks) =>\n // `marked(marked(v, a), b)` is one carrier with both marks, so a\n // func that wraps another func's result never hides the inner mark.\n value instanceof Marked\n ? new Marked(value.#value, [...value.#marks, ...marks])\n : new Marked(value, marks);\n openMarked = (result) =>\n result instanceof Marked\n ? { value: result.#value, marks: result.#marks }\n : { value: result, marks: [] };\n readCarrier = (result, into) => {\n if (!(result instanceof Marked)) return result;\n for (const mark of result.#marks) into.add(mark);\n return result.#value;\n };\n }\n}\n\n/**\n * Return this from a registered func to mark the call: every emission\n * and control decision that depends on the call's result reports\n * `marks`. The template sees `value`, exactly as if it had been returned\n * directly.\n */\nexport function marked(value: unknown, ...marks: unknown[]): Marked {\n return createMarked(value, marks);\n}\n\n/**\n * A func's return read apart: its value and the marks it carries (none\n * for a plain value). For JS code that builds on a marking func outside a\n * template — `const { value, marks } = unmarked(tween.fn(...))`, then\n * `return marked(Math.min(1, value as number), ...marks)`.\n */\nexport function unmarked(result: unknown): {\n readonly value: unknown;\n readonly marks: readonly unknown[];\n} {\n return openMarked(result);\n}\n\n/** `a ∪ b`, sharing an operand when the other is empty. */\nexport function unionMarks(a: Marks, b: Marks): Marks {\n if (b.size === 0) return a;\n if (a.size === 0) return b;\n return new Set([...a, ...b]);\n}\n","/**\n * Lexical scope chain for the evaluator.\n *\n * [LAW:dataflow-not-control-flow] A `Scope` is a `dot`, a parent\n * pointer and the variables declared in it. Entering a construct or an\n * iteration *constructs* a frame and leaving it drops the frame, so\n * nothing is ever undone: iterations of `{{range}}` cannot see each\n * other's `:=` declarations — the data shape itself prevents the bug.\n *\n * Only a frame's variables change. A lookup walks the parent chain.\n * Assignment via `=` searches the chain and overwrites the binding in\n * the frame that declared it; declaration via `:=` always creates the\n * binding in the current leaf frame.\n *\n * `$` is an ordinary variable declared in a chain's root frame, as in\n * Go, where it is `vars[0]`: so `$ = v` assigns it, and a `template` /\n * `block` invocation starts a fresh chain whose only variable is `$`.\n */\n\nimport { type Marks, unionMarks } from \"./marks.js\";\n\n/**\n * A bound value and the marks it depends on.\n *\n * [LAW:types-are-the-program] One record, so no binding can be made\n * without saying what it depends on: a variable or a dot that forgot\n * its marks would report them late, which is the one failure\n * provenance exists to rule out.\n */\nexport interface Binding {\n readonly value: unknown;\n readonly marks: Marks;\n}\n\nexport interface Scope {\n /** Current dot value — what `.` resolves to. */\n readonly dot: Binding;\n /** Parent scope, or undefined for a chain's root frame. */\n readonly parent: Scope | undefined;\n /** Variables declared in *this* frame. */\n readonly vars: Map<string, Binding>;\n}\n\n/** The frame a template body starts in: `.` and `$` are both `dot`. */\nexport function rootScope(dot: Binding): Scope {\n return { dot, parent: undefined, vars: new Map([[\"$\", dot]]) };\n}\n\nexport function pushScope(parent: Scope, dot: Binding): Scope {\n return { dot, parent, vars: new Map() };\n}\n\n// [LAW:single-enforcer] The one walk that decides which frame a name\n// resolves to, so a read and an assignment can never disagree.\nfunction findFrame(scope: Scope, name: string): Scope | undefined {\n let cur: Scope | undefined = scope;\n while (cur !== undefined && !cur.vars.has(name)) cur = cur.parent;\n return cur;\n}\n\n/**\n * Look up a `$var` binding, walking the parent chain.\n * Returns the binding on hit and `undefined` on miss — a `Binding` is a\n * record, so a variable declared as `undefined` is still a hit.\n */\nexport function lookupVar(scope: Scope, name: string): Binding | undefined {\n return findFrame(scope, name)?.vars.get(name);\n}\n\n/** Declare a new variable in the leaf scope (for `:=`). */\nexport function declareVar(scope: Scope, name: string, binding: Binding): void {\n scope.vars.set(name, binding);\n}\n\n/**\n * Overwrite the nearest frame's binding of `name` (for `=`), as Go's\n * text/template exec.go walks its variable stack. Returns whether any\n * frame declared it; the caller owns the \"undefined variable\" error,\n * which needs a position this module does not have.\n */\nexport function assignVar(scope: Scope, name: string, binding: Binding): boolean {\n const frame = findFrame(scope, name);\n frame?.vars.set(name, binding);\n return frame !== undefined;\n}\n\n/** Add `marks` to what `name`'s binding depends on, if any frame declared it. */\nexport function markVar(scope: Scope, name: string, marks: Marks): void {\n const binding = lookupVar(scope, name);\n if (binding === undefined) return;\n assignVar(scope, name, { value: binding.value, marks: unionMarks(binding.marks, marks) });\n}\n","/**\n * Engine<T> — generic-over-T template evaluator.\n *\n * [LAW:dataflow-not-control-flow] Evaluation is one switch on the AST\n * node's type. Every node kind has exactly one production rule; the\n * shape of work is fixed by the data, not by scattered branching.\n *\n * [LAW:single-enforcer] All `string → T` conversion goes through\n * `fromString`. There is exactly one place text becomes T. Function\n * returns of `string` are routed through the same converter on their\n * way to the output stream — the asymmetry between \"string in / T out\"\n * is encoded as a single function call, not duplicated at every site.\n *\n * State is threaded as a single `EvalContext` per `evaluate()` call —\n * no instance mutation, so the same Engine handles concurrent evaluate\n * calls (tested through the parse-once-eval-many invariant).\n */\n\nimport {\n type ArgCount,\n ArgCountError,\n EvalError,\n FailError,\n FuncNotFoundError,\n isStackOverflow,\n MissingFieldError,\n NotIntegerError,\n TemplateError,\n TypeMismatchError,\n} from \"../errors.js\";\nimport {\n assertNever,\n type CommandNode,\n type ListNode,\n type Node,\n type PipeNode,\n type VariableNode,\n} from \"../parser/ast.js\";\nimport type { Delims } from \"../parser/lexer.js\";\nimport {\n type DefineEntry,\n type Defines,\n lookupDefine,\n type ParseResult,\n parse as parseSource,\n} from \"../parser/parser.js\";\nimport type { Pos } from \"../parser/pos.js\";\nimport { walk } from \"../parser/walk.js\";\nimport { MISSING, walkFieldChain } from \"./access.js\";\nimport {\n defaultBuiltins,\n formatV,\n type IsT,\n isPlainObject,\n typeNameOf,\n UnprintableError,\n} from \"./builtins.js\";\nimport { CapturedText, includeKind, isCapturedText } from \"./include.js\";\nimport { isLazy } from \"./lazy.js\";\nimport { Marked, type Marks, NO_MARKS, readCarrier, unionMarks } from \"./marks.js\";\nimport {\n assignVar,\n type Binding,\n declareVar,\n lookupVar,\n markVar,\n pushScope,\n rootScope,\n type Scope,\n} from \"./scope.js\";\nimport { isTruthy } from \"./truthy.js\";\n\n// ---------------------------------------------------------------------------\n// Public API.\n// ---------------------------------------------------------------------------\n\n/**\n * Every kind a slot may declare.\n *\n * [LAW:one-source-of-truth] The kinds are a *list* first and a type\n * second. `validateArgSpecs` must reject a declaration naming a kind\n * that does not exist, and a runtime check needs a runtime list; writing\n * that list out beside a hand-maintained union would be the second\n * clock. So the array is authoritative and `ArgType` is derived from it\n * — one edit adds a kind to the type, to the construct-time check, and\n * to the two exhaustive switches that must then grow an arm.\n *\n * The per-kind semantics live on `ArgType` below, where a consumer\n * hovering the exported name finds them.\n */\nconst ARG_TYPES = [\n \"string\",\n // [LAW:types-are-the-program] \"int\", \"truncating-int\" and \"float\" are\n // validate-AND-parse numeric carriers. The matcher's membership\n // predicate IS the body's contract. Go has two integer semantics, and\n // each gets its own kind so a slot declares which one it has:\n // - \"int\" is a Go `int` parameter (`repeat`, `substr`, `until`, the\n // built-in `slice`'s indices …): Go refuses a fractional there\n // (\"expected integer; found 2.7\"), so the matcher admits only\n // safe integers, in either carrier. NaN, Infinity, fractionals,\n // and integers past 2^53 are rejected at the gate.\n // - \"truncating-int\" is the numeric half of sprig's `interface{}`\n // parameter read through `cast.ToInt64` (`add`, `sub`, `max` …):\n // Go truncates a fractional toward zero, so the matcher admits any\n // finite number and the gate truncates it. The cast's string, bool\n // and nil conversions are refused, as every slot here refuses a\n // kind it would have to flatten.\n // - \"float\" admits any number (NaN/Infinity are legitimate IEEE\n // 754 floats; Go's float64 has them too) and bigints whose\n // `Number()` is finite. The only rejected bigint is one whose\n // conversion overflows to Infinity.\n // After membership is proven the gate mutates `values[i]` to a\n // `number` carrier (\"int\"/\"float\": `Number(v)`; \"truncating-int\":\n // `Math.trunc(Number(v))`). Mirrors the \"liftable\" precedent: the\n // slot is both the membership rule and the parse step.\n \"int\",\n \"truncating-int\",\n \"float\",\n \"bool\",\n \"T\",\n \"ordered\",\n \"list\",\n \"dict\",\n \"sized\",\n \"comparable\",\n \"stringifiable\",\n \"liftable\",\n \"callable\",\n \"collection\",\n \"index-key\",\n \"sliceable\",\n \"truthy\",\n \"reflective\",\n \"value\",\n \"serializable\",\n] as const;\n\n/**\n * Declared parameter type for a registered template function. Used by\n * the no-silent-flatten guard to detect unsafe T-into-string flows.\n *\n * - \"string\" — must be a JS string. Non-string values raise\n * TypeMismatchError. This is the **architectural commitment**: T\n * never silently flattens into a string parameter.\n * - \"int\" — validate-AND-parse integer carrier: a Go `int`\n * parameter. Accepts any safe-integer `number` and any `bigint`\n * whose `Number()` is safe-integer-representable; rejects\n * fractionals, `NaN`, `±Infinity`, and integers past 2^53, as\n * Go refuses `repeat 2.7 \"x\"`. The gate normalizes `values[i]` to\n * `Number(v)` so bodies see `number`. Used by every slot Go declares\n * `int`: the built-in `slice`'s indices, `repeat`, `substr`, `trunc`,\n * `until`, `seq`, `chunk`, `splitn`, `round`'s precision ….\n * - \"truncating-int\" — the numeric half of sprig's `cast.ToInt64` read\n * of an `interface{}` parameter. Accepts what \"int\" accepts plus any\n * finite fractional `number`, which the gate truncates toward zero\n * (`max 1.5 2.5` is `2` in Go); refuses the strings, bools and nil\n * the cast would convert. Used by `add`, `add1`, `sub`, `mul`, `div`, `mod`,\n * `max`, `min`, `biggest`, and sprig's list `slice`.\n * - \"float\" — validate-AND-parse float carrier. Accepts any `number`\n * (including `NaN`/`±Infinity` — legitimate IEEE-754 floats) and any\n * `bigint` whose `Number()` is finite (overflow-to-Infinity rejected\n * as a magnitude failure). The gate normalizes to `Number(v)` so\n * bodies see `number`. Used by `addf`, `subf`, `mulf`, `divf`,\n * `maxf`, `minf`. Added by epic template-variance-num-carrier-hfv.\n * - \"bool\" — must be `typeof \"boolean\"`.\n * - \"T\" — a T: membership is exactly the engine's `isT` (see\n * `EngineConfig.isT`).\n * - \"ordered\" — orderable primitive (string, number, bigint, boolean).\n * When two or more \"ordered\" slots appear in the same call, all of\n * them must share a kind, with `number` and `bigint` bridged. Used\n * by `lt`/`le`/`gt`/`ge` to match Go's `text/template` rule that\n * ordering operands have the same type.\n *\n * Precise kinds (added template-laws-3gt.1, consumed in .2–.7):\n * - \"list\" — array. Excludes string (Go-parity: string is not a list).\n * - \"dict\" — plain object (not Map; Maps are handled separately).\n * - \"sized\" — has a meaningful `len`: string | array | Map | Set | object.\n * - \"comparable\" — accepted by `eq`/`ne`: any JSON-shaped value\n * (ordered primitive, nil, array, plain object, Map, or Set).\n * Functions and symbols are excluded. When two or more \"comparable\"\n * slots appear in the same call, all of them must share a kind, with\n * `number`↔`bigint` bridged and `nil` acting as a wildcard. Object\n * equality routes through `deepEqual` in `eq`/`ne` bodies.\n * - \"stringifiable\" — a value Go's `%v` can print: a string, nil, a\n * scalar, a T the engine's `toString` flattens, an object with its own\n * toString, a class instance (Go's struct), or a list/map of those; a\n * Set, function or symbol has no text form. The matcher *probes* `formatV`;\n * downstream func bodies call it again to actually print.\n * - \"callable\" — `typeof v === \"function\"`.\n * - \"collection\" — string | array | Map | plain object. The receiver\n * shape `index` accepts. Sets and primitives are rejected. Nil is\n * rejected by the gate; the body trusts a non-nil collection.\n * (Added template-laws-3gt.7 alongside the index migration.)\n * - \"index-key\" — string | number | bigint. The key shape `index`\n * accepts. The body decides which collection kind a given key fits\n * (arrays want integer; objects want string).\n * - \"sliceable\" — string | array. Receiver shape for `slice`. Folded\n * into template-laws-3gt.8 alongside the intent-named migration so\n * .9 could delete `\"any\"` from the union.\n *\n * Intent-named kinds (added template-laws-3gt.1, consumed in .8) —\n * the labels carry intent for readers; runtime behavior is documented\n * pass-through except where noted:\n * - \"truthy\" — anything (truthiness context).\n * - \"reflective\" — anything (type-inspection context).\n * - \"value\" — anything (genuinely heterogeneous: constructors,\n * structural ops). Documents intent.\n * - \"serializable\" — anything JSON-encodable. Runtime-validated:\n * functions, symbols, and circular refs fail the gate.\n *\n * [LAW:make-it-impossible] `\"any\"` is intentionally absent from this\n * union. Every slot must engage with the type system. If a slot is\n * genuinely heterogeneous, use the kind that documents the reason\n * (`\"truthy\"`, `\"reflective\"`, `\"serializable\"`, `\"value\"`,\n * `\"callable\"`). The history for this decision lives in epic\n * template-laws-3gt.\n */\nexport type ArgType = (typeof ARG_TYPES)[number];\n\n/**\n * How many arguments a func accepts, and how `argTypes` covers them.\n *\n * [LAW:types-are-the-program] Argument *count* used to live only in the\n * JS signature, where the gate could not see it: `enforceArgTypes`\n * iterated the supplied values, so a missing or surplus argument was\n * not a state it could represent, let alone reject. Declaring arity\n * alongside `argTypes` makes the count a fact the gate reads —\n * `acceptedArgCount` projects this union into the counts a declaration\n * admits and rejects the rest before the slot loop.\n *\n * [LAW:one-source-of-truth] No kind carries a count that `argTypes`\n * already holds. `\"exact\"` means exactly `argTypes.length`, and\n * `\"variadic\"` means at least `argTypes.length - 1` — which is Go's\n * gate for a variadic signature, always, since its fixed parameters are\n * every one but the last. A `minimum` field on either would be a second\n * copy of a number the array carries, and the copy is what drifts:\n * `minimum` survives here only on `\"alternating\"`, where `argTypes` is\n * a cycle length rather than a parameter count and the two are\n * genuinely unrelated.\n *\n * [LAW:one-type-per-behavior] The three kinds are exactly the three\n * slot-lookup rules, so `makeSlotLookup` switches on this union and\n * nothing else. Folding the former `argTypePattern` field in here is\n * what makes \"exact yet alternating\" unrepresentable rather than merely\n * unused.\n *\n * There is deliberately no `between`/optional-trailing kind: Go's own\n * `text/template` and `sprig` have no notion of an optional parameter,\n * so every signature is fixed-arity or variadic. That every declaration\n * here matches the Go function it mirrors is not a claim — it is\n * checked by `go-arity.test.ts` against `go-arity.fixture.json`, which\n * `conformance/gen/arity` extracts from Go. Do not add a fourth kind\n * without a Go signature that demands it.\n */\nexport type Arity =\n /** Exactly `argTypes.length` arguments; each slot is declared once. */\n | { readonly kind: \"exact\" }\n /**\n * At least `argTypes.length - 1` arguments — Go's own gate for a\n * variadic signature, whose fixed parameters are every one but the\n * last. The trailing `argTypes` entry is that last, repeating\n * parameter, so every argument past the declared ones validates\n * against `argTypes[argTypes.length - 1]`.\n *\n * Declare one slot per Go parameter, the repeating one last: `eq` is\n * `func(reflect.Value, ...reflect.Value)`, so it declares two\n * `\"comparable\"` slots and requires one. Collapsing those to a single\n * slot would render the same verdicts today and quietly lose the\n * minimum.\n */\n | { readonly kind: \"variadic\" }\n /**\n * At least `minimum` arguments — the one kind that needs the number,\n * because `argTypes` below is a cycle length, not a parameter count.\n * With `argTypes` read as a *cycle*:\n * the slot for argument `i` is `argTypes[i % argTypes.length]`. Used\n * by `dict`'s `string, value, string, value, …` kv pairing — without\n * it the gate cannot distinguish even-index keys (must be string)\n * from odd-index values (anything), and the body would re-validate\n * per key, splitting `[LAW:single-enforcer]` across two layers.\n */\n | { readonly kind: \"alternating\"; readonly minimum: number };\n\nexport interface TemplateFunc {\n /**\n * The function body. Parameter types are *contravariant-bottom*\n * (`never[]`) so any concrete signature is assignable here — write\n * `fn: (s: string, n: number) => …` if that's what the func wants,\n * and rely on `argTypes` + `enforceArgTypes` to validate at runtime.\n *\n * [LAW:single-enforcer] Param-type validation lives at the dispatch\n * site (`enforceArgTypes`). The compile-time signature does not\n * duplicate that gate — it stays out of the way so consumer\n * implementations can declare the precise types they expect.\n *\n * The signature is *not* a source of arity: `fn.length` stops at the\n * first rest parameter and lies about several registrations (`min`,\n * `max`, `mul` and friends report 0 while Go requires 1). Arity comes\n * from `arity`, never from here.\n *\n * Return `marked(value, ...tokens)` to mark the call; the template sees\n * `value`, and the tokens reach `EngineConfig.emitted` / `decided`\n * wherever the output depends on it.\n */\n readonly fn: (...args: never[]) => unknown;\n /**\n * Declared positional parameter types. Required.\n *\n * How the slots cover the supplied arguments is `arity`'s job: an\n * `\"exact\"` func declares one entry per parameter, a `\"variadic\"` one\n * declares the repeating slot last, and an `\"alternating\"` one\n * declares the cycle.\n *\n * The pipe-fed last argument is appended to the positional list\n * before validation, so it is checked against the slot its final\n * position selects.\n */\n readonly argTypes: readonly ArgType[];\n readonly returnType?: ArgType;\n /**\n * Argument count. Required — a func whose arity is undeclared is a\n * func the gate cannot check, and defaulting to a permissive value\n * would hide exactly the registrations that most need the\n * declaration.\n *\n * Minimums mirror Go's *arity gate*, which is not always the same as\n * the function body's own requirement; see `eq` and `dig`.\n */\n readonly arity: Arity;\n /**\n * `true` when the body stores anything it was handed — in place in an\n * argument, as sprig `set` and `unset` do, or in a closure or module\n * variable a later call returns — or runs code it was handed, which may\n * store (`call`). Omitted: it does neither, which is true of nearly\n * every func.\n *\n * [LAW:types-are-the-program] Whether a call writes is a fact about the\n * func, so it is declared rather than assumed of every call. Where a\n * write lands is beyond what the engine can follow (an object read\n * later, a fragment already emitted, the host's data for the next\n * evaluation), so each call of a writing func reports its inputs'\n * marks through `EngineConfig.decided` as it runs. A body that writes\n * without declaring it reports late.\n */\n readonly writes?: true;\n}\n\nexport type FuncMap = Record<string, TemplateFunc>;\n\n/**\n * Everything the argument gate reads off a registration.\n *\n * [LAW:types-are-the-program] `argTypes` and `arity` answer one\n * question between them — which arguments are legal — and neither\n * answers it alone: `argTypes` says what each slot holds, `arity` says\n * how many slots there are and how they cover the supplied values.\n * Passing them as one value is what makes \"types without their arity\"\n * unrepresentable at the gate; when they were two positional\n * parameters, the second one defaulted and the count check could be\n * skipped by omission.\n */\nexport type ArgSpec = Pick<TemplateFunc, \"argTypes\" | \"arity\">;\n\n/**\n * Policy for missing field/map-key access — mirrors Go's\n * `text/template` `Option(\"missingkey=...\")`:\n *\n * - `\"default\"` (Go's `missingkey=default` / `missingkey=invalid`):\n * missing access yields `undefined`; emitted output is `<no value>`.\n * This is the engine default, matching Go's `text/template` default.\n * - `\"zero\"` (Go's `missingkey=zero`): in Go, returns the zero value of\n * the map's element type. JavaScript has no static value-type info,\n * so the runtime cannot synthesize a typed zero — the option is\n * accepted for API parity and behaves identically to `\"default\"`.\n * Use sprig `default` (`{{ .x | default \"\" }}`) when you want a\n * typed-zero substitute at the use site.\n * - `\"error\"` (Go's `missingkey=error`): missing access throws\n * `MissingFieldError`. Use this in environments where a missing key\n * indicates a scope-construction bug that should fail loud.\n */\nexport type MissingKeyOption = \"default\" | \"zero\" | \"error\";\n\n// [LAW:one-source-of-truth] The valid-set lives next to the type it\n// validates. The `Engine` constructor's boundary check consumes this;\n// no other site decides what counts as a valid policy value.\nconst VALID_MISSING_KEYS: ReadonlySet<MissingKeyOption> = new Set([\"default\", \"zero\", \"error\"]);\n\n// [LAW:types-are-the-program] The TS union forbids invalid values at\n// compile time; this is the JS-boundary mirror of the same theorem so\n// a typo from a JS caller (or an `as`-cast TS caller) fails loud at\n// construct time instead of silently disabling the policy.\nfunction validateMissingKey(value: MissingKeyOption | undefined): MissingKeyOption {\n if (value === undefined) return \"default\";\n if (VALID_MISSING_KEYS.has(value)) return value;\n throw new Error(\n `EngineConfig.missingKey: expected \"default\" | \"zero\" | \"error\", got ${describeBoundaryValue(value)}`,\n );\n}\n\n// [LAW:one-type-per-behavior] Shared safe formatter for boundary\n// diagnostics — every validator that rejects an out-of-shape JS value\n// uses this to describe what was actually passed. `JSON.stringify`\n// would have thrown on bigint or cyclic inputs, swapping the intended\n// diagnostic for an unrelated TypeError; the diagnostic must survive\n// any value the caller might mis-pass.\nfunction describeBoundaryValue(value: unknown): string {\n if (typeof value === \"string\") return JSON.stringify(value);\n if (value === null) return \"null\";\n if (value === undefined) return \"undefined\";\n if (typeof value === \"bigint\") return `${value}n`;\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n if (typeof value === \"symbol\") return value.toString();\n if (typeof value === \"function\") return \"[Function]\";\n return `[${typeof value}]`;\n}\n\n// [LAW:one-source-of-truth] `Delims` is canonical in `parser/lexer.ts`\n// (the lowest layer that consumes it). Re-exported here so consumers\n// reaching `EngineConfig` see the type in the same module without\n// needing to import from internal paths.\nexport type { Delims };\n\n// [LAW:types-are-the-program] The TS interface is the canonical shape;\n// this is the JS-boundary mirror — a typo'd or partially-set object\n// from a JS caller (or an `as`-cast TS caller) fails loud at construct\n// time instead of producing pathological tokenization later. Returns\n// `undefined` for \"no override\" so the parser falls back to its own\n// default and we never need a separate \"are delims set\" boolean.\nfunction validateDelims(value: Delims | undefined): Delims | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"object\" || value === null) {\n throw new Error(\n `EngineConfig.delims: expected { left, right } object, got ${describeBoundaryValue(value)}`,\n );\n }\n if (typeof value.left !== \"string\" || value.left.length === 0) {\n throw new Error(\n `EngineConfig.delims.left: expected non-empty string, got ${describeBoundaryValue(value.left)}`,\n );\n }\n if (typeof value.right !== \"string\" || value.right.length === 0) {\n throw new Error(\n `EngineConfig.delims.right: expected non-empty string, got ${describeBoundaryValue(value.right)}`,\n );\n }\n return { left: value.left, right: value.right };\n}\n\n// [LAW:types-are-the-program] The strongest theorem the gate needs is\n// that every registration's declared arity actually covers its declared\n// slots. TypeScript carries most of it — `arity` is required, and the\n// three kinds are a closed union — but not this last correlation: only\n// `\"exact\"` may declare zero slots. `\"variadic\"` reads its repeating\n// slot off the end of `argTypes`, so with none declared its minimum\n// derives to -1 and the gate accepts any count; `\"alternating\"` indexes\n// `i % argTypes.length`, so with none declared every slot lookup is\n// NaN. Both silently disable the gate for that func rather than failing\n// — [LAW:no-silent-failure] — which is why this is a construct-time\n// error and not a permissive fallback.\n//\n// Expressing it in the type would mean splitting `TemplateFunc` into a\n// union discriminated on `arity.kind`, with the variadic arm requiring\n// a non-empty `argTypes` tuple. That correlation does not survive the\n// `Pick` the gate takes (`ArgSpec`), so it would buy a compile-time\n// check for registrations and lose one at the gate. This is the same\n// JS-boundary mirror `validateMissingKey` and `validateDelims` are.\n//\n// The predicate is a returning switch rather than `kind !== \"exact\"` so\n// that adding a fourth `Arity` kind fails to compile until someone says\n// which side of this line it falls on.\nfunction readsSlotsFromArgTypes(arity: Arity): boolean {\n switch (arity.kind) {\n case \"exact\":\n return false;\n case \"variadic\":\n return true;\n case \"alternating\":\n return true;\n }\n}\n\n// [LAW:parse-dont-validate] The one checkpoint for a declaration. It\n// runs at construct time, which is the only moment at which a malformed\n// `TemplateFunc` can be reported against the line that wrote it, and it\n// fails loudly — so the gate downstream may assume every `ArgSpec` it\n// reads is well-formed and never re-checks one.\n//\n// `argTypes` membership is checked here rather than at the gate for the\n// same reason arity well-formedness is (template-arity-n2j.7ve). A\n// declaration that casts past `ArgType` (`[\"number\" as ArgType]`, a\n// stale registration, a JS caller with no compile-time guard) used to\n// construct cleanly and then raw-throw `Error(\"invalid ArgType: number\")`\n// out of `matchesArgType` mid-render: outside the TemplateError\n// hierarchy, with no position, no caret, and no func name — from inside\n// the gate, which is exactly the failure shape this epic exists to\n// remove. The kind a slot declares is a fact about the *declaration*,\n// knowable before any template is parsed, so this is where it is known.\n//\n// The `default` arms in `matchesArgType` and `humanArgType` stay: their\n// `never` assignment is the compile-time guardrail that forces an arm\n// per kind, and their throw is now unreachable by construction rather\n// than a live path a consumer can reach.\nfunction validateArgSpecs(funcs: FuncMap): FuncMap {\n const legal: ReadonlySet<string> = new Set(ARG_TYPES);\n for (const [name, fn] of Object.entries(funcs)) {\n fn.argTypes.forEach((declared, slot) => {\n if (!legal.has(declared)) {\n throw new Error(\n `EngineConfig.funcs.${name}: argTypes[${slot}] is ${JSON.stringify(declared)}, ` +\n `which is not an ArgType; declare one of ${ARG_TYPES.join(\", \")}`,\n );\n }\n });\n if (readsSlotsFromArgTypes(fn.arity) && fn.argTypes.length === 0) {\n throw new Error(\n `EngineConfig.funcs.${name}: arity ${JSON.stringify(fn.arity.kind)} needs at ` +\n `least one declared argType (it reads its repeating slot from the end of ` +\n `argTypes); declare the slots the Go signature has, or use { kind: \"exact\" }`,\n );\n }\n if (\n fn.arity.kind === \"alternating\" &&\n (!Number.isSafeInteger(fn.arity.minimum) || fn.arity.minimum < 0)\n ) {\n throw new Error(\n `EngineConfig.funcs.${name}: arity \"alternating\" needs a non-negative integer ` +\n `minimum, got ${String(fn.arity.minimum)}; the gate rejects every count below ` +\n `it, so a negative or non-finite minimum would disable the lower bound`,\n );\n }\n }\n return funcs;\n}\n\n// [LAW:types-are-the-program] `isT` may be left at its string default only\n// when T is a string; any other T — an object, or `string | Frag` whose\n// funcs return fragments — must name its fragments, or they print as\n// `map[…]` text. The compiler is the one enforcer.\nexport type EngineConfig<T> = EngineConfigFields<T> &\n ([T] extends [string] ? unknown : { readonly isT: (value: unknown) => value is T });\n\ninterface EngineConfigFields<T> {\n /** Convert a text literal (or string-returning function result) into T. */\n readonly fromString: (s: string) => T;\n /**\n * Flatten a T (or other engine-managed value) into a string.\n *\n * [LAW:single-enforcer] Dual of `fromString`: one place owns the\n * string→T direction, this owns the T→string direction. Built-ins\n * registered against the `\"stringifiable\"` ArgType call this for each\n * T they print, nested ones included; every non-T value prints as Go's\n * `%v` and never reaches it.\n *\n * Default behaviour: passes through any value that is already a\n * `typeof \"string\"` and throws `TypeMismatchError` for everything\n * else. That makes the `T = string` case (consumer set\n * `fromString: (s) => s`) work out of the box, while a non-string T\n * configured without a `toString` errors loudly the first time a\n * `\"stringifiable\"` slot encounters a T value — never silently.\n */\n readonly toString?: (value: T) => string;\n /**\n * Is this value a T? At the output stream a T is pushed as itself and\n * anything else is printed as Go prints it (`[a b]`, `map[k:v …]`, a\n * Date's own String); at a call, a `\"T\"` ArgType slot accepts exactly\n * what this says.\n *\n * [LAW:single-enforcer] The one predicate for what is a T. At the output\n * stream a string, number, boolean or nil is lifted through `fromString`\n * before it is asked, so it decides only for structured values.\n * Default: a string — the T the default `fromString`/`toString` pair\n * supports — so a plain object prints `map[k:v …]` as Go's `%v` does.\n * Required by the type whenever T is not a string, e.g.\n * `isT: (v) => v instanceof RichText`.\n */\n readonly isT?: (value: unknown) => value is T;\n /**\n * PRNG source for `sprigRandom` functions. Defaults to `Math.random`.\n * Supply a seeded generator for reproducible templates.\n *\n * [LAW:single-enforcer] One config field owns the randomness source;\n * pass this to `sprigRandom(config.random)` when composing a full\n * sprig engine so the seam is wired once, not per-function.\n */\n readonly random?: () => number;\n /**\n * Clock source for `sprigDatetime` functions. Defaults to\n * `() => new Date()`. Supply a frozen clock for deterministic test\n * output.\n *\n * [LAW:single-enforcer] One config field owns the time source; pass\n * this to `sprigDatetime(config.clock)` when composing a full sprig\n * engine so the seam is wired once, not per-function.\n */\n readonly clock?: () => Date;\n /**\n * Policy for missing field / map-key access. Defaults to `\"default\"`\n * (matching Go's `text/template` default — silent `<no value>`). See\n * `MissingKeyOption` for the full enum semantics.\n *\n * [LAW:single-enforcer] One config field owns the policy; the\n * `resolveFieldChain` gate is the only site that consults it.\n * [LAW:dataflow-not-control-flow] The policy is data flowing into a\n * fixed gate, not a branch sprinkled across accessors.\n */\n readonly missingKey?: MissingKeyOption;\n /**\n * Optional override for the template action delimiters. Mirrors\n * Go's `text/template.Template.Delims(left, right)`. Both sides\n * are required if specified — neither may be empty.\n *\n * [LAW:single-enforcer] Validated once at construct time and\n * threaded into the parser as immutable data; no re-validation\n * along the call chain.\n * [LAW:dataflow-not-control-flow] The delim pair is data flowing\n * into the fixed lexer state machine — no new modes, no new\n * branches, just different constant values seeded at construction.\n */\n readonly delims?: Delims;\n /** Optional registry of named functions usable in pipelines. */\n readonly funcs?: FuncMap;\n /**\n * Every `T` the template emits passes through here with the marks it\n * depends on (see `marked`), and the return is what reaches the output.\n * The marks are those of every value the emitting action read and of\n * every `if`/`with`/`range` arm it sits in; a mark is reported early,\n * never late, and a mark bound somewhere nobody reads is not reported.\n * Called for every emission, an empty set included. Default: returns\n * `value` unchanged.\n */\n readonly emitted?: (value: T, marks: ReadonlySet<unknown>) => T;\n /**\n * Called once each time an `if`/`with`/`range` pipe is evaluated,\n * before either arm runs — so a decision whose taken arm emits nothing\n * (or which has no arm to take) still says what it depended on. Also\n * called for each call of a func that declares `writes` (the output may\n * show that write later with no cell to say it on), and for each action\n * or control pipe that throws. Every call carries the marks of the\n * values read and of every `if`/`with`/`range` arm it sits in.\n * Default: does nothing.\n */\n readonly decided?: (marks: ReadonlySet<unknown>) => void;\n}\n\n// Per-evaluate context. Threaded through every internal method.\n// The bodies a control construct chooses among.\ninterface Arms {\n readonly list: ListNode;\n readonly elseList?: ListNode;\n}\n\ninterface EvalContext<T> {\n // Where a fragment goes once produced. The root evaluation's sink\n // pushes through `emitted` onto the output; `include`'s sink captures\n // the fragment instead, because a captured fragment never reaches the\n // output until the caller emits the result.\n readonly emit: (value: T, marks: Marks) => void;\n // Where a decision's marks go. The root's sink is the engine's `decided`;\n // `include`'s also joins them to its result, which hangs on every\n // decision its body made, an arm that emitted nothing included.\n readonly decided: (marks: Marks) => void;\n readonly defines: Defines;\n readonly source: string | undefined;\n // The control-pipe marks of every arm being evaluated: an emission\n // here depends on the branches that led to it.\n readonly marks: Marks;\n // How many define bodies enclose this one, for the error that names a\n // recursion too deep for the host's stack.\n readonly depth: number;\n}\n\n// [LAW:types-are-the-program] Internal control-flow sentinels for\n// `{{break}}` / `{{continue}}`. They are NOT user-facing errors —\n// `TemplateError` deliberately is not their base — and they never\n// escape `evalRange`: the parser guarantees (via rangeDepth) that\n// every Break/Continue node is lexically inside a Range body, and\n// the range body is the only thrower-and-catcher of these. A\n// reference-identity check at the catch site is the strongest\n// possible discriminator: no string matching, no error-message\n// drift, no risk of swallowing user errors. See [LAW:single-enforcer]\n// — these constants are the one source of truth for the signal.\nconst BREAK_SIGNAL = Object.freeze({ kind: \"break\" as const });\nconst CONTINUE_SIGNAL = Object.freeze({ kind: \"continue\" as const });\n\n// [LAW:dataflow-not-control-flow] Pipeline-fed value, structurally\n// distinguished from absence. Replaces an earlier `unknown` parameter\n// where `undefined` was overloaded to mean both \"no pipe\" and \"pipe of\n// undefined\" — a sentinel collision that produced arity-mismatched\n// calls when a function legitimately returned `undefined`. The\n// discriminator now drives the append decision; the value (including\n// `undefined`) flows through unchanged.\ntype Piped = { readonly kind: \"none\" } | { readonly kind: \"value\"; readonly value: unknown };\n\nconst NO_PIPE: Piped = { kind: \"none\" };\n\n// The one wording for a by-name render whose name nothing defines, whether\n// a template or the host asked.\nconst notDefined = (name: string): string => `template ${JSON.stringify(name)} is not defined`;\n\n/**\n * A parsed template bound to its parent engine.\n *\n * Template instances are immutable — `evaluate(scope)` may be called\n * any number of times with different scopes, matching the\n * \"parse-once-eval-many\" invariant from the epic spec. The `source`\n * property exposes the original template text for debugging /\n * diagnostics.\n *\n * Construct via `engine.parse(src)`. The constructor is private so\n * the public type surface need not reference internal AST shapes.\n */\n// [LAW:one-source-of-truth] `internalCreateTemplate` is the *only*\n// callable factory for Template. Captured from the static block below\n// so that Engine (and only Engine) can construct Templates without\n// exposing the parsed AST shape on the public type surface.\nlet internalCreateTemplate: <U>(\n source: string,\n evaluate: (scope: unknown) => U[],\n evaluateDefine: (name: string, scope: unknown) => U[],\n defines: Defines,\n referencedFunctions: ReadonlySet<string>,\n referencedCalls: readonly ReferencedCall[],\n) => Template<U>;\n\n// [LAW:types-are-the-program] One command-head call site projected to the facts\n// a static consumer can act on: the callee name and its positional arguments,\n// with each LITERAL string argument decoded and every non-literal argument\n// (field, pipeline, bool, number, …) reported as `null` so positions are\n// preserved. This is the argument-aware companion to `referencedFunctions`:\n// where that answers \"is X called?\", this answers \"with what literal strings?\".\nexport interface ReferencedCall {\n /** The function name at the head of the command. */\n readonly name: string;\n /**\n * The positional arguments after the head. A literal string argument is its\n * decoded value; any non-string-literal argument is `null` (its value is only\n * known at evaluation time). Indices match the call site, so `args[0]` is the\n * first argument regardless of the kinds in between.\n *\n * [LAW:one-source-of-truth] A derived view of {@link argExprs} — the\n * string-literal projection kept for consumers that only read literal\n * string slots. `args[i]` is `argExprs[i].value` when that is a literal\n * string, `null` otherwise.\n */\n readonly args: readonly (string | null)[];\n /**\n * The positional arguments after the head, each statically projected to a\n * {@link ReferencedArg}. Indices match the call site (`argExprs[0]` is the\n * first argument), and `argExprs.length === args.length`.\n */\n readonly argExprs: readonly ReferencedArg[];\n}\n\n/**\n * A scalar value statically decodable from a literal argument node. Numbers\n * carry the same JS value evaluation would produce (safe ints as `number`,\n * larger ints as `bigint`); `null` is the projection of the `nil` literal.\n */\nexport type ReferencedLiteral = string | number | bigint | boolean | null;\n\n// [LAW:types-are-the-program] The total static projection of one call\n// argument. Three shapes cover the whole grammar: a literal scalar whose\n// value is known at parse time; a nested call `(f a b …)` projected\n// recursively so a consumer can read e.g. `(dict \"k\" \"v\")` option args\n// without evaluating; and `dynamic` for everything whose value only exists\n// at eval time (fields, variables, pipelines, function-valued idents, …).\n// A value is never guessed: anything not provably literal is `dynamic`\n// [LAW:no-silent-failure].\nexport type ReferencedArg =\n | { readonly kind: \"literal\"; readonly value: ReferencedLiteral }\n | { readonly kind: \"call\"; readonly name: string; readonly args: readonly ReferencedArg[] }\n | { readonly kind: \"dynamic\" };\n\nexport class Template<T> {\n readonly source: string;\n private readonly _evaluate: (scope: unknown) => T[];\n private readonly _evaluateDefine: (name: string, scope: unknown) => T[];\n private readonly _defines: Defines;\n // [LAW:types-are-the-program] The set of FuncMap names this template\n // references, computed ONCE from the parsed AST at construction. A name here\n // is a function the template *can* call (it is the head of some command, or\n // appears as a function-valued argument); whether a given evaluation reaches\n // it is a runtime question this static fact does not answer. Frozen so the\n // exposed set cannot be mutated by a caller.\n private readonly _referencedFunctions: ReadonlySet<string>;\n // [LAW:types-are-the-program] Every command-head call with its literal string\n // args, computed ONCE from the same parsed AST. A superset of the information\n // in `_referencedFunctions` (every call's name is also a referenced function),\n // exposed separately so the cheaper name-only query stays a `Set`.\n private readonly _referencedCalls: readonly ReferencedCall[];\n\n private constructor(\n source: string,\n evaluate: (scope: unknown) => T[],\n evaluateDefine: (name: string, scope: unknown) => T[],\n defines: Defines,\n referencedFunctions: ReadonlySet<string>,\n referencedCalls: readonly ReferencedCall[],\n ) {\n this.source = source;\n this._evaluate = evaluate;\n this._evaluateDefine = evaluateDefine;\n this._defines = defines;\n this._referencedFunctions = referencedFunctions;\n this._referencedCalls = referencedCalls;\n }\n\n static {\n internalCreateTemplate = <U>(\n source: string,\n evaluate: (scope: unknown) => U[],\n evaluateDefine: (name: string, scope: unknown) => U[],\n defines: Defines,\n referencedFunctions: ReadonlySet<string>,\n referencedCalls: readonly ReferencedCall[],\n ) =>\n new Template(source, evaluate, evaluateDefine, defines, referencedFunctions, referencedCalls);\n }\n\n /**\n * The named sub-templates this template can invoke — its own `{{define}}`s\n * chained onto whatever it inherited at parse. Pass it to `engine.parse` as\n * `inherit` to let another template invoke the same set without re-parsing\n * (and re-allocating) it: the idiom for a shared helper preamble is\n * `const helpers = engine.parse(preamble).defines()` once, then\n * `engine.parse(src, helpers)` per template. Opaque: the AST inside is not\n * part of the public surface.\n */\n defines(): Defines {\n return this._defines;\n }\n\n evaluate(scope: unknown): T[] {\n return this._evaluate(scope);\n }\n\n /**\n * Render one named sub-template — any `{{ define }}` in {@link defines}, its\n * own or inherited — with `scope` as its dot and `$`, as Go's\n * `ExecuteTemplate` does. The output is the same `T[]` a whole-template\n * {@link evaluate} produces, through the same `emitted` / `decided` hooks.\n */\n evaluateDefine(name: string, scope: unknown): T[] {\n return this._evaluateDefine(name, scope);\n }\n\n /**\n * The FuncMap function names this template references — every identifier that\n * names a function in this parse: the template body and its own `{{ define }}`\n * blocks. A set inherited at parse (see {@link Template.defines}) is described\n * by the template that parsed it, not here.\n *\n * This is a STATIC fact derived from the parsed AST, not an execution trace:\n * a name in the set is a function the template *can* invoke; a name absent\n * from the set is one it provably never invokes. Use it to ask \"does this\n * template use helper X?\" without evaluating it (e.g. to discover which\n * templates depend on a feature func) — robust where a source-text scan is\n * not, because it sees through whitespace, pipelines, and field/string\n * lookalikes.\n *\n * Built-in operators registered for every engine (`and`, `eq`, `index`,\n * `printf`, …) are reported the same as consumer funcs — a referenced name is\n * a referenced name regardless of who registered it.\n */\n referencedFunctions(): ReadonlySet<string> {\n return this._referencedFunctions;\n }\n\n /**\n * Every command-head call in this parse — the template body and its own\n * `{{ define }}` blocks, never an inherited set — in preorder, each paired with its positional arguments projected to literal\n * strings (a non-string-literal argument is reported as `null`, preserving\n * argument positions).\n *\n * Like {@link referencedFunctions} this is a STATIC fact from the parsed AST,\n * not an execution trace. Use it when \"is X called?\" is not enough and you\n * need the literal arguments a call was written with — e.g. to discover that a\n * template contains `{{ menu \"applyTheme\" \"themePage\" }}` and read its first\n * argument without evaluating the template. Each call's `argExprs` carries the\n * full {@link ReferencedArg} projection (scalar literals, nested literal calls\n * like `(dict \"k\" \"v\")`, `dynamic` for eval-time values); `args` is its\n * string-literal-only view. Calls whose head is not a bare function\n * identifier (e.g. a field invoked via `call`) are not reported here; their\n * names still appear in {@link referencedFunctions}.\n */\n referencedCalls(): readonly ReferencedCall[] {\n return this._referencedCalls;\n }\n}\n\n// [LAW:single-enforcer] The one place \"which functions does this AST reference\"\n// is computed — a single preorder walk (the shared traversal helper) over the\n// root body and every `{{ define }}` body. In go-template's grammar every\n// IdentifierNode names a function (bare `true`/`nil`/numbers parse to their own\n// node kinds), whether it is a command head (`{{ f x }}`) or a function-valued\n// argument (`{{ call .x f }}`), so collecting every Identifier is exactly the\n// set of referenced functions — no positional special-casing.\nfunction collectReferencedFunctions(parsed: ParseResult): ReadonlySet<string> {\n const names = new Set<string>();\n const collect = (root: Node): void => {\n walk(root, (node) => {\n if (node.type === \"Identifier\") names.add(node.ident);\n });\n };\n collect(parsed.root);\n for (const entry of parsed.ownDefines.values()) collect(entry.list);\n return names;\n}\n\nconst DYNAMIC_ARG: ReferencedArg = { kind: \"dynamic\" };\n\n// [LAW:single-enforcer] The one place an argument node becomes a\n// ReferencedArg. Literal leaves decode to the SAME JS value evaluation\n// produces — strings/bools directly, numbers via the shared `numberValue`\n// (complex literals have no scalar carrier, so they stay `dynamic` rather\n// than invent one), `nil` as `null`. A parenthesised argument parses as a\n// PipeNode; only the trivial pipe — no declarations, exactly one command,\n// an Identifier head — is a statically readable nested call `(f a b …)`,\n// projected recursively. Every other shape is an eval-time value: `dynamic`.\nfunction projectArg(node: Node): ReferencedArg {\n switch (node.type) {\n case \"String\":\n return { kind: \"literal\", value: node.value };\n case \"Bool\":\n return { kind: \"literal\", value: node.value };\n case \"Nil\":\n return { kind: \"literal\", value: null };\n case \"Number\": {\n const value = numberValue(node);\n return typeof value === \"number\" || typeof value === \"bigint\"\n ? { kind: \"literal\", value }\n : DYNAMIC_ARG;\n }\n case \"Pipe\": {\n if (node.decls.length !== 0 || node.cmds.length !== 1) return DYNAMIC_ARG;\n const cmd = node.cmds[0];\n if (cmd === undefined) return DYNAMIC_ARG;\n const head = cmd.args[0];\n if (head === undefined || head.type !== \"Identifier\") return DYNAMIC_ARG;\n return { kind: \"call\", name: head.ident, args: cmd.args.slice(1).map(projectArg) };\n }\n default:\n return DYNAMIC_ARG;\n }\n}\n\n// [LAW:single-enforcer] The one place \"which command-head calls, with what\n// literal args\" is computed — the same preorder walk as\n// `collectReferencedFunctions`, over the root body and every `{{ define }}`. A\n// CommandNode whose first arg is an Identifier is a call of that function; the\n// remaining args are projected via `projectArg`, preserving positions, and the\n// legacy string-only `args` view is derived from that projection\n// [LAW:one-source-of-truth]. Pipeline stages (`{{ x | f }}`) parse as Commands\n// too, so `f` is reported with the args written at its own stage (the piped\n// value is prepended at eval and is not an AST argument) — consistent with how\n// the head/args split is defined here.\nfunction collectReferencedCalls(parsed: ParseResult): readonly ReferencedCall[] {\n const calls: ReferencedCall[] = [];\n const collect = (root: Node): void => {\n walk(root, (node) => {\n if (node.type !== \"Command\") return;\n const head = node.args[0];\n if (head === undefined || head.type !== \"Identifier\") return;\n const argExprs = node.args.slice(1).map(projectArg);\n calls.push({\n name: head.ident,\n args: argExprs.map((arg) =>\n arg.kind === \"literal\" && typeof arg.value === \"string\" ? arg.value : null,\n ),\n argExprs,\n });\n });\n };\n collect(parsed.root);\n for (const entry of parsed.ownDefines.values()) collect(entry.list);\n return calls;\n}\n\nexport class Engine<T> {\n private readonly fromString: (s: string) => T;\n // [LAW:single-enforcer] Stored alongside `fromString` so the engine\n // owns both halves of the text↔T boundary. Threaded into\n // `enforceArgTypes` so `\"stringifiable\"` slots probe with the same\n // function that downstream func bodies will re-use to flatten.\n private readonly toString: (value: unknown) => string;\n private readonly isT: IsT;\n // [LAW:types-are-the-program] Only the producing engine can replay a\n // capture as its T. The template value exposes its text, never this array.\n private readonly captures = new WeakMap<CapturedText, readonly T[]>();\n private readonly funcs: FuncMap;\n // [LAW:single-enforcer] One field, consulted only at `resolveFieldChain`.\n // [LAW:one-source-of-truth] Default is `\"default\"` so the engine\n // matches Go's `text/template` default (\"missingkey=default\" /\n // \"invalid\"). The conformance corpus is generated by Go's reference\n // implementation under that default; aligning the JS default keeps\n // byte-parity for any fixture exercising missing keys.\n private readonly missingKey: MissingKeyOption;\n // [LAW:single-enforcer] One field, threaded into the parser as\n // immutable data. `undefined` means \"use parser's defaults\" — we\n // never store a synthesized default here, so the engine can't\n // accidentally diverge from whatever the parser considers default.\n private readonly delims: Delims | undefined;\n // [LAW:dataflow-not-control-flow] Always called; an unconfigured hook is\n // the identity / no-op, so provenance is one path whether or not anyone\n // listens.\n private readonly emitted: (value: T, marks: Marks) => T;\n private readonly decided: (marks: Marks) => void;\n\n constructor(config: EngineConfig<T>) {\n this.fromString = config.fromString;\n // `toString` collides with `Object.prototype.toString`, so a plain\n // `config.toString ?? default` would silently bind the prototype\n // method when the consumer didn't pass anything. Check for an own\n // property explicitly so the fallback only fires for unconfigured\n // engines.\n const userToString = Object.hasOwn(config, \"toString\") ? config.toString : undefined;\n this.toString = (userToString ?? defaultToString) as (value: unknown) => string;\n // [LAW:no-defensive-null-guards] exception: trust boundary — the\n // EngineConfig flows in from JS callers (no compile-time guard) and\n // TS callers using `as` casts. A typo like `\"erro\"` would silently\n // degrade to default semantics and disable the strict policy a\n // caller asked for. Validate at construct time so the bad value\n // fails loud at the only place it can be detected.\n this.missingKey = validateMissingKey(config.missingKey);\n // [LAW:no-defensive-null-guards] exception: trust boundary. Same\n // rationale as `missingKey`: a typo'd or partially-set delims\n // object from a JS caller would otherwise produce baffling\n // tokenization at parse time. Fail loud at the only place the\n // mistake can be detected.\n this.delims = validateDelims(config.delims);\n const isT = config.isT ?? DEFAULT_IS_T;\n this.isT = (value) => !isCapturedText(value) && isT(value);\n this.emitted = config.emitted ?? ((value) => value);\n this.decided = config.decided ?? (() => {});\n // [LAW:single-enforcer] Built-ins live in one registry; consumer\n // funcs override on a per-name basis (this gives consumers an\n // escape hatch — desired).\n //\n // [LAW:parse-dont-validate] Arity well-formedness is checked once,\n // here, on the merged map — after overrides, so a consumer cannot\n // shadow a built-in with a malformed declaration. The gate then\n // derives counts from these declarations without re-checking them.\n this.funcs = validateArgSpecs({\n ...defaultBuiltins(this.toString, this.isT),\n ...(config.funcs ?? {}),\n });\n }\n\n /**\n * Parse a template source into a reusable Template handle.\n *\n * The returned Template is immutable; calling `evaluate(scope)` on\n * it any number of times with different scopes is safe and avoids\n * re-parsing.\n */\n parse(source: string, inherit?: Defines): Template<T> {\n const parsed = parseSource(source, this.delims, inherit);\n return internalCreateTemplate(\n parsed.source,\n (scope) =>\n this.evalParsed(parsed, scope, (root, ctx) => this.evalList(parsed.root, root, ctx)),\n (name, scope) => {\n // The call is the host's, at no place in any source. A name it\n // cannot find is the host's mistake, as Go's ExecuteTemplate returns\n // a plain error; the define itself runs as if called from its own\n // body, in the source that declared it.\n const entry = lookupDefine(parsed.defines, name);\n if (!entry) throw new Error(notDefined(name));\n return this.evalParsed(parsed, scope, (root, ctx) =>\n this.renderDefine(name, entry, root.dot, entry.list.pos, {\n ...ctx,\n source: entry.source,\n }),\n );\n },\n parsed.defines,\n collectReferencedFunctions(parsed),\n collectReferencedCalls(parsed),\n );\n }\n\n /**\n * Convenience sugar for `parse(src).evaluate.bind(template)`.\n *\n * Returns a closure that takes a scope and produces T[]. Useful when\n * the template is parsed once at module load and called many times.\n */\n compile(source: string): (scope: unknown) => T[] {\n const template = this.parse(source);\n return (scope: unknown) => template.evaluate(scope);\n }\n\n /**\n * Evaluate a parsed template against a scope value, producing T[].\n *\n * Accepts only Templates produced by `engine.parse(src)` so the\n * public type surface stays clear of internal AST shapes.\n */\n evaluate(template: Template<T>, scope: unknown): T[] {\n return template.evaluate(scope);\n }\n\n // [LAW:single-enforcer] All evaluation flows through here; the\n // Template closure built in `parse()` calls back into this method.\n private evalParsed(\n parsed: ParseResult,\n scope: unknown,\n body: (root: Scope, ctx: EvalContext<T>) => void,\n ): T[] {\n const out: T[] = [];\n const root = rootScope({ value: scope, marks: NO_MARKS });\n const ctx: EvalContext<T> = {\n emit: (value, marks) => out.push(this.emitted(value, marks)),\n decided: this.decided,\n defines: parsed.defines,\n source: parsed.source,\n marks: NO_MARKS,\n depth: 0,\n };\n body(root, ctx);\n return out;\n }\n\n // -------------------------------------------------------------------\n // Statement-level dispatch (output-producing nodes).\n // -------------------------------------------------------------------\n\n private evalList(node: ListNode, scope: Scope, ctx: EvalContext<T>): void {\n for (const child of node.nodes) {\n this.evalNode(child, scope, ctx);\n }\n }\n\n private evalNode(node: Node, scope: Scope, ctx: EvalContext<T>): void {\n switch (node.type) {\n case \"Text\":\n ctx.emit(this.fromString(node.text), ctx.marks);\n return;\n case \"Comment\":\n return;\n case \"Action\":\n // The whole action — pipe, lift, `emitted` — is one read, so a throw\n // anywhere in it reports what it had consumed.\n this.read(ctx, (reads) => {\n const value = this.evalPipe(node.pipe, scope, ctx, reads);\n // Per Go's spec, actions whose pipeline declares variables\n // (`{{ $x := pipe }}`) contribute no output — they're pure\n // assignment statements. Only assignment-free actions emit.\n if (node.pipe.decls.length === 0) {\n this.emitValue(value, node.pos, ctx, unionMarks(reads, ctx.marks));\n }\n });\n return;\n case \"List\":\n this.evalList(node, scope, ctx);\n return;\n case \"If\":\n this.evalIf(node, scope, ctx);\n return;\n case \"Range\":\n this.evalRange(node, scope, ctx);\n return;\n case \"With\":\n this.evalWith(node, scope, ctx);\n return;\n case \"Break\":\n // [LAW:single-enforcer] The signal is the *only* mechanism;\n // the parser already guarantees we're lexically inside a\n // range, and `evalRange` is the only catcher.\n throw BREAK_SIGNAL;\n case \"Continue\":\n throw CONTINUE_SIGNAL;\n case \"Template\":\n this.evalTemplateInvoke(node, scope, ctx);\n return;\n case \"Block\":\n this.evalBlock(node, scope, ctx);\n return;\n case \"Pipe\":\n case \"Command\":\n case \"Identifier\":\n case \"Field\":\n case \"Variable\":\n case \"Chain\":\n case \"Dot\":\n case \"Nil\":\n case \"Bool\":\n case \"Number\":\n case \"String\":\n // These are *expression* nodes — they should never appear as\n // statements at list level. If one does, the AST is malformed.\n throw new EvalError(`unexpected ${node.type} at statement position`, node.pos, {\n source: ctx.source,\n });\n default:\n assertNever(node);\n }\n }\n\n // -------------------------------------------------------------------\n // Control flow.\n // -------------------------------------------------------------------\n\n private evalIf(\n node: { pipe: PipeNode; list: ListNode; elseList?: ListNode },\n scope: Scope,\n ctx: EvalContext<T>,\n ): void {\n const frame = constructFrame(scope);\n const { value: cond, reads } = this.read(ctx, (r) => this.evalPipe(node.pipe, frame, ctx, r));\n const arm = this.decide(reads, ctx, frame, node);\n if (isTruthy(cond)) {\n this.evalList(node.list, frame, arm);\n } else if (node.elseList) {\n this.evalList(node.elseList, frame, arm);\n }\n }\n\n private evalWith(\n node: { pipe: PipeNode; list: ListNode; elseList?: ListNode },\n scope: Scope,\n ctx: EvalContext<T>,\n ): void {\n const frame = constructFrame(scope);\n const { value, reads } = this.read(ctx, (r) => this.evalPipe(node.pipe, frame, ctx, r));\n const arm = this.decide(reads, ctx, frame, node);\n if (isTruthy(value)) {\n this.evalList(node.list, pushScope(frame, { value, marks: arm.marks }), arm);\n } else if (node.elseList) {\n this.evalList(node.elseList, frame, arm);\n }\n }\n\n private evalRange(\n node: { pipe: PipeNode; list: ListNode; elseList?: ListNode; pos: Pos },\n scope: Scope,\n ctx: EvalContext<T>,\n ): void {\n // The pipe's decls first bind to the ranged value as a whole (`=`\n // assigns the enclosing variables instead); each iteration then\n // rebinds them to its key and element, as Go's exec.go does.\n const rangeScope = constructFrame(scope);\n const { value, reads } = this.read(ctx, (r) => this.evalPipe(node.pipe, rangeScope, ctx, r));\n const arm = this.decide(reads, ctx, rangeScope, node);\n const { decls, isAssign } = node.pipe;\n\n const entries = enumerateForRange(value);\n // [LAW:single-enforcer] Two catch boundaries, exactly mirroring\n // Go's text/template `walkRange` (exec.go: two `defer recover`s\n // around the function and around `oneIteration`):\n //\n // - The *outer* try catches BREAK_SIGNAL only. It scopes both\n // the body-iteration loop *and* the `else` clause — so a\n // break inside a range's else (legal only when there is an\n // outer range, by the parser's `rangeDepth` rule) terminates\n // this range, not the outer one.\n //\n // - The *inner* per-iteration try catches CONTINUE_SIGNAL only.\n // Continue inside the body advances to the next iteration;\n // continue inside the else propagates up, because the outer\n // try doesn't catch it (matches Go: walkContinue is not\n // caught by walkRange's outer recover).\n //\n // Reference-identity catches — no message-string matching, so\n // unrelated user errors with similar shapes are never swallowed.\n try {\n if (entries.length === 0) {\n if (node.elseList) this.evalList(node.elseList, rangeScope, arm);\n return;\n }\n for (const [key, item] of entries) {\n // Every item, key and decl came out of the ranged value, so each\n // depends on what the range pipe read.\n // The last decl takes the element; a first of two takes the key.\n decls.forEach((decl, i) => {\n const binding = { value: i === decls.length - 1 ? item : key, marks: arm.marks };\n this.bind(rangeScope, decl, isAssign, binding, ctx);\n });\n const child = pushScope(rangeScope, { value: item, marks: arm.marks });\n try {\n this.evalList(node.list, child, arm);\n } catch (e) {\n if (e === CONTINUE_SIGNAL) continue;\n throw e;\n }\n }\n } catch (e) {\n if (e === BREAK_SIGNAL) return;\n throw e;\n }\n }\n\n private evalTemplateInvoke(\n node: { name: string; pipe?: PipeNode; pos: Pos },\n scope: Scope,\n ctx: EvalContext<T>,\n ): void {\n const entry = this.definedEntry(node.name, node.pos, ctx);\n const dot = this.invocationDot(node.pipe, scope, ctx);\n this.renderDefine(node.name, entry, dot, node.pos, ctx);\n }\n\n // [LAW:single-enforcer] The one lookup a by-name render inside a template\n // (`{{ template }}`, `include`) goes through, and so the one \"is not\n // defined\" error at a place in a source.\n private definedEntry(name: string, pos: Pos, ctx: EvalContext<T>): DefineEntry {\n const entry = lookupDefine(ctx.defines, name);\n if (!entry) {\n throw new EvalError(notDefined(name), pos, {\n source: ctx.source,\n });\n }\n return entry;\n }\n\n // [LAW:single-enforcer] Every define body runs here: `{{ template }}`,\n // `{{ block }}` and `include`.\n private renderDefine(\n name: string,\n body: { readonly list: ListNode; readonly source: string | undefined },\n dot: Binding,\n pos: Pos,\n ctx: EvalContext<T>,\n ): void {\n // A template body sees only its own `$`, never the caller's variables.\n // Its errors snippet against the source that declared it, which for an\n // inherited define is not this template's source.\n try {\n this.evalList(body.list, rootScope(dot), {\n ...ctx,\n source: body.source,\n depth: ctx.depth + 1,\n });\n } catch (e) {\n // Go caps nesting at 100000, deeper than any JS host's stack. The\n // recursion runs as deep as the host allows; the overflow becomes one\n // error naming the define, at the innermost frame that can build it,\n // and every frame above passes that `TemplateError` through.\n if (!isStackOverflow(e)) throw e;\n throw new EvalError(\n `template ${JSON.stringify(name)}: nesting depth ${ctx.depth + 1} exceeds the host's stack`,\n pos,\n { source: ctx.source, cause: e },\n );\n }\n }\n\n // Both registrations render the same body into a private sink. Its\n // emissions and decisions contribute to the dependencies of the result.\n private include(\n kind: \"text\" | \"fragments\",\n registered: string,\n name: string,\n data: unknown,\n pos: Pos,\n ctx: EvalContext<T>,\n reads: Set<unknown>,\n ): string | CapturedText {\n const entry = this.definedEntry(name, pos, ctx);\n const parts: string[] = [];\n const fragments: T[] | undefined = kind === \"fragments\" ? [] : undefined;\n const emit = (value: T, marks: Marks): void => {\n // [LAW:single-enforcer] T→string is the engine's `toString`, here as\n // everywhere; a non-string T with none configured fails loudly.\n parts.push(this.toString(value));\n fragments?.push(value);\n for (const mark of marks) reads.add(mark);\n };\n const decided = (marks: Marks): void => {\n ctx.decided(marks);\n for (const mark of marks) reads.add(mark);\n };\n // The dot depends on everything the call has read so far, its data\n // argument included: a mark is reported early, never late. A snapshot:\n // `reads` keeps growing as the body emits.\n const dot = { value: data, marks: new Set([...reads, ...ctx.marks]) };\n try {\n this.renderDefine(name, entry, dot, pos, { ...ctx, emit, decided });\n } catch (e) {\n // `error calling <registered name>` at the call, with the body's own error —\n // its class, position and source — as the cause. The text is the\n // innermost error's, not every level's again: a chain of includes\n // otherwise repeats itself once per level. A `fail` stays a\n // `FailError`, so the template's own refusal is told apart from the\n // engine's however many includes it passed through.\n if (!(e instanceof TemplateError)) throw e;\n const root = innermost(e);\n const Wrap = root instanceof FailError ? FailError : EvalError;\n throw new Wrap(`error calling ${registered} ${JSON.stringify(name)}: ${root.message}`, pos, {\n source: ctx.source,\n cause: e,\n });\n }\n const text = parts.join(\"\");\n if (!fragments) return text;\n const capture = new CapturedText(text);\n this.captures.set(capture, fragments);\n return capture;\n }\n\n private evalBlock(\n node: { name: string; pipe: PipeNode; list: ListNode; pos: Pos },\n scope: Scope,\n ctx: EvalContext<T>,\n ): void {\n // A block invokes the same-named template if one is registered (or\n // that registration came from the block itself at parse time).\n // The dot for the block body is the pipe's value when present.\n const dot = this.invocationDot(node.pipe, scope, ctx);\n const entry = lookupDefine(ctx.defines, node.name) ?? { list: node.list, source: ctx.source };\n this.renderDefine(node.name, entry, dot, node.pos, ctx);\n }\n\n // [LAW:single-enforcer] The one place a control pipe's marks are\n // reported, and the one place they join what depends on the decision:\n // whichever arm runs — an empty one, or none — the decision has already\n // said what it read, and every variable an arm may `=`-assign carries it,\n // since its value after the construct hangs on which arm ran.\n private decide(reads: Marks, ctx: EvalContext<T>, frame: Scope, arms: Arms): EvalContext<T> {\n const marks = unionMarks(ctx.marks, reads);\n ctx.decided(marks);\n for (const name of this.assignedIn(arms)) markVar(frame, name, marks);\n return { ...ctx, marks };\n }\n\n // The names any `=` in a construct's arms assigns, nested constructs\n // included; fixed by the AST, so found once per construct.\n private readonly assigned = new WeakMap<ListNode, readonly string[]>();\n private assignedIn(arms: Arms): readonly string[] {\n const cached = this.assigned.get(arms.list);\n if (cached !== undefined) return cached;\n const names = new Set<string>();\n const collect = (n: Node): void => {\n if (n.type === \"Pipe\" && n.isAssign) for (const d of n.decls) names.add(d.idents[0] ?? \"$\");\n };\n for (const list of [arms.list, arms.elseList]) if (list) walk(list, collect);\n const found = [...names];\n this.assigned.set(arms.list, found);\n return found;\n }\n\n // The dot a `template`/`block` invocation pushes: the pipe's value with\n // what it depends on, or, with no pipe, Go's nil data.\n private invocationDot(pipe: PipeNode | undefined, scope: Scope, ctx: EvalContext<T>): Binding {\n const { value, reads } = this.read(ctx, (r) =>\n pipe ? this.evalPipe(pipe, scope, ctx, r) : null,\n );\n return { value, marks: unionMarks(reads, ctx.marks) };\n }\n\n // [LAW:single-enforcer] Every set of reads starts here, and so does the\n // one guarantee for a pipe that throws: the error the host shows\n // instead of output may clear when a mark it read changes, and with no\n // output there is no cell to say so on, so its reads go to `decided`.\n private read(\n ctx: EvalContext<T>,\n evaluate: (reads: Set<unknown>) => unknown,\n ): { readonly value: unknown; readonly reads: Marks } {\n const reads = new Set<unknown>();\n try {\n return { value: evaluate(reads), reads };\n } catch (e) {\n ctx.decided(unionMarks(reads, ctx.marks));\n throw e;\n }\n }\n\n // -------------------------------------------------------------------\n // Expression-level dispatch (value-producing).\n // -------------------------------------------------------------------\n\n // `reads` receives the pipe's provenance: the marks its value depends\n // on. The pipe collects its own inputs — each command's arguments, the\n // value piped into it, the carrier its call returns — so a call's writes\n // depend on what its pipe consumed up to that call, not on what an\n // enclosing pipe read beside it.\n private evalPipe(\n pipe: PipeNode,\n scope: Scope,\n ctx: EvalContext<T>,\n reads: Set<unknown>,\n ): unknown {\n if (pipe.cmds.length === 0) {\n throw new EvalError(\"empty pipeline\", pipe.pos, { source: ctx.source });\n }\n const inputs = new Set<unknown>();\n let value: unknown;\n // The merge runs on every path, so a pipe that throws still hands\n // `read` what it had consumed when it failed.\n try {\n value = this.evalCommand(pipe.cmds[0] as CommandNode, scope, ctx, NO_PIPE, inputs);\n for (let i = 1; i < pipe.cmds.length; i++) {\n const next = pipe.cmds[i] as CommandNode;\n value = this.evalCommand(next, scope, ctx, { kind: \"value\", value }, inputs);\n }\n } finally {\n for (const mark of inputs) reads.add(mark);\n }\n\n // Apply variable declarations / assignments after the pipe is\n // fully evaluated; `evalRange` rebinds them per iteration.\n for (const decl of pipe.decls) {\n this.bind(scope, decl, pipe.isAssign, { value, marks: unionMarks(inputs, ctx.marks) }, ctx);\n }\n return value;\n }\n\n // [LAW:single-enforcer] The one place a decl binds: `:=` declares in\n // `scope`'s own frame, `=` overwrites the nearest frame that declared\n // the name and refuses a name no frame declared.\n private bind(\n scope: Scope,\n decl: VariableNode,\n isAssign: boolean,\n binding: Binding,\n ctx: EvalContext<T>,\n ): void {\n const name = decl.idents[0] ?? \"$\";\n if (!isAssign) {\n declareVar(scope, name, binding);\n } else if (!assignVar(scope, name, binding)) {\n throw undefinedVariable(name, decl.pos, ctx);\n }\n }\n\n private evalCommand(\n cmd: CommandNode,\n scope: Scope,\n ctx: EvalContext<T>,\n piped: Piped,\n reads: Set<unknown>,\n ): unknown {\n if (cmd.args.length === 0) {\n throw new EvalError(\"empty command\", cmd.pos, { source: ctx.source });\n }\n const head = cmd.args[0] as Node;\n\n if (head.type !== \"Identifier\") {\n if (cmd.args.length > 1) {\n throw new EvalError(\n `cannot apply arguments to a ${head.type} primary; only functions take arguments`,\n cmd.pos,\n { source: ctx.source },\n );\n }\n return this.evalPrimary(head, scope, ctx, reads);\n }\n\n const fn = this.funcs[head.ident];\n if (!fn)\n throw new FuncNotFoundError(head.ident, head.pos, {\n source: ctx.source,\n available: Object.keys(this.funcs),\n });\n\n const argNodes = cmd.args.slice(1);\n\n // [LAW:dataflow-not-control-flow] One dispatch path. Lazy funcs\n // receive thunks (so they can short-circuit), eager funcs receive\n // values — that's the only difference, and it's encoded in the\n // shape of `args`, not in whether `enforceArgTypes` runs. Lazy\n // funcs declare permissive slots (e.g. `\"truthy\"`) so the\n // validation is a no-op against thunks.\n const lazy = isLazy(fn);\n const args: unknown[] = argNodes.map((n) =>\n lazy ? () => this.evalPrimary(n, scope, ctx, reads) : this.evalPrimary(n, scope, ctx, reads),\n );\n // [LAW:dataflow-not-control-flow] The discriminator drives whether\n // the pipe value is appended; `undefined` flows through as a real\n // value when present, instead of colliding with \"no pipe\".\n if (piped.kind === \"value\") {\n const v = piped.value;\n args.push(lazy ? () => v : v);\n }\n\n return this.invoke(head.ident, fn, args, cmd.pos, ctx, reads);\n }\n\n // [LAW:single-enforcer] Every call of a registered function — a command\n // head or a bare identifier operand — crosses the gate and has its body's\n // error reported at the call site here, and nowhere else.\n private invoke(\n name: string,\n fn: TemplateFunc,\n args: unknown[],\n pos: Pos,\n ctx: EvalContext<T>,\n reads: Set<unknown>,\n ): unknown {\n try {\n enforceArgTypes(\n name,\n fn,\n args,\n pos,\n ctx.source,\n this.toString,\n this.fromString as (s: string) => unknown,\n this.isT,\n );\n } catch (e) {\n // The gate's own errors are positioned already; a failure it meets\n // while probing (a cyclic structure) is reported at the call as Go\n // reports a function's error.\n if (e instanceof TemplateError) throw e;\n throw new EvalError(`error calling ${name}: ${errorText(e)}`, pos, {\n source: ctx.source,\n cause: e,\n });\n }\n // [LAW:single-enforcer] One cast at the dispatch site. `TemplateFunc.fn`\n // declares `(...args: never[]) => unknown` so consumer impls can narrow\n // their parameter types; we erase that here, having already validated\n // the runtime types via `enforceArgTypes`.\n let result: unknown;\n try {\n // [LAW:single-enforcer] A `marked` carrier is unwrapped here and only\n // here — returned or thrown — so no template value is ever one.\n // [LAW:dataflow-not-control-flow] The gate and the error path below\n // are the same for every call; `include` differs only in which body\n // runs, because its body is a render the evaluator owns.\n const kind = includeKind(fn);\n result = readCarrier(\n kind !== undefined\n ? this.include(kind, name, args[0] as string, args[1], pos, ctx, reads)\n : (fn.fn as (...a: unknown[]) => unknown)(...args),\n reads,\n );\n } catch (thrown) {\n // A func whose failure depends on a marked value throws\n // `marked(error, …)`: the error may clear when the mark changes, and\n // the enclosing `read` reports it.\n const e = readCarrier(thrown, reads);\n // [LAW:single-enforcer] The dispatch site is the *one* place that\n // owns call-site context (pos, source). Funcs that validate nested\n // structure (e.g. list elements, alternating variadic positions)\n // throw TypeMismatchError without pos info; we re-emit with the\n // call-site pos so the snippet points at the failing call.\n if (e instanceof TypeMismatchError) {\n throw new TypeMismatchError(e.funcName, e.argIndex, e.expected, e.receivedSummary, pos, {\n source: ctx.source,\n });\n }\n if (e instanceof FailError) {\n throw new FailError(e.message, pos, { source: ctx.source, cause: e.cause });\n }\n if (e instanceof TemplateError) throw e;\n // Go reports a function's own error as `error calling <name>: <err>`\n // at the call site; the body's error rides along as the cause.\n throw new EvalError(`error calling ${name}: ${errorText(e)}`, pos, {\n source: ctx.source,\n cause: e,\n });\n }\n // Where a write lands escapes the engine — into an object read later,\n // into a fragment already emitted, into the host's data for the next\n // evaluation — so the marks it stored are reported now, on the channel\n // that needs no cell.\n // A snapshot: the command's set keeps growing after this call.\n if (fn.writes === true) ctx.decided(new Set([...reads, ...ctx.marks]));\n return result;\n }\n\n // A carrier is unwrapped only as a func's own return. One nested inside\n // a returned value is not read there; a func that later returns it alone\n // (`index`, `get`) reads it with its marks, so its value never reaches\n // output without them. Where a template operand reaches one directly\n // (`(box).c`) the likely mistake is named rather than printed.\n private evalPrimary(node: Node, scope: Scope, ctx: EvalContext<T>, reads: Set<unknown>): unknown {\n const value = this.evalOperand(node, scope, ctx, reads);\n if (value instanceof Marked) {\n throw new EvalError(\n \"a marked() value reached the template from inside a func's return; \" +\n \"return marked(...) itself, not a structure containing one\",\n node.pos,\n { source: ctx.source },\n );\n }\n return value;\n }\n\n private evalOperand(node: Node, scope: Scope, ctx: EvalContext<T>, reads: Set<unknown>): unknown {\n switch (node.type) {\n case \"Dot\":\n return this.readDot(scope, reads);\n case \"Nil\":\n return null;\n case \"Bool\":\n return node.value;\n case \"Number\":\n return numberValue(node);\n case \"String\":\n return node.value;\n case \"Field\":\n return this.resolveFieldChain(this.readDot(scope, reads), node.idents, node.pos, ctx);\n case \"Variable\":\n return this.resolveVariable(node.idents, scope, node.pos, ctx, reads);\n case \"Identifier\": {\n const fn = this.funcs[node.ident];\n if (!fn)\n throw new FuncNotFoundError(node.ident, node.pos, {\n source: ctx.source,\n available: Object.keys(this.funcs),\n });\n return this.invoke(node.ident, fn, [], node.pos, ctx, reads);\n }\n case \"Chain\":\n return this.resolveFieldChain(\n this.evalPrimary(node.node, scope, ctx, reads),\n node.fields,\n node.pos,\n ctx,\n );\n case \"Pipe\":\n return this.evalPipe(node, scope, ctx, reads);\n default:\n throw new EvalError(`cannot evaluate ${node.type} as a value`, node.pos, {\n source: ctx.source,\n });\n }\n }\n\n // -------------------------------------------------------------------\n // Field chains and variables.\n // -------------------------------------------------------------------\n\n private resolveFieldChain(\n receiver: unknown,\n idents: readonly string[],\n pos: Pos,\n ctx: EvalContext<T>,\n ): unknown {\n const result = walkFieldChain(receiver, idents);\n if (result !== MISSING) return result;\n // [LAW:dataflow-not-control-flow] Single gate, three productions.\n // The policy value (a discriminator already validated by the\n // EngineConfig type) drives which production runs — no checks\n // scattered across accessors. `\"default\"` and `\"zero\"` collapse to\n // the same JS-observable behavior because JS lacks the static\n // value-type info Go's `reflect.New(elemType).Elem()` consumes; the\n // option is accepted for API parity (see MissingKeyOption JSDoc).\n if (this.missingKey === \"error\") {\n throw new MissingFieldError(idents, pos, { source: ctx.source });\n }\n return undefined;\n }\n\n private resolveVariable(\n idents: readonly string[],\n scope: Scope,\n pos: Pos,\n ctx: EvalContext<T>,\n reads: Set<unknown>,\n ): unknown {\n const head = idents[0] ?? \"$\";\n const binding = lookupVar(scope, head);\n if (binding === undefined) throw undefinedVariable(head, pos, ctx);\n for (const mark of binding.marks) reads.add(mark);\n const tail = idents.slice(1);\n return tail.length === 0\n ? binding.value\n : this.resolveFieldChain(binding.value, tail, pos, ctx);\n }\n\n private readDot(scope: Scope, reads: Set<unknown>): unknown {\n for (const mark of scope.dot.marks) reads.add(mark);\n return scope.dot.value;\n }\n\n // -------------------------------------------------------------------\n // Output stream.\n // -------------------------------------------------------------------\n\n private emitValue(value: unknown, pos: Pos, ctx: EvalContext<T>, marks: Marks): void {\n if (isCapturedText(value)) {\n const fragments = this.captures.get(value);\n if (!fragments) {\n throw new EvalError(\"cannot emit fragments captured by a different engine\", pos, {\n source: ctx.source,\n });\n }\n for (const fragment of fragments) ctx.emit(fragment, marks);\n return;\n }\n ctx.emit(this.lift(value, pos, ctx.source), marks);\n }\n\n // The fragment an action's value becomes on the output stream.\n private lift(value: unknown, pos: Pos, source: string | undefined): T {\n // Matches Go's text/template, which prints `<no value>` for a nil\n // pipeline rather than skipping the emit.\n if (value === null || value === undefined) return this.fromString(\"<no value>\");\n if (typeof value === \"string\") return this.fromString(value);\n if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n return this.fromString(String(value));\n }\n // A T is pushed as itself; anything else prints as Go's\n // `fmt.Sprintf(\"%v\", v)` would (`[a b c]`, `map[k:v]`), which keeps the\n // conformance corpus byte-equal.\n if (this.isT(value)) return value as T;\n try {\n return this.fromString(formatV(value, this.toString, this.isT));\n } catch (err) {\n // Every failure to print — a refusal, a T with no flattener, a\n // cyclic structure — is reported at the action.\n const message =\n err instanceof UnprintableError ? err.message : `cannot print: ${errorText(err)}`;\n throw new EvalError(message, pos, { source, cause: err });\n }\n }\n}\n\n// [LAW:one-source-of-truth] The engine's default `isT`, shared by the\n// constructor and the standalone `enforceArgTypes`, so the output stream and\n// the `\"T\"` ArgType gate cannot disagree about what a T is by default.\nexport const DEFAULT_IS_T: IsT = (v) => typeof v === \"string\";\n\n// ---------------------------------------------------------------------------\n// Convenience constructor matching the future public-API shape (.api.1).\n// ---------------------------------------------------------------------------\n\nexport function createEngine<T>(config: EngineConfig<T>): Engine<T> {\n return new Engine(config);\n}\n\n// ---------------------------------------------------------------------------\n// No-silent-flatten guard.\n//\n// [LAW:single-enforcer] This is the *one* place where argument types\n// are validated against runtime values. Every function call routes\n// through here.\n// ---------------------------------------------------------------------------\n\n// Exported for the deep-import universal-property harness (see\n// `test/conformance/no-silent-flatten-universal.test.ts`). Not part of\n// the public stability surface — `src/index.ts` does not re-export it.\n//\n// `toString` is optional so the harness (and any other deep-import\n// caller) keeps compiling unchanged. When omitted, the default\n// stringifier is used; that only affects `\"stringifiable\"` slots, where\n// a T then follows `defaultToString` — a string flattens, any other T is\n// refused. The print family and the escapers declare those slots, so a\n// deep-import caller passing no `toString` is probing a stricter engine\n// than one a consumer configured with its own.\nexport function enforceArgTypes(\n funcName: string,\n spec: ArgSpec,\n values: unknown[],\n pos: Pos,\n src: string | undefined,\n toString: (value: unknown) => string = defaultToString,\n fromString: (s: string) => unknown = defaultFromString,\n isT: IsT = DEFAULT_IS_T,\n): void {\n const { argTypes, arity } = spec;\n // [LAW:parse-dont-validate] The count check is the first leg of this\n // checkpoint and it fails loudly: a call whose argument count the\n // declared arity does not accept never reaches the slot loop, and\n // never reaches the body. Everything below this line — and every\n // func body downstream of it — may assume `values.length` is one the\n // signature admits, so nothing inland counts arguments again.\n //\n // It runs *before* the slot loop deliberately. Too few arguments\n // shifts the remaining ones into the wrong slots, so checking types\n // first reports a missing argument as a type error: `substr \"a\"`\n // used to complain that a string flowed into an integer slot, which\n // is confidently wrong about which mistake the author made.\n const accepted = acceptedArgCount(argTypes, arity);\n if (values.length < accepted.minimum || values.length > accepted.maximum) {\n throw new ArgCountError(funcName, accepted, values.length, pos, { source: src });\n }\n // [LAW:dataflow-not-control-flow] No short-circuit. The shape of work\n // is fixed: validate every positional value against its declared\n // type. Variability lives in `argTypes` (use intent-named kinds like\n // `\"value\"` for genuinely heterogeneous slots), never in whether\n // validation runs.\n //\n // [LAW:single-enforcer] Slot lookup is a single function — the\n // variadic-overflow rule (trailing-repeat, modulo cycle when the\n // arity is `\"alternating\"`) lives here once, not duplicated at the\n // loop body. See template-laws-3gt.3 for the alternation motivation\n // (`dict`'s string/value kv pairing).\n const lookup = makeSlotLookup(argTypes, arity);\n let firstOrdered = -1;\n let firstComparable = -1;\n for (let i = 0; i < values.length; i++) {\n const declared = lookup(i);\n const value = values[i];\n const refusal = refusalOf(declared, value, toString, isT);\n if (refusal !== undefined) {\n // An integer slot refusing a number is Go's `expected integer`\n // refusal, and says so with the value; every other refusal is a\n // kind mismatch.\n if (\n (declared === \"int\" || declared === \"truncating-int\") &&\n (typeof value === \"number\" || typeof value === \"bigint\")\n ) {\n throw new NotIntegerError(funcName, i + 1, value, pos, { source: src });\n }\n throw new TypeMismatchError(funcName, i + 1, humanArgType(declared), refusal, pos, {\n source: src,\n });\n }\n // [LAW:single-enforcer] The lift lives at the gate, never in func\n // bodies — bodies of \"liftable\" slots see T, full stop. Mirrors the\n // T→string direction owned by `engine.toString` (used by\n // `\"stringifiable\"`); this is the string→T direction owned by\n // `engine.fromString`. Probe-only matchers stay pure; this gate\n // mutation is the one place a typed boundary actually rewrites.\n if (declared === \"liftable\" && typeof value === \"string\") {\n values[i] = fromString(value);\n }\n // [LAW:single-enforcer] Numeric carrier normalization lives at the\n // gate so bodies receive `number`, never `number | bigint`. Mirrors\n // the \"liftable\" lift above: matcher proves membership, gate\n // mutates to the canonical carrier. Bodies of \"int\"/\"float\" slots\n // can rely on `typeof value === \"number\"`. Added by epic\n // template-variance-num-carrier-hfv.1; consumers migrated in .2/.3;\n // the transitional \"number\" kind was retired in .4 so this gate is\n // the only normalization site.\n if (declared === \"truncating-int\") {\n values[i] = Math.trunc(Number(value));\n } else if (declared === \"int\" || declared === \"float\") {\n values[i] = Number(value);\n }\n // [LAW:single-enforcer] The cross-slot ordering rule lives here,\n // alongside the per-slot type rule, so \"what counts as a valid\n // comparison\" has a single enforcer. Each \"ordered\" slot must\n // share a kind with the first \"ordered\" slot in the same call,\n // with number↔bigint bridged.\n if (declared === \"ordered\") {\n if (firstOrdered === -1) {\n firstOrdered = i;\n } else if (!sameOrderedKind(values[firstOrdered], value)) {\n throw new TypeMismatchError(\n funcName,\n i + 1,\n `${humanArgType(\"ordered\")} of the same kind as ${typeNameOf(values[firstOrdered])}`,\n typeNameOf(value),\n pos,\n { source: src },\n );\n }\n }\n // [LAW:single-enforcer] Same-kind rule for \"comparable\" — Go's\n // `text/template` errors on `eq \"foo\" 1`. number↔bigint bridged;\n // nil acts as a wildcard so `eq .field nil` works regardless of\n // .field's kind.\n if (declared === \"comparable\") {\n if (firstComparable === -1) {\n firstComparable = i;\n } else if (!sameComparableKind(values[firstComparable], value)) {\n throw new TypeMismatchError(\n funcName,\n i + 1,\n `${humanArgType(\"comparable\")} of the same kind as ${typeNameOf(values[firstComparable])}`,\n typeNameOf(value),\n pos,\n { source: src },\n );\n }\n }\n }\n}\n\n// The counts a declaration accepts. Sibling projection to\n// `makeSlotLookup` below: both read the same `Arity` union, this one\n// for how many arguments are legal, that one for what each is. Neither\n// duplicates the other's rule.\n//\n// [LAW:one-source-of-truth] Every number here is derived. `\"exact\"`\n// accepts exactly as many arguments as it declares slots; `\"variadic\"`\n// requires all but the repeating one, which is Go's own gate for a\n// variadic signature; only `\"alternating\"` supplies a number, because\n// there `argTypes` is a cycle length and carries no count. Storing a\n// minimum on the other two kinds would be a second copy of\n// `argTypes.length`, and the copy is what drifts.\n//\n// No `Math.max(0, …)` floor is needed for the `\"variadic\"` subtraction:\n// a variadic registration declaring no slots is rejected at construct\n// time by `validateArgSpecs`, so `argTypes.length` is at least 1 here.\nfunction acceptedArgCount(argTypes: readonly ArgType[], arity: Arity): ArgCount {\n switch (arity.kind) {\n case \"exact\":\n return { minimum: argTypes.length, maximum: argTypes.length };\n case \"variadic\":\n return { minimum: argTypes.length - 1, maximum: Infinity };\n case \"alternating\":\n return { minimum: arity.minimum, maximum: Infinity };\n }\n}\n\n// [LAW:dataflow-not-control-flow] The overflow rule is picked once per\n// call as an index→slot map, so the loop in `enforceArgTypes` has the\n// same shape for every func — no per-iteration branch on the kind, and\n// none inside an arm either: `\"variadic\"` clamps to its trailing slot\n// rather than testing for the end of the declared ones.\n//\n// [LAW:one-type-per-behavior] One arm per `Arity` kind, because the\n// three kinds *are* the three slot-lookup rules.\n//\n// Every read is total on an upstream guarantee, which is why none is\n// guarded here: `\"exact\"` is never asked for a slot past the end, since\n// the count check in `enforceArgTypes` pinned `values.length ===\n// argTypes.length`; `\"variadic\"` and `\"alternating\"` always have a slot\n// to index, since `validateArgSpecs` rejects either kind with none.\nfunction makeSlotLookup(argTypes: readonly ArgType[], arity: Arity): (i: number) => ArgType {\n const len = argTypes.length;\n switch (arity.kind) {\n case \"exact\":\n return (i) => argTypes[i] as ArgType;\n case \"variadic\":\n return (i) => argTypes[Math.min(i, len - 1)] as ArgType;\n case \"alternating\":\n return (i) => argTypes[i % len] as ArgType;\n }\n}\n\nfunction matchesArgType(\n declared: Exclude<ArgType, \"stringifiable\">,\n value: unknown,\n isT: IsT,\n): boolean {\n switch (declared) {\n case \"truthy\":\n case \"reflective\":\n case \"value\":\n // [LAW:dataflow-not-control-flow] Permissive matcher; the\n // *label* carries reader-facing intent so a future grep can\n // distinguish \"we accept anything because we inspect the type\"\n // from \"we accept anything because we run truthiness\"\n // from \"any escape-hatch leftover\". Migration target for .8.\n return true;\n case \"string\":\n return typeof value === \"string\";\n case \"int\":\n // [LAW:types-are-the-program] Strongest true theorem for an \"int\"\n // slot: the value is a safe integer, whichever carrier holds it.\n // `Number.isSafeInteger` refuses NaN, Infinity, fractionals, and\n // integers past 2^53 in one predicate — the same bound the bigint\n // arm holds, since past it `Number()` silently corrupts the value.\n return (\n (typeof value === \"number\" && Number.isSafeInteger(value)) ||\n (typeof value === \"bigint\" && Number.isSafeInteger(Number(value)))\n );\n case \"truncating-int\":\n // [LAW:types-are-the-program] sprig's cast admits a fractional and\n // truncates it, so this slot admits every finite number; NaN and\n // Infinity have no integer interpretation (`Math.trunc(NaN)` is\n // NaN) and are refused like \"int\" refuses them.\n return (\n (typeof value === \"number\" && Number.isFinite(value)) ||\n (typeof value === \"bigint\" && Number.isSafeInteger(Number(value)))\n );\n case \"float\":\n // [LAW:types-are-the-program] \"float\" mirrors IEEE 754: NaN and\n // ±Infinity are legitimate float values (Go's float64 has them\n // too), so the matcher accepts them — they survive gate\n // normalization unchanged. The only rejected bigint shape is one\n // whose `Number()` conversion overflows to Infinity, because\n // that's a magnitude failure, not a float-precision tradeoff.\n // Bigints in the merely-precision-losing range (e.g. 2n**100n)\n // are accepted; float never promised exact preservation.\n return (\n typeof value === \"number\" || (typeof value === \"bigint\" && Number.isFinite(Number(value)))\n );\n case \"bool\":\n return typeof value === \"boolean\";\n case \"ordered\":\n return (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\"\n );\n case \"T\":\n // [LAW:single-enforcer] What the engine's output stream calls a T.\n return isT(value);\n case \"list\":\n // Go-parity: a string is not a list to sprig, even though it is\n // iterable. Excluding string here forces consumers to spell out\n // string-vs-list intent at the slot.\n return Array.isArray(value);\n case \"dict\":\n // Plain object only. Maps, arrays, Sets, class instances, and\n // null are not \"dicts\" — the dict slot expects bag-of-keys\n // semantics with `Object.keys` / `Record<string, unknown>` shape.\n return isPlainObject(value);\n case \"sized\":\n return (\n typeof value === \"string\" ||\n Array.isArray(value) ||\n value instanceof Map ||\n value instanceof Set ||\n isPlainObject(value)\n );\n case \"comparable\":\n // [LAW:one-source-of-truth] Membership is \"anything JSON-shaped\":\n // ordered primitives, nil, arrays, Maps, Sets, plain objects.\n // Functions and symbols are rejected. The cross-slot same-kind\n // rule (with nil-as-wildcard) is enforced in `enforceArgTypes`\n // alongside the per-slot match.\n return (\n value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\" ||\n Array.isArray(value) ||\n value instanceof Map ||\n value instanceof Set ||\n isPlainObject(value)\n );\n case \"callable\":\n return typeof value === \"function\";\n case \"collection\":\n // Receiver shape for `index`. Sets and class instances are\n // rejected (Sets aren't keyed; class instances aren't sprig\n // dicts). Nil is rejected so the body never has to defend.\n return (\n typeof value === \"string\" ||\n Array.isArray(value) ||\n value instanceof Map ||\n isPlainObject(value)\n );\n case \"index-key\":\n // Key shape for `index`. The body decides which collection kind\n // a key actually fits (array wants integer; object wants string;\n // Map's get accepts the key as-is for whatever it stores).\n return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"bigint\";\n case \"sliceable\":\n // Receiver shape for `slice`: string or array. Maps/dicts/Sets\n // are not sliceable in Go's `text/template`.\n return typeof value === \"string\" || Array.isArray(value);\n case \"liftable\":\n // Mirror of \"stringifiable\" in the opposite direction: a T, or a\n // string `enforceArgTypes` lifts once through `engine.fromString`.\n // [LAW:single-enforcer] The T half is the same predicate the \"T\" slot reads.\n return typeof value === \"string\" || isT(value);\n case \"serializable\":\n // Runtime-validate JSON encodability. `JSON.stringify` returns\n // `undefined` for functions/symbols and throws on circular refs;\n // either result fails the gate.\n return isJsonSerializable(value);\n default: {\n // [LAW:types-are-the-program] Explicit exhaustiveness check.\n // The `never` assignment is what makes adding a future ArgType\n // — or, equivalently, reintroducing the retired `\"number\"` —\n // a tsc error: a fresh union member is no longer assignable to\n // `never`, so the editor sees the missed case at compile time.\n // The `throw` is unreachable from an engine: a declaration that\n // casts past `ArgType` is rejected at construct time by\n // `validateArgSpecs`, so no template can drive an unknown kind\n // here (template-arity-n2j.7ve moved that check off the render\n // path, where it escaped as a raw, positionless `Error`). It\n // stays as the runtime floor for a direct deep-import caller,\n // which is the only remaining way in.\n const _exhaustive: never = declared;\n throw new Error(`invalid ArgType: ${String(_exhaustive)}`);\n }\n }\n}\n\n// Default lifter, used only when `enforceArgTypes` is called outside\n// the engine's dispatch path (e.g. tests exercising the gate\n// directly). Real engine calls always thread `this.fromString` from\n// `EngineConfig`, which is mandatory in the public API. Identity\n// keeps the gate honest in the synthetic case: a string literally\n// flows through unchanged, so `T = string` engines never need to\n// know about `\"liftable\"` for the gate to behave correctly.\nfunction defaultFromString(s: string): unknown {\n return s;\n}\n\n// Default flattener for engines that don't supply `toString`. It sees\n// only values `isT` claims: a string flows through unchanged (the\n// `T = string` happy path), a scalar or nil an `isT` claimed gets its\n// natural form, and any other T is the \"typed-T without consumer\n// flattener\" case the README contract is about, and throws a\n// TypeMismatchError. `evalCommand` wraps and re-emits with\n// the proper call-site pos (see [LAW:single-enforcer] above).\nfunction defaultToString(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined) return \"<nil>\";\n if (typeof value === \"number\" || typeof value === \"bigint\" || typeof value === \"boolean\") {\n return String(value);\n }\n throw new TypeMismatchError(\n \"<engine.toString>\",\n 1,\n \"string (or a consumer-supplied toString that flattens T)\",\n typeNameOf(value),\n { line: 0, column: 0, offset: 0 },\n );\n}\n\nfunction isJsonSerializable(value: unknown): boolean {\n try {\n const encoded = JSON.stringify(value);\n // `JSON.stringify` returns `undefined` for top-level functions /\n // symbols / undefined; treat that as \"not serializable\".\n return encoded !== undefined;\n } catch {\n // Circular references or BigInt land here.\n return false;\n }\n}\n\n// Same-kind check for two values declared `ordered`. Number and bigint\n// are bridged because compare() handles them as one numeric kind.\nfunction sameOrderedKind(a: unknown, b: unknown): boolean {\n if (typeof a === typeof b) return true;\n if (typeof a === \"number\" && typeof b === \"bigint\") return true;\n if (typeof a === \"bigint\" && typeof b === \"number\") return true;\n return false;\n}\n\n// Same-kind check for two \"comparable\" slots. Kinds: nil | string |\n// number (number/bigint bridged) | boolean | array | map | set |\n// object. nil is a wildcard, matching any kind.\nfunction sameComparableKind(a: unknown, b: unknown): boolean {\n const ka = comparableKind(a);\n const kb = comparableKind(b);\n if (ka === \"nil\" || kb === \"nil\") return true;\n return ka === kb;\n}\n\nfunction comparableKind(v: unknown): string {\n if (v === null || v === undefined) return \"nil\";\n if (typeof v === \"string\") return \"string\";\n if (typeof v === \"number\" || typeof v === \"bigint\") return \"number\";\n if (typeof v === \"boolean\") return \"boolean\";\n if (Array.isArray(v)) return \"array\";\n if (v instanceof Map) return \"map\";\n if (v instanceof Set) return \"set\";\n return \"object\";\n}\n\nfunction humanArgType(t: ArgType): string {\n switch (t) {\n case \"int\":\n return \"integer (safe-integer number or bigint)\";\n case \"truncating-int\":\n return \"integer (finite number, truncated toward zero, or safe-integer bigint)\";\n case \"float\":\n return \"float (number, including NaN/Infinity, or finite-convertible bigint)\";\n case \"T\":\n return \"T (a value the engine's isT accepts)\";\n case \"ordered\":\n return \"orderable primitive\";\n case \"list\":\n return \"list\";\n case \"dict\":\n return \"dict (plain object)\";\n case \"sized\":\n return \"sized value (string, list, map, set, or dict)\";\n case \"comparable\":\n return \"comparable value (orderable primitive, nil, list, dict, Map, or Set)\";\n case \"stringifiable\":\n 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)\";\n case \"liftable\":\n return \"liftable value (T or string, the latter lifted via the engine's fromString)\";\n case \"callable\":\n return \"callable (function value)\";\n case \"collection\":\n return \"collection (string, array, Map, or dict)\";\n case \"index-key\":\n return \"index key (number, bigint, or string)\";\n case \"sliceable\":\n return \"sliceable value (string or array)\";\n case \"serializable\":\n return \"JSON-serializable value\";\n case \"truthy\":\n case \"reflective\":\n case \"value\":\n case \"string\":\n case \"bool\":\n return t;\n default: {\n // [LAW:types-are-the-program] Same explicit exhaustiveness arm\n // as `matchesArgType` — see the rationale there. Mirrors it\n // here so the retirement-of-\"number\" guardrail is symmetric:\n // both the gate's membership predicate and its human-readable\n // labeller refuse to silently handle an unknown kind.\n const _exhaustive: never = t;\n throw new Error(`invalid ArgType: ${String(_exhaustive)}`);\n }\n }\n}\n\n// [LAW:single-enforcer] The frame every `if`, `with` and `range` opens,\n// spanning its pipe, its body and its else, so a `:=` anywhere in the\n// construct ends with it, as Go marks and pops its variable stack.\nfunction constructFrame(scope: Scope): Scope {\n return pushScope(scope, scope.dot);\n}\n\n// [LAW:single-enforcer] Reading and assigning an undeclared variable\n// fail alike, with Go's text/template exec.go message.\nfunction undefinedVariable(name: string, pos: Pos, ctx: { source: string | undefined }): EvalError {\n return new EvalError(`undefined variable: ${name}`, pos, { source: ctx.source });\n}\n\n// The template error a chain of `cause`s started from: where it went wrong.\nfunction innermost(e: TemplateError): TemplateError {\n return e.cause instanceof TemplateError ? innermost(e.cause) : e;\n}\n\n// The host ran out of stack in the template's own frames: V8 and JSC throw\n// a RangeError, SpiderMonkey an InternalError, each naming the condition.\n// A body may throw anything; Go's `%v` of an error is its message.\nfunction errorText(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n// What a refused argument is, as the gate's TypeMismatchError names it, or\n// undefined when the argument is accepted. A \"stringifiable\" refusal names\n// what `formatV` could not print — the argument, or the argument holding\n// it — from the one probe that decided it, so `toString` runs once. Every\n// other refusal names the argument's type.\nfunction refusalOf(\n declared: ArgType,\n value: unknown,\n toString: (value: unknown) => string,\n isT: IsT,\n): string | undefined {\n if (declared === \"stringifiable\") return printRefusal(value, toString, isT)?.summary;\n return matchesArgType(declared, value, isT) ? undefined : typeNameOf(value);\n}\n\n// The flatten the \"stringifiable\" bodies perform — `formatV`, Go's `%v`,\n// which hands every T (nested included) to `engine.toString` — returning its\n// refusal. Only a refusal to print is an answer; anything else, a stack\n// overflow on a cyclic structure, surfaces as itself.\nfunction printRefusal(\n value: unknown,\n toString: (value: unknown) => string,\n isT: IsT,\n): UnprintableError | undefined {\n try {\n formatV(value, toString, isT);\n return undefined;\n } catch (err) {\n if (err instanceof UnprintableError) return err;\n throw err;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Range support — iteration helpers.\n// ---------------------------------------------------------------------------\n\n/**\n * Produce [key, value] entries for a `range` operand.\n *\n * - Arrays / typed arrays / strings: numeric index → element\n * - Maps and plain objects: entries sorted by key. Matches Go's\n * `text/template`, which sorts map keys via `internal/fmtsort`\n * before iterating — same input always produces the same byte\n * output. Strings sort lexically; numbers numerically.\n * - Sets: index → element (Go ranges over channels but we map to Set\n * for symmetry with arrays/iteration)\n * - null/undefined: empty\n */\nfunction enumerateForRange(value: unknown): readonly (readonly [unknown, unknown])[] {\n if (value === null || value === undefined) return [];\n if (Array.isArray(value)) return value.map((v, i) => [i, v] as const);\n if (typeof value === \"string\") return [...value].map((c, i) => [i, c] as const);\n if (value instanceof Map) return sortMapEntries([...value.entries()]);\n if (value instanceof Set) return [...value.values()].map((v, i) => [i, v] as const);\n if (typeof value === \"object\") {\n return sortMapEntries(Object.entries(value as Record<string, unknown>));\n }\n return [];\n}\n\n// Sort map / object entries by key to match Go's text/template\n// `fmtsort` ordering. Numbers compare numerically, strings lexically,\n// mixed kinds fall back to string-ordering of the key. The compare is\n// stable enough for byte-equality conformance against Go.\nfunction sortMapEntries(\n entries: readonly (readonly [unknown, unknown])[],\n): readonly (readonly [unknown, unknown])[] {\n return [...entries].sort((a, b) => compareMapKeys(a[0], b[0]));\n}\n\nfunction compareMapKeys(a: unknown, b: unknown): number {\n const an = typeof a === \"number\" || typeof a === \"bigint\";\n const bn = typeof b === \"number\" || typeof b === \"bigint\";\n if (an && bn) {\n const ax = typeof a === \"bigint\" ? Number(a) : (a as number);\n const bx = typeof b === \"bigint\" ? Number(b) : (b as number);\n return ax === bx ? 0 : ax < bx ? -1 : 1;\n }\n const as = String(a);\n const bs = String(b);\n return as === bs ? 0 : as < bs ? -1 : 1;\n}\n\n// ---------------------------------------------------------------------------\n// Numeric-literal helper.\n// ---------------------------------------------------------------------------\n\nfunction numberValue(n: {\n readonly intValue?: bigint;\n readonly floatValue?: number;\n readonly complexValue?: readonly [number, number];\n}): unknown {\n if (n.intValue !== undefined) {\n const bi = n.intValue;\n if (bi >= BigInt(Number.MIN_SAFE_INTEGER) && bi <= BigInt(Number.MAX_SAFE_INTEGER)) {\n return Number(bi);\n }\n return bi;\n }\n if (n.floatValue !== undefined) return n.floatValue;\n if (n.complexValue !== undefined) return n.complexValue;\n // [LAW:one-source-of-truth] The AST contract guarantees one of\n // intValue/floatValue/complexValue is set on a NumberNode. Reaching\n // here means the parser produced a NumberNode missing all three —\n // an internal invariant break, not a runtime input we should\n // silently coerce to undefined.\n throw new Error(\n \"internal: NumberNode has none of intValue/floatValue/complexValue — parser invariant violated\",\n );\n}\n","/**\n * `atoi s` — parse a base-10 integer string. Returns 0 for any\n * non-parseable input, matching Go sprig (`strconv.Atoi(s)` with the\n * error discarded). Hex/octal prefixes are *not* accepted — that's\n * what `toDecimal` is for.\n */\n\n// [LAW:single-enforcer] The `\"string\"` gate validates the kind once;\n// the body trusts it. Parse failure → 0 (Go-parity: `strconv.Atoi`\n// errors, sprig discards).\n//\n// The `Number.isSafeInteger` guard is this converter's own\n// *output-precision policy*, not a mirror of Go's int64 boundary or\n// the gate's matcher predicate:\n// - Go's `strconv.Atoi` admits decimals up to int64 max\n// (9223372036854775807). JS doubles lose integer precision past\n// `Number.MAX_SAFE_INTEGER` (2^53 - 1), so values in\n// [MAX_SAFE_INTEGER+1, int64-max] are *valid in Go* but would\n// round on the way through JS — returning them would silently\n// hand the caller a different integer than the string named.\n// Collapsing the whole range to 0 is the precision-safe choice.\n// - The \"int\" ArgType matcher holds the same safe-integer bound at\n// the gate; this guard applies it at the parse step, because\n// atoi's input is a string the gate cannot see as a number.\n// Runaway-to-Infinity collapse falls out of the same predicate as a\n// free side effect.\nexport function atoi(s: string): number {\n if (!/^[+-]?\\d+$/.test(s)) return 0;\n const n = Number.parseInt(s, 10);\n return Number.isSafeInteger(n) ? n : 0;\n}\n","/**\n * `float64 v` — coerce to a JS number. Strings parse via\n * `Number.parseFloat` (Go: `strconv.ParseFloat(s, 64)`); non-numeric\n * input collapses to 0.\n */\n\n// [LAW:dataflow-not-control-flow] Per-kind dispatch lives here once;\n// callers don't repeat the shape check.\nexport function float64(v: unknown): number {\n if (typeof v === \"number\") return v;\n if (typeof v === \"bigint\") return Number(v);\n if (typeof v === \"string\") {\n const n = Number.parseFloat(v);\n return Number.isNaN(n) ? 0 : n;\n }\n if (typeof v === \"boolean\") return v ? 1 : 0;\n return 0;\n}\n","/**\n * Internal helper — Go's `strconv.ParseInt(s, 0, 64)` auto-detect rule.\n *\n * `0x`/`0X` → hex, `0b`/`0B` → binary, `0o`/`0O` → octal,\n * leading `0` → octal, otherwise decimal.\n *\n * Returns the parsed integer string-keyed (so callers can decide\n * `Number` vs `BigInt`), or `null` for unparseable input. Empty\n * string and lone `+`/`-` are unparseable.\n */\n// [LAW:one-source-of-truth] The base-detect rule lives in one place.\n// `int` and `int64` both route through here so their string-parse\n// behavior cannot drift from each other or from Go.\nexport function parseBase0(\n s: string,\n): { sign: 1 | -1; digits: string; base: 2 | 8 | 10 | 16 } | null {\n if (s === \"\") return null;\n let sign: 1 | -1 = 1;\n let body = s;\n if (body[0] === \"+\") body = body.slice(1);\n else if (body[0] === \"-\") {\n sign = -1;\n body = body.slice(1);\n }\n if (body === \"\") return null;\n\n if (/^0x[0-9a-fA-F]+$/i.test(body)) return { sign, digits: body.slice(2), base: 16 };\n if (/^0b[01]+$/i.test(body)) return { sign, digits: body.slice(2), base: 2 };\n if (/^0o[0-7]+$/i.test(body)) return { sign, digits: body.slice(2), base: 8 };\n if (body === \"0\") return { sign, digits: \"0\", base: 10 };\n if (body[0] === \"0\") {\n // Leading 0 + more chars → octal mode. Out-of-range digit fails;\n // we mirror Go (which errors) by returning null instead of\n // silently falling back to decimal.\n if (!/^0[0-7]+$/.test(body)) return null;\n return { sign, digits: body.slice(1), base: 8 };\n }\n if (!/^[0-9]+$/.test(body)) return null;\n return { sign, digits: body, base: 10 };\n}\n","import { parseBase0 } from \"./parseBase0.js\";\n\n/**\n * `int v` — coerce to integer, truncating toward zero. Strings parse\n * with Go's `strconv.ParseInt(s, 0, 64)` rule (base auto-detect: hex\n * `0x`, octal `0`/`0o`, binary `0b`, decimal default). Anything not\n * parseable → 0.\n */\n\n// [LAW:dataflow-not-control-flow] Variability lives in *values*; the\n// shape of the dispatch (one branch per JS kind) mirrors the JS type\n// system's discriminator, not an external mode flag.\n//\n// `Number.isSafeInteger` is this converter's *output-precision\n// policy*, not the gate's input predicate (the `\"int\"` ArgType\n// matcher happens to hold the same bound on its inputs). This\n// converter accepts heterogeneous input (`\"value\"` slot — number,\n// bigint, string, boolean, anything) and produces a number, so it\n// owns precision at the output edge: a returned value is guaranteed\n// to round-trip without loss. Sources of unsafe results — finite\n// `Math.trunc(2**60)`, `Number(2n**1024n)` → Infinity,\n// `Number.parseInt` of a long-enough digit string — all collapse to\n// 0 under one predicate. Stricter than Go-sprig's int64 boundary,\n// stricter than the gate's number-branch predicate, but stricter\n// in the precision-safe direction.\nexport function int(v: unknown): number {\n if (typeof v === \"number\") {\n const n = Math.trunc(v);\n return Number.isSafeInteger(n) ? n : 0;\n }\n if (typeof v === \"bigint\") {\n const n = Number(v);\n return Number.isSafeInteger(n) ? n : 0;\n }\n if (typeof v === \"string\") {\n const parsed = parseBase0(v);\n if (parsed === null) return 0;\n const n = parsed.sign * Number.parseInt(parsed.digits, parsed.base);\n return Number.isSafeInteger(n) ? n : 0;\n }\n if (typeof v === \"boolean\") return v ? 1 : 0;\n return 0;\n}\n","import { parseBase0 } from \"./parseBase0.js\";\n\n/**\n * `int64 v` — coerce to a 64-bit integer. Returns `bigint` so the\n * full Go-`int64` precision survives the round-trip (a JS `number`\n * loses precision past 2^53).\n *\n * Shares `parseBase0`'s base-detect + sign rules with `int`, so the\n * input shape (what string forms are recognized) is the same. The\n * **carrier** differs — `int` returns a JS `number` and applies a\n * `Number.isSafeInteger` clamp on output so the returned value\n * round-trips without precision loss; `int64`'s `bigint` carrier\n * holds the full int64 range, so no clamp is needed and string\n * forms like `\"9007199254740993\"` (past 2^53) survive unchanged.\n * The divergence is intentional: the carrier *forces* the precision\n * policy at this boundary, not the other way around.\n */\n\n// [LAW:types-are-the-program] Carrier choice (number vs bigint)\n// drives the policy split. Input parsing is shared (`parseBase0`) so\n// the string-form contract cannot drift; output handling diverges\n// only at the precision boundary the carrier itself defines.\nexport function int64(v: unknown): bigint {\n if (typeof v === \"bigint\") return v;\n if (typeof v === \"number\") return BigInt(Math.trunc(v));\n if (typeof v === \"string\") {\n const parsed = parseBase0(v);\n if (parsed === null) return 0n;\n // BigInt accepts \"0x\"/\"0b\"/\"0o\" literal forms directly; rebuild\n // a literal we can hand to BigInt() to avoid re-implementing\n // arbitrary-precision parsing per base.\n const prefix =\n parsed.base === 16 ? \"0x\" : parsed.base === 2 ? \"0b\" : parsed.base === 8 ? \"0o\" : \"\";\n const n = BigInt(prefix + parsed.digits);\n return parsed.sign === -1 ? -n : n;\n }\n if (typeof v === \"boolean\") return v ? 1n : 0n;\n return 0n;\n}\n","/**\n * `toDecimal s` — parse `s` as base-8 (octal) and return the decimal\n * value. Despite the name, sprig hard-codes base 8 — see Masterminds\n * `toDecimal`: `strconv.ParseInt(fmt.Sprintf(\"%v\", v), 8, 64)`.\n *\n * Prefixes are *not* accepted (only base-8 explicit means no `0o`/`0x`\n * detection). Non-octal digits or non-string-parseable input → 0.\n *\n * Examples:\n * toDecimal \"0755\" → 493 (the \"convert octal-string to decimal\" use case)\n * toDecimal \"08\" → 0 (8 is not an octal digit; Go errors)\n * toDecimal \"0xff\" → 0 (no prefix detection at base 8)\n */\n// [LAW:one-source-of-truth] Behavior is \"parse base-8\" full stop.\n// Anyone who wants base-detect uses `int` instead; that's where the\n// auto-detect rule lives (`parseBase0`).\n//\n// The `Number.isSafeInteger` guard is this converter's\n// *output-precision policy* (same shape as `atoi.ts` — see that file\n// for the full rationale). Two distinct boundaries collapse into\n// one predicate:\n// - Octal strings whose decimal value lands in\n// [MAX_SAFE_INTEGER+1, int64-max] are valid under Go's\n// `strconv.ParseInt(..., 8, 64)` but round under JS doubles.\n// Returning them silently would hand the caller a different\n// integer than the string named — collapsed to 0 instead.\n// - Octal strings long enough to overflow `Number.parseInt` to JS\n// Infinity (which Go *would* also reject) fall out of the same\n// predicate as a free side effect.\nexport function toDecimal(s: string): number {\n if (!/^[+-]?[0-7]+$/.test(s)) return 0;\n const sign = s[0] === \"-\" ? -1 : 1;\n const body = s[0] === \"+\" || s[0] === \"-\" ? s.slice(1) : s;\n const n = sign * Number.parseInt(body, 8);\n return Number.isSafeInteger(n) ? n : 0;\n}\n","/**\n * `toRawJson v` — JSON-encode without HTML escaping. Go uses a json\n * encoder with `SetEscapeHTML(false)`; JS `JSON.stringify` does not\n * HTML-escape by default, so the function is a direct mapping.\n *\n * The undefined→\"null\" coercion matches Go's `encoding/json` (which\n * encodes untyped-nil as `null`); JS would otherwise return\n * `undefined` and break callers expecting a string.\n */\n// [LAW:single-enforcer] The \"serializable\" gate already rejects\n// functions/symbols/circular refs upstream, so the body trusts the\n// kind and only routes the encoding step.\nexport function toRawJson(value: unknown): string {\n return JSON.stringify(value) ?? \"null\";\n}\n","/**\n * Sprig conversion utilities — pair-files per epic spec.\n *\n * [LAW:single-enforcer] One module owns FuncMap registration for this\n * category. Consumers either import individual functions or spread\n * the whole map via `sprigConversions()` into their EngineConfig.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { atoi } from \"./atoi.js\";\nimport { float64 } from \"./float64.js\";\nimport { int } from \"./int.js\";\nimport { int64 } from \"./int64.js\";\nimport { toDecimal } from \"./toDecimal.js\";\nimport { toRawJson } from \"./toRawJson.js\";\n\nexport { atoi, float64, int, int64, toDecimal, toRawJson };\n\nexport function sprigConversions(): FuncMap {\n // [LAW:one-source-of-truth] Slot kinds come straight from the epic\n // spec (template-sprig-ctz.1):\n // - \"string\" — atoi/toDecimal: parse-from-string\n // - \"value\" — int/int64/float64: heterogeneous-by-\n // intent; the body is the per-kind dispatch\n // [LAW:dataflow-not-control-flow]\n // - \"serializable\" — toRawJson: gate rejects functions/symbols/\n // circular refs so the body never silently\n // emits \"null\"\n const map: FuncMap = {\n atoi: {\n fn: (s) => atoi(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"int\",\n },\n int: { fn: (v) => int(v), argTypes: [\"value\"], arity: { kind: \"exact\" }, returnType: \"int\" },\n int64: { fn: (v) => int64(v), argTypes: [\"value\"], arity: { kind: \"exact\" } },\n float64: {\n fn: (v) => float64(v),\n argTypes: [\"value\"],\n arity: { kind: \"exact\" },\n returnType: \"float\",\n },\n toDecimal: {\n fn: (s) => toDecimal(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"int\",\n },\n toRawJson: {\n fn: (v) => toRawJson(v),\n argTypes: [\"serializable\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n };\n return map;\n}\n","/**\n * Go-style duration: parsing and formatting.\n *\n * Go's `time.ParseDuration` grammar:\n * duration = [-] component+\n * component = decimal unit\n * unit = ns | us | µs | ms | s | m | h\n *\n * Values are nanoseconds internally (same as Go's time.Duration).\n *\n * [LAW:one-source-of-truth] All duration string ↔ nanoseconds\n * conversions live here. No other file does this math.\n */\n\nconst NS_PER = {\n h: 3_600_000_000_000,\n m: 60_000_000_000,\n s: 1_000_000_000,\n ms: 1_000_000,\n us: 1_000,\n µs: 1_000,\n ns: 1,\n} as const;\n\ntype Unit = keyof typeof NS_PER;\n\n/**\n * Parse a Go duration string to nanoseconds (as a float for sub-ms\n * precision). Returns `NaN` on parse failure.\n *\n * Accepts: \"0\", \"300ms\", \"1.5h\", \"2h45m\", \"-1h30m\", \"100µs\".\n */\nexport function parseDurationNs(s: string): number {\n if (s === \"0\") return 0;\n\n let negative = false;\n let rest = s;\n if (rest.startsWith(\"-\")) {\n negative = true;\n rest = rest.slice(1);\n } else if (rest.startsWith(\"+\")) {\n rest = rest.slice(1);\n }\n\n if (!rest) return NaN;\n\n let total = 0;\n // Match: decimal (possibly with `.`) followed by unit name.\n // Units sorted longest-first to avoid \"m\" matching before \"ms\".\n const UNIT_RE = /^(\\d+(?:\\.\\d+)?)(ns|µs|us|ms|[smh])/;\n while (rest.length > 0) {\n const m = UNIT_RE.exec(rest);\n if (!m) return NaN;\n const value = parseFloat(m[1] ?? \"0\");\n const unit = m[2] as Unit;\n total += value * NS_PER[unit];\n rest = rest.slice(m[0].length);\n }\n\n return negative ? -total : total;\n}\n\n/**\n * Format nanoseconds as Go's `time.Duration.String()`.\n *\n * Go's algorithm mirrors time/time.go Duration.String():\n * - Values < 1µs: \"Xns\"\n * - Values < 1ms: \"X.YYYµs\" (trailing zeros trimmed)\n * - Values < 1s: \"X.YYYms\" (trailing zeros trimmed)\n * - Values >= 1s: \"XhYmZ.WWWs\" (hours/minutes shown when non-zero;\n * intermediate zero units always shown once hours or\n * minutes appear; e.g. \"1h0m0s\", \"1m0s\")\n */\nexport function formatDurationNs(ns: number): string {\n if (ns === 0) return \"0s\";\n\n let negative = false;\n let abs = ns;\n if (abs < 0) {\n negative = true;\n abs = -abs;\n }\n\n let out: string;\n if (abs < NS_PER.us) {\n out = `${Math.floor(abs)}ns`;\n } else if (abs < NS_PER.ms) {\n out = fmtSubUnit(abs, NS_PER.us, 3, \"µs\");\n } else if (abs < NS_PER.s) {\n out = fmtSubUnit(abs, NS_PER.ms, 6, \"ms\");\n } else {\n out = fmtGeqSecond(abs);\n }\n\n return negative ? `-${out}` : out;\n}\n\n/** Format sub-second values in a given unit (µs, ms). */\nfunction fmtSubUnit(abs: number, unit: number, fracDigits: number, suffix: string): string {\n const whole = Math.floor(abs / unit);\n const frac = Math.round(abs % unit);\n if (frac === 0) return `${whole}${suffix}`;\n const fracStr = String(frac).padStart(fracDigits, \"0\").replace(/0+$/, \"\");\n return `${whole}.${fracStr}${suffix}`;\n}\n\n/** Format durations >= 1 second as Go does. */\nfunction fmtGeqSecond(abs: number): string {\n const h = Math.floor(abs / NS_PER.h);\n abs -= h * NS_PER.h;\n const m = Math.floor(abs / NS_PER.m);\n abs -= m * NS_PER.m;\n // abs is now nanoseconds in the current second slot (0..59_999_999_999)\n const s = Math.floor(abs / NS_PER.s);\n const nsFrac = abs - s * NS_PER.s;\n\n // Format seconds, optionally with nanosecond fraction.\n const secStr =\n nsFrac === 0\n ? `${s}s`\n : `${s}.${String(Math.round(nsFrac)).padStart(9, \"0\").replace(/0+$/, \"\")}s`;\n\n if (h > 0) return `${h}h${m}m${secStr}`;\n if (m > 0) return `${m}m${secStr}`;\n return secStr;\n}\n\n/** Format nanoseconds as a duration, rounding to the largest non-zero unit. */\nexport function roundDurationNs(ns: number): string {\n const abs = Math.abs(ns);\n\n // Round to the appropriate precision level.\n let rounded: number;\n if (abs >= NS_PER.h) {\n rounded = Math.round(ns / NS_PER.h) * NS_PER.h;\n } else if (abs >= NS_PER.m) {\n rounded = Math.round(ns / NS_PER.m) * NS_PER.m;\n } else if (abs >= NS_PER.s) {\n rounded = Math.round(ns / NS_PER.s) * NS_PER.s;\n } else if (abs >= NS_PER.ms) {\n rounded = Math.round(ns / NS_PER.ms) * NS_PER.ms;\n } else if (abs >= NS_PER.us) {\n rounded = Math.round(ns / NS_PER.us) * NS_PER.us;\n } else {\n rounded = ns;\n }\n\n return formatDurationNs(rounded);\n}\n\n/** Convert integer seconds to nanoseconds. */\nexport function secondsToNs(s: number): number {\n return s * NS_PER.s;\n}\n","/**\n * Normalise the heterogeneous `t` argument accepted by date functions.\n *\n * Go sprig's `dateInZone` accepts: `time.Time`, `int64`, `int`, `int32`.\n * JS side: `Date`, `number` (Unix seconds), `bigint` (Unix seconds),\n * `string` (ISO / Go-layout string).\n *\n * When `t` is already a `Date`, it is returned unchanged.\n * When `t` is a number or bigint, it is treated as Unix seconds (matching\n * Go's `time.Unix(n, 0)` — NOT milliseconds).\n * When `t` is a string, it is parsed by `Date.parse` as a fallback.\n *\n * [LAW:single-enforcer] One place owns `t → Date` normalisation.\n * All date functions call this; none duplicate the logic.\n */\nexport function resolveDate(t: unknown): Date {\n if (t instanceof Date) return t;\n if (typeof t === \"bigint\") return new Date(Number(t) * 1000);\n if (typeof t === \"number\") return new Date(t * 1000);\n if (typeof t === \"string\") {\n const parsed = new Date(t);\n if (!Number.isNaN(parsed.getTime())) return parsed;\n throw new Error(`sprig: cannot parse date value ${JSON.stringify(t)}`);\n }\n throw new Error(`sprig: unsupported date type: ${typeof t}`);\n}\n","import type { Clock } from \"./_clock.js\";\nimport { formatDurationNs } from \"./_duration.js\";\nimport { resolveDate } from \"./_resolve.js\";\n\n/**\n * `ago t` — Go-style duration since `t`.\n * Mirrors Go sprig: `time.Since(t).Round(time.Second).String()`.\n */\nexport function ago(t: unknown, clock: Clock): string {\n const ms = clock().getTime() - resolveDate(t).getTime();\n // Round to nearest second then format.\n const ns = Math.round(ms / 1000) * 1_000_000_000;\n return formatDurationNs(ns);\n}\n","/**\n * Go reference-time layout tokenizer and formatter.\n *\n * Go's reference time: `Mon Jan 2 15:04:05 MST 2006`\n * Each component uses a unique value so the tokenizer can identify it\n * positionally without ambiguity markers.\n *\n * Strategy: greedy left-to-right scan — try each known token at the\n * current position (longest first); pass literal characters through.\n * Round-trips Go's exact output for every tested layout.\n *\n * [LAW:one-source-of-truth] Format-token definitions live here only;\n * the parser in `_parse.ts` imports the same token list inverted.\n */\n\nimport type { ZoneParts } from \"./_zone.js\";\n\n// ---------------------------------------------------------------------------\n// Constant tables\n// ---------------------------------------------------------------------------\n\nconst MONTHS_LONG = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\nconst MONTHS_SHORT = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n];\n\nconst WEEKDAYS_LONG = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n];\n\nconst WEEKDAYS_SHORT = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n\n// ---------------------------------------------------------------------------\n// Formatting helpers\n// ---------------------------------------------------------------------------\n\nfunction pad2(n: number): string {\n return n < 10 ? `0${n}` : String(n);\n}\n\nfunction pad3(n: number): string {\n return n < 10 ? `00${n}` : n < 100 ? `0${n}` : String(n);\n}\n\nfunction spacePad2(n: number): string {\n return n < 10 ? ` ${n}` : String(n);\n}\n\n// Go prints an offset in whole minutes truncated toward zero, signed by\n// those minutes (so -30s prints \"+0000\"), and writes \"Z\" only when the exact\n// offset in seconds is zero.\nfunction offsetParts(offsetSeconds: number): { sign: string; hh: string; mm: string } {\n const minutes = Math.trunc(offsetSeconds / 60);\n const abs = Math.abs(minutes);\n return {\n sign: minutes < 0 ? \"-\" : \"+\",\n hh: pad2(Math.floor(abs / 60)),\n mm: pad2(abs % 60),\n };\n}\n\n/** ±hhmm (no colon). E.g. \"+0500\", \"-0500\", \"+0000\". */\nfunction fmtOffset(offsetSeconds: number): string {\n const { sign, hh, mm } = offsetParts(offsetSeconds);\n return `${sign}${hh}${mm}`;\n}\n\n/** ±hh:mm (with colon). E.g. \"+05:00\", \"-05:00\", \"+00:00\". */\nfunction fmtOffsetColon(offsetSeconds: number): string {\n const { sign, hh, mm } = offsetParts(offsetSeconds);\n return `${sign}${hh}:${mm}`;\n}\n\n/** ±hh only. */\nfunction fmtOffsetHour(offsetSeconds: number): string {\n const { sign, hh } = offsetParts(offsetSeconds);\n return `${sign}${hh}`;\n}\n\n/** Z or ±hhmm. */\nfunction fmtOffsetZ(offsetSeconds: number): string {\n return offsetSeconds === 0 ? \"Z\" : fmtOffset(offsetSeconds);\n}\n\n/** Z or ±hh:mm. */\nfunction fmtOffsetColonZ(offsetSeconds: number): string {\n return offsetSeconds === 0 ? \"Z\" : fmtOffsetColon(offsetSeconds);\n}\n\n/** Z or ±hh. */\nfunction fmtOffsetHourZ(offsetSeconds: number): string {\n return offsetSeconds === 0 ? \"Z\" : fmtOffsetHour(offsetSeconds);\n}\n\n// Fractional second helper: pad/trim to `width` digits.\nfunction fmtFrac(ms: number, width: number, trimTrailing: boolean): string {\n // ms is 0–999; expand to full nanosecond-width by multiplying\n const nanosTotal = ms * 1_000_000; // ms → ns\n const full = String(nanosTotal).padStart(9, \"0\");\n const s = full.slice(0, width);\n if (trimTrailing) return s.replace(/0+$/, \"\");\n return s;\n}\n\n// ---------------------------------------------------------------------------\n// Token table — ordered longest-first so greedy matching is correct.\n// ---------------------------------------------------------------------------\n\ntype Replacer = (z: ZoneParts) => string;\n\n// Each entry: [tokenString, replacer].\n// Order MUST be stable and longest-first within the same starting character.\nconst TOKENS: [string, Replacer][] = [\n // 9-digit fractional seconds\n [\".000000000\", (z) => `.${fmtFrac(z.ms, 9, false)}`],\n [\n \".999999999\",\n (z) => {\n const s = fmtFrac(z.ms, 9, true);\n return s ? `.${s}` : \"\";\n },\n ],\n // 6-digit fractional seconds\n [\".000000\", (z) => `.${fmtFrac(z.ms, 6, false)}`],\n [\n \".999999\",\n (z) => {\n const s = fmtFrac(z.ms, 6, true);\n return s ? `.${s}` : \"\";\n },\n ],\n // 3-digit fractional seconds\n [\".000\", (z) => `.${pad3(z.ms)}`],\n [\n \".999\",\n (z) => {\n const s = pad3(z.ms).replace(/0+$/, \"\");\n return s ? `.${s}` : \"\";\n },\n ],\n // 7-char\n [\"January\", (z) => MONTHS_LONG[z.month - 1] ?? \"January\"],\n // 6-char\n [\"Monday\", (z) => WEEKDAYS_LONG[z.weekday] ?? \"Monday\"],\n [\"Z07:00\", (z) => fmtOffsetColonZ(z.offsetSeconds)],\n [\"-07:00\", (z) => fmtOffsetColon(z.offsetSeconds)],\n // 5-char\n [\"Z0700\", (z) => fmtOffsetZ(z.offsetSeconds)],\n [\"-0700\", (z) => fmtOffset(z.offsetSeconds)],\n // 4-char\n // Go: sign, then the magnitude padded to four digits (-5 → \"-0005\").\n [\"2006\", (z) => `${z.year < 0 ? \"-\" : \"\"}${String(Math.abs(z.year)).padStart(4, \"0\")}`],\n // 3-char\n [\"Jan\", (z) => MONTHS_SHORT[z.month - 1] ?? \"Jan\"],\n [\"Mon\", (z) => WEEKDAYS_SHORT[z.weekday] ?? \"Mon\"],\n [\"MST\", (z) => z.tzAbbr],\n [\"-07\", (z) => fmtOffsetHour(z.offsetSeconds)],\n [\"Z07\", (z) => fmtOffsetHourZ(z.offsetSeconds)],\n // 2-char\n [\"15\", (z) => pad2(z.hour)],\n [\"01\", (z) => pad2(z.month)],\n [\"02\", (z) => pad2(z.day)],\n // Space-padded day: `_2` is underscore+2 in the format string.\n [\"_2\", (z) => spacePad2(z.day)],\n [\"03\", (z) => pad2(z.hour12)],\n [\"04\", (z) => pad2(z.minute)],\n [\"05\", (z) => pad2(z.second)],\n [\"06\", (z) => pad2(Math.abs(z.year) % 100)],\n [\"PM\", (z) => (z.hour >= 12 ? \"PM\" : \"AM\")],\n [\"pm\", (z) => (z.hour >= 12 ? \"pm\" : \"am\")],\n // 1-char\n [\"1\", (z) => String(z.month)],\n [\"2\", (z) => String(z.day)],\n [\"3\", (z) => String(z.hour12)],\n [\"4\", (z) => String(z.minute)],\n [\"5\", (z) => String(z.second)],\n];\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Format `zoneParts` according to Go's reference-time layout string.\n * Literal characters pass through unchanged.\n */\nexport function formatGoLayout(layout: string, z: ZoneParts): string {\n let result = \"\";\n let i = 0;\n while (i < layout.length) {\n let matched = false;\n for (const [token, replacer] of TOKENS) {\n if (layout.startsWith(token, i)) {\n result += replacer(z);\n i += token.length;\n matched = true;\n break;\n }\n }\n if (!matched) {\n result += layout[i++];\n }\n }\n return result;\n}\n","/**\n * Timezone-aware date parts extraction via Intl.DateTimeFormat.\n *\n * No third-party deps. All modern runtimes (Node ≥ 14, Bun, Deno,\n * browsers) ship Intl with IANA tz database support.\n *\n * [LAW:single-enforcer] All timezone arithmetic routes through\n * `getZoneParts` — never through `date.getHours()` (host-tz) or manual\n * offset computation at callsites.\n */\n\nexport interface ZoneParts {\n year: number; // astronomical: 1 BC is 0\n month: number; // 1–12\n day: number; // 1–31\n weekday: number; // 0 = Sun, 1 = Mon, …, 6 = Sat\n hour: number; // 0–23\n hour12: number; // 1–12 (Go's `3` token)\n minute: number;\n second: number;\n ms: number; // milliseconds 0–999 (from UTC epoch)\n tzAbbr: string; // \"UTC\", \"EST\", \"EDT\", etc.\n offsetSeconds: number; // UTC offset, exact (e.g. -18000 for EST, -17762 for New York LMT)\n}\n\n// `era` lets BCE years be told from CE: Intl numbers 1 BC as year \"1\".\n// `timeZoneName` adds the short abbreviation as a part.\nconst INTL_OPTS: Intl.DateTimeFormatOptions = {\n era: \"short\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n weekday: \"long\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n timeZoneName: \"short\",\n};\n\nconst WEEKDAY_NAMES = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n];\n\n// INTL_OPTS requests every part read here, so a missing one is a runtime\n// that broke the contract, not a value to default past.\nfunction readParts(fmt: Intl.DateTimeFormat, date: Date) {\n const parts = new Map<string, string>();\n for (const p of fmt.formatToParts(date)) parts.set(p.type, p.value);\n return (type: Intl.DateTimeFormatPartTypes): string => {\n const value = parts.get(type);\n if (value === undefined) throw new Error(`Intl.DateTimeFormat omitted the ${type} part`);\n return value;\n };\n}\n\nfunction buildFormatter(timeZone: string): Intl.DateTimeFormat {\n return new Intl.DateTimeFormat(\"en-US\", { ...INTL_OPTS, timeZone });\n}\n\n// Go's time.LoadLocation rejects UTC offset names (\"+05:30\"), which Intl\n// accepts as zones.\nconst OFFSET_ZONE = /^[+-]/;\n\n// [LAW:no-shared-mutable-globals] Owned by `zoneFormatter` alone, the only\n// reader and writer. Invariant: each entry is a pure function of the key\n// (locale and options are fixed), so memoising leaves every result unchanged\n// and nothing is ever evicted. Only zones that load are stored, keyed\n// ASCII-case-insensitively as ECMA-402 matches them, so the map is bounded by\n// the IANA identifiers however a template spells them. Construction costs\n// tens of µs; formatting with a warm formatter, a few.\nconst formattersByZone = new Map<string, Intl.DateTimeFormat>();\n\n// Mirror Go sprig: a zone that does not load falls back to UTC. Intl rejects\n// an unknown zone with a RangeError. The UTC formatter is built outside the\n// `try`, so a runtime that cannot honour INTL_OPTS at all fails loudly.\nfunction zoneFormatter(name: string): Intl.DateTimeFormat {\n const key = name.replace(/[A-Z]/g, (c) => c.toLowerCase());\n const cached = formattersByZone.get(key);\n if (cached !== undefined) return cached;\n const loaded = OFFSET_ZONE.test(name) ? undefined : buildOrUnknown(name);\n if (loaded === undefined) return zoneFormatter(\"UTC\");\n formattersByZone.set(key, loaded);\n return loaded;\n}\n\nfunction buildOrUnknown(name: string): Intl.DateTimeFormat | undefined {\n if (name === \"UTC\") return buildFormatter(name);\n try {\n return buildFormatter(name);\n } catch (e) {\n if (e instanceof RangeError) return undefined;\n throw e;\n }\n}\n\n/** Extract date parts in the requested IANA timezone. Falls back to \"UTC\" on invalid zone, mirroring Go sprig. */\nexport function getZoneParts(date: Date, zone: string): ZoneParts {\n const part = readParts(zoneFormatter(zone), date);\n\n const eraYear = parseInt(part(\"year\"), 10);\n const year = part(\"era\") === \"BC\" ? 1 - eraYear : eraYear;\n const month = parseInt(part(\"month\"), 10);\n const day = parseInt(part(\"day\"), 10);\n // hour12: false returns \"24\" for midnight in some runtimes — normalise.\n const hour = parseInt(part(\"hour\"), 10) % 24;\n const minute = parseInt(part(\"minute\"), 10);\n const second = parseInt(part(\"second\"), 10);\n const ms = date.getUTCMilliseconds();\n\n // The UTC offset is the wall clock read as if it were UTC, minus the\n // instant: exact to the second, so local mean time offsets such as New\n // York's -4:56:02 before 1883 survive. Plain arithmetic, not a Date,\n // because the wall clock may lie past Date's ±8.64e15 ms range.\n const wallMs =\n daysFromCivil(year, month, day) * 86_400_000 + ((hour * 60 + minute) * 60 + second) * 1000 + ms;\n const offsetSeconds = (wallMs - date.getTime()) / 1000;\n\n const weekdayName = part(\"weekday\");\n const weekday = WEEKDAY_NAMES.indexOf(weekdayName);\n if (weekday === -1) throw new Error(`Intl.DateTimeFormat gave an unknown weekday ${weekdayName}`);\n\n return {\n year,\n month,\n day,\n weekday,\n hour,\n hour12: hour % 12 || 12,\n minute,\n second,\n ms,\n tzAbbr: part(\"timeZoneName\"),\n offsetSeconds,\n };\n}\n\n// Days from 1970-01-01 to a proleptic Gregorian date, for any integer year.\n// Howard Hinnant's days_from_civil: count in 400-year eras from 0000-03-01.\nfunction daysFromCivil(year: number, month: number, day: number): number {\n const y = month <= 2 ? year - 1 : year;\n const era = Math.floor(y / 400);\n const yearOfEra = y - era * 400;\n const dayOfYear = Math.floor((153 * ((month + 9) % 12) + 2) / 5) + day - 1;\n const dayOfEra =\n yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;\n return era * 146_097 + dayOfEra - 719_468;\n}\n\n// [LAW:no-shared-mutable-globals] Owned by `localTz` alone. Go fixes\n// `time.Local` before `main`, but in JS the host zone moves at runtime: Node\n// re-resolves it when `process.env.TZ` is assigned, a browser when the OS\n// zone changes. The memo is keyed on both signals (the offset stands in for\n// the OS zone where there is no `process`), so it resolves afresh, at the\n// cost of one formatter, only when one of them moves.\nlet hostZone: { key: string; zone: string } | undefined;\n\n/** Host timezone name (IANA string). */\nexport function localTz(): string {\n const key = `${globalThis.process?.env.TZ}|${new Date().getTimezoneOffset()}`;\n if (hostZone?.key !== key) {\n hostZone = { key, zone: Intl.DateTimeFormat().resolvedOptions().timeZone };\n }\n return hostZone.zone;\n}\n","import { formatGoLayout } from \"./_format.js\";\nimport { resolveDate } from \"./_resolve.js\";\nimport { getZoneParts, localTz } from \"./_zone.js\";\n\n/**\n * `date format t` — format `t` using Go's reference-time layout,\n * in the host timezone (mirrors Go's `date` which uses `time.Local`).\n */\nexport function date(format: string, t: unknown): string {\n const d = resolveDate(t);\n return formatGoLayout(format, getZoneParts(d, localTz()));\n}\n","import { formatGoLayout } from \"./_format.js\";\nimport { resolveDate } from \"./_resolve.js\";\nimport { getZoneParts } from \"./_zone.js\";\n\n/**\n * `dateInZone format t zone` — format `t` using Go's reference-time\n * layout, displayed in the named IANA timezone.\n */\nexport function dateInZone(format: string, t: unknown, zone: string): string {\n const d = resolveDate(t);\n return formatGoLayout(format, getZoneParts(d, zone));\n}\n","import { parseDurationNs } from \"./_duration.js\";\nimport { resolveDate } from \"./_resolve.js\";\n\n/**\n * `dateModify duration t` — add or subtract a Go duration from `t`.\n * `duration` is a Go duration string: \"1h30m\", \"-24h\", \"300ms\".\n */\nexport function dateModify(duration: string, t: unknown): Date {\n const d = resolveDate(t);\n const ns = parseDurationNs(duration);\n // Mirror Go sprig: return the original date unchanged on parse error.\n if (Number.isNaN(ns)) return d;\n return new Date(d.getTime() + ns / 1_000_000);\n}\n","import { formatDurationNs, secondsToNs } from \"./_duration.js\";\n\n/**\n * `duration sec` — seconds → Go-style duration string.\n * Mirrors Go sprig: accepts a string (parsed as decimal integer seconds)\n * or a number/bigint.\n *\n * `duration(\"3600\")` → `\"1h0m0s\"`, `duration(\"5\")` → `\"5s\"`.\n *\n * Note: Go sprig only handles `string` and `int64` inputs; `int` (the type\n * of a Go template integer literal) falls to a default-zero branch. To\n * maintain portable templates, always pass seconds as a string.\n */\nexport function duration(sec: unknown): string {\n if (typeof sec === \"string\") {\n const n = parseInt(sec, 10);\n return Number.isNaN(n) ? \"0s\" : formatDurationNs(secondsToNs(n));\n }\n if (typeof sec === \"bigint\") return formatDurationNs(secondsToNs(Number(sec)));\n if (typeof sec === \"number\") return formatDurationNs(secondsToNs(sec));\n return \"0s\";\n}\n","import { parseDurationNs } from \"./_duration.js\";\n\n// Mirror Go sprig's constants (nanoseconds). Comparisons are strict (>).\nconst YEAR = 3_600_000_000_000 * 24 * 365;\nconst MONTH = 3_600_000_000_000 * 24 * 30;\nconst DAY = 3_600_000_000_000 * 24;\nconst HOUR = 3_600_000_000_000;\nconst MINUTE = 60_000_000_000;\nconst SECOND = 1_000_000_000;\n\n/**\n * `durationRound d` — parse a Go duration string and truncate to the\n * largest unit. Mirrors Go sprig's `durationRound` which uses integer\n * division (NOT rounding) and custom single-unit suffixes.\n *\n * Examples: \"1h30m\" → \"1h\", \"90s\" → \"1m\", \"1h\" → \"60m\" (strict >).\n */\nexport function durationRound(d: unknown): string {\n const s = String(d);\n const ns = parseDurationNs(s);\n if (Number.isNaN(ns)) return \"0s\";\n\n const u = Math.abs(ns);\n if (u > YEAR) return `${Math.floor(u / YEAR)}y`;\n if (u > MONTH) return `${Math.floor(u / MONTH)}mo`;\n if (u > DAY) return `${Math.floor(u / DAY)}d`;\n if (u > HOUR) return `${Math.floor(u / HOUR)}h`;\n if (u > MINUTE) return `${Math.floor(u / MINUTE)}m`;\n if (u > SECOND) return `${Math.floor(u / SECOND)}s`;\n return \"0s\";\n}\n","import { formatGoLayout } from \"./_format.js\";\nimport { resolveDate } from \"./_resolve.js\";\nimport { getZoneParts, localTz } from \"./_zone.js\";\n\n/** `htmlDate t` — YYYY-MM-DD in the host timezone. */\nexport function htmlDate(t: unknown): string {\n return formatGoLayout(\"2006-01-02\", getZoneParts(resolveDate(t), localTz()));\n}\n","import { formatGoLayout } from \"./_format.js\";\nimport { resolveDate } from \"./_resolve.js\";\nimport { getZoneParts } from \"./_zone.js\";\n\n/** `htmlDateInZone t zone` — YYYY-MM-DD in the named timezone. */\nexport function htmlDateInZone(t: unknown, zone: string): string {\n return formatGoLayout(\"2006-01-02\", getZoneParts(resolveDate(t), zone));\n}\n","import type { Clock } from \"./_clock.js\";\n\n/** `now` — current instant. Routed through the clock seam. */\nexport function now(clock: Clock): Date {\n return clock();\n}\n","/**\n * Parse a date string according to Go's reference-time layout.\n *\n * Mirrors `time.ParseInLocation` with UTC as the default location\n * (when the layout contains no timezone token, the result is UTC).\n *\n * Strategy: tokenise the layout the same way the formatter does —\n * greedy longest-match — but instead of replacing tokens with values,\n * consume the corresponding characters from the value string.\n */\n\nconst MONTHS_LONG = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\nconst MONTHS_SHORT = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n];\n\n// ---------------------------------------------------------------------------\n// Parse state\n// ---------------------------------------------------------------------------\n\ninterface ParseState {\n year: number;\n month: number; // 1–12\n day: number; // 1–31\n hour: number; // 0–23\n minute: number;\n second: number;\n ms: number;\n offsetMinutes: number; // UTC offset; NaN means \"not set\" → default to UTC\n isPM: boolean;\n hour12: boolean; // did layout use 12h token?\n}\n\nfunction defaultState(): ParseState {\n return {\n year: 2000,\n month: 1,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n ms: 0,\n offsetMinutes: 0,\n isPM: false,\n hour12: false,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Value-string consumers\n// ---------------------------------------------------------------------------\n\nfunction consumeFixed(val: string, pos: number, n: number): [string, number] {\n return [val.slice(pos, pos + n), pos + n];\n}\n\nfunction consumeDigits(val: string, pos: number, min: number, max: number): [number, number] {\n let end = pos;\n while (\n end < val.length &&\n end - pos < max &&\n val.charCodeAt(end) >= 48 &&\n val.charCodeAt(end) <= 57\n )\n end++;\n if (end - pos < min) throw new Error(`sprig toDate: expected ${min}-${max} digits at pos ${pos}`);\n return [parseInt(val.slice(pos, end), 10), end];\n}\n\nfunction consumeMonthLong(val: string, pos: number): [number, number] {\n for (const [i, m] of MONTHS_LONG.entries()) {\n if (val.startsWith(m, pos)) return [i + 1, pos + m.length];\n }\n throw new Error(`sprig toDate: expected month name at pos ${pos}`);\n}\n\nfunction consumeMonthShort(val: string, pos: number): [number, number] {\n for (const [i, m] of MONTHS_SHORT.entries()) {\n if (val.startsWith(m, pos)) return [i + 1, pos + m.length];\n }\n throw new Error(`sprig toDate: expected short month name at pos ${pos}`);\n}\n\nfunction consumeWeekdayLong(val: string, pos: number): number {\n const days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\n for (const d of days) if (val.startsWith(d, pos)) return pos + d.length;\n throw new Error(`sprig toDate: expected weekday name at pos ${pos}`);\n}\n\nfunction consumeWeekdayShort(val: string, pos: number): number {\n const days = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n for (const d of days) if (val.startsWith(d, pos)) return pos + d.length;\n throw new Error(`sprig toDate: expected short weekday name at pos ${pos}`);\n}\n\nfunction consumeSpacePaddedDay(val: string, pos: number): [number, number] {\n // Leading space or digit for space-padded day (`_2` token).\n if (val[pos] === \" \") {\n const [n, end] = consumeDigits(val, pos + 1, 1, 1);\n return [n, end];\n }\n return consumeDigits(val, pos, 1, 2);\n}\n\n/** Parse offset like \"+0500\", \"-0500\", \"+05:00\", \"-05:00\", \"+05\", \"-05\". Returns minutes. */\nfunction consumeOffset(val: string, pos: number, withColon: boolean): [number, number] {\n const sign = val[pos] === \"+\" ? 1 : val[pos] === \"-\" ? -1 : 0;\n if (sign === 0) throw new Error(`sprig toDate: expected +/- at pos ${pos}`);\n let p = pos + 1;\n const [h, p2] = consumeDigits(val, p, 2, 2);\n p = p2;\n let m = 0;\n if (withColon && val[p] === \":\") {\n const [m2, p3] = consumeDigits(val, p + 1, 2, 2);\n m = m2;\n p = p3;\n } else if (!withColon) {\n const [m2, p3] = consumeDigits(val, p, 2, 2);\n m = m2;\n p = p3;\n }\n return [sign * (h * 60 + m), p];\n}\n\n/** Parse \"Z\" or an offset. withColon controls +05:00 vs +0500 form. Returns [offsetMinutes, newPos]. */\nfunction consumeZOrOffset(\n val: string,\n pos: number,\n withColon: boolean,\n hourOnly: boolean,\n): [number, number] {\n if (val[pos] === \"Z\") return [0, pos + 1];\n if (hourOnly) {\n const sign = val[pos] === \"+\" ? 1 : val[pos] === \"-\" ? -1 : 0;\n if (sign === 0) throw new Error(`sprig toDate: expected Z or +/- at pos ${pos}`);\n const [h, p2] = consumeDigits(val, pos + 1, 2, 2);\n return [sign * h * 60, p2];\n }\n return consumeOffset(val, pos, withColon);\n}\n\n/** Parse timezone abbreviation (e.g. \"UTC\", \"EST\"). Returns new pos. */\nfunction consumeTzAbbr(val: string, pos: number): number {\n // TZ abbreviation is a run of uppercase letters.\n let end = pos;\n while (end < val.length && val.charCodeAt(end) >= 65 && val.charCodeAt(end) <= 90) end++;\n if (end === pos) throw new Error(`sprig toDate: expected timezone abbreviation at pos ${pos}`);\n return end;\n}\n\n/** Parse fractional seconds (like \".000\", \".999\", etc.) starting AFTER the dot. */\nfunction consumeFrac(val: string, pos: number, width: number): [number, number] {\n const [raw, end] = consumeFixed(val, pos, width);\n const ns = parseInt(raw.padEnd(9, \"0\"), 10);\n return [Math.round(ns / 1_000_000), end]; // → ms\n}\n\n// ---------------------------------------------------------------------------\n// Token dispatch\n// ---------------------------------------------------------------------------\n\n// Returns [newValPos, modified state], consuming both layout and value tokens.\nfunction dispatchToken(\n token: string,\n val: string,\n vp: number,\n st: ParseState,\n): [number, ParseState] {\n const s = { ...st };\n switch (token) {\n case \"January\": {\n const [m, p2] = consumeMonthLong(val, vp);\n s.month = m;\n return [p2, s];\n }\n case \"Monday\": {\n const p2 = consumeWeekdayLong(val, vp);\n return [p2, s];\n }\n case \"Jan\": {\n const [m, p2] = consumeMonthShort(val, vp);\n s.month = m;\n return [p2, s];\n }\n case \"Mon\": {\n const p2 = consumeWeekdayShort(val, vp);\n return [p2, s];\n }\n case \"2006\": {\n const [y, p2] = consumeDigits(val, vp, 4, 4);\n s.year = y;\n return [p2, s];\n }\n case \"06\": {\n const [y, p2] = consumeDigits(val, vp, 2, 2);\n s.year = y < 70 ? 2000 + y : 1900 + y;\n return [p2, s];\n }\n case \"01\": {\n const [m, p2] = consumeDigits(val, vp, 2, 2);\n s.month = m;\n return [p2, s];\n }\n case \"1\": {\n const [m, p2] = consumeDigits(val, vp, 1, 2);\n s.month = m;\n return [p2, s];\n }\n case \"_2\": {\n const [d, p2] = consumeSpacePaddedDay(val, vp);\n s.day = d;\n return [p2, s];\n }\n case \"02\": {\n const [d, p2] = consumeDigits(val, vp, 2, 2);\n s.day = d;\n return [p2, s];\n }\n case \"2\": {\n const [d, p2] = consumeDigits(val, vp, 1, 2);\n s.day = d;\n return [p2, s];\n }\n case \"15\": {\n const [h, p2] = consumeDigits(val, vp, 2, 2);\n s.hour = h;\n return [p2, s];\n }\n case \"03\": {\n const [h, p2] = consumeDigits(val, vp, 2, 2);\n s.hour = h;\n s.hour12 = true;\n return [p2, s];\n }\n case \"3\": {\n const [h, p2] = consumeDigits(val, vp, 1, 2);\n s.hour = h;\n s.hour12 = true;\n return [p2, s];\n }\n case \"04\": {\n const [m, p2] = consumeDigits(val, vp, 2, 2);\n s.minute = m;\n return [p2, s];\n }\n case \"4\": {\n const [m, p2] = consumeDigits(val, vp, 1, 2);\n s.minute = m;\n return [p2, s];\n }\n case \"05\": {\n const [sec, p2] = consumeDigits(val, vp, 2, 2);\n s.second = sec;\n return [p2, s];\n }\n case \"5\": {\n const [sec, p2] = consumeDigits(val, vp, 1, 2);\n s.second = sec;\n return [p2, s];\n }\n case \"PM\":\n case \"pm\": {\n const ampm = val.slice(vp, vp + 2).toLowerCase();\n if (ampm !== \"am\" && ampm !== \"pm\")\n throw new Error(\n `sprig toDate: expected AM/PM at pos ${vp}, got ${JSON.stringify(val.slice(vp, vp + 2))}`,\n );\n s.isPM = ampm === \"pm\";\n s.hour12 = true;\n return [vp + 2, s];\n }\n case \"MST\": {\n const p2 = consumeTzAbbr(val, vp);\n // We don't map abbreviation → offset (ambiguous); keep current offset.\n return [p2, s];\n }\n case \"-0700\": {\n const [off, p2] = consumeOffset(val, vp, false);\n s.offsetMinutes = off;\n return [p2, s];\n }\n case \"-07:00\": {\n const [off, p2] = consumeOffset(val, vp, true);\n s.offsetMinutes = off;\n return [p2, s];\n }\n case \"-07\": {\n const sign = val[vp] === \"+\" ? 1 : val[vp] === \"-\" ? -1 : 0;\n if (sign === 0) throw new Error(`sprig toDate: expected +/- at pos ${vp}`);\n const [h, p2] = consumeDigits(val, vp + 1, 2, 2);\n s.offsetMinutes = sign * h * 60;\n return [p2, s];\n }\n case \"Z0700\": {\n const [off, p2] = consumeZOrOffset(val, vp, false, false);\n s.offsetMinutes = off;\n return [p2, s];\n }\n case \"Z07:00\": {\n const [off, p2] = consumeZOrOffset(val, vp, true, false);\n s.offsetMinutes = off;\n return [p2, s];\n }\n case \"Z07\": {\n const [off, p2] = consumeZOrOffset(val, vp, false, true);\n s.offsetMinutes = off;\n return [p2, s];\n }\n case \".000000000\": {\n // consume dot + 9 digits (dot is required)\n if (val[vp] !== \".\") throw new Error(`sprig toDate: expected . at pos ${vp}`);\n const [ms, p3] = consumeFrac(val, vp + 1, 9);\n s.ms = ms;\n return [p3, s];\n }\n case \".999999999\": {\n // optional: if val has a dot here, consume; otherwise skip\n if (val[vp] !== \".\") return [vp, s];\n const end = vp + 1;\n let e2 = end;\n while (e2 < val.length && val.charCodeAt(e2) >= 48 && val.charCodeAt(e2) <= 57) e2++;\n const frac = val.slice(end, e2).padEnd(9, \"0\");\n s.ms = Math.round(parseInt(frac, 10) / 1_000_000);\n return [e2, s];\n }\n case \".000000\": {\n // dot is required\n if (val[vp] !== \".\") throw new Error(`sprig toDate: expected . at pos ${vp}`);\n const [ms, p3] = consumeFrac(val, vp + 1, 6);\n s.ms = ms;\n return [p3, s];\n }\n case \".999999\": {\n if (val[vp] !== \".\") return [vp, s];\n const end = vp + 1;\n let e2 = end;\n while (e2 < val.length && val.charCodeAt(e2) >= 48 && val.charCodeAt(e2) <= 57) e2++;\n const frac = val.slice(end, e2).padEnd(9, \"0\");\n s.ms = Math.round(parseInt(frac, 10) / 1_000_000);\n return [e2, s];\n }\n case \".000\": {\n // dot is required\n if (val[vp] !== \".\") throw new Error(`sprig toDate: expected . at pos ${vp}`);\n const [ms, p3] = consumeFrac(val, vp + 1, 3);\n s.ms = ms;\n return [p3, s];\n }\n case \".999\": {\n if (val[vp] !== \".\") return [vp, s];\n const end = vp + 1;\n let e2 = end;\n while (e2 < val.length && val.charCodeAt(e2) >= 48 && val.charCodeAt(e2) <= 57) e2++;\n const frac = val.slice(end, e2).padEnd(3, \"0\");\n s.ms = parseInt(frac, 10);\n return [e2, s];\n }\n }\n throw new Error(`sprig toDate: unhandled token ${token}`);\n}\n\n// Token list in the same order as _format.ts (longest first).\nconst TOKENS: string[] = [\n \".000000000\",\n \".999999999\",\n \".000000\",\n \".999999\",\n \".000\",\n \".999\",\n \"January\",\n \"Monday\",\n \"Z07:00\",\n \"-07:00\",\n \"Z0700\",\n \"-0700\",\n \"2006\",\n \"Jan\",\n \"Mon\",\n \"MST\",\n \"-07\",\n \"Z07\",\n \"15\",\n \"01\",\n \"02\",\n \"_2\",\n \"03\",\n \"04\",\n \"05\",\n \"06\",\n \"PM\",\n \"pm\",\n \"1\",\n \"2\",\n \"3\",\n \"4\",\n \"5\",\n];\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Parse `value` according to Go's reference-time `layout`.\n * Returns a UTC-based `Date` whose wall time corresponds to the parsed\n * components adjusted for the parsed timezone offset.\n */\nexport function parseGoLayout(layout: string, value: string): Date {\n let lp = 0;\n let vp = 0;\n let st = defaultState();\n\n while (lp < layout.length) {\n let matched = false;\n for (const token of TOKENS) {\n if (layout.startsWith(token, lp)) {\n const [newVp, newSt] = dispatchToken(token, value, vp, st);\n vp = newVp;\n st = newSt;\n lp += token.length;\n matched = true;\n break;\n }\n }\n if (!matched) {\n // Literal character: must match in value.\n const lc = layout.charAt(lp);\n if (value[vp] !== lc) {\n throw new Error(\n `sprig toDate: expected ${JSON.stringify(lc)} at pos ${vp}, got ${JSON.stringify(value[vp])}`,\n );\n }\n lp++;\n vp++;\n }\n }\n\n // Verify the entire value string was consumed.\n if (vp !== value.length) {\n throw new Error(\n `sprig toDate: extra characters at pos ${vp}: ${JSON.stringify(value.slice(vp))}`,\n );\n }\n\n // Adjust 12-hour clock.\n if (st.hour12) {\n const h12 = st.hour % 12;\n st.hour = st.isPM ? h12 + 12 : h12;\n }\n\n // Build UTC timestamp from components + offset.\n const utcMs =\n Date.UTC(st.year, st.month - 1, st.day, st.hour, st.minute, st.second, st.ms) -\n st.offsetMinutes * 60 * 1000;\n return new Date(utcMs);\n}\n","import { parseGoLayout } from \"./_parse.js\";\n\n/**\n * `toDate format value` — parse `value` string using Go's reference-time\n * layout. Returns a `Date`. Mirrors Go sprig's `toDate`.\n */\nexport function toDate(format: string, value: string): Date {\n return parseGoLayout(format, value);\n}\n","import { resolveDate } from \"./_resolve.js\";\n\n/** `unixEpoch t` — seconds since Unix epoch as a decimal string. */\nexport function unixEpoch(t: unknown): string {\n return String(Math.floor(resolveDate(t).getTime() / 1000));\n}\n","/**\n * Sprig date/time functions — `now`, `date`, `dateInZone`, `dateModify`,\n * `htmlDate`, `htmlDateInZone`, `duration`, `durationRound`, `toDate`,\n * `ago`, `unixEpoch`.\n *\n * All \"current time\" reads go through the `clock` seam so tests can\n * freeze time deterministically. [LAW:single-enforcer]\n *\n * Go format-string support: the full reference-time token set including\n * fractional seconds, all timezone forms, and both 12h and 24h clocks.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport type { Clock } from \"./_clock.js\";\nimport { ago } from \"./ago.js\";\nimport { date } from \"./date.js\";\nimport { dateInZone } from \"./dateInZone.js\";\nimport { dateModify } from \"./dateModify.js\";\nimport { duration } from \"./duration.js\";\nimport { durationRound } from \"./durationRound.js\";\nimport { htmlDate } from \"./htmlDate.js\";\nimport { htmlDateInZone } from \"./htmlDateInZone.js\";\nimport { now } from \"./now.js\";\nimport { toDate } from \"./toDate.js\";\nimport { unixEpoch } from \"./unixEpoch.js\";\n\nexport {\n ago,\n date,\n dateInZone,\n dateModify,\n duration,\n durationRound,\n htmlDate,\n htmlDateInZone,\n now,\n toDate,\n unixEpoch,\n};\n\n/**\n * Build the sprig date/time FuncMap.\n *\n * @param clock - Source of \"current time\". Defaults to `() => new Date()`.\n * Pass a frozen clock for deterministic test output (mirrors\n * `EngineConfig.clock`).\n */\nexport function sprigDatetime(clock: Clock = () => new Date()): FuncMap {\n return {\n now: {\n fn: () => now(clock),\n argTypes: [],\n arity: { kind: \"exact\" },\n },\n date: {\n fn: (format, t) => date(format as string, t),\n argTypes: [\"string\", \"value\"],\n arity: { kind: \"exact\" },\n },\n dateInZone: {\n fn: (format, t, zone) => dateInZone(format as string, t, zone as string),\n argTypes: [\"string\", \"value\", \"string\"],\n arity: { kind: \"exact\" },\n },\n dateModify: {\n fn: (dur, t) => dateModify(dur as string, t),\n argTypes: [\"string\", \"value\"],\n arity: { kind: \"exact\" },\n },\n htmlDate: {\n fn: (t) => htmlDate(t),\n argTypes: [\"value\"],\n arity: { kind: \"exact\" },\n },\n htmlDateInZone: {\n fn: (t, zone) => htmlDateInZone(t, zone as string),\n argTypes: [\"value\", \"string\"],\n arity: { kind: \"exact\" },\n },\n duration: {\n fn: (sec) => duration(sec),\n argTypes: [\"value\"],\n arity: { kind: \"exact\" },\n },\n durationRound: {\n fn: (d) => durationRound(d),\n argTypes: [\"value\"],\n arity: { kind: \"exact\" },\n },\n toDate: {\n fn: (format, s) => toDate(format as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n ago: {\n fn: (t) => ago(t, clock),\n argTypes: [\"value\"],\n arity: { kind: \"exact\" },\n },\n unixEpoch: {\n fn: (t) => unixEpoch(t),\n argTypes: [\"value\"],\n arity: { kind: \"exact\" },\n },\n };\n}\n","/**\n * `empty val` — true if `val` is \"empty\" per Go sprig's rules:\n * nil, false, 0, 0.0, \"\", empty array/Map/object.\n *\n * Note: `empty 0` is true (this surprises newcomers — Go sprig matches\n * Go's reflect-IsZero semantics).\n */\n\nimport { isTruthy } from \"../../evaluator/truthy.js\";\n\nexport function empty(value: unknown): boolean {\n return !isTruthy(value);\n}\n","/**\n * `coalesce a b c …` — returns the first non-empty argument, or\n * undefined if none are non-empty.\n */\n\nimport { empty } from \"./empty.js\";\n\nexport function coalesce(...values: readonly unknown[]): unknown {\n for (const v of values) {\n if (!empty(v)) return v;\n }\n return undefined;\n}\n","/**\n * `default defaultVal val` — returns `val` if non-empty (per `empty`),\n * else `defaultVal`.\n *\n * Argument order matches Go sprig: the *default* comes first, the\n * value comes second. Pipelines feed the trailing arg, so\n * `{{ .name | default \"anonymous\" }}` evaluates default(\"anonymous\", .name).\n */\n\nimport { empty } from \"./empty.js\";\n\nexport function defaultFn(defaultVal: unknown, value: unknown): unknown {\n return empty(value) ? defaultVal : value;\n}\n","/**\n * `fromJson s` — parses a JSON string into a value.\n *\n * Returns the parsed value. Throws if the input is not valid JSON,\n * matching Go sprig's behaviour (Go sprig propagates the parse error).\n */\n\nexport function fromJson(input: string): unknown {\n return JSON.parse(input);\n}\n","/**\n * `ternary trueVal falseVal cond` — returns `trueVal` if `cond` is\n * truthy, else `falseVal`.\n *\n * Note: argument order matches Go sprig and surprises newcomers.\n * Pipelines feed cond as the trailing arg, e.g.\n * `{{ .ok | ternary \"YES\" \"NO\" }}` → ternary(\"YES\", \"NO\", .ok)\n */\n\nimport { isTruthy } from \"../../evaluator/truthy.js\";\n\nexport function ternary(trueVal: unknown, falseVal: unknown, cond: unknown): unknown {\n return isTruthy(cond) ? trueVal : falseVal;\n}\n","/**\n * `toJson val` — serializes a value to compact JSON.\n *\n * Matches Go sprig in spirit but uses JS `JSON.stringify`. Note that\n * `JSON.stringify(undefined)` is undefined; we coerce that to \"null\"\n * for byte-equivalence with Go's encoding/json (which encodes\n * untyped-nil as null).\n */\n\nexport function toJson(value: unknown): string {\n return JSON.stringify(value) ?? \"null\";\n}\n","/**\n * `toPrettyJson val` — JSON with 2-space indentation, matching Go\n * sprig's output exactly.\n */\n\nexport function toPrettyJson(value: unknown): string {\n return JSON.stringify(value, null, 2) ?? \"null\";\n}\n","/**\n * Sprig defaults — `default`, `empty`, `coalesce`, `ternary`, JSON.\n *\n * [LAW:single-enforcer] One module owns the FuncMap registration for\n * this category. Consumers either import individual functions or\n * spread the whole map via `sprigDefaults()` into their EngineConfig.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { coalesce } from \"./coalesce.js\";\nimport { defaultFn } from \"./default.js\";\nimport { empty } from \"./empty.js\";\nimport { fromJson } from \"./fromJson.js\";\nimport { ternary } from \"./ternary.js\";\nimport { toJson } from \"./toJson.js\";\nimport { toPrettyJson } from \"./toPrettyJson.js\";\n\nexport { coalesce, defaultFn, empty, fromJson, ternary, toJson, toPrettyJson };\n\nexport function sprigDefaults(): FuncMap {\n // [LAW:one-source-of-truth] Intent-named slots replace \"any\" so the\n // label tells the reader why each slot accepts anything:\n // - \"value\" — heterogeneous slot (constructor / pass-through)\n // - \"truthy\" — value is consulted for emptiness/truthiness\n // - \"serializable\" — value is about to be JSON-encoded; the gate\n // rejects functions, symbols, and circular refs\n // so toJson/toPrettyJson never silently emit\n // \"null\" or throw deep inside the body.\n return {\n // Go: `dfault(d interface{}, given ...interface{})` — the value to\n // test is variadic, so `default \"fallback\"` with nothing to test is\n // a legal call that yields the fallback.\n default: {\n fn: (a, b) => defaultFn(a, b),\n argTypes: [\"value\", \"truthy\"],\n arity: { kind: \"variadic\" },\n },\n empty: { fn: (v) => empty(v), argTypes: [\"truthy\"], arity: { kind: \"exact\" } },\n coalesce: {\n fn: (...vs) => coalesce(...vs),\n argTypes: [\"truthy\"],\n arity: { kind: \"variadic\" },\n },\n ternary: {\n fn: (a, b, c) => ternary(a, b, c),\n argTypes: [\"value\", \"value\", \"truthy\"],\n arity: { kind: \"exact\" },\n },\n fromJson: { fn: (s) => fromJson(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n toJson: {\n fn: (v) => toJson(v),\n argTypes: [\"serializable\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n toPrettyJson: {\n fn: (v) => toPrettyJson(v),\n argTypes: [\"serializable\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n };\n}\n","/**\n * `dict k1 v1 k2 v2 …` — builds a record from alternating key/value pairs.\n *\n * [LAW:single-enforcer] The boundary gate (`enforceArgTypes`) validates\n * the kv cycle via `arity: { kind: \"alternating\" }` against\n * `argTypes: [\"string\", \"value\"]`, so every key position is a string by\n * the time the body runs. The body trusts the gate; no per-key probe.\n *\n * Odd-length call (`dict \"a\"`) leaves the last value `undefined` —\n * matches Go sprig.\n */\n\nimport type { ReferencedArg, ReferencedLiteral } from \"../../evaluator/evaluator.js\";\n\nexport function dict(...kvs: unknown[]): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (let i = 0; i < kvs.length; i += 2) {\n out[kvs[i] as string] = kvs[i + 1];\n }\n return out;\n}\n\n/**\n * Statically read a `(dict k1 v1 …)` call argument's key/value pairs from a\n * {@link ReferencedArg} projection (see `Template.referencedCalls`).\n *\n * Returns the entries only when the argument is provably a literal dict: a\n * nested call named `dict` whose args are ALL literals, string-typed at every\n * key position, in complete pairs. Anything else — a non-`dict` call, a\n * dynamic entry (`(dict \"k\" .x)`), a non-string key (which would fail the\n * runtime arg gate anyway), an odd-length pair list — returns `null`: the\n * value is not statically readable, and a value is never guessed\n * [LAW:no-silent-failure].\n *\n * [LAW:one-source-of-truth] Lives beside — and folds through — the runtime\n * `dict` above, so the static reading and the evaluated value share one\n * pairing semantics (including later-wins on duplicate keys).\n */\nexport function staticDictEntries(arg: ReferencedArg): Record<string, ReferencedLiteral> | null {\n if (arg.kind !== \"call\" || arg.name !== \"dict\" || arg.args.length % 2 !== 0) return null;\n const values: ReferencedLiteral[] = [];\n for (const [i, entry] of arg.args.entries()) {\n if (entry.kind !== \"literal\") return null;\n if (i % 2 === 0 && typeof entry.value !== \"string\") return null;\n values.push(entry.value);\n }\n // Every value is a ReferencedLiteral and every key slot a string, in\n // complete pairs — the runtime fold cannot introduce `unknown` or\n // `undefined`, so the cast only restates what the loop established.\n return dict(...values) as Record<string, ReferencedLiteral>;\n}\n","/**\n * `get d key` — returns d[key] or undefined.\n *\n * [LAW:single-enforcer] The gate validates `d` is a plain object\n * (`\"dict\"`); the body trusts the receiver type. The Map case lives in\n * template-laws-3gt.7 (where the slot widens with an explicit Map-key\n * carve-out per audit B5/B6) — until then, Maps are rejected at the\n * gate.\n */\nexport function get(d: Record<string, unknown>, key: string): unknown {\n return d[key];\n}\n","/**\n * `hasKey d key` — true when `key` is a own-property of `d`.\n *\n * Note: sprig's name is `hasKey` though docs sometimes say `haskey`.\n * [LAW:single-enforcer] Receiver type validated at the gate.\n */\nexport function hasKey(d: Record<string, unknown>, key: string): boolean {\n return key in d;\n}\n","/**\n * `keys d` — list of own enumerable string keys.\n *\n * [LAW:single-enforcer] Receiver type validated at the gate (`\"dict\"`);\n * the body trusts the parameter. Maps are rejected by the dict gate —\n * closes audit finding B6 (no silent `String(key)` flattening of\n * typed-T Map keys, because Maps never reach this body).\n */\nexport function keys(d: Record<string, unknown>): string[] {\n return Object.keys(d);\n}\n","/**\n * `merge dst src1 src2 …` — copies missing keys from sources into dst,\n * leaving dst's existing keys untouched. Returns a new dict.\n *\n * [LAW:single-enforcer] Every dict slot is gated as `\"dict\"` (variadic\n * trailing-repeat), so dst and every source are plain objects by the\n * time the body runs.\n */\nexport function merge(\n dst: Record<string, unknown>,\n ...sources: Record<string, unknown>[]\n): Record<string, unknown> {\n const out: Record<string, unknown> = { ...dst };\n for (const s of sources) {\n for (const [k, v] of Object.entries(s)) {\n if (!(k in out)) out[k] = v;\n }\n }\n return out;\n}\n","/**\n * `mergeOverwrite dst src1 src2 …` — like `merge` but later sources\n * overwrite earlier values.\n *\n * [LAW:single-enforcer] Every dict slot is gated as `\"dict\"`.\n */\nexport function mergeOverwrite(\n dst: Record<string, unknown>,\n ...sources: Record<string, unknown>[]\n): Record<string, unknown> {\n const out: Record<string, unknown> = { ...dst };\n for (const s of sources) {\n Object.assign(out, s);\n }\n return out;\n}\n","/**\n * `omit d k1 k2 …` — sub-dict with the listed keys removed.\n *\n * [LAW:single-enforcer] Receiver type validated at the gate.\n */\nexport function omit(d: Record<string, unknown>, ...drop: string[]): Record<string, unknown> {\n const set = new Set(drop);\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(d)) {\n if (!set.has(k)) out[k] = v;\n }\n return out;\n}\n","/**\n * `pick d k1 k2 …` — sub-dict with only the listed keys.\n *\n * [LAW:single-enforcer] Receiver type validated at the gate.\n */\nexport function pick(d: Record<string, unknown>, ...wanted: string[]): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of wanted) {\n if (key in d) out[key] = d[key];\n }\n return out;\n}\n","/**\n * `pluck key d1 d2 …` — collect d[key] from each dict that has it.\n *\n * [LAW:single-enforcer] Every dict slot is gated as `\"dict\"`; the body\n * trusts each receiver and skips entries that lack the key.\n */\nexport function pluck(key: string, ...dicts: Record<string, unknown>[]): unknown[] {\n const out: unknown[] = [];\n for (const d of dicts) {\n if (key in d) out.push(d[key]);\n }\n return out;\n}\n","/**\n * `set d key value` — mutates the receiver to bind `key=value` and\n * returns it. Matches Go sprig: the receiver and the returned value\n * are the same dict.\n *\n * [LAW:single-enforcer] Non-dict receivers are rejected at the gate\n * (`argTypes: [\"dict\", \"string\", \"value\"]`); the body trusts the\n * receiver type. The previous body-level `bodyTypeMismatch` (working-\n * tree fix in template-laws-703.10) became dead code once the slot\n * declared `\"dict\"` and was deleted in template-laws-3gt.3.\n */\nexport function set(\n d: Record<string, unknown>,\n key: string,\n value: unknown,\n): Record<string, unknown> {\n d[key] = value;\n return d;\n}\n","/**\n * `unset d key` — mutates the receiver to drop `key` and returns it.\n * Matches Go sprig: the receiver and the returned value are the same\n * dict.\n *\n * [LAW:single-enforcer] Non-dict receivers are rejected at the gate;\n * see `set.ts` for the rationale.\n */\nexport function unset(d: Record<string, unknown>, key: string): Record<string, unknown> {\n delete d[key];\n return d;\n}\n","/**\n * `values d` — list of own enumerable values.\n *\n * [LAW:single-enforcer] Receiver type validated at the gate.\n */\nexport function values(d: Record<string, unknown>): unknown[] {\n return Object.values(d);\n}\n","/** Sprig dict utilities — pair-files per epic spec. */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { dict, staticDictEntries } from \"./dict.js\";\nimport { get } from \"./get.js\";\nimport { hasKey } from \"./hasKey.js\";\nimport { keys } from \"./keys.js\";\nimport { merge } from \"./merge.js\";\nimport { mergeOverwrite } from \"./mergeOverwrite.js\";\nimport { omit } from \"./omit.js\";\nimport { pick } from \"./pick.js\";\nimport { pluck } from \"./pluck.js\";\nimport { set } from \"./set.js\";\nimport { unset } from \"./unset.js\";\nimport { values } from \"./values.js\";\n\nexport {\n dict,\n get,\n hasKey,\n keys,\n merge,\n mergeOverwrite,\n omit,\n pick,\n pluck,\n set,\n staticDictEntries,\n unset,\n values,\n};\n\nexport function sprigDicts(): FuncMap {\n // [LAW:single-enforcer] Dict slots declare \"dict\" so the gate enforces\n // plain-object-ness once. Bodies trust the param type and drop the\n // `(d && typeof d === \"object\" && !(d instanceof Map))` guards that\n // previously duplicated the check across 11 funcs.\n //\n // `dict` (constructor) uses arity: { kind: \"alternating\" } so the\n // gate validates the kv cycle (string at every even index, value at\n // every odd index) — otherwise the body would re-validate every key\n // beyond the first, splitting [LAW:single-enforcer] in two.\n //\n // Receivers are typed `Record<string, unknown>` in the bodies; the\n // `as unknown[]` casts at registration are erased once the gate has\n // narrowed the runtime type.\n return {\n dict: {\n fn: (...kv) => dict(...kv),\n argTypes: [\"string\", \"value\"],\n // Go: `dict(v ...interface{})` — no required arguments; `{{ dict }}`\n // is an empty dict. The cycle pairs even-index keys with\n // odd-index values.\n arity: { kind: \"alternating\", minimum: 0 },\n },\n get: {\n fn: (d, k) => get(d as Record<string, unknown>, k as string),\n argTypes: [\"dict\", \"string\"],\n arity: { kind: \"exact\" },\n },\n set: {\n fn: (d, k, v) => set(d as Record<string, unknown>, k as string, v),\n argTypes: [\"dict\", \"string\", \"value\"],\n arity: { kind: \"exact\" },\n // Go's `set` writes into the dict it is handed and returns it.\n writes: true,\n },\n unset: {\n fn: (d, k) => unset(d as Record<string, unknown>, k as string),\n argTypes: [\"dict\", \"string\"],\n arity: { kind: \"exact\" },\n writes: true,\n },\n // Go: `keys(dicts ...map[string]interface{})` — variadic, so no\n // argument is required and every dict past the first contributes\n // its keys too. `arity` declares Go's gate, not what this body\n // currently consumes: the body reads one dict, ignores the rest,\n // and throws on none where Go returns `[]`. Narrowing the arity to\n // match the body would paper over that gap and invent a divergence\n // the gate would then enforce; the gap is tracked on the\n // conformance epic instead.\n keys: {\n fn: (d) => keys(d as Record<string, unknown>),\n argTypes: [\"dict\"],\n arity: { kind: \"variadic\" },\n },\n values: {\n fn: (d) => values(d as Record<string, unknown>),\n argTypes: [\"dict\"],\n arity: { kind: \"exact\" },\n },\n pluck: {\n fn: (k, ...d) => pluck(k as string, ...(d as Record<string, unknown>[])),\n argTypes: [\"string\", \"dict\"],\n arity: { kind: \"variadic\" },\n },\n pick: {\n fn: (d, ...k) => pick(d as Record<string, unknown>, ...(k as string[])),\n argTypes: [\"dict\", \"string\"],\n arity: { kind: \"variadic\" },\n },\n omit: {\n fn: (d, ...k) => omit(d as Record<string, unknown>, ...(k as string[])),\n argTypes: [\"dict\", \"string\"],\n arity: { kind: \"variadic\" },\n },\n hasKey: {\n fn: (d, k) => hasKey(d as Record<string, unknown>, k as string),\n argTypes: [\"dict\", \"string\"],\n arity: { kind: \"exact\" },\n },\n merge: {\n fn: (d, ...s) => merge(d as Record<string, unknown>, ...(s as Record<string, unknown>[])),\n argTypes: [\"dict\", \"dict\"],\n arity: { kind: \"variadic\" },\n },\n mergeOverwrite: {\n fn: (d, ...s) =>\n mergeOverwrite(d as Record<string, unknown>, ...(s as Record<string, unknown>[])),\n argTypes: [\"dict\", \"dict\"],\n arity: { kind: \"variadic\" },\n },\n };\n}\n","/**\n * `fail msg` — unconditionally abort template evaluation with `msg`.\n *\n * Mirrors Go sprig's `fail`, which returns `(string, error)` and causes\n * text/template to stop execution. Throws `FailError` so consumers can\n * catch it specifically and distinguish it from engine errors.\n *\n * [LAW:types-are-the-program] Return type `never` encodes the invariant\n * that this function never returns — the type system enforces what a\n * comment would only suggest.\n */\n\nimport { FailError } from \"../../errors.js\";\n\nexport function fail(msg: string): never {\n throw new FailError(msg);\n}\n","/**\n * Sprig flow-control functions — `fail`.\n *\n * [LAW:single-enforcer] One module owns the FuncMap registration.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { fail } from \"./fail.js\";\n\nexport { fail };\n\nexport function sprigFlow(): FuncMap {\n return {\n fail: { fn: (msg) => fail(msg as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n };\n}\n","const _enc = new TextEncoder();\nconst MOD_ADLER = 65521;\n\n/**\n * `adler32sum s` — Adler-32 checksum of `s` as a decimal string.\n *\n * Matches Go's `hash/adler32.Checksum([]byte(s))` formatted with `%d`.\n * Uses unsigned 32-bit arithmetic via `>>> 0` to mirror Go's uint32 result.\n */\nexport function adler32sum(s: string): string {\n const bytes = _enc.encode(s);\n let a = 1;\n let b = 0;\n for (const byte of bytes) {\n a = (a + byte) % MOD_ADLER;\n b = (b + a) % MOD_ADLER;\n }\n return String((b * 65536 + a) >>> 0);\n}\n","/**\n * [LAW:one-source-of-truth] RFC 4648 base32 alphabet and decode table —\n * shared by b32enc and b32dec.\n */\n\nexport const ALPHA32 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n\n/** Reverse lookup: character → 5-bit value. */\nexport const DECODE32: ReadonlyMap<string, number> = new Map(\n Array.from(ALPHA32).map((c, i) => [c, i] as [string, number]),\n);\n","import { DECODE32 } from \"./_b32.js\";\n\nconst _dec = new TextDecoder();\n\n/** `b32dec s` — RFC 4648 base32 decoded back to a UTF-8 string. */\nexport function b32dec(s: string): string {\n const stripped = s.replace(/=+$/, \"\").toUpperCase();\n const bytes: number[] = [];\n let bits = 0;\n let value = 0;\n for (const c of stripped) {\n const v = DECODE32.get(c);\n if (v === undefined) throw new Error(`b32dec: invalid character '${c}'`);\n value = (value << 5) | v;\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n bytes.push((value >> bits) & 0xff);\n }\n }\n return _dec.decode(new Uint8Array(bytes));\n}\n","import { ALPHA32 } from \"./_b32.js\";\n\nconst _enc = new TextEncoder();\n\n/** `b32enc s` — UTF-8 bytes of `s` encoded as RFC 4648 base32. */\nexport function b32enc(s: string): string {\n const bytes = _enc.encode(s);\n let result = \"\";\n let bits = 0;\n let value = 0;\n for (const byte of bytes) {\n value = (value << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n result += ALPHA32[(value >> bits) & 31];\n }\n }\n if (bits > 0) result += ALPHA32[(value << (5 - bits)) & 31];\n while (result.length % 8 !== 0) result += \"=\";\n return result;\n}\n","const _dec = new TextDecoder();\n\n/** `b64dec s` — standard base64 decoded back to a UTF-8 string. */\nexport function b64dec(s: string): string {\n const binary = atob(s);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return _dec.decode(bytes);\n}\n","const _enc = new TextEncoder();\n\n/** `b64enc s` — UTF-8 bytes of `s` encoded as standard base64. */\nexport function b64enc(s: string): string {\n const bytes = _enc.encode(s);\n const chars = [];\n for (const b of bytes) chars.push(String.fromCharCode(b));\n return btoa(chars.join(\"\"));\n}\n","import { sha1 } from \"@noble/hashes/legacy.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\n\n/** `sha1sum s` — hex-encoded SHA-1 digest of `s` (UTF-8). */\nexport function sha1sum(s: string): string {\n return bytesToHex(sha1(utf8ToBytes(s)));\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\n\n/** `sha256sum s` — hex-encoded SHA-256 digest of `s` (UTF-8). */\nexport function sha256sum(s: string): string {\n return bytesToHex(sha256(utf8ToBytes(s)));\n}\n","import { sha512 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\n\n/** `sha512sum s` — hex-encoded SHA-512 digest of `s` (UTF-8). */\nexport function sha512sum(s: string): string {\n return bytesToHex(sha512(utf8ToBytes(s)));\n}\n","/**\n * `uuidv4` — RFC 4122 v4 UUID via `globalThis.crypto.randomUUID()`.\n *\n * Available in Node >= 20.19 (package minimum), Bun, Deno, and all modern browsers.\n * Throws if the runtime lacks `crypto.randomUUID` — this should never\n * happen in the supported environment set.\n */\nexport function uuidv4(): string {\n // [LAW:no-defensive-null-guards] We assert availability rather than silently\n // falling back: a missing crypto.randomUUID is a configuration problem that\n // should surface loudly, not be papered over with a Math.random fallback.\n if (typeof globalThis.crypto?.randomUUID !== \"function\") {\n throw new Error(\"uuidv4: globalThis.crypto.randomUUID is not available\");\n }\n return globalThis.crypto.randomUUID();\n}\n","/**\n * Sprig hash, encoding, and UUID functions — `b64enc`, `b64dec`, `b32enc`,\n * `b32dec`, `sha1sum`, `sha256sum`, `sha512sum`, `adler32sum`, `uuidv4`.\n *\n * All functions are pure and synchronous. SHA-* use @noble/hashes (audited,\n * zero-dep, ~5 KB gzipped per family); encoding is hand-rolled per RFC 4648;\n * UUID uses globalThis.crypto.randomUUID.\n *\n * [LAW:single-enforcer] FuncMap registration is the only place that maps\n * sprig template names to implementations.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { adler32sum } from \"./adler32sum.js\";\nimport { b32dec } from \"./b32dec.js\";\nimport { b32enc } from \"./b32enc.js\";\nimport { b64dec } from \"./b64dec.js\";\nimport { b64enc } from \"./b64enc.js\";\nimport { sha1sum } from \"./sha1sum.js\";\nimport { sha256sum } from \"./sha256sum.js\";\nimport { sha512sum } from \"./sha512sum.js\";\nimport { uuidv4 } from \"./uuidv4.js\";\n\nexport { adler32sum, b32dec, b32enc, b64dec, b64enc, sha1sum, sha256sum, sha512sum, uuidv4 };\n\n/** Build the sprig hash/encoding FuncMap. */\nexport function sprigHash(): FuncMap {\n return {\n b64enc: { fn: (s) => b64enc(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n b64dec: { fn: (s) => b64dec(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n b32enc: { fn: (s) => b32enc(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n b32dec: { fn: (s) => b32dec(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n sha1sum: { fn: (s) => sha1sum(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n sha256sum: {\n fn: (s) => sha256sum(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n },\n sha512sum: {\n fn: (s) => sha512sum(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n },\n adler32sum: {\n fn: (s) => adler32sum(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n },\n uuidv4: { fn: () => uuidv4(), argTypes: [], arity: { kind: \"exact\" } },\n };\n}\n","/**\n * `all v1 v2 …` — true iff `empty(x)` is false for every argument.\n * An empty argument list returns true (Go sprig: vacuous truth).\n *\n * [LAW:one-source-of-truth] Truthiness uses the same `empty()` helper\n * the rest of the sprig surface (default, coalesce, empty) routes\n * through, so \"is this empty?\" has exactly one answer.\n */\n\nimport { empty } from \"../defaults/empty.js\";\n\nexport function all(...values: readonly unknown[]): boolean {\n for (const v of values) {\n if (empty(v)) return false;\n }\n return true;\n}\n","/**\n * `any v1 v2 …` — true iff `empty(x)` is false for at least one\n * argument. An empty argument list returns false.\n *\n * [LAW:one-source-of-truth] Truthiness uses the same `empty()` helper\n * the rest of the sprig surface (default, coalesce, empty) routes\n * through, so \"is this empty?\" has exactly one answer.\n */\n\nimport { empty } from \"../defaults/empty.js\";\n\nexport function any(...values: readonly unknown[]): boolean {\n for (const v of values) {\n if (!empty(v)) return true;\n }\n return false;\n}\n","/** `append list item` — add item at the end. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function append(list: unknown[], item: unknown): unknown[] {\n return [...list, item];\n}\n","/** `chunk size list` — split list into sub-lists of `size`. */\n// [LAW:single-enforcer] The \"int\" gate admits only an integer `size`\n// (Go declares it `int`); the \"list\" gate validates array-ness. Body clamps the lower\n// bound to 1 (domain rule: chunks of <1 are nonsensical).\nexport function chunk(size: number, list: unknown[]): unknown[][] {\n const n = Math.max(1, size);\n const out: unknown[][] = [];\n for (let i = 0; i < list.length; i += n) {\n out.push(list.slice(i, i + n));\n }\n return out;\n}\n","import { empty } from \"../defaults/empty.js\";\n\n/** `compact list` — drop empty values per sprig's `empty` rules. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function compact(list: unknown[]): unknown[] {\n return list.filter((v) => !empty(v));\n}\n","/** `concat a b c …` — flat-concat lists. */\n// [LAW:single-enforcer] The variadic \"list\" slot validates array-ness\n// for every argument; this body trusts the param type and skips the\n// per-element Array.isArray guard.\nexport function concat(...lists: unknown[][]): unknown[] {\n const out: unknown[] = [];\n for (const l of lists) {\n out.push(...l);\n }\n return out;\n}\n","/**\n * Re-exports from the unified error module, plus a small helper for\n * constructing `TypeMismatchError` from inside sprig func bodies.\n *\n * Historical location — code that imported from this path keeps\n * working. New code should import directly from `src/errors.ts`.\n */\n\nimport { TypeMismatchError } from \"../errors.js\";\n\nexport {\n type ArgCount,\n ArgCountError,\n EvalError,\n FuncNotFoundError,\n MissingFieldError,\n TemplateError,\n TypeMismatchError,\n} from \"../errors.js\";\n\nconst NO_POS = { line: 0, column: 0, offset: 0 } as const;\n\n/**\n * Construct a TypeMismatchError from inside a registered func body,\n * where the call-site `pos` is unavailable. The dispatch site\n * (`evalCommand`) catches this and re-emits with the correct pos —\n * see [LAW:single-enforcer] in evaluator.ts.\n *\n * Use when the gate cannot validate (nested elements, alternating\n * variadic positions). For first-class arg validation, declare the\n * type in `argTypes` so `enforceArgTypes` catches it at the boundary.\n */\nexport function bodyTypeMismatch(\n funcName: string,\n argIndex: number,\n expected: string,\n receivedSummary: string,\n): TypeMismatchError {\n return new TypeMismatchError(funcName, argIndex, expected, receivedSummary, NO_POS);\n}\n","/**\n * `dig key1 key2 … default dict` — walks nested dict by string keys,\n * returning the deepest value found, or `default` when a key along\n * the path is missing.\n *\n * The argument shape is *positional from the end*:\n *\n * dig \"a\" \"b\" \"c\" <default> <dict>\n *\n * — last arg is the dict, the one before it is the default, every\n * preceding arg is a string key. This shape comes straight from Go\n * sprig and is unintuitive but documented.\n *\n * [LAW:single-enforcer] exception: `argTypes: [\"value\"]` (variadic\n * trailing slot) — the from-the-end positional shape cannot be\n * expressed by the gate's positional-from-the-start + trailing-repeat\n * model. We accept body-side validation here and use\n * `bodyTypeMismatch` so failures still surface as TypeMismatchError\n * with the correct call-site pos.\n */\n\nimport { typeNameOf } from \"../../evaluator/builtins.js\";\nimport { bodyTypeMismatch } from \"../../evaluator/errors.js\";\n\nexport function dig(...args: unknown[]): unknown {\n if (args.length < 3) {\n // Match Go's `panic(\"dig needs at least three arguments\")`.\n throw bodyTypeMismatch(\n \"dig\",\n 0,\n \"at least 3 arguments (...keys, default, dict)\",\n `${args.length} argument${args.length === 1 ? \"\" : \"s\"}`,\n );\n }\n const dict = args[args.length - 1];\n const def = args[args.length - 2];\n const keys = args.slice(0, -2);\n\n if (!isPlainDict(dict)) {\n throw bodyTypeMismatch(\"dig\", args.length - 1, \"dict\", typeNameOf(dict));\n }\n for (let i = 0; i < keys.length; i++) {\n if (typeof keys[i] !== \"string\") {\n throw bodyTypeMismatch(\"dig\", i, \"string\", typeNameOf(keys[i]));\n }\n }\n\n return digFromDict(dict as Record<string, unknown>, def, keys as string[], args.length);\n}\n\nfunction digFromDict(\n d: Record<string, unknown>,\n def: unknown,\n ks: readonly string[],\n argCount: number,\n): unknown {\n const k = ks[0] as string;\n if (!Object.hasOwn(d, k)) return def;\n const step = d[k];\n if (ks.length === 1) return step;\n // Go would `step.(map[string]interface{})` here, panicking on a\n // non-map intermediate. Mirror that — surface it as a typed error\n // rather than letting JS coerce silently.\n if (!isPlainDict(step)) {\n // Attribute to dict arg (last arg position).\n throw bodyTypeMismatch(\"dig\", argCount - 1, \"dict at intermediate key\", typeNameOf(step));\n }\n return digFromDict(step as Record<string, unknown>, def, ks.slice(1), argCount);\n}\n\nfunction isPlainDict(v: unknown): v is Record<string, unknown> {\n return (\n v !== null &&\n typeof v === \"object\" &&\n !Array.isArray(v) &&\n !(v instanceof Map) &&\n !(v instanceof Set)\n );\n}\n","// [LAW:single-enforcer] The \"list\" gate validates array-ness; this\n// body trusts the param type. Per Go sprig, `first` accepts lists only\n// — strings are not lists, so the previous string fallback is gone.\nexport function first(list: unknown[]): unknown {\n return list[0];\n}\n","import { deepEqual } from \"../types/deepEqual.js\";\n\n/** `has item list` — true iff `item` ∈ `list`. Note arg order matches Go sprig. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\n// [LAW:one-source-of-truth] Element equality routes through `deepEqual`,\n// matching Go sprig's `reflect.DeepEqual` (closes audit G4).\nexport function has(item: unknown, list: unknown[]): boolean {\n return list.some((e) => deepEqual(e, item));\n}\n","/** All elements except the last. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function initial(list: unknown[]): unknown[] {\n return list.slice(0, -1);\n}\n","// [LAW:single-enforcer] The \"list\" gate validates array-ness; this\n// body trusts the param type. Per Go sprig, `last` accepts lists only\n// — strings are not lists, so the previous string fallback is gone.\nexport function last(list: unknown[]): unknown {\n return list[list.length - 1];\n}\n","/**\n * Sprig `len` — same shape as the evaluator's built-in `len`. Re-exposed\n * here so the sprig category is self-contained per the epic's required\n * layout.\n *\n * [LAW:single-enforcer] Sized-kind validation lives at the gate via\n * argTypes: [\"sized\"]. The body picks the per-kind readout; nil and\n * non-sized values are rejected once by `enforceArgTypes`, never here.\n */\nexport function len(value: unknown): number {\n if (Array.isArray(value)) return value.length;\n if (typeof value === \"string\") return value.length;\n if (value instanceof Map) return value.size;\n if (value instanceof Set) return value.size;\n return Object.keys(value as object).length;\n}\n","/** `list a b c …` — constructs a list from the given items. */\nexport function list(...items: unknown[]): unknown[] {\n return items;\n}\n","/** `prepend list item` — add item at the front. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function prepend(list: unknown[], item: unknown): unknown[] {\n return [item, ...list];\n}\n","/** All elements except the first. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function rest(list: unknown[]): unknown[] {\n return list.slice(1);\n}\n","// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function reverse(list: unknown[]): unknown[] {\n return [...list].reverse();\n}\n","/** `slice list [i [j]]` — Array.prototype.slice. */\n// [LAW:single-enforcer] The \"list\" and \"truncating-int\" gates validate\n// array-ness and hand over indices truncated toward zero (sprig's cast);\n// missing trailing args remain undefined (the gate loops only over\n// present values), so i/j stay optional but never null.\nexport function slice(list: unknown[], i?: number, j?: number): unknown[] {\n const start = i === undefined ? 0 : i;\n const end = j === undefined ? list.length : j;\n return list.slice(start, end);\n}\n","/**\n * `sortAlpha list` — stringify each element, sort lexicographically.\n * Returns `string[]`.\n *\n * Mirrors Go sprig's `sortAlpha`, which calls `strslice` (skips nil\n * entries, stringifies the rest via `strval`) then `sort.StringSlice`.\n * `String(v)` lines up with Go's `%v` for primitives; non-ASCII byte\n * ordering is identical to Go's `sort.StringSlice` for ASCII input\n * (the only kind the conformance fixtures exercise).\n */\n\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\nexport function sortAlpha(list: readonly unknown[]): string[] {\n const out: string[] = [];\n for (const v of list) {\n // Go's `strslice` skips nil entries — match.\n if (v === null || v === undefined) continue;\n out.push(String(v));\n }\n return out.sort();\n}\n","import { deepEqual } from \"../types/deepEqual.js\";\n\n/** Unique values, preserving first-occurrence order. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\n// [LAW:one-source-of-truth] Element equality routes through `deepEqual`,\n// matching Go sprig's `reflect.DeepEqual` (closes audit G4).\nexport function uniq(list: unknown[]): unknown[] {\n const out: unknown[] = [];\n for (const v of list) if (!out.some((e) => deepEqual(e, v))) out.push(v);\n return out;\n}\n","import { deepEqual } from \"../types/deepEqual.js\";\n\n/** `without list a b c …` — drop any of a/b/c… from list. */\n// [LAW:single-enforcer] The \"list\" gate validates array-ness.\n// [LAW:one-source-of-truth] Element equality routes through `deepEqual`,\n// matching Go sprig's `reflect.DeepEqual` (closes audit G4).\nexport function without(list: unknown[], ...exclude: unknown[]): unknown[] {\n return list.filter((v) => !exclude.some((e) => deepEqual(e, v)));\n}\n","/** Sprig list utilities — pair-files per epic spec. */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { all } from \"./all.js\";\nimport { any } from \"./any.js\";\nimport { append } from \"./append.js\";\nimport { chunk } from \"./chunk.js\";\nimport { compact } from \"./compact.js\";\nimport { concat } from \"./concat.js\";\nimport { dig } from \"./dig.js\";\nimport { first } from \"./first.js\";\nimport { has } from \"./has.js\";\nimport { initial } from \"./initial.js\";\nimport { last } from \"./last.js\";\nimport { len } from \"./len.js\";\nimport { list } from \"./list.js\";\nimport { prepend } from \"./prepend.js\";\nimport { rest } from \"./rest.js\";\nimport { reverse } from \"./reverse.js\";\nimport { slice } from \"./slice.js\";\nimport { sortAlpha } from \"./sortAlpha.js\";\nimport { uniq } from \"./uniq.js\";\nimport { without } from \"./without.js\";\n\nexport {\n all,\n any,\n append,\n chunk,\n compact,\n concat,\n dig,\n first,\n has,\n initial,\n last,\n len,\n list,\n prepend,\n rest,\n reverse,\n slice,\n sortAlpha,\n uniq,\n without,\n};\n\nexport function sprigLists(): FuncMap {\n // [LAW:single-enforcer] List slots declare \"list\" so the gate enforces\n // array-ness once. Bodies trust the param type and drop the defensive\n // `Array.isArray` guards that previously duplicated the check 14 times.\n // Item slots that are genuinely heterogeneous use \"value\" — they still\n // accept anything, but the label documents intent (per template-laws-3gt.1).\n // `len` declares \"sized\" (template-laws-3gt.4) — the body trusts the\n // gate. `list` (constructor) declares \"value\" (template-laws-3gt.8)\n // — heterogeneous-by-intent.\n return {\n list: {\n fn: (...a) => list(...a),\n argTypes: [\"value\"],\n arity: { kind: \"variadic\" },\n },\n first: { fn: (l) => first(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n last: { fn: (l) => last(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n rest: { fn: (l) => rest(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n initial: { fn: (l) => initial(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n len: { fn: (l) => len(l), argTypes: [\"sized\"], arity: { kind: \"exact\" } },\n reverse: { fn: (l) => reverse(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n uniq: { fn: (l) => uniq(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n without: {\n fn: (l, ...e) => without(l as unknown[], ...e),\n argTypes: [\"list\", \"value\"],\n arity: { kind: \"variadic\" },\n },\n has: {\n fn: (i, l) => has(i, l as unknown[]),\n argTypes: [\"value\", \"list\"],\n arity: { kind: \"exact\" },\n },\n compact: { fn: (l) => compact(l as unknown[]), argTypes: [\"list\"], arity: { kind: \"exact\" } },\n // Go: `slice(list interface{}, indices ...interface{})` — one\n // required list and any number of indices, so `slice .l 1` and\n // `slice .l` are both legal. Declaring three fixed slots would make\n // the gate reject them, inventing a divergence. The repeating\n // \"truncating-int\" slot covers both indices: sprig reads them through\n // `cast.ToInt`, which truncates a fractional.\n slice: {\n fn: (l, i, j) => slice(l as unknown[], i as number | undefined, j as number | undefined),\n argTypes: [\"list\", \"truncating-int\"],\n arity: { kind: \"variadic\" },\n },\n concat: {\n fn: (...l) => concat(...(l as unknown[][])),\n argTypes: [\"list\"],\n arity: { kind: \"variadic\" },\n },\n chunk: {\n fn: (s, l) => chunk(s as number, l as unknown[]),\n argTypes: [\"int\", \"list\"],\n arity: { kind: \"exact\" },\n },\n prepend: {\n fn: (l, i) => prepend(l as unknown[], i),\n argTypes: [\"list\", \"value\"],\n arity: { kind: \"exact\" },\n },\n append: {\n fn: (l, i) => append(l as unknown[], i),\n argTypes: [\"list\", \"value\"],\n arity: { kind: \"exact\" },\n },\n sortAlpha: {\n fn: (l) => sortAlpha(l as unknown[]),\n argTypes: [\"list\"],\n arity: { kind: \"exact\" },\n returnType: \"list\",\n },\n // [LAW:one-source-of-truth] `push` is Go sprig's deprecated alias for\n // `append`. Registered directly against the same closure so divergence\n // is impossible — same pattern as `biggest`→`max` in sprigMath.\n push: {\n fn: (l, i) => append(l as unknown[], i),\n argTypes: [\"list\", \"value\"],\n arity: { kind: \"exact\" },\n },\n // [LAW:one-source-of-truth] `tuple` is Go sprig's alias for `list`.\n tuple: {\n fn: (...a) => list(...a),\n argTypes: [\"value\"],\n arity: { kind: \"variadic\" },\n },\n // [LAW:single-enforcer] exception: `dig`'s \"...keys, default, dict\"\n // shape is positional from the *end* — the gate's positional-from-the-\n // start + trailing-repeat model can't express it. Body-side validation\n // surfaces failures via `bodyTypeMismatch` so call-site pos is preserved.\n // Go: `dig(ps ...interface{})` — the arity gate requires nothing.\n // Sprig's own \"dig needs at least three arguments\" is a body-side\n // panic, not an arity error, and `dig`'s body already reproduces it.\n // Declaring a minimum of 3 here would move that failure to the gate\n // and change its message away from Go's.\n dig: {\n fn: (...a) => dig(...a),\n argTypes: [\"value\"],\n arity: { kind: \"variadic\" },\n },\n all: {\n fn: (...a) => all(...a),\n argTypes: [\"truthy\"],\n arity: { kind: \"variadic\" },\n returnType: \"bool\",\n },\n any: {\n fn: (...a) => any(...a),\n argTypes: [\"truthy\"],\n arity: { kind: \"variadic\" },\n returnType: \"bool\",\n },\n };\n}\n","/** `add a b c …` — variadic integer sum. */\nexport function add(...args: number[]): number {\n return args.reduce((acc, v) => acc + v, 0);\n}\n","/** `add1 n` — integer increment. Mirrors Go sprig's `add1(i interface{}) int64`. */\nexport function add1(n: number): number {\n return n + 1;\n}\n","/** `add1f n` — float increment. Mirrors Go sprig's `add1f(i interface{}) float64`. */\nexport function add1f(n: number): number {\n return n + 1;\n}\n","export function addf(...args: number[]): number {\n return args.reduce((acc, v) => acc + v, 0);\n}\n","export function ceil(a: number): number {\n return Math.ceil(a);\n}\n","/** `div a b` — integer division (Go semantics: truncate toward zero). */\nexport function div(a: number, b: number): number {\n return Math.trunc(a / b);\n}\n","export function divf(a: number, ...rest: number[]): number {\n return rest.reduce((acc, v) => acc / v, a);\n}\n","export function floor(a: number): number {\n return Math.floor(a);\n}\n","/** `max a b c …` — variadic maximum (Go int64 semantics; args arrive truncated). */\nexport function max(...args: number[]): number {\n return args.reduce((m, v) => (v > m ? v : m), Number.NEGATIVE_INFINITY);\n}\n","/**\n * `maxf a b c …` — variadic float-typed maximum. Mirrors Go sprig's\n * `maxf` (float64, no truncation). Distinct from `max` (int64-truncated).\n */\nexport function maxf(...args: number[]): number {\n return args.reduce((m, v) => Math.max(m, v), -Infinity);\n}\n","/** `min a b c …` — variadic minimum (Go int64 semantics; args arrive truncated). */\nexport function min(...args: number[]): number {\n return args.reduce((m, v) => (v < m ? v : m), Number.POSITIVE_INFINITY);\n}\n","/** `minf a b c …` — variadic float-typed minimum. Float counterpart of `min` (int64-truncated). */\nexport function minf(...args: number[]): number {\n return args.reduce((m, v) => Math.min(m, v), Infinity);\n}\n","/** `mod a b` — modulo. JS `%` matches Go's: sign follows the dividend. */\nexport function mod(a: number, b: number): number {\n return a % b;\n}\n","/** `mul a b c …` — variadic integer product. */\nexport function mul(...args: number[]): number {\n return args.reduce((acc, v) => acc * v, 1);\n}\n","export function mulf(...args: number[]): number {\n return args.reduce((acc, v) => acc * v, 1);\n}\n","/** `round a [precision=0]` — round half-away-from-zero, matching Go sprig. */\nexport function round(a: number, precision: number = 0): number {\n const factor = 10 ** precision;\n return (Math.sign(a) * Math.round(Math.abs(a) * factor)) / factor;\n}\n","/**\n * `untilStep start stop step` — Python-`range`-shaped integer slice.\n * Mirrors Go sprig's `untilStep(start, stop, step int) []int`. Step\n * direction must agree with the start→stop direction; mismatched signs\n * (e.g. `start < stop` with `step <= 0`) yield an empty slice rather\n * than looping forever.\n */\n\nexport function untilStep(start: number, stop: number, step: number): number[] {\n const v: number[] = [];\n if (stop < start) {\n if (step >= 0) return v;\n for (let i = start; i > stop; i += step) v.push(i);\n return v;\n }\n if (step <= 0) return v;\n for (let i = start; i < stop; i += step) v.push(i);\n return v;\n}\n","/**\n * `seq …` — space-joined integer sequence. Mirrors Go sprig's `seq`,\n * which dispatches on arity and is **inclusive** of the end value:\n *\n * seq() → \"\"\n * seq(end) → 1..end (descending if end<1)\n * seq(start, end) → start..end (step ±1 by direction)\n * seq(start, step, end) → stepped, end inclusive when reached\n * 4+ args → \"\"\n *\n * Inclusivity is implemented the same way Go does it — by passing\n * `end + increment` (or `end + step` for the 2-arg case) into the\n * exclusive `untilStep`. The 3-arg form returns \"\" when the bounds\n * descend (`end < start`) but the caller passes a positive step —\n * matching Go's early-return at `if step > 0 { return \"\" }`.\n *\n * Output is the int slice joined with \" \", so `{{ seq 5 }}` emits\n * `1 2 3 4 5`. Result type is `string`, **not** `number[]`.\n */\n\nimport { untilStep } from \"./untilStep.js\";\n\nexport function seq(...params: number[]): string {\n let increment = 1;\n switch (params.length) {\n case 0:\n return \"\";\n case 1: {\n const start = 1;\n const end = params[0] as number;\n if (end < start) increment = -1;\n return untilStep(start, end + increment, increment).join(\" \");\n }\n case 2: {\n const start = params[0] as number;\n const end = params[1] as number;\n const step = end < start ? -1 : 1;\n return untilStep(start, end + step, step).join(\" \");\n }\n case 3: {\n const start = params[0] as number;\n const step = params[1] as number;\n const end = params[2] as number;\n if (end < start) {\n increment = -1;\n if (step > 0) return \"\";\n }\n return untilStep(start, end + increment, step).join(\" \");\n }\n default:\n return \"\";\n }\n}\n","export function sub(a: number, b: number): number {\n return a - b;\n}\n","export function subf(a: number, ...rest: number[]): number {\n return rest.reduce((acc, v) => acc - v, a);\n}\n","/**\n * `until count` — `[0, 1, …, count-1]` for positive counts, or\n * `[0, -1, …, count+1]` for negative counts. Mirrors Go sprig's\n * `until`, which derives step direction from the sign of `count`\n * and delegates to `untilStep`.\n */\n\nimport { untilStep } from \"./untilStep.js\";\n\nexport function until(count: number): number[] {\n return untilStep(0, count, count < 0 ? -1 : 1);\n}\n","/** Sprig math utilities — int and float arithmetic. */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { add } from \"./add.js\";\nimport { add1 } from \"./add1.js\";\nimport { add1f } from \"./add1f.js\";\nimport { addf } from \"./addf.js\";\nimport { ceil } from \"./ceil.js\";\nimport { div } from \"./div.js\";\nimport { divf } from \"./divf.js\";\nimport { floor } from \"./floor.js\";\nimport { max } from \"./max.js\";\nimport { maxf } from \"./maxf.js\";\nimport { min } from \"./min.js\";\nimport { minf } from \"./minf.js\";\nimport { mod } from \"./mod.js\";\nimport { mul } from \"./mul.js\";\nimport { mulf } from \"./mulf.js\";\nimport { round } from \"./round.js\";\nimport { seq } from \"./seq.js\";\nimport { sub } from \"./sub.js\";\nimport { subf } from \"./subf.js\";\nimport { until } from \"./until.js\";\nimport { untilStep } from \"./untilStep.js\";\n\nexport {\n add,\n add1,\n add1f,\n addf,\n ceil,\n div,\n divf,\n floor,\n max,\n maxf,\n min,\n minf,\n mod,\n mul,\n mulf,\n round,\n seq,\n sub,\n subf,\n until,\n untilStep,\n};\n\nexport function sprigMath(): FuncMap {\n // [LAW:single-enforcer] enforceArgTypes normalizes numeric slots to\n // plain `number` before dispatch. Sprig reads its `interface{}` math\n // arguments through `cast.ToInt64`, so those slots are\n // \"truncating-int\" (`max 1.5 2.5` is 2); `seq`/`until`/`untilStep` and\n // `round`'s precision are Go `int` parameters, so they are \"int\" and\n // refuse a fractional. \"float\" arrives coerced (IEEE-754 semantics).\n // Bodies receive `number`, never `bigint`.\n return {\n add: {\n fn: (...a) => add(...(a as number[])),\n argTypes: [\"truncating-int\"],\n arity: { kind: \"variadic\" },\n },\n sub: {\n fn: (a, b) => sub(a as number, b as number),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"exact\" },\n },\n mul: {\n fn: (...a) => mul(...(a as number[])),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"variadic\" },\n },\n div: {\n fn: (a, b) => div(a as number, b as number),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"exact\" },\n },\n mod: {\n fn: (a, b) => mod(a as number, b as number),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"exact\" },\n },\n min: {\n fn: (...a) => min(...(a as number[])),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"variadic\" },\n },\n max: {\n fn: (...a) => max(...(a as number[])),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"variadic\" },\n },\n floor: { fn: (a) => floor(a as number), argTypes: [\"float\"], arity: { kind: \"exact\" } },\n ceil: { fn: (a) => ceil(a as number), argTypes: [\"float\"], arity: { kind: \"exact\" } },\n // Go: `round(a interface{}, p int, rOpt ...float64)` — the\n // precision is a *required* parameter and only the rounding\n // threshold is variadic, so Go rejects `round 3.7`. `arity`\n // declares that gate; the body's `precision = 0` default and its\n // silent drop of `rOpt` are body-side gaps tracked on the\n // conformance epic, not reasons to widen the declaration.\n round: {\n fn: (a, p) => round(a as number, p as number),\n argTypes: [\"float\", \"int\", \"float\"],\n arity: { kind: \"variadic\" },\n },\n addf: {\n fn: (...a) => addf(...(a as number[])),\n argTypes: [\"float\"],\n arity: { kind: \"variadic\" },\n },\n // Go: `subf(a interface{}, v ...interface{})` — folds over every\n // argument, unlike the integer `sub`, which Go declares with two\n // fixed parameters.\n subf: {\n fn: (a, ...rest) => subf(a as number, ...(rest as number[])),\n argTypes: [\"float\", \"float\"],\n arity: { kind: \"variadic\" },\n },\n mulf: {\n fn: (...a) => mulf(...(a as number[])),\n argTypes: [\"float\", \"float\"],\n arity: { kind: \"variadic\" },\n },\n // Go: `divf(a interface{}, v ...interface{})` — folds over every\n // argument, unlike the integer `div`.\n divf: {\n fn: (a, ...rest) => divf(a as number, ...(rest as number[])),\n argTypes: [\"float\", \"float\"],\n arity: { kind: \"variadic\" },\n },\n add1: { fn: (n) => add1(n as number), argTypes: [\"truncating-int\"], arity: { kind: \"exact\" } },\n add1f: { fn: (n) => add1f(n as number), argTypes: [\"float\"], arity: { kind: \"exact\" } },\n maxf: {\n fn: (...a) => maxf(...(a as number[])),\n argTypes: [\"float\", \"float\"],\n arity: { kind: \"variadic\" },\n },\n minf: {\n fn: (...a) => minf(...(a as number[])),\n argTypes: [\"float\", \"float\"],\n arity: { kind: \"variadic\" },\n },\n // `biggest` is Go sprig's deprecated alias for `max`. Registered\n // directly against the same function so divergence is impossible.\n biggest: {\n fn: (...a) => max(...(a as number[])),\n argTypes: [\"truncating-int\", \"truncating-int\"],\n arity: { kind: \"variadic\" },\n },\n seq: {\n fn: (...a) => seq(...(a as number[])),\n argTypes: [\"int\"],\n arity: { kind: \"variadic\" },\n returnType: \"string\",\n },\n until: {\n fn: (n) => until(n as number),\n argTypes: [\"int\"],\n arity: { kind: \"exact\" },\n returnType: \"list\",\n },\n untilStep: {\n fn: (a, b, c) => untilStep(a as number, b as number, c as number),\n argTypes: [\"int\", \"int\", \"int\"],\n arity: { kind: \"exact\" },\n returnType: \"list\",\n },\n };\n}\n","/**\n * Internal PRNG seam for sprig random functions.\n *\n * [LAW:single-enforcer] All randomness in this module routes through\n * the `random` parameter — never through `Math.random` directly. The\n * caller supplies the source; these helpers consume it.\n */\n\nexport class RandIntRangeError extends Error {\n constructor(min: number, max: number) {\n super(`randIntFromRange: max must be greater than min (max=${max}, min=${min})`);\n this.name = \"RandIntRangeError\";\n }\n}\n\n/** Clamp PRNG output to [0, 1) to defend against out-of-range injected sources. */\nexport function clampRandom(value: number): number {\n // [LAW:no-defensive-null-guards] Non-finite check is valid here: `random`\n // is caller-supplied (trust boundary), and NaN/Infinity are out-of-range.\n if (!Number.isFinite(value)) return 0;\n return Math.max(0, Math.min(value, 0.9999999999999999));\n}\n\nexport const ALPHA = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nexport const ALPHANUM = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\nexport const NUMERIC = \"0123456789\";\n// ASCII printable range 32–126 inclusive (matches Go sprig: Intn(95)+32).\nexport const ASCII = Array.from({ length: 95 }, (_, i) => String.fromCharCode(i + 32)).join(\"\");\n\nexport function randString(n: number, charset: string, random: () => number): string {\n const chars = [];\n for (let i = 0; i < n; i++) {\n chars.push(charset.charAt(Math.floor(clampRandom(random()) * charset.length)));\n }\n return chars.join(\"\");\n}\n\n/** Inclusive `min`, exclusive `max` — mirrors Go `rand.Intn(max-min)+min`. */\nexport function randIntFromRange(min: number, max: number, random: () => number): number {\n if (max <= min) throw new RandIntRangeError(min, max);\n return Math.floor(clampRandom(random()) * (max - min)) + min;\n}\n","import { ALPHA, randString } from \"./_prng.js\";\n\n/** `randAlpha n` — `n` random letters [A-Za-z]. */\nexport function randAlpha(n: number, random: () => number): string {\n return randString(n, ALPHA, random);\n}\n","import { ALPHANUM, randString } from \"./_prng.js\";\n\n/** `randAlphaNum n` — `n` random alphanumeric characters [A-Za-z0-9]. */\nexport function randAlphaNum(n: number, random: () => number): string {\n return randString(n, ALPHANUM, random);\n}\n","import { ASCII, randString } from \"./_prng.js\";\n\n/** `randAscii n` — `n` random printable ASCII characters (0x20–0x7E). */\nexport function randAscii(n: number, random: () => number): string {\n return randString(n, ASCII, random);\n}\n","import { bodyTypeMismatch } from \"../../evaluator/errors.js\";\nimport { RandIntRangeError, randIntFromRange } from \"./_prng.js\";\n\n/** `randInt min max` — random integer in [min, max). Mirrors Go sprig. */\nexport function randInt(min: number, max: number, random: () => number): number {\n try {\n return randIntFromRange(min, max, random);\n } catch (e) {\n if (e instanceof RandIntRangeError) {\n throw bodyTypeMismatch(\n \"randInt\",\n 2,\n \"max > min\",\n `constraint violated (max=${max}, min=${min})`,\n );\n }\n throw e;\n }\n}\n","import { NUMERIC, randString } from \"./_prng.js\";\n\n/** `randNumeric n` — `n` random decimal digits [0-9]. */\nexport function randNumeric(n: number, random: () => number): string {\n return randString(n, NUMERIC, random);\n}\n","/**\n * The rune-level string seam: the operations Go gets for free on its\n * strings and JS does not.\n *\n * [LAW:parse-dont-validate] Go walks a string as runes; JS strings are\n * UTF-16, so a character-position operation done on the raw string\n * (`s.slice(0, 1)`, `s[i]`, `s.length`, `s.split(\"\")`) splits an astral\n * character in half and yields a lone surrogate — `trunc 1 \"𐍈x\"`\n * returned \"\\ud800\", for which `isWellFormed()` is false. Decoding once,\n * up front, is the checkpoint: every element of the returned array is a\n * whole character, so an index into the middle of one is unrepresentable\n * and no slice of it can produce a lone surrogate. Callers re-encode\n * with `.join(\"\")`.\n *\n * Code points deliberately — not UTF-16 units, and not grapheme\n * clusters. Grapheme clustering would hold `\"é\"` together, a third\n * behaviour matching neither Go nor this engine.\n *\n * For splitting this buys exact Go parity. For slicing it buys\n * well-formedness instead: Go slices `trunc`/`substr`/`abbrev` by BYTE,\n * so `trunc 1 \"𐍈x\"` is the single invalid byte `\\xf0` there and the\n * whole `𐍈` here. That residual divergence is intended and tracked\n * separately; a rune is the closest well-formed unit to Go's byte.\n */\n\n/**\n * Decode `s` to its code points. The array is freshly built per call,\n * so callers may permute it in place (`shuffle` does).\n */\nexport function runes(s: string): string[] {\n return Array.from(s);\n}\n\n/**\n * `strings.Split(s, sep)` — an empty separator splits between runes,\n * where JS's `s.split(\"\")` splits between UTF-16 units and shears\n * astral characters into lone surrogates.\n *\n * [LAW:single-enforcer] `split`, `splitList`, `splitn`, and `replace`\n * all reach for Go's split; the empty-separator rule lives here so the\n * four cannot drift on it.\n */\nexport function goSplit(sep: string, s: string): string[] {\n return sep === \"\" ? runes(s) : s.split(sep);\n}\n","import { runes } from \"../strings/runes.js\";\nimport { clampRandom } from \"./_prng.js\";\n\n/**\n * `shuffle s` — returns a randomly permuted copy of `s`.\n *\n * Operates on Unicode code points (matching Go sprig's rune-level Fisher-Yates).\n */\nexport function shuffle(s: string, random: () => number): string {\n const cps = runes(s);\n for (let i = cps.length - 1; i > 0; i--) {\n const j = Math.floor(clampRandom(random()) * (i + 1));\n const tmp = cps[i] as string;\n cps[i] = cps[j] as string;\n cps[j] = tmp;\n }\n return cps.join(\"\");\n}\n","/**\n * Sprig random functions — `randInt`, `randAlpha`, `randAlphaNum`,\n * `randNumeric`, `randAscii`, `shuffle`.\n *\n * [LAW:single-enforcer] The `random` parameter is the *only* source of\n * randomness in this module. All six functions receive it from the\n * factory closure so there is one seam, not six.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { randAlpha } from \"./randAlpha.js\";\nimport { randAlphaNum } from \"./randAlphaNum.js\";\nimport { randAscii } from \"./randAscii.js\";\nimport { randInt } from \"./randInt.js\";\nimport { randNumeric } from \"./randNumeric.js\";\nimport { shuffle } from \"./shuffle.js\";\n\nexport { randAlpha, randAlphaNum, randAscii, randInt, randNumeric, shuffle };\n\n/**\n * Build the sprig random FuncMap.\n *\n * @param random - PRNG source. Defaults to `Math.random`. Pass a seeded\n * generator for reproducible templates (matches `EngineConfig.random`).\n */\nexport function sprigRandom(random: () => number = Math.random): FuncMap {\n return {\n randInt: {\n fn: (min, max) => randInt(min as number, max as number, random),\n argTypes: [\"int\", \"int\"],\n arity: { kind: \"exact\" },\n },\n randAlpha: {\n fn: (n) => randAlpha(n as number, random),\n argTypes: [\"int\"],\n arity: { kind: \"exact\" },\n },\n randAlphaNum: {\n fn: (n) => randAlphaNum(n as number, random),\n argTypes: [\"int\"],\n arity: { kind: \"exact\" },\n },\n randNumeric: {\n fn: (n) => randNumeric(n as number, random),\n argTypes: [\"int\"],\n arity: { kind: \"exact\" },\n },\n randAscii: {\n fn: (n) => randAscii(n as number, random),\n argTypes: [\"int\"],\n arity: { kind: \"exact\" },\n },\n shuffle: {\n fn: (s) => shuffle(s as string, random),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n },\n };\n}\n","/** `regexFind pattern s` — first match, or \"\" when no match. */\nexport function regexFind(pattern: string, s: string): string {\n const m = new RegExp(pattern).exec(s);\n return m ? m[0] : \"\";\n}\n","/**\n * `regexFindAll pattern s n` — first `n` matches (or all if n<0).\n * Mirrors Go sprig's signature: pattern, s, then optional n.\n */\nexport function regexFindAll(pattern: string, s: string, n: number = -1): string[] {\n const re = new RegExp(pattern, \"g\");\n const out: string[] = [];\n for (const m of s.matchAll(re)) {\n // Check before push so n=0 returns [] (Go regexp.FindAllString parity:\n // a non-negative n means *at most* n matches; n=0 means zero).\n if (n >= 0 && out.length >= n) break;\n out.push(m[0]);\n }\n return out;\n}\n","/** `regexMatch pattern s` — true iff JS regex matches anywhere in s. */\nexport function regexMatch(pattern: string, s: string): boolean {\n return new RegExp(pattern).test(s);\n}\n","/**\n * `regexReplaceAll pattern s repl` — replace ALL pattern matches with\n * the replacement string. Replacement supports JS's $1/$2/$<name>\n * backreference syntax.\n */\nexport function regexReplaceAll(pattern: string, s: string, repl: string): string {\n return s.replace(new RegExp(pattern, \"g\"), repl);\n}\n","/**\n * `regexReplaceAllLiteral` — like regexReplaceAll but the replacement\n * string is treated literally ($1/$2 are not expanded).\n */\nexport function regexReplaceAllLiteral(pattern: string, s: string, repl: string): string {\n // Escape `$` so JS's String.prototype.replace doesn't interpret it.\n const literal = repl.replace(/\\$/g, \"$$$$\");\n return s.replace(new RegExp(pattern, \"g\"), literal);\n}\n","/** `regexSplit pattern s n` — split by regex, optional max count. */\nexport function regexSplit(pattern: string, s: string, n: number = -1): string[] {\n const re = new RegExp(pattern);\n if (n < 0) return s.split(re);\n return s.split(re).slice(0, n);\n}\n","/**\n * Sprig regex utilities.\n *\n * Important divergence from Go sprig: these use **JS regex semantics**\n * (ECMAScript), not Go's RE2. Most patterns work identically; the\n * notable differences are lookbehind syntax and Unicode property\n * escapes. Document the divergence in the README when it lands.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { regexFind } from \"./regexFind.js\";\nimport { regexFindAll } from \"./regexFindAll.js\";\nimport { regexMatch } from \"./regexMatch.js\";\nimport { regexReplaceAll } from \"./regexReplaceAll.js\";\nimport { regexReplaceAllLiteral } from \"./regexReplaceAllLiteral.js\";\nimport { regexSplit } from \"./regexSplit.js\";\n\nexport { regexFind, regexFindAll, regexMatch, regexReplaceAll, regexReplaceAllLiteral, regexSplit };\n\nexport function sprigRegex(): FuncMap {\n // [LAW:single-enforcer] argTypes is the *one* contract describing\n // what each func accepts. enforceArgTypes catches T flowing into a\n // string slot at the boundary, so the bodies trust their declared\n // types and no longer call `String(.)`.\n return {\n regexMatch: {\n fn: (p, s) => regexMatch(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n regexFind: {\n fn: (p, s) => regexFind(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n regexFindAll: {\n fn: (p, s, n) => regexFindAll(p as string, s as string, n as number),\n argTypes: [\"string\", \"string\", \"int\"],\n arity: { kind: \"exact\" },\n },\n regexReplaceAll: {\n fn: (p, s, r) => regexReplaceAll(p as string, s as string, r as string),\n argTypes: [\"string\", \"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n regexReplaceAllLiteral: {\n fn: (p, s, r) => regexReplaceAllLiteral(p as string, s as string, r as string),\n argTypes: [\"string\", \"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n regexSplit: {\n fn: (p, s, n) => regexSplit(p as string, s as string, n as number),\n argTypes: [\"string\", \"string\", \"int\"],\n arity: { kind: \"exact\" },\n },\n };\n}\n","/**\n * SemVer parsing and comparison utilities.\n *\n * Mirrors Masterminds/semver v3 semantics used by Go sprig:\n * - Optional v prefix; missing minor/patch default to 0\n * - Standard semver 2.0.0 ordering: major.minor.patch then pre-release\n * - Release (no pre-release) > pre-release of same version\n *\n * [LAW:one-source-of-truth] One parser, one comparator. Constraint\n * evaluation imports from here rather than re-implementing comparison.\n */\n\n// Matches: v?major[.minor[.patch]][-prerelease][+metadata]\n// Groups: 1=major, 2=minor, 3=patch, 4=prerelease, 5=metadata\n// SemVer 2.0.0: prerelease/metadata use [0-9A-Za-z-] with . separators.\nconst VERSION_RE =\n /^v?(\\d+)(?:\\.(\\d+)(?:\\.(\\d+))?)?(?:-([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$/;\n\n// [LAW:types-are-the-program] SemVer mirrors the fields Go sprig exposes\n// from Masterminds/semver v3's Version struct. Template access `.Major`\n// etc. maps directly to these keys via the engine's field accessor.\nexport interface SemVer {\n readonly Major: number;\n readonly Minor: number;\n readonly Patch: number;\n readonly Prerelease: string;\n readonly Metadata: string;\n readonly Original: string;\n}\n\nexport function parseSemVer(s: string): SemVer {\n const input = s.trim();\n const m = VERSION_RE.exec(input);\n if (!m) throw new Error(`invalid semver: ${JSON.stringify(s)}`);\n return {\n Major: parseInt(m[1] ?? \"0\", 10),\n Minor: m[2] !== undefined ? parseInt(m[2], 10) : 0,\n Patch: m[3] !== undefined ? parseInt(m[3], 10) : 0,\n Prerelease: m[4] ?? \"\",\n Metadata: m[5] ?? \"\",\n Original: input,\n };\n}\n\n/** Returns negative if a < b, 0 if equal, positive if a > b. */\nexport function compareSemVer(a: SemVer, b: SemVer): number {\n const d = a.Major - b.Major || a.Minor - b.Minor || a.Patch - b.Patch;\n if (d !== 0) return d;\n return comparePrerelease(a.Prerelease, b.Prerelease);\n}\n\nfunction comparePrerelease(a: string, b: string): number {\n if (a === b) return 0;\n if (a === \"\") return 1; // release > pre-release\n if (b === \"\") return -1; // pre-release < release\n\n const aParts = a.split(\".\");\n const bParts = b.split(\".\");\n for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {\n const ap = aParts[i];\n const bp = bParts[i];\n if (ap === undefined) return -1; // fewer identifiers = smaller\n if (bp === undefined) return 1;\n const an = /^\\d+$/.test(ap) ? parseInt(ap, 10) : null;\n const bn = /^\\d+$/.test(bp) ? parseInt(bp, 10) : null;\n if (an !== null && bn !== null) {\n if (an !== bn) return an - bn;\n } else if (an !== null) {\n return -1; // numeric < alphanumeric per semver spec\n } else if (bn !== null) {\n return 1;\n } else {\n if (ap < bp) return -1;\n if (ap > bp) return 1;\n }\n }\n return 0;\n}\n","/**\n * `semver s` — parse a semver string into a struct with Major, Minor,\n * Patch, Prerelease, Metadata, Original fields.\n *\n * Mirrors Go sprig's `semver` which wraps Masterminds/semver v3's\n * `NewVersion`. Template field access (`.Major`, `.Prerelease`, etc.)\n * maps to the same-named keys on the returned object.\n *\n * Throws on invalid input — matches Go's behaviour where `semver` returns\n * (Version, error) and sprig panics on error.\n */\n\nimport { parseSemVer, type SemVer } from \"./parse.js\";\n\nexport type { SemVer };\n\nexport function semver(s: string): SemVer {\n return parseSemVer(s);\n}\n","/**\n * Masterminds/semver v3-compatible constraint parsing and evaluation.\n *\n * Supports operators: =, !=, >, >=, <, <=, ~ (tilde), ^ (caret), \"\" (=).\n * AND groups: comma- or whitespace-separated.\n * OR groups: || separated.\n *\n * [LAW:types-are-the-program] A constraint IS a predicate function —\n * parsing produces (v: SemVer) => boolean directly. No intermediate\n * structural representation is needed at the call site.\n */\n\nimport { compareSemVer, parseSemVer, type SemVer } from \"./parse.js\";\n\ntype Predicate = (v: SemVer) => boolean;\n\n// Tokenizes individual constraint items: optional op + version string.\n// Version portion allows partial versions (1, 1.2, 1.2.3) and alphanumeric\n// pre-release/metadata suffixes. Commas are separators (skipped by \\d match).\n// Operators: =, !=, >, >=, <, <=, ~, ^ (longest-first for greedy matching).\nconst TOKEN_RE = /(!=|>=|<=|>|<|~|\\^|=)?\\s*(v?\\d[^\\s,]*)/g;\n\nexport function parseConstraintExpr(s: string): Predicate {\n const orGroups = s\n .split(/\\|\\|/)\n .map((p) => p.trim())\n .filter(Boolean);\n if (orGroups.length === 0) throw new Error(`empty constraint: ${JSON.stringify(s)}`);\n const preds = orGroups.map(parseAndGroup);\n return (v) => preds.some((p) => p(v));\n}\n\nfunction parseAndGroup(s: string): Predicate {\n const preds: Predicate[] = [];\n let consumed = 0;\n for (const m of s.matchAll(TOKEN_RE)) {\n // Validate gap between previous consumed position and this match is only separators.\n const gap = s.slice(consumed, m.index);\n if (gap.length > 0 && !/^[,\\s]*$/.test(gap))\n throw new Error(`unexpected characters in constraint: ${JSON.stringify(gap)}`);\n preds.push(buildSingle(m[1] ?? \"\", m[2] ?? \"\"));\n consumed = (m.index ?? 0) + m[0].length;\n }\n if (preds.length === 0) throw new Error(`no constraint tokens in: ${JSON.stringify(s)}`);\n // Validate entire string was consumed (allowing trailing whitespace)\n const remaining = s.slice(consumed).trim();\n if (remaining.length > 0)\n throw new Error(`unexpected characters in constraint: ${JSON.stringify(remaining)}`);\n return (v) => preds.every((p) => p(v));\n}\n\n// Counts explicitly-given version components (1 = major only, 2 = major.minor, 3 = all).\n// Needed for tilde/caret semantics where partial specs have different bounds.\nfunction countComponents(vstr: string): number {\n const core = vstr.replace(/^v/, \"\").replace(/[-+].*$/, \"\");\n return Math.min(core.split(\".\").length, 3);\n}\n\nfunction makeSemVer(major: number, minor: number, patch: number, pre: string): SemVer {\n const vstr = pre ? `${major}.${minor}.${patch}-${pre}` : `${major}.${minor}.${patch}`;\n return {\n Major: major,\n Minor: minor,\n Patch: patch,\n Prerelease: pre,\n Metadata: \"\",\n Original: vstr,\n };\n}\n\n// Masterminds/semver v3 pre-release exclusion rule: a version with a\n// pre-release is excluded from a non-pre-release constraint unless the\n// constraint has a pre-release at the exact same major.minor.patch.\nfunction preReleaseCheck(v: SemVer, constraint: SemVer): boolean {\n if (v.Prerelease === \"\") return true;\n if (constraint.Prerelease !== \"\") {\n return (\n v.Major === constraint.Major && v.Minor === constraint.Minor && v.Patch === constraint.Patch\n );\n }\n return false;\n}\n\nfunction buildSingle(op: string, vstr: string): Predicate {\n const cv = parseSemVer(vstr);\n const components = countComponents(vstr);\n const minorDirty = components < 2;\n const patchDirty = components < 3;\n\n switch (op) {\n case \"\":\n case \"=\":\n return (v) => compareSemVer(v, cv) === 0;\n case \"!=\":\n return (v) => compareSemVer(v, cv) !== 0;\n case \">\":\n return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) > 0;\n case \">=\":\n return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) >= 0;\n case \"<\":\n return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) < 0;\n case \"<=\":\n return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) <= 0;\n case \"~\":\n return buildTilde(cv, minorDirty);\n case \"^\":\n return buildCaret(cv, minorDirty, patchDirty);\n default:\n throw new Error(`unknown constraint operator: ${JSON.stringify(op)}`);\n }\n}\n\n// Tilde: locks major (and minor if given). Allows patch-level changes.\n// ~X.Y.Z or ~X.Y → >=X.Y.Z, <X.(Y+1).0\n// ~X → >=X.0.0, <(X+1).0.0\nfunction buildTilde(cv: SemVer, minorDirty: boolean): Predicate {\n if (minorDirty) {\n const lower = makeSemVer(cv.Major, 0, 0, cv.Prerelease);\n const upper = makeSemVer(cv.Major + 1, 0, 0, \"\");\n return (v) =>\n preReleaseCheck(v, lower) && compareSemVer(v, lower) >= 0 && compareSemVer(v, upper) < 0;\n }\n const upper = makeSemVer(cv.Major, cv.Minor + 1, 0, \"\");\n return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) >= 0 && compareSemVer(v, upper) < 0;\n}\n\n// Caret: locks the left-most non-zero element.\n// ^X.Y.Z or ^X.Y where X>0 → >=X.Y.Z, <(X+1).0.0\n// ^0.Y.Z or ^0.Y where Y>0 → >=0.Y.Z, <0.(Y+1).0\n// ^0.0.Z (patch explicit) → >=0.0.Z, <0.0.(Z+1)\n// ^0.0 (patch dirty) → >=0.0.0, <0.1.0\n// ^0 or ^X (minor dirty) → >=X.0.0, <(X+1).0.0\nfunction buildCaret(cv: SemVer, minorDirty: boolean, patchDirty: boolean): Predicate {\n let upper: SemVer;\n if (minorDirty) {\n upper = makeSemVer(cv.Major + 1, 0, 0, \"\");\n } else if (cv.Major > 0) {\n upper = makeSemVer(cv.Major + 1, 0, 0, \"\");\n } else if (cv.Minor > 0) {\n upper = makeSemVer(0, cv.Minor + 1, 0, \"\");\n } else if (patchDirty) {\n // ^0.0 (minor explicit 0, patch not given) → <0.1.0\n upper = makeSemVer(0, 1, 0, \"\");\n } else {\n // ^0.0.Z (patch explicit) → <0.0.(Z+1)\n upper = makeSemVer(0, 0, cv.Patch + 1, \"\");\n }\n return (v) => preReleaseCheck(v, cv) && compareSemVer(v, cv) >= 0 && compareSemVer(v, upper) < 0;\n}\n","/**\n * `semverCompare constraint version` — returns true iff `version`\n * satisfies `constraint`.\n *\n * Constraint syntax follows Masterminds/semver v3 (Go sprig's semver\n * library): =, !=, >, >=, <, <=, ~ (tilde), ^ (caret), || for OR,\n * comma/space for AND.\n *\n * Note: Go sprig's argument order is (constraint, version) — the\n * constraint comes first.\n */\n\nimport { parseConstraintExpr } from \"./constraint.js\";\nimport { parseSemVer } from \"./parse.js\";\n\nexport function semverCompare(constraint: string, version: string): boolean {\n const predicate = parseConstraintExpr(constraint);\n const v = parseSemVer(version);\n return predicate(v);\n}\n","/**\n * Sprig semver functions — `semver`, `semverCompare`.\n *\n * [LAW:single-enforcer] One module owns the FuncMap registration.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { type SemVer, semver } from \"./semver.js\";\nimport { semverCompare } from \"./semverCompare.js\";\n\nexport { type SemVer, semver, semverCompare };\n\nexport function sprigSemver(): FuncMap {\n return {\n // [LAW:types-are-the-program] Returns a plain object whose keys mirror\n // Masterminds/semver v3's method names so Go template field access\n // (`.Major`, `.Prerelease`, etc.) works without an adapter.\n semver: { fn: (s) => semver(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n semverCompare: {\n fn: (constraint, version) => semverCompare(constraint as string, version as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n returnType: \"bool\",\n },\n };\n}\n","/**\n * goutils.AbbreviateFull (Masterminds/goutils@v1.1.1 stringutils.go), the\n * function behind both sprig `abbrev` and `abbrevboth`: keep at most\n * `maxWidth` characters of `cps`, starting near `offset`, marking each cut\n * end with `...`.\n *\n * [LAW:one-source-of-truth] Ported whole, step for step in Go's order, so\n * both sprig wrappers share Go's one control flow instead of each\n * reconstructing the branch it noticed. Indexed by code point where Go\n * indexes by byte — see `runes.js`.\n *\n * Go returns an error at its two minimum-width checks; both sprig wrappers\n * guard against reaching them, so here they throw rather than model sprig's\n * swallowed error.\n */\nexport function abbreviateFull(cps: readonly string[], offset: number, maxWidth: number): string {\n if (cps.length === 0) return \"\";\n if (maxWidth < 4) {\n throw new Error(\"stringutils illegal argument: Minimum abbreviation width is 4\");\n }\n if (cps.length <= maxWidth) return cps.join(\"\");\n // Go's two offset clamps, to the length and then so that maxWidth-3\n // characters remain; past the check above the second is always tighter.\n const start = Math.min(offset, cps.length - (maxWidth - 3));\n if (start <= 4) return `${cps.slice(0, maxWidth - 3).join(\"\")}...`;\n if (maxWidth < 7) {\n throw new Error(\"stringutils illegal argument: Minimum abbreviation width with offset is 7\");\n }\n if (start + maxWidth - 3 < cps.length) {\n return `...${abbreviateFull(cps.slice(start), 0, maxWidth - 3)}`;\n }\n return `...${cps.slice(cps.length - (maxWidth - 3)).join(\"\")}`;\n}\n","import { abbreviateFull } from \"./abbreviateFull.js\";\nimport { runes } from \"./runes.js\";\n\n/**\n * `abbrev width s` — truncate `s` to `width` chars, replacing the tail\n * with `...` when truncation occurs: sprig's guard around\n * goutils.Abbreviate, which is AbbreviateFull at offset 0. Widths below 4\n * cannot fit the ellipsis and return `s` unchanged.\n *\n * `width` counts code points, so the cut never splits an astral\n * character — see `runes.js` for why that differs from Go's bytes.\n */\nexport function abbrev(width: number, s: string): string {\n if (width < 4) return s;\n return abbreviateFull(runes(s), 0, width);\n}\n","import { abbreviateFull } from \"./abbreviateFull.js\";\nimport { runes } from \"./runes.js\";\n\n/**\n * `abbrevboth left right s` — sprig's guard around goutils.AbbreviateFull\n * with `left` as the offset and `right` as the maximum width: a window of\n * `s` near `left`, with `...` at each end that was cut.\n *\n * Offsets count code points, so the window never splits an astral\n * character — see `runes.js` for why that differs from Go's bytes.\n */\nexport function abbrevboth(left: number, right: number, s: string): string {\n if (right < 4 || (left > 0 && right < 7)) return s;\n return abbreviateFull(runes(s), left, right);\n}\n","/**\n * Word-classifying state machine ported from huandu/xstrings v1.3.3\n * (https://github.com/huandu/xstrings/blob/v1.3.3/convert.go), which\n * Go sprig delegates to for `snakecase`, `camelcase`, and `kebabcase`.\n *\n * [LAW:one-source-of-truth] Three sprig funcs target the same\n * algorithm with two different connector chars (`_`, `-`) plus a\n * separate camel walk. The state machine lives once in this module;\n * the per-func files are thin specializations.\n *\n * ## Port notes\n *\n * Go iterates UTF-8 bytes via `utf8.DecodeRuneInString`. The `runes`\n * seam yields code points the same way Go yields runes, so the\n * rune-level logic carries over. We intentionally do NOT attempt to\n * mirror xstrings' `isAlphabet` CJK-exclusion table — for ASCII/Latin\n * templates, which are what real users feed sprig, the simpler\n * `isLetter` test matches Go's output. The fixture suite pins the\n * cases consumers actually exercise.\n *\n * `unicode.ToTitle` from Go has no JS equivalent for ASCII letters\n * (Title and Upper coincide for code points without a separate Title\n * mapping), so we use `String.toUpperCase()` everywhere xstrings would\n * have used either.\n */\n\nimport { runes } from \"./runes.js\";\n\n// [LAW:types-are-the-program] WordType is the discriminator the\n// state machine routes on. Object-frozen literal keeps the same\n// runtime shape as a const enum without the bundler/isolatedModules\n// pitfalls biome flags.\nconst WordType = {\n Invalid: 0,\n Number: 1,\n UpperCase: 2,\n Alphabet: 3,\n Connector: 4,\n Punct: 5,\n Other: 6,\n} as const;\ntype WordType = (typeof WordType)[keyof typeof WordType];\n\ninterface Word {\n readonly wt: WordType;\n readonly text: string;\n}\n\nconst isConnectorRe = /^[-_\\s]$/;\nconst isPunctRe = /^\\p{P}$/u;\nconst isLetterRe = /^\\p{L}$/u;\nconst isUpperRe = /^\\p{Lu}$/u;\nconst isNumberRe = /^\\p{N}$/u;\n\n// All classifiers accept `undefined` as a no-op false. The caller\n// shape is \"is the next code point in class X\" — out-of-bounds is\n// trivially \"no\", which keeps the loop conditions readable without\n// duplicating an `i < cps.length` guard at every call site.\nfunction isConnector(ch: string | undefined): boolean {\n return ch !== undefined && isConnectorRe.test(ch);\n}\n\nfunction isAlphabet(ch: string | undefined): boolean {\n return ch !== undefined && isLetterRe.test(ch);\n}\n\nfunction isUpper(ch: string | undefined): boolean {\n return ch !== undefined && isUpperRe.test(ch);\n}\n\nfunction isNumber(ch: string | undefined): boolean {\n return ch !== undefined && isNumberRe.test(ch);\n}\n\nfunction isPunct(ch: string | undefined): boolean {\n return ch !== undefined && isPunctRe.test(ch);\n}\n\n/**\n * Pull the next word off `cps` starting at `i`. Returns the word's\n * type + text and the index of the first code point after the word.\n *\n * Mirrors xstrings.nextWord: classifies the first rune, then extends\n * the word as long as the next rune fits the same class — with a\n * special \"HTTPStatus\" carve-out where an upper-run followed by a\n * lower letter releases the last upper into the next word.\n */\nfunction nextWord(cps: readonly string[], start: number): { word: Word; next: number } {\n if (start >= cps.length) {\n return { word: { wt: WordType.Invalid, text: \"\" }, next: start };\n }\n // Bounds checked above; the cast trades a redundant runtime check\n // for the same nullability shape used elsewhere in this module\n // (e.g. `split.ts` has `parts[i] as string`).\n const r = cps[start] as string;\n let i = start + 1;\n\n if (isConnector(r)) {\n while (i < cps.length && isConnector(cps[i])) i++;\n return { word: { wt: WordType.Connector, text: cps.slice(start, i).join(\"\") }, next: i };\n }\n if (isPunct(r)) {\n while (i < cps.length && isPunct(cps[i])) i++;\n return { word: { wt: WordType.Punct, text: cps.slice(start, i).join(\"\") }, next: i };\n }\n if (isUpper(r)) {\n if (i >= cps.length) {\n return { word: { wt: WordType.UpperCase, text: r }, next: i };\n }\n if (isUpper(cps[i])) {\n // Run of uppers. Walk until non-upper.\n let endOfRun = i;\n while (endOfRun < cps.length && isUpper(cps[endOfRun])) endOfRun++;\n // \"HTTPStatus\" carve-out: when the run is followed by a letter\n // (which must be lower since the run already ended), the LAST\n // upper of the run is released into the next word so it can\n // become \"HTTP\" + \"Status\" rather than \"HTTPS\" + \"tatus\".\n if (endOfRun < cps.length && isAlphabet(cps[endOfRun])) {\n return {\n word: { wt: WordType.UpperCase, text: cps.slice(start, endOfRun - 1).join(\"\") },\n next: endOfRun - 1,\n };\n }\n return {\n word: { wt: WordType.UpperCase, text: cps.slice(start, endOfRun).join(\"\") },\n next: endOfRun,\n };\n }\n if (isAlphabet(cps[i])) {\n // Single upper followed by lower-run: e.g. \"FirstName\" -> \"First\".\n let end = i + 1;\n while (end < cps.length && isAlphabet(cps[end]) && !isUpper(cps[end])) end++;\n return {\n word: { wt: WordType.UpperCase, text: cps.slice(start, end).join(\"\") },\n next: end,\n };\n }\n // Single upper followed by non-letter (digit, connector, etc.).\n return { word: { wt: WordType.UpperCase, text: r }, next: i };\n }\n if (isAlphabet(r)) {\n while (i < cps.length && isAlphabet(cps[i]) && !isUpper(cps[i])) i++;\n return { word: { wt: WordType.Alphabet, text: cps.slice(start, i).join(\"\") }, next: i };\n }\n if (isNumber(r)) {\n while (i < cps.length && isNumber(cps[i])) i++;\n return { word: { wt: WordType.Number, text: cps.slice(start, i).join(\"\") }, next: i };\n }\n while (\n i < cps.length &&\n !isConnector(cps[i]) &&\n !isAlphabet(cps[i]) &&\n !isNumber(cps[i]) &&\n !isPunct(cps[i])\n ) {\n i++;\n }\n return { word: { wt: WordType.Other, text: cps.slice(start, i).join(\"\") }, next: i };\n}\n\n/**\n * Lowercase a word's text into the output buffer. Connector words\n * have their internal connector chars rewritten to the target\n * connector; all other words are lowered character-by-character.\n */\nfunction pushLowered(buf: string[], word: Word, connector: string): void {\n if (word.wt !== WordType.UpperCase && word.wt !== WordType.Connector) {\n buf.push(word.text);\n return;\n }\n for (const ch of word.text) {\n if (isConnector(ch)) {\n buf.push(connector);\n } else if (isUpper(ch)) {\n buf.push(ch.toLowerCase());\n } else {\n buf.push(ch);\n }\n }\n}\n\n/**\n * Port of xstrings.camelCaseToLowerCase. Walks word-by-word and\n * inserts `connector` at the right transitions to produce snake/kebab\n * output.\n */\nexport function camelCaseToLowerCase(s: string, connector: string): string {\n if (s.length === 0) return \"\";\n const cps = runes(s);\n const buf: string[] = [];\n\n let { word, next: i } = nextWord(cps, 0);\n\n while (i < cps.length) {\n if (word.wt !== WordType.Connector) {\n pushLowered(buf, word, connector);\n }\n const prev = word;\n const last = word;\n ({ word, next: i } = nextWord(cps, i));\n\n if (prev.wt === WordType.Number) {\n while (word.wt === WordType.Alphabet || word.wt === WordType.Number) {\n pushLowered(buf, word, connector);\n ({ word, next: i } = nextWord(cps, i));\n }\n if (\n word.wt !== WordType.Invalid &&\n word.wt !== WordType.Punct &&\n word.wt !== WordType.Connector\n ) {\n buf.push(connector);\n }\n continue;\n }\n if (prev.wt === WordType.Connector) {\n pushLowered(buf, last, connector);\n continue;\n }\n if (prev.wt === WordType.Punct) {\n // nothing\n continue;\n }\n // default: prev is alphabet/upper/other\n if (word.wt !== WordType.Number) {\n if (word.wt !== WordType.Connector && word.wt !== WordType.Punct) {\n buf.push(connector);\n }\n continue;\n }\n // word is a Number — special handling per xstrings.\n if (i >= cps.length) {\n // No following word; let the loop tail emit `word`.\n continue;\n }\n const numberWord = word;\n ({ word, next: i } = nextWord(cps, i));\n // If after the number isn't an alphabet, treat the number as its\n // own word (e.g. \"Duration2m3s\" → \"duration_2m3s\").\n if (word.wt !== WordType.Alphabet) {\n pushLowered(buf, numberWord, connector);\n if (word.wt !== WordType.Connector && word.wt !== WordType.Punct) {\n buf.push(connector);\n }\n continue;\n }\n // Lowercase letters follow the number, so the number is its own\n // word with a leading connector: e.g. \"HTTP2xx\" → \"http_2xx\".\n buf.push(connector);\n pushLowered(buf, numberWord, connector);\n while (word.wt === WordType.Alphabet || word.wt === WordType.Number) {\n pushLowered(buf, word, connector);\n ({ word, next: i } = nextWord(cps, i));\n }\n if (\n word.wt !== WordType.Invalid &&\n word.wt !== WordType.Connector &&\n word.wt !== WordType.Punct\n ) {\n buf.push(connector);\n }\n }\n pushLowered(buf, word, connector);\n return buf.join(\"\").toLowerCase();\n}\n\n/**\n * Port of xstrings.ToCamelCase. Two-phase walk:\n * - Phase 1 preserves leading connectors verbatim, capitalizes the\n * first non-connector rune.\n * - Phase 2 walks `(prev, curr)` rune pairs, collapsing connector→\n * non-connector to a single uppered rune, preserving runs of\n * adjacent connectors, and lowercasing other runes.\n */\nexport function camelCase(s: string): string {\n if (s.length === 0) return \"\";\n const cps = runes(s);\n const buf: string[] = [];\n\n let i = 0;\n let r0 = \"\";\n\n while (i < cps.length) {\n r0 = cps[i] as string;\n i++;\n if (!isConnector(r0)) {\n r0 = r0.toUpperCase();\n break;\n }\n buf.push(r0);\n }\n\n if (i >= cps.length) {\n if (cps.length > 0) buf.push(r0);\n return buf.join(\"\");\n }\n\n while (i < cps.length) {\n const r1 = r0;\n r0 = cps[i] as string;\n i++;\n\n if (isConnector(r0) && isConnector(r1)) {\n buf.push(r1);\n continue;\n }\n if (isConnector(r1)) {\n r0 = r0.toUpperCase();\n } else {\n r0 = r0.toLowerCase();\n buf.push(r1);\n }\n }\n buf.push(r0);\n return buf.join(\"\");\n}\n","/**\n * `camelcase s` — port of `xstrings.ToCamelCase`. Note: despite the\n * name, Go sprig's `camelcase` is **PascalCase** — the first letter\n * is uppercased, not lowercased. This is a documented Go-sprig\n * quirk and we preserve it byte-for-byte.\n *\n * Examples (matching the xstrings docstring):\n * \"some_words\" -> \"SomeWords\"\n * \"http_server\" -> \"HttpServer\"\n * \"_complex__case_\" -> \"_Complex_Case_\"\n */\n\n// [LAW:one-source-of-truth] The walk lives in caseUtils alongside\n// the snake/kebab algorithm.\nimport { camelCase } from \"./caseUtils.js\";\n\nexport function camelcase(s: string): string {\n return camelCase(s);\n}\n","/** `cat a b c` — concatenates with spaces, like Go sprig. */\nexport function cat(...args: string[]): string {\n return args.join(\" \");\n}\n","export function contains(substr: string, s: string): boolean {\n return s.includes(substr);\n}\n","export function hasPrefix(prefix: string, s: string): boolean {\n return s.startsWith(prefix);\n}\n","export function hasSuffix(suffix: string, s: string): boolean {\n return s.endsWith(suffix);\n}\n","/** `indent n s` — prefix every line of `s` with `n` spaces. */\nexport function indent(n: number, s: string): string {\n const pad = \" \".repeat(Math.max(0, n));\n return s\n .split(\"\\n\")\n .map((line) => pad + line)\n .join(\"\\n\");\n}\n","/**\n * `initials s` — port of `goutils.Initials` (what Go sprig's `initials`\n * delegates to): the first character of each whitespace-separated word,\n * case preserved — `\"Ada Lovelace\"` -> `\"AL\"`, `\"foo bar baz\"` -> `\"fbb\"`.\n *\n * Byte-faithful: goutils indexes the word's first BYTE, so a multi-byte\n * leading character yields that byte as a code point — `\"Ölga\"` -> `\"Ã\"`,\n * `\"𐍈foo\"` -> `\"ð\"` (both verified against the Go conformance generator),\n * never the full glyph.\n */\nexport function initials(s: string): string {\n const enc = new TextEncoder();\n return (\n s\n .split(/\\s+/)\n .filter((w) => w.length > 0)\n // [LAW:dataflow-not-control-flow] spread of the 1-byte slice: an (impossible)\n // empty word contributes \"\" naturally instead of a guarded fallback value.\n .map((w) => String.fromCharCode(...enc.encode(w).slice(0, 1)))\n .join(\"\")\n );\n}\n","import { typeNameOf } from \"../../evaluator/builtins.js\";\nimport { bodyTypeMismatch } from \"../../evaluator/errors.js\";\n\n/**\n * `join sep list` — joins a list with the separator.\n *\n * [LAW:single-enforcer] The list-shape gate is `argTypes: [\"string\",\n * \"list\"]` — non-arrays raise TypeMismatchError before this body runs.\n * The body validates each *element* because the no-silent-flatten\n * commitment (\"typed values never become strings without an explicit\n * conversion\") applies inside lists too: primitives stringify\n * naturally; non-primitive (typed-T) elements throw, and `evalCommand`\n * re-emits with the call-site pos.\n */\nexport function join(sep: string, list: readonly unknown[]): string {\n const parts: string[] = [];\n for (const v of list) {\n if (v !== null && v !== undefined && typeof v === \"object\") {\n throw bodyTypeMismatch(\n \"join\",\n 2,\n \"list of strings/primitives\",\n `list element of type ${typeNameOf(v)}`,\n );\n }\n parts.push(String(v));\n }\n return parts.join(sep);\n}\n","/**\n * `kebabcase s` — port of `xstrings.ToKebabCase`. Identical to\n * `snakecase` except the connector is `-`.\n */\n\n// [LAW:one-source-of-truth] The state machine lives in caseUtils;\n// kebabcase is the `-` specialization.\nimport { camelCaseToLowerCase } from \"./caseUtils.js\";\n\nexport function kebabcase(s: string): string {\n return camelCaseToLowerCase(s, \"-\");\n}\n","export function lower(s: string): string {\n return s.toLowerCase();\n}\n","/** `nindent n s` — `indent` with a leading newline. */\nimport { indent } from \"./indent.js\";\n\nexport function nindent(n: number, s: string): string {\n return `\\n${indent(n, s)}`;\n}\n","/**\n * `nospace s` — strip whitespace from `s`. Mirrors Go sprig's\n * `goutils.DeleteWhiteSpace`, which iterates bytes and drops anything\n * `unicode.IsSpace` returns true for. ECMAScript `\\s` covers the same\n * ASCII whitespace set (space, tab, CR, LF, VT, FF) — the goutils\n * implementation is byte-indexed so multi-byte Unicode whitespace\n * already escapes its filter, leaving ASCII as the de-facto contract.\n */\n\n// [LAW:single-enforcer] The `\"string\"` gate validates the kind once\n// at dispatch; the body trusts it.\nexport function nospace(s: string): string {\n return s.replace(/\\s+/g, \"\");\n}\n","/**\n * `plural one many n` — return `one` if `n == 1`, else `many`.\n * Mirrors Go sprig's `plural(one, many string, count int) string`.\n */\n\n// [LAW:single-enforcer] Slot kinds (`[\"string\", \"string\", \"int\"]`) are\n// validated and normalized at the dispatch gate; the body receives a\n// finite `number`. Safe-integer bigints (|n| ≤ 2^53) normalize through\n// the gate to plain `number`; bigints outside that range are rejected\n// at the gate (precision-loss is a magnitude failure, not a tradeoff).\n// Either way, no body-side bigint comparison is needed.\nexport function plural(one: string, many: string, n: number): string {\n return n === 1 ? one : many;\n}\n","/** `quote a b c` — wraps each arg in double quotes, joined by spaces. */\nexport function quote(...args: string[]): string {\n return args.map((a) => `\"${a}\"`).join(\" \");\n}\n","/**\n * `regexQuoteMeta s` — escape regex metacharacters in `s` so it can be\n * embedded literally in a regex. Mirrors Go's `regexp.QuoteMeta`,\n * which backslash-escapes the set `\\.+*?()|[]{}^$`.\n *\n * ECMAScript regex shares the same metacharacter set, so the escape\n * list is identical.\n */\n\n// [LAW:single-enforcer] Kind validated at the dispatch gate; the body\n// just rewrites.\nexport function regexQuoteMeta(s: string): string {\n return s.replace(/[\\\\.+*?()|[\\]{}^$]/g, \"\\\\$&\");\n}\n","export function repeat(n: number, s: string): string {\n return s.repeat(Math.max(0, n));\n}\n","import { goSplit } from \"./runes.js\";\n\n/**\n * Replaces ALL occurrences of `old` with `nw` in `s` (Go's strings.Replace n=-1).\n *\n * An empty `old` splits between runes rather than UTF-16 units, so the\n * replacement is never inserted inside an astral character. Where Go\n * additionally inserts `nw` at both ends (`-a-b-c-` to this port's\n * `a-b-c`) it still differs — a separate, non-Unicode divergence.\n */\nexport function replace(old: string, nw: string, s: string): string {\n return goSplit(old, s).join(nw);\n}\n","/**\n * `snakecase s` — port of `xstrings.ToSnakeCase`. Inserts `_` between\n * camelCase/PascalCase word boundaries and rewrites any space, dash,\n * or underscore run into a single `_`. Runs of upper-case letters\n * release their last character into the next word, so `HTTPServer`\n * becomes `http_server`, not `https_erver`.\n */\n\n// [LAW:one-source-of-truth] The state machine lives in caseUtils;\n// snakecase is the `_` specialization.\nimport { camelCaseToLowerCase } from \"./caseUtils.js\";\n\nexport function snakecase(s: string): string {\n return camelCaseToLowerCase(s, \"_\");\n}\n","import { goSplit } from \"./runes.js\";\n\n/**\n * `split sep s` — Go sprig oddity: returns a DICT keyed by `_<index>`,\n * not a list. Use `splitList` for the list form.\n * split \"/\" \"a/b/c\" → { _0: \"a\", _1: \"b\", _2: \"c\" }\n */\nexport function split(sep: string, s: string): Record<string, string> {\n const parts = goSplit(sep, s);\n const out: Record<string, string> = {};\n for (let i = 0; i < parts.length; i++) {\n out[`_${i}`] = parts[i] as string;\n }\n return out;\n}\n","import { goSplit } from \"./runes.js\";\n\nexport function splitList(sep: string, s: string): string[] {\n return goSplit(sep, s);\n}\n","/**\n * `splitn sep n s` — split `s` on `sep` into at most `n` parts and\n * return a `{_0, _1, …}` map. Mirrors Go sprig:\n *\n * parts := strings.SplitN(orig, sep, n)\n * for i, v := range parts {\n * res[\"_\" + strconv.Itoa(i)] = v\n * }\n *\n * The `{_0, _1}` shape (rather than a list) is idiosyncratic to Go\n * sprig. Preserve it byte-for-byte — consumers index into the result\n * by name, e.g. `(splitn \":\" 2 \"a:b:c\")._1` → `\"b:c\"`.\n *\n * `strings.SplitN` semantics that JS `String.split(sep, n)` does *not*\n * match: when there are more parts than `n`, the last slot holds the\n * **unsplit remainder**, not a truncated prefix. JS `split` would\n * drop \"b:c\" entirely; Go keeps it. The body re-joins the tail\n * explicitly to recover the Go behavior.\n */\n\nimport { goSplit } from \"./runes.js\";\n\n// [LAW:single-enforcer] Slot kinds (`[\"string\", \"int\", \"string\"]`)\n// validate and normalize the inputs at the dispatch gate — `n` arrives\n// as a safe-integer `number`. Safe-integer bigints (|n| ≤ 2^53) are\n// accepted and normalized via `Number(v)`; fractionals, NaN, ±Infinity,\n// and integers outside that range are rejected at the gate.\n// The body owns the SplitN→map shape transform.\nexport function splitn(sep: string, n: number, s: string): Record<string, string> {\n const parts = goSplitN(s, sep, n);\n const res: Record<string, string> = {};\n for (let i = 0; i < parts.length; i++) {\n res[`_${i}`] = parts[i] ?? \"\";\n }\n return res;\n}\n\n// Go's strings.SplitN(s, sep, n):\n// n > 0 → at most n substrings; last is unsplit remainder\n// n == 0 → empty list\n// n < 0 → all substrings (== Split)\nfunction goSplitN(s: string, sep: string, n: number): string[] {\n if (n === 0) return [];\n const all = goSplit(sep, s);\n if (n < 0 || all.length <= n) return all;\n const head = all.slice(0, n - 1);\n const tail = all.slice(n - 1).join(sep);\n return [...head, tail];\n}\n","/** `squote a b c` — like `quote` but single quotes. */\nexport function squote(...args: string[]): string {\n return args.map((a) => `'${a}'`).join(\" \");\n}\n","import { runes } from \"./runes.js\";\n\n/**\n * `substr i j s` — substring [i, j) with out-of-range clamping.\n * Matches Go sprig's behavior of clamping rather than throwing:\n * negative `end` (and any `end` past the last char) clamps to the\n * string's length; `start` clamps to `[0, end]`.\n *\n * Offsets count code points, so a window never splits an astral\n * character — see `runes.js` for why that differs from Go's bytes.\n */\nexport function substr(start: number, end: number, s: string): string {\n const cps = runes(s);\n const j = end < 0 || end > cps.length ? cps.length : end;\n const i = Math.min(Math.max(0, start), j);\n return cps.slice(i, j).join(\"\");\n}\n","/**\n * `swapcase s` — flip case per code point. Mirrors Go sprig's\n * `goutils.SwapCase` for ASCII and Latin-1 inputs.\n *\n * Go's `goutils.SwapCase` carries a \"preceded by whitespace\" flag and\n * uses `unicode.ToTitle` instead of `ToUpper` for the first lowercase\n * letter of each word. For ASCII letters Title and Upper coincide, so\n * the flag has no observable effect on output and is omitted here —\n * keeping it would be load-bearing complexity that the type system\n * cannot constrain. Non-ASCII ligatures (e.g. German `ß` whose JS\n * `toUpperCase` returns `SS` while Go's `ToTitle` returns `ẞ`) diverge,\n * matching the README's existing Go/Unicode divergence statements.\n */\n\n// [LAW:single-enforcer] The \"string\" gate validates the kind once at\n// dispatch; the body trusts it.\n//\n// [LAW:dataflow-not-control-flow] Each iteration unconditionally\n// emits one transformed code point. The category check selects the\n// transformation; it never gates whether the emit happens.\nexport function swapcase(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (isUpper(ch)) {\n out += ch.toLowerCase();\n } else if (isLower(ch)) {\n out += ch.toUpperCase();\n } else {\n out += ch;\n }\n }\n return out;\n}\n\nfunction isUpper(ch: string): boolean {\n return ch !== ch.toLowerCase() && ch === ch.toUpperCase();\n}\n\nfunction isLower(ch: string): boolean {\n return ch !== ch.toUpperCase() && ch === ch.toLowerCase();\n}\n","/** Capitalize the first letter of each whitespace-separated word. */\nexport function title(s: string): string {\n return s.replace(/\\b([a-zA-Z])/g, (m) => m.toUpperCase());\n}\n","export function trim(s: string): string {\n return s.trim();\n}\n","import { runes } from \"./runes.js\";\n\n/**\n * `trimAll cutset s` — strip leading + trailing chars in `cutset`.\n *\n * Both sides are compared as code points, matching Go's `strings.Trim`,\n * which decodes the cutset as runes. Scanning `s` by UTF-16 unit\n * compared half an astral character against whole ones, so an astral\n * cutset char never matched and the string came back untrimmed.\n */\nexport function trimAll(cutset: string, s: string): string {\n if (cutset.length === 0) return s;\n const set = new Set(runes(cutset));\n const cps = runes(s);\n let start = 0;\n while (start < cps.length && set.has(cps[start] as string)) start += 1;\n let end = cps.length;\n while (end > start && set.has(cps[end - 1] as string)) end -= 1;\n return cps.slice(start, end).join(\"\");\n}\n","export function trimPrefix(prefix: string, s: string): string {\n return s.startsWith(prefix) ? s.slice(prefix.length) : s;\n}\n","export function trimSuffix(suffix: string, s: string): string {\n return s.endsWith(suffix) ? s.slice(0, s.length - suffix.length) : s;\n}\n","import { runes } from \"./runes.js\";\n\n/**\n * `trunc n s` — first `n` chars when n>=0; last |n| chars when n<0.\n * Strings shorter than |n| are returned unchanged. Matches Go sprig.\n *\n * `n` counts code points, so truncating never splits an astral\n * character — see `runes.js` for why that differs from Go's bytes.\n */\nexport function trunc(n: number, s: string): string {\n const cps = runes(s);\n if (n < 0) {\n const k = -n;\n return k >= cps.length ? s : cps.slice(cps.length - k).join(\"\");\n }\n return n >= cps.length ? s : cps.slice(0, n).join(\"\");\n}\n","/** Lowercase the first letter of each whitespace-separated word. */\nexport function untitle(s: string): string {\n return s.replace(/\\b([A-Z])/g, (m) => m.toLowerCase());\n}\n","export function upper(s: string): string {\n return s.toUpperCase();\n}\n","/**\n * `wrap width s` — soft-wrap `s` to `width` columns at word boundaries.\n * Lines longer than width that contain no spaces are emitted as-is.\n */\nexport function wrap(width: number, s: string): string {\n return wrapWithSeparator(width, \"\\n\", s);\n}\n\nexport function wrapWithSeparator(width: number, sep: string, s: string): string {\n if (width <= 0) return s;\n const out: string[] = [];\n for (const para of s.split(\"\\n\")) {\n let line = \"\";\n for (const word of para.split(/\\s+/)) {\n if (word.length === 0) continue;\n if (line.length === 0) {\n line = word;\n } else if (line.length + 1 + word.length <= width) {\n line += ` ${word}`;\n } else {\n out.push(line);\n line = word;\n }\n }\n if (line.length > 0) out.push(line);\n }\n return out.join(sep);\n}\n","import { wrapWithSeparator } from \"./wrap.js\";\n\n/** `wrapWith width sep s` — wrap to width using `sep` instead of \\n. */\nexport function wrapWith(width: number, sep: string, s: string): string {\n return wrapWithSeparator(width, sep, s);\n}\n","/**\n * Sprig string utilities.\n *\n * Each function lives in its own file with a co-located unit test.\n * `sprigStrings()` bundles them as a FuncMap for one-line consumer\n * registration on the engine.\n */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { abbrev } from \"./abbrev.js\";\nimport { abbrevboth } from \"./abbrevboth.js\";\nimport { camelcase } from \"./camelcase.js\";\nimport { cat } from \"./cat.js\";\nimport { contains } from \"./contains.js\";\nimport { hasPrefix } from \"./hasPrefix.js\";\nimport { hasSuffix } from \"./hasSuffix.js\";\nimport { indent } from \"./indent.js\";\nimport { initials } from \"./initials.js\";\nimport { join } from \"./join.js\";\nimport { kebabcase } from \"./kebabcase.js\";\nimport { lower } from \"./lower.js\";\nimport { nindent } from \"./nindent.js\";\nimport { nospace } from \"./nospace.js\";\nimport { plural } from \"./plural.js\";\nimport { quote } from \"./quote.js\";\nimport { regexQuoteMeta } from \"./regexQuoteMeta.js\";\nimport { repeat } from \"./repeat.js\";\nimport { replace } from \"./replace.js\";\nimport { snakecase } from \"./snakecase.js\";\nimport { split } from \"./split.js\";\nimport { splitList } from \"./splitList.js\";\nimport { splitn } from \"./splitn.js\";\nimport { squote } from \"./squote.js\";\nimport { substr } from \"./substr.js\";\nimport { swapcase } from \"./swapcase.js\";\nimport { title } from \"./title.js\";\nimport { trim } from \"./trim.js\";\nimport { trimAll } from \"./trimAll.js\";\nimport { trimPrefix } from \"./trimPrefix.js\";\nimport { trimSuffix } from \"./trimSuffix.js\";\nimport { trunc } from \"./trunc.js\";\nimport { untitle } from \"./untitle.js\";\nimport { upper } from \"./upper.js\";\nimport { wrap } from \"./wrap.js\";\nimport { wrapWith } from \"./wrapWith.js\";\n\nexport {\n abbrev,\n abbrevboth,\n camelcase,\n cat,\n contains,\n hasPrefix,\n hasSuffix,\n indent,\n initials,\n join,\n kebabcase,\n lower,\n nindent,\n nospace,\n plural,\n quote,\n regexQuoteMeta,\n repeat,\n replace,\n snakecase,\n split,\n splitList,\n splitn,\n squote,\n substr,\n swapcase,\n title,\n trim,\n trimAll,\n trimPrefix,\n trimSuffix,\n trunc,\n untitle,\n upper,\n wrap,\n wrapWith,\n};\n\nexport function sprigStrings(): FuncMap {\n // [LAW:single-enforcer] argTypes is the contract describing what each\n // func accepts; enforceArgTypes runs at the boundary, so the `as`\n // casts below are provably-safe — the runtime types match the\n // declared argTypes. Numeric slots use \"int\" (Go declares every one\n // of them `int`): the gate accepts integer-valued `number` and\n // safe-integer `bigint` (|n| ≤ 2^53), normalizes both to a `number`,\n // and rejects fractionals, out-of-range bigints, NaN, and ±Infinity\n // at the boundary. Bodies receive plain `number` and\n // drop the body-side `Number(v)` coercions that used to re-do the\n // gate's work. See template-variance-num-carrier-hfv.3.\n return {\n abbrev: {\n fn: (w, s) => abbrev(w as number, s as string),\n argTypes: [\"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n abbrevboth: {\n fn: (l, r, s) => abbrevboth(l as number, r as number, s as string),\n argTypes: [\"int\", \"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n camelcase: {\n fn: (s) => camelcase(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n cat: {\n fn: (...a) => cat(...(a as string[])),\n argTypes: [\"string\"],\n arity: { kind: \"variadic\" },\n },\n contains: {\n fn: (sub, s) => contains(sub as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n hasPrefix: {\n fn: (p, s) => hasPrefix(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n hasSuffix: {\n fn: (sf, s) => hasSuffix(sf as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n indent: {\n fn: (n, s) => indent(n as number, s as string),\n argTypes: [\"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n initials: { fn: (s) => initials(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n join: {\n fn: (sep, list) => join(sep as string, list as unknown[]),\n argTypes: [\"string\", \"list\"],\n arity: { kind: \"exact\" },\n },\n kebabcase: {\n fn: (s) => kebabcase(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n lower: { fn: (s) => lower(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n nindent: {\n fn: (n, s) => nindent(n as number, s as string),\n argTypes: [\"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n nospace: {\n fn: (s) => nospace(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n plural: {\n fn: (one, many, n) => plural(one as string, many as string, n as number),\n argTypes: [\"string\", \"string\", \"int\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n quote: {\n fn: (...a) => quote(...(a as string[])),\n argTypes: [\"string\"],\n arity: { kind: \"variadic\" },\n },\n regexQuoteMeta: {\n fn: (s) => regexQuoteMeta(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n repeat: {\n fn: (n, s) => repeat(n as number, s as string),\n argTypes: [\"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n replace: {\n fn: (o, n, s) => replace(o as string, n as string, s as string),\n argTypes: [\"string\", \"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n snakecase: {\n fn: (s) => snakecase(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n split: {\n fn: (sep, s) => split(sep as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n splitList: {\n fn: (sep, s) => splitList(sep as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n splitn: {\n fn: (sep, n, s) => splitn(sep as string, n as number, s as string),\n argTypes: [\"string\", \"int\", \"string\"],\n arity: { kind: \"exact\" },\n returnType: \"dict\",\n },\n squote: {\n fn: (...a) => squote(...(a as string[])),\n argTypes: [\"string\"],\n arity: { kind: \"variadic\" },\n },\n substr: {\n fn: (i, j, s) => substr(i as number, j as number, s as string),\n argTypes: [\"int\", \"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n swapcase: {\n fn: (s) => swapcase(s as string),\n argTypes: [\"string\"],\n arity: { kind: \"exact\" },\n returnType: \"string\",\n },\n title: { fn: (s) => title(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n trim: { fn: (s) => trim(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n trimAll: {\n fn: (cs, s) => trimAll(cs as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n trimPrefix: {\n fn: (p, s) => trimPrefix(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n trimSuffix: {\n fn: (sf, s) => trimSuffix(sf as string, s as string),\n argTypes: [\"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n trunc: {\n fn: (n, s) => trunc(n as number, s as string),\n argTypes: [\"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n untitle: { fn: (s) => untitle(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n upper: { fn: (s) => upper(s as string), argTypes: [\"string\"], arity: { kind: \"exact\" } },\n wrap: {\n fn: (w, s) => wrap(w as number, s as string),\n argTypes: [\"int\", \"string\"],\n arity: { kind: \"exact\" },\n },\n wrapWith: {\n fn: (w, sep, s) => wrapWith(w as number, sep as string, s as string),\n argTypes: [\"int\", \"string\", \"string\"],\n arity: { kind: \"exact\" },\n },\n };\n}\n","/**\n * `deepCopy v` — recursive structural clone.\n *\n * Uses `structuredClone` when available; falls back to a JSON\n * round-trip for older targets. The fallback drops functions and\n * symbols — same caveat as JSON.stringify.\n */\nexport function deepCopy<T>(value: T): T {\n if (typeof globalThis.structuredClone === \"function\") {\n return globalThis.structuredClone(value);\n }\n return JSON.parse(JSON.stringify(value)) as T;\n}\n","/**\n * `kindOf v` — JS-flavoured equivalent of Go's `reflect.Kind`.\n *\n * Go: int / float64 / string / bool / slice / map / struct / ptr / …\n * JS: number / string / boolean / array / map / object / null / undefined / function / bigint / symbol\n *\n * We return the JS-native kind. Consumers porting templates from Go\n * sprig should test against the JS-native names.\n */\nexport function kindOf(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n if (value instanceof Map) return \"map\";\n if (value instanceof Set) return \"set\";\n return typeof value;\n}\n","import { kindOf } from \"./kindOf.js\";\n\nexport function kindIs(kind: string, value: unknown): boolean {\n return kindOf(value) === kind;\n}\n","import { kindOf } from \"./kindOf.js\";\n\n/**\n * `typeOf v` — for JS, essentially the same as kindOf, with the\n * caveat that \"object\" is the catch-all for plain dicts and class\n * instances. Go's reflect.Type would distinguish struct names; we\n * don't have that info at runtime.\n */\nexport function typeOf(value: unknown): string {\n return kindOf(value);\n}\n","import { typeOf } from \"./typeOf.js\";\n\nexport function typeIs(type: string, value: unknown): boolean {\n return typeOf(value) === type;\n}\n","import { typeIs } from \"./typeIs.js\";\n\n/**\n * `typeIsLike type v` — Go sprig's \"like\" matches both value and\n * pointer-to-value. JS doesn't have pointers so this collapses to\n * `typeIs`.\n */\nexport function typeIsLike(type: string, value: unknown): boolean {\n return typeIs(type, value);\n}\n","/** Sprig type/reflection utilities. */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { deepCopy } from \"./deepCopy.js\";\nimport { deepEqual } from \"./deepEqual.js\";\nimport { kindIs } from \"./kindIs.js\";\nimport { kindOf } from \"./kindOf.js\";\nimport { typeIs } from \"./typeIs.js\";\nimport { typeIsLike } from \"./typeIsLike.js\";\nimport { typeOf } from \"./typeOf.js\";\n\nexport { deepCopy, deepEqual, kindIs, kindOf, typeIs, typeIsLike, typeOf };\n\nexport function sprigTypes(): FuncMap {\n // [LAW:one-source-of-truth] Reflection slots declare \"reflective\"\n // (intent: type-inspection context); structural-clone/compare slots\n // declare \"value\" (intent: genuinely heterogeneous). The *kind/type\n // name* arguments stay \"string\" — they exist to be compared against\n // typeOf's string output.\n return {\n kindOf: { fn: (v) => kindOf(v), argTypes: [\"reflective\"], arity: { kind: \"exact\" } },\n kindIs: {\n fn: (k, v) => kindIs(k as string, v),\n argTypes: [\"string\", \"reflective\"],\n arity: { kind: \"exact\" },\n },\n typeOf: { fn: (v) => typeOf(v), argTypes: [\"reflective\"], arity: { kind: \"exact\" } },\n typeIs: {\n fn: (t, v) => typeIs(t as string, v),\n argTypes: [\"string\", \"reflective\"],\n arity: { kind: \"exact\" },\n },\n typeIsLike: {\n fn: (t, v) => typeIsLike(t as string, v),\n argTypes: [\"string\", \"reflective\"],\n arity: { kind: \"exact\" },\n },\n deepEqual: {\n fn: (a, b) => deepEqual(a, b),\n argTypes: [\"value\", \"value\"],\n arity: { kind: \"exact\" },\n },\n deepCopy: { fn: (v) => deepCopy(v), argTypes: [\"value\"], arity: { kind: \"exact\" } },\n };\n}\n"],"mappings":";;;;AA0CA,IAAa,gBAAb,cAAmC,MAAM;CACvC,OAAiC;CACjC,OAA2B;CAC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