@pi-oxide/extension-js 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/worker.js CHANGED
@@ -1,24 +1,35 @@
1
- import z, { setLogLevel as L, ExtensionSession as G, registerJsCallBatch as H } from "../../pkg/extension_js.js";
2
- import "zod";
3
- const w = {
4
- debug: 0,
5
- info: 1,
6
- warn: 2,
7
- error: 3,
8
- none: 4
9
- };
10
- let E = "error", S = null;
11
- function J(r) {
12
- E = r, S && S(w[r]);
1
+ import x, { setLogLevel as C, ExtensionSession as ee, registerJsCallBatch as re } from "./extension_js.js";
2
+ const T = {
3
+ trace: 0,
4
+ debug: 1,
5
+ info: 2,
6
+ warn: 3,
7
+ error: 4,
8
+ none: 5
9
+ }, te = [
10
+ "trace",
11
+ "debug",
12
+ "info",
13
+ "warn",
14
+ "error",
15
+ "none"
16
+ ];
17
+ function se(r) {
18
+ const e = Math.max(0, Math.min(5, Math.round(r)));
19
+ return te[e] ?? "error";
13
20
  }
14
- function V(r) {
15
- S = r, E !== "error" && r(w[E]);
21
+ let P = "trace", L = null;
22
+ function ne(r) {
23
+ P = r, L && L(T[r]);
16
24
  }
17
- function q(r) {
18
- return w[r] >= w[E];
25
+ function ae(r) {
26
+ L = r, r(T[P]);
27
+ }
28
+ function oe(r) {
29
+ return T[r] >= T[P];
19
30
  }
20
- function U(r, e = "info") {
21
- var t;
31
+ function V(r, e = "info") {
32
+ var s;
22
33
  if (r === null) return "null";
23
34
  if (r === void 0) return "undefined";
24
35
  if (typeof r == "string") return r;
@@ -26,106 +37,109 @@ function U(r, e = "info") {
26
37
  return String(r);
27
38
  if (typeof r == "bigint") return `${r}n`;
28
39
  if (r instanceof Error) {
29
- const n = e === "debug" ? r.stack : (t = r.stack) == null ? void 0 : t.split(`
40
+ const t = e === "debug" || e === "trace" ? r.stack : (s = r.stack) == null ? void 0 : s.split(`
30
41
  `)[0];
31
- return JSON.stringify({ message: r.message, name: r.name, stack: n });
42
+ return JSON.stringify({ message: r.message, name: r.name, stack: t });
32
43
  }
33
44
  if (typeof r == "function") return "[Function]";
34
45
  if (typeof r == "symbol") return String(r);
35
46
  if (typeof r == "object")
36
47
  try {
37
48
  return JSON.stringify(r);
38
- } catch (n) {
39
- return n instanceof TypeError && n.message.includes("circular") ? "[Circular]" : `[Unserializable: ${n instanceof Error ? n.message : String(n)}]`;
49
+ } catch (t) {
50
+ return t instanceof TypeError && t.message.includes("circular") ? "[Circular]" : `[Unserializable: ${t instanceof Error ? t.message : String(t)}]`;
40
51
  }
41
52
  return String(r);
42
53
  }
43
- function K(r) {
54
+ function ie(r) {
44
55
  return `[extension-js][${r}]`;
45
56
  }
46
- function X(r, e) {
57
+ function le(r, e) {
47
58
  if (!r) return "";
48
- const t = [];
59
+ const s = [];
49
60
  try {
50
- for (const [n, s] of Object.entries(r))
51
- t.push(`${n}=${U(s, e)}`);
61
+ for (const [t, n] of Object.entries(r))
62
+ s.push(`${t}=${V(n, e)}`);
52
63
  } catch {
53
64
  return " metadata=[unreadable]";
54
65
  }
55
- return t.length > 0 ? ` ${t.join(" ")}` : "";
66
+ return s.length > 0 ? ` ${s.join(" ")}` : "";
56
67
  }
57
- function h(r, e) {
68
+ function E(r, e) {
58
69
  return e.length === 0 ? { event: r } : e.length === 1 && typeof e[0] == "object" && e[0] !== null && !Array.isArray(e[0]) ? { event: r, metadata: e[0] } : {
59
70
  event: r,
60
- metadata: { _args: e.map((t) => U(t)).join(" ") }
71
+ metadata: { _args: e.map((s) => V(s)).join(" ") }
61
72
  };
62
73
  }
63
- class I {
74
+ class $ {
64
75
  constructor(e = "root") {
65
76
  this.namespace = e;
66
77
  }
67
- log(e, t, n) {
78
+ log(e, s, t) {
68
79
  try {
69
- if (!q(e)) return;
70
- const s = K(this.namespace), a = X(n, e), o = `${s} ${t}${a}`;
80
+ if (!oe(e)) return;
81
+ const n = ie(this.namespace), o = le(t, e), i = `${n} ${s}${o}`;
71
82
  switch (e) {
83
+ case "trace":
72
84
  case "debug":
73
- console.log(o);
74
- break;
75
85
  case "info":
76
- console.log(o);
86
+ console.log(i);
77
87
  break;
78
88
  case "warn":
79
- console.warn(o);
89
+ console.warn(i);
80
90
  break;
81
91
  case "error":
82
- console.error(o);
92
+ console.error(i);
83
93
  break;
84
94
  case "none":
85
95
  break;
86
96
  default: {
87
- const f = e;
97
+ const a = e;
88
98
  break;
89
99
  }
90
100
  }
91
101
  } catch {
92
102
  }
93
103
  }
94
- debug(e, ...t) {
95
- const { event: n, metadata: s } = h(e, t);
96
- this.log("debug", n, s);
104
+ trace(e, ...s) {
105
+ const { event: t, metadata: n } = E(e, s);
106
+ this.log("trace", t, n);
107
+ }
108
+ debug(e, ...s) {
109
+ const { event: t, metadata: n } = E(e, s);
110
+ this.log("debug", t, n);
97
111
  }
98
- info(e, ...t) {
99
- const { event: n, metadata: s } = h(e, t);
100
- this.log("info", n, s);
112
+ info(e, ...s) {
113
+ const { event: t, metadata: n } = E(e, s);
114
+ this.log("info", t, n);
101
115
  }
102
- warn(e, ...t) {
103
- const { event: n, metadata: s } = h(e, t);
104
- this.log("warn", n, s);
116
+ warn(e, ...s) {
117
+ const { event: t, metadata: n } = E(e, s);
118
+ this.log("warn", t, n);
105
119
  }
106
- error(e, ...t) {
107
- const { event: n, metadata: s } = h(e, t);
108
- this.log("error", n, s);
120
+ error(e, ...s) {
121
+ const { event: t, metadata: n } = E(e, s);
122
+ this.log("error", t, n);
109
123
  }
110
124
  child(e) {
111
- return new I(`${this.namespace}.${e}`);
125
+ return new $(`${this.namespace}.${e}`);
112
126
  }
113
- timer(e, t, n = "info") {
114
- const s = typeof performance < "u" && performance.now, a = s ? performance.now() : Date.now();
115
- return (o) => {
127
+ timer(e, s, t = "info") {
128
+ const n = typeof performance < "u" && performance.now, o = n ? performance.now() : Date.now();
129
+ return (i) => {
116
130
  try {
117
- const f = s ? performance.now() : Date.now(), l = Math.round(f - a), d = {
118
- ...t,
119
- ...o,
120
- duration_ms: l
131
+ const a = n ? performance.now() : Date.now(), g = Math.round(a - o), u = {
132
+ ...s,
133
+ ...i,
134
+ duration_ms: g
121
135
  };
122
- this.log(n, e, d);
136
+ this.log(t, e, u);
123
137
  } catch {
124
138
  }
125
139
  };
126
140
  }
127
141
  }
128
- const m = new I("root"), Y = /* @__PURE__ */ new Set([
142
+ const l = new $("root"), ce = /* @__PURE__ */ new Set([
129
143
  "page_url",
130
144
  "page_title",
131
145
  "page_click",
@@ -154,38 +168,41 @@ const m = new I("root"), Y = /* @__PURE__ */ new Set([
154
168
  "tab_dblclick",
155
169
  "tab_back"
156
170
  ]);
157
- function Q(r) {
158
- return Y.has(r);
171
+ function ue(r) {
172
+ return ce.has(r);
159
173
  }
160
- const Z = /* @__PURE__ */ new Map();
161
- function x(r, e) {
162
- Z.set(r, e);
174
+ const J = /* @__PURE__ */ new Map();
175
+ function de(r, e) {
176
+ J.set(r, e);
163
177
  }
164
- function ee(r) {
178
+ function fe(r) {
179
+ return J.get(r);
180
+ }
181
+ function ge(r) {
165
182
  return r.startsWith("tab_") ? "required" : "active";
166
183
  }
167
- function re(r) {
184
+ function pe(r) {
168
185
  return r === "content-script" ? "content-script" : r === "main-thread" ? "main-thread" : r === "worker" ? "worker:default" : r.startsWith("worker:") ? r : "main-thread";
169
186
  }
170
- function te(r, e) {
171
- return e !== "main-thread" ? e : Q(r) ? "content-script" : e;
187
+ function me(r, e) {
188
+ return e !== "main-thread" ? e : ue(r) ? "content-script" : e;
172
189
  }
173
- function ne(r, e) {
190
+ function ye(r, e) {
174
191
  return {
175
- endpoint: re(te(r, e)),
176
- tabPolicy: ee(r)
192
+ endpoint: pe(me(r, e)),
193
+ tabPolicy: ge(r)
177
194
  };
178
195
  }
179
- function se(r) {
196
+ function _e(r) {
180
197
  for (const e of r)
181
- x(e.action, ne(e.action, e.owner));
198
+ de(e.action, ye(e.action, e.owner));
182
199
  }
183
200
  function k(r) {
184
201
  return r == null ? {} : r instanceof Map ? Object.fromEntries(
185
- [...r.entries()].map(([e, t]) => [e, k(t)])
202
+ [...r.entries()].map(([e, s]) => [e, k(s)])
186
203
  ) : Array.isArray(r) ? r.map(k) : r;
187
204
  }
188
- function oe(r) {
205
+ function be(r) {
189
206
  return {
190
207
  action: r.action,
191
208
  namespace: r.namespace,
@@ -209,251 +226,355 @@ function oe(r) {
209
226
  description: r.returnsDoc.description
210
227
  },
211
228
  errorCode: r.errorCode,
212
- errorCategory: r.errorCategory ?? null
229
+ errorCategory: r.errorCategory ?? null,
230
+ permission: r.permission ?? null,
231
+ example: r.example ?? null
213
232
  };
214
233
  }
215
- m.child("tool-registry");
216
- let c = null, T = !1;
217
- const y = /* @__PURE__ */ new Map();
218
- function R(r, e) {
234
+ l.child("tool-registry");
235
+ let _ = null, v = !1;
236
+ const b = /* @__PURE__ */ new Map();
237
+ function A(r, e) {
219
238
  try {
220
239
  return r.postMessage(e), !0;
221
- } catch (t) {
222
- const n = t instanceof Error ? t.message : String(t);
223
- return m.error("port_post_failed", { error: n }), !1;
240
+ } catch (s) {
241
+ const t = s instanceof Error ? s.message : String(s);
242
+ return l.error("port_post_failed", { error: t }), !1;
224
243
  }
225
244
  }
226
- const B = 1e3;
227
- function j(r, e, t) {
228
- e === "main-thread" || e === "content-script" ? R(t, { type: "relayCancel", id: r, owner: e }) : R(t, { type: "registryCallCancel", id: r });
245
+ const G = 1e3;
246
+ function K(r, e, s) {
247
+ e === "main-thread" || e === "content-script" ? A(s, { type: "relayCancel", id: r, owner: e }) : A(s, { type: "registryCallCancel", id: r });
229
248
  }
230
- function F(r, e) {
231
- for (const [t, n] of y)
232
- clearTimeout(n.timeoutId), j(t, n.owner, n.port), n.settle({
249
+ function z(r, e) {
250
+ for (const [s, t] of b)
251
+ clearTimeout(t.timeoutId), K(s, t.owner, t.port), t.settle({
233
252
  ok: !1,
234
253
  error: { message: e, code: r }
235
- }), y.delete(t);
254
+ }), b.delete(s);
255
+ }
256
+ const h = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Map();
257
+ let q = Promise.resolve(), f = null;
258
+ function he(r) {
259
+ l.trace("sessionQueue_enqueue");
260
+ const e = q.then(r);
261
+ return q = e.then(
262
+ () => {
263
+ },
264
+ () => {
265
+ }
266
+ ), e;
236
267
  }
237
- const A = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Map();
238
- function i(r, e) {
239
- A.set(r, e);
268
+ function Y(r) {
269
+ f && (l.error("runCell_worker_failure", {
270
+ runId: f.runId,
271
+ callId: f.id,
272
+ error: r
273
+ }), self.postMessage({
274
+ type: "error",
275
+ id: f.id,
276
+ error: r,
277
+ runId: f.runId
278
+ }), f = null);
240
279
  }
241
- function ae() {
280
+ self.addEventListener("error", (r) => {
281
+ const e = r.message || (r.error instanceof Error ? r.error.message : "Worker uncaught error");
282
+ l.error("worker_uncaught_error", { error: e }), Y(e);
283
+ });
284
+ self.addEventListener("unhandledrejection", (r) => {
285
+ const e = r.reason, s = e instanceof Error ? e.message : String(e ?? "Unhandled rejection");
286
+ l.error("worker_unhandled_rejection", { error: s }), Y(s);
287
+ });
288
+ function c(r, e) {
289
+ h.set(r, e);
290
+ }
291
+ function Ee() {
242
292
  const r = new Uint8Array(16);
243
293
  return crypto.getRandomValues(r), Array.from(r, (e) => e.toString(16).padStart(2, "0")).join("");
244
294
  }
245
- function ie(r) {
246
- return r <= 0 ? "debug" : r === 1 ? "info" : r === 2 ? "warn" : r === 3 ? "error" : "none";
295
+ function we(r) {
296
+ return se(r);
247
297
  }
248
- const C = /* @__PURE__ */ new Map(), _ = /* @__PURE__ */ new Map();
249
- function le(r, e) {
250
- var t;
251
- if (C.has(r))
298
+ const O = /* @__PURE__ */ new Map(), I = /* @__PURE__ */ new Map();
299
+ function ke(r, e) {
300
+ var s;
301
+ if (O.has(r))
252
302
  throw new Error(`Worker port already registered for owner: ${r}`);
253
303
  if (typeof e.addEventListener != "function")
254
304
  throw new Error(`Worker port for owner "${r}" cannot receive responses`);
255
- C.set(r, e), e.addEventListener("message", async (n) => {
256
- var a;
257
- const s = n.data;
258
- if (s !== null && (s.type === "asyncRelayResult" || s.type === "registryCallResult") && typeof s.id == "string") {
259
- $(s.id, s.result);
305
+ O.set(r, e), e.addEventListener("message", async (t) => {
306
+ var o;
307
+ const n = t.data;
308
+ if (n !== null && (n.type === "asyncRelayResult" || n.type === "registryCallResult") && typeof n.id == "string") {
309
+ N(n.id, n.result);
260
310
  return;
261
311
  }
262
- if (s !== null && s.type === "registryCallCancel" && typeof s.id == "string") {
263
- (a = _.get(s.id)) == null || a.abort(), _.delete(s.id);
312
+ if (n !== null && n.type === "registryCallCancel" && typeof n.id == "string") {
313
+ (o = I.get(n.id)) == null || o.abort(), I.delete(n.id);
264
314
  return;
265
315
  }
266
- if (s !== null && s.type === "registryCall" && typeof s.id == "string" && typeof s.action == "string") {
267
- const o = s.id, f = new AbortController();
268
- _.set(o, f);
269
- const l = A.get(s.action);
270
- let d;
271
- if (!l)
272
- d = {
316
+ if (n !== null && n.type === "registryCall" && typeof n.id == "string" && typeof n.action == "string") {
317
+ const i = n.id, a = new AbortController();
318
+ I.set(i, a);
319
+ const g = h.get(n.action);
320
+ let u;
321
+ if (!g)
322
+ u = {
273
323
  ok: !1,
274
- error: { message: `Unknown worker action: ${s.action}`, code: "E_UNKNOWN" }
324
+ error: { message: `Unknown worker action: ${n.action}`, code: "E_UNKNOWN" }
275
325
  };
276
326
  else
277
327
  try {
278
- const u = await l(s.params, {
279
- action: s.action,
280
- callId: s.callId,
281
- runId: s.runId,
282
- signal: f.signal
328
+ const d = await g(n.params, {
329
+ action: n.action,
330
+ callId: n.callId,
331
+ runId: n.runId,
332
+ signal: a.signal
283
333
  });
284
- d = f.signal.aborted ? { ok: !1, error: { message: "Relay aborted", code: "E_ABORT" } } : { ok: !0, value: u };
285
- } catch (u) {
286
- d = {
334
+ u = a.signal.aborted ? { ok: !1, error: { message: "Relay aborted", code: "E_ABORT" } } : { ok: !0, value: d };
335
+ } catch (d) {
336
+ u = {
287
337
  ok: !1,
288
338
  error: {
289
- message: u instanceof Error ? u.message : String(u),
290
- code: f.signal.aborted ? "E_ABORT" : "E_WORKER_HANDLER"
339
+ message: d instanceof Error ? d.message : String(d),
340
+ code: a.signal.aborted ? "E_ABORT" : "E_WORKER_HANDLER"
291
341
  }
292
342
  };
293
343
  }
294
- _.delete(o), R(e, { type: "registryCallResult", id: o, result: d }) || $(o, {
344
+ I.delete(i), A(e, { type: "registryCallResult", id: i, result: u }) || N(i, {
295
345
  ok: !1,
296
346
  error: { message: "Failed to deliver worker handler response", code: "E_PORT" }
297
347
  });
298
348
  }
299
- }), (t = e.start) == null || t.call(e);
349
+ }), (s = e.start) == null || s.call(e);
300
350
  }
301
- function $(r, e) {
302
- const t = y.get(r);
303
- return t ? (t.settle(e), !0) : (m.warn("asyncRelayResult_no_pending_relay", { id: r }), !1);
351
+ function N(r, e) {
352
+ l.trace("resolveAsyncRelayResult", { id: r });
353
+ const s = b.get(r);
354
+ return s ? (s.settle(e), !0) : (l.warn("asyncRelayResult_no_pending_relay", { id: r }), !1);
304
355
  }
305
- function ce(r) {
356
+ function Re(r) {
306
357
  if (r === "main-thread" || r === "content-script")
307
358
  return self;
308
- const e = C.get(r);
359
+ const e = O.get(r);
309
360
  return e || null;
310
361
  }
311
- function fe(r) {
312
- const { owner: e, action: t, timeoutMs: n, tabPolicy: s } = r;
313
- return (a, o) => new Promise((f, l) => {
314
- var D;
315
- if ((D = o == null ? void 0 : o.signal) != null && D.aborted) {
316
- const g = new Error(`Relay aborted for action: ${t}`);
317
- g.code = "E_ABORT", l(g);
318
- return;
319
- }
320
- const d = ce(e);
321
- if (!d) {
322
- l(new Error(`No port available for action: ${t}`));
323
- return;
324
- }
325
- if (y.size >= B) {
326
- l(new Error(
327
- `Too many pending calls (${B} limit exceeded). Action: ${t}`
328
- ));
329
- return;
330
- }
331
- const u = ae();
332
- let O = !1;
333
- const b = (g) => {
334
- O || (O = !0, clearTimeout(v), o != null && o.signal && o.signal.removeEventListener("abort", M), y.delete(u), g());
335
- }, W = () => {
336
- j(u, e, d);
337
- }, M = () => {
338
- W();
339
- const g = new Error(`Relay aborted for action: ${t}`);
340
- g.code = "E_ABORT", b(() => l(g));
341
- };
342
- o != null && o.signal && o.signal.addEventListener("abort", M);
343
- const v = setTimeout(() => {
344
- W(), b(() => l(new Error(`Relay timeout for action: ${t}`)));
345
- }, n);
346
- y.set(u, {
347
- settle: (g) => b(() => f(g)),
348
- timeoutId: v,
349
- abort: M,
350
- owner: e,
351
- port: d
362
+ function Q(r) {
363
+ const { owner: e, action: s, tabPolicy: t, resolveTimeoutMs: n } = r, o = r.timeoutMs ?? w;
364
+ return (i, a) => {
365
+ l.trace("safePostAsCall_invoke", { owner: e, action: s, callId: a == null ? void 0 : a.callId, runId: a == null ? void 0 : a.runId });
366
+ const g = (n == null ? void 0 : n(i)) ?? o;
367
+ return new Promise((u, d) => {
368
+ var j;
369
+ if ((j = a == null ? void 0 : a.signal) != null && j.aborted) {
370
+ const m = new Error(`Relay aborted for action: ${s}`);
371
+ m.code = "E_ABORT", d(m);
372
+ return;
373
+ }
374
+ const y = Re(e);
375
+ if (!y) {
376
+ d(new Error(`No port available for action: ${s}`));
377
+ return;
378
+ }
379
+ if (b.size >= G) {
380
+ d(new Error(
381
+ `Too many pending calls (${G} limit exceeded). Action: ${s}`
382
+ ));
383
+ return;
384
+ }
385
+ const R = Ee();
386
+ let W = !1;
387
+ const M = (m) => {
388
+ W || (W = !0, clearTimeout(U), a != null && a.signal && a.signal.removeEventListener("abort", S), b.delete(R), m());
389
+ }, D = () => {
390
+ K(R, e, y);
391
+ }, S = () => {
392
+ D();
393
+ const m = new Error(`Relay aborted for action: ${s}`);
394
+ m.code = "E_ABORT", M(() => d(m));
395
+ };
396
+ a != null && a.signal && a.signal.addEventListener("abort", S);
397
+ const U = setTimeout(() => {
398
+ D(), M(() => d(new Error(`Relay timeout for action: ${s}`)));
399
+ }, g);
400
+ b.set(R, {
401
+ settle: (m) => M(() => u(m)),
402
+ timeoutId: U,
403
+ abort: S,
404
+ owner: e,
405
+ port: y
406
+ });
407
+ const F = a == null ? void 0 : a.runId, B = a == null ? void 0 : a.callId;
408
+ A(y, {
409
+ type: e === "main-thread" || e === "content-script" ? "asyncRelay" : "registryCall",
410
+ id: R,
411
+ owner: e,
412
+ action: s,
413
+ params: i,
414
+ callId: B,
415
+ tabPolicy: t,
416
+ command: { action: s, params: i, runId: F, callId: B },
417
+ runId: F
418
+ }) || M(() => d(new Error(`Failed to post relay for action: ${s}`)));
352
419
  });
353
- const P = o == null ? void 0 : o.runId, N = o == null ? void 0 : o.callId;
354
- R(d, {
355
- type: e === "main-thread" || e === "content-script" ? "asyncRelay" : "registryCall",
356
- id: u,
357
- owner: e,
358
- action: t,
359
- params: a,
360
- callId: N,
361
- tabPolicy: s,
362
- command: { action: t, params: a, runId: P, callId: N },
363
- runId: P
364
- }) || b(() => l(new Error(`Failed to post relay for action: ${t}`)));
420
+ };
421
+ }
422
+ const Me = "worker", w = 3e4, H = 5e3, Ie = 500, Te = {
423
+ page_goto: "timeout",
424
+ page_wait_for: "timeout",
425
+ tab_wait_for_load: "timeout",
426
+ fetch: "timeout",
427
+ sleep: "duration",
428
+ page_wait: "duration",
429
+ sidepanel_wait: "duration"
430
+ }, X = /* @__PURE__ */ new Set(["page_goto"]);
431
+ function Ae(r, e) {
432
+ if (r === null || typeof r != "object" || Array.isArray(r))
433
+ return null;
434
+ const s = r[e];
435
+ return typeof s == "bigint" ? Number(s) : typeof s == "number" && Number.isFinite(s) ? s : null;
436
+ }
437
+ function Se(r, e) {
438
+ return X.has(r) ? e * 2 + Ie + H : e + H;
439
+ }
440
+ function Z(r, e) {
441
+ const s = Te[r];
442
+ if (!s) return w;
443
+ let t = Ae(e, s);
444
+ return t === null && X.has(r) && (t = w), t === null ? w : Math.max(
445
+ w,
446
+ Se(r, t)
447
+ );
448
+ }
449
+ function Ne(r, e) {
450
+ var o, i;
451
+ r = k(r);
452
+ const s = e == null ? void 0 : e.action;
453
+ if (l.trace("extensionDispatch", { action: s, callId: e == null ? void 0 : e.callId, runId: e == null ? void 0 : e.runId }), !s)
454
+ return Promise.resolve({
455
+ ok: !1,
456
+ error: { message: "Missing action in dispatch context", code: "E_MISSING_ACTION" }
457
+ });
458
+ if (h.has(s)) {
459
+ const a = h.get(s), g = (e == null ? void 0 : e.signal) ?? (e != null && e.runId ? (o = p.get(e.runId)) == null ? void 0 : o.signal : void 0);
460
+ return (async () => {
461
+ try {
462
+ return { ok: !0, value: await a(r, { ...e, signal: g }) };
463
+ } catch (u) {
464
+ const d = u instanceof Error ? u.message : String(u), y = typeof u == "object" && u !== null && "code" in u && typeof u.code == "string" ? u.code : "E_WORKER_HANDLER";
465
+ return { ok: !1, error: { message: d, code: y } };
466
+ }
467
+ })();
468
+ }
469
+ const t = fe(s);
470
+ return t ? Q({
471
+ owner: t.endpoint,
472
+ action: s,
473
+ resolveTimeoutMs: (a) => Z(s, a),
474
+ tabPolicy: t.tabPolicy
475
+ })(r, {
476
+ ...e,
477
+ signal: (e == null ? void 0 : e.signal) ?? (e != null && e.runId ? (i = p.get(e.runId)) == null ? void 0 : i.signal : void 0)
478
+ }) : Promise.resolve({
479
+ ok: !1,
480
+ error: { message: `No route registered for action: ${s}`, code: "E_NO_ROUTE" }
365
481
  });
366
482
  }
367
- const de = "worker", ue = 3e4;
368
- function ge(r) {
369
- if (r.owner === de) {
370
- const e = A.get(r.action);
483
+ function Ce(r) {
484
+ if (r.owner === Me) {
485
+ const e = h.get(r.action);
371
486
  if (!e)
372
487
  throw new Error(
373
488
  `No worker-local handler registered for action: ${r.action}`
374
489
  );
375
- return async (t, n) => {
376
- var a;
377
- t = k(t);
378
- const s = (n == null ? void 0 : n.signal) ?? (n != null && n.runId ? (a = p.get(n.runId)) == null ? void 0 : a.signal : void 0);
490
+ return async (s, t) => {
491
+ var o;
492
+ s = k(s);
493
+ const n = (t == null ? void 0 : t.signal) ?? (t != null && t.runId ? (o = p.get(t.runId)) == null ? void 0 : o.signal : void 0);
379
494
  try {
380
- return { ok: !0, value: await e(t, { ...n, action: r.action, signal: s }) };
381
- } catch (o) {
382
- const f = o instanceof Error ? o.message : String(o), l = typeof o == "object" && o !== null && "code" in o && typeof o.code == "string" ? o.code : r.errorCode;
383
- return { ok: !1, error: { message: f, code: l } };
495
+ return { ok: !0, value: await e(s, { ...t, action: r.action, signal: n }) };
496
+ } catch (i) {
497
+ const a = i instanceof Error ? i.message : String(i), g = typeof i == "object" && i !== null && "code" in i && typeof i.code == "string" ? i.code : r.errorCode;
498
+ return { ok: !1, error: { message: a, code: g } };
384
499
  }
385
500
  };
386
501
  } else {
387
- const e = fe({
502
+ const e = Q({
388
503
  owner: r.owner,
389
504
  action: r.action,
390
- timeoutMs: ue
505
+ resolveTimeoutMs: (s) => Z(r.action, s)
391
506
  });
392
- return (t, n) => {
393
- var s;
394
- return e(k(t), {
395
- ...n,
396
- signal: (n == null ? void 0 : n.signal) ?? (n != null && n.runId ? (s = p.get(n.runId)) == null ? void 0 : s.signal : void 0)
507
+ return (s, t) => {
508
+ var n;
509
+ return e(k(s), {
510
+ ...t,
511
+ signal: (t == null ? void 0 : t.signal) ?? (t != null && t.runId ? (n = p.get(t.runId)) == null ? void 0 : n.signal : void 0)
397
512
  });
398
513
  };
399
514
  }
400
515
  }
401
- function pe(r) {
402
- i("exists", (e) => r.fsExists(e)), i("stat", (e) => r.fsStat(e)), i("read", (e) => r.fsRead(e)), i("readText", (e) => r.fsReadText(e)), i("readBase64", (e) => r.fsReadBase64(e)), i("list", (e) => r.fsList(e)), i("mkdir", (e) => r.fsMkdir(e)), i("delete", (e) => r.fsDelete(e)), i("copy", (e) => r.fsCopy(e)), i("move", (e) => r.fsMove(e)), i("write", (e) => r.fsWrite(e)), i("writeText", (e) => r.fsWriteText(e)), i("writeBase64", (e) => r.fsWriteBase64(e)), i("append", (e) => r.fsAppend(e)), i("appendText", (e) => r.fsAppendText(e)), i("appendBase64", (e) => r.fsAppendBase64(e)), i("readRange", (e) => r.fsReadRange(e)), i("update", (e) => r.fsUpdate(e)), i("hash", (e) => r.fsHash(e));
403
- }
404
- async function me(r, e) {
405
- if (T) return;
406
- await z(), c = new G(), L(3), V(L), pe(c), se(r);
407
- const n = r.map((a) => ({
408
- entry: oe(a),
409
- callback: ge(a)
516
+ function Le(r) {
517
+ c("exists", (e) => r.fsExists(e)), c("stat", (e) => r.fsStat(e)), c("read", (e) => r.fsRead(e)), c("readText", (e) => r.fsReadText(e)), c("readBase64", (e) => r.fsReadBase64(e)), c("list", (e) => r.fsList(e)), c("mkdir", (e) => r.fsMkdir(e)), c("delete", (e) => r.fsDelete(e)), c("copy", (e) => r.fsCopy(e)), c("move", (e) => r.fsMove(e)), c("write", (e) => r.fsWrite(e)), c("writeText", (e) => r.fsWriteText(e)), c("writeBase64", (e) => r.fsWriteBase64(e)), c("append", (e) => r.fsAppend(e)), c("appendText", (e) => r.fsAppendText(e)), c("appendBase64", (e) => r.fsAppendBase64(e)), c("readRange", (e) => r.fsReadRange(e)), c("update", (e) => r.fsUpdate(e)), c("hash", (e) => r.fsHash(e));
518
+ }
519
+ async function ve(r, e) {
520
+ if (v) return;
521
+ await x(), _ = new ee(), C(0), ae(C), l.trace("initWasm_start"), Le(_), _e(r);
522
+ const t = r.map((o) => ({
523
+ entry: be(o),
524
+ callback: Ce(o)
410
525
  }));
411
526
  try {
412
- H(n);
413
- } catch (a) {
414
- const o = a instanceof Error ? a.message : String(a);
415
- throw new Error(`Registry registration failed: ${o}`);
527
+ re(t);
528
+ } catch (o) {
529
+ const i = o instanceof Error ? o.message : String(o);
530
+ throw new Error(`Registry registration failed: ${i}`);
531
+ }
532
+ const { freezeManifest: n } = await import("./extension_js.js");
533
+ try {
534
+ n();
535
+ } catch (o) {
536
+ const i = o instanceof Error ? o.message : String(o);
537
+ throw new Error(`Manifest freeze failed: ${i}`);
416
538
  }
417
- const { freezeManifest: s } = await import("../../pkg/extension_js.js");
418
- if (s(), c.injectRegistryBindings(), e) {
419
- const a = JSON.stringify(e);
420
- await c.runCellAsync(
421
- `(function(){var r=globalThis.chrome&&globalThis.chrome.runtime;if(!r){r={};if(!globalThis.chrome)globalThis.chrome={};globalThis.chrome.runtime=r;}r.id=${a};})();`,
539
+ if (_.injectRegistryBindings(), e) {
540
+ const o = JSON.stringify(e);
541
+ await _.runCellAsync(
542
+ `(function(){var r=globalThis.chrome&&globalThis.chrome.runtime;if(!r){r={};if(!globalThis.chrome)globalThis.chrome={};globalThis.chrome.runtime=r;}r.id=${o};})();`,
422
543
  "",
423
544
  "inject-runtime-id"
424
545
  );
425
546
  }
426
- T = !0;
547
+ v = !0, l.trace("initWasm_done");
427
548
  }
428
549
  self.onmessage = async (r) => {
429
550
  const e = r.data;
430
- if (e.type === "asyncRelayResult") {
431
- $(e.id, e.result);
551
+ if (l.trace("onmessage", { type: e.type, id: "id" in e ? e.id : void 0 }), e.type === "asyncRelayResult") {
552
+ l.trace("asyncRelayResult", { id: e.id }), N(e.id, e.result);
432
553
  return;
433
554
  }
434
555
  if (e.type === "registerWorkerPort") {
435
556
  const t = r.ports[0];
436
557
  if (!t) {
437
- m.error("register_worker_port_missing", { owner: e.owner });
558
+ l.error("register_worker_port_missing", { owner: e.owner });
438
559
  return;
439
560
  }
440
- le(e.owner, t);
561
+ ke(e.owner, t);
441
562
  return;
442
563
  }
443
564
  if (e.type === "init") {
444
565
  try {
445
- await me(e.manifest, e.extensionId), self.postMessage({ type: "ready" });
566
+ await ve(e.manifest, e.extensionId), self.postMessage({ type: "ready" });
446
567
  } catch (t) {
447
568
  const n = t instanceof Error ? t.message : String(t);
448
- m.error("worker_init_failed", { error: n }), self.postMessage({ type: "error", error: `WASM init failed: ${n}` });
569
+ l.error("worker_init_failed", { error: n }), self.postMessage({ type: "error", error: `WASM init failed: ${n}` });
449
570
  }
450
571
  return;
451
572
  }
452
573
  if (e.type === "setLogLevel") {
453
- L(e.level), J(ie(e.level)), m.debug("set_log_level", { level: e.level });
574
+ C(e.level), ne(we(e.level)), l.trace("set_log_level", { level: e.level });
454
575
  return;
455
576
  }
456
- if (!T || !c) {
577
+ if (!v || !_) {
457
578
  self.postMessage({
458
579
  type: "error",
459
580
  id: e.id,
@@ -461,107 +582,130 @@ self.onmessage = async (r) => {
461
582
  });
462
583
  return;
463
584
  }
464
- switch (e.type) {
465
- case "runCell": {
466
- const t = e.runId, n = new AbortController();
467
- t && p.set(t, n);
468
- try {
469
- const s = await c.runCellAsync(
470
- e.code,
471
- e.stdin || "",
472
- t || ""
473
- // propagate correlation ID to WASM so trace spans can be linked end-to-end
474
- );
475
- self.postMessage({
476
- type: "result",
477
- id: e.id,
478
- data: s,
479
- runId: t
480
- });
481
- } catch (s) {
482
- const a = s instanceof Error ? s.message : String(s);
483
- m.error("runCell_error", { runId: t, error: a }), self.postMessage({
484
- type: "error",
485
- id: e.id,
486
- error: a,
487
- runId: t
488
- });
489
- } finally {
490
- t && p.delete(t);
585
+ const s = _;
586
+ await he(async () => {
587
+ switch (e.type) {
588
+ case "runCell": {
589
+ const t = e.runId, n = new AbortController();
590
+ t && p.set(t, n), f = { id: e.id, runId: t }, l.trace("runCell_start", { runId: t, callId: e.id, codeLen: e.code.length });
591
+ try {
592
+ const o = await s.runCellAsync(
593
+ e.code,
594
+ e.stdin || "",
595
+ t || ""
596
+ );
597
+ l.trace("runCell_done", { runId: t, callId: e.id, status: o.status }), self.postMessage({
598
+ type: "result",
599
+ id: e.id,
600
+ data: o,
601
+ runId: t
602
+ });
603
+ } catch (o) {
604
+ const i = o instanceof Error ? o.message : String(o);
605
+ l.error("runCell_error", { runId: t, error: i }), self.postMessage({
606
+ type: "error",
607
+ id: e.id,
608
+ error: i,
609
+ runId: t
610
+ });
611
+ } finally {
612
+ (f == null ? void 0 : f.id) === e.id && (f = null), t && p.delete(t);
613
+ }
614
+ break;
491
615
  }
492
- break;
493
- }
494
- case "reset": {
495
- c.setAborted(!0);
496
- for (const t of p.values()) t.abort();
497
- p.clear(), F("E_RESET", "Worker reset");
498
- try {
499
- c.reset(), self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
500
- } catch (t) {
501
- const n = t instanceof Error ? t.message : String(t);
502
- self.postMessage({ type: "error", id: e.id, error: n });
616
+ case "reset": {
617
+ s.setAborted(!0);
618
+ for (const t of p.values()) t.abort();
619
+ p.clear(), z("E_RESET", "Worker reset");
620
+ try {
621
+ s.reset(), self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
622
+ } catch (t) {
623
+ const n = t instanceof Error ? t.message : String(t);
624
+ self.postMessage({ type: "error", id: e.id, error: n });
625
+ }
626
+ break;
503
627
  }
504
- break;
505
- }
506
- case "stop": {
507
- c.setAborted(!0);
508
- for (const t of p.values()) t.abort();
509
- p.clear(), F("E_STOPPED", "Worker stopped"), self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
510
- break;
511
- }
512
- case "setFuelLimit": {
513
- try {
514
- c.set_fuel_limit(e.limit), e.id && self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
515
- } catch (t) {
516
- if (e.id) {
628
+ case "stop": {
629
+ s.setAborted(!0);
630
+ for (const t of p.values()) t.abort();
631
+ p.clear(), z("E_STOPPED", "Worker stopped"), self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
632
+ break;
633
+ }
634
+ case "setFuelLimit": {
635
+ try {
636
+ s.set_fuel_limit(e.limit), e.id && self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
637
+ } catch (t) {
638
+ if (e.id) {
639
+ const n = t instanceof Error ? t.message : String(t);
640
+ self.postMessage({ type: "error", id: e.id, error: n });
641
+ }
642
+ }
643
+ break;
644
+ }
645
+ case "inspectGlobals": {
646
+ try {
647
+ const t = s.inspect_globals();
648
+ self.postMessage({ type: "result", id: e.id, data: t });
649
+ } catch (t) {
517
650
  const n = t instanceof Error ? t.message : String(t);
518
651
  self.postMessage({ type: "error", id: e.id, error: n });
519
652
  }
653
+ break;
520
654
  }
521
- break;
522
- }
523
- case "inspectGlobals": {
524
- try {
525
- const t = c.inspect_globals();
526
- self.postMessage({ type: "result", id: e.id, data: t });
527
- } catch (t) {
528
- const n = t instanceof Error ? t.message : String(t);
529
- self.postMessage({ type: "error", id: e.id, error: n });
655
+ case "apiDocs": {
656
+ try {
657
+ const t = s.apiDocs(e.format);
658
+ self.postMessage({ type: "result", id: e.id, data: t });
659
+ } catch (t) {
660
+ const n = t instanceof Error ? t.message : String(t);
661
+ self.postMessage({ type: "error", id: e.id, error: n });
662
+ }
663
+ break;
530
664
  }
531
- break;
532
- }
533
- case "loadLibrary": {
534
- try {
535
- const t = c.load_library(e.source);
536
- self.postMessage({ type: "result", id: e.id, data: t });
537
- } catch (t) {
538
- const n = t instanceof Error ? t.message : String(t);
539
- self.postMessage({ type: "error", id: e.id, error: n });
665
+ case "loadLibrary": {
666
+ try {
667
+ const t = s.load_library(e.source);
668
+ self.postMessage({ type: "result", id: e.id, data: t });
669
+ } catch (t) {
670
+ const n = t instanceof Error ? t.message : String(t);
671
+ self.postMessage({ type: "error", id: e.id, error: n });
672
+ }
673
+ break;
540
674
  }
541
- break;
542
- }
543
- case "fsCall": {
544
- const t = A.get(e.action);
545
- if (!t) {
546
- self.postMessage({
547
- type: "error",
548
- id: e.id,
549
- error: `Unknown fs action: ${e.action}`
550
- });
675
+ case "fsCall": {
676
+ const t = h.get(e.action);
677
+ if (!t) {
678
+ self.postMessage({
679
+ type: "error",
680
+ id: e.id,
681
+ error: `Unknown fs action: ${e.action}`
682
+ });
683
+ break;
684
+ }
685
+ try {
686
+ const n = await t(e.params);
687
+ self.postMessage({ type: "result", id: e.id, data: n });
688
+ } catch (n) {
689
+ const o = n instanceof Error ? n.message : String(n);
690
+ self.postMessage({ type: "error", id: e.id, error: o });
691
+ }
551
692
  break;
552
693
  }
553
- try {
554
- const n = await t(e.params);
555
- self.postMessage({ type: "result", id: e.id, data: n });
556
- } catch (n) {
557
- const s = n instanceof Error ? n.message : String(n);
558
- self.postMessage({ type: "error", id: e.id, error: s });
694
+ default: {
695
+ l.error("unhandled_worker_message", { type: e.type });
696
+ break;
559
697
  }
560
- break;
561
- }
562
- default: {
563
- m.error("unhandled_worker_message", { type: e.type });
564
- break;
565
698
  }
566
- }
699
+ });
700
+ };
701
+ export {
702
+ w as DEFAULT_RELAY_TIMEOUT_MS,
703
+ Ce as createExecutableCallback,
704
+ Ne as extensionDispatch,
705
+ c as registerWorkerHandler,
706
+ ke as registerWorkerPort,
707
+ N as resolveAsyncRelayResult,
708
+ Z as resolveRelayTimeoutMs,
709
+ Q as safePostAsCall,
710
+ z as settleAllPendingRelays
567
711
  };