docstudio/core API reference

Every public export of docstudio/core in DocStudio 0.2.0: functions, constants, types and interfaces with signatures.

Import from docstudio/core.

Never throws for JSON input. Problems are returned as diagnostics with a code, a severity and a JSON Pointer path.

Functions

appendPointer

Appends one property name or array index to a JSON Pointer, escaping the segment.

appendPointer(base: string, segment: string | number): string

builtinDefinitions

Returns a fresh list of the built-in component definitions.

builtinDefinitions(): readonly ComponentDefinition[]

canonicalize

Serializes JSON to a stable canonical string with sorted keys, so equal values give equal text.

canonicalize(value: unknown, limits?: Limits): CanonicalResult

canonicalizeTo

Streams the canonical form of a JSON value into a sink function instead of building one string.

canonicalizeTo(value: unknown, sink: ChunkSink, limits?: Limits): Diagnostic[]

checkBindings

Compares the data paths used by a template with a data schema and returns advisory warnings.

checkBindings(template: Template, schema: JsonObject, options?: CheckBindingsOptions): readonly Diagnostic[]
import {
  checkBindings,
  inferDataSchema,
  isJsonValue,
  validateTemplate,
  type Diagnostic,
  type JsonValue,
  type Template,
} from 'docstudio/core';

export function run(): readonly Diagnostic[] {
  const template: Template = {
    schemaVersion: '1.0.0',
    body: [{ id: 'who', type: 'text', content: [{ path: 'customer.fullName' }] }],
  };
  const sample: unknown = { customer: { name: 'Ada' } };
  if (!isJsonValue(sample)) throw new Error('sample data must be JSON');
  const verdict = validateTemplate(template);
  if (!verdict.valid) return verdict.diagnostics;
  const jsonSample: JsonValue = sample;
  const schema = inferDataSchema(jsonSample);
  return checkBindings(template, schema);
}

checkJsonData

Checks that data is plain JSON within the size limits and reports problems with JSON Pointers.

checkJsonData(data: unknown, limits?: Limits): Diagnostic[]

cloneJson

Deep copies a JSON value.

cloneJson(value: JsonValue): JsonValue

closestName

Finds the candidate name nearest to a misspelled one, used for did-you-mean hints.

closestName(name: string, candidates: readonly string[]): string | undefined

compareVersions

Orders two parsed schema versions; returns a negative, zero or positive number.

compareVersions(a: SchemaVersion, b: SchemaVersion): number

compile

Runs the whole pipeline (migrate, validate, configure, expand components, bind data) and returns the resolved document tree with diagnostics.

compile(options: CompileOptions): CompileResult

Errors. Never throws. A template that cannot be used returns tree: undefined and error diagnostics.

import { compile } from 'docstudio/core';
import { render } from 'docstudio/render';

export function run(): string {
  const template = {
    schemaVersion: '1.0.0',
    body: [{ id: 'greeting', type: 'text', content: ['Hello ', { path: 'name' }] }],
  };
  const compiled = compile({ template, data: { name: 'Ada' } });
  if (compiled.tree === undefined) throw new Error('the template did not compile');
  return render(compiled.tree, { target: 'screen' }).html;
}

compileLocks

Compiles lock patterns into a matcher for configuration paths that must stay read only.

compileLocks(patterns: readonly string[] | undefined, basePath?: string): CompiledLocks

createBinder

Creates a binder that turns expressions into text, collections and conditions under a missing-data policy.

createBinder(options?: BinderOptions): Binder
import { compile, createBinder, rootScope, parseExpression } from 'docstudio/core';

export function run(): { text: string; state: string } {
  const data = { customer: { name: 'Ada', tags: ['vip'] }, total: 0 };
  const parsed = parseExpression({
    path: 'customer.nickname',
    fallback: { path: 'customer.name' },
  });
  if (parsed.expression === undefined) throw new Error('invalid expression');
  const binder = createBinder({ policy: 'placeholder' });
  const bound = binder.bindText(parsed.expression, rootScope(data));
  const compiled = compile({
    template: {
      schemaVersion: '1.0.0',
      body: [{ id: 'who', type: 'text', content: ['Total: ', { path: 'total' }] }],
    },
    data,
  });
  if (compiled.tree === undefined) throw new Error('did not compile');
  return { text: bound.text, state: bound.state };
}

createCfworkerValidator

Creates the default JSON Schema validator adapter used by structural validation.

createCfworkerValidator(schema: JsonObject): SchemaValidator

createCollector

Creates a bounded diagnostic collector that stops adding entries at the given maximum.

createCollector(maxDiagnostics: number): DiagnosticCollector

createDefaultRegistry

Creates a registry holding all built-in component definitions.

createDefaultRegistry(): Registry
import {
  createDefaultRegistry,
  registerComponent,
  type Registry,
} from 'docstudio/core';

export function run(): { registry: Registry; registered: boolean } {
  const registry = createDefaultRegistry();
  const outcome = registerComponent(registry, {
    type: 'callout',
    category: 'container',
    childSlots: ['children'],
  });
  return { registry, registered: outcome.registered };
}

createDiagnostic

Builds a diagnostic object with a code, severity, message and JSON Pointer path.

createDiagnostic(code: "LIMIT_EXCEEDED" | "INVALID_JSON_VALUE" | "INVALID_LIMIT" | "DIAGNOSTICS_TRUNCATED" | "SCHEMA_VIOLATION" | "VALIDATOR_FAILURE" | "INVALID_EXPRESSION" | "UNKNOWN_FUNCTION" | "ARITY" | "TYPE_ERROR" | "DIVISION_BY_ZERO" | "NON_FINITE" | "UNSAFE_PATH" | "INVALID_PATH" | "UNKNOWN_FORMATTER" | "FORMATTER_FAILURE" | "LOCKED_PROPERTY" | "UNKNOWN_THEME" | "UNKNOWN_TOKEN" | "INVALID_STYLE_VALUE" | "UNKNOWN_STYLE" | "INVALID_LOCK" | "MISSING_DATA" | "WRONG_TYPE" | "INVALID_REGISTRATION" | "DUPLICATE_REGISTRATION" | "DUPLICATE_ID" | "UNKNOWN_COMPONENT" | "UNUSED_IMPORT" | "SCOPE_VIOLATION" | "FRAME_OUTSIDE_FIXED" | "FRAME_MISSING" | "INVALID_TABLE" | "INVALID_VERSION" | "UNSUPPORTED_VERSION" | "NEWER_VERSION" | "MIGRATION_GAP" | "MIGRATION_FAILED" | "COMPONENT_NOT_FOUND" | "COMPONENT_INVALID" | "UNPINNED_COMPONENT" | "COMPOSITE_CYCLE" | "UNKNOWN_SLOT" | "UNKNOWN_BINDING" | "BINDING_TYPE" | "INVALID_RDT" | "UNSAFE_STYLE_VALUE" | "ASSET_NOT_FOUND" | "ASSET_REJECTED" | "FONT_REJECTED" | "INVALID_PDF_REQUEST" | "PDF_TRANSPORT_FAILED" | "PDF_SERVER_ERROR" | "PDF_QUEUE_FULL" | "PDF_TIMEOUT" | "PDF_RENDER_FAILED" | "PDF_TOO_LARGE" | "PDF_UNAVAILABLE", severity: Severity, message: string, path?: string): Diagnostic

createEvaluator

Creates a reusable expression evaluator that can be called many times, for example once per table row.

createEvaluator(options?: EvaluatorOptions): Evaluator
import {
  createEvaluator,
  createFormatterRegistry,
  parseExpression,
  rootScope,
} from 'docstudio/core';

export function run(): { subtotal: unknown; label: unknown } {
  const evaluator = createEvaluator({ formatters: createFormatterRegistry({ locale: 'en' }) });
  const data = {
    lines: [
      { qty: 2, price: 10 },
      { qty: 1, price: 5.5 },
    ],
  };
  const subtotal = parseExpression({
    fn: 'sum',
    args: [{ path: 'lines' }],
    of: { fn: 'mul', args: [{ path: 'qty' }, { path: 'price' }] },
  });
  const label = parseExpression({
    fn: 'format',
    args: ['currency', { path: '$root.total' }, 'USD'],
  });
  if (subtotal.expression === undefined || label.expression === undefined) {
    throw new Error('invalid expression');
  }
  const scope = rootScope({ ...data, total: 25.5 });
  return {
    subtotal: evaluator.evaluate(subtotal.expression, scope).value,
    label: evaluator.evaluate(label.expression, scope).value,
  };
}

