api #

Declarations
#

utility belt for JS

248 declarations

Alea
#

random_alea.ts view source

Alea

uint32

type () => number

fract53

type () => number

version

type string

seeds

type Array<unknown>

ArrayElement
#

Assignable
#

AsyncStatus
#

attach_process_error_handlers
#

process.ts view source

(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): void

Attaches the 'uncoughtException' event to despawn all processes, and enables custom error logging with to_error_label.

to_error_label?

- Customize the error label or return null for the default origin.

type ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined
optional

map_error_text?

- Customize the error text. Return '' to silence, or null for the default print_error(err).

type ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined
optional

handle_error

type (err: Error, origin: UncaughtExceptionOrigin) => void
default () => process.exit(1)

returns

void

Blue
#

Brand
#

Branded
#

clamp
#

maths.ts view source

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

Returns n bounded to min and max.

n

type number

min

type number

max

type number

returns

number

ClassConstructor
#

types.ts view source

ClassConstructor<TInstance, TArgs>

generics

TInstance

TArgs

constraint Array<any>
default Array<any>

ClientIdCreator
#

compare_simple_map_entries
#

map.ts view source

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

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

a

type [any, any]

b

type [any, any]

returns

number

ComponentPropInfo
#

source_json.ts view source

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

Component prop information for Svelte components.

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

configure_print_colors
#

print.ts view source

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

Configures the module-level styling function for colored output.

s

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

returns

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

count_graphemes
#

string.ts view source

(str: string): number

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

str

type string

returns

number

count_iterator
#

iterator.ts view source

(iterator: Iterable<unknown>): number

Useful for fast counting when .length is not available.

iterator

type Iterable<unknown>

returns

number

Counter
#

create_client_id_creator
#

id.ts view source

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

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

name

type string

count?

type number | undefined
optional

separator

type string
default '_'

returns

ClientIdCreator

create_counter
#

counter.ts view source

(initial?: number | undefined): Counter

Creates a counter constructor function, starting at 0.

initial?

type number | undefined
optional

returns

Counter

create_deferred
#

async.ts view source

<T>(): Deferred<T>

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

returns

Deferred<T>

create_random_alea
#

create_stopwatch
#

timings.ts view source

(decimals?: number): Stopwatch

Tracks elapsed time in milliseconds.

decimals

type number
default 2

returns

Stopwatch

CreateCounter
#

declaration_generate_import
#

source_json.ts view source

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

Generate TypeScript import statement for a declaration.

declaration

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

module_path

type string

library_name

type string

returns

string

examples

Example 1

declaration_get_display_name
#

source_json.ts view source

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

Format declaration name with generic parameters for display.

declaration

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

returns

string

examples

Example 1

DeclarationJson
#

source_json.ts view source

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

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

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

DeclarationKind
#

source_json.ts view source

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

The kind of exported declaration.

deep_equal
#

deep_equal.ts view source

(a: unknown, b: unknown): boolean

Deep equality comparison that checks both structure and type.

Key behaviors:

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

a

first value to compare

type unknown

b

second value to compare

type unknown

returns

boolean

true if deeply equal, false otherwise

Deferred
#

async.ts view source

Deferred<T>

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

generics

T

promise

type Promise<T>

resolve

type (value: T) => void

reject

type (reason: any) => void

Defined
#

deindent
#

string.ts view source

(str: string): string

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

str

type string

returns

string

deserialize_cache
#

fetch.ts view source

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

Converts a serialized cache string to a FetchValueCache.

serialized

type string

returns

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

despawn
#

process.ts view source

(child: ChildProcess): Promise<SpawnResult>

Kills a child process and returns a SpawnResult.

child

type ChildProcess

returns

Promise<SpawnResult>

despawn_all
#

process.ts view source

(): Promise<SpawnResult[]>

Kills all globally registered child processes.

returns

Promise<SpawnResult[]>

EMPTY_ARRAY
#

EMPTY_OBJECT
#

object.ts view source

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

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

ensure_end
#

string.ts view source

(source: string, ensured: string): string

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

source

type string

ensured

type string

returns

