@andrew_l/toolkit 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -115,7 +115,7 @@ declare function chunk<T>(list: readonly T[], size?: number): T[][];
115
115
  *
116
116
  * @group Array
117
117
  */
118
- declare function chunkSeries(list: number[], step?: number): number[][];
118
+ declare function chunkSeries(list: readonly number[], step?: number): number[][];
119
119
 
120
120
  /**
121
121
  * Computes the difference between arrays.
@@ -136,11 +136,7 @@ declare function chunkSeries(list: number[], step?: number): number[][];
136
136
  *
137
137
  * @group Array
138
138
  */
139
- declare function difference<T>(...arrays: readonly T[][]): T[];
140
-
141
- type MaybePropertyKey<T> = T extends object
142
- ? keyof T | PropertyKey
143
- : PropertyKey;
139
+ declare function difference<T>(...arrays: (readonly T[])[]): T[];
144
140
 
145
141
  type PropertyKeyLiteralToType<T> = T extends string
146
142
  ? string
@@ -156,10 +152,14 @@ type IsPropertyKey<T, V, L> = T extends object
156
152
  : L
157
153
  : PropertyKeyLiteralToType<L>;
158
154
 
159
- declare function groupBy<T, K extends MaybePropertyKey<T>>(array: readonly T[], keyBy: K, objectMode?: false): Map<IsPropertyKey<T, K, K>, T[]>;
155
+ type ToPropertyKey<T> = T extends PropertyKey ? T : string;
156
+
157
+ declare function groupBy<T, K extends keyof T>(array: readonly T[], keyBy: K, objectMode?: false): Map<IsPropertyKey<T, K, unknown>, T[]>;
158
+ declare function groupBy<T, K extends PropertyKey>(array: readonly T[], keyBy: K, objectMode?: false): Map<IsPropertyKey<T, K, unknown>, T[]>;
160
159
  declare function groupBy<T, K>(array: readonly T[], keyBy: (item: T) => K, objectMode?: false): Map<K, T[]>;
161
- declare function groupBy<T, K extends MaybePropertyKey<T>>(array: readonly T[], keyBy: K, objectMode: true): Record<K, T[]>;
162
- declare function groupBy<T, K extends PropertyKey>(array: readonly T[], keyBy: (item: T) => K, objectMode: true): Record<K, T[]>;
160
+ declare function groupBy<T, K extends keyof T>(array: readonly T[], keyBy: K, objectMode: true): Record<ToPropertyKey<T[K]>, T[]>;
161
+ declare function groupBy<T, K extends PropertyKey>(array: readonly T[], keyBy: K, objectMode?: true): Record<ToPropertyKey<IsPropertyKey<T, K, unknown>>, T[]>;
162
+ declare function groupBy<T, K>(array: readonly T[], keyBy: (item: T) => K, objectMode: true): Record<ToPropertyKey<K>, T[]>;
163
163
 
164
164
  /**
165
165
  * Returns the intersection of arrays.
@@ -178,31 +178,18 @@ declare function groupBy<T, K extends PropertyKey>(array: readonly T[], keyBy: (
178
178
  *
179
179
  * @group Array
180
180
  */
181
- declare function intersection<T>(...arrays: readonly T[][]): T[];
181
+ declare function intersection<T>(...arrays: (readonly T[])[]): T[];
182
182
 
