@ekrooh/bare 0.6.2 → 0.8.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.
@@ -1,26 +1,46 @@
1
- import { g as ErrorCode, o as MessageProtocol, y as MessageType } from "./messages-CMNIFMFY.mjs";
2
- import { t as createLogRingBuffer } from "./store-DTg1jN5E.mjs";
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-B5HQRbFA.mjs";
3
+ import { i as createDiscoveryPlugin, n as createLogsPlugin, r as createHealthPlugin, t as createPermissionsPluginStub } from "./plugin-a3LvQrmS.mjs";
4
+ import { i as isMediaKind, n as mediaSpecs } from "./events-wkidvYuN.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")().final();
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
- wake
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: options.clock ?? new RealClock(),
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
- const capped = Math.min(s.initialBackoffMs * 2 ** (s.retries - 1), s.maxBackoffMs);
49
- const delay = Math.floor(capped * Math.max(0, Math.min(1, (options.random ?? Math.random)())));
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
- retries: 0,
67
- everConnected: true
112
+ everConnected: true,
113
+ replaced: false
68
114
  });
69
115
  return { state: connectedState };
70
116
  });
71
- m.on(openingState, socketClose, (_event, opts) => {
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: s.retries + 1
134
+ retries: 0
77
135
  });
78
- return { state: backoffState };
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: () => name(actor.snapshot()),
97
- isConnected: () => name(actor.snapshot()) === "connected",
98
- isGaveUp: () => name(actor.snapshot()) === "gaveUp",
99
- isDegraded: () => actor.context.everConnected && actor.context.retries > actor.context.maxRetries,
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,17 +264,32 @@ 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();
272
+ const readyWaiters = [];
273
+ const releaseReady = () => {
274
+ for (const release of readyWaiters.splice(0)) release();
275
+ };
169
276
  const queued = [];
170
277
  let socket = null;
278
+ /** Invokes sent on the current socket and not yet answered, by requestId.
279
+ * A socket's responses can only come back on that socket, so losing it
280
+ * fails them at once instead of leaving callers on their timeouts. */
281
+ const inflight = /* @__PURE__ */ new Map();
282
+ /** Set once `/login` succeeded: the HttpOnly cookie outlives a give-up. */
283
+ let loggedIn = false;
284
+ let started = false;
285
+ let closed = false;
171
286
  /** Human-readable reason when the give-up was caused by the `/login`
172
287
  * exchange. The surfaced transport error is the only telemetry CI gets
173
288
  * from an on-device WebView, so it must say which path fired instead of
174
289
  * collapsing login rejection, login timeout and retry exhaustion into a
175
290
  * single string. */
176
291
  let loginFailureDetail = null;
292
+ let loginTimedOut = false;
177
293
  /** Error text for requests lost to a terminal give-up. */
178
294
  function gaveUpMessage() {
179
295
  return loginFailureDetail === null ? `${WS_DISCONNECTED_MESSAGE} (socket never opened after ${maxRetries} retries)` : `${WS_DISCONNECTED_MESSAGE} (${loginFailureDetail})`;
@@ -182,7 +298,9 @@ function createWebSocketTransport(urlOrOptions = {}) {
182
298
  url,
183
299
  maxRetries,
184
300
  initialBackoffMs: initialBackoff,
185
- maxBackoffMs: MAX_BACKOFF_MS
301
+ maxBackoffMs: MAX_BACKOFF_MS,
302
+ minBootWindowMs: options.minBootWindowMs,
303
+ openTimeoutMs: options.openTimeoutMs
186
304
  });
187
305
  const reconnectingMessage = `${WS_DISCONNECTED_MESSAGE} (reconnecting)`;
