@xylabs/sdk-js
v5.0.86
Published
Base functionality used throughout XY Labs TypeScript/JavaScript libraries
Readme
@xylabs/sdk-js
[![main-build][]][main-build-link] [![npm-badge][]][npm-link] [![npm-downloads-badge][]][npm-link] [![jsdelivr-badge][]][jsdelivr-link] ![npm-license-badge][] [![codacy-badge][]][codacy-link] [![codeclimate-badge][]][codeclimate-link] [![snyk-badge][]][snyk-link] [![socket-badge][]][socket-link]
Base functionality used throughout XY Labs TypeScript/JavaScript libraries
Reference
@xylabs/sdk-js
Classes
| Class | Description |
| ------ | ------ |
| ApiClient | Abstract base class for API clients that provides stage and token configuration. |
| ApiEndpoint | Generic REST API endpoint wrapper that supports fetching and inserting typed data. |
| ~~AxiosJson~~ | - |
| Base | Abstract base class providing logging, telemetry, and global instance tracking with WeakRef-based GC. |
| UniqueBase | Base class that registers itself as globally unique, preventing duplicate module instances. |
| AbstractCreatable | Base class for objects that follow an asynchronous creation and lifecycle pattern. Instances must be created via the static create method rather than direct construction. Provides start/stop lifecycle management with status tracking and telemetry support. |
| AbstractCreatableWithFactory | Extends AbstractCreatable with a static factory method for creating pre-configured CreatableFactory instances. |
| Factory | A concrete factory that wraps a Creatable class with default parameters and labels. Instances are created by merging caller-provided params over the factory defaults. |
| EthAddressWrapper | Wrapper around an Ethereum address providing parsing, formatting, validation, and checksum support. |
| BaseEmitter | Base class that combines the Base utility class with typed event emission capabilities. Delegates all event operations to an internal Events instance. |
| Events | Core typed event emitter implementation supporting named events, wildcard listeners, serial and concurrent emission, listener filtering, and debug logging. |
| ForgetPromise | Node.js extension of ForgetPromise that can terminate the process on exceptions or timeouts. |
| ConsoleLogger | A LevelLogger that delegates to the global console object. |
| IdLogger | A logger wrapper that prefixes every log message with a bracketed identifier. Useful for distinguishing log output from different components or instances. |
| LevelLogger | A logger that filters messages based on a configured log level. Methods for levels above the configured threshold return a no-op function. |
| SilentLogger | A logger that does not log anything. This is useful when you want to disable logging like when running unit tests or in silent mode. It implements the Logger interface but all methods are no-op functions. |
| IsObjectFactory | Factory class for creating type-guard functions that validate objects against a given shape and optional additional checks. |
| ObjectWrapper | Abstract base class that wraps an object and provides typed access to it. |
| ValidatorBase | Abstract base class for validators that wraps a partial object and provides a validation method. |
| PromiseEx | An extended Promise that carries an optional attached value and supports cancellation. The value can be inspected via the then or value methods to conditionally cancel. |
| XyConsoleSpanExporter | A console span exporter that formats spans with color-coded durations using chalk. Spans are filtered by a configurable log level based on their duration. |
Interfaces
| Interface | Description |
| ------ | ------ |
| ApiConfig | Configuration for connecting to an API, including domain, authentication, and user identification. |
| CreatableFactory | A factory interface for creating instances of a Creatable with pre-configured parameters. Unlike the full Creatable, this only exposes the create method. |
| Creatable | Static interface for classes that support asynchronous creation. Provides the create, createHandler, and paramsHandler static methods used to construct instances through the creatable lifecycle. |
| CreatableWithFactory | Extends Creatable with a factory method that produces pre-configured CreatableFactory instances. |
| CreatableInstance | Represents a created instance with a managed lifecycle (start/stop) and event emission. |
| RequiredCreatableParams | The minimum required parameters for constructing a creatable. |
| CreatableParams | Parameters for creating a creatable instance, combining required params with emitter params. |
| CreatableStatusReporter | Reports status changes for a creatable, supporting progress tracking and error reporting. |
| Labels | Object used to represent labels identifying a resource. |
| WithLabels | Interface for objects that have labels. |
| WithOptionalLabels | Interface for objects that have labels. |
| BaseEmitterParamsFields | Fields specific to BaseEmitter configuration parameters. |
| EventEmitter | Interface for a typed event emitter that supports subscribing, unsubscribing, and emitting events. |
| ForgetNodeConfig | Node.js-specific forget configuration that extends ForgetConfig with process termination options. |
| HexConfig | Configuration of validation and output format |
| Logger | Interface to handle overlap between Winston & console with as much congruency as possible. |
| ObjectTypeConfig | Configuration options for object type checking. |
| Validator | Interface for validating objects and returning any errors found. |
| TypeCheckConfig | Configuration options for type check functions, with optional logging. |
| TypeCheckRequiredConfig | Type check configuration that marks the value as required, causing assertions on failure. |
| TypeCheckOptionalConfig | Type check configuration that marks the value as optional, returning undefined on failure. |
| PromiseType | An interface representing any thenable (promise-like) object. |
| RetryConfig | Configuration for retry behavior. |
| RetryConfigWithComplete | Retry configuration extended with a custom completion check. |
| ReadonlyKeyValueStore | A readonly storage device. |
| KeyValueStore | A read/write storage device. |
| SpanConfig | Configuration options for span creation and execution. |
| ZodFactoryConfigObject | Configuration object for zod factory functions, providing a name for error messages. |
Type Aliases
| Type Alias | Description |
| ------ | ------ |
| ApiStage | A valid API stage value ('prod', 'beta', or 'local'). |
| BaseClassName | Branded string type representing a class name used for global instance tracking. |
| BaseParamsFields | Common parameter fields available to all Base instances (logger, meter, tracer). |
| BaseParams | Parameters for constructing a Base instance, combining BaseParamsFields with optional additional params. |
| CreatableName | A branded string type used as the name identifier for creatables. |
| StandardCreatableStatus | The standard lifecycle statuses a creatable can transition through. |
| CreatableStatus | A creatable's status, optionally extended with additional custom status values. |
| Enum | A utility type that, given a Record<string, unknown>, returns a readonly version of that record. This results in a type where all properties of T are readonly. |
| EnumKey | A utility type that, given an Enum object, returns the union of its keys. |
| EnumValue | A utility type that, given an Enum object, returns the union of its values. |
| AssertConfig | Configuration for assertion behavior: a static message string, a boolean toggle, or a callback. |
| BaseEmitterParams | Parameters type for configuring a BaseEmitter instance. |
| DebugLogger | Emittery can collect and log debug information. |
| EventListenerInfo | Information about a registered event listener, including an optional filter for selective invocation. |
| DebugOptions | Configure debug options of an instance. |
| MetaEventData | Data shape for internal meta events that fire when listeners are added or removed. |
| EventsParams | Parameters for constructing an Events instance, with optional debug configuration. |
| EventName | A valid event name, which can be any property key (string, number, or symbol). |
| EventArgs | The allowed types for event argument payloads. |
| EventData | A mapping of event names to their corresponding event argument types. |
| EventUnsubscribeFunction | A function returned by event subscription methods that unsubscribes the listener when called. |
| EventAnyListener | A listener that receives all events regardless of name. |
| EventListener | A listener for a specific event type. |
| AddressTransformZodType | The output type of AddressTransformZod after parsing and transformation. |
| AddressValidationZodType | The output type of AddressValidationZod after parsing. |
| Address | A validated 20-byte address string type, inferred from the AddressZod schema. |
| EthAddress | Branded type representing a validated Ethereum address with 0x prefix. |
| HashBitLength | Valid bit lengths for hash values. |
| BrandedHash | Branded type representing a validated hash hex string. |
| Hash | A validated hash string type, inferred from the HashZod schema. |
| BrandedHex | Branded type representing a validated lowercase hex string. |
| Hex | A validated hex string type, inferred from the HexZod schema. |
| LogFunction | A generic logging function that accepts any number of arguments. |
| LogLevelKey | String key for a log level (e.g. 'error', 'warn', 'info'). |
| LogVerbosity | Alias for LogLevelKey, representing the verbosity setting as a string. |
| LogLevelValue | Numeric value of a log level (1 through 6). |
| JsonValue | A recursive JSON value: string, number, boolean, null, array, or object. |
| JsonObject | A JSON object with string keys and JSON values. |
| JsonArray | A JSON array containing JSON values. |
| OmitStartsWith | Omits the keys of T that start with the given prefix. |
| DeepOmitStartsWith | Recursively omits keys that start with the given prefix, including in nested objects and arrays. |
| DeepRestrictToStringKeys | Recursively removes all non-string keys from an object type, including in nested objects and arrays. |
| DeepRestrictToJson | Recursively restricts an object type to only JSON-compatible values, excluding non-serializable types. |
| Optional | Makes the specified fields of T optional while keeping the rest required. |
| Override | Overrides properties of T1 with those from T2. |
| ~~PartialRecord~~ | - |
| PickStartsWith | Picks only the keys of T that start with the given prefix. |
| DeepPickStartsWith | Recursively picks only the keys that start with the given prefix, including in nested objects and arrays. |
| Simplify | Flattens an intersection or complex mapped type into a single object type for better readability. |
| StringKeyObject | An object type with string keys and values of type T. |
| WithAdditional | Intersects T with TAdditional if TAdditional is an object, otherwise returns T unchanged. |
| OmitByPredicate | A predicate function used to determine which properties to omit from an object. |
| PickByPredicate | A predicate function used to determine which properties to pick from an object. |
| AnyObject | Any object, which means that it does not enforce the set of fields that it has. Extending from AnyObject will result in a type that includes the universal set of field names |
| AsTypeFunction | A type-narrowing function that attempts to cast a value to T, with optional assertion and configuration overloads. |
| AsOptionalTypeFunction | A simplified type-narrowing function that returns T or undefined, without assertion support. |
| Compare | A comparator function that returns a negative number if a < b, zero if a == b, and a positive number if a > b. |
| EmptyObject | An empty object, which means that it does enforce the set of field names, defaulting to an empty set until extended from, which then adds only those additional fields |
| StringOrAlertFunction | A string message or function that produces an assertion error message for a failed type check. |
| TypeCheck | A type guard function that checks whether a value conforms to type T, with optional configuration. |
| Profiler | A record of named timing entries, where each key maps to an array of timestamps. |
| PromiseExSubFunc | A resolve/reject callback used within PromiseEx. |
| PromiseExFunc | The executor function passed to the PromiseEx constructor. |
| PromiseExValueFunc | A callback that inspects the attached value and returns whether to cancel the promise. |
| Promisable | A value that may be a Promise, PromiseEx, or a plain synchronous value. |
| PromisableArray | A Promisable that resolves to an array. |
| OptionalPromisable | A Promisable that may resolve to undefined. |
| OptionalPromisableArray | A Promisable array where elements may be undefined. |
| NullablePromisable | A Promisable that may resolve to null. |
| NullablePromisableArray | A Promisable array where elements may be null. |
| AsyncMutex | - |
| AnyNonPromise | Any non-promise typed value, excluding thenables. |
| Brand | Creates a branded type by intersecting base type T with brand type B, enabling nominal typing in TypeScript. |
| IdentityFunction | A type guard function that narrows an unknown value to type T. |
| FieldType | Union of string literals representing the possible types of an object field. |
| ObjectTypeShape | Describes the expected shape of an object by mapping each key to its expected field type. |
| TypeOfTypes | Union of string literals representing the possible results of the extended typeOf function. |
| TypedValue | A value that can appear in a typed object tree (primitives, objects, arrays, functions, and symbols). |
| TypedKey | A valid key for a typed object. Defaults to string | number | symbol unless narrowed by T. |
| TypedObject | An object whose keys are TypedKey and whose values are TypedValue. |
| TypedArray | An array of TypedValue elements. |
| AnyFunction | A function type that accepts any arguments and returns unknown. |
| RecordKey | A union of valid object key types. |
| ZodFactoryConfig | Configuration for zod factory assertion behavior, either an AssertConfig or a named config object. |
| AllZodFactories | - |
Variables
| Variable | Description |
| ------ | ------ |
| ApiStage | Deployment stage identifiers for API environments. |
| getApiStage | Determines the API stage based on the hostname. |
| containsAll | Checks whether the source array contains every element in the target array. |
| distinct | Array filter callback that removes duplicate values, with correct NaN handling. Use with array.filter(distinct). |
| filterAs | Maps each element using the predicate and filters out nullish results. |
| filterAsync | Returns the elements of an array that meet the condition specified in a callback function. |
| findAs | Maps each element using the predicate and returns the first non-nullish result. |
| findLastAs | Maps each element using the predicate and returns the last non-nullish result. |
| flatten | Concatenates two values or arrays into a single flat array, filtering out nullish entries. |
| uniq | Returns a new array with duplicate values removed. |
| uniqBy | Returns a new array with duplicates removed, using a key function for comparison. |
| equalArrayBuffers | Compares two ArrayBuffers for byte-level equality. |
| axiosJson | - |
| ~~axios~~ | - |
| disableGloballyUnique | Disables global uniqueness checks, allowing duplicate registrations without throwing. |
| globallyUnique | Registers a value as globally unique under the given name and domain. Throws if a different value is already registered under the same key. |
| Buffer | - |
| bufferPolyfill | - |
| hasAllLabels | Returns true if the source object has all the labels from the required set |
| fromFixedPoint | Converts a fixed-point bigint back to a whole-number bigint by dividing out the decimal places. |
| toDecimalPrecision | Formats a number to the specified number of significant digits, returning a string with minimal trailing zeros. |
| toFixedPoint | Converts a bigint or decimal string to a fixed-point bigint representation. |
| delay | Returns a promise that resolves after the specified number of milliseconds. |
| Enum | Transforms a given record object into a readonly "enum-like" structure while preserving the literal types of its values. This allows you to use the returned object both at runtime (for lookups) and at compile time (for strongly typed values). |
| assertError | Throws an Error based on the assert configuration when a value fails validation. |
| handleError | Invokes the handler if the value is an Error, otherwise re-throws it. |
| handleErrorAsync | Async version of handleError. Invokes the async handler if the value is an Error, otherwise re-throws it. |
| isEthAddressWrapper | Type guard that checks if the given object is an instance of EthAddressWrapper. |
| ellipsize | Truncates a string to show the first and last length characters separated by an ellipsis. |
| padHex | - |
| exists | Used to type narrow an object which is possibly null or undefined. Works well with functional Array methods. For example: |
| defaultForgetNodeConfig | Default Node.js forget configuration with termination disabled. |
| forget | Node.js variant of forget that can optionally terminate the process on exceptions or timeouts. |
| functionName | Returns the name of the calling function by inspecting the stack trace. |
| HexRegExMinMax | Creates a RegExp matching lowercase hex strings with a byte length in the given range. |
| HexRegExMinMaxMixedCaseWithPrefix | Creates a RegExp matching mixed-case hex strings with a 0x prefix and a byte length in the given range. |
| HexRegEx | Regular expression matching a lowercase hex string without prefix. |
| HexRegExWithPrefix | Regular expression matching a lowercase hex string with a 0x prefix. |
| AddressTransformZod | Zod schema that accepts a string, bigint, or number and transforms it into a validated Address. |
| AddressValidationZod | Zod schema that validates a string is a properly formatted 40-character hex address. |
| ZERO_ADDRESS | A 160-bit zero address constant. |
| ADDRESS_LENGTH | The character length of an address hex string (40 hex characters / 20 bytes). |
| AddressRegEx | Regular expression matching a 20-byte (40 hex character) address string. |
| AddressZod | Zod schema that validates and transforms a string into a branded Address type. |
| isAddress | Type guard that checks whether a value is a valid 160-bit address. |
| toAddress | Converts a value to a 160-bit Address hex string. |
| EthAddressRegEx | Regular expression matching a 20-byte Ethereum address with 0x prefix (mixed case). |
| EthAddressToStringZod | Zod schema that validates a string is a properly formatted Ethereum address. |
| ~~EthAddressToStringSchema~~ | - |
| EthAddressFromStringZod | Zod schema that validates and transforms a string into an EthAddress type. |
| ~~EthAddressFromStringSchema~~ | - |
| ETH_ZERO_ADDRESS | The zero Ethereum address constant (0x followed by 40 zero characters). |
| toEthAddress | Converts a value to a 0x-prefixed Ethereum address string. |
| isEthAddress | Type guard that checks whether a value is a valid 0x-prefixed Ethereum address. |
| EthAddressZod | Zod schema that validates a string as a properly formatted Ethereum address using regex and type guard. |
| HASH_LENGTH | The byte length of a standard hash (32 bytes / 256 bits). |
| HashRegEx | Regular expression matching a 32-byte (64 hex character) hash string. |
| ZERO_HASH | A 256-bit zero hash constant. |
| HashBitLength | Array of all valid hash bit lengths for runtime validation. |
| isHashBitLength | Type guard that checks whether a value is a valid hash bit length. |
| HashZod | Zod schema that validates and transforms a string into a branded Hash type. |
| isHash | Type guard that checks whether a value is a valid hash of the specified bit length. |
| HashToJsonZod | Zod schema that transforms a Hash to a plain string for JSON serialization. |
| JsonToHashZod | Zod schema that parses a JSON string into a validated Hash, throwing on invalid input. |
| hexFrom | Takes unknown value and tries our best to convert it to a hex string |
| hexFromArrayBuffer | Convert an ArrayBuffer to a hex string |
| hexFromBigInt | Convert a bigint to a hex string |
| hexFromHexString | Normalizes a hex string by stripping an optional 0x prefix, lowercasing, and padding to byte/bit boundaries. |
| hexFromNumber | Converts a number to a hex string by converting to BigInt first. |
| HexZod | Zod schema that validates and transforms a string into a branded Hex type. |
| isHex | Type guard that checks whether a value is a valid hex string. |
| isHexZero | Checks whether a hex string represents a zero value. |
| toHexLegacy | Converts an ArrayBuffer to a hex string without padding or normalization. |
| bitsToNibbles | Converts a bit count to the equivalent number of hex nibbles (4 bits each). |
| nibblesToBits | Converts a nibble count to the equivalent number of bits. |
| toHex | takes any value and tries our best to convert it to a hex string |
| BigIntToJsonZod | Zod schema that transforms a non-negative BigInt into a hex string for JSON serialization. |
| JsonToBigIntZod | Zod schema that parses a JSON hex string into a BigInt. |
| LogLevel | Numeric log level values, from least verbose (error=1) to most verbose (trace=6). |
| NoOpLogFunction | A log function that silently discards all arguments. |
| getFunctionName | Retrieves the name of the calling function by inspecting the stack trace. |
| AsObjectFactory | Factory for creating type-narrowing functions for TypedObject types. |
| AsTypeFactory | Factory for creating type-narrowing 'as' functions that cast a value to T or return undefined. Supports optional assertion messages and configuration for required/optional behavior. |
| JsonObjectZod | Zod schema for a JSON object with string keys and recursive JSON values. |
| isJsonValue | Type guard that checks if a value is a valid JSON value. |
| asJsonValue | Casts a value to JsonValue or returns undefined if it does not conform. |
| toJsonValue | Parses a value into a JsonValue, throwing if it does not conform. |
| isJsonArray | Type guard that checks if a value is a valid JSON array. |
| asJsonArray | Casts a value to JsonArray or returns undefined if it does not conform. |
| toJsonArray | Parses a value into a JsonArray, throwing if it does not conform. |
| isJsonObject | Type guard that checks if a value is a valid JSON object. |
| asJsonObject | Casts a value to JsonObject or returns undefined if it does not conform. |
| toJsonObject | Parses a value into a JsonObject, throwing if it does not conform. |
| asAnyObject | Type-narrowing function that casts a value to AnyObject if it is a plain object, or returns undefined. |
| deepMerge | Deeply merges multiple objects into a new object. |
| omitBy | Creates a new object excluding properties that satisfy the predicate, with optional recursive depth. |
| omitByPrefix | Omits all properties whose keys start with the given prefix, recursively through nested objects. |
| pickBy | Creates a new object containing only the properties that satisfy the predicate, with optional recursive depth. |
| pickByPrefix | Picks all properties whose keys start with the given prefix, recursively through nested objects. |
| removeFields | Returns a shallow copy of the object with the specified fields removed. |
| toSafeJsonArray | Converts an array to a JSON-safe array, handling circular references and depth limits. |
| toSafeJsonObject | Converts an object to a JSON-safe object, handling circular references and depth limits. |
| toSafeJsonValue | Converts an unknown value to a JSON-safe value, replacing circular references with '[Circular]' and non-JSON types with descriptive placeholder strings. |
| toSafeJsonString | Converts a value to a pretty-printed JSON string, safely handling circular references and non-JSON types. |
| toSafeJson | Converts a value to a JSON-safe representation, handling circular references and non-serializable types. |
| isBrowser | Returns whether the current environment is a browser. Always returns false in Node.js. |
| isWebworker | Returns whether the current environment is a web worker. Always returns false in Node.js. |
| isNode | Returns whether the current environment is Node.js. Always returns true in this entry point. |
| createProfiler | Creates a new empty profiler instance. |
| profile | Records a timestamp for the given profile name. |
| profileReport | Generates a report of elapsed times for each profiled entry. |
| fulfilled | For use with Promise.allSettled to filter only successful results |
| fulfilledValues | For use with Promise.allSettled to reduce to only successful result values |
| rejected | For use with Promise.allSettled to filter only rejected results |
| retry | Retries an async function with exponential backoff until it completes or retries are exhausted. |
| difference | Returns a new set containing elements in a that are not in b. |
| intersection | Returns a new set containing only elements present in both a and b. |
| union | Returns a new set containing all elements from both a and b. |
| setTimeoutEx | Sets a timeout using an optimized internal timer that coalesces multiple timeouts into a single native timer. |
| clearTimeoutEx | Cancels a timeout previously created with setTimeoutEx. |
| isTypedKey | Type guard that checks whether a value is a valid TypedKey (string, bigint, number, or symbol). |
| isTypedValue | Type guard that checks whether a value is a valid TypedValue. |
| isTypedArray | Type guard that checks whether a value is a TypedArray (an array where every element is a TypedValue). |
| isValidTypedFieldPair | Type guard that checks whether a key-value pair has a valid TypedKey and TypedValue. |
| isTypedObject | Type guard that checks whether a value is a TypedObject (an object with TypedKey keys and TypedValue values). |
| ifDefined | Invokes the callback only if the value is neither null nor undefined. |
| ifTypeOf | Invokes the callback if the value matches the specified type, with an optional additional predicate. |
| isType | Checks whether a value matches the expected field type, with correct handling for arrays and nulls. |
| typeOf | Extended typeof that distinguishes arrays from objects (unlike native typeof). |
| validateType | Validates that a value matches the expected type, returning the value and any errors. |
| URL | Node.js-specific URL class, imported from the node:url module. |
| isLocalhost | Checks whether a hostname refers to the local machine (localhost, 127.0.0.1, ::1, or *.localhost). |
Functions
| Function | Description |
| ------ | ------ |
| isArrayBuffer | Type guard that checks if a value is an ArrayBuffer instance. |
| isArrayBufferLike | Type guard that checks if a value conforms to the ArrayBufferLike interface (has byteLength and slice). |
| toArrayBuffer | Converts a string, bigint, or ArrayBufferLike to an ArrayBufferLike, with optional zero-padding. |
| toUint8Array | Converts a string, bigint, or ArrayBufferLike to a Uint8Array, with optional zero-padding. |
| assertDefinedEx | Asserts that a value is defined (not undefined) and returns the value. Throws an error if the value is undefined. |
| assertEx | Asserts that an expression is truthy and returns the value. Throws an error if the expression is falsy. |
| axiosJsonConfig | Creates an Axios config preconfigured for JSON requests with optional gzip compression. Request bodies exceeding compressLength (default 1024 bytes) are automatically gzip-compressed. |
| creatable | Class annotation to be used to decorate Modules which support an asynchronous creation pattern |
| creatableFactory | Class annotation to be used to decorate Modules which support an asynchronous creation factory pattern |
| asAddress | Attempts to coerce a value into an Address type, returning undefined or throwing based on the assert config. |
| asAddressV2 | - |
| isAddressV2 | - |
| toAddressV2 | - |
| asEthAddress | Attempts to coerce a value into an EthAddress, returning undefined or throwing based on the assert config. |
| asHash | Attempts to coerce a value into a Hash type, returning undefined or throwing based on the assert config. |
| asHex | Attempts to coerce a value into a Hex type, returning undefined or throwing based on the assert config. |
| hexToBigInt | Converts a Hex string to a BigInt. |
| createDeepMerge | Creates a deep merge function with the specified options. |
| toPromise | Wraps a value in a Promise if it is not already one. |
| staticImplements | Annotation to decorate classes which implement static methods |
| cloneContextWithoutSpan | Creates a new OpenTelemetry context that preserves baggage and custom keys but has no active span. |
| span | Executes a synchronous function within an OpenTelemetry span, recording status and exceptions. |
| spanRoot | Executes a synchronous function within a new root span that has no parent, even if a span is already active. |
| spanAsync | Executes an async function within an OpenTelemetry span, with optional time budget monitoring. |
| spanRootAsync | Executes an async function within a new root span (no parent), with optional time budget monitoring. |
| timeBudget | Executes an async function and logs a warning if it exceeds the given time budget. |
| spanDurationInMillis | Calculates the duration of a span in milliseconds from its high-resolution time tuple. |
| isUndefined | Type guard that checks whether a value is undefined. |
| isDefined | Type guard that checks whether a value is not undefined. |
| isNull | Type guard that checks whether a value is null. |
| isDefinedNotNull | Type guard that checks whether a value is neither undefined nor null. |
| isUndefinedOrNull | Type guard that checks whether a value is undefined or null. |
| isBigInt | Type guard that checks whether a value is a bigint. |
| isString | Type guard that checks whether a value is a string. |
| isNumber | Type guard that checks whether a value is a number. |
| isObject | Type guard that checks whether a value is a plain object (not null and not an array). |
| isArray | Type guard that checks whether a value is an array. |
| isFunction | Type guard that checks whether a value is a function. |
| isSymbol | Type guard that checks whether a value is a symbol. |
| isEmptyObject | Type guard that checks whether a value is an object with no own keys. |
| isEmptyString | Type guard that checks whether a value is an empty string. |
| isEmptyArray | Type guard that checks whether a value is an empty array. |
| isPopulatedArray | Type guard that checks whether a value is a non-empty array. |
| isEmpty | Type guard that checks whether a value is empty (empty string, empty array, or empty object). |
| isFalsy | Type guard that checks whether a value is falsy (0, null, undefined, false, '', or 0n). |
| isTruthy | Type guard that checks whether a value is truthy (not 0, null, undefined, false, '', or 0n). |
| isBoolean | Type guard that checks whether a value is a boolean. |
| isDateString | Type guard that checks whether a value is a string that can be parsed as a valid date. |
| isDate | Type guard that checks whether a value is a Date instance. |
| isRegExp | Type guard that checks whether a value is a RegExp instance. |
| isError | Type guard that checks whether a value is an Error instance. |
| isPromise | Type guard that checks whether a value is a Promise instance. |
| isPromiseLike | Type guard that checks whether a value is promise-like (has a then method). |
| isMap | Type guard that checks whether a value is a Map instance. |
| isArrayBufferView | Type guard that checks whether a value is an ArrayBufferView (e.g., TypedArray or DataView). |
| isSet | Type guard that checks whether a value is a Set instance. |
| isWeakMap | Type guard that checks whether a value is a WeakMap instance. |
| isWeakSet | Type guard that checks whether a value is a WeakSet instance. |
| isDataView | Type guard that checks whether a value is a DataView instance. |
| isBlob | Type guard that checks whether a value is a Blob instance. |
| isFile | Type guard that checks whether a value is a File instance. |
| zodAllFactory | Creates a bundle of is, as, and to factory functions for a given zod schema. |
| zodAsAsyncFactory | Creates an async function that validates a value against a zod schema and returns it with a narrowed type. Uses safeParseAsync for schemas with async refinements. When called without an assert config, returns undefined on failure. |
| zodAsFactory | Creates a function that validates a value against a zod schema and returns it with a narrowed type. When called without an assert config, returns undefined on failure. When called with an assert config, throws on failure. |
| zodIsFactory | Creates a type guard function that checks if a value matches a zod schema. |
| zodToAsyncFactory | Creates an async function that converts a value to the zod schema type, delegating to zodAsAsyncFactory internally. Provides overloads for optional assertion: without assert config resolves to undefined on failure, with assert config throws on failure. |
| zodToFactory | Creates a function that converts a value to the zod schema type, delegating to zodAsFactory internally. Provides overloads for optional assertion: without assert config returns undefined on failure, with assert config throws on failure. |
classes
AbstractCreatable
Base class for objects that follow an asynchronous creation and lifecycle pattern.
Instances must be created via the static create method rather than direct construction.
Provides start/stop lifecycle management with status tracking and telemetry support.
Extends
BaseEmitter<Partial<TParams&RequiredCreatableParams>,TEventData>
Extended by
Type Parameters
| Type Parameter | Default type |
| ------ | ------ |
| TParams extends CreatableParams | CreatableParams |
| TEventData extends EventData | EventData |
Constructors
Constructor
new AbstractCreatable<TParams, TEventData>(key: unknown, params: Partial<TParams & RequiredCreatableParams>): AbstractCreatable<TParams, TEventData>;Parameters
| Parameter | Type |
| ------ | ------ |
| key | unknown |
| params | Partial<TParams & RequiredCreatableParams> |
Returns
AbstractCreatable<TParams, TEventData>
Overrides
Properties
| Property | Modifier | Type | Description | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| defaultLogger? | static | Logger | - | BaseEmitter.defaultLogger |
| globalInstances | readonly | Record<BaseClassName, WeakRef<Base>[]> | - | BaseEmitter.globalInstances |
| globalInstancesCountHistory | readonly | Record<BaseClassName, number[]> | - | BaseEmitter.globalInstancesCountHistory |
| defaultLogger? | public | Logger | Optional default logger for this instance. | - |
| _startPromise | protected | Promisable<boolean> | undefined | - | - |
| eventData | public | TEventData | Type-level reference to the event data shape for external type queries. | BaseEmitter.eventData |
Accessors
historyInterval
Get Signature
get static historyInterval(): number;Returns
number
Set Signature
set static historyInterval(value: number): void;Parameters
| Parameter | Type |
| ------ | ------ |
| value | number |
Returns
void
Inherited from
historyTime
Get Signature
get static historyTime(): number;Returns
number
Set Signature
set static historyTime(value: number): void;Parameters
| Parameter | Type |
| ------ | ------ |
| value | number |
Returns
void
Inherited from
maxGcFrequency
Get Signature
get static maxGcFrequency(): number;Returns
number
Set Signature
set static maxGcFrequency(value: number): void;Parameters
| Parameter | Type |
| ------ | ------ |
| value | number |
Returns
void
Inherited from
maxHistoryDepth
Get Signature
get static maxHistoryDepth(): number;Returns
number
Inherited from
logger
Get Signature
get logger(): Logger | undefined;Returns
Logger | undefined
Inherited from
meter
Get Signature
get meter(): Meter | undefined;Returns
Meter | undefined
Inherited from
tracer
Get Signature
get tracer(): Tracer | undefined;Returns
Tracer | undefined
Inherited from
name
Get Signature
get name(): CreatableName;The name identifier for this creatable instance.
Returns
params
Get Signature
get params(): TParams & RequiredCreatableParams<void>;The validated and merged parameters for this instance.
Returns
TParams & RequiredCreatableParams<void>
Overrides
startable
Get Signature
get startable(): boolean;Whether this instance can be started (must be in 'created' or 'stopped' status).
Returns
boolean
status
Get Signature
get status(): CreatableStatus | null;The current lifecycle status of this instance, or null if not yet initialized.
Returns
CreatableStatus | null
statusReporter
Get Signature
get statusReporter():
| CreatableStatusReporter<void>
| undefined;The status reporter used to broadcast lifecycle changes.
Returns
| CreatableStatusReporter<void>
| undefined
Methods
gc()
Call Signature
static gc(force?: boolean): void;Parameters
| Parameter | Type |
| ------ | ------ |
| force? | boolean |
Returns
void
Inherited from
Call Signature
static gc(className: BaseClassName): void;Parameters
| Parameter | Type |
| ------ | ------ |
| className | BaseClassName |
Returns
void
Inherited from
instanceCount()
static instanceCount(className: BaseClassName): number;Parameters
| Parameter | Type |
| ------ | ------ |
| className | BaseClassName |
Returns
number
Inherited from
instanceCounts()
static instanceCounts(): Record<BaseClassName, number>;Returns
Record<BaseClassName, number>
Inherited from
startHistory()
static startHistory(): void;Returns
void
Inherited from
stopHistory()
static stopHistory(): void;Returns
void
Inherited from
create()
static create<T>(this: Creatable<T>, inParams?: Partial<T["params"]>): Promise<T>;Asynchronously creates a new instance by processing params, constructing, and running both static and instance createHandlers.
Type Parameters
| Type Parameter |
| ------ |
| T extends CreatableInstance<CreatableParams, EventData> |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| this | Creatable<T> | - |
| inParams? | Partial<T["params"]> | Optional partial parameters to configure the instance |
Returns
Promise<T>
The fully initialized instance
createHandler()
static createHandler<T>(this: Creatable<T>, instance: T): Promisable<T>;Static hook called during creation to perform additional initialization. Override in subclasses to customize post-construction setup.
Type Parameters
| Type Parameter |
| ------ |
| T extends CreatableInstance<CreatableParams, EventData> |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| this | Creatable<T> | - |
| instance | T | The newly constructed instance |
Returns
Promisable<T>
The instance, potentially modified
paramsHandler()
static paramsHandler<T>(this: Creatable<T>, params?: Partial<T["params"]>): Promisable<T["params"]>;Static hook called during creation to validate and transform params. Override in subclasses to add default values or validation.
Type Parameters
| Type Parameter |
| ------ |
| T extends CreatableInstance<CreatableParams, EventData> |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| this | Creatable<T> | - |
| params? | Partial<T["params"]> | The raw partial params provided to create |
Returns
Promisable<T["params"]>
The processed params ready for construction
createHandler()
createHandler(): Promisable<void>;Instance-level creation hook. Override in subclasses to perform setup after construction.
Returns
Promisable<void>
paramsValidator()
paramsValidator(params: Partial<TParams & RequiredCreatableParams>): TParams & RequiredCreatableParams<void>;Validates and returns the merged params, ensuring required fields are present. Override in subclasses to add custom validation logic.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| params | Partial<TParams & RequiredCreatableParams> | The raw partial params to validate |
Returns
TParams & RequiredCreatableParams<void>
The validated params
span()
span<T>(name: string, fn: () => T): T;Executes a function within a telemetry span.
Type Parameters
| Type Parameter |
| ------ |
| T |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| name | string | The span name |
| fn | () => T | The function to execute within the span |
Returns
T
spanAsync()
spanAsync<T>(
name: string,
fn: () => Promise<T>,
config?: SpanConfig): Promise<T>;Executes an async function within a telemetry span.
Type Parameters
| Type Parameter |
| ------ |
| T |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| name | string | The span name |
| fn | () => Promise<T> | The async function to execute within the span |
| config? | SpanConfig | Optional span configuration |
Returns
Promise<T>
start()
start(): Promise<boolean>;Starts the instance, transitioning through 'starting' to 'started' status. Thread-safe via mutex. Returns true if already started or started successfully.
Returns
Promise<boolean>
started()
started(notStartedAction?: "error" | "throw" | "warn" | "log" | "none"): boolean;Checks whether this instance is currently started. Takes an action if not started, based on the notStartedAction parameter.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| notStartedAction? | "error" | "throw" | "warn" | "log" | "none" | What to do if not started: 'error'/'throw' throws, 'warn'/'log' logs, 'none' is silent |
Returns
boolean
True if started, false otherwise
startedAsync()
startedAsync(notStartedAction?: "error" | "throw" | "warn" | "log" | "none", tryStart?: boolean): Promise<boolean>;Async version of started that can optionally auto-start the instance.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| notStartedAction? | "error" | "throw" | "warn" | "log" | "none" | What to do if not started and auto-start is disabled |
| tryStart? | boolean | If true, attempts to start the instance automatically |
Returns
Promise<boolean>
True if the instance is or becomes started
stop()
stop(): Promise<boolean>;Stops the instance, transitioning through 'stopping' to 'stopped' status. Thread-safe via mutex. Returns true if already stopped or stopped successfully.
Returns
Promise<boolean>
_noOverride()
protected _noOverride(functionName?: string): void;Asserts that the given function has not been overridden in a subclass.
Used to enforce the handler pattern (override startHandler not start).
Parameters
| Parameter | Type |
| ------ | ------ |
| functionName? | string |
Returns
void
setStatus()
Call Signature
protected setStatus(value: "creating" | "created" | "starting" | "started" | "stopping" | "stopped", progress?: number): void;Sets the lifecycle status and reports it via the status reporter.
Parameters
| Parameter | Type |
| ------ | ------ |
| value | "creating" | "created" | "starting" | "started" | "stopping" | "stopped" |
| progress? | number |
Returns
void
Call Signature
protected setStatus(value: "error", error?: Error): void;Sets the lifecycle status and reports it via the status reporter.
Parameters
| Parameter | Type |
| ------ | ------ |
| value | "error" |
| error? | Error |
Returns
void
startHandler()
protected startHandler(): Promisable<void>;Override in subclasses to define start behavior. Throw an error on failure.
Returns
Promisable<void>
stopHandler()
protected stopHandler(): Promisable<void>;Override in subclasses to define stop behavior. Throw an error on failure.
Returns
Promisable<void>
clearListeners()
clearListeners(eventNames: keyof TEventData | keyof TEventData[]): this;Removes all listeners for the specified event name(s).
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| eventNames | keyof TEventData | keyof TEventData[] | One or more event names to clear listeners for. |
Returns
this
This instance for chaining.
Inherited from
emit()
emit<TEventName, TEventArgs>(eventName: TEventName, eventArgs: TEventArgs): Promise<void>;Emits an event, invoking all registered listeners concurrently.
Type Parameters
| Type Parameter | Default type |
| ------ | ------ |
| TEventName extends string | number | symbol | keyof TEventData |
| TEventArgs extends EventArgs | TEventData[TEventName] |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| eventName | TEventName | The event to emit. |
| eventArgs | TEventArgs | The data to pass to listeners. |
Returns
Promise<void>
Inherited from
emitSerial()
emitSerial<TEventName, TEventArgs>(eventName: TEventName, eventArgs: TEventArgs): Promise<void>;Emits an event, invoking all registered listeners sequentially in order.
Type Parameters
| Type Parameter | Default type |
| ------ | ------ |
| TEventName extends string | number | symbol | keyof TEventData |
| TEventArgs extends EventArgs | TEventData[TEventName] |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| eventName | TEventName | The event to emit. |
| eventArgs | TEventArgs | The data to pass to listeners. |
Returns
Promise<void>
Inherited from
listenerCount()
listenerCount(eventNames: keyof TEventData | keyof TEventData[]): number;Returns the total number of listeners registered for the specified event name(s).
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| eventNames | keyof TEventData | keyof TEventData[] | One or more event names to count listeners for. |
Returns
number
The total listener count.
Inherited from
off()
off<TEventName>(eventNames: TEventName | TEventName[], listener: EventListener<TEventData[TEventName]>): void;Removes a specific listener from the specified event name(s).
Type Parameters
| Type Parameter |
| ------ |
| TEventName extends string | number | symbol |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| eventNames | TEventName | TEventName[] | One or more event names to unsubscribe from. |
| listener | EventListener<TEventData[TEventName]> | The listener to remove. |
Returns
void
Inherited from
offAny()
offAny(listener: EventAnyListener): void;Removes a wildcard listener that was receiving all events.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| listener | EventAnyListener | The wildcard listener to remove. |
Returns
void
Inherited from
on()
on<TEventName>(eventNames: TEventName | TEventName[], listener: EventListener<TEventData[TEventName]>): () => void;Subscribes a listener to the specified event name(s).
Type Parameters
| Type Parameter |
| ------ |
| TEventName extends string | number | symbol |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| eventNames | TEventName | TEventName[] | One or more event names to listen for. |
| listener | EventListener<TEventData[TEventName]> | The callback to invoke when the event fires. |
Returns
An unsubscribe function.
(): void;Returns
void
Inherited from
onAny()
onAny(listener: EventAnyListener): () => void;Subscribes a wildcard listener that receives all events.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| listener | EventAnyListener | The callback to invoke for any event. |
Returns
An unsubscribe function.
(): void;Returns
void
Inherited from
once()
once<TEventName>(eventName: TEventName, listener: EventListener<TEventData[TEventName]>): () => void;Subscribes a listener that will be invoked only once for the specified event, then automatically removed.
Type Parameters
| Type Parameter |
| ------ |
| TEventName extends string | number | symbol |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| eventName | TEventName | The event to listen for. |
| listener | EventListener<TEventData[TEventName]> | The callback to invoke once. |
Returns
An unsubscribe function.
(): void;Returns
void
Inherited from
AbstractCreatableWithFactory
Extends AbstractCreatable with a static factory method for creating
pre-configured CreatableFactory instances.
Extends
AbstractCreatable<TParams,TEventData>
Type Parameters
| Type Parameter | Default type |
| ------ | ------ |
| TParams extends CreatableParams | CreatableParams |
| TEventData extends EventData | EventData |
Constructors
Constructor
new AbstractCreatableWithFactory<TParams, TEventData>(key: unknown, params: Partial<TParams & RequiredCreatableParams>): AbstractCreatableWithFactory<TParams, TEventData>;Parameters
| Parameter | Type |
| ------ | ------ |
| key | unknown |
| params | Partial<TParams & RequiredCreatableParams> |
Returns
AbstractCreatableWithFactory<TParams, TEventData>
Inherited from
Properties
| Property | Modifier | Type | Description | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| defaultLogger? | static | Logger | - | AbstractCreatable.defaultLogger |
| globalInstances | readonly | Record<BaseClassName, WeakRef<Base>[]> | - | AbstractCreatable.[globalInstances](AbstractCreatable.md#glo
