omowright 0.2.0 → 0.3.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.
Files changed (174) hide show
  1. package/README.md +24 -22
  2. package/TOOLS.md +6 -6
  3. package/dist/agent-tabs.d.ts +56 -0
  4. package/dist/aria-hidden.d.ts +1 -0
  5. package/dist/aside/cli-binary.d.ts +7 -0
  6. package/dist/aside/cli-contract.d.ts +9 -0
  7. package/dist/aside/errors.d.ts +8 -0
  8. package/dist/aside/line-transport.d.ts +11 -0
  9. package/dist/aside/mcp-transport.d.ts +11 -0
  10. package/dist/aside/onboard.d.ts +76 -0
  11. package/dist/aside/session-types.d.ts +68 -0
  12. package/dist/aside/session.d.ts +20 -0
  13. package/{bin/omowright-cloak.mjs → dist/bin/omowright-cloak.js} +28 -31
  14. package/dist/bridge-schemas.d.ts +326 -0
  15. package/dist/bridge-transport.d.ts +144 -0
  16. package/dist/browser-context.d.ts +4024 -0
  17. package/dist/browser-process.d.ts +10 -0
  18. package/dist/bsk/browser-signals.d.ts +23 -0
  19. package/dist/bsk/browsers.d.ts +46 -0
  20. package/dist/bsk/connect.d.ts +23 -0
  21. package/dist/bsk/daemon-info.d.ts +16 -0
  22. package/dist/bsk/external-extension.d.ts +74 -0
  23. package/dist/bsk/identify-browser.d.ts +48 -0
  24. package/dist/bsk/install-cli.d.ts +37 -0
  25. package/dist/bsk/ipc-client.d.ts +45 -0
  26. package/dist/bsk/onboard.d.ts +96 -0
  27. package/dist/bsk/reply-fields.d.ts +3 -0
  28. package/dist/bsk/screenshot.d.ts +24 -0
  29. package/dist/bsk/session.d.ts +142 -0
  30. package/dist/bsk/snapshot.d.ts +16 -0
  31. package/dist/bsk/targets.d.ts +20 -0
  32. package/dist/captcha-wait.d.ts +17 -0
  33. package/dist/captcha.d.ts +46 -0
  34. package/dist/cdp-errors.d.ts +38 -0
  35. package/dist/cdp-methods.d.ts +10 -0
  36. package/dist/cdp-protocol.d.ts +459 -0
  37. package/dist/chrome-profile.d.ts +77 -0
  38. package/dist/chrome.d.ts +130 -0
  39. package/dist/cloak-profile.d.ts +43 -0
  40. package/dist/connection.d.ts +4024 -0
  41. package/dist/console-events.d.ts +22 -0
  42. package/dist/cookies.d.ts +42 -0
  43. package/dist/core.d.ts +10810 -0
  44. package/dist/cua.d.ts +56 -0
  45. package/dist/dialog-policy.d.ts +43 -0
  46. package/dist/ego/bindings.d.ts +68 -0
  47. package/dist/ego/cdp-client.d.ts +28 -0
  48. package/dist/ego/client.d.ts +8 -0
  49. package/dist/ego/errors.d.ts +7 -0
  50. package/dist/emulate.d.ts +62 -0
  51. package/dist/engines.d.ts +59 -0
  52. package/dist/events.d.ts +93 -0
  53. package/dist/frames-snapshot.d.ts +58 -0
  54. package/dist/har.d.ts +88 -0
  55. package/dist/human-handoff.d.ts +30 -0
  56. package/{src/index.js → dist/index.d.ts} +11 -55
  57. package/dist/index.js +39262 -0
  58. package/dist/injected.d.ts +1 -0
  59. package/dist/instance-lock.d.ts +5 -0
  60. package/dist/instances.d.ts +45 -0
  61. package/dist/internal-capability.d.ts +1 -0
  62. package/dist/launch-endpoint.d.ts +34 -0
  63. package/dist/layers.d.ts +31 -0
  64. package/dist/llm.d.ts +1349 -0
  65. package/dist/lock-backend-win32-xbcm60vz.js +57 -0
  66. package/dist/lock-backend-win32.d.ts +3 -0
  67. package/dist/lock-backend.d.ts +6 -0
  68. package/dist/native-host-win32.d.ts +38 -0
  69. package/dist/network-events.d.ts +66 -0
  70. package/dist/network-snoop.d.ts +56 -0
  71. package/dist/nul-frames.d.ts +4 -0
  72. package/dist/open-shadow-query.d.ts +1 -0
  73. package/dist/owner-only.d.ts +15 -0
  74. package/dist/page-bundle.js +1587 -0
  75. package/dist/page-events.d.ts +25 -0
  76. package/dist/page-routes.d.ts +30 -0
  77. package/dist/page-setup.d.ts +55 -0
  78. package/dist/pipe.d.ts +71 -0
  79. package/dist/process-start-time.d.ts +2 -0
  80. package/dist/read-property.d.ts +2 -0
  81. package/dist/routes.d.ts +60 -0
  82. package/dist/running-browser.d.ts +39 -0
  83. package/dist/scroll-collect.d.ts +36 -0
  84. package/dist/serial-emitter.d.ts +5 -0
  85. package/dist/shared-connections.d.ts +11 -0
  86. package/dist/snapshot-diff.d.ts +57 -0
  87. package/dist/text-matching.d.ts +21 -0
  88. package/dist/trace.d.ts +59 -0
  89. package/dist/url-match.d.ts +7 -0
  90. package/dist/viewport.d.ts +26 -0
  91. package/dist/ws.d.ts +62 -0
  92. package/package.json +47 -26
  93. package/presets/agent-events/SKILL.md +1 -1
  94. package/presets/captcha/SKILL.md +1 -3
  95. package/presets/chrome/SKILL.md +2 -2
  96. package/presets/cloak-bridge/SKILL.md +11 -11
  97. package/presets/network/SKILL.md +15 -13
  98. package/presets/visual-browse/SKILL.md +14 -10
  99. package/skills/omowright/SKILL.md +77 -47
  100. package/skills/omowright/references/aside.md +50 -0
  101. package/skills/omowright/references/browserskill.md +29 -32
  102. package/skills/omowright/references/ego.md +24 -0
  103. package/skills/omowright/references/eval-kernel.md +44 -23
  104. package/skills/omowright/references/frames-layers-human.md +16 -7
  105. package/skills/omowright/references/quickstart.md +3 -3
  106. package/skills/omowright/references/stealth.md +7 -7
  107. package/src/agent-tabs.js +0 -179
  108. package/src/aria-hidden.js +0 -47
  109. package/src/bridge-schemas.js +0 -44
  110. package/src/bridge-transport.js +0 -83
  111. package/src/browser-context.js +0 -105
  112. package/src/browser-process.js +0 -127
  113. package/src/bsk/browser-signals.js +0 -90
  114. package/src/bsk/browsers.js +0 -114
  115. package/src/bsk/connect.js +0 -75
  116. package/src/bsk/daemon-info.js +0 -100
  117. package/src/bsk/external-extension.js +0 -110
  118. package/src/bsk/identify-browser.js +0 -88
  119. package/src/bsk/install-cli.js +0 -81
  120. package/src/bsk/ipc-client.js +0 -236
  121. package/src/bsk/onboard.js +0 -140
  122. package/src/bsk/screenshot.js +0 -49
  123. package/src/bsk/session.js +0 -131
  124. package/src/bsk/snapshot.js +0 -56
  125. package/src/bsk/targets.js +0 -25
  126. package/src/captcha-wait.js +0 -79
  127. package/src/captcha.js +0 -142
  128. package/src/cdp-errors.js +0 -23
  129. package/src/cdp-methods.js +0 -69
  130. package/src/chrome-profile.js +0 -176
  131. package/src/chrome.js +0 -194
  132. package/src/cloak-profile.js +0 -266
  133. package/src/connection.js +0 -234
  134. package/src/console-events.js +0 -12
  135. package/src/cookies.js +0 -39
  136. package/src/core.js +0 -1702
  137. package/src/cua.js +0 -74
  138. package/src/dialog-policy.js +0 -80
  139. package/src/emulate.js +0 -127
  140. package/src/events.js +0 -111
  141. package/src/frames-snapshot.js +0 -138
  142. package/src/har.js +0 -103
  143. package/src/human-handoff.js +0 -124
  144. package/src/injected.js +0 -3
  145. package/src/instance-lock.js +0 -74
  146. package/src/instances.js +0 -490
  147. package/src/internal-capability.js +0 -1
  148. package/src/launch-endpoint.js +0 -185
  149. package/src/layers.js +0 -138
  150. package/src/llm.js +0 -201
  151. package/src/lock-backend-win32.js +0 -54
  152. package/src/lock-backend.js +0 -81
  153. package/src/native-host-win32.js +0 -201
  154. package/src/network-events.js +0 -223
  155. package/src/network-snoop.js +0 -229
  156. package/src/nul-frames.js +0 -28
  157. package/src/open-shadow-query.js +0 -101
  158. package/src/owner-only.js +0 -196
  159. package/src/page-bundle.js +0 -1478
  160. package/src/page-events.js +0 -45
  161. package/src/page-routes.js +0 -94
  162. package/src/page-setup.js +0 -239
  163. package/src/pipe.js +0 -418
  164. package/src/process-start-time.js +0 -64
  165. package/src/routes.js +0 -256
  166. package/src/running-browser.js +0 -85
  167. package/src/scroll-collect.js +0 -73
  168. package/src/serial-emitter.js +0 -17
  169. package/src/shared-connections.js +0 -285
  170. package/src/snapshot-diff.js +0 -75
  171. package/src/text-matching.js +0 -101
  172. package/src/trace.js +0 -183
  173. package/src/url-match.js +0 -148
  174. package/src/viewport.js +0 -12