createFormatterRegistry

Creates the formatter map with the built-in date, number, currency, percent and boolean formatters for a locale.

createFormatterRegistry(options: FormatterOptions): FormatterMap

Errors. Never throws. An invalid locale makes a formatter return undefined.

import {
  compile,
  createFormatterRegistry,
  registerFormatter,
  type Rdt,
} from 'docstudio/core';

export function run(): Rdt {
  const formatters = createFormatterRegistry({ locale: 'en' });
  registerFormatter(formatters, 'mrn', (value) =>
    typeof value === 'string' ? `MRN-${value.padStart(8, '0')}` : undefined,
  );
  const result = compile({
    template: {
      schemaVersion: '1.0.0',
      body: [
        {
          id: 'id',
          type: 'text',
          content: [{ fn: 'format', args: ['mrn', { path: 'patient.id' }] }],
        },
        {
          id: 'amount',
          type: 'text',
          content: [{ fn: 'format', args: ['currency', { path: 'amount' }, 'USD'] }],
        },
      ],
    },
    data: { patient: { id: '42' }, amount: 1234.5 },
    formatters,
  });
  if (result.tree === undefined) throw new Error('did not compile');
  return result.tree;
}

createItemCursor

Creates a cursor that yields the scope of each row of a collection while reusing one scope object.

createItemCursor(parent: Scope, rows: JsonValue[]): ItemCursor

createMigrationRegistry

Creates a registry of migrations that upgrade templates between schema versions.

createMigrationRegistry(initial?: readonly Migration[]): MigrationRegistry
import { createMigrationRegistry, migrate } from 'docstudio/core';

export function run(): { applied: number; schemaVersion: unknown } {
  const registry = createMigrationRegistry([
    {
      from: '0.9.0',
      to: '1.0.0',
      apply: (template) => ({ ...template, schemaVersion: '1.0.0', name: 'Migrated' }),
    },
  ]);
  const result = migrate({ schemaVersion: '0.9.0', body: [] }, { registry });
  return { applied: result.applied.length, schemaVersion: result.template?.['schemaVersion'] };
}

createRegistry

Creates an empty component registry.

createRegistry(): Registry

createStyleResolver

Creates a resolver that turns template styles, tokens and themes into resolved style values.

createStyleResolver(scope: ConfigScope): StyleResolver

enterItem

Creates an independent scope for one item of a collection.

enterItem(parent: Scope, item: JsonValue, index: number, rows: JsonValue[]): Scope

enterProps

Adds the properties passed to a reusable component to a scope.

enterProps(scope: Scope, props: JsonValue): Scope

enterSection

Applies a section configuration (direction, tokens, style) to a configuration scope.

enterSection(scope: ConfigScope, config: SectionConfig | undefined, pointer: string): SectionEntry

escapePointerSegment

Escapes a string for use as one JSON Pointer segment.

escapePointerSegment(segment: string): string

evaluateExpression

Evaluates one expression against a scope in a single call.

evaluateExpression(expression: Expression, scope: Scope, options?: EvaluatorOptions): EvaluationResult

expandComponents

Replaces component references with their pinned templates, filling slots and applying locks.

expandComponents(template: Template, options: ExpandOptions): ExpansionResult
import { compile, type ComponentStore, type Rdt } from 'docstudio/core';

export function run(): Rdt {
  const store: ComponentStore = {
    get(name, version) {
      if (name === 'letterhead' && version === '1.0.0') {
        return {
          template: {
            schemaVersion: '1.0.0',
            body: [
              { id: 'org', type: 'text', content: [{ path: '$props.organisation' }] },
              { id: 'extra', type: 'slot', slot: 'extra' },
            ],
          },
        };
      }
      return undefined;
    },
  };
  const result = compile({
    template: {
      schemaVersion: '1.0.0',
      imports: [{ alias: 'head', ref: 'letterhead@1.0.0' }],
      body: [
        {
          id: 'top',
          type: 'component',
          ref: 'letterhead@1.0.0',
          props: { organisation: 'Northwind Clinic' },
          slots: { extra: [{ id: 'note', type: 'text', content: ['Open weekdays'] }] },
        },
      ],
    },
    data: {},
    components: store,
  });
  if (result.tree === undefined) throw new Error(JSON.stringify(result.diagnostics));
  return result.tree;
}

extractDependencies

Lists the pinned component references a template depends on.

extractDependencies(template: Template, registry?: Registry): readonly ComponentRef[]

formatVersion

Formats a parsed schema version as text.

formatVersion(version: SchemaVersion): string

hashTemplate

Returns the SHA-256 content hash of a template, or undefined if it cannot be hashed.

hashTemplate(value: unknown, limits?: Limits): string | undefined

hashValue

Returns the SHA-256 hash of any JSON value together with diagnostics.

hashValue(value: unknown, limits?: Limits): HashResult

inferDataSchema

Infers a JSON Schema from sample data.

inferDataSchema(sample: JsonValue, options?: InferOptions): JsonObject
import {
  checkBindings,
  inferDataSchema,
  isJsonValue,
  validateTemplate,
  type Diagnostic,
  type JsonValue,
  type Template,
} from 'docstudio/core';

export function run(): readonly Diagnostic[] {
  const template: Template = {
    schemaVersion: '1.0.0',
    body: [{ id: 'who', type: 'text', content: [{ path: 'customer.fullName' }] }],
  };
  const sample: unknown = { customer: { name: 'Ada' } };
  if (!isJsonValue(sample)) throw new Error('sample data must be JSON');
  const verdict = validateTemplate(template);
  if (!verdict.valid) return verdict.diagnostics;
  const jsonSample: JsonValue = sample;
  const schema = inferDataSchema(jsonSample);
  return checkBindings(template, schema);
}

isApplicationConfig

Type guard that checks application configuration against its schema.

isApplicationConfig(input: unknown, options?: StructureOptions): boolean

isFunctionName

Type guard for names in the expression function set.

isFunctionName(name: string): boolean

isJsonValue

Type guard for plain JSON values.

isJsonValue(value: unknown): boolean

isPlainObject

Type guard for plain objects, not arrays or class instances.

isPlainObject(value: unknown): boolean

isRdt

Type guard for a resolved document tree.

isRdt(value: unknown): boolean

isTruthy

Applies the expression truthiness rules: undefined, null, false, 0, empty text and empty arrays are false.

isTruthy(value: Value): boolean

isValidTemplate

Returns true when a value passes structural validation.

isValidTemplate(input: unknown, options?: StructureOptions): boolean

listBindingPaths

Lists every data path a schema describes, with its type.

listBindingPaths(schema: JsonObject, options?: ListPathsOptions): readonly BindingPath[]

mergeResolved

Merges two resolved styles, the overlay winning.

mergeResolved(base: ResolvedStyle, overlay: ResolvedStyle): ResolvedStyle

mergeSchemas

Merges two inferred data schemas into one that accepts both.

mergeSchemas(a: JsonObject, b: JsonObject): JsonObject

migrate

Upgrades a template through registered migrations to the current schema version.

migrate(input: unknown, options?: MigrateOptions): MigrationResult
import { createMigrationRegistry, migrate } from 'docstudio/core';

export function run(): { applied: number; schemaVersion: unknown } {
  const registry = createMigrationRegistry([
    {
      from: '0.9.0',
      to: '1.0.0',
      apply: (template) => ({ ...template, schemaVersion: '1.0.0', name: 'Migrated' }),
    },
  ]);
  const result = migrate({ schemaVersion: '0.9.0', body: [] }, { registry });
  return { applied: result.applied.length, schemaVersion: result.template?.['schemaVersion'] };
}

normalizeLimits

Validates limit overrides and returns the effective limits, never above the ceilings.

normalizeLimits(overrides?: unknown): NormalizedLimits
import { compile, normalizeLimits, type Rdt } from 'docstudio/core';

