api #

utility belt for JS

58 modules · 454 declarations

Modules
#

Args
#

args.ts view source

Args import type {Args} from '@fuzdev/fuz_util/args.js';

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>

[key: string]

type ArgValue

args_extract_aliases
#

args.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): ArgsAliasesResult import {args_extract_aliases} from '@fuzdev/fuz_util/args.js';

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

args_parse
#

args.ts view source

<TOutput extends Record<string, ArgValue> = Args>(unparsed_args: Args, schema: ZodType<TOutput, unknown, $ZodTypeInternals<TOutput, unknown>>): ZodSafeParseResult<...> import {args_parse} from '@fuzdev/fuz_util/args.js';

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>

z.ZodSafeParseResult with expanded/synced data on success

generics

args_parse<TOutput extends Record<string, ArgValue> = Args>
TOutput
constraint Record<string, ArgValue>
default Args

args_serialize
#

args.ts view source

(args: Args, schema?: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined): string[] import {args_serialize} from '@fuzdev/fuz_util/args.js';

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

type Args

schema?

optional zod schema to extract aliases for short form preference

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

returns

string[]

args_validate_schema
#

args.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): { success: true; } | { success: false; error: ZodError<unknown>; } import {args_validate_schema} from '@fuzdev/fuz_util/args.js';

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 import type {ArgsAliasesResult} from '@fuzdev/fuz_util/args.js';

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 import type {ArgSchema} from '@fuzdev/fuz_util/args.js';

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

type ArgValue

description

type string

argv_parse
#

args.ts view source

(argv: string[]): ParsedArgs import {argv_parse} from '@fuzdev/fuz_util/args.js';

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
#

args.ts view source

ArgValue import type {ArgValue} from '@fuzdev/fuz_util/args.js';

Value types supported in CLI arguments.

ArrayElement
#

types.ts view source

ArrayElement<T> import type {ArrayElement} from '@fuzdev/fuz_util/types.js';

generics

ArrayElement<T>
T

assert_property
#

testing.ts view source

<R extends object, P extends keyof R, const V extends R[P]>(obj: R, property: P, value: V): asserts obj is Extract<R, Record<P, V>> import {assert_property} from '@fuzdev/fuz_util/testing.js';

Narrows a discriminated union by a literal property value, failing the test if the value doesn't match. The assertion signature propagates the narrowed type so callers can access variant-specific fields directly.

Works with any discriminator key (kind, ok, type, _tag, etc.).

obj

type R

property

type P

value

type V

returns

void

generics

assert_property<R extends object, P extends keyof R, V extends R[P]>
R
constraint object
P
constraint keyof R
V
constraint R[P]

examples

type Shape = | {kind: 'circle'; radius: number} | {kind: 'square'; side: number}; const shape: Shape = get_shape(); assert_property(shape, 'kind', 'circle'); assert.strictEqual(shape.radius, 5); // `radius` now typed as `number`

assert_rejects
#

testing.ts view source

(fn: () => Promise<unknown>, pattern?: RegExp | undefined): Promise<Error> import {assert_rejects} from '@fuzdev/fuz_util/testing.js';

Asserts that fn rejects with an Error. Optionally matches the error message against pattern. Returns the caught Error for further assertions by the caller.

assert.fail is placed after the catch block so that assertion failures from the test itself are not swallowed by the catch.

fn

async function expected to reject

type () => Promise<unknown>

pattern?

optional regex to match against the error message

type RegExp | undefined
optional

returns

Promise<Error>

the caught Error

Assignable
#

types.ts view source

Assignable<T, K> import type {Assignable} from '@fuzdev/fuz_util/types.js';

generics

Assignable<T, K extends keyof T = keyof T>
T
K
constraint keyof T
default keyof T

AsyncSemaphore
#

async.ts view source

import {AsyncSemaphore} from '@fuzdev/fuz_util/async.js';

Async semaphore for concurrency limiting.

With Infinity permits, acquire() always resolves immediately.

constructor

type new (permits: number): AsyncSemaphore

permits

type number

throws

  • Error - if `permits < 0`

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 import {attach_process_error_handler} from '@fuzdev/fuz_util/process.js';

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

import {Benchmark} from '@fuzdev/fuz_util/benchmark.js';

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

bench.add('simple', () => fn()); // Or with setup/teardown: bench.add({ name: 'with setup', fn: () => process(data), setup: () => { data = load() }, teardown: () => { cleanup() }, });

throws

  • Error - if a task with the same name already exists, or if `fn` is missing when `name` is a string

remove

Remove a benchmark task by name.

type (name: string): this

name

type string
returns this

this Benchmark instance for chaining

bench.add('task1', () => fn1()); bench.add('task2', () => fn2()); bench.remove('task1'); // Only task2 remains

throws

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

run

Run all benchmark tasks.

Tasks execute in add() order. The first task runs against a colder runtime than subsequent ones (uncompiled JS, cold caches) — a property of in-process benchmarking that matters more when an early task has aggressive overrides like low warmup_iterations or min_iterations. If first-position bias is a concern, put a throwaway warm-up task first, or call run() twice and use the second result set.

type (): Promise<BenchmarkResult[]>

returns Promise<BenchmarkResult[]>

table

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

type (options?: BenchmarkFormatTableOptions | undefined): string

options?

type BenchmarkFormatTableOptions | undefined
optional
returns string
// Standard table console.log(bench.table()); // Grouped by category console.log(bench.table({ groups: [ { name: 'FAST PATHS', filter: (r) => r.name.includes('fast') }, { name: 'SLOW PATHS', filter: (r) => r.name.includes('slow') }, ] }));

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

// Standard table console.log(bench.markdown()); // Grouped by category with custom baseline console.log(bench.markdown({ groups: [ { name: 'Format', filter: (r) => r.name.startsWith('format/'), baseline: 'format/prettier' }, { name: 'Parse', filter: (r) => r.name.startsWith('parse/') }, ] }));

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.

type (): BenchmarkResult[]

returns BenchmarkResult[]

shallow copy of the results array (prevents external mutation)

results_by_name

Get results as a map for convenient lookup by task name.

type (): Map<string, BenchmarkResult>

returns Map<string, BenchmarkResult>

fresh Map of task name to benchmark result (prevents external mutation)

const results_map = bench.results_by_name(); const slugify_result = results_map.get('slugify'); if (slugify_result) { console.log(`slugify: ${slugify_result.stats.ops_per_second} ops/sec`); }

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).

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

console.log(bench.summary()); // "Fastest: slugify_v2 (1,285,515.00 ops/sec, 786.52ns per op)" // "Slowest: slugify (252,955.00 ops/sec, 3.95μs per op)" // "Speed difference: 5.08x"

has_results

Check if the benchmark has been run and has results.

type boolean

getter
if (bench.has_results) { console.log(bench.table()); }

benchmark_baseline_compare
#

benchmark_baseline.ts view source

(results: BenchmarkResult[], options?: BenchmarkBaselineCompareOptions): Promise<BenchmarkBaselineComparisonResult> import {benchmark_baseline_compare} from '@fuzdev/fuz_util/benchmark_baseline.js';

Compare benchmark results against the stored baseline.

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 import {benchmark_baseline_format_json} from '@fuzdev/fuz_util/benchmark_baseline.js';

Format a baseline comparison result as JSON for programmatic consumption.

result

comparison result from benchmark_baseline_compare

options

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

returns

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: { ...; }[]; metadata?: Record<...> | undefined; } | null> import {benchmark_baseline_load} from '@fuzdev/fuz_util/benchmark_baseline.js';

Load the current baseline from disk.

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; ... 9 more ...; budget: { ...; }; }[]; metadata?: Record<...> | undefined; } | 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> import {benchmark_baseline_save} from '@fuzdev/fuz_util/benchmark_baseline.js';

Save benchmark results as the current baseline.

Each entry's effective time-budget (duration_ms, warmup_iterations, min_iterations, max_iterations) is persisted alongside the stats so a later benchmark_baseline_compare can detect methodology drift — a budget mismatch between baseline and current routes the task to the methodology_changed bucket instead of producing false regressions / improvements. Suite-level config (timer, cooldown_ms) is *not* persisted; keep it stable across runs in the same baseline lineage.

results

type BenchmarkResult[]

options

default {}

returns

Promise<void>

throws

  • Error - if creating the baseline directory or writing the file fails

examples

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

benchmark_budget_diff
#

benchmark_baseline.ts view source

(baseline: { duration_ms: number; warmup_iterations: number; min_iterations: number; max_iterations: number; async_resolved: boolean; }, current: { duration_ms: number; warmup_iterations: number; min_iterations: number; max_iterations: number; async_resolved: boolean; }): BenchmarkBudgetDiffEntry[] import {benchmark_budget_diff} from '@fuzdev/fuz_util/benchmark_baseline.js';

Compute the per-field diff between two effective budgets. Returns an empty array if budgets are identical — the formatters use the length as a quick "methodology changed?" check without re-deriving the boolean.

baseline

type { duration_ms: number; warmup_iterations: number; min_iterations: number; max_iterations: number; async_resolved: boolean; }

current

type { duration_ms: number; warmup_iterations: number; min_iterations: number; max_iterations: number; async_resolved: boolean; }

returns

BenchmarkBudgetDiffEntry[]

benchmark_format_json
#

benchmark_format.ts view source

(results: BenchmarkResult[], options?: BenchmarkFormatJsonOptions | undefined): string import {benchmark_format_json} from '@fuzdev/fuz_util/benchmark_format.js';

Format results as JSON.

results

type BenchmarkResult[]

options?

type BenchmarkFormatJsonOptions | undefined
optional

returns

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 import {benchmark_format_markdown} from '@fuzdev/fuz_util/benchmark_format.js';

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

results

type BenchmarkResult[]

baseline?

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

type string | undefined
optional

returns

string

throws

  • Error - if `baseline` is provided but no result has that name

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 import {benchmark_format_markdown_grouped} from '@fuzdev/fuz_util/benchmark_format.js';

Format results as grouped Markdown tables with headers between groups.

results

type BenchmarkResult[]

groups

type BenchmarkGroup[]

returns

string

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 import {benchmark_format_number} from '@fuzdev/fuz_util/benchmark_format.js';

Format a number with fixed decimal places and thousands separators.

see also

  • ``format_number`` in maths.ts for the underlying implementation.

benchmark_format_table
#

benchmark_format.ts view source

(results: BenchmarkResult[], baseline?: string | undefined): string import {benchmark_format_table} from '@fuzdev/fuz_util/benchmark_format.js';

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

results

type BenchmarkResult[]

baseline?

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

type string | undefined
optional

returns

string

throws

  • Error - if `baseline` is provided but no result has that name

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 import {benchmark_format_table_grouped} from '@fuzdev/fuz_util/benchmark_format.js';

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

results

type BenchmarkResult[]

groups

type BenchmarkGroup[]

returns

string

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 import {benchmark_stats_compare} from '@fuzdev/fuz_util/benchmark_stats.js';

Compare two benchmark results for practical and statistical significance. Uses percentage difference for effect magnitude classification, with Welch's t-test for statistical confidence. Cohen's d is computed as an informational metric but does not drive classification — its thresholds (0.2/0.5/0.8) are calibrated for social science and produce false positives in benchmarking where within-run variance is tight.

a

first benchmark stats (or any object with required properties)

b

second benchmark stats (or any object with required properties)

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> import {benchmark_warmup} from '@fuzdev/fuz_util/benchmark.js';

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

When no async_hint is provided, at least one detection iteration runs even if iterations is 0 — otherwise async detection would be impossible and async functions would have their returned promises leaked as unhandled.

fn

function to warmup (sync or async)

type () => unknown

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<...>; metadata: ZodOptional<...>; }, $strip> import type {BenchmarkBaseline} from '@fuzdev/fuz_util/benchmark_baseline.js';

Schema for the complete baseline file.

metadata is an opt-in passthrough bag for context that applies to the whole run but isn't part of the comparison math — corpus identity (file counts, total bytes), dependency versions, binary sizes, hardware notes, build flags. Pass it on save and read it back on load; it's not interpreted by benchmark_baseline_compare. The intended use is to let consumers attach "did this run measure the same thing as the baseline?" context (e.g. corpus shape) without forking the schema, then surface mismatches in their own reporting. fuz_util doesn't surface metadata in comparison output because it has no shape — consumers know what their metadata means and how to display the diff.

BenchmarkBaselineCompareOptions
#

benchmark_baseline.ts view source

BenchmarkBaselineCompareOptions import type {BenchmarkBaselineCompareOptions} from '@fuzdev/fuz_util/benchmark_baseline.js';

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

min_percent_difference?

Minimum percentage difference to consider meaningful, as a ratio. Passed through to benchmark_stats_compare. See BenchmarkCompareOptions. Default: 0.10 (10%)

type number

noise_warning_cv_threshold?

Coefficient of variation (std_dev / mean) at or above which a comparison is flagged with noise_warning: true. Doesn't affect bucketing — the task still routes to regressions / improvements / unchanged as the Welch math dictates — but tells the formatter (and any custom consumer) that the underlying measurement is noisy enough that a "significant" call should be read with skepticism. The default is calibrated for system-noise/thermal/background-load contamination, not microbenchmark floor effects; lower it (e.g. 0.15) for sub-microsecond functions where any cv signal matters, raise it for inherently noisy workloads where 0.3 fires on every run. Default: 0.30

type number

noise_warning_outlier_ratio_threshold?

Outlier ratio (fraction of iterations rejected by MAD outlier removal) at or above which the comparison is flagged with noise_warning: true, OR-gated with the cv check. Catches the case where the post-cleaning cv looks tight because outlier removal already deflated the spread — a third of the iterations being tail events is itself a noise signal, even if the surviving samples cluster cleanly. Set higher (e.g. 0.2) for benchmarks where outliers are expected (allocator-bound, async I/O), lower (e.g. 0.05) for tight CPU loops. Default: 0.10

type number

BenchmarkBaselineComparisonResult
#

benchmark_baseline.ts view source

BenchmarkBaselineComparisonResult import type {BenchmarkBaselineComparisonResult} from '@fuzdev/fuz_util/benchmark_baseline.js';

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

baseline_node_version

Node.js version recorded in the baseline (null if no baseline).

type string | null

current_node_version

Node.js version of the process that produced the current results.

type string

node_version_changed

True if the baseline's node version differs from the current process. Informational only — surfaced in the comparison header so readers can apply the caveat across all task comparisons; does not affect per-task classification (Node bumps affect every task uniformly).

type boolean

baseline_metadata

The metadata bag persisted in the baseline file, or null if the baseline didn't have one (or no baseline was found). Returned verbatim — fuz_util doesn't validate the shape or diff it against any "current run" metadata. If the consumer needs a diff, they pass options.metadata (current-run context) and walk the two records themselves.

