@talismn/util 2.1.1 → 2.2.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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
2
+ // \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -20,22 +20,19 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
23
- //#endregion
24
23
  let bignumber_js = require("bignumber.js");
25
24
  bignumber_js = __toESM(bignumber_js);
26
25
  let lodash_es = require("lodash-es");
27
26
  let rxjs = require("rxjs");
28
- //#region src/configureBigNumber.ts
27
+ // src/configureBigNumber.ts
29
28
  bignumber_js.default.set({ STRICT: false });
30
29
  var configureBigNumber_default = bignumber_js.default;
31
- //#endregion
32
- //#region src/addTrailingSlash.ts
30
+ // src/addTrailingSlash.ts
33
31
  const addTrailingSlash = (url) => {
34
32
  if (url.endsWith("/")) return url;
35
33
  return `${url}/`;
36
34
  };
37
- //#endregion
38
- //#region src/assert.ts
35
+ // src/assert.ts
39
36
  /**
40
37
  * @name assert
41
38
  * @description Throws an Error with the given message if the condition is falsy.
@@ -46,8 +43,7 @@ function assert(condition, message) {
46
43
  if (condition) return;
47
44
  throw new Error(typeof message === "function" ? message() : message);
48
45
  }
49
- //#endregion
50
- //#region src/BigMath.ts
46
+ // src/BigMath.ts
51
47
  /**
52
48
  * Javascript's `Math` library for `BigInt`.
53
49
  * Taken from https://stackoverflow.com/questions/51867270/is-there-a-library-similar-to-math-that-supports-javascript-bigint/64953280#64953280
@@ -69,14 +65,12 @@ const BigMath = {
69
65
  return value;
70
66
  }
71
67
  };
72
- //#endregion
73
- //#region src/isHexString.ts
68
+ // src/isHexString.ts
74
69
  const REGEX_HEX_STRING = /^0x[0-9a-fA-F]*$/;
75
70
  const isHexString = (value) => {
76
71
  return typeof value === "string" && REGEX_HEX_STRING.test(value);
77
72
  };
78
- //#endregion
79
- //#region src/bytes.ts
73
+ // src/bytes.ts
80
74
  /**
81
75
  * Byte / hex primitives, drop-in equivalents of the `@polkadot/util` helpers we used to depend on.
82
76
  * Semantics intentionally match polkadot-js for migration safety.
@@ -158,14 +152,12 @@ const u8aUnwrapBytes = (value) => {
158
152
  const u8a = u8aToU8a(value);
159
153
  return u8aIsWrapped(u8a) ? u8a.subarray(U8A_WRAP_PREFIX.length, u8a.length - U8A_WRAP_POSTFIX.length) : u8a;
160
154
  };
161
- //#endregion
162
- //#region src/jsActivityHook.ts
155
+ // src/jsActivityHook.ts
163
156
  const reportJsActivity = (label, durationMs) => {
164
157
  const record = globalThis.__recordJsActivity;
165
158
  if (record) record(label, durationMs);
166
159
  };
167
- //#endregion
168
- //#region src/yieldToEventLoop.ts
160
+ // src/yieldToEventLoop.ts
169
161
  const yieldToEventLoop = () => {
170
162
  const { scheduler } = globalThis;
171
163
  if (typeof scheduler?.postTask === "function") return scheduler.postTask(() => {}, { priority: "background" });
@@ -182,8 +174,7 @@ const yieldToEventLoop = () => {
182
174
  });
183
175
  return new Promise((resolve) => setTimeout(resolve, 0));
184
176
  };
185
- //#endregion
186
- //#region src/timeSlicer.ts
177
+ // src/timeSlicer.ts
187
178
  /**
188
179
  * Default CPU budget for a single synchronous slice of chunked work.
189
180
  * ~50-60% of a 60fps frame, leaving the rest for the host (user interactions, rendering).
@@ -226,8 +217,7 @@ const createTimeSlicer = ({ budgetMs = 10, signal, now = defaultNow, label } = {
226
217
  throwIfAborted
227
218
  };
228
219
  };
229
- //#endregion
230
- //#region src/chunkedArray.ts
220
+ // src/chunkedArray.ts
231
221
  const getSlicer = (options) => options?.slicer ?? createTimeSlicer({
232
222
  budgetMs: options?.budgetMs,
233
223
  signal: options?.signal,
@@ -280,8 +270,7 @@ const arrayItemsEqualWithYield = async (a, b, options) => {
280
270
  }
281
271
  return true;
282
272
  };
283
- //#endregion
284
- //#region src/deferred.ts
273
+ // src/deferred.ts
285
274
  /**
286
275
  * In TypeScript, a deferred promise refers to a pattern that involves creating a promise that can be
287
276
  * resolved or rejected at a later point in time, typically by code outside of the current function scope.
@@ -315,8 +304,7 @@ function Deferred() {
315
304
  isRejected: () => isRejected
316
305
  };
317
306
  }
318
- //#endregion
319
- //#region src/firstThenDebounce.ts
307
+ // src/firstThenDebounce.ts
320
308
  /**
321
309
  * An rxjs operator which:
322
310
  *
@@ -324,8 +312,90 @@ function Deferred() {
324
312
  * 2. Debounces any future values by `timeout` ms.
325
313
  */
