@noeldemartin/utils 0.7.3 → 0.8.0

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.
Files changed (234) hide show
  1. package/dist/_virtual/_rolldown/runtime.js +13 -0
  2. package/dist/fluent/FluentArray.d.ts +48 -0
  3. package/dist/fluent/FluentArray.js +48 -0
  4. package/dist/fluent/FluentArray.js.map +1 -0
  5. package/dist/fluent/FluentObject.d.ts +16 -0
  6. package/dist/fluent/FluentObject.js +45 -0
  7. package/dist/fluent/FluentObject.js.map +1 -0
  8. package/dist/fluent/FluentString.d.ts +21 -0
  9. package/dist/fluent/FluentString.js +28 -0
  10. package/dist/fluent/FluentString.js.map +1 -0
  11. package/dist/fluent/facade.d.ts +17 -0
  12. package/dist/fluent/facade.js +45 -0
  13. package/dist/fluent/facade.js.map +1 -0
  14. package/dist/fluent/index.d.ts +29 -0
  15. package/dist/fluent/index.js +41 -0
  16. package/dist/fluent/index.js.map +1 -0
  17. package/dist/fluent/invade.d.ts +6 -0
  18. package/dist/fluent/invade.js +8 -0
  19. package/dist/fluent/invade.js.map +1 -0
  20. package/dist/fluent/lazyFacade.d.ts +16 -0
  21. package/dist/fluent/lazyFacade.js +67 -0
  22. package/dist/fluent/lazyFacade.js.map +1 -0
  23. package/dist/fluent/noop.d.ts +4 -0
  24. package/dist/fluent/noop.js +6 -0
  25. package/dist/fluent/noop.js.map +1 -0
  26. package/dist/fluent/required.d.ts +5 -0
  27. package/dist/fluent/required.js +32 -0
  28. package/dist/fluent/required.js.map +1 -0
  29. package/dist/fluent/tap.d.ts +7 -0
  30. package/dist/fluent/tap.js +22 -0
  31. package/dist/fluent/tap.js.map +1 -0
  32. package/dist/fluent/value.d.ts +5 -0
  33. package/dist/fluent/value.js +8 -0
  34. package/dist/fluent/value.js.map +1 -0
  35. package/dist/fluent/when.d.ts +6 -0
  36. package/dist/fluent/when.js +11 -0
  37. package/dist/fluent/when.js.map +1 -0
  38. package/dist/helpers/InMemoryStorageService.d.ts +8 -0
  39. package/dist/helpers/InMemoryStorageService.js +16 -0
  40. package/dist/helpers/InMemoryStorageService.js.map +1 -0
  41. package/dist/helpers/IndexedDBMap.d.ts +17 -0
  42. package/dist/helpers/IndexedDBMap.js +52 -0
  43. package/dist/helpers/IndexedDBMap.js.map +1 -0
  44. package/dist/helpers/JSError.d.ts +14 -0
  45. package/dist/helpers/JSError.js +14 -0
  46. package/dist/helpers/JSError.js.map +1 -0
  47. package/dist/helpers/ListenersManager.d.ts +15 -0
  48. package/dist/helpers/ListenersManager.js +23 -0
  49. package/dist/helpers/ListenersManager.js.map +1 -0
  50. package/dist/helpers/MagicObject.d.ts +29 -0
  51. package/dist/helpers/MagicObject.js +77 -0
  52. package/dist/helpers/MagicObject.js.map +1 -0
  53. package/dist/helpers/ObjectsMap.d.ts +28 -0
  54. package/dist/helpers/ObjectsMap.js +86 -0
  55. package/dist/helpers/ObjectsMap.js.map +1 -0
  56. package/dist/helpers/PromisedValue.d.ts +32 -0
  57. package/dist/helpers/PromisedValue.js +68 -0
  58. package/dist/helpers/PromisedValue.js.map +1 -0
  59. package/dist/helpers/Semaphore.d.ts +14 -0
  60. package/dist/helpers/Semaphore.js +45 -0
  61. package/dist/helpers/Semaphore.js.map +1 -0
  62. package/dist/helpers/Storage.d.ts +17 -0
  63. package/dist/helpers/Storage.js +39 -0
  64. package/dist/helpers/Storage.js.map +1 -0
  65. package/dist/helpers/array_helpers.d.ts +57 -0
  66. package/dist/helpers/array_helpers.js +208 -0
  67. package/dist/helpers/array_helpers.js.map +1 -0
  68. package/dist/helpers/boolean_helpers.d.ts +4 -0
  69. package/dist/helpers/boolean_helpers.js +10 -0
  70. package/dist/helpers/boolean_helpers.js.map +1 -0
  71. package/dist/helpers/caching_helpers.d.ts +17 -0
  72. package/dist/helpers/caching_helpers.js +55 -0
  73. package/dist/helpers/caching_helpers.js.map +1 -0
  74. package/dist/helpers/chaos_helpers.d.ts +6 -0
  75. package/dist/helpers/chaos_helpers.js +11 -0
  76. package/dist/helpers/chaos_helpers.js.map +1 -0
  77. package/dist/helpers/date_helpers.d.ts +4 -0
  78. package/dist/helpers/date_helpers.js +15 -0
  79. package/dist/helpers/date_helpers.js.map +1 -0
  80. package/dist/helpers/deprecated.d.ts +24 -0
  81. package/dist/helpers/env.d.ts +9 -0
  82. package/dist/helpers/env.js +42 -0
  83. package/dist/helpers/env.js.map +1 -0
  84. package/dist/helpers/error_helpers.d.ts +12 -0
  85. package/dist/helpers/error_helpers.js +20 -0
  86. package/dist/helpers/error_helpers.js.map +1 -0
  87. package/dist/helpers/escape_helpers.d.ts +5 -0
  88. package/dist/helpers/escape_helpers.js +11 -0
  89. package/dist/helpers/escape_helpers.js.map +1 -0
  90. package/dist/helpers/file_helpers.d.ts +4 -0
  91. package/dist/helpers/file_helpers.js +16 -0
  92. package/dist/helpers/file_helpers.js.map +1 -0
  93. package/dist/helpers/format_helpers.d.ts +7 -0
  94. package/dist/helpers/format_helpers.js +28 -0
  95. package/dist/helpers/format_helpers.js.map +1 -0
  96. package/dist/helpers/hash_helpers.d.ts +4 -0
  97. package/dist/helpers/hash_helpers.js +156 -0
  98. package/dist/helpers/hash_helpers.js.map +1 -0
  99. package/dist/helpers/identity_helpers.d.ts +5 -0
  100. package/dist/helpers/identity_helpers.js +15 -0
  101. package/dist/helpers/identity_helpers.js.map +1 -0
  102. package/dist/helpers/location_helpers.d.ts +8 -0
  103. package/dist/helpers/location_helpers.js +37 -0
  104. package/dist/helpers/location_helpers.js.map +1 -0
  105. package/dist/helpers/logical_helpers.d.ts +4 -0
  106. package/dist/helpers/logical_helpers.js +13 -0
  107. package/dist/helpers/logical_helpers.js.map +1 -0
  108. package/dist/helpers/math_helpers.d.ts +5 -0
  109. package/dist/helpers/math_helpers.js +12 -0
  110. package/dist/helpers/math_helpers.js.map +1 -0
  111. package/dist/helpers/mixin_helpers.d.ts +20 -0
  112. package/dist/helpers/mixin_helpers.js +43 -0
  113. package/dist/helpers/mixin_helpers.js.map +1 -0
  114. package/dist/helpers/network_helpers.d.ts +4 -0
  115. package/dist/helpers/network_helpers.js +8 -0
  116. package/dist/helpers/network_helpers.js.map +1 -0
  117. package/dist/helpers/object_helpers.d.ts +58 -0
  118. package/dist/helpers/object_helpers.js +179 -0
  119. package/dist/helpers/object_helpers.js.map +1 -0
  120. package/dist/helpers/promise_helpers.d.ts +10 -0
  121. package/dist/helpers/promise_helpers.js +25 -0
  122. package/dist/helpers/promise_helpers.js.map +1 -0
  123. package/dist/helpers/replacements-scope.js +21 -0
  124. package/dist/helpers/replacements-scope.js.map +1 -0
  125. package/dist/helpers/replacements.d.ts +5 -0
  126. package/dist/helpers/replacements.js +34 -0
  127. package/dist/helpers/replacements.js.map +1 -0
  128. package/dist/helpers/runtime_helpers.d.ts +4 -0
  129. package/dist/helpers/runtime_helpers.js +8 -0
  130. package/dist/helpers/runtime_helpers.js.map +1 -0
  131. package/dist/helpers/string_helpers.d.ts +17 -0
  132. package/dist/helpers/string_helpers.js +42 -0
  133. package/dist/helpers/string_helpers.js.map +1 -0
  134. package/dist/helpers/time_constants.d.ts +15 -0
  135. package/dist/helpers/time_constants.js +17 -0
  136. package/dist/helpers/time_constants.js.map +1 -0
  137. package/dist/helpers/time_helpers.d.ts +24 -0
  138. package/dist/helpers/time_helpers.js +57 -0
  139. package/dist/helpers/time_helpers.js.map +1 -0
  140. package/dist/helpers/url_helpers.d.ts +24 -0
  141. package/dist/helpers/url_helpers.js +90 -0
  142. package/dist/helpers/url_helpers.js.map +1 -0
  143. package/dist/helpers/value_helpers.d.ts +7 -0
  144. package/dist/helpers/value_helpers.js +11 -0
  145. package/dist/helpers/value_helpers.js.map +1 -0
  146. package/dist/index.d.ts +53 -0
  147. package/dist/index.js +49 -0
  148. package/dist/types/arrays.d.ts +12 -0
  149. package/dist/types/classes.d.ts +12 -0
  150. package/dist/types/helpers.d.ts +36 -0
  151. package/dist/types/helpers.js +6 -0
  152. package/dist/types/helpers.js.map +1 -0
  153. package/dist/types/objects.d.ts +8 -0
  154. package/package.json +38 -52
  155. package/src/fluent/FluentArray.test.ts +2 -9
  156. package/src/fluent/FluentArray.ts +6 -5
  157. package/src/fluent/FluentObject.ts +2 -4
  158. package/src/fluent/FluentString.test.ts +1 -8
  159. package/src/fluent/FluentString.ts +0 -2
  160. package/src/fluent/facade.test.ts +16 -4
  161. package/src/fluent/facade.ts +6 -4
  162. package/src/fluent/index.test.ts +3 -8
  163. package/src/fluent/index.ts +3 -3
  164. package/src/fluent/invade.test.ts +1 -5
  165. package/src/fluent/invade.ts +1 -1
  166. package/src/fluent/lazyFacade.test.ts +191 -0
  167. package/src/fluent/lazyFacade.ts +115 -0
  168. package/src/fluent/required.test.ts +1 -5
  169. package/src/fluent/required.ts +2 -4
  170. package/src/fluent/tap.test.ts +2 -9
  171. package/src/fluent/tap.ts +4 -3
  172. package/src/fluent/value.test.ts +1 -4
  173. package/src/fluent/when.test.ts +1 -6
  174. package/src/fluent/when.ts +2 -2
  175. package/src/helpers/InMemoryStorageService.ts +13 -0
  176. package/src/helpers/IndexedDBMap.ts +0 -2
  177. package/src/helpers/JSError.test.ts +1 -6
  178. package/src/helpers/JSError.ts +0 -2
  179. package/src/helpers/ListenersManager.test.ts +3 -7
  180. package/src/helpers/ListenersManager.ts +2 -4
  181. package/src/helpers/MagicObject.test.ts +14 -8
  182. package/src/helpers/MagicObject.ts +12 -3
  183. package/src/helpers/ObjectsMap.test.ts +1 -3
  184. package/src/helpers/ObjectsMap.ts +1 -5
  185. package/src/helpers/PromisedValue.test.ts +1 -3
  186. package/src/helpers/PromisedValue.ts +5 -6
  187. package/src/helpers/Semaphore.test.ts +6 -10
  188. package/src/helpers/Semaphore.ts +0 -2
  189. package/src/helpers/Storage.test.ts +47 -0
  190. package/src/helpers/Storage.ts +11 -19
  191. package/src/helpers/array_helpers.test.ts +127 -38
  192. package/src/helpers/array_helpers.ts +137 -78
  193. package/src/helpers/caching_helpers.test.ts +1 -3
  194. package/src/helpers/caching_helpers.ts +2 -2
  195. package/src/helpers/date_helpers.test.ts +1 -4
  196. package/src/helpers/date_helpers.ts +1 -1
  197. package/src/helpers/env.ts +5 -1
  198. package/src/helpers/error_helpers.test.ts +9 -8
  199. package/src/helpers/error_helpers.ts +11 -11
  200. package/src/helpers/format_helpers.test.ts +2 -4
  201. package/src/helpers/hash_helpers.test.ts +1 -4
  202. package/src/helpers/hash_helpers.ts +3 -3
  203. package/src/helpers/identity_helpers.test.ts +1 -3
  204. package/src/helpers/index.ts +3 -0
  205. package/src/helpers/logical_helpers.test.ts +1 -3
  206. package/src/helpers/logical_helpers.ts +1 -1
  207. package/src/helpers/math_helpers.test.ts +1 -3
  208. package/src/helpers/mixin_helpers.stubs.ts +1 -13
  209. package/src/helpers/mixin_helpers.test.ts +2 -7
  210. package/src/helpers/mixin_helpers.ts +6 -9
  211. package/src/helpers/object_helpers.test.ts +32 -19
  212. package/src/helpers/object_helpers.ts +43 -21
  213. package/src/helpers/promise_helpers.test.ts +1 -4
  214. package/src/helpers/promise_helpers.ts +9 -9
  215. package/src/helpers/replacements-scope.ts +15 -0
  216. package/src/helpers/replacements.test.ts +23 -0
  217. package/src/helpers/replacements.ts +52 -0
  218. package/src/helpers/runtime_helpers.ts +3 -3
  219. package/src/helpers/string_helpers.test.ts +3 -5
  220. package/src/helpers/time_constants.ts +13 -0
  221. package/src/helpers/time_helpers.ts +35 -0
  222. package/src/helpers/url_helpers.test.ts +12 -4
  223. package/src/helpers/url_helpers.ts +9 -15
  224. package/src/helpers/value_helpers.test.ts +12 -0
  225. package/src/helpers/value_helpers.ts +6 -0
  226. package/src/types/arrays.test.ts +1 -4
  227. package/src/types/classes.ts +1 -0
  228. package/src/types/helpers.test.ts +1 -6
  229. package/src/types/helpers.ts +6 -5
  230. package/src/types/objects.test.ts +1 -4
  231. package/src/types/objects.ts +3 -3
  232. package/dist/noeldemartin-utils.d.ts +0 -901
  233. package/dist/noeldemartin-utils.js +0 -1473
  234. package/dist/noeldemartin-utils.js.map +0 -1
