@talismn/util 2.1.1 → 2.3.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.mjs CHANGED
@@ -1,17 +1,15 @@
1
1
  import BigNumber from "bignumber.js";
2
2
  import { isEqual } from "lodash-es";
3
3
  import { BehaviorSubject, Observable, ReplaySubject, Subject, catchError, concat, concatMap, debounceTime, distinctUntilChanged, from, map, of, shareReplay, skip, startWith, switchMap, take, tap, timer } from "rxjs";
4
- //#region src/configureBigNumber.ts
4
+ // src/configureBigNumber.ts
5
5
  BigNumber.set({ STRICT: false });
6
6
  var configureBigNumber_default = BigNumber;
7
- //#endregion
8
- //#region src/addTrailingSlash.ts
7
+ // src/addTrailingSlash.ts
9
8
  const addTrailingSlash = (url) => {
10
9
  if (url.endsWith("/")) return url;
11
10
  return `${url}/`;
12
11
  };
13
- //#endregion
14
- //#region src/assert.ts
12
+ // src/assert.ts
15
13
  /**
16
14
  * @name assert
17
15
  * @description Throws an Error with the given message if the condition is falsy.
@@ -22,8 +20,7 @@ function assert(condition, message) {
22
20
  if (condition) return;
23
21
  throw new Error(typeof message === "function" ? message() : message);
24
22
  }
25
- //#endregion
26
- //#region src/BigMath.ts
23
+ // src/BigMath.ts
27
24
  /**
28
25
  * Javascript's `Math` library for `BigInt`.
29
26
  * Taken from https://stackoverflow.com/questions/51867270/is-there-a-library-similar-to-math-that-supports-javascript-bigint/64953280#64953280
@@ -45,14 +42,12 @@ const BigMath = {
45
42
  return value;
46
43
  }
47
44
  };
48
- //#endregion
49
- //#region src/isHexString.ts
45
+ // src/isHexString.ts
50
46
  const REGEX_HEX_STRING = /^0x[0-9a-fA-F]*$/;
51
47
  const isHexString = (value) => {
52
48
  return typeof value === "string" && REGEX_HEX_STRING.test(value);
53
49
  };
54
- //#endregion
55
- //#region src/bytes.ts
50
+ // src/bytes.ts
56
51
  /**
57
52
  * Byte / hex primitives, drop-in equivalents of the `@polkadot/util` helpers we used to depend on.
58
53
  * Semantics intentionally match polkadot-js for migration safety.
@@ -134,14 +129,12 @@ const u8aUnwrapBytes = (value) => {
134
129
  const u8a = u8aToU8a(value);
135
130
  return u8aIsWrapped(u8a) ? u8a.subarray(U8A_WRAP_PREFIX.length, u8a.length - U8A_WRAP_POSTFIX.length) : u8a;
136
131
  };
137
- //#endregion
138
- //#region src/jsActivityHook.ts
132
+ // src/jsActivityHook.ts
139
133
  const reportJsActivity = (label, durationMs) => {
140
134
  const record = globalThis.__recordJsActivity;
141
135
  if (record) record(label, durationMs);
142
136
  };
143
- //#endregion
144
- //#region src/yieldToEventLoop.ts
137
+ // src/yieldToEventLoop.ts
145
138
  const yieldToEventLoop = () => {
146
139
  const { scheduler } = globalThis;
147
140
  if (typeof scheduler?.postTask === "function") return scheduler.postTask(() => {}, { priority: "background" });
@@ -158,8 +151,7 @@ const yieldToEventLoop = () => {
158
151
  });
159
152
  return new Promise((resolve) => setTimeout(resolve, 0));
160
153
  };
161
- //#endregion
162
- //#region src/timeSlicer.ts
154
+ // src/timeSlicer.ts
163
155
  /**
164
156
  * Default CPU budget for a single synchronous slice of chunked work.
165
157
  * ~50-60% of a 60fps frame, leaving the rest for the host (user interactions, rendering).
@@ -202,8 +194,7 @@ const createTimeSlicer = ({ budgetMs = 10, signal, now = defaultNow, label } = {
202
194
  throwIfAborted
203
195
  };
204
196
  };
205
- //#endregion
206
- //#region src/chunkedArray.ts
197
+ // src/chunkedArray.ts
207
198
  const getSlicer = (options) => options?.slicer ?? createTimeSlicer({
208
199
  budgetMs: options?.budgetMs,
209
200
  signal: options?.signal,
@@ -256,8 +247,7 @@ const arrayItemsEqualWithYield = async (a, b, options) => {
256
247
  }
257
248
  return true;
258
249
  };
259
- //#endregion
260
- //#region src/deferred.ts
250
+ // src/deferred.ts
261
251
  /**
262
252
  * In TypeScript, a deferred promise refers to a pattern that involves creating a promise that can be
263
253
  * resolved or rejected at a later point in time, typically by code outside of the current function scope.
@@ -291,8 +281,7 @@ function Deferred() {
291
281
  isRejected: () => isRejected
292
282
  };
293
283
  }
294
- //#endregion
295
- //#region src/firstThenDebounce.ts
284
+ // src/firstThenDebounce.ts
296
285
  /**
297
286
  * An rxjs operator which:
298
287
  *
@@ -300,8 +289,90 @@ function Deferred() {
300
289
  * 2. Debounces any future values by `timeout` ms.
301
290
  */