326
314
  const firstThenDebounce = (timeout) => (source) => (0, rxjs.concat)(source.pipe((0, rxjs.take)(1)), source.pipe((0, rxjs.skip)(1)).pipe((0, rxjs.debounceTime)(timeout)));
327
- //#endregion
328
- //#region src/formatDecimals.ts
315
+ // src/formatCurrency.ts
316
+ const INTL_CURRENCY_OVERRIDES = {
317
+ btc: {
318
+ symbol: "₿",
319
+ fractionDigits: 6
320
+ },
321
+ eth: {
322
+ symbol: "Ξ",
323
+ fractionDigits: 5
324
+ },
325
+ tao: {
326
+ symbol: "τ",
327
+ fractionDigits: 4
328
+ },
329
+ idr: { fractionDigits: 0 }
330
+ };
331
+ const INTL_MAX_FRACTION_DIGITS = 20;
332
+ const clampFractionDigits = (digits) => digits === void 0 ? void 0 : Math.min(digits, INTL_MAX_FRACTION_DIGITS);
333
+ const fractionDigitsByCurrency = /* @__PURE__ */ new Map();
334
+ const getCurrencyFractionDigits = (currency) => {
335
+ const currencyId = currency.toLowerCase();
336
+ const cached = fractionDigitsByCurrency.get(currencyId);
337
+ if (cached !== void 0) return cached;
338
+ const { maximumFractionDigits: intlFractionDigits = 2 } = new Intl.NumberFormat(void 0, {
339
+ style: "currency",
340
+ currency
341
+ }).resolvedOptions();
342
+ const fractionDigits = INTL_CURRENCY_OVERRIDES[currencyId]?.fractionDigits ?? intlFractionDigits;
343
+ fractionDigitsByCurrency.set(currencyId, fractionDigits);
344
+ return fractionDigits;
345
+ };
346
+ const getDefaultFractionDigits = (currencyId, options) => {
347
+ if ([
348
+ options.minimumFractionDigits,
349
+ options.maximumFractionDigits,
350
+ options.minimumSignificantDigits,
351
+ options.maximumSignificantDigits
352
+ ].some((digits) => digits !== void 0) || options.notation === "compact") return void 0;
353
+ return INTL_CURRENCY_OVERRIDES[currencyId]?.fractionDigits;
354
+ };
355
+ const isSpacing = (part) => part?.type === "literal" && part.value.trim() === "";
356
+ const withTrailingCode = (parts, code) => {
357
+ const currencyIndex = parts.findIndex((part) => part.type === "currency");
358
+ const number = parts.filter((part, index) => index !== currencyIndex && !(isSpacing(part) && Math.abs(index - currencyIndex) === 1));
359
+ while (isSpacing(number[0])) number.shift();
360
+ while (isSpacing(number.at(-1))) number.pop();
361
+ return [
362
+ ...number,
363
+ {
364
+ type: "literal",
365
+ value: " "
366
+ },
367
+ {
368
+ type: "currency",
369
+ value: code
370
+ }
371
+ ];
372
+ };
373
+ const formatCurrencyToParts = (amount, currency, options = {}) => {
374
+ const currencyId = currency.toLowerCase();
375
+ const currencyDisplay = options.currencyDisplay ?? (currencyId === "usd" ? "narrowSymbol" : "symbol");
376
+ const defaultFractionDigits = getDefaultFractionDigits(currencyId, options);
377
+ const intlOptions = {
378
+ ...options,
379
+ style: "currency",
380
+ currency,
381
+ currencyDisplay,
382
+ minimumFractionDigits: clampFractionDigits(options.minimumFractionDigits ?? defaultFractionDigits),
383
+ maximumFractionDigits: clampFractionDigits(options.maximumFractionDigits ?? defaultFractionDigits)
384
+ };
385
+ if (currencyDisplay === "code") return withTrailingCode(new Intl.NumberFormat(void 0, intlOptions).formatToParts(amount), currency.toUpperCase());
386
+ const symbol = currencyDisplay === "name" ? void 0 : INTL_CURRENCY_OVERRIDES[currencyId]?.symbol;
387
+ if (!symbol) return new Intl.NumberFormat(void 0, intlOptions).formatToParts(amount);
388
+ return new Intl.NumberFormat(void 0, {
389
+ ...intlOptions,
390
+ currency: "USD",
391
+ currencyDisplay: "narrowSymbol"
392
+ }).formatToParts(amount).map((part) => part.type === "currency" ? {
393
+ ...part,
394
+ value: symbol
395
+ } : part);
396
+ };
397
+ const formatCurrency = (amount, currency, options = {}) => formatCurrencyToParts(amount, currency, options).map((part) => part.value).join("");
398
+ // src/formatDecimals.ts
329
399
  const MIN_DIGITS = 4;