type Record<string, unknown> | null

comparisons

Individual task comparisons for tasks where Welch's math is meaningful — i.e., budget unchanged between baseline and current. Methodology-changed tasks are NOT in here; they live in methodology_changed. Excluding them here keeps aggregate reads of c.comparison.faster / c.comparison.speedup_ratio / c.comparison.recommendation safe — those fields are still computed for methodology-changed rows but answer a counterfactual question (the math is correct over mismatched sample sizes) and would mislead consumers iterating this array.

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>

methodology_changed

Tasks whose effective budget differs between baseline and current. Excluded from regressions/improvements/unchanged because the Welch comparison is contaminated by sample-size or warmup differences — the math is correct but answers a different question than the reader thinks. Re-save the baseline after intentional methodology changes to surface any genuine drift that was masked.

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; ... 7 more ...; budget: ZodObject<...>; }, $strip> import type {BenchmarkBaselineEntry} from '@fuzdev/fuz_util/benchmark_baseline.js';

Schema for a single benchmark entry in the baseline.

outlier_ratio is persisted as a noise signal independent of the post-cleaning std_dev_ns/cv: outlier removal *deflates* std_dev (the cleaned set is by construction less variable than the raw set), so cv alone misses runs where a third of the iterations were tail events. benchmark_baseline_compare OR-gates noise_warning on this field so a noisy raw distribution gets flagged even when the cleaned cv looks tight.

BenchmarkBaselineLoadOptions
#

benchmark_baseline.ts view source

BenchmarkBaselineLoadOptions import type {BenchmarkBaselineLoadOptions} from '@fuzdev/fuz_util/benchmark_baseline.js';

Options for loading a baseline.

path?

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

type string

BenchmarkBaselineSaveOptions
#

benchmark_baseline.ts view source

BenchmarkBaselineSaveOptions import type {BenchmarkBaselineSaveOptions} from '@fuzdev/fuz_util/benchmark_baseline.js';

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

metadata?

Opt-in passthrough for run-level context (corpus identity, dependency versions, binary sizes, hardware notes). Round-trips on _load and is accessible via BenchmarkBaselineComparisonResult.baseline_metadata, but is *not* interpreted by _compare — consumers decide what to do with mismatches. Keep values JSON-serializable; this is written verbatim to the baseline file.

type Record<string, unknown>

BenchmarkBaselineTaskComparison
#

benchmark_baseline.ts view source

BenchmarkBaselineTaskComparison import type {BenchmarkBaselineTaskComparison} from '@fuzdev/fuz_util/benchmark_baseline.js';

Comparison result for a single task.

name

type string

baseline

type BenchmarkBaselineEntry

current

type BenchmarkBaselineEntry

comparison

Welch comparison of baseline vs. current means.

When the row is in methodology_changed, every field of this object is contaminated by sample-size or warmup differences — not just recommendation. The Welch math runs end-to-end and populates faster, speedup_ratio, significant, p_value, percent_difference, effect_size, effect_magnitude, ci_overlap, and recommendation, but it's comparing distributions produced under different methodologies. Treat the result as diagnostic ("how dramatic is the contamination?"), not authoritative.

The built-in formatters (benchmark_baseline_format, benchmark_baseline_format_json) never render comparison.* for methodology-changed rows for this reason — they show only the budget diff. Custom consumers reading this field directly should check methodology_changed first.

type BenchmarkComparison

methodology_changed

True if the effective time budget differs between baseline and current. When set, the task is routed to methodology_changed instead of regressions/improvements/unchanged, and the comparison field's contents become unreliable per the doc above.

type boolean

noise_warning

True when measurement noise is high enough to undermine the significance call on this row. OR-gated across two signals: - max(baseline.cv, current.cv) >= noise_warning_cv_threshold where cv = std_dev_ns / mean_ns (post-outlier-removal). - `max(baseline.outlier_ratio, current.outlier_ratio) >= noise_warning_outlier_ratio_threshold`, since outlier removal deflates cv — a high outlier ratio is itself a noise signal even when the cleaned cv looks tight. Independent of methodology_changed. The Welch math still ran; this flag tells the reader to take comparison.significant with skepticism on this row. Cv is recomputed at comparison time from persisted mean_ns/std_dev_ns; outlier_ratio is persisted directly.

type boolean

max_cv

The larger of the two coefficients of variation across baseline and current, exposed so consumers can render the actual noise level. Recomputed at comparison time from persisted mean_ns and std_dev_ns — not a persisted field.

type number

max_outlier_ratio

The larger of the two outlier ratios across baseline and current. Read directly from the persisted entries. Exposed so consumers can render the actual outlier rate alongside noise_warning.

type number

BenchmarkBudget
#

benchmark_types.ts view source

BenchmarkBudget import type {BenchmarkBudget} from '@fuzdev/fuz_util/benchmark_types.js';

Effective time-budget config used to produce a benchmark sample set. Resolved from per-task overrides on top of suite defaults — what the measurement loop actually saw, not what was configured.

async_resolved captures the boolean that benchmark_warmup actually returned for the measurement run — *not* the user's task.async hint. The two diverge when (a) the hint is undefined and the function is auto-detected sync vs. async, or (b) a conditional-async fn resolves differently between runs. Persisting the resolved value is what makes the budget describe "what the loop saw," not "what was configured."

duration_ms

type number

warmup_iterations

type number

min_iterations

type number

max_iterations

type number

async_resolved

type boolean

BenchmarkBudgetDiffEntry
#

benchmark_baseline.ts view source

BenchmarkBudgetDiffEntry import type {BenchmarkBudgetDiffEntry} from '@fuzdev/fuz_util/benchmark_baseline.js';

Per-field diff entry produced by benchmark_budget_diff. The async_resolved entry carries booleans; every other entry carries numbers. Consumers reading baseline/current should narrow on field before using the value arithmetically.

BenchmarkCompareOptions
#

benchmark_stats.ts view source

BenchmarkCompareOptions import type {BenchmarkCompareOptions} from '@fuzdev/fuz_util/benchmark_stats.js';

Options for benchmark comparison.

alpha?

Significance level for hypothesis testing (default: 0.05)

type number

min_percent_difference?

Minimum percentage difference to consider practically meaningful, as a ratio. Below this threshold, differences are classified as 'negligible' and significant is forced to false, regardless of p-value. This prevents the t-test's oversensitivity at large sample sizes from flagging system-level noise (thermal throttle, OS scheduler, cache pressure) as meaningful differences.

Effect magnitude thresholds scale from this value: negligible < min, small < min*3, medium < min*5, large >= min*5.

Default: 0.10 (10%).

type number

BenchmarkComparison
#

benchmark_stats.ts view source

BenchmarkComparison import type {BenchmarkComparison} from '@fuzdev/fuz_util/benchmark_stats.js';

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 both statistically and practically significant

type boolean

p_value

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

type number

percent_difference

Percentage difference between means as a ratio (0.05 = 5%, 1.0 = 100%)

type number

effect_size

Cohen's d effect size (informational — not used for classification)

type number

effect_magnitude

Interpretation of practical significance based on percentage difference

type EffectMagnitude

ci_overlap

Whether the 95% confidence intervals of the two means overlap.

Informational only — do not use this field to infer significance. Two means with overlapping 95% CIs can still differ significantly at p<0.05 (overlap of up to ~25% of CI width is consistent with significance); conversely, non-overlapping CIs are slightly *stronger* than the standard p<0.05 bar but the relationship is not strict. Use significant and p_value for classification. This field is exposed for consumers who want to render CIs side-by-side and need the visual overlap check.

Note: the underlying CIs are computed with a z-score (1.96) rather than the strict t-score, so at small n the CIs are slightly narrow — overlap is reported less often than a t-based CI would. Effect is ~2-3% at the n=30 floor after Bessel's correction on std_dev_ns.

type boolean

recommendation

Human-readable interpretation of the comparison

type string

BenchmarkConfig
#

benchmark_types.ts view source

BenchmarkConfig import type {BenchmarkConfig} from '@fuzdev/fuz_util/benchmark_types.js';

Configuration options for a benchmark suite.

duration_ms?

Target measurement duration per task in milliseconds. The loop runs at least min_iterations iterations *and* at least this long, with max_iterations and on_iteration abort() as hard ceilings. Default: 1000ms

type number

warmup_iterations?

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

type number

cooldown_ms?

Cooldown time between tasks in milliseconds. Lets the runtime settle GC and (partially) thermal state between tasks. Fixed regardless of the previous task's duration or allocation footprint — if a suite mixes heavy and light tasks, raise this so light tasks downstream don't run in the prior task's GC shadow. Default: 100ms

type number

min_iterations?

Minimum number of iterations to run. The loop continues past duration_ms if needed to reach this floor, so raising it in a slow suite extends wall-clock past duration_ms.

The default (30) is sized so the Welch's-t DOF approximation used by benchmark_stats_compare stays stable on the floor case. Lowering it below ~15 produces statistically unreliable significance calls on slow tasks that hit the floor exactly — the math still runs but comparison.significant becomes a coin flip on noisy outliers.

Default: 30

type number

max_iterations?

Maximum number of iterations to run. Prevents infinite loops on extremely fast functions, and also sizes the pre-allocated timings array — set this only as high as you expect to fill, since oversized caps waste memory and add GC pressure during measurement. 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

// Trigger GC between iterations (run node with --expose-gc) new Benchmark({ on_iteration: () => { if (globalThis.gc) globalThis.gc(); } }) // Log progress for long-running benchmarks new Benchmark({ on_iteration: (name, iteration) => { if (iteration % 1000 === 0) { console.log(`${name}: ${iteration} iterations`); } } }) // Stop early when converged new Benchmark({ on_iteration: (name, iteration, abort) => { if (iteration > 1000 && has_stabilized()) abort(); } })

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

new Benchmark({ on_task_complete: (result, index, total) => { console.log(`[${index + 1}/${total}] ${result.name}: ${result.stats.ops_per_second.toFixed(0)} ops/sec`); } })

BenchmarkFormatJsonOptions
#

benchmark_format.ts view source

BenchmarkFormatJsonOptions import type {BenchmarkFormatJsonOptions} from '@fuzdev/fuz_util/benchmark_format.js';

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 import type {BenchmarkFormatTableOptions} from '@fuzdev/fuz_util/benchmark_types.js';

Options for table formatting.

groups?

Group results by category using filter functions.

type Array<BenchmarkGroup>

BenchmarkGroup
#

benchmark_types.ts view source

BenchmarkGroup import type {BenchmarkGroup} from '@fuzdev/fuz_util/benchmark_types.js';

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 import type {BenchmarkResult} from '@fuzdev/fuz_util/benchmark_types.js';

Result from running a single benchmark task.

name

Task name

type string

stats

Statistical analysis of the benchmark

type BenchmarkStats

iterations

Number of iterations executed

type number

total_time_ms

Total wall-clock time for the task (setup + warmup + measurement + teardown) in milliseconds

type number

timings_ns

Raw timing data for each iteration in nanoseconds. Length equals iterations (the array is right-sized after measurement). Useful for custom statistical analysis, histogram generation, or exporting to external tools.

type Array<number>

budget

Effective per-task time budget after applying overrides to suite defaults. Persisted into baselines so benchmark_baseline_compare can detect methodology drift — a min_iterations bump between baseline and current shifts Welch's DOF and produces "regressions" that are sample-size artifacts, not real drift.

type BenchmarkBudget

BenchmarkStats
#

benchmark_stats.ts view source

import {BenchmarkStats} from '@fuzdev/fuz_util/benchmark_stats.js';

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

Outliers are treated asymmetrically, because high and low outliers in timing data mean different things:

- Upper-tail order statistics (max_ns, p75_nsp99_ns) are computed over the raw valid timings — high outliers (GC pauses, slow paths) are real latency events, so the tail stays honest and p99 reflects real events rather than a pre-stripped distribution. - min_ns is computed over the MAD-cleaned timings — nothing runs faster than its true cost, so a low outlier is an invalid measurement, not a fast run, and reporting it as the best case would mislead. - Central-tendency statistics (mean_ns, std_dev_ns, cv, confidence_interval_ns, ops_per_second) are computed over the MAD-cleaned timings so the Welch's-t comparison keeps a stable mean.

p50_ns (median) uses raw timings to stay paired with the percentile family; being robust, it's unaffected in practice. outlier_ratio reports how heavy the tail was either way. sample_size is the cleaned count behind central tendency and min_ns; the upper-tail order statistics use all valid timings (sample_size + outliers_ns.length); raw_sample_size is the total input count including the failed_iterations invalid values that were filtered out.

mean_ns

Mean (average) time in nanoseconds (over MAD-cleaned samples)

type number

readonly

p50_ns

50th percentile (median) time in nanoseconds (over raw samples)

type number

readonly

std_dev_ns

Standard deviation in nanoseconds (over MAD-cleaned samples)

type number

readonly

min_ns

Minimum time in nanoseconds (over MAD-cleaned samples)

type number

readonly

max_ns

Maximum time in nanoseconds (over raw samples)

type number

readonly

p75_ns

75th percentile in nanoseconds (over raw samples)

type number

readonly

p90_ns

90th percentile in nanoseconds (over raw samples)

type number

readonly

p95_ns

95th percentile in nanoseconds (over raw samples)

type number

readonly

p99_ns

99th percentile in nanoseconds (over raw samples)

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 valid samples after outlier removal (population for central tendency and min_ns)

type number

readonly

raw_sample_size

Number of input samples before filtering invalid/outlier values

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 import type {BenchmarkStatsComparable} from '@fuzdev/fuz_util/benchmark_stats.js';

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 import type {BenchmarkTask} from '@fuzdev/fuz_util/benchmark_types.js';

A benchmark task to execute.

The time-budget fields (duration_ms, warmup_iterations, min_iterations, max_iterations) override the suite-level BenchmarkConfig for this task only. Use them when one task is much faster or slower than the others — e.g. raise min_iterations on a slow task so its percentile/CI math has enough samples without inflating the budget for the fast tasks.

Reading output across overrides: when per-task overrides diverge across rows in the same table, cross-row comparison weakens. Percentiles (p50, p99, …) become unreliable when sample counts differ — p99 at n=30 and p99 at n=50000 estimate different things. Means (and the vs Best column) stay reasonable only if warmup_iterations is held comparable across tasks; asymmetric warmup biases the under-warmed task's mean upward. Per-task percentiles remain valid for that task alone.

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.

Mutations to fn and name made here are honored by the measurement loop — useful for dynamic configuration that depends on async state resolved during setup.

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. Auto-detected during warmup if not set; async: false skips per-iteration promise checking for sync functions, while async: true forces an await on every measurement iteration.