string

ensure_start
#

string.ts view source

(source: string, ensured: string): string

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

source

type string

ensured

type string

returns

string

escape_regexp
#

regexp.ts view source

(str: string): string

Escapes a string for literal matching in a RegExp.

str

type string

returns

string

ExportValue
#

fetch_value
#

fetch.ts view source

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

Specializes fetch with some slightly different behavior and additional features:

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

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

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

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

url

type string | URL

options?

type FetchValueOptions<TValue, TParams> | undefined
optional

returns

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

FetchValueCache
#

fetch.ts view source

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

FetchValueCacheItem
#

fetch.ts view source

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

FetchValueCacheKey
#

FetchValueOptions
#

fetch.ts view source

FetchValueOptions<TValue, TParams>

generics

TValue

TParams

default undefined

request

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

type RequestInit

params

type TParams

parse

type (v: any) => TValue

token

type string | null

cache

type FetchValueCache | null

return_early_from_cache

type boolean

log

type Logger

fetch

type typeof globalThis.fetch

FileFilter
#

Flavor
#

Flavored
#

types.ts view source

Flavored<TValue, TName>

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

generics

TValue

TName

see also

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

format_url
#

url.ts view source

(url: string): string

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

url

type string

returns

string

fs_empty_dir
#

fs.ts view source

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

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

dir

type string

should_remove?

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

options?

type RmOptions | undefined
optional

returns

Promise<void>

fs_exists
#

fs.ts view source

(path: string): Promise<boolean>

Checks if a file or directory exists.

path

type string

returns

Promise<boolean>

fs_search
#

FsSearchOptions
#

fs.ts view source

FsSearchOptions

filter

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

type PathFilter | Array<PathFilter>

file_filter

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

type FileFilter | Array<FileFilter>

sort

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

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

include_directories

Set to true to include directories. Defaults to false.

type boolean

cwd

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

type string | null

GenericParamInfo
#

source_json.ts view source

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

Generic type parameter information.

git_check_clean_workspace
#

git.ts view source

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

options?

type SpawnOptions | undefined
optional

returns

Promise<string | null>

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

git_check_fully_staged_workspace
#

git.ts view source

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

options?

type SpawnOptions | undefined
optional

returns

Promise<string | null>

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

git_check_setting_pull_rebase
#

git.ts view source

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

Returns the global git config setting for pull.rebase.

options?

type SpawnOptions | undefined
optional

returns

Promise<boolean>

git_check_workspace
#

git.ts view source

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

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

options?

type SpawnOptions | undefined
optional

returns

Promise<GitWorkspaceStatus>

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

git_checkout
#

git.ts view source

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

Calls git checkout and throws if anything goes wrong.

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<GitBranch | null>

the previous branch name, if it changed

git_clone_locally
#

git.ts view source

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

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

origin

branch

source_dir

type string

target_dir

type string

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_current_branch_first_commit_hash
#

git.ts view source

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

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

options?

type SpawnOptions | undefined
optional

returns

Promise<string>

git_current_branch_name
#

git.ts view source

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

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

options?

type SpawnOptions | undefined
optional

returns

Promise<GitBranch>

git_current_commit_hash
#

git.ts view source

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

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

branch?

type string | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<string | null>

git_delete_local_branch
#

git.ts view source

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

Deletes a branch locally and throws if anything goes wrong.

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_delete_remote_branch
#

git.ts view source

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

Deletes a branch remotely and throws if anything goes wrong.

origin

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_fetch
#

git.ts view source

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

Calls git fetch and throws if anything goes wrong.

origin

default 'origin' as GitOrigin

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_local_branch_exists
#

git.ts view source

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

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<boolean>

a boolean indicating if the local git branch exists

git_parse_workspace_status
#

git.ts view source

(stdout: string | null): GitWorkspaceStatus

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

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

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

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

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

stdout

- The raw output from git status --porcelain -z

type string | null

returns

GitWorkspaceStatus

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

git_pull
#

git.ts view source

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

Calls git pull and throws if anything goes wrong.

origin

default 'origin' as GitOrigin

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_push
#