330
400
  const MAX_DECIMALS_FORMAT = 12;
331
401
  /**
@@ -357,28 +427,39 @@ const formatDecimals = (num, digits = MIN_DIGITS, options = {}, locale = "en-US"
357
427
  ...options
358
428
  }).format(truncatedValue.toNumber());
359
429
  };
360
- //#endregion
361
- //#region src/formatPrice.ts
362
- const formatPrice = (price, currency, compact) => {
363
- return Intl.NumberFormat(void 0, {
364
- style: "currency",
365
- currency,
366
- currencyDisplay: currency === "usd" ? "narrowSymbol" : "symbol",
367
- minimumSignificantDigits: 3,
368
- maximumSignificantDigits: compact ? price < 1 ? 3 : 4 : void 0,
369
- roundingPriority: compact ? "auto" : "morePrecision",
370
- notation: compact ? "compact" : "standard"
371
- }).format(price);
372
- };
373
- //#endregion
374
- //#region src/getErrorMessage.ts
430
+ // src/formatPrice.ts
431
+ const getPriceOptions = (price, compact) => ({
432
+ minimumSignificantDigits: 3,
433
+ maximumSignificantDigits: compact ? price < 1 ? 3 : 4 : void 0,
434
+ roundingPriority: compact ? "auto" : "morePrecision",
435
+ notation: compact ? "compact" : "standard"
436
+ });
437
+ const formatPrice = (price, currency, compact) => formatCurrency(price, currency, getPriceOptions(price, compact));
438
+ const MIN_COLLAPSED_ZEROS = 4;
439
+ const formatCompactPrice = (price, currency) => {
440
+ const parts = formatCurrencyToParts(price, currency, getPriceOptions(price, true));
441
+ const joinParts = (from, to) => parts.slice(from, to).map((part) => part.value).join("");
442
+ const fractionIndex = parts.findIndex((part) => part.type === "fraction");
443
+ const integer = parts.find((part) => part.type === "integer")?.value;
444
+ const match = /^(0+)([1-9]\d*?)0*$/.exec(parts[fractionIndex]?.value ?? "");
445
+ if (integer !== "0" || !match || match[1].length < MIN_COLLAPSED_ZEROS) return {
446
+ kind: "plain",
447
+ text: joinParts(0)
448
+ };
449
+ return {
450
+ kind: "collapsedZeros",
451
+ head: joinParts(0, fractionIndex),
452
+ zeroCount: match[1].length,
453
+ tail: match[2] + joinParts(fractionIndex + 1)
454
+ };
455
+ };
456
+ // src/getErrorMessage.ts
375
457
  const getErrorMessage = (error, fallback = "Unknown error") => {
376
458
  if (typeof error === "string") return error || fallback;
377
459
  if (error && typeof error === "object" && "message" in error && typeof error.message === "string") return error.message || fallback;
378
460
  return fallback;
379
461
  };
380
- //#endregion
381
- //#region src/getLoadable.ts
462
+ // src/getLoadable.ts
382
463
  function getLoadable$(factory, options = {}) {
383
464
  const { getError, refreshInterval } = options;
384
465
  const createLoadableStream = () => (0, rxjs.from)(factory()).pipe((0, rxjs.map)((data) => ({
@@ -394,8 +475,7 @@ const getGenericError = (error) => ({
394
475
  name: "Error",
395
476
  message: getErrorMessage(error)
396
477
  });
397
- //#endregion
398
- //#region src/getSharedObservable.ts
478
+ // src/getSharedObservable.ts
399
479
  const CACHE = /* @__PURE__ */ new Map();
