@welshman/lib 0.0.33 → 0.0.35

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 (48) hide show
  1. package/build/src/Context.d.ts +1 -1
  2. package/build/src/{Context.mjs → Context.js} +1 -1
  3. package/build/src/Context.js.map +1 -0
  4. package/build/src/{Deferred.mjs → Deferred.js} +1 -1
  5. package/build/src/Deferred.js.map +1 -0
  6. package/build/src/Emitter.d.ts +1 -1
  7. package/build/src/{Emitter.mjs → Emitter.js} +3 -3
  8. package/build/src/Emitter.js.map +1 -0
  9. package/build/src/{LRUCache.mjs → LRUCache.js} +5 -4
  10. package/build/src/LRUCache.js.map +1 -0
  11. package/build/src/Tools.d.ts +11 -5
  12. package/build/src/{Tools.mjs → Tools.js} +35 -15
  13. package/build/src/Tools.js.map +1 -0
  14. package/build/src/Worker.js +97 -0
  15. package/build/src/Worker.js.map +1 -0
  16. package/build/src/index.d.ts +11 -7
  17. package/build/src/index.js +8 -0
  18. package/build/src/index.js.map +1 -0
  19. package/build/src/normalize-url/{index.mjs → index.js} +7 -8
  20. package/build/src/normalize-url/index.js.map +1 -0
  21. package/build/tsconfig.tsbuildinfo +1 -0
  22. package/package.json +5 -10
  23. package/build/src/Context.cjs +0 -24
  24. package/build/src/Context.cjs.map +0 -1
  25. package/build/src/Context.mjs.map +0 -1
  26. package/build/src/Deferred.cjs +0 -26
  27. package/build/src/Deferred.cjs.map +0 -1
  28. package/build/src/Deferred.mjs.map +0 -1
  29. package/build/src/Emitter.cjs +0 -22
  30. package/build/src/Emitter.cjs.map +0 -1
  31. package/build/src/Emitter.mjs.map +0 -1
  32. package/build/src/LRUCache.cjs +0 -67
  33. package/build/src/LRUCache.cjs.map +0 -1
  34. package/build/src/LRUCache.mjs.map +0 -1
  35. package/build/src/Tools.cjs +0 -993
  36. package/build/src/Tools.cjs.map +0 -1
  37. package/build/src/Tools.mjs.map +0 -1
  38. package/build/src/Worker.cjs +0 -119
  39. package/build/src/Worker.cjs.map +0 -1
  40. package/build/src/Worker.mjs +0 -115
  41. package/build/src/Worker.mjs.map +0 -1
  42. package/build/src/index.cjs +0 -29
  43. package/build/src/index.cjs.map +0 -1
  44. package/build/src/index.mjs +0 -8
  45. package/build/src/index.mjs.map +0 -1
  46. package/build/src/normalize-url/index.cjs +0 -254
  47. package/build/src/normalize-url/index.cjs.map +0 -1
  48. package/build/src/normalize-url/index.mjs.map +0 -1