git.ts view source

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

Calls git push and throws if anything goes wrong.

origin

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

set_upstream

type boolean
default false

returns

Promise<void>

git_push_to_create
#

git.ts view source

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

Calls git push and throws if anything goes wrong.

origin

default 'origin' as GitOrigin

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_remote_branch_exists
#

git.ts view source

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

origin

default 'origin' as GitOrigin

branch?

type GitBranch | undefined
optional

options?

type SpawnOptions | undefined
optional

returns

Promise<boolean>

a boolean indicating if the remote git branch exists

git_reset_branch_to_first_commit
#

git.ts view source

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

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

origin

branch

options?

type SpawnOptions | undefined
optional

returns

Promise<void>

git_workspace_is_clean
#

git_workspace_is_fully_staged
#

git.ts view source

(status: GitWorkspaceStatus): boolean

status

returns

boolean

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

git_workspace_status_message
#

GitBranch
#

GitOrigin
#

GitWorkspaceStatus
#

git.ts view source

GitWorkspaceStatus

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

unstaged_changes

type boolean

staged_changes

type boolean

untracked_files

type boolean

global_spawn
#

process.ts view source

Set<ChildProcess>

We register spawned processes gloabally so we can gracefully exit child processes. Otherwise, errors can cause zombie processes, sometimes blocking ports even!

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

dom.ts view source

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

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

cb

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

swallow_event

type boolean
default true

returns

(e: any) => void

hex_string_to_hsl
#

hex_string_to_rgb
#

hex_to_rgb
#

colors.ts view source

(hex: number): Rgb

Converts a hex color to an RGB color.

hex

type number

returns

Rgb

Hsl
#

hsl_to_hex
#

hsl_to_hex_string
#

hsl_to_rgb
#

hsl_to_string
#

Hue
#

hue_to_rgb_component
#

colors.ts view source

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

p

type number

q

type number

t

type number

returns

number

identity
#

inside_editable
#

dom.ts view source

(el: Element): boolean

Returns true if the element is within a contenteditable ancestor.

el

type Element

returns

boolean

is_editable
#

dom.ts view source

(el: any): boolean

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

el

type any

returns

boolean

is_iframed
#

dom.ts view source

(): boolean

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

returns

boolean

is_interactive
#

dom.ts view source

(el: any): boolean

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

el

type any

returns

boolean

is_plain_object
#

object.ts view source

(value: any): boolean

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

value

type any

returns

boolean

is_promise
#

async.ts view source

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

Checks if value is a Promise.

value

type any

returns

boolean

is_uuid
#

id.ts view source

(str: string): str is Uuid

Loosely validates a UUID string.

str

type string

returns

boolean

Json
#

json_embed
#

json.ts view source

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

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

data

type T

stringify

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

returns

string

json_stringify_deterministic
#

json.ts view source

(value: unknown): string

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

value

Any JSON-serializable value

type unknown

returns

string

Deterministic JSON string representation

json_type_of
#

json.ts view source

(value: Json): JsonType | undefined

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

value

type Json

returns

JsonType | undefined

JsonArray
#

JsonObject
#

JsonPrimitive
#

JsonType
#

json.ts view source

JsonType

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

KeyofUnion
#

lerp
#

maths.ts view source

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

Linear interpolation between a and b by amount.

a

type number

b

type number

amount

type number

returns

number

library_json_parse
#

library_json.ts view source

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

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

package_json

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

source_json

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

returns

LibraryJson

library_org_url_parse
#

library_json.ts view source

(library: LibraryJson): string | null

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

library

returns

string | null

library_repo_name_parse
#

library_json.ts view source

(name: string): string

Extracts repo name from a package name, e.g. @fuzdev/fuz_ui → fuz.

name

type string

returns

string

LibraryJson
#

library_json.ts view source

LibraryJson

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

package_json

source_json

name

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

type string

repo_name

Name without scope, e.g. fuz.

type string

repo_url

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

type Url

owner_name

GitHub user/org, e.g. ryanatkn.

type string | null

homepage_url

type Url | null

logo_url

Logo URL, falls back to favicon.png.

