@andrew_l/toolkit 0.3.6 → 0.3.7

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.cts CHANGED
@@ -466,6 +466,33 @@ declare namespace assert {
466
466
  export { assert_array as array, assert_arrayNumbers as arrayNumbers, assert_arrayStrings as arrayStrings, assert_boolean as boolean, assert_date as date, assert_equal as equal, assert_fn as fn, assert_greaterThan as greaterThan, assert_lessThan as lessThan, assert_notEmpty as notEmpty, assert_notEmptyString as notEmptyString, assert_number as number, assert_object as object, assert_ok as ok, assert_string as string };
467
467
  }
468
468
 
469
+ /**
470
+ * Base62 encoder/decoder for binary data.
471
+ *
472
+ * @example Basic usage
473
+ * ```typescript
474
+ * const data = new Uint8Array([255, 128, 64]);
475
+ * const encoded = base62.encode(data);
476
+ * console.log(encoded);
477
+ *
478
+ * const decoded = base62.decode(encoded);
479
+ * console.log(decoded); // Uint8Array [255, 128, 64]
480
+ * ```
481
+ *
482
+ * @example Text encoding
483
+ * ```typescript
484
+ * const text = "Hello World!";
485
+ * const bytes = new TextEncoder().encode(text);
486
+ * const encoded = base62.encode(bytes);
487
+ * const decoded = base62.decode(encoded);
488
+ * const result = new TextDecoder().decode(decoded);
489
+ * console.log(result); // "Hello World!"
490
+ * ```
491
+ *
492
+ * @group Binary
493
+ */
494
+ declare const base62: BaseX;
495
+
469
496
  interface BaseX {
470
497
  /**
471
498
  * Base alphabet
@@ -512,33 +539,6 @@ interface BaseX {
512
539
  */
513
540
  declare function basex(alphabet: string): BaseX;
514
541
 
515
- /**
516
- * Base62 encoder/decoder for binary data.
517
- *
518
- * @example Basic usage
519
- * ```typescript
520
- * const data = new Uint8Array([255, 128, 64]);
521
- * const encoded = base62.encode(data);
522
- * console.log(encoded);
523
- *
524
- * const decoded = base62.decode(encoded);
525
- * console.log(decoded); // Uint8Array [255, 128, 64]
526
- * ```
527
- *
528
- * @example Text encoding
529
- * ```typescript
530
- * const text = "Hello World!";
531
- * const bytes = new TextEncoder().encode(text);
532
- * const encoded = base62.encode(bytes);
533
- * const decoded = base62.decode(encoded);
534
- * const result = new TextDecoder().decode(decoded);
535
- * console.log(result); // "Hello World!"
536
- * ```
537
- *
538
- * @group Binary
539
- */
540
- declare const base62: BaseX;
541
-
542
542
  /**
543
543
  * Base62-like encoder/decoder for binary data but **super fast**. Useful for human readable tokens generation
544
544
  *
@@ -670,6 +670,11 @@ type Base64ToBytesOptions = {
670
670
  * Whether to enforce strict Base64 decoding.
671
671
  */
672
672
  strict?: boolean;
673
+ /**
674
+ * Prefer to use native `Uint8Array.fromBase64` and `Uint8Array.fromBase64` when possible
675
+ * @default true
676
+ */
677
+ native?: boolean;
673
678
  };
674
679
  /**
675
680
  * Decodes a Base64 or Base64URL encoded string into a `Uint8Array`.
@@ -700,7 +705,7 @@ type Base64ToBytesOptions = {
700
705
  *
701
706
  * @group Binary
702
707
  */
703
- declare function base64ToBytes(data: string, { encoding, strict }?: Base64ToBytesOptions): Uint8Array;
708
+ declare function base64ToBytes(data: string, { encoding, strict, native }?: Base64ToBytesOptions): Uint8Array;
704
709
 