400
480
  /**
401
481
  * How long an entry survives with no subscribers before being dropped. Long enough
@@ -455,8 +535,7 @@ const getSharedObservable = (namespace, args, createObservable, serializer = (ar
455
535
  scheduleCleanup(entry);
456
536
  return entry.observable;
457
537
  };
458
- //#endregion
459
- //#region src/getQuery.ts
538
+ // src/getQuery.ts
460
539
  /**
461
540
  * Creates a shared observable for executing queries with caching, loading states, and automatic refresh capabilities.
462
541
  *
@@ -521,8 +600,7 @@ const getQuery$ = ({ namespace, args, queryFn, defaultValue, refreshInterval, se
521
600
  bufferSize: 1
522
601
  })), serializer);
523
602
  };
524
- //#endregion
525
- //#region src/getLoadableQuery.ts
603
+ // src/getLoadableQuery.ts
526
604
  /**
527
605
  * Thin wrapper around getQuery$ that returns Loadable<T> and optionally
528
606
  * primes the stream with a loading state using the provided default value.
@@ -557,38 +635,31 @@ const getLoadableQuery$ = (params) => {
557
635
  }
558
636
  }), (0, rxjs.startWith)(...initial));
559
637
  };
560
- //#endregion
561
- //#region src/hasOwnProperty.ts
638
+ // src/hasOwnProperty.ts
562
639
  function hasOwnProperty(obj, prop) {
563
640
  if (typeof obj !== "object") return false;
564
641
  if (obj === null) return false;
565
642
  return prop in obj;
566
643
  }
567
- //#endregion
568
- //#region src/isAbortError.ts
644
+ // src/isAbortError.ts
569
645
  const isAbortError = (error) => {
570
646
  return error instanceof Error && error.name === "AbortError";
571
647
  };
572
- //#endregion
573
- //#region src/isArrayOf.ts
648
+ // src/isArrayOf.ts
574
649
  function isArrayOf(array, func) {
575
650
  if (array.length > 0 && array[0] instanceof func) return true;
576
651
  return false;
577
652
  }
578
- //#endregion
579
- //#region src/isAscii.ts
653
+ // src/isAscii.ts
580
654
  const isAscii = (str) => {
581
655
  return [...str].every((char) => char.charCodeAt(0) <= 127);
582
656
  };
583
- //#endregion
584
- //#region src/isBigInt.ts
657
+ // src/isBigInt.ts
585
658
  const isBigInt = (value) => typeof value === "bigint";
586
- //#endregion
587
- //#region src/isBooleanTrue.ts
659
+ // src/isBooleanTrue.ts
588
660
  /** @deprecated use isTruthy instead */