type Url | null

logo_alt

type string

npm_url

type Url | null

changelog_url

type Url | null

published

True if has exports and version is not 0.0.1.

type boolean

Lightness
#

log_level_parse
#

log.ts view source

(value: string | undefined): LogLevel | undefined

Parses and validates a log level string.

value

The value to parse as a log level

type string | undefined

returns

LogLevel | undefined

The validated log level, or undefined if value is undefined

throws

  • Error - if value is provided but invalid

log_level_to_number
#

log.ts view source

(level: LogLevel): number

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

level

The log level to convert

returns

number

Numeric value (0-4)

LogConsole
#

log.ts view source

LogConsole

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

Logger
#

log.ts view source

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

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

examples

Example 1

label

type string

readonly

parent

type Logger

readonly

constructor

Creates a new Logger instance.

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

label?

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

type string | undefined
optional
options

Optional configuration for level, colors, and console

default {}

clear_level_override

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

type (): void

returns void

clear_colors_override

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

type (): void

returns void

clear_console_override

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

type (): void

returns void

child

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

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

label

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

type string
options

Optional configuration overrides

default {}
returns Logger

New Logger instance with concatenated label

throws
  • Error - if label is an empty string

error

Logs an error message with 🞩error🞩 prefix. Only outputs if current level is error or higher.

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

args
type unknown[]
returns void

warn

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

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

args
type unknown[]
returns void

info

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

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

args
type unknown[]
returns void

debug

Logs a debug message with ┆debug┆ prefix. Only outputs if current level is debug.

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

args
type unknown[]
returns void

raw

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

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

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

args

Values to log directly to console

type unknown[]
returns void

LoggerOptions
#

log.ts view source

LoggerOptions

level

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

console

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

colors

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

type boolean

LogLevel
#

log.ts view source

LogLevel

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

map_concurrent
#

async.ts view source

<T, R>(items: T[], fn: (item: T, index: number) => Promise<R>, concurrency: number): Promise<R[]>

Maps over items with controlled concurrency, preserving input order.

items

array of items to process

type T[]

fn

async function to apply to each item

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

concurrency

maximum number of concurrent operations

type number

returns

Promise<R[]>

promise resolving to array of results in same order as input

examples

Example 1

map_concurrent_settled
#

async.ts view source

<T, R>(items: T[], fn: (item: T, index: number) => Promise<R>, concurrency: number): Promise<PromiseSettledResult<R>[]>

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

items

array of items to process

type T[]

fn

async function to apply to each item

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

concurrency

maximum number of concurrent operations

type number

returns

Promise<PromiseSettledResult<R>[]>

promise resolving to array of PromiseSettledResult objects in input order

examples

Example 1

map_record
#

object.ts view source

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

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

obj

type Record<K, T>

mapper

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

returns

Record<K, U>

masher
#

ModuleJson
#

source_json.ts view source

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

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

noop
#

noop_async
#

function.ts view source

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

Async function that returns a resolved promise.

args

type any[]

returns

Promise<any>

NOT_OK
#

result.ts view source

Readonly<{ readonly ok: false; }>

Frozen object representing a failed result.

NotNull
#

OK
#

result.ts view source

Readonly<{ readonly ok: true; }>

Frozen object representing a successful result.

omit
#

object.ts view source

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

Creates a new object without the specified keys.

obj

type T

keys

type K[]

returns

OmitStrict<T, K>

omit_undefined
#

OmitStrict
#

PackageJson
#

PackageJsonAuthor
#

package_json.ts view source

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

PackageJsonExports
#

package_json.ts view source

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

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

PackageJsonFunding
#

PackageJsonRepository
#

package_json.ts view source

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

ParameterInfo
#

source_json.ts view source

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

Parameter information for functions and methods.

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

parse_hsl_string
#

parse_path_parts
#

path.ts view source

(path: string): string[]

path

type string

returns

string[]

examples

Example 1

parse_path_pieces
#

path.ts view source

(raw_path: string): PathPiece[]

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

raw_path

type string

returns

PathPiece[]

parse_path_segments
#

path.ts view source

