@nexum-hub/browser 0.0.0-stage → 0.0.2

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 (100) hide show
  1. package/README.md +22 -2
  2. package/browser-extension/assets.js +654 -0
  3. package/browser-extension/build.mjs +111 -0
  4. package/browser-extension/clipboard.js +397 -0
  5. package/browser-extension/connection.js +880 -0
  6. package/browser-extension/dist/development/assets.js +654 -0
  7. package/browser-extension/dist/development/clipboard.js +397 -0
  8. package/browser-extension/dist/development/connection.js +880 -0
  9. package/browser-extension/dist/development/errors.js +106 -0
  10. package/browser-extension/dist/development/evaluate.js +160 -0
  11. package/browser-extension/dist/development/frames.js +256 -0
  12. package/browser-extension/dist/development/keyboard.js +167 -0
  13. package/browser-extension/dist/development/manifest.json +35 -0
  14. package/browser-extension/dist/development/native-node.js +85 -0
  15. package/browser-extension/dist/development/page-data.js +497 -0
  16. package/browser-extension/dist/development/page.js +772 -0
  17. package/browser-extension/dist/development/profile.js +2 -0
  18. package/browser-extension/dist/development/router.js +5961 -0
  19. package/browser-extension/dist/development/site-source.js +149 -0
  20. package/browser-extension/dist/development/transport.js +405 -0
  21. package/browser-extension/dist/development/visual.js +976 -0
  22. package/browser-extension/dist/development/worker.js +24 -0
  23. package/browser-extension/dist/production/assets.js +654 -0
  24. package/browser-extension/dist/production/clipboard.js +397 -0
  25. package/browser-extension/dist/production/connection.js +880 -0
  26. package/browser-extension/dist/production/errors.js +106 -0
  27. package/browser-extension/dist/production/evaluate.js +160 -0
  28. package/browser-extension/dist/production/frames.js +256 -0
  29. package/browser-extension/dist/production/keyboard.js +167 -0
  30. package/browser-extension/dist/production/manifest.json +35 -0
  31. package/browser-extension/dist/production/native-node.js +85 -0
  32. package/browser-extension/dist/production/page-data.js +497 -0
  33. package/browser-extension/dist/production/page.js +772 -0
  34. package/browser-extension/dist/production/profile.js +2 -0
  35. package/browser-extension/dist/production/router.js +5961 -0
  36. package/browser-extension/dist/production/site-source.js +149 -0
  37. package/browser-extension/dist/production/transport.js +405 -0
  38. package/browser-extension/dist/production/visual.js +976 -0
  39. package/browser-extension/dist/production/worker.js +24 -0
  40. package/browser-extension/errors.js +106 -0
  41. package/browser-extension/evaluate.js +160 -0
  42. package/browser-extension/frames.js +256 -0
  43. package/browser-extension/keyboard.js +167 -0
  44. package/browser-extension/native-node.js +85 -0
  45. package/browser-extension/page-data.js +497 -0
  46. package/browser-extension/page.js +772 -0
  47. package/browser-extension/release-info.json +21 -0
  48. package/browser-extension/route-manifest.json +807 -0
  49. package/browser-extension/router.js +5961 -0
  50. package/browser-extension/site-source.js +149 -0
  51. package/browser-extension/transport.js +405 -0
  52. package/browser-extension/visual.js +976 -0
  53. package/browser-extension/worker.js +24 -0
  54. package/dist/client/index.d.ts +6 -0
  55. package/dist/client/index.js +894 -0
  56. package/dist/client/index.js.map +1 -0
  57. package/dist/client/routes.d.ts +6 -0
  58. package/dist/client/routes.js +777 -0
  59. package/dist/client/routes.js.map +1 -0
  60. package/dist/client/serialize.d.ts +16 -0
  61. package/dist/client/serialize.js +355 -0
  62. package/dist/client/serialize.js.map +1 -0
  63. package/dist/client/types.d.ts +1342 -0
  64. package/dist/client/types.js +2 -0
  65. package/dist/client/types.js.map +1 -0
  66. package/dist/extension/artifacts.d.ts +60 -0
  67. package/dist/extension/artifacts.js +493 -0
  68. package/dist/extension/artifacts.js.map +1 -0
  69. package/dist/extension/assets.d.ts +10 -0
  70. package/dist/extension/assets.js +90 -0
  71. package/dist/extension/assets.js.map +1 -0
  72. package/dist/extension/batch.d.ts +6 -0
  73. package/dist/extension/batch.js +138 -0
  74. package/dist/extension/batch.js.map +1 -0
  75. package/dist/extension/files.d.ts +16 -0
  76. package/dist/extension/files.js +594 -0
  77. package/dist/extension/files.js.map +1 -0
  78. package/dist/extension/index.d.ts +3 -0
  79. package/dist/extension/index.js +623 -0
  80. package/dist/extension/index.js.map +1 -0
  81. package/dist/extension/protocol.d.ts +81 -0
  82. package/dist/extension/protocol.js +475 -0
  83. package/dist/extension/protocol.js.map +1 -0
  84. package/dist/extension/scope.d.ts +55 -0
  85. package/dist/extension/scope.js +563 -0
  86. package/dist/extension/scope.js.map +1 -0
  87. package/dist/extension/service.d.ts +113 -0
  88. package/dist/extension/service.js +905 -0
  89. package/dist/extension/service.js.map +1 -0
  90. package/docs/README.md +10 -0
  91. package/docs/api.md +1375 -0
  92. package/docs/connection.md +9 -0
  93. package/docs/lifecycle.md +17 -0
  94. package/docs/usage.md +75 -0
  95. package/implementation.json +2962 -0
  96. package/instructions/README.md +8 -0
  97. package/package.json +80 -4
  98. package/scripts/discover.js +12 -0
  99. package/scripts/screenshot.js +9 -0
  100. package/skills/browser-control/SKILL.md +12 -0