302
291
  const firstThenDebounce = (timeout) => (source) => concat(source.pipe(take(1)), source.pipe(skip(1)).pipe(debounceTime(timeout)));
303
- //#endregion
304
- //#region src/formatDecimals.ts
292
+ // src/formatCurrency.ts
293
+ const INTL_CURRENCY_OVERRIDES = {
294
+ btc: {
295
+ symbol: "₿",
296
+ fractionDigits: 6
297
+ },
298
+ eth: {
299
+ symbol: "Ξ",
300
+ fractionDigits: 5
301
+ },
302
+ tao: {
303
+ symbol: "τ",
304
+ fractionDigits: 4
305
+ },
306
+ idr: { fractionDigits: 0 }
307
+ };
308
+ const INTL_MAX_FRACTION_DIGITS = 20;
309
+ const clampFractionDigits = (digits) => digits === void 0 ? void 0 : Math.min(digits, INTL_MAX_FRACTION_DIGITS);
310
+ const fractionDigitsByCurrency = /* @__PURE__ */ new Map();
311
+ const getCurrencyFractionDigits = (currency) => {
312
+ const currencyId = currency.toLowerCase();
313
+ const cached = fractionDigitsByCurrency.get(currencyId);
314
+ if (cached !== void 0) return cached;
315
+ const { maximumFractionDigits: intlFractionDigits = 2 } = new Intl.NumberFormat(void 0, {
316
+ style: "currency",
317
+ currency
318
+ }).resolvedOptions();
319
+ const fractionDigits = INTL_CURRENCY_OVERRIDES[currencyId]?.fractionDigits ?? intlFractionDigits;
320
+ fractionDigitsByCurrency.set(currencyId, fractionDigits);
321
+ return fractionDigits;
322
+ };
323
+ const getDefaultFractionDigits = (currencyId, options) => {
324
+ if ([
325
+ options.minimumFractionDigits,
326
+ options.maximumFractionDigits,
327
+ options.minimumSignificantDigits,
328
+ options.maximumSignificantDigits
329
+ ].some((digits) => digits !== void 0) || options.notation === "compact") return void 0;
330
+ return INTL_CURRENCY_OVERRIDES[currencyId]?.fractionDigits;
331
+ };
332
+ const isSpacing = (part) => part?.type === "literal" && part.value.trim() === "";
333
+ const withTrailingCode = (parts, code) => {
334
+ const currencyIndex = parts.findIndex((part) => part.type === "currency");
335
+ const number = parts.filter((part, index) => index !== currencyIndex && !(isSpacing(part) && Math.abs(index - currencyIndex) === 1));
336
+ while (isSpacing(number[0])) number.shift();
337
+ while (isSpacing(number.at(-1))) number.pop();
338
+ return [
339
+ ...number,
340
+ {
341
+ type: "literal",
342
+ value: " "
343
+ },
344
+ {
345
+ type: "currency",
346
+ value: code
347
+ }
348
+ ];
349
+ };
350
+ const formatCurrencyToParts = (amount, currency, options = {}) => {
351
+ const currencyId = currency.toLowerCase();
352
+ const currencyDisplay = options.currencyDisplay ?? (currencyId === "usd" ? "narrowSymbol" : "symbol");
353
+ const defaultFractionDigits = getDefaultFractionDigits(currencyId, options);
354
+ const intlOptions = {
355
+ ...options,
356
+ style: "currency",
357
+ currency,
358
+ currencyDisplay,
359
+ minimumFractionDigits: clampFractionDigits(options.minimumFractionDigits ?? defaultFractionDigits),
360
+ maximumFractionDigits: clampFractionDigits(options.maximumFractionDigits ?? defaultFractionDigits)
361
+ };
362
+ if (currencyDisplay === "code") return withTrailingCode(new Intl.NumberFormat(void 0, intlOptions).formatToParts(amount), currency.toUpperCase());
363
+ const symbol = currencyDisplay === "name" ? void 0 : INTL_CURRENCY_OVERRIDES[currencyId]?.symbol;
364
+ if (!symbol) return new Intl.NumberFormat(void 0, intlOptions).formatToParts(amount);
365
+ return new Intl.NumberFormat(void 0, {
366
+ ...intlOptions,
367
+ currency: "USD",
368
+ currencyDisplay: "narrowSymbol"
369
+ }).formatToParts(amount).map((part) => part.type === "currency" ? {
370
+ ...part,
371
+ value: symbol
372
+ } : part);
373
+ };
374
+ const formatCurrency = (amount, currency, options = {}) => formatCurrencyToParts(amount, currency, options).map((part) => part.value).join("");
375
+ // src/formatDecimals.ts
305
376
  const MIN_DIGITS = 4;
306
377
  const MAX_DECIMALS_FORMAT = 12;