(path: string): string[]

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

path

type string

returns

string[]

examples

Example 1

PartialExcept
#

PartialOnly
#

PartialValues
#

PathFilter
#

path.ts view source

PathFilter

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

PathId
#

path.ts view source

PathId

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

PathInfo
#

PathPiece
#

path.ts view source

PathPiece

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

pick_by
#

object.ts view source

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

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

obj

type T

should_pick

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

returns

Partial<T>

PickUnion
#

plural
#

string.ts view source

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

Returns a plural suffix based on a count.

count

type number | null | undefined

suffix

type string
default 's'

returns

string

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
#

random_boolean
#

random.ts view source

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

Generates a random boolean.

random

type () => number
default Math.random

returns

boolean

random_float
#

random.ts view source

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

Generates a random number between min and max.

min

type number

max

type number

random

type () => number
default Math.random

returns

number

random_int
#

random_item
#

random.ts view source

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

Selects a random item from an array.

arr

type T

random

type () => number
default Math.random

returns

ArrayElement<T>

Red
#

register_global_spawn
#

process.ts view source

(child: ChildProcess): () => void

Returns a function that unregisters the child.

child

the child process to register

type ChildProcess

returns

() => void

cleanup function that removes the child from global_spawn

remove_unordered
#

array.ts view source

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

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

array

type any[]

index

type number

returns

void

reorder
#

object.ts view source

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

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

obj

type T

keys

type K[]

returns

T

reset_regexp
#

regexp.ts view source

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

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

regexp

type T

returns

T

resolved
#

ResolvedPath
#

path.ts view source

ResolvedPath

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

inheritance

extends:

path

type string

RestartableProcess
#

Result
#

result.ts view source

Result<TValue, TError>

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

generics

TValue

default object

TError

default object

ResultError
#

result.ts view source

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

inheritance

extends:
  • Error

DEFAULT_MESSAGE

static

result

type {ok: false; message?: string}

readonly

constructor

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

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

Rgb
#

rgb_to_hex
#

colors.ts view source

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

Converts an RGB color to a hex color.

r

type number

g

type number

b

type number

returns

number

rgb_to_hex_string
#

colors.ts view source

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

r

type number

g

type number

b

type number

returns

string

rgb_to_hsl
#

round
#

maths.ts view source

(n: number, decimals: number): number

Rounds a number to a specified number of decimal places.

n

type number

decimals

type number

returns

number

Saturation
#

serialize_cache
#

fetch.ts view source

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

Converts FetchValueCache to a JSON string.

cache

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

returns

string

shuffle
#

random.ts view source

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

Mutates array with random ordering.

array

type T

random?

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

returns

T

slugify
#

path.ts view source

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

Converts a string into a URL-compatible slug.

str

the string to convert

type string

map_special_characters

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

type boolean
default true

returns

string

sort_map
#

map.ts view source

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

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

map

type T

comparator

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

returns

T

SourceJson
#

source_json.ts view source

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

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

spawn
#

process.ts view source

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

A convenient promise wrapper around spawn_process intended for commands that have an end, not long running-processes like watchers. Any more advanced usage should use spawn_process directly for access to the child process.

args

type [command: string, args?: readonly string[] | undefined, options?: SpawnOptions | undefined]

returns

Promise<SpawnResult>

spawn_out
#

process.ts view source

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

Similar to spawn but buffers and returns stdout and stderr as strings.

command

type string

args

type readonly string[]
default []

options?

type SpawnOptions | undefined
optional

returns

Promise<SpawnedOut>

spawn_process
#

process.ts view source

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

Wraps the normal Node childProcess.spawn with graceful child shutdown behavior. Also returns a convenient closed promise. If you only need closed, prefer the shorthand function spawn.

command

type string

args

type readonly string[]
default []

options?

type SpawnOptions | undefined
optional

returns

SpawnedProcess

spawn_restartable_process
#

process.ts view source

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

Like spawn_process but with restart and kill, handling many concurrent restart calls gracefully.

command

type string

args

type readonly string[]
default []

options?

type SpawnOptions | undefined
optional

returns