589
661
  const isBooleanTrue = (x) => !!x;
590
- //#endregion
591
- //#region src/isErrorOfName.ts
662
+ // src/isErrorOfName.ts
592
663
  /**
593
664
  * Robust replacement for `error instanceof SomeErrorClass` when the class comes from a
594
665
  * package that gets bundled into multiple chunks/contexts (e.g. viem, @solana/web3.js).
@@ -601,8 +672,7 @@ const isBooleanTrue = (x) => !!x;
601
672
  * duck-type the shape instead.
602
673
  */
603
674
  const isErrorOfName = (error, ...names) => error instanceof Error && names.includes(error.name);
604
- //#endregion
605
- //#region src/isNotNil.ts
675
+ // src/isNotNil.ts
606
676
  /**
607
677
  * WARNING: This function only checks against null or undefined, it does not coerce the value.
608
678
  * ie: false and 0 are considered not nil
@@ -612,11 +682,9 @@ const isErrorOfName = (error, ...names) => error instanceof Error && names.inclu
612
682
  * @returns whether the value is neither null nor undefined
613
683
  */
614
684
  const isNotNil = (value) => value !== null && value !== void 0;
615
- //#endregion
616
- //#region src/isPromise.ts
685
+ // src/isPromise.ts
617
686
  const isPromise = (value) => !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
618
- //#endregion
619
- //#region src/isSubject.ts
687
+ // src/isSubject.ts
620
688
  /**
621
689
  * Tests to see if an object is an RxJS {@link Subject}.
622
690
  */
