Skip to content

@xtandard/lib

Isomorphic core utilities with zero dependencies: error handling, async primitives, iterables, type guards, disposables, strings.

import { … } from "@xtandard/lib";
Name Summary
assertNotNull Return value typed without null and undefined, or throw an AssertError when it is null or undefined.
asyncOf Create an AsyncIterable from a list of values.
cast Return value typed as T. The same as value as T: an unchecked type assertion with no runtime effect. As a function call it fits in expression chains and is easy to search for.
chainMaybePromise Apply fn to a value that might be a Promise, staying synchronous when the value is synchronous: a plain value is transformed immediately (no microtask), a Promise is chained with .then.
collect Collect all values from an iterable into an array.
defer Creates an async disposable with cancellation, resume, and double-dispose protection.
deferSync Creates a sync disposable with cancellation, resume, and double-dispose protection.
ensureString Normalize a value that could be a string, array of strings, null, or undefined into a single string or undefined.
enumerate Yield [index, value] tuples for an iterable.
enumerateAsync Always-async enumerate. Unlike enumerate on a sync iterable, this for awaits the source, so Promise values inside a sync iterable are awaited (sequentially, in order) before being yielded.
hoursToMs Convert hours to milliseconds (hours * 3_600_000). No rounding or validation. For calendar-aware durations, use the Temporal helpers in @xtandard/lib/temporal.
isAsyncDisposable Check if a value has a Symbol.asyncDispose method (async disposable), i.e. whether it can be bound with await using.
isAsyncGenerator Type guard for AsyncGenerator.
isAsyncIterable Type guard for AsyncIterable.
isDisposable Check if a value is disposable, sync or async: it has a Symbol.dispose or a Symbol.asyncDispose method. Use it in generic cleanup code, then narrow with isAsyncDisposable / isSyncDisposable to pick the call.
isGenerator Type guard for sync Generator.
isIterable Type guard for Iterable.
isIterator Type guard for Iterator.
isPromise Type guard for Promise-like values (thenables). Uses instanceof first (fast path), then duck-typing for non-native thenables.
isSyncDisposable Check if a value has a Symbol.dispose method (sync disposable), i.e. whether it can be bound with using.
jaroWinklerDistance The Jaro-Winkler similarity of two strings (1 = identical), under its old, misleading name. Returns exactly what jaroWinklerSimilarity returns, including 1 for two empty strings.
jaroWinklerSimilarity Calculate the Jaro-Winkler similarity of two strings: a score from 0 (nothing in common) to 1 (identical). Two empty strings are identical (1); one empty string scores 0. Case-insensitive unless caseSensitive: true.
log Log values to the console while preserving useful TypeScript inference.
makeDisposable Wrap a resource with an asyncDispose handler so it can be used with await using.
minutesToMs Convert minutes to milliseconds (minutes * 60_000). No rounding or validation.
naturalSortCompare Natural sort comparator (Finder/Explorer-like). Numbers within strings are compared numerically, not lexicographically.
prepareLoaderResult Map a batch of DB results back to the original keys in order.
range Create an eager range array (exclusive end).
rangeLazy Create a lazy range generator (exclusive end).
resolveMaybePromise Resolve a value that might already be synchronous or might be a Promise.
resolveStreamSource Resolve a stream source - calls the factory if it’s a function, otherwise returns the instance directly.
secondsToMs Convert seconds to milliseconds (seconds * 1000). No rounding or validation.
toAsyncIterable Convert an Iterable/Iterator/AsyncIterable/AsyncIterator into an AsyncIterable.
toIterator Convert an Iterable or Iterator into an Iterator.
tryCatch Convert a promise (or function) into a tuple result: [data, error].
tryCatchSync Convert a sync function call into a tuple result: [data, error].
valueOrThrow Return a fallback value or throw, depending on a caller-supplied flag. Call it on the invalid path of a function that offers both a lenient and a strict mode.
wait Sleep for a given amount of time.
Name Summary
AssertError The Error subclass thrown by assertNotNull. Its name is "AssertError", so you can tell a failed assertion apart from other failures with instanceof (or by error.name). Throw it from your own checks too.
AsyncChannel A push-based AsyncIterable that allows external control over yielded values.
Completer A small helper for “externally” resolving or rejecting a Promise.
Name Summary
DeferOptions Options for defer / deferSync: an abort signal plus dispose/cancel callbacks.
Deferred Handle returned by defer: an AsyncDisposable you can cancel, resume or dispose early.
DeferredSync Handle returned by deferSync: a sync Disposable you can cancel, resume or dispose early.
MakeDisposableOptions Options for makeDisposable: init/dispose hooks and whether to overwrite an existing disposer.
PrepareLoaderResultManyOptions prepareLoaderResult options for one-to-many mode (mode: "many"): an array of values per key.
PrepareLoaderResultOneOptions prepareLoaderResult options for one-to-one mode: one value (or defaultValue) per key.
Name Summary
ChannelMode
IsAny true only for any (the 1 & T intersection trick).
MadeDisposable The resource returned by makeDisposable: T plus Symbol.asyncDispose and a DisposedSymbol flag.
MaybePromise A value that can be either synchronous (T) or a thenable (PromiseLike<T>).
Result tryCatch result tuple: [value, null] on success, [null, error] on failure.
StreamSource A stream source can be an instance OR a factory function that creates one.
StreamSourceInstance All stream source types we accept as instances.
TryCatchReturn Return type of tryCatch for a function input: distributes over MaybePromise unions, so () => T yields Result<T, E>, () => Promise<T> yields Promise<Result<T, E>>, and () => MaybePromise<T> yields the union of both.
Waiter
Name Summary
CanceledSymbol Symbol key for whether a defer/deferSync has been canceled (by cancel() or an aborted signal), until resume(). Same value as its .canceled property.
CancelReasonSymbol Symbol key for the reason passed to the last cancel(reason) of a defer/deferSync (or the signal’s abort reason), or undefined. Same value as its .cancelReason property; resume() clears it.
DisposedSymbol Symbol key for whether a disposable has already been disposed. Available on defer, deferSync and makeDisposable results. A symbol (rather than a disposed property) can’t collide with the resource’s own fields, which matters for makeDisposable, since it adds state to your object.
EnabledSymbol Symbol key for whether a defer/deferSync is enabled: true while disposing would still run its cleanup (not canceled, not yet disposed). Same value as its .enabled property.