@sohanemon/utils 6.3.2 → 6.3.4

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.
@@ -0,0 +1,497 @@
1
+ import { ClassValue } from "clsx";
2
+ import * as React from "react";
3
+
4
+ //#region src/functions/cookie.d.ts
5
+ declare const setClientSideCookie: (name: string, value: string, days?: number, path?: string) => void;
6
+ declare const deleteClientSideCookie: (name: string, path?: string) => void;
7
+ declare const hasClientSideCookie: (name: string) => boolean;
8
+ declare const getClientSideCookie: (name: string) => {
9
+ value: string | undefined;
10
+ };
11
+ //#endregion
12
+ //#region src/functions/deepmerge.d.ts
13
+ type TAllKeys<T> = T extends any ? keyof T : never;
14
+ type TIndexValue<T, K$1 extends PropertyKey, D = never> = T extends any ? K$1 extends keyof T ? T[K$1] : D : never;
15
+ type TPartialKeys<T, K$1 extends keyof T> = Omit<T, K$1> & Partial<Pick<T, K$1>> extends infer O ? { [P in keyof O]: O[P] } : never;
16
+ type TFunction = (...a: any[]) => any;
17
+ type TPrimitives = string | number | boolean | bigint | symbol | Date | TFunction;
18
+ type TMerged<T> = [T] extends [Array<any>] ? { [K in keyof T]: TMerged<T[K]> } : [T] extends [TPrimitives] ? T : [T] extends [object] ? TPartialKeys<{ [K in TAllKeys<T>]: TMerged<TIndexValue<T, K>> }, never> : T;
19
+ /**
20
+ * Deeply merges multiple objects, with later sources taking precedence.
21
+ * Handles nested objects, arrays, and special object types with circular reference detection.
22
+ *
23
+ * Features:
24
+ * - Deep merging of nested objects
25
+ * - Configurable array merging strategies
26
+ * - Circular reference detection and handling
27
+ * - Support for symbols and special objects (Date, RegExp, etc.)
28
+ * - Type-safe with improved generics
29
+ * - Optional cloning to avoid mutation
30
+ * - Custom merge functions for specific keys
31
+ *
32
+ * @template T - The target object type
33
+ * @param target - The target object to merge into
34
+ * @param sources - Source objects to merge from (can have additional properties)
35
+ * @param options - Configuration options
36
+ * @param options.arrayMerge - How to merge arrays: 'replace' (default), 'concat', or 'merge'
37
+ * @param options.clone - Whether to clone the target (default: true)
38
+ * @param options.customMerge - Custom merge function for specific keys
39
+ * @param options.maxDepth - Maximum recursion depth (default: 100)
40
+ * @returns The merged object with proper typing
41
+ *
42
+ * @example
43
+ * // Basic merge
44
+ * deepmerge({ a: 1 }, { b: 2 }) // { a: 1, b: 2 }
45
+ *
46
+ * @example
47
+ * // Nested merge
48
+ * deepmerge({ a: { x: 1 } }, { a: { y: 2 } }) // { a: { x: 1, y: 2 } }
49
+ *
50
+ * @example
51
+ * // Array concat
52
+ * deepmerge({ arr: [1] }, { arr: [2] }, { arrayMerge: 'concat' }) // { arr: [1, 2] }
53
+ *
54
+ * @example
55
+ * // Sources with extra properties
56
+ * deepmerge({ a: 1 }, { b: 2, c: 3 }) // { a: 1, b: 2, c: 3 }
57
+ */
58
+ declare function deepmerge<T extends Record<string, any>, S extends Record<string, any>[]>(target: T, ...sources: S): TMerged<T | S[number]>;
59
+ declare function deepmerge<T extends Record<string, any>, S extends Record<string, any>[]>(target: T, sources: S, options?: {
60
+ arrayMerge?: 'replace' | 'concat' | 'merge' | ((target: any[], source: any[]) => any[]);
61
+ clone?: boolean;
62
+ customMerge?: (key: string | symbol, targetValue: any, sourceValue: any) => any;
63
+ maxDepth?: number;
64
+ }): TMerged<T | S[number]>;
65
+ //#endregion
66
+ //#region src/functions/hydrate.d.ts
67
+ type Hydrate<T> = T extends null ? undefined : T extends (infer U)[] ? Hydrate<U>[] : T extends object ? { [K in keyof T]: Hydrate<T[K]> } : T;
68
+ /**
69
+ * Converts all `null` values to `undefined` in the data structure recursively.
70
+ *
71
+ * @param data - Any input data (object, array, primitive)
72
+ * @returns Same type as input, but with all nulls replaced by undefined
73
+ *
74
+ * @example
75
+ * hydrate({ a: null, b: 'test' }) // { a: undefined, b: 'test' }
76
+ * hydrate([null, 1, { c: null }]) // [undefined, 1, { c: undefined }]
77
+ */
78
+ declare function hydrate<T>(data: T): Hydrate<T>;
79
+ //#endregion
80
+ //#region src/functions/object.d.ts
81
+ /**
82
+ * Type representing a path split into segments
83
+ * @template S - The original path string type
84
+ */
85
+ type SplitPath<S extends string> = S extends `${infer First}.${infer Rest}` ? [First, ...SplitPath<Rest>] : [S];
86
+ /**
87
+ * Recursive type to resolve nested object types based on path
88
+ * @template T - Current object type
89
+ * @template K - Array of path segments
90
+ */
91
+ type GetValue<T, K$1 extends Array<string | number>> = K$1 extends [infer First, ...infer Rest] ? First extends keyof T ? GetValue<T[First], Rest extends Array<string | number> ? Rest : []> : First extends `${number}` ? T extends any[] ? GetValue<T[number], Rest extends Array<string | number> ? Rest : []> : undefined : undefined : T;
92
+ /**
93
+ * Get a nested value from an object using array path segments
94
+ * @template T - Object type
95
+ * @template K - Path segments array type
96
+ * @template D - Default value type
97
+ * @param obj - Source object
98
+ * @param path - Array of path segments
99
+ * @param defaultValue - Fallback value if path not found
100
+ * @returns Value at path or default value
101
+ *
102
+ * @example
103
+ * getObjectValue({a: [{b: 1}]}, ['a', 0, 'b']) // 1
104
+ */
105
+ declare function getObjectValue<T, K$1 extends Array<string | number>, D>(obj: T, path: K$1, defaultValue: D): Exclude<GetValue<T, K$1>, undefined> | D;
106
+ /**
107
+ * Get a nested value from an object using array path segments
108
+ * @template T - Object type
109
+ * @template K - Path segments array type
110
+ * @param obj - Source object
111
+ * @param path - Array of path segments
112
+ * @returns Value at path or undefined
113
+ *
114
+ * @example
115
+ * getObjectValue({a: [{b: 1}]}, ['a', 0, 'b']) // 1
116
+ */
117
+ declare function getObjectValue<T, K$1 extends Array<string | number>>(obj: T, path: K$1): GetValue<T, K$1> | undefined;
118
+ /**
119
+ * Get a nested value from an object using dot notation path
120
+ * @template T - Object type
121
+ * @template S - Path string literal type
122
+ * @template D - Default value type
123
+ * @param obj - Source object
124
+ * @param path - Dot-separated path string
125
+ * @param defaultValue - Fallback value if path not found
126
+ * @returns Value at path or default value
127
+ *
128
+ * @example
129
+ * getObjectValue({a: [{b: 1}]}, 'a.0.b', 2) // 1
130
+ */
131
+ declare function getObjectValue<T, S extends string, D>(obj: T, path: S, defaultValue: D): Exclude<GetValue<T, SplitPath<S>>, undefined> | D;
132
+ /**
133
+ * Get a nested value from an object using dot notation path
134
+ * @template T - Object type
135
+ * @template S - Path string literal type
136
+ * @param obj - Source object
137
+ * @param path - Dot-separated path string
138
+ * @returns Value at path or undefined
139
+ *
140
+ * @example
141
+ * getObjectValue({a: [{b: 1}]}, 'a.0.b') // 1
142
+ */
143
+ declare function getObjectValue<T, S extends string>(obj: T, path: S): GetValue<T, SplitPath<S>> | undefined;
144
+ /**
145
+ * Extend an object or function with additional properties while
146
+ * preserving the original type information.
147
+ *
148
+ * Works with both plain objects and callable functions since
149
+ * functions in JavaScript are objects too.
150
+ *
151
+ * @template T The base object or function type
152
+ * @template P The additional properties type
153
+ *
154
+ * @param base - The object or function to extend
155
+ * @param props - An object containing properties to attach
156
+ *
157
+ * @returns The same object/function, augmented with the given properties
158
+ *
159
+ * @example
160
+ * // Extend an object
161
+ * const obj = extendProps({ a: 1 }, { b: "hello" });
162
+ * // obj has { a: number; b: string }
163
+ *
164
+ * // Extend a function
165
+ * const fn = (x: number) => x * 2;
166
+ * const enhanced = extendProps(fn, { name: "doubler" });
167
+ * // enhanced is callable and also has { name: string }
168
+ */
169
+ declare function extendProps<T extends object, P$1 extends object>(base: T, props: P$1): T & P$1;
170
+ //#endregion
171
+ //#region src/functions/poll.d.ts
172
+ /**
173
+ * Repeatedly polls an async `cond` function UNTIL it returns a TRUTHY value,
174
+ * or until the operation times out or is aborted.
175
+ *
176
+ * Designed for waiting on async jobs, external state, or delayed availability.
177
+ *
178
+ * @template T The type of the successful result.
179
+ *
180
+ * @param cond
181
+ * A function returning a Promise that resolves to:
182
+ * - a truthy value `T` → stop polling and return it
183
+ * - falsy/null/undefined → continue polling
184
+ *
185
+ * @param options
186
+ * Configuration options:
187
+ * - `interval` (number) — Time between polls in ms (default: 5000 ms)
188
+ * - `timeout` (number) — Max total duration before failing (default: 5 min)
189
+ * - `jitter` (boolean) — Add small random offset (±10%) to intervals to avoid sync bursts (default: true)
190
+ * - `signal` (AbortSignal) — Optional abort signal to cancel polling
191
+ *
192
+ * @returns
193
+ * Resolves with the truthy value `T` when successful.
194
+ * Throws `AbortError` if aborted
195
+ *
196
+ * @example
197
+ * ```ts
198
+ * const job = await poll(async () => {
199
+ * const status = await getJobStatus();
200
+ * return status === 'done' ? status : null;
201
+ * }, { interval: 3000, timeout: 60000 });
202
+ * ```
203
+ */
204
+ declare function poll<T>(cond: () => Promise<T | null | false | undefined>, {
205
+ interval,
206
+ timeout,
207
+ jitter,
208
+ signal
209
+ }?: Partial<{
210
+ interval: number;
211
+ timeout: number;
212
+ signal: AbortSignal;
213
+ jitter: boolean;
214
+ }>): Promise<T>;
215
+ //#endregion
216
+ //#region src/functions/schedule.d.ts
217
+ type Task = () => Promise<void> | void;
218
+ interface ScheduleOpts {
219
+ retry?: number;
220
+ delay?: number;
221
+ timeout?: number;
222
+ }
223
+ /**
224
+ * Runs a function asynchronously in the background.
225
+ * Returns immediately, retries on failure if configured.
226
+ * Logs total time taken.
227
+ */
228
+ declare function schedule(task: Task, options?: ScheduleOpts): void;
229
+ //#endregion
230
+ //#region src/functions/shield.d.ts
231
+ /**
232
+ * A helper to run sync or async operations safely without try/catch.
233
+ *
234
+ * Returns a tuple `[error, data]`:
235
+ * - `error`: the thrown error (if any), otherwise `null`
236
+ * - `data`: the resolved value (if successful), otherwise `null`
237
+ *
238
+ * @example
239
+ * ```ts
240
+ * const [err, value] = shield(() => riskySync());
241
+ * if (err) console.error(err);
242
+ *
243
+ * const [asyncErr, result] = await shield(fetchData());
244
+ * if (asyncErr) throw asyncErr;
245
+ * ```
246
+ */
247
+ declare function shield<T, E = Error>(operation: Promise<T>): Promise<[E | null, T | null]>;
248
+ declare function shield<T, E = Error>(operation: () => T): [E | null, T | null];
249
+ //#endregion
250
+ //#region src/functions/utils.d.ts
251
+ /**
252
+ * Utility to merge class names with Tailwind CSS and additional custom merging logic.
253
+ *
254
+ * @param {...ClassValue[]} inputs - Class names to merge.
255
+ * @returns {string} - A string of merged class names.
256
+ */
257
+ declare function cn(...inputs: ClassValue[]): string;
258
+ /**
259
+ * @deprecated Use isLinkActive instead.
260
+ *
261
+ * Determines if a navigation link is active based on the current path.
262
+ *
263
+ * @param href - The target URL.
264
+ * @param path - The current browser path.
265
+ * @returns - True if the navigation is active, false otherwise.
266
+ */
267
+ declare function isNavActive(href: string, path: string): boolean;
268
+ /**
269
+ * Checks if a link is active, considering optional localization prefixes.
270
+ *
271
+ * @param {Object} params - Parameters object.
272
+ * @param {string} params.path - The target path of the link.
273
+ * @param {string} params.currentPath - The current browser path.
274
+ * @param {string[]} [params.locales=['en', 'es', 'de', 'zh', 'bn', 'fr', 'it', 'nl']] - Supported locale prefixes.
275
+ * @returns {boolean} - True if the link is active, false otherwise.
276
+ */
277
+ declare function isLinkActive({
278
+ path,
279
+ currentPath,
280
+ locales,
281
+ exact
282
+ }: {
283
+ path: string;
284
+ currentPath: string;
285
+ locales?: string[];
286
+ exact?: boolean;
287
+ }): boolean;
288
+ /**
289
+ * Cleans a file path by removing the `/public/` prefix if present.
290
+ *
291
+ * @param src - The source path to clean.
292
+ * @returns - The cleaned path.
293
+ */
294
+ declare function cleanSrc(src: string): string;
295
+ /**
296
+ * Smoothly scrolls to the top or bottom of a specified container.
297
+ *
298
+ * @param containerSelector - The CSS selector or React ref for the container.
299
+ * @param to - Specifies whether to scroll to the top or bottom.
300
+ */
301
+ declare const scrollTo: (containerSelector: string | React.RefObject<HTMLDivElement>, to: "top" | "bottom") => void;
302
+ /**
303
+ * Copies a given string to the clipboard.
304
+ *
305
+ * @param value - The value to copy to the clipboard.
306
+ * @param [onSuccess=() => {}] - Optional callback executed after successful copy.
307
+ */
308
+ declare const copyToClipboard: (value: string, onSuccess?: () => void) => void;
309
+ /**
310
+ * Converts camelCase, PascalCase, kebab-case, snake_case into normal case.
311
+ *
312
+ * @param inputString - The string need to be converted into normal case
313
+ * @returns - Normal Case
314
+ */
315
+ declare function convertToNormalCase(inputString: string): string;
316
+ /**
317
+ * Converts a string to a URL-friendly slug by trimming, converting to lowercase,
318
+ * replacing diacritics, removing invalid characters, and replacing spaces with hyphens.
319
+ * @param {string} [str] - The input string to convert.
320
+ * @returns {string} The generated slug.
321
+ * @example
322
+ * convertToSlug("Hello World!"); // "hello-world"
323
+ * convertToSlug("Déjà Vu"); // "deja-vu"
324
+ */
325
+ declare const convertToSlug: (str: string) => string;
326
+ /**
327
+ * Checks if the code is running in a server-side environment.
328
+ *
329
+ * @returns - True if the code is executed in SSR (Server-Side Rendering) context, false otherwise
330
+ */
331
+ declare const isSSR: boolean;
332
+ /**
333
+ * Converts an SVG string to a Base64-encoded string.
334
+ *
335
+ * @param str - The SVG string to encode
336
+ * @returns - Base64-encoded string representation of the SVG
337
+ */
338
+ declare const svgToBase64: (str: string) => string;
339
+ /**
340
+ * Pauses execution for the specified time.
341
+ *
342
+ * `signal` allows cancelling the sleep via AbortSignal.
343
+ *
344
+ * @param time - Time in milliseconds to sleep (default is 1000ms)
345
+ * @param signal - Optional AbortSignal to cancel the sleep early
346
+ * @returns - A Promise that resolves after the specified time or when aborted
347
+ */
348
+ declare const sleep: (time?: number, signal?: AbortSignal) => Promise<void>;
349
+ type DebouncedFunction<F extends (...args: any[]) => any> = {
350
+ (...args: Parameters<F>): ReturnType<F> | undefined;
351
+ readonly isPending: boolean;
352
+ };
353
+ /**
354
+ * Creates a debounced function that delays invoking the provided function until
355
+ * after the specified `wait` time has elapsed since the last invocation.
356
+ *
357
+ * If the `immediate` option is set to `true`, the function will be invoked immediately
358
+ * on the leading edge of the wait interval. Subsequent calls during the wait interval
359
+ * will reset the timer but not invoke the function until the interval elapses again.
360
+ *
361
+ * The returned function includes the `isPending` property to check if the debounce
362
+ * timer is currently active.
363
+ *
364
+ * @typeParam F - The type of the function to debounce.
365
+ *
366
+ * @param function_ - The function to debounce.
367
+ * @param wait - The number of milliseconds to delay (default is 100ms).
368
+ * @param options - An optional object with the following properties:
369
+ * - `immediate` (boolean): If `true`, invokes the function on the leading edge
370
+ * of the wait interval instead of the trailing edge.
371
+ *
372
+ * @returns A debounced version of the provided function, enhanced with the `isPending` property.
373
+ *
374
+ * @throws {TypeError} If the first parameter is not a function.
375
+ * @throws {RangeError} If the `wait` parameter is negative.
376
+ *
377
+ * @example
378
+ * const log = debounce((message: string) => console.log(message), 200);
379
+ * log('Hello'); // Logs "Hello" after 200ms if no other call is made.
380
+ * console.log(log.isPending); // true if the timer is active.
381
+ */
382
+ declare function debounce<F extends (...args: any[]) => any>(function_: F, wait?: number, options?: {
383
+ immediate: boolean;
384
+ }): DebouncedFunction<F>;
385
+ type ThrottledFunction<F extends (...args: any[]) => any> = {
386
+ (...args: Parameters<F>): ReturnType<F> | undefined;
387
+ readonly isPending: boolean;
388
+ };
389
+ /**
390
+ * Creates a throttled function that invokes the provided function at most once
391
+ * every `wait` milliseconds.
392
+ *
393
+ * If the `leading` option is set to `true`, the function will be invoked immediately
394
+ * on the leading edge of the throttle interval. If the `trailing` option is set to `true`,
395
+ * the function will also be invoked at the end of the throttle interval if additional
396
+ * calls were made during the interval.
397
+ *
398
+ * The returned function includes the `isPending` property to check if the throttle
399
+ * timer is currently active.
400
+ *
401
+ * @typeParam F - The type of the function to throttle.
402
+ *
403
+ * @param function_ - The function to throttle.
404
+ * @param wait - The number of milliseconds to wait between invocations (default is 100ms).
405
+ * @param options - An optional object with the following properties:
406
+ * - `leading` (boolean): If `true`, invokes the function on the leading edge of the interval.
407
+ * - `trailing` (boolean): If `true`, invokes the function on the trailing edge of the interval.
408
+ *
409
+ * @returns A throttled version of the provided function, enhanced with the `isPending` property.
410
+ *
411
+ * @throws {TypeError} If the first parameter is not a function.
412
+ * @throws {RangeError} If the `wait` parameter is negative.
413
+ *
414
+ * @example
415
+ * const log = throttle((message: string) => console.log(message), 200);
416
+ * log('Hello'); // Logs "Hello" immediately if leading is true.
417
+ * console.log(log.isPending); // true if the timer is active.
418
+ */
419
+ declare function throttle<F extends (...args: any[]) => any>(function_: F, wait?: number, options?: {
420
+ leading?: boolean;
421
+ trailing?: boolean;
422
+ }): ThrottledFunction<F>;
423
+ /**
424
+ * Formats a string by replacing each '%s' placeholder with the corresponding argument.
425
+ * This function mimics the basic behavior of C's printf for %s substitution.
426
+ *
427
+ * It supports both calls like `printf(format, ...args)` and `printf(format, argsArray)`.
428
+ *
429
+ * @param format - The format string containing '%s' placeholders.
430
+ * @param args - The values to substitute into the placeholders, either as separate arguments or as a single array.
431
+ * @returns The formatted string with all '%s' replaced by the provided arguments.
432
+ *
433
+ * @example
434
+ * ```ts
435
+ * const message = printf("%s love %s", "I", "Bangladesh");
436
+ * // message === "I love Bangladesh"
437
+ *
438
+ * const arr = ["I", "Bangladesh"];
439
+ * const message2 = printf("%s love %s", arr);
440
+ * // message2 === "I love Bangladesh"
441
+ *
442
+ * // If there are too few arguments:
443
+ * const incomplete = printf("Bangladesh is %s %s", "beautiful");
444
+ * // incomplete === "Bangladesh is beautiful"
445
+ * ```
446
+ */
447
+ declare function printf(format: string, ...args: unknown[]): string;
448
+ /**
449
+ * Merges multiple refs into a single ref callback.
450
+ *
451
+ * @param refs - An array of refs to merge.
452
+ *
453
+ * @returns - A function that updates the merged ref with the provided value.
454
+ */
455
+ type MergeRefs = <T>(...refs: Array<React.Ref<T> | undefined>) => React.RefCallback<T>;
456
+ declare const mergeRefs: MergeRefs;
457
+ /**
458
+ * Navigates to the specified client-side hash without ssr.
459
+ * use `scroll-margin-top` with css to add margins
460
+ *
461
+ * @param id - The ID of the element without # to navigate to.
462
+ *
463
+ * @example goToClientSideHash('my-element');
464
+ */
465
+ declare function goToClientSideHash(id: string, opts?: ScrollIntoViewOptions): void;
466
+ /**
467
+ * Escapes a string for use in a regular expression.
468
+ *
469
+ * @param str - The string to escape
470
+ * @returns - The escaped string
471
+ *
472
+ * @example
473
+ * const escapedString = escapeRegExp('Hello, world!');
474
+ * // escapedString === 'Hello\\, world!'
475
+ */
476
+ declare function escapeRegExp(str: string): string;
477
+ /**
478
+ * Normalizes a string by:
479
+ * - Applying Unicode normalization (NFC)
480
+ * - Optionally removing diacritic marks (accents)
481
+ * - Optionally trimming leading/trailing non-alphanumeric characters
482
+ * - Optionally converting to lowercase
483
+ *
484
+ * @param str - The string to normalize
485
+ * @param options - Normalization options
486
+ * @param options.lowercase - Whether to convert the result to lowercase (default: true)
487
+ * @param options.removeAccents - Whether to remove diacritic marks like accents (default: true)
488
+ * @param options.removeNonAlphanumeric - Whether to trim non-alphanumeric characters from the edges (default: true)
489
+ * @returns The normalized string
490
+ */
491
+ declare function normalizeText(str?: string | null, options?: {
492
+ lowercase?: boolean;
493
+ removeAccents?: boolean;
494
+ removeNonAlphanumeric?: boolean;
495
+ }): string;
496
+ //#endregion
497
+ export { getClientSideCookie as A, schedule as C, hydrate as D, getObjectValue as E, setClientSideCookie as M, deepmerge as O, Task as S, extendProps as T, sleep as _, convertToSlug as a, shield as b, escapeRegExp as c, isNavActive as d, isSSR as f, scrollTo as g, printf as h, convertToNormalCase as i, hasClientSideCookie as j, deleteClientSideCookie as k, goToClientSideHash as l, normalizeText as m, cleanSrc as n, copyToClipboard as o, mergeRefs as p, cn as r, debounce as s, MergeRefs as t, isLinkActive as u, svgToBase64 as v, poll as w, ScheduleOpts as x, throttle as y };
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- let e=require(`clsx`),t=require(`tailwind-merge`);const n=(e,t,n,r=`/`)=>{let i=``;if(n){let e=new Date;e.setTime(e.getTime()+n*24*60*60*1e3),i=`; expires=${e.toUTCString()}`}document.cookie=`${e}=${t||``}${i}; path=${r}`},r=(e,t=`/`)=>{document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=${t}`},i=e=>document.cookie.split(`; `).some(t=>t.startsWith(`${e}=`)),a=e=>({value:document.cookie.split(`; `).find(t=>t.startsWith(`${e}=`))?.split(`=`)[1]}),o=e=>!e,s=e=>e==null,c=e=>{if(e==null)return!0;switch(typeof e){case`string`:case`number`:case`bigint`:case`boolean`:case`symbol`:return!0;default:return!1}};function l(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function u(e,...t){let n,r={},i=t[t.length-1];i&&typeof i==`object`&&!Array.isArray(i)&&(i.arrayMerge!==void 0||i.clone!==void 0||i.customMerge!==void 0||i.maxDepth!==void 0)?(r={...r,...i},n=t.slice(0,-1)):n=t;let{arrayMerge:a=`replace`,clone:o=!0,customMerge:s,maxDepth:c=100}=r,u=new WeakMap;return d(e,n,0);function d(e,t,n){if(n>=c)return console.warn(`[deepmerge] Maximum depth ${c} exceeded. Returning target as-is.`),e;if(!l(e)&&!Array.isArray(e)){for(let e of t)if(e!==void 0)return e;return e}let r=o?Array.isArray(e)?[...e]:{...e}:e;for(let e of t)if(e!=null&&!u.has(e))if(u.set(e,r),Array.isArray(r)&&Array.isArray(e))r=f(r,e,a);else if(l(r)&&l(e)){let t=new Set([...Object.keys(r),...Object.keys(e),...Object.getOwnPropertySymbols(r),...Object.getOwnPropertySymbols(e)]);for(let i of t){let t=r[i],o=e[i];s&&s(i,t,o)!==void 0?r[i]=s(i,t,o):l(t)&&l(o)?r[i]=d(t,[o],n+1):Array.isArray(t)&&Array.isArray(o)?r[i]=f(t,o,a):o!==void 0&&(r[i]=o)}}else r=e;return r}function f(e,t,n){if(typeof n==`function`)return n(e,t);switch(n){case`concat`:return[...e,...t];case`merge`:let n=Math.max(e.length,t.length),r=[];for(let i=0;i<n;i++)i<e.length&&i<t.length?l(e[i])&&l(t[i])?r[i]=d(e[i],[t[i]],0):r[i]=t[i]:i<e.length?r[i]=e[i]:r[i]=t[i];return r;case`replace`:default:return[...t]}}}function d(e){return f(e)}function f(e){if(e!==null){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(f);if(l(e)){let t={};for(let n in e)t[n]=f(e[n]);return t}return e}}function p(e,t,n){if(typeof t!=`string`&&!Array.isArray(t))return n;let r=(()=>Array.isArray(t)?t:t===``?[]:String(t).split(`.`).filter(e=>e!==``))();if(!Array.isArray(r))return n;let i=e;for(let e of r){if(i==null)return n;let t=typeof e==`string`&&Array.isArray(i)&&/^\d+$/.test(e)?Number.parseInt(e,10):e;i=i[t]}return i===void 0?n:i}function m(e,t){return Object.assign(e,t)}function h(...n){return(0,t.twMerge)((0,e.clsx)(n))}function g(e,t){return console.warn(`isNavActive is deprecated. Use isLinkActive instead.`),RegExp(`^/?${e}(/|$)`).test(t)}function _({path:e,currentPath:t,locales:n=[`en`,`es`,`de`,`zh`,`bn`,`fr`,`it`,`nl`],exact:r=!0}){let i=RegExp(`^/?(${n.join(`|`)})/`),a=e=>e.replace(i,``).replace(/^\/+|\/+$/g,``),o=a(e),s=a(t);return r?o===s:s.startsWith(o)}function v(e){let t=e;return e.includes(`/public/`)&&(t=e.replace(`/public/`,`/`)),t.trim()}const y=(e,t)=>{let n;if(typeof e==`string`)n=document.querySelector(e);else if(e.current)n=e.current;else return;n&&n.scrollTo({top:t===`top`?0:n.scrollHeight-n.clientHeight,behavior:`smooth`})},b=(e,t=()=>{})=>{typeof window>`u`||!navigator.clipboard?.writeText||e&&navigator.clipboard.writeText(e).then(t)};function x(e){return(e.split(`.`).pop()||e).replace(/([a-z])([A-Z])/g,`$1 $2`).split(/[-_|�\s]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}const S=`àáãäâèéëêìíïîòóöôùúüûñç·/_,:;`,C=`aaaaaeeeeiiiioooouuuunc------`,w=e=>{if(typeof e!=`string`)throw TypeError(`Input must be a string`);let t=e.trim().toLowerCase(),n={};for(let e=0;e<29;e++)n[S.charAt(e)]=`aaaaaeeeeiiiioooouuuunc------`.charAt(e);return t=t.replace(RegExp(`[${S}]`,`g`),e=>n[e]||e),t.replace(/[^a-z0-9 -]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).replace(/^-+/,``).replace(/-+$/,``)||``},T=typeof window>`u`,E=e=>T?Buffer.from(e).toString(`base64`):window.btoa(e),D=(e=1e3,t)=>new Promise(n=>{if(t?.aborted)return n();let r=setTimeout(()=>{a(),n()},e);function i(){clearTimeout(r),a(),n()}function a(){t?.removeEventListener(`abort`,i)}t&&t.addEventListener(`abort`,i,{once:!0})});function O(e,t=100,n){if(typeof e!=`function`)throw TypeError(`Expected the first parameter to be a function, got \`${typeof e}\`.`);if(t<0)throw RangeError("`wait` must not be negative.");let r=n?.immediate??!1,i,a,o,s;function c(){return s=e.apply(o,a),a=void 0,o=void 0,s}let l=function(...e){return a=e,o=this,i===void 0&&r&&(s=c.call(this)),i!==void 0&&clearTimeout(i),i=setTimeout(c.bind(this),t),s};return Object.defineProperty(l,`isPending`,{get(){return i!==void 0}}),l}function k(e,t=100,n){if(typeof e!=`function`)throw TypeError(`Expected the first parameter to be a function, got \`${typeof e}\`.`);if(t<0)throw RangeError("`wait` must not be negative.");let r=n?.leading??!0,i=n?.trailing??!0,a,o,s,c,l;function u(){c=Date.now(),l=e.apply(s,o),o=void 0,s=void 0}function d(){a=void 0,i&&o&&u()}let f=function(...e){let n=c?Date.now()-c:1/0;return o=e,s=this,n>=t?r?u():a=setTimeout(d,t):!a&&i&&(a=setTimeout(d,t-n)),l};return Object.defineProperty(f,`isPending`,{get(){return a!==void 0}}),f}function A(e,...t){let n=t.length===1&&Array.isArray(t[0])?t[0]:t,r=0;return e.replace(/%s/g,()=>{let e=n[r++];return e===void 0?``:String(e)})}const j=(...e)=>t=>{for(let n of e)n&&(typeof n==`function`?n(t):n.current=t)};function M(e,t){let n=document.getElementById(e);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`,...t}),window.history.pushState(null,``,`#${e}`))}function N(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function P(e,t={}){if(!e)return``;let{lowercase:n=!0,removeAccents:r=!0,removeNonAlphanumeric:i=!0}=t,a=e.normalize(`NFC`);return r&&(a=a.normalize(`NFD`).replace(/\p{M}/gu,``)),i&&(a=a.replace(/^[^\p{L}\p{N}]*|[^\p{L}\p{N}]*$/gu,``)),n&&(a=a.toLocaleLowerCase()),a}async function F(e,{interval:t=5e3,timeout:n=300*1e3,jitter:r=!0,signal:i}={}){let a=Date.now(),o=i?.aborted??!1,s=()=>{o=!0};i?.addEventListener(`abort`,s,{once:!0});try{for(let s=0;;s++){if(o)throw Error(`Polling aborted`);let s=await e();if(s)return s;if(Date.now()-a>=n)throw Error(`Polling timed out`,{cause:`Polling timed out after ${n}ms`});await D(r?t+(Math.random()-.5)*t*.2:t,i)}}catch(e){throw e}finally{i?.removeEventListener(`abort`,s)}}function I(e,t={}){let{retry:n=0,delay:r=0}=t,i=Date.now(),a=async t=>{try{await e();let t=Date.now()-i;console.log(`⚡[schedule.ts] Completed in ${t}ms`)}catch(e){if(console.log(`⚡[schedule.ts] err:`,e),t>0)console.log(`⚡[schedule.ts] Retrying in ${r}ms...`),setTimeout(()=>a(t-1),r);else{let e=Date.now()-i;console.log(`⚡[schedule.ts] Failed after ${e}ms`)}}};setTimeout(()=>a(n),0)}function L(e){if(e instanceof Promise)return e.then(e=>[null,e]).catch(e=>[e,null]);try{return[null,e()]}catch(t){return console.log(`\x1b[31m🛡 [shield]\x1b[0m ${e.name} failed →`,t),[t,null]}}exports.cleanSrc=v,exports.cn=h,exports.convertToNormalCase=x,exports.convertToSlug=w,exports.copyToClipboard=b,exports.debounce=O,exports.deepmerge=u,exports.deleteClientSideCookie=r,exports.escapeRegExp=N,exports.extendProps=m,exports.getClientSideCookie=a,exports.getObjectValue=p,exports.goToClientSideHash=M,exports.hasClientSideCookie=i,exports.hydrate=d,exports.isFalsy=o,exports.isLinkActive=_,exports.isNavActive=g,exports.isNullish=s,exports.isPlainObject=l,exports.isPrimitive=c,exports.isSSR=T,exports.mergeRefs=j,exports.normalizeText=P,exports.poll=F,exports.printf=A,exports.schedule=I,exports.scrollTo=y,exports.setClientSideCookie=n,exports.shield=L,exports.sleep=D,exports.svgToBase64=E,exports.throttle=k;
1
+ const e=require(`./functions-BSYagwi9.cjs`);exports.cleanSrc=e.i,exports.cn=e.a,exports.convertToNormalCase=e.o,exports.convertToSlug=e.s,exports.copyToClipboard=e.c,exports.debounce=e.l,exports.deepmerge=e.T,exports.deleteClientSideCookie=e.A,exports.escapeRegExp=e.u,exports.extendProps=e.S,exports.getClientSideCookie=e.j,exports.getObjectValue=e.C,exports.goToClientSideHash=e.d,exports.hasClientSideCookie=e.M,exports.hydrate=e.w,exports.isFalsy=e.E,exports.isLinkActive=e.f,exports.isNavActive=e.p,exports.isNullish=e.D,exports.isPlainObject=e.O,exports.isPrimitive=e.k,exports.isSSR=e.m,exports.mergeRefs=e.h,exports.normalizeText=e.g,exports.poll=e.r,exports.printf=e._,exports.schedule=e.n,exports.scrollTo=e.v,exports.setClientSideCookie=e.N,exports.shield=e.t,exports.sleep=e.y,exports.svgToBase64=e.b,exports.throttle=e.x;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,6 @@
1
- import { ClassValue } from "clsx";
1
+ import { n as Task, r as schedule, t as ScheduleOpts } from "./schedule-CRsY0oqG.cjs";
2
2
  import * as React from "react";
3
+ import { ClassValue } from "clsx";
3
4
 
4
5
  //#region src/functions/cookie.d.ts
5
6
  declare const setClientSideCookie: (name: string, value: string, days?: number, path?: string) => void;
@@ -213,20 +214,6 @@ declare function poll<T>(cond: () => Promise<T | null | false | undefined>, {
213
214
  jitter: boolean;
214
215
  }>): Promise<T>;
215
216
  //#endregion
216
- //#region src/functions/schedule.d.ts
217
- type Task = () => Promise<void> | void;
218
- interface ScheduleOpts {
219
- retry?: number;
220
- delay?: number;
221
- timeout?: number;
222
- }
223
- /**
224
- * Runs a function asynchronously in the background.
225
- * Returns immediately, retries on failure if configured.
226
- * Logs total time taken.
227
- */
228
- declare function schedule(task: Task, options?: ScheduleOpts): void;
229
- //#endregion
230
217
  //#region src/functions/shield.d.ts
231
218
  /**
232
219
  * A helper to run sync or async operations safely without try/catch.