@fuman/utils
Advanced tools
| import * as typed from './typed/index.js'; | ||
| import * as u8 from './u8/index.js'; | ||
| export * from './typed/types.js'; | ||
| export { typed, u8 }; |
| import { TypedArray } from './types.js'; | ||
| /** | ||
| * Compare two typed arrays element by element and return -1, 0, or 1, | ||
| * depending on whether the first typed array is less than, equal to, or greater than the second one | ||
| * (similar to the behavior of `String.prototype.localeCompare` for strings) | ||
| */ | ||
| export declare function compare<T extends TypedArray>(a: T, b: T): -1 | 0 | 1; | ||
| /** | ||
| * Check if two typed arrays are equal | ||
| * | ||
| * @param a First buffer | ||
| * @param b Second buffer | ||
| */ | ||
| export declare function equal<T extends TypedArray>(a: T, b: T): boolean; |
| import { TypedArray } from './types.js'; | ||
| export declare function indexOf(haystack: Exclude<TypedArray, BigInt64Array | BigUint64Array>, needle: number, start?: number): number; | ||
| export declare function indexOf(haystack: BigInt64Array | BigUint64Array, needle: bigint, start?: number): number; | ||
| export declare function lastIndexOf(haystack: Exclude<TypedArray, BigInt64Array | BigUint64Array>, needle: number, start?: number): number; | ||
| export declare function lastIndexOf(haystack: BigInt64Array | BigUint64Array, needle: bigint, start?: number): number; | ||
| export declare function indexOfArray<T extends TypedArray>(haystack: T, needle: T, start?: number): number; | ||
| export declare function lastIndexOfArray<T extends TypedArray>(haystack: T, needle: T, start?: number): number; | ||
| export declare function includes(haystack: Exclude<TypedArray, BigInt64Array | BigUint64Array>, needle: number): boolean; | ||
| export declare function includes(haystack: BigInt64Array | BigUint64Array, needle: bigint): boolean; | ||
| export declare function includesArray<T extends TypedArray>(haystack: T, needle: T): boolean; |
| export * from './compare.js'; | ||
| export * from './find.js'; | ||
| export * from './misc.js'; |
| import { TypedArray } from './types.js'; | ||
| /** | ||
| * Shortcut for creating a DataView from a typed array | ||
| */ | ||
| export declare function toDataView(buf: TypedArray): DataView; | ||
| export declare function view<Res extends TypedArray>(ctor: { | ||
| new (buffer: ArrayBufferLike, byteOffset: number, byteLength: number): Res; | ||
| BYTES_PER_ELEMENT: number; | ||
| }, buf: ArrayBufferView): Res; | ||
| /** Get the platform byte order (which is used in typed arrays) */ | ||
| export declare function getPlatformByteOrder(): 'little' | 'big'; |
| import { AnyToNever } from '../../types/misc.js'; | ||
| export type TypedArray = Uint8Array | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array | AnyToNever<BigInt64Array> | AnyToNever<BigUint64Array>; |
| /** | ||
| * Concatenate multiple byte arrays into one | ||
| */ | ||
| export declare function concat(buffers: Uint8Array[]): Uint8Array; | ||
| /** | ||
| * Concatenate two byte arrays into one, always copying the data. | ||
| * | ||
| * @param a First byte array | ||
| * @param b Second byte array | ||
| */ | ||
| export declare function concat2(a: ArrayLike<number>, b: ArrayLike<number>): Uint8Array; | ||
| /** | ||
| * Concatenate three byte arrays into one, always copying the data. | ||
| * | ||
| * @param a First byte array | ||
| * @param b Second byte array | ||
| * @param c Third byte array | ||
| */ | ||
| export declare function concat3(a: ArrayLike<number>, b: ArrayLike<number>, c: ArrayLike<number>): Uint8Array; |
| export * from './concat.js'; | ||
| export * from './misc.js'; | ||
| export * from './pool.js'; | ||
| export * from './reverse.js'; | ||
| export * from './swap.js'; | ||
| export * from './xor.js'; |
| /** | ||
| * An empty byte array with zero length | ||
| */ | ||
| export declare const empty: Uint8Array; | ||
| export declare function clone(buf: Uint8Array): Uint8Array; | ||
| /** Read N-th bit of a number (starting from the least significant bit) */ | ||
| export declare function readNthBit(byte: number, bit: number): number; |
| /** | ||
| * Pool for buffer allocations, as seen in [Node.js](https://github.com/nodejs/node/blob/main/lib/buffer.js) | ||
| */ | ||
| export declare class BufferPool { | ||
| #private; | ||
| readonly size: number; | ||
| constructor(size: number); | ||
| alloc(size: number): Uint8Array; | ||
| } | ||
| /** | ||
| * Override the default buffer pool size (the one used by `u8.alloc`) | ||
| */ | ||
| export declare function setDefaultPoolSize(size: number): void; | ||
| /** | ||
| * Allocate a new buffer of the given size. | ||
| * For smaller sizes, the allocation will be from the default buffer pool, | ||
| * similar to `Buffer.alloc` in Node.js | ||
| */ | ||
| export declare function alloc(size: number): Uint8Array; | ||
| /** | ||
| * Shortcut for allocating a buffer and filling it with the given data, | ||
| * similar to `Buffer.from` in Node.js | ||
| */ | ||
| export declare function allocWith(init: ArrayLike<number>): Uint8Array; |
| export declare function reverse(buffer: Uint8Array): void; | ||
| export declare function toReversed(buffer: ArrayLike<number>): Uint8Array; |
| /** | ||
| * Swap byte order of the byte array **in place**, | ||
| * interpreting the buffer as an array of 16-bit integers | ||
| * | ||
| * @example `swap16(new Uint8Array([0x12, 0x34, 0x56, 0x78])) // becomes [0x34, 0x12, 0x78, 0x56] | ||
| * @throws RangeError when the buffer length is not a multiple of 2 | ||
| */ | ||
| export declare function swap16(buf: Uint8Array): void; | ||
| /** | ||
| * Swap byte order of the byte array **in place**, | ||
| * interpreting the buffer as an array of 32-bit integers | ||
| * | ||
| * @example `swap32(new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0])) // becomes [0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a] | ||
| * @throws RangeError when the buffer length is not a multiple of 4 | ||
| */ | ||
| export declare function swap32(buf: Uint8Array): void; | ||
| /** | ||
| * Swap byte order of the byte array **in place**, | ||
| * interpreting the buffer as an array of 64-bit integers | ||
| * | ||
| * @example `swap32(new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0])) // becomes [0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12] | ||
| * @throws RangeError when the buffer length is not a multiple of 4 | ||
| */ | ||
| export declare function swap64(buf: Uint8Array): void; | ||
| /** | ||
| * Swap the *half-byte* ordering of each byte in the byte array, **in place** | ||
| * | ||
| * @example `swap8(new Uint8Array([0x12, 0x34, 0x56, 0x78])) // becomes [0x21, 0x43, 0x65, 0x87] | ||
| */ | ||
| export declare function swapNibbles(buf: Uint8Array): void; |
| /** | ||
| * Perform XOR operation on two buffers and return the new buffer | ||
| * | ||
| * @param data Buffer to XOR | ||
| * @param key Key to XOR with | ||
| */ | ||
| export declare function xor(data: Uint8Array, key: Uint8Array): Uint8Array; | ||
| /** | ||
| * Perform XOR operation on two buffers in-place | ||
| * | ||
| * @param data Buffer to XOR | ||
| * @param key Key to XOR with | ||
| */ | ||
| export declare function xorInPlace(data: Uint8Array, key: Uint8Array): void; |
| /** | ||
| * setInterval() alternative built with async functions in mind | ||
| * | ||
| * usage: | ||
| * ```ts | ||
| * const interval = new AsyncInterval(async (signal) => { | ||
| * await fetch('https://example.com/ping', { signal }) | ||
| * }, 60_000) | ||
| * interval.start() | ||
| * onAppClose(() => interval.stop()) | ||
| * ``` | ||
| * | ||
| * errors are ignored by default, but you can add a handler via `onError` method | ||
| */ | ||
| export declare class AsyncInterval { | ||
| #private; | ||
| constructor(handler: (abortSignal: AbortSignal) => Promise<void>, interval: number); | ||
| start(after?: number): void; | ||
| startNow(): void; | ||
| stop(): void; | ||
| onError(handler: (err: unknown) => void): void; | ||
| } |
| /** | ||
| * Simple class implementing a semaphore like | ||
| * behaviour. | ||
| */ | ||
| export declare class AsyncLock { | ||
| private _queue; | ||
| acquire(): Promise<void>; | ||
| release(): void; | ||
| with(func: () => Promise<void>): Promise<void>; | ||
| } |
| import { Deque } from '../structures/deque.js'; | ||
| export declare class AsyncQueue<T> { | ||
| #private; | ||
| constructor(from?: ArrayLike<T> | Deque<T>); | ||
| /** | ||
| * Underlying deque. | ||
| * | ||
| * Use with care and don't modify it directly, | ||
| * as it may break the async queue's internal state. | ||
| */ | ||
| readonly queue: Deque<T>; | ||
| get length(): number; | ||
| enqueue(item: T): void; | ||
| end(): void; | ||
| peek(): T | undefined; | ||
| next(): T | undefined; | ||
| nextOrWait(): Promise<T | undefined>; | ||
| [Symbol.asyncIterator](): AsyncIterableIterator<T>; | ||
| } |
| import { Emitter } from './emitter.js'; | ||
| export interface AsyncResourceContext<T> { | ||
| /** currently cached value of the resource */ | ||
| readonly current: T | null; | ||
| /** performance.now() when the resource was fetched */ | ||
| readonly currentFetchedAt: number; | ||
| /** performance.now() when the resource will/did expire */ | ||
| readonly currentExpiresAt: number; | ||
| /** | ||
| * whether the current fetch was initiated in the background | ||
| * (by the swr mechanism or because of auto-reload). | ||
| * this can be used to prioritize the fetch if needed | ||
| */ | ||
| readonly isBackground: boolean; | ||
| /** abort signal that should be used to abort the fetch */ | ||
| readonly abort: AbortSignal; | ||
| } | ||
| export interface AsyncResourceOptions<T> { | ||
| /** | ||
| * if true, the resource will be automatically | ||
| * reloaded after {@link autoReloadAfter} milliseconds | ||
| * once the resource is expires | ||
| * | ||
| * (note that it will need to be fetched manually at least once) | ||
| */ | ||
| autoReload?: boolean; | ||
| /** | ||
| * time in milliseconds after which the resource will be reloaded | ||
| * after expiring if {@link autoReload} is true. | ||
| * can be negative to reload before expiring | ||
| * | ||
| * @default 0 (i.e. as soon as it expires) | ||
| */ | ||
| autoReloadAfter?: number; | ||
| /** | ||
| * if true, the resource will keep returning expired data | ||
| * after it expires while the resource is being reloaded | ||
| */ | ||
| swr?: boolean; | ||
| /** | ||
| * if {@link swr} is true, this function will be called | ||
| * to validate if the cached data is still valid | ||
| */ | ||
| swrValidator?: (ctx: AsyncResourceContext<T>) => boolean; | ||
| /** | ||
| * function that will be called to fetch the resource | ||
| * | ||
| * @returns Promise that resolves to the resource and the number of milliseconds before it expires | ||
| */ | ||
| fetcher: (ctx: AsyncResourceContext<T>) => Promise<{ | ||
| data: T; | ||
| expiresIn: number; | ||
| }>; | ||
| /** | ||
| * function that will be called if {@link fetcher} throws an error | ||
| * | ||
| * @param err error thrown by {@link fetcher} | ||
| * @default `console.error(err)` | ||
| */ | ||
| onError?: (err: unknown, ctx: AsyncResourceContext<T>) => void; | ||
| } | ||
| export declare class AsyncResource<T> { | ||
| #private; | ||
| readonly params: AsyncResourceOptions<T>; | ||
| readonly onUpdated: Emitter<AsyncResourceContext<T>>; | ||
| constructor(params: AsyncResourceOptions<T>); | ||
| get isStale(): boolean; | ||
| setData(data: T, expiresIn: number): void; | ||
| /** | ||
| * update the resource | ||
| * | ||
| * @param force whether to force the update even if the resource hasn't expired yet | ||
| */ | ||
| update(force?: boolean): Promise<void>; | ||
| /** | ||
| * get the resource value, refreshing it if needed | ||
| * | ||
| * note: this method still *might* return `null` if the resource wasn't ever cached yet, | ||
| * and the underlying call to `fetcher` failed | ||
| */ | ||
| get(): Promise<T | null>; | ||
| /** | ||
| * get the cached resource value immediately (if any) | ||
| * note that it may be stale, which you should check separately | ||
| */ | ||
| getCached(): T | null; | ||
| destroy(): void; | ||
| } |
| /** | ||
| * Class implementing a condition variable like behaviour. | ||
| */ | ||
| export declare class ConditionVariable { | ||
| #private; | ||
| wait(): Promise<void>; | ||
| notify(): void; | ||
| } |
| export declare class Deferred<T = void> { | ||
| readonly resolve: (value: T) => void; | ||
| readonly reject: (reason: unknown) => void; | ||
| readonly promise: Promise<T>; | ||
| constructor(); | ||
| } |
| export {}; |
| export declare class Emitter<T> { | ||
| #private; | ||
| get length(): number; | ||
| add(listener: (value: T) => void): void; | ||
| forwardTo(emitter: Emitter<T>): void; | ||
| remove(listener: (value: T) => void): void; | ||
| emit(value: T): void; | ||
| once(listener: (value: T) => void): void; | ||
| listeners(): readonly ((value: T) => void)[]; | ||
| clear(): void; | ||
| } |
| import * as timers from './timers.js'; | ||
| export { timers }; | ||
| export * from './async-interval.js'; | ||
| export * from './async-lock.js'; | ||
| export * from './async-queue.js'; | ||
| export * from './async-resource.js'; | ||
| export * from './condition-variable.js'; | ||
| export * from './deferred.js'; | ||
| export * from './emitter.js'; | ||
| export * from './pool.js'; | ||
| export * from './sleep.js'; |
| import { MaybePromise } from '../types/misc.js'; | ||
| export interface AsyncPoolOptions<Item> { | ||
| /** | ||
| * Concurrency limit | ||
| * | ||
| * @default 16 | ||
| */ | ||
| limit?: number; | ||
| /** Abort signal */ | ||
| signal?: AbortSignal; | ||
| /** | ||
| * Customize the behavior when an error is thrown in the iterator. | ||
| * | ||
| * - `ignore` - Ignore the error and continue | ||
| * - `collect` - Collect the error and throw it at the end in an `AggregateError` | ||
| * - `throw` - Throw the error immediately, and stop any other pending tasks | ||
| * | ||
| * @default `() => 'throw'` | ||
| */ | ||
| onError?: (item: Item, index: number, error: unknown) => MaybePromise<'ignore' | 'collect' | 'throw'>; | ||
| } | ||
| declare class ErrorInfo<Item> { | ||
| readonly item: Item; | ||
| readonly index: number; | ||
| readonly error: unknown; | ||
| constructor(item: Item, index: number, error: unknown); | ||
| } | ||
| export declare class AggregateError<Item> extends Error { | ||
| readonly errors: ErrorInfo<Item>[]; | ||
| constructor(errors: ErrorInfo<Item>[]); | ||
| } | ||
| export declare function asyncPool<Item>(iterable: Iterable<Item> | AsyncIterable<Item>, executor: (item: Item, index: number) => MaybePromise<void>, options?: AsyncPoolOptions<Item>): Promise<void>; | ||
| export declare function parallelMap<Item, Result>(iterable: Iterable<Item> | AsyncIterable<Item>, executor: (item: Item, index: number) => MaybePromise<Result>, options?: AsyncPoolOptions<Item>): Promise<Result[]>; | ||
| export {}; |
| export declare function sleep(ms: number): Promise<void>; |
| import { Brand } from '../types/brand.js'; | ||
| export type Timer = Brand<object, 'Timer'>; | ||
| export type Interval = Brand<object, 'Interval'>; | ||
| declare const setTimeoutWrap: <T extends (...args: any[]) => any>(fn: T, ms: number, ...args: Parameters<T>) => Timer; | ||
| declare const setIntervalWrap: <T extends (...args: any[]) => any>(fn: T, ms: number, ...args: Parameters<T>) => Interval; | ||
| declare const clearTimeoutWrap: (timer?: Timer) => void; | ||
| declare const clearIntervalWrap: (timer?: Interval) => void; | ||
| export { clearIntervalWrap as clearInterval, clearTimeoutWrap as clearTimeout, setIntervalWrap as setInterval, setTimeoutWrap as setTimeout, }; |
| export * from './bytes.js'; | ||
| export * from './math.js'; |
| /** | ||
| * Convert a big integer to a byte array | ||
| * | ||
| * @param value Value to convert | ||
| * @param length Length of the resulting buffer (by default it's the minimum required) | ||
| * @param le Whether to use little-endian encoding | ||
| */ | ||
| export declare function toBytes(value: bigint, length?: number, le?: boolean): Uint8Array; | ||
| /** | ||
| * Convert a byte array to a big integer | ||
| * | ||
| * @param buffer Byte array to convert | ||
| * @param le Whether to use little-endian encoding | ||
| */ | ||
| export declare function fromBytes(buffer: Uint8Array, le?: boolean): bigint; |
| import * as bigint from './bundle.js'; | ||
| export { bigint }; |
| /** | ||
| * Get the minimum number of bits required to represent the number | ||
| */ | ||
| export declare function bitLength(n: bigint): number; | ||
| /** | ||
| * Compute the multiplicity of 2 in the prime factorization of n | ||
| * @param n | ||
| */ | ||
| export declare function twoMultiplicity(n: bigint): bigint; | ||
| export declare function min2(a: bigint, b: bigint): bigint; | ||
| export declare function min(...args: bigint[]): bigint; | ||
| export declare function max2(a: bigint, b: bigint): bigint; | ||
| export declare function max(...args: bigint[]): bigint; | ||
| export declare function abs(a: bigint): bigint; | ||
| export declare function euclideanGcd(a: bigint, b: bigint): bigint; | ||
| export declare function modPowBinary(base: bigint, exp: bigint, mod: bigint): bigint; | ||
| export declare function modInv(a: bigint, n: bigint): bigint; |
| export declare function decode(base64: string, url?: boolean): Uint8Array; | ||
| export declare function encode(bytes: Uint8Array, url?: boolean): string; | ||
| export declare function encodedLength(n: number): number; | ||
| export declare function decodedLength(n: number): number; |
| export declare function encode(buf: Uint8Array): string; | ||
| export declare function decode(string: string): Uint8Array; | ||
| export declare function encodedLength(n: number): number; | ||
| export declare function decodedLength(n: number): number; |
| import * as base64 from './base64.js'; | ||
| import * as hex from './hex.js'; | ||
| import * as utf8 from './utf8.js'; | ||
| export { base64, hex, utf8 }; |
| export declare const encoder: TextEncoder; | ||
| export declare const decoder: TextDecoder; | ||
| export declare function encodedLength(str: string): number; |
| export * from './arrays/index.js'; | ||
| export * from './async/index.js'; | ||
| export * from './bigint/index.js'; | ||
| export * from './encodings/index.js'; | ||
| export * from './iter/index.js'; | ||
| export * from './misc/index.js'; | ||
| export * from './structures/index.js'; | ||
| export * from './types/index.js'; |
| export * from './enumerate.js'; |
| export declare function enumerate<T>(iterable: Iterable<T>): IterableIterator<[number, T]>; |
| import * as iter from './bundle.js'; | ||
| export { iter }; |
| import { Brand } from '../types/brand.js'; | ||
| export declare function assert(condition: boolean, message?: unknown): asserts condition; | ||
| export declare function assertNonNull<T>(value: T): asserts value is Exclude<T, null | undefined>; | ||
| export declare function asNonNull<T>(value: null extends T ? T : undefined extends T ? T : Brand<'type is not nullable', 'TypeError'>): Exclude<T, null | undefined>; | ||
| export declare function assertMatches(str: string, regex: RegExp): RegExpMatchArray; |
| export type Middleware<Context, Result = void> = (ctx: Context, next: (ctx: Context) => Promise<Result>) => Promise<Result>; | ||
| export type ComposedMiddleware<Context, Result = void> = (ctx: Context) => Promise<Result>; | ||
| export declare function composeMiddlewares<Context, Result = void>(middlewares: Middleware<Context, Result>[], final: ComposedMiddleware<Context, Result>): ComposedMiddleware<Context, Result>; |
| import { AnyFunction, Truthy } from '../types/misc.js'; | ||
| export declare const isNotUndefined: <T>(val: T) => val is Exclude<T, undefined>; | ||
| export declare const isNotNull: <T>(val: T) => val is Exclude<T, null>; | ||
| export declare const isBoolean: (val: any) => val is boolean; | ||
| export declare const isTruthy: <T>(val: T) => val is Truthy<T>; | ||
| export declare const isFalsy: <T>(val: T) => val is Exclude<T, Truthy<T>>; | ||
| export declare const isFunction: (val: any) => val is AnyFunction; | ||
| export declare const isNumber: (val: any) => val is number; | ||
| export declare const isString: (val: unknown) => val is string; | ||
| export declare const isSymbol: (val: any) => val is symbol; | ||
| export declare const isBigInt: (val: any) => val is bigint; | ||
| export declare const isObject: (val: any) => val is object; |
| export * from './assert.js'; | ||
| export * from './composer.js'; | ||
| export * from './guards.js'; | ||
| export * from './objects.js'; | ||
| export * from './strings.js'; | ||
| export declare function noop(): void; |
| import { MaybeArray } from '../types/misc.js'; | ||
| /** | ||
| * Strictly typed `Object.keys` | ||
| */ | ||
| export declare function objectKeys<T extends object>(obj: T): Array<`${keyof T & (string | number | boolean | null | undefined)}`>; | ||
| /** | ||
| * Strictly typed `Object.entries` | ||
| */ | ||
| export declare function objectEntries<T extends object>(obj: T): Array<[keyof T, T[keyof T]]>; | ||
| /** | ||
| * remove undefined fields from an object (! mutates the object !) | ||
| */ | ||
| export declare function clearUndefined<T extends object>(obj: T): T; | ||
| export type MergeInsertions<T> = T extends object ? { | ||
| [K in keyof T]: MergeInsertions<T[K]>; | ||
| } : T; | ||
| export type DeepMerge<F, S> = MergeInsertions<{ | ||
| [K in keyof F | keyof S]: K extends keyof S & keyof F ? DeepMerge<F[K], S[K]> : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never; | ||
| }>; | ||
| export interface DeepMergeOptions { | ||
| /** | ||
| * when `undefined` value is encountered, should we **replace** the value | ||
| * in the target object with `undefined` or **ignore** it? | ||
| * | ||
| * @default 'ignore' | ||
| */ | ||
| undefined?: 'replace' | 'ignore'; | ||
| /** | ||
| * when a property is encountered that is already present in the target object, | ||
| * should we **replace** the value in the target object with the value from | ||
| * the source object or **ignore** it? | ||
| * | ||
| * @default 'replace' | ||
| */ | ||
| properties?: 'replace' | 'ignore'; | ||
| /** | ||
| * when an array is encountered that is already present in the target object, | ||
| * should we **replace** the value in the target object with the value from | ||
| * the source object, **merge** the arrays together or **ignore** it? | ||
| * | ||
| * @default 'replace' | ||
| */ | ||
| arrays?: 'replace' | 'merge' | 'ignore'; | ||
| /** | ||
| * when an object is encountered that is already present in the target object, | ||
| * should we **replace** the value in the target object with the value from | ||
| * the source object, **merge** the objects together or **ignore** it? | ||
| * | ||
| * @default 'merge' | ||
| */ | ||
| objects?: 'replace' | 'merge' | 'ignore'; | ||
| } | ||
| export declare function deepMerge<T extends object = object>(into: T, from: MaybeArray<T>, options?: DeepMergeOptions): T; | ||
| export declare function deepMerge<T extends object = object, S extends object = T>(into: T, from: MaybeArray<S>, options?: DeepMergeOptions): DeepMerge<T, S>; |
| export declare function splitOnce(str: string, separator: string): [string, string]; | ||
| export declare function assertStartsWith(str: string, prefix: string): asserts str is `${typeof prefix}${string}`; | ||
| export declare function assertEndsWith(str: string, suffix: string): asserts str is `${string}${typeof suffix}`; |
| export declare function maybeWrapIterator<T>(iter: IterableIterator<T>): IterableIterator<T>; |
| /** | ||
| * A `Map`-compatible class that allows using a custom key mapper | ||
| * function for both reading and writing. | ||
| */ | ||
| export declare class CustomMap<ExternalKey, InternalKey, V> implements Map<ExternalKey, V> { | ||
| #private; | ||
| readonly clear: Map<ExternalKey, V>['clear']; | ||
| constructor(externalToInternal: (key: ExternalKey) => InternalKey, internalToExternal: (key: InternalKey) => ExternalKey); | ||
| getInternalMap(): Map<InternalKey, V>; | ||
| delete(key: ExternalKey): boolean; | ||
| forEach(callbackfn: (value: V, key: ExternalKey, map: Map<ExternalKey, V>) => void, thisArg?: any): void; | ||
| get(key: ExternalKey): V | undefined; | ||
| has(key: ExternalKey): boolean; | ||
| set(key: ExternalKey, value: V): this; | ||
| get size(): number; | ||
| entries(): ReturnType<Map<ExternalKey, V>['entries']>; | ||
| keys(): ReturnType<Map<ExternalKey, V>['keys']>; | ||
| values(): ReturnType<Map<ExternalKey, V>['values']>; | ||
| [Symbol.iterator](): ReturnType<Map<ExternalKey, V>['entries']>; | ||
| get [Symbol.toStringTag](): string; | ||
| } |
| /** | ||
| * A `Set`-compatible class that allows using a custom key mapper | ||
| * function for both reading and writing. | ||
| * | ||
| * > **Important**: `union` and similar methods are not supported, | ||
| * > as there's no way which kind of key the other set uses. | ||
| * > This might change in the future. | ||
| */ | ||
| export declare class CustomSet<ExternalKey, InternalKey> implements Set<ExternalKey> { | ||
| #private; | ||
| readonly clear: Set<ExternalKey>['clear']; | ||
| constructor(externalToInternal: (key: ExternalKey) => InternalKey, internalToExternal: (key: InternalKey) => ExternalKey); | ||
| get size(): number; | ||
| add(value: ExternalKey): this; | ||
| delete(value: ExternalKey): boolean; | ||
| forEach(callbackfn: (value: ExternalKey, value2: ExternalKey, set: Set<ExternalKey>) => void, thisArg?: any): void; | ||
| has(value: ExternalKey): boolean; | ||
| entries(): ReturnType<Set<ExternalKey>['entries']>; | ||
| keys(): ReturnType<Set<ExternalKey>['keys']>; | ||
| values(): ReturnType<Set<ExternalKey>['keys']>; | ||
| union<U>(): Set<ExternalKey | U>; | ||
| intersection<U>(): Set<ExternalKey & U>; | ||
| difference(): Set<ExternalKey>; | ||
| symmetricDifference<U>(): Set<ExternalKey | U>; | ||
| isSubsetOf(): boolean; | ||
| isSupersetOf(): boolean; | ||
| isDisjointFrom(): boolean; | ||
| [Symbol.iterator](): ReturnType<Set<ExternalKey>['keys']>; | ||
| get [Symbol.toStringTag](): string; | ||
| getInternalSet(): Set<InternalKey>; | ||
| } |
| export interface DequeOptions { | ||
| /** | ||
| * Maximum number of items in the queue. | ||
| * When the queue is full, adding new items will remove the items | ||
| * at the other end of the queue. | ||
| */ | ||
| capacity?: number; | ||
| } | ||
| /** | ||
| * Custom implementation of a double ended queue. | ||
| */ | ||
| export declare class Deque<T> { | ||
| #private; | ||
| protected _list: (T | undefined)[]; | ||
| protected _head: number; | ||
| protected _tail: number; | ||
| protected _capacityMask: number; | ||
| protected _capacity?: number; | ||
| constructor(array?: ArrayLike<T>, options?: DequeOptions); | ||
| /** | ||
| * Return the number of items on the list, or 0 if empty. | ||
| */ | ||
| get length(): number; | ||
| /** | ||
| * Returns the item at the specified index from the list. | ||
| * 0 is the first element, 1 is the second, and so on... | ||
| * Elements at negative values are that many from the end: -1 is one before the end | ||
| * (the last element), -2 is two before the end (one before last), etc. | ||
| * Returns undefined if the index is out of bounds. | ||
| * | ||
| * @param index | ||
| */ | ||
| at(index: number): T | undefined; | ||
| /** | ||
| * Returns the first item in the list without removing it. | ||
| */ | ||
| peekFront(): T | undefined; | ||
| /** | ||
| * Returns the last item in the list without removing it. | ||
| */ | ||
| peekBack(): T | undefined; | ||
| /** | ||
| * Add an item at the beginning of the list. | ||
| * @param item | ||
| */ | ||
| pushFront(item: T): number; | ||
| /** | ||
| * Add an item to the end of the list. | ||
| * @param item | ||
| */ | ||
| pushBack(item: T): number; | ||
| /** | ||
| * Remove and return the last item on the list. | ||
| * Returns undefined if the list is empty. | ||
| */ | ||
| popBack(): T | undefined; | ||
| /** | ||
| * Remove and return the first item on the list, | ||
| * Returns undefined if the list is empty. | ||
| */ | ||
| popFront(): T | undefined; | ||
| /** | ||
| * Remove and return the item at the specified index from the list. | ||
| * Returns undefined if the list is empty. | ||
| * @param index | ||
| */ | ||
| removeOne(index: number): T | undefined; | ||
| removeBy(predicate: (item: T) => boolean): void; | ||
| /** | ||
| * Soft clear - does not reset capacity. | ||
| */ | ||
| clear(): void; | ||
| indexOf(item: T): number; | ||
| findIndex(predicate: (item: T) => boolean): number; | ||
| find(predicate: (item: T) => boolean): T | undefined; | ||
| includes(item: T): boolean; | ||
| /** | ||
| * Returns true or false whether the list is empty. | ||
| */ | ||
| isEmpty(): boolean; | ||
| /** | ||
| * Returns an array of all queue items. | ||
| */ | ||
| toArray(): T[]; | ||
| [Symbol.iterator](): Iterator<T>; | ||
| } |
| export * from './custom-map.js'; | ||
| export * from './custom-set.js'; | ||
| export * from './deque.js'; | ||
| export * from './lru-map.js'; | ||
| export * from './lru-set.js'; |
| interface TwoWayLinkedList<K, T> { | ||
| k: K; | ||
| v: T; | ||
| p?: TwoWayLinkedList<K, T>; | ||
| n?: TwoWayLinkedList<K, T>; | ||
| } | ||
| /** | ||
| * Simple class implementing LRU-like behaviour for a Map | ||
| * | ||
| * Can be used to handle local cache of *something* | ||
| * | ||
| * Uses two-way linked list internally to keep track of insertion/access order | ||
| */ | ||
| export declare class LruMap<K, V> { | ||
| #private; | ||
| constructor(capacity: number, MapImpl?: new <K, V>() => Map<K, TwoWayLinkedList<K, V>>); | ||
| get(key: K): V | undefined; | ||
| has(key: K): boolean; | ||
| set(key: K, value: V): void; | ||
| delete(key: K): void; | ||
| clear(): void; | ||
| } | ||
| export {}; |
| /** | ||
| * Simple class implementing LRU-like behaviour for a Set. | ||
| * | ||
| * Note: this is not exactly LRU, but rather "least recently added" | ||
| * and doesn't mark items as recently added if they are already in the set. | ||
| * | ||
| * Uses one-way linked list internally to keep track of insertion order | ||
| */ | ||
| export declare class LruSet<T> { | ||
| #private; | ||
| constructor(capacity: number, SetImpl?: new () => Set<T>); | ||
| clear(): void; | ||
| add(val: T): void; | ||
| has(val: T): boolean; | ||
| } |
| declare const brand: unique symbol; | ||
| export type Brand<T, Name extends string> = T & { | ||
| [brand]: Name; | ||
| }; | ||
| export {}; |
| export type TypesEqual<T, V> = (() => T) extends () => V ? ((() => V) extends () => T ? true : false) : false; |
| export declare function unknownToError(err: unknown): Error; | ||
| export declare class NotImplementedError extends Error { | ||
| constructor(message?: string); | ||
| } | ||
| export declare function notImplemented(message?: string): never; | ||
| export { notImplemented as todo }; |
| export * from './brand.js'; | ||
| export * from './equal.js'; | ||
| export * from './error.js'; | ||
| export * from './misc.js'; | ||
| export * from './unions.js'; |
| export type AnyToNever<T> = any extends T ? never : T; | ||
| export type MaybePromise<T> = T | Promise<T>; | ||
| export type MaybeArray<T> = T | T[]; | ||
| export type Simplify<T> = { | ||
| [KeyType in keyof T]: T[KeyType]; | ||
| } & {}; | ||
| export type AnyFunction = (...args: any[]) => any; | ||
| export type Values<T> = T[keyof T]; | ||
| export type Truthy<T> = T extends false | '' | 0 | null | undefined ? never : T; | ||
| /** | ||
| * Removes all `readonly` flags on a type (non-recursively), making it effectively mutable | ||
| * | ||
| * Considered unsafe as removing `readonly` modifiers may break semantics in some cases | ||
| */ | ||
| export type UnsafeMutable<T> = { | ||
| -readonly [P in keyof T]: T[P]; | ||
| }; |
| export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; | ||
| export type LastOfUnion<T> = UnionToIntersection<T extends any ? () => T : never> extends () => infer R ? R : never; | ||
| export type UnionToTuple<Union, Acc extends any[] = [], Last = LastOfUnion<Union>> = [Union] extends [never] ? Acc : UnionToTuple<Exclude<Union, Last>, [Last, ...Acc]>; |
| "use strict"; | ||
| Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); | ||
| const assert = require("../misc/assert.cjs"); | ||
| const deferred = require("./deferred.cjs"); | ||
@@ -80,2 +79,5 @@ const emitter = require("./emitter.cjs"); | ||
| * get the resource value, refreshing it if needed | ||
| * | ||
| * note: this method still *might* return `null` if the resource wasn't ever cached yet, | ||
| * and the underlying call to `fetcher` failed | ||
| */ | ||
@@ -94,3 +96,3 @@ async get() { | ||
| await this.update(); | ||
| return assert.asNonNull(this.#ctx.current); | ||
| return this.#ctx.current; | ||
| } | ||
@@ -97,0 +99,0 @@ /** |
@@ -77,4 +77,7 @@ import { Emitter } from './emitter.js'; | ||
| * get the resource value, refreshing it if needed | ||
| * | ||
| * note: this method still *might* return `null` if the resource wasn't ever cached yet, | ||
| * and the underlying call to `fetcher` failed | ||
| */ | ||
| get(): Promise<T>; | ||
| get(): Promise<T | null>; | ||
| /** | ||
@@ -81,0 +84,0 @@ * get the cached resource value immediately (if any) |
@@ -1,2 +0,1 @@ | ||
| import { asNonNull } from "../misc/assert.js"; | ||
| import { Deferred } from "./deferred.js"; | ||
@@ -78,2 +77,5 @@ import { Emitter } from "./emitter.js"; | ||
| * get the resource value, refreshing it if needed | ||
| * | ||
| * note: this method still *might* return `null` if the resource wasn't ever cached yet, | ||
| * and the underlying call to `fetcher` failed | ||
| */ | ||
@@ -92,3 +94,3 @@ async get() { | ||
| await this.update(); | ||
| return asNonNull(this.#ctx.current); | ||
| return this.#ctx.current; | ||
| } | ||
@@ -95,0 +97,0 @@ /** |
+1
-1
| { | ||
| "name": "@fuman/utils", | ||
| "type": "module", | ||
| "version": "0.0.4", | ||
| "version": "0.0.10", | ||
| "description": "various utils", | ||
@@ -6,0 +6,0 @@ "license": "MIT", |
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
168270
21.31%200
38.89%4934
0.14%10
100%