705
710
  /**
706
711
  * Converts a `bigint` value into a byte array (`Uint8Array`) in big-endian order.
@@ -947,7 +952,7 @@ interface Logger {
947
952
  error: (...args: unknown[]) => void;
948
953
  debug: (...args: unknown[]) => void;
949
954
  log: (...args: unknown[]) => void;
950
- extend: (...args: unknown[]) => void;
955
+ extend: (...args: unknown[]) => Logger;
951
956
  }
952
957
 
953
958
  declare namespace BitPack {
@@ -992,6 +997,31 @@ type Plan = {
992
997
  value?: unknown;
993
998
  child?: Plan;
994
999
  };
1000
+ /**
1001
+ * Define compact packed structure
1002
+ * @group Binary
1003
+ *
1004
+ * @example
1005
+ * ```typescript
1006
+ * const snowflake = bitPack({
1007
+ * totalBits: 64,
1008
+ * fields: [
1009
+ * { name: 'timestamp', bits: 42, take: 'low' },
1010
+ * { name: 'workerId', bits: 5, take: 'low' },
1011
+ * { name: 'processId', bits: 5, take: 'low' },
1012
+ * { name: 'increment', bits: 12, take: 'low' },
1013
+ * ],
1014
+ * optimize: true,
1015
+ * });
1016
+ *
1017
+ * const userId = snowflake.bigint({
1018
+ * timestamp: 1781295314562,
1019
+ * workerId: 1,
1020
+ * processId: 0,
1021
+ * increment: 0
1022
+ * }); // 7471294063048785920n
1023
+ * ```
1024
+ */
995
1025
  declare function bitPack<const TFields extends BitPack.Field[], TFieldNames extends string = BitPack.ExtractFieldNames<TFields>>(options: BitPack.Options<TFields>): BitPack.API<TFieldNames>;
996
1026
 
997
1027
  declare namespace BitUnpack {
@@ -1024,6 +1054,27 @@ declare namespace BitUnpack {
1024
1054
  [P in T]: number;
1025
1055
  };
1026
1056
  }
1057
+ /**
1058
+ * Define compact unpacked structure
1059
+ * @group Binary
1060
+ *
1061
+ * @example
1062
+ * ```typescript
1063
+ * const snowflake = bitUnpack({
1064
+ * totalBits: 64,
1065
+ * fields: [
1066
+ * { name: 'timestamp', bits: 42, take: 'low' },
1067
+ * { name: 'workerId', bits: 5, take: 'low' },
1068
+ * { name: 'processId', bits: 5, take: 'low' },
1069
+ * { name: 'increment', bits: 12, take: 'low' },
1070
+ * ],
1071
+ * });
1072
+ *
1073
+ * console.log(
1074
+ * snowflake.bigint(7471294063048785920n)
1075
+ * ); // { timestamp: 1781295314562, workerId: 1, processId: 0, increment: 0 }
1076
+ * ```
1077
+ */
1027
1078
  declare function bitUnpack<const TFields extends BitUnpack.Field[], TFieldNames extends string = BitUnpack.ExtractFieldNames<TFields>>(options: BitUnpack.Options<TFields>): BitUnpack.API<TFieldNames>;
1028
1079
 