Setting async: true on a function that returns sync forces an unnecessary microtask per iteration — for sub-microsecond functions this adds measurable bias. Prefer leaving async undefined (auto- detected during warmup) unless the conditional-async hazard below applies.

Required for conditional-async fns — without async: true, a first call that happens to return synchronously locks in the sync code path and any later Promise returns leak as unhandled rejections.

type boolean

duration_ms?

Override the suite's duration_ms for this task only. Useful when one task is much slower than others and needs a longer (or shorter) measurement window than the suite default.

type number

warmup_iterations?

Override the suite's warmup_iterations for this task only. Slow tasks may want fewer warmup iterations to keep wall-clock reasonable; tight/complex functions may want more so TurboFan reaches steady state.

type number

min_iterations?

Override the suite's min_iterations for this task only. Raise this on slow tasks so percentile and CI math have enough samples. Wins over duration_ms (see the suite field) — a slow task with a raised floor extends wall-clock until the count is reached.

Prefer raising this over duration_ms when you need more samples: per-iteration noise (GC, scheduler, thermal) is a time-rate process, so a longer wall-clock window proportionally inflates exposure to rare tail events. Raising the sample floor fixes the statistical-power problem without that inflation.

type number

max_iterations?

Override the suite's max_iterations for this task only. Cap a fast task to a fixed sample count, or raise the ceiling on a slow task that would otherwise be limited by the suite default. Also sizes the per-task pre-allocation — avoid extreme caps that won't actually be filled. When this differs sharply across tasks in the same suite, the larger allocation can leak GC pressure into subsequent tasks (cooldown_ms is fixed regardless of prior task footprint).

type number

blake3_ready
#

hash_blake3.ts view source

Promise<void> import {blake3_ready} from '@fuzdev/fuz_util/hash_blake3.js';

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.

Blake3Hash
#

hash_blake3.ts view source

ZodString import type {Blake3Hash} from '@fuzdev/fuz_util/hash_blake3.js';

Zod schema for a BLAKE3 hex hash — 64 lowercase hex characters (256-bit output).

Blue
#

Brand
#

types.ts view source

Brand<T> import type {Brand} from '@fuzdev/fuz_util/types.js';

generics

Brand<T>
T

Branded
#

types.ts view source

Branded<TValue, TName> import type {Branded} from '@fuzdev/fuz_util/types.js';

generics

Branded<TValue, TName>
TValue
TName

build_static_bindings
#

svelte_preprocess_helpers.ts view source

(ast: Root): Map<string, string> import {build_static_bindings} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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 import {clamp} from '@fuzdev/fuz_util/maths.js';

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> import type {ClassConstructor} from '@fuzdev/fuz_util/types.js';

generics

ClassConstructor<TInstance, TArgs extends Array<any> = Array<any>>
TInstance
TArgs
constraint Array<any>
default Array<any>

(construct)

type new (...args: TArgs): TInstance

args

type TArgs

ClientIdCreator
#

id.ts view source

ClientIdCreator import type {ClientIdCreator} from '@fuzdev/fuz_util/id.js';

(call)

type (): string

returns string

compare_simple_map_entries
#

map.ts view source

(a: [any, any], b: [any, any]): number import {compare_simple_map_entries} from '@fuzdev/fuz_util/map.js';

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

ConditionalChainBranch
#

svelte_preprocess_helpers.ts view source

ConditionalChainBranch import type {ConditionalChainBranch} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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 import {configure_print_colors} from '@fuzdev/fuz_util/print.js';

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 import {count_graphemes} from '@fuzdev/fuz_util/string.js';

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 import {count_iterator} from '@fuzdev/fuz_util/iterator.js';

Useful for fast counting when .length is not available.

iterator

type Iterable<unknown>

returns

number

Counter
#

counter.ts view source

Counter import type {Counter} from '@fuzdev/fuz_util/counter.js';

(call)

type (): number

returns number

create_client_id_creator
#

id.ts view source

(name: string, count?: number | undefined, separator?: string): ClientIdCreator import {create_client_id_creator} from '@fuzdev/fuz_util/id.js';

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 import {create_counter} from '@fuzdev/fuz_util/counter.js';

Creates a counter constructor function, starting at 0.

initial?

type number | undefined
optional

returns

Counter

create_deferred
#

async.ts view source

<T>(): Deferred<T> import {create_deferred} from '@fuzdev/fuz_util/async.js';

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

returns

Deferred<T>

generics

create_deferred<T>
T

create_mock_logger
#

testing.ts view source

(): MockLogger import {create_mock_logger} from '@fuzdev/fuz_util/testing.js';

Creates a mock Logger with vi.fn() on each logging method and tracking arrays for inspecting logged messages. Follows the fuz-stack convention of plain object mocks over mocking libraries.

returns

MockLogger

create_random_alea
#

create_random_xoshiro
#

random_xoshiro.ts view source

(seed?: number | undefined): RandomXoshiro import {create_random_xoshiro} from '@fuzdev/fuz_util/random_xoshiro.js';

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 import {create_stopwatch} from '@fuzdev/fuz_util/timings.js';

Tracks elapsed time in milliseconds.

decimals

type number
default 2

returns

Stopwatch

create_uuid
#

id.ts view source

(): string & $brand<"Uuid"> import {create_uuid} from '@fuzdev/fuz_util/id.js';

returns

string & $brand<"Uuid">

CreateCounter
#

counter.ts view source

CreateCounter import type {CreateCounter} from '@fuzdev/fuz_util/counter.js';

(call)

type (initial?: number | undefined): Counter

initial?

type number | undefined
optional
returns Counter

DagNode
#

dag.ts view source

DagNode import type {DagNode} from '@fuzdev/fuz_util/dag.js';

Minimum shape for a DAG node.

inheritance

extends: Sortable

id

type string

depends_on?

type Array<string>

DagNodeResult
#

dag.ts view source

DagNodeResult import type {DagNodeResult} from '@fuzdev/fuz_util/dag.js';

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> import type {DagOptions} from '@fuzdev/fuz_util/dag.js';

Options for running a DAG.

generics

DagOptions<T extends DagNode>
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 import type {DagResult} from '@fuzdev/fuz_util/dag.js';

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

Datetime
#

datetime.ts view source

$ZodBranded<ZodISODateTime, "Datetime", "out"> import type {Datetime} from '@fuzdev/fuz_util/datetime.js';

DatetimeNow
#

datetime.ts view source

ZodDefault<$ZodBranded<ZodISODateTime, "Datetime", "out">> import type {DatetimeNow} from '@fuzdev/fuz_util/datetime.js';

deep_equal
#

deep_equal.ts view source

(a: unknown, b: unknown): boolean import {deep_equal} from '@fuzdev/fuz_util/deep_equal.js';

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 + enumerable own properties) - Promises always return false (cannot be meaningfully compared) - Maps/Sets compare by reference for object keys/values

a

type unknown

b

type unknown

returns

boolean

true if deeply equal, false otherwise

Deferred
#

async.ts view source

Deferred<T> import type {Deferred} from '@fuzdev/fuz_util/async.js';

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

generics

Deferred<T>
T

promise

type Promise<T>

resolve

type (value: T) => void

reject

type (reason: any) => void

Defined
#

types.ts view source

Defined<T> import type {Defined} from '@fuzdev/fuz_util/types.js';

generics

Defined<T>
T

deindent
#

string.ts view source

(str: string): string import {deindent} from '@fuzdev/fuz_util/string.js';

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; }> import {deserialize_cache} from '@fuzdev/fuz_util/fetch.js';

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> import {despawn} from '@fuzdev/fuz_util/process.js';

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[]> import {despawn_all} from '@fuzdev/fuz_util/process.js';

Kills all processes in the default registry.

options?

type DespawnOptions | undefined
optional

returns

Promise<SpawnResult[]>

DespawnOptions
#

process.ts view source

DespawnOptions import type {DespawnOptions} from '@fuzdev/fuz_util/process.js';

Options for killing processes.

signal?

Signal to send.

type NodeJS.Signals

default 'SIGTERM'

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[] import {diff_lines} from '@fuzdev/fuz_util/diff.js';

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[]

DiffLine
#

diff.ts view source

DiffLine import type {DiffLine} from '@fuzdev/fuz_util/diff.js';

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<...> import {each_concurrent} from '@fuzdev/fuz_util/async.js';

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

items

type Iterable<T>

concurrency

maximum number of concurrent operations

type number

fn

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

signal?

optional AbortSignal to cancel processing

type AbortSignal | undefined
optional

returns

Promise<void>

generics

each_concurrent<T>
T

throws

  • Error - if `concurrency < 1`

examples

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

EffectMagnitude
#

benchmark_stats.ts view source

EffectMagnitude import type {EffectMagnitude} from '@fuzdev/fuz_util/benchmark_stats.js';

Effect size magnitude interpretation (Cohen's d).

EMPTY_ARRAY
#

EMPTY_OBJECT
#

object.ts view source

Record<string | number | symbol, undefined> & object import {EMPTY_OBJECT} from '@fuzdev/fuz_util/object.js';

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

ensure_end
#

string.ts view source

(source: string, ensured: string): string import {ensure_end} from '@fuzdev/fuz_util/string.js';

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 import {ensure_start} from '@fuzdev/fuz_util/string.js';

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 import {escape_js_string} from '@fuzdev/fuz_util/string.js';

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 import {escape_regexp} from '@fuzdev/fuz_util/regexp.js';

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 import {escape_svelte_text} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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 import {evaluate_static_expr} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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
#

package_json.ts view source

ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> import type {ExportValue} from '@fuzdev/fuz_util/package_json.js';

extract_static_string
#

svelte_preprocess_helpers.ts view source

(value: true | ExpressionTag | (ExpressionTag | Text)[], bindings?: ReadonlyMap<string, string> | undefined): string | null import {extract_static_string} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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

fact_hash_bytes
#

fact_hash.ts view source

(data: string | Uint8Array<ArrayBufferLike>): string & $brand<"FactHash"> import {fact_hash_bytes} from '@fuzdev/fuz_util/fact_hash.js';

Synchronously hash bytes into a fact hash.

Delegates to hash_blake3 (the fuz_util wrapper around @fuzdev/blake3_wasm) and prefixes the result with blake3:. Strings are UTF-8 encoded.

data

type string | Uint8Array<ArrayBufferLike>

returns

string & $brand<"FactHash">

fact_hash_extract_refs
#

fact_hash.ts view source

(value: Json): (string & $brand<"FactHash">)[] import {fact_hash_extract_refs} from '@fuzdev/fuz_util/fact_hash.js';

Walk a JSON value collecting every blake3:-prefixed string match.

Strings, object values, and array elements are scanned; object keys are intentionally skipped (a hash as an object key is exotic enough that callers should declare it explicitly via FactStore.put({refs})). The same hash appearing twice is deduplicated. Order follows depth-first traversal of the input.

Used by application code on cell snapshot writes and JSON fact writes.

value

type Json

returns

(string & $brand<"FactHash">)[]

FACT_HASH_PATTERN
#

fact_hash.ts view source

RegExp import {FACT_HASH_PATTERN} from '@fuzdev/fuz_util/fact_hash.js';

Pattern for detecting a fact hash anywhere in text.

Has the global flag because the primary use is String.matchAll over cell data / fact bytes. Callers that only need to validate a single known string should use is_fact_hash instead — RegExp.test mutates lastIndex on global patterns.

The trailing (?=blake3:|[^0-9a-f]|$) lookahead enforces a right boundary so a 64-hex digest is matched only when it actually *ends*: followed by a non-hex char, the end of string, or the start of another blake3: ref. This rejects malformed over-long runs (blake3: + 65+ hex) rather than silently truncating them to a different valid-shaped hash, while still matching two refs concatenated with no separator (the blake3: alternative is needed because the prefix itself begins with the hex char b). A bare (?![0-9a-f]) would instead drop the first of two glued refs.

FACT_HASH_PREFIX
#

fact_hash.ts view source

"blake3:" import {FACT_HASH_PREFIX} from '@fuzdev/fuz_util/fact_hash.js';

Algorithm prefix on every fact hash. The colon is the separator.

fact_hash_stream
#

fact_hash.ts view source

(stream: ReadableStream<Uint8Array<ArrayBufferLike>>): Promise<string & $brand<"FactHash">> import {fact_hash_stream} from '@fuzdev/fuz_util/fact_hash.js';

Hash a ReadableStream<Uint8Array> into a fact hash without buffering the full content. Used by FactStore.put_ref for large external content.

stream

type ReadableStream<Uint8Array<ArrayBufferLike>>

returns

Promise<string & $brand<"FactHash">>

fact_hash_verify
#

fact_hash.ts view source

(hash_value: string & $brand<"FactHash">, bytes: Uint8Array<ArrayBufferLike>): boolean import {fact_hash_verify} from '@fuzdev/fuz_util/fact_hash.js';

Verify that bytes produce the claimed hash.

Returns false on any mismatch, including a malformed hash. Callers doing security-sensitive integrity checks should treat false as not-found / corrupt and refuse to use the bytes.

hash_value

type string & $brand<"FactHash">

bytes

type Uint8Array<ArrayBufferLike>

returns

boolean

FactHash
#

fact_hash.ts view source

string & $brand<"FactHash"> import type {FactHash} from '@fuzdev/fuz_util/fact_hash.js';

intersects

z.infer<typeof FactHashSchema>

[key: number]

type string

FactHashSchema
#

fact_hash.ts view source

$ZodBranded<ZodString, "FactHash", "out"> import {FactHashSchema} from '@fuzdev/fuz_util/fact_hash.js';

Wire-form schema for a blake3:-prefixed fact hash. Branded so the type system distinguishes a fact hash from any other string, mirroring Uuid (id.ts). Construct only via fact_hash_bytes / fact_hash_stream / FactHashSchema.parse(s) — direct string literals don't satisfy the brand.

Both client-side (cell payloads) and server-side (DB-row hashes) consumers reuse this same schema.

FactMeta
#

fact_store.ts view source

FactMeta import type {FactMeta} from '@fuzdev/fuz_util/fact_store.js';

Per-fact metadata returned by FactStore.get_meta.

external is true when the fact is stored as a URL reference rather than embedded bytes — callers may use this to decide whether to stream vs load fully. The external URL itself is intentionally *not* exposed here: reads go through get, which fetches and verifies hash↔bytes internally, so handing out a live URL would bypass the verifiable-reads contract. The URL surfaces only from delete, where the caller must unlink the external resource.

content_type

type string | null

size

type number

created_at

type Date

external

type boolean

FactPutOptions
#

fact_store.ts view source

FactPutOptions import type {FactPutOptions} from '@fuzdev/fuz_util/fact_store.js';

Optional metadata + ref declarations on a put / put_ref call.

content_type is advisory and not part of the hash. Omitting it (undefined) reads back from get_meta as nullundefined means "caller didn't specify," null means "no type stored." refs lets callers declare references for binary content where text scanning isn't sound; for JSON content, implementations may auto-extract refs from the bytes when no explicit refs is supplied.

content_type?

type string

refs?

type Array<FactHash>

FactStore
#

fact_store.ts view source

FactStore import type {FactStore} from '@fuzdev/fuz_util/fact_store.js';

Backend-agnostic content-addressed byte store.

- Idempotent writes. put(x) and put(x) again — same hash, no error, no duplication. Content type and refs from the first write win. - Verifiable reads. Implementations should verify hash↔bytes on reads from external storage; embedded reads can skip verify because the storage is the hash table. - Backend-agnostic. Composes — a frontline store can check local, then remote, then peer (deferred).

put

Store bytes, return their hash. Idempotent — storing the same bytes twice is a no-op that returns the same hash.

type (bytes: Uint8Array, options?: FactPutOptions) => Promise<FactHash>

put_stream

Stream bytes into the store with bounded memory, returning the finalized digests + size. Hashes BLAKE3 (content address) and SHA-256 in a single pass over the stream, buffers in memory only up to the embedded threshold, then spills to the disk CAS — so a multi-GB upload never buffers in RAM.

Enforces max_bytes mid-stream: a body whose running byte count passes the cap throws PayloadTooLargeError (the backstop for a chunked or mis-declared Content-Length). A disk-full (ENOSPC) mid-stream throws StorageFullError. Idempotent like put — identical bytes land on the same content-addressed path and the underlying insert is ON CONFLICT DO NOTHING.

The streaming twin of put; mirrors the Rust FactStore::put_stream.

type ( stream: ReadableStream<Uint8Array>, max_bytes: number, options?: FactPutOptions, ) => Promise<PutStreamOutcome>

put_ref

Store a reference to external content (large files). Hashes the content at the URL (streaming) and records hash + URL + size.

size is supplied by the caller (typically from the upload's Content-Length); implementations may verify by counting bytes during streaming and rejecting on mismatch. Implementations decide how to fetch — production typically a signed URL into object storage, tests inject a stub.

type (url: string, size: number, options?: FactPutOptions) => Promise<FactHash>

get

Retrieve bytes by hash. Returns null when not found OR when fetching external content failed integrity verification — both are treated as unavailable from the caller's perspective.

type (hash: FactHash) => Promise<Uint8Array | null>

has

Existence check. Cheaper than get when bytes aren't needed.

type (hash: FactHash) => Promise<boolean>

get_meta

Metadata about a stored fact. Returns null when not found.

type (hash: FactHash) => Promise<FactMeta | null>

get_refs

Declared references for a fact (target hashes only). Returns [] for an absent hash as well as a present-but-ref-less fact — absence-as-no-refs is what a graph walker wants (a missing fact has no outgoing edges to follow), and callers needing presence should use has / get_meta.

type (hash: FactHash) => Promise<Array<FactHash>>

delete

Drop a fact. Idempotent — deleting an absent hash returns null. Returns the deleted fact's size and external_url so callers can tally freed bytes and unlink any external resource (the store doesn't know how to resolve file: / s3: / etc. URLs to a deletable handle, mirroring the read-side fetcher split).

Implementations do NOT verify the hash is unreferenced — that policy lives one layer up (orphan-fact admin, GC walker).

type (hash: FactHash) => Promise<{size: number; external_url: string | null} | null>

fetch_value
#

fetch.ts view source

<TValue = any, TParams = undefined>(url: string | URL, options?: FetchValueOptions<TValue, TParams> | undefined): Promise<Result<{ value: TValue; headers: Headers; }, { ...; }>> import {fetch_value} from '@fuzdev/fuz_util/fetch.js';

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 happening 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; }>>

