heliumts 0.9.6 → 0.10.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/README.md +39 -14
- package/dist/bin/helium.js +19 -10
- package/dist/bin/helium.js.map +1 -1
- package/dist/client/Router.d.ts.map +1 -1
- package/dist/client/Router.js +2 -4
- package/dist/client/Router.js.map +1 -1
- package/dist/client/callMethod.d.ts +8 -0
- package/dist/client/callMethod.d.ts.map +1 -0
- package/dist/client/callMethod.js +9 -0
- package/dist/client/callMethod.js.map +1 -0
- package/dist/client/index.d.ts +3 -2
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +2 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/rpcClient.d.ts +7 -37
- package/dist/client/rpcClient.d.ts.map +1 -1
- package/dist/client/rpcClient.js +118 -749
- package/dist/client/rpcClient.js.map +1 -1
- package/dist/client/rpcStreaming.d.ts +10 -0
- package/dist/client/rpcStreaming.d.ts.map +1 -0
- package/dist/client/rpcStreaming.js +125 -0
- package/dist/client/rpcStreaming.js.map +1 -0
- package/dist/client/useStreaming.d.ts +26 -0
- package/dist/client/useStreaming.d.ts.map +1 -0
- package/dist/client/useStreaming.js +126 -0
- package/dist/client/useStreaming.js.map +1 -0
- package/dist/runtime/protocol.d.ts +14 -0
- package/dist/runtime/protocol.d.ts.map +1 -1
- package/dist/runtime/protocol.js +3 -1
- package/dist/runtime/protocol.js.map +1 -1
- package/dist/server/config.d.ts +16 -101
- package/dist/server/config.d.ts.map +1 -1
- package/dist/server/config.js +5 -27
- package/dist/server/config.js.map +1 -1
- package/dist/server/context.d.ts +8 -6
- package/dist/server/context.d.ts.map +1 -1
- package/dist/server/context.js.map +1 -1
- package/dist/server/defineWorker.d.ts +1 -1
- package/dist/server/defineWorker.d.ts.map +1 -1
- package/dist/server/defineWorker.js +2 -1
- package/dist/server/defineWorker.js.map +1 -1
- package/dist/server/devServer.d.ts +1 -1
- package/dist/server/devServer.d.ts.map +1 -1
- package/dist/server/devServer.js +13 -250
- package/dist/server/devServer.js.map +1 -1
- package/dist/server/httpCompression.d.ts +8 -0
- package/dist/server/httpCompression.d.ts.map +1 -0
- package/dist/server/httpCompression.js +58 -0
- package/dist/server/httpCompression.js.map +1 -0
- package/dist/server/httpRouter.d.ts.map +1 -1
- package/dist/server/httpRouter.js +5 -2
- package/dist/server/httpRouter.js.map +1 -1
- package/dist/server/httpRpc.d.ts +10 -0
- package/dist/server/httpRpc.d.ts.map +1 -0
- package/dist/server/httpRpc.js +186 -0
- package/dist/server/httpRpc.js.map +1 -0
- package/dist/server/prodServer.d.ts +3 -1
- package/dist/server/prodServer.d.ts.map +1 -1
- package/dist/server/prodServer.js +36 -229
- package/dist/server/prodServer.js.map +1 -1
- package/dist/server/rateLimiter.d.ts +6 -36
- package/dist/server/rateLimiter.d.ts.map +1 -1
- package/dist/server/rateLimiter.js +18 -125
- package/dist/server/rateLimiter.js.map +1 -1
- package/dist/server/requestSignal.d.ts +10 -0
- package/dist/server/requestSignal.d.ts.map +1 -0
- package/dist/server/requestSignal.js +79 -0
- package/dist/server/requestSignal.js.map +1 -0
- package/dist/server/rpcRegistry.d.ts +10 -18
- package/dist/server/rpcRegistry.d.ts.map +1 -1
- package/dist/server/rpcRegistry.js +181 -269
- package/dist/server/rpcRegistry.js.map +1 -1
- package/dist/server/serializer.js +12 -6
- package/dist/server/serializer.js.map +1 -1
- package/dist/vite/heliumPlugin.d.ts.map +1 -1
- package/dist/vite/heliumPlugin.js +77 -43
- package/dist/vite/heliumPlugin.js.map +1 -1
- package/dist/vite/ssg.d.ts.map +1 -1
- package/dist/vite/ssg.js +20 -1
- package/dist/vite/ssg.js.map +1 -1
- package/package.json +2 -4
package/dist/client/rpcClient.js
CHANGED
|
@@ -1,789 +1,158 @@
|
|
|
1
1
|
import { decode as msgpackDecode, encode as msgpackEncode } from "@msgpack/msgpack";
|
|
2
2
|
import { RpcError } from "./RpcError.js";
|
|
3
|
-
|
|
4
|
-
if (data.buffer instanceof ArrayBuffer && data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
|
|
5
|
-
return data.buffer;
|
|
6
|
-
}
|
|
7
|
-
const buffer = new ArrayBuffer(data.byteLength);
|
|
8
|
-
new Uint8Array(buffer).set(data);
|
|
9
|
-
return buffer;
|
|
10
|
-
}
|
|
11
|
-
// Read build-time config with fallback defaults
|
|
12
|
-
const configuredTransport = typeof __HELIUM_RPC_TRANSPORT__ !== "undefined" ? __HELIUM_RPC_TRANSPORT__ : "websocket";
|
|
13
|
-
const configuredAutoHttpOnMobile = typeof __HELIUM_RPC_AUTO_HTTP_ON_MOBILE__ !== "undefined" ? __HELIUM_RPC_AUTO_HTTP_ON_MOBILE__ : false;
|
|
14
|
-
const configuredTokenValidityMs = typeof __HELIUM_RPC_TOKEN_VALIDITY_MS__ !== "undefined" && Number.isFinite(__HELIUM_RPC_TOKEN_VALIDITY_MS__) && __HELIUM_RPC_TOKEN_VALIDITY_MS__ > 0
|
|
3
|
+
const tokenValidityMs = typeof __HELIUM_RPC_TOKEN_VALIDITY_MS__ !== "undefined" && Number.isFinite(__HELIUM_RPC_TOKEN_VALIDITY_MS__) && __HELIUM_RPC_TOKEN_VALIDITY_MS__ > 0
|
|
15
4
|
? __HELIUM_RPC_TOKEN_VALIDITY_MS__
|
|
16
5
|
: 30000;
|
|
17
|
-
const
|
|
6
|
+
const maxBatchSize = typeof __HELIUM_RPC_MAX_BATCH_SIZE__ !== "undefined" && Number.isInteger(__HELIUM_RPC_MAX_BATCH_SIZE__) && __HELIUM_RPC_MAX_BATCH_SIZE__ > 0
|
|
18
7
|
? __HELIUM_RPC_MAX_BATCH_SIZE__
|
|
19
8
|
: 20;
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
* Check if auto HTTP on mobile is enabled (from helium.config.js).
|
|
28
|
-
*/
|
|
29
|
-
export function isAutoHttpOnMobileEnabled() {
|
|
30
|
-
return configuredAutoHttpOnMobile;
|
|
31
|
-
}
|
|
32
|
-
function isMobileDevice() {
|
|
33
|
-
if (typeof navigator === "undefined") {
|
|
34
|
-
return false;
|
|
35
|
-
}
|
|
36
|
-
const MOBILE_BREAKPOINT_MAX_WIDTH = 1024; // 1024px or less is a common breakpoint for mobile devices
|
|
37
|
-
const nav = navigator;
|
|
38
|
-
if (nav.userAgentData?.mobile === true) {
|
|
39
|
-
return true;
|
|
40
|
-
}
|
|
41
|
-
const userAgent = navigator.userAgent || "";
|
|
42
|
-
if (/Android|iPhone|iPad|iPod|IEMobile|Opera Mini|Mobi/i.test(userAgent)) {
|
|
43
|
-
return true;
|
|
44
|
-
}
|
|
45
|
-
if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
|
|
46
|
-
if (window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT_MAX_WIDTH}px)`).matches) {
|
|
47
|
-
return true;
|
|
48
|
-
}
|
|
49
|
-
if (window.matchMedia("(pointer: coarse)").matches || window.matchMedia("(any-pointer: coarse)").matches) {
|
|
50
|
-
return true;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
return navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1;
|
|
54
|
-
}
|
|
55
|
-
export function isMobileRpcDevice() {
|
|
56
|
-
return isMobileDevice();
|
|
57
|
-
}
|
|
58
|
-
// Detect if we should prefer HTTP transport (mobile/slow networks)
|
|
59
|
-
function shouldUseHttpTransport() {
|
|
60
|
-
if (isTemporaryHttpFallbackActive()) {
|
|
61
|
-
return true;
|
|
62
|
-
}
|
|
63
|
-
if (configuredTransport === "http") {
|
|
64
|
-
return true;
|
|
65
|
-
}
|
|
66
|
-
const mobileDevice = isMobileDevice();
|
|
67
|
-
if (mobileDevice && configuredAutoHttpOnMobile) {
|
|
68
|
-
return true;
|
|
69
|
-
}
|
|
70
|
-
if (configuredTransport === "websocket") {
|
|
71
|
-
return false;
|
|
72
|
-
}
|
|
73
|
-
// Auto mode: check if mobile HTTP optimization is enabled
|
|
74
|
-
if (!configuredAutoHttpOnMobile) {
|
|
75
|
-
return false;
|
|
76
|
-
}
|
|
77
|
-
// For non-mobile devices, prefer HTTP on slow/cellular connections
|
|
78
|
-
if (typeof navigator !== "undefined") {
|
|
79
|
-
const conn = navigator.connection;
|
|
80
|
-
if (conn) {
|
|
81
|
-
// Use HTTP for cellular connections or slow effective types
|
|
82
|
-
const slowTypes = ["slow-2g", "2g", "3g"];
|
|
83
|
-
if (conn.type === "cellular" || (conn.effectiveType && slowTypes.includes(conn.effectiveType))) {
|
|
84
|
-
return true;
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
return false;
|
|
9
|
+
const REQUEST_TIMEOUT_MS = 30000;
|
|
10
|
+
let cachedToken;
|
|
11
|
+
let tokenExpiresAt = 0;
|
|
12
|
+
let tokenRequest = null;
|
|
13
|
+
let requestId = 0;
|
|
14
|
+
export function createRpcRequest(method, args) {
|
|
15
|
+
return { id: requestId++, method, args };
|
|
89
16
|
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
if (isBatchScheduled) {
|
|
94
|
-
return;
|
|
17
|
+
function waitWithSignal(promise, signal) {
|
|
18
|
+
if (signal.aborted) {
|
|
19
|
+
return Promise.reject(signal.reason);
|
|
95
20
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
const onAbort = () => reject(signal.reason);
|
|
23
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
24
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
100
25
|
});
|
|
101
26
|
}
|
|
102
|
-
function
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
// Keep each HTTP envelope within the same cap enforced by the server.
|
|
106
|
-
// Groups run concurrently and a transport failure rejects only its own calls.
|
|
107
|
-
for (let offset = 0; offset < batch.length; offset += configuredMaxBatchSize) {
|
|
108
|
-
const group = batch.slice(offset, offset + configuredMaxBatchSize);
|
|
109
|
-
void sendBatchHttp(group).catch((error) => {
|
|
110
|
-
for (const item of group) {
|
|
111
|
-
item.reject(error);
|
|
112
|
-
}
|
|
113
|
-
});
|
|
27
|
+
async function getToken(signal, rejectedToken) {
|
|
28
|
+
if (cachedToken === rejectedToken) {
|
|
29
|
+
cachedToken = undefined;
|
|
114
30
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const headers = {
|
|
124
|
-
"Content-Type": "application/msgpack",
|
|
125
|
-
Accept: "application/msgpack",
|
|
126
|
-
};
|
|
127
|
-
if (token) {
|
|
128
|
-
headers["X-Helium-Token"] = token;
|
|
129
|
-
}
|
|
130
|
-
return fetch("/__helium__/rpc", {
|
|
31
|
+
if (cachedToken && Date.now() < tokenExpiresAt) {
|
|
32
|
+
return cachedToken;
|
|
33
|
+
}
|
|
34
|
+
if (!tokenRequest) {
|
|
35
|
+
const controller = new AbortController();
|
|
36
|
+
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
37
|
+
tokenRequest = (async () => {
|
|
38
|
+
const response = await fetch("/__helium__/refresh-token", {
|
|
131
39
|
method: "POST",
|
|
132
|
-
headers,
|
|
133
|
-
|
|
40
|
+
headers: { "X-Requested-With": "HeliumRPC" },
|
|
41
|
+
credentials: "same-origin",
|
|
42
|
+
cache: "no-store",
|
|
134
43
|
signal: controller.signal,
|
|
135
44
|
});
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
const
|
|
140
|
-
if (
|
|
141
|
-
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
else {
|
|
159
|
-
item.reject(new RpcError(res.error, res.stats));
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
else {
|
|
163
|
-
item.reject(new RpcError("No response for request"));
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
catch (error) {
|
|
168
|
-
if (controller.signal.aborted) {
|
|
169
|
-
throw new RpcError("Request timed out");
|
|
170
|
-
}
|
|
171
|
-
throw error;
|
|
172
|
-
}
|
|
173
|
-
finally {
|
|
174
|
-
clearTimeout(timeout);
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
// ============================================================================
|
|
178
|
-
// WebSocket Transport (original implementation)
|
|
179
|
-
// ============================================================================
|
|
180
|
-
let socket = null;
|
|
181
|
-
let connectionPromise = null;
|
|
182
|
-
const pending = new Map();
|
|
183
|
-
const pendingTimeouts = new Map();
|
|
184
|
-
const BLOCKED_HTTP_STATUSES = new Set([401, 403, 429]);
|
|
185
|
-
const BLOCKED_WS_CLOSE_CODES = new Set([1008, 1011, 1013]);
|
|
186
|
-
const BLOCKED_RETRY_THRESHOLD = 3;
|
|
187
|
-
const BLOCKED_RETRY_WINDOW_MS = 1000;
|
|
188
|
-
const BLOCKED_RELOAD_COOLDOWN_MS = 120000;
|
|
189
|
-
const BLOCKED_RELOAD_KEY = "helium:blocked-reload-ts";
|
|
190
|
-
const blockedAttempts = new Map();
|
|
191
|
-
let lastBlockedReloadAt = 0;
|
|
192
|
-
function shouldAutoReloadOnBlock(now) {
|
|
193
|
-
if (typeof window === "undefined") {
|
|
194
|
-
return false;
|
|
195
|
-
}
|
|
196
|
-
try {
|
|
197
|
-
const stored = window.sessionStorage.getItem(BLOCKED_RELOAD_KEY);
|
|
198
|
-
const storedTs = stored ? Number(stored) : 0;
|
|
199
|
-
if (storedTs && now - storedTs < BLOCKED_RELOAD_COOLDOWN_MS) {
|
|
200
|
-
return false;
|
|
201
|
-
}
|
|
202
|
-
window.sessionStorage.setItem(BLOCKED_RELOAD_KEY, String(now));
|
|
203
|
-
return true;
|
|
204
|
-
}
|
|
205
|
-
catch {
|
|
206
|
-
if (now - lastBlockedReloadAt < BLOCKED_RELOAD_COOLDOWN_MS) {
|
|
207
|
-
return false;
|
|
208
|
-
}
|
|
209
|
-
lastBlockedReloadAt = now;
|
|
210
|
-
return true;
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
function shouldTriggerBlockedAction(source, now) {
|
|
214
|
-
const state = blockedAttempts.get(source);
|
|
215
|
-
if (!state || now - state.lastTs > BLOCKED_RETRY_WINDOW_MS) {
|
|
216
|
-
blockedAttempts.set(source, { count: 1, lastTs: now });
|
|
217
|
-
return false;
|
|
218
|
-
}
|
|
219
|
-
const nextCount = state.count + 1;
|
|
220
|
-
blockedAttempts.set(source, { count: nextCount, lastTs: now });
|
|
221
|
-
return nextCount > BLOCKED_RETRY_THRESHOLD;
|
|
222
|
-
}
|
|
223
|
-
function dispatchBlockedEvent(detail) {
|
|
224
|
-
if (typeof window === "undefined") {
|
|
225
|
-
return;
|
|
226
|
-
}
|
|
227
|
-
window.dispatchEvent(new CustomEvent("helium:blocked", {
|
|
228
|
-
detail,
|
|
229
|
-
}));
|
|
230
|
-
}
|
|
231
|
-
function handleBlockedResponse(status, source) {
|
|
232
|
-
if (!BLOCKED_HTTP_STATUSES.has(status)) {
|
|
233
|
-
return;
|
|
234
|
-
}
|
|
235
|
-
const now = Date.now();
|
|
236
|
-
if (!shouldTriggerBlockedAction(source, now)) {
|
|
237
|
-
return;
|
|
238
|
-
}
|
|
239
|
-
dispatchBlockedEvent({ status, source });
|
|
240
|
-
if (shouldAutoReloadOnBlock(now) && typeof window.location?.reload === "function") {
|
|
241
|
-
window.location.reload();
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
function handleBlockedSocketClose(code) {
|
|
245
|
-
if (!BLOCKED_WS_CLOSE_CODES.has(code)) {
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
const now = Date.now();
|
|
249
|
-
if (!shouldTriggerBlockedAction("rpc-websocket", now)) {
|
|
250
|
-
return;
|
|
251
|
-
}
|
|
252
|
-
dispatchBlockedEvent({ code, source: "rpc-websocket" });
|
|
253
|
-
if (shouldAutoReloadOnBlock(now) && typeof window.location?.reload === "function") {
|
|
254
|
-
window.location.reload();
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
// ── Connection resilience constants ──────────────────────────────────────────
|
|
258
|
-
/** How long (ms) the page must be hidden before we consider the WebSocket stale. */
|
|
259
|
-
const STALE_THRESHOLD_MS = 15000;
|
|
260
|
-
/** Max time (ms) to wait for a WebSocket connection to open. */
|
|
261
|
-
const SOCKET_CONNECT_TIMEOUT_MS = 10000;
|
|
262
|
-
/** Duration (ms) to temporarily force HTTP after repeated WebSocket failures. */
|
|
263
|
-
const WS_FAILURE_HTTP_COOLDOWN_MS = 60000;
|
|
264
|
-
/** Max time (ms) to wait for a response before timing out a request. */
|
|
265
|
-
const REQUEST_TIMEOUT_MS = 30000;
|
|
266
|
-
/** Number of automatic retries on retriable connection errors. */
|
|
267
|
-
const MAX_RETRIES = 3;
|
|
268
|
-
/** Base delay (ms) for exponential backoff between retries (doubles each attempt). */
|
|
269
|
-
const RETRY_BASE_DELAY_MS = 500;
|
|
270
|
-
/** Maximum delay (ms) cap for backoff to avoid excessively long waits. */
|
|
271
|
-
const RETRY_MAX_DELAY_MS = 5000;
|
|
272
|
-
/** Timestamp when the page was last hidden (for visibility-change detection). */
|
|
273
|
-
let lastHiddenTimestamp = null;
|
|
274
|
-
let forceHttpUntilTimestamp = 0;
|
|
275
|
-
function isTemporaryHttpFallbackActive(now = Date.now()) {
|
|
276
|
-
return now < forceHttpUntilTimestamp;
|
|
277
|
-
}
|
|
278
|
-
function activateTemporaryHttpFallback(now = Date.now()) {
|
|
279
|
-
forceHttpUntilTimestamp = now + WS_FAILURE_HTTP_COOLDOWN_MS;
|
|
280
|
-
}
|
|
281
|
-
// ── Pending-request helpers ──────────────────────────────────────────────────
|
|
282
|
-
/**
|
|
283
|
-
* Register a pending request with an automatic timeout safeguard.
|
|
284
|
-
* If no response arrives within REQUEST_TIMEOUT_MS the promise is rejected
|
|
285
|
-
* so the caller's retry logic can kick in.
|
|
286
|
-
*/
|
|
287
|
-
function trackPending(id, resolve, reject) {
|
|
288
|
-
pending.set(id, { resolve, reject });
|
|
289
|
-
const timer = setTimeout(() => {
|
|
290
|
-
const entry = pending.get(id);
|
|
291
|
-
if (entry) {
|
|
292
|
-
pending.delete(id);
|
|
293
|
-
pendingTimeouts.delete(id);
|
|
294
|
-
entry.reject(new RpcError("Request timed out"));
|
|
295
|
-
}
|
|
296
|
-
}, REQUEST_TIMEOUT_MS);
|
|
297
|
-
pendingTimeouts.set(id, timer);
|
|
298
|
-
}
|
|
299
|
-
/**
|
|
300
|
-
* Remove a pending request and clear its timeout.
|
|
301
|
-
* Returns the entry so the caller can resolve/reject it.
|
|
302
|
-
*/
|
|
303
|
-
function removePending(id) {
|
|
304
|
-
const entry = pending.get(id);
|
|
305
|
-
if (!entry) {
|
|
306
|
-
return undefined;
|
|
307
|
-
}
|
|
308
|
-
pending.delete(id);
|
|
309
|
-
const timer = pendingTimeouts.get(id);
|
|
310
|
-
if (timer) {
|
|
311
|
-
clearTimeout(timer);
|
|
312
|
-
pendingTimeouts.delete(id);
|
|
313
|
-
}
|
|
314
|
-
return entry;
|
|
315
|
-
}
|
|
316
|
-
/** Reject every in-flight request (e.g. when the socket closes unexpectedly). */
|
|
317
|
-
function rejectAllPending(reason) {
|
|
318
|
-
for (const timer of pendingTimeouts.values()) {
|
|
319
|
-
clearTimeout(timer);
|
|
320
|
-
}
|
|
321
|
-
pendingTimeouts.clear();
|
|
322
|
-
const entries = [...pending.entries()];
|
|
323
|
-
pending.clear();
|
|
324
|
-
for (const [, entry] of entries) {
|
|
325
|
-
entry.reject(reason);
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
// ── Reconnection helpers ─────────────────────────────────────────────────────
|
|
329
|
-
/**
|
|
330
|
-
* Force-close the current WebSocket so the next call creates a fresh
|
|
331
|
-
* connection (which fetches a brand-new token).
|
|
332
|
-
*/
|
|
333
|
-
function forceReconnect() {
|
|
334
|
-
const oldSocket = socket;
|
|
335
|
-
socket = null;
|
|
336
|
-
connectionPromise = null;
|
|
337
|
-
if (oldSocket) {
|
|
338
|
-
// Detach handlers to avoid double-rejecting pending from the close event
|
|
339
|
-
oldSocket.onclose = null;
|
|
340
|
-
oldSocket.onerror = null;
|
|
341
|
-
oldSocket.onmessage = null;
|
|
342
|
-
oldSocket.close();
|
|
343
|
-
}
|
|
344
|
-
// Reject all in-flight requests – callers with retry logic will resend
|
|
345
|
-
rejectAllPending(new Error("Connection reset"));
|
|
346
|
-
}
|
|
347
|
-
function reconnectIfLikelyStale(force = false) {
|
|
348
|
-
if (!socket) {
|
|
349
|
-
lastHiddenTimestamp = null;
|
|
350
|
-
return;
|
|
351
|
-
}
|
|
352
|
-
if (force) {
|
|
353
|
-
forceReconnect();
|
|
354
|
-
lastHiddenTimestamp = null;
|
|
355
|
-
return;
|
|
356
|
-
}
|
|
357
|
-
if (lastHiddenTimestamp !== null) {
|
|
358
|
-
const hiddenDuration = Date.now() - lastHiddenTimestamp;
|
|
359
|
-
if (hiddenDuration > STALE_THRESHOLD_MS) {
|
|
360
|
-
forceReconnect();
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
lastHiddenTimestamp = null;
|
|
364
|
-
}
|
|
365
|
-
/** Determine whether an error warrants an automatic retry. */
|
|
366
|
-
function isRetriableError(err) {
|
|
367
|
-
// Network / connection errors are always retriable
|
|
368
|
-
if (err instanceof Error && !(err instanceof RpcError)) {
|
|
369
|
-
return true;
|
|
370
|
-
}
|
|
371
|
-
// Timed-out requests are retriable (socket may have died silently)
|
|
372
|
-
if (err instanceof RpcError && err.message === "Request timed out") {
|
|
373
|
-
return true;
|
|
374
|
-
}
|
|
375
|
-
return false;
|
|
376
|
-
}
|
|
377
|
-
// Clean up WebSocket connection on HMR (Hot Module Replacement)
|
|
378
|
-
if (import.meta.hot) {
|
|
379
|
-
import.meta.hot.dispose(() => {
|
|
380
|
-
if (socket) {
|
|
381
|
-
socket.onclose = null;
|
|
382
|
-
socket.close();
|
|
383
|
-
socket = null;
|
|
384
|
-
connectionPromise = null;
|
|
385
|
-
}
|
|
386
|
-
clearTokenRefreshTimer();
|
|
387
|
-
rejectAllPending(new Error("Module reloaded"));
|
|
388
|
-
});
|
|
389
|
-
}
|
|
390
|
-
let msgId = 0;
|
|
391
|
-
function nextId() {
|
|
392
|
-
return msgId++;
|
|
393
|
-
}
|
|
394
|
-
let cachedAuthToken;
|
|
395
|
-
let tokenRefreshTimer = null;
|
|
396
|
-
const TOKEN_REFRESH_MIN_DELAY_MS = 5000;
|
|
397
|
-
const TOKEN_REFRESH_RETRY_DELAY_MS = 5000;
|
|
398
|
-
const TOKEN_REFRESH_SAFETY_WINDOW_MS = Math.min(5000, Math.max(1000, Math.floor(configuredTokenValidityMs * 0.2)));
|
|
399
|
-
function clearTokenRefreshTimer() {
|
|
400
|
-
if (!tokenRefreshTimer) {
|
|
401
|
-
return;
|
|
402
|
-
}
|
|
403
|
-
clearTimeout(tokenRefreshTimer);
|
|
404
|
-
tokenRefreshTimer = null;
|
|
405
|
-
}
|
|
406
|
-
function parseTokenIssuedAt(token) {
|
|
407
|
-
const [timestampPart] = token.split(".");
|
|
408
|
-
if (!timestampPart) {
|
|
409
|
-
return null;
|
|
410
|
-
}
|
|
411
|
-
const issuedAt = Number.parseInt(timestampPart, 10);
|
|
412
|
-
if (!Number.isFinite(issuedAt) || issuedAt <= 0) {
|
|
413
|
-
return null;
|
|
414
|
-
}
|
|
415
|
-
return issuedAt;
|
|
416
|
-
}
|
|
417
|
-
function scheduleTokenRefreshFromToken(token) {
|
|
418
|
-
if (typeof window === "undefined") {
|
|
419
|
-
return;
|
|
420
|
-
}
|
|
421
|
-
const issuedAt = parseTokenIssuedAt(token);
|
|
422
|
-
if (!issuedAt) {
|
|
423
|
-
clearTokenRefreshTimer();
|
|
424
|
-
return;
|
|
425
|
-
}
|
|
426
|
-
const expiresAt = issuedAt + configuredTokenValidityMs;
|
|
427
|
-
const refreshAt = expiresAt - TOKEN_REFRESH_SAFETY_WINDOW_MS;
|
|
428
|
-
const delay = Math.max(TOKEN_REFRESH_MIN_DELAY_MS, refreshAt - Date.now());
|
|
429
|
-
clearTokenRefreshTimer();
|
|
430
|
-
tokenRefreshTimer = setTimeout(() => {
|
|
431
|
-
void fetchFreshToken(true).then((nextToken) => {
|
|
432
|
-
if (!nextToken) {
|
|
433
|
-
clearTokenRefreshTimer();
|
|
434
|
-
tokenRefreshTimer = setTimeout(() => {
|
|
435
|
-
void fetchFreshToken(true);
|
|
436
|
-
}, TOKEN_REFRESH_RETRY_DELAY_MS);
|
|
437
|
-
}
|
|
45
|
+
if (!response.ok) {
|
|
46
|
+
throw new RpcError(`RPC authorization failed (${response.status})`);
|
|
47
|
+
}
|
|
48
|
+
const result = (await response.json());
|
|
49
|
+
if (typeof result.token !== "string" || !result.token) {
|
|
50
|
+
throw new RpcError("Invalid RPC authorization response");
|
|
51
|
+
}
|
|
52
|
+
const issuedAt = Number.parseInt(result.token.split(".")[0], 10);
|
|
53
|
+
const safetyWindow = Math.min(5000, tokenValidityMs * 0.2);
|
|
54
|
+
cachedToken = result.token;
|
|
55
|
+
tokenExpiresAt = (Number.isFinite(issuedAt) && issuedAt > 0 ? issuedAt : Date.now()) + tokenValidityMs - safetyWindow;
|
|
56
|
+
return cachedToken;
|
|
57
|
+
})()
|
|
58
|
+
.catch((error) => {
|
|
59
|
+
if (controller.signal.aborted) {
|
|
60
|
+
throw new RpcError("RPC authorization timed out");
|
|
61
|
+
}
|
|
62
|
+
throw error;
|
|
63
|
+
})
|
|
64
|
+
.finally(() => {
|
|
65
|
+
clearTimeout(timeout);
|
|
66
|
+
tokenRequest = null;
|
|
438
67
|
});
|
|
439
|
-
}, delay);
|
|
440
|
-
}
|
|
441
|
-
function hasCachedToken() {
|
|
442
|
-
return Boolean(cachedAuthToken);
|
|
443
|
-
}
|
|
444
|
-
function setCachedToken(token) {
|
|
445
|
-
if (!token) {
|
|
446
|
-
cachedAuthToken = undefined;
|
|
447
|
-
clearTokenRefreshTimer();
|
|
448
|
-
return;
|
|
449
68
|
}
|
|
450
|
-
|
|
451
|
-
|
|
69
|
+
// A cancelled caller must not cancel another caller's shared token request.
|
|
70
|
+
return waitWithSignal(tokenRequest, signal);
|
|
452
71
|
}
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
try {
|
|
460
|
-
const response = await fetch("/__helium__/refresh-token", {
|
|
72
|
+
/** Shared HTTP request authentication for unary and streaming calls. */
|
|
73
|
+
export async function postRpc(endpoint, request, signal) {
|
|
74
|
+
const body = msgpackEncode(request);
|
|
75
|
+
const send = (token) => {
|
|
76
|
+
signal.throwIfAborted();
|
|
77
|
+
return fetch(endpoint, {
|
|
461
78
|
method: "POST",
|
|
462
|
-
headers: {
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
79
|
+
headers: { "Content-Type": "application/msgpack", "X-Helium-Token": token },
|
|
80
|
+
credentials: "same-origin",
|
|
81
|
+
cache: "no-store",
|
|
82
|
+
body,
|
|
83
|
+
signal,
|
|
466
84
|
});
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
const data = await response.json();
|
|
474
|
-
const token = data.token;
|
|
475
|
-
setCachedToken(token);
|
|
476
|
-
return token;
|
|
85
|
+
};
|
|
86
|
+
const token = await getToken(signal);
|
|
87
|
+
let response = await send(token);
|
|
88
|
+
if (response.status === 401) {
|
|
89
|
+
void response.body?.cancel().catch(() => { });
|
|
90
|
+
response = await send(await getToken(signal, token));
|
|
477
91
|
}
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
return undefined;
|
|
92
|
+
if (!response.ok) {
|
|
93
|
+
void response.body?.cancel().catch(() => { });
|
|
94
|
+
throw new RpcError(`RPC request failed (${response.status})`);
|
|
482
95
|
}
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
96
|
+
return response;
|
|
97
|
+
}
|
|
98
|
+
export function isRpcStats(value) {
|
|
99
|
+
if (!value || typeof value !== "object") {
|
|
100
|
+
return false;
|
|
487
101
|
}
|
|
102
|
+
const stats = value;
|
|
103
|
+
return typeof stats.remainingRequests === "number" && stats.remainingRequests >= 0 && typeof stats.resetInSeconds === "number" && stats.resetInSeconds >= 0;
|
|
488
104
|
}
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
const
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
if (data.length > 2 && data[0] === 0x1f && data[1] === 0x8b) {
|
|
503
|
-
try {
|
|
504
|
-
// Use DecompressionStream if available (Chrome 80+, Firefox 113+, Safari 16.4+)
|
|
505
|
-
if (typeof DecompressionStream !== "undefined") {
|
|
506
|
-
const ds = new DecompressionStream("gzip");
|
|
507
|
-
const stream = new Response(data).body;
|
|
508
|
-
if (stream) {
|
|
509
|
-
const decompressed = stream.pipeThrough(ds);
|
|
510
|
-
const reader = decompressed.getReader();
|
|
511
|
-
const chunks = [];
|
|
512
|
-
let totalSize = 0;
|
|
513
|
-
const MAX_DECOMPRESSED_SIZE = 10 * 1024 * 1024; // 10 MB
|
|
514
|
-
while (true) {
|
|
515
|
-
const { value, done } = await reader.read();
|
|
516
|
-
if (done) {
|
|
517
|
-
break;
|
|
518
|
-
}
|
|
519
|
-
totalSize += value.length;
|
|
520
|
-
if (totalSize > MAX_DECOMPRESSED_SIZE) {
|
|
521
|
-
reader.cancel();
|
|
522
|
-
console.error("Decompressed message exceeds size limit");
|
|
523
|
-
return;
|
|
524
|
-
}
|
|
525
|
-
chunks.push(value);
|
|
526
|
-
}
|
|
527
|
-
const combined = new Uint8Array(totalSize);
|
|
528
|
-
let offset = 0;
|
|
529
|
-
for (const chunk of chunks) {
|
|
530
|
-
combined.set(chunk, offset);
|
|
531
|
-
offset += chunk.length;
|
|
532
|
-
}
|
|
533
|
-
data = combined;
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
catch (err) {
|
|
538
|
-
console.error("Failed to decompress WebSocket message:", err);
|
|
539
|
-
return;
|
|
105
|
+
let pending = [];
|
|
106
|
+
let scheduled = false;
|
|
107
|
+
async function sendBatch(batch) {
|
|
108
|
+
const controller = new AbortController();
|
|
109
|
+
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
110
|
+
try {
|
|
111
|
+
const response = await postRpc("/__helium__/rpc", batch.map((item) => item.request), controller.signal);
|
|
112
|
+
const decoded = msgpackDecode(new Uint8Array(await response.arrayBuffer()));
|
|
113
|
+
const responses = Array.isArray(decoded) ? decoded : [decoded];
|
|
114
|
+
const byId = new Map();
|
|
115
|
+
for (const value of responses) {
|
|
116
|
+
if (value && typeof value === "object" && (typeof value.id === "string" || typeof value.id === "number") && typeof value.ok === "boolean" && isRpcStats(value.stats)) {
|
|
117
|
+
byId.set(value.id, value);
|
|
540
118
|
}
|
|
541
119
|
}
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
if (!entry) {
|
|
547
|
-
return;
|
|
120
|
+
for (const item of batch) {
|
|
121
|
+
const result = byId.get(item.request.id);
|
|
122
|
+
if (!result) {
|
|
123
|
+
item.reject(new RpcError("Invalid or missing RPC response"));
|
|
548
124
|
}
|
|
549
|
-
if (
|
|
550
|
-
|
|
125
|
+
else if (result.ok) {
|
|
126
|
+
item.resolve({ data: result.result, stats: result.stats });
|
|
551
127
|
}
|
|
552
128
|
else {
|
|
553
|
-
|
|
129
|
+
item.reject(new RpcError(typeof result.error === "string" ? result.error : "Invalid RPC error response", result.stats));
|
|
554
130
|
}
|
|
555
|
-
};
|
|
556
|
-
if (Array.isArray(msg)) {
|
|
557
|
-
msg.forEach(handleResponse);
|
|
558
|
-
}
|
|
559
|
-
else {
|
|
560
|
-
handleResponse(msg);
|
|
561
|
-
}
|
|
562
|
-
};
|
|
563
|
-
ws.onerror = () => {
|
|
564
|
-
// WebSocket errors are always followed by a close event.
|
|
565
|
-
// The close handler takes care of rejecting pending promises.
|
|
566
|
-
};
|
|
567
|
-
ws.onclose = (event) => {
|
|
568
|
-
handleBlockedSocketClose(event.code);
|
|
569
|
-
if (socket === ws) {
|
|
570
|
-
socket = null;
|
|
571
|
-
connectionPromise = null;
|
|
572
|
-
// Reject every in-flight request so callers can retry
|
|
573
|
-
rejectAllPending(new Error("WebSocket connection closed"));
|
|
574
131
|
}
|
|
575
|
-
};
|
|
576
|
-
return ws;
|
|
577
|
-
}
|
|
578
|
-
function waitForSocketOpen(ws) {
|
|
579
|
-
if (ws.readyState === WebSocket.OPEN) {
|
|
580
|
-
return Promise.resolve(ws);
|
|
581
|
-
}
|
|
582
|
-
return new Promise((resolve, reject) => {
|
|
583
|
-
const cleanup = () => {
|
|
584
|
-
ws.removeEventListener("open", handleOpen);
|
|
585
|
-
ws.removeEventListener("error", handleError);
|
|
586
|
-
ws.removeEventListener("close", handleClose);
|
|
587
|
-
clearTimeout(timeout);
|
|
588
|
-
};
|
|
589
|
-
const handleOpen = () => {
|
|
590
|
-
cleanup();
|
|
591
|
-
resolve(ws);
|
|
592
|
-
};
|
|
593
|
-
const handleError = () => {
|
|
594
|
-
cleanup();
|
|
595
|
-
if (socket === ws) {
|
|
596
|
-
socket = null;
|
|
597
|
-
}
|
|
598
|
-
setCachedToken(undefined);
|
|
599
|
-
reject(new Error("WebSocket connection failed"));
|
|
600
|
-
};
|
|
601
|
-
const handleClose = () => {
|
|
602
|
-
cleanup();
|
|
603
|
-
if (socket === ws) {
|
|
604
|
-
socket = null;
|
|
605
|
-
}
|
|
606
|
-
setCachedToken(undefined);
|
|
607
|
-
reject(new Error("WebSocket closed before opening"));
|
|
608
|
-
};
|
|
609
|
-
const timeout = setTimeout(() => {
|
|
610
|
-
cleanup();
|
|
611
|
-
if (socket === ws) {
|
|
612
|
-
socket = null;
|
|
613
|
-
}
|
|
614
|
-
setCachedToken(undefined);
|
|
615
|
-
reject(new Error("WebSocket connection timed out"));
|
|
616
|
-
}, SOCKET_CONNECT_TIMEOUT_MS);
|
|
617
|
-
ws.addEventListener("open", handleOpen);
|
|
618
|
-
ws.addEventListener("error", handleError);
|
|
619
|
-
ws.addEventListener("close", handleClose);
|
|
620
|
-
});
|
|
621
|
-
}
|
|
622
|
-
async function ensureSocketReady() {
|
|
623
|
-
// If we have an open socket, return it immediately
|
|
624
|
-
if (socket && socket.readyState === WebSocket.OPEN) {
|
|
625
|
-
return socket;
|
|
626
|
-
}
|
|
627
|
-
// If we have a connection in progress, reuse that promise
|
|
628
|
-
if (connectionPromise) {
|
|
629
|
-
return connectionPromise;
|
|
630
132
|
}
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
}
|
|
635
|
-
return waitForSocketOpen(socket);
|
|
636
|
-
})();
|
|
637
|
-
connectionPromise = pendingConnectPromise;
|
|
638
|
-
try {
|
|
639
|
-
return await pendingConnectPromise;
|
|
133
|
+
catch (error) {
|
|
134
|
+
const failure = controller.signal.aborted ? new RpcError("Request timed out") : error;
|
|
135
|
+
batch.forEach((item) => item.reject(failure));
|
|
640
136
|
}
|
|
641
137
|
finally {
|
|
642
|
-
|
|
643
|
-
connectionPromise = null;
|
|
644
|
-
}
|
|
138
|
+
clearTimeout(timeout);
|
|
645
139
|
}
|
|
646
140
|
}
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
catch (err) {
|
|
659
|
-
removePending(id);
|
|
660
|
-
reject(err);
|
|
141
|
+
/** Call an RPC method over HTTP; simultaneous calls share capped batch envelopes. */
|
|
142
|
+
export function rpcCall(method, args) {
|
|
143
|
+
const result = new Promise((resolve, reject) => pending.push({ request: createRpcRequest(method, args), resolve, reject }));
|
|
144
|
+
if (!scheduled) {
|
|
145
|
+
scheduled = true;
|
|
146
|
+
queueMicrotask(() => {
|
|
147
|
+
scheduled = false;
|
|
148
|
+
const batch = pending;
|
|
149
|
+
pending = [];
|
|
150
|
+
for (let offset = 0; offset < batch.length; offset += maxBatchSize) {
|
|
151
|
+
void sendBatch(batch.slice(offset, offset + maxBatchSize));
|
|
661
152
|
}
|
|
662
153
|
});
|
|
663
154
|
}
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
const req = { id, method: methodId, args };
|
|
667
|
-
return new Promise((resolve, reject) => {
|
|
668
|
-
trackPending(id, (v) => resolve(v), reject);
|
|
669
|
-
try {
|
|
670
|
-
// Always use msgpack encoding
|
|
671
|
-
const encoded = msgpackEncode(req);
|
|
672
|
-
ws.send(toArrayBuffer(encoded));
|
|
673
|
-
}
|
|
674
|
-
catch (err) {
|
|
675
|
-
removePending(id);
|
|
676
|
-
reject(err);
|
|
677
|
-
}
|
|
678
|
-
});
|
|
679
|
-
}
|
|
680
|
-
/**
|
|
681
|
-
* Make an RPC call using the appropriate transport.
|
|
682
|
-
* Automatically selects HTTP or WebSocket based on network conditions and configuration.
|
|
683
|
-
*
|
|
684
|
-
* Includes automatic retry logic: if a call fails due to a connection error
|
|
685
|
-
* (e.g. stale WebSocket after mobile browser was backgrounded), the client
|
|
686
|
-
* forces a fresh connection (with a new token) and retries once.
|
|
687
|
-
*/
|
|
688
|
-
export async function rpcCall(methodId, args) {
|
|
689
|
-
return rpcCallWithRetry(methodId, args, 0, {});
|
|
690
|
-
}
|
|
691
|
-
export async function rpcCallWithOptions(methodId, args, options) {
|
|
692
|
-
return rpcCallWithRetry(methodId, args, 0, options);
|
|
693
|
-
}
|
|
694
|
-
async function rpcCallViaHttpBatch(methodId, args) {
|
|
695
|
-
const id = nextId();
|
|
696
|
-
const req = { id, method: methodId, args };
|
|
697
|
-
return new Promise((resolve, reject) => {
|
|
698
|
-
pendingBatch.push({ req, resolve: resolve, reject });
|
|
699
|
-
scheduleBatch();
|
|
700
|
-
});
|
|
701
|
-
}
|
|
702
|
-
async function rpcCallWithRetry(methodId, args, attempt = 0, options = {}) {
|
|
703
|
-
try {
|
|
704
|
-
if (options.forceHttp || shouldUseHttpTransport()) {
|
|
705
|
-
return await rpcCallViaHttpBatch(methodId, args);
|
|
706
|
-
}
|
|
707
|
-
return await rpcCallWebSocket(methodId, args);
|
|
708
|
-
}
|
|
709
|
-
catch (err) {
|
|
710
|
-
if (attempt < MAX_RETRIES && isRetriableError(err)) {
|
|
711
|
-
// Force a fresh connection (fetches a new token)
|
|
712
|
-
forceReconnect();
|
|
713
|
-
// Exponential backoff with jitter: 500ms, 1000ms, 2000ms (capped at 5s)
|
|
714
|
-
const baseDelay = Math.min(RETRY_BASE_DELAY_MS * 2 ** attempt, RETRY_MAX_DELAY_MS);
|
|
715
|
-
const jitter = Math.random() * baseDelay * 0.3;
|
|
716
|
-
await new Promise((r) => setTimeout(r, baseDelay + jitter));
|
|
717
|
-
return rpcCallWithRetry(methodId, args, attempt + 1, options);
|
|
718
|
-
}
|
|
719
|
-
if (isRetriableError(err) && configuredTransport !== "http" && !options.forceHttp) {
|
|
720
|
-
activateTemporaryHttpFallback();
|
|
721
|
-
return rpcCallViaHttpBatch(methodId, args);
|
|
722
|
-
}
|
|
723
|
-
throw err;
|
|
724
|
-
}
|
|
725
|
-
}
|
|
726
|
-
/**
|
|
727
|
-
* Pre-establishes the WebSocket connection.
|
|
728
|
-
* Call this early (e.g., on page load) to avoid connection latency on first RPC call.
|
|
729
|
-
* This is especially beneficial on high-latency networks like mobile LTE.
|
|
730
|
-
* Note: Only effective when using WebSocket transport (not HTTP transport).
|
|
731
|
-
*/
|
|
732
|
-
export function preconnect() {
|
|
733
|
-
if (typeof window === "undefined") {
|
|
734
|
-
return;
|
|
735
|
-
}
|
|
736
|
-
// Only preconnect if we're using WebSocket transport
|
|
737
|
-
if (shouldUseHttpTransport()) {
|
|
738
|
-
return;
|
|
739
|
-
}
|
|
740
|
-
// Fire and forget - establishes connection in background
|
|
741
|
-
ensureSocketReady().catch(() => {
|
|
742
|
-
// Silently ignore preconnect failures, will retry on actual call
|
|
743
|
-
});
|
|
744
|
-
}
|
|
745
|
-
// Auto-preconnect when the module loads (browser only, WebSocket transport only)
|
|
746
|
-
if (typeof window !== "undefined" && typeof document !== "undefined") {
|
|
747
|
-
// Use requestIdleCallback if available, otherwise setTimeout
|
|
748
|
-
const schedulePreconnect = window.requestIdleCallback || ((cb) => setTimeout(cb, 1));
|
|
749
|
-
schedulePreconnect(() => preconnect());
|
|
750
|
-
}
|
|
751
|
-
// ============================================================================
|
|
752
|
-
// Visibility-change reconnection (critical for mobile browsers)
|
|
753
|
-
// ============================================================================
|
|
754
|
-
//
|
|
755
|
-
// Mobile browsers freeze or kill WebSocket connections when the tab is
|
|
756
|
-
// backgrounded. When the user returns the socket may *appear* open but
|
|
757
|
-
// is actually stale. We detect this via the Page Visibility API and
|
|
758
|
-
// proactively tear down the old connection so the next RPC call creates
|
|
759
|
-
// a fresh one (with a brand-new auth token).
|
|
760
|
-
// ============================================================================
|
|
761
|
-
if (typeof document !== "undefined") {
|
|
762
|
-
document.addEventListener("visibilitychange", () => {
|
|
763
|
-
if (document.hidden) {
|
|
764
|
-
lastHiddenTimestamp = Date.now();
|
|
765
|
-
}
|
|
766
|
-
else {
|
|
767
|
-
reconnectIfLikelyStale(false);
|
|
768
|
-
}
|
|
769
|
-
});
|
|
770
|
-
document.addEventListener("pagehide", () => {
|
|
771
|
-
lastHiddenTimestamp = Date.now();
|
|
772
|
-
});
|
|
773
|
-
}
|
|
774
|
-
if (typeof window !== "undefined") {
|
|
775
|
-
window.addEventListener("pageshow", (event) => {
|
|
776
|
-
if (event.persisted) {
|
|
777
|
-
reconnectIfLikelyStale(true);
|
|
778
|
-
return;
|
|
779
|
-
}
|
|
780
|
-
reconnectIfLikelyStale(false);
|
|
781
|
-
});
|
|
782
|
-
window.addEventListener("focus", () => {
|
|
783
|
-
reconnectIfLikelyStale(false);
|
|
784
|
-
});
|
|
785
|
-
window.addEventListener("online", () => {
|
|
786
|
-
reconnectIfLikelyStale(true);
|
|
787
|
-
});
|
|
155
|
+
// Network failures are not replayed: a lost response may follow a successful mutation.
|
|
156
|
+
return result;
|
|
788
157
|
}
|
|
789
158
|
//# sourceMappingURL=rpcClient.js.map
|