183
- /**
184
- * Maps each element of an array based on a provided key.
185
- *
186
- * @example
187
- * const data = [
188
- * { id: 1, name: 'group 1' },
189
- * { id: 2, name: 'group 2' },
190
- * { id: 1, name: 'group 2' }
191
- * ];
192
- *
193
- * const result = keyBy(data, 'id');
194
- * console.log(Object.entries(result));
195
- * // [
196
- * // [1, [{ id: 1, name: 'group 1' }, { id: 1, name: 'group 2' }],
197
- * // [2, { id: 2, name: 'group 2' }],
198
- * // ]
199
- *
200
- * @group Array
201
- */
202
- declare function keyBy<T, K extends MaybePropertyKey<T>>(array: readonly T[], keyBy: K, objectMode?: false): Map<IsPropertyKey<T, K, K>, T>;
183
+ declare function intersectionBy<T>(keyBy: keyof T, ...arrays: (readonly T[])[]): T[];
184
+ declare function intersectionBy<T>(keyBy: PropertyKey, ...arrays: (readonly T[])[]): T[];
185
+ declare function intersectionBy<T>(keyBy: (item: T) => unknown, ...arrays: (readonly T[])[]): T[];
186
+
187
+ declare function keyBy<T, K extends keyof T>(array: readonly T[], keyBy: K, objectMode?: false): Map<IsPropertyKey<T, K, unknown>, T>;
188
+ declare function keyBy<T, K extends PropertyKey>(array: readonly T[], keyBy: K, objectMode?: false): Map<IsPropertyKey<T, K, unknown>, T[]>;
203
189
  declare function keyBy<T, K>(array: readonly T[], keyBy: (item: T) => K, objectMode?: false): Map<K, T>;
204
- declare function keyBy<T, K extends MaybePropertyKey<T>>(array: readonly T[], keyBy: K, objectMode: true): Record<K, T>;
205
- declare function keyBy<T, K extends PropertyKey>(array: readonly T[], keyBy: (item: T) => K, objectMode: true): Record<K, T>;
190
+ declare function keyBy<T, K extends keyof T>(array: readonly T[], keyBy: K, objectMode: true): Record<ToPropertyKey<T[K]>, T>;
191
+ declare function keyBy<T, K extends PropertyKey>(array: readonly T[], keyBy: K, objectMode?: true): Record<ToPropertyKey<IsPropertyKey<T, K, unknown>>, T>;
192
+ declare function keyBy<T, K>(array: readonly T[], keyBy: (item: T) => K, objectMode: true): Record<ToPropertyKey<K>, T>;
206
193
 
207
194
  /**
208
195
  * Sort array by multiple fields
@@ -350,7 +337,7 @@ declare const sum: (values: readonly number[]) => number;
350
337
  *
351
338
  * @group Array
352
339
  */
353
- declare function union<T>(...arrays: readonly T[][]): T[];
340
+ declare function union<T>(...arrays: (readonly T[])[]): T[];
354
341
 
355
342
  /**
356
343
  * Returns a new array with duplicates removed.
@@ -369,7 +356,7 @@ declare function union<T>(...arrays: readonly T[][]): T[];
369
356
  *
370
357
  * @group Array
371
358
  */
372
- declare function uniq<T extends any[]>(value: T): T;
359
+ declare function uniq<T>(value: readonly T[]): T[];
373
360
 
374
361
  /**
375
362
  * Extracts unique elements from an array based on a comparator function or property key.
@@ -415,7 +402,7 @@ declare function uniq<T extends any[]>(value: T): T;
415
402
  *
416
403
  * @group Array
417
404
  */
418
- declare function uniqBy<T>(array: T[], comparator: ((value: T) => any) | PropertyKey): T[];
405
+ declare function uniqBy<T>(array: readonly T[], comparator: ((value: T) => any) | PropertyKey): T[];
419
406
 