generics

fetch_value<TValue = any, TParams = undefined>
TValue
default any
TParams
default undefined

FetchValueCache
#

fetch.ts view source

ZodMap<ZodString, ZodObject<{ key: ZodString; url: ZodString; params: ZodAny; value: ZodAny; etag: ZodNullable<ZodString>; last_modified: ZodNullable<...>; }, $strip>> import type {FetchValueCache} from '@fuzdev/fuz_util/fetch.js';

FetchValueCacheItem
#

fetch.ts view source

ZodObject<{ key: ZodString; url: ZodString; params: ZodAny; value: ZodAny; etag: ZodNullable<ZodString>; last_modified: ZodNullable<ZodString>; }, $strip> import type {FetchValueCacheItem} from '@fuzdev/fuz_util/fetch.js';

FetchValueCacheKey
#

fetch.ts view source

ZodString import type {FetchValueCacheKey} from '@fuzdev/fuz_util/fetch.js';

FetchValueOptions
#

fetch.ts view source

FetchValueOptions<TValue, TParams> import type {FetchValueOptions} from '@fuzdev/fuz_util/fetch.js';

generics

FetchValueOptions<TValue, TParams = undefined>
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
#

path.ts view source

FileFilter import type {FileFilter} from '@fuzdev/fuz_util/path.js';

A filter function for file paths only.

(call)

type (path: string): boolean

path

type string
returns boolean

filter_diff_context
#

diff.ts view source

(diff: DiffLine[], context_lines?: number): DiffLine[] import {filter_diff_context} from '@fuzdev/fuz_util/diff.js';

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

diff

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 import {find_attribute} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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

type Component

name

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 import {find_import_insert_position} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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

type Script

returns

number

Flavor
#

types.ts view source

Flavor<T> import type {Flavor} from '@fuzdev/fuz_util/types.js';

generics

Flavor<T>
T

Flavored
#

types.ts view source

Flavored<TValue, TName> import type {Flavored} from '@fuzdev/fuz_util/types.js';

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

Flavored<TValue, TName>
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 import {format_bytes} from '@fuzdev/fuz_util/bytes.js';

Formats a byte count as a human-readable string.

n

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 import {format_diff} from '@fuzdev/fuz_util/diff.js';

Format a diff for display.

diff

type DiffLine[]

current_path

path label for "current" content

type string

desired_path

path label for "desired" content

type string

options

default {}

returns

string

format_number
#

maths.ts view source

(n: number, decimals?: number): string import {format_number} from '@fuzdev/fuz_util/maths.js';

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 import {format_url} from '@fuzdev/fuz_util/url.js';

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 import type {FormatDiffOptions} from '@fuzdev/fuz_util/diff.js';

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

FRACTIONAL_INDEX_ALPHABET
#

fractional_index.ts view source

"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" import {FRACTIONAL_INDEX_ALPHABET} from '@fuzdev/fuz_util/fractional_index.js';

Base62 alphabet, monotonic in lex order: digits, then upper, then lower.

fractional_index_between
#

fractional_index.ts view source

(a: string | null, b: string | null, random?: () => number): string import {fractional_index_between} from '@fuzdev/fuz_util/fractional_index.js';

Returns a key strictly between a and b in lex order.

Either bound may be null (open). Throws when the bracket is invalid (a >= b lex-wise) or when the gap is structurally too tight to fit a key under the no-trailing-'0' invariant (only happens with bounds shaped (a, a + '0…0'); the helper itself never produces those).

Emits a deterministic mid-key, then appends a random jitter suffix. The deterministic mid is what guarantees lex order; the jitter widens the keyspace within the slot to defend against concurrent-insert collisions on the same (prev, next) view.

Pass random to inject a deterministic source for tests; omit for production (uses Math.random). The callback must honor the standard [0, 1) contract; jitter_suffix clamps defensively for safety. The jitter is best-effort collision avoidance, not a security primitive — the server's cell_item_position_taken error is the load-bearing safety net.

a

type string | null

b

type string | null

random

type () => number
default Math.random

returns

string

throws

  • Error - if the bracket is invalid (`a >= b`), a bound breaks the

FRACTIONAL_INDEX_LENGTH_MAX
#

fractional_index.ts view source

200 import {FRACTIONAL_INDEX_LENGTH_MAX} from '@fuzdev/fuz_util/fractional_index.js';

Soft length cap on positions, mirrored at the wire. Primarily DOS protection; the algorithm has no inherent length limit but realistic UX bounds keep emitted keys under 100 chars even after thousands of consecutive front- or back-inserts. Inputs above this cap surface as an explicit throw rather than producing oversized output the wire would later reject.

FRACTIONAL_INDEX_REGEX
#

fractional_index.ts view source

RegExp import {FRACTIONAL_INDEX_REGEX} from '@fuzdev/fuz_util/fractional_index.js';

Wire-grammar regex for cell_item.position: at least one base62 digit. The stricter no-trailing-'0' rule is an invariant of *this* generator, not the wire. See module docstring §"Wire vs. emitted invariants".

fractional_indices_between
#

fractional_index.ts view source

(a: string | null, b: string | null, n: number, random?: () => number): string[] import {fractional_indices_between} from '@fuzdev/fuz_util/fractional_index.js';

Generate n strictly-ordered keys between a and b.

Used for batch inserts (paste, bulk-import) so positions don't all collapse onto a single deterministic mid-point. Output is monotonically increasing; equal spacing is not guaranteed (clumping under the same mid is acceptable and rare in practice).

Implemented by recursive bisection: pick the deterministic mid of (a, b), generate floor(n/2) keys in (a, mid), the mid itself, and the rest in (mid, b). Each emitted key carries its own jitter.

Atomic on failure: if the bracket is structurally too tight at any recursion depth, the whole call throws and no partial array is returned. (Sub-brackets generated by mid_between never have the tight shape, so this only fires when the *initial* bracket is tight.)

a

type string | null

b

type string | null

n

type number

random

type () => number
default Math.random

returns

string[]

throws

  • Error - if `n` is negative or non-integer, or if the initial bracket

from_hex
#

hex.ts view source

(hex: string): Uint8Array<ArrayBufferLike> | null import {from_hex} from '@fuzdev/fuz_util/hex.js';

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_classify_error
#

fs.ts view source

(error: unknown): FsError import {fs_classify_error} from '@fuzdev/fuz_util/fs.js';

Classifies a thrown filesystem error into a discriminated FsError.

Reads the Node code property (ENOENT/EACCES/EPERM/EEXIST) — Deno surfaces the same codes when throwing from node:fs/promises. Unknown codes fall through to io_error.

error

type unknown

returns

FsError

fs_empty_dir
#

fs.ts view source

(dir: string, should_remove?: ((name: string) => boolean) | undefined, options?: RmOptions | undefined): Promise<void> import {fs_empty_dir} from '@fuzdev/fuz_util/fs.js';

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> import {fs_exists} from '@fuzdev/fuz_util/fs.js';

Checks if a file or directory exists.

path

type string

returns

Promise<boolean>

fs_search
#

FsError
#

fs.ts view source

FsError import type {FsError} from '@fuzdev/fuz_util/fs.js';

Discriminated filesystem error kinds.

The shared error shape for Result<{value: T}, FsError>-returning filesystem deps across the ecosystem. Callers branch on kind instead of regex-matching message. The set is deliberately small — add kinds only when a caller needs to distinguish them.

FsJsonError
#

fs.ts view source

FsJsonError import type {FsJsonError} from '@fuzdev/fuz_util/fs.js';

Extends FsError with invalid_json for read_json-style ops where the file exists but parse fails. Callers can distinguish missing from corrupt (e.g. self-healing config loads) without regex-matching message.

FsSearchOptions
#

fs.ts view source

FsSearchOptions import type {FsSearchOptions} from '@fuzdev/fuz_util/fs.js';

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 import {generate_diff} from '@fuzdev/fuz_util/diff.js';

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

type string

desired

type string

path

file path for labels

type string

options

default {}

returns

string | null

generate_import_lines
#

svelte_preprocess_helpers.ts view source

(imports: Map<string, PreprocessImportInfo>, indent?: string): string import {generate_import_lines} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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

get_datetime_now
#

datetime.ts view source

(): string & $brand<"Datetime"> import {get_datetime_now} from '@fuzdev/fuz_util/datetime.js';

Returns an ISO 8601 datetime string for the current time.

returns

string & $brand<"Datetime">

git_check_clean_workspace
#

git.ts view source

(options?: SpawnOptions | undefined): Promise<string | null> import {git_check_clean_workspace} from '@fuzdev/fuz_util/git.js';

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> import {git_check_fully_staged_workspace} from '@fuzdev/fuz_util/git.js';

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> import {git_check_setting_pull_rebase} from '@fuzdev/fuz_util/git.js';

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> import {git_check_workspace} from '@fuzdev/fuz_util/git.js';

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>

git_checkout
#

git.ts view source

(branch: GitBranch, options?: SpawnOptions | undefined): Promise<GitBranch | null> import {git_checkout} from '@fuzdev/fuz_util/git.js';

Calls git checkout.

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<GitBranch | null>

the previous branch name, if it changed

throws

  • Error - if the underlying git command fails

git_clone_locally
#

git.ts view source

(origin: GitOrigin, branch: GitBranch, source_dir: string, target_dir: string, options?: SpawnOptions | undefined): Promise<void> import {git_clone_locally} from '@fuzdev/fuz_util/git.js';

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> import {git_current_branch_first_commit_hash} from '@fuzdev/fuz_util/git.js';

Returns the hash of the current branch's first commit.

options?

type SpawnOptions | undefined
optional

returns

Promise<string>

throws

  • Error - if the underlying git command fails

git_current_branch_name
#

git.ts view source

(options?: SpawnOptions | undefined): Promise<GitBranch> import {git_current_branch_name} from '@fuzdev/fuz_util/git.js';

Returns the current git branch name.

options?

type SpawnOptions | undefined
optional

returns

Promise<GitBranch>

throws

  • Error - if the underlying git command fails

git_current_commit_hash
#

git.ts view source

(branch?: string | undefined, options?: SpawnOptions | undefined): Promise<string | null> import {git_current_commit_hash} from '@fuzdev/fuz_util/git.js';

Returns the branch's latest commit hash.

branch?

type string | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<string | null>

throws

  • Error - if the underlying git command fails

git_delete_local_branch
#

git.ts view source

(branch: GitBranch, options?: SpawnOptions | undefined): Promise<void> import {git_delete_local_branch} from '@fuzdev/fuz_util/git.js';

Deletes a branch locally.

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

throws

  • Error - if the underlying git command fails

git_delete_remote_branch
#

git.ts view source

(origin: GitOrigin, branch: GitBranch, options?: SpawnOptions | undefined): Promise<void> import {git_delete_remote_branch} from '@fuzdev/fuz_util/git.js';

Deletes a branch remotely.

origin

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

throws

  • Error - if the underlying git command fails

git_fetch
#

git.ts view source

(origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<void> import {git_fetch} from '@fuzdev/fuz_util/git.js';

Calls git fetch.

origin

default 'origin'

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

throws

  • Error - if the underlying git command fails

git_info_get
#

git.ts view source

(options?: SpawnOptions | undefined): Promise<GitInfo> import {git_info_get} from '@fuzdev/fuz_util/git.js';

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> import {git_local_branch_exists} from '@fuzdev/fuz_util/git.js';

Checks if a local git branch exists.

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<boolean>

git_parse_workspace_status
#

git.ts view source

(stdout: string | null): GitWorkspaceStatus import {git_parse_workspace_status} from '@fuzdev/fuz_util/git.js';

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

git_pull
#

git.ts view source

(origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<void> import {git_pull} from '@fuzdev/fuz_util/git.js';

Calls git pull.

origin

default 'origin'

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

throws

  • Error - if the underlying git command fails

git_push
#

git.ts view source

(origin: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined, set_upstream?: boolean): Promise<void> import {git_push} from '@fuzdev/fuz_util/git.js';

Calls git push.

origin

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

set_upstream

type boolean
default false

returns

Promise<void>

throws

  • Error - if the underlying git command fails

git_push_to_create
#

git.ts view source

(origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<void> import {git_push_to_create} from '@fuzdev/fuz_util/git.js';

Calls git push, setting upstream if the remote branch does not yet exist.

origin

default 'origin'

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

throws

  • Error - if the underlying git command fails

git_remote_branch_exists
#

git.ts view source

(origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<boolean> import {git_remote_branch_exists} from '@fuzdev/fuz_util/git.js';

Checks if a remote git branch exists.

origin

default 'origin'

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<boolean>

throws

  • Error - if the `git ls-remote` command fails for a reason other than the branch not existing

git_reset_branch_to_first_commit
#

git.ts view source

(origin: GitOrigin, branch: GitBranch, options?: SpawnOptions | undefined): Promise<void> import {git_reset_branch_to_first_commit} from '@fuzdev/fuz_util/git.js';

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.ts view source

(status: GitWorkspaceStatus): boolean import {git_workspace_is_clean} from '@fuzdev/fuz_util/git.js';

status

returns

boolean

true if the workspace has no changes at all

git_workspace_is_fully_staged
#

git.ts view source

(status: GitWorkspaceStatus): boolean import {git_workspace_is_fully_staged} from '@fuzdev/fuz_util/git.js';

status

returns

boolean

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

git_workspace_status_message
#

git.ts view source

(status: GitWorkspaceStatus): string import {git_workspace_status_message} from '@fuzdev/fuz_util/git.js';

Converts a workspace status to a human-readable message.

status

returns

string

GitBranch
#

git.ts view source

ZodString import type {GitBranch} from '@fuzdev/fuz_util/git.js';

GitInfo
#

git.ts view source

GitInfo import type {GitInfo} from '@fuzdev/fuz_util/git.js';

Basic git repository info.

commit

type string | null

branch

type string | null

GitOrigin
#

git.ts view source

ZodString import type {GitOrigin} from '@fuzdev/fuz_util/git.js';

GitWorkspaceStatus
#

git.ts view source

GitWorkspaceStatus import type {GitWorkspaceStatus} from '@fuzdev/fuz_util/git.js';

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 import {handle_preprocess_error} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

Handles errors during Svelte preprocessing with configurable behavior.

error

type unknown

prefix

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

type string

filename

type string | undefined

on_error

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

type "log" | "throw"

returns

void

throws

  • Error - wrapping `error` (with original as `cause`) when `on_error` is `'throw'`

handle_target_value
#

dom.ts view source

(cb: (value: any, event: any) => void, swallow_event?: boolean): (e: any) => void import {handle_target_value} from '@fuzdev/fuz_util/dom.js';

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

mutates

  • event — calls `swallow()` which mutates the event if `swallow_event` is true

has_identifier_in_tree
#

svelte_preprocess_helpers.ts view source

(node: unknown, name: string, skip?: Set<unknown> | undefined): boolean import {has_identifier_in_tree} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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 | Uint8Array<ArrayBufferLike> | BufferSource): string import {hash_blake3} from '@fuzdev/fuz_util/hash_blake3.js';

Computes a BLAKE3 hash synchronously.

data

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

type string | Uint8Array<ArrayBufferLike> | BufferSource

returns

string

64-character hexadecimal hash string (32 bytes)

hash_insecure
#

hash.ts view source

(data: string | BufferSource): string import {hash_insecure} from '@fuzdev/fuz_util/hash.js';

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> import {hash_sha1} from '@fuzdev/fuz_util/hash.js';

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> import {hash_sha256} from '@fuzdev/fuz_util/hash.js';

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> import {hash_sha384} from '@fuzdev/fuz_util/hash.js';

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> import {hash_sha512} from '@fuzdev/fuz_util/hash.js';

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
#

colors.ts view source

(hex: string): Hsl import {hex_string_to_hsl} from '@fuzdev/fuz_util/colors.js';

hex

type string

returns

Hsl

hex_string_to_rgb
#

colors.ts view source

(hex: string): Rgb import {hex_string_to_rgb} from '@fuzdev/fuz_util/colors.js';

hex

type string

returns

Rgb

hex_to_rgb
#

colors.ts view source

(hex: number): Rgb import {hex_to_rgb} from '@fuzdev/fuz_util/colors.js';

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 import {hue_to_rgb_component} from '@fuzdev/fuz_util/colors.js';

p

type number

q

type number

t

type number

returns

number

identity
#

function.ts view source

<T>(t: T): T import {identity} from '@fuzdev/fuz_util/function.js';

Returns the first arg.

t

type T

returns

T

generics

identity<T>
T

inside_editable
#

dom.ts view source

(el: Element): boolean import {inside_editable} from '@fuzdev/fuz_util/dom.js';

Returns true if the element is within a contenteditable ancestor.

el

type Element

returns

boolean

is_editable
#

dom.ts view source

(el: any): boolean import {is_editable} from '@fuzdev/fuz_util/dom.js';

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

el

type any

returns

boolean

is_fact_hash
#

fact_hash.ts view source

(s: string): s is string & $brand<"FactHash"> import {is_fact_hash} from '@fuzdev/fuz_util/fact_hash.js';

Type guard. Useful when receiving a hash from an external boundary — narrows string to FactHash without going through Zod.

s

type string

returns

boolean

is_iframed
#

dom.ts view source

(): boolean import {is_iframed} from '@fuzdev/fuz_util/dom.js';

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 import {is_interactive} from '@fuzdev/fuz_util/dom.js';

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 import {is_plain_object} from '@fuzdev/fuz_util/object.js';

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> import {is_promise} from '@fuzdev/fuz_util/async.js';

Checks if value is a Promise (or thenable).

value

type unknown

returns

boolean

is_uuid
#

id.ts view source

(str: string): boolean import {is_uuid} from '@fuzdev/fuz_util/id.js';

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 import {json_embed} from '@fuzdev/fuz_util/json.js';

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

generics

json_embed<T>
T

json_stringify_deterministic
#

json.ts view source

(value: unknown): string import {json_stringify_deterministic} from '@fuzdev/fuz_util/json.js';

Serializes a value to JSON with deterministic key ordering. Recursively sorts object keys alphabetically for consistent hashing.

value

type unknown

returns

string

deterministic JSON string representation

json_type_of
#

json.ts view source

(value: Json): JsonType | undefined import {json_type_of} from '@fuzdev/fuz_util/json.js';

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

value

type Json

returns

JsonType | undefined

JsonArray
#

json.ts view source

JsonArray import type {JsonArray} from '@fuzdev/fuz_util/json.js';

inheritance

extends: Array<Json>

JsonObject
#

json.ts view source

JsonObject import type {JsonObject} from '@fuzdev/fuz_util/json.js';

inheritance

extends: Record<string, Json>

JsonPrimitive
#

json.ts view source

JsonPrimitive import type {JsonPrimitive} from '@fuzdev/fuz_util/json.js';

JsonType
#

json.ts view source

JsonType import type {JsonType} from '@fuzdev/fuz_util/json.js';

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 import {lerp} from '@fuzdev/fuz_util/maths.js';

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 import {levenshtein_distance} from '@fuzdev/fuz_util/string.js';

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

a

type string

b

type string

returns

number

the edit distance between the strings

library_json_from_modules
#

library_json.ts view source

(package_json: { [x: string]: unknown; name: string; version?: string | undefined; private?: boolean | undefined; description?: string | undefined; tagline?: string | undefined; glyph?: string | undefined; ... 24 more ...; exports?: string | ... 2 more ... | undefined; }, modules: { ...; }[] | undefined, keys?: readonly string[]): LibraryJson import {library_json_from_modules} from '@fuzdev/fuz_util/library_json.js';

Builds a LibraryJson from a package.json and analyzed modules.

Curates package_json to the publish-safe PkgJson subset via pkg_json_from_package_json, so a full package.json (the common case from gro's loader or a JSON import) is accepted and stripped, while an already-curated PkgJson passes through unchanged.

keys overrides the curated field set, and must match the keys passed to the build-time strip (fuz_ui's vite_plugin_pkg_json): the re-strip here drops any field not in keys, so a wider build-time list with the default here would silently discard the extras. Pass the same shared list to both.

package_json

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

modules

type { path: string; declarations?: ({ kind: "function"; name: string; returnType?: string | undefined; returnDescription?: string | undefined; parameters?: { name: string; type: string; optional?: boolean | undefined; rest?: boolean | undefined; description?: string | undefined; defaultValue?: string | undefined; proper...

keys

type readonly string[]
default pkg_json_keys

returns

LibraryJson

LibraryJson
#

library_json.ts view source

LibraryJson import type {LibraryJson} from '@fuzdev/fuz_util/library_json.js';

A library, as two clean projections of its inputs: pkg_json (the curated, publish-safe subset of package.json) and source_json (the svelte-docinfo analysis). Both are raw data — every derived value (repo url, npm url, published, the module/declaration hierarchy, …) is computed by the consumer (fuz_ui's Library class), not stored here, so nothing can go stale.

pkg_json

type PkgJson

source_json

type SourceJson

Lightness
#

log_level_parse
#

log.ts view source

(value: string | undefined): LogLevel | undefined import {log_level_parse} from '@fuzdev/fuz_util/log.js';

Parses and validates a log level string.

value

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 import {log_level_to_number} from '@fuzdev/fuz_util/log.js';

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

level

returns

number

numeric value (0-4)

LogConsole
#

log.ts view source

LogConsole import type {LogConsole} from '@fuzdev/fuz_util/log.js';

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

intersects

Pick<typeof console, 'error' | 'warn' | 'log'>

Logger
#

log.ts view source

import {Logger} from '@fuzdev/fuz_util/log.js';

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

const app_log = new Logger('app'); const db_log = app_log.child('db'); // label: 'app:db' const query_log = db_log.child('query'); // label: 'app:db:query'

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.

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

type unknown[]
returns void

level

Dynamic getter for level - checks override, then parent, then default.

type LogLevel

gettersetter

colors

Dynamic getter for colors - checks override, then parent, then environment variables.

Colors are disabled if either the NO_COLOR or CLAUDECODE environment variable is set. The CLAUDECODE check disables colors in Claude Code environments where ANSI color codes may not render correctly in the output.

type boolean

gettersetter

console

Dynamic getter for console - checks override, then parent, then global console.

type LogConsole

gettersetter

root

Gets the root logger by walking up the parent chain. Useful for setting global configuration that affects all child loggers.

type Logger

getter

LoggerOptions
#

log.ts view source

LoggerOptions import type {LoggerOptions} from '@fuzdev/fuz_util/log.js';

level?

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

type LogLevel

console?

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

type LogConsole

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 import type {LogLevel} from '@fuzdev/fuz_util/log.js';

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

LruMap
#

lru_map.ts view source

import {LruMap} from '@fuzdev/fuz_util/lru_map.js';

Bounded LRU (least-recently-used) map with a hard capacity.

Behaves like Map for get/set/has/delete/size/iteration, with these differences:

- Inserting a new key when size === capacity evicts the least-recently-used entry. - get(key) marks the entry as most-recently-used. - set(key, value) marks the entry as most-recently-used (including when overwriting). - has(key) does NOT mark as used (matches Map parity). - peek(key) reads without marking as used.

Iteration order is LRU → MRU, matching Map's insertion-order guarantee where "insertion" is redefined as "last use".

Implementation uses a single backing Map and relies on its insertion-order iteration — on use, the entry is deleted and re-inserted to move it to the MRU end.

Iterators (keys(), values(), entries(), [Symbol.iterator]) are live views over the backing Map, not snapshots. Per the ECMAScript Map iteration spec, calling get(key) or set(existing_key, …) during iteration moves that entry to the MRU end and causes it to be re-visited later in the same iteration. If you need a stable view while mutating, copy first (e.g. [...lru.entries()]).

generics

LruMap<K, V>
K
V

examples

const cache = new LruMap<string, Buffer>(100, { on_evict: (key, value) => value.release(), }); cache.set('a.png', buf_a); cache.set('b.png', buf_b); cache.get('a.png'); // refreshes 'a.png' as most-recently-used

capacity

type number

readonly

constructor

type new <K, V>(capacity: number, options?: LruMapOptions<K, V> | undefined): LruMap<K, V>

capacity

maximum number of entries; must be a positive integer

type number

options?

optional on_evict hook

type LruMapOptions<K, V> | undefined
optional

throws

  • Error - if `capacity` is not a positive integer

get

Returns the value for key and marks it as most-recently-used.

type (key: K): V | undefined

key

type K
returns V | undefined

peek

Returns the value for key without affecting eviction order.

type (key: K): V | undefined

key

type K
returns V | undefined

has

Returns true if key is present. Does NOT mark as used (matches Map).

type (key: K): boolean

key

type K
returns boolean

set

Sets value for key and marks it as most-recently-used. Evicts the least-recently-used entry when inserting a new key at capacity. The on_evict hook (if any) fires AFTER the new entry is inserted.

type (key: K, value: V): this

key

type K

value

type V
returns this

delete

type (key: K): boolean

key

type K
returns boolean

clear

type (): void

returns void

[Symbol.iterator]

type (): IterableIterator<[K, V]>

returns IterableIterator<[K, V]>

keys

type (): IterableIterator<K>

returns IterableIterator<K>

values

type (): IterableIterator<V>

returns IterableIterator<V>

entries

type (): IterableIterator<[K, V]>

returns IterableIterator<[K, V]>

size

type number

getter

LruMapOnEvict
#

lru_map.ts view source

LruMapOnEvict<K, V> import type {LruMapOnEvict} from '@fuzdev/fuz_util/lru_map.js';

Optional hook invoked when an entry is evicted due to capacity overflow. Not called on delete() or clear().

Called AFTER the new entry is inserted, so the map is already in its post-set state when the callback runs. A throwing callback does not leave the map inconsistent — the eviction and insertion are already committed.

generics

LruMapOnEvict<K, V>
K
V

(call)

type (key: K, value: V): void

key

type K

value

type V
returns void

LruMapOptions
#

lru_map.ts view source

LruMapOptions<K, V> import type {LruMapOptions} from '@fuzdev/fuz_util/lru_map.js';

Options for LruMap.

generics

LruMapOptions<K, V>
K
V

on_evict?

Called with the evicted (key, value) when a set() exceeds capacity. Fires after the new entry is inserted. Not called on delete() or clear().

type LruMapOnEvict<K, V>

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<...> import {map_concurrent} from '@fuzdev/fuz_util/async.js';

Maps over items with controlled concurrency, preserving input order.

items

type Iterable<T>

concurrency

maximum number of concurrent operations

type number

fn

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

signal?

optional AbortSignal to cancel processing

type AbortSignal | undefined
optional

returns

Promise<R[]>

array of results in same order as input

generics

map_concurrent<T, R>
T
R

throws

  • Error - if `concurrency < 1`

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<...> import {map_concurrent_settled} from '@fuzdev/fuz_util/async.js';

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

type Iterable<T>

concurrency

maximum number of concurrent operations

type number

fn

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

signal?

optional AbortSignal to cancel processing

type AbortSignal | undefined
optional

returns

Promise<PromiseSettledResult<R>[]>

array of PromiseSettledResult objects in input order

generics

map_concurrent_settled<T, R>
T
R

throws

  • Error - if `concurrency < 1`

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> import {map_record} from '@fuzdev/fuz_util/object.js';

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>

generics

map_record<T, K extends string | number, U>
T
K
constraint string | number
U

MockLogger
#

testing.ts view source

MockLogger import type {MockLogger} from '@fuzdev/fuz_util/testing.js';

A mock Logger with vi.fn() methods and call tracking arrays. Assignable to Logger for use in code under test. Each tracking array captures the first argument of each call. For full call details, use vi.fn() introspection on the methods directly.

label?

type string

readonly

parent?

type Logger

readonly

#level_override?

type LogLevel

#colors_override?

type boolean

#console_override?

type LogConsole

#cached_colors?

type boolean

#cached_st?

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

#cached_error?

type string

#cached_warn?

type string

#cached_info?

type string

#cached_debug?

type string

#cached_level_string?

type LogLevel

#cached_level?

type number

level

Dynamic getter for level - checks override, then parent, then default.

type LogLevel

colors

Dynamic getter for colors - checks override, then parent, then environment variables.

Colors are disabled if either the NO_COLOR or CLAUDECODE environment variable is set. The CLAUDECODE check disables colors in Claude Code environments where ANSI color codes may not render correctly in the output.

type boolean

console

Dynamic getter for console - checks override, then parent, then global console.

type LogConsole

root

Gets the root logger by walking up the parent chain. Useful for setting global configuration that affects all child loggers.

type Logger

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

#ensure_cache_valid

Ensures prefix cache is valid by checking if colors configuration changed. Uses pull-based invalidation: checks colors on each access and invalidates cached prefixes if colors changed. This automatically handles inheritance changes since this.colors getter walks the parent chain on each access.

Invalidates all 4 cached prefix strings when colors change, since they all depend on the color configuration.

type (): void

returns void

#format_label

Formats the label portion of log output with given styleText function. Applies color styling if enabled, otherwise returns plain bracketed label.

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

st

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

colored

type boolean
returns string

#get_error_prefix

Gets the formatted error prefix, lazily computing and caching if needed. Lazy computation means prefixes are only built when the corresponding log method is first called, avoiding work for unused log levels.

type (): string

returns string

#get_warn_prefix

Gets the formatted warn prefix, lazily computing and caching if needed.

type (): string

returns string

#get_info_prefix

Gets the formatted info prefix, lazily computing and caching if needed. Note: info has no colored prefix character, only the label.

type (): string

returns string

#get_debug_prefix

Gets the formatted debug prefix, lazily computing and caching if needed.

type (): string

returns string

#get_cached_level

Gets the cached numeric level value, updating cache if level changed. Called on every log method invocation to check if the message should be filtered. Caches the numeric value (from LOG_LEVEL_VALUES dictionary) to avoid repeated lookups. Uses pull-based invalidation: checks this.level getter which handles inheritance.

type (): number

returns number

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

const app_log = new Logger('app'); const db_log = app_log.child('db'); // label: 'app:db' const query_log = db_log.child('query'); // label: 'app:db:query'

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.

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

type unknown[]
returns void

error_calls

type unknown[]

warn_calls

type unknown[]

info_calls

type unknown[]

debug_calls

type unknown[]

noop
#

function.ts view source

(...args: any[]): any import {noop} from '@fuzdev/fuz_util/function.js';

Does nothing when called.

args

type any[]

returns

any

noop_async
#

function.ts view source

(...args: any[]): Promise<any> import {noop_async} from '@fuzdev/fuz_util/function.js';

Async function that returns a resolved promise.

args

type any[]

returns

Promise<any>

NOT_OK
#

result.ts view source

Readonly<{ readonly ok: false; }> import {NOT_OK} from '@fuzdev/fuz_util/result.js';

Frozen object representing a failed result.

NotNull
#

types.ts view source

NotNull<T> import type {NotNull} from '@fuzdev/fuz_util/types.js';

generics

NotNull<T>
T

OK
#

result.ts view source

Readonly<{ readonly ok: true; }> import {OK} from '@fuzdev/fuz_util/result.js';

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> import {omit} from '@fuzdev/fuz_util/object.js';

Creates a new object without the specified keys.

obj

type T

keys

type K[]

returns

OmitStrict<T, K>

generics

omit<T extends Record<K, any>, K extends keyof T>
T
constraint Record<K, any>
K
constraint keyof T

omit_undefined
#

object.ts view source

<T extends Record<string | number, any>>(obj: T): T import {omit_undefined} from '@fuzdev/fuz_util/object.js';

A commonly used form of pick_by.

obj

type T

returns

T

obj with all undefined properties removed

generics

omit_undefined<T extends Record<string | number, any>>
T
constraint Record<string | number, any>

see also

OmitStrict
#

types.ts view source

OmitStrict<T, K> import type {OmitStrict} from '@fuzdev/fuz_util/types.js';

generics

OmitStrict<T, K extends keyof T>
T
K
constraint keyof T

package_is_published
#

package_helpers.ts view source

(package_json: { [x: string]: unknown; name: string; version?: string | undefined; private?: boolean | undefined; description?: string | undefined; tagline?: string | undefined; glyph?: string | undefined; ... 24 more ...; exports?: string | ... 2 more ... | undefined; }): boolean import {package_is_published} from '@fuzdev/fuz_util/package_helpers.js';

Check if a package is published to npm.

A package is considered published if: - It's not marked as private - It has exports defined - Its version is not the initial '0.0.1'

package_json

the package.json object to check

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

returns

boolean

true if the package appears to be published

PackageJson
#

PackageJsonAuthor
#

package_json.ts view source

ZodUnion<readonly [ZodString, ZodObject<{ name: ZodString; email: ZodOptional<ZodEmail>; url: ZodOptional<ZodURL>; }, $loose>]> import type {PackageJsonAuthor} from '@fuzdev/fuz_util/package_json.js';

PackageJsonExports
#

package_json.ts view source

ZodUnion<readonly [ZodString, ZodNull, ZodRecord<ZodString, ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>>]> import type {PackageJsonExports} from '@fuzdev/fuz_util/package_json.js';

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

PackageJsonFunding
#

package_json.ts view source

ZodUnion<readonly [ZodString, ZodObject<{ type: ZodString; url: ZodURL; }, $loose>]> import type {PackageJsonFunding} from '@fuzdev/fuz_util/package_json.js';

PackageJsonRepository
#

package_json.ts view source

ZodUnion<readonly [ZodString, ZodObject<{ type: ZodString; url: ZodURL; directory: ZodOptional<ZodString>; }, $loose>]> import type {PackageJsonRepository} from '@fuzdev/fuz_util/package_json.js';

pad_width
#

string.ts view source

(str: string, target_width: number, align?: "left" | "right"): string import {pad_width} from '@fuzdev/fuz_util/string.js';

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

parse_hsl_string
#

colors.ts view source

(hsl: string): Hsl import {parse_hsl_string} from '@fuzdev/fuz_util/colors.js';

hsl

type string

returns

Hsl

parse_path_parts
#

path.ts view source

(path: string): string[] import {parse_path_parts} from '@fuzdev/fuz_util/path.js';

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[] import {parse_path_pieces} from '@fuzdev/fuz_util/path.js';

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[] import {parse_path_segments} from '@fuzdev/fuz_util/path.js';

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 import type {ParsedArgs} from '@fuzdev/fuz_util/args.js';

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

inheritance

extends: Args

_

type Array<string>

PartialExcept
#

types.ts view source

PartialExcept<T, K> import type {PartialExcept} from '@fuzdev/fuz_util/types.js';

generics

PartialExcept<T, K extends keyof T>
T
K
constraint keyof T

PartialOnly
#

types.ts view source

PartialOnly<T, K> import type {PartialOnly} from '@fuzdev/fuz_util/types.js';

generics

PartialOnly<T, K extends keyof T>
T
K
constraint keyof T

PartialValues
#

types.ts view source

PartialValues<T> import type {PartialValues} from '@fuzdev/fuz_util/types.js';

generics

PartialValues<T>
T

PathFilter
#

path.ts view source

PathFilter import type {PathFilter} from '@fuzdev/fuz_util/path.js';

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

(call)

type (path: string, is_directory: boolean): boolean

path

type string

is_directory

type boolean
returns boolean

PathId
#

path.ts view source

PathId import type {PathId} from '@fuzdev/fuz_util/path.js';

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

[key: number]

type string

PathInfo
#

path.ts view source

PathInfo import type {PathInfo} from '@fuzdev/fuz_util/path.js';

Basic information about a filesystem path.

id

type PathId

is_directory

type boolean

PathPiece
#

path.ts view source

PathPiece import type {PathPiece} from '@fuzdev/fuz_util/path.js';

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> import {pick_by} from '@fuzdev/fuz_util/object.js';

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>

generics

pick_by<T extends Record<K, any>, K extends string | number>
T
constraint Record<K, any>
K
constraint string | number

PickUnion
#

pkg_json_from_package_json
#

pkg_json.ts view source

(source: { [x: string]: unknown; name: string; version?: string | undefined; private?: boolean | undefined; description?: string | undefined; tagline?: string | undefined; glyph?: string | undefined; ... 24 more ...; exports?: string | ... 2 more ... | undefined; }, keys?: readonly string[]): PkgJson import {pkg_json_from_package_json} from '@fuzdev/fuz_util/pkg_json.js';

Picks the curated, publish-safe subset from a full package.json-shaped object — the runtime counterpart of the PkgJson type, keyed off the same pkg_json_keys so the strip and the type can't drift. Idempotent: an already-curated PkgJson passes through unchanged.

Use it at every boundary that feeds package.json into a LibraryJson so the curation the type promises actually holds at runtime — otherwise the full manifest rides along, typed as the subset (see fuz_ui's vite_plugin_pkg_json for the parallel build-time strip).

keys overrides the field set to keep — pass a wider list (typically `` [...pkg_json_keys, 'keywords'] ``) to expose extra publish-safe fields. The result is then a superset of PkgJson, so the extra fields stay statically untyped; the same keys must reach library_json_from_modules (and the consumer's virtual:pkg.json ambient type) for them to survive end to end.

source

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

keys

type readonly string[]
default pkg_json_keys

returns

PkgJson

pkg_json_keys
#

pkg_json.ts view source

readonly ["name", "version", "private", "description", "tagline", "glyph", "logo", "logo_alt", "license", "homepage", "repository", "funding", "exports"] import {pkg_json_keys} from '@fuzdev/fuz_util/pkg_json.js';

The keys kept when stripping package.json down to a PkgJson — package identity plus the Fuz extension fields (tagline, glyph, logo, logo_alt). exports and private are kept because a consumer derives a library's published status from them; everything omitted stays out of the client.

PkgJson
#

pkg_json.ts view source

PkgJson import type {PkgJson} from '@fuzdev/fuz_util/pkg_json.js';

Publish-safe subset of PackageJson.

name

type string

version?

type string

description?

type string

private?

type boolean

tagline?

type string

glyph?

type string

logo?

type string

logo_alt?

type string

license?

type string

homepage?

type string

repository?

type string | { [x: string]: unknown; type: string; url: string; directory?: string | undefined; }

funding?

type string | { [x: string]: unknown; type: string; url: string; } | (string | { [x: string]: unknown; type: string; url: string; })[]

exports?

type string | Record<string, unknown>

PkgJsonKey
#

pkg_json.ts view source

"name" | "version" | "description" | "private" | "tagline" | "glyph" | "logo" | "logo_alt" | "license" | "homepage" | "repository" | "funding" | "exports" import type {PkgJsonKey} from '@fuzdev/fuz_util/pkg_json.js';

plural
#

string.ts view source

(count: number | null | undefined, suffix?: string): string import {plural} from '@fuzdev/fuz_util/string.js';

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 type {PreprocessImportInfo} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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 import {process_is_pid_running} from '@fuzdev/fuz_util/process.js';

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 import {process_registry_default} from '@fuzdev/fuz_util/process.js';

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

import {ProcessRegistry} from '@fuzdev/fuz_util/process.js';

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

type string

args

type readonly string[]
default []

options?

spawn options including signal and timeout_ms

type SpawnProcessOptions | undefined
optional

throws

  • Error - if `timeout_ms` is negative

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

type string

args

type readonly string[]
default []

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

throws

  • Error - if `timeout_ms` is negative

despawn

Kills a child process and waits for it to exit.

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

child

type ChildProcess

options?

kill options including signal and timeout

type DespawnOptions | undefined
optional
returns Promise<SpawnResult>

throws

  • Error - if `timeout_ms` is negative

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[]>

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

throws

  • Error - if a handler is already attached to this registry

PutStreamOutcome
#

fact_store.ts view source

PutStreamOutcome import type {PutStreamOutcome} from '@fuzdev/fuz_util/fact_store.js';

Outcome of a streaming put_stream — the finalized digests + byte count.

hash is the blake3:-prefixed fact hash (content address); sha256 is the bare-hex SHA-256 computed in the same pass, so a consumer can persist it alongside the fact and let clients verify downloads with the ubiquitous sha256sum (there is no universal shell BLAKE3 tool); size is the streamed byte count. Mirrors the Rust PutStreamOutcome.

hash

type FactHash

sha256

type string

size

type number

random_boolean
#

random.ts view source

(random?: () => number): boolean import {random_boolean} from '@fuzdev/fuz_util/random.js';

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 import {random_float} from '@fuzdev/fuz_util/random.js';

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> import {random_item} from '@fuzdev/fuz_util/random.js';

Selects a random item from an array.

arr

type T

random

type () => number
default Math.random

returns

ArrayElement<T>

generics

random_item<T extends ReadonlyArray<any>>
T
constraint ReadonlyArray<any>

RandomAlea
#

random_alea.ts view source

RandomAlea import type {RandomAlea} from '@fuzdev/fuz_util/random_alea.js';

uint32

type () => number

fract53

type () => number

version

type string

seeds

type Array<unknown>

(call)

type (): number

returns number

RandomXoshiro
#

random_xoshiro.ts view source

RandomXoshiro import type {RandomXoshiro} from '@fuzdev/fuz_util/random_xoshiro.js';

uint32

type () => number

fract53

type () => number

version

type string

seed

type number

(call)

type (): number

returns 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 import {remove_import_declaration} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

Removes an ImportDeclaration from source using MagicString.

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

s

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

import_node

the ImportDeclaration AST node with Svelte position data

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

source

type string

returns

void

mutates

  • s — removes the declaration's character range

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 import {remove_import_specifier} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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

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

node

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

specifier_to_remove

type ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier

source

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

mutates

  • s — overwrites the import declaration's character range

remove_unordered
#

array.ts view source

(array: any[], index: number): void import {remove_unordered} from '@fuzdev/fuz_util/array.js';

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

array

type any[]

index

type number

returns

void

mutates

  • array — swaps element at index with last element, then pops

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 import {remove_variable_declaration} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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

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

declaration_node

the VariableDeclaration AST node with Svelte position data

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

source

type string

returns

void

mutates

  • s — removes the declaration's character range

reorder
#

object.ts view source

<T extends Record<K, any>, K extends string | number>(obj: T, keys: K[]): T import {reorder} from '@fuzdev/fuz_util/object.js';

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

obj

type T

keys

type K[]

returns

T

generics

reorder<T extends Record<K, any>, K extends string | number>
T
constraint Record<K, any>
K
constraint string | number

repo_name_parse
#

package_helpers.ts view source

(name: string): string import {repo_name_parse} from '@fuzdev/fuz_util/package_helpers.js';

Extract repository name without scope from package name.

name

package name (can be scoped like '@org/package')

type string

returns

string

repository name without scope

throws

  • Error - if scoped package name is malformed

examples

repo_name_parse('@fuzdev/fuz_ui') // => 'fuz_ui'
repo_name_parse('lodash') // => 'lodash'

repo_url_github_owner
#

package_helpers.ts view source

(repo_url: string): string | null import {repo_url_github_owner} from '@fuzdev/fuz_util/package_helpers.js';

Extract GitHub owner/org name from repository URL.

repo_url

repository URL (e.g., 'https://github.com/owner/repo')

type string

returns

string | null

owner name, or null if not a valid GitHub URL

examples

repo_url_github_owner('https://github.com/fuzdev/fuz_ui') // => 'fuzdev'
repo_url_github_owner('https://gitlab.com/foo/bar') // => null (not a GitHub URL)

repo_url_parse
#

package_helpers.ts view source

(repository: string | { [x: string]: unknown; type: string; url: string; directory?: string | undefined; } | undefined): string | null import {repo_url_parse} from '@fuzdev/fuz_util/package_helpers.js';

Parse repository URL from package.json format.

Handles both string format and object format with url property. Strips common prefixes ('git+') and suffixes ('.git', '/').

repository

the repository field from package.json

type string | { [x: string]: unknown; type: string; url: string; directory?: string | undefined; } | undefined

returns

string | null

clean repository URL, or null if not provided

examples

repo_url_parse('https://github.com/foo/bar') // => 'https://github.com/foo/bar'
repo_url_parse({url: 'git+https://github.com/foo/bar.git'}) // => 'https://github.com/foo/bar'
repo_url_parse(undefined) // => null

reset_regexp
#

regexp.ts view source

<T extends RegExp>(regexp: T): T import {reset_regexp} from '@fuzdev/fuz_util/regexp.js';

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

generics

reset_regexp<T extends RegExp>
T
constraint RegExp

mutates

  • regexp — sets lastIndex to 0 if regexp is global or sticky

resolve_component_names
#

svelte_preprocess_helpers.ts view source

(ast: Root, component_imports: string[]): Map<string, ResolvedComponentImport> import {resolve_component_names} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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
#

function.ts view source

Promise<void> import {resolved} from '@fuzdev/fuz_util/function.js';

A singleton resolved Promise.

ResolvedComponentImport
#

svelte_preprocess_helpers.ts view source

ResolvedComponentImport import type {ResolvedComponentImport} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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 import type {ResolvedPath} from '@fuzdev/fuz_util/path.js';

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

inheritance

extends: PathInfo

path

type string

RestartableProcess
#

process.ts view source

RestartableProcess import type {RestartableProcess} from '@fuzdev/fuz_util/process.js';

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
const rp = spawn_restartable_process('node', ['server.js']); await rp.spawned; // Safe to access rp.child now

Result
#

result.ts view source

Result<TValue, TError> import type {Result} from '@fuzdev/fuz_util/result.js';

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

Result<TValue = object, TError = object>
TValue
default object
TError
default object

ResultError
#

result.ts view source

import {ResultError} from '@fuzdev/fuz_util/result.js';

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

type string

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 import {rgb_to_hex} from '@fuzdev/fuz_util/colors.js';

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 import {rgb_to_hex_string} from '@fuzdev/fuz_util/colors.js';

r

type number

g

type number

b

type number

returns

string

rgb_to_hsl
#

colors.ts view source

(r: number, g: number, b: number): Hsl import {rgb_to_hsl} from '@fuzdev/fuz_util/colors.js';

Converts an RGB color value to HSL. Conversion formula adapted from http://wikipedia.org/wiki/HSL_color_space. Values r/g/b are in the range [0,255] and returns h/s/l in the range [0,1].

r

type number

g

type number

b

type number

returns

Hsl

round
#

maths.ts view source

(n: number, decimals: number): number import {round} from '@fuzdev/fuz_util/maths.js';

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> import {run_dag} from '@fuzdev/fuz_util/dag.js';

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

generics

run_dag<T extends DagNode>
T
constraint DagNode

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 import {serialize_cache} from '@fuzdev/fuz_util/fetch.js';

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 import {should_exclude_path} from '@fuzdev/fuz_util/path.js';

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 import {shuffle} from '@fuzdev/fuz_util/random.js';

Mutates array with random ordering.

array

type T

random?

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

returns

T

generics

shuffle<T extends Array<any>>
T
constraint Array<any>

mutates

  • array — randomly reorders elements in place using Fisher-Yates shuffle

slugify
#

path.ts view source

(str: string, map_special_characters?: boolean): string import {slugify} from '@fuzdev/fuz_util/path.js';

Converts a string into a URL-compatible slug.

str

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 import {sort_map} from '@fuzdev/fuz_util/map.js';

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

map

type T

comparator

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

returns

T

generics

sort_map<T extends Map<any, any>>
T
constraint Map<any, any>

Sortable
#

sort.ts view source

Sortable import type {Sortable} from '@fuzdev/fuz_util/sort.js';

Minimum shape required for topological sorting.

id

type string

depends_on?

type Array<string>

SourceJson
#

library_json.ts view source

SourceJson import type {SourceJson} from '@fuzdev/fuz_util/library_json.js';

A library's analyzed source: the module metadata produced by svelte-docinfo.

modules is typed as svelte-docinfo's wire shape (ModuleJsonInput), the input side where defaulted arrays and booleans may be absent. Its Vite plugin (virtual:svelte-docinfo) and CLI emit exactly this compacted shape; gro's loader instead hands back the parsed output-side superset (defaults materialized), which is structurally assignable and can be re-compacted to the wire shape with compactReplacer. Either way consumers must treat defaulted fields as optional. svelte-docinfo is an optional peer dependency — install it to type this field, otherwise the reference degrades to any.

modules?

type Array<ModuleJsonInput>

spawn
#

process.ts view source

(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): Promise<SpawnResult> import {spawn} from '@fuzdev/fuz_util/process.js';

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 import {spawn_detached} from '@fuzdev/fuz_util/process.js';

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

type string

args

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> import {spawn_out} from '@fuzdev/fuz_util/process.js';

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 import {spawn_process} from '@fuzdev/fuz_util/process.js';

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 import {spawn_restartable_process} from '@fuzdev/fuz_util/process.js';

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_to_message
#

process.ts view source

(result: SpawnResult): string import {spawn_result_to_message} from '@fuzdev/fuz_util/process.js';

Formats a spawn result for use in error messages.

result

returns

string

SpawnDetachedResult
#

process.ts view source

SpawnDetachedResult import type {SpawnDetachedResult} from '@fuzdev/fuz_util/process.js';

Result of spawning a detached process.

SpawnedOut
#

process.ts view source

SpawnedOut import type {SpawnedOut} from '@fuzdev/fuz_util/process.js';

Result of spawn_out with captured output streams.

result

type SpawnResult

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 import type {SpawnedProcess} from '@fuzdev/fuz_util/process.js';

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 import type {SpawnProcessOptions} from '@fuzdev/fuz_util/process.js';

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
#

process.ts view source

SpawnResult import type {SpawnResult} from '@fuzdev/fuz_util/process.js';

Discriminated union representing all possible spawn outcomes. Narrow via result.kind === 'error' | 'exited' | 'signaled'.

SpawnResultError
#

process.ts view source

SpawnResultError import type {SpawnResultError} from '@fuzdev/fuz_util/process.js';

Spawn failed before the process could run.

Note: child is still present because node:child_process.spawn returns a ChildProcess synchronously and then emits 'error' asynchronously — the handle exists but the OS process never started.

examples

ENOENT when command not found

kind

type 'error'

ok

type false

child

type ChildProcess

error

type Error

SpawnResultExited
#

process.ts view source

SpawnResultExited import type {SpawnResultExited} from '@fuzdev/fuz_util/process.js';

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

kind

type 'exited'

ok

type boolean

child

type ChildProcess

code

type number

SpawnResultSignaled
#

process.ts view source

SpawnResultSignaled import type {SpawnResultSignaled} from '@fuzdev/fuz_util/process.js';

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

kind

type 'signaled'

ok

type false

child

type ChildProcess

signal

type NodeJS.Signals

st
#

print.ts view source

(format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions | undefined): string import {st} from '@fuzdev/fuz_util/print.js';

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] import {stats_confidence_interval} from '@fuzdev/fuz_util/stats.js';

Calculate confidence interval for the mean.

values

type number[]

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] import {stats_confidence_interval_from_summary} from '@fuzdev/fuz_util/stats.js';

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

mean

type number

std_dev

type number

sample_size

type number

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 import {stats_confidence_level_to_z_score} from '@fuzdev/fuz_util/stats.js';

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

level

type number

returns

number

throws

  • Error - if `level` is not in the open interval (0, 1)

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.ts view source

Record<number, number> import {STATS_CONFIDENCE_Z_SCORES} from '@fuzdev/fuz_util/stats.js';

Common z-scores for confidence intervals.

stats_cv
#

stats.ts view source

(mean: number, std_dev: number): number import {stats_cv} from '@fuzdev/fuz_util/stats.js';

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 import {stats_incomplete_beta} from '@fuzdev/fuz_util/stats.js';

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 import {stats_ln_gamma} from '@fuzdev/fuz_util/stats.js';

Log gamma function approximation (Lanczos approximation).

z

type number

returns

number

stats_mean
#

stats.ts view source

(values: number[]): number import {stats_mean} from '@fuzdev/fuz_util/stats.js';

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

values

type number[]

returns

number

stats_median
#

stats.ts view source

(values: number[]): number import {stats_median} from '@fuzdev/fuz_util/stats.js';

Calculate the median of an array of numbers. NaN values are filtered out before computing.

values

type number[]

returns

number

stats_min_max
#

stats.ts view source

(values: number[]): { min: number; max: number; } import {stats_min_max} from '@fuzdev/fuz_util/stats.js';

Calculate min and max values. NaN values are ignored.

values

type number[]

returns

{ min: number; max: number; }

stats_normal_cdf
#

stats.ts view source

(x: number): number import {stats_normal_cdf} from '@fuzdev/fuz_util/stats.js';

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 import {stats_outliers_iqr} from '@fuzdev/fuz_util/stats.js';

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 import {stats_outliers_mad} from '@fuzdev/fuz_util/stats.js';

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 import {stats_percentile} from '@fuzdev/fuz_util/stats.js';

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

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 import {stats_std_dev} from '@fuzdev/fuz_util/stats.js';

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 import {stats_t_distribution_p_value} from '@fuzdev/fuz_util/stats.js';

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 import {stats_variance} from '@fuzdev/fuz_util/stats.js';

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 import {stats_welch_t_test} from '@fuzdev/fuz_util/stats.js';

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.

Params suffixed 1 describe the first sample, 2 the second.

mean1

type number

std1

type number

n1

type number

mean2

type number

std2

type number

n2

type number

returns

StatsWelchTTestResult

StatsConfidenceIntervalOptions
#

stats.ts view source

StatsConfidenceIntervalOptions import type {StatsConfidenceIntervalOptions} from '@fuzdev/fuz_util/stats.js';

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 import type {StatsOutlierResult} from '@fuzdev/fuz_util/stats.js';

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 import type {StatsOutliersIqrOptions} from '@fuzdev/fuz_util/stats.js';

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 import type {StatsOutliersMadOptions} from '@fuzdev/fuz_util/stats.js';

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

type StatsOutliersIqrOptions

StatsWelchTTestResult
#

stats.ts view source

StatsWelchTTestResult import type {StatsWelchTTestResult} from '@fuzdev/fuz_util/stats.js';

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
#

timings.ts view source

Stopwatch import type {Stopwatch} from '@fuzdev/fuz_util/timings.js';

(call)

type (reset?: boolean | undefined): number

reset?

type boolean | undefined
optional
returns number

string_display_width
#

string.ts view source

(str: string): number import {string_display_width} from '@fuzdev/fuz_util/string.js';

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 import {string_is_binary} from '@fuzdev/fuz_util/string.js';

Check if content appears to be binary.

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

content

type string

returns

boolean

stringify
#

string.ts view source

(value: unknown): string import {stringify} from '@fuzdev/fuz_util/string.js';

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 import {strip_after} from '@fuzdev/fuz_util/string.js';

Removes characters inclusive of stripped.

source

type string

stripped

type string

returns

string

strip_ansi
#

string.ts view source

(str: string): string import {strip_ansi} from '@fuzdev/fuz_util/string.js';

Strips ANSI escape sequences from a string.

str

type string

returns

string

strip_before
#

string.ts view source

(source: string, stripped: string): string import {strip_before} from '@fuzdev/fuz_util/string.js';

Removes characters inclusive of stripped.

source

type string

stripped

type string

returns

string

strip_end
#

string.ts view source

(source: string, stripped: string): string import {strip_end} from '@fuzdev/fuz_util/string.js';

Removes characters inclusive of stripped.

source

type string

stripped

type string

returns

string

strip_start
#

string.ts view source

(source: string, stripped: string): string import {strip_start} from '@fuzdev/fuz_util/string.js';

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 import {swallow} from '@fuzdev/fuz_util/dom.js';

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

generics

swallow<T extends Pick<Event, 'preventDefault' | 'stopPropagation' | 'stopImmediatePropagation'>>
T
constraint Pick<Event, 'preventDefault' | 'stopPropagation' | 'stopImmediatePropagation'>

mutates

  • event — calls `preventDefault()`, `stopPropagation()`, or `stopImmediatePropagation()`

throttle
#

throttle.ts view source

<T extends (...args: Array<any>) => Promise<void>>(cb: T, { delay, when }?: ThrottleOptions): T import {throttle} from '@fuzdev/fuz_util/throttle.js';

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 when to '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

generics

throttle<T extends (...args: Array<any>) => Promise<void>>
T
constraint (...args: Array<any>) => Promise<void>

ThrottleOptions
#

throttle.ts view source

ThrottleOptions import type {ThrottleOptions} from '@fuzdev/fuz_util/throttle.js';

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> import type {Thunk} from '@fuzdev/fuz_util/function.js';

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

generics

Thunk<T>
T

(call)

type (): T

returns T

time_async
#

time.ts view source

<T>(fn: () => Promise<T>, timer?: Timer): Promise<{ result: T; timing: TimeResult; }> import {time_async} from '@fuzdev/fuz_util/time.js';

Time an asynchronous function execution.

fn

type () => Promise<T>

timer

timer to use (defaults to timer_default)

type Timer
default timer_default

returns

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

generics

time_async<T>
T

examples

const {result, timing} = await time_async(async () => { await fetch('https://api.fuz.dev/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 import {time_format} from '@fuzdev/fuz_util/time.js';

Format time with a specific unit.

ns

type number

unit

decimals

type number
default 2

returns

string

formatted string like "3.87μs"

time_format_adaptive
#

time.ts view source

(ns: number, decimals?: number): string import {time_format_adaptive} from '@fuzdev/fuz_util/time.js';

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

ns

type number

decimals

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[]> import {time_measure} from '@fuzdev/fuz_util/time.js';

Measure multiple executions of a function and return all timings.

fn

type () => unknown

iterations

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.ts view source

1000 import {TIME_NS_PER_US} from '@fuzdev/fuz_util/time.js';

Time units and conversions.

time_ns_to_ms
#

time.ts view source

(ns: number): number import {time_ns_to_ms} from '@fuzdev/fuz_util/time.js';

Convert nanoseconds to milliseconds.

ns

type number

returns

number

time_ns_to_sec
#

time.ts view source

(ns: number): number import {time_ns_to_sec} from '@fuzdev/fuz_util/time.js';

Convert nanoseconds to seconds.

ns

type number

returns

number

time_ns_to_us
#

time.ts view source

(ns: number): number import {time_ns_to_us} from '@fuzdev/fuz_util/time.js';

Convert nanoseconds to microseconds.

ns

type number

returns

number

time_sync
#

time.ts view source

<T>(fn: () => T, timer?: Timer): { result: T; timing: TimeResult; } import {time_sync} from '@fuzdev/fuz_util/time.js';

Time a synchronous function execution.

fn

type () => T

timer

timer to use (defaults to timer_default)

type Timer
default timer_default

returns

{ result: T; timing: TimeResult; }

generics

time_sync<T>
T

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 import {time_unit_detect_best} from '@fuzdev/fuz_util/time.js';

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

type number[]

returns

TimeUnit

TIME_UNIT_DISPLAY
#

time.ts view source

Record<TimeUnit, string> import {TIME_UNIT_DISPLAY} from '@fuzdev/fuz_util/time.js';

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

Timer
#

time.ts view source

Timer import type {Timer} from '@fuzdev/fuz_util/time.js';

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 import {timer_browser} from '@fuzdev/fuz_util/time.js';

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 import {timer_default} from '@fuzdev/fuz_util/time.js';

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 import {timer_node} from '@fuzdev/fuz_util/time.js';

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

TimeResult
#

time.ts view source

TimeResult import type {TimeResult} from '@fuzdev/fuz_util/time.js';

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
#

time.ts view source

TimeUnit import type {TimeUnit} from '@fuzdev/fuz_util/time.js';

Time unit for formatting.

Timings
#

timings.ts view source

import {Timings} from '@fuzdev/fuz_util/timings.js';

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[] import {to_array} from '@fuzdev/fuz_util/array.js';

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

value

type T

returns

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

generics

to_array<T>
T

to_bytes
#

bytes.ts view source

(data: string | Uint8Array<ArrayBufferLike> | BufferSource): Uint8Array<ArrayBufferLike> import {to_bytes} from '@fuzdev/fuz_util/bytes.js';

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

data

type string | Uint8Array<ArrayBufferLike> | 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 import {to_fetch_value_cache_key} from '@fuzdev/fuz_util/fetch.js';

url

type string

params

type any

method

type string

returns

FetchValueCacheKey

to_file_path
#

path.ts view source

(path_or_url: string | URL): string import {to_file_path} from '@fuzdev/fuz_util/path.js';

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 import {to_hex} from '@fuzdev/fuz_util/hex.js';

Converts a Uint8Array to a lowercase hex string.

bytes

type Uint8Array<ArrayBufferLike>

returns

string

hex string with two characters per byte

to_hex_component
#

colors.ts view source

(v: number): string import {to_hex_component} from '@fuzdev/fuz_util/colors.js';

v

type number

returns

string

to_next
#

array.ts view source

<T extends ReadonlyArray<any>>(array: T): () => ArrayElement<T> import {to_next} from '@fuzdev/fuz_util/array.js';

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>

generics

to_next<T extends ReadonlyArray<any>>
T
constraint ReadonlyArray<any>

topological_sort
#

sort.ts view source

<T extends Sortable>(items: T[], label?: string): TopologicalSortResult<T> import {topological_sort} from '@fuzdev/fuz_util/sort.js';

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

generics

topological_sort<T extends Sortable>
T
constraint Sortable

TopologicalSortResult
#

sort.ts view source

TopologicalSortResult<T> import type {TopologicalSortResult} from '@fuzdev/fuz_util/sort.js';

Result of topological sort.

generics

TopologicalSortResult<T extends Sortable>
T
constraint Sortable

transform_empty_object_to_undefined
#

object.ts view source

<T>(obj: T): T | undefined import {transform_empty_object_to_undefined} from '@fuzdev/fuz_util/object.js';

obj

type T

returns

T | undefined

generics

transform_empty_object_to_undefined<T>
T

traverse
#

object.ts view source

(obj: any, cb: (key: string, value: any, obj: any) => void): void import {traverse} from '@fuzdev/fuz_util/object.js';

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

obj

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 import {truncate} from '@fuzdev/fuz_util/string.js';

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 import {try_extract_conditional_chain} from '@fuzdev/fuz_util/svelte_preprocess_helpers.js';

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 import {unreachable} from '@fuzdev/fuz_util/error.js';

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

import {UnreachableError} from '@fuzdev/fuz_util/error.js';

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 import {unthunk} from '@fuzdev/fuz_util/function.js';

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

generics

unthunk<T>
T

unwrap
#

result.ts view source

<TValue extends { value?: unknown; }, TError extends { message?: string; }>(result: Result<TValue, TError>, message?: string | undefined): TValue["value"] import {unwrap} from '@fuzdev/fuz_util/result.js';

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

type Result<TValue, TError>

message?

type string | undefined
optional

returns

TValue["value"]

generics

unwrap<TValue extends {value?: unknown}, TError extends {message?: string}>
TValue
constraint {value?: unknown}
TError
constraint {message?: string}

throws

  • ResultError - if `result.ok` is false

unwrap_error
#

result.ts view source

<TError extends object>(result: Result<object, TError>, message?: string): { ok: false; } & TError import {unwrap_error} from '@fuzdev/fuz_util/result.js';

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

type Result<object, TError>

message

type string
default 'Failed to unwrap result error'

returns

{ ok: false; } & TError

generics

unwrap_error<TError extends object>
TError
constraint object

throws

  • Error - if `result.ok` is true

Url
#

url_github_file
#

package_helpers.ts view source

(repo_url: string, file_path: string, line?: number | undefined): string import {url_github_file} from '@fuzdev/fuz_util/package_helpers.js';

Build GitHub file URL for a repository.

repo_url

repository URL (e.g., 'https://github.com/owner/repo')

type string

file_path

path to the file (leading './' is stripped)

type string

line?

optional line number for deep linking

type number | undefined
optional

returns

string

full GitHub URL to the file on the main branch

examples

url_github_file('https://github.com/foo/bar', 'src/index.ts') // => 'https://github.com/foo/bar/blob/main/src/index.ts'
url_github_file('https://github.com/foo/bar', './src/index.ts', 42) // => 'https://github.com/foo/bar/blob/main/src/index.ts#L42'

url_logo
#

url_npm_package
#

package_helpers.ts view source

(package_name: string): string import {url_npm_package} from '@fuzdev/fuz_util/package_helpers.js';

Build npm package URL.

package_name

package name (can be scoped like '@org/package')

type string

returns

string

full npm package page URL

examples

url_npm_package('@fuzdev/fuz_ui') // => 'https://www.npmjs.com/package/@fuzdev/fuz_ui'

Uuid
#

id.ts view source

$ZodBranded<ZodUUID, "Uuid", "out"> import type {Uuid} from '@fuzdev/fuz_util/id.js';

UUID_MATCHER
#

id.ts view source

RegExp import {UUID_MATCHER} from '@fuzdev/fuz_util/id.js';

Postgres doesn't support the namespace prefix, so neither does Felt. For more see the UUID RFC - https://tools.ietf.org/html/rfc4122 The Ajv validator does support the namespace, hence this custom implementation.

UuidWithDefault
#

id.ts view source

ZodDefault<$ZodBranded<ZodUUID, "Uuid", "out">> import type {UuidWithDefault} from '@fuzdev/fuz_util/id.js';

wait
#

async.ts view source

(duration?: number): Promise<void> import {wait} from '@fuzdev/fuz_util/async.js';

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[] import {zod_extract_fields} from '@fuzdev/fuz_util/zod.js';

Extract field metadata from a Zod object schema.

schema

type ZodObject<$ZodLooseShape, $strip>

returns

ZodFieldInfo[]

zod_format_value
#

zod.ts view source

(value: unknown): string import {zod_format_value} from '@fuzdev/fuz_util/zod.js';

Format a value for display in help text.

value

type unknown

returns

string

zod_get_base_type
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): string import {zod_get_base_type} from '@fuzdev/fuz_util/zod.js';

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

schema

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

returns

string

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

zod_get_field_schema
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>, key: string): ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> import {zod_get_field_schema} from '@fuzdev/fuz_util/zod.js';

Get the field schema for a key in an object schema.

schema

Zod schema (typically a ZodObject with possible wrappers)

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

key

type string

returns

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

throws

  • Error - if the schema is not an object or the key is missing

zod_get_innermost_type
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> import {zod_get_innermost_type} from '@fuzdev/fuz_util/zod.js';

Unwrap a schema through every wrapper type (optional, nullable, default, transform, pipe, prefault) to reach the innermost schema. Like zod_unwrap_def but returns the schema (so callers can .shape, instanceof-check, etc.) instead of the def.

schema

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

returns

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

the innermost non-wrapper schema

zod_get_schema_keys
#

zod.ts view source

<T extends z.ZodType>(schema: T): (keyof output<T> & string)[] import {zod_get_schema_keys} from '@fuzdev/fuz_util/zod.js';

Get all property keys from an object schema, unwrapping wrappers. Returns an empty array if the innermost type is not an object.

schema

Zod schema (typically a ZodObject with possible wrappers)

type T

returns

(keyof output<T> & string)[]

generics

zod_get_schema_keys<T extends z.ZodType>
T
constraint z.ZodType

zod_has_default
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): boolean import {zod_has_default} from '@fuzdev/fuz_util/zod.js';

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

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

returns

boolean

zod_is_nullable
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): boolean import {zod_is_nullable} from '@fuzdev/fuz_util/zod.js';

Check if a schema accepts null at any wrapping level.

schema

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

returns

boolean

zod_is_optional
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): boolean import {zod_is_optional} from '@fuzdev/fuz_util/zod.js';

Check if a schema is optional at the outermost level.

schema

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

returns

boolean

zod_maybe_get_field_schema
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>, key: string): ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined import {zod_maybe_get_field_schema} from '@fuzdev/fuz_util/zod.js';

Get the field schema for a key in an object schema, returning undefined if the schema is not an object or the key is missing.

schema

Zod schema (typically a ZodObject with possible wrappers)

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

key

the property name

type string

returns

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

the field's schema, or undefined

zod_to_schema_aliases
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): string[] import {zod_to_schema_aliases} from '@fuzdev/fuz_util/zod.js';

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

schema

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

returns

string[]

zod_to_schema_default
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): unknown import {zod_to_schema_default} from '@fuzdev/fuz_util/zod.js';

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

schema

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 import {zod_to_schema_description} from '@fuzdev/fuz_util/zod.js';

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

schema

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> import {zod_to_schema_names_with_aliases} from '@fuzdev/fuz_util/zod.js';

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

schema

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

returns

Set<string>

zod_to_schema_properties
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): ZodSchemaProperty[] import {zod_to_schema_properties} from '@fuzdev/fuz_util/zod.js';

Extract properties from a Zod object schema.

schema

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

returns

ZodSchemaProperty[]

zod_to_schema_type_string
#

zod.ts view source

(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): string import {zod_to_schema_type_string} from '@fuzdev/fuz_util/zod.js';

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

schema

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 import {zod_to_subschema} from '@fuzdev/fuz_util/zod.js';

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

def

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 import {zod_unwrap_def} from '@fuzdev/fuz_util/zod.js';

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

schema

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 import {zod_unwrap_to_object} from '@fuzdev/fuz_util/zod.js';

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

schema

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

returns

ZodObject<$ZodLooseShape, $strip> | null

ZOD_WRAPPER_TYPES
#

ZodFieldInfo
#

zod.ts view source

ZodFieldInfo import type {ZodFieldInfo} from '@fuzdev/fuz_util/zod.js';

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 import type {ZodSchemaProperty} from '@fuzdev/fuz_util/zod.js';

Property extracted from an object schema.

name

type string

type

type string

description

type string

default

type unknown

aliases

type Array<string>