@ekrooh/bare 0.6.2 → 0.7.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 +3 -2
- package/dist/errors-Bl5w-m62.mjs +56 -0
- package/dist/events-DUGMT3B9.mjs +40 -0
- package/dist/{index-Do-kTNXw.d.mts → index-B3AmX7mC.d.mts} +35 -146
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +3 -1
- package/dist/{messages-CMNIFMFY.mjs → messages-BxviiFuh.mjs} +182 -73
- package/dist/plugin-BnDh08L_.mjs +111 -0
- package/dist/plugins-discovery-events.d.mts +1 -1
- package/dist/plugins-discovery-events.mjs +1 -1
- package/dist/plugins-health-events.d.mts +1 -1
- package/dist/plugins-health-events.mjs +1 -1
- package/dist/plugins-logs-events.d.mts +2 -1
- package/dist/plugins-logs-events.mjs +1 -1
- package/dist/plugins-media-events.d.mts +1 -1
- package/dist/plugins-media-events.mjs +1 -26
- package/dist/plugins-permissions-events.d.mts +2 -1
- package/dist/plugins-permissions-events.mjs +11 -3
- package/dist/plugins-q6Wno9wN.mjs +77 -0
- package/dist/plugins.d.mts +7 -4
- package/dist/plugins.mjs +1 -1
- package/dist/runtime.d.mts +31 -7
- package/dist/runtime.mjs +657 -124
- package/dist/{static-file-server-COxd-PFR.d.mts → static-file-server-drT1AHqV.d.mts} +26 -4
- package/dist/{store-DTg1jN5E.mjs → store-Bd2wL58k.mjs} +11 -2
- package/dist/sync.d.mts +36 -0
- package/dist/sync.mjs +323 -0
- package/dist/transports.d.mts +28 -1
- package/dist/transports.mjs +332 -168
- package/dist/types-BC39OoZB.d.mts +152 -0
- package/package.json +10 -5
- package/dist/plugins-BnpdCi3A.mjs +0 -156
package/dist/transports.mjs
CHANGED
|
@@ -1,26 +1,46 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { l as MessageType, n as err, o as ErrorCode, r as ok } from "./errors-Bl5w-m62.mjs";
|
|
2
|
+
import { d as createPluginRouter, o as MessageProtocol, r as definePlugin, u as createPluginRegistry } from "./messages-BxviiFuh.mjs";
|
|
3
|
+
import { i as createDiscoveryPlugin, n as createLogsPlugin, r as createHealthPlugin, t as createPermissionsPluginStub } from "./plugin-BnDh08L_.mjs";
|
|
4
|
+
import { i as isMediaKind, n as mediaSpecs } from "./events-DUGMT3B9.mjs";
|
|
5
|
+
import { t as createLogRingBuffer } from "./store-Bd2wL58k.mjs";
|
|
3
6
|
import { Actor, RealClock, event, state } from "@mantaq/core";
|
|
4
7
|
// web/connection-machine.ts
|
|
8
|
+
const DEFAULT_MIN_BOOT_WINDOW_MS = 1e4;
|
|
9
|
+
const DEFAULT_STABLE_MS = 5e3;
|
|
10
|
+
const DEFAULT_REPLACED_BACKOFF_MS = 3e4;
|
|
11
|
+
const DEFAULT_OPEN_TIMEOUT_MS = 1e4;
|
|
5
12
|
const idleState = state("idle")();
|
|
6
13
|
const openingState = state("opening")();
|
|
7
14
|
const connectedState = state("connected")();
|
|
8
15
|
const backoffState = state("backoff")();
|
|
9
|
-
const gaveUpState = state("gaveUp")()
|
|
16
|
+
const gaveUpState = state("gaveUp")();
|
|
17
|
+
const closedState = state("closed")().final();
|
|
10
18
|
const loginOk = event("LOGIN_OK")();
|
|
11
19
|
const loginFail = event("LOGIN_FAIL")();
|
|
12
20
|
const socketOpen = event("SOCKET_OPEN")();
|
|
13
21
|
const socketClose = event("SOCKET_CLOSE")();
|
|
22
|
+
const socketReplaced = event("SOCKET_REPLACED")();
|
|
14
23
|
const wake = event("WAKE")();
|
|
24
|
+
const close = event("CLOSE")();
|
|
15
25
|
const retryTimer = event("RETRY_TIMER")();
|
|
26
|
+
const stableTimer = event("STABLE_TIMER")();
|
|
27
|
+
const openTimeout = event("OPEN_TIMEOUT")();
|
|
16
28
|
function createConnectionMachine(options) {
|
|
29
|
+
const clockImpl = options.clock ?? new RealClock();
|
|
30
|
+
const minBootWindowMs = options.minBootWindowMs ?? DEFAULT_MIN_BOOT_WINDOW_MS;
|
|
31
|
+
const stableMs = options.stableMs ?? DEFAULT_STABLE_MS;
|
|
32
|
+
const replacedBackoffMs = options.replacedBackoffMs ?? DEFAULT_REPLACED_BACKOFF_MS;
|
|
33
|
+
const openTimeoutMs = options.openTimeoutMs ?? DEFAULT_OPEN_TIMEOUT_MS;
|
|
34
|
+
const random = options.random ?? Math.random;
|
|
17
35
|
const context = {
|
|
18
36
|
url: options.url,
|
|
19
37
|
maxRetries: options.maxRetries,
|
|
20
38
|
initialBackoffMs: options.initialBackoffMs,
|
|
21
39
|
maxBackoffMs: options.maxBackoffMs,
|
|
22
40
|
retries: 0,
|
|
23
|
-
everConnected: false
|
|
41
|
+
everConnected: false,
|
|
42
|
+
bootStartedAt: 0,
|
|
43
|
+
replaced: false
|
|
24
44
|
};
|
|
25
45
|
const actor = new Actor({
|
|
26
46
|
inputs: [
|
|
@@ -28,80 +48,150 @@ function createConnectionMachine(options) {
|
|
|
28
48
|
loginFail,
|
|
29
49
|
socketOpen,
|
|
30
50
|
socketClose,
|
|
31
|
-
|
|
51
|
+
socketReplaced,
|
|
52
|
+
wake,
|
|
53
|
+
close
|
|
54
|
+
],
|
|
55
|
+
internal: [
|
|
56
|
+
retryTimer,
|
|
57
|
+
stableTimer,
|
|
58
|
+
openTimeout
|
|
32
59
|
],
|
|
33
|
-
internal: [retryTimer],
|
|
34
60
|
outputs: [],
|
|
35
61
|
states: [
|
|
36
62
|
idleState,
|
|
37
63
|
openingState,
|
|
38
64
|
connectedState,
|
|
39
65
|
backoffState,
|
|
40
|
-
gaveUpState
|
|
66
|
+
gaveUpState,
|
|
67
|
+
closedState
|
|
41
68
|
],
|
|
42
69
|
initial: idleState,
|
|
43
|
-
clock:
|
|
70
|
+
clock: clockImpl,
|
|
44
71
|
context,
|
|
45
72
|
setup: (m) => {
|
|
46
73
|
m.effect(backoffState, ({ signal, context, clock, emit }) => {
|
|
47
74
|
const s = context.get();
|
|
48
|
-
|
|
49
|
-
|
|
75
|
+
let delay;
|
|
76
|
+
if (s.replaced) delay = replacedBackoffMs;
|
|
77
|
+
else {
|
|
78
|
+
const capped = Math.min(s.initialBackoffMs * 2 ** (s.retries - 1), s.maxBackoffMs);
|
|
79
|
+
const r = Math.max(0, Math.min(1, random()));
|
|
80
|
+
delay = Math.floor(capped / 2 + capped / 2 * r);
|
|
81
|
+
}
|
|
50
82
|
clock.setTimeout(delay, () => {
|
|
51
|
-
if (signal.aborted)
|
|
52
|
-
try {
|
|
53
|
-
console.debug(`[ws-machine] backoff aborted by signal; dropping pending retry (retries=${s.retries})`);
|
|
54
|
-
} catch {}
|
|
55
|
-
return;
|
|
56
|
-
}
|
|
83
|
+
if (signal.aborted) return;
|
|
57
84
|
emit({ type: "RETRY_TIMER" });
|
|
85
|
+
}, { signal });
|
|
86
|
+
});
|
|
87
|
+
m.effect(connectedState, ({ signal, clock, emit }) => {
|
|
88
|
+
clock.setTimeout(stableMs, () => {
|
|
89
|
+
if (signal.aborted) return;
|
|
90
|
+
emit({ type: "STABLE_TIMER" });
|
|
91
|
+
}, { signal });
|
|
92
|
+
});
|
|
93
|
+
m.effect(openingState, ({ signal, clock, emit }) => {
|
|
94
|
+
clock.setTimeout(openTimeoutMs, () => {
|
|
95
|
+
if (signal.aborted) return;
|
|
96
|
+
emit({ type: "OPEN_TIMEOUT" });
|
|
97
|
+
}, { signal });
|
|
98
|
+
});
|
|
99
|
+
m.on(idleState, loginOk, (_event, opts) => {
|
|
100
|
+
const s = opts.context.get();
|
|
101
|
+
opts.context.set({
|
|
102
|
+
...s,
|
|
103
|
+
bootStartedAt: clockImpl.now()
|
|
58
104
|
});
|
|
105
|
+
return { state: openingState };
|
|
59
106
|
});
|
|
60
|
-
m.on(idleState, loginOk, () => ({ state: openingState }));
|
|
61
107
|
m.on(idleState, loginFail, () => ({ state: gaveUpState }));
|
|
62
108
|
m.on(openingState, socketOpen, (_event, opts) => {
|
|
63
109
|
const s = opts.context.get();
|
|
64
110
|
opts.context.set({
|
|
65
111
|
...s,
|
|
66
|
-
|
|
67
|
-
|
|
112
|
+
everConnected: true,
|
|
113
|
+
replaced: false
|
|
68
114
|
});
|
|
69
115
|
return { state: connectedState };
|
|
70
116
|
});
|
|
71
|
-
|
|
117
|
+
const openFailed = (ctx) => {
|
|
118
|
+
const s = ctx.get();
|
|
119
|
+
if (!s.everConnected && s.retries >= s.maxRetries && clockImpl.now() - s.bootStartedAt >= minBootWindowMs) return { state: gaveUpState };
|
|
120
|
+
ctx.set({
|
|
121
|
+
...s,
|
|
122
|
+
retries: s.retries + 1,
|
|
123
|
+
replaced: false
|
|
124
|
+
});
|
|
125
|
+
return { state: backoffState };
|
|
126
|
+
};
|
|
127
|
+
m.on(openingState, socketClose, (_e, opts) => openFailed(opts.context));
|
|
128
|
+
m.on(openingState, openTimeout, (_e, opts) => openFailed(opts.context));
|
|
129
|
+
m.on(openingState, socketReplaced, (_e, opts) => openFailed(opts.context));
|
|
130
|
+
m.on(connectedState, stableTimer, (_event, opts) => {
|
|
72
131
|
const s = opts.context.get();
|
|
73
|
-
if (!s.everConnected && s.retries >= s.maxRetries) return { state: gaveUpState };
|
|
74
132
|
opts.context.set({
|
|
75
133
|
...s,
|
|
76
|
-
retries:
|
|
134
|
+
retries: 0
|
|
77
135
|
});
|
|
78
|
-
return {
|
|
136
|
+
return {};
|
|
79
137
|
});
|
|
80
138
|
m.on(connectedState, socketClose, (_event, opts) => {
|
|
81
139
|
const s = opts.context.get();
|
|
82
140
|
opts.context.set({
|
|
83
141
|
...s,
|
|
84
|
-
retries: s.retries + 1
|
|
142
|
+
retries: s.retries + 1,
|
|
143
|
+
replaced: false
|
|
144
|
+
});
|
|
145
|
+
return { state: backoffState };
|
|
146
|
+
});
|
|
147
|
+
m.on(connectedState, socketReplaced, (_event, opts) => {
|
|
148
|
+
const s = opts.context.get();
|
|
149
|
+
opts.context.set({
|
|
150
|
+
...s,
|
|
151
|
+
retries: 0,
|
|
152
|
+
replaced: true
|
|
85
153
|
});
|
|
86
154
|
return { state: backoffState };
|
|
87
155
|
});
|
|
88
156
|
m.on(backoffState, retryTimer, () => ({ state: openingState }));
|
|
89
157
|
m.on(backoffState, wake, () => ({ state: openingState }));
|
|
90
158
|
m.on(backoffState, socketClose, () => ({}));
|
|
159
|
+
m.on(backoffState, socketReplaced, () => ({}));
|
|
160
|
+
m.on(gaveUpState, wake, (_event, opts) => {
|
|
161
|
+
const s = opts.context.get();
|
|
162
|
+
opts.context.set({
|
|
163
|
+
...s,
|
|
164
|
+
retries: 0,
|
|
165
|
+
replaced: false
|
|
166
|
+
});
|
|
167
|
+
return { state: idleState };
|
|
168
|
+
});
|
|
169
|
+
for (const from of [
|
|
170
|
+
idleState,
|
|
171
|
+
openingState,
|
|
172
|
+
connectedState,
|
|
173
|
+
backoffState,
|
|
174
|
+
gaveUpState
|
|
175
|
+
]) m.on(from, close, () => ({ state: closedState }));
|
|
91
176
|
}
|
|
92
177
|
});
|
|
93
178
|
const name = (snapshot) => snapshot.path[0];
|
|
179
|
+
const current = () => name(actor.snapshot());
|
|
94
180
|
return {
|
|
95
181
|
url: () => actor.context.url,
|
|
96
|
-
state:
|
|
97
|
-
isConnected: () =>
|
|
98
|
-
isGaveUp: () =>
|
|
99
|
-
|
|
182
|
+
state: current,
|
|
183
|
+
isConnected: () => current() === "connected",
|
|
184
|
+
isGaveUp: () => current() === "gaveUp",
|
|
185
|
+
isClosed: () => current() === "closed",
|
|
186
|
+
isReplaced: () => current() === "backoff" && actor.context.replaced,
|
|
187
|
+
isDegraded: () => current() !== "connected" && actor.context.everConnected && actor.context.retries > actor.context.maxRetries,
|
|
100
188
|
sendLoginOk: () => actor.send(loginOk.create()),
|
|
101
189
|
sendLoginFail: () => actor.send(loginFail.create()),
|
|
102
190
|
sendOpen: () => actor.send(socketOpen.create()),
|
|
103
191
|
sendClose: () => actor.send(socketClose.create()),
|
|
192
|
+
sendReplaced: () => actor.send(socketReplaced.create()),
|
|
104
193
|
sendWake: () => actor.send(wake.create()),
|
|
194
|
+
sendStop: () => actor.send(close.create()),
|
|
105
195
|
onChange(fn) {
|
|
106
196
|
return actor.on("change", (snapshot) => fn(name(snapshot)));
|
|
107
197
|
}
|
|
@@ -117,6 +207,17 @@ const LOGIN_TIMEOUT_MS = 2e3;
|
|
|
117
207
|
/** Wait before the single retry after a 409 (`bootstrap` nonce already
|
|
118
208
|
* spent): long enough for the sibling document's `Set-Cookie` to land. */
|
|
119
209
|
const SPENT_NONCE_RETRY_MS = 250;
|
|
210
|
+
/** Requests held while connecting before new ones fail fast. */
|
|
211
|
+
const DEFAULT_MAX_QUEUED = 256;
|
|
212
|
+
/** Sent invokes tracked per socket so a lost socket can fail them. Past this,
|
|
213
|
+
* the oldest entry is forgotten (its caller still has its own timeout). */
|
|
214
|
+
const MAX_TRACKED_INFLIGHT = 1024;
|
|
215
|
+
/** WebSocket close code the loopback server uses when another document took
|
|
216
|
+
* over the session (the replaced protocol socket). */
|
|
217
|
+
const REPLACED_CLOSE_CODE = 4001;
|
|
218
|
+
const SOCKET_LOST_MESSAGE = "WebSocket closed before the response arrived";
|
|
219
|
+
const REPLACED_MESSAGE = "WebSocket replaced by another page holding the session; reconnects in 30 s or when this page returns to the foreground";
|
|
220
|
+
const CLOSED_MESSAGE = "WebSocket transport was closed";
|
|
120
221
|
/** Same-origin default: on-device the page is served by the loopback server,
|
|
121
222
|
* so `ws://<location.host>` is the protocol socket with no mixed content and
|
|
122
223
|
* no custom scheme. */
|
|
@@ -163,11 +264,21 @@ function createWebSocketTransport(urlOrOptions = {}) {
|
|
|
163
264
|
const maxRetries = options.maxRetries ?? DEFAULT_RETRIES;
|
|
164
265
|
const initialBackoff = options.backoffMs ?? DEFAULT_BACKOFF_MS;
|
|
165
266
|
const loginTimeoutMs = options.loginTimeoutMs ?? LOGIN_TIMEOUT_MS;
|
|
267
|
+
const maxQueued = options.maxQueued ?? DEFAULT_MAX_QUEUED;
|
|
268
|
+
const diagnostics = options.diagnostics === true;
|
|
166
269
|
const credential = (typeof window !== "undefined" ? window.__ekrooh : void 0)?.bootstrap;
|
|
167
270
|
const shouldLogin = options.login !== false && typeof credential === "string" && credential.length > 0;
|
|
168
271
|
const listeners = /* @__PURE__ */ new Set();
|
|
169
272
|
const queued = [];
|
|
170
273
|
let socket = null;
|
|
274
|
+
/** Invokes sent on the current socket and not yet answered, by requestId.
|
|
275
|
+
* A socket's responses can only come back on that socket, so losing it
|
|
276
|
+
* fails them at once instead of leaving callers on their timeouts. */
|
|
277
|
+
const inflight = /* @__PURE__ */ new Map();
|
|
278
|
+
/** Set once `/login` succeeded: the HttpOnly cookie outlives a give-up. */
|
|
279
|
+
let loggedIn = false;
|
|
280
|
+
let started = false;
|
|
281
|
+
let closed = false;
|
|
171
282
|
/** Human-readable reason when the give-up was caused by the `/login`
|
|
172
283
|
* exchange. The surfaced transport error is the only telemetry CI gets
|
|
173
284
|
* from an on-device WebView, so it must say which path fired instead of
|
|
@@ -182,7 +293,9 @@ function createWebSocketTransport(urlOrOptions = {}) {
|
|
|
182
293
|
url,
|
|
183
294
|
maxRetries,
|
|
184
295
|
initialBackoffMs: initialBackoff,
|
|
185
|
-
maxBackoffMs: MAX_BACKOFF_MS
|
|
296
|
+
maxBackoffMs: MAX_BACKOFF_MS,
|
|
297
|
+
minBootWindowMs: options.minBootWindowMs,
|
|
298
|
+
openTimeoutMs: options.openTimeoutMs
|
|
186
299
|
});
|
|
187
300
|
const reconnectingMessage = `${WS_DISCONNECTED_MESSAGE} (reconnecting)`;
|
|
188
301
|
const emitTransportError = (header, message) => {
|
|
@@ -206,10 +319,36 @@ function createWebSocketTransport(urlOrOptions = {}) {
|
|
|
206
319
|
for (const queuedMessage of queued) emitTransportError(queuedMessage.header, message);
|
|
207
320
|
queued.length = 0;
|
|
208
321
|
};
|
|
322
|
+
/** Sends on the open socket, tracking invokes until they are answered. */
|
|
323
|
+
const sendNow = (target, bytes, header) => {
|
|
324
|
+
if (header.type === "INVOKE_REQUEST" && typeof header.requestId === "string") {
|
|
325
|
+
if (inflight.size >= MAX_TRACKED_INFLIGHT) {
|
|
326
|
+
const oldest = inflight.keys().next().value;
|
|
327
|
+
if (oldest !== void 0) inflight.delete(oldest);
|
|
328
|
+
}
|
|
329
|
+
inflight.set(header.requestId, header);
|
|
330
|
+
}
|
|
331
|
+
target.send(toSendable(bytes));
|
|
332
|
+
};
|
|
209
333
|
const flushQueued = () => {
|
|
210
|
-
|
|
211
|
-
|
|
334
|
+
const target = socket;
|
|
335
|
+
if (!target) return;
|
|
336
|
+
const pending = queued.splice(0);
|
|
337
|
+
for (const queuedMessage of pending) sendNow(target, queuedMessage.bytes, queuedMessage.header);
|
|
212
338
|
};
|
|
339
|
+
/** Forgets the current socket: fails the invokes sent on it (their answers
|
|
340
|
+
* can only arrive on that socket) and closes it if it is still around.
|
|
341
|
+
* Late events from it are ignored (`socket !== current`). */
|
|
342
|
+
function dropSocket(message) {
|
|
343
|
+
const lost = socket;
|
|
344
|
+
socket = null;
|
|
345
|
+
const pending = [...inflight.values()];
|
|
346
|
+
inflight.clear();
|
|
347
|
+
for (const header of pending) emitTransportError(header, message);
|
|
348
|
+
if (lost && lost.readyState !== WebSocket.CLOSED) try {
|
|
349
|
+
lost.close();
|
|
350
|
+
} catch {}
|
|
351
|
+
}
|
|
213
352
|
/** Opens a WebSocket for the machine's current URL and wires it to the
|
|
214
353
|
* machine's lifecycle events. */
|
|
215
354
|
function openSocket() {
|
|
@@ -231,39 +370,52 @@ function createWebSocketTransport(urlOrOptions = {}) {
|
|
|
231
370
|
}
|
|
232
371
|
try {
|
|
233
372
|
const message = protocol.decode(event.data);
|
|
373
|
+
if (message.header.type === "INVOKE_RESPONSE" && typeof message.header.requestId === "string") inflight.delete(message.header.requestId);
|
|
234
374
|
for (const listener of listeners) listener(message);
|
|
235
375
|
} catch (err) {
|
|
236
376
|
console.error("Failed to parse WS message:", err);
|
|
237
377
|
}
|
|
238
378
|
};
|
|
239
|
-
current.onclose = () => {
|
|
379
|
+
current.onclose = (event) => {
|
|
240
380
|
if (socket !== current) return;
|
|
241
|
-
|
|
381
|
+
const replaced = event?.code === REPLACED_CLOSE_CODE;
|
|
382
|
+
dropSocket(replaced ? REPLACED_MESSAGE : SOCKET_LOST_MESSAGE);
|
|
383
|
+
if (replaced) machine.sendReplaced();
|
|
384
|
+
else machine.sendClose();
|
|
242
385
|
};
|
|
243
386
|
current.onerror = () => {};
|
|
244
387
|
}
|
|
245
388
|
machine.onChange((state) => {
|
|
389
|
+
if (state !== "opening" && state !== "connected" && socket) dropSocket(state === "closed" ? CLOSED_MESSAGE : SOCKET_LOST_MESSAGE);
|
|
246
390
|
if (state === "opening") openSocket();
|
|
247
391
|
else if (state === "gaveUp") failWithServerDetail();
|
|
392
|
+
else if (state === "closed") failQueuedMessages(CLOSED_MESSAGE);
|
|
393
|
+
else if (state === "idle" && started) bootstrap();
|
|
394
|
+
else if (state === "backoff" && machine.isReplaced()) failQueuedMessages(REPLACED_MESSAGE);
|
|
248
395
|
else if (state === "backoff" && machine.isDegraded()) failQueuedMessages(reconnectingMessage);
|
|
249
396
|
});
|
|
250
397
|
/** The app returned to the foreground. A suspended page may hold a socket
|
|
251
398
|
* the browser already closed without firing `onclose`; treat it as lost, and
|
|
252
399
|
* retry now instead of waiting out the backoff. */
|
|
253
400
|
function onForeground() {
|
|
254
|
-
if (machine.isConnected() && socket && socket.readyState !== WebSocket.OPEN)
|
|
401
|
+
if (machine.isConnected() && socket && socket.readyState !== WebSocket.OPEN) {
|
|
402
|
+
dropSocket(SOCKET_LOST_MESSAGE);
|
|
403
|
+
machine.sendClose();
|
|
404
|
+
}
|
|
255
405
|
machine.sendWake();
|
|
256
406
|
}
|
|
257
|
-
|
|
407
|
+
const onVisibilityChange = () => {
|
|
258
408
|
if (document.visibilityState === "visible") onForeground();
|
|
259
|
-
}
|
|
409
|
+
};
|
|
410
|
+
const hasDocument = typeof document !== "undefined" && typeof document.addEventListener === "function";
|
|
411
|
+
if (hasDocument) document.addEventListener("visibilitychange", onVisibilityChange);
|
|
260
412
|
/** Terminal give-up: when we have no better name for the failure, fold the
|
|
261
413
|
* server's own view (its `[loopback]` upgrade rejections) into the surfaced
|
|
262
414
|
* error. Async by one localhost round-trip — queued requests are already
|
|
263
415
|
* terminally lost, so a short delay changes nothing semantically. */
|
|
264
416
|
async function failWithServerDetail() {
|
|
265
417
|
let message = gaveUpMessage();
|
|
266
|
-
if (loginFailureDetail === null) {
|
|
418
|
+
if (diagnostics && loginFailureDetail === null) {
|
|
267
419
|
const tail = await serverRejectionTail(url);
|
|
268
420
|
if (tail !== null) message = `${message}; server: ${tail}`;
|
|
269
421
|
}
|
|
@@ -273,8 +425,9 @@ function createWebSocketTransport(urlOrOptions = {}) {
|
|
|
273
425
|
* the server recognized our nonce as already consumed by a sibling
|
|
274
426
|
* document whose session cookie is on its way — worth exactly one retry. */
|
|
275
427
|
function postLogin() {
|
|
428
|
+
let timer;
|
|
276
429
|
const loginTimeout = new Promise((resolve) => {
|
|
277
|
-
setTimeout(() => resolve("timeout"), loginTimeoutMs);
|
|
430
|
+
timer = setTimeout(() => resolve("timeout"), loginTimeoutMs);
|
|
278
431
|
});
|
|
279
432
|
const attempt = fetch("/login", {
|
|
280
433
|
method: "POST",
|
|
@@ -283,49 +436,74 @@ function createWebSocketTransport(urlOrOptions = {}) {
|
|
|
283
436
|
if (response.ok) return "ok";
|
|
284
437
|
return response.status === 409 ? "spent" : "rejected";
|
|
285
438
|
});
|
|
286
|
-
return Promise.race([attempt, loginTimeout]);
|
|
439
|
+
return Promise.race([attempt, loginTimeout]).finally(() => clearTimeout(timer));
|
|
287
440
|
}
|
|
288
441
|
async function bootstrap() {
|
|
289
|
-
if (shouldLogin)
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
await
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
442
|
+
if (shouldLogin && !loggedIn) {
|
|
443
|
+
loginFailureDetail = null;
|
|
444
|
+
try {
|
|
445
|
+
let outcome = await postLogin();
|
|
446
|
+
if (outcome === "spent") {
|
|
447
|
+
await new Promise((resolve) => {
|
|
448
|
+
setTimeout(resolve, SPENT_NONCE_RETRY_MS);
|
|
449
|
+
});
|
|
450
|
+
outcome = await postLogin();
|
|
451
|
+
}
|
|
452
|
+
if (outcome === "ok") {
|
|
453
|
+
loggedIn = true;
|
|
454
|
+
machine.sendLoginOk();
|
|
455
|
+
} else {
|
|
456
|
+
loginFailureDetail = outcome === "timeout" ? `session login timed out after ${loginTimeoutMs}ms` : "session login rejected";
|
|
457
|
+
machine.sendLoginFail();
|
|
458
|
+
}
|
|
459
|
+
} catch {
|
|
460
|
+
loginFailureDetail = "session login request failed";
|
|
300
461
|
machine.sendLoginFail();
|
|
301
462
|
}
|
|
302
|
-
}
|
|
303
|
-
loginFailureDetail = "session login request failed";
|
|
304
|
-
machine.sendLoginFail();
|
|
305
|
-
}
|
|
306
|
-
else machine.sendLoginOk();
|
|
463
|
+
} else machine.sendLoginOk();
|
|
307
464
|
}
|
|
465
|
+
started = true;
|
|
308
466
|
bootstrap();
|
|
309
467
|
return {
|
|
310
468
|
send(type, header, payload) {
|
|
469
|
+
if (closed) {
|
|
470
|
+
emitTransportError(header, CLOSED_MESSAGE);
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
311
473
|
const encoded = protocol.encode(type, header, payload);
|
|
312
474
|
if (machine.isConnected() && socket && socket.readyState === WebSocket.OPEN) {
|
|
313
|
-
socket
|
|
475
|
+
sendNow(socket, encoded, header);
|
|
314
476
|
return;
|
|
315
477
|
}
|
|
316
478
|
if (machine.isGaveUp()) {
|
|
317
479
|
emitTransportError(header, gaveUpMessage());
|
|
318
480
|
return;
|
|
319
481
|
}
|
|
482
|
+
if (machine.isReplaced()) {
|
|
483
|
+
emitTransportError(header, REPLACED_MESSAGE);
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
320
486
|
if (machine.state() === "backoff" && machine.isDegraded()) {
|
|
321
487
|
emitTransportError(header, reconnectingMessage);
|
|
322
488
|
return;
|
|
323
489
|
}
|
|
490
|
+
if (queued.length >= maxQueued) {
|
|
491
|
+
emitTransportError(header, `${WS_DISCONNECTED_MESSAGE} (${maxQueued} requests already waiting for the connection)`);
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
324
494
|
queued.push({
|
|
325
495
|
bytes: encoded,
|
|
326
496
|
header
|
|
327
497
|
});
|
|
328
498
|
},
|
|
499
|
+
close() {
|
|
500
|
+
if (closed) return;
|
|
501
|
+
closed = true;
|
|
502
|
+
if (hasDocument) document.removeEventListener?.("visibilitychange", onVisibilityChange);
|
|
503
|
+
machine.sendStop();
|
|
504
|
+
dropSocket(CLOSED_MESSAGE);
|
|
505
|
+
failQueuedMessages(CLOSED_MESSAGE);
|
|
506
|
+
},
|
|
329
507
|
subscribe(handler) {
|
|
330
508
|
listeners.add(handler);
|
|
331
509
|
return () => {
|
|
@@ -334,130 +512,116 @@ function createWebSocketTransport(urlOrOptions = {}) {
|
|
|
334
512
|
}
|
|
335
513
|
};
|
|
336
514
|
}
|
|
337
|
-
//
|
|
338
|
-
|
|
515
|
+
// plugins/permissions/ids.ts
|
|
516
|
+
/** Canonical permission ids. Internal (not an `exports` entry): hosts keep
|
|
517
|
+
* their own allowlists (Android `DefaultHostPlugins.kt`, iOS
|
|
518
|
+
* `DefaultHostPlugins.swift`); the mock transport uses this one so an unknown
|
|
519
|
+
* or missing id answers `unsupported` there too, never a fake grant. */
|
|
520
|
+
const PERMISSION_IDS = ["storage", "camera"];
|
|
521
|
+
function isPermissionId(value) {
|
|
522
|
+
return PERMISSION_IDS.includes(value);
|
|
523
|
+
}
|
|
524
|
+
// web/transports/mock.ts
|
|
525
|
+
const MOCK_MEDIA_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAbUlEQVR4nO3O7UkCABiAQcd5hjXSyCKLPrCiklRswHOM/rw3wS0s4yquYxXruInb2MRd3MdDbOMxnuI5XuI13mIX7/ERn/EV3/ET+/iNQxzjFOf4y2ICE5jABCYwgQlMYAITmMAEJjCBCfx34ALvwBam5OydHgAAAABJRU5ErkJggg==";
|
|
526
|
+
/** The host side the mock stands in for: the permission handlers a native
|
|
527
|
+
* host registers. Unknown or missing ids answer `unsupported`, as the real
|
|
528
|
+
* hosts do — the mock never fakes a grant for an id the host would refuse. */
|
|
529
|
+
const MOCK_HOST_CAPABILITIES = [{
|
|
530
|
+
pluginId: "core.permissions",
|
|
531
|
+
capabilities: ["permissions"],
|
|
532
|
+
events: ["permissions.request", "permissions.status"],
|
|
533
|
+
runtimes: []
|
|
534
|
+
}];
|
|
535
|
+
async function mockHostInvoke(header) {
|
|
536
|
+
const raw = header.args?.permission;
|
|
537
|
+
const known = isPermissionId(raw);
|
|
339
538
|
return {
|
|
340
|
-
"
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
}) };
|
|
349
|
-
},
|
|
350
|
-
"logs.clear": () => ({ cleared: store.clear() })
|
|
539
|
+
type: "INVOKE_RESPONSE",
|
|
540
|
+
pluginId: header.pluginId,
|
|
541
|
+
event: header.event,
|
|
542
|
+
requestId: header.requestId,
|
|
543
|
+
result: {
|
|
544
|
+
permission: typeof raw === "string" ? raw : "",
|
|
545
|
+
status: known ? "granted" : "unsupported"
|
|
546
|
+
}
|
|
351
547
|
};
|
|
352
548
|
}
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
const payloadSize = typeof payload === "string" ? new TextEncoder().encode(payload).byteLength : payload instanceof ArrayBuffer ? payload.byteLength : payload?.byteLength ?? 0;
|
|
361
|
-
return {
|
|
362
|
-
label: String(args?.label ?? "payload"),
|
|
363
|
-
payloadSize
|
|
364
|
-
};
|
|
365
|
-
},
|
|
366
|
-
"health.roundtrip": () => ({
|
|
367
|
-
pong: true,
|
|
368
|
-
ts: Date.now()
|
|
369
|
-
})
|
|
549
|
+
/** `vendor.media` without a native picker or loopback server: same `kind`
|
|
550
|
+
* check as the real plugin, a fixed `data:` image instead of a mounted URL. */
|
|
551
|
+
function createMockMediaPlugin() {
|
|
552
|
+
const pick = (args) => {
|
|
553
|
+
const kind = args?.kind;
|
|
554
|
+
if (kind !== void 0 && !isMediaKind(kind)) return err(ErrorCode.PLUGIN_ERROR, "Unknown media kind");
|
|
555
|
+
return ok({ url: MOCK_MEDIA_DATA_URI });
|
|
370
556
|
};
|
|
557
|
+
return definePlugin("vendor.media", mediaSpecs, {
|
|
558
|
+
capabilities: ["media"],
|
|
559
|
+
invoke: {
|
|
560
|
+
pick,
|
|
561
|
+
capture: pick
|
|
562
|
+
}
|
|
563
|
+
});
|
|
371
564
|
}
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
{
|
|
398
|
-
pluginId: "core.permissions",
|
|
399
|
-
capabilities: ["permissions"],
|
|
400
|
-
events: ["permissions.request", "permissions.status"],
|
|
401
|
-
runtimes: []
|
|
402
|
-
},
|
|
403
|
-
{
|
|
404
|
-
pluginId: "vendor.media",
|
|
405
|
-
capabilities: ["media"],
|
|
406
|
-
events: ["media.pick", "media.capture"],
|
|
407
|
-
runtimes: ["bare"]
|
|
408
|
-
}
|
|
409
|
-
]
|
|
410
|
-
}),
|
|
411
|
-
"permissions.request": (args) => ({
|
|
412
|
-
permission: permissionOf(args),
|
|
413
|
-
status: "granted"
|
|
414
|
-
}),
|
|
415
|
-
"permissions.status": (args) => ({
|
|
416
|
-
permission: permissionOf(args),
|
|
417
|
-
status: "granted"
|
|
418
|
-
}),
|
|
419
|
-
"media.pick": () => ({ url: MOCK_MEDIA_DATA_URI }),
|
|
420
|
-
"media.capture": () => ({ url: MOCK_MEDIA_DATA_URI })
|
|
421
|
-
};
|
|
565
|
+
function toPayloadBytes(payload) {
|
|
566
|
+
if (payload == null) return /* @__PURE__ */ new Uint8Array(0);
|
|
567
|
+
if (typeof payload === "string") return new TextEncoder().encode(payload);
|
|
568
|
+
if (payload instanceof ArrayBuffer) return new Uint8Array(payload);
|
|
569
|
+
return payload;
|
|
570
|
+
}
|
|
571
|
+
let warnedInShell = false;
|
|
572
|
+
/** The mock fakes the host (every known permission granted). Inside a real
|
|
573
|
+
* embedding shell that is a shipped test double, so say so loudly once. */
|
|
574
|
+
function warnIfInShell() {
|
|
575
|
+
if (warnedInShell || typeof window === "undefined") return;
|
|
576
|
+
const w = window;
|
|
577
|
+
if (w.BareShell || typeof w.__ekrooh?.bootstrap === "string") {
|
|
578
|
+
warnedInShell = true;
|
|
579
|
+
console.warn("[ekrooh] createMockTransport is running inside an app shell. It fakes the native host and every permission; it is for tests and browser dev only.");
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* Deterministic in-process transport for tests and browser dev. Requests are
|
|
584
|
+
* routed through the real plugin kernel and the real `core.health`,
|
|
585
|
+
* `core.discovery`, `core.logs` and `core.permissions` manifests, so argument
|
|
586
|
+
* checks, unsupported-event errors and discovery match the worklet. Only the
|
|
587
|
+
* host (permission handlers) and `vendor.media` (no native picker, no
|
|
588
|
+
* loopback server: a `data:` URL) are stand-ins.
|
|
589
|
+
*/
|
|
422
590
|
function createMockTransport() {
|
|
591
|
+
warnIfInShell();
|
|
423
592
|
const listeners = /* @__PURE__ */ new Set();
|
|
424
|
-
const
|
|
425
|
-
const
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
593
|
+
const registry = createPluginRegistry();
|
|
594
|
+
const getHostCapabilities = async () => MOCK_HOST_CAPABILITIES;
|
|
595
|
+
for (const plugin of [
|
|
596
|
+
createHealthPlugin(),
|
|
597
|
+
createDiscoveryPlugin({
|
|
598
|
+
listBareCapabilities: () => registry.listCapabilities(),
|
|
599
|
+
queryHostCapabilities: getHostCapabilities
|
|
600
|
+
}),
|
|
601
|
+
createPermissionsPluginStub(),
|
|
602
|
+
createMockMediaPlugin(),
|
|
603
|
+
createLogsPlugin({ store: createLogRingBuffer(500) })
|
|
604
|
+
]) registry.register(plugin);
|
|
605
|
+
const router = createPluginRouter(registry, "bare", {
|
|
606
|
+
delegateToHost: mockHostInvoke,
|
|
607
|
+
getHostCapabilities,
|
|
608
|
+
logger: {
|
|
609
|
+
warn() {},
|
|
610
|
+
error() {},
|
|
611
|
+
debug() {}
|
|
612
|
+
}
|
|
613
|
+
});
|
|
430
614
|
return {
|
|
431
615
|
send(type, header, payload) {
|
|
432
616
|
if (type !== MessageType.ENVELOPE || header.type !== "INVOKE_REQUEST") return;
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
617
|
+
router.route(header, toPayloadBytes(payload)).then((response) => {
|
|
618
|
+
if (!response) return;
|
|
619
|
+
const message = {
|
|
436
620
|
type: MessageType.ENVELOPE,
|
|
437
|
-
header:
|
|
438
|
-
type: "INVOKE_RESPONSE",
|
|
439
|
-
pluginId: header.pluginId,
|
|
440
|
-
event: header.event,
|
|
441
|
-
requestId: header.requestId,
|
|
442
|
-
error: {
|
|
443
|
-
code: ErrorCode.UNSUPPORTED_EVENT,
|
|
444
|
-
message: `Unsupported mock event: ${header.event}`
|
|
445
|
-
}
|
|
446
|
-
},
|
|
621
|
+
header: response,
|
|
447
622
|
payload: /* @__PURE__ */ new Uint8Array(0)
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
}
|
|
451
|
-
emit({
|
|
452
|
-
type: MessageType.ENVELOPE,
|
|
453
|
-
header: {
|
|
454
|
-
type: "INVOKE_RESPONSE",
|
|
455
|
-
pluginId: header.pluginId,
|
|
456
|
-
event: header.event,
|
|
457
|
-
requestId: header.requestId,
|
|
458
|
-
result: handler(header.args, payload)
|
|
459
|
-
},
|
|
460
|
-
payload: /* @__PURE__ */ new Uint8Array(0)
|
|
623
|
+
};
|
|
624
|
+
for (const listener of listeners) listener(message);
|
|
461
625
|
});
|
|
462
626
|
},
|
|
463
627
|
subscribe(handler) {
|