export function run(): Rdt {
  const limits = normalizeLimits({ maxTemplateNodes: 2000 });
  const result = compile({
    template: {
      schemaVersion: '1.0.0',
      body: [{ id: 'a', type: 'text', content: [{ path: 'missing' }] }],
    },
    data: {},
    config: { missingData: 'blank', page: { size: 'Letter', margins: 20 } },
    limits: limits.limits,
  });
  if (result.tree === undefined) throw new Error('did not compile');
  return result.tree;
}

normalizeSpacing

Converts a spacing value (one number or four) into top, right, bottom and left values.

normalizeSpacing(spacing: Spacing): SpacingBox | undefined

parseComponentRef

Parses a component reference of the form name@major.minor.patch.

parseComponentRef(ref: string): ParsedComponentRef

parseExpression

Validates an untrusted expression once and returns the parsed form with diagnostics.

parseExpression(input: unknown, options?: ParseOptions): ParseResult
import {
  createEvaluator,
  createFormatterRegistry,
  parseExpression,
  rootScope,
} from 'docstudio/core';

export function run(): { subtotal: unknown; label: unknown } {
  const evaluator = createEvaluator({ formatters: createFormatterRegistry({ locale: 'en' }) });
  const data = {
    lines: [
      { qty: 2, price: 10 },
      { qty: 1, price: 5.5 },
    ],
  };
  const subtotal = parseExpression({
    fn: 'sum',
    args: [{ path: 'lines' }],
    of: { fn: 'mul', args: [{ path: 'qty' }, { path: 'price' }] },
  });
  const label = parseExpression({
    fn: 'format',
    args: ['currency', { path: '$root.total' }, 'USD'],
  });
  if (subtotal.expression === undefined || label.expression === undefined) {
    throw new Error('invalid expression');
  }
  const scope = rootScope({ ...data, total: 25.5 });
  return {
    subtotal: evaluator.evaluate(subtotal.expression, scope).value,
    label: evaluator.evaluate(label.expression, scope).value,
  };
}

parsePointer

Splits a JSON Pointer into segments, or returns undefined when it is malformed.

parsePointer(pointer: string): string[] | undefined

parseVersion

Parses a semantic version string into its parts, or returns undefined.

parseVersion(text: unknown): SchemaVersion | undefined

registerComponent

Adds a component definition to a registry and reports invalid or duplicate registrations.

registerComponent(registry: Registry, definition: ComponentDefinition): Registration
import {
  createDefaultRegistry,
  registerComponent,
  type Registry,
} from 'docstudio/core';

export function run(): { registry: Registry; registered: boolean } {
  const registry = createDefaultRegistry();
  const outcome = registerComponent(registry, {
    type: 'callout',
    category: 'container',
    childSlots: ['children'],
  });
  return { registry, registered: outcome.registered };
}

registerFormatter

Adds a custom formatter to a formatter map; returns a diagnostic for a bad or duplicate name.

registerFormatter(registry: FormatterMap, name: string, formatter: Formatter): Diagnostic | undefined
import {
  compile,
  createFormatterRegistry,
  registerFormatter,
  type Rdt,
} from 'docstudio/core';

export function run(): Rdt {
  const formatters = createFormatterRegistry({ locale: 'en' });
  registerFormatter(formatters, 'mrn', (value) =>
    typeof value === 'string' ? `MRN-${value.padStart(8, '0')}` : undefined,
  );
  const result = compile({
    template: {
      schemaVersion: '1.0.0',
      body: [
        {
          id: 'id',
          type: 'text',
          content: [{ fn: 'format', args: ['mrn', { path: 'patient.id' }] }],
        },
        {
          id: 'amount',
          type: 'text',
          content: [{ fn: 'format', args: ['currency', { path: 'amount' }, 'USD'] }],
        },
      ],
    },
    data: { patient: { id: '42' }, amount: 1234.5 },
    formatters,
  });
  if (result.tree === undefined) throw new Error('did not compile');
  return result.tree;
}

resolveColorValue

Resolves a color value, including token references, to a final color string.

resolveColorValue(value: Color, ctx: StyleContext, pointer: string): string | undefined

resolveConfig

Resolves the configuration cascade (engine, application, template, section) into effective values.

resolveConfig(layers: ConfigLayers, limits?: Limits): ConfigResolution

resolvePageDimensions

Returns the page width and height in millimetres for a size and orientation.

resolvePageDimensions(page: Pick<EffectivePage, "size" | "orientation">): PageDimensions

resolveSchemaPath

Looks up the schema node for a dotted data path.

resolveSchemaPath(schema: JsonObject, path: string): JsonObject | undefined

resolveSegments

Looks up the schema node for a list of path segments.

resolveSegments(schema: JsonObject, segments: readonly PathSegment[]): SchemaResolution

resolveStyleLayer

Resolves one style object into validated style values.

resolveStyleLayer(layer: Style, ctx: StyleContext, pointer: string): ResolvedStyle

rootScope

Creates the top expression scope from data and optional component props.

rootScope(data: JsonValue, props?: JsonValue | undefined): Scope

sha256Hex

Returns the SHA-256 digest of a text as lowercase hexadecimal.

sha256Hex(text: string): string

unescapePointerSegment

Reverses escapePointerSegment.

unescapePointerSegment(segment: string): string

validateAgainst

Runs a validator against input after enforcing the JSON limits.

validateAgainst(validator: SchemaValidator, input: unknown, limits: Limits): StructureResult

validateApplicationConfig

Validates application configuration against its schema.

validateApplicationConfig(input: unknown, options?: StructureOptions): StructureResult

validateTemplate

Validates a template structurally and then semantically, optionally against a data schema.

validateTemplate(input: unknown, options?: ValidateTemplateOptions): TemplateValidation
import {
  checkBindings,
  inferDataSchema,
  isJsonValue,
  validateTemplate,
  type Diagnostic,
  type JsonValue,
  type Template,
} from 'docstudio/core';

export function run(): readonly Diagnostic[] {
  const template: Template = {
    schemaVersion: '1.0.0',
    body: [{ id: 'who', type: 'text', content: [{ path: 'customer.fullName' }] }],
  };
  const sample: unknown = { customer: { name: 'Ada' } };
  if (!isJsonValue(sample)) throw new Error('sample data must be JSON');
  const verdict = validateTemplate(template);
  if (!verdict.valid) return verdict.diagnostics;
  const jsonSample: JsonValue = sample;
  const schema = inferDataSchema(jsonSample);
  return checkBindings(template, schema);
}

validateTemplateSemantics

Runs only the semantic checks (references, scopes, expression rules) on a structurally valid template.

validateTemplateSemantics(template: Template, options?: SemanticOptions): readonly Diagnostic[]

validateTemplateStructure

Runs only the structural check against the template schema.

validateTemplateStructure(input: unknown, options?: StructureOptions): StructureResult

Classes

Sha256

Incremental SHA-256 hasher implemented without platform APIs so core runs everywhere.

export class Sha256 {
  private readonly state = new Uint32Array(INITIAL_STATE);
  private readonly block = new Uint8Array(64);
  private readonly words = new Uint32Array(64);
  private blockLength = 0;
  private totalBytes = 0;
  private pendingHighSurrogate = 0;
  private finished = false;

  updateBytes(bytes: Uint8Array): void {
    this.assertOpen();
    for (let i = 0; i < bytes.length; i += 1) this.pushByte(bytes[i] ?? 0);
  }

  updateString(text: string): void {
    this.assertOpen();
    for (let i = 0; i < text.length; i += 1) {
      const unit = text.charCodeAt(i);
      if (this.pendingHighSurrogate !== 0) {
        const high = this.pendingHighSurrogate;
        this.pendingHighSurrogate = 0;
        if (unit >= 0xdc00 && unit <= 0xdfff) {
          this.writeCodePoint(0x10000 + ((high - 0xd800) << 10) + (unit - 0xdc00));
          continue;
        }
        this.writeCodePoint(REPLACEMENT_CHARACTER);
      }
      if (unit < 0x80) {
        this.pushByte(unit);
      } else if (unit >= 0xd800 && unit <= 0xdbff) {
        this.pendingHighSurrogate = unit;
      } else if (unit >= 0xdc00 && unit <= 0xdfff) {
        this.writeCodePoint(REPLACEMENT_CHARACTER);
      } else {
        this.writeCodePoint(unit);
      }
    }
  }

