@promptctl/go-template-js 0.1.1 → 0.4.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 +23 -9
- package/dist/index.d.ts +149 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2223 -324
- package/dist/index.js.map +1 -1
- package/package.json +5 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["parseSource","sprigToString","sprigToStrings","isUpper"],"sources":["../src/errors.ts","../src/parser/ast.ts","../src/parser/lexer.ts","../src/parser/parser.ts","../src/evaluator/access.ts","../src/sprig/types/deepEqual.ts","../src/evaluator/lazy.ts","../src/evaluator/truthy.ts","../src/evaluator/builtins.ts","../src/evaluator/errors.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/toString.ts","../src/sprig/conversions/toStrings.ts","../src/sprig/conversions/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/lists/append.ts","../src/sprig/lists/chunk.ts","../src/sprig/lists/compact.ts","../src/sprig/lists/concat.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/uniq.ts","../src/sprig/lists/without.ts","../src/sprig/lists/index.ts","../src/sprig/math/add.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/min.ts","../src/sprig/math/mod.ts","../src/sprig/math/mul.ts","../src/sprig/math/mulf.ts","../src/sprig/math/round.ts","../src/sprig/math/sub.ts","../src/sprig/math/subf.ts","../src/sprig/math/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/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 * ├── 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 | \"TypeMismatchError\"\n | \"MissingFieldError\";\n\nexport interface TemplateErrorContext {\n readonly source?: string | undefined;\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);\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\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 ${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\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// 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// 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 | 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 | \"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 [\"define\", \"Define\"],\n [\"template\", \"Template\"],\n [\"block\", \"Block\"],\n [\"true\", \"Bool\"],\n [\"false\", \"Bool\"],\n [\"nil\", \"Nil\"],\n]);\n\nconst LEFT_DELIM = \"{{\";\nconst RIGHT_DELIM = \"}}\";\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 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) {\n this.src = src;\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 `{{` or EOF.\n let end = this.offset;\n while (end < this.src.length && !this.src.startsWith(LEFT_DELIM, 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 + LEFT_DELIM.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(LEFT_DELIM.length);\n if (trimLeft) {\n // skip the `-`\n this.advanceBy(1);\n // skip the whitespace right after `{{-` 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 `*/}}`\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 ? \"{{-\" : \"{{\",\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: \"*/}}\",\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 `}}` / `-}}`.\n // Go's spec says `-}}` requires *adjacent* whitespace; we accept\n // either `*/ -}}`, `*/-}}`, `*/ }}`, or `*/}}` for 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(RIGHT_DELIM, this.offset)) {\n throw this.err(\"expected `}}` to close comment\", this.pos(), {\n expected: \"}}\",\n found: this.src[this.offset] ?? \"end of input\",\n });\n }\n this.advanceBy(RIGHT_DELIM.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?\n if (this.src.startsWith(RIGHT_DELIM, this.offset)) {\n const start = this.pos();\n this.advanceBy(RIGHT_DELIM.length);\n this.mode = \"text\";\n return this.makeToken(\"RightDelim\", \"}}\", start);\n }\n if (this.src.startsWith(\"-}}\", this.offset)) {\n const start = this.pos();\n this.advanceBy(3);\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\", \"-}}\", start, { trimRight: true });\n }\n\n if (this.offset >= this.src.length) {\n throw this.err(\"unclosed action\", this.pos(), {\n expected: \"}}\",\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): readonly Token[] {\n const lex = 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 ChainNode,\n CommandNode,\n CommentNode,\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 { Lexer, type Token, type TokenType } from \"./lexer.js\";\nimport type { Pos } from \"./pos.js\";\n\n// ---------------------------------------------------------------------------\n// Public API.\n// ---------------------------------------------------------------------------\n\nexport interface ParseResult {\n /** The body of the unnamed/root template. */\n readonly root: ListNode;\n /** Templates created by `{{define \"name\"}}...{{end}}` blocks. */\n readonly defines: ReadonlyMap<string, ListNode>;\n /** Original source text — preserved for error snippets and Template.source. */\n readonly source: string;\n}\n\nexport function parse(source: string): ParseResult {\n const parser = new Parser(source);\n return parser.parseTemplate();\n}\n\n// ---------------------------------------------------------------------------\n// Internals.\n// ---------------------------------------------------------------------------\n\nclass Parser {\n private readonly lex: Lexer;\n private readonly buf: Token[] = [];\n private readonly defines = new Map<string, ListNode>();\n private readonly source: string;\n\n constructor(source: string) {\n this.source = source;\n this.lex = 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 { root, defines: this.defines, source: this.source };\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 \"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();\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();\n this.expect(\"RightDelim\", \"`}}`\");\n const list = this.parseList();\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 * 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 = this.peek().type === \"RightDelim\" ? undefined : this.parsePipeline();\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.peek().type === \"RightDelim\" ? undefined : this.parsePipeline();\n this.expect(\"RightDelim\", \"`}}`\");\n const list = this.parseList();\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 takes precedence —\n // the block body is the fallback, not the override.\n if (!this.defines.has(name)) {\n this.defines.set(name, list);\n }\n return pipe\n ? ({ type: \"Block\", pos: startPos, name, pipe, list, trim } satisfies BlockNode)\n : ({ type: \"Block\", pos: startPos, name, list, trim } satisfies BlockNode);\n }\n\n private parseDefine(_startPos: Pos, _trimLeft: boolean): void {\n const name = this.parseQuotedName();\n this.expect(\"RightDelim\", \"`}}`\");\n const list = this.parseList();\n this.consumeEnd();\n if (this.defines.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);\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\n private parsePipeline(): PipeNode {\n const startPos = this.peek().pos;\n const decls = this.tryParseDecls();\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(): { vars: VariableNode[]; isAssign: boolean } | undefined {\n if (this.peek().type !== \"Variable\") 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 (this.peek(n + 1).type !== \"Variable\") 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 this.next();\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();\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\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 * 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 matches Go's `missingkey=error` default: a\n * genuinely absent field returns `MISSING`, which the caller surfaces as\n * a `MissingFieldError`. The receiver-is-nullish case at the top of\n * `getField` is the trust-boundary exception documented inline below.\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 { 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 closes over the\n// engine's `toString` so that the value flattening uses the same\n// function the `\"stringifiable\"` matcher probes with. Two callsites\n// (probe at the gate, flatten in the body) — one source of truth.\n// ---------------------------------------------------------------------------\n\nfunction eagerBuiltins(toString: (v: unknown) => string): 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 argTypes: [\"comparable\"],\n },\n ne: {\n fn: (a: unknown, b: unknown) => !goEqPair(a, b),\n argTypes: [\"comparable\", \"comparable\"],\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: { fn: (a: unknown, b: unknown) => compare(a, b) < 0, argTypes: [\"ordered\", \"ordered\"] },\n le: { fn: (a: unknown, b: unknown) => compare(a, b) <= 0, argTypes: [\"ordered\", \"ordered\"] },\n gt: { fn: (a: unknown, b: unknown) => compare(a, b) > 0, argTypes: [\"ordered\", \"ordered\"] },\n ge: { fn: (a: unknown, b: unknown) => compare(a, b) >= 0, argTypes: [\"ordered\", \"ordered\"] },\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\"] },\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 },\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\n // \"number\". Body trusts the kinds and only routes the slice op.\n slice: {\n fn: (collection: unknown, ...indices: unknown[]) => {\n const i = indices.length >= 1 ? Number(indices[0]) : 0;\n const j = indices.length >= 2 ? Number(indices[1]) : undefined;\n return typeof collection === \"string\"\n ? collection.slice(i, j)\n : (collection as unknown[]).slice(i, j);\n },\n argTypes: [\"sliceable\", \"number\"],\n },\n\n // [LAW:single-enforcer] Formatted printers declare \"stringifiable\"\n // so the gate probes each non-string arg through `engine.toString`.\n // Bodies re-call `toString` to actually flatten — same source of\n // truth as the matcher. Closes audit findings B1–B4: typed-T no\n // longer silently `String(v)`-flattens to \"[object Object]\".\n print: {\n fn: (...args: unknown[]) => goPrint(args, toString),\n argTypes: [\"stringifiable\"],\n returnType: \"string\",\n },\n println: {\n fn: (...args: unknown[]) => `${goPrint(args, toString)}\\n`,\n argTypes: [\"stringifiable\"],\n returnType: \"string\",\n },\n printf: {\n fn: (format: string, ...args: unknown[]) => sprintf(format, args, toString),\n argTypes: [\"string\", \"stringifiable\"],\n returnType: \"string\",\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 },\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\"] },\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\"],\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\"],\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): FuncMap {\n return { ...eagerBuiltins(toString), ...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)) {\n const i = Number(key);\n if (!Number.isInteger(i))\n throw new Error(`index: array index must be integer, got ${describeType(key)}`);\n if (i < 0 || i >= collection.length) {\n throw new Error(`index: out of range [${i}] with length ${collection.length}`);\n }\n return collection[i];\n }\n if (collection instanceof Map) {\n return collection.get(key);\n }\n if (typeof collection === \"string\") {\n const i = Number(key);\n return collection[i];\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\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: (v: unknown) => string): 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 += stringifyForPrint(arg, toString);\n prevIsString = isString;\n }\n return out;\n}\n\n// [LAW:single-enforcer] No `String(value)` here — the gate guarantees\n// each arg is `\"stringifiable\"`. nil keeps Go-parity (\"<nil>\"); strings\n// pass through; anything else routes through the engine's `toString`.\nfunction stringifyForPrint(value: unknown, toString: (v: unknown) => string): string {\n if (value === null || value === undefined) return \"<nil>\";\n if (typeof value === \"string\") return value;\n return toString(value);\n}\n\nfunction sprintf(\n format: string,\n args: readonly unknown[],\n toString: (v: unknown) => string,\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 arg = args[argIdx++];\n out += formatVerb(verb ?? \"\", spec, arg, toString);\n i = j + 1;\n }\n return out;\n}\n\nfunction formatVerb(\n verb: string,\n spec: string,\n arg: unknown,\n toString: (v: unknown) => string,\n): string {\n switch (verb) {\n case \"s\":\n return typeof arg === \"string\"\n ? applyWidth(spec, arg)\n : applyWidth(spec, stringifyForPrint(arg, toString));\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 `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;\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, formatV(arg));\n case \"q\":\n return applyWidth(spec, JSON.stringify(stringifyForPrint(arg, toString)));\n case \"f\": {\n // [LAW:single-enforcer] See %d.\n if (typeof arg !== \"number\" && typeof arg !== \"bigint\") {\n return `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;\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 return applyWidth(spec, isTruthy(arg) ? \"true\" : \"false\");\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 `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;\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 `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;\n }\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// [LAW:one-source-of-truth] Exported so sprig's `toString`/`toStrings`\n// share this Go-`%v` formatter with printf's `%v` verb. Two places\n// computing \"%v shape\" would drift; exporting makes it impossible.\nexport function formatV(value: unknown): string {\n if (value === null || value === undefined) return \"<nil>\";\n if (typeof value === \"string\") return value;\n if (typeof value === \"bigint\") return value.toString();\n if (Array.isArray(value)) return `[${value.map(formatV).join(\" \")}]`;\n if (value instanceof Map) {\n return `map[${[...value.entries()].map(([k, v]) => `${formatV(k)}:${formatV(v)}`).join(\" \")}]`;\n }\n if (typeof value === \"object\") {\n return `{${Object.values(value).map(formatV).join(\" \")}}`;\n }\n return String(value);\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 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 * Lexical scope chain for the evaluator.\n *\n * [LAW:dataflow-not-control-flow] A `Scope` is an immutable record of\n * `dot`, `root` (the original `$`), and a parent pointer. New frames\n * are *constructed*; we never mutate an existing frame to \"leave\" it.\n * That means iterations of `{{range}}` cannot see each other's `$var`\n * declarations — the data shape itself prevents the bug.\n *\n * Variables are stored on the leaf frame as a flat record. A lookup\n * walks the parent chain. Assignment via `=` searches the chain and\n * mutates the *binding's* frame; declaration via `:=` always creates\n * the binding in the current leaf frame.\n */\n\nexport interface Scope {\n /** Current dot value — what `.` resolves to. */\n readonly dot: unknown;\n /** Top-level scope value — what `$` resolves to. */\n readonly root: unknown;\n /** Parent scope, or undefined for the top-level. */\n readonly parent: Scope | undefined;\n /** Variables declared in *this* frame. */\n readonly vars: Map<string, unknown>;\n}\n\nexport function rootScope(value: unknown): Scope {\n return { dot: value, root: value, parent: undefined, vars: new Map() };\n}\n\nexport function pushScope(parent: Scope, dot: unknown): Scope {\n return { dot, root: parent.root, parent, vars: new Map() };\n}\n\n/**\n * Look up a `$var` binding, walking the parent chain.\n * Returns `{ found: true, value }` on hit and `{ found: false }` on miss\n * — explicit shape rather than `undefined` so callers can disambiguate\n * \"not declared\" from \"declared but undefined\".\n */\nexport function lookupVar(\n scope: Scope,\n name: string,\n): { found: true; value: unknown } | { found: false } {\n let cur: Scope | undefined = scope;\n while (cur !== undefined) {\n if (cur.vars.has(name)) return { found: true, value: cur.vars.get(name) };\n cur = cur.parent;\n }\n return { found: false };\n}\n\n/** Declare a new variable in the leaf scope (for `:=`). */\nexport function declareVar(scope: Scope, name: string, value: unknown): void {\n scope.vars.set(name, value);\n}\n\n/**\n * Reassign an existing variable (for `=`). Walks the chain to find the\n * declaring frame and mutates its binding map. Throws via the caller's\n * supplied `notFound` factory when the variable was never declared.\n */\nexport function assignVar(scope: Scope, name: string, value: unknown): boolean {\n let cur: Scope | undefined = scope;\n while (cur !== undefined) {\n if (cur.vars.has(name)) {\n cur.vars.set(name, value);\n return true;\n }\n cur = cur.parent;\n }\n return false;\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 ActionNode,\n assertNever,\n type CommandNode,\n type ListNode,\n type Node,\n type PipeNode,\n} from \"../parser/ast.js\";\nimport { type ParseResult, parse as parseSource } from \"../parser/parser.js\";\nimport type { Pos } from \"../parser/pos.js\";\nimport { MISSING, walkFieldChain } from \"./access.js\";\nimport { defaultBuiltins } from \"./builtins.js\";\nimport { EvalError, FuncNotFoundError, MissingFieldError, TypeMismatchError } from \"./errors.js\";\nimport { isLazy } from \"./lazy.js\";\nimport { declareVar, lookupVar, pushScope, rootScope, type Scope } from \"./scope.js\";\nimport { isTruthy } from \"./truthy.js\";\n\n// ---------------------------------------------------------------------------\n// Public API.\n// ---------------------------------------------------------------------------\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 * - \"number\" — must be `typeof \"number\"` or `bigint`.\n * - \"bool\" — must be `typeof \"boolean\"`.\n * - \"T\" — opaque caller-defined T; treated as \"anything that is\n * not a string\". The guard does no further checking.\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\" — string directly OR a value the engine's\n * `toString` can flatten. The matcher *probes* the conversion;\n * downstream func bodies call `engine.toString` to actually flatten.\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 =\n | \"string\"\n | \"number\"\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\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 readonly fn: (...args: never[]) => unknown;\n /**\n * Declared positional parameter types. Required.\n *\n * For variadic funcs, declare the type of the trailing parameter\n * once — the no-silent-flatten guard validates every excess argument\n * against `argTypes[argTypes.length - 1]`. This matches Go's\n * `text/template` validation against repeated parameter types when\n * `Variadic`.\n *\n * The pipe-fed last argument is appended to the positional list\n * before validation, so it is checked against the trailing slot.\n */\n readonly argTypes: readonly ArgType[];\n readonly returnType?: ArgType;\n /**\n * Variadic-position lookup pattern.\n *\n * Default (omitted): the trailing slot repeats. `[\"string\", \"value\"]`\n * means \"first arg string, every arg after is value (heterogeneous)\".\n *\n * `\"alternating\"`: `argTypes` describes a *cycle*. The slot for arg\n * index `i` is `argTypes[i % argTypes.length]`. Used by `dict`'s\n * `string, value, string, value, …` kv pairing — without this the\n * gate cannot distinguish even-index keys (must be string) from\n * odd-index values (anything), and the body would re-validate per\n * key, splitting `[LAW:single-enforcer]` across two layers.\n *\n * Added by template-laws-3gt.3.\n */\n readonly argTypePattern?: \"alternating\";\n}\n\nexport type FuncMap = Record<string, TemplateFunc>;\n\nexport interface EngineConfig<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 when\n * they need to format a non-string value (the matcher probes via\n * `toString` to validate; the body re-uses it to flatten).\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 /** Optional registry of named functions usable in pipelines. */\n readonly funcs?: FuncMap;\n}\n\n// Per-evaluate context. Threaded through every internal method.\ninterface EvalContext<T> {\n readonly out: T[];\n readonly defines: ReadonlyMap<string, ListNode>;\n readonly source: string | undefined;\n}\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/**\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>(source: string, evaluate: (scope: unknown) => U[]) => Template<U>;\n\nexport class Template<T> {\n readonly source: string;\n private readonly _evaluate: (scope: unknown) => T[];\n\n private constructor(source: string, evaluate: (scope: unknown) => T[]) {\n this.source = source;\n this._evaluate = evaluate;\n }\n\n static {\n internalCreateTemplate = <U>(source: string, evaluate: (scope: unknown) => U[]) =>\n new Template(source, evaluate);\n }\n\n evaluate(scope: unknown): T[] {\n return this._evaluate(scope);\n }\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 funcs: FuncMap;\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: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 this.funcs = { ...defaultBuiltins(this.toString), ...(config.funcs ?? {}) };\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): Template<T> {\n const parsed = parseSource(source);\n return internalCreateTemplate(parsed.source, (scope) => this.evalParsed(parsed, scope));\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(parsed: ParseResult, scope: unknown): T[] {\n const out: T[] = [];\n const root = rootScope(scope);\n const ctx: EvalContext<T> = {\n out,\n defines: parsed.defines,\n source: parsed.source,\n };\n this.evalList(parsed.root, 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.out.push(this.fromString(node.text));\n return;\n case \"Comment\":\n return;\n case \"Action\": {\n const value = this.evalAction(node, scope, ctx);\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) this.emitFromValue(value, ctx);\n return;\n }\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 \"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 cond = this.evalPipe(node.pipe, scope, ctx);\n if (isTruthy(cond)) {\n this.evalList(node.list, scope, ctx);\n } else if (node.elseList) {\n this.evalList(node.elseList, scope, ctx);\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 value = this.evalPipe(node.pipe, scope, ctx);\n if (isTruthy(value)) {\n const child = pushScope(scope, value);\n this.evalList(node.list, child, ctx);\n } else if (node.elseList) {\n this.evalList(node.elseList, scope, ctx);\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 // For `range`, the pipeline's declarations bind to (key, value)\n // *per iteration*, not to the iterable as a whole. We evaluate the\n // pipe with its decls suppressed, then handle the bindings here.\n const value = this.evalPipeWithoutDecls(node.pipe, scope, ctx);\n const decls = node.pipe.decls;\n\n const entries = enumerateForRange(value);\n if (entries.length === 0) {\n if (node.elseList) this.evalList(node.elseList, scope, ctx);\n return;\n }\n for (const [key, item] of entries) {\n const child = pushScope(scope, item);\n if (decls.length === 1) {\n const name = decls[0]?.idents[0] ?? \"$\";\n declareVar(child, name, item);\n } else if (decls.length >= 2) {\n const k = decls[0]?.idents[0] ?? \"$\";\n const v = decls[1]?.idents[0] ?? \"$\";\n declareVar(child, k, key);\n declareVar(child, v, item);\n }\n this.evalList(node.list, child, ctx);\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 tpl = ctx.defines.get(node.name);\n if (!tpl) {\n throw new EvalError(`template ${JSON.stringify(node.name)} is not defined`, node.pos, {\n source: ctx.source,\n });\n }\n const arg = node.pipe ? this.evalPipe(node.pipe, scope, ctx) : scope.dot;\n const child = pushScope(scope, arg);\n this.evalList(tpl, child, ctx);\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 arg = node.pipe ? this.evalPipe(node.pipe, scope, ctx) : scope.dot;\n const child = pushScope(scope, arg);\n const tpl = ctx.defines.get(node.name) ?? node.list;\n this.evalList(tpl, child, ctx);\n }\n\n // -------------------------------------------------------------------\n // Expression-level dispatch (value-producing).\n // -------------------------------------------------------------------\n\n private evalAction(node: ActionNode, scope: Scope, ctx: EvalContext<T>): unknown {\n return this.evalPipe(node.pipe, scope, ctx);\n }\n\n private evalPipe(pipe: PipeNode, scope: Scope, ctx: EvalContext<T>): unknown {\n if (pipe.cmds.length === 0) {\n throw new EvalError(\"empty pipeline\", pipe.pos, { source: ctx.source });\n }\n let value: unknown = this.evalCommand(pipe.cmds[0] as CommandNode, scope, ctx, NO_PIPE);\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 });\n }\n\n // Apply variable declarations / assignments after the pipe is\n // fully evaluated. Multi-decl tuple semantics for `range` are\n // handled inside `evalRange` (which calls `evalPipeWithoutDecls`).\n if (pipe.decls.length > 0) {\n for (const decl of pipe.decls) {\n const name = decl.idents[0] ?? \"$\";\n declareVar(scope, name, value);\n }\n }\n return value;\n }\n\n private evalPipeWithoutDecls(pipe: PipeNode, scope: Scope, ctx: EvalContext<T>): unknown {\n // Synthesise a pipe with empty decls so the standard `evalPipe`\n // doesn't attempt the (single-binding) declaration. `evalRange`\n // handles its own multi-binding semantics.\n const stripped: PipeNode = {\n type: \"Pipe\",\n pos: pipe.pos,\n decls: [],\n isAssign: false,\n cmds: pipe.cmds,\n };\n return this.evalPipe(stripped, scope, ctx);\n }\n\n private evalCommand(cmd: CommandNode, scope: Scope, ctx: EvalContext<T>, piped: Piped): 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);\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) : this.evalPrimary(n, scope, ctx),\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 enforceArgTypes(\n head.ident,\n fn.argTypes,\n args,\n cmd.pos,\n ctx.source,\n this.toString,\n fn.argTypePattern,\n this.fromString as (s: string) => unknown,\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 try {\n return (fn.fn as (...a: unknown[]) => unknown)(...args);\n } catch (e) {\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(\n e.funcName,\n e.argIndex,\n e.expected,\n e.receivedSummary,\n cmd.pos,\n { source: ctx.source },\n );\n }\n throw e;\n }\n }\n\n private evalPrimary(node: Node, scope: Scope, ctx: EvalContext<T>): unknown {\n switch (node.type) {\n case \"Dot\":\n return scope.dot;\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(scope.dot, node.idents, node.pos, ctx);\n case \"Variable\":\n return this.resolveVariable(node.idents, scope, node.pos, ctx);\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 enforceArgTypes(\n node.ident,\n fn.argTypes,\n [],\n node.pos,\n ctx.source,\n this.toString,\n fn.argTypePattern,\n this.fromString as (s: string) => unknown,\n );\n return (fn.fn as () => unknown)();\n }\n case \"Chain\":\n return this.resolveFieldChain(\n this.evalPrimary(node.node, scope, ctx),\n node.fields,\n node.pos,\n ctx,\n );\n case \"Pipe\":\n return this.evalPipe(node, scope, ctx);\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) {\n throw new MissingFieldError(idents, pos, { source: ctx.source });\n }\n return result;\n }\n\n private resolveVariable(\n idents: readonly string[],\n scope: Scope,\n pos: Pos,\n ctx: EvalContext<T>,\n ): unknown {\n const head = idents[0] ?? \"$\";\n if (head === \"$\") {\n const tail = idents.slice(1);\n return tail.length === 0 ? scope.root : this.resolveFieldChain(scope.root, tail, pos, ctx);\n }\n const lookup = lookupVar(scope, head);\n if (!lookup.found) {\n throw new EvalError(`undefined variable ${head}`, pos, { source: ctx.source });\n }\n const tail = idents.slice(1);\n return tail.length === 0 ? lookup.value : this.resolveFieldChain(lookup.value, tail, pos, ctx);\n }\n\n // -------------------------------------------------------------------\n // Output stream.\n // -------------------------------------------------------------------\n\n private emitFromValue(value: unknown, ctx: EvalContext<T>): void {\n // [LAW:dataflow-not-control-flow] No skip-when-null branch. The\n // emit always runs; the value (including null/undefined) drives\n // what is pushed. Matches Go's text/template, which emits\n // `<no value>` for nil pipelines uniformly.\n if (value === null || value === undefined) {\n ctx.out.push(this.fromString(\"<no value>\"));\n return;\n }\n if (typeof value === \"string\") {\n ctx.out.push(this.fromString(value));\n return;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n ctx.out.push(this.fromString(String(value)));\n return;\n }\n // Arrays / Maps / plain objects: format Go-like (`[a b c]`, `map[k:v]`,\n // `{f1 f2}`) when the value lands in a string-output stream. This\n // matches Go's `fmt.Sprintf(\"%v\", v)` shape for the common cases\n // and keeps the conformance corpus byte-equal.\n if (Array.isArray(value)) {\n ctx.out.push(this.fromString(formatArrayLikeGo(value)));\n return;\n }\n if (value instanceof Map) {\n ctx.out.push(this.fromString(formatMapLikeGo(value)));\n return;\n }\n ctx.out.push(value as T);\n }\n}\n\nfunction formatArrayLikeGo(arr: readonly unknown[]): string {\n return `[${arr.map(formatScalarLikeGo).join(\" \")}]`;\n}\n\nfunction formatMapLikeGo(m: ReadonlyMap<unknown, unknown>): string {\n const parts: string[] = [];\n for (const [k, v] of m) {\n parts.push(`${formatScalarLikeGo(k)}:${formatScalarLikeGo(v)}`);\n }\n return `map[${parts.join(\" \")}]`;\n}\n\nfunction formatScalarLikeGo(v: unknown): string {\n if (v === null || v === undefined) return \"<nil>\";\n if (Array.isArray(v)) return formatArrayLikeGo(v);\n if (v instanceof Map) return formatMapLikeGo(v);\n return String(v);\n}\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, none\n// of which appear in any registration as of template-laws-3gt.1.\nexport function enforceArgTypes(\n funcName: string,\n argTypes: readonly ArgType[],\n values: unknown[],\n pos: Pos,\n src: string | undefined,\n toString: (value: unknown) => string = defaultToString,\n pattern?: \"alternating\",\n fromString: (s: string) => unknown = defaultFromString,\n): void {\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 by default, modulo cycle\n // when `pattern === \"alternating\"`) lives here once, not duplicated\n // at the loop body. See template-laws-3gt.3 for the alternation\n // motivation (`dict`'s string/value kv pairing).\n const lookup = makeSlotLookup(argTypes, pattern);\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 if (!matchesArgType(declared, value, toString)) {\n throw new TypeMismatchError(\n funcName,\n i + 1,\n humanArgType(declared),\n describeValue(value),\n 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] 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 ${describeValue(values[firstOrdered])}`,\n describeValue(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 ${describeValue(values[firstComparable])}`,\n describeValue(value),\n pos,\n { source: src },\n );\n }\n }\n }\n}\n\n// [LAW:dataflow-not-control-flow] The variadic-overflow rule is encoded\n// as a function that maps an arg index to its declared kind, picked\n// once per call. The loop in `enforceArgTypes` then has the same shape\n// for every func — no per-iteration `if (pattern === \"alternating\")`.\nfunction makeSlotLookup(\n argTypes: readonly ArgType[],\n pattern: \"alternating\" | undefined,\n): (i: number) => ArgType {\n if (argTypes.length === 0) {\n // Funcs registered with `argTypes: []` are zero-arity at the gate.\n // The loop only runs when `values.length > argTypes.length`, which\n // is itself a registration bug — fall back to \"value\" so the loop\n // does not throw on a stale zero-arity registration.\n return () => \"value\";\n }\n if (pattern === \"alternating\") {\n const len = argTypes.length;\n return (i) => argTypes[i % len] as ArgType;\n }\n const trailing = argTypes[argTypes.length - 1] as ArgType;\n return (i) => (i < argTypes.length ? (argTypes[i] as ArgType) : trailing);\n}\n\nfunction matchesArgType(\n declared: ArgType,\n value: unknown,\n toString: (value: unknown) => string,\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 \"number\":\n return typeof value === \"number\" || typeof value === \"bigint\";\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 return (\n value !== null &&\n value !== undefined &&\n typeof value !== \"string\" &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\" &&\n typeof value !== \"bigint\" &&\n typeof value !== \"symbol\"\n );\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 \"stringifiable\": {\n // Probe (do not transform). String passes through trivially —\n // avoids invoking the consumer's `toString` for the common case.\n // For non-strings, attempt the conversion: a successful return\n // means the value can flatten, a throw means it cannot. The\n // matcher reports the boolean; downstream func bodies (.6) call\n // `engine.toString` again to actually flatten.\n if (typeof value === \"string\") return true;\n try {\n toString(value);\n return true;\n } catch {\n return false;\n }\n }\n case \"liftable\":\n // Mirror of \"stringifiable\" in the opposite direction: a slot\n // that accepts T or a string the engine can lift to T via\n // `engine.fromString`. The matcher only validates membership;\n // the actual lift happens once in `enforceArgTypes` so func\n // bodies see T uniformly. Non-string non-T values fail the\n // gate — the same shape rules as \"T\".\n return (\n typeof value === \"string\" ||\n (value !== null &&\n value !== undefined &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\" &&\n typeof value !== \"bigint\" &&\n typeof value !== \"symbol\")\n );\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 }\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`. Strings\n// flow through unchanged (the `T = string` happy path). Primitives\n// (number/bigint/boolean) and nil get their natural string form so\n// vanilla string-engine consumers can `print 1`, `printf \"%s\" true`\n// etc. without configuring a flattener. Anything else — arrays,\n// objects, Maps, Sets, functions, symbols — is the actual \"typed-T\n// without consumer flattener\" case the README contract is about, and\n// throws a 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 describeValue(value),\n { line: 0, column: 0, offset: 0 },\n );\n}\n\nfunction 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, and other built-ins by\n // requiring a null prototype or the plain Object prototype.\n const proto = Object.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\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 \"T\":\n return \"T (consumer-defined fragment)\";\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 or convertible via the engine's toString)\";\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 \"number\":\n case \"bool\":\n return t;\n }\n}\n\nfunction describeValue(value: unknown): string {\n if (value === null) return \"null\";\n if (value === undefined) return \"undefined\";\n if (Array.isArray(value)) return \"array\";\n if (value instanceof Map) return \"Map\";\n return typeof value;\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).\nexport function atoi(s: string): number {\n if (!/^[+-]?\\d+$/.test(s)) return 0;\n const n = Number.parseInt(s, 10);\n return Number.isNaN(n) ? 0 : n;\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.\nexport function int(v: unknown): number {\n if (typeof v === \"number\") return Math.trunc(v);\n if (typeof v === \"bigint\") return Number(v);\n if (typeof v === \"string\") {\n const parsed = parseBase0(v);\n if (parsed === null) return 0;\n const n = Number.parseInt(parsed.digits, parsed.base);\n return Number.isNaN(n) ? 0 : parsed.sign * n;\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 * Same coercion rules as `int`; differs only in the carrier type.\n */\n\n// [LAW:one-type-per-behavior] `int` and `int64` differ only in\n// representation precision, not in coercion semantics. They share\n// `parseBase0` so the string-parse behavior cannot drift.\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`).\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 = Number.parseInt(body, 8);\n return Number.isNaN(n) ? 0 : sign * n;\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","import { formatV } from \"../../evaluator/builtins.js\";\n\n/**\n * `toString v` — Go sprig's `strval`. Strings pass through; everything\n * else routes through Go's `%v` formatter (`fmt.Sprintf(\"%v\", v)`).\n *\n * [LAW:one-source-of-truth] Shares `formatV` with printf's `%v` verb —\n * one place owns \"what does Go's %v look like\".\n */\nexport function toString(v: unknown): string {\n return typeof v === \"string\" ? v : formatV(v);\n}\n","import { toString } from \"./toString.js\";\n\n/**\n * `toStrings list` — map each element through `toString`.\n *\n * The `\"list\"` gate validates array-ness once; this body trusts it\n * and only routes the per-element conversion.\n */\n// [LAW:single-enforcer] List shape is the gate's job; per-element\n// conversion is `toString`'s job. This function only composes.\nexport function toStrings(list: unknown[]): string[] {\n return list.map(toString);\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// Renamed local bindings — `toString` as a property key in the\n// returned FuncMap collides with `Object.prototype.toString`'s implicit\n// type, which broke TS's contextual inference for the entry. Using\n// distinct local names (`sprigToString`) inside the factory keeps the\n// public func name `toString` while letting the property key stand on\n// its own.\nimport { toString as sprigToString } from \"./toString.js\";\nimport { toStrings as sprigToStrings } from \"./toStrings.js\";\n\nexport {\n atoi,\n float64,\n int,\n int64,\n sprigToString as toString,\n sprigToStrings as toStrings,\n toDecimal,\n toRawJson,\n};\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/toString: heterogeneous-by-\n // intent; the body is the per-kind dispatch\n // [LAW:dataflow-not-control-flow]\n // - \"list\" — toStrings: per-element conversion, list shape\n // enforced once at the gate\n // - \"serializable\" — toRawJson: gate rejects functions/symbols/\n // circular refs so the body never silently\n // emits \"null\"\n //\n // The local-binding indirection (`const map: FuncMap = ...`) forces\n // TS to apply the FuncMap contextual type to the literal. Without it,\n // a property key named `toString` shadows `Object.prototype.toString`\n // during TS's literal-type inference, which widens `argTypes` from\n // a tuple of ArgType to `string[]` and breaks the entry.\n const map: FuncMap = {\n atoi: { fn: (s) => atoi(s as string), argTypes: [\"string\"], returnType: \"number\" },\n int: { fn: (v) => int(v), argTypes: [\"value\"], returnType: \"number\" },\n int64: { fn: (v) => int64(v), argTypes: [\"value\"] },\n float64: { fn: (v) => float64(v), argTypes: [\"value\"], returnType: \"number\" },\n // The `toString` key matches `Object.prototype.toString`, which\n // shadows TS's contextual typing for this single entry. Pinning\n // the literal types with `as const` (or `satisfies TemplateFunc`)\n // is the standard escape — the entry's shape is identical to its\n // siblings; only TS inference needs the hint.\n toString: {\n fn: (v: unknown) => sprigToString(v),\n argTypes: [\"value\"] as const,\n returnType: \"string\" as const,\n },\n toStrings: {\n fn: (l) => sprigToStrings(l as unknown[]),\n argTypes: [\"list\"],\n },\n toDecimal: {\n fn: (s) => toDecimal(s as string),\n argTypes: [\"string\"],\n returnType: \"number\",\n },\n toRawJson: {\n fn: (v) => toRawJson(v),\n argTypes: [\"serializable\"],\n returnType: \"string\",\n },\n };\n return map;\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 default: { fn: (a, b) => defaultFn(a, b), argTypes: [\"value\", \"truthy\"] },\n empty: { fn: (v) => empty(v), argTypes: [\"truthy\"] },\n coalesce: { fn: (...vs) => coalesce(...vs), argTypes: [\"truthy\"] },\n ternary: { fn: (a, b, c) => ternary(a, b, c), argTypes: [\"value\", \"value\", \"truthy\"] },\n fromJson: { fn: (s) => fromJson(s as string), argTypes: [\"string\"] },\n toJson: { fn: (v) => toJson(v), argTypes: [\"serializable\"], returnType: \"string\" },\n toPrettyJson: {\n fn: (v) => toPrettyJson(v),\n argTypes: [\"serializable\"],\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 `argTypePattern: \"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 */\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 * `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 } 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 { dict, get, hasKey, keys, merge, mergeOverwrite, omit, pick, pluck, set, unset, values };\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 argTypePattern: \"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 argTypePattern: \"alternating\",\n },\n get: {\n fn: (d, k) => get(d as Record<string, unknown>, k as string),\n argTypes: [\"dict\", \"string\"],\n },\n set: {\n fn: (d, k, v) => set(d as Record<string, unknown>, k as string, v),\n argTypes: [\"dict\", \"string\", \"value\"],\n },\n unset: {\n fn: (d, k) => unset(d as Record<string, unknown>, k as string),\n argTypes: [\"dict\", \"string\"],\n },\n keys: { fn: (d) => keys(d as Record<string, unknown>), argTypes: [\"dict\"] },\n values: { fn: (d) => values(d as Record<string, unknown>), argTypes: [\"dict\"] },\n pluck: {\n fn: (k, ...d) => pluck(k as string, ...(d as Record<string, unknown>[])),\n argTypes: [\"string\", \"dict\"],\n },\n pick: {\n fn: (d, ...k) => pick(d as Record<string, unknown>, ...(k as string[])),\n argTypes: [\"dict\", \"string\"],\n },\n omit: {\n fn: (d, ...k) => omit(d as Record<string, unknown>, ...(k as string[])),\n argTypes: [\"dict\", \"string\"],\n },\n hasKey: {\n fn: (d, k) => hasKey(d as Record<string, unknown>, k as string),\n argTypes: [\"dict\", \"string\"],\n },\n merge: {\n fn: (d, ...s) => merge(d as Record<string, unknown>, ...(s as Record<string, unknown>[])),\n argTypes: [\"dict\"],\n },\n mergeOverwrite: {\n fn: (d, ...s) =>\n mergeOverwrite(d as Record<string, unknown>, ...(s as Record<string, unknown>[])),\n argTypes: [\"dict\"],\n },\n };\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 \"list\" gate validates array-ness.\nexport function chunk(size: number | bigint, list: unknown[]): unknown[][] {\n const n = Math.max(1, Math.trunc(Number(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","// [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\" gate validates array-ness.\nexport function slice(list: unknown[], i?: number | bigint, j?: number | bigint): unknown[] {\n const start = i === undefined ? 0 : Number(i);\n const end = j === undefined ? list.length : Number(j);\n return list.slice(start, end);\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 { append } from \"./append.js\";\nimport { chunk } from \"./chunk.js\";\nimport { compact } from \"./compact.js\";\nimport { concat } from \"./concat.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 { uniq } from \"./uniq.js\";\nimport { without } from \"./without.js\";\n\nexport {\n append,\n chunk,\n compact,\n concat,\n first,\n has,\n initial,\n last,\n len,\n list,\n prepend,\n rest,\n reverse,\n slice,\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: { fn: (...a) => list(...a), argTypes: [\"value\"] },\n first: { fn: (l) => first(l as unknown[]), argTypes: [\"list\"] },\n last: { fn: (l) => last(l as unknown[]), argTypes: [\"list\"] },\n rest: { fn: (l) => rest(l as unknown[]), argTypes: [\"list\"] },\n initial: { fn: (l) => initial(l as unknown[]), argTypes: [\"list\"] },\n len: { fn: (l) => len(l), argTypes: [\"sized\"] },\n reverse: { fn: (l) => reverse(l as unknown[]), argTypes: [\"list\"] },\n uniq: { fn: (l) => uniq(l as unknown[]), argTypes: [\"list\"] },\n without: {\n fn: (l, ...e) => without(l as unknown[], ...e),\n argTypes: [\"list\", \"value\"],\n },\n has: { fn: (i, l) => has(i, l as unknown[]), argTypes: [\"value\", \"list\"] },\n compact: { fn: (l) => compact(l as unknown[]), argTypes: [\"list\"] },\n slice: {\n fn: (l, i, j) => slice(l as unknown[], i as number | bigint, j as number | bigint),\n argTypes: [\"list\", \"number\", \"number\"],\n },\n concat: { fn: (...l) => concat(...(l as unknown[][])), argTypes: [\"list\"] },\n chunk: {\n fn: (s, l) => chunk(s as number | bigint, l as unknown[]),\n argTypes: [\"number\", \"list\"],\n },\n prepend: {\n fn: (l, i) => prepend(l as unknown[], i),\n argTypes: [\"list\", \"value\"],\n },\n append: {\n fn: (l, i) => append(l as unknown[], i),\n argTypes: [\"list\", \"value\"],\n },\n };\n}\n","/** `add a b c …` — variadic integer sum. */\nexport function add(...args: (number | bigint)[]): number {\n return args.reduce<number>((acc, v) => acc + Math.trunc(Number(v)), 0);\n}\n","export function addf(...args: (number | bigint)[]): number {\n return args.reduce<number>((acc, v) => acc + Number(v), 0);\n}\n","export function ceil(a: number | bigint): number {\n return Math.ceil(Number(a));\n}\n","/** `div a b` — integer division (Go semantics: truncate toward zero). */\nexport function div(a: number | bigint, b: number | bigint): number {\n return Math.trunc(Math.trunc(Number(a)) / Math.trunc(Number(b)));\n}\n","export function divf(a: number | bigint, b: number | bigint): number {\n return Number(a) / Number(b);\n}\n","export function floor(a: number | bigint): number {\n return Math.floor(Number(a));\n}\n","/** `max a b c …` — variadic maximum. */\nexport function max(...args: (number | bigint)[]): number {\n return args.map((v) => Number(v)).reduce((m, v) => (v > m ? v : m), Number.NEGATIVE_INFINITY);\n}\n","/** `min a b c …` — variadic minimum. */\nexport function min(...args: (number | bigint)[]): number {\n return args.map((v) => Number(v)).reduce((m, v) => (v < m ? v : m), Number.POSITIVE_INFINITY);\n}\n","/** `mod a b` — modulo. JS `%` matches Go's: sign follows the dividend. */\nexport function mod(a: number | bigint, b: number | bigint): number {\n return Math.trunc(Number(a)) % Math.trunc(Number(b));\n}\n","/** `mul a b c …` — variadic integer product. */\nexport function mul(...args: (number | bigint)[]): number {\n return args.reduce<number>((acc, v) => acc * Math.trunc(Number(v)), 1);\n}\n","export function mulf(...args: (number | bigint)[]): number {\n return args.reduce<number>((acc, v) => acc * Number(v), 1);\n}\n","/** `round a [precision=0]` — round half-away-from-zero, matching Go sprig. */\nexport function round(a: number | bigint, precision: number | bigint = 0): number {\n const n = Number(a);\n const p = Math.trunc(Number(precision));\n const factor = 10 ** p;\n return (Math.sign(n) * Math.round(Math.abs(n) * factor)) / factor;\n}\n","export function sub(a: number | bigint, b: number | bigint): number {\n return Math.trunc(Number(a)) - Math.trunc(Number(b));\n}\n","export function subf(a: number | bigint, b: number | bigint): number {\n return Number(a) - Number(b);\n}\n","/** Sprig math utilities — int and float arithmetic. */\n\nimport type { FuncMap } from \"../../evaluator/evaluator.js\";\nimport { add } from \"./add.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 { min } from \"./min.js\";\nimport { mod } from \"./mod.js\";\nimport { mul } from \"./mul.js\";\nimport { mulf } from \"./mulf.js\";\nimport { round } from \"./round.js\";\nimport { sub } from \"./sub.js\";\nimport { subf } from \"./subf.js\";\n\nexport { add, addf, ceil, div, divf, floor, max, min, mod, mul, mulf, round, sub, subf };\n\nexport function sprigMath(): FuncMap {\n // [LAW:single-enforcer] enforceArgTypes guarantees runtime values\n // match the declared \"number\" type (number or bigint). The bodies'\n // remaining `Number(v)` calls are bigint→number conversions, not\n // boundary coercions — they do real arithmetic work.\n return {\n add: { fn: (...a) => add(...(a as (number | bigint)[])), argTypes: [\"number\"] },\n sub: {\n fn: (a, b) => sub(a as number | bigint, b as number | bigint),\n argTypes: [\"number\", \"number\"],\n },\n mul: { fn: (...a) => mul(...(a as (number | bigint)[])), argTypes: [\"number\"] },\n div: {\n fn: (a, b) => div(a as number | bigint, b as number | bigint),\n argTypes: [\"number\", \"number\"],\n },\n mod: {\n fn: (a, b) => mod(a as number | bigint, b as number | bigint),\n argTypes: [\"number\", \"number\"],\n },\n min: { fn: (...a) => min(...(a as (number | bigint)[])), argTypes: [\"number\"] },\n max: { fn: (...a) => max(...(a as (number | bigint)[])), argTypes: [\"number\"] },\n floor: { fn: (a) => floor(a as number | bigint), argTypes: [\"number\"] },\n ceil: { fn: (a) => ceil(a as number | bigint), argTypes: [\"number\"] },\n round: {\n fn: (a, p) => round(a as number | bigint, p as number | bigint),\n argTypes: [\"number\", \"number\"],\n },\n addf: { fn: (...a) => addf(...(a as (number | bigint)[])), argTypes: [\"number\"] },\n subf: {\n fn: (a, b) => subf(a as number | bigint, b as number | bigint),\n argTypes: [\"number\", \"number\"],\n },\n mulf: { fn: (...a) => mulf(...(a as (number | bigint)[])), argTypes: [\"number\"] },\n divf: {\n fn: (a, b) => divf(a as number | bigint, b as number | bigint),\n argTypes: [\"number\", \"number\"],\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 | bigint = -1): string[] {\n const re = new RegExp(pattern, \"g\");\n const limit = Number(n);\n const out: string[] = [];\n for (const m of s.matchAll(re)) {\n out.push(m[0]);\n if (limit >= 0 && out.length >= limit) break;\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 | bigint = -1): string[] {\n const re = new RegExp(pattern);\n const limit = Number(n);\n if (limit < 0) return s.split(re);\n return s.split(re).slice(0, limit);\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 },\n regexFind: {\n fn: (p, s) => regexFind(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n regexFindAll: {\n fn: (p, s, n) => regexFindAll(p as string, s as string, n as number | bigint),\n argTypes: [\"string\", \"string\", \"number\"],\n },\n regexReplaceAll: {\n fn: (p, s, r) => regexReplaceAll(p as string, s as string, r as string),\n argTypes: [\"string\", \"string\", \"string\"],\n },\n regexReplaceAllLiteral: {\n fn: (p, s, r) => regexReplaceAllLiteral(p as string, s as string, r as string),\n argTypes: [\"string\", \"string\", \"string\"],\n },\n regexSplit: {\n fn: (p, s, n) => regexSplit(p as string, s as string, n as number | bigint),\n argTypes: [\"string\", \"string\", \"number\"],\n },\n };\n}\n","/**\n * `abbrev width s` — truncate `s` to `width` chars, replacing the tail\n * with `...` when truncation occurs. Width must be at least 4 to fit\n * the ellipsis; smaller widths return `s` unchanged (Go sprig\n * behavior).\n */\nexport function abbrev(width: number | bigint, s: string): string {\n const w = Number(width);\n if (s.length <= w) return s;\n if (w < 4) return s;\n return `${s.slice(0, w - 3)}...`;\n}\n","/**\n * `abbrevboth left right s` — abbreviate from both ends, leaving `...`\n * around the visible window. Mirrors Go sprig's abbrevboth semantics:\n * left/right specify offsets (0-indexed); the result has `...` around\n * a slice taken between them.\n */\nexport function abbrevboth(left: number | bigint, right: number | bigint, s: string): string {\n const l = Number(left);\n const r = Number(right);\n if (r < 7 || s.length < r) return s;\n if (l < 0 || l > s.length - r + 1) return s;\n return `...${s.slice(l, l + r - 6)}...`;\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`. JS strings\n * are UTF-16; iterating with `for…of` (or `Array.from(s)`) yields\n * code points the same way Go yields runes, so the rune-level logic\n * carries over. We intentionally do NOT attempt to mirror xstrings'\n * `isAlphabet` CJK-exclusion table — for ASCII/Latin templates, which\n * are what real users feed sprig, the simpler `isLetter` test\n * matches Go's output. The fixture suite pins the cases consumers\n * 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\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 = Array.from(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 = Array.from(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 | bigint, s: string): string {\n const pad = \" \".repeat(Math.max(0, Number(n)));\n return s\n .split(\"\\n\")\n .map((line) => pad + line)\n .join(\"\\n\");\n}\n","/** `initials s` — first letter of each whitespace-separated word, uppercased. */\nexport function initials(s: string): string {\n return s\n .split(/\\s+/)\n .filter((w) => w.length > 0)\n .map((w) => (w[0] ?? \"\").toUpperCase())\n .join(\"\");\n}\n","import { 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 ${describe(v)}`,\n );\n }\n parts.push(String(v));\n }\n return parts.join(sep);\n}\n\nfunction describe(v: unknown): string {\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","/**\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 | bigint, 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 at the dispatch gate; the body trusts them. Bigint comes\n// in via the \"int\" slot for >2^53 counts — convert to a comparison\n// against 1 that works for both.\nexport function plural(one: string, many: string, n: number | bigint): string {\n return n === 1 || n === 1n ? 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 | bigint, s: string): string {\n const count = Math.max(0, Number(n));\n return s.repeat(count);\n}\n","/** Replaces ALL occurrences of `old` with `nw` in `s` (Go's strings.Replace n=-1). */\nexport function replace(old: string, nw: string, s: string): string {\n return s.split(old).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","/**\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 = s.split(sep);\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","export function splitList(sep: string, s: string): string[] {\n return s.split(sep);\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\n// [LAW:single-enforcer] Slot kinds (`[\"string\", \"int\", \"string\"]`)\n// validate the inputs at the dispatch gate. The body owns the\n// SplitN→map shape transform.\nexport function splitn(sep: string, n: number | bigint, s: string): Record<string, string> {\n const cap = typeof n === \"bigint\" ? Number(n) : n;\n const parts = goSplitN(s, sep, cap);\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)\n// Empty `sep` splits after each rune; for ASCII inputs the JS code-\n// unit split matches.\nfunction goSplitN(s: string, sep: string, n: number): string[] {\n if (n === 0) return [];\n const all = sep === \"\" ? Array.from(s) : s.split(sep);\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","/**\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 */\nexport function substr(start: number | bigint, end: number | bigint, s: string): string {\n let i = Math.max(0, Number(start));\n let j = end === undefined || end === null ? s.length : Number(end);\n if (j > s.length) j = s.length;\n if (i > j) i = j;\n return s.slice(i, j);\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","/** `trimAll cutset s` — strip leading + trailing chars in `cutset`. */\nexport function trimAll(cutset: string, s: string): string {\n if (cutset.length === 0) return s;\n const set = new Set([...cutset]);\n let start = 0;\n while (start < s.length && set.has(s[start] as string)) start += 1;\n let end = s.length;\n while (end > start && set.has(s[end - 1] as string)) end -= 1;\n return s.slice(start, end);\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","/**\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 */\nexport function trunc(n: number | bigint, s: string): string {\n const len = Number(n);\n if (Number.isNaN(len)) return s;\n if (len < 0) {\n const k = -len;\n return k >= s.length ? s : s.slice(s.length - k);\n }\n return len >= s.length ? s : s.slice(0, len);\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 | bigint, s: string): string {\n return wrapWithSeparator(Number(width), \"\\n\", s);\n}\n\nexport function wrapWithSeparator(width: number, sep: string, s: string): string {\n if (!Number.isFinite(width) || 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 | bigint, sep: string, s: string): string {\n return wrapWithSeparator(Number(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. Function bodies coerce primitives with\n // `String(.)` only after asserting the value is not a typed-T\n // object; see `join` for the nested-element case the boundary gate\n // can't describe.\n return {\n abbrev: {\n fn: (w, s) => abbrev(w as number | bigint, s as string),\n argTypes: [\"number\", \"string\"],\n },\n abbrevboth: {\n fn: (l, r, s) => abbrevboth(l as number | bigint, r as number | bigint, s as string),\n argTypes: [\"number\", \"number\", \"string\"],\n },\n camelcase: { fn: (s) => camelcase(s as string), argTypes: [\"string\"], returnType: \"string\" },\n cat: { fn: (...a) => cat(...(a as string[])), argTypes: [\"string\"] },\n contains: {\n fn: (sub, s) => contains(sub as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n hasPrefix: {\n fn: (p, s) => hasPrefix(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n hasSuffix: {\n fn: (sf, s) => hasSuffix(sf as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n indent: {\n fn: (n, s) => indent(n as number | bigint, s as string),\n argTypes: [\"number\", \"string\"],\n },\n initials: { fn: (s) => initials(s as string), argTypes: [\"string\"] },\n join: {\n fn: (sep, list) => join(sep as string, list as unknown[]),\n argTypes: [\"string\", \"list\"],\n },\n kebabcase: { fn: (s) => kebabcase(s as string), argTypes: [\"string\"], returnType: \"string\" },\n lower: { fn: (s) => lower(s as string), argTypes: [\"string\"] },\n nindent: {\n fn: (n, s) => nindent(n as number | bigint, s as string),\n argTypes: [\"number\", \"string\"],\n },\n nospace: { fn: (s) => nospace(s as string), argTypes: [\"string\"], returnType: \"string\" },\n plural: {\n fn: (one, many, n) => plural(one as string, many as string, n as number | bigint),\n argTypes: [\"string\", \"string\", \"number\"],\n returnType: \"string\",\n },\n quote: { fn: (...a) => quote(...(a as string[])), argTypes: [\"string\"] },\n regexQuoteMeta: {\n fn: (s) => regexQuoteMeta(s as string),\n argTypes: [\"string\"],\n returnType: \"string\",\n },\n repeat: {\n fn: (n, s) => repeat(n as number | bigint, s as string),\n argTypes: [\"number\", \"string\"],\n },\n replace: {\n fn: (o, n, s) => replace(o as string, n as string, s as string),\n argTypes: [\"string\", \"string\", \"string\"],\n },\n snakecase: { fn: (s) => snakecase(s as string), argTypes: [\"string\"], returnType: \"string\" },\n split: { fn: (sep, s) => split(sep as string, s as string), argTypes: [\"string\", \"string\"] },\n splitList: {\n fn: (sep, s) => splitList(sep as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n splitn: {\n fn: (sep, n, s) => splitn(sep as string, n as number | bigint, s as string),\n argTypes: [\"string\", \"number\", \"string\"],\n returnType: \"dict\",\n },\n squote: { fn: (...a) => squote(...(a as string[])), argTypes: [\"string\"] },\n substr: {\n fn: (i, j, s) => substr(i as number | bigint, j as number | bigint, s as string),\n argTypes: [\"number\", \"number\", \"string\"],\n },\n swapcase: { fn: (s) => swapcase(s as string), argTypes: [\"string\"], returnType: \"string\" },\n title: { fn: (s) => title(s as string), argTypes: [\"string\"] },\n trim: { fn: (s) => trim(s as string), argTypes: [\"string\"] },\n trimAll: {\n fn: (cs, s) => trimAll(cs as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n trimPrefix: {\n fn: (p, s) => trimPrefix(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n trimSuffix: {\n fn: (sf, s) => trimSuffix(sf as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n trunc: {\n fn: (n, s) => trunc(n as number | bigint, s as string),\n argTypes: [\"number\", \"string\"],\n },\n untitle: { fn: (s) => untitle(s as string), argTypes: [\"string\"] },\n upper: { fn: (s) => upper(s as string), argTypes: [\"string\"] },\n wrap: {\n fn: (w, s) => wrap(w as number | bigint, s as string),\n argTypes: [\"number\", \"string\"],\n },\n wrapWith: {\n fn: (w, sep, s) => wrapWith(w as number | bigint, sep as string, s as string),\n argTypes: [\"number\", \"string\", \"string\"],\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\"] },\n kindIs: { fn: (k, v) => kindIs(k as string, v), argTypes: [\"string\", \"reflective\"] },\n typeOf: { fn: (v) => typeOf(v), argTypes: [\"reflective\"] },\n typeIs: { fn: (t, v) => typeIs(t as string, v), argTypes: [\"string\", \"reflective\"] },\n typeIsLike: { fn: (t, v) => typeIsLike(t as string, v), argTypes: [\"string\", \"reflective\"] },\n deepEqual: { fn: (a, b) => deepEqual(a, b), argTypes: [\"value\", \"value\"] },\n deepCopy: { fn: (v) => deepCopy(v), argTypes: [\"value\"] },\n };\n}\n"],"mappings":";AAqCA,IAAa,gBAAb,cAAmC,MAAM;CACvC,OAAiC;CACjC,OAA2B;CAC3B;CACA;CAEA,YAAY,SAAiB,KAAU,MAA4B,EAAE,EAAE;AACrE,QAAM,QAAQ;AACd,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,E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_enc","_dec","_enc","isUpper"],"sources":["../src/errors.ts","../src/parser/ast.ts","../src/parser/lexer.ts","../src/parser/parser.ts","../src/evaluator/access.ts","../src/sprig/types/deepEqual.ts","../src/evaluator/lazy.ts","../src/evaluator/truthy.ts","../src/evaluator/builtins.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/toString.ts","../src/sprig/conversions/toStrings.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/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/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 * ├── 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 | \"TypeMismatchError\"\n | \"MissingFieldError\"\n | \"FailError\";\n\nexport interface TemplateErrorContext {\n readonly source?: string | undefined;\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);\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\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 ${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\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\nexport interface ParseResult {\n /** The body of the unnamed/root template. */\n readonly root: ListNode;\n /** Templates created by `{{define \"name\"}}...{{end}}` blocks. */\n readonly defines: ReadonlyMap<string, ListNode>;\n /** Original source text — preserved for error snippets and Template.source. */\n readonly source: string;\n}\n\nexport function parse(source: string, delims?: Delims): ParseResult {\n const parser = new Parser(source, delims);\n return parser.parseTemplate();\n}\n\n// ---------------------------------------------------------------------------\n// Internals.\n// ---------------------------------------------------------------------------\n\nclass Parser {\n private readonly lex: Lexer;\n private readonly buf: Token[] = [];\n private readonly defines = new Map<string, ListNode>();\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) {\n this.source = source;\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 { root, defines: this.defines, source: this.source };\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();\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();\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 = this.peek().type === \"RightDelim\" ? undefined : this.parsePipeline();\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.peek().type === \"RightDelim\" ? undefined : this.parsePipeline();\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 takes precedence —\n // the block body is the fallback, not the override.\n if (!this.defines.has(name)) {\n this.defines.set(name, list);\n }\n return pipe\n ? ({ type: \"Block\", pos: startPos, name, pipe, list, trim } satisfies BlockNode)\n : ({ type: \"Block\", pos: startPos, name, 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)) {\n throw new ParseError(`redefinition of template ${JSON.stringify(name)}`, list.pos, {\n source: this.source,\n });\n }\n this.defines.set(name, list);\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\n private parsePipeline(): PipeNode {\n const startPos = this.peek().pos;\n const decls = this.tryParseDecls();\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(): { vars: VariableNode[]; isAssign: boolean } | undefined {\n if (this.peek().type !== \"Variable\") 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 (this.peek(n + 1).type !== \"Variable\") 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 this.next();\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();\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\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 * 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 { 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 closes over the\n// engine's `toString` so that the value flattening uses the same\n// function the `\"stringifiable\"` matcher probes with. Two callsites\n// (probe at the gate, flatten in the body) — one source of truth.\n// ---------------------------------------------------------------------------\n\nfunction eagerBuiltins(toString: (v: unknown) => string): 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 argTypes: [\"comparable\"],\n },\n ne: {\n fn: (a: unknown, b: unknown) => !goEqPair(a, b),\n argTypes: [\"comparable\", \"comparable\"],\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: { fn: (a: unknown, b: unknown) => compare(a, b) < 0, argTypes: [\"ordered\", \"ordered\"] },\n le: { fn: (a: unknown, b: unknown) => compare(a, b) <= 0, argTypes: [\"ordered\", \"ordered\"] },\n gt: { fn: (a: unknown, b: unknown) => compare(a, b) > 0, argTypes: [\"ordered\", \"ordered\"] },\n ge: { fn: (a: unknown, b: unknown) => compare(a, b) >= 0, argTypes: [\"ordered\", \"ordered\"] },\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\"] },\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 },\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 // so the gate normalizes `number|bigint` to a finite-integer\n // `number` carrier before the body runs. Body trusts both kinds\n // and only routes the slice op — no defensive `Number(...)`.\n slice: {\n fn: (collection: unknown, ...indices: unknown[]) => {\n const i = indices.length >= 1 ? (indices[0] as number) : 0;\n const j = indices.length >= 2 ? (indices[1] as number) : undefined;\n return typeof collection === \"string\"\n ? collection.slice(i, j)\n : (collection as unknown[]).slice(i, j);\n },\n argTypes: [\"sliceable\", \"int\"],\n },\n\n // [LAW:single-enforcer] Formatted printers declare \"stringifiable\"\n // so the gate probes each non-string arg through `engine.toString`.\n // Bodies re-call `toString` to actually flatten — same source of\n // truth as the matcher. Closes audit findings B1–B4: typed-T no\n // longer silently `String(v)`-flattens to \"[object Object]\".\n print: {\n fn: (...args: unknown[]) => goPrint(args, toString),\n argTypes: [\"stringifiable\"],\n returnType: \"string\",\n },\n println: {\n fn: (...args: unknown[]) => `${goPrint(args, toString)}\\n`,\n argTypes: [\"stringifiable\"],\n returnType: \"string\",\n },\n printf: {\n fn: (format: string, ...args: unknown[]) => sprintf(format, args, toString),\n argTypes: [\"string\", \"stringifiable\"],\n returnType: \"string\",\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 },\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)),\n argTypes: [\"stringifiable\"],\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)),\n argTypes: [\"stringifiable\"],\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)),\n argTypes: [\"stringifiable\"],\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\"] },\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\"],\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\"],\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): FuncMap {\n return { ...eagerBuiltins(toString), ...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)) {\n const i = Number(key);\n if (!Number.isInteger(i))\n throw new Error(`index: array index must be integer, got ${describeType(key)}`);\n if (i < 0 || i >= collection.length) {\n throw new Error(`index: out of range [${i}] with length ${collection.length}`);\n }\n return collection[i];\n }\n if (collection instanceof Map) {\n return collection.get(key);\n }\n if (typeof collection === \"string\") {\n const i = Number(key);\n return collection[i];\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\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: (v: unknown) => string): 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 += stringifyForPrint(arg, toString);\n prevIsString = isString;\n }\n return out;\n}\n\n// [LAW:single-enforcer] No `String(value)` here — the gate guarantees\n// each arg is `\"stringifiable\"`. nil keeps Go-parity (\"<nil>\"); strings\n// pass through; anything else routes through the engine's `toString`.\nfunction stringifyForPrint(value: unknown, toString: (v: unknown) => string): string {\n if (value === null || value === undefined) return \"<nil>\";\n if (typeof value === \"string\") return value;\n return toString(value);\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): 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 arg = args[argIdx++];\n out += formatVerb(verb ?? \"\", spec, arg, toString);\n i = j + 1;\n }\n return out;\n}\n\nfunction formatVerb(\n verb: string,\n spec: string,\n arg: unknown,\n toString: (v: unknown) => string,\n): string {\n switch (verb) {\n case \"s\":\n return typeof arg === \"string\"\n ? applyWidth(spec, arg)\n : applyWidth(spec, stringifyForPrint(arg, toString));\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 `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;\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, formatV(arg));\n case \"q\":\n return applyWidth(spec, JSON.stringify(stringifyForPrint(arg, toString)));\n case \"f\": {\n // [LAW:single-enforcer] See %d.\n if (typeof arg !== \"number\" && typeof arg !== \"bigint\") {\n return `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;\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 return applyWidth(spec, isTruthy(arg) ? \"true\" : \"false\");\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 `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;\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 `%!${verb}(${goPrintfType(arg)}=${stringifyForPrint(arg, toString)})`;\n }\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// [LAW:one-source-of-truth] Exported so sprig's `toString`/`toStrings`\n// share this Go-`%v` formatter with printf's `%v` verb. Two places\n// computing \"%v shape\" would drift; exporting makes it impossible.\nexport function formatV(value: unknown): string {\n if (value === null || value === undefined) return \"<nil>\";\n if (typeof value === \"string\") return value;\n if (typeof value === \"bigint\") return value.toString();\n if (Array.isArray(value)) return `[${value.map(formatV).join(\" \")}]`;\n if (value instanceof Map) {\n return `map[${[...value.entries()].map(([k, v]) => `${formatV(k)}:${formatV(v)}`).join(\" \")}]`;\n }\n if (typeof value === \"object\") {\n return `{${Object.values(value).map(formatV).join(\" \")}}`;\n }\n return String(value);\n}\n","/**\n * Lexical scope chain for the evaluator.\n *\n * [LAW:dataflow-not-control-flow] A `Scope` is an immutable record of\n * `dot`, `root` (the original `$`), and a parent pointer. New frames\n * are *constructed*; we never mutate an existing frame to \"leave\" it.\n * That means iterations of `{{range}}` cannot see each other's `$var`\n * declarations — the data shape itself prevents the bug.\n *\n * Variables are stored on the leaf frame as a flat record. A lookup\n * walks the parent chain. Assignment via `=` searches the chain and\n * mutates the *binding's* frame; declaration via `:=` always creates\n * the binding in the current leaf frame.\n */\n\nexport interface Scope {\n /** Current dot value — what `.` resolves to. */\n readonly dot: unknown;\n /** Top-level scope value — what `$` resolves to. */\n readonly root: unknown;\n /** Parent scope, or undefined for the top-level. */\n readonly parent: Scope | undefined;\n /** Variables declared in *this* frame. */\n readonly vars: Map<string, unknown>;\n}\n\nexport function rootScope(value: unknown): Scope {\n return { dot: value, root: value, parent: undefined, vars: new Map() };\n}\n\nexport function pushScope(parent: Scope, dot: unknown): Scope {\n return { dot, root: parent.root, parent, vars: new Map() };\n}\n\n/**\n * Look up a `$var` binding, walking the parent chain.\n * Returns `{ found: true, value }` on hit and `{ found: false }` on miss\n * — explicit shape rather than `undefined` so callers can disambiguate\n * \"not declared\" from \"declared but undefined\".\n */\nexport function lookupVar(\n scope: Scope,\n name: string,\n): { found: true; value: unknown } | { found: false } {\n let cur: Scope | undefined = scope;\n while (cur !== undefined) {\n if (cur.vars.has(name)) return { found: true, value: cur.vars.get(name) };\n cur = cur.parent;\n }\n return { found: false };\n}\n\n/** Declare a new variable in the leaf scope (for `:=`). */\nexport function declareVar(scope: Scope, name: string, value: unknown): void {\n scope.vars.set(name, value);\n}\n\n/**\n * Reassign an existing variable (for `=`). Walks the chain to find the\n * declaring frame and mutates its binding map. Throws via the caller's\n * supplied `notFound` factory when the variable was never declared.\n */\nexport function assignVar(scope: Scope, name: string, value: unknown): boolean {\n let cur: Scope | undefined = scope;\n while (cur !== undefined) {\n if (cur.vars.has(name)) {\n cur.vars.set(name, value);\n return true;\n }\n cur = cur.parent;\n }\n return false;\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 EvalError,\n FailError,\n FuncNotFoundError,\n MissingFieldError,\n TypeMismatchError,\n} from \"../errors.js\";\nimport {\n type ActionNode,\n assertNever,\n type CommandNode,\n type ListNode,\n type Node,\n type PipeNode,\n} from \"../parser/ast.js\";\nimport type { Delims } from \"../parser/lexer.js\";\nimport { type ParseResult, parse as parseSource } from \"../parser/parser.js\";\nimport type { Pos } from \"../parser/pos.js\";\nimport { MISSING, walkFieldChain } from \"./access.js\";\nimport { defaultBuiltins } from \"./builtins.js\";\nimport { isLazy } from \"./lazy.js\";\nimport { declareVar, lookupVar, pushScope, rootScope, type Scope } from \"./scope.js\";\nimport { isTruthy } from \"./truthy.js\";\n\n// ---------------------------------------------------------------------------\n// Public API.\n// ---------------------------------------------------------------------------\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. Accepts any finite\n * `number` and any `bigint` whose `Number()` is safe-integer-\n * representable; rejects `NaN`, `±Infinity`, and precision-losing\n * bigints. The gate normalizes `values[i]` to `Math.trunc(Number(v))`\n * so bodies see `number`. Used by `add`, `sub`, `mul`, `mod`, `max`,\n * `min`, the built-in `slice`'s index slots, `chunk`, `splitn`,\n * `repeat`. Added by epic template-variance-num-carrier-hfv.\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\" — opaque caller-defined T; treated as \"anything that is\n * not a string\". The guard does no further checking.\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\" — string directly OR a value the engine's\n * `toString` can flatten. The matcher *probes* the conversion;\n * downstream func bodies call `engine.toString` to actually flatten.\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 =\n | \"string\"\n // [LAW:types-are-the-program] \"int\" and \"float\" are validate-AND-parse\n // numeric carriers. The matcher's membership predicate IS the body's\n // contract — neither slot accepts \"anything `typeof number|bigint`\":\n // - \"int\" admits only carriers that survive normalization as a\n // finite integer-valued `number`: finite numbers, and bigints\n // whose `Number()` conversion is safe-integer-representable.\n // NaN, Infinity, and precision-losing bigints are rejected at\n // the gate so the body's \"I receive an integer\" assumption is\n // a theorem, not a defense.\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\": `Math.trunc(Number(v))`; \"float\":\n // `Number(v)`). Mirrors the \"liftable\" precedent: the slot is both\n // the membership rule and the parse step. Added by epic\n // template-variance-num-carrier-hfv.1; tightened by .1.1; the legacy\n // permissive \"number\" slot was retired in .4 once all consumers\n // migrated (.2/.3) — every numeric slot now picks the integer-or-\n // float carrier explicitly.\n | \"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\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 readonly fn: (...args: never[]) => unknown;\n /**\n * Declared positional parameter types. Required.\n *\n * For variadic funcs, declare the type of the trailing parameter\n * once — the no-silent-flatten guard validates every excess argument\n * against `argTypes[argTypes.length - 1]`. This matches Go's\n * `text/template` validation against repeated parameter types when\n * `Variadic`.\n *\n * The pipe-fed last argument is appended to the positional list\n * before validation, so it is checked against the trailing slot.\n */\n readonly argTypes: readonly ArgType[];\n readonly returnType?: ArgType;\n /**\n * Variadic-position lookup pattern.\n *\n * Default (omitted): the trailing slot repeats. `[\"string\", \"value\"]`\n * means \"first arg string, every arg after is value (heterogeneous)\".\n *\n * `\"alternating\"`: `argTypes` describes a *cycle*. The slot for arg\n * index `i` is `argTypes[i % argTypes.length]`. Used by `dict`'s\n * `string, value, string, value, …` kv pairing — without this the\n * gate cannot distinguish even-index keys (must be string) from\n * odd-index values (anything), and the body would re-validate per\n * key, splitting `[LAW:single-enforcer]` across two layers.\n *\n * Added by template-laws-3gt.3.\n */\n readonly argTypePattern?: \"alternating\";\n}\n\nexport type FuncMap = Record<string, TemplateFunc>;\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\nexport interface EngineConfig<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 when\n * they need to format a non-string value (the matcher probes via\n * `toString` to validate; the body re-uses it to flatten).\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 * 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\n// Per-evaluate context. Threaded through every internal method.\ninterface EvalContext<T> {\n readonly out: T[];\n readonly defines: ReadonlyMap<string, ListNode>;\n readonly source: string | undefined;\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/**\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>(source: string, evaluate: (scope: unknown) => U[]) => Template<U>;\n\nexport class Template<T> {\n readonly source: string;\n private readonly _evaluate: (scope: unknown) => T[];\n\n private constructor(source: string, evaluate: (scope: unknown) => T[]) {\n this.source = source;\n this._evaluate = evaluate;\n }\n\n static {\n internalCreateTemplate = <U>(source: string, evaluate: (scope: unknown) => U[]) =>\n new Template(source, evaluate);\n }\n\n evaluate(scope: unknown): T[] {\n return this._evaluate(scope);\n }\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 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\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 // [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 this.funcs = { ...defaultBuiltins(this.toString), ...(config.funcs ?? {}) };\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): Template<T> {\n const parsed = parseSource(source, this.delims);\n return internalCreateTemplate(parsed.source, (scope) => this.evalParsed(parsed, scope));\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(parsed: ParseResult, scope: unknown): T[] {\n const out: T[] = [];\n const root = rootScope(scope);\n const ctx: EvalContext<T> = {\n out,\n defines: parsed.defines,\n source: parsed.source,\n };\n this.evalList(parsed.root, 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.out.push(this.fromString(node.text));\n return;\n case \"Comment\":\n return;\n case \"Action\": {\n const value = this.evalAction(node, scope, ctx);\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) this.emitFromValue(value, ctx);\n return;\n }\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 cond = this.evalPipe(node.pipe, scope, ctx);\n if (isTruthy(cond)) {\n this.evalList(node.list, scope, ctx);\n } else if (node.elseList) {\n this.evalList(node.elseList, scope, ctx);\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 value = this.evalPipe(node.pipe, scope, ctx);\n if (isTruthy(value)) {\n const child = pushScope(scope, value);\n this.evalList(node.list, child, ctx);\n } else if (node.elseList) {\n this.evalList(node.elseList, scope, ctx);\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 // For `range`, the pipeline's declarations bind to (key, value)\n // *per iteration*, not to the iterable as a whole. We evaluate the\n // pipe with its decls suppressed, then handle the bindings here.\n const value = this.evalPipeWithoutDecls(node.pipe, scope, ctx);\n const decls = node.pipe.decls;\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, scope, ctx);\n return;\n }\n for (const [key, item] of entries) {\n const child = pushScope(scope, item);\n if (decls.length === 1) {\n const name = decls[0]?.idents[0] ?? \"$\";\n declareVar(child, name, item);\n } else if (decls.length >= 2) {\n const k = decls[0]?.idents[0] ?? \"$\";\n const v = decls[1]?.idents[0] ?? \"$\";\n declareVar(child, k, key);\n declareVar(child, v, item);\n }\n try {\n this.evalList(node.list, child, ctx);\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 tpl = ctx.defines.get(node.name);\n if (!tpl) {\n throw new EvalError(`template ${JSON.stringify(node.name)} is not defined`, node.pos, {\n source: ctx.source,\n });\n }\n const arg = node.pipe ? this.evalPipe(node.pipe, scope, ctx) : scope.dot;\n const child = pushScope(scope, arg);\n this.evalList(tpl, child, ctx);\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 arg = node.pipe ? this.evalPipe(node.pipe, scope, ctx) : scope.dot;\n const child = pushScope(scope, arg);\n const tpl = ctx.defines.get(node.name) ?? node.list;\n this.evalList(tpl, child, ctx);\n }\n\n // -------------------------------------------------------------------\n // Expression-level dispatch (value-producing).\n // -------------------------------------------------------------------\n\n private evalAction(node: ActionNode, scope: Scope, ctx: EvalContext<T>): unknown {\n return this.evalPipe(node.pipe, scope, ctx);\n }\n\n private evalPipe(pipe: PipeNode, scope: Scope, ctx: EvalContext<T>): unknown {\n if (pipe.cmds.length === 0) {\n throw new EvalError(\"empty pipeline\", pipe.pos, { source: ctx.source });\n }\n let value: unknown = this.evalCommand(pipe.cmds[0] as CommandNode, scope, ctx, NO_PIPE);\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 });\n }\n\n // Apply variable declarations / assignments after the pipe is\n // fully evaluated. Multi-decl tuple semantics for `range` are\n // handled inside `evalRange` (which calls `evalPipeWithoutDecls`).\n if (pipe.decls.length > 0) {\n for (const decl of pipe.decls) {\n const name = decl.idents[0] ?? \"$\";\n declareVar(scope, name, value);\n }\n }\n return value;\n }\n\n private evalPipeWithoutDecls(pipe: PipeNode, scope: Scope, ctx: EvalContext<T>): unknown {\n // Synthesise a pipe with empty decls so the standard `evalPipe`\n // doesn't attempt the (single-binding) declaration. `evalRange`\n // handles its own multi-binding semantics.\n const stripped: PipeNode = {\n type: \"Pipe\",\n pos: pipe.pos,\n decls: [],\n isAssign: false,\n cmds: pipe.cmds,\n };\n return this.evalPipe(stripped, scope, ctx);\n }\n\n private evalCommand(cmd: CommandNode, scope: Scope, ctx: EvalContext<T>, piped: Piped): 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);\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) : this.evalPrimary(n, scope, ctx),\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 enforceArgTypes(\n head.ident,\n fn.argTypes,\n args,\n cmd.pos,\n ctx.source,\n this.toString,\n fn.argTypePattern,\n this.fromString as (s: string) => unknown,\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 try {\n return (fn.fn as (...a: unknown[]) => unknown)(...args);\n } catch (e) {\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(\n e.funcName,\n e.argIndex,\n e.expected,\n e.receivedSummary,\n cmd.pos,\n { source: ctx.source },\n );\n }\n if (e instanceof FailError) {\n throw new FailError(e.message, cmd.pos, { source: ctx.source });\n }\n throw e;\n }\n }\n\n private evalPrimary(node: Node, scope: Scope, ctx: EvalContext<T>): unknown {\n switch (node.type) {\n case \"Dot\":\n return scope.dot;\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(scope.dot, node.idents, node.pos, ctx);\n case \"Variable\":\n return this.resolveVariable(node.idents, scope, node.pos, ctx);\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 enforceArgTypes(\n node.ident,\n fn.argTypes,\n [],\n node.pos,\n ctx.source,\n this.toString,\n fn.argTypePattern,\n this.fromString as (s: string) => unknown,\n );\n return (fn.fn as () => unknown)();\n }\n case \"Chain\":\n return this.resolveFieldChain(\n this.evalPrimary(node.node, scope, ctx),\n node.fields,\n node.pos,\n ctx,\n );\n case \"Pipe\":\n return this.evalPipe(node, scope, ctx);\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 ): unknown {\n const head = idents[0] ?? \"$\";\n if (head === \"$\") {\n const tail = idents.slice(1);\n return tail.length === 0 ? scope.root : this.resolveFieldChain(scope.root, tail, pos, ctx);\n }\n const lookup = lookupVar(scope, head);\n if (!lookup.found) {\n throw new EvalError(`undefined variable ${head}`, pos, { source: ctx.source });\n }\n const tail = idents.slice(1);\n return tail.length === 0 ? lookup.value : this.resolveFieldChain(lookup.value, tail, pos, ctx);\n }\n\n // -------------------------------------------------------------------\n // Output stream.\n // -------------------------------------------------------------------\n\n private emitFromValue(value: unknown, ctx: EvalContext<T>): void {\n // [LAW:dataflow-not-control-flow] No skip-when-null branch. The\n // emit always runs; the value (including null/undefined) drives\n // what is pushed. Matches Go's text/template, which emits\n // `<no value>` for nil pipelines uniformly.\n if (value === null || value === undefined) {\n ctx.out.push(this.fromString(\"<no value>\"));\n return;\n }\n if (typeof value === \"string\") {\n ctx.out.push(this.fromString(value));\n return;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n ctx.out.push(this.fromString(String(value)));\n return;\n }\n // Arrays / Maps / plain objects: format Go-like (`[a b c]`, `map[k:v]`,\n // `{f1 f2}`) when the value lands in a string-output stream. This\n // matches Go's `fmt.Sprintf(\"%v\", v)` shape for the common cases\n // and keeps the conformance corpus byte-equal.\n if (Array.isArray(value)) {\n ctx.out.push(this.fromString(formatArrayLikeGo(value)));\n return;\n }\n if (value instanceof Map) {\n ctx.out.push(this.fromString(formatMapLikeGo(value)));\n return;\n }\n ctx.out.push(value as T);\n }\n}\n\nfunction formatArrayLikeGo(arr: readonly unknown[]): string {\n return `[${arr.map(formatScalarLikeGo).join(\" \")}]`;\n}\n\nfunction formatMapLikeGo(m: ReadonlyMap<unknown, unknown>): string {\n const parts: string[] = [];\n for (const [k, v] of m) {\n parts.push(`${formatScalarLikeGo(k)}:${formatScalarLikeGo(v)}`);\n }\n return `map[${parts.join(\" \")}]`;\n}\n\nfunction formatScalarLikeGo(v: unknown): string {\n if (v === null || v === undefined) return \"<nil>\";\n if (Array.isArray(v)) return formatArrayLikeGo(v);\n if (v instanceof Map) return formatMapLikeGo(v);\n return String(v);\n}\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, none\n// of which appear in any registration as of template-laws-3gt.1.\nexport function enforceArgTypes(\n funcName: string,\n argTypes: readonly ArgType[],\n values: unknown[],\n pos: Pos,\n src: string | undefined,\n toString: (value: unknown) => string = defaultToString,\n pattern?: \"alternating\",\n fromString: (s: string) => unknown = defaultFromString,\n): void {\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 by default, modulo cycle\n // when `pattern === \"alternating\"`) lives here once, not duplicated\n // at the loop body. See template-laws-3gt.3 for the alternation\n // motivation (`dict`'s string/value kv pairing).\n const lookup = makeSlotLookup(argTypes, pattern);\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 if (!matchesArgType(declared, value, toString)) {\n throw new TypeMismatchError(\n funcName,\n i + 1,\n humanArgType(declared),\n describeValue(value),\n 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 === \"int\") {\n values[i] = Math.trunc(Number(value));\n } else if (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 ${describeValue(values[firstOrdered])}`,\n describeValue(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 ${describeValue(values[firstComparable])}`,\n describeValue(value),\n pos,\n { source: src },\n );\n }\n }\n }\n}\n\n// [LAW:dataflow-not-control-flow] The variadic-overflow rule is encoded\n// as a function that maps an arg index to its declared kind, picked\n// once per call. The loop in `enforceArgTypes` then has the same shape\n// for every func — no per-iteration `if (pattern === \"alternating\")`.\nfunction makeSlotLookup(\n argTypes: readonly ArgType[],\n pattern: \"alternating\" | undefined,\n): (i: number) => ArgType {\n if (argTypes.length === 0) {\n // Funcs registered with `argTypes: []` are zero-arity at the gate.\n // The loop only runs when `values.length > argTypes.length`, which\n // is itself a registration bug — fall back to \"value\" so the loop\n // does not throw on a stale zero-arity registration.\n return () => \"value\";\n }\n if (pattern === \"alternating\") {\n const len = argTypes.length;\n return (i) => argTypes[i % len] as ArgType;\n }\n const trailing = argTypes[argTypes.length - 1] as ArgType;\n return (i) => (i < argTypes.length ? (argTypes[i] as ArgType) : trailing);\n}\n\nfunction matchesArgType(\n declared: ArgType,\n value: unknown,\n toString: (value: unknown) => string,\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 finite integer-valued carrier. The matcher\n // is what makes this a theorem the body can assume, not a comment\n // it has to defend with re-checks. NaN and Infinity have no\n // integer interpretation (`Math.trunc(NaN) === NaN`); bigints\n // outside `Number.MAX_SAFE_INTEGER` lose precision under\n // `Number()` and would silently propagate corrupted values.\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 return (\n value !== null &&\n value !== undefined &&\n typeof value !== \"string\" &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\" &&\n typeof value !== \"bigint\" &&\n typeof value !== \"symbol\"\n );\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 \"stringifiable\": {\n // Probe (do not transform). String passes through trivially —\n // avoids invoking the consumer's `toString` for the common case.\n // For non-strings, attempt the conversion: a successful return\n // means the value can flatten, a throw means it cannot. The\n // matcher reports the boolean; downstream func bodies (.6) call\n // `engine.toString` again to actually flatten.\n if (typeof value === \"string\") return true;\n try {\n toString(value);\n return true;\n } catch {\n return false;\n }\n }\n case \"liftable\":\n // Mirror of \"stringifiable\" in the opposite direction: a slot\n // that accepts T or a string the engine can lift to T via\n // `engine.fromString`. The matcher only validates membership;\n // the actual lift happens once in `enforceArgTypes` so func\n // bodies see T uniformly. Non-string non-T values fail the\n // gate — the same shape rules as \"T\".\n return (\n typeof value === \"string\" ||\n (value !== null &&\n value !== undefined &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\" &&\n typeof value !== \"bigint\" &&\n typeof value !== \"symbol\")\n );\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` covers the only escape from the type system —\n // callers that cast past `ArgType` at runtime (e.g. a stale\n // `argTypes: [\"number\" as ArgType]` registration) get a clear\n // \"invalid ArgType\" diagnostic instead of a silent `undefined`-\n // returning matcher that would surface later as a confusing\n // \"expected undefined\" TypeMismatchError.\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`. Strings\n// flow through unchanged (the `T = string` happy path). Primitives\n// (number/bigint/boolean) and nil get their natural string form so\n// vanilla string-engine consumers can `print 1`, `printf \"%s\" true`\n// etc. without configuring a flattener. Anything else — arrays,\n// objects, Maps, Sets, functions, symbols — is the actual \"typed-T\n// without consumer flattener\" case the README contract is about, and\n// throws a 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 describeValue(value),\n { line: 0, column: 0, offset: 0 },\n );\n}\n\nfunction 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, and other built-ins by\n // requiring a null prototype or the plain Object prototype.\n const proto = Object.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\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 (finite number or safe-integer bigint)\";\n case \"float\":\n return \"float (number, including NaN/Infinity, or finite-convertible bigint)\";\n case \"T\":\n return \"T (consumer-defined fragment)\";\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 or convertible via the engine's toString)\";\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\nfunction describeValue(value: unknown): string {\n if (value === null) return \"null\";\n if (value === undefined) return \"undefined\";\n if (Array.isArray(value)) return \"array\";\n if (value instanceof Map) return \"Map\";\n return typeof value;\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 is looser than this guard for\n// `number`-discriminant inputs (accepts any finite number, even\n// unsafe ones — callers passing a number are trusted to mean it).\n// This guard is stricter because atoi's input is a string, not a\n// trusted JS number, so the strictness applies at the parse step.\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 is looser for `number`-discriminant inputs at the gate —\n// it accepts any finite number, including unsafe ones like 2^60,\n// because callers passing a number are trusted to mean it. 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","import { formatV } from \"../../evaluator/builtins.js\";\n\n/**\n * `toString v` — Go sprig's `strval`. Strings pass through; everything\n * else routes through Go's `%v` formatter (`fmt.Sprintf(\"%v\", v)`).\n *\n * [LAW:one-source-of-truth] Shares `formatV` with printf's `%v` verb —\n * one place owns \"what does Go's %v look like\".\n */\nexport function toString(v: unknown): string {\n return typeof v === \"string\" ? v : formatV(v);\n}\n","import { toString } from \"./toString.js\";\n\n/**\n * `toStrings list` — map each element through `toString`.\n *\n * The `\"list\"` gate validates array-ness once; this body trusts it\n * and only routes the per-element conversion.\n */\n// [LAW:single-enforcer] List shape is the gate's job; per-element\n// conversion is `toString`'s job. This function only composes.\nexport function toStrings(list: unknown[]): string[] {\n return list.map(toString);\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// Renamed local bindings — `toString` as a property key in the\n// returned FuncMap collides with `Object.prototype.toString`'s implicit\n// type, which broke TS's contextual inference for the entry. Using\n// distinct local names (`sprigToString`) inside the factory keeps the\n// public func name `toString` while letting the property key stand on\n// its own.\nimport { toString as sprigToString } from \"./toString.js\";\nimport { toStrings as sprigToStrings } from \"./toStrings.js\";\n\nexport {\n atoi,\n float64,\n int,\n int64,\n sprigToString as toString,\n sprigToStrings as toStrings,\n toDecimal,\n toRawJson,\n};\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/toString: heterogeneous-by-\n // intent; the body is the per-kind dispatch\n // [LAW:dataflow-not-control-flow]\n // - \"list\" — toStrings: per-element conversion, list shape\n // enforced once at the gate\n // - \"serializable\" — toRawJson: gate rejects functions/symbols/\n // circular refs so the body never silently\n // emits \"null\"\n //\n // The local-binding indirection (`const map: FuncMap = ...`) forces\n // TS to apply the FuncMap contextual type to the literal. Without it,\n // a property key named `toString` shadows `Object.prototype.toString`\n // during TS's literal-type inference, which widens `argTypes` from\n // a tuple of ArgType to `string[]` and breaks the entry.\n const map: FuncMap = {\n atoi: { fn: (s) => atoi(s as string), argTypes: [\"string\"], returnType: \"int\" },\n int: { fn: (v) => int(v), argTypes: [\"value\"], returnType: \"int\" },\n int64: { fn: (v) => int64(v), argTypes: [\"value\"] },\n float64: { fn: (v) => float64(v), argTypes: [\"value\"], returnType: \"float\" },\n // The `toString` key matches `Object.prototype.toString`, which\n // shadows TS's contextual typing for this single entry. Pinning\n // the literal types with `as const` (or `satisfies TemplateFunc`)\n // is the standard escape — the entry's shape is identical to its\n // siblings; only TS inference needs the hint.\n toString: {\n fn: (v: unknown) => sprigToString(v),\n argTypes: [\"value\"] as const,\n returnType: \"string\" as const,\n },\n toStrings: {\n fn: (l) => sprigToStrings(l as unknown[]),\n argTypes: [\"list\"],\n },\n toDecimal: {\n fn: (s) => toDecimal(s as string),\n argTypes: [\"string\"],\n returnType: \"int\",\n },\n toRawJson: {\n fn: (v) => toRawJson(v),\n argTypes: [\"serializable\"],\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/** ±hhmm (no colon). E.g. \"+0500\", \"-0500\", \"+0000\". */\nfunction fmtOffset(offsetMinutes: number): string {\n const sign = offsetMinutes >= 0 ? \"+\" : \"-\";\n const abs = Math.abs(offsetMinutes);\n return `${sign}${pad2(Math.floor(abs / 60))}${pad2(abs % 60)}`;\n}\n\n/** ±hh:mm (with colon). E.g. \"+05:00\", \"-05:00\", \"+00:00\". */\nfunction fmtOffsetColon(offsetMinutes: number): string {\n const sign = offsetMinutes >= 0 ? \"+\" : \"-\";\n const abs = Math.abs(offsetMinutes);\n return `${sign}${pad2(Math.floor(abs / 60))}:${pad2(abs % 60)}`;\n}\n\n/** ±hh only. */\nfunction fmtOffsetHour(offsetMinutes: number): string {\n const sign = offsetMinutes >= 0 ? \"+\" : \"-\";\n return `${sign}${pad2(Math.floor(Math.abs(offsetMinutes) / 60))}`;\n}\n\n/** Z or ±hhmm. */\nfunction fmtOffsetZ(offsetMinutes: number): string {\n return offsetMinutes === 0 ? \"Z\" : fmtOffset(offsetMinutes);\n}\n\n/** Z or ±hh:mm. */\nfunction fmtOffsetColonZ(offsetMinutes: number): string {\n return offsetMinutes === 0 ? \"Z\" : fmtOffsetColon(offsetMinutes);\n}\n\n/** Z or ±hh. */\nfunction fmtOffsetHourZ(offsetMinutes: number): string {\n return offsetMinutes === 0 ? \"Z\" : fmtOffsetHour(offsetMinutes);\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.offsetMinutes)],\n [\"-07:00\", (z) => fmtOffsetColon(z.offsetMinutes)],\n // 5-char\n [\"Z0700\", (z) => fmtOffsetZ(z.offsetMinutes)],\n [\"-0700\", (z) => fmtOffset(z.offsetMinutes)],\n // 4-char\n [\"2006\", (z) => String(z.year)],\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.offsetMinutes)],\n [\"Z07\", (z) => fmtOffsetHourZ(z.offsetMinutes)],\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(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;\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 offsetMinutes: number; // UTC offset in minutes (e.g. -300 for EST)\n}\n\nconst INTL_OPTS: Intl.DateTimeFormatOptions = {\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};\n\n// Index parts array by type for O(1) access.\nfunction indexParts(parts: Intl.DateTimeFormatPart[]): Map<string, string> {\n const out = new Map<string, string>();\n for (const p of parts) out.set(p.type, p.value);\n return out;\n}\n\nconst WEEKDAY_NAMES = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\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, tzInput: string): ZoneParts {\n // Mirror Go sprig: unknown tz → fall back to UTC.\n let tz: string;\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: tzInput });\n tz = tzInput;\n } catch {\n tz = \"UTC\";\n }\n const fmt = new Intl.DateTimeFormat(\"en-US\", { ...INTL_OPTS, timeZone: tz });\n const p = indexParts(fmt.formatToParts(date));\n\n // hour12: false returns \"24\" for midnight in some runtimes — normalise.\n const hour = parseInt(p.get(\"hour\") ?? \"0\", 10) % 24;\n\n // Get timezone abbreviation via separate formatter (avoids mixing options).\n const abbrFmt = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tz,\n timeZoneName: \"short\",\n });\n const abbrParts = indexParts(abbrFmt.formatToParts(date));\n const tzAbbr = abbrParts.get(\"timeZoneName\") ?? tz;\n\n // UTC offset in minutes from \"GMT±h:mm\" or \"GMT\" produced by shortOffset.\n const offsetFmt = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tz,\n timeZoneName: \"shortOffset\",\n });\n const offsetParts = indexParts(offsetFmt.formatToParts(date));\n const offsetMinutes = parseGMTOffset(offsetParts.get(\"timeZoneName\") ?? \"GMT\");\n\n const weekday = WEEKDAY_NAMES.indexOf(p.get(\"weekday\") ?? \"Sunday\");\n\n return {\n year: parseInt(p.get(\"year\") ?? \"2000\", 10),\n month: parseInt(p.get(\"month\") ?? \"1\", 10),\n day: parseInt(p.get(\"day\") ?? \"1\", 10),\n weekday: weekday === -1 ? 0 : weekday,\n hour,\n hour12: hour % 12 || 12,\n minute: parseInt(p.get(\"minute\") ?? \"0\", 10),\n second: parseInt(p.get(\"second\") ?? \"0\", 10),\n ms: date.getUTCMilliseconds(),\n tzAbbr,\n offsetMinutes,\n };\n}\n\n/** Parse \"GMT\", \"GMT+5\", \"GMT+5:30\", \"GMT-4\" → offset in minutes. */\nfunction parseGMTOffset(s: string): number {\n if (s === \"GMT\" || s === \"UTC\") return 0;\n const m = s.match(/^GMT([+-])(\\d{1,2})(?::(\\d{2}))?$/);\n if (!m) return 0;\n const sign = m[1] === \"+\" ? 1 : -1;\n const h = parseInt(m[2] ?? \"0\", 10);\n const min = parseInt(m[3] ?? \"0\", 10);\n return sign * (h * 60 + min);\n}\n\n/** Host timezone name (IANA string). */\nexport function localTz(): string {\n return Intl.DateTimeFormat().resolvedOptions().timeZone;\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 { 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 const z = getZoneParts(resolveDate(t), localTz());\n return `${z.year}-${String(z.month).padStart(2, \"0\")}-${String(z.day).padStart(2, \"0\")}`;\n}\n","import { 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 const z = getZoneParts(resolveDate(t), zone);\n return `${z.year}-${String(z.month).padStart(2, \"0\")}-${String(z.day).padStart(2, \"0\")}`;\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 },\n date: {\n fn: (format, t) => date(format as string, t),\n argTypes: [\"string\", \"value\"],\n },\n dateInZone: {\n fn: (format, t, zone) => dateInZone(format as string, t, zone as string),\n argTypes: [\"string\", \"value\", \"string\"],\n },\n dateModify: {\n fn: (dur, t) => dateModify(dur as string, t),\n argTypes: [\"string\", \"value\"],\n },\n htmlDate: {\n fn: (t) => htmlDate(t),\n argTypes: [\"value\"],\n },\n htmlDateInZone: {\n fn: (t, zone) => htmlDateInZone(t, zone as string),\n argTypes: [\"value\", \"string\"],\n },\n duration: {\n fn: (sec) => duration(sec),\n argTypes: [\"value\"],\n },\n durationRound: {\n fn: (d) => durationRound(d),\n argTypes: [\"value\"],\n },\n toDate: {\n fn: (format, s) => toDate(format as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n ago: {\n fn: (t) => ago(t, clock),\n argTypes: [\"value\"],\n },\n unixEpoch: {\n fn: (t) => unixEpoch(t),\n argTypes: [\"value\"],\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 default: { fn: (a, b) => defaultFn(a, b), argTypes: [\"value\", \"truthy\"] },\n empty: { fn: (v) => empty(v), argTypes: [\"truthy\"] },\n coalesce: { fn: (...vs) => coalesce(...vs), argTypes: [\"truthy\"] },\n ternary: { fn: (a, b, c) => ternary(a, b, c), argTypes: [\"value\", \"value\", \"truthy\"] },\n fromJson: { fn: (s) => fromJson(s as string), argTypes: [\"string\"] },\n toJson: { fn: (v) => toJson(v), argTypes: [\"serializable\"], returnType: \"string\" },\n toPrettyJson: {\n fn: (v) => toPrettyJson(v),\n argTypes: [\"serializable\"],\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 `argTypePattern: \"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 */\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 * `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 } 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 { dict, get, hasKey, keys, merge, mergeOverwrite, omit, pick, pluck, set, unset, values };\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 argTypePattern: \"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 argTypePattern: \"alternating\",\n },\n get: {\n fn: (d, k) => get(d as Record<string, unknown>, k as string),\n argTypes: [\"dict\", \"string\"],\n },\n set: {\n fn: (d, k, v) => set(d as Record<string, unknown>, k as string, v),\n argTypes: [\"dict\", \"string\", \"value\"],\n },\n unset: {\n fn: (d, k) => unset(d as Record<string, unknown>, k as string),\n argTypes: [\"dict\", \"string\"],\n },\n keys: { fn: (d) => keys(d as Record<string, unknown>), argTypes: [\"dict\"] },\n values: { fn: (d) => values(d as Record<string, unknown>), argTypes: [\"dict\"] },\n pluck: {\n fn: (k, ...d) => pluck(k as string, ...(d as Record<string, unknown>[])),\n argTypes: [\"string\", \"dict\"],\n },\n pick: {\n fn: (d, ...k) => pick(d as Record<string, unknown>, ...(k as string[])),\n argTypes: [\"dict\", \"string\"],\n },\n omit: {\n fn: (d, ...k) => omit(d as Record<string, unknown>, ...(k as string[])),\n argTypes: [\"dict\", \"string\"],\n },\n hasKey: {\n fn: (d, k) => hasKey(d as Record<string, unknown>, k as string),\n argTypes: [\"dict\", \"string\"],\n },\n merge: {\n fn: (d, ...s) => merge(d as Record<string, unknown>, ...(s as Record<string, unknown>[])),\n argTypes: [\"dict\"],\n },\n mergeOverwrite: {\n fn: (d, ...s) =>\n mergeOverwrite(d as Record<string, unknown>, ...(s as Record<string, unknown>[])),\n argTypes: [\"dict\"],\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\"] },\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\"] },\n b64dec: { fn: (s) => b64dec(s as string), argTypes: [\"string\"] },\n b32enc: { fn: (s) => b32enc(s as string), argTypes: [\"string\"] },\n b32dec: { fn: (s) => b32dec(s as string), argTypes: [\"string\"] },\n sha1sum: { fn: (s) => sha1sum(s as string), argTypes: [\"string\"] },\n sha256sum: { fn: (s) => sha256sum(s as string), argTypes: [\"string\"] },\n sha512sum: { fn: (s) => sha512sum(s as string), argTypes: [\"string\"] },\n adler32sum: { fn: (s) => adler32sum(s as string), argTypes: [\"string\"] },\n uuidv4: { fn: () => uuidv4(), argTypes: [] },\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 truncates `size` to a finite\n// integer; 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 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 { 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\", describeKind(dict));\n }\n for (let i = 0; i < keys.length; i++) {\n if (typeof keys[i] !== \"string\") {\n throw bodyTypeMismatch(\"dig\", i, \"string\", describeKind(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\", describeKind(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\nfunction describeKind(v: unknown): string {\n if (v === null) return \"null\";\n if (Array.isArray(v)) return \"array\";\n if (v instanceof Map) return \"Map\";\n if (v instanceof Set) return \"Set\";\n return typeof v;\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 \"int\" gates validate array-ness\n// and integer-ness; missing trailing args remain undefined (the gate\n// loops only over 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: { fn: (...a) => list(...a), argTypes: [\"value\"] },\n first: { fn: (l) => first(l as unknown[]), argTypes: [\"list\"] },\n last: { fn: (l) => last(l as unknown[]), argTypes: [\"list\"] },\n rest: { fn: (l) => rest(l as unknown[]), argTypes: [\"list\"] },\n initial: { fn: (l) => initial(l as unknown[]), argTypes: [\"list\"] },\n len: { fn: (l) => len(l), argTypes: [\"sized\"] },\n reverse: { fn: (l) => reverse(l as unknown[]), argTypes: [\"list\"] },\n uniq: { fn: (l) => uniq(l as unknown[]), argTypes: [\"list\"] },\n without: {\n fn: (l, ...e) => without(l as unknown[], ...e),\n argTypes: [\"list\", \"value\"],\n },\n has: { fn: (i, l) => has(i, l as unknown[]), argTypes: [\"value\", \"list\"] },\n compact: { fn: (l) => compact(l as unknown[]), argTypes: [\"list\"] },\n slice: {\n fn: (l, i, j) => slice(l as unknown[], i as number | undefined, j as number | undefined),\n argTypes: [\"list\", \"int\", \"int\"],\n },\n concat: { fn: (...l) => concat(...(l as unknown[][])), argTypes: [\"list\"] },\n chunk: {\n fn: (s, l) => chunk(s as number, l as unknown[]),\n argTypes: [\"int\", \"list\"],\n },\n prepend: {\n fn: (l, i) => prepend(l as unknown[], i),\n argTypes: [\"list\", \"value\"],\n },\n append: {\n fn: (l, i) => append(l as unknown[], i),\n argTypes: [\"list\", \"value\"],\n },\n sortAlpha: {\n fn: (l) => sortAlpha(l as unknown[]),\n argTypes: [\"list\"],\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 },\n // [LAW:one-source-of-truth] `tuple` is Go sprig's alias for `list`.\n tuple: { fn: (...a) => list(...a), argTypes: [\"value\"] },\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 dig: { fn: (...a) => dig(...a), argTypes: [\"value\"] },\n all: { fn: (...a) => all(...a), argTypes: [\"truthy\"], returnType: \"bool\" },\n any: { fn: (...a) => any(...a), argTypes: [\"truthy\"], returnType: \"bool\" },\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, b: number): number {\n return a / b;\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, b: number): number {\n return a - b;\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 \"int\"/\"float\" slots\n // to plain `number` before dispatch — \"int\" arrives truncated toward zero\n // (Go int64 semantics); \"float\" arrives coerced (IEEE-754 semantics).\n // Bodies receive `number`, never `bigint`.\n return {\n add: { fn: (...a) => add(...(a as number[])), argTypes: [\"int\"] },\n sub: { fn: (a, b) => sub(a as number, b as number), argTypes: [\"int\", \"int\"] },\n mul: { fn: (...a) => mul(...(a as number[])), argTypes: [\"int\"] },\n div: { fn: (a, b) => div(a as number, b as number), argTypes: [\"int\", \"int\"] },\n mod: { fn: (a, b) => mod(a as number, b as number), argTypes: [\"int\", \"int\"] },\n min: { fn: (...a) => min(...(a as number[])), argTypes: [\"int\"] },\n max: { fn: (...a) => max(...(a as number[])), argTypes: [\"int\"] },\n floor: { fn: (a) => floor(a as number), argTypes: [\"float\"] },\n ceil: { fn: (a) => ceil(a as number), argTypes: [\"float\"] },\n round: { fn: (a, p) => round(a as number, p as number), argTypes: [\"float\", \"int\"] },\n addf: { fn: (...a) => addf(...(a as number[])), argTypes: [\"float\"] },\n subf: { fn: (a, b) => subf(a as number, b as number), argTypes: [\"float\", \"float\"] },\n mulf: { fn: (...a) => mulf(...(a as number[])), argTypes: [\"float\"] },\n divf: { fn: (a, b) => divf(a as number, b as number), argTypes: [\"float\", \"float\"] },\n add1: { fn: (n) => add1(n as number), argTypes: [\"int\"] },\n add1f: { fn: (n) => add1f(n as number), argTypes: [\"float\"] },\n maxf: { fn: (...a) => maxf(...(a as number[])), argTypes: [\"float\"] },\n minf: { fn: (...a) => minf(...(a as number[])), argTypes: [\"float\"] },\n // `biggest` is Go sprig's deprecated alias for `max`. Registered\n // directly against the same function so divergence is impossible.\n biggest: { fn: (...a) => max(...(a as number[])), argTypes: [\"int\"] },\n seq: {\n fn: (...a) => seq(...(a as number[])),\n argTypes: [\"int\"],\n returnType: \"string\",\n },\n until: { fn: (n) => until(n as number), argTypes: [\"int\"], returnType: \"list\" },\n untilStep: {\n fn: (a, b, c) => untilStep(a as number, b as number, c as number),\n argTypes: [\"int\", \"int\", \"int\"],\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","import { 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 runes = [...s];\n for (let i = runes.length - 1; i > 0; i--) {\n const j = Math.floor(clampRandom(random()) * (i + 1));\n const tmp = runes[i] as string;\n runes[i] = runes[j] as string;\n runes[j] = tmp;\n }\n return runes.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 },\n randAlpha: {\n fn: (n) => randAlpha(n as number, random),\n argTypes: [\"int\"],\n },\n randAlphaNum: {\n fn: (n) => randAlphaNum(n as number, random),\n argTypes: [\"int\"],\n },\n randNumeric: {\n fn: (n) => randNumeric(n as number, random),\n argTypes: [\"int\"],\n },\n randAscii: {\n fn: (n) => randAscii(n as number, random),\n argTypes: [\"int\"],\n },\n shuffle: {\n fn: (s) => shuffle(s as string, random),\n argTypes: [\"string\"],\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 },\n regexFind: {\n fn: (p, s) => regexFind(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n regexFindAll: {\n fn: (p, s, n) => regexFindAll(p as string, s as string, n as number),\n argTypes: [\"string\", \"string\", \"int\"],\n },\n regexReplaceAll: {\n fn: (p, s, r) => regexReplaceAll(p as string, s as string, r as string),\n argTypes: [\"string\", \"string\", \"string\"],\n },\n regexReplaceAllLiteral: {\n fn: (p, s, r) => regexReplaceAllLiteral(p as string, s as string, r as string),\n argTypes: [\"string\", \"string\", \"string\"],\n },\n regexSplit: {\n fn: (p, s, n) => regexSplit(p as string, s as string, n as number),\n argTypes: [\"string\", \"string\", \"int\"],\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\"] },\n semverCompare: {\n fn: (constraint, version) => semverCompare(constraint as string, version as string),\n argTypes: [\"string\", \"string\"],\n returnType: \"bool\",\n },\n };\n}\n","/**\n * `abbrev width s` — truncate `s` to `width` chars, replacing the tail\n * with `...` when truncation occurs. Width must be at least 4 to fit\n * the ellipsis; smaller widths return `s` unchanged (Go sprig\n * behavior).\n */\nexport function abbrev(width: number, s: string): string {\n if (s.length <= width) return s;\n if (width < 4) return s;\n return `${s.slice(0, width - 3)}...`;\n}\n","/**\n * `abbrevboth left right s` — abbreviate from both ends, leaving `...`\n * around the visible window. Mirrors Go sprig's abbrevboth semantics:\n * left/right specify offsets (0-indexed); the result has `...` around\n * a slice taken between them.\n */\nexport function abbrevboth(left: number, right: number, s: string): string {\n if (right < 7 || s.length < right) return s;\n if (left < 0 || left > s.length - right + 1) return s;\n return `...${s.slice(left, left + right - 6)}...`;\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`. JS strings\n * are UTF-16; iterating with `for…of` (or `Array.from(s)`) yields\n * code points the same way Go yields runes, so the rune-level logic\n * carries over. We intentionally do NOT attempt to mirror xstrings'\n * `isAlphabet` CJK-exclusion table — for ASCII/Latin templates, which\n * are what real users feed sprig, the simpler `isLetter` test\n * matches Go's output. The fixture suite pins the cases consumers\n * 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\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 = Array.from(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 = Array.from(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","/** `initials s` — first letter of each whitespace-separated word, uppercased. */\nexport function initials(s: string): string {\n return s\n .split(/\\s+/)\n .filter((w) => w.length > 0)\n .map((w) => (w[0] ?? \"\").toUpperCase())\n .join(\"\");\n}\n","import { 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 ${describe(v)}`,\n );\n }\n parts.push(String(v));\n }\n return parts.join(sep);\n}\n\nfunction describe(v: unknown): string {\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","/**\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","/** Replaces ALL occurrences of `old` with `nw` in `s` (Go's strings.Replace n=-1). */\nexport function replace(old: string, nw: string, s: string): string {\n return s.split(old).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","/**\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 = s.split(sep);\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","export function splitList(sep: string, s: string): string[] {\n return s.split(sep);\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\n// [LAW:single-enforcer] Slot kinds (`[\"string\", \"int\", \"string\"]`)\n// validate and normalize the inputs at the dispatch gate — `n` arrives\n// as an integer-valued `number`. Safe-integer bigints (|n| ≤ 2^53)\n// are accepted and normalized via `Math.trunc(Number(v))`; bigints\n// outside that range, NaN, and ±Infinity 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)\n// Empty `sep` splits after each rune; for ASCII inputs the JS code-\n// unit split matches.\nfunction goSplitN(s: string, sep: string, n: number): string[] {\n if (n === 0) return [];\n const all = sep === \"\" ? Array.from(s) : s.split(sep);\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","/**\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 > s.length`) clamps to `s.length`;\n * `start` clamps to `[0, end]`.\n */\nexport function substr(start: number, end: number, s: string): string {\n const j = end < 0 || end > s.length ? s.length : end;\n const i = Math.min(Math.max(0, start), j);\n return s.slice(i, j);\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","/** `trimAll cutset s` — strip leading + trailing chars in `cutset`. */\nexport function trimAll(cutset: string, s: string): string {\n if (cutset.length === 0) return s;\n const set = new Set([...cutset]);\n let start = 0;\n while (start < s.length && set.has(s[start] as string)) start += 1;\n let end = s.length;\n while (end > start && set.has(s[end - 1] as string)) end -= 1;\n return s.slice(start, end);\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","/**\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 */\nexport function trunc(n: number, s: string): string {\n if (n < 0) {\n const k = -n;\n return k >= s.length ? s : s.slice(s.length - k);\n }\n return n >= s.length ? s : s.slice(0, n);\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\": the gate accepts\n // finite `number` and safe-integer `bigint` (|n| ≤ 2^53), normalizes\n // both to a finite `number`, and rejects out-of-range bigints / NaN\n // / ±Infinity 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 },\n abbrevboth: {\n fn: (l, r, s) => abbrevboth(l as number, r as number, s as string),\n argTypes: [\"int\", \"int\", \"string\"],\n },\n camelcase: { fn: (s) => camelcase(s as string), argTypes: [\"string\"], returnType: \"string\" },\n cat: { fn: (...a) => cat(...(a as string[])), argTypes: [\"string\"] },\n contains: {\n fn: (sub, s) => contains(sub as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n hasPrefix: {\n fn: (p, s) => hasPrefix(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n hasSuffix: {\n fn: (sf, s) => hasSuffix(sf as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n indent: {\n fn: (n, s) => indent(n as number, s as string),\n argTypes: [\"int\", \"string\"],\n },\n initials: { fn: (s) => initials(s as string), argTypes: [\"string\"] },\n join: {\n fn: (sep, list) => join(sep as string, list as unknown[]),\n argTypes: [\"string\", \"list\"],\n },\n kebabcase: { fn: (s) => kebabcase(s as string), argTypes: [\"string\"], returnType: \"string\" },\n lower: { fn: (s) => lower(s as string), argTypes: [\"string\"] },\n nindent: {\n fn: (n, s) => nindent(n as number, s as string),\n argTypes: [\"int\", \"string\"],\n },\n nospace: { fn: (s) => nospace(s as string), argTypes: [\"string\"], returnType: \"string\" },\n plural: {\n fn: (one, many, n) => plural(one as string, many as string, n as number),\n argTypes: [\"string\", \"string\", \"int\"],\n returnType: \"string\",\n },\n quote: { fn: (...a) => quote(...(a as string[])), argTypes: [\"string\"] },\n regexQuoteMeta: {\n fn: (s) => regexQuoteMeta(s as string),\n argTypes: [\"string\"],\n returnType: \"string\",\n },\n repeat: {\n fn: (n, s) => repeat(n as number, s as string),\n argTypes: [\"int\", \"string\"],\n },\n replace: {\n fn: (o, n, s) => replace(o as string, n as string, s as string),\n argTypes: [\"string\", \"string\", \"string\"],\n },\n snakecase: { fn: (s) => snakecase(s as string), argTypes: [\"string\"], returnType: \"string\" },\n split: { fn: (sep, s) => split(sep as string, s as string), argTypes: [\"string\", \"string\"] },\n splitList: {\n fn: (sep, s) => splitList(sep as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n splitn: {\n fn: (sep, n, s) => splitn(sep as string, n as number, s as string),\n argTypes: [\"string\", \"int\", \"string\"],\n returnType: \"dict\",\n },\n squote: { fn: (...a) => squote(...(a as string[])), argTypes: [\"string\"] },\n substr: {\n fn: (i, j, s) => substr(i as number, j as number, s as string),\n argTypes: [\"int\", \"int\", \"string\"],\n },\n swapcase: { fn: (s) => swapcase(s as string), argTypes: [\"string\"], returnType: \"string\" },\n title: { fn: (s) => title(s as string), argTypes: [\"string\"] },\n trim: { fn: (s) => trim(s as string), argTypes: [\"string\"] },\n trimAll: {\n fn: (cs, s) => trimAll(cs as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n trimPrefix: {\n fn: (p, s) => trimPrefix(p as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n trimSuffix: {\n fn: (sf, s) => trimSuffix(sf as string, s as string),\n argTypes: [\"string\", \"string\"],\n },\n trunc: {\n fn: (n, s) => trunc(n as number, s as string),\n argTypes: [\"int\", \"string\"],\n },\n untitle: { fn: (s) => untitle(s as string), argTypes: [\"string\"] },\n upper: { fn: (s) => upper(s as string), argTypes: [\"string\"] },\n wrap: {\n fn: (w, s) => wrap(w as number, s as string),\n argTypes: [\"int\", \"string\"],\n },\n wrapWith: {\n fn: (w, sep, s) => wrapWith(w as number, sep as string, s as string),\n argTypes: [\"int\", \"string\", \"string\"],\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\"] },\n kindIs: { fn: (k, v) => kindIs(k as string, v), argTypes: [\"string\", \"reflective\"] },\n typeOf: { fn: (v) => typeOf(v), argTypes: [\"reflective\"] },\n typeIs: { fn: (t, v) => typeIs(t as string, v), argTypes: [\"string\", \"reflective\"] },\n typeIsLike: { fn: (t, v) => typeIsLike(t as string, v), argTypes: [\"string\", \"reflective\"] },\n deepEqual: { fn: (a, b) => deepEqual(a, b), argTypes: [\"value\", \"value\"] },\n deepCopy: { fn: (v) => deepCopy(v), argTypes: [\"value\"] },\n };\n}\n"],"mappings":";;;;AAsCA,IAAa,gBAAb,cAAmC,MAAM;CACvC,OAAiC;CACjC,OAA2B;CAC3B;CACA;CAEA,YAAY,SAAiB,KAAU,MAA4B,EAAE,EAAE;AACrE,QAAM,QAAQ;AACd,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,MAA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