RestartableProcess

Spawned
#

process.ts view source

Spawned

child

type ChildProcess

signal

type NodeJS.Signals | null

code

type number | null

SpawnedOut
#

SpawnedProcess
#

SpawnResult
#

st
#

print.ts view source

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

format

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

text

type string

options?

type StyleTextOptions | undefined
optional

returns

string

Stopwatch
#

stringify
#

string.ts view source

(value: unknown): string

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

value

type unknown

returns

string

strip_after
#

string.ts view source

(source: string, stripped: string): string

Removes characters inclusive of stripped.

source

type string

stripped

type string

returns

string

strip_ansi
#

string.ts view source

(str: string): string

Strips ANSI escape sequences from a string

str

type string

returns

string

strip_before
#

string.ts view source

(source: string, stripped: string): string

Removes characters inclusive of stripped.

source

type string

stripped

type string

returns

string

strip_end
#

string.ts view source

(source: string, stripped: string): string

Removes characters inclusive of stripped.

source

type string

stripped

type string

returns

string

strip_start
#

string.ts view source

(source: string, stripped: string): string

Removes characters inclusive of stripped.

source

type string

stripped

type string

returns

string

swallow
#

dom.ts view source

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

Stops an event from bubbling and doing default behavior.

event

type T

immediate

defaults to true to use stopImmediatePropagation over stopPropagation

type boolean
default true

preventDefault

defaults to true

type boolean
default true

returns

T

throttle
#

throttle.ts view source

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

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

cb

type T

__1

default EMPTY_OBJECT

returns

T

same as cb

ThrottleOptions
#

throttle.ts view source

ThrottleOptions

delay

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

type number

when

When to call the throttled function. Defaults to both.

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

Thunk
#

function.ts view source

Thunk<T>

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

generics

T

Timings
#

timings.ts view source

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

decimals

type number | undefined

readonly

timings

type Map<TimingsKey, number | undefined>

privatereadonly

stopwatches

type Map<TimingsKey, Stopwatch>

privatereadonly

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

next_key

type (key: TimingsKey): TimingsKey

private
key
returns TimingsKey

stop

Stops a timing operation and records the elapsed time.

type (key: TimingsKey): number

private
key
returns number

get

type (key: TimingsKey): number

key
returns number

entries

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

returns IterableIterator<[TimingsKey, number | undefined]>

merge

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

type (timings: Timings): void

timings
type Timings
returns void

TimingsKey
#

to_array
#

array.ts view source

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

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

value

type T

returns

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

to_fetch_value_cache_key
#

fetch.ts view source

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

url

type string

params

type any

method

type string

returns

FetchValueCacheKey

to_file_path
#

path.ts view source

(path_or_url: string | URL): string

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

path_or_url

type string | URL

returns

string

to_hex_component
#

to_next
#

array.ts view source

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

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

array

type T

returns

() => ArrayElement<T>

transform_empty_object_to_undefined
#

traverse
#

object.ts view source

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

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

obj

- any object with enumerable properties

type any

cb

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

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

returns

void

truncate
#

string.ts view source

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

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

str

type string

maxLength

type number

suffix

type string
default '...'

returns

string

unreachable
#

error.ts view source

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

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

value

type never

message?

type string | undefined
optional

returns

void

UnreachableError
#

error.ts view source

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

inheritance

extends:
  • Error

constructor

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

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

unthunk
#

function.ts view source

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

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

value

type T | Thunk<T>

returns

T

unwrap
#

result.ts view source

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

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

result

Some Result object.

type Result<TValue, TError>

message?

Optional custom error message.

type string | undefined
optional

returns

TValue["value"]

The wrapped value.

unwrap_error
#

result.ts view source

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

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

result

Some Result object.

type Result<object, TError>

message

Optional custom error message.

type string
default 'Failed to unwrap result error'

returns

{ ok: false; } & TError

The type-narrowed result.

Url
#

Uuid
#

UUID_MATCHER
#

wait
#

async.ts view source

(duration?: number): Promise<void>

Waits for the given duration before resolving.

duration

type number
default 0

returns

Promise<void>