307
378
  /**
@@ -333,28 +404,39 @@ const formatDecimals = (num, digits = MIN_DIGITS, options = {}, locale = "en-US"
333
404
  ...options
334
405
  }).format(truncatedValue.toNumber());
335
406
  };
336
- //#endregion
337
- //#region src/formatPrice.ts
338
- const formatPrice = (price, currency, compact) => {
339
- return Intl.NumberFormat(void 0, {
340
- style: "currency",
341
- currency,
342
- currencyDisplay: currency === "usd" ? "narrowSymbol" : "symbol",
343
- minimumSignificantDigits: 3,
344
- maximumSignificantDigits: compact ? price < 1 ? 3 : 4 : void 0,
345
- roundingPriority: compact ? "auto" : "morePrecision",
346
- notation: compact ? "compact" : "standard"
347
- }).format(price);
348
- };
349
- //#endregion
350
- //#region src/getErrorMessage.ts
407
+ // src/formatPrice.ts
408
+ const getPriceOptions = (price, compact) => ({
409
+ minimumSignificantDigits: 3,
410
+ maximumSignificantDigits: compact ? price < 1 ? 3 : 4 : void 0,
411
+ roundingPriority: compact ? "auto" : "morePrecision",
412
+ notation: compact ? "compact" : "standard"
413
+ });
414
+ const formatPrice = (price, currency, compact) => formatCurrency(price, currency, getPriceOptions(price, compact));
415
+ const MIN_COLLAPSED_ZEROS = 4;
416
+ const formatCompactPrice = (price, currency) => {
417
+ const parts = formatCurrencyToParts(price, currency, getPriceOptions(price, true));
418
+ const joinParts = (from, to) => parts.slice(from, to).map((part) => part.value).join("");
419
+ const fractionIndex = parts.findIndex((part) => part.type === "fraction");
420
+ const integer = parts.find((part) => part.type === "integer")?.value;
421
+ const match = /^(0+)([1-9]\d*?)0*$/.exec(parts[fractionIndex]?.value ?? "");
422
+ if (integer !== "0" || !match || match[1].length < MIN_COLLAPSED_ZEROS) return {
423
+ kind: "plain",
424
+ text: joinParts(0)
425
+ };
426
+ return {
427
+ kind: "collapsedZeros",
428
+ head: joinParts(0, fractionIndex),
429
+ zeroCount: match[1].length,
430
+ tail: match[2] + joinParts(fractionIndex + 1)
431
+ };
432
+ };
433
+ // src/getErrorMessage.ts
351
434
  const getErrorMessage = (error, fallback = "Unknown error") => {
352
435
  if (typeof error === "string") return error || fallback;
353
436
  if (error && typeof error === "object" && "message" in error && typeof error.message === "string") return error.message || fallback;
354
437
  return fallback;
355
438
  };
356
- //#endregion
357
- //#region src/getLoadable.ts
439
+ // src/getLoadable.ts
358
440
  function getLoadable$(factory, options = {}) {
359
441
  const { getError, refreshInterval } = options;
360
442
  const createLoadableStream = () => from(factory()).pipe(map((data) => ({
@@ -370,8 +452,7 @@ const getGenericError = (error) => ({
370
452
  name: "Error",
371
453
  message: getErrorMessage(error)
372
454
  });
373
- //#endregion
374
- //#region src/getSharedObservable.ts
455
+ // src/getSharedObservable.ts
375
456
  const CACHE = /* @__PURE__ */ new Map();
376
457
  /**
377
458
  * How long an entry survives with no subscribers before being dropped. Long enough
@@ -431,8 +512,7 @@ const getSharedObservable = (namespace, args, createObservable, serializer = (ar
431
512
  scheduleCleanup(entry);
432
513
  return entry.observable;
433
514
  };
434
- //#endregion
435
- //#region src/getQuery.ts
515
+ // src/getQuery.ts
436
516
  /**
437
517
  * Creates a shared observable for executing queries with caching, loading states, and automatic refresh capabilities.
438
518
  *
@@ -497,8 +577,7 @@ const getQuery$ = ({ namespace, args, queryFn, defaultValue, refreshInterval, se
497
577
  bufferSize: 1
498
578
  })), serializer);
499
579
  };
500
- //#endregion
501
- //#region src/getLoadableQuery.ts
580
+ // src/getLoadableQuery.ts
502
581
  /**
503
582
  * Thin wrapper around getQuery$ that returns Loadable<T> and optionally
504
583
  * primes the stream with a loading state using the provided default value.
@@ -533,38 +612,31 @@ const getLoadableQuery$ = (params) => {
533
612
  }
534
613
  }), startWith(...initial));
535
614
  };
536
- //#endregion
537
- //#region src/hasOwnProperty.ts
615
+ // src/hasOwnProperty.ts
538
616
  function hasOwnProperty(obj, prop) {
539
617
  if (typeof obj !== "object") return false;
540
618
  if (obj === null) return false;
541
619
  return prop in obj;
542
620
  }
543
- //#endregion
544
- //#region src/isAbortError.ts
621
+ // src/isAbortError.ts
545
622
  const isAbortError = (error) => {
546
623
  return error instanceof Error && error.name === "AbortError";
547
624
  };
548
- //#endregion
549
- //#region src/isArrayOf.ts
625
+ // src/isArrayOf.ts
550
626
  function isArrayOf(array, func) {
551
627
  if (array.length > 0 && array[0] instanceof func) return true;
552
628
  return false;
553
629
  }
554
- //#endregion
555
- //#region src/isAscii.ts
630
+ // src/isAscii.ts
556
631
  const isAscii = (str) => {
557
632
  return [...str].every((char) => char.charCodeAt(0) <= 127);
558
633
  };
559
- //#endregion
560
- //#region src/isBigInt.ts
634
+ // src/isBigInt.ts
561
635
  const isBigInt = (value) => typeof value === "bigint";
562
- //#endregion
563
- //#region src/isBooleanTrue.ts
636
+ // src/isBooleanTrue.ts
564
637
  /** @deprecated use isTruthy instead */
