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.
package/src/pipe.js CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  } from "./browser-process.js";
11
11
  import { BrowserConnection } from "./connection.js";
12
12
  import { Dialog, answerWithPolicy, normalizeDialogPolicy } from "./dialog-policy.js";
13
+ import { NulFrameReader } from "./nul-frames.js";
13
14
  import { targetCreationCapability } from "./internal-capability.js";
14
15
  import { SerialEmitter as Emittery } from "./serial-emitter.js";
15
16
  import { CdpCommandTimeoutError, CdpPipeClosedError, CdpSessionDetachedError, CdpSessionCrashedError } from "./cdp-errors.js";
@@ -25,7 +26,7 @@ export class PipeCdpClient {
25
26
  #child;
26
27
  #writeStream;
27
28
  #readStream;
28
- #buffer = Buffer.alloc(0);
29
+ #frames = new NulFrameReader();
29
30
  #seq = 1;
30
31
  #pending = new Map();
31
32
  #closedSessions = new Set();
@@ -83,6 +84,14 @@ export class PipeCdpClient {
83
84
  ...this.#spawnOptions,
84
85
  stdio,
85
86
  });
87
+ // A spawn that fails (missing or non-executable browserPath) has no pid and
88
+ // emits "error" instead of "spawn"; unheard, that error crashes the caller.
89
+ const spawnFailed = new Promise(resolve => this.#child.once("error", resolve));
90
+ if (this.#child.pid === undefined) {
91
+ const error = await spawnFailed;
92
+ this.#child = undefined;
93
+ throw error;
94
+ }
86
95
  const browserPid = this.#child.pid;
87
96
  // A helper process can keep an old launch's pipe open after that browser is
88
97
  // gone; its late events must never touch the launch that replaced it.
@@ -93,7 +102,7 @@ export class PipeCdpClient {
93
102
  this.#launchedAt = performance.now();
94
103
  this.#receivedBytes = 0;
95
104
  this.#malformedFrameCount = 0;
96
- this.#buffer = Buffer.alloc(0);
105
+ this.#frames = new NulFrameReader();
97
106
  this.#sessionTargets.clear();
98
107
  this.#closedSessions.clear();
99
108
  this.#child.once("exit", () => removeBrowserPidFile(profileDir, browserPid));
@@ -105,7 +114,11 @@ export class PipeCdpClient {
105
114
  stream.setEncoding("utf8");
106
115
  stream.on("data", (chunk) => {
107
116
  this.#stdioTail = (this.#stdioTail + chunk).slice(-STDIO_TAIL_LIMIT);
108
- if (stream === stderr) this.#stderrHead = (this.#stderrHead + chunk).slice(0, STDIO_TAIL_LIMIT);
117
+ // Only the first stderr line is read: stop growing the head once it holds
118
+ // a complete non-blank line or is full.
119
+ if (stream === stderr && this.#stderrHead.length < STDIO_TAIL_LIMIT && !this.#stderrHead.trimStart().includes("\n")) {
120
+ this.#stderrHead = (this.#stderrHead + chunk).slice(0, STDIO_TAIL_LIMIT);
121
+ }
109
122
  });
110
123
  stream.on("error", () => {});
111
124
  }
@@ -173,7 +186,12 @@ export class PipeCdpClient {
173
186
  lastError = error;
174
187
  }
175
188
  if (child.exitCode !== null || child.signalCode !== null) throw await this.#exitedBeforeReady(child, deadline);
176
- await Promise.race([new Promise(resolve => setTimeout(resolve, 100)), exited]);
189
+ let timer;
190
+ try {
191
+ await Promise.race([new Promise(resolve => { timer = setTimeout(resolve, 100); }), exited]);
192
+ } finally {
193
+ clearTimeout(timer);
194
+ }
177
195
  }
178
196
  const reason = lastError ? String(lastError.message ?? lastError) : "no response";
179
197
  const tail = this.#stdioTail.trim();
@@ -196,11 +214,15 @@ export class PipeCdpClient {
196
214
  }
197
215
  const how = child.signalCode ? `signal ${child.signalCode}` : `exit code ${child.exitCode}`;
198
216
  const firstLine = this.#stderrHead.split("\n").map(line => line.trim()).find(Boolean);
199
- const tail = this.#stdioTail.trim();
217
+ // The first line already follows the colon; drop its repeat from the tail.
218
+ const tailLines = this.#stdioTail.trim().split("\n");
219
+ const repeat = tailLines.findIndex(line => line.trim() === firstLine);
220
+ if (repeat !== -1) tailLines.splice(repeat, 1);
221
+ const tail = tailLines.join("\n").trim();
200
222
  return Error(
201
223
  `Browser exited before it became ready over the CDP pipe (${how})` +
202
224
  (firstLine ? `: ${firstLine}` : "") +
203
- (tail && tail !== firstLine ? `\nBrowser stdio tail:\n${tail}` : ""),
225
+ (tail ? `\nBrowser stdio tail:\n${tail}` : ""),
204
226
  );
205
227
  }
