api #

utility belt for JS

51 modules ยท 415 declarations

Modules
#

Args
#

args.ts view source

Args

CLI arguments container. Positional arguments stored in _, named flags/options as string keys. Produced by argv_parse or external parsers (mri, minimist, etc.).

_

type Array<string>

args_extract_aliases
#

args.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): ArgsAliasesResult

Extracts alias mappings and canonical keys from a zod schema's metadata.

Useful for consumers building custom tooling (help generators, conflict detection, etc.). Results are cached per schema (WeakMap).

Note: Returns copies of the cached data to prevent mutation of internal cache.

schema

Zod object schema with optional .meta({aliases}) on fields

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

ArgsAliasesResult

Object with aliases map and canonical_keys set

args_parse
#

args.ts view source

<TOutput extends Record<string, ArgValue> = Args>(unparsed_args: Args, schema: ZodType<TOutput, unknown, $ZodTypeInternals<TOutput, unknown>>): ZodSafeParseResult<...>

Validates parsed CLI args against a zod schema.

Handles CLI-specific concerns before validation: 1. Validates schema (cached) - returns error if alias conflicts exist 2. Expands aliases defined in schema .meta({aliases: ['v']}) 3. Strips alias keys (required for strictObject schemas) 4. Validates with zod 5. After validation, syncs no- prefixed boolean flags with their base keys

Schema analysis is cached per schema (WeakMap) for performance.

unparsed_args

Args object from CLI parser (mri, minimist, etc.)

type Args

schema

Zod object schema with optional alias metadata

type ZodType<TOutput, unknown, $ZodTypeInternals<TOutput, unknown>>

returns

ZodSafeParseResult<TOutput>

Zod SafeParseResult with expanded/synced data on success

args_serialize
#

args.ts view source

(args: Args, schema?: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined): string[]

Serializes Args to CLI string array for subprocess forwarding.

Handles CLI conventions: - Positionals first, then flags - Single-char keys get single dash, multi-char get double dash - Boolean true becomes bare flag, false is skipped - undefined values are skipped - no- prefixed keys skipped when base key is truthy (avoid contradiction) - When schema provided, extracts aliases and prefers shortest form

Schema analysis is cached per schema (WeakMap) for performance.

args

Args object to serialize

type Args

schema?

Optional zod schema to extract aliases for short form preference

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined
optional

returns

string[]

Array of CLI argument strings

args_validate_schema
#

args.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): { success: true; } | { success: false; error: ZodError<unknown>; }

Validates a zod schema for CLI arg usage.

Checks for: - Alias conflicts with canonical keys - Duplicate aliases across different keys

Results are cached per schema (WeakMap). Safe to call multiple times.

schema

Zod object schema with optional alias metadata

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

{ success: true; } | { success: false; error: ZodError<unknown>; }

Validation result with success flag and optional error

ArgsAliasesResult
#

args.ts view source

ArgsAliasesResult

Result of alias extraction from a schema. Includes canonical keys for downstream conflict detection.

aliases

type Map<string, string>

canonical_keys

type Set<string>

ArgSchema
#

args.ts view source

ArgSchema

Schema description for help text generation. Not used by args_parse/args_serialize directly - provided for consumers building CLI help output.

type

type string

default

description

type string

argv_parse
#

args.ts view source

(argv: string[]): ParsedArgs

Parses raw CLI argv array into an Args object.

A lightweight, dependency-free alternative to mri/minimist with compatible behavior.

Features: - --flag โ†’ {flag: true} - --flag value โ†’ {flag: 'value'} or {flag: 123} (numeric coercion) - --flag=value โ†’ equals syntax - --flag= โ†’ {flag: ''} (empty string, differs from mri which returns true) - -f โ†’ {f: true} (short flag) - -f value โ†’ {f: 'value'} - -abc โ†’ {a: true, b: true, c: true} (combined short flags) - -abc value โ†’ {a: true, b: true, c: 'value'} (last flag gets value) - --no-flag โ†’ {flag: false} (negation prefix) - -- โ†’ stops flag parsing, rest become positionals - Positionals collected in _ array - Repeated flags become arrays

Intentional differences from mri: - --flag= returns '' (mri returns true) - --flag= next returns {flag: '', _: ['next']} (mri takes next as the value) - ---flag returns {'-flag': true} (mri strips all dashes) - ['--flag', ''] preserves '' (mri coerces to 0) - --__proto__ works as a normal key (mri silently fails)

The returned object uses Object.create(null) to prevent prototype pollution and allow any key name including __proto__ and constructor.

argv

Raw argument array (typically process.argv.slice(2))

type string[]

returns

ParsedArgs

Parsed Args object with guaranteed _ array (null prototype)

ArgValue
#

ArrayElement
#

Assignable
#

AsyncSemaphore
#

async.ts view source

Async semaphore for concurrency limiting.

With Infinity permits, acquire() always resolves immediately.

constructor

type new (permits: number): AsyncSemaphore

permits
type number

acquire

type (): Promise<void>

returns Promise<void>

release

type (): void

returns void

AsyncStatus
#

attach_process_error_handler
#

process.ts view source

(options?: { to_error_label?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; map_error_text?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; handle_error?: ((err: Error, origin: UncaughtExceptionOrigin) => void) | undefined; graceful_timeout_ms?: number | ... 1 more ... | undefined; } | undefined): () => void

Attaches an uncaughtException handler to the default registry.

options?