188
306
  const emitTransportError = (header, message) => {
@@ -206,10 +324,36 @@ function createWebSocketTransport(urlOrOptions = {}) {
206
324
  for (const queuedMessage of queued) emitTransportError(queuedMessage.header, message);
207
325
  queued.length = 0;
208
326
  };
327
+ /** Sends on the open socket, tracking invokes until they are answered. */
328
+ const sendNow = (target, bytes, header) => {
329
+ if (header.type === "INVOKE_REQUEST" && typeof header.requestId === "string") {
330
+ if (inflight.size >= MAX_TRACKED_INFLIGHT) {
331
+ const oldest = inflight.keys().next().value;
332
+ if (oldest !== void 0) inflight.delete(oldest);
333
+ }
334
+ inflight.set(header.requestId, header);
335
+ }
336
+ target.send(toSendable(bytes));
337
+ };
209
338
  const flushQueued = () => {
210
- for (const queuedMessage of queued) socket?.send(toSendable(queuedMessage.bytes));
211
- queued.length = 0;
339
+ const target = socket;
340
+ if (!target) return;
341
+ const pending = queued.splice(0);
342
+ for (const queuedMessage of pending) sendNow(target, queuedMessage.bytes, queuedMessage.header);
212
343
  };
344
+ /** Forgets the current socket: fails the invokes sent on it (their answers
345
+ * can only arrive on that socket) and closes it if it is still around.
346
+ * Late events from it are ignored (`socket !== current`). */
347
+ function dropSocket(message) {
348
+ const lost = socket;
349
+ socket = null;
350
+ const pending = [...inflight.values()];
351
+ inflight.clear();
352
+ for (const header of pending) emitTransportError(header, message);
353
+ if (lost && lost.readyState !== WebSocket.CLOSED) try {
354
+ lost.close();
355
+ } catch {}
356
+ }
213
357
  /** Opens a WebSocket for the machine's current URL and wires it to the
214
358
  * machine's lifecycle events. */
215
359
  function openSocket() {
@@ -220,6 +364,7 @@ function createWebSocketTransport(urlOrOptions = {}) {
220
364
  if (socket !== current) return;
221
365
  machine.sendOpen();
222
366
  flushQueued();
367
+ releaseReady();
223
368
  };
224
369
  current.onmessage = (event) => {
225
370
  if (socket !== current) return;
@@ -231,39 +376,53 @@ function createWebSocketTransport(urlOrOptions = {}) {
231
376
  }
232
377
  try {
233
378
  const message = protocol.decode(event.data);
379
+ if (message.header.type === "INVOKE_RESPONSE" && typeof message.header.requestId === "string") inflight.delete(message.header.requestId);
234
380
  for (const listener of listeners) listener(message);
235
381
  } catch (err) {
236
382
  console.error("Failed to parse WS message:", err);
237
383
  }
238
384
  };
239
- current.onclose = () => {
385
+ current.onclose = (event) => {
240
386
  if (socket !== current) return;
241
- machine.sendClose();
387
+ const replaced = event?.code === REPLACED_CLOSE_CODE;
388
+ dropSocket(replaced ? REPLACED_MESSAGE : SOCKET_LOST_MESSAGE);
389
+ if (replaced) machine.sendReplaced();
390
+ else machine.sendClose();
242
391
  };
243
392
  current.onerror = () => {};
244
393
  }
245
394
  machine.onChange((state) => {
395
+ if (state === "gaveUp" || state === "closed" || machine.isReplaced()) releaseReady();
396
+ if (state !== "opening" && state !== "connected" && socket) dropSocket(state === "closed" ? CLOSED_MESSAGE : SOCKET_LOST_MESSAGE);
246
397
  if (state === "opening") openSocket();
247
398
  else if (state === "gaveUp") failWithServerDetail();
399
+ else if (state === "closed") failQueuedMessages(CLOSED_MESSAGE);
400
+ else if (state === "idle" && started) bootstrap();
401
+ else if (state === "backoff" && machine.isReplaced()) failQueuedMessages(REPLACED_MESSAGE);
248
402
  else if (state === "backoff" && machine.isDegraded()) failQueuedMessages(reconnectingMessage);
249
403
  });
250
404
  /** The app returned to the foreground. A suspended page may hold a socket
251
405
  * the browser already closed without firing `onclose`; treat it as lost, and
252
406
  * retry now instead of waiting out the backoff. */
253
407
  function onForeground() {
254
- if (machine.isConnected() && socket && socket.readyState !== WebSocket.OPEN) machine.sendClose();
408
+ if (machine.isConnected() && socket && socket.readyState !== WebSocket.OPEN) {
409
+ dropSocket(SOCKET_LOST_MESSAGE);
410
+ machine.sendClose();
411
+ }
255
412
  machine.sendWake();
256
413
  }
257
- if (typeof document !== "undefined" && document.addEventListener) document.addEventListener("visibilitychange", () => {
414
+ const onVisibilityChange = () => {
258
415
  if (document.visibilityState === "visible") onForeground();
259
- });
416
+ };
417
+ const hasDocument = typeof document !== "undefined" && typeof document.addEventListener === "function";
418
+ if (hasDocument) document.addEventListener("visibilitychange", onVisibilityChange);
260
419
  /** Terminal give-up: when we have no better name for the failure, fold the
261
420
  * server's own view (its `[loopback]` upgrade rejections) into the surfaced
262
421
  * error. Async by one localhost round-trip — queued requests are already
263
422
  * terminally lost, so a short delay changes nothing semantically. */
264
423
  async function failWithServerDetail() {
265
424
  let message = gaveUpMessage();
266
- if (loginFailureDetail === null) {
425
+ if (diagnostics && loginFailureDetail === null) {
267
426
  const tail = await serverRejectionTail(url);
268
427
  if (tail !== null) message = `${message}; server: ${tail}`;
269
428
  }
@@ -273,8 +432,9 @@ function createWebSocketTransport(urlOrOptions = {}) {
273
432
  * the server recognized our nonce as already consumed by a sibling
274
433
  * document whose session cookie is on its way — worth exactly one retry. */
275
434
  function postLogin() {
435
+ let timer;
276
436
  const loginTimeout = new Promise((resolve) => {
277
- setTimeout(() => resolve("timeout"), loginTimeoutMs);
437
+ timer = setTimeout(() => resolve("timeout"), loginTimeoutMs);
278
438
  });
279
439
  const attempt = fetch("/login", {
280
440
  method: "POST",
@@ -283,49 +443,83 @@ function createWebSocketTransport(urlOrOptions = {}) {
283
443
  if (response.ok) return "ok";
284
444
  return response.status === 409 ? "spent" : "rejected";
285
445
  });
286
- return Promise.race([attempt, loginTimeout]);
446
+ return Promise.race([attempt, loginTimeout]).finally(() => clearTimeout(timer));
287
447
  }
288
448
  async function bootstrap() {
289
- if (shouldLogin) try {
290
- let outcome = await postLogin();
291
- if (outcome === "spent") {
292
- await new Promise((resolve) => {
293
- setTimeout(resolve, SPENT_NONCE_RETRY_MS);
294
- });
295
- outcome = await postLogin();
296
- }
297
- if (outcome === "ok") machine.sendLoginOk();
298
- else {
299
- loginFailureDetail = outcome === "timeout" ? `session login timed out after ${loginTimeoutMs}ms` : "session login rejected";
449
+ if (shouldLogin && !loggedIn) {
450
+ loginFailureDetail = null;
451
+ loginTimedOut = false;
452
+ try {
453
+ let outcome = await postLogin();
454
+ if (outcome === "spent") {
455
+ await new Promise((resolve) => {
456
+ setTimeout(resolve, SPENT_NONCE_RETRY_MS);
457
+ });
458
+ outcome = await postLogin();
459
+ }
460
+ if (outcome === "ok") {
461
+ loggedIn = true;
462
+ machine.sendLoginOk();
463
+ } else {
464
+ loginTimedOut = outcome === "timeout";
465
+ loginFailureDetail = outcome === "timeout" ? `session login timed out after ${loginTimeoutMs}ms` : "session login rejected";
466
+ machine.sendLoginFail();
467
+ }
468
+ } catch {
469
+ loginFailureDetail = "session login request failed";
300
470
  machine.sendLoginFail();
301
471
  }
302
- } catch {
303
- loginFailureDetail = "session login request failed";
304
- machine.sendLoginFail();
305
- }
306
- else machine.sendLoginOk();
472
+ } else machine.sendLoginOk();
307
473
  }
474
+ started = true;
308
475
  bootstrap();
309
476
  return {
310
477
  send(type, header, payload) {
478
+ if (closed) {
479
+ emitTransportError(header, CLOSED_MESSAGE);
480
+ return;
481
+ }
311
482
  const encoded = protocol.encode(type, header, payload);
312
483
  if (machine.isConnected() && socket && socket.readyState === WebSocket.OPEN) {
313
- socket.send(toSendable(encoded));
484
+ sendNow(socket, encoded, header);
314
485
  return;
315
486
  }
316
487
  if (machine.isGaveUp()) {
317
488
  emitTransportError(header, gaveUpMessage());
489
+ if (shouldLogin && !loggedIn && loginTimedOut) machine.sendWake();
490
+ return;
491
+ }
492
+ if (machine.isReplaced()) {
493
+ emitTransportError(header, REPLACED_MESSAGE);
318
494
  return;
319
495
  }
320
496
  if (machine.state() === "backoff" && machine.isDegraded()) {
321
497
  emitTransportError(header, reconnectingMessage);
322
498
  return;
323
499
  }
500
+ if (queued.length >= maxQueued) {
501
+ emitTransportError(header, `${WS_DISCONNECTED_MESSAGE} (${maxQueued} requests already waiting for the connection)`);
502
+ return;
503
+ }
324
504
  queued.push({
325
505
  bytes: encoded,
326
506
  header
327
507
  });
328
508
  },
509
+ close() {
510
+ if (closed) return;
511
+ closed = true;
512
+ if (hasDocument) document.removeEventListener?.("visibilitychange", onVisibilityChange);
513
+ machine.sendStop();
514
+ dropSocket(CLOSED_MESSAGE);
515
+ failQueuedMessages(CLOSED_MESSAGE);
516
+ },
517
+ ready() {
518
+ if (closed || machine.isGaveUp() || machine.isReplaced() || machine.isConnected() && socket?.readyState === WebSocket.OPEN) return Promise.resolve();
519
+ return new Promise((resolve) => {
520
+ readyWaiters.push(resolve);
521
+ });
522
+ },
329
523
  subscribe(handler) {
330
524
  listeners.add(handler);
331
525
  return () => {
@@ -334,130 +528,116 @@ function createWebSocketTransport(urlOrOptions = {}) {
334
528
  }
335
529
  };
336
530
  }
337
- // web/transports/mock-handlers.ts
338
- function createLogsInvokeHandlers(store = createLogRingBuffer(500)) {
531
+ // plugins/permissions/ids.ts
532
+ /** Canonical permission ids. Internal (not an `exports` entry): hosts keep
533
+ * their own allowlists (Android `DefaultHostPlugins.kt`, iOS
534
+ * `DefaultHostPlugins.swift`); the mock transport uses this one so an unknown
535
+ * or missing id answers `unsupported` there too, never a fake grant. */
536
+ const PERMISSION_IDS = ["storage", "camera"];
537
+ function isPermissionId(value) {
538
+ return PERMISSION_IDS.includes(value);
539
+ }
540
+ // web/transports/mock.ts
541
+ const MOCK_MEDIA_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAbUlEQVR4nO3O7UkCABiAQcd5hjXSyCKLPrCiklRswHOM/rw3wS0s4yquYxXruInb2MRd3MdDbOMxnuI5XuI13mIX7/ERn/EV3/ET+/iNQxzjFOf4y2ICE5jABCYwgQlMYAITmMAEJjCBCfx34ALvwBam5OydHgAAAABJRU5ErkJggg==";
542
+ /** The host side the mock stands in for: the permission handlers a native
543
+ * host registers. Unknown or missing ids answer `unsupported`, as the real
544
+ * hosts do — the mock never fakes a grant for an id the host would refuse. */
545
+ const MOCK_HOST_CAPABILITIES = [{
546
+ pluginId: "core.permissions",
547
+ capabilities: ["permissions"],
548
+ events: ["permissions.request", "permissions.status"],
549
+ runtimes: []
550
+ }];
551
+ async function mockHostInvoke(header) {
552
+ const raw = header.args?.permission;
553
+ const known = isPermissionId(raw);
339
554
  return {
340
- "logs.view": (args) => {
341
- const tail = args?.tail === void 0 ? void 0 : Number(args.tail);
342
- const level = args?.level === "debug" || args?.level === "info" || args?.level === "warn" || args?.level === "error" ? args.level : void 0;
343
- const source = args?.source === "backend" || args?.source === "web" ? args.source : void 0;
344
- return { entries: store.view({
345
- tail: tail !== void 0 && Number.isFinite(tail) ? tail : void 0,
346
- level,
347
- source
348
- }) };
349
- },
350
- "logs.clear": () => ({ cleared: store.clear() })
555
+ type: "INVOKE_RESPONSE",
556
+ pluginId: header.pluginId,
557
+ event: header.event,
558
+ requestId: header.requestId,
559
+ result: {
560
+ permission: typeof raw === "string" ? raw : "",
561
+ status: known ? "granted" : "unsupported"
562
+ }
351
563
  };
352
564
  }
353
- function createHealthInvokeHandlers() {
354
- return {
355
- "health.ping": (args) => ({
356
- message: String(args?.message ?? "pong"),
357
- ts: Date.now()
358
- }),
359
- "health.payloadEcho": (args, payload) => {
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
- })
565
+ /** `vendor.media` without a native picker or loopback server: same `kind`
566
+ * check as the real plugin, a fixed `data:` image instead of a mounted URL. */
567
+ function createMockMediaPlugin() {
568
+ const pick = (args) => {
569
+ const kind = args?.kind;
570
+ if (kind !== void 0 && !isMediaKind(kind)) return err(ErrorCode.PLUGIN_ERROR, "Unknown media kind");
571
+ return ok({ url: MOCK_MEDIA_DATA_URI });
370
572
  };
573
+ return definePlugin("vendor.media", mediaSpecs, {
574
+ capabilities: ["media"],
575
+ invoke: {
576
+ pick,
577
+ capture: pick
578
+ }
579
+ });
371
580
  }
372
- // web/transports/mock.ts
373
- const MOCK_MEDIA_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAbUlEQVR4nO3O7UkCABiAQcd5hjXSyCKLPrCiklRswHOM/rw3wS0s4yquYxXruInb2MRd3MdDbOMxnuI5XuI13mIX7/ERn/EV3/ET+/iNQxzjFOf4y2ICE5jABCYwgQlMYAITmMAEJjCBCfx34ALvwBam5OydHgAAAABJRU5ErkJggg==";
374
- const permissionOf = (args) => typeof args?.permission === "string" ? args.permission : "storage";
375
- const mockInvokeHandlers = {
376
- ...createHealthInvokeHandlers(),
377
- ...createLogsInvokeHandlers(createLogRingBuffer(500)),
378
- "discovery.list": () => ({
379
- schemaVersion: 1,
380
- capabilities: [
381
- {
382
- pluginId: "core.health",
383
- capabilities: [],
384
- events: [
385
- "health.ping",
386
- "health.payloadEcho",
387
- "health.roundtrip"
388
- ],
389
- runtimes: ["bare"]
390
- },
391
- {
392
- pluginId: "core.discovery",
393
- capabilities: ["discovery"],
394
- events: ["discovery.list"],
395
- runtimes: ["bare"]
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
- };
581
+ function toPayloadBytes(payload) {
582
+ if (payload == null) return /* @__PURE__ */ new Uint8Array(0);
583
+ if (typeof payload === "string") return new TextEncoder().encode(payload);
584
+ if (payload instanceof ArrayBuffer) return new Uint8Array(payload);
585
+ return payload;
586
+ }
587
+ let warnedInShell = false;
588
+ /** The mock fakes the host (every known permission granted). Inside a real
589
+ * embedding shell that is a shipped test double, so say so loudly once. */
590
+ function warnIfInShell() {
591
+ if (warnedInShell || typeof window === "undefined") return;
592
+ const w = window;
593
+ if (w.BareShell || typeof w.__ekrooh?.bootstrap === "string") {
594
+ warnedInShell = true;
595
+ 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.");
596
+ }
597
+ }
598
+ /**
599
+ * Deterministic in-process transport for tests and browser dev. Requests are
600
+ * routed through the real plugin kernel and the real `core.health`,
601
+ * `core.discovery`, `core.logs` and `core.permissions` manifests, so argument
602
+ * checks, unsupported-event errors and discovery match the worklet. Only the
603
+ * host (permission handlers) and `vendor.media` (no native picker, no
604
+ * loopback server: a `data:` URL) are stand-ins.
605
+ */
422
606
  function createMockTransport() {
607
+ warnIfInShell();
423
608
  const listeners = /* @__PURE__ */ new Set();
424
- const invokeHandlers = mockInvokeHandlers;
425
- const emit = (message) => {
426
- queueMicrotask(() => {
427
- for (const listener of listeners) listener(message);
428
- });
429
- };
609
+ const registry = createPluginRegistry();
610
+ const getHostCapabilities = async () => MOCK_HOST_CAPABILITIES;
611
+ for (const plugin of [
612
+ createHealthPlugin(),
613
+ createDiscoveryPlugin({
614
+ listBareCapabilities: () => registry.listCapabilities(),
615
+ queryHostCapabilities: getHostCapabilities
616
+ }),
617
+ createPermissionsPluginStub(),
618
+ createMockMediaPlugin(),
619
+ createLogsPlugin({ store: createLogRingBuffer(500) })
620
+ ]) registry.register(plugin);
621
+ const router = createPluginRouter(registry, "bare", {
622
+ delegateToHost: mockHostInvoke,
623
+ getHostCapabilities,
624
+ logger: {
625
+ warn() {},
626
+ error() {},
627
+ debug() {}
628
+ }
629
+ });
430
630
  return {
431
631
  send(type, header, payload) {
432
632
  if (type !== MessageType.ENVELOPE || header.type !== "INVOKE_REQUEST") return;
433
- const handler = invokeHandlers[header.event];
434
- if (!handler) {
435
- emit({
633
+ router.route(header, toPayloadBytes(payload)).then((response) => {
634
+ if (!response) return;
635
+ const message = {
436
636
  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
- },
637
+ header: response,
447
638
  payload: /* @__PURE__ */ new Uint8Array(0)
448
- });
449
- return;
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)
639
+ };
640
+ for (const listener of listeners) listener(message);
461
641
  });
462
642
  },
463
643
  subscribe(handler) {