package/README.md CHANGED
@@ -1,3 +1,23 @@
1
- # Temporary Holding Version
1
+ # Nexum browser
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 这是 Nexum 的可选浏览器客户端、受管扩展与匹配 MV3 插件源码。Agent 默认不安装或启用它;普通 `import "@nexum-hub/browser"` 和 `createBrowserClient(browser)` 不监听端口、不扫描浏览器。
4
+
5
+ 本包当前处于开发验证阶段,计划先通过 npm 的 `next` 标签发行。客户端接口、Node loopback 服务和 MV3 原生路由正在组合验证;本机 fixture 结果不表示真实 Chrome/Edge、全部高阶能力或 npm 发行已验收。当前进度与具体缺口见 [实现台账](implementation.json)。
6
+
7
+ 普通入口:
8
+
9
+ ```javascript
10
+ import { createBrowserClient } from "@nexum-hub/browser";
11
+ const client = createBrowserClient(browser);
12
+ const choices = await client.browsers.list();
13
+ const selected = await client.browsers.get(choices[0].id);
14
+ const tabs = await selected.tabs.list();
15
+ const tab = await selected.tabs.get(tabs[0].id);
16
+ return await tab.playwright.domSnapshot();
17
+ ```
18
+
19
+ `browser` 来自当前运行注入的受管方法表。普通 Node 客户端只构造公开门面;实际 I/O 逐项调用已经注册的公共扩展方法。未实现或未注册的方法明确失败。
20
+
21
+ 平台注册入口为 `@nexum-hub/browser/nexum` 的默认 `createExtension(host)`。它只使用 `@nexum-hub/sdk` 当前公开类型和标准 Node/WS。模块顶层不初始化服务,工厂先登记冷资源,启用成功才监听本 profile 固定 loopback 端口。
22
+
23
+ [使用手册](docs/README.md) · [连接](docs/connection.md) · [生命周期](docs/lifecycle.md)
@@ -0,0 +1,654 @@
1
+ import {
2
+ BrowserActionError,
3
+ requireValue,
4
+ record,
5
+ text,
6
+ nativeId,
7
+ } from "./errors.js";
8
+ import { readPageBytes } from "./page-data.js";
9
+ import { observeSiteSource } from "./site-source.js";
10
+
11
+ const maximum = 128 * 1024 * 1024;
12
+ // Office exports are ZIP documents: confirm their actual central-directory parts, not merely a PK prefix.
13
+ function officeArchive(data, format) {
14
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength),
15
+ names = new Set();
16
+ let end = -1;
17
+ for (let at = data.length - 22; at >= Math.max(0, data.length - 65557); at--)
18
+ if (
19
+ view.getUint32(at, true) === 0x06054b50 &&
20
+ at + 22 + view.getUint16(at + 20, true) === data.length
21
+ ) {
22
+ end = at;
23
+ break;
24
+ }
25
+ if (
26
+ end < 0 ||
27
+ view.getUint16(end + 4, true) !== 0 ||
28
+ view.getUint16(end + 6, true) !== 0
29
+ )
30
+ return false;
31
+ const count = view.getUint16(end + 10, true),
32
+ size = view.getUint32(end + 12, true),
33
+ offset = view.getUint32(end + 16, true);
34
+ if (
35
+ count === 65535 ||
36
+ count !== view.getUint16(end + 8, true) ||
37
+ offset + size !== end
38
+ )
39
+ return false;
40
+ let at = offset;
41
+ for (let index = 0; index < count; index++) {
42
+ if (at + 46 > end || view.getUint32(at, true) !== 0x02014b50) return false;
43
+ const length = view.getUint16(at + 28, true),
44
+ extra = view.getUint16(at + 30, true),
45
+ comment = view.getUint16(at + 32, true),
46
+ next = at + 46 + length + extra + comment;
47
+ if (next > end) return false;
48
+ const local = view.getUint32(at + 42, true),
49
+ compressed = view.getUint32(at + 20, true),
50
+ flags = view.getUint16(at + 8, true),
51
+ method = view.getUint16(at + 10, true);
52
+ if (
53
+ (flags & 1) !== 0 ||
54
+ ![0, 8].includes(method) ||
55
+ local + 30 > offset ||
56
+ view.getUint32(local, true) !== 0x04034b50 ||
57
+ view.getUint16(local + 8, true) !== method
58
+ )
59
+ return false;
60
+ const localName = view.getUint16(local + 26, true),
61
+ localExtra = view.getUint16(local + 28, true);
62
+ if (
63
+ localName !== length ||
64
+ local + 30 + localName + localExtra + compressed > offset
65
+ )
66
+ return false;
67
+ const name = new TextDecoder().decode(
68
+ data.subarray(at + 46, at + 46 + length),
69
+ );
70
+ if (
71
+ name !==
72
+ new TextDecoder().decode(
73
+ data.subarray(local + 30, local + 30 + localName),
74
+ )
75
+ )
76
+ return false;
77
+ names.add(name);
78
+ at = next;
79
+ }
80
+ return (
81
+ at === end &&
82
+ names.has("[Content_Types].xml") &&
83
+ names.has(
84
+ {
85
+ docx: "word/document.xml",
86
+ xlsx: "xl/workbook.xml",
87
+ pptx: "ppt/presentation.xml",
88
+ }[format],
89
+ )
90
+ );
91
+ }
92
+ const filename = (value, fallback = "document") => {
93
+ let name = String(value || fallback)
94
+ .replace(/[\\/\x00-\x1f\x7f<>:"|?*]/g, "_")
95
+ .replace(/^\.+$/, fallback)
96
+ .slice(0, 120);
97
+ while (new TextEncoder().encode(name).byteLength > 180)
98
+ name = name.slice(0, -1);
99
+ return name || fallback;
100
+ };
101
+ const nameFromUrl = (url, fallback) => {
102
+ try {
103
+ return filename(
104
+ decodeURIComponent(new URL(url).pathname.split("/").pop()),
105
+ fallback,
106
+ );
107
+ } catch {
108
+ return fallback;
109
+ }
110
+ };
111
+ const epoch = (ctx) => ctx.lease.epochs?.get(nativeId(ctx.target.tabId));
112
+ function current(ctx, value) {
113
+ requireValue(
114
+ value &&
115
+ value.tabId === ctx.target.tabId &&
116
+ value.pageVersion === ctx.router.version(ctx.target.tabId) &&
117
+ value.controlEpoch === epoch(ctx),
118
+ "STALE_REF",
119
+ "The original document-data observation is no longer current.",
120
+ );
121
+ return value;
122
+ }
123
+ async function fetchFile(ctx, url, token, limit = maximum, name) {
124
+ const metadata = await ctx.router.dataPage(ctx, {
125
+ command: "fetch",
126
+ token,
127
+ url,
128
+ maxBytes: limit,
129
+ });
130
+ return {
131
+ url,
132
+ name: name ?? nameFromUrl(url, "download.bin"),
133
+ mimeType: metadata.mimeType,
134
+ data: await readPageBytes(ctx, token, metadata),
135
+ };
136
+ }
137
+
138
+ async function readNativeContent(ctx, handle, plan) {
139
+ const chunks = [];
140
+ let total = 0;
141
+ while (true) {
142
+ ctx.signal?.throwIfAborted();
143
+ current(ctx, plan);
144
+ const value = await ctx.router.send(ctx, "IO.read", {
145
+ handle,
146
+ size: 65536,
147
+ });
148
+ current(ctx, plan);
149
+ requireValue(
150
+ typeof value.data === "string" && value.data.length <= 90000,
151
+ "OUTPUT_TOO_LARGE",
152
+ "The native document stream chunk exceeds its byte budget.",
153
+ );
154
+ const bytes = value.base64Encoded
155
+ ? Uint8Array.from(atob(value.data), (character) =>
156
+ character.charCodeAt(0),
157
+ )
158
+ : new TextEncoder().encode(value.data);
159
+ total += bytes.byteLength;
160
+ requireValue(
161
+ bytes.byteLength <= 65536 && total <= maximum,
162
+ "OUTPUT_TOO_LARGE",
163
+ "The native document exceeds its export byte budget.",
164
+ );
165
+ chunks.push(bytes);
166
+ if (value.eof) break;
167
+ }
168
+ ctx.signal?.throwIfAborted();
169
+ const data = new Uint8Array(total);
170
+ let offset = 0;
171
+ for (const chunk of chunks) {
172
+ data.set(chunk, offset);
173
+ offset += chunk.byteLength;
174
+ }
175
+ return data;
176
+ }
177
+
178
+ async function fetchGoogleDocument(ctx, source, plan) {
179
+ const tree = await ctx.router.send(ctx, "Page.getFrameTree", {});
180
+ text(tree.frameTree?.frame?.id, 1024);
181
+ current(ctx, plan);
182
+ const response = await ctx.router.send(ctx, "Network.loadNetworkResource", {
183
+ frameId: tree.frameTree.frame.id,
184
+ url: source.url,
185
+ options: { disableCache: false, includeCredentials: true },
186
+ });
187
+ const resource = response.resource;
188
+ const diagnostics = [];
189
+ if (
190
+ Number.isInteger(resource?.httpStatusCode) &&
191
+ resource.httpStatusCode >= 100 &&
192
+ resource.httpStatusCode <= 599
193
+ )
194
+ diagnostics.push(`HTTP ${resource.httpStatusCode}`);
195
+ if (
196
+ typeof resource?.netErrorName === "string" &&
197
+ /^net::ERR_[A-Z0-9_]{1,64}$/.test(resource.netErrorName)
198
+ )
199
+ diagnostics.push(resource.netErrorName);
200
+ const outcome = diagnostics.length ? ` (${diagnostics.join(", ")})` : "";
201
+ requireValue(
202
+ resource &&
203
+ typeof resource.stream === "string" &&
204
+ resource.stream.length > 0,
205
+ "FILE_UNAVAILABLE",
206
+ `The browser could not open the Google Workspace document response${outcome}.`,
207
+ );
208
+ text(resource.stream, 1024);
209
+ try {
210
+ await ctx.router.trackNativeStream(ctx, resource.stream);
211
+ requireValue(
212
+ resource.success === true &&
213
+ resource.httpStatusCode >= 200 &&
214
+ resource.httpStatusCode < 300,
215
+ "FILE_UNAVAILABLE",
216
+ `The browser could not read the Google Workspace document response${outcome}.`,
217
+ );
218
+ const header = Object.entries(resource.headers ?? {}).find(
219
+ ([name]) => name.toLowerCase() === "content-type",
220
+ )?.[1];
221
+ return {
222
+ data: await readNativeContent(ctx, resource.stream, plan),
223
+ mimeType:
224
+ typeof header === "string"
225
+ ? header.slice(0, 256)
226
+ : "application/octet-stream",
227
+ };
228
+ } finally {
229
+ await ctx.router.closeNativeStream(ctx, resource.stream);
230
+ }
231
+ }
232
+ export async function listAssets(ctx) {
233
+ const inventories = (ctx.lease.assetInventories ??= new Map());
234
+ const previous = [...inventories].filter(
235
+ ([, value]) => value.tabId === ctx.target.tabId,
236
+ );
237
+ if (previous.length >= 4) {
238
+ const [id, value] = previous[0];
239
+ await ctx.router.dataPage(
240
+ ctx,
241
+ { command: "drop", token: value.token },
242
+ true,
243
+ );
244
+ inventories.delete(id);
245
+ }
246
+ const token = crypto.randomUUID(),
247
+ id = crypto.randomUUID();
248
+ let complete = false;
249
+ try {
250
+ const tree = await ctx.router.send(ctx, "Page.getResourceTree", {}),
251
+ resources = [];
252
+ requireValue(
253
+ tree.frameTree?.frame,
254
+ "CAPABILITY_NOT_ALLOWED",
255
+ "The native page resource tree is unavailable.",
256
+ );
257
+ const visit = (entry) => {
258
+ for (const resource of entry.resources ?? []) {
259
+ requireValue(
260
+ resources.length < 4096,
261
+ "OUTPUT_TOO_LARGE",
262
+ "The native resource inventory exceeds its count budget.",
263
+ );
264
+ resources.push({
265
+ url: resource.url,
266
+ kind:
267
+ {
268
+ Font: "font",
269
+ Image: "image",
270
+ Stylesheet: "stylesheet",
271
+ Media: "video",
272
+ Script: "script",
273
+ }[resource.type] ?? "other",
274
+ });
275
+ }
276
+ for (const child of entry.childFrames ?? []) visit(child);
277
+ };
278
+ visit(tree.frameTree);
279
+ const data = await ctx.router.dataPage(ctx, {
280
+ command: "inventory",
281
+ token,
282
+ resources,
283
+ });
284
+ const value = {
285
+ id,
286
+ target: ctx.router.target(ctx.target.tabId, ctx.lease),
287
+ ...data,
288
+ };
289
+ inventories.set(id, {
290
+ token,
291
+ tabId: ctx.target.tabId,
292
+ pageVersion: ctx.router.version(ctx.target.tabId),
293
+ controlEpoch: epoch(ctx),
294
+ value,
295
+ });
296
+ complete = true;
297
+ return value;
298
+ } finally {
299
+ if (!complete)
300
+ await ctx.router.dataPage(ctx, { command: "drop", token }, true);
301
+ }
302
+ }
303
+ export async function planAssets(ctx, input) {
304
+ const options = input.options ?? input;
305
+ text(options.inventoryId, 512);
306
+ const inventory = current(
307
+ ctx,
308
+ ctx.lease.assetInventories?.get(options.inventoryId),
309
+ );
310
+ const checked = await ctx.router.dataPage(ctx, {
311
+ command: "inventoryCheck",
312
+ token: inventory.token,
313
+ });
314
+ requireValue(
315
+ checked.pageUrl === inventory.value.pageUrl,
316
+ "STALE_REF",
317
+ "The original native inventory document URL changed.",
318
+ );
319
+ const ids =
320
+ options.assetIds === undefined ? undefined : new Set(options.assetIds);
321
+ requireValue(
322
+ ids === undefined ||
323
+ (Array.isArray(options.assetIds) &&
324
+ ids.size === options.assetIds.length &&
325
+ ids.size <= 128),
326
+ );
327
+ requireValue(
328
+ options.kinds === undefined ||
329
+ (Array.isArray(options.kinds) &&
330
+ options.kinds.every((kind) =>
331
+ ["font", "image", "stylesheet", "video"].includes(kind),
332
+ )),
333
+ );
334
+ const assets = inventory.value.assets.filter(
335
+ (asset) =>
336
+ (!ids || ids.has(asset.id)) &&
337
+ (!options.kinds || options.kinds.includes(asset.kind)),
338
+ );
339
+ requireValue(
340
+ assets.length <= 128,
341
+ "OUTPUT_TOO_LARGE",
342
+ "Select at most 128 explicit assets for one browser bundle.",
343
+ );
344
+ if (ids)
345
+ requireValue(
346
+ [...ids].every((id) => assets.some((asset) => asset.id === id)),
347
+ "INVALID_ARGUMENT",
348
+ "An asset ID is absent from this exact selected inventory.",
349
+ );
350
+ return {
351
+ inventoryId: options.inventoryId,
352
+ target: inventory.value.target,
353
+ pageUrl: inventory.value.pageUrl,
354
+ assets: assets.map(({ id, kind, url, name }) => ({
355
+ id,
356
+ kind,
357
+ url,
358
+ name,
359
+ embedded: /^(?:blob:|data:)/.test(url),
360
+ })),
361
+ };
362
+ }
363
+ export async function downloadAssets(ctx, urls) {
364
+ requireValue(Array.isArray(urls) && urls.length <= 128);
365
+ urls.forEach((url) => {
366
+ text(url, 1024 * 1024);
367
+ requireValue(/^(?:https?:|blob:|data:)/.test(url));
368
+ });
369
+ const files = [],
370
+ failures = [],
371
+ token = crypto.randomUUID();
372
+ let total = 0;
373
+ try {
374
+ for (const url of urls) {
375
+ ctx.signal?.throwIfAborted();
376
+ try {
377
+ const file = await fetchFile(ctx, url, token, maximum - total);
378
+ total += file.data.byteLength;
379
+ files.push(file);
380
+ } catch (cause) {
381
+ ctx.signal?.throwIfAborted();
382
+ failures.push({
383
+ url,
384
+ reason:
385
+ cause instanceof BrowserActionError
386
+ ? cause.message
387
+ : "The native browser response could not be exported.",
388
+ });
389
+ }
390
+ }
391
+ return { files, failures };
392
+ } finally {
393
+ await ctx.router.dataPage(ctx, { command: "drop", token }, true);
394
+ }
395
+ }
396
+ export async function bundleAssets(ctx, input) {
397
+ const plan = await planAssets(ctx, input),
398
+ inventory = current(ctx, ctx.lease.assetInventories.get(plan.inventoryId));
399
+ const assets = [],
400
+ failures = [];
401
+ let total = 0;
402
+ for (const selected of plan.assets) {
403
+ ctx.signal?.throwIfAborted();
404
+ current(ctx, inventory);
405
+ try {
406
+ const file = await fetchFile(
407
+ ctx,
408
+ selected.url,
409
+ inventory.token,
410
+ maximum - total,
411
+ selected.name,
412
+ );
413
+ total += file.data.byteLength;
414
+ assets.push({ id: selected.id, kind: selected.kind, ...file });
415
+ } catch (cause) {
416
+ ctx.signal?.throwIfAborted();
417
+ failures.push({
418
+ id: selected.id,
419
+ url: selected.url,
420
+ name: selected.name,
421
+ reason:
422
+ cause instanceof BrowserActionError
423
+ ? cause.message
424
+ : "The native browser asset could not be exported.",
425
+ });
426
+ }
427
+ }
428
+ return {
429
+ inventoryId: plan.inventoryId,
430
+ target: plan.target,
431
+ pageUrl: plan.pageUrl,
432
+ assets,
433
+ failures,
434
+ };
435
+ }
436
+ export async function planContent(ctx, args) {
437
+ text(args.method, 128);
438
+ const tab = await ctx.chrome.tabs.get(nativeId(ctx.target.tabId));
439
+ let format, source;
440
+ if (
441
+ ["content.exportGsuite", "content.exportYouTubeTranscript"].includes(
442
+ args.method,
443
+ )
444
+ ) {
445
+ const response = await ctx.chrome.scripting.executeScript({
446
+ target: { tabId: nativeId(ctx.target.tabId) },
447
+ world: "MAIN",
448
+ func: observeSiteSource,
449
+ args: [{ method: args.method, format: args.type }],
450
+ });
451
+ requireValue(
452
+ response.length === 1 && response[0]?.result,
453
+ "INVALID_TARGET",
454
+ "The actual site observation produced no main-document result.",
455
+ );
456
+ const observed = response[0].result;
457
+ if (!observed.ok)
458
+ throw new BrowserActionError(observed.error.code, observed.error.message);
459
+ source = observed.value;
460
+ format = args.type ?? "txt";
461
+ requireValue(
462
+ source.pageUrl === tab.url,
463
+ "STALE_REF",
464
+ "The current site document changed during source observation.",
465
+ );
466
+ } else if (
467
+ [
468
+ "cua.downloadMedia",
469
+ "dom.downloadMedia",
470
+ "locator.downloadMedia",
471
+ ].includes(args.method)
472
+ ) {
473
+ const input = args.options ?? args;
474
+ source = {
475
+ kind: "media",
476
+ ...(await ctx.router.page(ctx, {
477
+ ...args,
478
+ ...input,
479
+ nodeId: input.node_id,
480
+ command: "mediaSource",
481
+ })),
482
+ framePath: args.locator?.framePath ?? [],
483
+ };
484
+ format = "media";
485
+ } else {
486
+ requireValue(
487
+ ["tab.exportFile", "content.export"].includes(args.method),
488
+ "CAPABILITY_NOT_ALLOWED",
489
+ "This native content source has no export adapter.",
490
+ );
491
+ format = args.method === "content.export" ? "html" : args.options?.format;
492
+ requireValue(["pdf", "html", "markdown"].includes(format));
493
+ }
494
+ const plans = (ctx.lease.contentPlans ??= new Map());
495
+ while (plans.size >= 16) plans.delete(plans.keys().next().value);
496
+ const id = crypto.randomUUID();
497
+ plans.set(id, {
498
+ tabId: ctx.target.tabId,
499
+ pageVersion: ctx.router.version(ctx.target.tabId),
500
+ controlEpoch: epoch(ctx),
501
+ method: args.method,
502
+ format,
503
+ url: tab.url,
504
+ title: tab.title,
505
+ source,
506
+ });
507
+ return { id, urls: source?.url ? [source.url] : [], sourceUrl: tab.url };
508
+ }
509
+ export async function exportContent(ctx, args) {
510
+ text(args.planId, 512);
511
+ const plan = current(ctx, ctx.lease.contentPlans?.get(args.planId));
512
+ requireValue(
513
+ plan.method === ctx.method,
514
+ "INVALID_ARGUMENT",
515
+ "The export plan belongs to another content method.",
516
+ );
517
+ const tab = await ctx.chrome.tabs.get(nativeId(ctx.target.tabId));
518
+ requireValue(
519
+ tab.url === plan.url,
520
+ "STALE_REF",
521
+ "The authorized source document changed before export.",
522
+ );
523
+ if (plan.source) {
524
+ const source = plan.source;
525
+ if (source.kind === "transcript-dom")
526
+ return {
527
+ text: source.text,
528
+ name: `${filename(source.title)}.txt`,
529
+ mimeType: "text/plain;charset=utf-8",
530
+ sourceUrl: plan.url,
531
+ };
532
+ if (source.kind === "media") {
533
+ const observed = await ctx.router.page(ctx, {
534
+ framePath: source.framePath,
535
+ ref: source.ref,
536
+ command: "mediaSource",
537
+ });
538
+ requireValue(
539
+ observed.url === source.url,
540
+ "STALE_REF",
541
+ "The observed media source changed after its URL was authorized.",
542
+ );
543
+ }
544
+ const token = crypto.randomUUID();
545
+ try {
546
+ const file =
547
+ source.kind === "gsuite"
548
+ ? await fetchGoogleDocument(ctx, source, plan)
549
+ : await fetchFile(ctx, source.url, token);
550
+ if (source.kind === "transcript-track") {
551
+ const converted = await ctx.router.dataPage(ctx, {
552
+ command: "transcript",
553
+ token,
554
+ });
555
+ return {
556
+ data: await readPageBytes(ctx, token, converted),
557
+ name: `${filename(source.title)}.txt`,
558
+ mimeType: converted.mimeType,
559
+ sourceUrl: source.url,
560
+ };
561
+ }
562
+ if (source.kind === "gsuite") {
563
+ const expected = {
564
+ pdf: "application/pdf",
565
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
566
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
567
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
568
+ csv: "text/csv",
569
+ md: "text/markdown",
570
+ }[plan.format];
571
+ const signature = new TextDecoder().decode(file.data.subarray(0, 8));
572
+ requireValue(
573
+ plan.format === "pdf"
574
+ ? signature.startsWith("%PDF-")
575
+ : ["docx", "xlsx", "pptx"].includes(plan.format)
576
+ ? officeArchive(file.data, plan.format)
577
+ : !/^\s*</.test(
578
+ new TextDecoder().decode(file.data.subarray(0, 512)),
579
+ ) &&
580
+ (plan.format === "csv"
581
+ ? /^text\/csv(?:;|$)/i.test(file.mimeType)
582
+ : /^text\/(?:markdown|x-markdown|plain)(?:;|$)/i.test(
583
+ file.mimeType,
584
+ )),
585
+ "FILE_UNAVAILABLE",
586
+ "The browser returned no actual document in the requested Google Workspace format.",
587
+ );
588
+ return {
589
+ data: file.data,
590
+ name: `${filename(source.title)}.${plan.format}`,
591
+ mimeType: expected,
592
+ sourceUrl: source.url,
593
+ };
594
+ }
595
+ return {
596
+ data: file.data,
597
+ name: file.name,
598
+ mimeType: file.mimeType,
599
+ sourceUrl: source.url,
600
+ };
601
+ } finally {
602
+ await ctx.router.dataPage(ctx, { command: "drop", token }, true);
603
+ }
604
+ }
605
+ if (plan.format === "pdf") {
606
+ const response = await ctx.router.send(ctx, "Page.printToPDF", {
607
+ printBackground: true,
608
+ transferMode: "ReturnAsStream",
609
+ });
610
+ text(response.stream, 1024);
611
+ let data;
612
+ try {
613
+ await ctx.router.trackNativeStream(ctx, response.stream);
614
+ data = await readNativeContent(ctx, response.stream, plan);
615
+ } finally {
616
+ await ctx.router.closeNativeStream(ctx, response.stream);
617
+ }
618
+ requireValue(
619
+ data.length >= 5 &&
620
+ new TextDecoder().decode(data.subarray(0, 5)) === "%PDF-",
621
+ "FILE_UNAVAILABLE",
622
+ "The browser did not produce a native PDF document.",
623
+ );
624
+ return {
625
+ data,
626
+ mimeType: "application/pdf",
627
+ name: `${filename(plan.title)}.pdf`,
628
+ sourceUrl: plan.url,
629
+ };
630
+ }
631
+ // Markdown conversion is owned by the approved Node HTML-to-Markdown adapter; raw HTML remains a truthful native source.
632
+ requireValue(["html", "markdown"].includes(plan.format));
633
+ const token = crypto.randomUUID();
634
+ try {
635
+ const metadata = await ctx.router.dataPage(ctx, {
636
+ command: "export",
637
+ format: "html",
638
+ token,
639
+ });
640
+ requireValue(
641
+ metadata.url === plan.url,
642
+ "STALE_REF",
643
+ "The native source document changed during extraction.",
644
+ );
645
+ return {
646
+ text: new TextDecoder().decode(await readPageBytes(ctx, token, metadata)),
647
+ mimeType: "text/html",
648
+ name: `${filename(plan.title)}.html`,
649
+ sourceUrl: plan.url,
650
+ };
651
+ } finally {
652
+ await ctx.router.dataPage(ctx, { command: "drop", token }, true);
653
+ }
654
+ }