@@ -1,993 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.toggle = exports.without = exports.remove = exports.difference = exports.intersection = exports.union = exports.append = exports.concat = exports.sleep = exports.displayDomain = exports.displayUrl = exports.stripProtocol = exports.randomId = exports.randomInt = exports.within = exports.between = exports.mergeRight = exports.mergeLeft = exports.mapVals = exports.mapKeys = exports.range = exports.pick = exports.omitVals = exports.omit = exports.take = exports.drop = exports.avg = exports.sum = exports.min = exports.max = exports.gte = exports.gt = exports.lte = exports.lt = exports.dec = exports.inc = exports.div = exports.mul = exports.sub = exports.add = exports.num = exports.not = exports.always = exports.identity = exports.last = exports.ffirst = exports.first = exports.noop = exports.ifLet = exports.isNil = void 0;
4
- exports.HOUR = exports.MINUTE = exports.switcher = exports.pushToMapKey = exports.addToMapKey = exports.pushToKey = exports.addToKey = exports.batcher = exports.batch = exports.throttleWithValue = exports.throttle = exports.memoize = exports.once = exports.chunks = exports.chunk = exports.initArray = exports.indexBy = exports.groupBy = exports.sortBy = exports.sort = exports.uniqBy = exports.uniq = exports.partition = exports.flatten = exports.fromPairs = exports.ensureNumber = exports.ensurePlural = exports.toIterable = exports.isIterable = exports.sample = exports.shuffle = exports.choice = exports.insert = exports.splitAt = exports.hash = exports.assoc = exports.prop = exports.ne = exports.eq = exports.nthNe = exports.nthEq = exports.nth = exports.equals = exports.isPojo = exports.ellipsize = exports.tryCatch = exports.setJson = exports.getJson = exports.parseJson = exports.clamp = void 0;
5
- exports.bech32ToHex = exports.hexToBech32 = exports.uploadFile = exports.postJson = exports.fetchJson = exports.ms = exports.ago = exports.now = exports.int = exports.YEAR = exports.QUARTER = exports.MONTH = exports.WEEK = exports.DAY = void 0;
6
- const base_1 = require("@scure/base");
7
- /** Checks if a value is null or undefined */
8
- const isNil = (x) => [null, undefined].includes(x);
9
- exports.isNil = isNil;
10
- /**
11
- * Executes a function if the value is defined
12
- * @param x - The value to check
13
- * @param f - Function to execute if x is defined
14
- * @returns Result of f(x) if x is defined, undefined otherwise
15
- */
16
- const ifLet = (x, f) => x === undefined ? undefined : f(x);
17
- exports.ifLet = ifLet;
18
- /** Function that does nothing and returns undefined */
19
- const noop = (...args) => undefined;
20
- exports.noop = noop;
21
- /**
22
- * Returns the first element of an array
23
- * @param xs - The array
24
- * @returns First element or undefined
25
- */
26
- const first = (xs, ...args) => xs[0];
27
- exports.first = first;
28
- /**
29
- * Returns the first element of the first array in a nested array
30
- * @param xs - Array of arrays
31
- * @returns First element of first array or undefined
32
- */
33
- const ffirst = (xs, ...args) => xs[0][0];
34
- exports.ffirst = ffirst;
35
- /**
36
- * Returns the last element of an array
37
- * @param xs - The array
38
- * @returns Last element or undefined
39
- */
40
- const last = (xs, ...args) => xs[xs.length - 1];
41
- exports.last = last;
42
- /**
43
- * Returns the input value unchanged
44
- * @param x - Any value
45
- * @returns The same value
46
- */
47
- const identity = (x, ...args) => x;
48
- exports.identity = identity;
49
- /**
50
- * Creates a function that always returns the same value
51
- * @param x - Value to return
52
- * @returns Function that returns x
53
- */
54
- const always = (x, ...args) => () => x;
55
- exports.always = always;
56
- /**
57
- * Returns the logical NOT of a value
58
- * @param x - Value to negate
59
- * @returns !x
60
- */
61
- const not = (x, ...args) => !x;
62
- exports.not = not;
63
- /** Converts a Maybe<number> to a number, defaulting to 0 */
64
- const num = (x) => x || 0;
65
- exports.num = num;
66
- /** Adds two numbers, handling undefined values */
67
- const add = (x, y) => (0, exports.num)(x) + (0, exports.num)(y);
68
- exports.add = add;
69
- /** Subtracts two numbers, handling undefined values */
70
- const sub = (x, y) => (0, exports.num)(x) - (0, exports.num)(y);
71
- exports.sub = sub;
72
- /** Multiplies two numbers, handling undefined values */
73
- const mul = (x, y) => (0, exports.num)(x) * (0, exports.num)(y);
74
- exports.mul = mul;
75
- /** Divides two numbers, handling undefined values */
76
- const div = (x, y) => (0, exports.num)(x) / y;
77
- exports.div = div;
78
- /** Increments a number by 1, handling undefined values */
79
- const inc = (x) => (0, exports.add)(x, 1);
80
- exports.inc = inc;
81
- /** Decrements a number by 1, handling undefined values */
82
- const dec = (x) => (0, exports.sub)(x, 1);
83
- exports.dec = dec;
84
- /** Less than comparison, handling undefined values */
85
- const lt = (x, y) => (0, exports.num)(x) < (0, exports.num)(y);
86
- exports.lt = lt;
87
- /** Less than or equal comparison, handling undefined values */
88
- const lte = (x, y) => (0, exports.num)(x) <= (0, exports.num)(y);
89
- exports.lte = lte;
90
- /** Greater than comparison, handling undefined values */
91
- const gt = (x, y) => (0, exports.num)(x) > (0, exports.num)(y);
92
- exports.gt = gt;
93
- /** Greater than or equal comparison, handling undefined values */
94
- const gte = (x, y) => (0, exports.num)(x) >= (0, exports.num)(y);
95
- exports.gte = gte;
96
- /** Returns maximum value in array, handling undefined values */
97
- const max = (xs) => xs.reduce((a, b) => Math.max((0, exports.num)(a), (0, exports.num)(b)), 0);
98
- exports.max = max;
99
- /** Returns minimum value in array, handling undefined values */
100
- const min = (xs) => xs.reduce((a, b) => Math.min((0, exports.num)(a), (0, exports.num)(b)), 0);
101
- exports.min = min;
102
- /** Returns sum of array values, handling undefined values */
103
- const sum = (xs) => xs.reduce((a, b) => (0, exports.add)(a, b), 0);
104
- exports.sum = sum;
105
- /** Returns average of array values, handling undefined values */
106
- const avg = (xs) => (0, exports.sum)(xs) / xs.length;
107
- exports.avg = avg;
108
- /**
109
- * Returns array with first n elements removed
110
- * @param n - Number of elements to drop
111
- * @param xs - Input array
112
- * @returns Array with first n elements removed
113
- */
114
- const drop = (n, xs) => xs.slice(n);
115
- exports.drop = drop;
116
- /**
117
- * Returns first n elements of array
118
- * @param n - Number of elements to take
119
- * @param xs - Input array
120
- * @returns Array of first n elements
121
- */
122
- const take = (n, xs) => xs.slice(0, n);
123
- exports.take = take;
124
- /**
125
- * Creates new object with specified keys removed
126
- * @param ks - Keys to remove
127
- * @param x - Source object
128
- * @returns New object without specified keys
129
- */
130
- const omit = (ks, x) => {
131
- const r = { ...x };
132
- for (const k of ks) {
133
- delete r[k];
134
- }
135
- return r;
136
- };
137
- exports.omit = omit;
138
- /**
139
- * Creates new object excluding entries with specified values
140
- * @param xs - Values to exclude
141
- * @param x - Source object
142
- * @returns New object without entries containing specified values
143
- */
144
- const omitVals = (xs, x) => {
145
- const r = {};
146
- for (const [k, v] of Object.entries(x)) {
147
- if (!xs.includes(v)) {
148
- r[k] = v;
149
- }
150
- }
151
- return r;
152
- };
153
- exports.omitVals = omitVals;
154
- /**
155
- * Creates new object with only specified keys
156
- * @param ks - Keys to keep
157
- * @param x - Source object
158
- * @returns New object with only specified keys
159
- */
160
- const pick = (ks, x) => {
161
- const r = { ...x };
162
- for (const k of Object.keys(x)) {
163
- if (!ks.includes(k)) {
164
- delete r[k];
165
- }
166
- }
167
- return r;
168
- };
169
- exports.pick = pick;
170
- /**
171
- * Generates sequence of numbers from a to b
172
- * @param a - Start number (inclusive)
173
- * @param b - End number (exclusive)
174
- * @param step - Increment between numbers
175
- * @yields Numbers in sequence
176
- */
177
- function* range(a, b, step = 1) {
178
- for (let i = a; i < b; i += step) {
179
- yield i;
180
- }
181
- }
182
- exports.range = range;
183
- /**
184
- * Creates new object with transformed keys
185
- * @param f - Function to transform keys
186
- * @param x - Source object
187
- * @returns Object with transformed keys
188
- */
189
- const mapKeys = (f, x) => {
190
- const r = {};
191
- for (const [k, v] of Object.entries(x)) {
192
- r[f(k)] = v;
193
- }
194
- return r;
195
- };
196
- exports.mapKeys = mapKeys;
197
- /**
198
- * Creates new object with transformed values
199
- * @param f - Function to transform values
200
- * @param x - Source object
201
- * @returns Object with transformed values
202
- */
203
- const mapVals = (f, x) => {
204
- const r = {};
205
- for (const [k, v] of Object.entries(x)) {
206
- r[k] = f(v);
207
- }
208
- return r;
209
- };
210
- exports.mapVals = mapVals;
211
- /**
212
- * Merges two objects, with left object taking precedence
213
- * @param a - Left object
214
- * @param b - Right object
215
- * @returns Merged object with a's properties overriding b's
216
- */
217
- const mergeLeft = (a, b) => ({ ...b, ...a });
218
- exports.mergeLeft = mergeLeft;
219
- /**
220
- * Merges two objects, with right object taking precedence
221
- * @param a - Left object
222
- * @param b - Right object
223
- * @returns Merged object with b's properties overriding a's
224
- */
225
- const mergeRight = (a, b) => ({ ...a, ...b });
226
- exports.mergeRight = mergeRight;
227
- /**
228
- * Checks if a number is between two values (exclusive)
229
- * @param bounds - Lower and upper bounds
230
- * @param n - Number to check
231
- * @returns True if n is between low and high
232
- */
233
- const between = ([low, high], n) => n > low && n < high;
234
- exports.between = between;
235
- /**
236
- * Checks if a number is between two values (inclusive)
237
- * @param bounds - Lower and upper bounds
238
- * @param n - Number to check
239
- * @returns True if n is between low and high
240
- */
241
- const within = ([low, high], n) => n >= low && n <= high;
242
- exports.within = within;
243
- /**
244
- * Generates random integer between min and max (inclusive)
245
- * @param min - Minimum value
246
- * @param max - Maximum value
247
- * @returns Random integer
248
- */
249
- const randomInt = (min = 0, max = 9) => min + Math.round(Math.random() * (max - min));
250
- exports.randomInt = randomInt;
251
- /**
252
- * Generates random string ID
253
- * @returns Random string suitable for use as an ID
254
- */
255
- const randomId = () => Math.random().toString().slice(2);
256
- exports.randomId = randomId;
257
- /**
258
- * Removes protocol (http://, https://, etc) from URL
259
- * @param url - URL to process
260
- * @returns URL without protocol
261
- */
262
- const stripProtocol = (url) => url.replace(/.*:\/\//, "");
263
- exports.stripProtocol = stripProtocol;
264
- /**
265
- * Formats URL for display by removing protocol, www, and trailing slash
266
- * @param url - URL to format
267
- * @returns Formatted URL
268
- */
269
- const displayUrl = (url) => (0, exports.stripProtocol)(url).replace(/^(www\.)?/i, "").replace(/\/$/, "");
270
- exports.displayUrl = displayUrl;
271
- /**
272
- * Extracts and formats domain from URL
273
- * @param url - URL to process
274
- * @returns Formatted domain name
275
- */
276
- const displayDomain = (url) => (0, exports.displayUrl)((0, exports.first)(url.split(/[\/\?]/)));
277
- exports.displayDomain = displayDomain;
278
- /**
279
- * Creates a promise that resolves after specified time
280
- * @param t - Time in milliseconds
281
- * @returns Promise that resolves after t milliseconds
282
- */
283
- const sleep = (t) => new Promise(resolve => setTimeout(resolve, t));
284
- exports.sleep = sleep;
285
- /**
286
- * Concatenates multiple arrays, filtering out null/undefined
287
- * @param xs - Arrays to concatenate
288
- * @returns Combined array
289
- */
290
- const concat = (...xs) => xs.flatMap(x => (0, exports.isNil)(x) ? [] : x);
291
- exports.concat = concat;
292
- /**
293
- * Appends element to array
294
- * @param x - Element to append
295
- * @param xs - Array to append to
296
- * @returns New array with element appended
297
- */
298
- const append = (x, xs) => (0, exports.concat)(xs, [x]);
299
- exports.append = append;
300
- /**
301
- * Creates union of two arrays
302
- * @param a - First array
303
- * @param b - Second array
304
- * @returns Array containing unique elements from both arrays
305
- */
306
- const union = (a, b) => (0, exports.uniq)([...a, ...b]);
307
- exports.union = union;
308
- /**
309
- * Returns elements common to both arrays
310
- * @param a - First array
311
- * @param b - Second array
312
- * @returns Array of elements present in both inputs
313
- */
314
- const intersection = (a, b) => {
315
- const s = new Set(b);
316
- return a.filter(x => s.has(x));
317
- };
318
- exports.intersection = intersection;
319
- /**
320
- * Returns elements in first array not present in second
321
- * @param a - Source array
322
- * @param b - Array of elements to exclude
323
- * @returns Array containing elements unique to first array
324
- */
325
- const difference = (a, b) => {
326
- const s = new Set(b);
327
- return a.filter(x => !s.has(x));
328
- };
329
- exports.difference = difference;
330
- /**
331
- * Removes all instances of an element from array
332
- * @param a - Element to remove
333
- * @param xs - Source array
334
- * @returns New array with element removed
335
- */
336
- const remove = (a, xs) => xs.filter(x => x !== a);
337
- exports.remove = remove;
338
- /**
339
- * Returns elements from second array not present in first
340
- * @param a - Array of elements to exclude
341
- * @param b - Source array
342
- * @returns Filtered array
343
- */
344
- const without = (a, b) => b.filter(x => !a.includes(x));
345
- exports.without = without;
346
- /**
347
- * Toggles presence of element in array
348
- * @param x - Element to toggle
349
- * @param xs - Source array
350
- * @returns New array with element added or removed
351
- */
352
- const toggle = (x, xs) => xs.includes(x) ? (0, exports.remove)(x, xs) : (0, exports.append)(x, xs);
353
- exports.toggle = toggle;
354
- /**
355
- * Constrains number between min and max values
356
- * @param bounds - Minimum and maximum allowed values
357
- * @param n - Number to clamp
358
- * @returns Clamped value
359
- */
360
- const clamp = ([min, max], n) => Math.min(max, Math.max(min, n));
361
- exports.clamp = clamp;
362
- /**
363
- * Safely parses JSON string
364
- * @param json - JSON string to parse
365
- * @returns Parsed object or null if invalid
366
- */
367
- const parseJson = (json) => {
368
- if (!json)
369
- return undefined;
370
- try {
371
- return JSON.parse(json);
372
- }
373
- catch (e) {
374
- return undefined;
375
- }
376
- };
377
- exports.parseJson = parseJson;
378
- /**
379
- * Gets and parses JSON from localStorage
380
- * @param k - Storage key
381
- * @returns Parsed value or undefined if invalid/missing
382
- */
383
- const getJson = (k) => (0, exports.parseJson)(localStorage.getItem(k) || "");
384
- exports.getJson = getJson;
385
- /**
386
- * Stringifies and stores value in localStorage
387
- * @param k - Storage key
388
- * @param v - Value to store
389
- */
390
- const setJson = (k, v) => localStorage.setItem(k, JSON.stringify(v));
391
- exports.setJson = setJson;
392
- /**
393
- * Safely executes function and handles errors
394
- * @param f - Function to execute
395
- * @param onError - Optional error handler
396
- * @returns Function result or undefined if error
397
- */
398
- const tryCatch = (f, onError) => {
399
- try {
400
- const r = f();
401
- if (r instanceof Promise) {
402
- r.catch(e => onError === null || onError === void 0 ? void 0 : onError(e));
403
- }
404
- return r;
405
- }
406
- catch (e) {
407
- onError === null || onError === void 0 ? void 0 : onError(e);
408
- }
409
- return undefined;
410
- };
411
- exports.tryCatch = tryCatch;
412
- /**
413
- * Truncates string to length, breaking at word boundaries
414
- * @param s - String to truncate
415
- * @param l - Maximum length
416
- * @param suffix - String to append if truncated
417
- * @returns Truncated string
418
- */
419
- const ellipsize = (s, l, suffix = '...') => {
420
- if (s.length < l * 1.1) {
421
- return s;
422
- }
423
- while (s.length > l && s.includes(' ')) {
424
- s = s.split(' ').slice(0, -1).join(' ');
425
- }
426
- return s + suffix;
427
- };
428
- exports.ellipsize = ellipsize;
429
- /**
430
- * Checks if value is a plain object
431
- * @param obj - Value to check
432
- * @returns True if value is a plain object
433
- */
434
- const isPojo = (obj) => {
435
- if (obj === null || typeof obj !== "object") {
436
- return false;
437
- }
438
- return Object.getPrototypeOf(obj) === Object.prototype;
439
- };
440
- exports.isPojo = isPojo;
441
- /**
442
- * Deep equality comparison
443
- * @param a - First value
444
- * @param b - Second value
445
- * @returns True if values are deeply equal
446
- */
447
- const equals = (a, b) => {
448
- if (a === b)
449
- return true;
450
- if (a instanceof Set && b instanceof Set) {
451
- a = Array.from(a);
452
- b = Array.from(b);
453
- }
454
- if (a instanceof Set) {
455
- if (!(b instanceof Set) || a.size !== b.size) {
456
- return false;
457
- }
458
- return Array.from(a).every(x => b.has(x));
459
- }
460
- if (Array.isArray(a)) {
461
- if (!Array.isArray(b) || a.length !== b.length) {
462
- return false;
463
- }
464
- for (let i = 0; i < a.length; i++) {
465
- if (!(0, exports.equals)(a[i], b[i])) {
466
- return false;
467
- }
468
- }
469
- return true;
470
- }
471
- if ((0, exports.isPojo)(a)) {
472
- if (!(0, exports.isPojo)(b)) {
473
- return false;
474
- }
475
- const aKeys = Object.keys(a);
476
- const bKeys = Object.keys(b);
477
- if (aKeys.length !== bKeys.length) {
478
- return false;
479
- }
480
- for (const k of aKeys) {
481
- if (!(0, exports.equals)(a[k], b[k])) {
482
- return false;
483
- }
484
- }
485
- return true;
486
- }
487
- return false;
488
- };
489
- exports.equals = equals;
490
- // Curried utils
491
- /** Returns a function that gets the nth element of an array */
492
- const nth = (i) => (xs, ...args) => xs[i];
493
- exports.nth = nth;
494
- /** Returns a function that checks if nth element equals value */
495
- const nthEq = (i, v) => (xs, ...args) => xs[i] === v;
496
- exports.nthEq = nthEq;
497
- /** Returns a function that checks if nth element does not equal value */
498
- const nthNe = (i, v) => (xs, ...args) => xs[i] !== v;
499
- exports.nthNe = nthNe;
500
- /** Returns a function that checks equality with value */
501
- const eq = (v) => (x) => x === v;
502
- exports.eq = eq;
503
- /** Returns a function that checks inequality with value */
504
- const ne = (v) => (x) => x !== v;
505
- exports.ne = ne;
506
- /** Returns a function that gets property value from object */
507
- const prop = (k) => (x) => x[k];
508
- exports.prop = prop;
509
- /** Returns a function that adds/updates property on object */
510
- const assoc = (k, v) => (o) => ({ ...o, [k]: v });
511
- exports.assoc = assoc;
512
- /** Generates a hash string from input string */
513
- const hash = (s) => Math.abs(s.split("").reduce((a, b) => ((a << 5) - a + b.charCodeAt(0)) | 0, 0)).toString();
514
- exports.hash = hash;
515
- // Collections
516
- /** Splits array into two parts at index */
517
- const splitAt = (n, xs) => [xs.slice(0, n), xs.slice(n)];
518
- exports.splitAt = splitAt;
519
- /** Inserts element into array at index */
520
- const insert = (n, x, xs) => [...xs.slice(0, n), x, ...xs.slice(n)];
521
- exports.insert = insert;
522
- /** Returns random element from array */
523
- const choice = (xs) => xs[Math.floor(xs.length * Math.random())];
524
- exports.choice = choice;
525
- /** Returns shuffled copy of iterable */
526
- const shuffle = (xs) => Array.from(xs).sort(() => Math.random() > 0.5 ? 1 : -1);
527
- exports.shuffle = shuffle;
528
- /** Returns n random elements from array */
529
- const sample = (n, xs) => (0, exports.shuffle)(xs).slice(0, n);
530
- exports.sample = sample;
531
- /** Checks if value is iterable */
532
- const isIterable = (x) => Symbol.iterator in Object(x);
533
- exports.isIterable = isIterable;
534
- /** Ensures value is iterable by wrapping in array if needed */
535
- const toIterable = (x) => (0, exports.isIterable)(x) ? x : [x];
536
- exports.toIterable = toIterable;
537
- /** Ensures value is array by wrapping if needed */
538
- const ensurePlural = (x) => (x instanceof Array ? x : [x]);
539
- exports.ensurePlural = ensurePlural;
540
- /** Converts string or number to number */
541
- const ensureNumber = (x) => parseFloat(x);
542
- exports.ensureNumber = ensureNumber;
543
- /**
544
- * Creates object from array of key-value pairs
545
- * @param pairs - Array of [key, value] tuples
546
- * @returns Object with keys and values from pairs
547
- */
548
- const fromPairs = (pairs) => {
549
- const r = {};
550
- for (const [k, v] of pairs) {
551
- if (k && v) {
552
- r[k] = v;
553
- }
554
- }
555
- return r;
556
- };
557
- exports.fromPairs = fromPairs;
558
- /**
559
- * Flattens array of arrays into single array
560
- * @param xs - Array of arrays to flatten
561
- * @returns Flattened array
562
- */
563
- const flatten = (xs) => xs.flatMap(exports.identity);
564
- exports.flatten = flatten;
565
- /**
566
- * Splits array into two arrays based on predicate
567
- * @param f - Function to test elements
568
- * @param xs - Array to partition
569
- * @returns Tuple of [matching, non-matching] arrays
570
- */
571
- const partition = (f, xs) => {
572
- const a = [];
573
- const b = [];
574
- for (const x of xs) {
575
- if (f(x)) {
576
- a.push(x);
577
- }
578
- else {
579
- b.push(x);
580
- }
581
- }
582
- return [a, b];
583
- };
584
- exports.partition = partition;
585
- /**
586
- * Returns array with duplicate elements removed
587
- * @param xs - Array with possible duplicates
588
- * @returns Array with unique elements
589
- */
590
- const uniq = (xs) => Array.from(new Set(xs));
591
- exports.uniq = uniq;
592
- /**
593
- * Returns array with elements unique by key function
594
- * @param f - Function to generate key for each element
595
- * @param xs - Input array
596
- * @returns Array with elements unique by key
597
- */
598
- const uniqBy = (f, xs) => {
599
- const s = new Set();
600
- const r = [];
601
- for (const x of xs) {
602
- const k = f(x);
603
- if (s.has(k)) {
604
- continue;
605
- }
606
- s.add(k);
607
- r.push(x);
608
- }
609
- return r;
610
- };
611
- exports.uniqBy = uniqBy;
612
- /**
613
- * Returns sorted copy of array
614
- * @param xs - Array to sort
615
- * @returns New sorted array
616
- */
617
- const sort = (xs) => [...xs].sort();
618
- exports.sort = sort;
619
- /**
620
- * Returns array sorted by key function
621
- * @param f - Function to generate sort key
622
- * @param xs - Array to sort
623
- * @returns Sorted array
624
- */
625
- const sortBy = (f, xs) => [...xs].sort((a, b) => {
626
- const x = f(a);
627
- const y = f(b);
628
- return x < y ? -1 : x > y ? 1 : 0;
629
- });
630
- exports.sortBy = sortBy;
631
- /**
632
- * Groups array elements by key function
633
- * @param f - Function to generate group key
634
- * @param xs - Array to group
635
- * @returns Map of groups
636
- */
637
- const groupBy = (f, xs) => {
638
- const r = new Map();
639
- for (const x of xs) {
640
- const k = f(x);
641
- let v = r.get(k);
642
- if (!v) {
643
- v = [];
644
- r.set(k, v);
645
- }
646
- v.push(x);
647
- }
648
- return r;
649
- };
650
- exports.groupBy = groupBy;
651
- /**
652
- * Creates map from array using key function
653
- * @param f - Function to generate key
654
- * @param xs - Array to index
655
- * @returns Map of values by key
656
- */
657
- const indexBy = (f, xs) => {
658
- const r = new Map();
659
- for (const x of xs) {
660
- r.set(f(x), x);
661
- }
662
- return r;
663
- };
664
- exports.indexBy = indexBy;
665
- /**
666
- * Creates array of specified length using generator function
667
- * @param n - Length of array
668
- * @param f - Function to generate each element
669
- * @returns Generated array
670
- */
671
- const initArray = (n, f) => {
672
- const result = [];
673
- for (let i = 0; i < n; i++) {
674
- result.push(f());
675
- }
676
- return result;
677
- };
678
- exports.initArray = initArray;
679
- /**
680
- * Splits array into chunks of specified length
681
- * @param chunkLength - Maximum length of each chunk
682
- * @param xs - Array to split
683
- * @returns Array of chunks
684
- */
685
- const chunk = (chunkLength, xs) => {
686
- const result = [];
687
- const current = [];
688
- for (const item of xs) {
689
- if (current.length < chunkLength) {
690
- current.push(item);
691
- }
692
- else {
693
- result.push(current.splice(0));
694
- }
695
- }
696
- if (current.length > 0) {
697
- result.push(current);
698
- }
699
- return result;
700
- };
701
- exports.chunk = chunk;
702
- /**
703
- * Splits array into specified number of chunks
704
- * @param n - Number of chunks
705
- * @param xs - Array to split
706
- * @returns Array of n chunks
707
- */
708
- const chunks = (n, xs) => {
709
- const result = (0, exports.initArray)(n, () => []);
710
- for (let i = 0; i < xs.length; i++) {
711
- result[i % n].push(xs[i]);
712
- }
713
- return result;
714
- };
715
- exports.chunks = chunks;
716
- /**
717
- * Creates function that only executes once
718
- * @param f - Function to wrap
719
- * @returns Function that executes f only on first call
720
- */
721
- const once = (f) => {
722
- let called = false;
723
- return (...args) => {
724
- if (!called) {
725
- called = true;
726
- f(...args);
727
- }
728
- };
729
- };
730
- exports.once = once;
731
- /**
732
- * Memoizes function results based on arguments
733
- * @param f - Function to memoize
734
- * @returns Memoized function
735
- */
736
- const memoize = (f) => {
737
- let prevArgs;
738
- let result;
739
- return (...args) => {
740
- if (!(0, exports.equals)(prevArgs, args)) {
741
- prevArgs = args;
742
- result = f(...args);
743
- }
744
- return result;
745
- };
746
- };
747
- exports.memoize = memoize;
748
- /**
749
- * Creates throttled version of function
750
- * @param ms - Minimum time between calls
751
- * @param f - Function to throttle
752
- * @returns Throttled function
753
- */
754
- const throttle = (ms, f) => {
755
- if (ms === 0) {
756
- return f;
757
- }
758
- let paused = false;
759
- let nextArgs;
760
- const unpause = () => {
761
- if (nextArgs) {
762
- f(...nextArgs);
763
- nextArgs = undefined;
764
- }
765
- paused = false;
766
- };
767
- return (...thisArgs) => {
768
- if (!paused) {
769
- f(...thisArgs);
770
- paused = true;
771
- setTimeout(unpause, ms);
772
- }
773
- else {
774
- nextArgs = thisArgs;
775
- }
776
- };
777
- };
778
- exports.throttle = throttle;
779
- /**
780
- * Creates throttled function that returns cached value
781
- * @param ms - Minimum time between updates
782
- * @param f - Function to throttle
783
- * @returns Function returning latest value
784
- */
785
- const throttleWithValue = (ms, f) => {
786
- let value;
787
- const update = (0, exports.throttle)(ms, () => {
788
- value = f();
789
- });
790
- return () => {
791
- update();
792
- return value;
793
- };
794
- };
795
- exports.throttleWithValue = throttleWithValue;
796
- /**
797
- * Creates batching function that collects items
798
- * @param t - Time window for batching
799
- * @param f - Function to process batch
800
- * @returns Function that adds items to batch
801
- */
802
- const batch = (t, f) => {
803
- const xs = [];
804
- const cb = (0, exports.throttle)(t, () => xs.length > 0 && f(xs.splice(0)));
805
- return (x) => {
806
- xs.push(x);
807
- cb();
808
- };
809
- };
810
- exports.batch = batch;
811
- /**
812
- * Creates batching function that returns results
813
- * @param t - Time window for batching
814
- * @param execute - Function to process batch
815
- * @returns Function that returns promise of result
816
- */
817
- const batcher = (t, execute) => {
818
- const queue = [];
819
- const _execute = async () => {
820
- const items = queue.splice(0);
821
- const results = await execute(items.map(item => item.request));
822
- if (results.length !== items.length) {
823
- throw new Error("Execute must return a result for each request");
824
- }
825
- results.forEach(async (r, i) => items[i].resolve(await r));
826
- };
827
- return (request) => new Promise(resolve => {
828
- if (queue.length === 0) {
829
- setTimeout(_execute, t);
830
- }
831
- queue.push({ request, resolve });
832
- });
833
- };
834
- exports.batcher = batcher;
835
- /**
836
- * Adds value to Set at key in object
837
- * @param m - Object mapping keys to Sets
838
- * @param k - Key to add to
839
- * @param v - Value to add
840
- */
841
- const addToKey = (m, k, v) => {
842
- const s = m[k] || new Set();
843
- s.add(v);
844
- m[k] = s;
845
- };
846
- exports.addToKey = addToKey;
847
- /**
848
- * Pushes value to array at key in object
849
- * @param m - Object mapping keys to arrays
850
- * @param k - Key to push to
851
- * @param v - Value to push
852
- */
853
- const pushToKey = (m, k, v) => {
854
- const a = m[k] || [];
855
- a.push(v);
856
- m[k] = a;
857
- };
858
- exports.pushToKey = pushToKey;
859
- /**
860
- * Adds value to Set at key in Map
861
- * @param m - Map of Sets
862
- * @param k - Key to add to
863
- * @param v - Value to add
864
- */
865
- const addToMapKey = (m, k, v) => {
866
- const s = m.get(k) || new Set();
867
- s.add(v);
868
- m.set(k, s);
869
- };
870
- exports.addToMapKey = addToMapKey;
871
- /**
872
- * Pushes value to array at key in Map
873
- * @param m - Map of arrays
874
- * @param k - Key to push to
875
- * @param v - Value to push
876
- */
877
- const pushToMapKey = (m, k, v) => {
878
- const a = m.get(k) || [];
879
- a.push(v);
880
- m.set(k, a);
881
- };
882
- exports.pushToMapKey = pushToMapKey;
883
- /**
884
- * Switches on key in object, with default fallback
885
- * @param k - Key to look up
886
- * @param m - Object with values and optional default
887
- * @returns Value at key or default value
888
- */
889
- const switcher = (k, m) => m[k] === undefined ? m.default : m[k];
890
- exports.switcher = switcher;
891
- /** One minute in seconds */
892
- exports.MINUTE = 60;
893
- /** One hour in seconds */
894
- exports.HOUR = 60 * exports.MINUTE;
895
- /** One day in seconds */
896
- exports.DAY = 24 * exports.HOUR;
897
- /** One week in seconds */
898
- exports.WEEK = 7 * exports.DAY;
899
- /** One month in seconds (approximate) */
900
- exports.MONTH = 30 * exports.DAY;
901
- /** One quarter in seconds (approximate) */
902
- exports.QUARTER = 90 * exports.DAY;
903
- /** One year in seconds (approximate) */
904
- exports.YEAR = 365 * exports.DAY;
905
- /**
906
- * Multiplies time unit by count
907
- * @param unit - Time unit in seconds
908
- * @param count - Number of units
909
- * @returns Total seconds
910
- */
911
- const int = (unit, count = 1) => unit * count;
912
- exports.int = int;
913
- /** Returns current Unix timestamp in seconds */
914
- const now = () => Math.round(Date.now() / 1000);
915
- exports.now = now;
916
- /**
917
- * Returns Unix timestamp from specified time ago
918
- * @param unit - Time unit in seconds
919
- * @param count - Number of units
920
- * @returns Timestamp in seconds
921
- */
922
- const ago = (unit, count = 1) => (0, exports.now)() - (0, exports.int)(unit, count);
923
- exports.ago = ago;
924
- /**
925
- * Converts seconds to milliseconds
926
- * @param seconds - Time in seconds
927
- * @returns Time in milliseconds
928
- */
929
- const ms = (seconds) => seconds * 1000;
930
- exports.ms = ms;
931
- /**
932
- * Fetches JSON from URL with options
933
- * @param url - URL to fetch from
934
- * @param opts - Fetch options
935
- * @returns Promise of parsed JSON response
936
- */
937
- const fetchJson = async (url, opts = {}) => {
938
- if (!opts.headers) {
939
- opts.headers = {};
940
- }
941
- opts.headers["Accept"] = "application/json";
942
- const res = await fetch(url, opts);
943
- const json = await res.json();
944
- return json;
945
- };
946
- exports.fetchJson = fetchJson;
947
- /**
948
- * Posts JSON data to URL
949
- * @param url - URL to post to
950
- * @param data - Data to send
951
- * @param opts - Additional fetch options
952
- * @returns Promise of parsed JSON response
953
- */
954
- const postJson = async (url, data, opts = {}) => {
955
- if (!opts.method) {
956
- opts.method = "POST";
957
- }
958
- if (!opts.headers) {
959
- opts.headers = {};
960
- }
961
- opts.headers["Content-Type"] = "application/json";
962
- opts.body = JSON.stringify(data);
963
- return (0, exports.fetchJson)(url, opts);
964
- };
965
- exports.postJson = postJson;
966
- /**
967
- * Uploads file to URL
968
- * @param url - Upload URL
969
- * @param file - File to upload
970
- * @returns Promise of parsed JSON response
971
- */
972
- const uploadFile = (url, file) => {
973
- const body = new FormData();
974
- body.append("file", file);
975
- return (0, exports.fetchJson)(url, { method: "POST", body });
976
- };
977
- exports.uploadFile = uploadFile;
978
- /**
979
- * Converts hex string to bech32 format
980
- * @param prefix - Bech32 prefix
981
- * @param hex - Hex string to convert
982
- * @returns Bech32 encoded string
983
- */
984
- const hexToBech32 = (prefix, hex) => base_1.bech32.encode(prefix, base_1.bech32.toWords(base_1.utf8.decode(hex)), false);
985
- exports.hexToBech32 = hexToBech32;
986
- /**
987
- * Converts bech32 string to hex format
988
- * @param b32 - Bech32 string to convert
989
- * @returns Hex encoded string
990
- */
991
- const bech32ToHex = (b32) => base_1.utf8.encode(base_1.bech32.fromWords(base_1.bech32.decode(b32, false).words));
992
- exports.bech32ToHex = bech32ToHex;
993
- //# sourceMappingURL=Tools.cjs.map