206
228
 
@@ -281,10 +303,15 @@ export class PipeCdpClient {
281
303
  this.#connected = false;
282
304
  this.#failAll(Error("CDP pipe client closed"));
283
305
  if (child.exitCode === null) {
284
- await Promise.race([
285
- exited,
286
- new Promise(resolve => setTimeout(resolve, GRACEFUL_CLOSE_TIMEOUT_MS)),
287
- ]);
306
+ let timer;
307
+ try {
308
+ await Promise.race([
309
+ exited,
310
+ new Promise(resolve => { timer = setTimeout(resolve, GRACEFUL_CLOSE_TIMEOUT_MS); }),
311
+ ]);
312
+ } finally {
313
+ clearTimeout(timer);
314
+ }
288
315
  }
289
316
  await terminateChild(child, { quitRequested });
290
317
  return;
@@ -295,11 +322,7 @@ export class PipeCdpClient {
295
322
 
296
323
  #onData(chunk) {
297
324
  this.#receivedBytes += chunk.length;
298
- this.#buffer = Buffer.concat([this.#buffer, chunk]);
299
- let idx;
300
- while ((idx = this.#buffer.indexOf(0)) !== -1) {
301
- const raw = this.#buffer.subarray(0, idx).toString("utf8");
302
- this.#buffer = this.#buffer.subarray(idx + 1);
325
+ for (const raw of this.#frames.push(chunk)) {
303
326
  if (raw.length === 0) continue;
304
327
  let msg;
305
328
  try { msg = JSON.parse(raw); } catch { this.#malformedFrameCount++; continue; }
@@ -327,14 +350,17 @@ export class PipeCdpClient {
327
350
  return;
328
351
  }
329
352
  if (typeof msg.method === "string") {
330
- if (msg.method === "Target.attachedToTarget") {
353
+ if (msg.method === "Target.attachedToTarget" && msg.params?.sessionId && msg.params.targetInfo?.targetId) {
331
354
  this.#sessionTargets.set(msg.params.sessionId, msg.params.targetInfo.targetId);
332
355
  } else if (msg.method === "Target.detachedFromTarget" && msg.params?.sessionId) {
333
356
  this.#failCommands(CdpSessionDetachedError, "CDP session detached", msg.params.sessionId);
334
357
  this.#sessionTargets.delete(msg.params.sessionId);
335
358
  } else if (msg.method === "Inspector.targetCrashed" && msg.sessionId) {
336
- this.#failCommands(CdpSessionCrashedError, "CDP session crashed", msg.sessionId);
337
- this.#sessionTargets.delete(msg.sessionId);
359
+ // The session outlives a renderer crash and Page.reload brings the target
360
+ // back: Chromium answers a pending reload, so leave it and keep the
361
+ // session's target. Commands the dead renderer held are answered only by a
362
+ // later reload, with "Target crashed"; reject those now.
363
+ this.#failCommands(CdpSessionCrashedError, "CDP session crashed", msg.sessionId, "Page.reload");
338
364
  }
339
365
  const meta = { sessionId: msg.sessionId };
340
366
  if (msg.method === "Page.javascriptDialogOpening" && msg.sessionId) {
@@ -363,9 +389,10 @@ export class PipeCdpClient {
363
389
  return new ErrorType(`${reason}: ${entry.method} (${context})`, details);
364
390
  }
365
391
 
366
- #failCommands(ErrorType, reason, sessionId) {
392
+ #failCommands(ErrorType, reason, sessionId, sparedMethod) {
367
393
  for (const [id, entry] of this.#pending) {
368
394
  if (sessionId !== undefined && entry.sessionId !== sessionId) continue;
395
+ if (entry.method === sparedMethod) continue;
369
396
  if (entry.timeout) clearTimeout(entry.timeout);
370
397
  this.#pending.delete(id);
371
398
  entry.reject(this.#commandError(ErrorType, reason, entry));
@@ -0,0 +1,64 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+
6
+ const execFileAsync = promisify(execFile);
7
+ const WINDOWS_START_TIME_TIMEOUT_MS = 15_000;
8
+ let ownStartTime;
9
+
10
+ // When the process holding `pid` started, in a form that only has to compare
11
+ // equal to itself on this machine; null when the platform cannot say. A dead
12
+ // holder's pid can be reused, and pid plus start time is what stays unique.
13
+ export async function processStartTime(pid) {
14
+ if (process.platform === "win32") {
15
+ if (!Number.isInteger(pid) || pid <= 0) return null;
16
+ // Win32_Process.CreationDate is readable for every process, not only the
17
+ // caller's own (Get-Process StartTime is not), and a reused pid usually
18
+ // belongs to someone else. FILETIME ticks keep the value locale-free.
19
+ // PowerShell is spawned by absolute path: a bare name resolves from the cwd
20
+ // before PATH, which another user may be able to write.
21
+ const systemRoot = process.env.SystemRoot || process.env.windir || "C:\\Windows";
22
+ try {
23
+ const { stdout } = await execFileAsync(
24
+ path.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
25
+ [
26
+ "-NoLogo",
27
+ "-NoProfile",
28
+ "-NonInteractive",
29
+ "-Command",
30
+ `(Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToFileTimeUtc()`,
31
+ ],
32
+ { timeout: WINDOWS_START_TIME_TIMEOUT_MS, windowsHide: true },
33
+ );
34
+ const ticks = String(stdout).trim();
35
+ return /^\d+$/.test(ticks) ? ticks : null;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+ if (process.platform === "linux") {
41
+ try {
42
+ const text = await readFile(`/proc/${pid}/stat`, "utf8");
43
+ // Field 22 (starttime); the fields after the parenthesised comm start at 3.
44
+ return text.slice(text.lastIndexOf(")") + 2).split(" ")[19] ?? null;
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+ try {
50
+ const { stdout } = await execFileAsync("ps", ["-o", "lstart=", "-p", String(pid)], {
51
+ env: { ...process.env, LC_ALL: "C", TZ: "UTC" },
52
+ });
53
+ return stdout.trim() || null;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ // This process's own start time, looked up once: on Windows each lookup is a
60
+ // PowerShell call.
61
+ export function ownProcessStartTime() {
62
+ ownStartTime ??= processStartTime(process.pid);
63
+ return ownStartTime;
64
+ }
@@ -116,10 +116,16 @@ function lease(key, entry, connection) {
116
116
  });
117
117
  const client = connection.cdp;
118
118
  // Transport events reach every holder: through a handle, clearListeners
119
- // removes only that handle's listeners and emit is refused.
119
+ // removes only that handle's listeners and emit is refused. The emitter keys
120
+ // listeners by function, so each registration gets a function of its own:
121
+ // two holders adding the same function never share one entry that either
122
+ // could remove (#140).
120
123
  const transportEvents = new Proxy(client.transportEvents, readOnly("the shared transport events", (target, property) => {
121
124
  ensureOpen(property);
122
- if (property === "on") return tracked(target.on.bind(target), subscriptions, transportSubscriptions);
125
+ if (property === "on") {
126
+ const on = (name, listener) => target.on(name, (event) => listener(event));
127
+ return tracked(on, subscriptions, transportSubscriptions);
128
+ }
123
129
  if (property === "clearListeners") return () => unsubscribeAll(transportSubscriptions);
124
130
  if (property === "emit") {
125
131
  return () => {
@@ -138,7 +144,8 @@ function lease(key, entry, connection) {
138
144
  }));
139
145
  return new Proxy(connection, {
140
146
  get(target, property) {
141
- if (property === "close") return close;
147
+ // Disposing a lease releases only this holder, like close() (#244).
148
+ if (property === "close" || property === Symbol.asyncDispose) return close;
142
149
  ensureOpen(property);
143
150
  if (property === "setDialogPolicy") return setDialogPolicy;
144
151
  if (property === "cdp") return clientView;
@@ -0,0 +1,101 @@
1
+ // Self-contained: locator queries serialize this factory into the document's world.
2
+ // Playwright's selectorUtils/createTextMatcher and roleUtils define the matching and naming rules.
3
+ export function createTextMatching(isHidden = () => false, getRole = () => "", includeHidden = false) {
4
+ const normalize = value => String(value ?? "").replace(/[\u200b\u00ad]/g, "").trim().replace(/\s+/g, " ");
5
+ const matches = (value, matcher) => {
6
+ if (matcher instanceof RegExp) {
7
+ matcher.lastIndex = 0;
8
+ return matcher.test(value);
9
+ }
10
+ const text = normalize(value);
11
+ return "exact" in matcher
12
+ ? text === normalize(matcher.exact)
13
+ : text.toLowerCase().includes(normalize(matcher.contains).toLowerCase());
14
+ };
15
+ const skipped = node => ["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT"].includes(node.nodeName) ||
16
+ !!node.ownerDocument?.head?.contains(node);
17
+ const textCache = new Map();
18
+ const text = node => {
19
+ if (textCache.has(node)) return textCache.get(node);
20
+ let value = "";
21
+ if (!skipped(node)) {
22
+ if (node.nodeName === "INPUT" && ["submit", "button", "reset"].includes(node.type)) value = node.value;
23
+ else {
24
+ for (const child of node.childNodes) {
25
+ if (child.nodeType === 3) value += child.nodeValue;
26
+ else if (child.nodeType === 1) value += text(child);
27
+ }
28
+ if (node.shadowRoot) value += text(node.shadowRoot);
29
+ }
30
+ }
31
+ textCache.set(node, value);
32
+ return value;
33
+ };
34
+ const matchesText = (node, matcher) => !skipped(node) && matches(text(node), matcher);
35
+ const labelledBy = node => {
36
+ const refs = node.ariaLabelledByElements ?? (node.getAttribute("aria-labelledby") ?? "")
37
+ .trim().split(/\s+/).filter(Boolean).map(id => node.getRootNode().getElementById?.(id)).filter(Boolean);
38
+ return refs.length ? [...new Set(refs)] : null;
39
+ };
40
+ const labels = node => {
41
+ const refs = labelledBy(node);
42
+ if (refs) return refs.map(text);
43
+ const ariaLabel = node.getAttribute("aria-label");
44
+ if (ariaLabel?.trim()) return [ariaLabel];
45
+ return Array.from(node.labels ?? [], text);
46
+ };
47
+ const contentRoles = new Set(["button", "cell", "checkbox", "columnheader", "gridcell", "heading", "link",
48
+ "menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio", "row", "rowheader", "switch",
49
+ "tab", "tooltip", "treeitem"]);
50
+ const prohibitedRoles = new Set(["caption", "code", "definition", "deletion", "emphasis", "generic",
51
+ "insertion", "mark", "paragraph", "presentation", "strong", "subscript", "suggestion", "superscript", "term", "time"]);
52
+ const accessibleName = node => {
53
+ const visited = new Set();
54
+ const alternative = (element, referenced = false, hiddenReference = false, descendant = false, inLabelledBy = false) => {
55
+ if (visited.has(element) || skipped(element)) return "";
56
+ if (!includeHidden && !hiddenReference && isHidden(element)) return "";
57
+ visited.add(element);
58
+ const refs = labelledBy(element);
59
+ if (refs && !inLabelledBy) {
60
+ const value = refs.map(ref => alternative(ref, true, isHidden(ref), false, true)).join(" ");
61
+ if (value) return value;
62
+ }
63
+ const ariaLabel = element.getAttribute("aria-label");
64
+ if (ariaLabel?.trim()) return ariaLabel;
65
+ const tag = element.nodeName;
66
+ if (tag === "INPUT" && ["button", "submit", "reset"].includes(element.type))
67
+ return element.value || ({ submit: "Submit", reset: "Reset" }[element.type]) || element.getAttribute("title") || "";
68
+ if (element.labels?.length && !inLabelledBy)
69
+ return Array.from(element.labels, label => alternative(label, true, isHidden(label))).join(" ");
70
+ if (tag === "IMG" || tag === "AREA" || (tag === "INPUT" && element.type === "image"))
71
+ return element.getAttribute("alt") || element.getAttribute("title") || (tag === "INPUT" ? "Submit" : "");
72
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") {
73
+ if (descendant && ["INPUT", "TEXTAREA"].includes(tag)) return element.value;
74
+ if (tag === "INPUT" && element.type === "file") return "Choose File";
75
+ const usePlaceholder = tag === "TEXTAREA" || ["text", "password", "number", "search", "tel", "email", "url"].includes(element.type);
76
+ return element.getAttribute("title") || (usePlaceholder ? element.getAttribute("placeholder") : "") || "";
77
+ }
78
+ const nativeChild = { FIELDSET: "LEGEND", FIGURE: "FIGCAPTION", TABLE: "CAPTION", SVG: "title" }[tag];
79
+ const child = nativeChild && Array.from(element.children).find(child => child.nodeName === nativeChild);
80
+ if (child) return alternative(child, true, isHidden(child));
81
+ if (referenced || descendant || tag === "SUMMARY" || contentRoles.has(getRole(element))) {
82
+ let value = "";
83
+ const assigned = tag === "SLOT" ? element.assignedNodes() : [];
84
+ const children = assigned.length ? assigned : [...element.childNodes, ...(element.shadowRoot?.childNodes ?? [])];
85
+ for (const child of children) {
86
+ if (!assigned.length && child.assignedSlot) continue;
87
+ if (child.nodeType === 3) value += child.nodeValue;
88
+ else if (child.nodeType === 1) {
89
+ const token = alternative(child, referenced, hiddenReference, true, inLabelledBy);
90
+ const display = child.ownerDocument.defaultView.getComputedStyle(child).display;
91
+ value += display !== "inline" || child.nodeName === "BR" ? ` ${token} ` : token;
92
+ }
93
+ }
94
+ if (normalize(value)) return value;
95
+ }
96
+ return element.getAttribute("title") || "";
97
+ };
98
+ return prohibitedRoles.has(getRole(node)) ? "" : normalize(alternative(node));
99
+ };
100
+ return { normalize, matches, skipped, text, matchesText, labels, accessibleName };
101
+ }
package/src/viewport.js CHANGED
@@ -6,7 +6,7 @@ function validateViewport(viewport) {
6
6
  }
7
7
  export async function repinViewport(page, viewport, options = {}) {
8
8
  const size = validateViewport(viewport); const sessionId = await page.resolveSessionId();
9
- await page.cdp.send("Emulation.setDeviceMetricsOverride", { ...size, deviceScaleFactor: options.deviceScaleFactor ?? 1, mobile: options.mobile ?? false }, sessionId);
9
+ await page.cdp.send("Emulation.setDeviceMetricsOverride", { ...size, screenWidth: size.width, screenHeight: size.height, deviceScaleFactor: options.deviceScaleFactor ?? 1, mobile: options.mobile ?? false }, sessionId);
10
10
  page.setCachedViewportSize(size); return { ...size };
11
11
  }
12
12
  export { validateViewport };
package/src/lock-file.js DELETED
@@ -1,130 +0,0 @@
1
- import { execFile } from "node:child_process";
2
- import { randomUUID } from "node:crypto";
3
- import { link, open, readFile, unlink } from "node:fs/promises";
4
- import path from "node:path";
5
- import { promisify } from "node:util";
6
- import { restrictNewFileToOwner } from "./owner-only.js";
7
-
8
- const execFileAsync = promisify(execFile);
9
- const WINDOWS_START_TIME_TIMEOUT_MS = 15_000;
10
- let ownStartTime;
11
-
12
- // When the process holding `pid` started, in a form that only has to compare
13
- // equal to itself on this machine; null when the platform cannot say. A dead
14
- // holder's pid can be reused, and pid plus start time is what stays unique.
15
- export async function processStartTime(pid) {
16
- if (process.platform === "win32") {
17
- if (!Number.isInteger(pid) || pid <= 0) return null;
18
- // Win32_Process.CreationDate is readable for every process, not only the
19
- // caller's own (Get-Process StartTime is not), and a reused pid usually
20
- // belongs to someone else. FILETIME ticks keep the value locale-free.
21
- // PowerShell is spawned by absolute path: a bare name resolves from the cwd
22
- // before PATH, which another user may be able to write.
23
- const systemRoot = process.env.SystemRoot || process.env.windir || "C:\\Windows";
24
- try {
25
- const { stdout } = await execFileAsync(
26
- path.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
27
- [
28
- "-NoLogo",
29
- "-NoProfile",
30
- "-NonInteractive",
31
- "-Command",
32
- `(Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToFileTimeUtc()`,
33
- ],
34
- { timeout: WINDOWS_START_TIME_TIMEOUT_MS, windowsHide: true },
35
- );
36
- const ticks = String(stdout).trim();
37
- return /^\d+$/.test(ticks) ? ticks : null;
38
- } catch {
39
- return null;
40
- }
41
- }
42
- if (process.platform === "linux") {
43
- try {
44
- const text = await readFile(`/proc/${pid}/stat`, "utf8");
45
- // Field 22 (starttime); the fields after the parenthesised comm start at 3.
46
- return text.slice(text.lastIndexOf(")") + 2).split(" ")[19] ?? null;
47
- } catch {
48
- return null;
49
- }
50
- }
51
- try {
52
- const { stdout } = await execFileAsync("ps", ["-o", "lstart=", "-p", String(pid)], {
53
- env: { ...process.env, LC_ALL: "C", TZ: "UTC" },
54
- });
55
- return stdout.trim() || null;
56
- } catch {
57
- return null;
58
- }
59
- }
60
-
61
- // This process's own start time, looked up once: on Windows each lookup is a
62
- // PowerShell call.
63
- export function ownProcessStartTime() {
64
- ownStartTime ??= processStartTime(process.pid);
65
- return ownStartTime;
66
- }
67
-
68
- // Build the lock out of sight and hard-link it into place, so a lock file is
69
- // never visible half-written: a reader either misses it or reads it whole.
70
- // Returns the inode and token that identify our lock, or null when the path is taken.
71
- export async function createLock(lockPath) {
72
- const ownStart = ownProcessStartTime();
73
- const token = randomUUID();
74
- const tempPath = `${lockPath}.${process.pid}.${randomUUID()}.tmp`;
75
- let handle;
76
- try {
77
- handle = await open(tempPath, "wx", 0o600);
78
- await handle.writeFile(
79
- `${JSON.stringify({ pid: process.pid, start: await ownStart, token, acquiredAt: new Date().toISOString() })}\n`,
80
- "utf8",
81
- );
82
- const { ino } = await handle.stat();
83
- await handle.close();
84
- handle = null;
85
- await restrictNewFileToOwner(tempPath);
86
- try {
87
- await link(tempPath, lockPath);
88
- } catch (error) {
89
- if (error?.code === "EEXIST") return null;
90
- throw error;
91
- }
92
- return { ino, token };
93
- } finally {
94
- await handle?.close().catch(() => {});
95
- await unlink(tempPath).catch(() => {});
96
- }
97
- }
98
-
99
- // Content and inode come from one open handle, so the identity we act on is
100
- // bound to the exact file we inspected rather than to the path.
101
- export async function readLockState(lockPath) {
102
- let handle;
103
- try {
104
- handle = await open(lockPath, "r");
105
- } catch (error) {
106
- if (error?.code === "ENOENT") return null;
107
- throw error;
108
- }
109
- try {
110
- const stats = await handle.stat();
111
- const text = await handle.readFile("utf8");
112
- const state = { ino: stats.ino, mtimeMs: stats.mtimeMs, pid: null, start: null, token: null };
113
- try {
114
- const value = JSON.parse(text);
115
- if (Number.isInteger(value?.pid) && value.pid > 0) state.pid = value.pid;
116
- if (typeof value?.start === "string") state.start = value.start;
117
- if (typeof value?.token === "string") state.token = value.token;
118
- } catch {
119
- // No identity: an empty or partial lock is aged out, never reclaimed on
120
- // the spot, because a live contender may have just created it.
121
- }
122
- return state;
123
- } finally {
124
- await handle.close().catch(() => {});
125
- }
126
- }
127
-
128
- export function isSameLock(state, ino, token) {
129
- return state !== null && state.ino === ino && state.token === token;
130
- }