diff --git a/.changeset/jsdoc-1-0.md b/.changeset/jsdoc-1-0.md new file mode 100644 index 0000000..1eae54b --- /dev/null +++ b/.changeset/jsdoc-1-0.md @@ -0,0 +1,5 @@ +--- +"hyperfly": patch +--- + +Every public export now has JSDoc, including defaults, error codes and spec references. The README links the stability and security policies. diff --git a/STABILITY.md b/STABILITY.md index 5ba1e01..174c65a 100644 --- a/STABILITY.md +++ b/STABILITY.md @@ -24,7 +24,7 @@ add API and options. Patch releases fix bugs. Error codes are part of each package's public API. These include `limit`, `depth`, `ir` and `fingerprint`; TypeScript and Python also expose `options`, -`validation` and `json`. Message text is not part of the contract. +`validation` and `json`, and TypeScript exposes `artifact` for artifact loading. Message text is not part of the contract. Match on the code rather than the message. HTTP request failures are also part of the contract: the status codes diff --git a/apps/web/app/docs/page.tsx b/apps/web/app/docs/page.tsx index 71d459f..b61470f 100644 --- a/apps/web/app/docs/page.tsx +++ b/apps/web/app/docs/page.tsx @@ -303,6 +303,8 @@ async function getEvents(url: string) {
  • plan-columnar-v5: column layouts and profiles.
  • negotiation-v1: HTTP headers, discovery, and rotation.
  • Golden vectors: shared conformance fixtures.
  • +
  • Stability and versioning: what 1.x keeps stable, and the spec's stability contract.
  • +
  • Security policy: how to report a vulnerability.
  • diff --git a/packages/hyperfly/README.md b/packages/hyperfly/README.md index 7ae0492..bf305af 100644 --- a/packages/hyperfly/README.md +++ b/packages/hyperfly/README.md @@ -506,6 +506,16 @@ A future implementation ports against the [golden vectors](https://github.com/eliahilse/hyperfly/tree/main/spec/vectors), not against this code. +## Stability + +From 1.0.0 this package follows semver. The wire format, IR, fingerprints, error +codes, limits and negotiation are frozen for 1.x +([wire v0, Stability](https://github.com/eliahilse/hyperfly/blob/main/spec/wire-v0.md#stability)). +[STABILITY.md](https://github.com/eliahilse/hyperfly/blob/main/STABILITY.md) covers +what counts as breaking, and +[SECURITY.md](https://github.com/eliahilse/hyperfly/blob/main/SECURITY.md) covers +vulnerability reporting. + ## License [Apache License 2.0](./LICENSE) diff --git a/packages/hyperfly/src/canonical.ts b/packages/hyperfly/src/canonical.ts index 788b859..7cd7b9e 100644 --- a/packages/hyperfly/src/canonical.ts +++ b/packages/hyperfly/src/canonical.ts @@ -59,6 +59,7 @@ export function serializeNode(node: IRNode): string { } } +/** Artifact body layout: row v1 or columnar v5 (wire-v0 §5, plan-columnar-v5 §1). */ export type PlanLayout = "row" | "columnar"; const PLAN_VERSION: Record = { row: 1, columnar: 5 }; @@ -93,6 +94,7 @@ export function canonicalArtifact( return profile ? `${head},"profile":${serializeShared(profile.shared)}}` : `${head}}`; } +/** Validates and serializes canonical artifact text; layout defaults to `row`, with no profile (wire-v0 §5). */ export function serializeArtifact( ir: IRNode, layout: PlanLayout = "row", diff --git a/packages/hyperfly/src/codec.ts b/packages/hyperfly/src/codec.ts index 29b3e94..652aea9 100644 --- a/packages/hyperfly/src/codec.ts +++ b/packages/hyperfly/src/codec.ts @@ -8,27 +8,44 @@ import { validateIR, withinStack, type IRNode } from "./ir.js"; import { DEFAULT_LIMITS, Reader, type Limits } from "./reader.js"; import { Writer } from "./writer.js"; +/** Envelope magic bytes `0x68 0x66` (wire-v0 §2). */ export const MAGIC = new Uint8Array([0x68, 0x66]); +/** Wire major stored in the envelope and canonical artifact: 1 (wire-v0 §2, wire-v0 §5). */ export const WIRE_VERSION = 1; +/** Envelope header length in bytes, including the 16-byte fingerprint (wire-v0 §2). */ export const HEADER_SIZE = 19; +/** Synchronous raw DEFLATE capabilities for packed string columns (plan-columnar-v5 §3). */ export interface PackHooks { + /** Compresses one raw DEFLATE stream; omission disables packed-column encoding. */ deflate?: (data: Uint8Array) => Uint8Array; + /** Inflates exactly one stream, rejecting trailing bytes and output above maxOutputLength; omission refuses packed columns. */ inflate?: (data: Uint8Array, maxOutputLength: number) => Uint8Array; } +/** Local codec policy and artifact layout selected at compile time. */ export interface CompileOptions { + /** Resource caps; omitted entries use DEFAULT_LIMITS. Values must be non-negative safe integers (wire-v0 §6). */ limits?: Partial; + /** Body layout included in the fingerprint. Default: `row`. */ plan?: PlanLayout; + /** Raw DEFLATE capabilities. Default: defaultPackHooks(); false disables both compression and inflation. */ pack?: PackHooks | false; + /** Shared string-column model, valid only with the columnar plan. Default: none. */ profile?: Profile; } +/** Frozen codec whose schema, layout and shared profile determine its fingerprint (wire-v0 §5). */ export interface Codec { + /** Validated, cloned and deeply frozen schema. */ readonly ir: IRNode; + /** Canonical artifact text identifying the wire major, plan, schema and shared profile (wire-v0 §5). */ readonly artifact: string; + /** First 16 SHA-256 bytes of the artifact as 32 lowercase hex characters (wire-v0 §5). */ readonly fingerprint: string; + /** Body layout fixed in the artifact. */ readonly plan: PlanLayout; + /** Validated, cloned and deeply frozen training profile, when supplied. */ readonly profile?: Profile; /** * Encode a value into an envelope. A struct value must be an object whose `Object.prototype.toString` tag is @@ -36,8 +53,11 @@ export interface Codec { * boxed primitives fail with `type`. */ encode(value: T): Uint8Array; + /** Checks the envelope header and fingerprint, then decodes the complete body (wire-v0 §2). */ decode(bytes: Uint8Array): T; + /** Encodes a body without the envelope header, enforcing the same value checks and limits. */ encodeBody(value: T): Uint8Array; + /** Decodes a complete body without a header or fingerprint check; rejects trailing bytes. */ decodeBody(bytes: Uint8Array): T; } @@ -158,6 +178,10 @@ function compileArtifact( return { ir, profile: frozen, artifact: canonicalArtifact(ir, plan, frozen) }; } +/** + * Validates and snapshots an IR and optional profile into a frozen codec (wire-v0 §4, wire-v0 §5). + * Invalid options fail with `options`; invalid IR or profiles fail with `ir`. + */ export function compileIR(input: IRNode, options: CompileOptions = {}): Codec { const { limits, plan, pack: packOptions, profile } = checkedOptions(options); const { ir, profile: frozenProfile, artifact } = withinStack(() => compileArtifact(input, plan, profile)); diff --git a/packages/hyperfly/src/errors.ts b/packages/hyperfly/src/errors.ts index 961eed4..93142bf 100644 --- a/packages/hyperfly/src/errors.ts +++ b/packages/hyperfly/src/errors.ts @@ -1,4 +1,27 @@ -/** Stable failure codes. `artifact` means an unreadable discovery response or artifact JSON text; invalid parsed content is `ir`. */ +/** + * Stable failure categories; messages are descriptive, not contractual (wire-v0 §9). + * `varint`: non-minimal ULEB128 or more than eight bytes on decode. + * `range`: declared bounds or a numeric value, index, code or derived source is out of range. + * `type`: an encoded value mismatches its type, literal, enum, fixed length or nullability. + * `required`: an encoded struct omits a required field. + * `utf8`: a string contains a lone surrogate on encode or invalid UTF-8 on decode. + * `float`: a float is non-finite, or decode encounters negative zero or non-minimal XOR encoding. + * `marker`: a boolean, nullable marker, column mode or mode parameter is invalid. + * `bitmap`: bitmap or packed padding, null bits, escape bits or patched-frame exceptions are invalid. + * `trailing`: bytes remain after a complete body. + * `truncated`: input ends before a value is complete. + * `depth`: traversal exceeds maxDepth. + * `limit`: an item, byte, amplification or remaining-input bound is exceeded. + * `header`: an envelope is short or has invalid magic or wire major. + * `fingerprint`: an envelope or artifact fingerprint mismatches, or an artifact fingerprint is malformed. + * `ir`: IR or a profile is invalid, or an artifact names an unimplemented wire, layout or plan version. + * `packed`: DEFLATE is invalid, has trailing bytes or produces the wrong inflated length, or a deflate hook fails or returns a non-Uint8Array. + * `unsupported`: inflate capability, a required profile entry or a schema construct is unsupported. + * `artifact`: a discovery response or artifact text cannot be read: a non-2xx status other than a 404 miss, or a body that is unreadable, oversized, non-UTF-8 or not well-formed JSON; parsed content that is not a valid artifact is `ir`. + * `json`: in an adapter, JSON parsing or UTF-8 decoding fails, or a JSON value does not convert under the codec (for example invalid base64 at a bytes position). + * `validation`: schema parsing fails when Zod validation is enabled. + * `options`: compile, training or adapter options are invalid or cannot be read. + */ export type ErrorCode = | "varint" | "range" @@ -22,9 +45,12 @@ export type ErrorCode = | "validation" | "options"; +/** Base error carrying a stable failure code (wire-v0 §9). */ export class HyperflyError extends Error { + /** Machine-readable failure category; message text may vary (wire-v0 §9). */ readonly code: ErrorCode; + /** Sets the failure category and message, preserving an optional cause. */ constructor(code: ErrorCode, message: string, options?: ErrorOptions) { super(message, options); this.name = new.target.name; @@ -51,14 +77,20 @@ export function messageOf(value: unknown, fallback: string): string { return typeof value === "string" ? value : fallback; } +/** Failure to encode a value under the schema, plan or limits (wire-v0 §9). */ export class EncodeError extends HyperflyError {} +/** Failure to decode a body or envelope under the schema, plan or limits (wire-v0 §9). */ export class DecodeError extends HyperflyError {} +/** Decode failure with code `fingerprint` when codec and payload fingerprints differ (wire-v0 §2). */ export class FingerprintMismatchError extends DecodeError { + /** Fingerprint required by the codec or artifact request. */ readonly expected: string; + /** Fingerprint found in the envelope or computed from the loaded artifact. */ readonly actual: string; + /** Records both fingerprints and sets code `fingerprint`. */ constructor(expected: string, actual: string) { super("fingerprint", `codec fingerprint ${expected} does not match payload ${actual}`); this.expected = expected; @@ -66,9 +98,12 @@ export class FingerprintMismatchError extends DecodeError { } } +/** Schema-adapter failure with code `unsupported` for a construct without an IR encoding (wire-v0 §9). */ export class UnsupportedSchemaError extends HyperflyError { + /** Schema location of the unsupported construct, rooted at `$`. */ readonly path: string; + /** Includes the schema path in the failure message. */ constructor(path: string, message: string) { super("unsupported", `${path}: ${message}`); this.path = path; diff --git a/packages/hyperfly/src/http.ts b/packages/hyperfly/src/http.ts index 6ee2a6d..2c92394 100644 --- a/packages/hyperfly/src/http.ts +++ b/packages/hyperfly/src/http.ts @@ -8,11 +8,17 @@ import type { CodecRegistry } from "./registry.js"; import { byteLengthOf, isUint8Array } from "./typed-array.js"; import { INT_MAX, INT_MIN } from "./varint.js"; +/** The media type of a binary body (negotiation-v1 §1). */ export const HYPERFLY_MEDIA_TYPE = "application/vnd.hyperfly"; +/** The request header listing the fingerprints a client holds, in preference order (negotiation-v1 §1). */ export const ACCEPT_HEADER = "hyperfly-accept"; +/** The header naming the fingerprint a binary body was encoded with (negotiation-v1 §1). */ export const CODEC_HEADER = "hyperfly-codec"; +/** The advisory header naming an artifact the server can encode with (negotiation-v1 §2). */ export const OFFER_HEADER = "hyperfly-offer"; +/** The path prefix artifacts are served under, followed by the fingerprint (negotiation-v1 §3). */ export const WELL_KNOWN_PREFIX = "/.well-known/hyperfly/"; +/** The default bound on a request body or a fetched artifact: 1 MiB. */ export const DEFAULT_MAX_BODY_BYTES = 1 << 20; /** Negotiation §6: client-controlled input, so parsing is bounded. */ @@ -129,8 +135,11 @@ export function negotiate( }; } +/** An encoded response: the body and the headers to send with it. */ export interface Encoded { + /** Binary bytes, or JSON text on a fallback. */ body: Uint8Array | string; + /** Content-Type, Vary and, when they apply, Hyperfly-Codec or Hyperfly-Offer. */ headers: Record; } @@ -471,8 +480,11 @@ export function serveArtifact(pathname: string, registry: CodecRegistry): Artifa }; } +/** Options for compiling a loaded artifact. */ export interface LoadArtifactOptions { + /** Decoder and encoder limits for the compiled codec. Default: `DEFAULT_LIMITS`. */ limits?: Partial; + /** Deflate/inflate hooks for packed columns, or `false` for none. Default: `defaultPackHooks()`. */ pack?: PackHooks | false; } @@ -555,10 +567,15 @@ export function loadArtifact(text: string, fingerprint: string, opt return codec; } +/** Options for fetching an artifact; the compile options of `LoadArtifactOptions` also apply. */ export interface FetchArtifactOptions extends LoadArtifactOptions { + /** The fetch implementation. Default: `globalThis.fetch`. */ fetch?: typeof fetch; + /** Extra request headers, such as authorization. Default: none. */ headers?: HeadersInit; + /** The bound on the artifact body; a larger body throws code `artifact`. Default: `DEFAULT_MAX_BODY_BYTES`. */ maxBytes?: number; + /** Aborts the request; its reason propagates. Default: none. */ signal?: AbortSignal; } @@ -758,7 +775,9 @@ export function discovery(request: Request, registry: CodecRegistry): Response | return new Response(body, { status: served.status, headers: served.headers }); } +/** Options for reading a request body. */ export interface ReadBodyOptions { + /** The bound on the request body; a larger body is refused with 413 `too-large`. Default: `DEFAULT_MAX_BODY_BYTES`. */ maxBytes?: number; } diff --git a/packages/hyperfly/src/ir.ts b/packages/hyperfly/src/ir.ts index c573beb..43dcb96 100644 --- a/packages/hyperfly/src/ir.ts +++ b/packages/hyperfly/src/ir.ts @@ -2,24 +2,41 @@ import { HyperflyError, isInstance } from "./errors.js"; import { checkIRNesting } from "./nesting.js"; import { INT_MAX, INT_MIN } from "./varint.js"; +/** Constant encoded without payload bytes; numeric literals must be safe integers (wire-v0 §4.2). */ export type LiteralValue = string | number | boolean | null; +/** Portable schema nodes whose declared order and bounds are part of the artifact (wire-v0 §4). */ export type IRNode = + /** Boolean encoded as one byte, zero or one (wire-v0 §4.1). */ | { kind: "bool" } + /** Safe integer with optional inclusive bounds; a declared minimum selects offset encoding (wire-v0 §4.4). */ | { kind: "int"; min?: number; max?: number } + /** Finite binary64 value; encoding canonicalizes negative zero (wire-v0 §4.5). */ | { kind: "float64" } + /** Strict UTF-8 text with a byte-length prefix (wire-v0 §4.6). */ | { kind: "string" } + /** Raw bytes with a length prefix (wire-v0 §4.7). */ | { kind: "bytes" } + /** Exact schema constant with no body bytes (wire-v0 §4.2). */ | { kind: "literal"; value: LiteralValue } + /** Non-empty, unique string members indexed in declaration order (wire-v0 §4.3). */ | { kind: "enum"; members: readonly string[] } + /** Null marker or an inner value; nullable or null-literal inner nodes are invalid (wire-v0 §4.9). */ | { kind: "nullable"; inner: IRNode } + /** Repeated elements; an optional non-negative safe-integer length fixes the count and omits its prefix (wire-v0 §4.8). */ | { kind: "array"; element: IRNode; length?: number } + /** Named fields in declaration order, with presence and null bitmaps as needed (wire-v0 §4.10). */ | { kind: "struct"; fields: readonly IRField[] }; +/** Ordered struct field with optional presence and null flags (wire-v0 §4.10). */ export interface IRField { + /** Unique, non-empty Unicode name; `__proto__` and decimal array-index keys are invalid. */ name: string; + /** Encoding of a present, non-null field value. */ type: IRNode; + /** Permits an absent or undefined field and adds a presence bit. Default: false. */ optional?: boolean; + /** Permits null and adds a null bit instead of a nullable-node marker. Default: false. */ nullable?: boolean; } @@ -102,6 +119,7 @@ function checkKeys(value: object, allowed: readonly string[], path: string): voi } } +/** Validates closed IR shapes, portable names, bounds and artifact nesting; throws code `ir` (wire-v0 §4). */ export function validateIR(node: IRNode, path = "$"): void { checkIRNesting(node); withinStack(() => checkNode(node, path)); diff --git a/packages/hyperfly/src/pack.ts b/packages/hyperfly/src/pack.ts index ea98ef5..891ca64 100644 --- a/packages/hyperfly/src/pack.ts +++ b/packages/hyperfly/src/pack.ts @@ -45,6 +45,10 @@ function zlibInflate(zlib: ZlibLike, data: Uint8Array, maxOutputLength: number): return new Uint8Array(out.buffer, out.byteOffset, out.length); } +/** + * Supplies raw DEFLATE hooks using node:zlib when available, with compression level 6. + * Otherwise supplies only the strict JavaScript inflater (plan-columnar-v5 §3). + */ export function defaultPackHooks(): PackHooks { const zlib = builtinZlib(); if (!zlib) return { inflate: inflateRaw }; diff --git a/packages/hyperfly/src/profile.ts b/packages/hyperfly/src/profile.ts index 9c23f59..98afd5f 100644 --- a/packages/hyperfly/src/profile.ts +++ b/packages/hyperfly/src/profile.ts @@ -3,40 +3,61 @@ import { HyperflyError, isInstance } from "./errors.js"; import { describeValue, hasLoneSurrogate, validateIR, withinStack } from "./ir.js"; import type { IRNode } from "./ir.js"; +/** Letter case of grammar digits; decimal tokens require `lower` (plan-columnar-v5 §6.3). */ export type GrammarCase = "lower" | "upper"; +/** Radix of a fixed-width numeric grammar token (plan-columnar-v5 §6.3). */ export type GrammarBase = 10 | 16 | 36; +/** Fixed-width unsigned digit run in a string grammar (plan-columnar-v5 §6.3). */ export interface GrammarNum { + /** Radix used to parse and reconstruct digits. */ base: GrammarBase; + /** Digit count: 1–15 for base 10, 1–13 for base 16, or 1–10 for base 36. */ len: number; + /** Case required for alphabetic digits; base 10 uses `lower`. */ case: GrammarCase; } +/** Non-empty literal text or a numeric run; adjacent literal tokens are invalid (plan-columnar-v5 §6.3). */ export type GrammarToken = { lit: string } | { num: GrammarNum }; +/** String lookup driven by an earlier dictionary column in the same eligible array (plan-columnar-v5 §6.4). */ export interface Derivation { + /** Global leaf ordinal of the earlier string column whose profile contains the source dictionary. */ source: number; + /** Reconstructed target strings in source-dictionary order, one per entry. */ values: readonly string[]; } +/** Shared models for one string leaf; version 2 requires at least one model (plan-columnar-v5 §6.2). */ export interface ProfileColumn { + /** Global leaf ordinal across eligible arrays in schema traversal order (plan-columnar-v5 §6.1). */ leaf: number; + /** Ordered, unique strings: 1–16383 entries, with one-based codes and zero reserved for escapes. */ dict?: readonly string[]; + /** One to eight tokens with at least one numeric run; requires profile version 2. */ grammar?: readonly GrammarToken[]; + /** Mapping from an earlier dictionary column; requires profile version 2. */ derived?: Derivation; } +/** Shared profile content embedded in the artifact and fingerprint (plan-columnar-v5 §6.5). */ export interface SharedProfile { + /** Non-empty string-column models, sorted by ascending leaf ordinal with no duplicates. */ columns: readonly ProfileColumn[]; } +/** Training document with fingerprinted shared models and optional advisory hints (plan-columnar-v5 §6.2). */ export interface Profile { + /** Document shape: 1 requires dictionaries only; 2 also permits grammars and derivations. */ version: 1 | 2; + /** Models needed to encode and decode shared column modes. */ shared: SharedProfile; /** Advisory encoder guidance; never part of the artifact or the fingerprint. */ hints?: Record; } +/** Maximum entries in one shared dictionary (plan-columnar-v5 §6.2). */ export const MAX_DICT_ENTRIES = 16383; export interface ColumnRef { @@ -173,6 +194,7 @@ function snapshotProfile(profile: Profile): Profile { } } +/** Validates IR and profile structure, ordinals and model constraints; throws code `ir` (wire-v0 §9, plan-columnar-v5 §6). */ export function validateProfile(ir: IRNode, profile: Profile): void { checkedProfile(ir, profile); } diff --git a/packages/hyperfly/src/reader.ts b/packages/hyperfly/src/reader.ts index b8896cf..09fa669 100644 --- a/packages/hyperfly/src/reader.ts +++ b/packages/hyperfly/src/reader.ts @@ -1,30 +1,31 @@ import { DecodeError } from "./errors.js"; +/** Local encode and decode resource policy; each value must be a non-negative safe integer (wire-v0 §6). */ export interface Limits { + /** Maximum enclosing struct, array and nullable nodes. Default: 64 (wire-v0 §6). */ maxDepth: number; + /** Maximum elements in one fixed or variable array. Default: 2^24 (wire-v0 §6). */ maxItems: number; + /** Maximum bytes per string/bytes value, packed blob or declared inflated total; schema literals and enum members are not capped. Default: 2^28 (wire-v0 §6). */ maxByteLength: number; /** - * Width-zero columns and arrays of literals legitimately encode any number of - * rows in a handful of bytes, so input length cannot bound such a count. This - * caps the work a byte of hostile input can demand instead: a count above - * maxAmplification * (remaining bytes + 1) is rejected, and the item budget - * of one body is capped at maxAmplification * (body length + 1). Local - * policy, like every other limit — raise it for routes that really ship - * millions of constant rows. + * Caps array counts at maxAmplification * (remaining bytes + 1) and the body item + * budget at maxAmplification * (body length + 1). Row arrays with nonzero-bit + * elements use the stricter remaining-bit bound for their counts. Default: 32 (wire-v0 §6). */ maxAmplification: number; - /** Sum of every array count in one body, nested and sibling arrays alike (wire-v0 §6). */ + /** Maximum sum of every array count in one body, nested and sibling arrays alike. Default: 2^24 (wire-v0 §6). */ maxTotalItems: number; /** - * Sum of the decoded bytes of every string and bytes value in one body, including - * literals, enum members and profile reconstructions (wire-v0 §6). + * Maximum sum of decoded bytes of every string and bytes value in one body, including + * literals, enum members and profile reconstructions. Default: 2^26 (wire-v0 §6). */ maxTotalBytes: number; - /** The byte budget of one body is capped at maxByteAmplification * (body length + 1). */ + /** Caps one body's decoded bytes at maxByteAmplification * (body length + 1). Default: 64 (wire-v0 §6). */ maxByteAmplification: number; } +/** Frozen default resource policy for encoders and decoders (wire-v0 §6). */ export const DEFAULT_LIMITS: Readonly = Object.freeze({ maxDepth: 64, maxItems: 2 ** 24, diff --git a/packages/hyperfly/src/train.ts b/packages/hyperfly/src/train.ts index 5105998..cdeb9f0 100644 --- a/packages/hyperfly/src/train.ts +++ b/packages/hyperfly/src/train.ts @@ -15,10 +15,14 @@ import { type ProfileColumn, } from "./profile.js"; +/** + * Dictionary training thresholds; both default when omitted or undefined. + * Options must be a plain or null-prototype object with only these keys; invalid or unreadable options fail with `options`. + */ export interface TrainOptions { /** Minimum occurrences across samples; a non-negative integer, with 0 clamped to 1. Defaults to 2. */ minOccurrences?: number; - /** Maximum dictionary entries; a non-negative integer, with values above 16383 clamped to 16383. Defaults to 16383. */ + /** Maximum dictionary entries; a non-negative integer, with values above 16383 clamped to 16383. Zero disables dictionaries. Default: 16383. */ maxEntries?: number; } @@ -488,11 +492,10 @@ function detectDerivation( } /** - * Deterministic reference trainer. Explicitly non-normative (spec §6.7): the - * artifact pins its output, but other trainers may make different valid choices. - * - * Dictionary prefix costing, grammar induction, and functional-dependency - * detection are intentionally separated here so none is mistaken for wire logic. + * Deterministically trains string dictionaries, grammars and derivations for eligible arrays (plan-columnar-v5 §6.7). + * Returns undefined when no model is selected; dictionaries alone use profile version 1, other models use version 2. + * Requires a samples array and valid IR. Samples contribute usable string leaves without full schema validation. + * Training is non-normative; the artifact fixes the selected models, and other trainers may choose differently. */ export function train(ir: IRNode, samples: readonly unknown[], options: TrainOptions = {}): Profile | undefined { if (!Array.isArray(samples)) throw new HyperflyError("options", "samples: must be an array"); diff --git a/packages/hyperfly/src/zod.ts b/packages/hyperfly/src/zod.ts index 5e970e0..8932141 100644 --- a/packages/hyperfly/src/zod.ts +++ b/packages/hyperfly/src/zod.ts @@ -16,14 +16,20 @@ interface ZodInternals { output?: unknown; } +/** Structural Zod 4 schema contract accepted by the adapter. */ export interface ZodSchemaLike { + /** Zod 4 schema definition, numeric metadata and inferred output marker. */ _zod: ZodInternals; + /** Schema parser required by validate: true; its result is used for encoding. */ parse?: (value: unknown) => unknown; } +/** Inferred Zod output, or unknown when the schema has no output marker. */ export type InferOutput = S extends { _zod: { output: infer O } } ? O : unknown; +/** Codec compilation options with optional Zod parsing on encode and decode. */ export interface ZodCompileOptions extends CompileOptions { + /** Calls schema.parse before encoding and after decoding; decode retains the wire value. Default: false. */ validate?: boolean; } @@ -214,6 +220,7 @@ function nodeOf(z: ZodInternals, path: string, depth: number): IRNode { } } +/** Converts supported Zod 4 constructs to portable IR; unsupported constructs fail with `unsupported` (wire-v0 §4). */ export function toIR(schema: ZodSchemaLike): IRNode { const { inner, optional, nullable } = unwrap(internals(schema, "$"), "$"); if (optional) unsupported("$", "top-level optional has no v0 encoding"); @@ -221,6 +228,10 @@ export function toIR(schema: ZodSchemaLike): IRNode { return nullable ? { kind: "nullable", inner: node } : node; } +/** + * Compiles a supported Zod 4 schema using the compileIR defaults. + * With validate: true, parse failures carry code `validation` and preserve the cause. + */ export function compile( schema: S, options: ZodCompileOptions = {},