@ricsam/r5d-browser 0.0.50 → 0.0.53

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,261 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ const MAX_DOWNLOAD_CHUNK_BYTES = 1024 * 1024;
4
+ class BrowserRuntime {
5
+ constructor(context, downloadsPath) {
6
+ this.context = context;
7
+ this.downloadsPath = downloadsPath;
8
+ fs.mkdirSync(downloadsPath, { recursive: true });
9
+ for (const page of context.pages()) this.track(page);
10
+ context.on("page", (page) => this.track(page));
11
+ }
12
+ context;
13
+ downloadsPath;
14
+ ids = /* @__PURE__ */ new WeakMap();
15
+ pages = /* @__PURE__ */ new Map();
16
+ cursor = /* @__PURE__ */ new Map();
17
+ downloadSaveQueue = Promise.resolve();
18
+ track(page) {
19
+ const existing = this.ids.get(page);
20
+ if (existing) return existing;
21
+ const id = crypto.randomUUID();
22
+ this.ids.set(page, id);
23
+ this.pages.set(id, page);
24
+ page.on("download", (download) => {
25
+ this.downloadSaveQueue = this.downloadSaveQueue.then(() => this.persistDownload(download)).catch((error) => {
26
+ process.stderr.write(`[r5d-browser] failed to save download: ${error instanceof Error ? error.message : String(error)}
27
+ `);
28
+ });
29
+ });
30
+ page.once("close", () => {
31
+ this.pages.delete(id);
32
+ this.cursor.delete(id);
33
+ });
34
+ return id;
35
+ }
36
+ safeDownloadFilename(suggestedFilename) {
37
+ const basename = path.basename(suggestedFilename).replace(/[\\/\0]/g, "-").trim();
38
+ if (!basename || basename === "." || basename === "..") return "download";
39
+ const extension = path.extname(basename).slice(0, 30);
40
+ let stem = basename.slice(0, basename.length - path.extname(basename).length) || "download";
41
+ while (Buffer.byteLength(`${stem}${extension}`) > 200) stem = stem.slice(0, -1);
42
+ return `${stem || "download"}${extension}`;
43
+ }
44
+ availableDownloadPath(suggestedFilename) {
45
+ const filename = this.safeDownloadFilename(suggestedFilename);
46
+ const extension = path.extname(filename);
47
+ const stem = filename.slice(0, filename.length - extension.length) || "download";
48
+ for (let suffix = 1; ; suffix += 1) {
49
+ const candidate = suffix === 1 ? filename : `${stem}-${suffix}${extension}`;
50
+ const candidatePath = path.join(this.downloadsPath, candidate);
51
+ if (!fs.existsSync(candidatePath)) return candidatePath;
52
+ }
53
+ }
54
+ async persistDownload(download) {
55
+ const failure = await download.failure();
56
+ if (failure) throw new Error(failure);
57
+ const targetPath = this.availableDownloadPath(download.suggestedFilename());
58
+ await download.saveAs(targetPath);
59
+ process.stdout.write(`[r5d-browser] downloaded ${path.basename(targetPath)}
60
+ `);
61
+ }
62
+ downloadId(filename) {
63
+ return Buffer.from(filename, "utf8").toString("base64url");
64
+ }
65
+ resolveDownload(downloadId) {
66
+ if (typeof downloadId !== "string" || !downloadId) throw new Error("downloadId is required.");
67
+ const filename = Buffer.from(downloadId, "base64url").toString("utf8");
68
+ if (this.downloadId(filename) !== downloadId || filename !== path.basename(filename) || filename.includes("\0")) {
69
+ throw new Error("Invalid downloadId.");
70
+ }
71
+ const filePath = path.join(this.downloadsPath, filename);
72
+ let stats;
73
+ try {
74
+ stats = fs.lstatSync(filePath);
75
+ } catch {
76
+ throw new Error(`Browser download ${downloadId} no longer exists.`);
77
+ }
78
+ if (!stats.isFile() || stats.isSymbolicLink()) throw new Error("Browser download is not a regular file.");
79
+ return { filename, filePath, stats };
80
+ }
81
+ async listDownloads() {
82
+ await this.downloadSaveQueue;
83
+ return fs.readdirSync(this.downloadsPath, { withFileTypes: true }).flatMap((entry) => {
84
+ if (!entry.isFile() || entry.name.startsWith(".")) return [];
85
+ const { filename, stats } = this.resolveDownload(this.downloadId(entry.name));
86
+ return [
87
+ {
88
+ downloadId: this.downloadId(filename),
89
+ filename,
90
+ size: stats.size,
91
+ modifiedAt: stats.mtime.toISOString()
92
+ }
93
+ ];
94
+ }).sort((left, right) => right.modifiedAt.localeCompare(left.modifiedAt) || left.filename.localeCompare(right.filename));
95
+ }
96
+ async getDownloadChunk(input) {
97
+ await this.downloadSaveQueue;
98
+ const { filename, filePath, stats } = this.resolveDownload(input.downloadId);
99
+ const offset = input.offset === void 0 ? 0 : Number(input.offset);
100
+ const requestedBytes = input.maxBytes === void 0 ? MAX_DOWNLOAD_CHUNK_BYTES : Number(input.maxBytes);
101
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > stats.size) throw new Error("Invalid download offset.");
102
+ if (!Number.isSafeInteger(requestedBytes) || requestedBytes < 1) throw new Error("Invalid download chunk size.");
103
+ const chunkSize = Math.min(requestedBytes, MAX_DOWNLOAD_CHUNK_BYTES, stats.size - offset);
104
+ const bytes = Buffer.alloc(chunkSize);
105
+ const handle = fs.openSync(filePath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
106
+ let bytesRead = 0;
107
+ try {
108
+ const openedStats = fs.fstatSync(handle);
109
+ if (!openedStats.isFile() || openedStats.dev !== stats.dev || openedStats.ino !== stats.ino) {
110
+ throw new Error("Browser download changed before it could be read.");
111
+ }
112
+ bytesRead = fs.readSync(handle, bytes, 0, chunkSize, offset);
113
+ const completedStats = fs.fstatSync(handle);
114
+ if (completedStats.size !== stats.size || completedStats.mtimeMs !== stats.mtimeMs) {
115
+ throw new Error("Browser download changed while it was being read.");
116
+ }
117
+ } finally {
118
+ fs.closeSync(handle);
119
+ }
120
+ const nextOffset = offset + bytesRead;
121
+ return {
122
+ downloadId: this.downloadId(filename),
123
+ filename,
124
+ size: stats.size,
125
+ modifiedAt: stats.mtime.toISOString(),
126
+ offset,
127
+ nextOffset,
128
+ eof: nextOffset === stats.size,
129
+ base64: bytes.subarray(0, bytesRead).toString("base64")
130
+ };
131
+ }
132
+ page(tabId) {
133
+ if (typeof tabId !== "string") throw new Error("tabId is required.");
134
+ const page = this.pages.get(tabId);
135
+ if (!page || page.isClosed()) throw new Error(`Browser tab ${tabId} is no longer open.`);
136
+ return page;
137
+ }
138
+ async tabInfo(page) {
139
+ const tabId = this.track(page);
140
+ let windowId = "unknown";
141
+ try {
142
+ const cdp = await this.context.newCDPSession(page);
143
+ const result = await cdp.send("Browser.getWindowForTarget");
144
+ windowId = String(result.windowId);
145
+ await cdp.detach();
146
+ } catch {
147
+ }
148
+ return { tabId, windowId, title: await page.title().catch(() => ""), url: page.url() };
149
+ }
150
+ async listTabs() {
151
+ return await Promise.all([...this.pages.values()].filter((page) => !page.isClosed()).map((page) => this.tabInfo(page)));
152
+ }
153
+ async drainDownloads() {
154
+ await this.downloadSaveQueue;
155
+ }
156
+ async execute(action, input) {
157
+ if (action === "list_tabs") return { tabs: await this.listTabs() };
158
+ if (action === "list_downloads") return { downloads: await this.listDownloads() };
159
+ if (action === "get_download") return await this.getDownloadChunk(input);
160
+ if (action === "open_tab") {
161
+ const previous = this.context.pages().findLast((candidate) => !candidate.isClosed());
162
+ let page2;
163
+ if (previous) {
164
+ const cdp = await this.context.newCDPSession(previous);
165
+ const pagePromise = this.context.waitForEvent("page");
166
+ await cdp.send("Target.createTarget", {
167
+ url: "about:blank",
168
+ newWindow: input.disposition === "window",
169
+ background: true
170
+ });
171
+ page2 = await pagePromise;
172
+ await cdp.detach();
173
+ if (input.disposition === "window") {
174
+ const pageCdp = await this.context.newCDPSession(page2);
175
+ const { windowId } = await pageCdp.send("Browser.getWindowForTarget");
176
+ await pageCdp.send("Browser.setWindowBounds", { windowId, bounds: { windowState: "minimized" } });
177
+ await pageCdp.detach();
178
+ }
179
+ } else {
180
+ page2 = await this.context.newPage();
181
+ }
182
+ const url = typeof input.url === "string" ? input.url : "about:blank";
183
+ if (url !== "about:blank") await page2.goto(url, { waitUntil: "domcontentloaded" });
184
+ return { tab: await this.tabInfo(page2) };
185
+ }
186
+ const page = this.page(input.tabId);
187
+ const tabId = input.tabId;
188
+ switch (action) {
189
+ case "close_tab":
190
+ await page.close();
191
+ return { closed: true, tabId };
192
+ case "navigate":
193
+ await page.goto(String(input.url), { waitUntil: "domcontentloaded" });
194
+ return { tab: await this.tabInfo(page) };
195
+ case "screenshot": {
196
+ const bytes = await page.screenshot({ type: "png" });
197
+ const viewport = page.viewportSize();
198
+ const cursor = this.cursor.get(tabId);
199
+ return {
200
+ base64: bytes.toString("base64"),
201
+ width: viewport?.width ?? Number(await page.evaluate(() => window.innerWidth)),
202
+ height: viewport?.height ?? Number(await page.evaluate(() => window.innerHeight)),
203
+ cursorX: cursor?.x,
204
+ cursorY: cursor?.y
205
+ };
206
+ }
207
+ case "move_mouse": {
208
+ const x = Number(input.x);
209
+ const y = Number(input.y);
210
+ if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error("move_mouse requires numeric x and y coordinates.");
211
+ await page.mouse.move(x, y);
212
+ this.cursor.set(tabId, { x, y });
213
+ return { tabId, x, y };
214
+ }
215
+ case "mouse_click": {
216
+ const cursor = this.cursor.get(tabId);
217
+ if (!cursor) throw new Error("Move the mouse in this tab before clicking.");
218
+ const button = input.button === "middle" || input.button === "right" ? input.button : "left";
219
+ await page.mouse.click(cursor.x, cursor.y, { button, clickCount: input.clickCount === 2 ? 2 : 1 });
220
+ return { tabId, ...cursor, button };
221
+ }
222
+ case "keyboard": {
223
+ const keys = Array.isArray(input.keys) ? input.keys : [];
224
+ const modifiers = Array.isArray(input.modifiers) ? input.modifiers.filter((value) => typeof value === "string") : [];
225
+ for (const modifier of modifiers) await page.keyboard.down(modifier);
226
+ try {
227
+ for (const key of keys) {
228
+ if (typeof key !== "string") throw new Error("keyboard keys must all be strings.");
229
+ await page.keyboard.press(key);
230
+ }
231
+ } finally {
232
+ for (const modifier of modifiers.toReversed()) await page.keyboard.up(modifier);
233
+ }
234
+ return { tabId, keys, modifiers };
235
+ }
236
+ case "keyboard_type":
237
+ if (typeof input.text !== "string") throw new Error("keyboard_type requires text.");
238
+ await page.keyboard.insertText(input.text);
239
+ return { tabId, characters: input.text.length };
240
+ case "run_js": {
241
+ if (typeof input.code !== "string") throw new Error("run_js requires code.");
242
+ const result = await page.evaluate(async (code) => {
243
+ const invoke = new Function(`"use strict"; return (async () => {
244
+ ${code}
245
+ })()`);
246
+ return await invoke();
247
+ }, input.code);
248
+ const serialized = JSON.stringify(result);
249
+ if (serialized && Buffer.byteLength(serialized) > 1024 * 1024) {
250
+ throw new Error("Browser JavaScript result exceeded the 1 MiB limit.");
251
+ }
252
+ return { tabId, result };
253
+ }
254
+ default:
255
+ throw new Error(`Unsupported browser operation: ${action}`);
256
+ }
257
+ }
258
+ }
259
+ export {
260
+ BrowserRuntime
261
+ };