@@ -637,11 +705,9 @@ function isFn(value) {
637
705
  function isBool(value) {
638
706
  return typeof value === "boolean";
639
707
  }
640
- //#endregion
641
- //#region src/isTruthy.ts
708
+ // src/isTruthy.ts
642
709
  const isTruthy = (value) => Boolean(value);
643
- //#endregion
644
- //#region src/keepAlive.ts
710
+ // src/keepAlive.ts
645
711
  /**
646
712
  * An RxJS operator that keeps the source observable alive for a specified duration
647
713
  * after all subscribers have unsubscribed. This prevents expensive re-subscriptions
@@ -675,8 +741,7 @@ const keepSourceSubscribed = (observable, ms) => {
675
741
  const sub = observable.subscribe();
676
742
  return () => setTimeout(() => sub.unsubscribe(), ms);
677
743
  };
678
- //#endregion
679
- //#region src/lruMap.ts
744
+ // src/lruMap.ts
680
745
  /**
681
746
  * A Map with a maximum size and least-recently-used eviction.
682
747
  *
@@ -720,8 +785,7 @@ var LruMap = class {
720
785
  return this.#map.size;
721
786
  }
722
787
  };
723
- //#endregion
724
- //#region src/mapChunked.ts
788
+ // src/mapChunked.ts
725
789
  const runChunkedProject = (project, options, value, index) => new rxjs.Observable((subscriber) => {
726
790
  const controller = new AbortController();
727
791
  project(value, {
@@ -758,15 +822,13 @@ const switchMapChunked = (project, options) => (0, rxjs.switchMap)((value, index
758
822
  * still aborts it).
759
823
  */
760
824
  const concatMapChunked = (project, options) => (0, rxjs.concatMap)((value, index) => runChunkedProject(project, options, value, index));
761
- //#endregion
762
- //#region src/planckToTokens.ts
825
+ // src/planckToTokens.ts
763
826
  function planckToTokens(planck, tokenDecimals) {
764
827
  if (typeof planck !== "string" || typeof tokenDecimals !== "number") return;
765
828
  const multiplier = 10 ** (-1 * tokenDecimals);
766
829
  return new configureBigNumber_default(planck).multipliedBy(multiplier).toString(10);
767
830
  }
768
- //#endregion
769
- //#region src/replaySubjectFrom.ts
831
+ // src/replaySubjectFrom.ts
770
832
  /**
771
833
  * Turns a value into a {@link ReplaySubject} of size 1.
772
834
  *
@@ -787,14 +849,12 @@ const replaySubjectFrom = (initialValue) => {
787
849
  subject.next(initialValue);
788
850
  return subject;
789
851
  };
790
- //#endregion
791
- //#region src/sleep.ts
852
+ // src/sleep.ts
792
853
  const sleep = (ms) => new Promise((resolve) => {
793
854
  if (process.env.NODE_ENV === "test") resolve();
794
855
  else setTimeout(resolve, ms);
795
856
  });
796
- //#endregion
797
- //#region src/splitSubject.ts
857
+ // src/splitSubject.ts
798
858
  /**
799
859
  * Takes a subject and splits it into two parts:
800
860
  *
@@ -808,8 +868,7 @@ function splitSubject(subject) {
808
868
  const next = (value) => subject.next(value);
809
869
  return [next, subject.asObservable()];
810
870
  }
811
- //#endregion
812
- //#region src/stripHexPrefix.ts
871
+ // src/stripHexPrefix.ts
813
872
  /**
814
873
  * @name stripHexPrefix
815
874
  * @description Removes a leading `0x` prefix from a string, if present.
@@ -820,18 +879,15 @@ function splitSubject(subject) {
820
879
  * stripHexPrefix("1234") // "1234"
821
880
  **/
822
881
  const stripHexPrefix = (str) => str.startsWith("0x") ? str.slice(2) : str;
823
- //#endregion
824
- //#region src/throwAfter.ts
882
+ // src/throwAfter.ts
825
883
  const throwAfter = (ms, reason) => new Promise((_, reject) => setTimeout(() => reject(new Error(reason)), ms));
826
- //#endregion
827
- //#region src/tokensToPlanck.ts
884
+ // src/tokensToPlanck.ts
828
885
  function tokensToPlanck(tokens, tokenDecimals) {
829
886
  if (typeof tokens !== "string" || typeof tokenDecimals !== "number") return;
830
887
  const multiplier = 10 ** tokenDecimals;
831
888
  return new configureBigNumber_default(tokens).multipliedBy(multiplier).toString(10);
832
889
  }
833
- //#endregion
834
- //#region src/validateArrayWithYield.ts
890
+ // src/validateArrayWithYield.ts
835
891
  /**
836
892
  * Validates every item of an array within a cooperative time budget, yielding the thread
837
893
  * to the host event loop whenever the budget for the current slice is exhausted.
@@ -859,8 +915,7 @@ const validateArrayWithYield = async (items, parseItem, options) => {
859
915
  data
860
916
  };
861
917
  };
862
- //#endregion
863
- //#region src/validateHexString.ts
918
+ // src/validateHexString.ts
864
919
  /**
865
920
  * @name validateHexString
866
921
  * @description Checks if a string is a hex string. Required to account for type differences between different polkadot libraries
@@ -876,7 +931,6 @@ const validateHexString = (str) => {
876
931
  if (str.startsWith("0x")) return str;
877
932
  throw new Error("Expected a hex string");
878
933
  };
879
- //#endregion
880
934
  exports.BigMath = BigMath;
881
935
  exports.DEFAULT_TIME_SLICE_BUDGET_MS = DEFAULT_TIME_SLICE_BUDGET_MS;
882
936
  exports.Deferred = Deferred;
@@ -890,8 +944,12 @@ exports.concatMapChunked = concatMapChunked;
890
944
  exports.createTimeSlicer = createTimeSlicer;
891
945
  exports.firstThenDebounce = firstThenDebounce;
892
946
  exports.forEachWithYield = forEachWithYield;
947
+ exports.formatCompactPrice = formatCompactPrice;
948
+ exports.formatCurrency = formatCurrency;
949
+ exports.formatCurrencyToParts = formatCurrencyToParts;
893
950
  exports.formatDecimals = formatDecimals;
894
951
  exports.formatPrice = formatPrice;
952
+ exports.getCurrencyFractionDigits = getCurrencyFractionDigits;
895
953
  exports.getErrorMessage = getErrorMessage;
896
954
  exports.getLoadable$ = getLoadable$;
897
955
  exports.getLoadableQuery$ = getLoadableQuery$;