type { to_error_label?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; map_error_text?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; handle_error?: ((err: Error, origin: UncaughtExceptionOrigin) => void) | undefined; graceful_timeout_ms?: number | ... 1 more...
optional

returns

() => void

see also

  • ProcessRegistry.attach_error_handler

Benchmark
#

benchmark.ts view source

Benchmark class for measuring and comparing function performance.

constructor

type new (config?: BenchmarkConfig): Benchmark

config
default {}

add

Add a benchmark task.

type (name: string, fn: () => unknown): this

name

Task name or full task object

type string
fn

Function to benchmark (if name is string). Return values are ignored.

type () => unknown
returns this

This Benchmark instance for chaining

add

type (name: string, fn: () => unknown): this

name
type string
fn
type () => unknown
returns this

add

type (name: string, fn: () => unknown): this

name
type string
fn
type () => unknown
returns this

remove

Remove a benchmark task by name.

type (name: string): this

name

Name of the task to remove

type string
returns this

This Benchmark instance for chaining

throws
  • Error - if task with given name doesn't exist

skip

Mark a task to be skipped during benchmark runs.

type (name: string): this

name

Name of the task to skip

type string
returns this

This Benchmark instance for chaining

throws
  • Error - if task with given name doesn't exist

only

Mark a task to run exclusively (along with other only tasks).

type (name: string): this

name

Name of the task to run exclusively

type string
returns this

This Benchmark instance for chaining

throws
  • Error - if task with given name doesn't exist

run

Run all benchmark tasks.

type (): Promise<BenchmarkResult[]>

returns Promise<BenchmarkResult[]>

Array of benchmark results

table

Format results as an ASCII table with percentiles, min/max, and relative performance.

type (options?: BenchmarkFormatTableOptions | undefined): string

options?

Formatting options

type BenchmarkFormatTableOptions | undefined
optional
returns string

Formatted table string

markdown

Format results as a Markdown table.

type (options?: BenchmarkFormatTableOptions | undefined): string

options?

Formatting options (groups for organized output with optional baselines)

type BenchmarkFormatTableOptions | undefined
optional
returns string

Formatted markdown string

json

Format results as JSON.

type (options?: BenchmarkFormatJsonOptions | undefined): string

options?

Formatting options (pretty, include_timings)

type BenchmarkFormatJsonOptions | undefined
optional
returns string

JSON string

results

Get the benchmark results. Returns a shallow copy to prevent external mutation.

type (): BenchmarkResult[]

returns BenchmarkResult[]

Array of benchmark results

results_by_name

Get results as a map for convenient lookup by task name. Returns a new Map each call to prevent external mutation.

type (): Map<string, BenchmarkResult>

returns Map<string, BenchmarkResult>

Map of task name to benchmark result

reset

Reset the benchmark results. Keeps tasks intact so benchmarks can be rerun.

type (): this

returns this

This Benchmark instance for chaining

clear

Clear everything (results and tasks). Use this to start fresh with a new set of benchmarks.

type (): this

returns this

This Benchmark instance for chaining

summary

Get a quick text summary of the fastest task.

type (): string

returns string

Human-readable summary string

benchmark_baseline_compare
#

benchmark_baseline.ts view source

(results: BenchmarkResult[], options?: BenchmarkBaselineCompareOptions): Promise<BenchmarkBaselineComparisonResult>

Compare benchmark results against the stored baseline.

results

Current benchmark results

type BenchmarkResult[]

options

Comparison options including regression threshold and staleness warning

default {}

returns

Promise<BenchmarkBaselineComparisonResult>

Comparison result with regressions, improvements, and unchanged tasks

examples

const bench = new Benchmark(); bench.add('test', () => fn()); await bench.run(); const comparison = await benchmark_baseline_compare(bench.results(), { regression_threshold: 1.05, // Only flag regressions 5% or more slower staleness_warning_days: 7, // Warn if baseline is older than 7 days }); if (comparison.regressions.length > 0) { console.log('Performance regressions detected!'); for (const r of comparison.regressions) { console.log(` ${r.name}: ${r.comparison.speedup_ratio.toFixed(2)}x slower`); } process.exit(1); }

benchmark_baseline_format
#

benchmark_baseline_format_json
#

benchmark_baseline.ts view source

(result: BenchmarkBaselineComparisonResult, options?: { pretty?: boolean | undefined; }): string

Format a baseline comparison result as JSON for programmatic consumption.

result

Comparison result from benchmark_baseline_compare

options

Formatting options

type { pretty?: boolean | undefined; }
default {}

returns

string

JSON string

benchmark_baseline_load
#

benchmark_baseline.ts view source

(options?: BenchmarkBaselineLoadOptions): Promise<{ version: number; timestamp: string; git_commit: string | null; git_branch: string | null; node_version: string; entries: { ...; }[]; } | null>

Load the current baseline from disk.

options

Load options

default {}

returns

Promise<{ version: number; timestamp: string; git_commit: string | null; git_branch: string | null; node_version: string; entries: { name: string; mean_ns: number; p50_ns: number; std_dev_ns: number; ... 7 more ...; sample_size: number; }[]; } | null>

The baseline, or null if not found or invalid

examples

const baseline = await benchmark_baseline_load(); if (baseline) { console.log(`Baseline from ${baseline.timestamp}`); }

benchmark_baseline_save
#

benchmark_baseline.ts view source

(results: BenchmarkResult[], options?: BenchmarkBaselineSaveOptions): Promise<void>

Save benchmark results as the current baseline.

results

Benchmark results to save

type BenchmarkResult[]

options

Save options

default {}

returns

Promise<void>

examples

const bench = new Benchmark(); bench.add('test', () => fn()); await bench.run(); await benchmark_baseline_save(bench.results());

benchmark_format_json
#

benchmark_format.ts view source

(results: BenchmarkResult[], options?: BenchmarkFormatJsonOptions | undefined): string

Format results as JSON.

results

Array of benchmark results

type BenchmarkResult[]

options?

Formatting options

type BenchmarkFormatJsonOptions | undefined
optional

returns

string

JSON string

examples

console.log(format_json(results)); console.log(format_json(results, {pretty: false})); console.log(format_json(results, {include_timings: true}));

benchmark_format_markdown
#

benchmark_format.ts view source

(results: BenchmarkResult[], baseline?: string | undefined): string

Format results as a Markdown table with key metrics. All times use the same unit for easy comparison.

results

Array of benchmark results

type BenchmarkResult[]

baseline?

Optional task name to use as baseline for comparison (defaults to fastest)

type string | undefined
optional

returns

string

Formatted markdown table string

examples

console.log(benchmark_format_markdown(results)); // | Task Name | ops/sec | p50 (ฮผs) | p75 (ฮผs) | p90 (ฮผs) | p95 (ฮผs) | p99 (ฮผs) | min (ฮผs) | max (ฮผs) | vs Best | // |------------|------------|----------|----------|----------|----------|----------|----------|----------|----------| // | slugify v2 | 1,237,144 | 0.81 | 0.85 | 0.89 | 0.95 | 1.20 | 0.72 | 2.45 | baseline | // | slugify | 261,619 | 3.82 | 3.95 | 4.12 | 4.35 | 5.10 | 3.21 | 12.45 | 4.73x |

benchmark_format_markdown_grouped
#

benchmark_format.ts view source

(results: BenchmarkResult[], groups: BenchmarkGroup[]): string

Format results as grouped Markdown tables with headers between groups.

results

Array of benchmark results

type BenchmarkResult[]

groups

Array of group definitions

type BenchmarkGroup[]

returns

string

Formatted markdown string with group headers and tables

examples

const groups = [ { name: 'Fast Paths', filter: (r) => r.name.includes('fast'), baseline: 'fast/reference' }, { name: 'Slow Paths', filter: (r) => r.name.includes('slow') }, ]; console.log(benchmark_format_markdown_grouped(results, groups)); // ### Fast Paths // | Task Name | ops/sec | ... | vs fast/reference | // |-----------|---------|-----|-------------------| // | ... | ... | ... | ... | // // ### Slow Paths // | Task Name | ops/sec | ... | vs Best | // |-----------|---------|-----|---------| // | ... | ... | ... | ... |

benchmark_format_number
#

benchmark_format.ts view source

(n: number, decimals?: number) => string

Format a number with fixed decimal places and thousands separators.

see also

  • {@link format_number} in maths.ts for the underlying implementation.

benchmark_format_table
#

benchmark_format.ts view source

(results: BenchmarkResult[], baseline?: string | undefined): string

Format results as an ASCII table with percentiles, min/max, and relative performance. All times use the same unit for easy comparison.

results

Array of benchmark results

type BenchmarkResult[]

baseline?

Optional task name to use as baseline for comparison (defaults to fastest)

type string | undefined
optional

returns

string

Formatted table string with enhanced metrics

examples

console.log(benchmark_format_table(results)); // โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” // โ”‚ Task Name โ”‚ ops/sec โ”‚ p50 (ฮผs) โ”‚ p75 (ฮผs) โ”‚ p90 (ฮผs) โ”‚ p95 (ฮผs) โ”‚ p99 (ฮผs) โ”‚ min (ฮผs) โ”‚ max (ฮผs) โ”‚ vs Best โ”‚ // โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค // โ”‚ slugify v2 โ”‚ 1,237,144 โ”‚ 0.81 โ”‚ 0.85 โ”‚ 0.89 โ”‚ 0.95 โ”‚ 1.20 โ”‚ 0.72 โ”‚ 2.45 โ”‚ baseline โ”‚ // โ”‚ slugify โ”‚ 261,619 โ”‚ 3.82 โ”‚ 3.95 โ”‚ 4.12 โ”‚ 4.35 โ”‚ 5.10 โ”‚ 3.21 โ”‚ 12.45 โ”‚ 4.73x โ”‚ // โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

benchmark_format_table_grouped
#

benchmark_format.ts view source

(results: BenchmarkResult[], groups: BenchmarkGroup[]): string

Format results as a grouped table with visual separators between groups.

results

Array of benchmark results

type BenchmarkResult[]

groups

Array of group definitions

type BenchmarkGroup[]

returns

string

Formatted table string with group separators

examples

const groups = [ { name: 'FAST PATHS', filter: (r) => r.name.includes('fast') }, { name: 'SLOW PATHS', filter: (r) => r.name.includes('slow') }, ]; console.log(benchmark_format_table_grouped(results, groups)); // ๐Ÿ“ฆ FAST PATHS // โ”Œโ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌ...โ” // โ”‚ ๐Ÿ† โ”‚ fast test 1 โ”‚ 1,237,144 โ”‚...โ”‚ // โ”‚ ๐Ÿ‡ โ”‚ fast test 2 โ”‚ 261,619 โ”‚...โ”‚ // โ””โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ด...โ”˜ // // ๐Ÿ“ฆ SLOW PATHS // โ”Œโ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌ...โ” // โ”‚ ๐Ÿข โ”‚ slow test 1 โ”‚ 10,123 โ”‚...โ”‚ // โ””โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ด...โ”˜

benchmark_stats_compare
#

benchmark_stats.ts view source

(a: BenchmarkStatsComparable, b: BenchmarkStatsComparable, options?: BenchmarkCompareOptions | undefined): BenchmarkComparison

Compare two benchmark results for statistical significance. Uses Welch's t-test (handles unequal variances) and Cohen's d effect size.

a

First benchmark stats (or any object with required properties)

b

Second benchmark stats (or any object with required properties)

options?

Comparison options

type BenchmarkCompareOptions | undefined
optional

returns

BenchmarkComparison

Comparison result with significance, effect size, and recommendation

examples

const comparison = benchmark_stats_compare(result_a.stats, result_b.stats); if (comparison.significant) { console.log(`${comparison.faster} is ${comparison.speedup_ratio.toFixed(2)}x faster`); }

benchmark_warmup
#

benchmark.ts view source

(fn: () => unknown, iterations: number, async_hint?: boolean | undefined): Promise<boolean>

Warmup function by running it multiple times. Detects whether the function is async based on return value.

fn

Function to warmup (sync or async)

type () => unknown

iterations

Number of warmup iterations

type number

async_hint?

If provided, use this instead of detecting

type boolean | undefined
optional

returns

Promise<boolean>

Whether the function is async

examples

const is_async = await benchmark_warmup(() => expensive_operation(), 10);

BenchmarkBaseline
#

benchmark_baseline.ts view source

ZodObject<{ version: ZodNumber; timestamp: ZodString; git_commit: ZodNullable<ZodString>; git_branch: ZodNullable<ZodString>; node_version: ZodString; entries: ZodArray<...>; }, $strip>

Schema for the complete baseline file.

BenchmarkBaselineCompareOptions
#

benchmark_baseline.ts view source

BenchmarkBaselineCompareOptions

Options for comparing against a baseline.

inheritance

regression_threshold

Minimum speedup ratio to consider a regression. For example, 1.05 means only flag regressions that are 5% or more slower. Default: 1.0 (any statistically significant slowdown is a regression)

type number

staleness_warning_days

Number of days after which to warn about stale baseline. Default: undefined (no staleness warning)

type number

BenchmarkBaselineComparisonResult
#

benchmark_baseline.ts view source

BenchmarkBaselineComparisonResult

Result of comparing current results against a baseline.

baseline_found

Whether a baseline was found

type boolean

baseline_timestamp

Timestamp of the baseline

type string | null

baseline_commit

Git commit of the baseline

type string | null

baseline_age_days

Age of the baseline in days

type number | null

baseline_stale

Whether the baseline is considered stale based on staleness_warning_days option

type boolean

comparisons

Individual task comparisons

type Array<BenchmarkBaselineTaskComparison>

regressions

Tasks that regressed (slower with statistical significance), sorted by effect size (largest first)

type Array<BenchmarkBaselineTaskComparison>

improvements

Tasks that improved (faster with statistical significance), sorted by effect size (largest first)

type Array<BenchmarkBaselineTaskComparison>

unchanged

Tasks with no significant change

type Array<BenchmarkBaselineTaskComparison>

new_tasks

Tasks in current run but not in baseline

type Array<string>

removed_tasks

Tasks in baseline but not in current run

type Array<string>

BenchmarkBaselineEntry
#

benchmark_baseline.ts view source

ZodObject<{ name: ZodString; mean_ns: ZodNumber; p50_ns: ZodNumber; std_dev_ns: ZodNumber; min_ns: ZodNumber; max_ns: ZodNumber; ... 5 more ...; sample_size: ZodNumber; }, $strip>

Schema for a single benchmark entry in the baseline.

BenchmarkBaselineLoadOptions
#

benchmark_baseline.ts view source

BenchmarkBaselineLoadOptions

Options for loading a baseline.

path

Directory to load baseline from (default: '.gro/benchmarks')

type string

BenchmarkBaselineSaveOptions
#

benchmark_baseline.ts view source

BenchmarkBaselineSaveOptions

Options for saving a baseline.

path

Directory to store baselines (default: '.gro/benchmarks')

type string

git_commit

Git commit hash (auto-detected if not provided)

type string | null

git_branch

Git branch name (auto-detected if not provided)

type string | null

BenchmarkBaselineTaskComparison
#

BenchmarkCompareOptions
#

benchmark_stats.ts view source

BenchmarkCompareOptions

Options for benchmark comparison.

alpha

Significance level for hypothesis testing (default: 0.05)

type number

BenchmarkComparison
#

benchmark_stats.ts view source

BenchmarkComparison

Result from comparing two benchmark stats.

faster

Which benchmark is faster ('a', 'b', or 'equal' if difference is negligible)

type 'a' | 'b' | 'equal'

speedup_ratio

How much faster the winner is (e.g., 1.5 means 1.5x faster)

type number

significant

Whether the difference is statistically significant at the given alpha

type boolean

p_value

P-value from Welch's t-test (lower = more confident the difference is real)

type number

effect_size

Cohen's d effect size (magnitude of difference independent of sample size)

type number

effect_magnitude

Interpretation of effect size

ci_overlap

Whether the 95% confidence intervals overlap

type boolean

recommendation

Human-readable interpretation of the comparison

type string

BenchmarkConfig
#

benchmark_types.ts view source

BenchmarkConfig

Configuration options for a benchmark suite.

duration_ms

Target duration to run each benchmark task in milliseconds. The benchmark will run until this duration is reached or max_iterations is hit. Default: 1000ms

type number

warmup_iterations

Number of warmup iterations before actual measurements. Warmup helps stabilize JIT compilation and caches. Default: 5

type number

cooldown_ms

Cooldown time between tasks in milliseconds. Helps prevent interference between benchmarks. Default: 100ms

type number

min_iterations

Minimum number of iterations to run. Default: 10

type number

max_iterations

Maximum number of iterations to run. Prevents infinite loops if function is extremely fast. Default: 100000

type number

timer

Custom timer to use for measurements. Default: timer_default (auto-detects environment)

type Timer

on_iteration

Callback invoked after each iteration completes. Useful for triggering garbage collection, logging progress, early termination, or custom instrumentation.

Note: The callback time is NOT included in iteration measurements - it runs after the timing capture. However, frequent GC calls will slow overall benchmark execution time.

type (task_name: string, iteration: number, abort: () => void) => void

on_task_complete

Callback invoked after each task completes. Useful for logging progress during long benchmark runs.

type (result: BenchmarkResult, index: number, total: number) => void

BenchmarkFormatJsonOptions
#

benchmark_format.ts view source

BenchmarkFormatJsonOptions

pretty

Whether to pretty-print (default: true)

type boolean

include_timings

Whether to include raw timings array (default: false, can be large)

type boolean

BenchmarkFormatTableOptions
#

benchmark_types.ts view source

BenchmarkFormatTableOptions

Options for table formatting.

groups

Group results by category using filter functions.

type Array<BenchmarkGroup>

BenchmarkGroup
#

benchmark_types.ts view source

BenchmarkGroup

A group definition for organizing benchmark results.

name

Display name for the group

type string

description

Optional description shown below the group name

type string

filter

Filter function to determine which results belong to this group

type (result: BenchmarkResult) => boolean

baseline

Task name to use as baseline for the "vs" column. When specified, ratios are computed against this task instead of the fastest. If the baseline task is not found in the group, falls back to "vs Best" with a warning.

type string

BenchmarkResult
#

benchmark_types.ts view source

BenchmarkResult

Result from running a single benchmark task.

name

Task name

type string

stats

Statistical analysis of the benchmark

iterations

Number of iterations executed

type number

total_time_ms

Total time spent benchmarking (including warmup) in milliseconds

type number

timings_ns

Raw timing data for each iteration in nanoseconds. Useful for custom statistical analysis, histogram generation, or exporting to external tools.

type Array<number>

BenchmarkStats
#

benchmark_stats.ts view source

Complete statistical analysis of timing measurements. Includes outlier detection, descriptive statistics, and performance metrics. All timing values are in nanoseconds.

mean_ns

Mean (average) time in nanoseconds

type number

readonly

p50_ns

50th percentile (median) time in nanoseconds

type number

readonly

std_dev_ns

Standard deviation in nanoseconds

type number

readonly

min_ns

Minimum time in nanoseconds

type number

readonly

max_ns

Maximum time in nanoseconds

type number

readonly

p75_ns

75th percentile in nanoseconds

type number

readonly

p90_ns

90th percentile in nanoseconds

type number

readonly

p95_ns

95th percentile in nanoseconds

type number

readonly

p99_ns

99th percentile in nanoseconds

type number

readonly

cv

Coefficient of variation (std_dev / mean)

type number

readonly

confidence_interval_ns

95% confidence interval for the mean in nanoseconds

type [number, number]

readonly

outliers_ns

Array of detected outlier values in nanoseconds

type Array<number>

readonly

outlier_ratio

Ratio of outliers to total samples

type number

readonly

sample_size

Number of samples after outlier removal

type number

readonly

raw_sample_size

Original number of samples (before outlier removal)

type number

readonly

ops_per_second

Operations per second (NS_PER_SEC / mean_ns)

type number

readonly

failed_iterations

Number of failed iterations (NaN, Infinity, or negative values)

type number

readonly

constructor

type new (timings_ns: number[]): BenchmarkStats

timings_ns
type number[]

toString

Format stats as a human-readable string.

type (): string

returns string

BenchmarkStatsComparable
#

benchmark_stats.ts view source

BenchmarkStatsComparable

Minimal stats interface for comparison. This allows comparing stats from different sources (e.g., loaded baselines).

mean_ns

type number

std_dev_ns

type number

sample_size

type number

confidence_interval_ns

type [number, number]

BenchmarkTask
#

benchmark_types.ts view source

BenchmarkTask

A benchmark task to execute.

name

Name of the task (for display)

type string

fn

Function to benchmark (sync or async). Return values are ignored.

type () => unknown

setup

Optional setup function run before benchmarking this task. Not included in timing measurements.

type () => void | Promise<void>

teardown

Optional teardown function run after benchmarking this task. Not included in timing measurements.

type () => void | Promise<void>

skip

If true, skip this task during benchmark runs. Useful for temporarily disabling tasks during development.

type boolean

only

If true, run only this task (and other tasks marked only). Useful for focusing on specific tasks during development.

type boolean

async

Hint for whether the function is sync or async. If not provided, automatically detected during warmup. Setting this explicitly skips per-iteration promise checking for sync functions.

type boolean

blake3_ready
#

hash_blake3.ts view source

Promise<void>

Resolves when the BLAKE3 WASM module is initialized and ready. Initialization starts eagerly on import. Idempotent โ€” safe to await multiple times. In Node.js/Deno (sync init), this resolves immediately.

Blue
#

Brand
#

Branded
#

build_static_bindings
#

svelte_preprocess_helpers.ts view source

(ast: Root): Map<string, string>

Builds a map of statically resolvable const bindings from a Svelte AST.

Scans top-level const variable declarations in both instance and module scripts. For each declarator with a plain Identifier pattern and a statically evaluable initializer, adds the binding to the map. Processes declarations in source order so that chained references resolve: const a = 'x'; const b = a; maps b to 'x'.

Skips destructuring patterns, let/var declarations, and declarations whose initializers reference dynamic values.

ast

The parsed Svelte AST root node.

type Root

returns

Map<string, string>

Map of variable names to their resolved static string values.

clamp
#

maths.ts view source

(n: number, min: number, max: number): number

Returns n bounded to min and max.

n

type number

min

type number

max

type number

returns

number

ClassConstructor
#

types.ts view source

ClassConstructor<TInstance, TArgs>

generics

TInstance

TArgs

constraint Array<any>
default Array<any>

ClientIdCreator
#

compare_simple_map_entries
#

map.ts view source

(a: [any, any], b: [any, any]): number

Compares two map entries for sorting purposes. If the key is a string, it uses localeCompare for comparison. For other types, it uses >.

a

type [any, any]

b

type [any, any]

returns

number

ComponentPropInfo
#

source_json.ts view source

ZodObject<{ name: ZodString; type: ZodString; optional: ZodOptional<ZodBoolean>; description: ZodOptional<ZodString>; ... 6 more ...; since: ZodOptional<...>; }, $loose>

Component prop information for Svelte components.

Kept distinct from ParameterInfo despite structural similarity. Component props are named attributes with different semantics: no positional order when passing (<Foo {a} {b} /> = <Foo {b} {a} />), support two-way binding via $bindable rune.

ConditionalChainBranch
#

svelte_preprocess_helpers.ts view source

ConditionalChainBranch

A single branch in a conditional chain extracted from nested ternary expressions.

test_source

The source text of the test expression, or null for the final else branch.

type string | null

value

The resolved static string value for this branch.

type string

configure_print_colors
#

print.ts view source

(s: ((format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions | undefined) => string) | null | undefined): (format: ForegroundColors | ... 2 more ... | (ForegroundColors | ... 1 more ... | Modifiers)[], text: string, options?: StyleTextOptions | undefined) => string

Configures the module-level styling function for colored output.

s

type ((format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions | undefined) => string) | null | undefined

returns

(format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions | undefined) => string

count_graphemes
#

string.ts view source

(str: string): number

Returns the count of graphemes in a string, the individually rendered characters.

str

type string

returns

number

count_iterator
#

iterator.ts view source

(iterator: Iterable<unknown>): number

Useful for fast counting when .length is not available.

iterator

type Iterable<unknown>

returns

number

Counter
#

create_client_id_creator
#

id.ts view source

(name: string, count?: number | undefined, separator?: string): ClientIdCreator

Creates a string id generator function, outputting ${name}_${count} by default.

name

type string

count?

type number | undefined
optional

separator

type string
default '_'

returns

ClientIdCreator

create_counter
#

counter.ts view source

(initial?: number | undefined): Counter

Creates a counter constructor function, starting at 0.

initial?

type number | undefined
optional

returns

Counter

create_deferred
#

async.ts view source

<T>(): Deferred<T>

Creates an object with a promise and its resolve/reject handlers.

returns

Deferred<T>

create_random_alea
#

create_random_xoshiro
#

random_xoshiro.ts view source

(seed?: number | undefined): RandomXoshiro

Seeded pseudo-random number generator using the Xoshiro128** algorithm. DO NOT USE when security matters, use webcrypto APIs instead.

seed?

type number | undefined
optional

returns

RandomXoshiro

see also

create_stopwatch
#

timings.ts view source

(decimals?: number): Stopwatch

Tracks elapsed time in milliseconds.

decimals

type number
default 2

returns

Stopwatch

CreateCounter
#

DagNode
#

dag.ts view source

DagNode

Minimum shape for a DAG node.

inheritance

extends:

id

type string

depends_on

type Array<string>

DagNodeResult
#

dag.ts view source

DagNodeResult

Result for a single node.

id

type string

status

type 'completed' | 'failed' | 'skipped'

error

type string

duration_ms

type number

DagOptions
#

dag.ts view source

DagOptions<T>

Options for running a DAG.

generics

T

constraint DagNode

nodes

Nodes to execute.

type Array<T>

execute

Execute a node. Throw on failure.

type (node: T) => Promise<void>

on_error

Called after a node fails. For observability โ€” the error is already recorded.

type (node: T, error: Error) => Promise<void>

on_skip

Called when a node is skipped (pre-skip or dependency failure).

type (node: T, reason: string) => Promise<void>

should_skip

Return true to skip a node without executing. Dependents still proceed.

type (node: T) => boolean

max_concurrency

Maximum concurrent executions. Default: Infinity.

type number

stop_on_failure

Stop starting new nodes on first failure. Default: true.

type boolean

skip_validation

Skip internal graph validation (caller already validated).

type boolean

DagResult
#

dag.ts view source

DagResult

Result of a DAG execution.

success

Whether all executed nodes succeeded.

type boolean

results

Per-node results.

type Map<string, DagNodeResult>

completed

Number of nodes that completed successfully.

type number

failed

Number of nodes that failed.

type number

skipped

Number of nodes that were skipped.

type number

duration_ms

Total execution time in milliseconds.

type number

error

Error message if any nodes failed.

type string

declaration_generate_import
#

source_json.ts view source

โš ๏ธ deprecated: Use `generateImport` from `@fuzdev/svelte-docinfo/types.js` instead.

(declaration: { [x: string]: unknown; name: string; kind: "function" | "type" | "variable" | "class" | "constructor" | "component" | "json" | "css"; doc_comment?: string | undefined; type_signature?: string | undefined; ... 18 more ...; alias_of?: { ...; } | undefined; }, module_path: string, library_name: string): string

Generate TypeScript import statement for a declaration.

declaration

type { [x: string]: unknown; name: string; kind: "function" | "type" | "variable" | "class" | "constructor" | "component" | "json" | "css"; doc_comment?: string | undefined; type_signature?: string | undefined; ... 18 more ...; alias_of?: { ...; } | undefined; }

module_path

type string

library_name

type string

returns

string

examples

declaration_generate_import({name: 'Foo', kind: 'type'}, 'foo.ts', '@pkg/lib') // => "import type {Foo} from '@pkg/lib/foo.js';"

declaration_get_display_name
#

source_json.ts view source

โš ๏ธ deprecated: Use `getDisplayName` from `@fuzdev/svelte-docinfo/types.js` instead.

(declaration: { [x: string]: unknown; name: string; kind: "function" | "type" | "variable" | "class" | "constructor" | "component" | "json" | "css"; doc_comment?: string | undefined; type_signature?: string | undefined; ... 18 more ...; alias_of?: { ...; } | undefined; }): string

Format declaration name with generic parameters for display.

declaration

type { [x: string]: unknown; name: string; kind: "function" | "type" | "variable" | "class" | "constructor" | "component" | "json" | "css"; doc_comment?: string | undefined; type_signature?: string | undefined; ... 18 more ...; alias_of?: { ...; } | undefined; }

returns

string

examples

declaration_get_display_name({name: 'Map', kind: 'type', generic_params: [{name: 'K'}, {name: 'V'}]}) // => 'Map<K, V>'

DeclarationJson
#

source_json.ts view source

ZodObject<{ name: ZodString; kind: ZodEnum<{ function: "function"; type: "type"; variable: "variable"; class: "class"; constructor: "constructor"; component: "component"; json: "json"; css: "css"; }>; ... 20 more ...; alias_of: ZodOptional<...>; }, $loose>

Metadata for an exported declaration (function, type, class, component, etc.).

Extracted from TypeScript source and JSDoc/TSDoc comments at build time.

DeclarationKind
#

source_json.ts view source

ZodEnum<{ function: "function"; type: "type"; variable: "variable"; class: "class"; constructor: "constructor"; component: "component"; json: "json"; css: "css"; }>

The kind of exported declaration.

deep_equal
#

deep_equal.ts view source

(a: unknown, b: unknown): boolean

Deep equality comparison that checks both structure and type.

Key behaviors:

- Compares by constructor to prevent type confusion (security: {} โ‰  [], {} โ‰  new Map(), new ClassA() โ‰  new ClassB()) - Prevents asymmetry bugs: deep_equal(a, b) always equals deep_equal(b, a) - Compares only enumerable own properties (ignores prototypes, symbols, non-enumerable) - Special handling for: Date (timestamp), Number/Boolean (boxed primitives), Error (message/name) - Promises always return false (cannot be meaningfully compared) - Maps/Sets compare by reference for object keys/values

a

first value to compare

type unknown

b

second value to compare

type unknown

returns

boolean

true if deeply equal, false otherwise

Deferred
#

async.ts view source

Deferred<T>

A deferred object with a promise and its resolve/reject handlers.

generics

T

promise

type Promise<T>

resolve

type (value: T) => void

reject

type (reason: any) => void

Defined
#

deindent
#

string.ts view source

(str: string): string

Removes leading and trailing spaces from each line of a string.

str

type string

returns

string

deserialize_cache
#

fetch.ts view source

(serialized: string): Map<string, { key: string; url: string; params: any; value: any; etag: string | null; last_modified: string | null; }>

Converts a serialized cache string to a FetchValueCache.

serialized

type string

returns

Map<string, { key: string; url: string; params: any; value: any; etag: string | null; last_modified: string | null; }>

despawn
#

process.ts view source

(child: ChildProcess, options?: DespawnOptions | undefined): Promise<SpawnResult>

Kills a child process and returns the result.

child

type ChildProcess

options?

type DespawnOptions | undefined
optional

returns

Promise<SpawnResult>

examples

const result = await despawn(child, {timeout_ms: 5000}); // If process ignores SIGTERM, SIGKILL sent after 5s

despawn_all
#

process.ts view source

(options?: DespawnOptions | undefined): Promise<SpawnResult[]>

Kills all processes in the default registry.

options?

type DespawnOptions | undefined
optional

returns

Promise<SpawnResult[]>

DespawnOptions
#

process.ts view source

DespawnOptions

Options for killing processes.

signal

Signal to send.

type NodeJS.Signals

timeout_ms

Timeout in ms before escalating to SIGKILL. Must be non-negative. Useful for processes that may ignore SIGTERM. A value of 0 triggers immediate SIGKILL escalation.

type number

diff_lines
#

diff.ts view source

(a: string, b: string): DiffLine[]

Generate a line-based diff between two strings using LCS algorithm.

a

The original/current content.

type string

b

The new/desired content.

type string

returns

DiffLine[]

Array of diff lines with type annotations.

DiffLine
#

diff.ts view source

DiffLine

Line diff result

type

type 'same' | 'add' | 'remove'

line

type string

each_concurrent
#

async.ts view source

<T>(items: Iterable<T>, concurrency: number, fn: (item: T, index: number) => void | Promise<void>, signal?: AbortSignal | undefined): Promise<...>

Runs a function on each item with controlled concurrency. Like map_concurrent but doesn't collect results (more efficient for side effects).

items

items to process

type Iterable<T>

concurrency

maximum number of concurrent operations

type number

fn

function to apply to each item

type (item: T, index: number) => void | Promise<void>

signal?

optional AbortSignal to cancel processing

type AbortSignal | undefined
optional

returns

Promise<void>

examples

await each_concurrent( file_paths, 5, // max 5 concurrent deletions async (path) => { await unlink(path); }, );

EffectMagnitude
#

EMPTY_ARRAY
#

EMPTY_OBJECT
#

object.ts view source

Record<string | number | symbol, undefined> & object

Frozen empty object with no properties, good for options default values.

ensure_end
#

string.ts view source

(source: string, ensured: string): string

Adds the substring ensured to the end of the source string if it's not already present.

source

type string

ensured

type string

returns

string

ensure_start
#

string.ts view source

(source: string, ensured: string): string

Adds the substring ensured to the start of the source string if it's not already present.

source

type string

ensured

type string

returns

string

escape_js_string
#

string.ts view source

(value: string): string

Escapes a string for use inside a single-quoted JS string literal.

Uses a single-pass regex replacement to escape backslashes, single quotes, newlines, carriage returns, and Unicode line/paragraph separators.

value

type string

returns

string

escape_regexp
#

regexp.ts view source

(str: string): string

Escapes a string for literal matching in a RegExp.

str

type string

returns

string

escape_svelte_text
#

svelte_preprocess_helpers.ts view source

(text: string): string

Escapes text for safe embedding in Svelte template markup.

Uses a single-pass regex replacement to avoid corruption that occurs with sequential .replace() calls (where the second replace matches characters introduced by the first).

Escapes four characters: - { โ†’ {'{'} and } โ†’ {'}'} โ€” prevents Svelte expression interpretation - < โ†’ &lt; โ€” prevents HTML/Svelte tag interpretation - & โ†’ &amp; โ€” prevents HTML entity interpretation

The & escaping is necessary because runtime MdzNodeView.svelte renders text with {node.content} (a Svelte expression), which auto-escapes & to &amp;. The preprocessor emits raw template text where & is NOT auto-escaped, so manual escaping is required to match the runtime behavior.

text

type string

returns

string

evaluate_static_expr
#

svelte_preprocess_helpers.ts view source

(expr: Expression, bindings?: ReadonlyMap<string, string> | undefined): string | null

Recursively evaluates an expression AST node to a static string value.

Handles string Literal, TemplateLiteral (including interpolations when all expressions resolve), BinaryExpression with +, and Identifier lookup via an optional bindings map built by build_static_bindings. Returns null for dynamic expressions, non-string literals, or unsupported node types.

expr

An ESTree expression AST node.

type Expression

bindings?

Optional map of variable names to their resolved static string values.

type ReadonlyMap<string, string> | undefined
optional

returns

string | null

The resolved static string, or null if the expression is dynamic.

ExportValue
#

extract_static_string
#

svelte_preprocess_helpers.ts view source

(value: true | ExpressionTag | (ExpressionTag | Text)[], bindings?: ReadonlyMap<string, string> | undefined): string | null

Extracts a static string value from a Svelte attribute value AST node.

Handles three forms: - Boolean true (bare attribute like inline) -- returns null. - Array with a single Text node (quoted attribute like content="text") -- returns the text data. - ExpressionTag (expression like content={'text'}) -- delegates to evaluate_static_expr.

Returns null for null literals, mixed arrays, dynamic expressions, and non-string values.

value

The attribute value from AST.Attribute['value'].

type true | ExpressionTag | (ExpressionTag | Text)[]

bindings?

Optional map of variable names to their resolved static string values.

type ReadonlyMap<string, string> | undefined
optional

returns

string | null

The resolved static string, or null if the value is dynamic.

fetch_value
#

fetch.ts view source

<TValue = any, TParams = undefined>(url: string | URL, options?: FetchValueOptions<TValue, TParams> | undefined): Promise<Result<{ value: TValue; headers: Headers; }, { ...; }>>

Specializes fetch with some slightly different behavior and additional features:

- throws on ratelimit errors to mitigate unintentional abuse - optional parse function called on the return value - optional cache (different from the browser cache, the caller can serialize it so e.g. dev setups can avoid hitting the network) - optional simplified API for authorization and data types (you can still provide headers directly)

Unlike fetch, this throws on ratelimits (status code 429) to halt whatever is happpening in its tracks to avoid accidental abuse, but returns a Result in all other cases. Handling ratelimit headers with more sophistication gets tricky because behavior differs across services. (e.g. Mastodon returns an ISO string for x-ratelimit-reset, but GitHub returns Date.now()/1000, and other services may do whatever, or even use a different header)

It's also stateless to avoid the complexity and bugs, so we don't try to track x-ratelimit-remaining per domain.

If the value is cached, only the cached safe subset of the headers are returned. (currently just etag and last-modified) Otherwise the full res.headers are included.

url

type string | URL

options?

type FetchValueOptions<TValue, TParams> | undefined
optional

returns

Promise<Result<{ value: TValue; headers: Headers; }, { status: number; message: string; }>>

FetchValueCache
#

fetch.ts view source

ZodMap<ZodString, ZodObject<{ key: ZodString; url: ZodString; params: ZodAny; value: ZodAny; etag: ZodNullable<ZodString>; last_modified: ZodNullable<...>; }, $strip>>

FetchValueCacheItem
#

fetch.ts view source

ZodObject<{ key: ZodString; url: ZodString; params: ZodAny; value: ZodAny; etag: ZodNullable<ZodString>; last_modified: ZodNullable<ZodString>; }, $strip>

FetchValueCacheKey
#

FetchValueOptions
#

fetch.ts view source

FetchValueOptions<TValue, TParams>

generics

TValue

TParams

default undefined

request

The request.headers take precedence over the headers computed from other options.

type RequestInit

params

type TParams

parse

type (v: any) => TValue

token

type string | null

cache

type FetchValueCache | null

return_early_from_cache

type boolean

log

type Logger

fetch

type typeof globalThis.fetch

FileFilter
#

filter_diff_context
#

diff.ts view source

(diff: DiffLine[], context_lines?: number): DiffLine[]

Filter diff to only include lines within N lines of context around changes.

diff

The full diff lines.

type DiffLine[]

context_lines

Number of context lines to show around changes (default: 3).

type number
default 3

returns

DiffLine[]

Filtered diff with ellipsis markers for skipped regions.

find_attribute
#

svelte_preprocess_helpers.ts view source

(node: Component, name: string): Attribute | undefined

Finds an attribute by name on a component AST node.

Iterates the node's attributes array and returns the first Attribute node whose name matches. Skips SpreadAttribute, directive, and other node types.

node

The component AST node to search.

type Component

name

The attribute name to find.

type string

returns

Attribute | undefined

The matching Attribute node, or undefined if not found.

find_import_insert_position
#

svelte_preprocess_helpers.ts view source

(script: Script): number

Finds the position to insert new import statements within a script block.

Returns the end position of the last ImportDeclaration, or the start of the script body content if no imports exist.

script

The parsed AST.Script node.

type Script

returns

number

The character position where new imports should be inserted.

Flavor
#

Flavored
#

types.ts view source

Flavored<TValue, TName>

The Flavored and Branded type helpers add varying degrees of nominal typing to other types. This is especially useful with primitives like strings and numbers.

generics

TValue

TName

see also

  • https://spin.atomicobject.com/typescript-flexible-nominal-typing/ * Flavored is a looser form of Branded that trades explicitness and a little safety in some cases for ergonomics. With Flavored you don't need to cast unflavored types: * ``ts type Email = Flavored<string, 'Email'>; const email1: Email = 'foo'; // ok type Address = Flavored<string, 'Address'>; const email2: Email = 'foo' as Address; // error! `` * Branded requires casting: * ``ts type PhoneNumber = Branded<string, 'PhoneNumber'>; const phone1: PhoneNumber = 'foo'; // error! const phone2: PhoneNumber = 'foo' as PhoneNumber; // ok `` * See also Zod's .brand schema helper:

format_bytes
#

bytes.ts view source

(n: number): string

Formats a byte count as a human-readable string.

n

byte count.

type number

returns

string

formatted string like '1.2 KB' or '3.4 MB'.

format_diff
#

diff.ts view source

(diff: DiffLine[], current_path: string, desired_path: string, options?: FormatDiffOptions): string

Format a diff for display.

diff

The diff lines to format.

type DiffLine[]

current_path

Path label for "current" content.

type string

desired_path

Path label for "desired" content.

type string

options

Formatting options.

default {}

returns

string

Formatted diff string.

format_number
#

maths.ts view source

(n: number, decimals?: number): string

Format a number with fixed decimal places and thousands separators.

n

type number

decimals

type number
default 2

returns

string

format_url
#

url.ts view source

(url: string): string

Formats a URL by removing 'https://', 'www.', and trailing slashes. Notably it does not remove 'http://', so the user can see that it's insecure.

url

type string

returns

string

FormatDiffOptions
#

diff.ts view source

FormatDiffOptions

Format options for diff output.

prefix

Prefix for each line (for indentation in plan output).

type string

use_color

Whether to use ANSI colors.

type boolean

max_lines

Maximum number of diff lines to show (0 = unlimited).

type number

from_hex
#

hex.ts view source

(hex: string): Uint8Array<ArrayBufferLike> | null

Decodes a hex string to a Uint8Array. Whitespace is stripped before parsing. Returns null for invalid hex.

hex

Hex string to decode (case-insensitive, whitespace allowed).

type string

returns

Uint8Array<ArrayBufferLike> | null

Decoded bytes, or null if the input is not valid hex.

fs_empty_dir
#

fs.ts view source

(dir: string, should_remove?: ((name: string) => boolean) | undefined, options?: RmOptions | undefined): Promise<void>

Empties a directory, recursively by default. If should_remove is provided, only entries where it returns true are removed.

dir

type string

should_remove?

type ((name: string) => boolean) | undefined
optional

options?

type RmOptions | undefined
optional

returns

Promise<void>

fs_exists
#

fs.ts view source

(path: string): Promise<boolean>

Checks if a file or directory exists.

path

type string

returns

Promise<boolean>

fs_search
#

FsSearchOptions
#

fs.ts view source

FsSearchOptions

filter

One or more filter functions, any of which can short-circuit the search by returning false.

type PathFilter | Array<PathFilter>

file_filter

One or more file filter functions. Every filter must pass for a file to be included.

type FileFilter | Array<FileFilter>

sort

Pass null or false to speed things up at the cost of volatile ordering.

type boolean | null | ((a: ResolvedPath, b: ResolvedPath) => number)

include_directories

Set to true to include directories. Defaults to false.

type boolean

cwd

Sets the cwd for dir unless it's an absolute path or null.

type string | null

generate_diff
#

diff.ts view source

(current: string, desired: string, path: string, options?: FormatDiffOptions): string | null

Generate a formatted diff between two strings.

Combines diff_lines, filter_diff_context, and format_diff for convenience. Returns null if content is binary.

current

Current content.

type string

desired

Desired content.

type string

path

File path for labels.

type string

options

Formatting options.

default {}

returns

string | null

Formatted diff string, or null if binary.

generate_import_lines
#

svelte_preprocess_helpers.ts view source

(imports: Map<string, PreprocessImportInfo>, indent?: string): string

Generates indented import statement lines from an import map.

Default imports produce import Name from 'path'; lines. Named imports are grouped by path into import {a, b} from 'path'; lines.

imports

Map of local names to their import info.

type Map<string, PreprocessImportInfo>

indent

Indentation prefix for each line.

type string
default '\t'

returns

string

A string of newline-separated import statements.

GenericParamInfo
#

source_json.ts view source

ZodObject<{ name: ZodString; constraint: ZodOptional<ZodString>; default_type: ZodOptional<ZodString>; }, $loose>

Generic type parameter information.

git_check_clean_workspace
#

git.ts view source

(options?: SpawnOptions | undefined): Promise<string | null>

options?

type SpawnOptions | undefined
optional

returns

Promise<string | null>

an error message if the git workspace has any unstaged or uncommitted changes, or null if it's clean

git_check_fully_staged_workspace
#

git.ts view source

(options?: SpawnOptions | undefined): Promise<string | null>

options?

type SpawnOptions | undefined
optional

returns

Promise<string | null>

an error message if the git workspace has any unstaged changes or untracked files, or null if fully staged

git_check_setting_pull_rebase
#

git.ts view source

(options?: SpawnOptions | undefined): Promise<boolean>

Returns the global git config setting for pull.rebase.

options?

type SpawnOptions | undefined
optional

returns

Promise<boolean>

git_check_workspace
#

git.ts view source

(options?: SpawnOptions | undefined): Promise<GitWorkspaceStatus>

Checks the git workspace status using a single git status --porcelain -z call. The -z format provides more reliable parsing by using NUL separators and avoiding escaping.

options?

type SpawnOptions | undefined
optional

returns

Promise<GitWorkspaceStatus>

status object with flags for unstaged changes, staged changes, and untracked files

git_checkout
#

git.ts view source

(branch: GitBranch, options?: SpawnOptions | undefined): Promise<GitBranch | null>

Calls git checkout and throws if anything goes wrong.

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<GitBranch | null>

the previous branch name, if it changed

git_clone_locally
#

git.ts view source

(origin: GitOrigin, branch: GitBranch, source_dir: string, target_dir: string, options?: SpawnOptions | undefined): Promise<void>

Clones a branch locally to another directory and updates the origin to match the source.

origin

branch

source_dir

type string

target_dir

type string

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_current_branch_first_commit_hash
#

git.ts view source

(options?: SpawnOptions | undefined): Promise<string>

Returns the hash of the current branch's first commit or throws if something goes wrong.

options?

type SpawnOptions | undefined
optional

returns

Promise<string>

git_current_branch_name
#

git.ts view source

(options?: SpawnOptions | undefined): Promise<GitBranch>

Returns the current git branch name or throws if something goes wrong.

options?

type SpawnOptions | undefined
optional

returns

Promise<GitBranch>

git_current_commit_hash
#

git.ts view source

(branch?: string | undefined, options?: SpawnOptions | undefined): Promise<string | null>

Returns the branch's latest commit hash or throws if something goes wrong.

branch?

type string | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<string | null>

git_delete_local_branch
#

git.ts view source

(branch: GitBranch, options?: SpawnOptions | undefined): Promise<void>

Deletes a branch locally and throws if anything goes wrong.

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_delete_remote_branch
#

git.ts view source

(origin: GitOrigin, branch: GitBranch, options?: SpawnOptions | undefined): Promise<void>

Deletes a branch remotely and throws if anything goes wrong.

origin

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_fetch
#

git.ts view source

(origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<void>

Calls git fetch and throws if anything goes wrong.

origin

default 'origin' as GitOrigin

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_info_get
#

git.ts view source

(options?: SpawnOptions | undefined): Promise<GitInfo>

Get basic git info (commit hash and branch name) without throwing. Returns null values if git commands fail (e.g., not in a git repo).

options?

type SpawnOptions | undefined
optional

returns

Promise<GitInfo>

git_local_branch_exists
#

git.ts view source

(branch: GitBranch, options?: SpawnOptions | undefined): Promise<boolean>

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<boolean>

a boolean indicating if the local git branch exists

git_parse_workspace_status
#

git.ts view source

(stdout: string | null): GitWorkspaceStatus

Parses the output of git status --porcelain -z (v1 format) into a status object. This is a pure function that can be tested independently.

Format: XY path\0 where: - X = staged status (index) - Y = unstaged status (work tree) - path = file path (unescaped with -z)

Supported status codes: - M = modified - A = added - D = deleted - R = renamed - C = copied - T = type changed (regular file, symbolic link or submodule) - U = unmerged - ? = untracked - ! = ignored

For renames/copies: XY new\0old\0 (two NUL-separated paths)

Note: This implementation treats submodules the same as regular files. Submodule-specific status codes (lowercase m, ?) are interpreted as changes.

stdout

The raw output from git status --porcelain -z

type string | null

returns

GitWorkspaceStatus

status object with flags for unstaged changes, staged changes, and untracked files

git_pull
#

git.ts view source

(origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<void>

Calls git pull and throws if anything goes wrong.

origin

default 'origin' as GitOrigin

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_push
#

git.ts view source

(origin: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined, set_upstream?: boolean): Promise<void>

Calls git push and throws if anything goes wrong.

origin

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

set_upstream

type boolean
default false

returns

Promise<void>

git_push_to_create
#

git.ts view source

(origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<void>

Calls git push and throws if anything goes wrong.

origin

default 'origin' as GitOrigin

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_remote_branch_exists
#

git.ts view source

(origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<boolean>

origin

default 'origin' as GitOrigin

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<boolean>

a boolean indicating if the remote git branch exists

git_reset_branch_to_first_commit
#

git.ts view source

(origin: GitOrigin, branch: GitBranch, options?: SpawnOptions | undefined): Promise<void>

Resets the target branch back to its first commit both locally and remotely.

origin

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_workspace_is_clean
#

git_workspace_is_fully_staged
#

git.ts view source

(status: GitWorkspaceStatus): boolean

status

returns

boolean

true if the workspace has no unstaged changes and no untracked files (staged changes are OK)

git_workspace_status_message
#

GitBranch
#

GitInfo
#

git.ts view source

GitInfo

Basic git repository info.

commit

type string | null

branch

type string | null

GitOrigin
#

GitWorkspaceStatus
#

git.ts view source

GitWorkspaceStatus

Git workspace status flags indicating which types of changes are present.

unstaged_changes

type boolean

staged_changes

type boolean

untracked_files

type boolean

GR
#

GR_2
#

GR_2i
#

GR_3
#

GR_3i
#

GR_4
#

GR_4i
#

GR_5
#

GR_5i
#

GR_6
#

GR_6i
#

GR_7
#

GR_7i
#

GR_8
#

GR_8i
#

GR_9
#

GR_9i
#

GR_i
#

Green
#

handle_preprocess_error
#

svelte_preprocess_helpers.ts view source

(error: unknown, prefix: string, filename: string | undefined, on_error: "log" | "throw"): void

Handles errors during Svelte preprocessing with configurable behavior.

error

The caught error.

type unknown

prefix

Log prefix (e.g. '[fuz-mdz]', '[fuz-code]').

type string

filename

The file being processed.

type string | undefined

on_error

'throw' to re-throw as a new Error, 'log' to console.error.

type "log" | "throw"

returns

void

handle_target_value
#

dom.ts view source

(cb: (value: any, event: any) => void, swallow_event?: boolean): (e: any) => void

Handles the value of an event's target and invokes a callback. Defaults to swallowing the event to prevent default actions and propagation.

cb

type (value: any, event: any) => void

swallow_event

type boolean
default true

returns

(e: any) => void

has_identifier_in_tree
#

svelte_preprocess_helpers.ts view source

(node: unknown, name: string, skip?: Set<unknown> | undefined): boolean

Checks if an identifier with the given name appears anywhere in an AST subtree.

Recursively walks all object and array properties of the tree, matching ESTree Identifier nodes ({type: 'Identifier', name}). Nodes in the skip set are excluded from traversal โ€” used to skip ImportDeclaration nodes so the import's own specifier identifier doesn't false-positive.

Skips Identifier nodes in non-reference positions defined by NON_REFERENCE_FIELDS โ€” for example, obj.Mdz (non-computed member property), { Mdz: value } (non-computed object key), and statement labels.

Safe for Svelte template ASTs: Component.name is a plain string property (not an Identifier node), so <Mdz> tags do not produce false matches.

node

The AST subtree to search.

type unknown

name

The identifier name to look for.

type string

skip?

Set of AST nodes to skip during traversal.

type Set<unknown> | undefined
optional

returns

boolean

true if a matching Identifier node is found.

hash_blake3
#

hash_blake3.ts view source

(data: string | BufferSource): string

Computes a BLAKE3 hash synchronously.

data

String or binary data to hash. Strings are UTF-8 encoded.

type string | BufferSource

returns

string

64-character hexadecimal hash string (32 bytes).

hash_insecure
#

hash.ts view source

(data: string | BufferSource): string

Computes a fast non-cryptographic hash using DJB2 algorithm. Use for content comparison and cache keys, not security.

Note: Strings use UTF-16 code units, buffers use raw bytes. For non-ASCII, hash_insecure(str) !== hash_insecure(encoder.encode(str)).

data

String or binary data to hash.

type string | BufferSource

returns

string

8-character hex-encoded unsigned 32-bit hash.

hash_sha1
#

hash.ts view source

(data: string | BufferSource): Promise<string>

Computes a SHA-1 hash using Web Crypto API.

data

String or binary data to hash. Strings are UTF-8 encoded.

type string | BufferSource

returns

Promise<string>

40-character hexadecimal hash string.

hash_sha256
#

hash.ts view source

(data: string | BufferSource): Promise<string>

Computes a SHA-256 hash using Web Crypto API.

data

String or binary data to hash. Strings are UTF-8 encoded.

type string | BufferSource

returns

Promise<string>

64-character hexadecimal hash string.

hash_sha384
#

hash.ts view source

(data: string | BufferSource): Promise<string>

Computes a SHA-384 hash using Web Crypto API.

data

String or binary data to hash. Strings are UTF-8 encoded.

type string | BufferSource

returns

Promise<string>

96-character hexadecimal hash string.

hash_sha512
#

hash.ts view source

(data: string | BufferSource): Promise<string>

Computes a SHA-512 hash using Web Crypto API.

data

String or binary data to hash. Strings are UTF-8 encoded.

type string | BufferSource

returns

Promise<string>

128-character hexadecimal hash string.

hex_string_to_hsl
#

hex_string_to_rgb
#

hex_to_rgb
#

colors.ts view source

(hex: number): Rgb

Converts a hex color to an RGB color.

hex

type number

returns

Rgb

Hsl
#

hsl_to_hex
#

hsl_to_hex_string
#

hsl_to_rgb
#

hsl_to_string
#

Hue
#

hue_to_rgb_component
#

colors.ts view source

(p: number, q: number, t: number): number

p

type number

q

type number

t

type number

returns

number

identity
#

inside_editable
#

dom.ts view source

(el: Element): boolean

Returns true if the element is within a contenteditable ancestor.

el

type Element

returns

boolean

is_editable
#

dom.ts view source

(el: any): boolean

Checks if the given element is editable. Returns true for text-based input types, textareas, and contenteditable elements.

el

type any

returns

boolean

is_iframed
#

dom.ts view source

(): boolean

Returns a boolean indicating if the current browser window, if any, is iframed inside of another.

returns

boolean

is_interactive
#

dom.ts view source

(el: any): boolean

Checks if the element is interactive (clickable, focusable, or otherwise accepts user input). Returns true for buttons, links, form controls, and elements with interactive attributes and ARIA roles.

el

type any

returns

boolean

is_plain_object
#

object.ts view source

(value: any): boolean

Returns a boolean indicating if value is a plain object, possibly created with Object.create(null). But warning! This fails for some obscure corner cases, use a proper library for weird things.

value

type any

returns

boolean

is_promise
#

async.ts view source

(value: unknown): value is Promise<unknown>

Checks if value is a Promise (or thenable).

value

type unknown

returns

boolean

is_uuid
#

id.ts view source

(str: string): str is Uuid

Loosely validates a UUID string.

str

type string

returns

boolean

Json
#

json_embed
#

json.ts view source

<T>(data: T, stringify?: (data: T) => string): string

Embeds data as a JSON string, escaping single quotes. Useful for optimizing JSON in JS because it parses faster.

data

type T

stringify

type (data: T) => string
default JSON.stringify

returns

string

json_stringify_deterministic
#

json.ts view source

(value: unknown): string

Serializes a value to JSON with deterministic key ordering. Recursively sorts object keys alphabetically for consistent hashing. Arrays and primitives are serialized as-is.

value

Any JSON-serializable value

type unknown

returns

string

Deterministic JSON string representation

json_type_of
#

json.ts view source

(value: Json): JsonType | undefined

Returns the JsonType of value, which is like typeof json but includes 'array' and omits 'undefined'.

value

type Json

returns

JsonType | undefined

JsonArray
#

JsonObject
#

JsonPrimitive
#

JsonType
#

json.ts view source

JsonType

Like typeof json, but includes arrays. Excludes 'undefined' because it's not valid JSON.

KeyofUnion
#

lerp
#

maths.ts view source

(a: number, b: number, amount: number): number

Linear interpolation between a and b by amount.

a

type number

b

type number

amount

type number

returns

number

levenshtein_distance
#

string.ts view source

(a: string, b: string): number

Calculates the Levenshtein distance between two strings. Useful for typo detection and fuzzy matching.

a

First string

type string

b

Second string

type string

returns

number

The edit distance between the strings

library_json_parse
#

library_json.ts view source

(package_json: { [x: string]: unknown; name: string; version: string; private?: boolean | undefined; description?: string | undefined; motto?: string | undefined; glyph?: string | undefined; logo?: string | undefined; ... 23 more ...; exports?: string | ... 2 more ... | undefined; }, source_json: { ...; }): LibraryJson

Creates a LibraryJson with computed properties from package.json and source metadata.

package_json

type { [x: string]: unknown; name: string; version: string; private?: boolean | undefined; description?: string | undefined; motto?: string | undefined; glyph?: string | undefined; logo?: string | undefined; ... 23 more ...; exports?: string | ... 2 more ... | undefined; }

source_json

type { [x: string]: unknown; name: string; version: string; modules?: { [x: string]: unknown; path: string; declarations?: { [x: string]: unknown; name: string; kind: "function" | "type" | "variable" | "class" | "constructor" | "component" | "json" | "css"; ... 20 more ...; alias_of?: { ...; } | undefined; }[] | undefine...

returns

LibraryJson

library_org_url_parse
#

library_json.ts view source

(library: LibraryJson): string | null

Extracts GitHub org URL from a library, e.g. https://github.com/ryanatkn.

library

returns

string | null

library_repo_name_parse
#

library_json.ts view source

(name: string): string

Extracts repo name from a package name, e.g. @fuzdev/fuz_ui โ†’ fuz.

name

type string

returns

string

LibraryJson
#

library_json.ts view source

LibraryJson

A library's package.json and source metadata with computed properties.

name

Package name, e.g. @fuzdev/fuz_ui.

type string

repo_name

Name without scope, e.g. fuz.

type string

repo_url

GitHub repo URL, e.g. https://github.com/fuzdev/fuz_ui.

type Url

owner_name

GitHub user/org, e.g. ryanatkn.

type string | null

homepage_url

type Url | null

logo_url

Logo URL, falls back to favicon.png.

type Url | null

logo_alt

type string

npm_url

type Url | null

changelog_url

type Url | null

published

True if has exports and version is not 0.0.1.

type boolean

package_json

source_json

Lightness
#

log_level_parse
#

log.ts view source

(value: string | undefined): LogLevel | undefined

Parses and validates a log level string.

value

The value to parse as a log level

type string | undefined

returns

LogLevel | undefined

The validated log level, or undefined if value is undefined

throws

  • Error - if value is provided but invalid

log_level_to_number
#

log.ts view source

(level: LogLevel): number

Converts a log level to its numeric value for comparison. Higher numbers indicate more verbose logging.

level

The log level to convert

returns

number

Numeric value (0-4)

LogConsole
#

log.ts view source

LogConsole

Console interface subset used by Logger for output. Allows custom console implementations for testing.

Logger
#

log.ts view source

Simple, flexible logger with support for child loggers and automatic context.

Features: - Instance-based configuration (no global state) - Child loggers with automatic label concatenation - Parent chain inheritance for level, console, and colors - Respects NO_COLOR environment variable

examples

// Basic logger const log = new Logger('app'); log.info('starting'); // [app] โžค starting // Child logger const db_log = log.child('db'); db_log.info('connected'); // [app:db] โžค connected // Custom configuration const verbose_log = new Logger('debug', { level: 'debug', colors: true });

label

type string

readonly

parent

type Logger

readonly

constructor

Creates a new Logger instance.

type new (label?: string | undefined, options?: LoggerOptions): Logger

label?

Optional label for this logger. Can be undefined for no label, or an empty string '' which is functionally equivalent (both produce no brackets in output). Note: Empty strings are only allowed for root loggers - child loggers cannot have empty labels.

type string | undefined
optional
options

Optional configuration for level, colors, and console

default {}

clear_level_override

Clears the level override for this logger, restoring inheritance from parent. After calling this, the logger will dynamically inherit the level from its parent (or use the default level if it has no parent).

type (): void

returns void

clear_colors_override

Clears the colors override for this logger, restoring inheritance from parent. After calling this, the logger will dynamically inherit colors from its parent (or use the default colors behavior if it has no parent).

type (): void

returns void

clear_console_override

Clears the console override for this logger, restoring inheritance from parent. After calling this, the logger will dynamically inherit the console from its parent (or use the global console if it has no parent).

type (): void

returns void

child

Creates a child logger with automatic label concatenation. Children inherit parent configuration unless overridden.

type (label: string, options?: LoggerOptions): Logger

label

Child label (will be concatenated with parent label using :). Cannot be an empty string - empty labels would result in confusing output like parent: with a trailing colon. Use undefined or '' only for root loggers.

type string
options

Optional configuration overrides

default {}
returns Logger

New Logger instance with concatenated label

throws
  • Error - if label is an empty string

error

Logs an error message with ๐Ÿžฉerror๐Ÿžฉ prefix. Only outputs if current level is error or higher.

type (...args: unknown[]): void

args
type unknown[]
returns void

warn

Logs a warning message with โš‘warnโš‘ prefix. Only outputs if current level is warn or higher.

type (...args: unknown[]): void

args
type unknown[]
returns void

info

Logs an informational message. Unlike error/warn/debug, info has no character prefix - only the label is shown. This keeps standard output clean since info is the default log level. Only outputs if current level is info or higher.

type (...args: unknown[]): void

args
type unknown[]
returns void

debug

Logs a debug message with โ”†debugโ”† prefix. Only outputs if current level is debug.

type (...args: unknown[]): void

args
type unknown[]
returns void

raw

Logs raw output without any prefix, formatting, or level filtering. Bypasses the logger's level checking, prefix formatting, and color application entirely. Useful for outputting structured data or when you need full control over formatting.

Note: This method ignores the configured log level - it always outputs regardless of whether the logger is set to 'off' or any other level.

type (...args: unknown[]): void

args

Values to log directly to console

type unknown[]
returns void

LoggerOptions
#

log.ts view source

LoggerOptions

level

Log level for this logger instance. Inherits from parent or defaults to 'info'.

console

Console interface for output. Inherits from parent or defaults to global console. Useful for testing.

colors

Whether to use colors in output. Inherits from parent or defaults to enabled (unless NO_COLOR env var is set).

type boolean

LogLevel
#

log.ts view source

LogLevel

Log level hierarchy from least to most verbose. - 'off': No logging - 'error': Only errors - 'warn': Errors and warnings - 'info': Errors, warnings, and info (default) - 'debug': All messages including debug

map_concurrent
#

async.ts view source

<T, R>(items: Iterable<T>, concurrency: number, fn: (item: T, index: number) => R | Promise<R>, signal?: AbortSignal | undefined): Promise<...>

Maps over items with controlled concurrency, preserving input order.

items

items to process

type Iterable<T>

concurrency

maximum number of concurrent operations

type number

fn

function to apply to each item

type (item: T, index: number) => R | Promise<R>

signal?

optional AbortSignal to cancel processing

type AbortSignal | undefined
optional

returns

Promise<R[]>

promise resolving to array of results in same order as input

examples

const results = await map_concurrent( file_paths, 5, // max 5 concurrent reads async (path) => readFile(path, 'utf8'), );

map_concurrent_settled
#

async.ts view source

<T, R>(items: Iterable<T>, concurrency: number, fn: (item: T, index: number) => R | Promise<R>, signal?: AbortSignal | undefined): Promise<...>

Like map_concurrent but collects all results/errors instead of failing fast. Returns an array of settlement objects matching the Promise.allSettled pattern.

On abort, resolves with partial results: completed items keep their real settlements, in-flight and un-started items are settled as rejected with the abort reason.

items

items to process

type Iterable<T>

concurrency

maximum number of concurrent operations

type number

fn

function to apply to each item

type (item: T, index: number) => R | Promise<R>

signal?

optional AbortSignal to cancel processing

type AbortSignal | undefined
optional

returns

Promise<PromiseSettledResult<R>[]>

promise resolving to array of PromiseSettledResult objects in input order

examples

const results = await map_concurrent_settled(urls, 5, fetch); for (const [i, result] of results.entries()) { if (result.status === 'fulfilled') { console.log(`${urls[i]}: ${result.value.status}`); } else { console.error(`${urls[i]}: ${result.reason}`); } }

map_record
#

object.ts view source

<T, K extends string | number, U>(obj: Record<K, T>, mapper: (value: T, key: string) => U): Record<K, U>

Iterated keys in for..in are always returned as strings, so to prevent usage errors the key type of mapper is always a string. Symbols are not enumerable as keys, so they're excluded.

obj

type Record<K, T>

mapper

type (value: T, key: string) => U

returns

Record<K, U>

ModuleJson
#

source_json.ts view source

ZodObject<{ path: ZodString; declarations: ZodOptional<ZodArray<ZodObject<{ name: ZodString; kind: ZodEnum<{ function: "function"; type: "type"; variable: "variable"; class: "class"; constructor: "constructor"; component: "component"; json: "json"; css: "css"; }>; ... 20 more ...; alias_of: ZodOptional<...>; }, $loo...

A source file in src/lib/ with its exported declarations.

noop
#

noop_async
#

function.ts view source

(...args: any[]): Promise<any>

Async function that returns a resolved promise.

args

type any[]

returns

Promise<any>

NOT_OK
#

result.ts view source

Readonly<{ readonly ok: false; }>

Frozen object representing a failed result.

NotNull
#

OK
#

result.ts view source

Readonly<{ readonly ok: true; }>

Frozen object representing a successful result.

omit
#

object.ts view source

<T extends Record<K, any>, K extends keyof T>(obj: T, keys: K[]): OmitStrict<T, K>

Creates a new object without the specified keys.

obj

type T

keys

type K[]

returns

OmitStrict<T, K>

omit_undefined
#

OmitStrict
#

PackageJson
#

PackageJsonAuthor
#

package_json.ts view source

ZodUnion<readonly [ZodString, ZodObject<{ name: ZodString; email: ZodOptional<ZodEmail>; url: ZodOptional<ZodURL>; }, $loose>]>

PackageJsonExports
#

package_json.ts view source

ZodUnion<readonly [ZodString, ZodNull, ZodRecord<ZodString, ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>>]>

Package exports can be: 1. A string (shorthand for main export) 2. null (to block exports) 3. A record of export conditions/paths

PackageJsonFunding
#

PackageJsonRepository
#

package_json.ts view source

ZodUnion<readonly [ZodString, ZodObject<{ type: ZodString; url: ZodURL; directory: ZodOptional<ZodString>; }, $loose>]>

pad_width
#

string.ts view source

(str: string, target_width: number, align?: "left" | "right"): string

Pad a string to a target display width (accounting for wide characters).

str

type string

target_width

type number

align

type "left" | "right"
default 'left'

returns

string

ParameterInfo
#

source_json.ts view source

ZodObject<{ name: ZodString; type: ZodString; optional: ZodOptional<ZodBoolean>; description: ZodOptional<ZodString>; default_value: ZodOptional<...>; }, $loose>

Parameter information for functions and methods.

Kept distinct from ComponentPropInfo despite structural similarity. Function parameters form a tuple with positional semantics: calling order matters (fn(a, b) vs fn(b, a)), may include rest parameters and destructuring patterns.

parse_hsl_string
#

parse_path_parts
#

path.ts view source

(path: string): string[]

path

type string

returns

string[]

examples

parse_path_parts('./foo/bar/baz.ts') // => ['foo', 'foo/bar', 'foo/bar/baz.ts']

parse_path_pieces
#

path.ts view source

(raw_path: string): PathPiece[]

Treats all paths as absolute, so the first piece is always a '/' with type 'separator'.

raw_path

type string

returns

PathPiece[]

parse_path_segments
#

path.ts view source

(path: string): string[]

Gets the individual parts of a path, ignoring dots and separators.

path

type string

returns

string[]

examples

parse_path_segments('/foo/bar/baz.ts') // => ['foo', 'bar', 'baz.ts']

ParsedArgs
#

args.ts view source

ParsedArgs

Parsed CLI arguments with guaranteed positionals array. Returned by argv_parse which always initializes _.

inheritance

extends:

_

type Array<string>

PartialExcept
#

PartialOnly
#

PartialValues
#

PathFilter
#

path.ts view source

PathFilter

A filter function for paths, can distinguish between files and directories.

PathId
#

path.ts view source

PathId

An absolute path on the filesystem. Named "id" to be consistent with Rollup.

PathInfo
#

PathPiece
#

path.ts view source

PathPiece

A piece of a parsed path, either a path segment or separator.

pick_by
#

object.ts view source

<T extends Record<K, any>, K extends string | number>(obj: T, should_pick: (value: any, key: K) => boolean): Partial<T>

Creates a new object with properties that pass the should_pick predicate.

obj

type T

should_pick

type (value: any, key: K) => boolean

returns

Partial<T>

PickUnion
#

plural
#

string.ts view source

(count: number | null | undefined, suffix?: string): string

Returns a plural suffix based on a count.

count

type number | null | undefined

suffix

type string
default 's'

returns

string

PreprocessImportInfo
#

svelte_preprocess_helpers.ts view source

PreprocessImportInfo

Import metadata for a single import specifier.

path

The module path to import from.

type string

kind

Whether this is a default or named import.

type 'default' | 'named'

print_boolean
#

print_child_process
#

print_error
#

print_key_value
#

print_ms
#

print_number
#

print_number_with_separators
#

print_spawn_result
#

print_string
#

print_timing
#

print_timings
#

print_value
#

process_is_pid_running
#

process.ts view source

(pid: number): boolean

Checks if a process with the given PID is running. Uses signal 0 which checks existence without sending a signal.

pid

The process ID to check (must be a positive integer)

type number

returns

boolean

true if the process exists (even without permission to signal it), false if the process doesn't exist or if pid is invalid (non-positive, non-integer, NaN, Infinity)

process_registry_default
#

process.ts view source

ProcessRegistry

Default process registry used by module-level spawn functions. For testing or isolated process groups, create a new ProcessRegistry instance.

ProcessRegistry
#

process.ts view source

Manages a collection of spawned processes for lifecycle tracking and cleanup.

The default instance process_registry_default is used by module-level functions. Create separate instances for isolated process groups or testing.

examples

// Use default registry via module functions const result = await spawn('echo', ['hello']); // Or create isolated registry for testing const registry = new ProcessRegistry(); const {child, closed} = registry.spawn('node', ['server.js']); await registry.despawn_all();

processes

All currently tracked child processes

type Set<ChildProcess>

readonly

spawn

Spawns a process and tracks it in this registry. The process is automatically unregistered when it exits.

type (command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): SpawnedProcess

command

The command to run

type string
args

Arguments to pass to the command

type readonly string[]
default []
options?

Spawn options including signal and timeout_ms

type SpawnProcessOptions | undefined
optional

Handle with child process and closed promise

spawn_out

Spawns a process and captures stdout/stderr as strings. Sets stdio: 'pipe' automatically.

type (command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): Promise<SpawnedOut>

command

The command to run

type string
args

Arguments to pass to the command

type readonly string[]
default []
options?

Spawn options

type SpawnProcessOptions | undefined
optional
returns Promise<SpawnedOut>

Result with captured stdout and stderr. - null means spawn failed (ENOENT, etc.) or stream was unavailable - '' (empty string) means process ran but produced no output - non-empty string contains the captured output

despawn

Kills a child process and waits for it to exit.

type (child: ChildProcess, options?: DespawnOptions | undefined): Promise<SpawnResult>

child

The child process to kill

type ChildProcess
options?

Kill options including signal and timeout

type DespawnOptions | undefined
optional
returns Promise<SpawnResult>

The spawn result after the process exits

despawn_all

Kills all processes in this registry.

type (options?: DespawnOptions | undefined): Promise<SpawnResult[]>

options?

Kill options applied to all processes

type DespawnOptions | undefined
optional
returns Promise<SpawnResult[]>

Array of spawn results

attach_error_handler

Attaches an uncaughtException handler that kills all processes before exiting. Prevents zombie processes when the parent crashes.

By default uses SIGKILL for immediate termination. Set graceful_timeout_ms to attempt SIGTERM first (allowing processes to clean up) before escalating to SIGKILL after the timeout.

Note: Node's uncaughtException handler cannot await async operations, so graceful shutdown uses a blocking busy-wait. This may not be sufficient for processes that need significant cleanup time.

type (options?: { to_error_label?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; map_error_text?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; handle_error?: ((err: Error, origin: UncaughtExceptionOrigin) => void) | undefined; graceful_timeout_ms?: number | ... 1 more ... | undefined; } | undefined): () => void

options?

Configuration options

type { to_error_label?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; map_error_text?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined; handle_error?: ((err: Error, origin: UncaughtExceptionOrigin) => void) | undefined; graceful_timeout_ms?: number | ... 1 more...
optional
returns () => void

Cleanup function to remove the handler

random_boolean
#

random.ts view source

(random?: () => number): boolean

Generates a random boolean.

random

type () => number
default Math.random

returns

boolean

random_float
#

random.ts view source

(min: number, max: number, random?: () => number): number

Generates a random number between min and max.

min

type number

max

type number

random

type () => number
default Math.random

returns

number

random_int
#

random_item
#

random.ts view source

<T extends ReadonlyArray<any>>(arr: T, random?: () => number): ArrayElement<T>

Selects a random item from an array.

arr

type T

random

type () => number
default Math.random

returns

ArrayElement<T>

RandomAlea
#

random_alea.ts view source

RandomAlea

Alea: a seedable pseudo-random number generator by Johannes Baagรธe. Supports variadic and string seeds (create_random_alea('my', 3, 'seeds')). For numeric seeds, prefer create_random_xoshiro which is faster with equal quality.

DO NOT USE when security matters โ€” use the Web Crypto API (crypto.getRandomValues) instead.

Alea passes all 11 distribution quality tests at 10M samples, performing on par with Math.random (V8's xorshift128+):

- mean, variance, chi-squared uniformity, Kolmogorov-Smirnov - lag-1 through lag-8 autocorrelation - runs test, gap test, permutation test (triples) - bit-level frequency (bits 0-7) - 2D serial pairs (25x25 through 200x200 grids) - birthday spacings (Marsaglia parameters)

Speed is ~19% slower than Math.random (~12.2M ops/sec vs ~15.0M ops/sec).

To reproduce:

npm run benchmark_random_quality # distribution tests (N=1M) npm run benchmark_random_quality -- --deep # thorough (N=10M, multi-trial) npm run benchmark_random # speed comparison

see also

uint32

type () => number

fract53

type () => number

version

type string

seeds

type Array<unknown>

RandomXoshiro
#

random_xoshiro.ts view source

RandomXoshiro

Xoshiro128**: a seedable pseudo-random number generator by Blackman & Vigna (2018). Recommended for reproducible randomness (testing, simulations, procedural generation).

DO NOT USE when security matters โ€” use the Web Crypto API (crypto.getRandomValues) instead.

Xoshiro128** has a 2^128-1 period and passes BigCrush. It uses pure 32-bit arithmetic (shifts, rotates, XOR, multiply) making it very fast in JavaScript via Math.imul.

Xoshiro128** passes all 11 distribution quality tests at 10M samples, performing on par with Math.random (V8's xorshift128+):

- mean, variance, chi-squared uniformity, Kolmogorov-Smirnov - lag-1 through lag-8 autocorrelation - runs test, gap test, permutation test (triples) - bit-level frequency (bits 0-7) - 2D serial pairs (25x25 through 200x200 grids) - birthday spacings (Marsaglia parameters)

Speed is near-native (~4% slower than Math.random) and ~18% faster than Alea (~14.4M ops/sec vs ~15.0M and ~12.2M respectively).

To reproduce:

npm run benchmark_random_quality # distribution tests (N=1M) npm run benchmark_random_quality -- --deep # thorough (N=10M, multi-trial) npm run benchmark_random # speed comparison

see also

uint32

type () => number

fract53

type () => number

version

type string

seed

type number

Red
#

remove_import_declaration
#

svelte_preprocess_helpers.ts view source

(s: { remove: (start: number, end: number) => unknown; }, import_node: ImportDeclaration & { start: number; end: number; }, source: string): void

Removes an ImportDeclaration from source using MagicString.

Consumes leading whitespace (tabs/spaces) and trailing newline to avoid leaving blank lines.

s

The MagicString instance to modify.

type { remove: (start: number, end: number) => unknown; }

import_node

The ImportDeclaration AST node with Svelte position data.

type ImportDeclaration & { start: number; end: number; }

source

The original source string.

type string

returns

void

remove_import_specifier
#

svelte_preprocess_helpers.ts view source

(s: { overwrite: (start: number, end: number, content: string) => unknown; }, node: ImportDeclaration & { start: number; end: number; }, specifier_to_remove: ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier, source: string, additional_lines?: string): void

Removes a specifier from a multi-specifier import declaration by reconstructing the statement without the removed specifier.

Overwrites the entire declaration range to avoid character-level comma surgery.

Handles: - import Mdz, {other} from '...' โ†’ import {other} from '...' - import {default as Mdz, other} from '...' โ†’ import {other} from '...' - import {Mdz, other} from '...' โ†’ import {other} from '...'

s

The MagicString instance to modify.

type { overwrite: (start: number, end: number, content: string) => unknown; }

node

The positioned ImportDeclaration AST node.

type ImportDeclaration & { start: number; end: number; }

specifier_to_remove

The specifier to remove from the import.

type ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier

source

The original source string.

type string

additional_lines

Extra content appended after the reconstructed import (used to bundle new imports into the overwrite to avoid MagicString boundary conflicts).

type string
default ''

returns

void

remove_unordered
#

array.ts view source

(array: any[], index: number): void

Removes an element from array at index in an unordered manner.

array

type any[]

index

type number

returns

void

remove_variable_declaration
#

svelte_preprocess_helpers.ts view source

(s: { remove: (start: number, end: number) => unknown; }, declaration_node: VariableDeclaration & { start: number; end: number; }, source: string): void

Removes a single-declarator VariableDeclaration from source using MagicString.

Consumes leading whitespace (tabs/spaces) and trailing newline to avoid leaving blank lines. Only safe for single-declarator statements (const x = 'val';); callers must verify node.declarations.length === 1 before calling.

s

The MagicString instance to modify.

type { remove: (start: number, end: number) => unknown; }

declaration_node

The VariableDeclaration AST node with Svelte position data.

type VariableDeclaration & { start: number; end: number; }

source

The original source string.

type string

returns

void

reorder
#

object.ts view source

<T extends Record<K, any>, K extends string | number>(obj: T, keys: K[]): T

A more explicit form of {put_this_first: obj.put_this_first, ...obj}.

obj

type T

keys

type K[]

returns

T

reset_regexp
#

regexp.ts view source

<T extends RegExp>(regexp: T): T

Reset a RegExp's lastIndex to 0 for global and sticky patterns. Ensures consistent behavior by clearing state that affects subsequent matches.

regexp

type T

returns

T

resolve_component_names
#

svelte_preprocess_helpers.ts view source

(ast: Root, component_imports: string[]): Map<string, ResolvedComponentImport>

Resolves local names that import from specified source paths.

Scans ImportDeclaration nodes in both the instance and module scripts. Handles default, named, and aliased imports. Skips namespace imports and import type declarations (both whole-declaration and per-specifier). Returns import node references alongside names to support import removal.

ast

The parsed Svelte AST root node.

type Root

component_imports

Array of import source paths to match against.

type string[]

returns

Map<string, ResolvedComponentImport>

Map of local names to their resolved import info.

resolved
#

ResolvedComponentImport
#

svelte_preprocess_helpers.ts view source

ResolvedComponentImport

Information about a resolved component import.

import_node

The ImportDeclaration AST node that provides this name.

type ImportDeclaration

specifier

The specific import specifier for this name.

type ImportSpecifier | ImportDefaultSpecifier

ResolvedPath
#

path.ts view source

ResolvedPath

A resolved path with both the original path string and its absolute id.

inheritance

extends:

path

type string

RestartableProcess
#

process.ts view source

RestartableProcess

Handle for a process that can be restarted. Exposes closed promise for observing exits and implementing restart policies.

restart

Restart the process, killing the current one if active. Concurrent calls are coalesced - multiple calls before the first completes will share the same restart operation.

type () => Promise<void>

kill

Kill the process and set active to false

type () => Promise<void>

active

Whether this handle is managing a process.

Note: This reflects handle state, not whether the underlying OS process is executing. Remains true after a process exits naturally until kill() or restart() is called. To check if the process actually exited, await closed.

type boolean
readonly

child

The current child process, or null if not active

type ChildProcess | null
readonly

closed

Promise that resolves when the current process exits

type Promise<SpawnResult>
readonly

spawned

Promise that resolves when the initial spawn_process() call completes.

Note: This resolves when the spawn syscall returns, NOT when the process is "ready" or has produced output. For commands that fail immediately (e.g., ENOENT), spawned still resolves - check closed for errors.

type Promise<void>
readonly

Result
#

result.ts view source

Result<TValue, TError>

An alternative pattern to throwing and catching errors. Uses the type system to strongly type error return values when desired. Catching errors is then reserved for unexpected situations.

generics

TValue

default object

TError

default object

ResultError
#

result.ts view source

A custom error class that's thrown by unwrap. Wraps a failed Result with an optional message, and also accepts an optional message that overrides the result's. Useful for generic handling of unwrapped results to forward custom messages and other failed result data.

inheritance

extends:
  • Error

DEFAULT_MESSAGE

static

result

type {ok: false; message?: string}

readonly

constructor

type new (result: { ok: false; message?: string | undefined; }, message?: string | undefined, options?: ErrorOptions | undefined): ResultError

result
type { ok: false; message?: string | undefined; }
message?
type string | undefined
optional
options?
type ErrorOptions | undefined
optional

Rgb
#

rgb_to_hex
#

colors.ts view source

(r: number, g: number, b: number): number

Converts an RGB color to a hex color.

r

type number

g

type number

b

type number

returns

number

rgb_to_hex_string
#

colors.ts view source

(r: number, g: number, b: number): string

r

type number

g

type number

b

type number

returns

string

rgb_to_hsl
#

round
#

maths.ts view source

(n: number, decimals: number): number

Rounds a number to a specified number of decimal places.

n

type number

decimals

type number

returns

number

run_dag
#

dag.ts view source

<T extends DagNode>(options: DagOptions<T>): Promise<DagResult>

Execute nodes in a dependency graph concurrently.

Independent nodes (no unmet dependencies) run in parallel up to max_concurrency. When a node completes, its dependents become eligible to start. Failure cascading and stop-on-failure are handled per the options.

options

DAG execution options.

type DagOptions<T>

returns

Promise<DagResult>

Aggregated result with per-node details.

Saturation
#

serialize_cache
#

fetch.ts view source

(cache: Map<string, { key: string; url: string; params: any; value: any; etag: string | null; last_modified: string | null; }>): string

Converts FetchValueCache to a JSON string.

cache

type Map<string, { key: string; url: string; params: any; value: any; etag: string | null; last_modified: string | null; }>

returns

string

should_exclude_path
#

path.ts view source

(filename: string | undefined, exclude: (string | RegExp)[]): boolean

Checks if a filename matches any exclusion pattern.

Returns false when filename is undefined, empty string, or exclude is empty. String patterns use substring matching. RegExp patterns use .test().

filename

The file path to check, or undefined for virtual files.

type string | undefined

exclude

Array of string or RegExp exclusion patterns.

type (string | RegExp)[]

returns

boolean

true if the file should be excluded from processing.

shuffle
#

random.ts view source

<T extends Array<any>>(array: T, random?: ((min: number, max: number, random?: () => number) => number) | undefined): T

Mutates array with random ordering.

array

type T

random?

type ((min: number, max: number, random?: () => number) => number) | undefined
optional

returns

T

slugify
#

path.ts view source

(str: string, map_special_characters?: boolean): string

Converts a string into a URL-compatible slug.

str

the string to convert

type string

map_special_characters

if true, characters like รฑ are converted to their ASCII equivalents, runs around 5x faster when disabled

type boolean
default true

returns

string

sort_map
#

map.ts view source

<T extends Map<any, any>>(map: T, comparator?: (a: [any, any], b: [any, any]) => number): T

Sorts a map by comparator, a function that compares two entries, defaulting to using localCompare and >.

map

type T

comparator

type (a: [any, any], b: [any, any]) => number
default compare_simple_map_entries

returns

T

Sortable
#

sort.ts view source

Sortable

Minimum shape required for topological sorting.

id

type string

depends_on

type Array<string>

SourceJson
#

source_json.ts view source

ZodObject<{ name: ZodString; version: ZodString; modules: ZodOptional<ZodArray<ZodObject<{ path: ZodString; declarations: ZodOptional<ZodArray<ZodObject<{ name: ZodString; kind: ZodEnum<{ function: "function"; ... 6 more ...; css: "css"; }>; ... 20 more ...; alias_of: ZodOptional<...>; }, $loose>>>; module_comment: ...

Metadata for a library's src/lib/ exports.

spawn
#

process.ts view source

(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): Promise<SpawnResult>

Spawns a process and returns a promise that resolves when it exits. Use this for commands that complete (not long-running processes).

command

type string

args

type readonly string[]
default []

options?

type SpawnProcessOptions | undefined
optional

returns

Promise<SpawnResult>

examples

const result = await spawn('npm', ['install']); if (!result.ok) console.error('Install failed');

spawn_detached
#

process.ts view source

(command: string, args?: readonly string[], options?: SpawnOptions | undefined): SpawnDetachedResult

Spawns a detached process that continues after parent exits.

Unlike other spawn functions, this is NOT tracked in any ProcessRegistry. The spawned process is meant to outlive the parent (e.g., daemon processes).

command

The command to run

type string

args

Arguments to pass to the command

type readonly string[]
default []

options?

Spawn options (use stdio to redirect output to file descriptors)

type SpawnOptions | undefined
optional

returns

SpawnDetachedResult

Result with pid on success, or error message on failure

examples

// Simple detached process const result = spawn_detached('node', ['daemon.js'], {cwd: '/app'}); // With log file (caller handles file opening) import {openSync, closeSync} from 'node:fs'; const log_fd = openSync('/var/log/daemon.log', 'a'); const result = spawn_detached('node', ['daemon.js'], { cwd: '/app', stdio: ['ignore', log_fd, log_fd], }); closeSync(log_fd);

spawn_out
#

process.ts view source

(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): Promise<SpawnedOut>

Spawns a process and captures stdout/stderr as strings.

command

type string

args

type readonly string[]
default []

options?

type SpawnProcessOptions | undefined
optional

returns

Promise<SpawnedOut>

examples

const {result, stdout} = await spawn_out('git', ['status', '--porcelain']); if (result.ok && stdout) console.log(stdout);

spawn_process
#

process.ts view source

(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): SpawnedProcess

Spawns a process with graceful shutdown behavior. Returns a handle with access to the child process and closed promise.

command

type string

args

type readonly string[]
default []

options?

type SpawnProcessOptions | undefined
optional

returns

SpawnedProcess

examples

const {child, closed} = spawn_process('node', ['server.js']); // Later... child.kill(); const result = await closed;

spawn_restartable_process
#

process.ts view source

(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): RestartableProcess

Spawns a process that can be restarted. Handles concurrent restart calls gracefully.

Note: The signal and timeout_ms options are reapplied on each restart. If the AbortSignal is already aborted when restart() is called, the new process will be killed immediately.

command

type string

args

type readonly string[]
default []

options?

type SpawnProcessOptions | undefined
optional

returns

RestartableProcess

examples

Simple restart on crash

const rp = spawn_restartable_process('node', ['server.js']); while (rp.active) { const result = await rp.closed; if (result.ok) break; // Clean exit await rp.restart(); }

Restart with backoff

const rp = spawn_restartable_process('node', ['server.js']); let failures = 0; while (rp.active) { const result = await rp.closed; if (result.ok || ++failures > 5) break; await new Promise((r) => setTimeout(r, 1000 * failures)); await rp.restart(); }

spawn_result_is_error
#

process.ts view source

(result: SpawnResult): result is SpawnResultError

Type guard for spawn errors (process failed to start).

result

returns

boolean

spawn_result_is_exited
#

spawn_result_is_signaled
#

spawn_result_to_message
#

SpawnDetachedResult
#

SpawnedOut
#

process.ts view source

SpawnedOut

Result of spawn_out with captured output streams.

result

stdout

Captured stdout, or null if stream unavailable

type string | null

stderr

Captured stderr, or null if stream unavailable

type string | null

SpawnedProcess
#

process.ts view source

SpawnedProcess

Handle for a spawned process with access to the child and completion promise.

child

The underlying Node.js ChildProcess

type ChildProcess

closed

Resolves when the process exits

type Promise<SpawnResult>

SpawnProcessOptions
#

process.ts view source

SpawnProcessOptions

Options for spawning processes, extending Node's SpawnOptions.

inheritance

extends:
  • SpawnOptions

signal

AbortSignal to cancel the process. When aborted, sends SIGTERM to the child.

type AbortSignal

timeout_ms

Timeout in milliseconds. Must be non-negative. Sends SIGTERM when exceeded. A value of 0 triggers immediate SIGTERM.

type number

spawn_child_process

Custom spawn function for testing. Defaults to node:child_process spawn.

type typeof node_spawn_child_process

SpawnResult
#

SpawnResultError
#

process.ts view source

SpawnResultError

Spawn failed before the process could run.

examples

ENOENT when command not found

ok

type false

child

type ChildProcess

error

type Error

code

type null

signal

type null

SpawnResultExited
#

process.ts view source

SpawnResultExited

Process ran and exited with a code. ok is true when code is 0.

ok

type boolean

child

type ChildProcess

error

type null

code

type number

signal

type null

SpawnResultSignaled
#

process.ts view source

SpawnResultSignaled

Process was terminated by a signal (e.g., SIGTERM, SIGKILL).

ok

type false

child

type ChildProcess

error

type null

code

type null

signal

type NodeJS.Signals

st
#

print.ts view source

(format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions | undefined): string

format

type ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[]

text

type string

options?

type StyleTextOptions | undefined
optional

returns

string

stats_confidence_interval
#

stats.ts view source

(values: number[], options?: StatsConfidenceIntervalOptions | undefined): [number, number]

Calculate confidence interval for the mean.

values

Array of numbers

type number[]

options?

Configuration options

type StatsConfidenceIntervalOptions | undefined
optional

returns

[number, number]

[lower_bound, upper_bound]

stats_confidence_interval_from_summary
#

stats.ts view source

(mean: number, std_dev: number, sample_size: number, options?: StatsConfidenceIntervalOptions | undefined): [number, number]

Calculate confidence interval from summary statistics (mean, std_dev, sample_size). Useful when raw data is not available.

mean

Mean of the data

type number

std_dev

Standard deviation of the data

type number

sample_size

Number of samples

type number

options?

Configuration options

type StatsConfidenceIntervalOptions | undefined
optional

returns

[number, number]

[lower_bound, upper_bound]

stats_confidence_level_to_z_score
#

stats.ts view source

(level: number): number

Convert a confidence level (0-1) to a z-score. Uses a lookup table for common values, approximates others.

level

type number

returns

number

examples

stats_confidence_level_to_z_score(0.95); // 1.96 stats_confidence_level_to_z_score(0.99); // 2.576

STATS_CONFIDENCE_Z_SCORES
#

stats_cv
#

stats.ts view source

(mean: number, std_dev: number): number

Calculate the coefficient of variation (CV). CV = standard deviation / mean, expressed as a ratio. Useful for comparing relative variability between datasets.

mean

type number

std_dev

type number

returns

number

stats_incomplete_beta
#

stats.ts view source

(x: number, a: number, b: number): number

Approximate regularized incomplete beta function for p-value calculation. Uses continued fraction expansion for reasonable accuracy.

x

type number

a

type number

b

type number

returns

number

stats_ln_gamma
#

stats.ts view source

(z: number): number

Log gamma function approximation (Lanczos approximation).

z

type number

returns

number

stats_mean
#

stats.ts view source

(values: number[]): number

Calculate the mean (average) of an array of numbers.

values

type number[]

returns

number

stats_median
#

stats.ts view source

(values: number[]): number

Calculate the median of an array of numbers.

values

type number[]

returns

number

stats_min_max
#

stats.ts view source

(values: number[]): { min: number; max: number; }

Calculate min and max values.

values

type number[]

returns

{ min: number; max: number; }

stats_normal_cdf
#

stats.ts view source

(x: number): number

Standard normal CDF approximation (Abramowitz and Stegun formula 7.1.26).

x

type number

returns

number

stats_outliers_iqr
#

stats.ts view source

(values: number[], options?: StatsOutliersIqrOptions | undefined): StatsOutlierResult

Detect outliers using the IQR (Interquartile Range) method. Values outside [Q1 - multiplier*IQR, Q3 + multiplier*IQR] are considered outliers.

values

type number[]

options?

type StatsOutliersIqrOptions | undefined
optional

returns

StatsOutlierResult

stats_outliers_mad
#

stats.ts view source

(values: number[], options?: StatsOutliersMadOptions | undefined): StatsOutlierResult

Detect outliers using the MAD (Median Absolute Deviation) method. More robust than IQR for skewed distributions. Uses modified Z-score: |0.6745 * (x - median) / MAD| Values with modified Z-score > threshold are considered outliers.

values

type number[]

options?

type StatsOutliersMadOptions | undefined
optional

returns

StatsOutlierResult

stats_percentile
#

stats.ts view source

(values: number[], p: number): number

Calculate a percentile of an array of numbers using linear interpolation. Uses the "R-7" method (default in R, NumPy, Excel) which interpolates between data points for more accurate percentile estimates, especially with smaller samples.

values

Array of numbers

type number[]

p

Percentile (0-1, e.g., 0.95 for 95th percentile)

type number

returns

number

stats_std_dev
#

stats.ts view source

(values: number[], mean?: number | undefined): number

Calculate the standard deviation of an array of numbers. Uses population standard deviation (divides by n, not n-1). For benchmarks with many samples, this is typically appropriate.

values

type number[]

mean?

type number | undefined
optional

returns

number

stats_t_distribution_p_value
#

stats.ts view source

(t: number, df: number): number

Approximate two-tailed p-value from t-distribution. For large df (>100), uses normal approximation. For smaller df, uses incomplete beta function.

t

Absolute value of t-statistic

type number

df

Degrees of freedom

type number

returns

number

Two-tailed p-value

stats_variance
#

stats.ts view source

(values: number[], mean?: number | undefined): number

Calculate the variance of an array of numbers.

values

type number[]

mean?

type number | undefined
optional

returns

number

stats_welch_t_test
#

stats.ts view source

(mean1: number, std1: number, n1: number, mean2: number, std2: number, n2: number): StatsWelchTTestResult

Calculate Welch's t-test statistic and degrees of freedom. Welch's t-test is more robust than Student's t-test when variances are unequal.

mean1

Mean of first sample

type number

std1

Standard deviation of first sample

type number

n1

Size of first sample

type number

mean2

Mean of second sample

type number

std2

Standard deviation of second sample

type number

n2

Size of second sample

type number

returns

StatsWelchTTestResult

StatsConfidenceIntervalOptions
#

stats.ts view source

StatsConfidenceIntervalOptions

Configuration options for confidence interval calculation.

z_score

Z-score for confidence level (default: 1.96 for 95% CI)

type number

confidence_level

Confidence level (0-1), alternative to z_score. If both provided, z_score takes precedence.

type number

StatsOutlierResult
#

stats.ts view source

StatsOutlierResult

Result from outlier detection.

cleaned

Values after removing outliers

type Array<number>

outliers

Detected outlier values

type Array<number>

StatsOutliersIqrOptions
#

stats.ts view source

StatsOutliersIqrOptions

Configuration options for IQR outlier detection.

iqr_multiplier

Multiplier for IQR bounds (default: 1.5)

type number

min_sample_size

Minimum sample size to perform outlier detection (default: 3)

type number

StatsOutliersMadOptions
#

stats.ts view source

StatsOutliersMadOptions

Configuration options for MAD outlier detection.

z_score_threshold

Modified Z-score threshold for outlier detection (default: 3.5)

type number

z_score_extreme

Extreme Z-score threshold when too many outliers detected (default: 5.0)

type number

mad_constant

MAD constant for normal distribution (default: 0.6745)

type number

outlier_ratio_high

Ratio threshold to switch to extreme mode (default: 0.3)

type number

outlier_ratio_extreme

Ratio threshold to switch to keep-closest mode (default: 0.4)

type number

outlier_keep_ratio

Ratio of values to keep in keep-closest mode (default: 0.8)

type number

min_sample_size

Minimum sample size to perform outlier detection (default: 3)

type number

iqr_options

Options to pass to IQR fallback when MAD is zero

StatsWelchTTestResult
#

stats.ts view source

StatsWelchTTestResult

Result from Welch's t-test calculation.

t_statistic

The t-statistic

type number

degrees_of_freedom

Welch-Satterthwaite degrees of freedom

type number

Stopwatch
#

string_display_width
#

string.ts view source

(str: string): number

Calculate the display width of a string in terminal columns. - Strips ANSI escape codes (they have 0 width) - Emojis and other wide characters take 2 columns - Tab characters take 4 columns - Newlines and other control characters take 0 columns - Uses Intl.Segmenter to properly handle grapheme clusters (e.g., family emoji "๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ")

str

type string

returns

number

string_is_binary
#

string.ts view source

(content: string): boolean

Check if content appears to be binary.

Checks for null bytes in the first 8KB of content.

content

Content to check.

type string

returns

boolean

True if content appears to be binary.

stringify
#

string.ts view source

(value: unknown): string

Stringifies a value like JSON.stringify but with some corner cases handled better.

value

type unknown

returns

string

strip_after
#

string.ts view source

(source: string, stripped: string): string

Removes characters inclusive of stripped.

source

type string

stripped

type string

returns

string

strip_ansi
#

string.ts view source

(str: string): string

Strips ANSI escape sequences from a string

str

type string

returns

string

strip_before
#

string.ts view source

(source: string, stripped: string): string

Removes characters inclusive of stripped.

source

type string

stripped

type string

returns

string

strip_end
#

string.ts view source

(source: string, stripped: string): string

Removes characters inclusive of stripped.

source

type string

stripped

type string

returns

string

strip_start
#

string.ts view source

(source: string, stripped: string): string

Removes characters inclusive of stripped.

source

type string

stripped

type string

returns

string

swallow
#

dom.ts view source

<T extends Pick<Event, "preventDefault" | "stopPropagation" | "stopImmediatePropagation">>(event: T, immediate?: boolean, preventDefault?: boolean): T

Stops an event from bubbling and doing default behavior.

event

type T

immediate

defaults to true to use stopImmediatePropagation over stopPropagation

type boolean
default true

preventDefault

defaults to true

type boolean
default true

returns

T

throttle
#

throttle.ts view source

<T extends (...args: Array<any>) => Promise<void>>(cb: T, { delay, when }?: ThrottleOptions): T

Throttles calls to a callback that returns a void promise. Immediately invokes the callback on the first call unless leading=false. If the throttled function is called while the promise is already pending, the call is queued to run after the pending promise completes plus delay, and only the last call is invoked. In other words, all calls and their args are discarded during the pending window except for the most recent. Unlike debouncing, this calls the throttled callback both on the leading and trailing edges of the delay window by default, and this can be customized by setting leading or `trailing. It also differs from a queue where every call to the throttled callback eventually runs.

cb

type T

__1

default EMPTY_OBJECT

returns

T

same as cb

ThrottleOptions
#

throttle.ts view source

ThrottleOptions

delay

Enforced milliseconds between calls. For when='trailing' this is the debounce delay.

type number

when

When to call the throttled function. Defaults to both.

type 'both' | 'leading' | 'trailing'

Thunk
#

function.ts view source

Thunk<T>

Represents a value wrapped in a function. Useful for lazy values and bridging reactive boundaries in Svelte.

generics

T

time_async
#

time.ts view source

<T>(fn: () => Promise<T>, timer?: Timer): Promise<{ result: T; timing: TimeResult; }>

Time an asynchronous function execution.

fn

Async function to time

type () => Promise<T>

timer

Timer to use (defaults to timer_default)

type Timer
default timer_default

returns

Promise<{ result: T; timing: TimeResult; }>

Object containing the function result and timing information

examples

const {result, timing} = await time_async(async () => { await fetch('https://api.example.com/data'); return 42; }); console.log(`Result: ${result}, took ${time_format_adaptive(timing.elapsed_ns)}`);

time_format
#

time.ts view source

(ns: number, unit: TimeUnit, decimals?: number): string

Format time with a specific unit.

ns

Time in nanoseconds

type number

unit

Unit to use ('ns', 'us', 'ms', 's')

decimals

Number of decimal places (default: 2)

type number
default 2

returns

string

Formatted string like "3.87ฮผs"

time_format_adaptive
#

time.ts view source

(ns: number, decimals?: number): string

Format time with adaptive units (ns/ฮผs/ms/s) based on magnitude.

ns

Time in nanoseconds

type number

decimals

Number of decimal places (default: 2)

type number
default 2

returns

string

Formatted string like "3.87ฮผs" or "1.23ms"

examples

time_format_adaptive(1500) // "1.50ฮผs" time_format_adaptive(3870) // "3.87ฮผs" time_format_adaptive(1500000) // "1.50ms" time_format_adaptive(1500000000) // "1.50s"

time_measure
#

time.ts view source

(fn: () => unknown, iterations: number, timer?: Timer): Promise<number[]>

Measure multiple executions of a function and return all timings.

fn

Function to measure (sync or async)

type () => unknown

iterations

Number of times to execute

type number

timer

Timer to use (defaults to timer_default)

type Timer
default timer_default

returns

Promise<number[]>

Array of elapsed times in nanoseconds

examples

const timings_ns = await time_measure(async () => { await process_data(); }, 100); import {BenchmarkStats} from './benchmark_stats.js'; const stats = new BenchmarkStats(timings_ns); console.log(`Mean: ${time_format_adaptive(stats.mean_ns)}`);

TIME_NS_PER_MS
#

TIME_NS_PER_SEC
#

TIME_NS_PER_US
#

time_ns_to_ms
#

time.ts view source

(ns: number): number

Convert nanoseconds to milliseconds.

ns

type number

returns

number

time_ns_to_sec
#

time.ts view source

(ns: number): number

Convert nanoseconds to seconds.

ns

type number

returns

number

time_ns_to_us
#

time.ts view source

(ns: number): number

Convert nanoseconds to microseconds.

ns

type number

returns

number

time_sync
#

time.ts view source

<T>(fn: () => T, timer?: Timer): { result: T; timing: TimeResult; }

Time a synchronous function execution.

fn

Sync function to time

type () => T

timer

Timer to use (defaults to timer_default)

type Timer
default timer_default

returns

{ result: T; timing: TimeResult; }

Object containing the function result and timing information

examples

const {result, timing} = time_sync(() => { return expensive_computation(); }); console.log(`Result: ${result}, took ${time_format_adaptive(timing.elapsed_ns)}`);

time_unit_detect_best
#

time.ts view source

(values_ns: number[]): TimeUnit

Detect the best time unit for a set of nanosecond values. Chooses the unit where most values fall in the range 1-9999.

values_ns

Array of times in nanoseconds

type number[]

returns

TimeUnit

Best unit to use for all values

TIME_UNIT_DISPLAY
#

time.ts view source

Record<TimeUnit, string>

Display labels for time units (uses proper Unicode ฮผ for microseconds).

Timer
#

time.ts view source

Timer

Timer interface for measuring elapsed time. Returns time in nanoseconds for maximum precision.

now

Get current time in nanoseconds

type () => number

timer_browser
#

time.ts view source

Timer

Browser high-resolution timer using performance.now(). Converts milliseconds to nanoseconds for consistent API.

Precision varies by browser due to Spectre/Meltdown mitigations: - Chrome: ~100ฮผs (coarsened) - Firefox: ~1ms (rounded) - Safari: ~100ฮผs - Node.js: ~1ฮผs

For nanosecond-precision benchmarks, use Node.js with timer_node.

timer_default
#

time.ts view source

Timer

Auto-detected timer based on environment. Uses process.hrtime in Node.js, performance.now() in browsers. The timer function is detected once and cached for performance.

timer_node
#

time.ts view source

Timer

Node.js high-resolution timer using process.hrtime.bigint(). Provides true nanosecond precision.

TimeResult
#

time.ts view source

TimeResult

Result from timing a function execution. All times in nanoseconds for maximum precision.

elapsed_ns

Elapsed time in nanoseconds

type number

elapsed_us

Elapsed time in microseconds (convenience)

type number

elapsed_ms

Elapsed time in milliseconds (convenience)

type number

started_at_ns

Start time in nanoseconds (from timer.now())

type number

ended_at_ns

End time in nanoseconds (from timer.now())

type number

TimeUnit
#

Timings
#

timings.ts view source

Tracks and manages multiple timing operations. Allows starting, stopping, and retrieving timings with optional precision.

decimals

type number | undefined

readonly

constructor

type new (decimals?: number | undefined): Timings

decimals?
type number | undefined
optional

start

Starts a timing operation for the given key.

type (key: TimingsKey, decimals?: number | undefined): () => number

key
decimals
type number | undefined
default this.decimals
returns () => number

get

type (key: TimingsKey): number

key
returns number

entries

type (): IterableIterator<[TimingsKey, number | undefined]>

returns IterableIterator<[TimingsKey, number | undefined]>

merge

Merges other timings into this one, adding together values with identical keys.

type (timings: Timings): void

timings
type Timings
returns void

TimingsKey
#

to_array
#

array.ts view source

<T>(value: T): T extends readonly any[] ? T : T[]

Converts value to an array if it's not already.

value

type T

returns

T extends readonly any[] ? T : T[]

to_bytes
#

bytes.ts view source

(data: string | BufferSource): Uint8Array<ArrayBufferLike>

Converts string or binary data to a Uint8Array. Strings are UTF-8 encoded. Uint8Array inputs are returned as-is.

data

String or BufferSource to convert.

type string | BufferSource

returns

Uint8Array<ArrayBufferLike>

Uint8Array view of the data.

to_fetch_value_cache_key
#

fetch.ts view source

(url: string, params: any, method: string): FetchValueCacheKey

url

type string

params

type any

method

type string

returns

FetchValueCacheKey

to_file_path
#

path.ts view source

(path_or_url: string | URL): string

Converts a URL to a file path string, or returns the string as-is.

path_or_url

type string | URL

returns

string

to_hex
#

hex.ts view source

(bytes: Uint8Array<ArrayBufferLike>): string

Converts a Uint8Array to a lowercase hex string.

bytes

Binary data to encode.

type Uint8Array<ArrayBufferLike>

returns

string

Hex string with two characters per byte.

to_hex_component
#

to_next
#

array.ts view source

<T extends ReadonlyArray<any>>(array: T): () => ArrayElement<T>

Returns a function that returns the next item in the array in a linear sequence, looping back to index 0 when it reaches the end.

array

type T

returns

() => ArrayElement<T>

topological_sort
#

sort.ts view source

<T extends Sortable>(items: T[], label?: string): TopologicalSortResult<T>

Sort items by their dependencies using Kahn's algorithm.

Returns items ordered so that dependencies come before dependents. If a cycle is detected, returns an error with the cycle path.

items

Array of items to sort.

type T[]

label

Label for error messages (e.g. "resource", "step").

type string
default 'item'

returns

TopologicalSortResult<T>

Sorted items or error if cycle detected.

TopologicalSortResult
#

transform_empty_object_to_undefined
#

traverse
#

object.ts view source

(obj: any, cb: (key: string, value: any, obj: any) => void): void

Performs a depth-first traversal of an object's enumerable properties, calling cb for every key and value with the current obj context.

obj

any object with enumerable properties

type any

cb

receives the key, value, and obj for every enumerable property on obj and its descendents

type (key: string, value: any, obj: any) => void

returns

void

truncate
#

string.ts view source

(str: string, maxLength: number, suffix?: string): string

Truncates a string to a maximum length, adding a suffix if needed that defaults to ....

str

type string

maxLength

type number

suffix

type string
default '...'

returns

string

try_extract_conditional_chain
#

svelte_preprocess_helpers.ts view source

(value: true | ExpressionTag | (ExpressionTag | Text)[], source: string, bindings: ReadonlyMap<string, string>): ConditionalChainBranch[] | null

Extracts a chain of conditional expressions where all leaf values are static strings.

Handles nested ternaries like a ? 'x' : b ? 'y' : 'z' by iteratively walking the right-recursive ConditionalExpression chain. At each level, evaluates the consequent via evaluate_static_expr and continues into the alternate if it is another ConditionalExpression. The final alternate is the else branch.

Returns null if the attribute value is not an ExpressionTag containing a ConditionalExpression, if any leaf fails to resolve to a static string, or if the chain exceeds 10 branches (safety limit).

A 2-branch result covers the simple ternary case (a ? 'x' : 'y').

value

The attribute value from AST.Attribute['value'].

type true | ExpressionTag | (ExpressionTag | Text)[]

source

The full source string (needed to slice test expression source text).

type string

bindings

Map of variable names to their resolved static string values.

type ReadonlyMap<string, string>

returns

ConditionalChainBranch[] | null

Array of conditional chain branches, or null if not extractable.

unreachable
#

error.ts view source

(value: never, message?: string | undefined): asserts value is never

Beyond terseness, this is useful because throw is not an expression, and therefore can't be used in places like Svelte markup without a workaround, at least until this proposal is accepted and widely available: https://github.com/tc39/proposal-throw-expressions

value

type never

message?

type string | undefined
optional

returns

void

UnreachableError
#

error.ts view source

Error for asserting unreachable code paths in TypeScript. Useful for exhaustive matching.

inheritance

extends:
  • Error

constructor

type new (value: never, message?: string, options?: ErrorOptions | undefined): UnreachableError

value
type never
message
type string
default `Unreachable case: ${value}`
options?
type ErrorOptions | undefined
optional

unthunk
#

function.ts view source

<T>(value: T | Thunk<T>): T

Returns the result of calling value if it's a function, otherwise it's like the identity function and passes it through.

value

type T | Thunk<T>

returns

T

unwrap
#

result.ts view source

<TValue extends { value?: unknown; }, TError extends { message?: string; }>(result: Result<TValue, TError>, message?: string | undefined): TValue["value"]

A helper that says, "hey I know this is wrapped in a Result, but I expect it to be ok, so if it's not, I understand it will throw an error that wraps the result".

result

Some Result object.

type Result<TValue, TError>

message?

Optional custom error message.

type string | undefined
optional

returns

TValue["value"]

The wrapped value.

unwrap_error
#

result.ts view source

<TError extends object>(result: Result<object, TError>, message?: string): { ok: false; } & TError

A helper that does the opposite of unwrap, throwing if the Result is ok. Note that while unwrap returns the wrapped value, unwrap_error returns the entire result.

result

Some Result object.

type Result<object, TError>

message

Optional custom error message.

type string
default 'Failed to unwrap result error'

returns

{ ok: false; } & TError

The type-narrowed result.

Url
#

Uuid
#

UUID_MATCHER
#

wait
#

async.ts view source

(duration?: number): Promise<void>

Waits for the given duration before resolving.

duration

type number
default 0

returns

Promise<void>

zod_extract_fields
#

zod.ts view source

(schema: ZodObject<$ZodLooseShape, $strip>): ZodFieldInfo[]

Extract field metadata from a Zod object schema.

schema

Zod object schema to extract from

type ZodObject<$ZodLooseShape, $strip>

returns

ZodFieldInfo[]

array of field info for each property

zod_format_value
#

zod.ts view source

(value: unknown): string

Format a value for display in help text.

value

Value to format.

type unknown

returns

string

Formatted string representation.

zod_get_base_type
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): string

Get the base type name for a Zod schema, unwrapping all wrappers.

schema

Zod schema to inspect

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

string

base type name (e.g. 'string', 'object', 'uuid')

zod_has_default
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): boolean

Check if a schema has a default value at any wrapping level.

Unlike zod_to_schema_default (which returns the value), this returns a boolean. Distinguishes "no default" from "default is undefined".

schema

Zod schema to check

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

boolean

zod_is_nullable
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): boolean

Check if a schema accepts null at any wrapping level.

schema

Zod schema to check

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

boolean

zod_is_optional
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): boolean

Check if a schema is optional at the outermost level.

schema

Zod schema to check

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

boolean

zod_to_schema_aliases
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): string[]

Get aliases from a schema's metadata, unwrapping if needed.

schema

Zod schema to extract aliases from.

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

string[]

Array of alias strings.

zod_to_schema_default
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): unknown

Get the default value from a schema, unwrapping if needed.

schema

Zod schema to extract default from.

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

unknown

Default value or undefined.

zod_to_schema_description
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): string | null

Get the description from a schema's metadata, unwrapping if needed.

schema

Zod schema to extract description from.

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

string | null

Description string or null if not found.

zod_to_schema_names_with_aliases
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): Set<string>

Get all property names and their aliases from an object schema.

schema

Zod object schema.

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

Set<string>

Set of all names and aliases.

zod_to_schema_properties
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): ZodSchemaProperty[]

Extract properties from a Zod object schema.

schema

Zod object schema to extract from.

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

ZodSchemaProperty[]

Array of property definitions.

zod_to_schema_type_string
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): string

Get the type string for a schema, suitable for display.

schema

Zod schema to get type string for.

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

string

Human-readable type string.

zod_to_subschema
#

zod.ts view source

(def: $ZodTypeDef): ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined

Unwrap nested schema types (optional, default, nullable, etc).

def

Zod type definition to unwrap.

type $ZodTypeDef

returns

ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined

Inner schema if wrapped, undefined otherwise.

zod_unwrap_def
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): $ZodTypeDef

Unwrap Zod wrappers (optional, default, nullable, pipe, transform) to get the base type definition.

schema

Zod schema to unwrap

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

$ZodTypeDef

the innermost non-wrapper type definition

zod_unwrap_to_object
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): ZodObject<$ZodLooseShape, $strip> | null

Unwrap a schema to find the inner ZodObject, or null if not an object schema. Handles wrappers like z.strictObject({...}).default({...}).

schema

Zod schema to unwrap

type ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

returns

ZodObject<$ZodLooseShape, $strip> | null

the inner ZodObject or null

ZOD_WRAPPER_TYPES
#

ZodFieldInfo
#

zod.ts view source

ZodFieldInfo

Metadata extracted from a single field of a Zod object schema.

name

type string

base_type

type string

required

type boolean

has_default

type boolean

nullable

type boolean

ZodSchemaProperty
#

zod.ts view source

ZodSchemaProperty

Property extracted from an object schema.

name

type string

type

type string

description

type string

default

type unknown

aliases

type Array<string>