420
407
  type WrrItem<T> = {
421
408
  item: T;
@@ -2545,7 +2532,7 @@ declare class EJSON {
2545
2532
  * @param {string} value - The JSON string to parse.
2546
2533
  * @returns {any} - The decoded JavaScript object.
2547
2534
  */
2548
- parse(value: string): any;
2535
+ parse<T = any>(value: string): T;
2549
2536
  /** @internal */
2550
2537
  protected _replacer(value: any, key: string): any;
2551
2538
  /** @internal */
@@ -3373,6 +3360,21 @@ declare function isPromise<T = void>(value: unknown): value is Promise<T>;
3373
3360
  * @group Predicates
3374
3361
  */
3375
3362
  declare const isPrimitive: (value: unknown) => value is Primitive;
3363
+ /**
3364
+ * Checks if the current environment is Node.js.
3365
+ *
3366
+ * This function checks for the existence of the `process.versions.node` property,
3367
+ * which only exists in Node.js environments.
3368
+ *
3369
+ * @returns {boolean} `true` if the current environment is Node.js, otherwise `false`.
3370
+ *
3371
+ * @example
3372
+ * if (isNode()) {
3373
+ * console.log('This is running in Node.js');
3374
+ * const fs = import('node:fs');
3375
+ * }
3376
+ */
3377
+ declare function isNode(): boolean;
3376
3378
 
3377
3379
  type LogLevel = Exclude<keyof Logger, 'extend'>;
3378
3380
  /**
@@ -4452,7 +4454,9 @@ declare const unset: (object: any, path: lodash.PropertyPath) => boolean;
4452
4454
  *
4453
4455
  * @group Promise
4454
4456
  */
4455
- declare function asyncFilter<T>(array: T[], predicate: (value: T, index: number, array: Array<T>) => Promise<boolean> | boolean): Promise<T[]>;
4457
+ declare function asyncFilter<T>(array: T[], predicate: (value: T, index: number, array: Array<T>) => Promise<boolean> | boolean, { concurrency }?: {
4458
+ concurrency?: number | undefined;
4459
+ }): Promise<T[]>;
4456
4460
 
4457
4461
  /**
4458
4462
  * Asynchronously finds the first element in an array that satisfies the provided async predicate.
@@ -5125,6 +5129,82 @@ declare class ResourcePool<T = unknown> extends SimpleEventEmitter<ResourcePoolE
5125
5129
  */
5126
5130
  declare function timeout<T = any>(ms: number, promiseOrCallback: Promise<T> | ((abortSignal: AbortSignal) => Awaitable<T>), timeoutError?: any): Promise<T>;
5127
5131
 
5132
+ type ResolverFn<R extends Promise<any>, T = any, A extends any[] = any[]> = (this: T, ...args: A) => R;
5133
+ type WithResolve<R extends Promise<any>, T = any, A extends any[] = any[]> = (this: T, ...args: A) => R;
5134
+ /**
5135
+ * A function that generates cache key based on the arguments.
5136
+ *
5137
+ * @param args - The original function arguments
5138
+ * @param computeKey - A helper function to stringify arguments into a cache key
5139
+ * @returns A cache key string if a variant should be used, or undefined to skip this variant
5140
+ */
5141
+ type GetCacheKey = (args: any[], computeKey: (...args: any[]) => string) => string | null | undefined;
5142
+ /**
5143
+ * Wraps an async function to guarantee single execution for identical arguments.
5144
+ * Acts as a request deduplication mechanism - when multiple calls are made with the same
5145
+ * arguments before the first call completes, all calls wait for and receive the result
5146
+ * of the first execution.
5147
+ *
5148
+ * This is useful for preventing redundant async operations like duplicate API calls or
5149
+ * database queries that are triggered simultaneously.
5150
+ *
5151
+ * @template R - The Promise return type of the wrapped function
5152
+ * @template T - The `this` context type for the function
5153
+ * @template A - The argument types tuple for the function
5154
+ *
5155
+ * @param fn - The async function to wrap
5156
+ * @param getCacheKey - Optional array of functions to generate alternative cache keys.
5157
+ * Useful when different argument combinations should be treated as equivalent.
5158
+ *
5159
+ * @returns A wrapped version of the function with deduplication behavior
5160
+ *
5161
+ * @example Basic usage - deduplicating database queries
5162
+ * ```ts
5163
+ * const fetchUserById = withResolve((userId: number) =>
5164
+ * db.users.findById(userId)
5165
+ * );
5166
+ *
5167
+ * // Only produces 1 database query, both calls receive the same result
5168
+ * const [user1, user2] = await Promise.all([
5169
+ * fetchUserById(100),
5170
+ * fetchUserById(100)
5171
+ * ]);
5172
+ * ```
5173
+ *
5174
+ * @example With cache key variants
5175
+ * ```ts
5176
+ * const fetchUser = withResolve(
5177
+ * (id: number, options?: { fresh?: boolean }) => api.getUser(id, options),
5178
+ * [
5179
+ * // Treat calls with/without options as equivalent if fresh is false/undefined
5180
+ * (args, computeKey) => {
5181
+ * const [id, options] = args;
5182
+ * if (options?.fresh) {
5183
+ * return null;
5184
+ * }
5185
+ *
5186
+ * return computeKey(id, {});
5187
+ * }
5188
+ * ]
5189
+ * );
5190
+ *
5191
+ * // Both calls deduplicated to single request
5192
+ * await Promise.all([
5193
+ * fetchUser(1),
5194
+ * fetchUser(1, { fresh: false })
5195
+ * ]);
5196
+ * ```
5197
+ *
5198
+ * @remarks
5199
+ * - The cache is held only during the execution of the first call
5200
+ * - Once the promise resolves or rejects, the cache entry is cleared
5201
+ * - All waiting calls receive the same result (success or error)
5202
+ * - Works with both resolved and rejected promises
5203
+ *
5204
+ * @group Promise
5205
+ */
5206
+ declare function withResolve<R extends Promise<any>, T = any, A extends any[] = any[]>(fn: ResolverFn<R, T, A>, getCacheKey?: Arrayable<GetCacheKey>): WithResolve<R, T, A>;
5207
+
5128
5208
  /**
5129
5209
  * Converts a string to camel case.
5130
5210
  *
@@ -5662,4 +5742,4 @@ declare function wrapText(value: string, maxLength?: number): string;
5662
5742
  */
5663
5743
  declare function toError<T>(value: T, unknownMessage?: string): T extends Error ? T : Error;
5664
5744
 
5665
- export { type AnyFunction, AppError, type AppErrorOptions, type ArgumentsType, type Arrayable, AsyncIterableQueue, type Awaitable, type Base64ToBytesOptions, type BaseX, BrowserAssertionError, type BytesToBase64Options, CancellablePromise, type CatchErrorResult, Color, type ColorChannels, ColorParser, type Data, type DateObject, type DateObjectInput, type DebouncedFunction, type DeepPartial, type DeepReadonly, type Defer, instance as EJSON, EJSON as EJSONInstance, EJSONStream, type EJSONStreamOptions, type EJSONStreamOptionsWithPayload, type EJSONType, type EnvParser, type ExecResult, type ExecResultToSkip, type ExecResultToSuccess, type ExecSkip, type ExecSuccess, FindMean, FixedMap, FixedWeakMap, type Fn, type FormatMoney, type FormatNumber, type FunctionArgs, type GenericObject, type IfAny, type IsAny, type LiteralUnion, type Logger, LruCache, type Nothing, type OverwriteWith, type Prettify, type Primitive, type PromisifyFn, Queue, type RandomizerOptions, ResourcePool, type ResourcePoolEventMap, type ResourcePoolOptions, type RetryOnErrorConfig, type SecureCustomizerOptions, type SelectOptionItem, type SelectOptions, type SimpleDefaultEventMap, SimpleEventEmitter, type SimpleEventMap, SortedArray, type SortedArrayCompareFn, _default as TWEMOJI_REGEX, type ThemeConfig, type ThrottledFunction, TimeBucket, type TimeBucketOptions, type TimeObject, type TimeObjectInput, TimeSpan, type TimeSpanUnit, type TimeString, type TimeValue, type TimestampMsInput, type TypeOf, type TypeOfMap, type ValuesOfObject, type WithCache, type WithCacheBucketBatchOptions, type WithCacheBucketOptions, type WithCacheFixedOptions, type WithCacheLruOptions, type WithCacheOptions, type WithCachePointer, type WithCacheResult, type WithCacheStorage, type WithCustomizer, type WithCustomizerFactory, type WithCustomizerValue, type WrrItem, alpha, arrayable, assert, asyncFilter, asyncFind, asyncForEach, asyncMap, avg, avgCircular, base62, base62Fast, base64, base64ToBytes, base64url, basex, bigIntBytes, bigIntFromBytes, blendColors, buildCssColor, bytesToBase64, cache, cacheBucket, cacheFixed, cacheLRU, camelCase, capitalize, captureStackTrace, catchError, channelsToHSL, channelsToHex, channelsToRGB, checkBitmask, chunk, chunkSeries, clamp, cleanEmpty, cleanObject, colorToChannels, compareBytes, concatenateBytes, contrastRatio, convertToUnit, crc32, createCustomizer, createCustomizerFactory, createDateObject, createDeepCloneWith, createEJSON, createEJSONStream, createEnvParser, createRandomizer, createSecureCustomizer, createTimeObject, createTimeSpan, createWithCache, cssVariable, dateInDays, dateInSeconds, debounce, deepAssign, deepClone, deepCloneWith, deepDefaults, deepFreeze, def, defer, delay, difference, dropCache, env, escapeHtml, escapeNumeric, escapeRegExp, fastIdle, fastIdlePromise, fastRaf, findMean, flagsToMap, flatten, formatMoney, formatNumber, get, getFileExtension, getFileName, getInitials, getMostSpecificPaths, getRandomInt, getRandomTime, getWords, groupBy, has, hasOwn, hasProtocol, hex, hexToChannels, hmToSeconds, hslToChannels, humanFileSize, humanize, interpolateColor, intersection, isBigInt, isBoolean, isCached, isClient, isColorChannels, isCustomizerFactory, isDate, isDateObject, isDef, isEmpty, isEqual, isError, isFunction, isInfinity, isMap, isNullOrUndefined, isNumber, isObject, isOneEmoji, isPlainObject, isPrimitive, isPromise, isRegExp, isSet, isSkip, isString, isSuccess, isSymbol, isTimeObject, isTimeString, isTimeValue, isValidWeekDay, isWeakMap, isWeakSet, isWithCache, isoToFlagEmoji, kebabCase, keyBy, logger, loggerSetLevel, lowerCase, luminance, maskingEmail, maskingPhone, maskingWords, nextTickIteration, noop, objectId, omit, omitPrefixed, orderBy, parseAllNumbers, parseAlpha, parsePercentage, percentOf, pick, pickPrefixed, qs, rafPromise, randomString, removeVS16s, retryOnError, rgbToChannels, round2digits, secondsToHm, set, shuffle, snakeCase, sprintf, startCase, strAssign, sum, textDecoder, textEncoder, throttle, timeFromMinutes, timeStringify, timeToMinutes, timeout, timestamp, timestampMs, timestampToDate, tintedTextColor, toError, toMap, truncate, typeOf, uint16ToUint8, uint32ToUint8, uint8ToUint16, uint8ToUint32, unflatten, union, uniq, uniqBy, unset, weeksInYear, weightedRoundRobin, withCache, withCacheBucket, withCacheBucketBatch, withCacheFixed, withCacheLRU, withDeepClone, withPointerCache, wrapText };
5745
+ export { type AnyFunction, AppError, type AppErrorOptions, type ArgumentsType, type Arrayable, AsyncIterableQueue, type Awaitable, type Base64ToBytesOptions, type BaseX, BrowserAssertionError, type BytesToBase64Options, CancellablePromise, type CatchErrorResult, Color, type ColorChannels, ColorParser, type Data, type DateObject, type DateObjectInput, type DebouncedFunction, type DeepPartial, type DeepReadonly, type Defer, instance as EJSON, EJSON as EJSONInstance, EJSONStream, type EJSONStreamOptions, type EJSONStreamOptionsWithPayload, type EJSONType, type EnvParser, type ExecResult, type ExecResultToSkip, type ExecResultToSuccess, type ExecSkip, type ExecSuccess, FindMean, FixedMap, FixedWeakMap, type Fn, type FormatMoney, type FormatNumber, type FunctionArgs, type GenericObject, type IfAny, type IsAny, type LiteralUnion, type Logger, LruCache, type Nothing, type OverwriteWith, type Prettify, type Primitive, type PromisifyFn, Queue, type RandomizerOptions, ResourcePool, type ResourcePoolEventMap, type ResourcePoolOptions, type RetryOnErrorConfig, type SecureCustomizerOptions, type SelectOptionItem, type SelectOptions, type SimpleDefaultEventMap, SimpleEventEmitter, type SimpleEventMap, SortedArray, type SortedArrayCompareFn, _default as TWEMOJI_REGEX, type ThemeConfig, type ThrottledFunction, TimeBucket, type TimeBucketOptions, type TimeObject, type TimeObjectInput, TimeSpan, type TimeSpanUnit, type TimeString, type TimeValue, type TimestampMsInput, type TypeOf, type TypeOfMap, type ValuesOfObject, type WithCache, type WithCacheBucketBatchOptions, type WithCacheBucketOptions, type WithCacheFixedOptions, type WithCacheLruOptions, type WithCacheOptions, type WithCachePointer, type WithCacheResult, type WithCacheStorage, type WithCustomizer, type WithCustomizerFactory, type WithCustomizerValue, type WrrItem, alpha, arrayable, assert, asyncFilter, asyncFind, asyncForEach, asyncMap, avg, avgCircular, base62, base62Fast, base64, base64ToBytes, base64url, basex, bigIntBytes, bigIntFromBytes, blendColors, buildCssColor, bytesToBase64, cache, cacheBucket, cacheFixed, cacheLRU, camelCase, capitalize, captureStackTrace, catchError, channelsToHSL, channelsToHex, channelsToRGB, checkBitmask, chunk, chunkSeries, clamp, cleanEmpty, cleanObject, colorToChannels, compareBytes, concatenateBytes, contrastRatio, convertToUnit, crc32, createCustomizer, createCustomizerFactory, createDateObject, createDeepCloneWith, createEJSON, createEJSONStream, createEnvParser, createRandomizer, createSecureCustomizer, createTimeObject, createTimeSpan, createWithCache, cssVariable, dateInDays, dateInSeconds, debounce, deepAssign, deepClone, deepCloneWith, deepDefaults, deepFreeze, def, defer, delay, difference, dropCache, env, escapeHtml, escapeNumeric, escapeRegExp, fastIdle, fastIdlePromise, fastRaf, findMean, flagsToMap, flatten, formatMoney, formatNumber, get, getFileExtension, getFileName, getInitials, getMostSpecificPaths, getRandomInt, getRandomTime, getWords, groupBy, has, hasOwn, hasProtocol, hex, hexToChannels, hmToSeconds, hslToChannels, humanFileSize, humanize, interpolateColor, intersection, intersectionBy, isBigInt, isBoolean, isCached, isClient, isColorChannels, isCustomizerFactory, isDate, isDateObject, isDef, isEmpty, isEqual, isError, isFunction, isInfinity, isMap, isNode, isNullOrUndefined, isNumber, isObject, isOneEmoji, isPlainObject, isPrimitive, isPromise, isRegExp, isSet, isSkip, isString, isSuccess, isSymbol, isTimeObject, isTimeString, isTimeValue, isValidWeekDay, isWeakMap, isWeakSet, isWithCache, isoToFlagEmoji, kebabCase, keyBy, logger, loggerSetLevel, lowerCase, luminance, maskingEmail, maskingPhone, maskingWords, nextTickIteration, noop, objectId, omit, omitPrefixed, orderBy, parseAllNumbers, parseAlpha, parsePercentage, percentOf, pick, pickPrefixed, qs, rafPromise, randomString, removeVS16s, retryOnError, rgbToChannels, round2digits, secondsToHm, set, shuffle, snakeCase, sprintf, startCase, strAssign, sum, textDecoder, textEncoder, throttle, timeFromMinutes, timeStringify, timeToMinutes, timeout, timestamp, timestampMs, timestampToDate, tintedTextColor, toError, toMap, truncate, typeOf, uint16ToUint8, uint32ToUint8, uint8ToUint16, uint8ToUint32, unflatten, union, uniq, uniqBy, unset, weeksInYear, weightedRoundRobin, withCache, withCacheBucket, withCacheBucketBatch, withCacheFixed, withCacheLRU, withDeepClone, withPointerCache, withResolve, wrapText };