@@ -0,0 +1,58 @@
1
+ import { Equals, GetObjectMethods, KeyOf, Pretty, TypeGuard, VoidClosure } from "../types/helpers.js";
2
+ import { Constructor } from "../types/classes.js";
3
+ import { DeepKeyOf, DeepValue } from "../types/objects.js";
4
+ //#region src/helpers/object_helpers.d.ts
5
+ export type Obj = Record<string, unknown>;
6
+ export type GetObjectKeys<T> = T extends Record<infer Key, any> ? Key : keyof T;
7
+ export type GetObjectValues<T> = T extends Record<any, infer Value> ? Value : never;
8
+ export type ValueWithout<TValue, TExclude> = TValue extends TExclude ? never : TValue;
9
+ export type ReplaceValues<TObj, TExclude> = { [K in keyof TObj]: ValueWithout<TObj[K], TExclude>; };
10
+ export type GetRequiredKeysWithout<TObj, TExclude, U extends Record<keyof TObj, unknown> = ReplaceValues<TObj, TExclude>> = { [K in keyof TObj]: Record<string, never> extends Pick<TObj, K> ? never : U[K] extends never ? never : Equals<TObj[K], U[K]> extends true ? K : never; }[keyof TObj];
11
+ export type GetOptionalKeysWithout<TObj, TExclude, U extends Record<keyof TObj, unknown> = ReplaceValues<TObj, TExclude>> = { [K in keyof TObj]: Record<string, never> extends Pick<TObj, K> ? K : U[K] extends never ? never : Equals<TObj[K], U[K]> extends true ? never : K; }[keyof TObj];
12
+ export type ObjectWithout<TObj, TExclude> = Pretty<{ [K in GetRequiredKeysWithout<TObj, TExclude>]: ValueWithout<TObj[K], TExclude>; } & { [K in GetOptionalKeysWithout<TObj, TExclude>]?: ValueWithout<TObj[K], TExclude>; }>;
13
+ export type Inverted<T extends { [K in keyof T]: PropertyKey; }> = { [K in keyof T as T[K]]: `${K & (string | number)}`; };
14
+ export declare function deepEquals(a: unknown, b: unknown): boolean;
15
+ export declare function deepAssign<T extends object>(target: T, ...sources: T[]): T;
16
+ export declare function deepGet<T extends object, K extends DeepKeyOf<T>>(object: T, key: K): DeepValue<T, K>;
17
+ export declare function deepSet<T extends object, K extends DeepKeyOf<T>>(object: T, key: K, value: DeepValue<T, K>): void;
18
+ export declare function getClassMethods(target: object): string[];
19
+ export declare function invert<T extends { [K in keyof T]: PropertyKey; }>(map: T): Inverted<T>;
20
+ export declare const isArray: (arg: any) => arg is any[];
21
+ export declare function isConstructor(value: object): value is Constructor;
22
+ export declare function isEmpty(value: unknown): boolean;
23
+ export declare function isInstanceOf<T>(value: unknown, objectClass: Constructor<T>): value is T;
24
+ export declare function isIterable(value: unknown): value is Iterable<unknown>;
25
+ export declare function isObject(value: unknown): value is Obj;
26
+ export declare function isPlainObject(value: unknown): value is object;
27
+ export declare function isString(value: unknown): value is string | String;
28
+ export declare function isNullable(value: unknown): value is undefined | null;
29
+ export declare function isPromiseLike(value: unknown): value is PromiseLike<unknown>;
30
+ export declare function isSubclassOf(value: Constructor, baseClass: Constructor): boolean;
31
+ export declare function monkeyPatch<T, K extends GetObjectMethods<T>>(object: T, method: K, callback: VoidClosure<T[K]>): void;
32
+ export declare function objectDeepClone<T extends Obj>(object: T): T;
33
+ export declare const objectEntries: <T extends Parameters<typeof Object.entries>[0]>(obj: T) => [GetObjectKeys<T>, GetObjectValues<T>][];
34
+ export declare const objectFromEntries: <K extends string | number | symbol, V>(value: Iterable<readonly [K, V]>) => Record<K, V>;
35
+ export declare const objectValues: <T extends {
36
+ [k: string]: any;
37
+ } | ArrayLike<any>>(object: T) => GetObjectValues<T>[];
38
+ export declare const objectKeys: <T extends {
39
+ [k: string]: any;
40
+ } | ArrayLike<any>>(object: T) => GetObjectKeys<T>[];
41
+ export declare function objectHasOwnProperty(object: Obj, property: string): boolean;
42
+ export declare function objectMap<T>(items: T[], property: KeyOf<T, number | string>): Record<string, T>;
43
+ export declare function objectOnly<T extends object, K extends keyof T>(obj: T, keys: K | K[]): Pick<T, K>;
44
+ export declare function objectPropertyIsObject<T extends string>(object: Obj, property: T): object is { [t in T]: Obj; };
45
+ export declare function objectPull<T extends Obj, K extends keyof T>(obj: T, key: K): T[K];
46
+ export declare function objectWithout<TObj extends Obj, TKey extends keyof TObj>(obj: TObj, key: TKey): Omit<TObj, TKey>;
47
+ export declare function objectWithout<TObj extends object, TKey extends keyof TObj>(obj: TObj, key: TKey): Omit<TObj, TKey>;
48
+ export declare function objectWithout<TObj extends Obj, TKey extends keyof TObj>(obj: TObj, keys: TKey[]): Omit<TObj, TKey>;
49
+ export declare function objectWithout<TObj extends object, TKey extends keyof TObj>(obj: TObj, keys: TKey[]): Omit<TObj, TKey>;
50
+ export declare function objectWithout<TObj extends Obj, TExclude>(obj: TObj, exclude: TypeGuard<TExclude>): ObjectWithout<TObj, TExclude>;
51
+ export declare function objectWithout<TObj extends object, TExclude>(obj: TObj, exclude: TypeGuard<TExclude>): ObjectWithout<TObj, TExclude>;
52
+ export declare function objectWithoutEmpty<T extends Obj>(obj: T): ObjectWithout<T, null | undefined>;
53
+ export declare function objectWithoutEmpty<T extends object>(obj: T): ObjectWithout<T, null | undefined>;
54
+ export declare function overridePrototypeMethod<T, K extends GetObjectMethods<T>>(target: Constructor<T>, method: K, implementation: T[K]): void;
55
+ export declare function toString(value: unknown): string;
56
+ export declare function toError(value: unknown): Error;
57
+ //#endregion
58
+ //# sourceMappingURL=object_helpers.d.ts.map
@@ -0,0 +1,179 @@
1
+ //#region src/helpers/object_helpers.ts
2
+ function deepEquals(a, b) {
3
+ if (a === b) return true;
4
+ if (!isObject(a) || !isObject(b)) return false;
5
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
6
+ if (Object.keys(a).length !== Object.keys(b).length) return false;
7
+ return !Object.keys(a).some((key) => !deepEquals(a[key], b[key]));
8
+ }
9
+ function deepAssign(target, ...sources) {
10
+ const [source, ...otherSources] = sources;
11
+ if (!source) return target;
12
+ if (isObject(target) && isObject(source)) for (const key of objectKeys(source)) {
13
+ if (!isObject(source[key])) {
14
+ Object.assign(target, { [key]: source[key] });
15
+ continue;
16
+ }
17
+ target[key] ??= {};
18
+ if (!isObject(target[key])) continue;
19
+ deepAssign(target[key], source[key]);
20
+ }
21
+ return deepAssign(target, ...otherSources);
22
+ }
23
+ function deepGet(object, key) {
24
+ let value = object;
25
+ const objectKeys = key.split(".");
26
+ for (const deepKey of objectKeys) {
27
+ if (Array.isArray(value)) {
28
+ value = value[Number(deepKey)];
29
+ continue;
30
+ }
31
+ if (!isObject(value)) return;
32
+ value = value[deepKey];
33
+ }
34
+ return value;
35
+ }
36
+ function deepSet(object, key, value) {
37
+ let wrapper = object;
38
+ const objectKeys = key.split(".");
39
+ const lastKey = objectKeys.pop();
40
+ if (!lastKey) return;
41
+ for (const deepKey of objectKeys) {
42
+ if (!isObject(wrapper)) return;
43
+ wrapper = wrapper[deepKey];
44
+ }
45
+ wrapper[lastKey] = value;
46
+ }
47
+ function getClassMethods(target) {
48
+ const properties = /* @__PURE__ */ new Set();
49
+ let prototype = (target.constructor === Object.constructor ? target : target.constructor).prototype;
50
+ while (prototype.constructor !== Object) {
51
+ Object.getOwnPropertyNames(prototype).forEach((property) => properties.add(property));
52
+ prototype = Object.getPrototypeOf(prototype);
53
+ }
54
+ properties.delete("constructor");
55
+ return Array.from(properties);
56
+ }
57
+ function invert(map) {
58
+ return Object.entries(map).reduce((invertedMap, [key, value]) => {
59
+ invertedMap[value] = key;
60
+ return invertedMap;
61
+ }, {});
62
+ }
63
+ const isArray = Array.isArray.bind(Array);
64
+ function isConstructor(value) {
65
+ return "prototype" in value;
66
+ }
67
+ function isEmpty(value) {
68
+ if (value === null || value === void 0) return true;
69
+ if (Array.isArray(value) || typeof value === "string") return value.length === 0;
70
+ if (typeof value === "object") return Object.keys(value).length === 0;
71
+ return false;
72
+ }
73
+ function isInstanceOf(value, objectClass) {
74
+ return value instanceof objectClass;
75
+ }
76
+ function isIterable(value) {
77
+ return typeof value?.[Symbol.iterator] === "function";
78
+ }
79
+ function isObject(value) {
80
+ return typeof value === "object" && value !== null;
81
+ }
82
+ function isPlainObject(value) {
83
+ return isObject(value) && Object.getPrototypeOf(value) === Object.prototype;
84
+ }
85
+ function isString(value) {
86
+ return typeof value === "string" || value instanceof String;
87
+ }
88
+ function isNullable(value) {
89
+ return typeof value === "undefined" || value === null;
90
+ }
91
+ function isPromiseLike(value) {
92
+ return (isObject(value) || typeof value === "function") && typeof value?.then === "function";
93
+ }
94
+ function isSubclassOf(value, baseClass) {
95
+ let prototype = Object.getPrototypeOf(value);
96
+ while (prototype !== null && prototype !== Object) {
97
+ if (prototype === baseClass) return true;
98
+ prototype = Object.getPrototypeOf(prototype);
99
+ }
100
+ return false;
101
+ }
102
+ function monkeyPatch(object, method, callback) {
103
+ const originalMethod = object[method];
104
+ object[method] = ((...args) => {
105
+ callback(...args);
106
+ return originalMethod.call(object, ...args);
107
+ });
108
+ }
109
+ function objectDeepClone(object) {
110
+ object = { ...object };
111
+ for (const property in object) {
112
+ if (!objectPropertyIsObject(object, property)) continue;
113
+ object[property] = objectDeepClone(object[property]);
114
+ }
115
+ return object;
116
+ }
117
+ const objectEntries = Object.entries.bind(Object);
118
+ const objectFromEntries = Object.fromEntries.bind(Object);
119
+ const objectValues = Object.values.bind(Object);
120
+ const objectKeys = Object.keys.bind(Object);
121
+ function objectHasOwnProperty(object, property) {
122
+ return Object.prototype.hasOwnProperty.call(object, property);
123
+ }
124
+ function objectMap(items, property) {
125
+ return items.reduce((map, item) => {
126
+ map[item[property]] = item;
127
+ return map;
128
+ }, {});
129
+ }
130
+ function objectOnly(obj, keys) {
131
+ const newObject = {};
132
+ const keysArray = Array.isArray(keys) ? keys : [keys];
133
+ for (const key of keysArray) {
134
+ if (!(key in obj)) continue;
135
+ newObject[key] = obj[key];
136
+ }
137
+ return newObject;
138
+ }
139
+ function objectPropertyIsObject(object, property) {
140
+ let value;
141
+ return objectHasOwnProperty(object, property) && isObject(value = object[property]) && value.constructor === Object;
142
+ }
143
+ function objectPull(obj, key) {
144
+ const value = obj[key];
145
+ delete obj[key];
146
+ return value;
147
+ }
148
+ function objectWithout(obj, keysOrExclude) {
149
+ if (typeof keysOrExclude === "function") {
150
+ const exclude = keysOrExclude;
151
+ const cleanObject = {};
152
+ for (const [key, value] of Object.entries(obj)) {
153
+ if (exclude(value)) continue;
154
+ cleanObject[key] = value;
155
+ }
156
+ return cleanObject;
157
+ }
158
+ const newObject = { ...obj };
159
+ const keysArray = Array.isArray(keysOrExclude) ? keysOrExclude : [keysOrExclude];
160
+ for (const key of keysArray) delete newObject[key];
161
+ return newObject;
162
+ }
163
+ function objectWithoutEmpty(obj) {
164
+ return objectWithout(obj, (value) => value === null || value === void 0);
165
+ }
166
+ function overridePrototypeMethod(target, method, implementation) {
167
+ target.prototype[method] = implementation;
168
+ }
169
+ function toString(value) {
170
+ return String(value);
171
+ }
172
+ function toError(value) {
173
+ if (value instanceof Error) return value;
174
+ return new Error(toString(value));
175
+ }
176
+ //#endregion
177
+ export { deepAssign, deepEquals, deepGet, deepSet, getClassMethods, invert, isArray, isConstructor, isEmpty, isInstanceOf, isIterable, isNullable, isObject, isPlainObject, isPromiseLike, isString, isSubclassOf, monkeyPatch, objectDeepClone, objectEntries, objectFromEntries, objectHasOwnProperty, objectKeys, objectMap, objectOnly, objectPropertyIsObject, objectPull, objectValues, objectWithout, objectWithoutEmpty, overridePrototypeMethod, toError, toString };
178
+
179
+ //# sourceMappingURL=object_helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"object_helpers.js","names":[],"sources":["../../src/helpers/object_helpers.ts"],"sourcesContent":["import type { DeepKeyOf, DeepValue } from '@noeldemartin/utils/types';\nimport type { Constructor } from '@noeldemartin/utils/types/classes';\nimport type {\n Closure,\n ClosureArgs,\n Equals,\n GetObjectMethods,\n KeyOf,\n Pretty,\n TypeGuard,\n VoidClosure,\n} from '@noeldemartin/utils/types/helpers';\n\nexport type Obj = Record<string, unknown>;\n\n// oxlint-disable-next-line typescript/no-explicit-any\nexport type GetObjectKeys<T> = T extends Record<infer Key, any> ? Key : keyof T;\n\n// oxlint-disable-next-line typescript/no-explicit-any\nexport type GetObjectValues<T> = T extends Record<any, infer Value> ? Value : never;\n\nexport type ValueWithout<TValue, TExclude> = TValue extends TExclude ? never : TValue;\nexport type ReplaceValues<TObj, TExclude> = { [K in keyof TObj]: ValueWithout<TObj[K], TExclude> };\nexport type GetRequiredKeysWithout<\n TObj,\n TExclude,\n U extends Record<keyof TObj, unknown> = ReplaceValues<TObj, TExclude>,\n> = {\n [K in keyof TObj]: Record<string, never> extends Pick<TObj, K>\n ? never\n : U[K] extends never\n ? never\n : Equals<TObj[K], U[K]> extends true\n ? K\n : never;\n}[keyof TObj];\nexport type GetOptionalKeysWithout<\n TObj,\n TExclude,\n U extends Record<keyof TObj, unknown> = ReplaceValues<TObj, TExclude>,\n> = {\n [K in keyof TObj]: Record<string, never> extends Pick<TObj, K>\n ? K\n : U[K] extends never\n ? never\n : Equals<TObj[K], U[K]> extends true\n ? never\n : K;\n}[keyof TObj];\n\n// Given an existing bug in TypeScript, it's not possible to define optional keys using type generics without having\n// them defined as `| undefined` as well. Until that is fixed, this may cause some problems for keys that can have\n// empty values but not always do.\n// See https://github.com/microsoft/TypeScript/issues/13195\nexport type ObjectWithout<TObj, TExclude> = Pretty<\n { [K in GetRequiredKeysWithout<TObj, TExclude>]: ValueWithout<TObj[K], TExclude> } & {\n [K in GetOptionalKeysWithout<TObj, TExclude>]?: ValueWithout<TObj[K], TExclude>;\n }\n>;\n\nexport type Inverted<T extends { [K in keyof T]: PropertyKey }> = {\n [K in keyof T as T[K]]: `${K & (string | number)}`;\n};\n\nexport function deepEquals(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n\n if (!isObject(a) || !isObject(b)) return false;\n\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n\n if (Object.keys(a).length !== Object.keys(b).length) return false;\n\n return !Object.keys(a).some((key) => !deepEquals(a[key], b[key]));\n}\n\nexport function deepAssign<T extends object>(target: T, ...sources: T[]): T {\n const [source, ...otherSources] = sources;\n\n if (!source) {\n return target;\n }\n\n if (isObject(target) && isObject(source)) {\n for (const key of objectKeys(source)) {\n if (!isObject(source[key])) {\n Object.assign(target, { [key]: source[key] });\n\n continue;\n }\n\n (target as Record<string, unknown>)[key] ??= {};\n\n if (!isObject(target[key])) {\n continue;\n }\n\n deepAssign(target[key], source[key]);\n }\n }\n\n return deepAssign(target, ...otherSources);\n}\n\nexport function deepGet<T extends object, K extends DeepKeyOf<T>>(object: T, key: K): DeepValue<T, K> {\n // oxlint-disable-next-line typescript/no-explicit-any, typescript/no-unsafe-assignment\n let value = object as any;\n const objectKeys = key.split('.');\n\n for (const deepKey of objectKeys) {\n if (Array.isArray(value)) {\n value = value[Number(deepKey)];\n\n continue;\n }\n\n if (!isObject(value)) {\n return undefined as DeepValue<T, K>;\n }\n\n value = value[deepKey];\n }\n\n return value as DeepValue<T, K>;\n}\n\nexport function deepSet<T extends object, K extends DeepKeyOf<T>>(object: T, key: K, value: DeepValue<T, K>): void {\n // oxlint-disable-next-line typescript/no-explicit-any, typescript/no-unsafe-assignment\n let wrapper = object as any;\n const objectKeys = key.split('.');\n const lastKey = objectKeys.pop();\n\n if (!lastKey) {\n return;\n }\n\n for (const deepKey of objectKeys) {\n if (!isObject(wrapper)) {\n return;\n }\n\n wrapper = wrapper[deepKey];\n }\n\n // oxlint-disable-next-line typescript/no-unsafe-member-access\n wrapper[lastKey] = value;\n}\n\nexport function getClassMethods(target: object): string[] {\n const properties = new Set<string>();\n const classDefinition = target.constructor === Object.constructor ? target : target.constructor;\n\n let prototype = (classDefinition as { prototype: Constructor }).prototype;\n while (prototype.constructor !== Object) {\n Object.getOwnPropertyNames(prototype).forEach((property) => properties.add(property));\n\n prototype = Object.getPrototypeOf(prototype);\n }\n\n properties.delete('constructor');\n\n return Array.from(properties);\n}\n\nexport function invert<T extends { [K in keyof T]: PropertyKey }>(map: T): Inverted<T> {\n return Object.entries(map as Record<string, PropertyKey>).reduce(\n (invertedMap, [key, value]) => {\n invertedMap[value] = key;\n\n return invertedMap;\n },\n {} as Record<PropertyKey, string>,\n ) as Inverted<T>;\n}\n\nexport const isArray = Array.isArray.bind(Array);\n\nexport function isConstructor(value: object): value is Constructor {\n return 'prototype' in value;\n}\n\nexport function isEmpty(value: unknown): boolean {\n if (value === null || value === undefined) return true;\n\n if (Array.isArray(value) || typeof value === 'string') return value.length === 0;\n\n if (typeof value === 'object') return Object.keys(value as Record<string, unknown>).length === 0;\n\n return false;\n}\n\nexport function isInstanceOf<T>(value: unknown, objectClass: Constructor<T>): value is T {\n return value instanceof objectClass;\n}\n\nexport function isIterable(value: unknown): value is Iterable<unknown> {\n return typeof (value as { [Symbol.iterator]?: unknown })?.[Symbol.iterator] === 'function';\n}\n\nexport function isObject(value: unknown): value is Obj {\n return typeof value === 'object' && value !== null;\n}\n\nexport function isPlainObject(value: unknown): value is object {\n return isObject(value) && Object.getPrototypeOf(value) === Object.prototype;\n}\n\n// oxlint-disable-next-line typescript/no-wrapper-object-types\nexport function isString(value: unknown): value is string | String {\n return typeof value === 'string' || value instanceof String;\n}\n\nexport function isNullable(value: unknown): value is undefined | null {\n return typeof value === 'undefined' || value === null;\n}\n\nexport function isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n // oxlint-disable-next-line typescript/no-explicit-any\n return (isObject(value) || typeof value === 'function') && typeof (value as any)?.then === 'function';\n}\n\nexport function isSubclassOf(value: Constructor, baseClass: Constructor): boolean {\n let prototype = Object.getPrototypeOf(value);\n\n while (prototype !== null && prototype !== Object) {\n if (prototype === baseClass) {\n return true;\n }\n\n prototype = Object.getPrototypeOf(prototype);\n }\n\n return false;\n}\n\nexport function monkeyPatch<T, K extends GetObjectMethods<T>>(object: T, method: K, callback: VoidClosure<T[K]>): void {\n const originalMethod = object[method] as unknown as Closure;\n\n object[method] = ((...args: ClosureArgs) => {\n (callback as unknown as Closure)(...args);\n\n return originalMethod.call(object, ...args);\n }) as unknown as T[K];\n}\n\nexport function objectDeepClone<T extends Obj>(object: T): T {\n object = { ...object };\n\n for (const property in object) {\n if (!objectPropertyIsObject(object, property)) continue;\n\n object[property] = objectDeepClone(object[property]);\n }\n\n return object;\n}\n\nexport const objectEntries = Object.entries.bind(Object) as <T extends Parameters<typeof Object.entries>[0]>(\n obj: T,\n) => [GetObjectKeys<T>, GetObjectValues<T>][];\n\nexport const objectFromEntries = Object.fromEntries.bind(Object) as <K extends string | number | symbol, V>(\n value: Iterable<readonly [K, V]>,\n) => Record<K, V>;\n\n// oxlint-disable-next-line typescript/no-explicit-any\nexport const objectValues = Object.values.bind(Object) as <T extends { [k: string]: any } | ArrayLike<any>>(\n object: T,\n) => GetObjectValues<T>[];\n\n// oxlint-disable-next-line typescript/no-explicit-any\nexport const objectKeys = Object.keys.bind(Object) as <T extends { [k: string]: any } | ArrayLike<any>>(\n object: T,\n) => GetObjectKeys<T>[];\n\nexport function objectHasOwnProperty(object: Obj, property: string): boolean {\n return Object.prototype.hasOwnProperty.call(object, property);\n}\n\nexport function objectMap<T>(items: T[], property: KeyOf<T, number | string>): Record<string, T> {\n return items.reduce(\n (map, item) => {\n map[item[property] as unknown as number | string] = item;\n\n return map;\n },\n {} as Record<string, T>,\n );\n}\n\nexport function objectOnly<T extends object, K extends keyof T>(obj: T, keys: K | K[]): Pick<T, K> {\n const newObject: Pick<T, K> = {} as Pick<T, K>;\n const keysArray = Array.isArray(keys) ? keys : [keys];\n\n for (const key of keysArray) {\n if (!(key in obj)) continue;\n\n newObject[key] = obj[key];\n }\n\n return newObject;\n}\n\nexport function objectPropertyIsObject<T extends string>(object: Obj, property: T): object is { [t in T]: Obj } {\n let value;\n\n return (\n objectHasOwnProperty(object, property) && isObject((value = object[property])) && value.constructor === Object\n );\n}\n\nexport function objectPull<T extends Obj, K extends keyof T>(obj: T, key: K): T[K] {\n const value = obj[key];\n\n delete obj[key];\n\n return value;\n}\n\nexport function objectWithout<TObj extends Obj, TKey extends keyof TObj>(obj: TObj, key: TKey): Omit<TObj, TKey>;\nexport function objectWithout<TObj extends object, TKey extends keyof TObj>(obj: TObj, key: TKey): Omit<TObj, TKey>;\nexport function objectWithout<TObj extends Obj, TKey extends keyof TObj>(obj: TObj, keys: TKey[]): Omit<TObj, TKey>;\nexport function objectWithout<TObj extends object, TKey extends keyof TObj>(obj: TObj, keys: TKey[]): Omit<TObj, TKey>;\nexport function objectWithout<TObj extends Obj, TExclude>(\n obj: TObj,\n exclude: TypeGuard<TExclude>,\n): ObjectWithout<TObj, TExclude>;\nexport function objectWithout<TObj extends object, TExclude>(\n obj: TObj,\n exclude: TypeGuard<TExclude>,\n): ObjectWithout<TObj, TExclude>;\n\nexport function objectWithout(obj: Obj, keysOrExclude: string | string[] | TypeGuard): unknown {\n if (typeof keysOrExclude === 'function') {\n const exclude = keysOrExclude;\n const cleanObject = {} as Record<string, unknown>;\n\n for (const [key, value] of Object.entries(obj)) {\n if (exclude(value)) {\n continue;\n }\n\n cleanObject[key] = value;\n }\n\n return cleanObject;\n }\n\n const newObject = { ...obj };\n const keysArray = Array.isArray(keysOrExclude) ? keysOrExclude : [keysOrExclude];\n\n for (const key of keysArray) {\n delete newObject[key];\n }\n\n return newObject;\n}\n\nexport function objectWithoutEmpty<T extends Obj>(obj: T): ObjectWithout<T, null | undefined>;\nexport function objectWithoutEmpty<T extends object>(obj: T): ObjectWithout<T, null | undefined>;\nexport function objectWithoutEmpty<T extends Obj>(obj: T): ObjectWithout<T, null | undefined> {\n return objectWithout(obj, (value): value is null | undefined => value === null || value === undefined);\n}\n\nexport function overridePrototypeMethod<T, K extends GetObjectMethods<T>>(\n target: Constructor<T>,\n method: K,\n implementation: T[K],\n): void {\n target.prototype[method] = implementation;\n}\n\nexport function toString(value: unknown): string {\n return String(value);\n}\n\nexport function toError(value: unknown): Error {\n if (value instanceof Error) {\n return value;\n }\n\n return new Error(toString(value));\n}\n"],"mappings":";AAgEA,SAAgB,WAAW,GAAY,GAAqB;CACxD,IAAI,MAAM,GAAG,OAAO;CAEpB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,SAAS,CAAC,GAAG,OAAO;CAEzC,IAAI,aAAa,QAAQ,aAAa,MAAM,OAAO,EAAE,QAAQ,MAAM,EAAE,QAAQ;CAE7E,IAAI,OAAO,KAAK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OAAO,WAAW;EACzB,IAAI,EAAE,OAAO,MAAM;EAEnB,UAAU,OAAO,IAAI;CACzB;CAEA,OAAO;AACX;AAEA,SAAgB,uBAAyC,QAAa,UAA0C;CAC5G,IAAI;CAEJ,OACI,qBAAqB,QAAQ,QAAQ,KAAK,SAAU,QAAQ,OAAO,SAAU,KAAK,MAAM,gBAAgB;AAEhH;AAEA,SAAgB,WAA6C,KAAQ,KAAc;CAC/E,MAAM,QAAQ,IAAI;CAElB,OAAO,IAAI;CAEX,OAAO;AACX;AAeA,SAAgB,cAAc,KAAU,eAAuD;CAC3F,IAAI,OAAO,kBAAkB,YAAY;EACrC,MAAM,UAAU;EAChB,MAAM,cAAc,CAAC;EAErB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAAG;GAC5C,IAAI,QAAQ,KAAK,GACb;GAGJ,YAAY,OAAO;EACvB;EAEA,OAAO;CACX;CAEA,MAAM,YAAY,EAAE,GAAG,IAAI;CAC3B,MAAM,YAAY,MAAM,QAAQ,aAAa,IAAI,gBAAgB,CAAC,aAAa;CAE/E,KAAK,MAAM,OAAO,WACd,OAAO,UAAU;CAGrB,OAAO;AACX;AAIA,SAAgB,mBAAkC,KAA4C;CAC1F,OAAO,cAAc,MAAM,UAAqC,UAAU,QAAQ,UAAU,KAAA,CAAS;AACzG;AAEA,SAAgB,wBACZ,QACA,QACA,gBACI;CACJ,OAAO,UAAU,UAAU;AAC/B;AAEA,SAAgB,SAAS,OAAwB;CAC7C,OAAO,OAAO,KAAK;AACvB;AAEA,SAAgB,QAAQ,OAAuB;CAC3C,IAAI,iBAAiB,OACjB,OAAO;CAGX,OAAO,IAAI,MAAM,SAAS,KAAK,CAAC;AACpC"}
@@ -0,0 +1,10 @@
1
+ import { Closure, ClosureArgs } from "../types/helpers.js";
2
+ //#region src/helpers/promise_helpers.d.ts
3
+ export declare function asyncFirst<TValue, TResult>(values: TValue[], operation: (value: TValue) => Promise<TResult | null>): Promise<TResult | null>;
4
+ export declare function isPromise(p: unknown): p is Promise<unknown>;
5
+ export declare function silenced<Args extends ClosureArgs, Result>(operation: Closure<Args, Promise<Result>>): Closure<Args, Promise<Result | null>>;
6
+ export declare function silenced<Args extends ClosureArgs, Result, Default>(operation: Closure<Args, Promise<Result>>, defaultValue: Default): Closure<Args, Promise<Result | Default>>;
7
+ export declare function silenced<Result>(promise: Promise<Result>): Promise<Result | null>;
8
+ export declare function silenced<Args extends ClosureArgs, Result, Default>(operation: Closure<Args, Promise<Result>>, defaultValue: Default): Closure<Args, Promise<Result | Default>>;
9
+ //#endregion
10
+ //# sourceMappingURL=promise_helpers.d.ts.map
@@ -0,0 +1,25 @@
1
+ //#region src/helpers/promise_helpers.ts
2
+ async function asyncFirst(values, operation) {
3
+ for (const value of values) {
4
+ const result = await operation(value);
5
+ if (!result) continue;
6
+ return result;
7
+ }
8
+ return null;
9
+ }
10
+ function isPromise(p) {
11
+ return "then" in p;
12
+ }
13
+ function silenced(operationOrPromise, defaultValue = null) {
14
+ return typeof operationOrPromise !== "function" ? operationOrPromise.catch(() => defaultValue) : async (...args) => {
15
+ try {
16
+ return await operationOrPromise(...args);
17
+ } catch {
18
+ return defaultValue ?? null;
19
+ }
20
+ };
21
+ }
22
+ //#endregion
23
+ export { asyncFirst, isPromise, silenced };
24
+
25
+ //# sourceMappingURL=promise_helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"promise_helpers.js","names":[],"sources":["../../src/helpers/promise_helpers.ts"],"sourcesContent":["import type { Closure, ClosureArgs } from '@noeldemartin/utils/types';\n\nexport async function asyncFirst<TValue, TResult>(\n values: TValue[],\n operation: (value: TValue) => Promise<TResult | null>,\n): Promise<TResult | null> {\n for (const value of values) {\n const result = await operation(value);\n\n if (!result) {\n continue;\n }\n\n return result;\n }\n\n return null;\n}\n\nexport function isPromise(p: unknown): p is Promise<unknown> {\n return 'then' in (p as Promise<unknown>);\n}\n\nexport function silenced<Args extends ClosureArgs, Result>(\n operation: Closure<Args, Promise<Result>>,\n): Closure<Args, Promise<Result | null>>;\nexport function silenced<Args extends ClosureArgs, Result, Default>(\n operation: Closure<Args, Promise<Result>>,\n defaultValue: Default,\n): Closure<Args, Promise<Result | Default>>;\nexport function silenced<Result>(promise: Promise<Result>): Promise<Result | null>;\nexport function silenced<Args extends ClosureArgs, Result, Default>(\n operation: Closure<Args, Promise<Result>>,\n defaultValue: Default,\n): Closure<Args, Promise<Result | Default>>;\nexport function silenced<Args extends ClosureArgs, Result, Default>(\n operationOrPromise: Closure<Args, Promise<Result>> | Promise<Result>,\n defaultValue: Default | null = null,\n): Closure<Args, Promise<Result | Default | null>> | Promise<Result | Default | null> {\n return typeof operationOrPromise !== 'function'\n ? operationOrPromise.catch(() => defaultValue)\n : async (...args: Args) => {\n try {\n return await operationOrPromise(...args);\n } catch {\n return defaultValue ?? null;\n }\n };\n}\n"],"mappings":";AAEA,eAAsB,WAClB,QACA,WACuB;CACvB,KAAK,MAAM,SAAS,QAAQ;EACxB,MAAM,SAAS,MAAM,UAAU,KAAK;EAEpC,IAAI,CAAC,QACD;EAGJ,OAAO;CACX;CAEA,OAAO;AACX;AAEA,SAAgB,UAAU,GAAmC;CACzD,OAAO,UAAW;AACtB;AAcA,SAAgB,SACZ,oBACA,eAA+B,MACmD;CAClF,OAAO,OAAO,uBAAuB,aAC/B,mBAAmB,YAAY,YAAY,IAC3C,OAAO,GAAG,SAAe;EACrB,IAAI;GACA,OAAO,MAAM,mBAAmB,GAAG,IAAI;EAC3C,QAAQ;GACJ,OAAO,gBAAgB;EAC3B;CACJ;AACV"}
@@ -0,0 +1,21 @@
1
+ import { __exportAll } from "../_virtual/_rolldown/runtime.js";
2
+ import { uuid as uuid$1 } from "./identity_helpers.js";
3
+ //#region src/helpers/replacements-scope.ts
4
+ var replacements_scope_exports = /* @__PURE__ */ __exportAll({
5
+ date: () => date,
6
+ now: () => now,
7
+ uuid: () => uuid
8
+ });
9
+ function date(description) {
10
+ return new Date(Date.parse(description)).toISOString();
11
+ }
12
+ function now() {
13
+ return (/* @__PURE__ */ new Date()).toISOString();
14
+ }
15
+ function uuid() {
16
+ return uuid$1();
17
+ }
18
+ //#endregion
19
+ export { date, now, replacements_scope_exports, uuid };
20
+
21
+ //# sourceMappingURL=replacements-scope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replacements-scope.js","names":["generateUUID"],"sources":["../../src/helpers/replacements-scope.ts"],"sourcesContent":["import { uuid as generateUUID } from '@noeldemartin/utils/helpers/identity_helpers';\n\nexport interface ReplacementsScope {}\n\nexport function date(description: string): string {\n return new Date(Date.parse(description)).toISOString();\n}\n\nexport function now(): string {\n return new Date().toISOString();\n}\n\nexport function uuid(this: ReplacementsScope): string {\n return generateUUID();\n}\n"],"mappings":";;;;;;;;AAIA,SAAgB,KAAK,aAA6B;CAC9C,OAAO,IAAI,KAAK,KAAK,MAAM,WAAW,CAAC,CAAC,CAAC,YAAY;AACzD;AAEA,SAAgB,MAAc;CAC1B,wBAAO,IAAI,KAAK,EAAA,CAAE,YAAY;AAClC;AAEA,SAAgB,OAAsC;CAClD,OAAOA,OAAa;AACxB"}
@@ -0,0 +1,5 @@
1
+ //#region src/helpers/replacements.d.ts
2
+ export type Replacements = Record<string, unknown>;
3
+ export declare function applyReplacements(text: string, replacements?: Replacements): string;
4
+ //#endregion
5
+ //# sourceMappingURL=replacements.d.ts.map
@@ -0,0 +1,34 @@
1
+ import { toString } from "./object_helpers.js";
2
+ import { stringMatch, stringMatchAll } from "./string_helpers.js";
3
+ import { replacements_scope_exports } from "./replacements-scope.js";
4
+ //#region src/helpers/replacements.ts
5
+ function renderReplacement(script, scope) {
6
+ try {
7
+ return Function(`with (this) { return (${script}).toString() }`).bind({
8
+ ...replacements_scope_exports,
9
+ ...scope
10
+ })();
11
+ } catch (error) {
12
+ const undefinedVariable = stringMatch(toString(error), /([^\s]+) is not defined/)?.[1];
13
+ if (!undefinedVariable) throw error;
14
+ return renderReplacement(script, {
15
+ ...scope,
16
+ [undefinedVariable]: void 0
17
+ });
18
+ }
19
+ }
20
+ const REPLACEMENTS_REGEX = /{{([^}]+)}}/gm;
21
+ function reduce(items, initial, callback) {
22
+ let result = initial;
23
+ for (const item of items) result = callback(result, item);
24
+ return result;
25
+ }
26
+ function applyReplacements(text, replacements = {}) {
27
+ return reduce(stringMatchAll(text, REPLACEMENTS_REGEX), text, (renderedText, match) => {
28
+ return renderedText.replace(match[0], renderReplacement(match[1], replacements));
29
+ });
30
+ }
31
+ //#endregion
32
+ export { applyReplacements };
33
+
34
+ //# sourceMappingURL=replacements.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replacements.js","names":["replacementsScope"],"sources":["../../src/helpers/replacements.ts"],"sourcesContent":["import { toString } from '@noeldemartin/utils/helpers/object_helpers';\nimport { stringMatch, stringMatchAll } from '@noeldemartin/utils/helpers/string_helpers';\n\nimport * as replacementsScope from './replacements-scope';\nimport type { ReplacementsScope } from './replacements-scope';\n\nfunction renderReplacement(script: string, scope: ReplacementsScope): string {\n try {\n // oxlint-disable-next-line typescript/no-implied-eval\n return Function(`with (this) { return (${script}).toString() }`).bind({\n ...replacementsScope,\n ...scope,\n })();\n } catch (error) {\n const undefinedVariable = stringMatch<2>(toString(error), /([^\\s]+) is not defined/)?.[1];\n\n if (!undefinedVariable) {\n throw error;\n }\n\n return renderReplacement(script, {\n ...scope,\n [undefinedVariable]: undefined,\n });\n }\n}\n\nconst REPLACEMENTS_REGEX = /{{([^}]+)}}/gm;\n\nfunction reduce<TItem, TResult>(\n items: IterableIterator<TItem>,\n initial: TResult,\n callback: (result: TResult, item: TItem) => TResult,\n) {\n let result = initial;\n\n for (const item of items) {\n result = callback(result, item);\n }\n\n return result;\n}\n\nexport type Replacements = Record<string, unknown>;\n\nexport function applyReplacements(text: string, replacements: Replacements = {}): string {\n const matches = stringMatchAll<2>(text, REPLACEMENTS_REGEX);\n\n return reduce(matches, text, (renderedText, match) => {\n return renderedText.replace(match[0], renderReplacement(match[1], replacements));\n });\n}\n"],"mappings":";;;;AAMA,SAAS,kBAAkB,QAAgB,OAAkC;CACzE,IAAI;EAEA,OAAO,SAAS,yBAAyB,OAAO,eAAe,CAAC,CAAC,KAAK;GAClE,GAAGA;GACH,GAAG;EACP,CAAC,CAAC,CAAC;CACP,SAAS,OAAO;EACZ,MAAM,oBAAoB,YAAe,SAAS,KAAK,GAAG,yBAAyB,CAAC,GAAG;EAEvF,IAAI,CAAC,mBACD,MAAM;EAGV,OAAO,kBAAkB,QAAQ;GAC7B,GAAG;IACF,oBAAoB,KAAA;EACzB,CAAC;CACL;AACJ;AAEA,MAAM,qBAAqB;AAE3B,SAAS,OACL,OACA,SACA,UACF;CACE,IAAI,SAAS;CAEb,KAAK,MAAM,QAAQ,OACf,SAAS,SAAS,QAAQ,IAAI;CAGlC,OAAO;AACX;AAIA,SAAgB,kBAAkB,MAAc,eAA6B,CAAC,GAAW;CAGrF,OAAO,OAFS,eAAkB,MAAM,kBAEpB,GAAG,OAAO,cAAc,UAAU;EAClD,OAAO,aAAa,QAAQ,MAAM,IAAI,kBAAkB,MAAM,IAAI,YAAY,CAAC;CACnF,CAAC;AACL"}
@@ -0,0 +1,4 @@
1
+ //#region src/helpers/runtime_helpers.d.ts
2
+ export declare function runtimeGlobal<T = any>(): T;
3
+ //#endregion
4
+ //# sourceMappingURL=runtime_helpers.d.ts.map
@@ -0,0 +1,8 @@
1
+ //#region src/helpers/runtime_helpers.ts
2
+ function runtimeGlobal() {
3
+ return typeof global !== "undefined" ? global : typeof globalThis !== "undefined" ? globalThis : window;
4
+ }
5
+ //#endregion
6
+ export { runtimeGlobal };
7
+
8
+ //# sourceMappingURL=runtime_helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime_helpers.js","names":[],"sources":["../../src/helpers/runtime_helpers.ts"],"sourcesContent":["// oxlint-disable-next-line typescript/no-explicit-any\nexport function runtimeGlobal<T = any>(): T {\n return typeof global !== 'undefined'\n ? (global as T)\n : typeof globalThis !== 'undefined'\n ? (globalThis as T)\n : (window as T);\n}\n"],"mappings":";AACA,SAAgB,gBAA4B;CACxC,OAAO,OAAO,WAAW,cAClB,SACD,OAAO,eAAe,cACnB,aACA;AACb"}
@@ -0,0 +1,17 @@
1
+ import { Branded } from "../types/helpers.js";
2
+ import { ArrayItem, Tuple } from "../types/arrays.js";
3
+ //#region src/helpers/string_helpers.d.ts
4
+ export type Slug = Branded<string, 'slug'>;
5
+ export declare function stringCapitalize(text: string): string;
6
+ export declare function stringExcerpt(text: string, maxLength?: number, filler?: string): string;
7
+ export declare function stringMatch<Length extends number, Optional extends number = number>(text: string, pattern: RegExp): Tuple<ArrayItem<RegExpMatchArray>, Length, Optional> | null;
8
+ export declare function stringMatchAll<Length extends number, Optional extends number = number>(text: string, pattern: RegExp): IterableIterator<Tuple<ArrayItem<RegExpMatchArray>, Length, Optional>>;
9
+ export declare function stringReverse(text: string): string;
10
+ export declare function stringSplitWords(text: string): string[];
11
+ export declare function stringToCamelCase(text: string): string;
12
+ export declare function stringToSlug(text: string, separator?: string): Slug;
13
+ export declare function stringToStudlyCase(text: string): string;
14
+ export declare function stringToTitleCase(text: string): string;
15
+ export declare function stringTrimmed(text: string): string;
16
+ //#endregion
17
+ //# sourceMappingURL=string_helpers.d.ts.map
@@ -0,0 +1,42 @@
1
+ //#region src/helpers/string_helpers.ts
2
+ function stringCapitalize(text) {
3
+ return text[0]?.toUpperCase() + text.slice(1);
4
+ }
5
+ function stringExcerpt(text, maxLength = 300, filler = "...") {
6
+ if (text.length < maxLength) return text;
7
+ return text.substring(0, maxLength - filler.length) + filler;
8
+ }
9
+ function stringMatch(text, pattern) {
10
+ return text.match(pattern);
11
+ }
12
+ function stringMatchAll(text, pattern) {
13
+ return text.matchAll(pattern);
14
+ }
15
+ function stringReverse(text) {
16
+ return text.split("").reverse().join("");
17
+ }
18
+ function stringSplitWords(text) {
19
+ return text.split(/_|-|\s|(?=[A-Z])/);
20
+ }
21
+ function stringToCamelCase(text) {
22
+ const [firstWord, ...otherWords] = stringSplitWords(text);
23
+ return (firstWord ?? "").toLowerCase() + otherWords.map((word) => word.slice(0, 1).toUpperCase() + word.slice(1).toLowerCase()).join("");
24
+ }
25
+ function stringToSlug(text, separator = "-") {
26
+ text = text.normalize("NFD").replace(/[֊־᐀‐‑‒–—―⸗⸚⸺⸻~〜〰゠︱︲﹘﹣-(){}><[\]]/g, " ").replace(/[\u0300-\u036f]/g, "").replace(/[\u3000-\u303f]/g, "").replace(/['".,#!$%/\\^&*;:=`@+?]/g, "").toLowerCase().trim().replace(/\s+/g, separator);
27
+ if (separator.length > 0) text = text.replace(new RegExp(`${separator}+`, "g"), separator);
28
+ return text;
29
+ }
30
+ function stringToStudlyCase(text) {
31
+ return stringSplitWords(text).map((word) => word.slice(0, 1).toUpperCase() + word.slice(1).toLowerCase()).join("");
32
+ }
33
+ function stringToTitleCase(text) {
34
+ return stringSplitWords(text).map((word) => word.slice(0, 1).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
35
+ }
36
+ function stringTrimmed(text) {
37
+ return text.trim();
38
+ }
39
+ //#endregion
40
+ export { stringCapitalize, stringExcerpt, stringMatch, stringMatchAll, stringReverse, stringSplitWords, stringToCamelCase, stringToSlug, stringToStudlyCase, stringToTitleCase, stringTrimmed };
41
+
42
+ //# sourceMappingURL=string_helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"string_helpers.js","names":[],"sources":["../../src/helpers/string_helpers.ts"],"sourcesContent":["import type { ArrayItem, Branded, Tuple } from '@noeldemartin/utils/types';\n\nexport type Slug = Branded<string, 'slug'>;\n\nexport function stringCapitalize(text: string): string {\n return text[0]?.toUpperCase() + text.slice(1);\n}\n\nexport function stringExcerpt(text: string, maxLength: number = 300, filler: string = '...'): string {\n if (text.length < maxLength) return text;\n\n return text.substring(0, maxLength - filler.length) + filler;\n}\n\nexport function stringMatch<Length extends number, Optional extends number = number>(\n text: string,\n pattern: RegExp,\n): Tuple<ArrayItem<RegExpMatchArray>, Length, Optional> | null {\n return text.match(pattern) as Tuple<ArrayItem<RegExpMatchArray>, Length, Optional> | null;\n}\n\nexport function stringMatchAll<Length extends number, Optional extends number = number>(\n text: string,\n pattern: RegExp,\n): IterableIterator<Tuple<ArrayItem<RegExpMatchArray>, Length, Optional>> {\n return text.matchAll(pattern) as IterableIterator<Tuple<ArrayItem<RegExpMatchArray>, Length, Optional>>;\n}\n\nexport function stringReverse(text: string): string {\n return text.split('').reverse().join('');\n}\n\nexport function stringSplitWords(text: string): string[] {\n return text.split(/_|-|\\s|(?=[A-Z])/);\n}\n\nexport function stringToCamelCase(text: string): string {\n const [firstWord, ...otherWords] = stringSplitWords(text);\n\n return (\n (firstWord ?? '').toLowerCase() +\n otherWords.map((word) => word.slice(0, 1).toUpperCase() + word.slice(1).toLowerCase()).join('')\n );\n}\n\nexport function stringToSlug(text: string, separator: string = '-'): Slug {\n text = text\n .normalize('NFD')\n .replace(/[֊־᐀‐‑‒–—―⸗⸚⸺⸻~〜〰゠︱︲﹘﹣-(){}><[\\]]/g, ' ')\n .replace(/[\\u0300-\\u036f]/g, '') // Remove diacritical marks\n .replace(/[\\u3000-\\u303f]/g, '') // Remove punctuation\n .replace(/['\".,#!$%/\\\\^&*;:=`@+?]/g, '') // Remove special characters\n .toLowerCase()\n .trim()\n .replace(/\\s+/g, separator);\n\n if (separator.length > 0) {\n text = text.replace(new RegExp(`${separator}+`, 'g'), separator);\n }\n\n return text as Slug;\n}\n\nexport function stringToStudlyCase(text: string): string {\n const words = stringSplitWords(text);\n\n return words.map((word) => word.slice(0, 1).toUpperCase() + word.slice(1).toLowerCase()).join('');\n}\n\nexport function stringToTitleCase(text: string): string {\n const words = stringSplitWords(text);\n\n return words.map((word) => word.slice(0, 1).toUpperCase() + word.slice(1).toLowerCase()).join(' ');\n}\n\nexport function stringTrimmed(text: string): string {\n return text.trim();\n}\n"],"mappings":";AAIA,SAAgB,iBAAiB,MAAsB;CACnD,OAAO,KAAK,EAAE,EAAE,YAAY,IAAI,KAAK,MAAM,CAA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AC,YAAY,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,EAAE;AACpG;AAEA,SAAgB,kBAAkB,MAAsB;CAGpD,OAFc,iBAAiB,IAEpB,CAAC,CAAC,KAAK,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC,CAAC,YAAY,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,GAAG;AACrG;AAEA,SAAgB,cAAc,MAAsB;CAChD,OAAO,KAAK,KAAK;AACrB"}
@@ -0,0 +1,15 @@
1
+ //#region src/helpers/time_constants.d.ts
2
+ export declare const MINUTE_MILLISECONDS: number;
3
+ export declare const HOUR_MILLISECONDS: number;
4
+ export declare const DAY_MILLISECONDS: number;
5
+ export declare const WEEK_MILLISECONDS: number;
6
+ export declare const MONTH_MILLISECONDS: number;
7
+ export declare const YEAR_MILLISECONDS: number;
8
+ export declare const MINUTE_SECONDS = 60;
9
+ export declare const HOUR_SECONDS: number;
10
+ export declare const DAY_SECONDS: number;
11
+ export declare const WEEK_SECONDS: number;
12
+ export declare const MONTH_SECONDS: number;
13
+ export declare const YEAR_SECONDS: number;
14
+ //#endregion
15
+ //# sourceMappingURL=time_constants.d.ts.map
@@ -0,0 +1,17 @@
1
+ //#region src/helpers/time_constants.ts
2
+ const MINUTE_MILLISECONDS = 6e4;
3
+ const HOUR_MILLISECONDS = 60 * MINUTE_MILLISECONDS;
4
+ const DAY_MILLISECONDS = 24 * HOUR_MILLISECONDS;
5
+ const WEEK_MILLISECONDS = 7 * DAY_MILLISECONDS;
6
+ const MONTH_MILLISECONDS = 30 * DAY_MILLISECONDS;
7
+ const YEAR_MILLISECONDS = 365 * DAY_MILLISECONDS;
8
+ const MINUTE_SECONDS = 60;
9
+ const HOUR_SECONDS = 3600;
10
+ const DAY_SECONDS = 24 * HOUR_SECONDS;
11
+ const WEEK_SECONDS = 7 * DAY_SECONDS;
12
+ const MONTH_SECONDS = 30 * DAY_SECONDS;
13
+ const YEAR_SECONDS = 365 * DAY_SECONDS;
14
+ //#endregion
15
+ export { DAY_MILLISECONDS, DAY_SECONDS, HOUR_MILLISECONDS, HOUR_SECONDS, MINUTE_MILLISECONDS, MINUTE_SECONDS, MONTH_MILLISECONDS, MONTH_SECONDS, WEEK_MILLISECONDS, WEEK_SECONDS, YEAR_MILLISECONDS, YEAR_SECONDS };
16
+
17
+ //# sourceMappingURL=time_constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"time_constants.js","names":[],"sources":["../../src/helpers/time_constants.ts"],"sourcesContent":["export const MINUTE_MILLISECONDS = 60 * 1000;\nexport const HOUR_MILLISECONDS = 60 * MINUTE_MILLISECONDS;\nexport const DAY_MILLISECONDS = 24 * HOUR_MILLISECONDS;\nexport const WEEK_MILLISECONDS = 7 * DAY_MILLISECONDS;\nexport const MONTH_MILLISECONDS = 30 * DAY_MILLISECONDS;\nexport const YEAR_MILLISECONDS = 365 * DAY_MILLISECONDS;\n\nexport const MINUTE_SECONDS = 60;\nexport const HOUR_SECONDS = 60 * MINUTE_SECONDS;\nexport const DAY_SECONDS = 24 * HOUR_SECONDS;\nexport const WEEK_SECONDS = 7 * DAY_SECONDS;\nexport const MONTH_SECONDS = 30 * DAY_SECONDS;\nexport const YEAR_SECONDS = 365 * DAY_SECONDS;\n"],"mappings":";AAAA,MAAa,sBAAsB;AACnC,MAAa,oBAAoB,KAAK;AACtC,MAAa,mBAAmB,KAAK;AACrC,MAAa,oBAAoB,IAAI;AACrC,MAAa,qBAAqB,KAAK;AACvC,MAAa,oBAAoB,MAAM;AAEvC,MAAa,iBAAiB;AAC9B,MAAa,eAAe;AAC5B,MAAa,cAAc,KAAK;AAChC,MAAa,eAAe,IAAI;AAChC,MAAa,gBAAgB,KAAK;AAClC,MAAa,eAAe,MAAM"}
@@ -0,0 +1,24 @@
1
+ import { ClosureArgs } from "../types/helpers.js";
2
+ //#region src/helpers/time_helpers.d.ts
3
+ export interface DebouncedFunction<Args extends ClosureArgs> {
4
+ (...args: Args): void;
5
+ cancel(): void;
6
+ }
7
+ export interface AfterOptions {
8
+ ms?: number;
9
+ milliseconds?: number;
10
+ s?: number;
11
+ seconds?: number;
12
+ }
13
+ export declare function after(ms: number): Promise<void>;
14
+ export declare function after(options?: AfterOptions): Promise<void>;
15
+ export declare function sleep(ms: number): Promise<void>;
16
+ export declare function sleep(options?: AfterOptions): Promise<void>;
17
+ export declare function afterAnimationFrame(): Promise<void>;
18
+ export declare function debounce<Args extends ClosureArgs>(callback: (...args: Args) => unknown, delay: number): DebouncedFunction<Args>;
19
+ export declare function throttle<Args extends ClosureArgs>(callback: (...args: Args) => unknown, delay?: number): (...args: Args) => void;
20
+ export declare function forever(): Promise<void>;
21
+ export declare function isValidDateString(value: string): boolean;
22
+ export declare function seconds(time?: Date | number, round?: boolean): number;
23
+ //#endregion
24
+ //# sourceMappingURL=time_helpers.d.ts.map
@@ -0,0 +1,57 @@
1
+ //#region src/helpers/time_helpers.ts
2
+ function after(msOrOptions = {}) {
3
+ const time = typeof msOrOptions === "number" ? msOrOptions : (msOrOptions.milliseconds || msOrOptions.ms || 0) + (msOrOptions.seconds || 0) * 1e3;
4
+ return new Promise((resolve) => setTimeout(resolve, time));
5
+ }
6
+ function sleep(msOrOptions = {}) {
7
+ return after(msOrOptions);
8
+ }
9
+ function afterAnimationFrame() {
10
+ return new Promise((resolve) => requestAnimationFrame(() => resolve()));
11
+ }
12
+ function debounce(callback, delay) {
13
+ let timeout;
14
+ const debouncedCallback = (...args) => {
15
+ debouncedCallback.cancel();
16
+ timeout = setTimeout(() => callback(...args), delay);
17
+ };
18
+ debouncedCallback.cancel = () => clearTimeout(timeout);
19
+ return debouncedCallback;
20
+ }
21
+ function throttle(callback, delay = 100) {
22
+ let trailingArgs = null;
23
+ let timeout = null;
24
+ const throttledCallback = (...args) => {
25
+ if (timeout) {
26
+ trailingArgs = args;
27
+ return;
28
+ }
29
+ callback(...args);
30
+ timeout = setTimeout(() => {
31
+ const nextArgs = trailingArgs;
32
+ trailingArgs = null;
33
+ timeout = null;
34
+ nextArgs && throttledCallback(...nextArgs);
35
+ }, delay);
36
+ };
37
+ return throttledCallback;
38
+ }
39
+ async function forever() {
40
+ await new Promise(() => {});
41
+ }
42
+ function isValidDateString(value) {
43
+ if (typeof value !== "string") return false;
44
+ const date = new Date(value);
45
+ return !isNaN(date.getTime());
46
+ }
47
+ function seconds(time, round = false) {
48
+ if (typeof time === "undefined") return seconds(Date.now(), round);
49
+ else if (typeof time === "number") {
50
+ time = time / 1e3;
51
+ return round ? Math.round(time) : time;
52
+ } else return seconds(time.getTime(), round);
53
+ }
54
+ //#endregion
55
+ export { after, afterAnimationFrame, debounce, forever, isValidDateString, seconds, sleep, throttle };
56
+
57
+ //# sourceMappingURL=time_helpers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"time_helpers.js","names":[],"sources":["../../src/helpers/time_helpers.ts"],"sourcesContent":["import type { ClosureArgs } from '@noeldemartin/utils/types';\n\nexport interface DebouncedFunction<Args extends ClosureArgs> {\n (...args: Args): void;\n cancel(): void;\n}\n\nexport interface AfterOptions {\n ms?: number;\n milliseconds?: number;\n s?: number;\n seconds?: number;\n}\n\nexport function after(ms: number): Promise<void>;\nexport function after(options?: AfterOptions): Promise<void>;\nexport function after(msOrOptions: number | AfterOptions = {}): Promise<void> {\n const time =\n typeof msOrOptions === 'number'\n ? msOrOptions\n : (msOrOptions.milliseconds || msOrOptions.ms || 0) + (msOrOptions.seconds || 0) * 1000;\n\n return new Promise((resolve) => setTimeout(resolve, time));\n}\n\nexport function sleep(ms: number): Promise<void>;\nexport function sleep(options?: AfterOptions): Promise<void>;\nexport function sleep(msOrOptions: number | AfterOptions = {}): Promise<void> {\n return after(msOrOptions as number);\n}\n\nexport function afterAnimationFrame(): Promise<void> {\n return new Promise((resolve) => requestAnimationFrame(() => resolve()));\n}\n\nexport function debounce<Args extends ClosureArgs>(\n callback: (...args: Args) => unknown,\n delay: number,\n): DebouncedFunction<Args> {\n let timeout: unknown;\n\n const debouncedCallback: DebouncedFunction<Args> = (...args: Args) => {\n debouncedCallback.cancel();\n timeout = setTimeout(() => callback(...args), delay);\n };\n\n debouncedCallback.cancel = () => clearTimeout(timeout as number);\n\n return debouncedCallback;\n}\n\nexport function throttle<Args extends ClosureArgs>(\n callback: (...args: Args) => unknown,\n delay: number = 100,\n): (...args: Args) => void {\n let trailingArgs: Args | null = null;\n let timeout: ReturnType<typeof setTimeout> | null = null;\n\n const throttledCallback = (...args: Args) => {\n if (timeout) {\n trailingArgs = args;\n\n return;\n }\n\n callback(...args);\n\n timeout = setTimeout(() => {\n const nextArgs = trailingArgs;\n\n trailingArgs = null;\n timeout = null;\n\n nextArgs && throttledCallback(...nextArgs);\n }, delay);\n };\n\n return throttledCallback;\n}\n\nexport async function forever(): Promise<void> {\n await new Promise(() => {\n // Nothing to do here.\n });\n}\n\nexport function isValidDateString(value: string): boolean {\n if (typeof value !== 'string') return false;\n\n const date = new Date(value);\n\n return !isNaN(date.getTime());\n}\n\nexport function seconds(time?: Date | number, round: boolean = false): number {\n if (typeof time === 'undefined') {\n return seconds(Date.now(), round);\n } else if (typeof time === 'number') {\n time = time / 1000;\n return round ? Math.round(time) : time;\n } else {\n return seconds(time.getTime(), round);\n }\n}\n"],"mappings":";AAgBA,SAAgB,MAAM,cAAqC,CAAC,GAAkB;CAC1E,MAAM,OACF,OAAO,gBAAgB,WACjB,eACC,YAAY,gBAAgB,YAAY,MAAM,MAAM,YAAY,WAAW,KAAK;CAE3F,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,IAAI,CAAC;AAC7D;AAIA,SAAgB,MAAM,cAAqC,CAAC,GAAkB;CAC1E,OAAO,MAAM,WAAqB;AACtC;AAEA,SAAgB,sBAAqC;CACjD,OAAO,IAAI,SAAS,YAAY,4BAA4B,QAAQ,CAAC,CAAC;AAC1E;AAEA,SAAgB,SACZ,UACA,OACuB;CACvB,IAAI;CAEJ,MAAM,qBAA8C,GAA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