package/src/cua.js DELETED
@@ -1,74 +0,0 @@
1
- const MODIFIER_KEYS = new Set(["Alt", "Control", "Meta", "Shift"]);
2
-
3
- function splitModifiers(keys = []) {
4
- const modifiers = keys.filter(key => MODIFIER_KEYS.has(key) || /^(cmd|command|ctrl|option|controlormeta)$/i.test(key));
5
- const rest = keys.filter(key => !modifiers.includes(key));
6
- return { modifiers, rest };
7
- }
8
-
9
- export function createCua(page) {
10
- async function holdModifiers(keys, fn) {
11
- const { modifiers } = splitModifiers(keys);
12
- for (const key of modifiers) await page.keyboard.down(key);
13
- try {
14
- return await fn();
15
- } finally {
16
- for (const key of [...modifiers].reverse()) await page.keyboard.up(key);
17
- }
18
- }
19
-
20
- return {
21
- page,
22
-
23
- async click({ x, y, button = "left", keypress }) {
24
- await holdModifiers(keypress, () => page.mouse.click(x, y, { button }));
25
- },
26
-
27
- async doubleClick({ x, y, keypress }) {
28
- await holdModifiers(keypress, () => page.mouse.click(x, y, { clickCount: 2 }));
29
- },
30
-
31
- async drag({ path, keys }) {
32
- if (!Array.isArray(path) || path.length < 2) {
33
- throw new TypeError("cua.drag requires path with at least two points");
34
- }
35
- await holdModifiers(keys, async () => {
36
- const [first, ...rest] = path;
37
- await page.mouse.move(first.x, first.y);
38
- await page.mouse.down();
39
- try {
40
- for (const point of rest) await page.mouse.move(point.x, point.y);
41
- } finally {
42
- await page.mouse.up();
43
- }
44
- });
45
- },
46
-
47
- async getVisibleScreenshot() {
48
- const buffer = await page.screenshot({ type: "png" });
49
- return buffer.toString("base64");
50
- },
51
-
52
- async keypress({ keys }) {
53
- if (!Array.isArray(keys) || keys.length === 0) {
54
- throw new TypeError("cua.keypress requires a non-empty keys array");
55
- }
56
- await page.keyboard.press(keys.join("+"));
57
- },
58
-
59
- async move({ x, y, keys }) {
60
- await holdModifiers(keys, () => page.mouse.move(x, y));
61
- },
62
-
63
- async scroll({ x, y, scrollX, scrollY, keypress }) {
64
- await holdModifiers(keypress, async () => {
65
- await page.mouse.move(x, y);
66
- await page.mouse.wheel(scrollX, scrollY);
67
- });
68
- },
69
-
70
- async type({ text }) {
71
- await page.keyboard.type(text);
72
- },
73
- };
74
- }
@@ -1,80 +0,0 @@
1
- export function normalizeDialogPolicy(policy) {
2
- return policy ?? { accept: true };
3
- }
4
-
5
- function dialogFromOpening(params = {}) {
6
- return {
7
- type: params.type,
8
- message: params.message,
9
- defaultPrompt: params.defaultPrompt ?? "",
10
- url: params.url,
11
- };
12
- }
13
-
14
- function decisionFromResult(result) {
15
- if (typeof result === "boolean") return { accept: result };
16
- if (result && typeof result === "object") {
17
- const decision = { accept: result.accept !== false };
18
- if (result.promptText !== undefined) decision.promptText = result.promptText;
19
- return decision;
20
- }
21
- return { accept: true };
22
- }
23
-
24
- export async function resolveDialogAction(policy, params = {}) {
25
- try {
26
- const result = typeof policy === "function"
27
- ? await policy(dialogFromOpening(params))
28
- : policy;
29
- return decisionFromResult(result);
30
- } catch {
31
- return { accept: true };
32
- }
33
- }
34
-
35
- let isAnswered;
36
- let answer;
37
-
38
- // The "dialog" event object, shaped like Playwright's Dialog. The client makes one
39
- // per Page.javascriptDialogOpening and hands it to listeners; it is answered at
40
- // most once, by a listener through accept()/dismiss() or else by the policy.
41
- export class Dialog {
42
- #params;
43
- #send;
44
- #answered = false;
45
-
46
- constructor(params, send) {
47
- this.#params = params ?? {};
48
- this.#send = send;
49
- }
50
-
51
- get url() { return this.#params.url; }
52
- type() { return this.#params.type; }
53
- message() { return this.#params.message; }
54
- defaultValue() { return this.#params.defaultPrompt ?? ""; }
55
- accept(promptText) {
56
- return this.#answer(promptText === undefined ? { accept: true } : { accept: true, promptText });
57
- }
58
- dismiss() { return this.#answer({ accept: false }); }
59
-
60
- // Marks the dialog answered before the first await, so a listener that
61
- // answers synchronously always wins over the policy.
62
- async #answer(action) {
63
- if (this.#answered) throw new Error("this dialog is already handled");
64
- this.#answered = true;
65
- await this.#send(action);
66
- }
67
-
68
- static {
69
- isAnswered = (dialog) => dialog.#answered;
70
- answer = (dialog, action) => dialog.#answer(action);
71
- }
72
- }
73
-
74
- // Runs once the dialog's listeners have run: the policy answers only a dialog
75
- // none of them answered.
76
- export async function answerWithPolicy(dialog, policy, params) {
77
- if (isAnswered(dialog)) return;
78
- const action = await resolveDialogAction(policy, params);
79
- if (!isAnswered(dialog)) await answer(dialog, action);
80
- }
package/src/emulate.js DELETED
@@ -1,127 +0,0 @@
1
- // Device presets for emulation
2
- export const DEVICE_PRESETS = Object.freeze({
3
- "iphone-14": {
4
- width: 390,
5
- height: 844,
6
- deviceScaleFactor: 3,
7
- mobile: true,
8
- hasTouch: true,
9
- userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",
10
- platform: "iPhone",
11
- },
12
- "pixel-7": {
13
- width: 412,
14
- height: 915,
15
- deviceScaleFactor: 2.625,
16
- mobile: true,
17
- hasTouch: true,
18
- userAgent: "Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",
19
- platform: "Linux armv8l",
20
- },
21
- "ipad-air": {
22
- width: 820,
23
- height: 1180,
24
- deviceScaleFactor: 2,
25
- mobile: true,
26
- hasTouch: true,
27
- userAgent: "Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",
28
- platform: "MacIntel",
29
- },
30
- "desktop-1440": {
31
- width: 1440,
32
- height: 900,
33
- deviceScaleFactor: 1,
34
- mobile: false,
35
- hasTouch: false,
36
- userAgent: undefined,
37
- platform: undefined,
38
- },
39
- });
40
-
41
- // WeakMap to store original UA per page
42
- const originalUAs = new WeakMap();
43
-
44
- /**
45
- * Emulate a device on the given page.
46
- * @param {object} page - The page object with cdp.send(), resolveSessionId(), evaluate(), refreshViewportSize()
47
- * @param {string|object|null} presetNameOrObject - Preset name, object, or null to restore
48
- * @returns {object} The resolved preset object
49
- */
50
- export async function emulate(page, presetNameOrObject) {
51
- // Resolve preset
52
- let preset;
53
- if (presetNameOrObject === null) {
54
- // Restore mode: resolve to a clear object
55
- preset = null;
56
- } else if (typeof presetNameOrObject === "string") {
57
- if (!DEVICE_PRESETS[presetNameOrObject]) {
58
- throw new Error(`unknown device preset: ${presetNameOrObject}`);
59
- }
60
- preset = DEVICE_PRESETS[presetNameOrObject];
61
- } else {
62
- preset = presetNameOrObject;
63
- }
64
-
65
- const sessionId = await page.resolveSessionId();
66
-
67
- if (preset === null) {
68
- // Restore mode: clear metrics and restore original UA
69
- await page.cdp.send("Emulation.clearDeviceMetricsOverride", {}, sessionId);
70
- await page.cdp.send("Emulation.setTouchEmulationEnabled", { enabled: false }, sessionId);
71
-
72
- const originalUA = originalUAs.get(page);
73
- if (originalUA) {
74
- await page.cdp.send("Emulation.setUserAgentOverride", { userAgent: originalUA }, sessionId);
75
- }
76
- } else {
77
- // Emulation mode: set metrics and UA
78
- // Capture original UA on first emulation if not already done
79
- if (!originalUAs.has(page)) {
80
- const ua = await page.evaluate(() => navigator.userAgent);
81
- originalUAs.set(page, ua);
82
- }
83
-
84
- // Set device metrics
85
- await page.cdp.send(
86
- "Emulation.setDeviceMetricsOverride",
87
- {
88
- width: preset.width,
89
- height: preset.height,
90
- deviceScaleFactor: preset.deviceScaleFactor,
91
- mobile: preset.mobile,
92
- screenWidth: preset.width,
93
- screenHeight: preset.height,
94
- },
95
- sessionId
96
- );
97
-
98
- // Set touch emulation
99
- await page.cdp.send(
100
- "Emulation.setTouchEmulationEnabled",
101
- {
102
- enabled: preset.hasTouch,
103
- maxTouchPoints: preset.hasTouch ? 5 : 1,
104
- },
105
- sessionId
106
- );
107
-
108
- // Set user agent if defined
109
- if (preset.userAgent !== undefined) {
110
- await page.cdp.send(
111
- "Emulation.setUserAgentOverride",
112
- {
113
- userAgent: preset.userAgent,
114
- platform: preset.platform,
115
- },
116
- sessionId
117
- );
118
- }
119
- }
120
-
121
- // Refresh viewport size
122
- if (page.refreshViewportSize) {
123
- await page.refreshViewportSize();
124
- }
125
-
126
- return preset;
127
- }
package/src/events.js DELETED
@@ -1,111 +0,0 @@
1
- const EVENT_NAMES = ["tabOpened", "tabClosed", "popupOpened", "downloadStarted", "downloadProgress", "downloadFinished"];
2
- export const BROWSER_EVENT_NAMES = Object.freeze([...EVENT_NAMES]);
3
- const DEFAULT_TIMEOUT = 30_000;
4
- const TERMINAL_LIMIT = 4_096;
5
-
6
- function pageTarget(info) { return info?.type === "page" && info?.targetId ? info : null; }
7
- function normalizeTarget(info) {
8
- return { targetId: String(info.targetId), type: "page", url: info.url ?? "about:blank", title: info.title ?? "", openerId: info.openerId ?? null, openerFrameId: info.openerFrameId ?? null, browserContextId: info.browserContextId ?? null, attached: Boolean(info.attached), subtype: info.subtype ?? null };
9
- }
10
- function errorValue(value) { return value instanceof Error ? value : Error(String(value)); }
11
-
12
- class BrowserEventBridge {
13
- #cdp; #options; #listeners = new Map(); #unsubscribers = [];
14
- #targetInfos = new Map(); #crashes = new Map(); #downloads = new Map(); #terminalDownloads = new Map(); #terminal = new Set();
15
- #frameToTarget = new Map(); #sessionToTarget = new Map(); #waits = new Set(); #disposed = false; #explicitDispose = false;
16
- ready;
17
- constructor(connection, options) {
18
- if (!connection?.cdp) throw new TypeError("createEvents requires a browser connection");
19
- this.#cdp = connection.cdp; this.#options = this.#validate(options); this.#register(); this.ready = this.#initialize();
20
- }
21
- #validate(options) {
22
- const behavior = options.downloadBehavior ?? "default";
23
- if (!["default", "allow", "deny", "allowAndName"].includes(behavior)) throw new TypeError("Invalid downloadBehavior");
24
- if (behavior === "allow" && !pathIsAbsolute(options.downloadPath)) throw new TypeError("downloadPath must be an absolute path for allow");
25
- return { ...options, downloadBehavior: behavior };
26
- }
27
- #register() {
28
- const on = (method, fn) => this.#unsubscribers.push(this.#cdp.on(method, fn));
29
- on("Target.targetCreated", info => this.#created(info, false));
30
- on("Target.targetDestroyed", info => this.#destroyed(info));
31
- on("Target.targetInfoChanged", info => { const target = pageTarget(info?.targetInfo); if (target && this.#targetInfos.has(target.targetId)) this.#targetInfos.set(target.targetId, normalizeTarget(target)); });
32
- on("Target.targetCrashed", info => { if (info?.targetId) this.#crashes.set(info.targetId, { status: info.status ?? "", errorCode: info.errorCode ?? 0 }); });
33
- on("Target.attachedToTarget", (info, meta) => { const targetId = info?.targetInfo?.targetId; const sessionId = info?.sessionId ?? meta?.sessionId; if (targetId && sessionId) { this.#sessionToTarget.set(sessionId, targetId); } });
34
- on("Target.detachedFromTarget", (info, meta) => { const sessionId = info?.sessionId ?? meta?.sessionId; if (sessionId) this.#sessionToTarget.delete(sessionId); });
35
- on("Browser.downloadWillBegin", info => this.#downloadBegin(info));
36
- on("Browser.downloadProgress", info => this.#downloadProgress(info));
37
- on("Page.frameAttached", (info, meta) => { const sessionId = info?.sessionId ?? meta?.sessionId; if (sessionId && info?.frameId) this.#mapFrame(info.frameId, sessionId); });
38
- on("Page.frameNavigated", (info, meta) => { const sessionId = info?.sessionId ?? meta?.sessionId; if (sessionId && info?.frame?.id) this.#mapFrame(info.frame.id, sessionId); });
39
- if (this.#cdp.transportEvents?.on) {
40
- this.#unsubscribers.push(this.#cdp.transportEvents.on("disconnected", () => { this.#disconnectDownloads(); this.#cancelWaits(Error("Browser transport disconnected")); }));
41
- this.#unsubscribers.push(this.#cdp.transportEvents.on("reconnected", () => { this.#reconcile().catch(error => console.warn("[events] target reconciliation failed", error)); this.#configureDownloads().catch(error => console.warn("[events] download reconfiguration failed", error)); }));
42
- }
43
- }
44
- async #initialize() {
45
- await this.#cdp.ensureConnected(); await this.#cdp.send("Target.setDiscoverTargets", { discover: true });
46
- const result = await this.#cdp.send("Target.getTargets"); await this.#configureDownloads();
47
- const targets = (result?.targetInfos ?? []).filter(info => pageTarget(info));
48
- targets.sort((a, b) => Boolean(a.openerId) - Boolean(b.openerId));
49
- for (const info of targets) this.#created(info, true);
50
- }
51
- async #reconcile() {
52
- const result = await this.#cdp.send("Target.getTargets");
53
- const current = new Set((result?.targetInfos ?? []).filter(info => pageTarget(info)).map(info => String(info.targetId)));
54
- for (const id of [...this.#targetInfos.keys()]) if (!current.has(id)) this.#destroyed({ targetId: id });
55
- const targets = (result?.targetInfos ?? []).filter(info => pageTarget(info));
56
- targets.sort((a, b) => Boolean(a.openerId) - Boolean(b.openerId));
57
- for (const info of targets) this.#created(info, true);
58
- }
59
- async #configureDownloads() {
60
- const params = { behavior: this.#options.downloadBehavior, eventsEnabled: true };
61
- if (this.#options.downloadBehavior === "allow" || this.#options.downloadBehavior === "allowAndName") params.downloadPath = this.#options.downloadPath;
62
- await this.#cdp.send("Browser.setDownloadBehavior", params);
63
- }
64
- #mapFrame(frameId, sessionId) {
65
- const targetId = this.#sessionToTarget.get(sessionId) ?? [...this.#targetInfos.values()].find(info => info.attached && info.targetId === sessionId)?.targetId;
66
- if (targetId) this.#frameToTarget.set(frameId, targetId);
67
- }
68
- #created(info, initial) {
69
- const target = pageTarget(info?.targetInfo ?? info); if (!target) return;
70
- const normalized = normalizeTarget(target); const id = normalized.targetId;
71
- if (this.#targetInfos.has(id)) return;
72
- this.#targetInfos.set(id, normalized);
73
- const popup = Boolean(normalized.openerId && this.#targetInfos.has(normalized.openerId));
74
- this.#dispatch("tabOpened", { ...normalized, popup, initial: Boolean(initial) });
75
- if (popup) this.#dispatch("popupOpened", { targetId: id, openerTargetId: normalized.openerId, openerFrameId: normalized.openerFrameId, url: normalized.url, title: normalized.title, initial: Boolean(initial) });
76
- }
77
- #destroyed(info) {
78
- const id = info?.targetId; const last = this.#targetInfos.get(id); if (!last) return;
79
- this.#targetInfos.delete(id); const crash = this.#crashes.get(id) ?? null; this.#crashes.delete(id);
80
- for (const [frame, targetId] of this.#frameToTarget) if (targetId === id) this.#frameToTarget.delete(frame);
81
- this.#dispatch("tabClosed", { targetId: id, reason: crash ? "crashed" : "destroyed", lastKnown: last, crash });
82
- }
83
- #rememberTerminal(guid) { this.#terminal.delete(guid); this.#terminal.add(guid); if (this.#terminal.size > TERMINAL_LIMIT) { const oldest = this.#terminal.values().next().value; this.#terminal.delete(oldest); this.#terminalDownloads.delete(oldest); } }
84
- #downloadBegin(info = {}) {
85
- if (!info.guid || this.#terminal.has(info.guid)) return;
86
- const record = { guid: info.guid, url: info.url ?? null, suggestedFilename: info.suggestedFilename ?? "", frameId: info.frameId ?? null, targetId: this.#frameToTarget.get(info.frameId) ?? null, totalBytes: 0, receivedBytes: 0, filePath: null };
87
- this.#downloads.set(info.guid, record); this.#dispatch("downloadStarted", { guid: record.guid, url: record.url, suggestedFilename: record.suggestedFilename, frameId: record.frameId, targetId: record.targetId });
88
- }
89
- #downloadProgress(info = {}) {
90
- if (!info.guid) return;
91
- const alreadyTerminal = this.#terminal.has(info.guid);
92
- const record = this.#downloads.get(info.guid) ?? this.#terminalDownloads.get(info.guid); if (!record) return;
93
- Object.assign(record, { totalBytes: Number(info.totalBytes ?? 0), receivedBytes: Number(info.receivedBytes ?? 0), filePath: info.filePath ?? null });
94
- this.#dispatch("downloadProgress", { guid: info.guid, totalBytes: record.totalBytes, receivedBytes: record.receivedBytes, state: info.state, filePath: record.filePath, targetId: record.targetId });
95
- if ((info.state === "completed" || info.state === "canceled") && !alreadyTerminal) { this.#rememberTerminal(info.guid); this.#downloads.delete(info.guid); this.#terminalDownloads.set(info.guid, record); this.#dispatch("downloadFinished", { guid: info.guid, totalBytes: record.totalBytes, receivedBytes: record.receivedBytes, state: info.state, cdpState: info.state, filePath: record.filePath, targetId: record.targetId, error: null }); }
96
- }
97
- #disconnectDownloads() {
98
- if (this.#explicitDispose) return;
99
- for (const record of this.#downloads.values()) { this.#rememberTerminal(record.guid); this.#dispatch("downloadFinished", { guid: record.guid, totalBytes: record.totalBytes, receivedBytes: record.receivedBytes, state: "failed", cdpState: null, filePath: record.filePath, targetId: record.targetId, error: { code: "browserDisconnected", message: "Browser transport disconnected" } }); }
100
- this.#downloads.clear();
101
- }
102
- #dispatch(name, payload) { const listeners = [...this.#listeners.get(name) ?? []]; Promise.allSettled(listeners.map(listener => Promise.resolve().then(() => listener(payload)))).then(results => results.filter(r => r.status === "rejected").forEach(r => console.warn(`[events] ${name} listener failed`, r.reason))); }
103
- on(name, listener) { this.#assertName(name); if (typeof listener !== "function") throw new TypeError("listener must be a function"); const set = this.#listeners.get(name) ?? new Set(); set.add(listener); this.#listeners.set(name, set); return () => this.off(name, listener); }
104
- off(name, listener) { this.#assertName(name); this.#listeners.get(name)?.delete(listener); }
105
- #cancelWaits(error) { for (const cancel of this.#waits) cancel(error); this.#waits.clear(); }
106
- waitForEvent(name, options = {}) { this.#assertName(name); if (this.#disposed) return Promise.reject(Error("Events bridge is disposed")); const timeout = options.timeout ?? DEFAULT_TIMEOUT; return new Promise((resolve, reject) => { let done = false; let timer; const off = this.on(name, async value => { try { if (options.predicate && !await options.predicate(value)) return; if (done) return; done = true; clearTimeout(timer); this.#waits.delete(cancel); off(); resolve(value); } catch (error) { if (!done) { done = true; clearTimeout(timer); this.#waits.delete(cancel); off(); reject(errorValue(error)); } } }); const cancel = error => { if (!done) { done = true; clearTimeout(timer); this.#waits.delete(cancel); off(); reject(error ?? Error("Events bridge disposed")); } }; this.#waits.add(cancel); timer = setTimeout(() => cancel(Error(`Timed out waiting for browser event "${name}"`)), timeout); }); }
107
- #assertName(name) { if (!EVENT_NAMES.includes(name)) throw new TypeError(`Unknown browser event: ${String(name)}`); }
108
- async dispose() { if (this.#disposed) return; this.#disposed = true; this.#explicitDispose = true; this.#cancelWaits(); for (const off of this.#unsubscribers) off(); this.#unsubscribers = []; this.#listeners.clear(); await this.ready.catch(() => {}); }
109
- }
110
- function pathIsAbsolute(value) { return typeof value === "string" && (value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value)); }
111
- export function createEvents(connection, options = {}) { return new BrowserEventBridge(connection, options); }
@@ -1,138 +0,0 @@
1
- // OOPIF-aware snapshots.
2
- //
3
- // core.js already snapshots every frame its FrameManager knows about, prefixes child refs
4
- // with f<N>, stitches the child trees into the parent tree and routes page.locator("f1e1")
5
- // to the owning session. What it misses is an out-of-process iframe that already existed
6
- // when the page was attached (attach-to-existing-tab, reconnect): FrameManager.initialize()
7
- // sends Target.setAutoAttach before it registers its Target.attachedToTarget listener, and
8
- // the parent's Page.getFrameTree never lists OOPIF children, so nothing backfills them.
9
- //
10
- // reconcileFrames() closes that gap from the outside, using only public members, and
11
- // snapshotWithFrames() is reconcile + page.snapshot(). Refs stay page-level: use
12
- // page.locator(ref), not frame.locator(ref).
13
-
14
- const AUTO_ATTACH = { autoAttach: true, waitForDebuggerOnStart: false, flatten: true };
15
- const REF_PATTERN = /^(f\d+)?e\d+$/;
16
-
17
- function detach(page, sessionId) {
18
- return page.cdp.send("Target.detachFromTarget", { sessionId }).catch(() => {});
19
- }
20
-
21
- async function iframeTargets(page) {
22
- const { targetInfo } = await page.cdp.send("Target.getTargetInfo", { targetId: page.targetId });
23
- const browserContextId = targetInfo?.browserContextId;
24
- const { targetInfos } = await page.cdp.send("Target.getTargets", { filter: [{ type: "iframe" }] });
25
- return targetInfos.filter(info => info.type === "iframe"
26
- && (!browserContextId || !info.browserContextId || info.browserContextId === browserContextId));
27
- }
28
-
29
- // A frame only participates in snapshots if its parent chain reaches the main frame.
30
- // A dropped or late attach can leave an entry behind with no parent link at all (the
31
- // Target.attachedToTarget handler falls back to null when the target info carries no
32
- // parent), and core then never walks into it, so the child content stays invisible.
33
- // Such an entry counts as missing and is re-attributed.
34
- function isAttributed(fm, frameId) {
35
- const seen = new Set();
36
- let frame = fm.frames.get(frameId);
37
- while (frame && !seen.has(frame.frameId)) {
38
- if (frame.frameId === fm.mainFrameId) return true;
39
- seen.add(frame.frameId);
40
- frame = frame.parentFrameId ? fm.frames.get(frame.parentFrameId) : null;
41
- }
42
- return false;
43
- }
44
-
45
- // Attach, then ask the child itself who its parent is: Page.getFrameTree on the child
46
- // session is the only reliable attribution for an iframe target.
47
- async function describeTarget(page, targetId) {
48
- const { sessionId } = await page.cdp.send("Target.attachToTarget", { targetId, flatten: true });
49
- try {
50
- await page.cdp.send("Page.enable", undefined, sessionId);
51
- const { frameTree } = await page.cdp.send("Page.getFrameTree", undefined, sessionId);
52
- return { sessionId, frame: frameTree.frame };
53
- } catch (error) {
54
- await detach(page, sessionId);
55
- throw error;
56
- }
57
- }
58
-
59
- async function adopt(page, sessionId, frame, parentFrameId) {
60
- await page.cdp.send("DOM.enable", undefined, sessionId);
61
- // Nested OOPIFs then arrive through core's own Target.attachedToTarget handler, which
62
- // accepts the event once one of its frames carries this session.
63
- await page.cdp.send("Target.setAutoAttach", AUTO_ATTACH, sessionId).catch(() => {});
64
- page.frameManager.frames.set(frame.id, {
65
- frameId: frame.id,
66
- parentFrameId,
67
- url: frame.url ?? "",
68
- name: frame.name ?? "",
69
- sessionId,
70
- });
71
- const isolatedContextId = await page.frameManager.ensureInjected(frame.id);
72
- return { frameId: frame.id, parentFrameId, url: frame.url ?? "", sessionId, isolatedContextId };
73
- }
74
-
75
- /**
76
- * Adopt every iframe target of this page that FrameManager does not know yet.
77
- * Returns the frames that were added (empty when there was nothing to recover).
78
- */
79
- export async function reconcileFrames(page) {
80
- const fm = page.frameManager;
81
- const added = [];
82
- let pending = (await iframeTargets(page)).filter(info => !isAttributed(fm, info.targetId));
83
- let progress = true;
84
- while (progress && pending.length > 0) {
85
- progress = false;
86
- const retry = [];
87
- for (const target of pending) {
88
- if (isAttributed(fm, target.targetId)) continue;
89
- const { sessionId, frame } = await describeTarget(page, target.targetId);
90
- const parentFrameId = frame.parentId ?? null;
91
- if (!parentFrameId || !isAttributed(fm, parentFrameId)) {
92
- // Not ours (another tab), or its parent is itself still pending: never adopt a
93
- // frame we cannot attribute to this page.
94
- await detach(page, sessionId);
95
- if (parentFrameId) retry.push(target);
96
- continue;
97
- }
98
- added.push(await adopt(page, sessionId, frame, parentFrameId));
99
- progress = true;
100
- }
101
- pending = retry;
102
- }
103
- return added;
104
- }
105
-
106
- // Mirrors core's prefix assignment: main frame "", the remaining frames f1..fN in the
107
- // BFS order of collectDescendantFrames.
108
- function framePrefixes(fm) {
109
- let counter = 1;
110
- return fm.collectDescendantFrames(fm.mainFrameId)
111
- .map(({ frameId }) => ({ frameId, prefix: frameId === fm.mainFrameId ? "" : `f${counter++}` }));
112
- }
113
-
114
- // Diagnostics only: a frame that contributed no ref *and* has no isolated world is a frame
115
- // the snapshot could not enter. Frames that are merely empty keep their world, so they are
116
- // not reported.
117
- function collectMissingFrames(page, refs) {
118
- const seen = new Set(Object.keys(refs ?? {}).map(ref => ref.match(REF_PATTERN)?.[1] ?? ""));
119
- const missing = [];
120
- for (const { frameId, prefix } of framePrefixes(page.frameManager)) {
121
- if (prefix === "" || seen.has(prefix)) continue;
122
- const frame = page.frameManager.getFrame(frameId);
123
- if (frame?.isolatedContextId) continue;
124
- missing.push({ frameId, url: frame?.url ?? "", injected: false });
125
- }
126
- return missing;
127
- }
128
-
129
- /**
130
- * page.snapshot() with pre-existing out-of-process iframes recovered first.
131
- * Adds `missingFrames` only when a frame could not be entered at all.
132
- */
133
- export async function snapshotWithFrames(page, opts = {}) {
134
- await reconcileFrames(page);
135
- const result = await page.snapshot(opts);
136
- const missingFrames = collectMissingFrames(page, result.refs);
137
- return missingFrames.length > 0 ? { ...result, missingFrames } : result;
138
- }
package/src/har.js DELETED
@@ -1,103 +0,0 @@
1
- const HTTP_VERSION = "HTTP/1.1";
2
- // Kept in sync with package.json; har.js stays pure so it never reads the manifest from disk.
3
- const CREATOR = Object.freeze({ name: "omowright", version: "0.0.1" });
4
-
5
- function headerList(headers) {
6
- return Object.entries(headers ?? {}).map(([name, value]) => ({ name, value: String(value) }));
7
- }
8
-
9
- function headerValue(headers, name) {
10
- for (const [key, value] of Object.entries(headers ?? {})) {
11
- if (key.toLowerCase() === name) return String(value);
12
- }
13
- return null;
14
- }
15
-
16
- function queryString(url) {
17
- try {
18
- return [...new URL(String(url)).searchParams].map(([name, value]) => ({ name, value }));
19
- } catch {
20
- // Non-absolute or malformed urls carry no parsable query.
21
- return [];
22
- }
23
- }
24
-
25
- function elapsed(entry) {
26
- const started = Number(entry.startedAt);
27
- const finished = Number(entry.finishedAt);
28
- if (!Number.isFinite(started) || !Number.isFinite(finished)) return 0;
29
- return Math.max(0, finished - started);
30
- }
31
-
32
- function requestOf(entry) {
33
- const postData = entry.postData ?? null;
34
- const request = {
35
- method: entry.method ?? "GET",
36
- url: entry.url ?? "",
37
- httpVersion: HTTP_VERSION,
38
- cookies: [],
39
- headers: headerList(entry.requestHeaders),
40
- queryString: queryString(entry.url),
41
- headersSize: -1,
42
- bodySize: postData === null ? 0 : Buffer.byteLength(postData),
43
- };
44
- if (postData !== null) {
45
- request.postData = {
46
- mimeType: headerValue(entry.requestHeaders, "content-type") ?? "",
47
- text: postData,
48
- };
49
- }
50
- return request;
51
- }
52
-
53
- function contentOf(entry) {
54
- const content = {
55
- size: Number(entry.encodedDataLength ?? 0),
56
- mimeType: entry.mimeType ?? "",
57
- };
58
- if (typeof entry.body === "string") content.text = entry.body;
59
- if (entry.base64Encoded) content.encoding = "base64";
60
- return content;
61
- }
62
-
63
- function responseOf(entry) {
64
- return {
65
- status: entry.failed ? 0 : Number(entry.status ?? 0),
66
- statusText: entry.statusText ?? "",
67
- httpVersion: HTTP_VERSION,
68
- cookies: [],
69
- headers: headerList(entry.responseHeaders),
70
- content: contentOf(entry),
71
- redirectURL: headerValue(entry.responseHeaders, "location") ?? "",
72
- headersSize: -1,
73
- bodySize: Number(entry.encodedDataLength ?? 0),
74
- };
75
- }
76
-
77
- /**
78
- * Converts network snoop entries into a HAR 1.2 log.
79
- *
80
- * Pure: it touches no disk and mutates nothing, so callers can serialize the result
81
- * themselves or embed it in a larger artifact.
82
- */
83
- export function toHar(entries, { creator = CREATOR, pages = [] } = {}) {
84
- const log = {
85
- version: "1.2",
86
- creator,
87
- pages,
88
- entries: [...entries ?? []].map(entry => {
89
- const time = elapsed(entry);
90
- const har = {
91
- startedDateTime: new Date(Number(entry.startedAt) || 0).toISOString(),
92
- time,
93
- request: requestOf(entry),
94
- response: responseOf(entry),
95
- cache: {},
96
- timings: { send: 0, wait: time, receive: 0 },
97
- };
98
- if (entry.failed) har._errorText = entry.errorText ?? "";
99
- return har;
100
- }),
101
- };
102
- return { log };
103
- }