  digestHex(): string {
    this.assertOpen();
    if (this.pendingHighSurrogate !== 0) {
      this.pendingHighSurrogate = 0;
      this.writeCodePoint(REPLACEMENT_CHARACTER);
    }
    this.finished = true;
    const bitLengthHigh = Math.floor(this.totalBytes / 0x20000000);
    const bitLengthLow = (this.totalBytes << 3) >>> 0;
    this.pushPadding(0x80);
    while (this.blockLength !== 56) this.pushPadding(0);
    this.pushLengthWord(bitLengthHigh);
    this.pushLengthWord(bitLengthLow);
    let hex = '';
    for (let i = 0; i < 8; i += 1) {
      const word = this.state[i] ?? 0;
      for (let shift = 28; shift >= 0; shift -= 4) hex += HEX.charAt((word >>> shift) & 0xf);
    }
    return hex;
  }

  private assertOpen(): void {
    if (this.finished) throw new Error('Sha256 instance is already finalized');
  }

  private writeCodePoint(codePoint: number): void {
    if (codePoint < 0x80) {
      this.pushByte(codePoint);
    } else if (codePoint < 0x800) {
      this.pushByte(0xc0 | (codePoint >> 6));
      this.pushByte(0x80 | (codePoint & 0x3f));
    } else if (codePoint < 0x10000) {
      this.pushByte(0xe0 | (codePoint >> 12));
      this.pushByte(0x80 | ((codePoint >> 6) & 0x3f));
      this.pushByte(0x80 | (codePoint & 0x3f));
    } else {
      this.pushByte(0xf0 | (codePoint >> 18));
      this.pushByte(0x80 | ((codePoint >> 12) & 0x3f));
      this.pushByte(0x80 | ((codePoint >> 6) & 0x3f));
      this.pushByte(0x80 | (codePoint & 0x3f));
    }
  }

  private pushByte(byte: number): void {
    this.block[this.blockLength] = byte;
    this.blockLength += 1;
    this.totalBytes += 1;
    if (this.blockLength === 64) this.compress();
  }

  private pushPadding(byte: number): void {
    this.block[this.blockLength] = byte;
    this.blockLength += 1;
    if (this.blockLength === 64) this.compress();
  }

  private pushLengthWord(word: number): void {
    this.pushPadding((word >>> 24) & 0xff);
    this.pushPadding((word >>> 16) & 0xff);
    this.pushPadding((word >>> 8) & 0xff);
    this.pushPadding(word & 0xff);
  }

  private compress(): void {
    const w = this.words;
    const block = this.block;
    for (let i = 0; i < 16; i += 1) {
      const offset = i * 4;
      w[i] =
        (((block[offset] ?? 0) << 24) |
          ((block[offset + 1] ?? 0) << 16) |
          ((block[offset + 2] ?? 0) << 8) |
          (block[offset + 3] ?? 0)) >>>
        0;
    }
    for (let i = 16; i < 64; i += 1) {
      const w15 = w[i - 15] ?? 0;
      const w2 = w[i - 2] ?? 0;
      const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3);
      const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10);
      w[i] = ((w[i - 16] ?? 0) + s0 + (w[i - 7] ?? 0) + s1) >>> 0;
    }
    const s = this.state;
    let a = s[0] ?? 0;
    let b = s[1] ?? 0;
    let c = s[2] ?? 0;
    let d = s[3] ?? 0;
    let e = s[4] ?? 0;
    let f = s[5] ?? 0;
    let g = s[6] ?? 0;
    let h = s[7] ?? 0;
    for (let i = 0; i < 64; i += 1) {
      const sum1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
      const choose = (e & f) ^ (~e & g);
      const temp1 = (h + sum1 + choose + (ROUND_CONSTANTS[i] ?? 0) + (w[i] ?? 0)) >>> 0;
      const sum0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
      const majority = (a & b) ^ (a & c) ^ (b & c);
      const temp2 = (sum0 + majority) >>> 0;
      h = g;
      g = f;
      f = e;
      e = (d + temp1) >>> 0;
      d = c;
      c = b;
      b = a;
      a = (temp1 + temp2) >>> 0;
    }
    s[0] = ((s[0] ?? 0) + a) >>> 0;
    s[1] = ((s[1] ?? 0) + b) >>> 0;
    s[2] = ((s[2] ?? 0) + c) >>> 0;
    s[3] = ((s[3] ?? 0) + d) >>> 0;
    s[4] = ((s[4] ?? 0) + e) >>> 0;
    s[5] = ((s[5] ?? 0) + f) >>> 0;
    s[6] = ((s[6] ?? 0) + g) >>> 0;
    s[7] = ((s[7] ?? 0) + h) >>> 0;
    this.blockLength = 0;
  }
}

Constants

APPLICATION_CONFIG_SCHEMA

The JSON Schema that validates application configuration passed to resolveConfig.

const APPLICATION_CONFIG_SCHEMA: JsonObject

BUILTIN_TYPES

The built-in node type names registered by createDefaultRegistry.

const BUILTIN_TYPES: readonly BuiltinType[]

CORE_MODULE_ID

The identifier of the core module, used by the dependency boundary tests.

const CORE_MODULE_ID: "ds:core"

DEFAULT_LIMITS

The default resource limits applied by every core function.

const DEFAULT_LIMITS: Limits

DEFAULT_PLACEHOLDER

The text shown for missing data under the placeholder policy, a single hyphen.

const DEFAULT_PLACEHOLDER: "-"

DIAGNOSTIC_CODES

The closed list of diagnostic codes the engine can produce.

