omowright 0.1.0 → 0.2.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.
@@ -106,9 +106,11 @@ export async function requestHuman(page, { prompt, until, timeoutMs = 300000, po
106
106
 
107
107
  for (;;) {
108
108
  if (signal?.aborted) return finish("cancelled", "signal");
109
- if (Date.now() - started >= timeoutMs) return finish("timed_out", "timed_out");
109
+ // Check the conditions before the deadline: a slow bringToFront or banner
110
+ // injection must not time the wait out before its first check.
110
111
  if (await matchesUntil(page, until)) return finish("continued", "until");
111
112
  if (await isDone(page)) return finish("continued", "done-button");
113
+ if (Date.now() - started >= timeoutMs) return finish("timed_out", "timed_out");
112
114
  // Human waits are idle time, not a race against a specific event; a timer
113
115
  // poll loop is the correct tool here.
114
116
  await ensureBanner(page, prompt);
package/src/index.js CHANGED
@@ -21,6 +21,7 @@ export { compactSnapshot, snapshotTokens, toolSchemas } from "./llm.js";
21
21
  export { createCua } from "./cua.js";
22
22
  export { createCaptcha, macOSVisionOcr } from "./captcha.js";
23
23
  export { BROWSER_EVENT_NAMES, createEvents } from "./events.js";
24
+ export { PAGE_EVENT_NAMES } from "./page-events.js";
24
25
  export { AgentTabManager, createAgentTabs } from "./agent-tabs.js";
25
26
  export { DEFAULT_AGENT_VIEWPORT, repinViewport } from "./viewport.js";
26
27
  export { createChromeApi } from "./bridge-transport.js";
@@ -53,6 +54,8 @@ export {
53
54
  OmOPage,
54
55
  SessionManager,
55
56
  UnsupportedOperationError,
57
+ VideoRecordingError,
58
+ WaitForFunctionTimeoutError,
56
59
  takeSnapshot,
57
60
  selectors,
58
61
  } from "./core.js";
@@ -1,18 +1,7 @@
1
- import { randomUUID } from "node:crypto";
2
- import { watch } from "node:fs";
3
- import { link, readdir, rename, stat, unlink } from "node:fs/promises";
4
- import path from "node:path";
1
+ import { unlink } from "node:fs/promises";
5
2
  import { setTimeout as sleep } from "node:timers/promises";
6
- import {
7
- createLock,
8
- isSameLock,
9
- processStartTime,
10
- readLockState,
11
- } from "./lock-file.js";
3
+ import { probeOnce, tryAcquire } from "./lock-backend.js";
12
4
 
13
- const LOCK_POLL_INTERVAL_MS = 250;
14
- const LOCK_RETRY_JITTER_MS = 25;
15
- const LOCK_PUT_BACK_TIMEOUT_MS = 30_000;
16
5
  const localLocks = new Map();
17
6
 
18
7
  export function isPidAlive(pid) {
@@ -32,168 +21,24 @@ export async function unlinkIfPresent(target) {
32
21
  });
33
22
  }
34
23
 
35
- async function isAbandoned(state, staleGraceMs, startTimeOf) {
36
- if (state.pid === null) return Date.now() - state.mtimeMs >= staleGraceMs;
37
- if (!isPidAlive(state.pid)) return true;
38
- if (state.start === null) return false;
39
- const start = await startTimeOf(state.pid);
40
- return start !== null && start !== state.start;
41
- }
42
-
43
- // Deletes only the lock that was proved abandoned, identified by inode AND
44
- // token, never another one. The rename is the exclusive step: of two
45
- // reclaimers only one moves a given entry, and whatever we moved is ours alone
46
- // to inspect. An inode number alone is not enough because ext4 reuses them, so
47
- // a live lock created after the dead one vanished can carry the same inode;
48
- // its token differs, and anything that does not match is put back.
49
- // Known residuals of a takeover built from path operations (#62 replaces it):
50
- // while a live lock is moved aside another contender can take the name, so two
51
- // processes hold it until the put-back; and a holder that releases while its
52
- // lock is moved aside can have that finished lock put back, which keeps the
53
- // name locked until the holder's process exits.
54
- // `hooks` lets a test run code inside the gaps between these steps.
55
- export async function reclaimLock(lockPath, ino, token, { deadline = Date.now() + LOCK_PUT_BACK_TIMEOUT_MS, hooks = {} } = {}) {
56
- if (!isSameLock(await readLockState(lockPath), ino, token)) {
57
- return (await stat(lockPath).catch(() => null)) === null;
58
- }
59
- const movedPath = `${lockPath}.${process.pid}.${randomUUID()}.stale`;
60
- await hooks.beforeMove?.();
61
- try {
62
- await rename(lockPath, movedPath);
63
- } catch (error) {
64
- if (error?.code === "ENOENT") return true;
65
- throw error;
66
- }
67
- await hooks.afterMove?.();
68
- if (isSameLock(await readLockState(movedPath).catch(() => null), ino, token)) {
69
- await unlinkIfPresent(movedPath);
70
- return true;
71
- }
72
- await putBack(movedPath, lockPath, deadline, hooks);
73
- return false;
74
- }
75
-
76
- // The moved file is a live holder's lock. While the name was empty another
77
- // contender may have locked it; the moved lock then waits for that one to go.
78
- // It is never deleted here: it leaves only when it is back under its name, when
79
- // its holder released it (releaseLock removes moved copies of its own lock), or
80
- // it stays where it is past the deadline for that holder to release.
81
- async function putBack(movedPath, lockPath, deadline, hooks) {
24
+ async function acquireLock(lockPath, timeoutMs) {
25
+ const deadline = performance.now() + timeoutMs;
26
+ let delay = 10;
82
27
  for (;;) {
83
- try {
84
- await link(movedPath, lockPath);
85
- await unlinkIfPresent(movedPath);
86
- return;
87
- } catch (error) {
88
- if (error?.code === "ENOENT") return;
89
- if (error?.code !== "EEXIST") throw error;
90
- }
91
- await hooks.onPutBackBlocked?.();
92
- if ((await stat(movedPath).catch(() => null)) === null) return;
93
- const remainingMs = deadline - Date.now();
94
- if (remainingMs <= 0) return;
95
- await waitForLockRelease(lockPath, Math.min(remainingMs, LOCK_POLL_INTERVAL_MS));
96
- }
97
- }
98
-
99
- // Unlink only entries that still name the lock we created: if ours was
100
- // reclaimed under us, the file at this path belongs to the next owner. A
101
- // reclaimer may be holding our lock moved aside, so those copies go first;
102
- // checked in this order, a copy put back meanwhile is found under the name.
103
- async function releaseLock(lockPath, ino, token) {
104
- const prefix = `${path.basename(lockPath)}.`;
105
- const entries = await readdir(path.dirname(lockPath)).catch(() => []);
106
- for (const entry of entries) {
107
- if (!entry.startsWith(prefix) || !entry.endsWith(".stale")) continue;
108
- const moved = path.join(path.dirname(lockPath), entry);
109
- if (isSameLock(await readLockState(moved).catch(() => null), ino, token)) {
110
- await unlinkIfPresent(moved);
111
- }
112
- }
113
- if (!isSameLock(await readLockState(lockPath), ino, token)) return;
114
- await unlinkIfPresent(lockPath);
115
- }
116
-
117
- function waitForLockRelease(lockPath, timeoutMs) {
118
- return new Promise((resolve, reject) => {
119
- let settled = false;
120
- let watcher;
121
- let timer;
122
- const finish = (error, released) => {
123
- if (settled) return;
124
- settled = true;
125
- clearTimeout(timer);
126
- watcher?.close();
127
- if (error) reject(error);
128
- else resolve(released);
129
- };
130
- const check = () => {
131
- stat(lockPath).then(
132
- () => {},
133
- (error) => {
134
- if (error?.code === "ENOENT") finish(null, true);
135
- else finish(error);
136
- },
137
- );
138
- };
139
- try {
140
- watcher = watch(path.dirname(lockPath), (event, filename) => {
141
- if (
142
- (event === "rename" || event === "change") &&
143
- (!filename || filename.toString() === path.basename(lockPath))
144
- ) {
145
- check();
146
- }
147
- });
148
- } catch (error) {
149
- if (error?.code !== "ENOENT") {
150
- finish(error);
151
- return;
28
+ const held = await tryAcquire(lockPath);
29
+ if (held) {
30
+ try {
31
+ await probeOnce(lockPath);
32
+ return held;
33
+ } catch (error) {
34
+ await held.release();
35
+ throw error;
152
36
  }
153
37
  }
154
- timer = setTimeout(() => finish(null, false), timeoutMs);
155
- check();
156
- });
157
- }
158
-
159
- async function acquireLock(lockPath, timeoutMs, staleGraceMs, lookupStartTime) {
160
- const deadline = Date.now() + timeoutMs;
161
- // A live holder's start time cannot change while we wait, and on Windows each
162
- // lookup is a PowerShell call of about a second, so one acquire looks each
163
- // holder pid up once. A holder that dies is still caught by isPidAlive; only
164
- // a pid reused within one wait pass escapes it, and the wait then times out.
165
- const startTimes = new Map();
166
- const startTimeOf = async (pid) => {
167
- if (!startTimes.has(pid)) {
168
- const start = await lookupStartTime(pid);
169
- if (start === null) return null;
170
- startTimes.set(pid, start);
171
- }
172
- return startTimes.get(pid);
173
- };
174
- let holderPid = null;
175
- for (;;) {
176
- const ours = await createLock(lockPath);
177
- if (ours !== null) return () => releaseLock(lockPath, ours.ino, ours.token);
178
- if (Date.now() >= deadline) {
179
- throw new Error(
180
- `timed out waiting for instance lock held by pid ${holderPid ?? "unknown"}`,
181
- );
182
- }
183
-
184
- const state = await readLockState(lockPath);
185
- if (state === null) continue;
186
- holderPid = state.pid ?? holderPid;
187
- if (await isAbandoned(state, staleGraceMs, startTimeOf)) {
188
- await reclaimLock(lockPath, state.ino, state.token, { deadline });
189
- // Jitter keeps two reclaimers from retrying in lockstep forever.
190
- await sleep(Math.random() * LOCK_RETRY_JITTER_MS);
191
- continue;
192
- }
193
- const remainingMs = deadline - Date.now();
194
- if (remainingMs > 0) {
195
- await waitForLockRelease(lockPath, Math.min(remainingMs, LOCK_POLL_INTERVAL_MS));
196
- }
38
+ const remaining = deadline - performance.now();
39
+ if (remaining <= 0) throw new Error(`timed out waiting for instance lock ${lockPath}`);
40
+ await sleep(Math.min(remaining, delay * (0.75 + Math.random() * 0.5)));
41
+ delay = Math.min(delay * 2, 250);
197
42
  }
198
43
  }
199
44
 
@@ -212,17 +57,16 @@ async function acquireLocalLock(key) {
212
57
  };
213
58
  }
214
59
 
215
- // Runs `run` while this process and every other one agree we hold `lockPath`.
216
- // A lock with no readable identity counts as held until it is `staleGraceMs` old.
217
- // `startTimeOf` lets a test count start-time lookups; production callers pass none.
218
- export async function withLock(lockPath, { timeoutMs, staleGraceMs, startTimeOf = processStartTime }, run) {
60
+ // The kernel owns exclusion and crash release; the local FIFO avoids polling
61
+ // between callers in this process. Neither acquisition nor release removes files.
62
+ export async function withLock(lockPath, { timeoutMs }, run) {
219
63
  const releaseLocal = await acquireLocalLock(lockPath);
220
64
  try {
221
- const release = await acquireLock(lockPath, timeoutMs, staleGraceMs, startTimeOf);
65
+ const held = await acquireLock(lockPath, timeoutMs);
222
66
  try {
223
67
  return await run();
224
68
  } finally {
225
- await release();
69
+ await held.release();
226
70
  }
227
71
  } finally {
228
72
  releaseLocal();
package/src/instances.js CHANGED
@@ -39,10 +39,6 @@ const BROWSER_CLOSE_TIMEOUT_MS = 2_000;
39
39
  const LOCK_TIMEOUT_MARGIN_MS = 5_000;
40
40
  // Same sum the per-call resolver below computes, for callers with no overrides.
41
41
  const DEFAULT_LOCK_TIMEOUT_MS = resolveLockTimeoutMs({});
42
- // A lock whose content never became readable counts as held until it is older
43
- // than any legitimate hold: an unreadable lock is far more likely to be a
44
- // contender caught mid-acquire than an abandoned file.
45
- const STALE_LOCK_GRACE_MS = DEFAULT_LOCK_TIMEOUT_MS;
46
42
 
47
43
  function normalizeName(name) {
48
44
  if (
@@ -61,7 +57,7 @@ function registryPaths(registryRoot, name) {
61
57
  return {
62
58
  root,
63
59
  recordPath: path.join(root, `${name}.json`),
64
- lockPath: path.join(root, `${name}.lock`),
60
+ lockPath: path.join(root, `${name}.flock`),
65
61
  };
66
62
  }
67
63
 
@@ -173,7 +169,7 @@ function resolveLockTimeoutMs(options) {
173
169
  if (options.lockTimeoutMs !== undefined) return options.lockTimeoutMs;
174
170
  return (
175
171
  (options.launchTimeoutMs ?? DEFAULT_LAUNCH_TIMEOUT_MS) +
176
- (options.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS) +
172
+ (options.probeTimeoutMs ?? resolveConnectTimeoutMs(options)) +
177
173
  resolveConnectTimeoutMs(options) +
178
174
  LOCK_TIMEOUT_MARGIN_MS
179
175
  );
@@ -182,7 +178,6 @@ function resolveLockTimeoutMs(options) {
182
178
  function nameLockOptions(options) {
183
179
  return {
184
180
  timeoutMs: resolveLockTimeoutMs(options),
185
- staleGraceMs: STALE_LOCK_GRACE_MS,
186
181
  };
187
182
  }
188
183
 
@@ -381,10 +376,10 @@ export async function withEngineLock(registryRoot, engineKey, run) {
381
376
  .update(path.resolve(engineKey))
382
377
  .digest("hex")
383
378
  .slice(0, 16);
384
- const lockPath = path.join(root, `_engine-${digest}.lock`);
379
+ const lockPath = path.join(root, `_engine-${digest}.flock`);
385
380
  return withLock(
386
381
  lockPath,
387
- { timeoutMs: DEFAULT_LOCK_TIMEOUT_MS, staleGraceMs: STALE_LOCK_GRACE_MS },
382
+ { timeoutMs: DEFAULT_LOCK_TIMEOUT_MS },
388
383
  run,
389
384
  );
390
385
  }
@@ -407,7 +402,9 @@ async function attachOrLaunch(normalizedName, paths, options) {
407
402
  try {
408
403
  version = await probeEndpoint(
409
404
  loaded.record.endpoint,
410
- options.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS,
405
+ // Attaching is not a one-second listInstances health check. A
406
+ // healthy holder may still be busy finishing startup under load.
407
+ options.probeTimeoutMs ?? resolveConnectTimeoutMs(options),
411
408
  );
412
409
  } catch (error) {
413
410
  if (!isConnectionRefused(error)) {
@@ -0,0 +1,54 @@
1
+ import { dlopen, ptr } from "bun:ffi";
2
+ import path from "node:path";
3
+
4
+ const systemRoot = process.env.SystemRoot || process.env.windir || "C:\\Windows";
5
+ const { symbols } = dlopen(path.win32.join(systemRoot, "System32", "ntdll.dll"), {
6
+ // NTSTATUS is returned in the same native call, unlike GetLastError's
7
+ // thread-local state, whose preservation across FFI/JS is not guaranteed.
8
+ NtCreateFile: {
9
+ args: ["buffer", "u32", "buffer", "buffer", "ptr", "u32", "u32", "u32", "u32", "ptr", "u32"],
10
+ returns: "u32",
11
+ },
12
+ NtClose: { args: ["u64"], returns: "u32" },
13
+ RtlNtStatusToDosError: { args: ["u32"], returns: "u32" },
14
+ });
15
+
16
+ function nativeError(operation, lockPath, status) {
17
+ const error = symbols.RtlNtStatusToDosError(status);
18
+ return Object.assign(
19
+ new Error(`instance lock ${operation} failed for ${lockPath} (Windows error ${error}, NTSTATUS 0x${status.toString(16)})`),
20
+ { code: "ERR_INSTANCE_LOCK" },
21
+ );
22
+ }
23
+
24
+ export function tryAcquireWindows(lockPath) {
25
+ // Bun Windows is 64-bit: UNICODE_STRING has its pointer at offset 8 and
26
+ // OBJECT_ATTRIBUTES is 48 bytes. Translate the Win32 extended namespace to NT.
27
+ const filename = Buffer.from(`${path.toNamespacedPath(path.resolve(lockPath)).replace(/^\\\\\?\\/, "\\??\\")}\0`, "utf16le");
28
+ const name = Buffer.alloc(16);
29
+ name.writeUInt16LE(filename.length - 2, 0);
30
+ name.writeUInt16LE(filename.length, 2);
31
+ name.writeBigUInt64LE(BigInt(ptr(filename)), 8);
32
+ const attributes = Buffer.alloc(48);
33
+ attributes.writeUInt32LE(48, 0);
34
+ attributes.writeBigUInt64LE(BigInt(ptr(name)), 16);
35
+ attributes.writeUInt32LE(0x40, 24); // OBJ_CASE_INSENSITIVE, not OBJ_INHERIT.
36
+ const handleOut = Buffer.alloc(8);
37
+ const ioStatus = Buffer.alloc(16);
38
+ // GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, share mode 0, FILE_OPEN_IF
39
+ // (OPEN_ALWAYS), synchronous non-directory file. NULL security descriptor
40
+ // inherits the registry's DACL; no truncation, deletion, or inheritance.
41
+ const status = symbols.NtCreateFile(
42
+ handleOut, 0xc0100000, attributes, ioStatus, null, 0x80, 0, 3, 0x60, null, 0,
43
+ );
44
+ // STATUS_SHARING_VIOLATION is exactly ERROR_SHARING_VIOLATION (32).
45
+ if (status === 0xc0000043) return null;
46
+ if (status >= 0x80000000) throw nativeError("NtCreateFile", lockPath, status);
47
+ const handle = handleOut.readBigUInt64LE();
48
+ return {
49
+ release() {
50
+ const status = symbols.NtClose(handle);
51
+ if (status >= 0x80000000) throw nativeError("NtClose", lockPath, status);
52
+ },
53
+ };
54
+ }
@@ -0,0 +1,81 @@
1
+ import { spawn } from "node:child_process";
2
+ import { constants } from "node:fs";
3
+ import { open } from "node:fs/promises";
4
+
5
+ // xnu bsd/sys/fcntl.h: O_EXLOCK and O_NONBLOCK. Node does not export O_EXLOCK.
6
+ const DARWIN_EXCLUSIVE_NONBLOCK = 0x20 | 0x4;
7
+ // libuv include/uv/win.h: UV_FS_O_EXLOCK makes CreateFile's share mode zero.
8
+ const WINDOWS_EXCLUSIVE = 0x10000000;
9
+ const probedPaths = new Set();
10
+
11
+ async function lockLinux(fd) {
12
+ return new Promise((resolve, reject) => {
13
+ const child = spawn("flock", ["-n", "3"], {
14
+ stdio: ["ignore", "ignore", "pipe", fd],
15
+ });
16
+ let stderr = "";
17
+ child.stderr.setEncoding("utf8");
18
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
19
+ child.once("error", (error) => {
20
+ reject(error.code === "ENOENT"
21
+ ? new Error(`instance lock needs the flock utility (util-linux or busybox) on Linux: ${error.message}`, { cause: error })
22
+ : error);
23
+ });
24
+ // close follows exit and drains stderr, so real utility errors are intact.
25
+ child.once("close", (code, signal) => {
26
+ if (code === 0) resolve(true);
27
+ // util-linux and BusyBox are silent on EWOULDBLOCK. BusyBox also
28
+ // returns 1 for real errors, but prints their errno description.
29
+ else if (code === 1 && stderr.trim() === "") resolve(false);
30
+ else reject(Object.assign(
31
+ new Error(`instance lock flock failed (${signal ?? code}): ${stderr.trim()}`),
32
+ { code: "ERR_INSTANCE_LOCK" },
33
+ ));
34
+ });
35
+ });
36
+ }
37
+
38
+ export async function tryAcquire(lockPath) {
39
+ const platform = process.platform;
40
+ // Bun on Windows drops libuv's exclusive-open bit. Use the same kernel
41
+ // share reservation directly; Node and non-Windows runtimes never load FFI.
42
+ if (platform === "win32" && process.versions.bun) {
43
+ const { tryAcquireWindows } = await import("./lock-backend-win32.js");
44
+ return tryAcquireWindows(lockPath);
45
+ }
46
+ let flags = constants.O_RDWR | constants.O_CREAT;
47
+ if (platform === "darwin") flags |= DARWIN_EXCLUSIVE_NONBLOCK;
48
+ else if (platform === "win32") flags |= WINDOWS_EXCLUSIVE;
49
+ else if (platform !== "linux") throw new Error(`instance lock is unsupported on ${platform}`);
50
+
51
+ let handle;
52
+ try {
53
+ handle = await open(lockPath, flags, 0o600);
54
+ } catch (error) {
55
+ if (platform === "darwin" && ["EAGAIN", "EWOULDBLOCK"].includes(error.code)) return null;
56
+ if (platform === "win32" && error.code === "EBUSY") return null;
57
+ throw error;
58
+ }
59
+ try {
60
+ if (platform === "linux" && !await lockLinux(handle.fd)) {
61
+ await handle.close();
62
+ return null;
63
+ }
64
+ } catch (error) {
65
+ await handle.close();
66
+ throw error;
67
+ }
68
+ // The runtime opens close-on-exec; only the one-shot flock child receives it.
69
+ // Never unlink: another opener must always reach the same kernel object.
70
+ return { release: () => handle.close() };
71
+ }
72
+
73
+ export async function probeOnce(lockPath) {
74
+ if (probedPaths.has(lockPath)) return;
75
+ const second = await tryAcquire(lockPath);
76
+ if (second !== null) {
77
+ await second.release();
78
+ throw new Error(`instance lock is not enforced for ${lockPath} on this runtime and filesystem`);
79
+ }
80
+ probedPaths.add(lockPath);
81
+ }
@@ -1,3 +1,5 @@
1
+ import { urlMatches } from "./url-match.js";
2
+
1
3
  const sessions = new WeakMap();
2
4
  const streams = new WeakMap();
3
5
  const METHODS = [
@@ -80,6 +82,7 @@ function recordFor(cdp, sessionId, params) {
80
82
  method: record.request.method,
81
83
  headers: () => headers(response.headers),
82
84
  status: () => response.status,
85
+ ok: () => response.status >= 200 && response.status <= 299,
83
86
  ...bodyReaders(async () => {
84
87
  const result = await record.rawBody();
85
88
  return Buffer.from(result.body ?? "", result.base64Encoded ? "base64" : "utf8");
@@ -169,6 +172,25 @@ export function subscribeNetwork(page, handlers) {
169
172
  };
170
173
  }
171
174
 
175
+ // Holds the shared stream for one navigation call. A frame's document records
176
+ // are exposed so bodies stay readable after the domain is released.
177
+ export function trackDocumentResponses(page, frameId) {
178
+ const documents = new Map();
179
+ const dispose = subscribeNetwork(page, {
180
+ "Network.requestWillBeSent": (params, record) => {
181
+ if (params.type !== "Document" || params.frameId !== frameId) return;
182
+ record.exposed = true;
183
+ // Redirect hops share the loader id; the last hop carries the final response.
184
+ documents.set(params.loaderId, record);
185
+ },
186
+ });
187
+ return {
188
+ ready: networkReady(page),
189
+ response: loaderId => documents.get(loaderId)?.response ?? null,
190
+ dispose,
191
+ };
192
+ }
193
+
172
194
  export function disposeNetwork(page) {
173
195
  streams.get(page)?.close(true);
174
196
  }
@@ -196,6 +218,6 @@ export function networkPredicate(match) {
196
218
  match.lastIndex = 0;
197
219
  return match.test(value.url());
198
220
  };
199
- if (typeof match === "string") return value => value.url() === match;
221
+ if (typeof match === "string") return value => urlMatches(value.url(), match);
200
222
  throw new TypeError("urlOrPredicate must be a URL string, RegExp or predicate");
201
223
  }
@@ -0,0 +1,28 @@
1
+ // Reassembles NUL-delimited frames (the CDP pipe's framing) from stream chunks.
2
+ // Only the newly arrived chunk is scanned for the delimiter, and a frame that
3
+ // spans chunks is joined once, when its delimiter arrives, so receiving costs
4
+ // one copy of each byte. Re-copying the pending bytes on every chunk made a
5
+ // large reply quadratic in its size (#237).
6
+ export class NulFrameReader {
7
+ #parts = [];
8
+
9
+ // Returns the frames that chunk completes, decoded as UTF-8, empty ones included.
10
+ push(chunk) {
11
+ const frames = [];
12
+ let start = 0;
13
+ let end;
14
+ while ((end = chunk.indexOf(0, start)) !== -1) {
15
+ const tail = chunk.subarray(start, end);
16
+ let frame = tail;
17
+ if (this.#parts.length > 0) {
18
+ this.#parts.push(tail);
19
+ frame = Buffer.concat(this.#parts);
20
+ this.#parts = [];
21
+ }
22
+ frames.push(frame.toString("utf8"));
23
+ start = end + 1;
24
+ }
25
+ if (start < chunk.length) this.#parts.push(chunk.subarray(start));
26
+ return frames;
27
+ }
28
+ }
@@ -1,22 +1,101 @@
1
1
  // Self-contained because locator queries serialize this into the frame's page or isolated world.
2
- // Order matches the CSS locator traversal: each scope's own matches, then its open shadow roots.
2
+ // Order matches the CSS locator traversal: the scope's own matches, then each open shadow root below
3
+ // it, depth first in document order, nested roots included. Closed roots stay excluded.
4
+ // A selector with combinators also matches across open shadow boundaries (a host is the parent of its
5
+ // shadow root's top-level children), but matching never climbs above the scope, and an element scope
6
+ // anchors the selector to itself: `:scope` and leading compounds resolve inside it, not against its ancestors.
3
7
  export function queryOpenShadowAll(root, selector) {
4
- const scan = scope => {
5
- const elements = scope.querySelectorAll("*");
6
- const shadows = scope instanceof Element && scope.shadowRoot ? [scope.shadowRoot] : [];
7
- for (let index = 0; index < elements.length; index++) {
8
- const shadow = elements[index].shadowRoot;
9
- if (shadow) shadows.push(shadow);
10
- }
11
- return { matches: selector === "*" ? elements : scope.querySelectorAll(selector), shadows };
8
+ const groups = [];
9
+ let parts = [], token = "", depth = 0, quote = "", escaped = false, combinator = " ";
10
+ const flush = () => {
11
+ if (!token.trim()) return;
12
+ parts.push({ selector: token.trim(), combinator });
13
+ token = "";
14
+ combinator = " ";
12
15
  };
13
- const top = scan(root);
14
- if (top.shadows.length === 0) return Array.from(top.matches);
16
+ for (const char of selector) {
17
+ if (escaped) { token += char; escaped = false; continue; }
18
+ if (char === "\\") { token += char; escaped = true; continue; }
19
+ if (quote) { token += char; if (char === quote) quote = ""; continue; }
20
+ if (char === '"' || char === "'") { quote = char; token += char; continue; }
21
+ if (char === "[" || char === "(") depth++;
22
+ if (char === "]" || char === ")") depth--;
23
+ if (!depth && (char === "," || char === ">" || char === "+" || char === "~" || /\s/.test(char))) {
24
+ flush();
25
+ if (char === ",") { groups.push(parts); parts = []; combinator = " "; }
26
+ else if (!/\s/.test(char)) combinator = char;
27
+ } else token += char;
28
+ }
29
+ flush();
30
+ groups.push(parts);
31
+ // One compound per group matches the same nodes in every tree scope, so each scope stays a native query.
32
+ const simple = groups.every(parts => parts.length === 1 && !/^:scope\b/.test(parts[0].selector));
33
+ let rootSelector = selector;
34
+ if (!simple && root instanceof Element) {
35
+ const scopedSelectors = [];
36
+ for (const parts of groups) {
37
+ const first = parts[0].selector;
38
+ const rest = parts.slice(1).map(part => `${part.combinator} ${part.selector}`).join(" ");
39
+ const scoped = /^:scope\b/.test(first);
40
+ scopedSelectors.push(`${scoped ? "" : ":scope "}${first} ${rest}`);
41
+ if (!scoped && parts.length > 1 && root.matches(first)) scopedSelectors.push(`:scope ${rest}`);
42
+ }
43
+ rootSelector = scopedSelectors.join(", ");
44
+ }
45
+ const rootElements = root.querySelectorAll("*");
46
+ const rootMatches = rootSelector === "*" ? rootElements : root.querySelectorAll(rootSelector);
47
+ // A stack of open roots, popped depth first; the scope's own shadow root comes first.
48
+ const pending = [];
49
+ for (let index = rootElements.length - 1; index >= 0; index--) {
50
+ if (rootElements[index].shadowRoot) pending.push(rootElements[index].shadowRoot);
51
+ }
52
+ if (root instanceof Element && root.shadowRoot) pending.push(root.shadowRoot);
53
+ if (pending.length === 0) return Array.from(rootMatches);
15
54
  const results = [];
16
- const visit = ({ matches, shadows }) => {
17
- for (let index = 0; index < matches.length; index++) results.push(matches[index]);
18
- for (const shadow of shadows) visit(scan(shadow));
55
+ // Index loops, never spread: a scope can hold more nodes than the engine's argument limit.
56
+ for (let index = 0; index < rootMatches.length; index++) results.push(rootMatches[index]);
57
+ const parent = node => node.parentElement ?? node.getRootNode().host ?? null;
58
+ const scope = root instanceof Element ? root : root.documentElement;
59
+ const matches = (node, parts, index) => {
60
+ if (node === root && index > 0) return false;
61
+ const part = parts[index];
62
+ const scoped = /^:scope\b/.test(part.selector);
63
+ const compound = scoped ? part.selector.replace(/^:scope\b/, "*") : part.selector;
64
+ if (scoped && node !== scope) return false;
65
+ if (!node.matches(compound)) return false;
66
+ if (index === 0) return true;
67
+ if (part.combinator === ">") {
68
+ const ancestor = parent(node);
69
+ return !!ancestor && matches(ancestor, parts, index - 1);
70
+ }
71
+ if (part.combinator === "+") return !!node.previousElementSibling && matches(node.previousElementSibling, parts, index - 1);
72
+ if (part.combinator === "~") {
73
+ for (let sibling = node.previousElementSibling; sibling; sibling = sibling.previousElementSibling) {
74
+ if (matches(sibling, parts, index - 1)) return true;
75
+ }
76
+ return false;
77
+ }
78
+ for (let ancestor = parent(node); ancestor; ancestor = parent(ancestor)) {
79
+ if (matches(ancestor, parts, index - 1)) return true;
80
+ if (ancestor === root) break;
81
+ }
82
+ return false;
19
83
  };
20
- visit(top);
84
+ while (pending.length) {
85
+ const shadow = pending.pop();
86
+ const elements = shadow.querySelectorAll("*");
87
+ for (let index = elements.length - 1; index >= 0; index--) {
88
+ if (elements[index].shadowRoot) pending.push(elements[index].shadowRoot);
89
+ }
90
+ if (simple) {
91
+ const found = selector === "*" ? elements : shadow.querySelectorAll(selector);
92
+ for (let index = 0; index < found.length; index++) results.push(found[index]);
93
+ continue;
94
+ }
95
+ for (let index = 0; index < elements.length; index++) {
96
+ const node = elements[index];
97
+ if (groups.some(parts => matches(node, parts, parts.length - 1))) results.push(node);
98
+ }
99
+ }
21
100
  return results;
22
101
  }