@cbxss/eoka 0.0.0-stage → 0.1.0-beta.10
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/README.md +170 -2
- package/dist/LICENSE +21 -0
- package/dist/browser-install-diagnostics.d.ts +1 -0
- package/dist/browser-install-diagnostics.js +21 -0
- package/dist/browser-install-engine.d.ts +10 -0
- package/dist/browser-install-engine.js +286 -0
- package/dist/browser-install-inventory.d.ts +34 -0
- package/dist/browser-install-inventory.js +107 -0
- package/dist/browser-install-worker.d.ts +21 -0
- package/dist/browser-install-worker.js +65 -0
- package/dist/browser-install.d.ts +22 -0
- package/dist/browser-install.js +7 -0
- package/dist/browser.d.ts +62 -0
- package/dist/browser.js +452 -0
- package/dist/client.d.ts +11 -0
- package/dist/client.js +1 -0
- package/dist/cloudflare.d.ts +12 -0
- package/dist/cloudflare.js +19 -0
- package/dist/errors.d.ts +33 -0
- package/dist/errors.js +44 -0
- package/dist/generated/protocol.d.ts +4878 -0
- package/dist/generated/protocol.js +2 -0
- package/dist/generated/schema-bundle.json +23846 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +11 -0
- package/dist/install-errors.d.ts +4 -0
- package/dist/install-errors.js +6 -0
- package/dist/operations.d.ts +22 -0
- package/dist/operations.js +87 -0
- package/dist/page.d.ts +107 -0
- package/dist/page.js +299 -0
- package/dist/platform.d.ts +4 -0
- package/dist/platform.js +27 -0
- package/dist/recording.d.ts +27 -0
- package/dist/recording.js +124 -0
- package/dist/release-manifest.json +101 -0
- package/dist/release.d.ts +36 -0
- package/dist/release.js +76 -0
- package/dist/server-binary.d.ts +12 -0
- package/dist/server-binary.js +130 -0
- package/dist/transport.d.ts +89 -0
- package/dist/transport.js +737 -0
- package/examples/capture.mjs +36 -0
- package/examples/consume-schema.mjs +7 -0
- package/examples/explicit-paths.mjs +42 -0
- package/examples/install-browser.mjs +20 -0
- package/examples/offline.mjs +20 -0
- package/package.json +70 -4
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ChromePlatformRelease } from './release.js';
|
|
2
|
+
export interface WorkerRequest {
|
|
3
|
+
action: 'verify' | 'install';
|
|
4
|
+
root: string;
|
|
5
|
+
buildId: string;
|
|
6
|
+
platform: string;
|
|
7
|
+
pin: ChromePlatformRelease;
|
|
8
|
+
executablePath: string;
|
|
9
|
+
}
|
|
10
|
+
export type WorkerMessage = {
|
|
11
|
+
type: 'result';
|
|
12
|
+
verified: boolean;
|
|
13
|
+
} | {
|
|
14
|
+
type: 'progress';
|
|
15
|
+
downloadedBytes: number;
|
|
16
|
+
totalBytes: number;
|
|
17
|
+
} | {
|
|
18
|
+
type: 'error';
|
|
19
|
+
code: string;
|
|
20
|
+
message: string;
|
|
21
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { Browser, install, getDownloadUrl } from '@puppeteer/browsers';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createMarker, verifyInstallation } from './browser-install-inventory.js';
|
|
5
|
+
import { sanitizeInstallationDiagnostic } from './browser-install-diagnostics.js';
|
|
6
|
+
process.once('disconnect', () => {
|
|
7
|
+
if (process.platform === 'win32') {
|
|
8
|
+
spawn('taskkill', ['/PID', String(process.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }).once('error', () => process.exit(1));
|
|
9
|
+
}
|
|
10
|
+
else {
|
|
11
|
+
try {
|
|
12
|
+
process.kill(-process.pid, 'SIGKILL');
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
process.exit(1);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
process.once('message', async (request) => {
|
|
20
|
+
try {
|
|
21
|
+
if (request.action === 'verify') {
|
|
22
|
+
const verified = await verifyInstallation(request.root, request.buildId, request.platform, request.pin, request.executablePath);
|
|
23
|
+
process.send?.({ type: 'result', verified });
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
if (process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0')
|
|
27
|
+
throw new Error('Browser downloads require TLS certificate verification; remove NODE_TLS_REJECT_UNAUTHORIZED=0');
|
|
28
|
+
if (!request.pin.sha256 || !/^[a-f0-9]{64}$/.test(request.pin.sha256))
|
|
29
|
+
throw new Error('Missing archive checksum');
|
|
30
|
+
const platform = request.pin.platform;
|
|
31
|
+
const url = new URL(request.pin.url);
|
|
32
|
+
const baseUrl = new URL('../../', url).href.replace(/\/$/, '');
|
|
33
|
+
if (getDownloadUrl(Browser.CHROME, platform, request.buildId, baseUrl).href !== url.href)
|
|
34
|
+
throw new Error('Pinned URL does not match the Chrome distribution');
|
|
35
|
+
const browser = await install({
|
|
36
|
+
browser: Browser.CHROME,
|
|
37
|
+
buildId: request.buildId,
|
|
38
|
+
platform,
|
|
39
|
+
cacheDir: request.root,
|
|
40
|
+
baseUrl,
|
|
41
|
+
expectedHash: request.pin.sha256,
|
|
42
|
+
installDeps: false,
|
|
43
|
+
downloadProgressCallback: (downloadedBytes, totalBytes) => {
|
|
44
|
+
process.send?.({ type: 'progress', downloadedBytes, totalBytes });
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
if (path.relative(request.root, browser.executablePath).replaceAll(path.sep, '/') !== request.executablePath)
|
|
48
|
+
throw new Error('Installer returned an unexpected executable path');
|
|
49
|
+
await createMarker(request.root, request.buildId, request.platform, request.pin, request.executablePath);
|
|
50
|
+
process.send?.({ type: 'result', verified: true });
|
|
51
|
+
}
|
|
52
|
+
process.exitCode = 0;
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
const rawMessage = error instanceof Error ? error.message : String(error);
|
|
56
|
+
const message = sanitizeInstallationDiagnostic(rawMessage, process.env);
|
|
57
|
+
const code = error && typeof error === 'object' && 'name' in error && error.name === 'InstallationError' && 'code' in error && typeof error.code === 'string' ? error.code : /integrity check failed/i.test(rawMessage) ? 'IntegrityMismatch' : 'InstallationFailed';
|
|
58
|
+
process.send?.({ type: 'error', code, message });
|
|
59
|
+
process.exitCode = 1;
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
process.removeAllListeners('disconnect');
|
|
63
|
+
process.disconnect?.();
|
|
64
|
+
}
|
|
65
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type PlatformId } from './platform.js';
|
|
2
|
+
export interface InstallProgress {
|
|
3
|
+
downloadedBytes: number;
|
|
4
|
+
totalBytes: number;
|
|
5
|
+
buildId: string;
|
|
6
|
+
}
|
|
7
|
+
export interface InstallBrowserOptions {
|
|
8
|
+
browserCacheDir?: string;
|
|
9
|
+
download?: 'auto' | 'never';
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
onProgress?: (progress: InstallProgress) => void;
|
|
13
|
+
env?: NodeJS.ProcessEnv;
|
|
14
|
+
}
|
|
15
|
+
export interface BrowserInstallation {
|
|
16
|
+
executablePath: string;
|
|
17
|
+
cacheDir: string;
|
|
18
|
+
buildId: string;
|
|
19
|
+
platform: PlatformId;
|
|
20
|
+
source: 'cache' | 'download';
|
|
21
|
+
}
|
|
22
|
+
export declare function installBrowser(options?: InstallBrowserOptions): Promise<BrowserInstallation>;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createBrowserInstaller } from './browser-install-engine.js';
|
|
2
|
+
import { detectPlatform } from './platform.js';
|
|
3
|
+
import { releaseManifest } from './release.js';
|
|
4
|
+
export async function installBrowser(options = {}) {
|
|
5
|
+
const platform = detectPlatform();
|
|
6
|
+
return await createBrowserInstaller({ platform, buildId: releaseManifest.chrome.buildId, pin: releaseManifest.chrome.platforms[platform] })(options);
|
|
7
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { CallOptions, InvokeClient } from './client.js';
|
|
2
|
+
import type { MethodName, MethodParams, MethodResults } from './generated/protocol.js';
|
|
3
|
+
import { Operation } from './operations.js';
|
|
4
|
+
import { Page, type PerformOptions } from './page.js';
|
|
5
|
+
import { Recording } from './recording.js';
|
|
6
|
+
import { type InstallProgress } from './browser-install.js';
|
|
7
|
+
import { type CloudflareOptions } from './cloudflare.js';
|
|
8
|
+
export interface BrowserOptions {
|
|
9
|
+
serverPath?: string;
|
|
10
|
+
serverEnv?: NodeJS.ProcessEnv;
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
timeoutMs?: number;
|
|
13
|
+
shutdownTimeoutMs?: number;
|
|
14
|
+
/** Have the server watch every tab and solve full-page Cloudflare challenges. */
|
|
15
|
+
autoSolveCloudflare?: boolean | CloudflareOptions;
|
|
16
|
+
}
|
|
17
|
+
export interface LaunchOptions extends BrowserOptions {
|
|
18
|
+
executablePath?: string;
|
|
19
|
+
headless?: boolean;
|
|
20
|
+
sandbox?: boolean;
|
|
21
|
+
viewport?: {
|
|
22
|
+
width: number;
|
|
23
|
+
height: number;
|
|
24
|
+
deviceScaleFactor?: number;
|
|
25
|
+
};
|
|
26
|
+
runtimeDir?: string;
|
|
27
|
+
userDataDir?: string;
|
|
28
|
+
browserCacheDir?: string;
|
|
29
|
+
download?: 'auto' | 'never';
|
|
30
|
+
onProgress?: (progress: InstallProgress) => void;
|
|
31
|
+
userAgent?: string;
|
|
32
|
+
timezone?: string;
|
|
33
|
+
proxy?: NonNullable<MethodParams['browser.launch']['proxy']>;
|
|
34
|
+
}
|
|
35
|
+
export interface ConnectOptions extends BrowserOptions {
|
|
36
|
+
browserWSEndpoint: string;
|
|
37
|
+
}
|
|
38
|
+
export declare class Browser implements InvokeClient {
|
|
39
|
+
#private;
|
|
40
|
+
private constructor();
|
|
41
|
+
static launch(options?: LaunchOptions): Promise<Browser>;
|
|
42
|
+
static connect(options: ConnectOptions): Promise<Browser>;
|
|
43
|
+
private static start;
|
|
44
|
+
get hello(): MethodResults['server.hello'];
|
|
45
|
+
get sessionInfo(): MethodResults['browser.launch'];
|
|
46
|
+
get ownership(): MethodResults['browser.launch']['ownership'];
|
|
47
|
+
get browserVersion(): string;
|
|
48
|
+
supports(method: string): boolean;
|
|
49
|
+
hasCapability(name: string): boolean;
|
|
50
|
+
invoke<M extends MethodName>(method: M, params: MethodParams[M], options?: CallOptions): Promise<MethodResults[M]>;
|
|
51
|
+
page(id: string): Page;
|
|
52
|
+
operation(id: string): Operation;
|
|
53
|
+
recording(id: string): Recording;
|
|
54
|
+
tabs(options?: CallOptions): Promise<MethodResults['browser.tabs']['tabs']>;
|
|
55
|
+
pages(options?: CallOptions): Promise<Page[]>;
|
|
56
|
+
operations(params?: MethodParams['operations.list'], options?: CallOptions): Promise<MethodResults['operations.list']>;
|
|
57
|
+
newPage(url?: string, options?: PerformOptions): Promise<Page>;
|
|
58
|
+
private createPage;
|
|
59
|
+
private cleanupAbandonedCreation;
|
|
60
|
+
close(): Promise<void>;
|
|
61
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
62
|
+
}
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
import { access, chmod, mkdir, mkdtemp, rm, stat } from 'node:fs/promises';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
import { ConfigurationError, EokaError, ProtocolError, TransportError } from './errors.js';
|
|
6
|
+
import { Operation } from './operations.js';
|
|
7
|
+
import { Page } from './page.js';
|
|
8
|
+
import { Recording } from './recording.js';
|
|
9
|
+
import { SidecarTransport } from './transport.js';
|
|
10
|
+
import { installBrowser } from './browser-install.js';
|
|
11
|
+
import { resolveCloudflareOptions } from './cloudflare.js';
|
|
12
|
+
import { resolveServerBinary } from './server-binary.js';
|
|
13
|
+
function validateTimeout(value, name) {
|
|
14
|
+
if (value !== undefined && (!Number.isFinite(value) || value <= 0 || value > 2_147_483_647)) {
|
|
15
|
+
throw new ConfigurationError(`${name} must be finite, positive and at most 2147483647 milliseconds`);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function pathOption(value, name) {
|
|
19
|
+
if (typeof value !== 'string' || value.trim() === '' || value.includes('\0')) {
|
|
20
|
+
throw new ConfigurationError(`${name} must be a nonempty filesystem path`);
|
|
21
|
+
}
|
|
22
|
+
return resolve(value);
|
|
23
|
+
}
|
|
24
|
+
async function executablePath(value, name) {
|
|
25
|
+
const absolute = pathOption(value, name);
|
|
26
|
+
try {
|
|
27
|
+
if (!(await stat(absolute)).isFile())
|
|
28
|
+
throw new Error('not a regular file');
|
|
29
|
+
await access(absolute, process.platform === 'win32' ? constants.F_OK : constants.X_OK);
|
|
30
|
+
}
|
|
31
|
+
catch (cause) {
|
|
32
|
+
throw new ConfigurationError(`${name} is not an accessible executable: ${absolute}`, { cause });
|
|
33
|
+
}
|
|
34
|
+
return absolute;
|
|
35
|
+
}
|
|
36
|
+
function checkAbort(signal, requestState = 'not_sent') {
|
|
37
|
+
if (signal?.aborted) {
|
|
38
|
+
const reason = signal.reason;
|
|
39
|
+
throw new TransportError(reason instanceof TransportError ? reason.code : 'Aborted', reason instanceof TransportError ? reason.message : 'Browser lifecycle operation was aborted; cleanup is not canceled', { cause: reason, requestState });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function remainingTimeout(deadline) {
|
|
43
|
+
if (deadline === undefined)
|
|
44
|
+
return undefined;
|
|
45
|
+
const remaining = deadline - performance.now();
|
|
46
|
+
if (remaining <= 0)
|
|
47
|
+
throw new TransportError('DeadlineExceeded', 'Browser lifecycle operation exceeded its local deadline', { requestState: 'not_sent' });
|
|
48
|
+
return remaining;
|
|
49
|
+
}
|
|
50
|
+
function localOptions(options, deadline) {
|
|
51
|
+
const timeoutMs = remainingTimeout(deadline);
|
|
52
|
+
const local = {};
|
|
53
|
+
if (options.signal !== undefined)
|
|
54
|
+
local.signal = options.signal;
|
|
55
|
+
if (options.operationId !== undefined)
|
|
56
|
+
local.operationId = options.operationId;
|
|
57
|
+
if (timeoutMs !== undefined)
|
|
58
|
+
local.timeoutMs = timeoutMs;
|
|
59
|
+
return local;
|
|
60
|
+
}
|
|
61
|
+
function lifecycleScope(options) {
|
|
62
|
+
validateTimeout(options.timeoutMs, 'timeoutMs');
|
|
63
|
+
validateTimeout(options.shutdownTimeoutMs, 'shutdownTimeoutMs');
|
|
64
|
+
checkAbort(options.signal);
|
|
65
|
+
const deadline = options.timeoutMs === undefined ? undefined : performance.now() + options.timeoutMs;
|
|
66
|
+
const controller = new AbortController();
|
|
67
|
+
const abort = () => controller.abort(new TransportError('Aborted', 'Browser lifecycle operation was aborted; cleanup is not canceled', { cause: options.signal?.reason, requestState: 'not_sent' }));
|
|
68
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
69
|
+
const timer = options.timeoutMs === undefined ? undefined : setTimeout(() => {
|
|
70
|
+
controller.abort(new TransportError('DeadlineExceeded', 'Browser lifecycle operation exceeded its local deadline', { requestState: 'not_sent' }));
|
|
71
|
+
}, options.timeoutMs);
|
|
72
|
+
return {
|
|
73
|
+
options: { ...options, signal: controller.signal },
|
|
74
|
+
deadline,
|
|
75
|
+
dispose: () => {
|
|
76
|
+
clearTimeout(timer);
|
|
77
|
+
options.signal?.removeEventListener('abort', abort);
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function lifecycleFailure(primary, signal, deadline) {
|
|
82
|
+
if (signal?.aborted && signal.reason instanceof TransportError && primary instanceof EokaError && ['Aborted', 'InstallationAborted', 'InstallationTimeout'].includes(primary.code)) {
|
|
83
|
+
return new TransportError(signal.reason.code, signal.reason.message, { cause: primary, requestState: primary.requestState ?? 'not_sent', requestId: primary.requestId, stderr: primary.stderr });
|
|
84
|
+
}
|
|
85
|
+
if (deadline !== undefined && primary instanceof EokaError && primary.code === 'InstallationTimeout') {
|
|
86
|
+
return new TransportError('DeadlineExceeded', 'Browser lifecycle operation exceeded its local deadline', { cause: primary, requestState: 'not_sent' });
|
|
87
|
+
}
|
|
88
|
+
return primary;
|
|
89
|
+
}
|
|
90
|
+
async function runtimeDirectory(root) {
|
|
91
|
+
try {
|
|
92
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
93
|
+
const directory = await mkdtemp(join(root, 'e-'));
|
|
94
|
+
try {
|
|
95
|
+
if (process.platform !== 'win32')
|
|
96
|
+
await chmod(directory, 0o700);
|
|
97
|
+
return directory;
|
|
98
|
+
}
|
|
99
|
+
catch (primary) {
|
|
100
|
+
await removeRuntime(directory, primary);
|
|
101
|
+
throw primary;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
catch (cause) {
|
|
105
|
+
throw new ConfigurationError(`Could not create private browser runtime under ${root}`, { cause });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
async function removeRuntime(directory, primary) {
|
|
109
|
+
try {
|
|
110
|
+
await rm(directory, { recursive: true, force: true });
|
|
111
|
+
}
|
|
112
|
+
catch (cause) {
|
|
113
|
+
const cleanup = new TransportError('RuntimeCleanup', `Could not remove owned browser runtime ${directory}`, { cause });
|
|
114
|
+
if (primary !== undefined)
|
|
115
|
+
throw new AggregateError([primary, cleanup], 'Browser lifecycle failed and owned runtime cleanup failed', { cause: primary });
|
|
116
|
+
throw cleanup;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
async function removeClosedRuntime(directory, transport, primary) {
|
|
120
|
+
if (transport !== undefined && !transport.ownedProcessesTerminated) {
|
|
121
|
+
const cleanup = new TransportError('RuntimeCleanupUncertain', `Owned browser runtime retained at ${directory}: sidecar process-tree termination could not be confirmed`, { data: { runtimeDir: directory } });
|
|
122
|
+
if (primary !== undefined)
|
|
123
|
+
throw new AggregateError([primary, cleanup], 'Browser lifecycle failed and owned runtime was retained because process cleanup is uncertain', { cause: primary });
|
|
124
|
+
throw cleanup;
|
|
125
|
+
}
|
|
126
|
+
await removeRuntime(directory, primary);
|
|
127
|
+
}
|
|
128
|
+
function validateEndpoint(value) {
|
|
129
|
+
let endpoint;
|
|
130
|
+
try {
|
|
131
|
+
endpoint = new URL(value);
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
throw new ConfigurationError('browserWSEndpoint must be a ws:// browser DevTools endpoint');
|
|
135
|
+
}
|
|
136
|
+
if (typeof value !== 'string' || endpoint.protocol !== 'ws:' || !endpoint.hostname || endpoint.username || endpoint.password || value.includes('?') || value.includes('#') || !/^\/devtools\/browser\/[^/]+$/.test(endpoint.pathname)) {
|
|
137
|
+
throw new ConfigurationError('browserWSEndpoint must be a ws:// browser DevTools endpoint without credentials, query or fragment; wss:// is unsupported');
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function launchParams(options) {
|
|
141
|
+
const params = { headless: options.headless ?? true, sandbox: options.sandbox ?? true, deviceScaleFactor: null };
|
|
142
|
+
for (const name of ['headless', 'sandbox']) {
|
|
143
|
+
if (options[name] !== undefined && typeof options[name] !== 'boolean')
|
|
144
|
+
throw new ConfigurationError(`${name} must be a boolean`);
|
|
145
|
+
}
|
|
146
|
+
for (const name of ['userAgent', 'timezone']) {
|
|
147
|
+
if (options[name] !== undefined) {
|
|
148
|
+
if (typeof options[name] !== 'string')
|
|
149
|
+
throw new ConfigurationError(`${name} must be a string`);
|
|
150
|
+
params[name] = options[name];
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
for (const name of ['runtimeDir', 'userDataDir']) {
|
|
154
|
+
if (options[name] !== undefined)
|
|
155
|
+
params[name] = pathOption(options[name], name);
|
|
156
|
+
}
|
|
157
|
+
if (options.viewport !== undefined) {
|
|
158
|
+
const viewport = options.viewport;
|
|
159
|
+
if (!viewport || !Number.isInteger(viewport.width) || !Number.isInteger(viewport.height) || viewport.width < 1 || viewport.height < 1 || viewport.width > 2_147_483_647 || viewport.height > 2_147_483_647) {
|
|
160
|
+
throw new ConfigurationError('viewport width and height must be positive integers at most 2147483647');
|
|
161
|
+
}
|
|
162
|
+
if (viewport.deviceScaleFactor !== undefined && (!Number.isFinite(viewport.deviceScaleFactor) || viewport.deviceScaleFactor <= 0)) {
|
|
163
|
+
throw new ConfigurationError('viewport deviceScaleFactor must be finite and positive');
|
|
164
|
+
}
|
|
165
|
+
params.viewportWidth = viewport.width;
|
|
166
|
+
params.viewportHeight = viewport.height;
|
|
167
|
+
params.deviceScaleFactor = viewport.deviceScaleFactor ?? null;
|
|
168
|
+
}
|
|
169
|
+
if (options.proxy !== undefined) {
|
|
170
|
+
const proxy = options.proxy;
|
|
171
|
+
let endpoint;
|
|
172
|
+
try {
|
|
173
|
+
endpoint = new URL(proxy.server);
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
throw new ConfigurationError('proxy.server must be an http:// or socks5:// URL with host and port');
|
|
177
|
+
}
|
|
178
|
+
if (!['http:', 'socks5:'].includes(endpoint.protocol) || !endpoint.hostname || !endpoint.port || endpoint.username || endpoint.password || !['', '/'].includes(endpoint.pathname) || proxy.server.includes('?') || proxy.server.includes('#')) {
|
|
179
|
+
throw new ConfigurationError('proxy.server must include host and port without credentials, path, query or fragment');
|
|
180
|
+
}
|
|
181
|
+
const username = proxy.username ?? null;
|
|
182
|
+
const password = proxy.password ?? null;
|
|
183
|
+
if ((username === null) !== (password === null) || (username !== null && typeof username !== 'string') || (password !== null && typeof password !== 'string')) {
|
|
184
|
+
throw new ConfigurationError('proxy credentials require both username and password strings');
|
|
185
|
+
}
|
|
186
|
+
params.proxy = { server: proxy.server, username, password };
|
|
187
|
+
}
|
|
188
|
+
return params;
|
|
189
|
+
}
|
|
190
|
+
export class Browser {
|
|
191
|
+
#transport;
|
|
192
|
+
#sessionInfo;
|
|
193
|
+
#capabilities;
|
|
194
|
+
#shutdownTimeoutMs;
|
|
195
|
+
#closePromise;
|
|
196
|
+
#pageOwners = new Set();
|
|
197
|
+
#creationCleanupFailures = [];
|
|
198
|
+
#runtimeCleanup;
|
|
199
|
+
constructor(transport, sessionInfo, shutdownTimeoutMs, runtimeDir) {
|
|
200
|
+
this.#transport = transport;
|
|
201
|
+
this.#sessionInfo = Object.freeze(sessionInfo);
|
|
202
|
+
this.#capabilities = new Set(transport.hello.capabilities);
|
|
203
|
+
this.#shutdownTimeoutMs = shutdownTimeoutMs;
|
|
204
|
+
this.#runtimeCleanup = runtimeDir === undefined
|
|
205
|
+
? Promise.resolve()
|
|
206
|
+
: transport.whenClosed().then(() => removeClosedRuntime(runtimeDir, transport), () => removeClosedRuntime(runtimeDir, transport));
|
|
207
|
+
void this.#runtimeCleanup.catch(() => { });
|
|
208
|
+
}
|
|
209
|
+
static async launch(options = {}) {
|
|
210
|
+
const params = launchParams(options);
|
|
211
|
+
if (options.download !== undefined && !['auto', 'never'].includes(options.download))
|
|
212
|
+
throw new ConfigurationError("download must be 'auto' or 'never'");
|
|
213
|
+
if (options.onProgress !== undefined && typeof options.onProgress !== 'function')
|
|
214
|
+
throw new ConfigurationError('onProgress must be a function');
|
|
215
|
+
const browserCacheDir = options.browserCacheDir === undefined ? undefined : pathOption(options.browserCacheDir, 'browserCacheDir');
|
|
216
|
+
const env = { ...process.env, ...options.serverEnv };
|
|
217
|
+
const root = pathOption(options.runtimeDir ?? env.EOKA_RUNTIME_DIR ?? tmpdir(), 'runtimeDir');
|
|
218
|
+
const scope = lifecycleScope(options);
|
|
219
|
+
let runtimeDir;
|
|
220
|
+
const runtimeOwner = {};
|
|
221
|
+
try {
|
|
222
|
+
const server = await resolveServerBinary({ ...(options.serverPath === undefined ? {} : { serverPath: options.serverPath }), env, signal: scope.options.signal });
|
|
223
|
+
checkAbort(scope.options.signal);
|
|
224
|
+
remainingTimeout(scope.deadline);
|
|
225
|
+
const chromePath = options.executablePath ?? env.EOKA_CHROME_PATH;
|
|
226
|
+
let expectedBrowserVersion;
|
|
227
|
+
if (chromePath !== undefined) {
|
|
228
|
+
params.executablePath = await executablePath(chromePath, 'executablePath');
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
const installation = await installBrowser({
|
|
232
|
+
...(browserCacheDir === undefined ? {} : { browserCacheDir }),
|
|
233
|
+
...(options.download === undefined ? {} : { download: options.download }),
|
|
234
|
+
...(options.onProgress === undefined ? {} : { onProgress: options.onProgress }),
|
|
235
|
+
...localOptions(scope.options, scope.deadline),
|
|
236
|
+
env,
|
|
237
|
+
});
|
|
238
|
+
params.executablePath = installation.executablePath;
|
|
239
|
+
expectedBrowserVersion = installation.buildId;
|
|
240
|
+
}
|
|
241
|
+
checkAbort(scope.options.signal);
|
|
242
|
+
remainingTimeout(scope.deadline);
|
|
243
|
+
runtimeDir = await runtimeDirectory(root);
|
|
244
|
+
params.runtimeDir = runtimeDir;
|
|
245
|
+
const childEnv = { ...env, TMPDIR: runtimeDir, TMP: runtimeDir, TEMP: runtimeDir };
|
|
246
|
+
const redactionValues = [params.proxy?.username, params.proxy?.password].filter((value) => typeof value === 'string' && value.length > 0);
|
|
247
|
+
return await Browser.start(scope.options, server.executablePath, childEnv, 'browser.launch', params, scope.deadline, redactionValues, runtimeDir, server.expectedServerVersion, expectedBrowserVersion, runtimeOwner);
|
|
248
|
+
}
|
|
249
|
+
catch (primary) {
|
|
250
|
+
const failure = lifecycleFailure(primary, scope.options.signal, scope.deadline);
|
|
251
|
+
if (runtimeDir !== undefined)
|
|
252
|
+
await removeClosedRuntime(runtimeDir, runtimeOwner.transport, failure);
|
|
253
|
+
throw failure;
|
|
254
|
+
}
|
|
255
|
+
finally {
|
|
256
|
+
scope.dispose();
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
static async connect(options) {
|
|
260
|
+
validateEndpoint(options.browserWSEndpoint);
|
|
261
|
+
for (const name of ['executablePath', 'headless', 'sandbox', 'viewport', 'runtimeDir', 'browserCacheDir', 'download', 'onProgress', 'userDataDir', 'userAgent', 'timezone', 'proxy']) {
|
|
262
|
+
if (Object.hasOwn(options, name))
|
|
263
|
+
throw new ConfigurationError(`connect does not accept the launch option ${name}`);
|
|
264
|
+
}
|
|
265
|
+
const scope = lifecycleScope(options);
|
|
266
|
+
try {
|
|
267
|
+
const env = { ...process.env, ...options.serverEnv };
|
|
268
|
+
const server = await resolveServerBinary({ ...(options.serverPath === undefined ? {} : { serverPath: options.serverPath }), env, signal: scope.options.signal });
|
|
269
|
+
return await Browser.start(scope.options, server.executablePath, env, 'browser.connect', { wsEndpoint: options.browserWSEndpoint }, scope.deadline, [options.browserWSEndpoint], undefined, server.expectedServerVersion);
|
|
270
|
+
}
|
|
271
|
+
catch (primary) {
|
|
272
|
+
throw lifecycleFailure(primary, scope.options.signal, scope.deadline);
|
|
273
|
+
}
|
|
274
|
+
finally {
|
|
275
|
+
scope.dispose();
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
static async start(options, serverPath, env, method, params, deadline, redactionValues, runtimeDir, expectedServerVersion, expectedBrowserVersion, runtimeOwner) {
|
|
279
|
+
checkAbort(options.signal);
|
|
280
|
+
const transport = await SidecarTransport.start({
|
|
281
|
+
serverPath,
|
|
282
|
+
env,
|
|
283
|
+
redactionValues,
|
|
284
|
+
...localOptions(options, deadline),
|
|
285
|
+
...(options.shutdownTimeoutMs === undefined ? {} : { shutdownTimeoutMs: options.shutdownTimeoutMs }),
|
|
286
|
+
...(runtimeOwner === undefined ? {} : { onTransport: (transport) => { runtimeOwner.transport = transport; } }),
|
|
287
|
+
});
|
|
288
|
+
try {
|
|
289
|
+
if (expectedServerVersion !== undefined && transport.hello.serverVersion !== expectedServerVersion) {
|
|
290
|
+
throw new ProtocolError(`Packaged server version mismatch: expected ${expectedServerVersion}, received ${transport.hello.serverVersion}`, { requestState: 'acknowledged' });
|
|
291
|
+
}
|
|
292
|
+
const cloudflare = resolveCloudflareOptions(options.autoSolveCloudflare);
|
|
293
|
+
if (cloudflare !== undefined) {
|
|
294
|
+
if (!transport.hasCapability('cloudflareAutoSolve'))
|
|
295
|
+
throw new ConfigurationError('autoSolveCloudflare requires a server with the cloudflareAutoSolve capability');
|
|
296
|
+
params = { ...params, autoSolveCloudflare: cloudflare };
|
|
297
|
+
}
|
|
298
|
+
const session = await transport.invoke(method, params, localOptions(options, deadline));
|
|
299
|
+
if (!session || !['owned', 'borrowed'].includes(session.ownership) || typeof session.browserVersion !== 'string' || !session.browserVersion.trim() || (method === 'browser.connect' && session.ownership !== 'borrowed')) {
|
|
300
|
+
throw new ProtocolError('Invalid browser session ownership or browserVersion', { requestState: 'acknowledged' });
|
|
301
|
+
}
|
|
302
|
+
if (expectedBrowserVersion !== undefined && session.browserVersion !== expectedBrowserVersion && session.browserVersion !== `Chrome/${expectedBrowserVersion}` && session.browserVersion !== `HeadlessChrome/${expectedBrowserVersion}`) {
|
|
303
|
+
throw new ProtocolError(`Managed browser version mismatch: expected ${expectedBrowserVersion}, received ${session.browserVersion}`, { requestState: 'acknowledged' });
|
|
304
|
+
}
|
|
305
|
+
checkAbort(options.signal, 'acknowledged');
|
|
306
|
+
return new Browser(transport, session, options.shutdownTimeoutMs ?? 45_000, runtimeDir);
|
|
307
|
+
}
|
|
308
|
+
catch (primary) {
|
|
309
|
+
try {
|
|
310
|
+
await transport.close();
|
|
311
|
+
}
|
|
312
|
+
catch (cleanup) {
|
|
313
|
+
throw new AggregateError([primary, cleanup], 'Browser lifecycle failed and sidecar cleanup failed; browser cleanup may be uncertain', { cause: primary });
|
|
314
|
+
}
|
|
315
|
+
throw primary;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
get hello() { return this.#transport.hello; }
|
|
319
|
+
get sessionInfo() { return this.#sessionInfo; }
|
|
320
|
+
get ownership() { return this.#sessionInfo.ownership; }
|
|
321
|
+
get browserVersion() { return this.#sessionInfo.browserVersion; }
|
|
322
|
+
supports(method) { return this.#transport.supports(method); }
|
|
323
|
+
hasCapability(name) { return this.#capabilities.has(name); }
|
|
324
|
+
invoke(method, params, options) {
|
|
325
|
+
return this.#transport.invoke(method, params, options);
|
|
326
|
+
}
|
|
327
|
+
page(id) { return new Page(this, id); }
|
|
328
|
+
operation(id) { return new Operation(this, id); }
|
|
329
|
+
recording(id) { return new Recording(this, id); }
|
|
330
|
+
async tabs(options) {
|
|
331
|
+
return (await this.invoke('browser.tabs', {}, options)).tabs;
|
|
332
|
+
}
|
|
333
|
+
async pages(options) {
|
|
334
|
+
return (await this.tabs(options)).map(tab => this.page(tab.id));
|
|
335
|
+
}
|
|
336
|
+
operations(params = {}, options) {
|
|
337
|
+
return this.invoke('operations.list', params, options);
|
|
338
|
+
}
|
|
339
|
+
newPage(url, options = {}) {
|
|
340
|
+
const result = this.createPage(url, options);
|
|
341
|
+
const owner = result.then(() => { this.#pageOwners.delete(owner); }, () => { this.#pageOwners.delete(owner); });
|
|
342
|
+
this.#pageOwners.add(owner);
|
|
343
|
+
return result;
|
|
344
|
+
}
|
|
345
|
+
async createPage(url, options) {
|
|
346
|
+
if (url !== undefined && (typeof url !== 'string' || !url.trim()))
|
|
347
|
+
throw new ConfigurationError('newPage URL must be a nonempty string');
|
|
348
|
+
validateTimeout(options.timeoutMs, 'timeoutMs');
|
|
349
|
+
const deadline = options.timeoutMs === undefined ? undefined : performance.now() + options.timeoutMs;
|
|
350
|
+
const tracked = this.#transport.invokeTracked('browser.new_page', {}, localOptions(options, deadline));
|
|
351
|
+
let result;
|
|
352
|
+
try {
|
|
353
|
+
result = await tracked.result;
|
|
354
|
+
}
|
|
355
|
+
catch (primary) {
|
|
356
|
+
if (primary instanceof Error && 'requestState' in primary && primary.requestState === 'not_sent')
|
|
357
|
+
throw primary;
|
|
358
|
+
const cleanup = this.cleanupAbandonedCreation(tracked.completion);
|
|
359
|
+
try {
|
|
360
|
+
await cleanup;
|
|
361
|
+
}
|
|
362
|
+
catch (failure) {
|
|
363
|
+
this.#creationCleanupFailures.push(failure);
|
|
364
|
+
throw new AggregateError([primary, failure], 'New page creation failed and late-created-tab cleanup failed', { cause: primary });
|
|
365
|
+
}
|
|
366
|
+
throw primary;
|
|
367
|
+
}
|
|
368
|
+
const page = this.page(result.pageId);
|
|
369
|
+
try {
|
|
370
|
+
if (url !== undefined)
|
|
371
|
+
await page.goto(url, { ...options, ...localOptions(options, deadline) });
|
|
372
|
+
checkAbort(options.signal, 'acknowledged');
|
|
373
|
+
return page;
|
|
374
|
+
}
|
|
375
|
+
catch (primary) {
|
|
376
|
+
try {
|
|
377
|
+
const cleanup = await this.#transport.invokeCleanup('browser.close_tab', { pageId: page.id }, { timeoutMs: this.#shutdownTimeoutMs });
|
|
378
|
+
if (cleanup.cleanupError)
|
|
379
|
+
throw new TransportError('CleanupFailed', 'Created tab was closed but input cleanup failed', { data: cleanup });
|
|
380
|
+
}
|
|
381
|
+
catch (cleanup) {
|
|
382
|
+
throw new AggregateError([primary, cleanup], 'New page failed and created-tab cleanup failed', { cause: primary });
|
|
383
|
+
}
|
|
384
|
+
throw primary;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
async cleanupAbandonedCreation(completion) {
|
|
388
|
+
const deadline = performance.now() + this.#shutdownTimeoutMs;
|
|
389
|
+
let timer;
|
|
390
|
+
let timedOut = false;
|
|
391
|
+
try {
|
|
392
|
+
const result = await Promise.race([
|
|
393
|
+
completion,
|
|
394
|
+
new Promise((_, reject) => {
|
|
395
|
+
timer = setTimeout(() => {
|
|
396
|
+
timedOut = true;
|
|
397
|
+
reject(new TransportError('CleanupUncertain', 'Abandoned page creation did not return its page ID within the cleanup deadline; a borrowed browser may retain the unknown tab'));
|
|
398
|
+
}, this.#shutdownTimeoutMs);
|
|
399
|
+
}),
|
|
400
|
+
]);
|
|
401
|
+
const cleanup = await this.#transport.invokeCleanup('browser.close_tab', { pageId: result.pageId }, { timeoutMs: remainingTimeout(deadline) ?? this.#shutdownTimeoutMs });
|
|
402
|
+
if (cleanup.cleanupError)
|
|
403
|
+
throw new TransportError('CleanupFailed', 'Late-created tab was closed but input cleanup failed', { data: cleanup });
|
|
404
|
+
}
|
|
405
|
+
catch (cause) {
|
|
406
|
+
const uncertainty = new TransportError('CleanupUncertain', 'Could not establish cleanup of an abandoned page creation', { cause });
|
|
407
|
+
if (timedOut) {
|
|
408
|
+
try {
|
|
409
|
+
await this.#transport.close();
|
|
410
|
+
}
|
|
411
|
+
catch (cleanup) {
|
|
412
|
+
throw new AggregateError([uncertainty, cleanup], 'Abandoned page creation and sidecar cleanup remain uncertain', { cause: uncertainty });
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
throw uncertainty;
|
|
416
|
+
}
|
|
417
|
+
finally {
|
|
418
|
+
clearTimeout(timer);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
close() {
|
|
422
|
+
this.#closePromise ??= (async () => {
|
|
423
|
+
this.#transport.quiesce();
|
|
424
|
+
await Promise.all(this.#pageOwners);
|
|
425
|
+
let transportFailure;
|
|
426
|
+
try {
|
|
427
|
+
await this.#transport.close();
|
|
428
|
+
}
|
|
429
|
+
catch (failure) {
|
|
430
|
+
transportFailure = failure;
|
|
431
|
+
}
|
|
432
|
+
let runtimeFailure;
|
|
433
|
+
try {
|
|
434
|
+
await this.#runtimeCleanup;
|
|
435
|
+
}
|
|
436
|
+
catch (failure) {
|
|
437
|
+
runtimeFailure = failure;
|
|
438
|
+
}
|
|
439
|
+
const failures = [...this.#creationCleanupFailures];
|
|
440
|
+
if (transportFailure !== undefined)
|
|
441
|
+
failures.unshift(transportFailure);
|
|
442
|
+
if (runtimeFailure !== undefined)
|
|
443
|
+
failures.push(runtimeFailure);
|
|
444
|
+
if (failures.length === 1 && this.#creationCleanupFailures.length === 0 && runtimeFailure === undefined)
|
|
445
|
+
throw transportFailure;
|
|
446
|
+
if (failures.length)
|
|
447
|
+
throw new AggregateError(failures, 'Browser disposal includes resource cleanup failures', { cause: failures[0] });
|
|
448
|
+
})();
|
|
449
|
+
return this.#closePromise;
|
|
450
|
+
}
|
|
451
|
+
[Symbol.asyncDispose]() { return this.close(); }
|
|
452
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { MethodName, MethodParams, MethodResults } from './generated/protocol.js';
|
|
2
|
+
export interface CallOptions {
|
|
3
|
+
signal?: AbortSignal;
|
|
4
|
+
timeoutMs?: number;
|
|
5
|
+
operationId?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface InvokeClient {
|
|
8
|
+
invoke<M extends MethodName>(method: M, params: MethodParams[M], options?: CallOptions): Promise<MethodResults[M]>;
|
|
9
|
+
supports?(method: string): boolean;
|
|
10
|
+
hasCapability?(name: string): boolean;
|
|
11
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Options for the server-side Cloudflare challenge watcher. */
|
|
2
|
+
export interface CloudflareOptions {
|
|
3
|
+
/** Poll interval in milliseconds. Defaults to 500. */
|
|
4
|
+
intervalMs?: number;
|
|
5
|
+
/** Deadline for each challenge solve. Defaults to 30000. */
|
|
6
|
+
timeoutMs?: number;
|
|
7
|
+
}
|
|
8
|
+
export interface ResolvedCloudflareOptions {
|
|
9
|
+
intervalMs: number;
|
|
10
|
+
timeoutMs: number;
|
|
11
|
+
}
|
|
12
|
+
export declare function resolveCloudflareOptions(value: boolean | CloudflareOptions | undefined): ResolvedCloudflareOptions | undefined;
|