@talismn/util 2.2.0 → 2.3.1

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
@@ -376,12 +376,16 @@ const formatCurrency = (amount, currency, options = {}) => formatCurrencyToParts
376
376
  const MIN_DIGITS = 4;
377
377
  const MAX_DECIMALS_FORMAT = 12;
378
378
  /**
379
- * Custom decimal number formatting for Talisman
379
+ * Custom decimal number formatting for Talisman: `digits` digits, counting the integer part, the
380
+ * last one rounded half away from zero. At 4 digits, 1.23456 is "1.235", 0.0005966 is "0.0006"
381
+ * and 12345 is "12.35K": a value below 1 keeps at most `digits` decimal places, and a value above
382
+ * 9999 takes compact notation. A value closer to zero than the last digit reads "< 0.0001", or
383
+ * "> -0.0001" below zero. A negative value reads as its positive value with a minus sign.
380
384
  * note that the NumberFormat().format() call is the ressource heavy part, it's not worth trying to optimize other parts
381
385
  * @param num input number
382
- * @param digits number of significant digits to display
386
+ * @param digits number of digits to display, at least 4
387
+ * @param options formatting options, passed to Intl.NumberFormat
383
388
  * @param locale locale used to format the number
384
- * @param options formatting options
385
389
  * @returns the formatted value
386
390
  */
387
391
  const formatDecimals = (num, digits = MIN_DIGITS, options = {}, locale = "en-US") => {
@@ -389,20 +393,21 @@ const formatDecimals = (num, digits = MIN_DIGITS, options = {}, locale = "en-US"
389
393
  if (digits < MIN_DIGITS) digits = MIN_DIGITS;
390
394
  const value = new configureBigNumber_default(num);
391
395
  const minDisplayVal = 1 / 10 ** digits;
392
- if (value.gt(0) && value.lt(minDisplayVal)) return `< ${formatDecimals(minDisplayVal)}`;
393
- const flooredValue = value.integerValue();
394
- const intDigits = flooredValue.isEqualTo(0) ? 0 : flooredValue.toString().length;
395
- let truncatedValue = value;
396
+ if (value.gt(0) && value.lt(minDisplayVal)) return `< ${formatDecimals(minDisplayVal, digits, options, locale)}`;
397
+ if (value.lt(0) && value.gt(-minDisplayVal)) return `> ${formatDecimals(-minDisplayVal, digits, options, locale)}`;
398
+ const integerPart = value.abs().integerValue();
399
+ const intDigits = integerPart.isEqualTo(0) ? 0 : integerPart.toString().length;
400
+ let roundedValue = value;
396
401
  const excessFractionDigitsPow10 = new configureBigNumber_default(10).pow(digits > intDigits ? digits - intDigits : 0);
397
- truncatedValue = truncatedValue.multipliedBy(excessFractionDigitsPow10).integerValue().dividedBy(excessFractionDigitsPow10);
402
+ roundedValue = roundedValue.multipliedBy(excessFractionDigitsPow10).integerValue().dividedBy(excessFractionDigitsPow10);
398
403
  const excessIntegerDigits = new configureBigNumber_default(intDigits > digits ? intDigits - digits : 0);
399
404
  const excessIntegerDigitsPow10 = new configureBigNumber_default(10).pow(excessIntegerDigits);
400
- if (excessIntegerDigits.gt(0)) truncatedValue = truncatedValue.dividedBy(excessIntegerDigitsPow10).integerValue().multipliedBy(excessIntegerDigitsPow10);
405
+ if (excessIntegerDigits.gt(0)) roundedValue = roundedValue.dividedBy(excessIntegerDigitsPow10).integerValue().multipliedBy(excessIntegerDigitsPow10);
401
406
  return Intl.NumberFormat(locale, {
402
- notation: truncatedValue.abs().gt(9999) ? "compact" : "standard",
403
- maximumSignificantDigits: Math.max(1, Math.min(digits + (truncatedValue.lt(1) ? 1 : 0), 21)),
407
+ notation: roundedValue.abs().gt(9999) ? "compact" : "standard",
408
+ maximumSignificantDigits: Math.max(1, Math.min(digits + (roundedValue.abs().lt(1) ? 1 : 0), 21)),
404
409
  ...options
405
- }).format(truncatedValue.toNumber());
410
+ }).format(roundedValue.isZero() ? 0 : roundedValue.toNumber());
406
411
  };
