@talismn/util 2.2.0 → 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
@@ -856,6 +856,301 @@ function splitSubject(subject) {
856
856
  * stripHexPrefix("1234") // "1234"
857
857
  **/
858
858
  const stripHexPrefix = (str) => str.startsWith("0x") ? str.slice(2) : str;
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
+ };
859
1154
  // src/throwAfter.ts
860
1155
  const throwAfter = (ms, reason) => new Promise((_, reject) => setTimeout(() => reject(new Error(reason)), ms));
861
1156
  // src/tokensToPlanck.ts
@@ -908,6 +1203,6 @@ const validateHexString = (str) => {
908
1203
  if (str.startsWith("0x")) return str;
909
1204
  throw new Error("Expected a hex string");
910
1205
  };
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 };
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 };
912
1207
 
913
1208
  //# sourceMappingURL=index.mjs.map