565
638
  const isBooleanTrue = (x) => !!x;
566
- //#endregion
567
- //#region src/isErrorOfName.ts
639
+ // src/isErrorOfName.ts
568
640
  /**
569
641
  * Robust replacement for `error instanceof SomeErrorClass` when the class comes from a
570
642
  * package that gets bundled into multiple chunks/contexts (e.g. viem, @solana/web3.js).
@@ -577,8 +649,7 @@ const isBooleanTrue = (x) => !!x;
577
649
  * duck-type the shape instead.
578
650
  */
579
651
  const isErrorOfName = (error, ...names) => error instanceof Error && names.includes(error.name);
580
- //#endregion
581
- //#region src/isNotNil.ts
652
+ // src/isNotNil.ts
582
653
  /**
583
654
  * WARNING: This function only checks against null or undefined, it does not coerce the value.
584
655
  * ie: false and 0 are considered not nil
@@ -588,11 +659,9 @@ const isErrorOfName = (error, ...names) => error instanceof Error && names.inclu
588
659
  * @returns whether the value is neither null nor undefined
589
660
  */
590
661
  const isNotNil = (value) => value !== null && value !== void 0;
591
- //#endregion
592
- //#region src/isPromise.ts
662
+ // src/isPromise.ts
593
663
  const isPromise = (value) => !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
594
- //#endregion
595
- //#region src/isSubject.ts
664
+ // src/isSubject.ts
596
665
  /**
597
666
  * Tests to see if an object is an RxJS {@link Subject}.
598
667
  */
