@extension-use/host 0.0.0-stage → 0.1.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.
@@ -0,0 +1,843 @@
1
+ import {
2
+ OFFSCREEN_MESSAGE
3
+ } from "./chunk-5X4QMMKA.js";
4
+
5
+ // src/background/tab-capture.ts
6
+ import { ExtensionUseError } from "@extension-use/protocol";
7
+ var offscreenPath;
8
+ function configureTabCapture(path) {
9
+ offscreenPath = path;
10
+ }
11
+ function tabCaptureAvailable() {
12
+ return !!offscreenPath && !!chrome.tabCapture?.getMediaStreamId && !!chrome.offscreen?.createDocument;
13
+ }
14
+ function assertAvailable() {
15
+ if (!chrome.tabCapture?.getMediaStreamId || !chrome.offscreen?.createDocument) {
16
+ throw new ExtensionUseError("NEEDS_PERMISSION", 'Tab capture needs the "tabCapture" and "offscreen" permissions (the tabCapture group)');
17
+ }
18
+ if (!offscreenPath) {
19
+ throw new ExtensionUseError(
20
+ "NEEDS_PERMISSION",
21
+ 'Tab capture needs an offscreen page: add one that calls mountOffscreen() from "@extension-use/host/offscreen", and pass its path to defineHost as `offscreen`'
22
+ );
23
+ }
24
+ }
25
+ var creating;
26
+ async function ensureOffscreen() {
27
+ const url = chrome.runtime.getURL(offscreenPath);
28
+ const existing = await chrome.runtime.getContexts({ contextTypes: ["OFFSCREEN_DOCUMENT"], documentUrls: [url] });
29
+ if (existing.length) return;
30
+ creating ??= chrome.offscreen.createDocument({ url, reasons: ["USER_MEDIA"], justification: "Capture a tab so it keeps rendering in the background, and take screenshots of it" }).catch((err) => {
31
+ if (!/single offscreen document/i.test(String(err?.message ?? err))) throw err;
32
+ }).finally(() => creating = void 0);
33
+ await creating;
34
+ }
35
+ async function send(command) {
36
+ await ensureOffscreen();
37
+ const reply = await chrome.runtime.sendMessage({ [OFFSCREEN_MESSAGE]: command });
38
+ if (!reply) throw new ExtensionUseError("INTERNAL", "The offscreen page did not answer (does it call mountOffscreen()?)");
39
+ if (!reply.ok) throw new ExtensionUseError("INTERNAL", reply.error);
40
+ return reply.output;
41
+ }
42
+ async function hasOffscreen() {
43
+ if (!offscreenPath || !chrome.runtime.getContexts) return false;
44
+ const url = chrome.runtime.getURL(offscreenPath);
45
+ return (await chrome.runtime.getContexts({ contextTypes: ["OFFSCREEN_DOCUMENT"], documentUrls: [url] })).length > 0;
46
+ }
47
+ async function capturedTabs() {
48
+ if (!await hasOffscreen()) return [];
49
+ return (await send({ op: "list" })).tabIds;
50
+ }
51
+ async function startCapture(tabId, size) {
52
+ assertAvailable();
53
+ if ((await capturedTabs()).includes(tabId)) return send({ op: "start", tabId });
54
+ let streamId;
55
+ try {
56
+ streamId = await chrome.tabCapture.getMediaStreamId({ targetTabId: tabId });
57
+ } catch (err) {
58
+ const message2 = String(err?.message ?? err);
59
+ if (/not been invoked/i.test(message2)) {
60
+ throw new ExtensionUseError(
61
+ "NEEDS_USER_GESTURE",
62
+ "Chrome lets an extension capture a tab only after the person invoked it there (toolbar button, side panel, shortcut or context menu) since the tab last navigated. Ask them to do that, or bring the tab to the front (tabs.activate)."
63
+ );
64
+ }
65
+ if (/active stream/i.test(message2)) throw new ExtensionUseError("INVALID_INPUT", "The tab is already being captured by something else");
66
+ throw new ExtensionUseError("INTERNAL", message2);
67
+ }
68
+ const clamp = (n) => Math.max(64, Math.min(4096, Math.round(n)));
69
+ return send({ op: "start", tabId, streamId, width: clamp(size.width), height: clamp(size.height) });
70
+ }
71
+ async function stopCapture(tabId) {
72
+ if (!await hasOffscreen()) return false;
73
+ return (await send({ op: "stop", tabId })).stopped;
74
+ }
75
+ function captureFrame(tabId, opts) {
76
+ return send({ op: "frame", tabId, ...opts });
77
+ }
78
+ async function withCapture(tabId, size, fn) {
79
+ assertAvailable();
80
+ if ((await capturedTabs()).includes(tabId)) return fn();
81
+ await startCapture(tabId, size);
82
+ try {
83
+ return await fn();
84
+ } finally {
85
+ await stopCapture(tabId).catch(() => {
86
+ });
87
+ }
88
+ }
89
+
90
+ // src/background/groups.ts
91
+ import { ExtensionUseError as ExtensionUseError3, matchPattern } from "@extension-use/protocol";
92
+ import { coreActionSchemas as coreActionSchemas2, z } from "@extension-use/protocol/schemas";
93
+
94
+ // src/background/browser-data.ts
95
+ import { ExtensionUseError as ExtensionUseError2 } from "@extension-use/protocol";
96
+ import { coreActionSchemas } from "@extension-use/protocol/schemas";
97
+ function bg(name, handler) {
98
+ return { name, schema: coreActionSchemas[name], handler };
99
+ }
100
+ var message = (err) => String(err?.message ?? err);
101
+ async function chromeCall(p, code = "INVALID_INPUT") {
102
+ try {
103
+ return await p;
104
+ } catch (err) {
105
+ throw new ExtensionUseError2(code, message(err));
106
+ }
107
+ }
108
+ function checkScheme(ctx, url, schemes, what) {
109
+ ctx.assertAllowedUrl(url);
110
+ if (!schemes.test(url)) throw new ExtensionUseError2("BLOCKED_BY_POLICY", `${what} must be ${schemes.source.replace(/[\^():|]/g, " ").trim()} URLs, got ${url}`);
111
+ }
112
+ function toDownload(d) {
113
+ return {
114
+ id: d.id,
115
+ url: d.finalUrl || d.url,
116
+ filename: d.filename,
117
+ state: d.state,
118
+ mime: d.mime ?? "",
119
+ bytesReceived: d.bytesReceived,
120
+ totalBytes: d.totalBytes,
121
+ startTime: d.startTime,
122
+ ...d.error ? { error: d.error } : {}
123
+ };
124
+ }
125
+ async function getDownload(id) {
126
+ const [d] = await chrome.downloads.search({ id });
127
+ if (!d) throw new ExtensionUseError2("TARGET_NOT_FOUND", `No download ${id}`);
128
+ return d;
129
+ }
130
+ function waitForDownload(id, signal) {
131
+ return new Promise((resolve, reject) => {
132
+ const finish = () => getDownload(id).then((d) => {
133
+ if (d.state === "in_progress") return;
134
+ cleanup();
135
+ resolve(d);
136
+ }, (err) => {
137
+ cleanup();
138
+ reject(err);
139
+ });
140
+ const onChanged = (delta) => {
141
+ if (delta.id === id && delta.state) void finish();
142
+ };
143
+ const onAbort = () => {
144
+ cleanup();
145
+ reject(signal.reason);
146
+ };
147
+ const cleanup = () => {
148
+ chrome.downloads.onChanged.removeListener(onChanged);
149
+ signal.removeEventListener("abort", onAbort);
150
+ };
151
+ chrome.downloads.onChanged.addListener(onChanged);
152
+ signal.addEventListener("abort", onAbort, { once: true });
153
+ void finish();
154
+ });
155
+ }
156
+ var downloadsGroup = {
157
+ name: "downloads",
158
+ permissions: ["downloads"],
159
+ needsHostAccess: false,
160
+ actions: [
161
+ bg("downloads.start", async (input, ctx) => {
162
+ checkScheme(ctx, input.url, /^(https?|data):/i, "Downloads");
163
+ const options = { url: input.url, conflictAction: input.conflictAction, saveAs: input.saveAs };
164
+ if (input.filename) options.filename = input.filename;
165
+ const id = await chromeCall(chrome.downloads.download(options));
166
+ const item = input.waitForComplete ? await waitForDownload(id, ctx.signal) : await getDownload(id);
167
+ return toDownload(item);
168
+ }),
169
+ bg("downloads.list", async (input) => {
170
+ const query = { limit: input.limit, orderBy: ["-startTime"] };
171
+ if (input.query) query.query = [input.query];
172
+ if (input.state) query.state = input.state;
173
+ return { downloads: (await chrome.downloads.search(query)).map(toDownload) };
174
+ }),
175
+ bg("downloads.cancel", async (input) => {
176
+ await getDownload(input.id);
177
+ await chromeCall(chrome.downloads.cancel(input.id));
178
+ return {};
179
+ })
180
+ ]
181
+ };
182
+ function toBookmark(n) {
183
+ return {
184
+ id: n.id,
185
+ title: n.title,
186
+ ...n.url !== void 0 ? { url: n.url } : {},
187
+ ...n.parentId !== void 0 ? { parentId: n.parentId } : {},
188
+ ...n.index !== void 0 ? { index: n.index } : {},
189
+ ...n.dateAdded !== void 0 ? { dateAdded: n.dateAdded } : {},
190
+ folder: n.url === void 0
191
+ };
192
+ }
193
+ async function getBookmark(id) {
194
+ const [n] = await chromeCall(chrome.bookmarks.get(id), "TARGET_NOT_FOUND");
195
+ if (!n) throw new ExtensionUseError2("TARGET_NOT_FOUND", `No bookmark ${id}`);
196
+ return n;
197
+ }
198
+ var checkBookmarkUrl = (ctx, url) => checkScheme(ctx, url, /^(https?|file):/i, "Bookmarks");
199
+ var bookmarksGroup = {
200
+ name: "bookmarks",
201
+ permissions: ["bookmarks"],
202
+ needsHostAccess: false,
203
+ actions: [
204
+ bg("bookmarks.search", async (input) => ({
205
+ bookmarks: (await chrome.bookmarks.search(input.query)).slice(0, input.limit).map(toBookmark)
206
+ })),
207
+ bg("bookmarks.list", async (input) => ({
208
+ bookmarks: (await chromeCall(chrome.bookmarks.getChildren(input.parentId), "TARGET_NOT_FOUND")).map(toBookmark)
209
+ })),
210
+ bg("bookmarks.create", async (input, ctx) => {
211
+ const details = { title: input.title };
212
+ if (input.url !== void 0) {
213
+ checkBookmarkUrl(ctx, input.url);
214
+ details.url = input.url;
215
+ }
216
+ if (input.parentId !== void 0) details.parentId = input.parentId;
217
+ if (input.index !== void 0) details.index = input.index;
218
+ return toBookmark(await chromeCall(chrome.bookmarks.create(details)));
219
+ }),
220
+ bg("bookmarks.update", async (input, ctx) => {
221
+ await getBookmark(input.id);
222
+ const changes = {};
223
+ if (input.title !== void 0) changes.title = input.title;
224
+ if (input.url !== void 0) {
225
+ checkBookmarkUrl(ctx, input.url);
226
+ changes.url = input.url;
227
+ }
228
+ if (Object.keys(changes).length) await chromeCall(chrome.bookmarks.update(input.id, changes));
229
+ if (input.parentId !== void 0 || input.index !== void 0) {
230
+ const dest = {};
231
+ if (input.parentId !== void 0) dest.parentId = input.parentId;
232
+ if (input.index !== void 0) dest.index = input.index;
233
+ await chromeCall(chrome.bookmarks.move(input.id, dest));
234
+ }
235
+ return toBookmark(await getBookmark(input.id));
236
+ }),
237
+ bg("bookmarks.remove", async (input) => {
238
+ const node = await getBookmark(input.id);
239
+ if (node.url === void 0 && input.recursive) await chromeCall(chrome.bookmarks.removeTree(input.id));
240
+ else {
241
+ await chromeCall(chrome.bookmarks.remove(input.id)).catch((err) => {
242
+ throw node.url === void 0 ? new ExtensionUseError2("INVALID_INPUT", `${err.message} Pass recursive: true to delete a folder and its contents.`) : err;
243
+ });
244
+ }
245
+ return {};
246
+ })
247
+ ]
248
+ };
249
+ var historyGroup = {
250
+ name: "history",
251
+ permissions: ["history"],
252
+ needsHostAccess: false,
253
+ actions: [
254
+ bg("history.search", async (input) => {
255
+ const query = { text: input.text, startTime: input.startTime ?? 0, maxResults: input.limit };
256
+ if (input.endTime !== void 0) query.endTime = input.endTime;
257
+ const items = await chrome.history.search(query);
258
+ return {
259
+ items: items.map((h) => ({
260
+ url: h.url ?? "",
261
+ title: h.title ?? "",
262
+ ...h.lastVisitTime !== void 0 ? { lastVisitTime: h.lastVisitTime } : {},
263
+ visitCount: h.visitCount ?? 0,
264
+ typedCount: h.typedCount ?? 0
265
+ }))
266
+ };
267
+ }),
268
+ bg("history.delete", async (input) => {
269
+ await chromeCall(chrome.history.deleteUrl({ url: input.url }));
270
+ return {};
271
+ })
272
+ ]
273
+ };
274
+ function toCookie(c) {
275
+ return {
276
+ name: c.name,
277
+ value: c.value,
278
+ domain: c.domain,
279
+ path: c.path,
280
+ secure: c.secure,
281
+ httpOnly: c.httpOnly,
282
+ sameSite: c.sameSite,
283
+ session: c.session,
284
+ hostOnly: c.hostOnly,
285
+ ...c.expirationDate !== void 0 ? { expirationDate: c.expirationDate } : {}
286
+ };
287
+ }
288
+ var checkCookieUrl = (ctx, url) => checkScheme(ctx, url, /^https?:/i, "Cookies");
289
+ function cookieApi() {
290
+ if (!chrome.cookies) throw new ExtensionUseError2("NEEDS_PERMISSION", 'The cookies group needs the "cookies" permission');
291
+ return chrome.cookies;
292
+ }
293
+ var cookiesGroup = {
294
+ name: "cookies",
295
+ permissions: ["cookies"],
296
+ // Chrome only shows cookies of sites the extension has host access to.
297
+ needsHostAccess: true,
298
+ actions: [
299
+ bg("cookies.list", async (input, ctx) => {
300
+ const filter = {};
301
+ if (input.url) {
302
+ checkCookieUrl(ctx, input.url);
303
+ filter.url = input.url;
304
+ }
305
+ if (input.domain) {
306
+ ctx.assertAllowedUrl(`https://${input.domain.replace(/^\./, "")}/`);
307
+ filter.domain = input.domain;
308
+ }
309
+ if (input.name) filter.name = input.name;
310
+ return { cookies: (await cookieApi().getAll(filter)).map(toCookie) };
311
+ }),
312
+ bg("cookies.set", async (input, ctx) => {
313
+ checkCookieUrl(ctx, input.url);
314
+ const details = { url: input.url, name: input.name, value: input.value };
315
+ if (input.domain !== void 0) details.domain = input.domain;
316
+ if (input.path !== void 0) details.path = input.path;
317
+ if (input.secure !== void 0) details.secure = input.secure;
318
+ if (input.httpOnly !== void 0) details.httpOnly = input.httpOnly;
319
+ if (input.sameSite !== void 0) details.sameSite = input.sameSite;
320
+ if (input.expirationDate !== void 0) details.expirationDate = input.expirationDate;
321
+ const cookie = await chromeCall(cookieApi().set(details));
322
+ if (!cookie) throw new ExtensionUseError2("INVALID_INPUT", "Chrome refused the cookie (check url, domain, secure and sameSite)");
323
+ return toCookie(cookie);
324
+ }),
325
+ bg("cookies.remove", async (input, ctx) => {
326
+ checkCookieUrl(ctx, input.url);
327
+ const existing = await cookieApi().get({ url: input.url, name: input.name });
328
+ if (existing) await chromeCall(cookieApi().remove({ url: input.url, name: input.name }));
329
+ return { removed: Boolean(existing) };
330
+ })
331
+ ]
332
+ };
333
+
334
+ // src/background/groups.ts
335
+ function bg2(name, handler) {
336
+ return { name, schema: coreActionSchemas2[name], handler };
337
+ }
338
+ function content(name) {
339
+ return { name, schema: coreActionSchemas2[name] };
340
+ }
341
+ function toTabInfo(t) {
342
+ return {
343
+ id: t.id ?? -1,
344
+ windowId: t.windowId,
345
+ url: t.url ?? t.pendingUrl ?? "",
346
+ title: t.title ?? "",
347
+ active: t.active,
348
+ status: t.status ?? "unknown",
349
+ ...t.discarded ? { discarded: true } : {},
350
+ ...t.autoDiscardable === false ? { autoDiscardable: false } : {}
351
+ };
352
+ }
353
+ async function waitForLoad(tabId, signal, opts = {}) {
354
+ const done = (t) => t.status === "complete" && !t.pendingUrl && !(opts.notBlank && (!t.url || t.url === "about:blank"));
355
+ const tab = await chrome.tabs.get(tabId);
356
+ if (done(tab)) return tab;
357
+ return new Promise((resolve, reject) => {
358
+ const onUpdated = (id, _info, t) => {
359
+ if (id === tabId && done(t)) {
360
+ cleanup();
361
+ resolve(t);
362
+ }
363
+ };
364
+ const onRemoved = (id) => {
365
+ if (id === tabId) {
366
+ cleanup();
367
+ reject(new ExtensionUseError3("TAB_CLOSED", "The tab was closed"));
368
+ }
369
+ };
370
+ const onAbort = () => {
371
+ cleanup();
372
+ reject(signal.reason);
373
+ };
374
+ const cleanup = () => {
375
+ chrome.tabs.onUpdated.removeListener(onUpdated);
376
+ chrome.tabs.onRemoved.removeListener(onRemoved);
377
+ signal.removeEventListener("abort", onAbort);
378
+ };
379
+ chrome.tabs.onUpdated.addListener(onUpdated);
380
+ chrome.tabs.onRemoved.addListener(onRemoved);
381
+ signal.addEventListener("abort", onAbort, { once: true });
382
+ chrome.tabs.get(tabId).then((t) => {
383
+ if (done(t)) {
384
+ cleanup();
385
+ resolve(t);
386
+ }
387
+ }, () => {
388
+ });
389
+ });
390
+ }
391
+ function toWindowInfo(w) {
392
+ return {
393
+ id: w.id ?? -1,
394
+ focused: w.focused,
395
+ state: w.state ?? "normal",
396
+ type: w.type ?? "normal",
397
+ incognito: w.incognito,
398
+ ...w.left !== void 0 ? { left: w.left } : {},
399
+ ...w.top !== void 0 ? { top: w.top } : {},
400
+ ...w.width !== void 0 ? { width: w.width } : {},
401
+ ...w.height !== void 0 ? { height: w.height } : {},
402
+ tabCount: w.tabs?.length ?? 0
403
+ };
404
+ }
405
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
406
+ function assertMayClose(ctx, url) {
407
+ if (!url || /^(about:blank|chrome:\/\/newtab\/?|chrome:\/\/new-tab-page\/?|edge:\/\/newtab\/?)$/i.test(url)) return;
408
+ ctx.assertAllowedUrl(url);
409
+ }
410
+ async function navigateAndWait(tabId, start, signal, wait) {
411
+ let onUpdated;
412
+ const loading = new Promise((resolve) => {
413
+ onUpdated = (id, info) => {
414
+ if (id === tabId && info.status === "loading") resolve();
415
+ };
416
+ chrome.tabs.onUpdated.addListener(onUpdated);
417
+ });
418
+ try {
419
+ await start();
420
+ if (!wait) return await chrome.tabs.get(tabId);
421
+ await Promise.race([loading, sleep(500)]);
422
+ } finally {
423
+ chrome.tabs.onUpdated.removeListener(onUpdated);
424
+ }
425
+ return waitForLoad(tabId, signal);
426
+ }
427
+ async function historyInPage(tabId, dir) {
428
+ if (!chrome.scripting?.executeScript) return false;
429
+ const [result] = await chrome.scripting.executeScript({
430
+ target: { tabId },
431
+ func: (back) => {
432
+ const nav = globalThis.navigation;
433
+ if (!nav || !(back ? nav.canGoBack : nav.canGoForward)) return false;
434
+ history.go(back ? -1 : 1);
435
+ return true;
436
+ },
437
+ args: [dir === "back"]
438
+ });
439
+ return result?.result === true;
440
+ }
441
+ async function historyStep(ctx, dir, wait) {
442
+ const { tabId } = await ctx.tab();
443
+ const go = async () => {
444
+ try {
445
+ await (dir === "back" ? chrome.tabs.goBack(tabId) : chrome.tabs.goForward(tabId));
446
+ } catch (err) {
447
+ if (await historyInPage(tabId, dir).catch(() => false)) return;
448
+ throw new ExtensionUseError3("INVALID_INPUT", `Can't go ${dir}: ${String(err?.message ?? err)}`);
449
+ }
450
+ };
451
+ return toTabInfo(await navigateAndWait(tabId, go, ctx.signal, wait));
452
+ }
453
+ function checkUrl(ctx, url) {
454
+ ctx.assertAllowedUrl(url);
455
+ if (!/^(https?|file|data):/i.test(url)) {
456
+ throw new ExtensionUseError3("BLOCKED_BY_POLICY", `Only http(s), file and data URLs can be opened, got ${url}`);
457
+ }
458
+ }
459
+ var runtimeGroup = {
460
+ name: "runtime",
461
+ permissions: [],
462
+ needsHostAccess: false,
463
+ actions: [
464
+ bg2("runtime.ping", () => ({ pong: true, ts: Date.now() })),
465
+ bg2("runtime.describe", (input, ctx) => {
466
+ const toJson = (schema, io) => z.toJSONSchema(schema, { io, unrepresentable: "any", reused: "inline", cycles: "ref" });
467
+ const wanted = input.actions ? new Set(input.actions) : void 0;
468
+ return {
469
+ host: ctx.host,
470
+ actions: ctx.listActions().filter((d) => !wanted || wanted.has(d.name)).map((d) => ({
471
+ name: d.name,
472
+ description: d.schema.description,
473
+ where: d.schema.where,
474
+ version: d.schema.version,
475
+ input: toJson(d.schema.input, "input"),
476
+ output: toJson(d.schema.output, "output")
477
+ }))
478
+ };
479
+ })
480
+ ]
481
+ };
482
+ var runGroup = {
483
+ name: "run",
484
+ permissions: [],
485
+ needsHostAccess: false,
486
+ actions: [
487
+ bg2("run.sequence", async (input, ctx) => {
488
+ const results = [];
489
+ let completed = 0;
490
+ for (const step of input.steps) {
491
+ if (ctx.signal.aborted) throw ctx.signal.reason;
492
+ try {
493
+ const output = await ctx.call(step.action, step.input ?? {}, {
494
+ ...step.target ? { target: step.target } : {},
495
+ ...step.timeoutMs !== void 0 ? { timeoutMs: step.timeoutMs } : {}
496
+ });
497
+ results.push({ ok: true, action: step.action, output });
498
+ completed++;
499
+ if (step.pauseMs) await new Promise((r) => setTimeout(r, step.pauseMs));
500
+ } catch (err) {
501
+ const e = ExtensionUseError3.from(err);
502
+ if (e.code === "BLOCKED_BY_POLICY" && /paused/i.test(e.message)) throw e;
503
+ results.push({ ok: false, action: step.action, error: { code: e.code, message: e.message } });
504
+ if ((step.onError ?? input.onError) === "stop") break;
505
+ }
506
+ }
507
+ return { completed, ok: results.every((r) => r.ok) && results.length === input.steps.length, results };
508
+ })
509
+ ]
510
+ };
511
+ var tabsGroup = {
512
+ name: "tabs",
513
+ permissions: ["tabs"],
514
+ needsHostAccess: false,
515
+ actions: [
516
+ bg2("tabs.list", async (input, ctx) => {
517
+ const query = {};
518
+ if (input.currentWindow) {
519
+ if (ctx.session.windowId !== void 0) query.windowId = ctx.session.windowId;
520
+ else query.lastFocusedWindow = true;
521
+ }
522
+ const tabs = await chrome.tabs.query(query);
523
+ return {
524
+ tabs: tabs.map(toTabInfo).filter((t) => !input.urlMatch || matchPattern(input.urlMatch, t.url))
525
+ };
526
+ }),
527
+ bg2("tabs.open", async (input, ctx) => {
528
+ checkUrl(ctx, input.url);
529
+ const props = { url: input.url, active: input.active };
530
+ if (ctx.session.windowId !== void 0) props.windowId = ctx.session.windowId;
531
+ const tab = await chrome.tabs.create(props);
532
+ return toTabInfo(input.waitForLoad && tab.id !== void 0 ? await waitForLoad(tab.id, ctx.signal, { notBlank: true }) : tab);
533
+ }),
534
+ bg2("tabs.close", async (input, ctx) => {
535
+ const tab = await chrome.tabs.get(input.tabId).catch(() => {
536
+ throw new ExtensionUseError3("TARGET_NOT_FOUND", `No tab ${input.tabId}`);
537
+ });
538
+ assertMayClose(ctx, tab.url ?? "");
539
+ await chrome.tabs.remove(input.tabId);
540
+ return {};
541
+ }),
542
+ bg2("tabs.activate", async (input) => {
543
+ const tab = await chrome.tabs.update(input.tabId, { active: true }).catch(() => {
544
+ throw new ExtensionUseError3("TARGET_NOT_FOUND", `No tab ${input.tabId}`);
545
+ });
546
+ if (tab?.windowId !== void 0) await chrome.windows.update(tab.windowId, { focused: true }).catch(() => {
547
+ });
548
+ return toTabInfo(tab);
549
+ }),
550
+ bg2("tabs.navigate", async (input, ctx) => {
551
+ checkUrl(ctx, input.url);
552
+ const { tabId } = await ctx.tab();
553
+ return toTabInfo(await navigateAndWait(tabId, () => chrome.tabs.update(tabId, { url: input.url }), ctx.signal, input.waitForLoad));
554
+ }),
555
+ bg2("tabs.reload", async (input, ctx) => {
556
+ const { tabId } = await ctx.tab();
557
+ return toTabInfo(await navigateAndWait(tabId, () => chrome.tabs.reload(tabId), ctx.signal, input.waitForLoad));
558
+ }),
559
+ bg2("tabs.waitForLoad", async (_input, ctx) => {
560
+ const { tabId } = await ctx.tab();
561
+ return toTabInfo(await waitForLoad(tabId, ctx.signal));
562
+ }),
563
+ bg2("tabs.goBack", (input, ctx) => historyStep(ctx, "back", input.waitForLoad)),
564
+ bg2("tabs.goForward", (input, ctx) => historyStep(ctx, "forward", input.waitForLoad)),
565
+ bg2("tabs.update", async (input, ctx) => {
566
+ const { tabId } = await ctx.tab();
567
+ const props = {};
568
+ if (input.pinned !== void 0) props.pinned = input.pinned;
569
+ if (input.muted !== void 0) props.muted = input.muted;
570
+ if (input.autoDiscardable !== void 0) props.autoDiscardable = input.autoDiscardable;
571
+ if (Object.keys(props).length) await chrome.tabs.update(tabId, props);
572
+ if (input.zoom !== void 0) await chrome.tabs.setZoom(tabId, input.zoom);
573
+ const t = await chrome.tabs.get(tabId);
574
+ return {
575
+ ...toTabInfo(t),
576
+ pinned: t.pinned,
577
+ muted: t.mutedInfo?.muted ?? false,
578
+ zoom: await chrome.tabs.getZoom(tabId),
579
+ autoDiscardable: t.autoDiscardable
580
+ };
581
+ })
582
+ ]
583
+ };
584
+ async function getWindow(windowId) {
585
+ return chrome.windows.get(windowId, { populate: true }).catch(() => {
586
+ throw new ExtensionUseError3("TARGET_NOT_FOUND", `No window ${windowId}`);
587
+ });
588
+ }
589
+ var BOUNDS = ["left", "top", "width", "height"];
590
+ var windowsGroup = {
591
+ name: "windows",
592
+ permissions: [],
593
+ needsHostAccess: false,
594
+ actions: [
595
+ bg2("windows.list", async () => {
596
+ const wins = await chrome.windows.getAll({ populate: true, windowTypes: ["normal", "popup"] });
597
+ return { windows: wins.map(toWindowInfo) };
598
+ }),
599
+ bg2("windows.open", async (input, ctx) => {
600
+ if (input.url) checkUrl(ctx, input.url);
601
+ const data = { focused: input.focused, type: input.type };
602
+ if (input.url) data.url = input.url;
603
+ for (const k of BOUNDS) if (input[k] !== void 0) data[k] = input[k];
604
+ const created = await chrome.windows.create(data).catch((err) => {
605
+ throw new ExtensionUseError3("INVALID_INPUT", String(err?.message ?? err));
606
+ });
607
+ if (created?.id === void 0) throw new ExtensionUseError3("INTERNAL", "The window was not created");
608
+ let tab = created.tabs?.[0];
609
+ if (tab?.id !== void 0 && input.url && input.waitForLoad) tab = await waitForLoad(tab.id, ctx.signal, { notBlank: true });
610
+ const win = await getWindow(created.id);
611
+ return { ...toWindowInfo(win), ...tab ? { tab: toTabInfo(tab) } : {} };
612
+ }),
613
+ bg2("windows.update", async (input) => {
614
+ await getWindow(input.windowId);
615
+ const info = {};
616
+ if (input.focused !== void 0) info.focused = input.focused;
617
+ if (input.state !== void 0) info.state = input.state;
618
+ for (const k of BOUNDS) if (input[k] !== void 0) info[k] = input[k];
619
+ await chrome.windows.update(input.windowId, info).catch((err) => {
620
+ throw new ExtensionUseError3("INVALID_INPUT", String(err?.message ?? err));
621
+ });
622
+ return toWindowInfo(await getWindow(input.windowId));
623
+ }),
624
+ bg2("windows.close", async (input, ctx) => {
625
+ const win = await getWindow(input.windowId);
626
+ for (const t of win.tabs ?? []) assertMayClose(ctx, t.url ?? t.pendingUrl ?? "");
627
+ await chrome.windows.remove(input.windowId);
628
+ return {};
629
+ })
630
+ ]
631
+ };
632
+ var captureGroup = {
633
+ name: "capture",
634
+ permissions: [],
635
+ needsHostAccess: true,
636
+ actions: [
637
+ bg2("capture.screenshot", async (input, ctx) => {
638
+ const tab = await ctx.tab();
639
+ const opts = { format: input.format, ...input.quality !== void 0 ? { quality: input.quality } : {} };
640
+ const dataUrl = await withShooter(ctx, tab, (shooter) => shooter.shoot(opts));
641
+ const bitmap = await createImageBitmap(await (await fetch(dataUrl)).blob());
642
+ if (!input.locator) {
643
+ const out = { dataUrl, width: bitmap.width, height: bitmap.height };
644
+ bitmap.close();
645
+ return out;
646
+ }
647
+ const [{ elements }, page] = await Promise.all([
648
+ ctx.callContent("dom.query", { locator: input.locator }),
649
+ ctx.callContent("page.info", {})
650
+ ]);
651
+ const box = elements[0]?.box;
652
+ if (!box) throw new ExtensionUseError3("ELEMENT_NOT_FOUND", "Element not found");
653
+ const scale = bitmap.width / page.viewport.width;
654
+ const sx = Math.max(0, Math.round(box.x * scale));
655
+ const sy = Math.max(0, Math.round(box.y * scale));
656
+ const sw = Math.max(1, Math.min(bitmap.width - sx, Math.round(box.width * scale)));
657
+ const sh = Math.max(1, Math.min(bitmap.height - sy, Math.round(box.height * scale)));
658
+ const canvas = new OffscreenCanvas(sw, sh);
659
+ canvas.getContext("2d").drawImage(bitmap, sx, sy, sw, sh, 0, 0, sw, sh);
660
+ bitmap.close();
661
+ const blob = await canvas.convertToBlob({
662
+ type: input.format === "jpeg" ? "image/jpeg" : "image/png",
663
+ ...input.quality !== void 0 ? { quality: input.quality / 100 } : {}
664
+ });
665
+ return { dataUrl: await blobToDataUrl(blob), width: sw, height: sh };
666
+ }),
667
+ bg2("capture.fullPage", async (input, ctx) => {
668
+ const tab = await ctx.tab();
669
+ const page = await ctx.callContent("page.info", {});
670
+ const vh = page.viewport.height;
671
+ let total = Math.min(page.document.height, input.maxHeight);
672
+ let truncated = page.document.height > input.maxHeight;
673
+ let canvas;
674
+ let lastShot = 0;
675
+ await withShooter(ctx, tab, async (shooter) => {
676
+ try {
677
+ for (let y = 0; y < total; y += vh) {
678
+ if (ctx.signal.aborted) throw ctx.signal.reason;
679
+ const { scroll } = await ctx.callContent("page.scroll", { x: 0, y });
680
+ await sleep(Math.max(120, lastShot + shooter.minGapMs - Date.now()));
681
+ const shot = await shooter.shoot({ format: "png" });
682
+ lastShot = Date.now();
683
+ const bitmap = await createImageBitmap(await (await fetch(shot)).blob());
684
+ const scale = bitmap.width / page.viewport.width;
685
+ if (!canvas) {
686
+ const maxCss = Math.floor(32e3 / scale);
687
+ if (total > maxCss) {
688
+ total = maxCss;
689
+ truncated = true;
690
+ }
691
+ canvas = new OffscreenCanvas(bitmap.width, Math.round(total * scale));
692
+ }
693
+ canvas.getContext("2d").drawImage(bitmap, 0, Math.round(scroll.y * scale));
694
+ bitmap.close();
695
+ if (scroll.y + vh >= total) break;
696
+ }
697
+ } finally {
698
+ await ctx.callContent("page.scroll", { x: page.scroll.x, y: page.scroll.y }).catch(() => {
699
+ });
700
+ }
701
+ });
702
+ if (!canvas) throw new ExtensionUseError3("INTERNAL", "Nothing was captured");
703
+ const blob = await canvas.convertToBlob({
704
+ type: input.format === "jpeg" ? "image/jpeg" : "image/png",
705
+ ...input.quality !== void 0 ? { quality: input.quality / 100 } : {}
706
+ });
707
+ return { dataUrl: await blobToDataUrl(blob), width: canvas.width, height: canvas.height, truncated };
708
+ })
709
+ ]
710
+ };
711
+ async function withShooter(ctx, tab, fn) {
712
+ const info = await chrome.tabs.get(tab.tabId);
713
+ const win = await chrome.windows.get(info.windowId).catch(() => void 0);
714
+ if (info.active && win?.state !== "minimized") {
715
+ return fn({ shoot: (opts) => captureWithRetry(tab.windowId, opts, ctx.signal), minGapMs: 550 });
716
+ }
717
+ if (!tabCaptureAvailable()) {
718
+ if (info.active) throw new ExtensionUseError3("TARGET_NOT_FOUND", "The window is minimized. Restore it (windows.update), or enable the tabCapture group to capture tabs Chrome isn't showing");
719
+ throw new ExtensionUseError3("TARGET_NOT_FOUND", "The tab is in the background. Bring it to the front (tabs.activate), or enable the tabCapture group to capture background tabs");
720
+ }
721
+ return withCapture(
722
+ tab.tabId,
723
+ await viewportSize(ctx, info),
724
+ () => fn({ shoot: async (opts) => (await captureFrame(tab.tabId, opts)).dataUrl, minGapMs: 0 })
725
+ );
726
+ }
727
+ async function viewportSize(ctx, info) {
728
+ try {
729
+ const { viewport } = await ctx.callContent("page.info", {});
730
+ return { width: viewport.width * viewport.devicePixelRatio, height: viewport.height * viewport.devicePixelRatio };
731
+ } catch {
732
+ return { width: info.width ?? 1280, height: info.height ?? 800 };
733
+ }
734
+ }
735
+ async function captureWithRetry(windowId, opts, signal) {
736
+ for (let attempt = 0; ; attempt++) {
737
+ try {
738
+ return await chrome.tabs.captureVisibleTab(windowId, opts);
739
+ } catch (err) {
740
+ const message2 = String(err?.message ?? err);
741
+ const rateLimited = /MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND/i.test(message2);
742
+ const transient = rateLimited || /readback failed|Failed to capture tab/i.test(message2);
743
+ if (!transient || attempt >= 2 || signal.aborted) throw new ExtensionUseError3("INTERNAL", message2);
744
+ await new Promise((r) => setTimeout(r, rateLimited ? 550 : 150));
745
+ }
746
+ }
747
+ }
748
+ async function blobToDataUrl(blob) {
749
+ const bytes = new Uint8Array(await blob.arrayBuffer());
750
+ let binary = "";
751
+ for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
752
+ return `data:${blob.type};base64,${btoa(binary)}`;
753
+ }
754
+ var framesGroup = {
755
+ name: "frames",
756
+ permissions: ["webNavigation"],
757
+ needsHostAccess: false,
758
+ actions: [
759
+ bg2("frames.list", async (_input, ctx) => {
760
+ const { tabId } = await ctx.tab();
761
+ if (!chrome.webNavigation?.getAllFrames) throw new ExtensionUseError3("NEEDS_PERMISSION", 'frames.list needs the "webNavigation" permission');
762
+ const frames = await chrome.webNavigation.getAllFrames({ tabId }) ?? [];
763
+ return { frames: frames.map((f) => ({ frameId: f.frameId, parentFrameId: f.parentFrameId, url: f.url })) };
764
+ })
765
+ ]
766
+ };
767
+ var tabCaptureGroup = {
768
+ name: "tabCapture",
769
+ permissions: ["tabCapture", "offscreen"],
770
+ needsHostAccess: false,
771
+ actions: [
772
+ bg2("tabCapture.start", async (_input, ctx) => {
773
+ const tab = await ctx.tab();
774
+ const size = await startCapture(tab.tabId, await viewportSize(ctx, await chrome.tabs.get(tab.tabId)));
775
+ return { tabId: tab.tabId, ...size };
776
+ }),
777
+ bg2("tabCapture.stop", async (_input, ctx) => {
778
+ const { tabId } = await ctx.tab();
779
+ return { stopped: await stopCapture(tabId) };
780
+ }),
781
+ bg2("tabCapture.list", async () => ({ tabIds: await capturedTabs() }))
782
+ ]
783
+ };
784
+ function contentGroup(name, actions) {
785
+ return { name, permissions: [], needsHostAccess: true, actions: actions.map(content) };
786
+ }
787
+ var pageGroup = contentGroup("page", ["page.info", "page.scroll"]);
788
+ var domGroup = contentGroup("dom", [
789
+ "dom.query",
790
+ "dom.text",
791
+ "dom.snapshot",
792
+ "dom.html",
793
+ "dom.click",
794
+ "dom.hover",
795
+ "dom.focus",
796
+ "dom.type",
797
+ "dom.fill",
798
+ "dom.select",
799
+ "dom.check",
800
+ "dom.press",
801
+ "dom.scrollTo",
802
+ "dom.blur",
803
+ "dom.drag",
804
+ "dom.upload",
805
+ "dom.scroll",
806
+ "dom.wheel",
807
+ "dom.selectText",
808
+ "dom.paste",
809
+ "dom.pointer"
810
+ ]);
811
+ var editGroup = contentGroup("edit", ["edit.setHtml", "edit.setText", "edit.setAttributes", "edit.remove"]);
812
+ var waitGroup = contentGroup("wait", ["wait.for"]);
813
+ var overlayGroup = contentGroup("overlay", ["overlay.highlight", "overlay.clear", "overlay.toast"]);
814
+ var pickerGroup = contentGroup("picker", ["picker.start", "picker.cancel"]);
815
+ var builtinGroups = {
816
+ runtime: runtimeGroup,
817
+ run: runGroup,
818
+ tabs: tabsGroup,
819
+ windows: windowsGroup,
820
+ capture: captureGroup,
821
+ frames: framesGroup,
822
+ page: pageGroup,
823
+ dom: domGroup,
824
+ edit: editGroup,
825
+ wait: waitGroup,
826
+ overlay: overlayGroup,
827
+ picker: pickerGroup,
828
+ tabCapture: tabCaptureGroup,
829
+ downloads: downloadsGroup,
830
+ bookmarks: bookmarksGroup,
831
+ history: historyGroup,
832
+ cookies: cookiesGroup
833
+ };
834
+ var OPT_IN_GROUPS = ["tabCapture", "downloads", "bookmarks", "history", "cookies"];
835
+ var allBuiltinGroups = Object.entries(builtinGroups).filter(([name]) => !OPT_IN_GROUPS.includes(name)).map(([, g]) => g);
836
+
837
+ export {
838
+ configureTabCapture,
839
+ waitForLoad,
840
+ builtinGroups,
841
+ OPT_IN_GROUPS,
842
+ allBuiltinGroups
843
+ };