@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,1523 @@
1
+ import {
2
+ CONTENT_CANCEL,
3
+ CONTENT_EVENT,
4
+ CONTENT_MESSAGE
5
+ } from "../chunk-5X4QMMKA.js";
6
+
7
+ // src/content/index.ts
8
+ import { ExtensionUseError as ExtensionUseError6 } from "@extension-use/protocol";
9
+
10
+ // src/content/dom.ts
11
+ import { ExtensionUseError as ExtensionUseError2, matchPattern } from "@extension-use/protocol";
12
+
13
+ // src/content/aria.ts
14
+ var INPUT_ROLES = {
15
+ button: "button",
16
+ submit: "button",
17
+ reset: "button",
18
+ image: "button",
19
+ checkbox: "checkbox",
20
+ radio: "radio",
21
+ range: "slider",
22
+ number: "spinbutton",
23
+ search: "searchbox",
24
+ email: "textbox",
25
+ tel: "textbox",
26
+ text: "textbox",
27
+ url: "textbox",
28
+ password: "textbox",
29
+ "": "textbox"
30
+ };
31
+ var TAG_ROLES = {
32
+ button: "button",
33
+ select: "combobox",
34
+ textarea: "textbox",
35
+ h1: "heading",
36
+ h2: "heading",
37
+ h3: "heading",
38
+ h4: "heading",
39
+ h5: "heading",
40
+ h6: "heading",
41
+ img: "img",
42
+ nav: "navigation",
43
+ main: "main",
44
+ header: "banner",
45
+ footer: "contentinfo",
46
+ aside: "complementary",
47
+ form: "form",
48
+ ul: "list",
49
+ ol: "list",
50
+ li: "listitem",
51
+ table: "table",
52
+ tr: "row",
53
+ td: "cell",
54
+ th: "columnheader",
55
+ dialog: "dialog",
56
+ option: "option",
57
+ progress: "progressbar",
58
+ summary: "button",
59
+ details: "group",
60
+ fieldset: "group",
61
+ article: "article",
62
+ p: "paragraph",
63
+ label: "label",
64
+ iframe: "iframe",
65
+ video: "video",
66
+ audio: "audio"
67
+ };
68
+ var INTERACTIVE_ROLES = /* @__PURE__ */ new Set([
69
+ "button",
70
+ "link",
71
+ "checkbox",
72
+ "radio",
73
+ "textbox",
74
+ "searchbox",
75
+ "combobox",
76
+ "listbox",
77
+ "option",
78
+ "slider",
79
+ "spinbutton",
80
+ "switch",
81
+ "tab",
82
+ "menuitem",
83
+ "menuitemcheckbox",
84
+ "menuitemradio",
85
+ "treeitem"
86
+ ]);
87
+ function roleOf(el) {
88
+ const explicit = el.getAttribute("role")?.trim().split(/\s+/)[0];
89
+ if (explicit) return explicit;
90
+ const tag = el.tagName.toLowerCase();
91
+ if (tag === "a" || tag === "area") return el.hasAttribute("href") ? "link" : "generic";
92
+ if (tag === "input") {
93
+ const type = (el.getAttribute("type") ?? "").toLowerCase();
94
+ if (type === "hidden") return "none";
95
+ return INPUT_ROLES[type] ?? "textbox";
96
+ }
97
+ if (tag === "select" && (el.multiple || el.size > 1)) return "listbox";
98
+ if (tag === "section" && (el.hasAttribute("aria-label") || el.hasAttribute("aria-labelledby"))) return "region";
99
+ if (tag === "img" && el.getAttribute("alt") === "") return "presentation";
100
+ if (el.isContentEditable && !el.parentElement?.isContentEditable) return "textbox";
101
+ return TAG_ROLES[tag] ?? "generic";
102
+ }
103
+ function collapse(s) {
104
+ return (s ?? "").replace(/\s+/g, " ").trim();
105
+ }
106
+ function textOf(el, depth = 0) {
107
+ if (depth > 20) return "";
108
+ let out = "";
109
+ for (const node of el.childNodes) {
110
+ if (node.nodeType === Node.TEXT_NODE) out += node.textContent ?? "";
111
+ else if (node.nodeType === Node.ELEMENT_NODE) {
112
+ const child = node;
113
+ if (child.getAttribute("aria-hidden") === "true" || ["script", "style", "noscript", "template"].includes(child.tagName.toLowerCase())) continue;
114
+ const tag = child.tagName.toLowerCase();
115
+ out += tag === "img" ? child.getAttribute("alt") ?? "" : textOf(child, depth + 1);
116
+ out += " ";
117
+ }
118
+ }
119
+ return out;
120
+ }
121
+ function nameOf(el) {
122
+ const labelledBy = el.getAttribute("aria-labelledby");
123
+ if (labelledBy) {
124
+ const doc = el.ownerDocument;
125
+ const text = labelledBy.split(/\s+/).map((id) => doc.getElementById(id)).filter(Boolean).map((n) => textOf(n)).join(" ");
126
+ if (collapse(text)) return collapse(text);
127
+ }
128
+ const aria = collapse(el.getAttribute("aria-label"));
129
+ if (aria) return aria;
130
+ const tag = el.tagName.toLowerCase();
131
+ if (tag === "input" || tag === "textarea" || tag === "select") {
132
+ const input = el;
133
+ const type = (input.type ?? "").toLowerCase();
134
+ if (type === "button" || type === "submit" || type === "reset") return collapse(input.value) || (type === "submit" ? "Submit" : type === "reset" ? "Reset" : "");
135
+ if (type === "image") return collapse(input.alt);
136
+ const labels = input.labels ? [...input.labels].map((l) => textOf(l)).join(" ") : "";
137
+ if (collapse(labels)) return collapse(labels);
138
+ return collapse(input.getAttribute("placeholder")) || collapse(el.getAttribute("title"));
139
+ }
140
+ if (tag === "img" || tag === "area") return collapse(el.getAttribute("alt")) || collapse(el.getAttribute("title"));
141
+ if (tag === "fieldset") {
142
+ const legend = el.querySelector(":scope > legend");
143
+ if (legend) return collapse(textOf(legend));
144
+ }
145
+ if (tag === "table") {
146
+ const caption = el.querySelector(":scope > caption");
147
+ if (caption) return collapse(textOf(caption));
148
+ }
149
+ const role = roleOf(el);
150
+ const nameFromContent = INTERACTIVE_ROLES.has(role) || ["heading", "cell", "columnheader", "listitem", "row", "tooltip", "option", "label"].includes(role);
151
+ if (nameFromContent) {
152
+ const text = collapse(textOf(el));
153
+ if (text) return text.slice(0, 300);
154
+ }
155
+ return collapse(el.getAttribute("title"));
156
+ }
157
+ function isVisible(el) {
158
+ if (!el.isConnected) return false;
159
+ const anyEl = el;
160
+ if (typeof anyEl.checkVisibility === "function") {
161
+ if (!anyEl.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) return false;
162
+ } else {
163
+ const style = getComputedStyle(el);
164
+ if (style.visibility === "hidden" || style.display === "none" || style.opacity === "0") return false;
165
+ }
166
+ const rect = el.getBoundingClientRect();
167
+ return rect.width > 0 && rect.height > 0;
168
+ }
169
+ function isDisabled(el) {
170
+ if (el.disabled) return true;
171
+ if (el.getAttribute("aria-disabled") === "true") return true;
172
+ return Boolean(el.closest("fieldset[disabled]") && !el.closest("legend"));
173
+ }
174
+ function isSensitive(el) {
175
+ if (el.tagName === "INPUT") {
176
+ const input = el;
177
+ if (input.type === "password") return true;
178
+ const ac = (input.autocomplete || input.getAttribute("autocomplete") || "").toLowerCase();
179
+ if (/\bcc-|current-password|new-password|one-time-code/.test(ac)) return true;
180
+ }
181
+ return false;
182
+ }
183
+
184
+ // src/content/locator.ts
185
+ import { ExtensionUseError } from "@extension-use/protocol";
186
+ var refByEl = /* @__PURE__ */ new WeakMap();
187
+ var elByRef = /* @__PURE__ */ new Map();
188
+ var nextRef = 1;
189
+ function refFor(el) {
190
+ let ref = refByEl.get(el);
191
+ if (!ref) {
192
+ ref = `e${nextRef++}`;
193
+ refByEl.set(el, ref);
194
+ elByRef.set(ref, new WeakRef(el));
195
+ }
196
+ return ref;
197
+ }
198
+ function elementForRef(ref) {
199
+ const el = elByRef.get(ref)?.deref();
200
+ if (el && !el.isConnected) return void 0;
201
+ return el;
202
+ }
203
+ function textMatches(actual, wanted, exact) {
204
+ const a = actual.replace(/\s+/g, " ").trim();
205
+ const w = wanted.replace(/\s+/g, " ").trim();
206
+ return exact ? a === w : a.toLowerCase().includes(w.toLowerCase());
207
+ }
208
+ function* walkAll(root) {
209
+ const stack = [root];
210
+ while (stack.length) {
211
+ const node = stack.pop();
212
+ const children = node.children ?? node.children;
213
+ for (let i = children.length - 1; i >= 0; i--) {
214
+ const child = children[i];
215
+ yield child;
216
+ if (child.shadowRoot) stack.push(child.shadowRoot);
217
+ stack.push(child);
218
+ }
219
+ }
220
+ }
221
+ function deepQueryAll(root, selector) {
222
+ const out = [...root.querySelectorAll(selector)];
223
+ for (const el of root.querySelectorAll("*")) if (el.shadowRoot) out.push(...deepQueryAll(el.shadowRoot, selector));
224
+ return out;
225
+ }
226
+ function candidates(locator, root) {
227
+ if (locator.ref) {
228
+ const el = elementForRef(locator.ref);
229
+ return el ? [el] : [];
230
+ }
231
+ let list;
232
+ if (locator.css) {
233
+ try {
234
+ list = deepQueryAll(root, locator.css);
235
+ } catch {
236
+ throw new ExtensionUseError("INVALID_INPUT", `Invalid CSS selector: ${locator.css}`);
237
+ }
238
+ } else if (locator.testId) {
239
+ list = deepQueryAll(root, `[data-testid="${CSS.escape(locator.testId)}"], [data-test-id="${CSS.escape(locator.testId)}"]`);
240
+ } else {
241
+ list = [...walkAll(root)];
242
+ }
243
+ if (locator.testId && locator.css) {
244
+ list = list.filter((el) => el.getAttribute("data-testid") === locator.testId || el.getAttribute("data-test-id") === locator.testId);
245
+ }
246
+ if (locator.role) {
247
+ const role = locator.role.toLowerCase();
248
+ list = list.filter((el) => roleOf(el) === role);
249
+ }
250
+ if (locator.name !== void 0) {
251
+ list = list.filter((el) => textMatches(nameOf(el), locator.name, locator.exact));
252
+ }
253
+ if (locator.text !== void 0) {
254
+ const matching = list.filter((el) => {
255
+ if (["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "HEAD", "HTML", "BODY"].includes(el.tagName)) return false;
256
+ return textMatches(el.innerText ?? el.textContent ?? "", locator.text, locator.exact);
257
+ });
258
+ const set = new Set(matching);
259
+ list = matching.filter((el) => ![...el.querySelectorAll("*")].some((c) => set.has(c)));
260
+ }
261
+ return list;
262
+ }
263
+ function findAll(locator, root = document) {
264
+ return candidates(locator, root);
265
+ }
266
+ async function resolve(locator, opts) {
267
+ const deadline = Date.now() + opts.timeoutMs;
268
+ const wantVisible = opts.visible ?? true;
269
+ for (; ; ) {
270
+ if (opts.signal?.aborted) throw opts.signal.reason ?? new ExtensionUseError("CANCELLED", "Cancelled");
271
+ let found = candidates(locator, opts.root ?? document);
272
+ if (wantVisible) found = found.filter(isVisible);
273
+ const el = found[locator.nth ?? 0];
274
+ if (el) return el;
275
+ if (Date.now() >= deadline) {
276
+ throw new ExtensionUseError("ELEMENT_NOT_FOUND", `No ${wantVisible ? "visible " : ""}element matches ${JSON.stringify(locator)}`);
277
+ }
278
+ await new Promise((r) => setTimeout(r, 50));
279
+ }
280
+ }
281
+ var KEPT_ATTRIBUTES = ["id", "class", "type", "name", "placeholder", "aria-label", "data-testid", "title", "alt", "src", "role"];
282
+ function describe(el, textMaxLength = 200) {
283
+ const rect = el.getBoundingClientRect();
284
+ const attributes = {};
285
+ for (const name of KEPT_ATTRIBUTES) {
286
+ const v = el.getAttribute(name);
287
+ if (v !== null) attributes[name] = v.length > 200 ? `${v.slice(0, 200)}\u2026` : v;
288
+ }
289
+ const info = {
290
+ ref: refFor(el),
291
+ tag: el.tagName.toLowerCase(),
292
+ role: roleOf(el),
293
+ name: nameOf(el),
294
+ attributes,
295
+ box: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
296
+ visible: isVisible(el)
297
+ };
298
+ if (textMaxLength > 0) {
299
+ const text = (el.innerText ?? el.textContent ?? "").replace(/\s+/g, " ").trim();
300
+ if (text) info.text = text.length > textMaxLength ? `${text.slice(0, textMaxLength)}\u2026` : text;
301
+ }
302
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) {
303
+ info.value = isSensitive(el) ? "\u2022\u2022\u2022\u2022" : el.value;
304
+ }
305
+ if (el instanceof HTMLInputElement && (el.type === "checkbox" || el.type === "radio")) info.checked = el.checked;
306
+ else if (el.hasAttribute("aria-checked")) info.checked = el.getAttribute("aria-checked") === "true";
307
+ if (isDisabled(el)) info.disabled = true;
308
+ if (el instanceof HTMLAnchorElement && el.href) info.href = el.href;
309
+ return info;
310
+ }
311
+ function cssPath(el) {
312
+ if (el.id && document.querySelectorAll(`#${CSS.escape(el.id)}`).length === 1) return `#${CSS.escape(el.id)}`;
313
+ const parts = [];
314
+ let node = el;
315
+ while (node && node !== document.documentElement && parts.length < 8) {
316
+ if (node.id && document.querySelectorAll(`#${CSS.escape(node.id)}`).length === 1) {
317
+ parts.unshift(`#${CSS.escape(node.id)}`);
318
+ break;
319
+ }
320
+ const tag = node.tagName.toLowerCase();
321
+ const parentEl = node.parentElement;
322
+ if (!parentEl) {
323
+ parts.unshift(tag);
324
+ break;
325
+ }
326
+ const same = [...parentEl.children].filter((c) => c.tagName === node.tagName);
327
+ parts.unshift(same.length > 1 ? `${tag}:nth-of-type(${same.indexOf(node) + 1})` : tag);
328
+ node = parentEl;
329
+ }
330
+ return parts.join(" > ");
331
+ }
332
+
333
+ // src/content/dom.ts
334
+ var find = (locator, ctx, visible = true) => resolve(locator, { timeoutMs: ctx.timeoutMs, signal: ctx.signal, visible });
335
+ function center(el) {
336
+ const r = el.getBoundingClientRect();
337
+ return { clientX: r.left + r.width / 2, clientY: r.top + r.height / 2 };
338
+ }
339
+ function modifierFlags(mods = []) {
340
+ return { altKey: mods.includes("Alt"), ctrlKey: mods.includes("Control"), metaKey: mods.includes("Meta"), shiftKey: mods.includes("Shift") };
341
+ }
342
+ function pointer(el, type, init) {
343
+ el.dispatchEvent(new PointerEvent(type, { bubbles: true, cancelable: true, composed: true, pointerId: 1, pointerType: "mouse", isPrimary: true, view: window, ...init }));
344
+ }
345
+ function mouse(el, type, init) {
346
+ return el.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, composed: true, view: window, ...init }));
347
+ }
348
+ function hoverSequence(el) {
349
+ const pos = center(el);
350
+ for (const t of ["pointerover", "pointerenter", "pointermove"]) pointer(el, t, { ...pos, bubbles: t !== "pointerenter" });
351
+ for (const t of ["mouseover", "mouseenter", "mousemove"]) mouse(el, t, { ...pos, bubbles: t !== "mouseenter" });
352
+ }
353
+ async function waitEnabled(el, ctx) {
354
+ const deadline = Date.now() + ctx.timeoutMs;
355
+ while (isDisabled(el)) {
356
+ if (Date.now() >= deadline) throw new ExtensionUseError2("TIMEOUT", "The element stayed disabled");
357
+ if (ctx.signal.aborted) throw ctx.signal.reason;
358
+ await new Promise((r) => setTimeout(r, 50));
359
+ }
360
+ }
361
+ function prepare(el) {
362
+ el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
363
+ }
364
+ function clickElement(el, opts = {}) {
365
+ const button = opts.button === "middle" ? 1 : opts.button === "right" ? 2 : 0;
366
+ const buttons = button === 0 ? 1 : button === 1 ? 4 : 2;
367
+ const base = { ...center(el), ...modifierFlags(opts.modifiers), button };
368
+ hoverSequence(el);
369
+ for (let i = 1; i <= (opts.clickCount ?? 1); i++) {
370
+ pointer(el, "pointerdown", { ...base, buttons });
371
+ const allowDefault = mouse(el, "mousedown", { ...base, buttons, detail: i });
372
+ if (allowDefault && el instanceof HTMLElement) {
373
+ const focusTarget2 = el.closest("a[href], button, input, select, textarea, [tabindex], [contenteditable]") ?? el;
374
+ if (document.activeElement !== focusTarget2) focusTarget2.focus({ preventScroll: true });
375
+ }
376
+ pointer(el, "pointerup", { ...base, buttons: 0 });
377
+ mouse(el, "mouseup", { ...base, buttons: 0, detail: i });
378
+ if (button === 2) mouse(el, "contextmenu", { ...base, buttons: 0, detail: i });
379
+ else if (button === 0) mouse(el, "click", { ...base, buttons: 0, detail: i });
380
+ else mouse(el, "auxclick", { ...base, buttons: 0, detail: i });
381
+ }
382
+ if ((opts.clickCount ?? 1) === 2 && button === 0) mouse(el, "dblclick", { ...base, detail: 2 });
383
+ }
384
+ async function longPress(el, opts) {
385
+ const button = opts.button === "middle" ? 1 : opts.button === "right" ? 2 : 0;
386
+ const buttons = button === 0 ? 1 : button === 1 ? 4 : 2;
387
+ const base = { ...center(el), ...modifierFlags(opts.modifiers), button };
388
+ hoverSequence(el);
389
+ pointer(el, "pointerdown", { ...base, buttons });
390
+ if (mouse(el, "mousedown", { ...base, buttons, detail: 1 }) && el instanceof HTMLElement) el.focus({ preventScroll: true });
391
+ await new Promise((r) => setTimeout(r, opts.holdMs));
392
+ pointer(el, "pointerup", { ...base, buttons: 0 });
393
+ mouse(el, "mouseup", { ...base, buttons: 0, detail: 1 });
394
+ if (button === 0) mouse(el, "click", { ...base, buttons: 0, detail: 1 });
395
+ }
396
+ function setNativeValue(el, value) {
397
+ const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
398
+ Object.getOwnPropertyDescriptor(proto, "value").set.call(el, value);
399
+ }
400
+ function isTextField(el) {
401
+ if (el instanceof HTMLTextAreaElement) return true;
402
+ if (!(el instanceof HTMLInputElement)) return false;
403
+ return !["checkbox", "radio", "button", "submit", "reset", "file", "image", "range", "color", "hidden"].includes(el.type);
404
+ }
405
+ function codeFor(key) {
406
+ if (/^[a-z]$/i.test(key)) return `Key${key.toUpperCase()}`;
407
+ if (/^[0-9]$/.test(key)) return `Digit${key}`;
408
+ if (key === " ") return "Space";
409
+ return key;
410
+ }
411
+ function keyboard(el, type, key, mods = []) {
412
+ return el.dispatchEvent(
413
+ new KeyboardEvent(type, { key, code: codeFor(key), bubbles: true, cancelable: true, composed: true, view: window, ...modifierFlags(mods) })
414
+ );
415
+ }
416
+ function insertText(el, text) {
417
+ if (isTextField(el)) {
418
+ let start = el.value.length;
419
+ let end = start;
420
+ try {
421
+ start = el.selectionStart ?? start;
422
+ end = el.selectionEnd ?? end;
423
+ } catch {
424
+ }
425
+ const before = el.dispatchEvent(new InputEvent("beforeinput", { inputType: "insertText", data: text, bubbles: true, cancelable: true, composed: true }));
426
+ if (!before) return;
427
+ setNativeValue(el, el.value.slice(0, start) + text + el.value.slice(end));
428
+ try {
429
+ el.setSelectionRange(start + text.length, start + text.length);
430
+ } catch {
431
+ }
432
+ el.dispatchEvent(new InputEvent("input", { inputType: "insertText", data: text, bubbles: true, composed: true }));
433
+ } else if (el.isContentEditable) {
434
+ document.execCommand("insertText", false, text);
435
+ } else {
436
+ throw new ExtensionUseError2("INVALID_INPUT", "The element does not accept text");
437
+ }
438
+ }
439
+ function guardSensitive(el, ctx) {
440
+ if (ctx.policy.sensitiveFields === "refuse" && isSensitive(el)) {
441
+ throw new ExtensionUseError2("BLOCKED_BY_POLICY", "Typing into password and payment fields is not allowed for controllers");
442
+ }
443
+ }
444
+ function focusTarget() {
445
+ let el = document.activeElement;
446
+ while (el?.shadowRoot?.activeElement) el = el.shadowRoot.activeElement;
447
+ return el ?? document.body;
448
+ }
449
+ var FOCUSABLE = 'a[href], area[href], button, input:not([type="hidden"]), select, textarea, iframe, summary, [tabindex], [contenteditable=""], [contenteditable="true"]';
450
+ function* deepElements(root) {
451
+ for (const el of root.querySelectorAll("*")) {
452
+ yield el;
453
+ if (el.shadowRoot) yield* deepElements(el.shadowRoot);
454
+ }
455
+ }
456
+ function tabbables() {
457
+ const list = [...deepElements(document)].filter(
458
+ (el) => el instanceof HTMLElement && el.matches(FOCUSABLE) && el.tabIndex >= 0 && !isDisabled(el) && isVisible(el)
459
+ );
460
+ const positive = list.filter((e) => e.tabIndex > 0).sort((a, b) => a.tabIndex - b.tabIndex);
461
+ return [...positive, ...list.filter((e) => e.tabIndex === 0)];
462
+ }
463
+ function moveFocus(from, backwards) {
464
+ const order = tabbables();
465
+ if (!order.length) return;
466
+ const i = order.indexOf(from);
467
+ const next = i < 0 ? order[backwards ? order.length - 1 : 0] : order[(i + (backwards ? -1 : 1) + order.length) % order.length];
468
+ next?.focus();
469
+ if (next && isTextField(next)) {
470
+ try {
471
+ next.select();
472
+ } catch {
473
+ }
474
+ }
475
+ }
476
+ function moveCaret(el, key, extend) {
477
+ let start;
478
+ let end;
479
+ try {
480
+ start = el.selectionStart ?? el.value.length;
481
+ end = el.selectionEnd ?? start;
482
+ } catch {
483
+ return;
484
+ }
485
+ const backward = el.selectionDirection === "backward";
486
+ if (!extend && start !== end && (key === "ArrowLeft" || key === "ArrowRight")) {
487
+ const to = key === "ArrowLeft" ? start : end;
488
+ el.setSelectionRange(to, to);
489
+ return;
490
+ }
491
+ const anchor = extend ? backward ? end : start : start;
492
+ let focus = extend ? backward ? start : end : key === "ArrowLeft" || key === "Home" ? start : end;
493
+ const len = el.value.length;
494
+ const lineStart = el.value.lastIndexOf("\n", Math.max(0, focus - 1)) + 1;
495
+ const nextBreak = el.value.indexOf("\n", focus);
496
+ const lineEnd = nextBreak < 0 ? len : nextBreak;
497
+ if (key === "ArrowLeft") focus = Math.max(0, focus - 1);
498
+ else if (key === "ArrowRight") focus = Math.min(len, focus + 1);
499
+ else if (key === "Home") focus = el instanceof HTMLTextAreaElement ? focus > 0 && el.value[focus - 1] === "\n" ? focus : lineStart : 0;
500
+ else if (key === "End") focus = el instanceof HTMLTextAreaElement ? lineEnd : len;
501
+ if (extend) el.setSelectionRange(Math.min(anchor, focus), Math.max(anchor, focus), focus < anchor ? "backward" : "forward");
502
+ else el.setSelectionRange(focus, focus);
503
+ }
504
+ function stepSelect(el, delta) {
505
+ const options = [...el.options];
506
+ let i = el.selectedIndex;
507
+ do
508
+ i += delta;
509
+ while (i >= 0 && i < options.length && options[i].disabled);
510
+ if (i < 0 || i >= options.length || i === el.selectedIndex) return;
511
+ el.selectedIndex = i;
512
+ el.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
513
+ el.dispatchEvent(new Event("change", { bubbles: true }));
514
+ }
515
+ function stepRadio(el, delta) {
516
+ const scope = el.form ?? el.getRootNode();
517
+ const group = [...scope.querySelectorAll(`input[type="radio"][name="${CSS.escape(el.name)}"]`)].filter((r) => !r.disabled);
518
+ const next = group[(group.indexOf(el) + delta + group.length) % group.length];
519
+ if (next && next !== el) {
520
+ next.focus();
521
+ clickElement(next);
522
+ }
523
+ }
524
+ var NAV_KEYS = /* @__PURE__ */ new Set(["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"]);
525
+ async function pressKey(el, key, mods) {
526
+ const allowed = keyboard(el, "keydown", key, mods);
527
+ const printable = key.length === 1;
528
+ const shortcut = mods.some((m) => m === "Control" || m === "Meta");
529
+ if (allowed && (printable || key === "Enter") && !shortcut) keyboard(el, "keypress", key, mods);
530
+ if (allowed) {
531
+ if (printable && shortcut && key.toLowerCase() === "a") {
532
+ if (isTextField(el)) el.select();
533
+ else document.getSelection()?.selectAllChildren(el.isContentEditable ? el : document.body);
534
+ } else if (printable && !shortcut && !mods.includes("Alt")) {
535
+ if (isTextField(el) || el.isContentEditable) insertText(el, key);
536
+ } else if (key === "Enter") {
537
+ if (el instanceof HTMLInputElement && el.form) el.form.requestSubmit();
538
+ else if (el instanceof HTMLAnchorElement || el instanceof HTMLButtonElement) clickElement(el);
539
+ else if (el instanceof HTMLTextAreaElement || el.isContentEditable) insertText(el, "\n");
540
+ } else if ((key === "Backspace" || key === "Delete") && isTextField(el)) {
541
+ const start = el.selectionStart ?? el.value.length;
542
+ const end = el.selectionEnd ?? start;
543
+ const [from, to] = start !== end ? [start, end] : key === "Backspace" ? [Math.max(0, start - 1), end] : [start, Math.min(el.value.length, end + 1)];
544
+ setNativeValue(el, el.value.slice(0, from) + el.value.slice(to));
545
+ try {
546
+ el.setSelectionRange(from, from);
547
+ } catch {
548
+ }
549
+ el.dispatchEvent(new InputEvent("input", { inputType: key === "Backspace" ? "deleteContentBackward" : "deleteContentForward", bubbles: true, composed: true }));
550
+ } else if (key === "Tab") {
551
+ moveFocus(el, mods.includes("Shift"));
552
+ } else if (NAV_KEYS.has(key)) {
553
+ if (isTextField(el) && (key === "ArrowLeft" || key === "ArrowRight" || key === "Home" || key === "End")) moveCaret(el, key, mods.includes("Shift"));
554
+ else if (el instanceof HTMLSelectElement && !el.multiple && (key === "ArrowUp" || key === "ArrowDown")) stepSelect(el, key === "ArrowDown" ? 1 : -1);
555
+ else if (el instanceof HTMLInputElement && el.type === "radio") stepRadio(el, key === "ArrowDown" || key === "ArrowRight" ? 1 : -1);
556
+ else if (!isTextField(el) && !el.isContentEditable) {
557
+ if (key === "Home") window.scrollTo({ top: 0, behavior: "instant" });
558
+ else if (key === "End") window.scrollTo({ top: document.documentElement.scrollHeight, behavior: "instant" });
559
+ else window.scrollBy({ left: key === "ArrowRight" ? 40 : key === "ArrowLeft" ? -40 : 0, top: key === "ArrowDown" ? 40 : key === "ArrowUp" ? -40 : 0, behavior: "instant" });
560
+ }
561
+ } else if ((key === "PageDown" || key === "PageUp") && !isTextField(el)) {
562
+ window.scrollBy({ top: (key === "PageDown" ? 1 : -1) * window.innerHeight * 0.9, behavior: "instant" });
563
+ }
564
+ }
565
+ keyboard(el, "keyup", key, mods);
566
+ if (allowed && key === " " && (el instanceof HTMLButtonElement || el instanceof HTMLInputElement && ["checkbox", "radio", "button", "submit"].includes(el.type))) {
567
+ clickElement(el);
568
+ }
569
+ }
570
+ var SKIP_TAGS = /* @__PURE__ */ new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "HEAD", "META", "LINK", "SVG"]);
571
+ var STRUCTURAL_ROLES = /* @__PURE__ */ new Set(["generic", "none", "presentation", "label", "group"]);
572
+ function inViewport(el) {
573
+ const r = el.getBoundingClientRect();
574
+ return r.bottom > 0 && r.right > 0 && r.top < window.innerHeight && r.left < window.innerWidth;
575
+ }
576
+ function buildSnapshot(root, { maxNodes, interactiveOnly, viewportOnly, textMaxLength }) {
577
+ let count = 0;
578
+ let truncated = false;
579
+ const visit = (el) => {
580
+ if (count >= maxNodes) {
581
+ truncated = true;
582
+ return [];
583
+ }
584
+ if (SKIP_TAGS.has(el.tagName.toUpperCase()) || el.getAttribute("aria-hidden") === "true") return [];
585
+ if (el.id === OVERLAY_HOST_ID) return [];
586
+ const style = getComputedStyle(el);
587
+ if (style.display === "none" || style.visibility === "hidden") return [];
588
+ if (viewportOnly && style.display !== "contents" && el !== document.body && el !== document.documentElement && !inViewport(el)) return [];
589
+ const role = roleOf(el);
590
+ const interactive = INTERACTIVE_ROLES.has(role) || el.isContentEditable;
591
+ const children = [];
592
+ if (!interactive) {
593
+ const kids = el.shadowRoot ? [...el.shadowRoot.childNodes, ...el.childNodes] : [...el.childNodes];
594
+ for (const node2 of kids) {
595
+ if (node2.nodeType === Node.TEXT_NODE) {
596
+ if (interactiveOnly) continue;
597
+ const text = (node2.textContent ?? "").replace(/\s+/g, " ").trim();
598
+ if (text) {
599
+ count++;
600
+ children.push({ role: "text", name: text.length > textMaxLength ? `${text.slice(0, textMaxLength)}\u2026` : text });
601
+ }
602
+ } else if (node2.nodeType === Node.ELEMENT_NODE) {
603
+ children.push(...visit(node2));
604
+ }
605
+ }
606
+ }
607
+ const keep = interactive || !interactiveOnly && !STRUCTURAL_ROLES.has(role) && role !== "paragraph" || !interactiveOnly && role === "paragraph" && children.length > 0;
608
+ if (!keep) return children;
609
+ if (!interactive && !isVisible(el) && children.length === 0) return [];
610
+ count++;
611
+ const node = { role, ref: refFor(el) };
612
+ const name = nameOf(el);
613
+ if (name) node.name = name;
614
+ if (isTextField(el)) node.value = isSensitive(el) ? "\u2022\u2022\u2022\u2022" : el.value;
615
+ if (el instanceof HTMLSelectElement) node.value = [...el.selectedOptions].map((o) => o.label).join(", ");
616
+ if (el instanceof HTMLInputElement && (el.type === "checkbox" || el.type === "radio")) node.checked = el.checked;
617
+ else if (el.hasAttribute("aria-checked")) node.checked = el.getAttribute("aria-checked") === "true";
618
+ if (isDisabled(el)) node.disabled = true;
619
+ if (role === "heading") node.level = Number(el.getAttribute("aria-level") ?? el.tagName.slice(1)) || 2;
620
+ if (el instanceof HTMLAnchorElement && el.href) node.href = el.href;
621
+ const onlyText = children.length === 1 && children[0].role === "text" ? children[0].name : void 0;
622
+ if (onlyText && onlyText === name) children.length = 0;
623
+ if (children.length) node.children = children;
624
+ return [node];
625
+ };
626
+ const rootNode = { role: "document", children: visit(root) };
627
+ return { root: rootNode, nodeCount: count, truncated };
628
+ }
629
+ function snapshotText(node, depth = 0, lines = []) {
630
+ for (const child of node.children ?? []) {
631
+ const pad = " ".repeat(depth);
632
+ if (child.role === "text") {
633
+ lines.push(`${pad}- text: ${child.name}`);
634
+ continue;
635
+ }
636
+ let line = `${pad}- ${child.role}`;
637
+ if (child.name) line += ` ${JSON.stringify(child.name)}`;
638
+ if (child.level) line += ` [level=${child.level}]`;
639
+ if (child.checked !== void 0) line += ` [checked=${child.checked}]`;
640
+ if (child.disabled) line += " [disabled]";
641
+ if (child.ref) line += ` [ref=${child.ref}]`;
642
+ const onlyText = child.children?.length === 1 && child.children[0].role === "text" ? child.children[0].name : void 0;
643
+ if (child.value !== void 0) line += `: ${JSON.stringify(child.value)}`;
644
+ else if (onlyText) line += `: ${onlyText}`;
645
+ else if (child.children?.length) line += ":";
646
+ lines.push(line);
647
+ if (child.children?.length && !onlyText) snapshotText(child, depth + 1, lines);
648
+ }
649
+ return lines;
650
+ }
651
+ var OVERLAY_HOST_ID = "extension-use-overlay";
652
+ function serialize(el, outer, mask) {
653
+ const clone = document.implementation.createHTMLDocument("").importNode(el, true);
654
+ const FIELDS = "input, textarea, select";
655
+ const live = [...el.querySelectorAll(FIELDS)];
656
+ const copies = [...clone.querySelectorAll(FIELDS)];
657
+ if (el.matches(FIELDS)) {
658
+ live.unshift(el);
659
+ copies.unshift(clone);
660
+ }
661
+ live.forEach((src, i) => {
662
+ const dst = copies[i];
663
+ if (!dst) return;
664
+ const hide = mask && isSensitive(src);
665
+ if (src instanceof HTMLInputElement) {
666
+ if (src.type === "checkbox" || src.type === "radio") dst.toggleAttribute("checked", src.checked);
667
+ else if (src.type !== "file") dst.setAttribute("value", hide && src.value ? "\u2022\u2022\u2022\u2022" : src.value);
668
+ } else if (src instanceof HTMLTextAreaElement) {
669
+ dst.textContent = src.value;
670
+ } else if (src instanceof HTMLSelectElement) {
671
+ [...src.options].forEach((o, j) => dst.options[j]?.toggleAttribute("selected", o.selected));
672
+ }
673
+ });
674
+ for (const n of clone.querySelectorAll(`#${OVERLAY_HOST_ID}`)) n.remove();
675
+ return outer ? clone.outerHTML : clone.innerHTML;
676
+ }
677
+ var pageContent = {
678
+ name: "page",
679
+ handlers: {
680
+ "page.info": () => ({
681
+ url: location.href,
682
+ title: document.title,
683
+ viewport: { width: window.innerWidth, height: window.innerHeight, devicePixelRatio: window.devicePixelRatio },
684
+ scroll: { x: window.scrollX, y: window.scrollY },
685
+ document: { width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight }
686
+ }),
687
+ "page.scroll": (input) => {
688
+ const behavior = input.behavior;
689
+ if (input.to === "top") window.scrollTo({ top: 0, behavior });
690
+ else if (input.to === "bottom") window.scrollTo({ top: document.documentElement.scrollHeight, behavior });
691
+ else if (input.by) window.scrollBy({ left: input.x ?? 0, top: input.y ?? 0, behavior });
692
+ else window.scrollTo({ ...input.x !== void 0 ? { left: input.x } : {}, ...input.y !== void 0 ? { top: input.y } : {}, behavior });
693
+ return { scroll: { x: window.scrollX, y: window.scrollY } };
694
+ }
695
+ }
696
+ };
697
+ var domContent = {
698
+ name: "dom",
699
+ handlers: {
700
+ "dom.query": async (input, ctx) => {
701
+ if (input.wait) await find(input.locator, ctx, false);
702
+ let els = findAll(input.locator);
703
+ if (input.locator.nth !== void 0 && !input.all) els = els.slice(input.locator.nth, input.locator.nth + 1);
704
+ if (!input.all) els = els.slice(0, 1);
705
+ return { elements: els.slice(0, input.limit).map((el) => describe(el, input.textMaxLength)) };
706
+ },
707
+ "dom.text": async (input, ctx) => {
708
+ const el = input.locator ? await find(input.locator, ctx, false) : document.body;
709
+ const text = (el.innerText ?? el.textContent ?? "").replace(/\n{3,}/g, "\n\n").trim();
710
+ return { text: text.slice(0, input.maxLength), truncated: text.length > input.maxLength };
711
+ },
712
+ "dom.snapshot": async (input, ctx) => {
713
+ const root = input.locator ? await find(input.locator, ctx, false) : document.body;
714
+ const snap = buildSnapshot(root, input);
715
+ return {
716
+ ...input.format !== "text" ? { root: snap.root } : {},
717
+ ...input.format !== "tree" ? { text: snapshotText(snap.root).join("\n") } : {},
718
+ nodeCount: snap.nodeCount,
719
+ truncated: snap.truncated
720
+ };
721
+ },
722
+ "dom.html": async (input, ctx) => {
723
+ const el = input.locator ? await find(input.locator, ctx, false) : document.documentElement;
724
+ const html = serialize(el, input.outer, ctx.policy.sensitiveFields === "refuse");
725
+ const doctype = !input.locator && input.outer && document.doctype ? `${new XMLSerializer().serializeToString(document.doctype)}
726
+ ` : "";
727
+ const full = doctype + html;
728
+ return { html: full.slice(0, input.maxLength), length: full.length, truncated: full.length > input.maxLength };
729
+ },
730
+ "dom.click": async (input, ctx) => {
731
+ const el = await find(input.locator, ctx);
732
+ await waitEnabled(el, ctx);
733
+ prepare(el);
734
+ if (input.holdMs > 0) await longPress(el, input);
735
+ else clickElement(el, input);
736
+ return { ref: refFor(el) };
737
+ },
738
+ "dom.hover": async (input, ctx) => {
739
+ const el = await find(input.locator, ctx);
740
+ prepare(el);
741
+ hoverSequence(el);
742
+ return { ref: refFor(el) };
743
+ },
744
+ "dom.focus": async (input, ctx) => {
745
+ const el = await find(input.locator, ctx);
746
+ el.focus();
747
+ return { ref: refFor(el) };
748
+ },
749
+ "dom.type": async (input, ctx) => {
750
+ const el = input.locator ? await find(input.locator, ctx) : focusTarget();
751
+ guardSensitive(el, ctx);
752
+ await waitEnabled(el, ctx);
753
+ if (input.locator) {
754
+ prepare(el);
755
+ el.focus();
756
+ }
757
+ if (input.clear && isTextField(el)) {
758
+ setNativeValue(el, "");
759
+ el.dispatchEvent(new InputEvent("input", { inputType: "deleteContentBackward", bubbles: true, composed: true }));
760
+ }
761
+ for (const ch of input.text) {
762
+ if (ctx.signal.aborted) throw ctx.signal.reason;
763
+ await pressKey(el, ch === "\n" ? "Enter" : ch, []);
764
+ if (input.delayMs) await new Promise((r) => setTimeout(r, input.delayMs));
765
+ }
766
+ el.dispatchEvent(new Event("change", { bubbles: true }));
767
+ return { ref: refFor(el) };
768
+ },
769
+ "dom.fill": async (input, ctx) => {
770
+ const el = await find(input.locator, ctx);
771
+ guardSensitive(el, ctx);
772
+ await waitEnabled(el, ctx);
773
+ prepare(el);
774
+ el.focus();
775
+ if (isTextField(el)) {
776
+ setNativeValue(el, input.value);
777
+ el.dispatchEvent(new InputEvent("input", { inputType: "insertReplacementText", data: input.value, bubbles: true, composed: true }));
778
+ el.dispatchEvent(new Event("change", { bubbles: true }));
779
+ } else if (el.isContentEditable) {
780
+ document.getSelection()?.selectAllChildren(el);
781
+ document.execCommand("insertText", false, input.value);
782
+ } else {
783
+ throw new ExtensionUseError2("INVALID_INPUT", "dom.fill needs an input, textarea or contenteditable element");
784
+ }
785
+ return { ref: refFor(el) };
786
+ },
787
+ "dom.select": async (input, ctx) => {
788
+ const el = await find(input.locator, ctx);
789
+ if (!(el instanceof HTMLSelectElement)) throw new ExtensionUseError2("INVALID_INPUT", "dom.select needs a <select> element");
790
+ await waitEnabled(el, ctx);
791
+ const options = [...el.options];
792
+ const picked = input.values.map((v) => {
793
+ const opt = options.find((o) => o.value === v) ?? options.find((o) => o.label.trim() === v.trim());
794
+ if (!opt) throw new ExtensionUseError2("ELEMENT_NOT_FOUND", `No option "${v}"`);
795
+ return opt;
796
+ });
797
+ if (!el.multiple && picked.length > 1) throw new ExtensionUseError2("INVALID_INPUT", "This <select> allows one option");
798
+ for (const o of options) o.selected = picked.includes(o);
799
+ el.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
800
+ el.dispatchEvent(new Event("change", { bubbles: true }));
801
+ return { ref: refFor(el), selected: picked.map((o) => o.value) };
802
+ },
803
+ "dom.check": async (input, ctx) => {
804
+ const el = await find(input.locator, ctx);
805
+ await waitEnabled(el, ctx);
806
+ const state = () => el instanceof HTMLInputElement ? el.checked : el.getAttribute("aria-checked") === "true";
807
+ if (state() !== input.checked) {
808
+ prepare(el);
809
+ clickElement(el);
810
+ }
811
+ if (state() !== input.checked) throw new ExtensionUseError2("INTERNAL", "The element did not change state");
812
+ return { ref: refFor(el), checked: state() };
813
+ },
814
+ "dom.press": async (input, ctx) => {
815
+ const el = input.locator ? await find(input.locator, ctx) : focusTarget();
816
+ if (input.locator) el.focus();
817
+ guardSensitive(el, ctx);
818
+ await pressKey(el, input.key, input.modifiers);
819
+ return {};
820
+ },
821
+ "dom.scrollTo": async (input, ctx) => {
822
+ const el = await find(input.locator, ctx, false);
823
+ el.scrollIntoView({ block: input.block, inline: "nearest", behavior: input.behavior });
824
+ return { ref: refFor(el) };
825
+ }
826
+ }
827
+ };
828
+ var waitContent = {
829
+ name: "wait",
830
+ handlers: {
831
+ "wait.for": async (input, ctx) => {
832
+ const deadline = Date.now() + ctx.timeoutMs;
833
+ for (; ; ) {
834
+ if (ctx.signal.aborted) throw ctx.signal.reason;
835
+ let ok = true;
836
+ let ref;
837
+ if (input.urlMatch && !matchPattern(input.urlMatch, location.href)) ok = false;
838
+ if (ok && input.locator) {
839
+ const els = findAll(input.locator);
840
+ const el = els[input.locator.nth ?? 0];
841
+ switch (input.state) {
842
+ case "attached":
843
+ ok = Boolean(el);
844
+ break;
845
+ case "detached":
846
+ ok = !el;
847
+ break;
848
+ case "visible":
849
+ ok = Boolean(el && isVisible(el));
850
+ break;
851
+ case "hidden":
852
+ ok = !el || !isVisible(el);
853
+ break;
854
+ }
855
+ if (ok && el && el.isConnected) ref = refFor(el);
856
+ }
857
+ if (ok) return ref ? { ref } : {};
858
+ if (Date.now() >= deadline) throw new ExtensionUseError2("TIMEOUT", "Condition not met in time");
859
+ await new Promise((r) => setTimeout(r, 50));
860
+ }
861
+ }
862
+ }
863
+ };
864
+
865
+ // src/content/overlay.ts
866
+ import { ExtensionUseError as ExtensionUseError3, randomId } from "@extension-use/protocol";
867
+ var STYLE = `
868
+ :host { all: initial; }
869
+ .layer { position: fixed; inset: 0; pointer-events: none; z-index: 2147483647; font: 13px/1.4 system-ui, sans-serif; }
870
+ .box { position: fixed; box-sizing: border-box; border: 2px solid var(--c); background: color-mix(in srgb, var(--c) 12%, transparent); border-radius: 3px; transition: all 60ms linear; }
871
+ .label { position: absolute; left: -2px; bottom: 100%; margin-bottom: 2px; background: var(--c); color: #fff; padding: 1px 6px; border-radius: 3px; font-size: 12px; white-space: nowrap; max-width: 320px; overflow: hidden; text-overflow: ellipsis; }
872
+ .box.below .label { bottom: auto; top: 100%; margin: 2px 0 0; }
873
+ .toasts { position: fixed; right: 16px; bottom: 16px; display: flex; flex-direction: column; gap: 8px; align-items: flex-end; }
874
+ .toast { background: #1f2937; color: #f9fafb; padding: 8px 12px; border-radius: 8px; box-shadow: 0 4px 16px rgb(0 0 0 / 25%); max-width: 360px; border-left: 4px solid #60a5fa; }
875
+ .toast.success { border-left-color: #34d399; }
876
+ .toast.error { border-left-color: #f87171; }
877
+ .banner { position: fixed; top: 12px; left: 50%; transform: translateX(-50%); background: #111827; color: #fff; padding: 8px 14px; border-radius: 999px; box-shadow: 0 4px 16px rgb(0 0 0 / 30%); }
878
+ .banner kbd { background: #374151; border-radius: 4px; padding: 0 5px; font: inherit; }
879
+ .controlled { position: fixed; left: 12px; bottom: 12px; display: flex; align-items: center; gap: 6px; background: #111827; color: #f9fafb; padding: 5px 10px; border-radius: 999px; font-size: 12px; box-shadow: 0 2px 10px rgb(0 0 0 / 30%); opacity: 0.92; }
880
+ .controlled::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: #ef4444; }
881
+ `;
882
+ var controlledTimer;
883
+ function showControlIndicator(text, ms = 4e3) {
884
+ const root = overlayLayer();
885
+ let pill = root.querySelector(".controlled");
886
+ if (!pill) {
887
+ pill = document.createElement("div");
888
+ pill.className = "controlled";
889
+ pill.setAttribute("role", "status");
890
+ root.append(pill);
891
+ }
892
+ pill.textContent = text;
893
+ clearTimeout(controlledTimer);
894
+ controlledTimer = setTimeout(() => pill.remove(), ms);
895
+ }
896
+ var layer;
897
+ function overlayLayer() {
898
+ if (layer?.isConnected) return layer;
899
+ const host = document.createElement("div");
900
+ host.id = OVERLAY_HOST_ID;
901
+ host.setAttribute("aria-hidden", "true");
902
+ const shadow = host.attachShadow({ mode: "open" });
903
+ const style = document.createElement("style");
904
+ style.textContent = STYLE;
905
+ layer = document.createElement("div");
906
+ layer.className = "layer";
907
+ shadow.append(style, layer);
908
+ document.documentElement.append(host);
909
+ return layer;
910
+ }
911
+ var highlights = /* @__PURE__ */ new Map();
912
+ var raf = 0;
913
+ function place(div, el) {
914
+ const r = el.getBoundingClientRect();
915
+ const hidden = !el.isConnected || r.width === 0 && r.height === 0;
916
+ div.style.display = hidden ? "none" : "block";
917
+ div.style.left = `${r.left - 2}px`;
918
+ div.style.top = `${r.top - 2}px`;
919
+ div.style.width = `${r.width + 4}px`;
920
+ div.style.height = `${r.height + 4}px`;
921
+ div.classList.toggle("below", r.top < 24);
922
+ }
923
+ function tick() {
924
+ for (const h of highlights.values()) for (const b of h.boxes) place(b.div, b.el);
925
+ raf = highlights.size ? requestAnimationFrame(tick) : 0;
926
+ }
927
+ function makeBox(el, color, label) {
928
+ const div = document.createElement("div");
929
+ div.className = "box";
930
+ div.style.setProperty("--c", color);
931
+ if (label) {
932
+ const l = document.createElement("div");
933
+ l.className = "label";
934
+ l.textContent = label;
935
+ div.append(l);
936
+ }
937
+ overlayLayer().append(div);
938
+ place(div, el);
939
+ return div;
940
+ }
941
+ function clearHighlight(id) {
942
+ for (const [key, h] of highlights) {
943
+ if (id !== void 0 && key !== id) continue;
944
+ clearTimeout(h.timer);
945
+ for (const b of h.boxes) b.div.remove();
946
+ highlights.delete(key);
947
+ }
948
+ }
949
+ var activePicker;
950
+ function pickLocator(el) {
951
+ const role = roleOf(el);
952
+ const name = nameOf(el);
953
+ const testId = el.getAttribute("data-testid") ?? el.getAttribute("data-test-id");
954
+ const text = (el.innerText ?? "").replace(/\s+/g, " ").trim();
955
+ return {
956
+ css: cssPath(el),
957
+ ...role !== "generic" ? { role } : {},
958
+ ...name && role !== "generic" ? { name } : {},
959
+ ...testId ? { testId } : {},
960
+ ...text && text.length <= 80 ? { text } : {}
961
+ };
962
+ }
963
+ var overlayContent = {
964
+ name: "overlay",
965
+ handlers: {
966
+ "overlay.highlight": async (input, ctx) => {
967
+ await resolve(input.locator, { timeoutMs: ctx.timeoutMs, signal: ctx.signal, visible: false });
968
+ let els = findAll(input.locator);
969
+ if (!input.all) els = els.slice(input.locator.nth ?? 0, (input.locator.nth ?? 0) + 1);
970
+ const id = input.id ?? randomId();
971
+ clearHighlight(id);
972
+ const h = { boxes: els.map((el, i) => ({ el, div: makeBox(el, input.color, input.label && els.length > 1 ? `${input.label} ${i + 1}` : input.label) })) };
973
+ if (input.durationMs > 0) h.timer = setTimeout(() => clearHighlight(id), input.durationMs);
974
+ highlights.set(id, h);
975
+ if (!raf) raf = requestAnimationFrame(tick);
976
+ return { id, count: els.length };
977
+ },
978
+ "overlay.clear": (input) => {
979
+ clearHighlight(input.id);
980
+ return {};
981
+ },
982
+ "overlay.toast": (input) => {
983
+ const root = overlayLayer();
984
+ let stack = root.querySelector(".toasts");
985
+ if (!stack) {
986
+ stack = document.createElement("div");
987
+ stack.className = "toasts";
988
+ root.append(stack);
989
+ }
990
+ const toast = document.createElement("div");
991
+ toast.className = `toast ${input.kind}`;
992
+ toast.setAttribute("role", "status");
993
+ toast.textContent = input.message;
994
+ stack.append(toast);
995
+ setTimeout(() => toast.remove(), input.durationMs);
996
+ return {};
997
+ }
998
+ }
999
+ };
1000
+ var pickerContent = {
1001
+ name: "picker",
1002
+ handlers: {
1003
+ "picker.start": (input, ctx) => {
1004
+ activePicker?.abort(new ExtensionUseError3("CANCELLED", "Another picker started"));
1005
+ const controller = new AbortController();
1006
+ activePicker = controller;
1007
+ return new Promise((resolvePick, reject) => {
1008
+ const root = overlayLayer();
1009
+ const banner = document.createElement("div");
1010
+ banner.className = "banner";
1011
+ banner.append(input.prompt ?? "Click an element to select it", " \xB7 ");
1012
+ const kbd = document.createElement("kbd");
1013
+ kbd.textContent = "Esc";
1014
+ banner.append(kbd, " to cancel");
1015
+ root.append(banner);
1016
+ let hovered;
1017
+ const box = makeBox(document.body, "#2563eb");
1018
+ box.style.display = "none";
1019
+ const isOurs = (el) => !el || el.id === OVERLAY_HOST_ID;
1020
+ const onMove = (e) => {
1021
+ const el = document.elementFromPoint(e.clientX, e.clientY);
1022
+ if (isOurs(el) || el === hovered) return;
1023
+ hovered = el;
1024
+ place(box, hovered);
1025
+ const role = roleOf(hovered);
1026
+ const label = box.querySelector(".label") ?? box.appendChild(Object.assign(document.createElement("div"), { className: "label" }));
1027
+ label.textContent = `${hovered.tagName.toLowerCase()}${role !== "generic" ? ` \xB7 ${role}` : ""}`;
1028
+ ctx.emit("picker.hovered", { ref: refFor(hovered), role, name: nameOf(hovered) });
1029
+ };
1030
+ const swallow = (e) => {
1031
+ e.preventDefault();
1032
+ e.stopImmediatePropagation();
1033
+ };
1034
+ const onClick = (e) => {
1035
+ swallow(e);
1036
+ const el = document.elementFromPoint(e.clientX, e.clientY);
1037
+ if (isOurs(el)) return;
1038
+ const locator = pickLocator(el);
1039
+ const result = { ref: refFor(el), locator, element: describe(el) };
1040
+ ctx.emit("picker.selected", { ref: result.ref, locator, url: location.href });
1041
+ cleanup();
1042
+ resolvePick(result);
1043
+ };
1044
+ const onKey = (e) => {
1045
+ if (e.key !== "Escape") return;
1046
+ swallow(e);
1047
+ cleanup();
1048
+ reject(new ExtensionUseError3("CANCELLED", "The person cancelled the picker"));
1049
+ };
1050
+ const onAbort = () => {
1051
+ cleanup();
1052
+ reject(controller.signal.aborted ? controller.signal.reason : ctx.signal.reason);
1053
+ };
1054
+ const opts = { capture: true };
1055
+ const blocked = ["mousedown", "mouseup", "pointerdown", "pointerup", "dblclick", "contextmenu"];
1056
+ function cleanup() {
1057
+ window.removeEventListener("mousemove", onMove, opts);
1058
+ window.removeEventListener("click", onClick, opts);
1059
+ window.removeEventListener("keydown", onKey, opts);
1060
+ for (const t of blocked) window.removeEventListener(t, swallow, opts);
1061
+ ctx.signal.removeEventListener("abort", onAbort);
1062
+ controller.signal.removeEventListener("abort", onAbort);
1063
+ banner.remove();
1064
+ box.remove();
1065
+ if (activePicker === controller) activePicker = void 0;
1066
+ }
1067
+ window.addEventListener("mousemove", onMove, opts);
1068
+ window.addEventListener("click", onClick, opts);
1069
+ window.addEventListener("keydown", onKey, opts);
1070
+ for (const t of blocked) window.addEventListener(t, swallow, opts);
1071
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
1072
+ controller.signal.addEventListener("abort", onAbort, { once: true });
1073
+ });
1074
+ },
1075
+ "picker.cancel": () => {
1076
+ activePicker?.abort(new ExtensionUseError3("CANCELLED", "Picker cancelled by controller"));
1077
+ return {};
1078
+ }
1079
+ }
1080
+ };
1081
+
1082
+ // src/content/input.ts
1083
+ import { ExtensionUseError as ExtensionUseError4 } from "@extension-use/protocol";
1084
+ function elementAt(p) {
1085
+ const hits = document.elementsFromPoint(p.clientX, p.clientY);
1086
+ return hits.find((e) => e.id !== OVERLAY_HOST_ID && !e.closest(`#${OVERLAY_HOST_ID}`)) ?? document.body;
1087
+ }
1088
+ function dragEvent(el, type, dataTransfer, p) {
1089
+ return el.dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, composed: true, view: window, dataTransfer, ...p }));
1090
+ }
1091
+ var lerp = (a, b, t) => ({ clientX: a.clientX + (b.clientX - a.clientX) * t, clientY: a.clientY + (b.clientY - a.clientY) * t });
1092
+ var yieldTask = () => new Promise((r) => {
1093
+ const c = new MessageChannel();
1094
+ c.port1.onmessage = () => r();
1095
+ c.port2.postMessage(0);
1096
+ });
1097
+ var settle = () => Promise.race([new Promise((r) => requestAnimationFrame(() => r())), new Promise((r) => setTimeout(r, 50))]);
1098
+ function isScrollable(el, axis = "any") {
1099
+ if (el === document.scrollingElement) return true;
1100
+ const s = getComputedStyle(el);
1101
+ const canY = /(auto|scroll|overlay)/.test(s.overflowY) && el.scrollHeight > el.clientHeight;
1102
+ const canX = /(auto|scroll|overlay)/.test(s.overflowX) && el.scrollWidth > el.clientWidth;
1103
+ return axis === "y" ? canY : axis === "x" ? canX : canX || canY;
1104
+ }
1105
+ function scrollContainer(el, axis = "any") {
1106
+ let node = el;
1107
+ while (node) {
1108
+ if (isScrollable(node, axis)) return node;
1109
+ node = node.parentElement ?? node.getRootNode().host ?? null;
1110
+ }
1111
+ return document.scrollingElement ?? document.documentElement;
1112
+ }
1113
+ function scrollMetrics(el) {
1114
+ return { scrollTop: el.scrollTop, scrollLeft: el.scrollLeft, scrollHeight: el.scrollHeight, scrollWidth: el.scrollWidth, clientHeight: el.clientHeight, clientWidth: el.clientWidth };
1115
+ }
1116
+ function base64ToBytes(b64) {
1117
+ const bin = atob(b64);
1118
+ const out = new Uint8Array(bin.length);
1119
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
1120
+ return out;
1121
+ }
1122
+ function textRange(el, start, end) {
1123
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
1124
+ const range = document.createRange();
1125
+ let offset = 0;
1126
+ let started = false;
1127
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
1128
+ const len = n.data.length;
1129
+ if (!started && start <= offset + len) {
1130
+ range.setStart(n, start - offset);
1131
+ started = true;
1132
+ }
1133
+ if (started && end <= offset + len) {
1134
+ range.setEnd(n, end - offset);
1135
+ return range;
1136
+ }
1137
+ offset += len;
1138
+ }
1139
+ return void 0;
1140
+ }
1141
+ var pressedButtons = 0;
1142
+ var inputHandlers = {
1143
+ "dom.blur": async (input, ctx) => {
1144
+ const el = input.locator ? await find(input.locator, ctx, false) : focusTarget();
1145
+ el.blur?.();
1146
+ return el === document.body ? {} : { ref: refFor(el) };
1147
+ },
1148
+ "dom.drag": async (input, ctx) => {
1149
+ const src = await find(input.from, ctx);
1150
+ prepare(src);
1151
+ const dst = input.to ? await find(input.to, ctx) : void 0;
1152
+ if (dst) dst.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "instant" });
1153
+ const start = center(src);
1154
+ const end = dst ? center(dst) : { clientX: start.clientX + input.offset.x, clientY: start.clientY + input.offset.y };
1155
+ hoverSequence(src);
1156
+ pointer(src, "pointerdown", { ...start, button: 0, buttons: 1 });
1157
+ mouse(src, "mousedown", { ...start, button: 0, buttons: 1, detail: 1 });
1158
+ const draggable = src.closest('[draggable="true"]');
1159
+ let html5 = false;
1160
+ if (draggable) {
1161
+ const dataTransfer = new DataTransfer();
1162
+ if (dragEvent(draggable, "dragstart", dataTransfer, start)) {
1163
+ html5 = true;
1164
+ let over;
1165
+ let dropAllowed = false;
1166
+ for (let i = 1; i <= input.steps; i++) {
1167
+ if (ctx.signal.aborted) throw ctx.signal.reason;
1168
+ const p = lerp(start, end, i / input.steps);
1169
+ const target2 = i === input.steps && dst ? dst : elementAt(p);
1170
+ dragEvent(draggable, "drag", dataTransfer, p);
1171
+ if (target2 !== over) {
1172
+ if (over) dragEvent(over, "dragleave", dataTransfer, p);
1173
+ dragEvent(target2, "dragenter", dataTransfer, p);
1174
+ over = target2;
1175
+ }
1176
+ dropAllowed = !dragEvent(target2, "dragover", dataTransfer, p);
1177
+ await yieldTask();
1178
+ }
1179
+ if (over && dropAllowed) dragEvent(over, "drop", dataTransfer, end);
1180
+ else if (over) dragEvent(over, "dragleave", dataTransfer, end);
1181
+ dragEvent(draggable, "dragend", dataTransfer, end);
1182
+ }
1183
+ }
1184
+ if (!html5) {
1185
+ for (let i = 1; i <= input.steps; i++) {
1186
+ if (ctx.signal.aborted) throw ctx.signal.reason;
1187
+ const p = lerp(start, end, i / input.steps);
1188
+ const target2 = elementAt(p);
1189
+ pointer(target2, "pointermove", { ...p, buttons: 1 });
1190
+ mouse(target2, "mousemove", { ...p, buttons: 1 });
1191
+ await yieldTask();
1192
+ }
1193
+ }
1194
+ const last = dst ?? elementAt(end);
1195
+ pointer(last, "pointerup", { ...end, button: 0, buttons: 0 });
1196
+ mouse(last, "mouseup", { ...end, button: 0, buttons: 0, detail: 1 });
1197
+ return { from: refFor(src), ...dst ? { to: refFor(dst) } : {}, html5 };
1198
+ },
1199
+ "dom.upload": async (input, ctx) => {
1200
+ const el = await find(input.locator, ctx, false);
1201
+ const total = input.files.reduce((n, f) => n + (f.text?.length ?? Math.ceil((f.base64?.length ?? 0) * 3 / 4)), 0);
1202
+ if (total > 25 * 1024 * 1024) throw new ExtensionUseError4("INVALID_INPUT", "Files are limited to 25 MB in total");
1203
+ const files = input.files.map((f) => new File([f.text !== void 0 ? f.text : base64ToBytes(f.base64)], f.name, { type: f.mimeType, lastModified: Date.now() }));
1204
+ const dataTransfer = new DataTransfer();
1205
+ for (const f of files) dataTransfer.items.add(f);
1206
+ const fileInput = el instanceof HTMLInputElement && el.type === "file" ? el : el instanceof HTMLLabelElement && el.control instanceof HTMLInputElement && el.control.type === "file" ? el.control : el.querySelector('input[type="file"]');
1207
+ if (fileInput) {
1208
+ if (fileInput.disabled) throw new ExtensionUseError4("INVALID_INPUT", "The file input is disabled");
1209
+ if (!fileInput.multiple && files.length > 1) throw new ExtensionUseError4("INVALID_INPUT", "This file input takes one file");
1210
+ fileInput.files = dataTransfer.files;
1211
+ fileInput.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
1212
+ fileInput.dispatchEvent(new Event("change", { bubbles: true }));
1213
+ return { ref: refFor(fileInput), files: files.length, via: "input" };
1214
+ }
1215
+ prepare(el);
1216
+ const p = center(el);
1217
+ dragEvent(el, "dragenter", dataTransfer, p);
1218
+ dragEvent(el, "dragover", dataTransfer, p);
1219
+ dragEvent(el, "drop", dataTransfer, p);
1220
+ return { ref: refFor(el), files: files.length, via: "drop" };
1221
+ },
1222
+ "dom.scroll": async (input, ctx) => {
1223
+ const el = await find(input.locator, ctx, false);
1224
+ const box = scrollContainer(el, input.y !== void 0 || input.to === "top" || input.to === "bottom" ? "y" : input.x !== void 0 ? "x" : "any");
1225
+ const behavior = input.behavior;
1226
+ if (input.to === "top") box.scrollTo({ top: 0, behavior });
1227
+ else if (input.to === "bottom") box.scrollTo({ top: box.scrollHeight, behavior });
1228
+ else if (input.to === "left") box.scrollTo({ left: 0, behavior });
1229
+ else if (input.to === "right") box.scrollTo({ left: box.scrollWidth, behavior });
1230
+ else if (input.by) box.scrollBy({ left: input.x ?? 0, top: input.y ?? 0, behavior });
1231
+ else box.scrollTo({ ...input.x !== void 0 ? { left: input.x } : {}, ...input.y !== void 0 ? { top: input.y } : {}, behavior });
1232
+ await settle();
1233
+ return { ref: refFor(box), ...scrollMetrics(box) };
1234
+ },
1235
+ "dom.wheel": async (input, ctx) => {
1236
+ const el = input.locator ? await find(input.locator, ctx) : elementAt({ clientX: window.innerWidth / 2, clientY: window.innerHeight / 2 });
1237
+ const p = center(el);
1238
+ const dx = input.deltaX / input.steps;
1239
+ const dy = input.deltaY / input.steps;
1240
+ hoverSequence(el);
1241
+ let box;
1242
+ const before = /* @__PURE__ */ new Map();
1243
+ for (let i = 0; i < input.steps; i++) {
1244
+ if (ctx.signal.aborted) throw ctx.signal.reason;
1245
+ const notCancelled = el.dispatchEvent(new WheelEvent("wheel", { deltaX: dx, deltaY: dy, deltaMode: WheelEvent.DOM_DELTA_PIXEL, bubbles: true, cancelable: true, composed: true, view: window, ...p }));
1246
+ if (notCancelled) {
1247
+ box = scrollContainer(el, dy !== 0 ? "y" : "x");
1248
+ if (!before.has(box)) before.set(box, [box.scrollTop, box.scrollLeft]);
1249
+ box.scrollBy({ left: dx, top: dy, behavior: "instant" });
1250
+ }
1251
+ await settle();
1252
+ }
1253
+ const scrolled = [...before.entries()].some(([b, [t, l]]) => b.scrollTop !== t || b.scrollLeft !== l);
1254
+ const metrics = box ?? document.scrollingElement ?? document.documentElement;
1255
+ return { ...el !== document.body ? { ref: refFor(el) } : {}, scrolled, scrollTop: metrics.scrollTop, scrollLeft: metrics.scrollLeft };
1256
+ },
1257
+ "dom.selectText": async (input, ctx) => {
1258
+ const el = await find(input.locator, ctx);
1259
+ if (isTextField(el)) {
1260
+ const value = el.value;
1261
+ let start2 = input.start ?? 0;
1262
+ let end2 = input.end ?? value.length;
1263
+ if (input.text !== void 0) {
1264
+ start2 = value.indexOf(input.text);
1265
+ if (start2 < 0) throw new ExtensionUseError4("ELEMENT_NOT_FOUND", `"${input.text}" is not in the field`);
1266
+ end2 = start2 + input.text.length;
1267
+ }
1268
+ el.focus();
1269
+ try {
1270
+ el.setSelectionRange(Math.min(start2, value.length), Math.min(end2, value.length));
1271
+ } catch {
1272
+ el.select();
1273
+ }
1274
+ return { ref: refFor(el), selected: value.slice(el.selectionStart ?? 0, el.selectionEnd ?? value.length) };
1275
+ }
1276
+ const text = el.textContent ?? "";
1277
+ let start = input.start ?? 0;
1278
+ let end = input.end ?? text.length;
1279
+ if (input.text !== void 0) {
1280
+ start = text.indexOf(input.text);
1281
+ if (start < 0) throw new ExtensionUseError4("ELEMENT_NOT_FOUND", `"${input.text}" is not in the element`);
1282
+ end = start + input.text.length;
1283
+ }
1284
+ const range = textRange(el, Math.min(start, text.length), Math.min(end, text.length));
1285
+ const selection = document.getSelection();
1286
+ selection.removeAllRanges();
1287
+ if (range) selection.addRange(range);
1288
+ else selection.selectAllChildren(el);
1289
+ return { ref: refFor(el), selected: selection.toString() };
1290
+ },
1291
+ "dom.paste": async (input, ctx) => {
1292
+ const el = input.locator ? await find(input.locator, ctx) : focusTarget();
1293
+ guardSensitive(el, ctx);
1294
+ if (input.locator) el.focus();
1295
+ const clipboardData = new DataTransfer();
1296
+ clipboardData.setData("text/plain", input.text);
1297
+ const handledByPage = !el.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true, composed: true }));
1298
+ if (!handledByPage && (isTextField(el) || el.isContentEditable)) insertText(el, input.text);
1299
+ return { ref: refFor(el), handledByPage };
1300
+ },
1301
+ "dom.pointer": async (input, ctx) => {
1302
+ const el = input.locator ? await find(input.locator, ctx) : void 0;
1303
+ const p = el ? center(el) : { clientX: input.x, clientY: input.y };
1304
+ const target2 = el ?? elementAt(p);
1305
+ const button = input.button === "middle" ? 1 : input.button === "right" ? 2 : 0;
1306
+ const mask = button === 0 ? 1 : button === 1 ? 4 : 2;
1307
+ if (input.type === "down") {
1308
+ pressedButtons |= mask;
1309
+ pointer(target2, "pointerdown", { ...p, button, buttons: pressedButtons });
1310
+ if (mouse(target2, "mousedown", { ...p, button, buttons: pressedButtons, detail: 1 }) && target2 instanceof HTMLElement) target2.focus({ preventScroll: true });
1311
+ } else if (input.type === "move") {
1312
+ pointer(target2, "pointermove", { ...p, buttons: pressedButtons });
1313
+ mouse(target2, "mousemove", { ...p, buttons: pressedButtons });
1314
+ } else {
1315
+ pressedButtons &= ~mask;
1316
+ pointer(target2, "pointerup", { ...p, button, buttons: pressedButtons });
1317
+ mouse(target2, "mouseup", { ...p, button, buttons: pressedButtons, detail: 1 });
1318
+ }
1319
+ return { ...el ? { ref: refFor(el) } : {}, x: p.clientX, y: p.clientY };
1320
+ }
1321
+ };
1322
+
1323
+ // src/content/edit.ts
1324
+ import { ExtensionUseError as ExtensionUseError5 } from "@extension-use/protocol";
1325
+ var BLOCKED_TAGS = /* @__PURE__ */ new Set(["script", "iframe", "frame", "frameset", "object", "embed", "applet", "base", "meta", "portal", "fencedframe", "noscript"]);
1326
+ var PROTECTED = /* @__PURE__ */ new Set(["HTML", "HEAD", "BODY"]);
1327
+ var HTML_NS = "http://www.w3.org/1999/xhtml";
1328
+ function isCodeUrl(value) {
1329
+ return /^(javascript|vbscript):/i.test(value.replace(/[\u0000- ]/g, ""));
1330
+ }
1331
+ function isBadAttribute(name, value) {
1332
+ const n = name.toLowerCase();
1333
+ return n.startsWith("on") || n === "srcdoc" || isCodeUrl(value);
1334
+ }
1335
+ function inertDocument() {
1336
+ return document.implementation.createHTMLDocument("");
1337
+ }
1338
+ function sanitize(html) {
1339
+ const tpl = inertDocument().createElement("template");
1340
+ try {
1341
+ tpl.innerHTML = html;
1342
+ } catch (err) {
1343
+ throw new ExtensionUseError5("BLOCKED_BY_POLICY", `The page doesn't allow inserting HTML: ${String(err?.message ?? err)}`);
1344
+ }
1345
+ let removed = 0;
1346
+ const rebuild = (node) => {
1347
+ if (node.nodeType === Node.TEXT_NODE) return document.createTextNode(node.nodeValue ?? "");
1348
+ if (node.nodeType === Node.COMMENT_NODE) return document.createComment(node.nodeValue ?? "");
1349
+ if (node.nodeType !== Node.ELEMENT_NODE) return null;
1350
+ const src = node;
1351
+ const tag = src.localName.toLowerCase();
1352
+ const hrefAnimation = (tag === "animate" || tag === "set") && /href/i.test(src.getAttribute("attributeName") ?? "");
1353
+ if (BLOCKED_TAGS.has(tag) || hrefAnimation) {
1354
+ removed++;
1355
+ return null;
1356
+ }
1357
+ const is = src.namespaceURI === HTML_NS ? src.getAttribute("is") : null;
1358
+ const el = src.namespaceURI === HTML_NS ? document.createElement(src.localName, is ? { is } : void 0) : document.createElementNS(src.namespaceURI, src.localName);
1359
+ for (const attr of src.attributes) {
1360
+ if (isBadAttribute(attr.name, attr.value)) removed++;
1361
+ else el.setAttributeNS(attr.namespaceURI, attr.name, attr.value);
1362
+ }
1363
+ const [from, to] = src instanceof HTMLTemplateElement ? [src.content, el.content] : [src, el];
1364
+ for (const child of from.childNodes) {
1365
+ const copy = rebuild(child);
1366
+ if (copy) to.appendChild(copy);
1367
+ }
1368
+ return el;
1369
+ };
1370
+ const fragment = document.createDocumentFragment();
1371
+ for (const child of tpl.content.childNodes) {
1372
+ const copy = rebuild(child);
1373
+ if (copy) fragment.appendChild(copy);
1374
+ }
1375
+ return { fragment, removed };
1376
+ }
1377
+ function assertEditable(el) {
1378
+ if (el.closest(`#${OVERLAY_HOST_ID}`)) throw new ExtensionUseError5("INVALID_INPUT", "That element belongs to Extension-use's own overlay");
1379
+ if (el.tagName.toUpperCase() === "SCRIPT") throw new ExtensionUseError5("BLOCKED_BY_POLICY", "<script> elements can't be edited");
1380
+ }
1381
+ var target = (input, ctx) => find(input.locator, ctx, false);
1382
+ var editContent = {
1383
+ name: "edit",
1384
+ handlers: {
1385
+ "edit.setHtml": async (input, ctx) => {
1386
+ const el = await target(input, ctx);
1387
+ assertEditable(el);
1388
+ if (input.position === "outer" && PROTECTED.has(el.tagName.toUpperCase())) {
1389
+ throw new ExtensionUseError5("INVALID_INPUT", `Can't replace <${el.tagName.toLowerCase()}>; use position "inner"`);
1390
+ }
1391
+ if ((input.position === "beforebegin" || input.position === "afterbegin") && el === document.documentElement) {
1392
+ throw new ExtensionUseError5("INVALID_INPUT", "Can't insert outside <html>");
1393
+ }
1394
+ const { fragment, removed } = sanitize(input.html);
1395
+ const inserted = [...fragment.children];
1396
+ switch (input.position) {
1397
+ case "inner":
1398
+ el.replaceChildren(fragment);
1399
+ break;
1400
+ case "outer":
1401
+ el.replaceWith(fragment);
1402
+ break;
1403
+ case "beforebegin":
1404
+ el.before(fragment);
1405
+ break;
1406
+ case "afterbegin":
1407
+ el.prepend(fragment);
1408
+ break;
1409
+ case "beforeend":
1410
+ el.append(fragment);
1411
+ break;
1412
+ case "afterend":
1413
+ el.after(fragment);
1414
+ break;
1415
+ }
1416
+ return { refs: inserted.filter((n) => n.isConnected).map(refFor), removed };
1417
+ },
1418
+ "edit.setText": async (input, ctx) => {
1419
+ const el = await target(input, ctx);
1420
+ assertEditable(el);
1421
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) {
1422
+ throw new ExtensionUseError5("INVALID_INPUT", "Use dom.fill to change a form field's value");
1423
+ }
1424
+ el.textContent = input.text;
1425
+ return { ref: refFor(el) };
1426
+ },
1427
+ "edit.setAttributes": async (input, ctx) => {
1428
+ const el = await target(input, ctx);
1429
+ assertEditable(el);
1430
+ const entries = Object.entries(input.attributes);
1431
+ for (const [name, value] of entries) {
1432
+ if (!/^[^\s"'<>/=\u0000-\u001f]+$/.test(name)) throw new ExtensionUseError5("INVALID_INPUT", `"${name}" is not a valid attribute name`);
1433
+ if (value !== null && isBadAttribute(name, value)) {
1434
+ throw new ExtensionUseError5("BLOCKED_BY_POLICY", `Setting "${name}" could run code, so it's not allowed`);
1435
+ }
1436
+ if (name.toLowerCase() === "value") guardSensitive(el, ctx);
1437
+ }
1438
+ for (const [name, value] of entries) {
1439
+ if (value === null) el.removeAttribute(name);
1440
+ else el.setAttribute(name, value);
1441
+ }
1442
+ return { ref: refFor(el), attributes: Object.fromEntries([...el.attributes].map((a) => [a.name, a.value])) };
1443
+ },
1444
+ "edit.remove": async (input, ctx) => {
1445
+ const first = await target(input, ctx);
1446
+ const els = input.all ? findAll(input.locator) : [first];
1447
+ for (const el of els) {
1448
+ assertEditable(el);
1449
+ if (PROTECTED.has(el.tagName.toUpperCase())) throw new ExtensionUseError5("INVALID_INPUT", `Can't remove <${el.tagName.toLowerCase()}>`);
1450
+ }
1451
+ for (const el of els) el.remove();
1452
+ return { removed: els.length };
1453
+ }
1454
+ }
1455
+ };
1456
+
1457
+ // src/content/index.ts
1458
+ import { ExtensionUseError as ExtensionUseError7 } from "@extension-use/protocol";
1459
+ var contentGroups = {
1460
+ page: pageContent,
1461
+ dom: { name: "dom", handlers: { ...domContent.handlers, ...inputHandlers } },
1462
+ edit: editContent,
1463
+ wait: waitContent,
1464
+ overlay: overlayContent,
1465
+ picker: pickerContent
1466
+ };
1467
+ var allContentGroups = Object.values(contentGroups);
1468
+ var FLAG = "__extensionUseContentRuntime";
1469
+ function startContentRuntime(options = {}) {
1470
+ const g = globalThis;
1471
+ if (g[FLAG]) return;
1472
+ g[FLAG] = true;
1473
+ const handlers = /* @__PURE__ */ new Map();
1474
+ for (const group of options.groups ?? allContentGroups) for (const [k, v] of Object.entries(group.handlers)) handlers.set(k, v);
1475
+ for (const [k, v] of Object.entries(options.handlers ?? {})) handlers.set(k, v);
1476
+ const pending = /* @__PURE__ */ new Map();
1477
+ const emit = (name, payload) => {
1478
+ chrome.runtime.sendMessage({ [CONTENT_EVENT]: { name, payload } }).catch(() => {
1479
+ });
1480
+ };
1481
+ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
1482
+ if (sender.id !== chrome.runtime.id || !msg) return false;
1483
+ if (typeof msg[CONTENT_CANCEL] === "string") {
1484
+ pending.get(msg[CONTENT_CANCEL])?.abort(new ExtensionUseError6("CANCELLED", "Cancelled"));
1485
+ return false;
1486
+ }
1487
+ const req = msg[CONTENT_MESSAGE];
1488
+ if (!req) return false;
1489
+ const handler = handlers.get(req.action);
1490
+ if (!handler) {
1491
+ sendResponse({ ok: false, error: { code: "UNKNOWN_ACTION", message: `This page's runtime has no "${req.action}"` } });
1492
+ return false;
1493
+ }
1494
+ if (req.controller && ["remote", "agent", "page"].includes(req.controller.transport) && options.indicator !== false) {
1495
+ try {
1496
+ showControlIndicator(`Controlled by ${req.controller.origin.replace(/^relay:/, "remote: ").replace(/^agent:/, "agent: ")}`);
1497
+ } catch {
1498
+ }
1499
+ }
1500
+ const abort = new AbortController();
1501
+ pending.set(req.callId, abort);
1502
+ const ctx = { signal: abort.signal, timeoutMs: req.timeoutMs, policy: req.policy, emit };
1503
+ Promise.resolve().then(() => handler(req.input, ctx)).then(
1504
+ (output) => sendResponse({ ok: true, output: output ?? {} }),
1505
+ (err) => sendResponse({ ok: false, error: ExtensionUseError6.from(err).toPayload() })
1506
+ ).finally(() => pending.delete(req.callId));
1507
+ return true;
1508
+ });
1509
+ }
1510
+ export {
1511
+ ExtensionUseError7 as ExtensionUseError,
1512
+ allContentGroups,
1513
+ contentGroups,
1514
+ cssPath,
1515
+ describe,
1516
+ findAll,
1517
+ isVisible,
1518
+ nameOf,
1519
+ refFor,
1520
+ resolve as resolveLocator,
1521
+ roleOf,
1522
+ startContentRuntime
1523
+ };