TypeScript API reference
Prompt
Section titled “Prompt”Prompt
Section titled “Prompt”class PromptAn immutable, fully-validated prompt. Wraps a NapiPrompt handle; all construction invariants (shape-valid, template-parseable, agreement-sound, reserved-name clean) are enforced by the Rust consumer at construction time There are no setters; the sole mutator is Prompt.derive. ## Construction — four entry points, all throwing on invalid input ts const p = new Prompt(shape, validators?); const p = Prompt.fromYaml(text, validators?); const p = Prompt.fromJson(text, validators?); const p = Prompt.fromToml(text, validators?); // TOML routed to Rust, no smol-toml dep ## validators? — validation_required coverage check When supplied, any variable with validation_required: true must appear in validators.shape. Construction throws a PromptValidationError if a required variable is uncovered. When validators.shape is absent (non-ZodObject schema), the check is skipped. ## render — validate-then-render ts p.render(schema, data, opts?); // schema form: safeParse before templating p.render(data, opts?); // static form (or uses bound validators when present) ## derive(overlay, validators?) — sole mutator Shallow-replaces top-level fields; re-validates the merged whole. Validators carry forward from the source by default; pass validators to override.
get body(): stringThe root body template source (the default arm’s unrendered template text).
metadata
Section titled “metadata”get metadata(): Record<string, unknown>The metadata opaque map (library-defined top-level annotations, if any).
get name(): stringThe prompt’s name (the name field of the underlying definition).
outputModel
Section titled “outputModel”get outputModel(): string | undefinedThe output_model reference, if declared. Carried as metadata only — the library never parses against it.
get role(): stringThe conversational role ("system" / "user" / "assistant").
variables
Section titled “variables”get variables(): object | undefinedThe declared variables map ({ [name]: PromptVariable }). Read-only metadata. Each entry carries the variable’s type, trusted flag, and optional validation_required.
variants
Section titled “variants”get variants(): object | undefinedThe named variants map ({ [name]: PromptVariant }). Empty object when the prompt has no named variants (only the implicit default arm).
constructor
Section titled “constructor”new Prompt(shape: PromptDefinition, validators?: ValidatorMap): PromptPrimary public constructor — constructs a Prompt from a PromptDefinition-shaped object. The optional third parameter _internal is a module-private token (type InternalCtorArg) that can only be formed by code within this module. External callers cannot construct a valid InternalCtorArg value (its type uses a unique symbol brand), so new Prompt(shape, v?) is effectively the only publicly-callable form. The static factories (fromYaml, fromJson, fromToml) and with use the internal path to avoid re-running the Rust validator on an already-validated handle.
check(): CheckReportPure advisory lint: returns a CheckReport containing only the trusted/guard finding class ("untrusted_without_guard"). Construction already enforces agreement, parse, and reserved-name invariants; those are structurally unreachable here. Pure: never renders, never mutates.
derive
Section titled “derive”derive(overlay: Partial<PromptDefinition>, validators?: ValidatorMap): PromptThe sole mutator: shallow-replace top-level fields from overlay onto a clone of this prompt’s definition, then re-validate the merged whole via the Rust consumer. The original Prompt is untouched (immutability guaranteed). Validators carry forward from the source by default; pass validators to override/augment. Coverage is re-checked against the merged definition.
fromJson
Section titled “fromJson”static fromJson(text: string, validators?: ValidatorMap): PromptConstruct a Prompt from already-read JSON text.
fromToml
Section titled “fromToml”static fromToml(text: string, validators?: ValidatorMap): PromptConstruct a Prompt from already-read TOML text. TOML parsing is done by the Rust consumer (toml@1.1.2 via Prompt::from_toml). Raw text is routed to the addon — no smol-toml or other JS TOML library needed.
fromYaml
Section titled “fromYaml”static fromYaml(text: string, validators?: ValidatorMap): PromptConstruct a Prompt from already-read YAML text. The text is routed to the Rust consumer’s Prompt::from_yaml — no JS YAML parsing. Error semantics mirror new Prompt.
getSource
Section titled “getSource”getSource(opts?: { variant: string } | null): stringReturn a variant’s unrendered template source (the exact string the kernel hashes into templateHash). Pure: no vars, no validation. opts.variant selects an arm (absent ⇒ the reserved default).
render
Section titled “render”render(data: unknown, opts?: RenderOptions | null): RenderResultRender this prompt’s resolved variant with typed inputs, validating first. Three call forms, selected at runtime: - Schema form: render(schema, data, opts?) — schema.safeParse(data) runs here, before any templating; on failure a PromptValidationError is thrown and the kernel is never reached. - Static form: render(data, opts?) — already-typed plain data, marshaled directly (no Zod check at render time). - Bound-validator form: render(data, opts?) when the prompt was constructed with validators — the bound schema’s safeParse(data) runs automatically. opts carries { variant?, guard? } as named fields.
RenderResult
Section titled “RenderResult”RenderResult
Section titled “RenderResult”class RenderResultA rendered prompt + its content-addressed provenance, read-only from JS. The Node mirror of the kernel’s RenderResult. Surfaced 1:1 — the binding adds nothing and interprets nothing. Read-only class with camelCase JS accessors (template_hash → templateHash). A result is produced by renderPrompt, never constructed from JS.
get guard(): string | nullThe opt-in guard instruction text (present iff a guard was enabled and the prompt declares a trusted: false field); null for a plain render. Never part of text.
get name(): stringThe prompt name.
renderHash
Section titled “renderHash”get renderHash(): stringLowercase-hex SHA256(rendered text). Surfaces as renderHash.
templateHash
Section titled “templateHash”get templateHash(): stringLowercase-hex SHA256(resolved variant source). Surfaces as templateHash.
get text(): stringThe rendered body text. The guard text is NEVER concatenated here.
variant
Section titled “variant”get variant(): stringThe resolved variant name (the reserved default, or the named arm).
GuardConfig
Section titled “GuardConfig”GuardConfig
Section titled “GuardConfig”interface GuardConfigThe opt-in guard-expansion config, accepted from JS as a plain object and plumbed through to the kernel. A 1:1 mirror of the kernel’s GuardConfig. This is config only; it carries no logic. The kernel owns guard expansion; the binding only marshals fields across the boundary and surfaces whatever [RenderResult::guard] the kernel populates. Accepted from JS as a plain TS object { enabled, advisory? }. ## Advisory override When advisory is supplied it replaces the fixed default wording returned in RenderResult.guard. The override MUST reference the <untrusted> opening tag, the </untrusted> closing tag, AND an escape indication (&/</> or the word “escap”) — otherwise the kernel rejects it and a [PromptRenderError] is thrown with errors[0].code === "render" and errors[0].field === "guard".
advisory
Section titled “advisory”advisory?: stringOptional override for the advisory sentence returned in RenderResult.guard. null / absent ⇒ the fixed default advisory. When provided, must reference <untrusted>, </untrusted>, and an escape indication; otherwise the kernel rejects it with a structured PromptRenderError.
enabled
Section titled “enabled”enabled: booleanWhen false, the render is plain and [RenderResult::guard] is None.
RenderOptions
Section titled “RenderOptions”interface RenderOptionsOptions for Prompt.render.
guard?: GuardConfig | nullOpt-in guard config; absent / { enabled: false } ⇒ a plain render (RenderResult.guard === null).
unsafeRevealRenderDetail
Section titled “unsafeRevealRenderDetail”unsafeRevealRenderDetail?: booleanOff by default. When true, the full underlying render-error detail is surfaced in the thrown PromptRenderError“.errors[0].messageinstead of the fixed scrubbed string. **Risk:** enabling this may place **bound-value content** — untrusted input, PII, secrets — into the thrown error and into any log line or stack trace derived from it. Use only in a controlled debug context with a trusted log destination, and only after deliberately accepting that exposure. Never settrue` by default or via ambient configuration.
variant
Section titled “variant”variant?: stringSelect a named variant arm; absent ⇒ the reserved default arm.
CheckReport
Section titled “CheckReport”CheckReport
Section titled “CheckReport”class CheckReportThe output of a lint check: an ordered, read-only list of [Finding]s. Empty ⇒ the lint passed. The Node mirror of the consumer’s CheckReport. Surfaced 1:1 — the binding adds nothing and interprets nothing. Read-only class with read-only accessors; a report is produced by prompt.check, never constructed from JS.
findings
Section titled “findings”get findings(): Finding[]Every lint failure found, in the consumer’s deterministic order. Empty ⇒ pass.
isEmpty
Section titled “isEmpty”isEmpty(): booleanreport.isEmpty — alias for passed: true iff there are no findings.
passed
Section titled “passed”passed(): booleanreport.passed — true iff there are no findings (the lint passed). Reads clearly at a CI gate (if (!prompt.check.passed) process.exit(1)).
Finding
Section titled “Finding”Finding
Section titled “Finding”interface FindingOne actionable lint finding, read-only from JS. Names the prompt, the variant where applicable (null for a prompt-level finding), the failure kind (a stable snake_case discriminant string — see the module docs), and a human-readable detail. The detail carries no bound-value content (it is built by the consumer from prompt/field names only). Surfaced as a plain JS object with all four fields (the natural shape for the findings array the TS facade iterates / matches on).
detail
Section titled “detail”detail: stringA human-readable, actionable description. Carries no bound-value content.
kind: stringThe failure kind as a stable snake_case discriminant string — the value JS matches on. Currently always "untrusted_without_guard". The kind’s inner datum is echoed in detail.
prompt
Section titled “prompt”prompt: stringThe prompt’s name.
variant
Section titled “variant”variant?: stringThe variant the finding pertains to; None (undefined in JS) for a prompt-level provenance finding.
Composition
Section titled “Composition”Composition
Section titled “Composition”class CompositionAn explicit, ordered composition of (Prompt, vars, variant?) entries that resolves to an ordered Message[]. Built with new Composition + append or Composition.fromMessages([...]). No fluent .chain. No Registry: each entry holds an owned Prompt object. resolve takes no arguments — it renders using each entry’s stored Prompt handle directly. No-partial guarantee: if any entry fails validation at append/fromMessages, the whole call throws and nothing is stored. If an entry fails at resolve (unknown variant, undefined variable, parse/render), resolve throws and the partial result is discarded.
length
Section titled “length”get length(): numberThe number of appended entries (== the resolved-message count on success).
append
Section titled “append”append(entry: CompositionEntry): voidMarshal + store one CompositionEntry. When entry.schema is present, validation runs here (schema.safeParse(entry.data)); on failure a PromptValidationError is thrown and nothing is stored. Returns void (not this): intentionally not fluent.
fromMessages
Section titled “fromMessages”static fromMessages(entries: readonly CompositionEntry[]): CompositionBuild a composition from an ordered array of CompositionEntry objects, validating each in order. The first entry whose schema.safeParse(data) fails throws a PromptValidationError and no Composition is returned (no partial state —).
resolve
Section titled “resolve”resolve(): Message[]Resolve the composition to an ordered Message[], rendering each entry in append order through the kernel (via NapiPrompt.renderPrompt on each stored handle). No Registry — each entry holds its own NapiPrompt handle. One entry’s failure (unknown variant, undefined variable, parse/render error) throws the mapped PromptingPressError subclass and the partial result is discarded — never returned as success. An empty composition resolves to [].
CompositionEntry
Section titled “CompositionEntry”interface CompositionEntryOne composition entry, as a named-field options object. - prompt — the Prompt object to render. - schema — optional Zod-like schema. Present ⇒ schema.safeParse(data) runs at append. - data — the vars value (validated against schema when present). - variant — the selected variant arm (absent ⇒ the reserved default).
data: unknownThe vars value passed to the prompt renderer (validated against schema when present).
prompt
Section titled “prompt”prompt: PromptThe Prompt object to render.
schema
Section titled “schema”schema?: ZodLikeSchema<unknown>Optional Zod-like schema. When present, schema.safeParse(data) runs at append time.
variant
Section titled “variant”variant?: stringThe selected variant arm. Absent means the reserved default variant.
Message
Section titled “Message”Message
Section titled “Message”interface MessageOne resolved message in a composition’s output: a role-tagged rendered string. role is the prompt definition’s role stringified ("system" / "user" / "assistant"); text is that prompt rendered with the entry’s own validated value. Surfaced as a plain JS object { role, text }; a message is produced by [Composition::resolve], never constructed from JS.
role: stringThe conversational role, taken from the prompt definition’s role.
text: stringThe rendered body text for this entry. The guard text is never concatenated here.
Errors
Section titled “Errors”LoadError
Section titled “LoadError”class LoadErrorRaised when a document fails to load: malformed YAML/JSON/TOML, or a prompt-definition shape violation. Nothing is partially loaded. Top-level code "load".
PromptingPressError
Section titled “PromptingPressError”class PromptingPressErrorThe base class for every failure the library raises. Carries the normalized, already-scrubbed errors rows. Every thrown error is an instanceof PromptingPressError; callers branch on the concrete subclass (or on err.errors[*].code) and never see a ZodError or a native napi error.
errors
Section titled “errors”readonly errors: readonly FieldError[]The structured failure rows (the cross-language contract).
PromptRenderError
Section titled “PromptRenderError”class PromptRenderErrorRaised when the kernel rejects a render: an unknown variant, a referenced-but-undefined root variable (the loud three-sets gap — never a silent empty render), a parse/render failure, or an excluded template feature. Maps the kernel codes unknown_variant / undefined_variable / parse / render / excluded_feature. parse/render/excluded_feature detail is scrubbed.
PromptValidationError
Section titled “PromptValidationError”class PromptValidationErrorRaised when typed input fails validation — either the facade’s Zod safeParse (before any templating) or a garde-class validation surfaced by the consumer. Top-level code "validation". It is not a ZodError: the facade copies only the value-free issue message + path.
FieldError
Section titled “FieldError”interface FieldErrorOne normalized failure row. The TS mirror of the Rust consumer’s FieldError and the cross-language error contract. Reconstructed by the facade from the addon’s JSON payload (or, for a Zod validation failure, built locally from issue.message + issue.path).
readonly code: stringA stable code from the consumer’s closed vocabulary (e.g. "validation", "render").
readonly field: stringThe offending field or dotted path; "" when no single field applies.
message
Section titled “message”readonly message: stringA human-readable message safe to log (never the rejected value).
ZodLikeSchema
Section titled “ZodLikeSchema”interface ZodLikeSchemaThe minimal structural contract this facade needs from a Zod schema: a safeParse returning a tagged result. Typing it structurally (rather than importing Zod’s concrete ZodType) keeps the facade decoupled from a specific Zod minor and lets a caller pass any object exposing the same shape — the library never depends on Zod’s identity, only on safeParse. The optional shape field supports the validation_required coverage check at construction: if present (it is on a ZodObject), field in schema.shape proves that a validation_required variable is covered. If absent, the coverage check is skipped with a documented “cannot assert coverage” limitation.
shape?: Record<string, unknown>Optional: ZodObject.shape — a record of field name → ZodType. Present on a ZodObject; absent on other schema types. When absent, validation_required coverage cannot be introspected and the check is skipped (documented limitation).
safeParse
Section titled “safeParse”safeParse(data: unknown): ZodSafeParseResult<T>Validate data and return a tagged success/failure result without throwing.
coreVersion
Section titled “coreVersion”coreVersion(): stringReturns the version string of the underlying rendering kernel. Surfaces as coreVersion in JS (napi renames snake_case → camelCase).
ValidatorMap
Section titled “ValidatorMap”type ValidatorMap = ZodLikeSchemaA validator bound at Prompt construction. In practice this is a Zod schema (a ZodObject) whose shape property the construction-time validation_required coverage check introspects. Typed as ZodLikeSchema so callers aren’t forced to import Zod types.
Shape types
Section titled “Shape types”-
PromptDefinition— see the Prompt definition shape. -
PromptVariable— see the Prompt definition shape. -
PromptVariant— see the Prompt definition shape.
docs current as of 0.2.0