const DIAGNOSTIC_CODES: readonly ["LIMIT_EXCEEDED", "INVALID_JSON_VALUE", "INVALID_LIMIT", "DIAGNOSTICS_TRUNCATED", "SCHEMA_VIOLATION", "VALIDATOR_FAILURE", "INVALID_EXPRESSION", "UNKNOWN_FUNCTION", "ARITY", "TYPE_ERROR", "DIVISION_BY_ZERO", "NON_FINITE", "UNSAFE_PATH", "INVALID_PATH", "UNKNOWN_FORMATTER", "FORMATTER_FAILURE", "LOCKED_PROPERTY", "UNKNOWN_THEME", "UNKNOWN_TOKEN", "INVALID_STYLE_VALUE", "UNKNOWN_STYLE", "INVALID_LOCK", "MISSING_DATA", "WRONG_TYPE", "INVALID_REGISTRATION", "DUPLICATE_REGISTRATION", "DUPLICATE_ID", "UNKNOWN_COMPONENT", "UNUSED_IMPORT", "SCOPE_VIOLATION", "FRAME_OUTSIDE_FIXED", "FRAME_MIS

EMPTY_LOCKS

A lock set that locks nothing.

const EMPTY_LOCKS: LockSet

ENGINE_DEFAULTS

The engine default configuration values used at the bottom of the configuration cascade.

const ENGINE_DEFAULTS: EngineDefaults

EXPRESSION_FUNCTIONS

The closed set of expression function names with their minimum and maximum argument counts.

const EXPRESSION_FUNCTIONS: { readonly add: readonly [2, 64]; readonly sub: readonly [2, 2]; readonly mul: readonly [2, 64]; readonly div: readonly [2, 2]; readonly mod: readonly [2, 2]; readonly round: readonly [1, 2]; readonly abs: readonly [1, 1]; readonly number: readonly [1, 1]; readonly min: readonly [1, 64]; readonly max: readonly [1, 64]; readonly eq: readonly [2, 2]; readonly ne: readonly [2, 2]; readonly gt: readonly [2, 2]; readonly gte: readonly [2, 2]; readonly lt: readonly [2, 2]; readonly lte: readonly [2, 2]; readonly and: readonly [1, 64]; readonly or: readonly [1, 64]; readonly not: readonly [1, 1]; rea

HASH_PREFIX

The prefix of content hashes, sha256:.

const HASH_PREFIX: "sha256:"

LIMIT_CEILINGS

The absolute maximum for every limit; hosts cannot raise limits beyond these.

const LIMIT_CEILINGS: Limits

LIMIT_NAMES

The names of all configurable limits.

const LIMIT_NAMES: readonly (keyof Limits)[]

LOCK_PATTERN

The regular expression that lock patterns must match.

const LOCK_PATTERN: "^[A-Za-z*][A-Za-z0-9_*-]{0,63}(\\.[A-Za-z0-9_*-]{1,64}){0,7}$"

NODE_TYPES

The node type names defined by the template schema.

const NODE_TYPES: readonly ["text", "image", "divider", "shape", "stack", "row", "grid", "fixed", "section", "table", "repeater", "pageNumber", "qr", "barcode", "component", "slot"]

RDT_VERSION

The version of the resolved document tree contract, 1.

const RDT_VERSION: "1"

TEMPLATE_SCHEMA

The JSON Schema (2020-12) for templates.

const TEMPLATE_SCHEMA: JsonObject

TEMPLATE_SCHEMA_VERSION

The current template schema version, 1.0.0.

const TEMPLATE_SCHEMA_VERSION: "1.0.0"

Types

Alignment

export type Alignment = 'start' | 'center' | 'end';

BindingOutcome

export type BindingOutcome = 'value' | 'empty' | 'blank' | 'placeholder' | 'warned' | 'failed';

BindingState

export type BindingState = 'present' | 'empty' | 'missing' | 'null' | 'wrongType';

CanonicalResult

export type CanonicalResult =
  | { readonly ok: true; readonly text: string }
  | { readonly ok: false; readonly diagnostics: readonly Diagnostic[] };

ChunkSink

export type ChunkSink = (chunk: string) => void;

Color

export type Color = string | TokenRef;

CompiledNode

export type CompiledNode = LiteralNode | PathNode | CallNode;

ComponentCategory

export type ComponentCategory = 'leaf' | 'container' | 'data';

ConditionEvaluator

export type ConditionEvaluator = (condition: Expr, pointer: string) => boolean;

DataSchema

export type DataSchema = JsonObject;

DiagnosticCode

export type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[number];

ExpandedComponentScope

export type ExpandedComponentScope = Omit<ComponentNode, 'type' | 'slots'> &
  Expanded & { readonly type: 'componentScope'; readonly props?: JsonObject } & Origin;

ExpandedContainer

export type ExpandedContainer = (
  | (Omit<StackNode, 'children'> & Expanded)
  | (Omit<RowNode, 'children'> & Expanded)
  | (Omit<GridNode, 'children'> & Expanded)
  | (Omit<FixedNode, 'children'> & Expanded)
  | (Omit<SectionNode, 'children'> & Expanded)
) &
  Origin;

ExpandedLeaf

export type ExpandedLeaf = (
  TextNode | ImageNode | DividerNode | ShapeNode | TableNode | PageNumberNode | QrNode | BarcodeNode
) &
  Origin;

ExpandedNode

export type ExpandedNode =
  | ExpandedLeaf
  | ExpandedContainer
  | ExpandedRepeater
  | ExpandedComponentScope
  | ExpandedSlotContent;

ExpandedRepeater

export type ExpandedRepeater = Omit<RepeaterNode, 'children' | 'empty'> &
  Expanded & { readonly empty?: readonly ExpandedNode[] } & Origin;

Expr

export type Expr = null | boolean | number | string | PathExpr | CallExpr;

Formatter

export type Formatter = (value: JsonValue, options: readonly JsonValue[]) => string | undefined;

FormatterMap

export type FormatterMap = Map<string, Formatter>;

FormatterRegistry

export type FormatterRegistry = ReadonlyMap<string, Formatter>;

FunctionName

export type FunctionName = keyof typeof EXPRESSION_FUNCTIONS;

HashResult

export type HashResult =
  | { readonly ok: true; readonly hash: string }
  | { readonly ok: false; readonly diagnostics: readonly Diagnostic[] };

JsonObject

export type JsonObject = { [key: string]: JsonValue };

JsonPrimitive

export type JsonPrimitive = null | boolean | number | string;

JsonValue

export type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };

LimitName

export type LimitName = keyof Limits;

MissingPolicy

export type MissingPolicy = 'blank' | 'placeholder' | 'warn' | 'error';

NodeType

export type NodeType = TemplateNode['type'];

PageSize

export type PageSize =
  'A3' | 'A4' | 'A5' | 'A6' | 'Letter' | 'Legal' | { readonly w: number; readonly h: number };

RdtNode

export type RdtNode =
  | RdtText
  | RdtImage
  | RdtDivider
  | RdtShape
  | RdtPageNumber
  | RdtQr
  | RdtBarcode
  | RdtStack
  | RdtRow
  | RdtGrid
  | RdtFixed
  | RdtSection
  | RdtTable;

ResolveFacet

export type ResolveFacet = (props: JsonObject) => JsonObject | undefined;

SchemaValidatorFactory

export type SchemaValidatorFactory = (schema: JsonObject) => SchemaValidator;

Severity

export type Severity = 'error' | 'warning' | 'info';

SizeSpec

export type SizeSpec = number | string;

Spacing

export type Spacing = number | readonly number[];

SpacingBox

export type SpacingBox = readonly [number, number, number, number];

TableFooterCell

export type TableFooterCell = TableCell;

TemplateNode

export type TemplateNode =
  | TextNode
  | ImageNode
  | DividerNode
  | ShapeNode
  | StackNode
  | RowNode
  | GridNode
  | FixedNode
  | SectionNode
  | TableNode
  | RepeaterNode
  | PageNumberNode
  | QrNode
  | BarcodeNode
  | ComponentNode
  | SlotNode;

TokenMap

export type TokenMap = Readonly<Record<string, string | number>>;

TrackSpec

export type TrackSpec = number | string;

ValidateTemplateOptions

export type ValidateTemplateOptions = StructureOptions &
  Omit<SemanticOptions, 'limits'> & { readonly dataSchema?: DataSchema };

Value

export type Value = JsonValue | undefined;

ValueType

export type ValueType = 'undefined' | 'null' | 'string' | 'number' | 'boolean' | 'array' | 'object';

Interfaces

ApplicationConfig

export interface ApplicationConfig extends TemplateConfig {
  readonly style?: Style;
  readonly styles?: Readonly<Record<string, Style>>;
  readonly themes?: Readonly<Record<string, ApplicationTheme>>;
  readonly locks?: readonly string[];
}

ApplicationTheme

export interface ApplicationTheme {
  readonly tokens: TokenMap;
}

AppliedMigration

export interface AppliedMigration {
  readonly from: string;
  readonly to: string;
}

BarcodeNode

export interface BarcodeNode extends NodeBase {
  readonly type: 'barcode';
  readonly value: Expr;
  readonly format: 'code128' | 'code39' | 'ean13';
}

Binder

export interface Binder {
  bindText(expression: Expression, scope: Scope, policy?: MissingPolicy): TextResult;
  bindSegments(segments: readonly Expression[], scope: Scope, policy?: MissingPolicy): TextResult;
  bindCollection(expression: Expression, scope: Scope, policy?: MissingPolicy): CollectionResult;
  condition(expression: Expression, scope: Scope): boolean;
  value(expression: Expression, scope: Scope): Value;
  report(): BinderReport;
}

BinderOptions

export interface BinderOptions {
  readonly policy?: MissingPolicy;
  readonly placeholder?: string;
  readonly limits?: Limits;
  readonly formatters?: FormatterRegistry;
  readonly trace?: boolean;
}

BinderReport

export interface BinderReport {
  readonly diagnostics: readonly Diagnostic[];
  readonly trace: readonly TraceEntry[];
  readonly traceTruncated: boolean;
}

BindingPath

export interface BindingPath {
  readonly path: string;
  readonly type: string;
}

Border

export interface Border {
  readonly width?: number;
  readonly color?: Color;
  readonly style?: 'solid' | 'dashed' | 'dotted' | 'none';
  readonly radius?: number;
}

BreakSettings

export interface BreakSettings {
  readonly before?: boolean;
  readonly after?: boolean;
  readonly inside?: 'auto' | 'avoid';
}

CallExpr

export interface CallExpr {
  readonly fn: string;
  readonly args: readonly Expr[];
  readonly of?: Expr;
}

CallNode

export interface CallNode {
  readonly kind: 'call';
  readonly fn: FunctionName;
  readonly args: readonly CompiledNode[];
  readonly of: CompiledNode | undefined;
  readonly pointer: string;
}

CheckBindingsOptions

export interface CheckBindingsOptions {
  readonly limits?: Limits;
}

CollectionResult

export interface CollectionResult {
  readonly items: JsonValue[];
  readonly state: BindingState;
  readonly failed: boolean;
}

ColumnWidth

export interface ColumnWidth {
  readonly mode: 'auto' | 'fixed' | 'percent';
  readonly value?: number;
}

CompiledLocks

export interface CompiledLocks {
  readonly locks: LockSet;
  readonly diagnostics: readonly Diagnostic[];
}

CompileMeta

export interface CompileMeta {
  readonly rdtVersion: Rdt['rdtVersion'];
  readonly schemaVersion: string;
  readonly migrations: readonly AppliedMigration[];
  readonly templateHash: string | undefined;
  readonly configHash: string | undefined;
  readonly dataHash: string | undefined;
  readonly treeHash: string | undefined;
  readonly components: readonly ComponentLock[];
  readonly stats: CompileStats;
  readonly errors: number;
  readonly warnings: number;
}

CompileOptions

export interface CompileOptions {
  readonly template: unknown;
  readonly data: unknown;
  readonly config?: unknown;
  readonly components?: ComponentStore;
  readonly registry?: Registry;
  readonly formatters?: FormatterRegistry;
  readonly migrations?: MigrationRegistry;
  readonly limits?: Limits;
  readonly dataSchema?: DataSchema;
  readonly trace?: boolean;
  readonly hash?: { readonly tree?: boolean; readonly data?: boolean };
}

CompileResult

export interface CompileResult {
  readonly ok: boolean;
  readonly tree: Rdt | undefined;
  readonly diagnostics: readonly Diagnostic[];
  readonly meta: CompileMeta | undefined;
  readonly trace: CompileTrace | undefined;
}

CompileStats

export interface CompileStats {
  readonly nodes: number;
  readonly tableRows: number;
  readonly cells: number;
  readonly textRuns: number;
}

CompileTrace

export interface CompileTrace {
  readonly entries: readonly TraceEntry[];
  readonly truncated: boolean;
}

ComponentDefinition

export interface ComponentDefinition {
  readonly type: string;
  readonly category: ComponentCategory;
  readonly childSlots: readonly string[];
  readonly schema?: JsonObject;
  readonly resolve?: ResolveFacet;
}

ComponentLock

export interface ComponentLock {
  readonly ref: string;
  readonly name: string;
  readonly version: string;
  readonly hash: string;
}

ComponentNode

export interface ComponentNode extends NodeBase {
  readonly type: 'component';
  readonly ref: string;
  readonly props?: JsonObject;
  readonly slots?: Readonly<Record<string, readonly TemplateNode[]>>;
}

ComponentRecord

export interface ComponentRecord {
  readonly template: unknown;
}

ComponentRef

export interface ComponentRef {
  readonly ref: string;
  readonly name: string;
  readonly version: string | undefined;
  readonly alias: string | undefined;
  readonly imported: boolean;
  readonly used: boolean;
}

ComponentStore

export interface ComponentStore {
  get(name: string, version: string): ComponentRecord | undefined;
}

ConfigLayers

export interface ConfigLayers {
  readonly application?: ApplicationConfig | undefined;
  readonly template?:
    | {
        readonly config?: TemplateConfig | undefined;
        readonly styles?: Readonly<Record<string, Style>> | undefined;
      }
    | undefined;
}

ConfigResolution

export interface ConfigResolution {
  readonly config: EffectiveConfig;
  readonly scope: ConfigScope;
  readonly hash: string | undefined;
  readonly diagnostics: readonly Diagnostic[];
}

ConfigScope

export interface ConfigScope {
  readonly tokens: TokenMap;
  readonly style: ResolvedStyle;
  readonly styles: Readonly<Record<string, NamedStyle>>;
  readonly locks: LockSet;
}

Diagnostic

export interface Diagnostic {
  readonly code: DiagnosticCode;
  readonly severity: Severity;
  readonly message: string;
  readonly path: string;
}

DiagnosticCollector

export interface DiagnosticCollector {
  add(diagnostic: Diagnostic): void;
  list(): readonly Diagnostic[];
  hasErrors(): boolean;
  isTruncated(): boolean;
}

DividerNode

export interface DividerNode extends NodeBase {
  readonly type: 'divider';
  readonly thickness?: number;
  readonly color?: Color;
}

EffectiveConfig

export interface EffectiveConfig {
  readonly page: EffectivePage;
  readonly locale: string;
  readonly missingData: 'blank' | 'placeholder' | 'warn' | 'error';
  readonly theme?: string;
  readonly tokens: TokenMap;
  readonly style: ResolvedStyle;
  readonly styles: Readonly<Record<string, Style>>;
}

EffectivePage

export interface EffectivePage {
  readonly size: PageSize;
  readonly orientation: 'portrait' | 'landscape';
  readonly margins: SpacingBox;
  readonly direction: 'ltr' | 'rtl';
  readonly mode: 'flow' | 'fixed';
  readonly background?: string;
}

EngineDefaults

export interface EngineDefaults {
  readonly page: {
    readonly size: PageSize;
    readonly orientation: 'portrait' | 'landscape';
    readonly margins: number;
    readonly direction: 'ltr' | 'rtl';
    readonly mode: 'flow' | 'fixed';
  };
  readonly locale: string;
  readonly missingData: 'blank' | 'placeholder' | 'warn' | 'error';
  readonly style: Style;
}

EvaluationResult

export interface EvaluationResult {
  readonly value: Value;
  readonly diagnostics: readonly Diagnostic[];
}

Evaluator

export interface Evaluator {
  evaluate(expression: Expression, scope: Scope): EvaluationResult;
}

EvaluatorOptions

export interface EvaluatorOptions {
  readonly limits?: Limits;
  readonly formatters?: FormatterRegistry;
}

ExpandedRegion

export interface ExpandedRegion {
  readonly height: number;
  readonly children: readonly ExpandedNode[];
}

ExpandedSlotContent

export interface ExpandedSlotContent extends Expanded, Origin {
  readonly type: 'slotContent';
  readonly id: string;
  readonly name: string;
}

ExpandedTemplate

export interface ExpandedTemplate {
  readonly source: Template;
  readonly body: readonly ExpandedNode[];
  readonly header: ExpandedRegion | undefined;
  readonly footer: ExpandedRegion | undefined;
}

ExpandOptions

export interface ExpandOptions {
  readonly store: ComponentStore;
  readonly limits?: Limits;
  readonly registry?: Registry;
  readonly migrations?: MigrationRegistry;
  readonly formatters?: ReadonlyMap<string, unknown>;
}

ExpansionResult

export interface ExpansionResult {
  readonly expanded: ExpandedTemplate;
  readonly locks: readonly ComponentLock[];
  readonly diagnostics: readonly Diagnostic[];
}

Expression

export interface Expression {
  readonly root: CompiledNode;
  readonly nodeCount: number;
  readonly pointer: string;
}

FixedNode

export interface FixedNode extends NodeBase {
  readonly type: 'fixed';
  readonly size: { readonly w: number; readonly h: number };
  readonly children: readonly TemplateNode[];
}

FormatterOptions

export interface FormatterOptions {
  readonly locale: string;
}

Frame

export interface Frame {
  readonly x: number;
  readonly y: number;
  readonly w?: number;
  readonly h?: number;
  readonly rotate?: number;
  readonly z?: number;
}

GridNode

export interface GridNode extends NodeBase {
  readonly type: 'grid';
  readonly columns: readonly TrackSpec[];
  readonly children: readonly TemplateNode[];
  readonly gap?: number;
}

ImageNode

export interface ImageNode extends NodeBase {
  readonly type: 'image';
  readonly src: string;
  readonly alt?: string;
  readonly fit?: 'contain' | 'cover' | 'fill' | 'none';
}

ImportRef

export interface ImportRef {
  readonly alias: string;
  readonly ref: string;
}

InferOptions

export interface InferOptions {
  readonly sampleLimit?: number;
}

ItemCursor

export interface ItemCursor {
  at(index: number): Scope;
}

Limits

export interface Limits {
  readonly maxJsonDepth: number;
  readonly maxJsonNodes: number;
  readonly maxJsonChars: number;
  readonly maxStringLength: number;
  readonly maxArrayLength: number;
  readonly maxObjectKeys: number;
  readonly maxTemplateNodes: number;
  readonly maxExpressionDepth: number;
  readonly maxExpressionNodes: number;
  readonly maxEvaluationSteps: number;
  readonly maxRepeaterRows: number;
  readonly maxCompositeDepth: number;
  readonly maxDiagnostics: number;
  readonly maxTraceEntries: number;
}

ListPathsOptions

export interface ListPathsOptions {
  readonly maxPaths?: number;
  readonly maxDepth?: number;
}

LiteralNode

export interface LiteralNode {
  readonly kind: 'literal';
  readonly value: JsonPrimitive;
}

LockSet

export interface LockSet {
  readonly patterns: readonly string[];
  isLocked(path: readonly string[]): boolean;
}

MigrateOptions

export interface MigrateOptions {
  readonly registry?: MigrationRegistry;
  readonly target?: string;
  readonly limits?: Limits;
}

Migration

export interface Migration {
  readonly from: string;
  readonly to: string;
  readonly apply: (template: JsonObject) => JsonObject;
}

MigrationRegistry

export interface MigrationRegistry {
  register(migration: Migration): Diagnostic | undefined;
  from(version: string): Migration | undefined;
  list(): readonly Migration[];
}

MigrationResult

export interface MigrationResult {
  readonly template: JsonObject | undefined;
  readonly applied: readonly AppliedMigration[];
  readonly diagnostics: readonly Diagnostic[];
}

NamedStyle

export interface NamedStyle {
  readonly style: Style;
  readonly enforceLocks: boolean;
  readonly pointer: string;
}

NodeBase

export interface NodeBase {
  readonly id: string;
  readonly name?: string;
  readonly style?: Style;
  readonly styleRef?: string;
  readonly styleWhen?: readonly StyleWhen[];
  readonly when?: Expr;
  readonly frame?: Frame;
  readonly width?: SizeSpec;
  readonly height?: SizeSpec;
  readonly break?: BreakSettings;
}

NormalizedLimits

export interface NormalizedLimits {
  readonly limits: Limits;
  readonly diagnostics: readonly Diagnostic[];
}

PageConfig

export interface PageConfig {
  readonly size?: PageSize;
  readonly orientation?: 'portrait' | 'landscape';
  readonly margins?: Spacing;
  readonly direction?: 'ltr' | 'rtl';
  readonly mode?: 'flow' | 'fixed';
  readonly background?: Color;
}

PageDimensions

export interface PageDimensions {
  readonly width: number;
  readonly height: number;
}

PageFurniture

export interface PageFurniture {
  readonly header?: PageRegion;
  readonly footer?: PageRegion;
}

PageNumberNode

export interface PageNumberNode extends NodeBase {
  readonly type: 'pageNumber';
  readonly format?: string;
}

PageRegion

export interface PageRegion {
  readonly height: number;
  readonly children: readonly TemplateNode[];
}

ParseOptions

export interface ParseOptions {
  readonly limits?: Limits;
  readonly basePath?: string;
}

ParseResult

export interface ParseResult {
  readonly expression: Expression | undefined;
  readonly diagnostics: readonly Diagnostic[];
}

PathExpr

export interface PathExpr {
  readonly path: string;
  readonly fallback?: Expr;
}

PathNode

export interface PathNode {
  readonly kind: 'path';
  readonly base: PathBase;
  readonly parents: number;
  readonly segments: readonly PathSegment[];
  readonly fallback: CompiledNode | undefined;
  readonly pointer: string;
  readonly source: string;
}

QrNode

export interface QrNode extends NodeBase {
  readonly type: 'qr';
  readonly value: Expr;
  readonly size?: number;
}

Rdt

export interface Rdt {
  readonly rdtVersion: typeof RDT_VERSION;
  readonly page: RdtPage;
  readonly header?: RdtRegion;
  readonly footer?: RdtRegion;
  readonly body: readonly RdtNode[];
}

RdtBarcode

export interface RdtBarcode extends RdtBase {
  readonly kind: 'barcode';
  readonly value: string;
  readonly format: 'code128' | 'code39' | 'ean13';
}

RdtBase

export interface RdtBase {
  readonly id: string;
  readonly name?: string;
  readonly style: ResolvedStyle;
  readonly width?: SizeSpec;
  readonly height?: SizeSpec;
  readonly frame?: Frame;
  readonly break?: BreakSettings;
}

RdtCell

export interface RdtCell {
  readonly text: string;
  readonly bound: boolean;
  readonly span?: number;
  readonly align?: Alignment;
  readonly style?: ResolvedStyle;
}

RdtColumn

export interface RdtColumn {
  readonly id: string;
  readonly header: string;
  readonly width?: ColumnWidth;
  readonly align?: Alignment;
  readonly style: ResolvedStyle;
  readonly headerStyle?: ResolvedStyle;
}

RdtContainerBase

export interface RdtContainerBase extends RdtBase {
  readonly children: readonly RdtNode[];
  readonly gap?: number;
  readonly align?: Alignment | 'stretch';
}

RdtDivider

export interface RdtDivider extends RdtBase {
  readonly kind: 'divider';
  readonly thickness?: number;
  readonly color?: string;
}

RdtFixed

export interface RdtFixed extends RdtContainerBase {
  readonly kind: 'fixed';
  readonly size: { readonly w: number; readonly h: number };
}

RdtFooterCell

export interface RdtFooterCell extends RdtCell {
  readonly span: number;
}

RdtFooterRow

export interface RdtFooterRow {
  readonly cells: readonly RdtFooterCell[];
  readonly style?: ResolvedStyle;
}

RdtGrid

export interface RdtGrid extends RdtContainerBase {
  readonly kind: 'grid';
  readonly columns: readonly TrackSpec[];
}

RdtImage

export interface RdtImage extends RdtBase {
  readonly kind: 'image';
  readonly src: string;
  readonly alt?: string;
  readonly fit?: 'contain' | 'cover' | 'fill' | 'none';
}

RdtPage

export interface RdtPage {
  readonly width: number;
  readonly height: number;
  readonly orientation: 'portrait' | 'landscape';
  readonly margins: SpacingBox;
  readonly direction: 'ltr' | 'rtl';
  readonly mode: 'flow' | 'fixed';
  readonly locale: string;
  readonly background?: string;
}

RdtPageNumber

export interface RdtPageNumber extends RdtBase {
  readonly kind: 'pageNumber';
  readonly format?: string;
}

RdtQr

export interface RdtQr extends RdtBase {
  readonly kind: 'qr';
  readonly value: string;
  readonly size?: number;
}

RdtRegion

export interface RdtRegion {
  readonly height: number;
  readonly children: readonly RdtNode[];
}

RdtRow

export interface RdtRow extends RdtContainerBase {
  readonly kind: 'row';
  readonly justify?: Alignment | 'between';
}

RdtRun

export interface RdtRun {
  readonly text: string;
  readonly bound: boolean;
}

RdtSection

export interface RdtSection extends RdtContainerBase {
  readonly kind: 'section';
}

RdtShape

export interface RdtShape extends RdtBase {
  readonly kind: 'shape';
  readonly shape: 'rect' | 'ellipse' | 'line';
  readonly fill?: string;
  readonly stroke?: string;
  readonly strokeWidth?: number;
  readonly radius?: number;
}

RdtStack

export interface RdtStack extends RdtContainerBase {
  readonly kind: 'stack';
}

RdtTable

export interface RdtTable extends RdtBase {
  readonly kind: 'table';
  readonly columns: readonly RdtColumn[];
  readonly headerStyle?: ResolvedStyle;
  readonly rows: readonly RdtTableRow[];
  readonly footer: readonly RdtFooterRow[];
  readonly repeatHeader: boolean;
  readonly zebra: boolean;
  readonly rowBreak: 'avoid' | 'auto';
  readonly emptyText?: string;
}

RdtTableRow

export interface RdtTableRow {
  readonly cells: readonly RdtCell[];
  readonly style?: ResolvedStyle;
}

RdtText

export interface RdtText extends RdtBase {
  readonly kind: 'text';
  readonly runs: readonly RdtRun[];
}

Registration

export interface Registration {
  readonly registered: boolean;
  readonly diagnostics: readonly Diagnostic[];
}

Registry

export interface Registry {
  get(type: string): ComponentDefinition | undefined;
  has(type: string): boolean;
  types(): readonly string[];
  register(definition: ComponentDefinition): boolean;
}

RepeaterNode

export interface RepeaterNode extends NodeBase {
  readonly type: 'repeater';
  readonly source: Expr;
  readonly as?: string;
  readonly children: readonly TemplateNode[];
  readonly empty?: readonly TemplateNode[];
}

ResolvedBorder

export interface ResolvedBorder {
  readonly width?: number;
  readonly color?: string;
  readonly style?: 'solid' | 'dashed' | 'dotted' | 'none';
  readonly radius?: number;
}

ResolvedStyle

export interface ResolvedStyle {
  readonly fontSize?: number;
  readonly fontWeight?: number | 'normal' | 'bold';
  readonly fontStyle?: 'normal' | 'italic';
  readonly fontFamily?: string;
  readonly color?: string;
  readonly background?: string;
  readonly textAlign?: 'start' | 'end' | 'center' | 'justify';
  readonly lineHeight?: number;
  readonly letterSpacing?: number;
  readonly padding?: SpacingBox;
  readonly margin?: SpacingBox;
  readonly border?: ResolvedBorder;
  readonly opacity?: number;
  readonly direction?: 'ltr' | 'rtl';
  readonly whiteSpace?: 'normal' | 'nowrap' | 'pre-wrap';
  readonly overflowWrap?: 'normal' | 'anywhere' | 'break-word';
  readonly textDecoration?: 'none' | 'underline' | 'line-through';
}

RowNode

export interface RowNode extends NodeBase {
  readonly type: 'row';
  readonly children: readonly TemplateNode[];
  readonly gap?: number;
  readonly align?: Alignment | 'stretch';
  readonly justify?: Alignment | 'between';
}

SchemaCheck

export interface SchemaCheck {
  readonly valid: boolean;
  readonly issues: readonly SchemaIssue[];
}

SchemaIssue

export interface SchemaIssue {
  readonly pointer: string;
  readonly keyword: string;
  readonly message: string;
}

SchemaValidator

export interface SchemaValidator {
  check(instance: unknown, maxIssues: number): SchemaCheck;
}

SchemaVersion

export interface SchemaVersion {
  readonly major: number;
  readonly minor: number;
  readonly patch: number;
}

Scope

export interface Scope {
  readonly root: JsonValue;
  readonly current: JsonValue;
  readonly parent?: Scope | undefined;
  readonly index?: number | undefined;
  readonly rows?: JsonValue[] | undefined;
  readonly props?: JsonValue | undefined;
}

SectionConfig

export interface SectionConfig {
  readonly direction?: 'ltr' | 'rtl';
  readonly tokens?: Readonly<Record<string, string | number>>;
  readonly style?: Style;
}

SectionEntry

export interface SectionEntry {
  readonly scope: ConfigScope;
  readonly diagnostics: readonly Diagnostic[];
}

SectionNode

export interface SectionNode extends NodeBase {
  readonly type: 'section';
  readonly children: readonly TemplateNode[];
  readonly config?: SectionConfig;
}

SemanticOptions

export interface SemanticOptions {
  readonly limits?: Limits;
  readonly registry?: Registry;
  readonly formatters?: ReadonlyMap<string, unknown>;
  readonly allowProps?: boolean;
  readonly allowSlots?: boolean;
}

ShapeNode

export interface ShapeNode extends NodeBase {
  readonly type: 'shape';
  readonly shape: 'rect' | 'ellipse' | 'line';
  readonly fill?: Color;
  readonly stroke?: Color;
  readonly strokeWidth?: number;
  readonly radius?: number;
}

StackNode

export interface StackNode extends NodeBase {
  readonly type: 'stack';
  readonly children: readonly TemplateNode[];
  readonly gap?: number;
  readonly align?: Alignment | 'stretch';
}

StructureOptions

export interface StructureOptions {
  readonly limits?: Limits;
  readonly validator?: SchemaValidator;
}

StructureResult

export interface StructureResult {
  readonly valid: boolean;
  readonly diagnostics: readonly Diagnostic[];
}

Style

export interface Style {
  readonly fontSize?: number | TokenRef;
  readonly fontWeight?: number | 'normal' | 'bold';
  readonly fontStyle?: 'normal' | 'italic';
  readonly fontFamily?: string | TokenRef;
  readonly color?: Color;
  readonly background?: Color;
  readonly textAlign?: 'start' | 'end' | 'center' | 'justify';
  readonly lineHeight?: number;
  readonly letterSpacing?: number;
  readonly padding?: Spacing;
  readonly margin?: Spacing;
  readonly border?: Border;
  readonly opacity?: number;
  readonly direction?: 'ltr' | 'rtl';
  readonly whiteSpace?: 'normal' | 'nowrap' | 'pre-wrap';
  readonly overflowWrap?: 'normal' | 'anywhere' | 'break-word';
  readonly textDecoration?: 'none' | 'underline' | 'line-through';
}

StyleContext

export interface StyleContext {
  readonly tokens: TokenMap;
  readonly locks: LockSet;
  readonly enforceLocks: boolean;
  readonly diagnostics: Diagnostic[];
}

StyledNode

export interface StyledNode {
  readonly style?: Style | undefined;
  readonly styleRef?: string | undefined;
  readonly styleWhen?: readonly StyleWhen[] | undefined;
}

StyleResolution

export interface StyleResolution {
  readonly style: ResolvedStyle;
  readonly diagnostics: readonly Diagnostic[];
}

StyleResolver

export interface StyleResolver {
  resolve(node: StyledNode, pointer: string, evaluate: ConditionEvaluator): StyleResolution;
}

StyleWhen

export interface StyleWhen {
  readonly when: Expr;
  readonly style: Style;
}

TableBodyRow

export interface TableBodyRow {
  readonly cells: readonly TableCell[];
  readonly style?: Style;
}

TableCell

export interface TableCell {
  readonly text?: string;
  readonly expr?: Expr;
  readonly span?: number;
  readonly align?: Alignment;
  readonly style?: Style;
}

TableColumn

export interface TableColumn {
  readonly id: string;
  readonly header: string;
  readonly cell?: Expr;
  readonly width?: ColumnWidth;
  readonly align?: Alignment;
  readonly visible?: Expr;
  readonly style?: Style;
  readonly headerStyle?: Style;
}

TableEmptyState

export interface TableEmptyState {
  readonly mode: 'hide' | 'message' | 'showHeader';
  readonly text?: string;
}

TableFooterRow

export interface TableFooterRow {
  readonly cells: readonly TableFooterCell[];
  readonly style?: Style;
}

TableNode

export interface TableNode extends NodeBase {
  readonly type: 'table';
  readonly source?: Expr;
  readonly columns: readonly TableColumn[];
  readonly headerStyle?: Style;
  readonly rows?: readonly TableBodyRow[];
  readonly footer?: readonly TableFooterRow[];
  readonly repeatHeader?: boolean;
  readonly zebra?: boolean;
  readonly emptyState?: TableEmptyState;
  readonly rowBreak?: 'avoid' | 'auto';
}

Template

export interface Template {
  readonly schemaVersion: string;
  readonly id?: string;
  readonly name?: string;
  readonly description?: string;
  readonly config?: TemplateConfig;
  readonly styles?: Readonly<Record<string, Style>>;
  readonly imports?: readonly ImportRef[];
  readonly page?: PageFurniture;
  readonly body: readonly TemplateNode[];
}

TemplateConfig

export interface TemplateConfig {
  readonly page?: PageConfig;
  readonly locale?: string;
  readonly missingData?: 'blank' | 'placeholder' | 'warn' | 'error';
  readonly tokens?: Readonly<Record<string, string | number>>;
  readonly theme?: string;
}

TemplateValidation

export interface TemplateValidation {
  readonly valid: boolean;
  readonly template: Template | undefined;
  readonly diagnostics: readonly Diagnostic[];
}

TextNode

export interface TextNode extends NodeBase {
  readonly type: 'text';
  readonly content: readonly Expr[];
}

TextResult

export interface TextResult {
  readonly text: string;
  readonly state: BindingState;
  readonly failed: boolean;
}

TokenRef

export interface TokenRef {
  readonly token: string;
}

TraceEntry

export interface TraceEntry {
  readonly pointer: string;
  readonly label: string;
  readonly kind: 'literal' | 'path' | 'call';
  readonly valueType: ValueType;
  readonly state: BindingState;
  readonly usedFallback: boolean;
  readonly outcome: BindingOutcome;
  readonly preview: string;
}