@@ -613,11 +682,9 @@ function isFn(value) {
613
682
  function isBool(value) {
614
683
  return typeof value === "boolean";
615
684
  }
616
- //#endregion
617
- //#region src/isTruthy.ts
685
+ // src/isTruthy.ts
618
686
  const isTruthy = (value) => Boolean(value);
619
- //#endregion
620
- //#region src/keepAlive.ts
687
+ // src/keepAlive.ts
621
688
  /**
622
689
  * An RxJS operator that keeps the source observable alive for a specified duration
623
690
  * after all subscribers have unsubscribed. This prevents expensive re-subscriptions
@@ -651,8 +718,7 @@ const keepSourceSubscribed = (observable, ms) => {
651
718
  const sub = observable.subscribe();
652
719
  return () => setTimeout(() => sub.unsubscribe(), ms);
653
720
  };
654
- //#endregion
655
- //#region src/lruMap.ts
721
+ // src/lruMap.ts
656
722
  /**
657
723
  * A Map with a maximum size and least-recently-used eviction.
658
724
  *
@@ -696,8 +762,7 @@ var LruMap = class {
696
762
  return this.#map.size;
697
763
  }
698
764
  };
699
- //#endregion
700
- //#region src/mapChunked.ts
765
+ // src/mapChunked.ts
701
766
  const runChunkedProject = (project, options, value, index) => new Observable((subscriber) => {
702
767
  const controller = new AbortController();
703
768
  project(value, {
@@ -734,15 +799,13 @@ const switchMapChunked = (project, options) => switchMap((value, index) => runCh
734
799
  * still aborts it).
735
800
  */
736
801
  const concatMapChunked = (project, options) => concatMap((value, index) => runChunkedProject(project, options, value, index));
737
- //#endregion
738
- //#region src/planckToTokens.ts
802
+ // src/planckToTokens.ts
739
803
  function planckToTokens(planck, tokenDecimals) {
740
804
  if (typeof planck !== "string" || typeof tokenDecimals !== "number") return;
741
805
  const multiplier = 10 ** (-1 * tokenDecimals);
742
806
  return new configureBigNumber_default(planck).multipliedBy(multiplier).toString(10);
743
807
  }
744
- //#endregion
745
- //#region src/replaySubjectFrom.ts
808
+ // src/replaySubjectFrom.ts
746
809
  /**
747
810
  * Turns a value into a {@link ReplaySubject} of size 1.
748
811
  *
@@ -763,14 +826,12 @@ const replaySubjectFrom = (initialValue) => {
763
826
  subject.next(initialValue);
764
827
  return subject;
765
828
  };
766
- //#endregion
767
- //#region src/sleep.ts
829
+ // src/sleep.ts
768
830
  const sleep = (ms) => new Promise((resolve) => {
769
831
  if (process.env.NODE_ENV === "test") resolve();
770
832
  else setTimeout(resolve, ms);
771
833
  });
772
- //#endregion
773
- //#region src/splitSubject.ts
834
+ // src/splitSubject.ts
774
835
  /**
775
836
  * Takes a subject and splits it into two parts:
776
837
  *
@@ -784,8 +845,7 @@ function splitSubject(subject) {
784
845
  const next = (value) => subject.next(value);
785
846
  return [next, subject.asObservable()];
786
847
  }
787
- //#endregion
788
- //#region src/stripHexPrefix.ts
848
+ // src/stripHexPrefix.ts
789
849
  /**
790
850
  * @name stripHexPrefix
791
851
  * @description Removes a leading `0x` prefix from a string, if present.
@@ -796,18 +856,310 @@ function splitSubject(subject) {
796
856
  * stripHexPrefix("1234") // "1234"
797
857
  **/
798
858
  const stripHexPrefix = (str) => str.startsWith("0x") ? str.slice(2) : str;
799
- //#endregion
800
- //#region src/throwAfter.ts
859
+ // src/suspension.ts
860
+ /**
861
+ * Detects when the JS runtime has been suspended, and provides timeouts that count only the
862
+ * time it was running.
863
+ *
864
+ * A mobile OS freezes an app that goes to the background, its webviews included, and a
865
+ * browser can freeze a tab or put a laptop to sleep. No timer fires while the runtime is
866
+ * frozen, and on resume every timer that came due in the meantime fires at once, before the
867
+ * socket messages that arrived while it was frozen. A 30s request timeout armed shortly
868
+ * before a 90s suspension therefore fails its request the moment the runtime resumes,
869
+ * although the answer may already be waiting.
870
+ *
871
+ * A one-second ticker runs while anything is watching. A gap between two ticks longer than
872
+ * `SUSPENSION_GAP_MS` (`HOST_SUSPENSION_GAP_MS` once a host marks suspensions) is taken to be
873
+ * a suspension. Timer callbacks call `checkSuspension()` first, because on resume a due timer
874
+ * can run before the ticker does.
875
+ *
876
+ * A page that is hidden can't tell a freeze from timer throttling: browsers run the timers of
877
+ * a hidden tab once a second, and Chrome once a minute after five minutes. Both leave gaps
878
+ * between ticks while socket messages keep arriving. In a hidden page, the first gap starts a
879
+ * suspension that lasts until the page is shown again, or until its ticks run on time again
880
+ * (a frozen page that resumes while hidden, or an extension's background page, which is never
881
+ * shown). Taking each gap for a resume would restart every timeout once a minute, so that
882
+ * none ever fires.
883
+ *
884
+ * A runtime can also be cut off while it keeps running: a webview whose network traffic goes
885
+ * through its app's native code stays alive while the app is frozen in the background. Its
886
+ * host marks that time with `setSuspended()`. An app can mark its own runtime the same way
887
+ * from the OS's background and foreground events.
888
+ */
889
+ const TICK_MS = 1e3;
890
+ /**
891
+ * A gap between ticks longer than this is a suspension. Well above the longest stall the JS
892
+ * thread is expected to have while it runs, so that a busy thread is not taken for a frozen
893
+ * one.
894
+ */
895
+ const SUSPENSION_GAP_MS = 5e3;
896
+ /**
897
+ * A gap between ticks longer than this is a suspension once a host has marked suspensions
898
+ * (`setSuspended`). The marks cover the freezes the host knows of, and a gap only has to
899
+ * catch one whose mark arrived too late, such as a webview frozen before its app's message
900
+ * reached it. A stall of the JS thread under this long (a metadata parse on a slow phone)
901
+ * then doesn't restart the timeouts.
902
+ */
903
+ const HOST_SUSPENSION_GAP_MS = 15e3;
904
+ /**
905
+ * A tick that comes `TICK_MS / 2` to this long after the one before is on time. Browsers
906
+ * align a hidden page's timers to whole seconds, so its ticks can be up to two seconds apart.
907
+ */
908
+ const ON_TIME_TICK_GAP_MS = 3e3;
909
+ /** On-time ticks in a row that end a hidden page's suspension */
910
+ const ON_TIME_TICKS_TO_RESUME = 5;
911
+ const listeners = /* @__PURE__ */ new Set();
912
+ let holds = 0;
913
+ let ticker = null;
914
+ let lastRunAt = 0;
915
+ /** when the ticker last ran */
916
+ let lastTickAt = 0;
917
+ /** on-time ticks in a row since a hidden page's suspension started */
918
+ let onTimeTicks = 0;
919
+ /** how far the clock has moved back in all, for the timeouts to shift their start by */
920
+ let clockMovedBackMs = 0;
921
+ let lastResumedAt = Number.NEGATIVE_INFINITY;
922
+ /** when the host marked the runtime suspended (`setSuspended(true)`), or null */
923
+ let suspendedSince = null;
924
+ /** whether the page (when there is one) is hidden */
925
+ let pageHidden = false;
926
+ /** the longest gap between ticks since the page was hidden */
927
+ let hiddenGapMs = 0;
928
+ /** a suspension that has ended for the host or the page while the other still holds it */
929
+ let pending = null;
930
+ let watchingPage = false;
931
+ /** whether a host has marked suspensions (`setSuspended`) */
932
+ let hostMarksSuspensions = false;
933
+ const suspensionGapMs = () => hostMarksSuspensions ? HOST_SUSPENSION_GAP_MS : SUSPENSION_GAP_MS;
934
+ const getPage = () => {
935
+ const page = globalThis.document;
936
+ return typeof page?.addEventListener === "function" ? page : void 0;
937
+ };
938
+ const isHeld = () => suspendedSince !== null || pageHidden && hiddenGapMs > suspensionGapMs();
939
+ /** Ends the host's or the page's part of a suspension, and resumes once neither holds it */
940
+ const endHold = (now, ms, byHost) => {
941
+ pending = {
942
+ ms: Math.max(pending?.ms ?? 0, ms),
943
+ byHost: (pending?.byHost ?? false) || byHost
944
+ };
945
+ if (isHeld()) return;
946
+ const ended = pending;
947
+ pending = null;
948
+ lastRunAt = now;
949
+ if (ended.byHost || ended.ms > suspensionGapMs()) resume(now, ended.ms);
950
+ };
951
+ const handleVisibilityChange = () => {
952
+ const hidden = getPage()?.visibilityState === "hidden";
953
+ if (hidden === pageHidden) return;
954
+ if (hidden) {
955
+ checkSuspension();
956
+ pageHidden = true;
957
+ hiddenGapMs = 0;
958
+ onTimeTicks = 0;
959
+ return;
960
+ }
961
+ const now = Date.now();
962
+ followClock(now);
963
+ const ms = Math.max(hiddenGapMs, ticker ? now - lastRunAt : 0);
964
+ pageHidden = false;
965
+ endPageHold(now, ms);
966
+ };
967
+ const endPageHold = (now, ms) => {
968
+ hiddenGapMs = 0;
969
+ onTimeTicks = 0;
970
+ endHold(now, ms, false);
971
+ };
972
+ /**
973
+ * Ends a hidden page's suspension once its ticks have run on time for a while: its timers run
974
+ * at their normal pace again. A tick that runs right after another (the timers that came due
975
+ * during a freeze, run together) counts neither way.
976
+ */
977
+ const tick = () => {
978
+ const now = Date.now();
979
+ const sinceLastTick = now - lastTickAt;
980
+ lastTickAt = now;
981
+ checkSuspension();
982
+ if (!pageHidden || hiddenGapMs <= suspensionGapMs()) return;
983
+ if (sinceLastTick > ON_TIME_TICK_GAP_MS) onTimeTicks = 0;
984
+ else if (sinceLastTick >= TICK_MS / 2) onTimeTicks++;
985
+ if (onTimeTicks >= ON_TIME_TICKS_TO_RESUME) endPageHold(now, hiddenGapMs);
986
+ };
987
+ const watchPage = () => {
988
+ const page = getPage();
989
+ if (watchingPage || !page) return;
990
+ watchingPage = true;
991
+ pageHidden = page.visibilityState === "hidden";
992
+ page.addEventListener("visibilitychange", handleVisibilityChange);
993
+ };
994
+ const hold = () => {
995
+ holds++;
996
+ if (ticker) return;
997
+ watchPage();
998
+ const now = Date.now();
999
+ followClock(now);
1000
+ lastRunAt = now;
1001
+ lastTickAt = now;
1002
+ ticker = setInterval(tick, TICK_MS);
1003
+ };
1004
+ const release = () => {
1005
+ holds--;
1006
+ if (holds > 0 || !ticker) return;
1007
+ clearInterval(ticker);
1008
+ ticker = null;
1009
+ };
1010
+ /**
1011
+ * Shifts the times kept here when the clock has moved back since the runtime last ran, so that
1012
+ * time since a resume, or since the host marked a suspension, keeps counting from where it was
1013
+ */
1014
+ const followClock = (now) => {
1015
+ if (now >= lastRunAt) return;
1016
+ const movedBackMs = lastRunAt - now;
1017
+ clockMovedBackMs += movedBackMs;
1018
+ lastRunAt = now;
1019
+ lastTickAt -= movedBackMs;
1020
+ lastResumedAt -= movedBackMs;
1021
+ if (suspendedSince !== null) suspendedSince -= movedBackMs;
1022
+ };
1023
+ /**
1024
+ * Records that the JS runtime is running now. When it last ran longer than
1025
+ * `SUSPENSION_GAP_MS` (or `HOST_SUSPENSION_GAP_MS`) ago, it was suspended in between, and the resume listeners run before
1026
+ * this returns. When the host or a hidden page holds the suspension, they run once it ends.
1027
+ * Cheap enough to call at the start of every timer callback that measures time.
1028
+ */
1029
+ const checkSuspension = () => {
1030
+ const now = Date.now();
1031
+ followClock(now);
1032
+ const suspendedMs = ticker ? now - lastRunAt : 0;
1033
+ lastRunAt = now;
1034
+ if (pageHidden) {
1035
+ hiddenGapMs = Math.max(hiddenGapMs, suspendedMs);
1036
+ return;
1037
+ }
1038
+ if (suspendedSince !== null || suspendedMs <= suspensionGapMs()) return;
1039
+ resume(now, suspendedMs);
1040
+ };
1041
+ const resume = (now, suspendedMs) => {
1042
+ lastResumedAt = now;
1043
+ for (const listener of [...listeners]) try {
1044
+ listener(suspendedMs);
1045
+ } catch (error) {
1046
+ queueMicrotask(() => {
1047
+ throw error;
1048
+ });
1049
+ }
1050
+ };
1051
+ /**
1052
+ * Marks the JS runtime suspended (`true`) or running again (`false`), for a host that knows
1053
+ * when the runtime is frozen or cut off (it may keep running). While suspended,
1054
+ * `setAwakeTimeout` timeouts don't fire. `setSuspended(false)` is a resume: the timeouts start
1055
+ * over, and the resume listeners run with the time since `setSuspended(true)`. When the page
1056
+ * is also held suspended (hidden, with a gap between ticks), the resume waits until it is
1057
+ * shown or its ticks run on time again.
1058
+ *
1059
+ * From the first call on, a gap between ticks counts as a suspension only from
1060
+ * `HOST_SUSPENSION_GAP_MS` (15s), so that a stall of the JS thread doesn't restart the
1061
+ * timeouts. A host calls it at startup with the runtime's state, for that to apply from then.
1062
+ *
1063
+ * The state is global to the module: the mark reaches the code that reads it (such as
1064
+ * `ChainConnectorDot`) only when both load the same copy of `@talismn/util`. A second copy in
1065
+ * the bundle, from mismatched `@talismn/*` versions or from CJS and ESM builds side by side,
1066
+ * keeps a state of its own, without an error.
1067
+ */
1068
+ const setSuspended = (suspended) => {
1069
+ hostMarksSuspensions = true;
1070
+ if (suspended) {
1071
+ checkSuspension();
1072
+ suspendedSince ??= Date.now();
1073
+ return;
1074
+ }
1075
+ if (suspendedSince === null) return;
1076
+ const now = Date.now();
1077
+ followClock(now);
1078
+ const suspendedMs = now - suspendedSince;
1079
+ suspendedSince = null;
1080
+ endHold(now, suspendedMs, true);
1081
+ };
1082
+ /**
1083
+ * Whether the runtime is held suspended until a later resume: marked by the host
1084
+ * (`setSuspended(true)`), or a hidden page whose timers have stopped or been throttled
1085
+ */
1086
+ const isSuspended = () => {
1087
+ checkSuspension();
1088
+ return isHeld();
1089
+ };
1090
+ /**
1091
+ * When the JS runtime last resumed from a suspension (`Date.now()` time), or -Infinity when
1092
+ * no suspension has been seen. A freeze is only seen while something is watching (an
1093
+ * `onResume` listener or a pending `setAwakeTimeout`); the end of a suspension the host
1094
+ * marked (`setSuspended(false)`) is a resume in any case.
1095
+ */
1096
+ const getLastResumedAt = () => {
1097
+ checkSuspension();
1098
+ return lastResumedAt;
1099
+ };
1100
+ /**
1101
+ * Calls `listener` each time the JS runtime resumes from a suspension, with how long it was
1102
+ * suspended for. Returns the function that removes it.
1103
+ */
1104
+ const onResume = (listener) => {
1105
+ listeners.add(listener);
1106
+ hold();
1107
+ let removed = false;
1108
+ return () => {
1109
+ if (removed) return;
1110
+ removed = true;
1111
+ listeners.delete(listener);
1112
+ release();
1113
+ };
1114
+ };
1115
+ /**
1116
+ * Like `setTimeout`, but time the JS runtime spends suspended does not count. When the runtime
1117
+ * resumes from a suspension before the timeout is up, the timeout starts over from the resume,
1118
+ * so the work it guards gets its full time again. Returns the function that cancels it.
1119
+ */
1120
+ const setAwakeTimeout = (callback, ms) => {
1121
+ hold();
1122
+ let startedAt = Date.now();
1123
+ let clockMovedBackAtStartMs = clockMovedBackMs;
1124
+ let token = null;
1125
+ let done = false;
1126
+ const finish = () => {
1127
+ if (done) return;
1128
+ done = true;
1129
+ if (token) clearTimeout(token);
1130
+ token = null;
1131
+ release();
1132
+ };
1133
+ const fire = () => {
1134
+ checkSuspension();
1135
+ if (done) return;
1136
+ if (isHeld()) {
1137
+ token = setTimeout(fire, ms);
1138
+ return;
1139
+ }
1140
+ startedAt -= clockMovedBackMs - clockMovedBackAtStartMs;
1141
+ clockMovedBackAtStartMs = clockMovedBackMs;
1142
+ const now = Date.now();
1143
+ const remaining = ms - (now - Math.min(now, Math.max(startedAt, lastResumedAt)));
1144
+ if (remaining > 0) {
1145
+ token = setTimeout(fire, remaining);
1146
+ return;
1147
+ }
1148
+ finish();
1149
+ callback();
1150
+ };
1151
+ token = setTimeout(fire, ms);
1152
+ return finish;
1153
+ };
1154
+ // src/throwAfter.ts
801
1155
  const throwAfter = (ms, reason) => new Promise((_, reject) => setTimeout(() => reject(new Error(reason)), ms));
802
- //#endregion
803
- //#region src/tokensToPlanck.ts
1156
+ // src/tokensToPlanck.ts
804
1157
  function tokensToPlanck(tokens, tokenDecimals) {
805
1158
  if (typeof tokens !== "string" || typeof tokenDecimals !== "number") return;
806
1159
  const multiplier = 10 ** tokenDecimals;
807
1160
  return new configureBigNumber_default(tokens).multipliedBy(multiplier).toString(10);
808
1161
  }
809
- //#endregion
810
- //#region src/validateArrayWithYield.ts
1162
+ // src/validateArrayWithYield.ts
811
1163
  /**
812
1164
  * Validates every item of an array within a cooperative time budget, yielding the thread
813
1165
  * to the host event loop whenever the budget for the current slice is exhausted.
@@ -835,8 +1187,7 @@ const validateArrayWithYield = async (items, parseItem, options) => {
835
1187
  data
836
1188
  };
837
1189
  };
838
- //#endregion
839
- //#region src/validateHexString.ts
1190
+ // src/validateHexString.ts
840
1191
  /**
841
1192
  * @name validateHexString
842
1193
  * @description Checks if a string is a hex string. Required to account for type differences between different polkadot libraries
@@ -852,7 +1203,6 @@ const validateHexString = (str) => {
852
1203
  if (str.startsWith("0x")) return str;
853
1204
  throw new Error("Expected a hex string");
854
1205
  };
855
- //#endregion
856
- export { BigMath, DEFAULT_TIME_SLICE_BUDGET_MS, Deferred, LruMap, MAX_DECIMALS_FORMAT, REGEX_HEX_STRING, addTrailingSlash, arrayItemsEqualWithYield, assert, concatMapChunked, createTimeSlicer, firstThenDebounce, forEachWithYield, formatDecimals, formatPrice, getErrorMessage, getLoadable$, getLoadableQuery$, getQuery$, getSharedObservable, hasOwnProperty, hexToNumber, hexToString, hexToU8a, isAbortError, isArrayOf, isAscii, isAsciiPrintable, isBigInt, isBooleanTrue, isErrorOfName, isHexString, isNotNil, isPromise, isSubject, isTruthy, keepAlive, keyByWithYield, mapWithYield, newAbortError, numberToU8a, planckToTokens, replaySubjectFrom, reportJsActivity, sleep, splitSubject, stringToU8a, stripHexPrefix, switchMapChunked, throwAfter, tokensToPlanck, u8aCmp, u8aConcat, u8aEq, u8aToHex, u8aToString, u8aToU8a, u8aUnwrapBytes, u8aWrapBytes, validateArrayWithYield, validateHexString, yieldToEventLoop };
1206
+ export { BigMath, DEFAULT_TIME_SLICE_BUDGET_MS, Deferred, LruMap, MAX_DECIMALS_FORMAT, REGEX_HEX_STRING, addTrailingSlash, arrayItemsEqualWithYield, assert, checkSuspension, concatMapChunked, createTimeSlicer, firstThenDebounce, forEachWithYield, formatCompactPrice, formatCurrency, formatCurrencyToParts, formatDecimals, formatPrice, getCurrencyFractionDigits, getErrorMessage, getLastResumedAt, getLoadable$, getLoadableQuery$, getQuery$, getSharedObservable, hasOwnProperty, hexToNumber, hexToString, hexToU8a, isAbortError, isArrayOf, isAscii, isAsciiPrintable, isBigInt, isBooleanTrue, isErrorOfName, isHexString, isNotNil, isPromise, isSubject, isSuspended, isTruthy, keepAlive, keyByWithYield, mapWithYield, newAbortError, numberToU8a, onResume, planckToTokens, replaySubjectFrom, reportJsActivity, setAwakeTimeout, setSuspended, sleep, splitSubject, stringToU8a, stripHexPrefix, switchMapChunked, throwAfter, tokensToPlanck, u8aCmp, u8aConcat, u8aEq, u8aToHex, u8aToString, u8aToU8a, u8aUnwrapBytes, u8aWrapBytes, validateArrayWithYield, validateHexString, yieldToEventLoop };
857
1207
 
858
1208
  //# sourceMappingURL=index.mjs.map