1029
1080
  type BytesToBase64Options = {
@@ -1035,6 +1086,11 @@ type BytesToBase64Options = {
1035
1086
  * Whether or not to include padding (`=`) in the encoded result. Defaults to `true` for Base64, `false` for Base64URL.
1036
1087
  */
1037
1088
  padding?: boolean;
1089
+ /**
1090
+ * Prefer to use native `Uint8Array.toBase64` and `Uint8Array.toBase64` when possible
1091
+ * @default true
1092
+ */
1093
+ native?: boolean;
1038
1094
  };
1039
1095
  /**
1040
1096
  * Encodes a byte array (`Uint8Array`) into a Base64 or Base64URL encoded string.
@@ -1074,7 +1130,7 @@ type BytesToBase64Options = {
1074
1130
  *
1075
1131
  * @group Binary
1076
1132
  */
1077
- declare function bytesToBase64(data: Uint8Array, { encoding, padding }?: BytesToBase64Options): string;
1133
+ declare function bytesToBase64(data: Uint8Array, { encoding, padding, native }?: BytesToBase64Options): string;
1078
1134
 
1079
1135
  /**
1080
1136
  * Compares two `Uint8Array` instances to check if their contents are identical.
@@ -3487,7 +3543,12 @@ type LogLevel = Exclude<keyof Logger, 'extend'>;
3487
3543
  * Set global log level.
3488
3544
  * @group Utility Functions
3489
3545
  */
3490
- declare const loggerSetLevel: (level: LogLevel) => void;
3546
+ declare const setLoggerLevel: (level: LogLevel) => void;
3547
+ /**
3548
+ * Set global log level.
3549
+ * @group Utility Functions
3550
+ */
3551
+ declare const getLoggerLevel: () => LogLevel;
3491
3552
  /**
3492
3553
  * Create pretty simple `console.log` wrapper interface.
3493
3554
  *
@@ -5199,6 +5260,78 @@ declare class ResourcePool<T = unknown> extends SimpleEventEmitter<ResourcePoolE
5199
5260
  private resolveDestroyQueue;
5200
5261
  }
5201
5262
 
5263
+ declare const SCHEDULER_JOB_FLAGS: {
5264
+ readonly QUEUED: number;
5265
+ readonly ALLOW_RECURSE: number;
5266
+ readonly DISPOSED: number;
5267
+ };
5268
+ /**
5269
+ * Creates a microtask scheduler that batches jobs and flushes them in
5270
+ * priority order on the next tick.
5271
+ *
5272
+ * Jobs are functions queued via {@link Scheduler.queueJob}. Each job may carry
5273
+ * an optional numeric `id` used to order the queue — lower `id` runs first,
5274
+ * and jobs without an `id` run last. Re-queueing the same job within an
5275
+ * active flush cycle is a no-op unless `SCHEDULER_JOB_FLAGS.ALLOW_RECURSE`
5276
+ * is set on the job. Use {@link Scheduler.queueJobWait} when you need to
5277
+ * await a job's result through a {@link CancellablePromise}, and the
5278
+ * `onJob` / `onJobStart` / `onJobComplete` hooks to observe lifecycle.
5279
+ *
5280
+ * @example
5281
+ * ```typescript
5282
+ * const scheduler = createScheduler();
5283
+ *
5284
+ * const log = (msg: string) => () => console.log(msg);
5285
+ *
5286
+ * const first = log('first');
5287
+ * first.id = 1;
5288
+ * const second = log('second');
5289
+ * second.id = 2;
5290
+ *
5291
+ * scheduler.queueJob(second);
5292
+ * scheduler.queueJob(first);
5293
+ *
5294
+ * scheduler.nextTick().then(() => console.log('flushed'));
5295
+ * // → first
5296
+ * // → second
5297
+ * // → flushed
5298
+ * ```
5299
+ *
5300
+ * @group Promise
5301
+ */
5302
+ declare function createScheduler(): Scheduler;
5303
+ declare namespace Scheduler {
5304
+ type Job<T = any> = (() => T) & JobOptions;
5305
+ type JobOptions = {
5306
+ id?: number;
5307
+ /**
5308
+ * flags can technically be undefined, but it can still be used in bitwise
5309
+ * operations just like 0.
5310
+ */
5311
+ flags?: number;
5312
+ jobName?: string;
5313
+ };
5314
+ }
5315
+ declare class Scheduler {
5316
+ protected queue: Scheduler.Job[];
5317
+ protected flushIndex: number;
5318
+ protected resolvedPromise: Promise<any>;
5319
+ protected currentFlushPromise: Promise<void> | null;
5320
+ protected onJobCbs: ((job: Scheduler.JobOptions) => void)[];
5321
+ protected onJobStartCbs: ((job: Scheduler.JobOptions) => void)[];
5322
+ protected onJobCompleteCbs: ((job: Scheduler.JobOptions) => void)[];
5323
+ constructor();
5324
+ onJob(fn: (job: Scheduler.JobOptions) => void): void;
5325
+ onJobStart(fn: (job: Scheduler.JobOptions) => void): void;
5326
+ onJobComplete(fn: (job: Scheduler.JobOptions) => void): void;
5327
+ nextTick(fn?: () => void): Promise<void>;
5328
+ queueJob<T>(job: Scheduler.Job<T>, opts?: Scheduler.JobOptions): void;
5329
+ queueJobWait<T>(job: Scheduler.Job<T>, opts?: Scheduler.JobOptions): CancellablePromise<Awaited<T>>;
5330
+ protected findInsertionIndex(id: number): number;
5331
+ protected flushJobs(): Promise<void>;
5332
+ protected queueFlush(): void;
5333
+ }
5334
+
5202
5335
  /**
5203
5336
  * Throws an error if the provided promise or callback is not resolved within the specified timeout period.
5204
5337
  *
@@ -5848,4 +5981,4 @@ declare function wrapText(value: string, maxLength?: number): string;
5848
5981
  */
5849
5982
  declare function toError<T>(value: T, unknownMessage?: string): T extends Error ? T : Error;
5850
5983
 
5851
- export { type AnyFunction, AppError, type AppErrorOptions, type ArgumentsType, type Arrayable, AssertionError, AsyncIterableQueue, type Awaitable, type Base64ToBytesOptions, type BaseX, BitPack, BitUnpack, 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, 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 WithCode, 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, bitPack, bitUnpack, 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, createFunction, 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, rleDecode, rleEncode, 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 };
5984
+ export { type AnyFunction, AppError, type AppErrorOptions, type ArgumentsType, type Arrayable, AssertionError, AsyncIterableQueue, type Awaitable, type Base64ToBytesOptions, type BaseX, BitPack, BitUnpack, 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, Fn, type FormatMoney, type FormatNumber, type FunctionArgs, type GenericObject, type IfAny, type IsAny, type LiteralUnion, type LogLevel, type Logger, LruCache, type Nothing, type OverwriteWith, type Prettify, type Primitive, type PromisifyFn, Queue, type RandomizerOptions, ResourcePool, type ResourcePoolEventMap, type ResourcePoolOptions, type RetryOnErrorConfig, SCHEDULER_JOB_FLAGS, Scheduler, 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 WithCode, 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, bitPack, bitUnpack, 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, createFunction, createRandomizer, createScheduler, 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, getLoggerLevel, 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, lowerCase, luminance, maskingEmail, maskingPhone, maskingWords, nextTickIteration, noop, objectId, omit, omitPrefixed, orderBy, parseAllNumbers, parseAlpha, parsePercentage, percentOf, pick, pickPrefixed, qs, rafPromise, randomString, removeVS16s, retryOnError, rgbToChannels, rleDecode, rleEncode, round2digits, secondsToHm, set, setLoggerLevel, 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 };
package/dist/index.d.mts CHANGED
@@ -466,6 +466,33 @@ declare namespace assert {
466
466
  export { assert_array as array, assert_arrayNumbers as arrayNumbers, assert_arrayStrings as arrayStrings, assert_boolean as boolean, assert_date as date, assert_equal as equal, assert_fn as fn, assert_greaterThan as greaterThan, assert_lessThan as lessThan, assert_notEmpty as notEmpty, assert_notEmptyString as notEmptyString, assert_number as number, assert_object as object, assert_ok as ok, assert_string as string };
467
467
  }
468
468
 
469
+ /**
470
+ * Base62 encoder/decoder for binary data.
471
+ *
472
+ * @example Basic usage
473
+ * ```typescript
474
+ * const data = new Uint8Array([255, 128, 64]);
475
+ * const encoded = base62.encode(data);
476
+ * console.log(encoded);
477
+ *
478
+ * const decoded = base62.decode(encoded);
479
+ * console.log(decoded); // Uint8Array [255, 128, 64]
480
+ * ```
481
+ *
482
+ * @example Text encoding
483
+ * ```typescript
484
+ * const text = "Hello World!";
485
+ * const bytes = new TextEncoder().encode(text);
486
+ * const encoded = base62.encode(bytes);
487
+ * const decoded = base62.decode(encoded);
488
+ * const result = new TextDecoder().decode(decoded);
489
+ * console.log(result); // "Hello World!"
490
+ * ```
491
+ *
492
+ * @group Binary
493
+ */
494
+ declare const base62: BaseX;
495
+
469
496
  interface BaseX {
470
497
  /**
471
498
  * Base alphabet
@@ -512,33 +539,6 @@ interface BaseX {
512
539
  */
513
540
  declare function basex(alphabet: string): BaseX;
514
541
 
515
- /**
516
- * Base62 encoder/decoder for binary data.
517
- *
518
- * @example Basic usage
519
- * ```typescript
520
- * const data = new Uint8Array([255, 128, 64]);
521
- * const encoded = base62.encode(data);
522
- * console.log(encoded);
523
- *
524
- * const decoded = base62.decode(encoded);
525
- * console.log(decoded); // Uint8Array [255, 128, 64]
526
- * ```
527
- *
528
- * @example Text encoding
529
- * ```typescript
530
- * const text = "Hello World!";
531
- * const bytes = new TextEncoder().encode(text);
532
- * const encoded = base62.encode(bytes);
533
- * const decoded = base62.decode(encoded);
534
- * const result = new TextDecoder().decode(decoded);
535
- * console.log(result); // "Hello World!"
536
- * ```
537
- *
538
- * @group Binary
539
- */
540
- declare const base62: BaseX;
541
-
542
542
  /**
543
543
  * Base62-like encoder/decoder for binary data but **super fast**. Useful for human readable tokens generation
544
544
  *
@@ -670,6 +670,11 @@ type Base64ToBytesOptions = {
670
670
  * Whether to enforce strict Base64 decoding.
671
671
  */
672
672
  strict?: boolean;
673
+ /**
674
+ * Prefer to use native `Uint8Array.fromBase64` and `Uint8Array.fromBase64` when possible
675
+ * @default true
676
+ */
677
+ native?: boolean;
673
678
  };
674
679
  /**
675
680
  * Decodes a Base64 or Base64URL encoded string into a `Uint8Array`.
@@ -700,7 +705,7 @@ type Base64ToBytesOptions = {
700
705
  *
701
706
  * @group Binary
702
707
  */
703
- declare function base64ToBytes(data: string, { encoding, strict }?: Base64ToBytesOptions): Uint8Array;
708
+ declare function base64ToBytes(data: string, { encoding, strict, native }?: Base64ToBytesOptions): Uint8Array;
704
709
 
705
710
  /**
706
711
  * Converts a `bigint` value into a byte array (`Uint8Array`) in big-endian order.
@@ -947,7 +952,7 @@ interface Logger {
947
952
  error: (...args: unknown[]) => void;
948
953
  debug: (...args: unknown[]) => void;
949
954
  log: (...args: unknown[]) => void;
950
- extend: (...args: unknown[]) => void;
955
+ extend: (...args: unknown[]) => Logger;
951
956
  }
952
957
 
953
958
  declare namespace BitPack {
@@ -992,6 +997,31 @@ type Plan = {
992
997
  value?: unknown;
993
998
  child?: Plan;
994
999
  };
1000
+ /**
1001
+ * Define compact packed structure
1002
+ * @group Binary
1003
+ *
1004
+ * @example
1005
+ * ```typescript
1006
+ * const snowflake = bitPack({
1007
+ * totalBits: 64,
1008
+ * fields: [
1009
+ * { name: 'timestamp', bits: 42, take: 'low' },
1010
+ * { name: 'workerId', bits: 5, take: 'low' },
1011
+ * { name: 'processId', bits: 5, take: 'low' },
1012
+ * { name: 'increment', bits: 12, take: 'low' },
1013
+ * ],
1014
+ * optimize: true,
1015
+ * });
1016
+ *
1017
+ * const userId = snowflake.bigint({
1018
+ * timestamp: 1781295314562,
1019
+ * workerId: 1,
1020
+ * processId: 0,
1021
+ * increment: 0
1022
+ * }); // 7471294063048785920n
1023
+ * ```
1024
+ */
995
1025
  declare function bitPack<const TFields extends BitPack.Field[], TFieldNames extends string = BitPack.ExtractFieldNames<TFields>>(options: BitPack.Options<TFields>): BitPack.API<TFieldNames>;
996
1026
 
997
1027
  declare namespace BitUnpack {
@@ -1024,6 +1054,27 @@ declare namespace BitUnpack {
1024
1054
  [P in T]: number;
1025
1055
  };
1026
1056
  }
1057
+ /**
1058
+ * Define compact unpacked structure
1059
+ * @group Binary
1060
+ *
1061
+ * @example
1062
+ * ```typescript
1063
+ * const snowflake = bitUnpack({
1064
+ * totalBits: 64,
1065
+ * fields: [
1066
+ * { name: 'timestamp', bits: 42, take: 'low' },
1067
+ * { name: 'workerId', bits: 5, take: 'low' },
1068
+ * { name: 'processId', bits: 5, take: 'low' },
1069
+ * { name: 'increment', bits: 12, take: 'low' },
1070
+ * ],
1071
+ * });
1072
+ *
1073
+ * console.log(
1074
+ * snowflake.bigint(7471294063048785920n)
1075
+ * ); // { timestamp: 1781295314562, workerId: 1, processId: 0, increment: 0 }
1076
+ * ```
1077
+ */
1027
1078
  declare function bitUnpack<const TFields extends BitUnpack.Field[], TFieldNames extends string = BitUnpack.ExtractFieldNames<TFields>>(options: BitUnpack.Options<TFields>): BitUnpack.API<TFieldNames>;
1028
1079
 
1029
1080
  type BytesToBase64Options = {
@@ -1035,6 +1086,11 @@ type BytesToBase64Options = {
1035
1086
  * Whether or not to include padding (`=`) in the encoded result. Defaults to `true` for Base64, `false` for Base64URL.
1036
1087
  */
1037
1088
  padding?: boolean;
1089
+ /**
1090
+ * Prefer to use native `Uint8Array.toBase64` and `Uint8Array.toBase64` when possible
1091
+ * @default true
1092
+ */
1093
+ native?: boolean;
1038
1094
  };
1039
1095
  /**
1040
1096
  * Encodes a byte array (`Uint8Array`) into a Base64 or Base64URL encoded string.
@@ -1074,7 +1130,7 @@ type BytesToBase64Options = {
1074
1130
  *
1075
1131
  * @group Binary
1076
1132
  */
1077
- declare function bytesToBase64(data: Uint8Array, { encoding, padding }?: BytesToBase64Options): string;
1133
+ declare function bytesToBase64(data: Uint8Array, { encoding, padding, native }?: BytesToBase64Options): string;
1078
1134
 
1079
1135
  /**
1080
1136
  * Compares two `Uint8Array` instances to check if their contents are identical.
@@ -3487,7 +3543,12 @@ type LogLevel = Exclude<keyof Logger, 'extend'>;
3487
3543
  * Set global log level.
3488
3544
  * @group Utility Functions
3489
3545
  */
3490
- declare const loggerSetLevel: (level: LogLevel) => void;
3546
+ declare const setLoggerLevel: (level: LogLevel) => void;
3547
+ /**
3548
+ * Set global log level.
3549
+ * @group Utility Functions
3550
+ */
3551
+ declare const getLoggerLevel: () => LogLevel;
3491
3552
  /**
3492
3553
  * Create pretty simple `console.log` wrapper interface.
3493
3554
  *
@@ -5199,6 +5260,78 @@ declare class ResourcePool<T = unknown> extends SimpleEventEmitter<ResourcePoolE
5199
5260
  private resolveDestroyQueue;
5200
5261
  }
5201
5262
 
5263
+ declare const SCHEDULER_JOB_FLAGS: {
5264
+ readonly QUEUED: number;
5265
+ readonly ALLOW_RECURSE: number;
5266
+ readonly DISPOSED: number;
5267
+ };
5268
+ /**
5269
+ * Creates a microtask scheduler that batches jobs and flushes them in
5270
+ * priority order on the next tick.
5271
+ *
5272
+ * Jobs are functions queued via {@link Scheduler.queueJob}. Each job may carry
5273
+ * an optional numeric `id` used to order the queue — lower `id` runs first,
5274
+ * and jobs without an `id` run last. Re-queueing the same job within an
5275
+ * active flush cycle is a no-op unless `SCHEDULER_JOB_FLAGS.ALLOW_RECURSE`
5276
+ * is set on the job. Use {@link Scheduler.queueJobWait} when you need to
5277
+ * await a job's result through a {@link CancellablePromise}, and the
5278
+ * `onJob` / `onJobStart` / `onJobComplete` hooks to observe lifecycle.
5279
+ *
5280
+ * @example
5281
+ * ```typescript
5282
+ * const scheduler = createScheduler();
5283
+ *
5284
+ * const log = (msg: string) => () => console.log(msg);
5285
+ *
5286
+ * const first = log('first');
5287
+ * first.id = 1;
5288
+ * const second = log('second');
5289
+ * second.id = 2;
5290
+ *
5291
+ * scheduler.queueJob(second);
5292
+ * scheduler.queueJob(first);
5293
+ *
5294
+ * scheduler.nextTick().then(() => console.log('flushed'));
5295
+ * // → first
5296
+ * // → second
5297
+ * // → flushed
5298
+ * ```
5299
+ *
5300
+ * @group Promise
5301
+ */
5302
+ declare function createScheduler(): Scheduler;
5303
+ declare namespace Scheduler {
5304
+ type Job<T = any> = (() => T) & JobOptions;
5305
+ type JobOptions = {
5306
+ id?: number;
5307
+ /**
5308
+ * flags can technically be undefined, but it can still be used in bitwise
5309
+ * operations just like 0.
5310
+ */
5311
+ flags?: number;
5312
+ jobName?: string;
5313
+ };
5314
+ }
5315
+ declare class Scheduler {
5316
+ protected queue: Scheduler.Job[];
5317
+ protected flushIndex: number;
5318
+ protected resolvedPromise: Promise<any>;
5319
+ protected currentFlushPromise: Promise<void> | null;
5320
+ protected onJobCbs: ((job: Scheduler.JobOptions) => void)[];
5321
+ protected onJobStartCbs: ((job: Scheduler.JobOptions) => void)[];
5322
+ protected onJobCompleteCbs: ((job: Scheduler.JobOptions) => void)[];
5323
+ constructor();
5324
+ onJob(fn: (job: Scheduler.JobOptions) => void): void;
5325
+ onJobStart(fn: (job: Scheduler.JobOptions) => void): void;
5326
+ onJobComplete(fn: (job: Scheduler.JobOptions) => void): void;
5327
+ nextTick(fn?: () => void): Promise<void>;
5328
+ queueJob<T>(job: Scheduler.Job<T>, opts?: Scheduler.JobOptions): void;
5329
+ queueJobWait<T>(job: Scheduler.Job<T>, opts?: Scheduler.JobOptions): CancellablePromise<Awaited<T>>;
5330
+ protected findInsertionIndex(id: number): number;
5331
+ protected flushJobs(): Promise<void>;
5332
+ protected queueFlush(): void;
5333
+ }
5334
+
5202
5335
  /**
5203
5336
  * Throws an error if the provided promise or callback is not resolved within the specified timeout period.
5204
5337
  *
@@ -5848,4 +5981,4 @@ declare function wrapText(value: string, maxLength?: number): string;
5848
5981
  */
5849
5982
  declare function toError<T>(value: T, unknownMessage?: string): T extends Error ? T : Error;
5850
5983
 
5851
- export { type AnyFunction, AppError, type AppErrorOptions, type ArgumentsType, type Arrayable, AssertionError, AsyncIterableQueue, type Awaitable, type Base64ToBytesOptions, type BaseX, BitPack, BitUnpack, 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, 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 WithCode, 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, bitPack, bitUnpack, 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, createFunction, 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, rleDecode, rleEncode, 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 };
5984
+ export { type AnyFunction, AppError, type AppErrorOptions, type ArgumentsType, type Arrayable, AssertionError, AsyncIterableQueue, type Awaitable, type Base64ToBytesOptions, type BaseX, BitPack, BitUnpack, 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, Fn, type FormatMoney, type FormatNumber, type FunctionArgs, type GenericObject, type IfAny, type IsAny, type LiteralUnion, type LogLevel, type Logger, LruCache, type Nothing, type OverwriteWith, type Prettify, type Primitive, type PromisifyFn, Queue, type RandomizerOptions, ResourcePool, type ResourcePoolEventMap, type ResourcePoolOptions, type RetryOnErrorConfig, SCHEDULER_JOB_FLAGS, Scheduler, 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 WithCode, 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, bitPack, bitUnpack, 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, createFunction, createRandomizer, createScheduler, 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, getLoggerLevel, 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, lowerCase, luminance, maskingEmail, maskingPhone, maskingWords, nextTickIteration, noop, objectId, omit, omitPrefixed, orderBy, parseAllNumbers, parseAlpha, parsePercentage, percentOf, pick, pickPrefixed, qs, rafPromise, randomString, removeVS16s, retryOnError, rgbToChannels, rleDecode, rleEncode, round2digits, secondsToHm, set, setLoggerLevel, 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 };