407
412
  // src/formatPrice.ts
408
413
  const getPriceOptions = (price, compact) => ({
@@ -856,6 +861,301 @@ function splitSubject(subject) {
856
861
  * stripHexPrefix("1234") // "1234"
857
862
  **/
858
863
  const stripHexPrefix = (str) => str.startsWith("0x") ? str.slice(2) : str;
864
+ // src/suspension.ts
865
+ /**
866
+ * Detects when the JS runtime has been suspended, and provides timeouts that count only the
867
+ * time it was running.
868
+ *
869
+ * A mobile OS freezes an app that goes to the background, its webviews included, and a
870
+ * browser can freeze a tab or put a laptop to sleep. No timer fires while the runtime is
871
+ * frozen, and on resume every timer that came due in the meantime fires at once, before the
872
+ * socket messages that arrived while it was frozen. A 30s request timeout armed shortly
873
+ * before a 90s suspension therefore fails its request the moment the runtime resumes,
874
+ * although the answer may already be waiting.
875
+ *
876
+ * A one-second ticker runs while anything is watching. A gap between two ticks longer than
877
+ * `SUSPENSION_GAP_MS` (`HOST_SUSPENSION_GAP_MS` once a host marks suspensions) is taken to be
878
+ * a suspension. Timer callbacks call `checkSuspension()` first, because on resume a due timer
879
+ * can run before the ticker does.
880
+ *
881
+ * A page that is hidden can't tell a freeze from timer throttling: browsers run the timers of
882
+ * a hidden tab once a second, and Chrome once a minute after five minutes. Both leave gaps
883
+ * between ticks while socket messages keep arriving. In a hidden page, the first gap starts a
884
+ * suspension that lasts until the page is shown again, or until its ticks run on time again
885
+ * (a frozen page that resumes while hidden, or an extension's background page, which is never
886
+ * shown). Taking each gap for a resume would restart every timeout once a minute, so that
887
+ * none ever fires.
888
+ *
889
+ * A runtime can also be cut off while it keeps running: a webview whose network traffic goes
890
+ * through its app's native code stays alive while the app is frozen in the background. Its
891
+ * host marks that time with `setSuspended()`. An app can mark its own runtime the same way
892
+ * from the OS's background and foreground events.
893
+ */
894
+ const TICK_MS = 1e3;
895
+ /**
896
+ * A gap between ticks longer than this is a suspension. Well above the longest stall the JS
897
+ * thread is expected to have while it runs, so that a busy thread is not taken for a frozen
898
+ * one.
899
+ */
900
+ const SUSPENSION_GAP_MS = 5e3;
901
+ /**
902
+ * A gap between ticks longer than this is a suspension once a host has marked suspensions
903
+ * (`setSuspended`). The marks cover the freezes the host knows of, and a gap only has to
904
+ * catch one whose mark arrived too late, such as a webview frozen before its app's message
905
+ * reached it. A stall of the JS thread under this long (a metadata parse on a slow phone)
906
+ * then doesn't restart the timeouts.
907
+ */
908
+ const HOST_SUSPENSION_GAP_MS = 15e3;
909
+ /**
910
+ * A tick that comes `TICK_MS / 2` to this long after the one before is on time. Browsers
911
+ * align a hidden page's timers to whole seconds, so its ticks can be up to two seconds apart.
912
+ */
913
+ const ON_TIME_TICK_GAP_MS = 3e3;
914
+ /** On-time ticks in a row that end a hidden page's suspension */
915
+ const ON_TIME_TICKS_TO_RESUME = 5;
916
+ const listeners = /* @__PURE__ */ new Set();
917
+ let holds = 0;
918
+ let ticker = null;
919
+ let lastRunAt = 0;
920
+ /** when the ticker last ran */
921
+ let lastTickAt = 0;
922
+ /** on-time ticks in a row since a hidden page's suspension started */
923
+ let onTimeTicks = 0;
924
+ /** how far the clock has moved back in all, for the timeouts to shift their start by */
925
+ let clockMovedBackMs = 0;
926
+ let lastResumedAt = Number.NEGATIVE_INFINITY;
927
+ /** when the host marked the runtime suspended (`setSuspended(true)`), or null */
928
+ let suspendedSince = null;
929
+ /** whether the page (when there is one) is hidden */
930
+ let pageHidden = false;
931
+ /** the longest gap between ticks since the page was hidden */
932
+ let hiddenGapMs = 0;
933
+ /** a suspension that has ended for the host or the page while the other still holds it */
934
+ let pending = null;
935
+ let watchingPage = false;
936
+ /** whether a host has marked suspensions (`setSuspended`) */
937
+ let hostMarksSuspensions = false;
938
+ const suspensionGapMs = () => hostMarksSuspensions ? HOST_SUSPENSION_GAP_MS : SUSPENSION_GAP_MS;
939
+ const getPage = () => {
940
+ const page = globalThis.document;
941
+ return typeof page?.addEventListener === "function" ? page : void 0;
942
+ };
943
+ const isHeld = () => suspendedSince !== null || pageHidden && hiddenGapMs > suspensionGapMs();
944
+ /** Ends the host's or the page's part of a suspension, and resumes once neither holds it */
945
+ const endHold = (now, ms, byHost) => {
946
+ pending = {
947
+ ms: Math.max(pending?.ms ?? 0, ms),
948
+ byHost: (pending?.byHost ?? false) || byHost
949
+ };
950
+ if (isHeld()) return;
951
+ const ended = pending;
952
+ pending = null;
953
+ lastRunAt = now;
954
+ if (ended.byHost || ended.ms > suspensionGapMs()) resume(now, ended.ms);
955
+ };
956
+ const handleVisibilityChange = () => {
957
+ const hidden = getPage()?.visibilityState === "hidden";
958
+ if (hidden === pageHidden) return;
959
+ if (hidden) {
960
+ checkSuspension();
961
+ pageHidden = true;
962
+ hiddenGapMs = 0;
963
+ onTimeTicks = 0;
964
+ return;
965
+ }
966
+ const now = Date.now();
967
+ followClock(now);
968
+ const ms = Math.max(hiddenGapMs, ticker ? now - lastRunAt : 0);
969
+ pageHidden = false;
970
+ endPageHold(now, ms);
971
+ };
972
+ const endPageHold = (now, ms) => {
973
+ hiddenGapMs = 0;
974
+ onTimeTicks = 0;
975
+ endHold(now, ms, false);
976
+ };
977
+ /**
978
+ * Ends a hidden page's suspension once its ticks have run on time for a while: its timers run
979
+ * at their normal pace again. A tick that runs right after another (the timers that came due
980
+ * during a freeze, run together) counts neither way.
981
+ */
982
+ const tick = () => {
983
+ const now = Date.now();
984
+ const sinceLastTick = now - lastTickAt;
985
+ lastTickAt = now;
986
+ checkSuspension();
987
+ if (!pageHidden || hiddenGapMs <= suspensionGapMs()) return;
988
+ if (sinceLastTick > ON_TIME_TICK_GAP_MS) onTimeTicks = 0;
989
+ else if (sinceLastTick >= TICK_MS / 2) onTimeTicks++;
990
+ if (onTimeTicks >= ON_TIME_TICKS_TO_RESUME) endPageHold(now, hiddenGapMs);
991
+ };
992
+ const watchPage = () => {
993
+ const page = getPage();
994
+ if (watchingPage || !page) return;
995
+ watchingPage = true;
996
+ pageHidden = page.visibilityState === "hidden";
997
+ page.addEventListener("visibilitychange", handleVisibilityChange);
998
+ };
999
+ const hold = () => {
1000
+ holds++;
1001
+ if (ticker) return;
1002
+ watchPage();
1003
+ const now = Date.now();
1004
+ followClock(now);
1005
+ lastRunAt = now;
1006
+ lastTickAt = now;
1007
+ ticker = setInterval(tick, TICK_MS);
1008
+ };
1009
+ const release = () => {
1010
+ holds--;
1011
+ if (holds > 0 || !ticker) return;
1012
+ clearInterval(ticker);
1013
+ ticker = null;
1014
+ };
1015
+ /**
1016
+ * Shifts the times kept here when the clock has moved back since the runtime last ran, so that
1017
+ * time since a resume, or since the host marked a suspension, keeps counting from where it was
1018
+ */
1019
+ const followClock = (now) => {
1020
+ if (now >= lastRunAt) return;
1021
+ const movedBackMs = lastRunAt - now;
1022
+ clockMovedBackMs += movedBackMs;
1023
+ lastRunAt = now;
1024
+ lastTickAt -= movedBackMs;
1025
+ lastResumedAt -= movedBackMs;
1026
+ if (suspendedSince !== null) suspendedSince -= movedBackMs;
1027
+ };
1028
+ /**
1029
+ * Records that the JS runtime is running now. When it last ran longer than
1030
+ * `SUSPENSION_GAP_MS` (or `HOST_SUSPENSION_GAP_MS`) ago, it was suspended in between, and the resume listeners run before
1031
+ * this returns. When the host or a hidden page holds the suspension, they run once it ends.
1032
+ * Cheap enough to call at the start of every timer callback that measures time.
1033
+ */
1034
+ const checkSuspension = () => {
1035
+ const now = Date.now();
1036
+ followClock(now);
1037
+ const suspendedMs = ticker ? now - lastRunAt : 0;
1038
+ lastRunAt = now;
1039
+ if (pageHidden) {
1040
+ hiddenGapMs = Math.max(hiddenGapMs, suspendedMs);
1041
+ return;
1042
+ }
1043
+ if (suspendedSince !== null || suspendedMs <= suspensionGapMs()) return;
1044
+ resume(now, suspendedMs);
1045
+ };
1046
+ const resume = (now, suspendedMs) => {
1047
+ lastResumedAt = now;
1048
+ for (const listener of [...listeners]) try {
1049
+ listener(suspendedMs);
1050
+ } catch (error) {
1051
+ queueMicrotask(() => {
1052
+ throw error;
1053
+ });
1054
+ }
1055
+ };
1056
+ /**
1057
+ * Marks the JS runtime suspended (`true`) or running again (`false`), for a host that knows
1058
+ * when the runtime is frozen or cut off (it may keep running). While suspended,
1059
+ * `setAwakeTimeout` timeouts don't fire. `setSuspended(false)` is a resume: the timeouts start
1060
+ * over, and the resume listeners run with the time since `setSuspended(true)`. When the page
1061
+ * is also held suspended (hidden, with a gap between ticks), the resume waits until it is
1062
+ * shown or its ticks run on time again.
1063
+ *
1064
+ * From the first call on, a gap between ticks counts as a suspension only from
1065
+ * `HOST_SUSPENSION_GAP_MS` (15s), so that a stall of the JS thread doesn't restart the
1066
+ * timeouts. A host calls it at startup with the runtime's state, for that to apply from then.
1067
+ *
1068
+ * The state is global to the module: the mark reaches the code that reads it (such as
1069
+ * `ChainConnectorDot`) only when both load the same copy of `@talismn/util`. A second copy in
1070
+ * the bundle, from mismatched `@talismn/*` versions or from CJS and ESM builds side by side,
1071
+ * keeps a state of its own, without an error.
1072
+ */
1073
+ const setSuspended = (suspended) => {
1074
+ hostMarksSuspensions = true;
1075
+ if (suspended) {
1076
+ checkSuspension();
1077
+ suspendedSince ??= Date.now();
1078
+ return;
1079
+ }
1080
+ if (suspendedSince === null) return;
1081
+ const now = Date.now();
1082
+ followClock(now);
1083
+ const suspendedMs = now - suspendedSince;
1084
+ suspendedSince = null;
1085
+ endHold(now, suspendedMs, true);
1086
+ };
1087
+ /**
1088
+ * Whether the runtime is held suspended until a later resume: marked by the host
1089
+ * (`setSuspended(true)`), or a hidden page whose timers have stopped or been throttled
1090
+ */
1091
+ const isSuspended = () => {
1092
+ checkSuspension();
1093
+ return isHeld();
1094
+ };
1095
+ /**
1096
+ * When the JS runtime last resumed from a suspension (`Date.now()` time), or -Infinity when
1097
+ * no suspension has been seen. A freeze is only seen while something is watching (an
1098
+ * `onResume` listener or a pending `setAwakeTimeout`); the end of a suspension the host
1099
+ * marked (`setSuspended(false)`) is a resume in any case.
1100
+ */
1101
+ const getLastResumedAt = () => {
1102
+ checkSuspension();
1103
+ return lastResumedAt;
1104
+ };
1105
+ /**
1106
+ * Calls `listener` each time the JS runtime resumes from a suspension, with how long it was
1107
+ * suspended for. Returns the function that removes it.
1108
+ */
1109
+ const onResume = (listener) => {
1110
+ listeners.add(listener);
1111
+ hold();
1112
+ let removed = false;
1113
+ return () => {
1114
+ if (removed) return;
1115
+ removed = true;
1116
+ listeners.delete(listener);
1117
+ release();
1118
+ };
1119
+ };
1120
+ /**
1121
+ * Like `setTimeout`, but time the JS runtime spends suspended does not count. When the runtime
1122
+ * resumes from a suspension before the timeout is up, the timeout starts over from the resume,
1123
+ * so the work it guards gets its full time again. Returns the function that cancels it.
1124
+ */
1125
+ const setAwakeTimeout = (callback, ms) => {
1126
+ hold();
1127
+ let startedAt = Date.now();
1128
+ let clockMovedBackAtStartMs = clockMovedBackMs;
1129
+ let token = null;
1130
+ let done = false;
1131
+ const finish = () => {
1132
+ if (done) return;
1133
+ done = true;
1134
+ if (token) clearTimeout(token);
1135
+ token = null;
1136
+ release();
1137
+ };
1138
+ const fire = () => {
1139
+ checkSuspension();
1140
+ if (done) return;
1141
+ if (isHeld()) {
1142
+ token = setTimeout(fire, ms);
1143
+ return;
1144
+ }
1145
+ startedAt -= clockMovedBackMs - clockMovedBackAtStartMs;
1146
+ clockMovedBackAtStartMs = clockMovedBackMs;
1147
+ const now = Date.now();
1148
+ const remaining = ms - (now - Math.min(now, Math.max(startedAt, lastResumedAt)));
1149
+ if (remaining > 0) {
1150
+ token = setTimeout(fire, remaining);
1151
+ return;
1152
+ }
1153
+ finish();
1154
+ callback();
1155
+ };
1156
+ token = setTimeout(fire, ms);
1157
+ return finish;
1158
+ };
859
1159
  // src/throwAfter.ts
860
1160
  const throwAfter = (ms, reason) => new Promise((_, reject) => setTimeout(() => reject(new Error(reason)), ms));
861
1161
  // src/tokensToPlanck.ts
@@ -908,6 +1208,6 @@ const validateHexString = (str) => {
908
1208
  if (str.startsWith("0x")) return str;
909
1209
  throw new Error("Expected a hex string");
910
1210
  };
911
- export { BigMath, DEFAULT_TIME_SLICE_BUDGET_MS, Deferred, LruMap, MAX_DECIMALS_FORMAT, REGEX_HEX_STRING, addTrailingSlash, arrayItemsEqualWithYield, assert, concatMapChunked, createTimeSlicer, firstThenDebounce, forEachWithYield, formatCompactPrice, formatCurrency, formatCurrencyToParts, formatDecimals, formatPrice, getCurrencyFractionDigits, 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 };
1211
+ 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 };
912
1212
 
913
1213
  //# sourceMappingURL=index.mjs.map