@cbxss/eoka 0.1.0-beta.10 → 0.1.0-beta.12

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 CHANGED
@@ -11,20 +11,19 @@ Requires Node.js 24.21+ (ESM only). Supported platforms: Linux x64/arm64 (glibc
11
11
  ## Quick start
12
12
 
13
13
  ```js
14
+ import { writeFile } from "node:fs/promises";
14
15
  import { Browser } from "@cbxss/eoka";
15
16
 
16
- const browser = await Browser.launch();
17
- try {
18
- const page = await browser.newPage("https://example.com");
19
- console.log(await page.title());
20
- await page.screenshotToFile({ path: "./example.png" });
21
- } finally {
22
- await browser.close();
23
- }
17
+ await using browser = await Browser.launch();
18
+ const page = await browser.newPage("https://example.com");
19
+ console.log(await page.title());
20
+ await writeFile("example.png", await page.screenshot());
24
21
  ```
25
22
 
26
23
  The first launch downloads a pinned Chrome for Testing build (about 200 MB) into a per-user cache. Later launches reuse it.
27
24
 
25
+ `await using` closes the browser when the script or the enclosing block ends, including when it throws. Without it, call `await browser.close()` in a `finally`. A browser that is never closed keeps Chrome and your Node.js process running.
26
+
28
27
  ## Pages
29
28
 
30
29
  ```js
@@ -36,7 +35,7 @@ await page.click("button[type=submit]", {
36
35
 
37
36
  await page.waitForText("Welcome");
38
37
  const heading = await page.getText("h1");
39
- const count = await page.evaluate("()=>document.querySelectorAll('li').length");
38
+ const count = await page.evaluate(() => document.querySelectorAll("li").length);
40
39
  ```
41
40
 
42
41
  String targets are CSS selectors. An action resolves only after its result is verified. `click`, `type`, `pressKey`, `submit` and `drag` need an `expect` that describes the result.
@@ -45,6 +44,81 @@ String targets are CSS selectors. An action resolves only after its result is ve
45
44
  - **Waits:** `waitFor`, `waitForVisible`, `waitForText`
46
45
  - **Actions:** `goto`, `fill`, `select`, `hover`, `click`, `type`, `pressKey`, `submit`, `drag`
47
46
 
47
+ `evaluate(fn, args)` runs a function in the page and returns its result. Pass a function or its source as a string. Only the source is sent, so the function cannot see variables from your script; pass them through `args`. Arguments and the result must be JSON-compatible (no `undefined`, `NaN`, `Date` or DOM nodes) and at most 1 MiB. `execute(fn, args)` is for side effects: it runs the function and discards the result.
48
+
49
+ ```js
50
+ const total = await page.evaluate((a, b) => a + b, [2, 3]); // 5
51
+ await page.execute(() => window.scrollTo(0, document.body.scrollHeight));
52
+ ```
53
+
54
+ Every page-scoped operation in the `eoka` CLI's catalog is available under `page.ops`, generated from that catalog: console and error logs, cookies and storage, network recording and interception, downloads, JavaScript policy, dialogs and more. Inputs are typed; results are untyped for now. Tabs, recording and the browser lifecycle keep their own methods on `Browser` and `Page`. Catalog actions such as `page.ops.reload()` return their operation record, including when the outcome is unverified, so check `outcome` on it. These operations include ones that read and write local files; see the protocol reference before passing untrusted input.
55
+
56
+ ```js
57
+ await page.ops.networkRecordStart();
58
+ const logs = await page.ops.console({ clear: true });
59
+ const cookies = await page.ops.cookies();
60
+ ```
61
+
62
+ ### Timeouts
63
+
64
+ For an action, `timeoutMs` is how long the server keeps trying. The default is 30 seconds.
65
+
66
+ ```js
67
+ await page.fill("#email", "ada@example.com", { timeoutMs: 5000 });
68
+ ```
69
+
70
+ When that time runs out the call rejects with `code: "action_timeout"` and a message that gives the reason, such as `fill "#email" timed out after 5000 ms: target not found. The page received no input.` If the input was sent but `expect` was not met, the message says so. The action is not undone, so check the page before you act again.
71
+
72
+ The SDK waits 10 seconds past the action deadline for the server's answer before it gives up with `DeadlineExceeded`. `actionOptions.timeout_ms` is the same server deadline under its protocol name. Set it together with `timeoutMs` only when you want a different local deadline; both are then used exactly as given. Unknown keys in `actionOptions` are rejected before anything is sent.
73
+
74
+ For every other call, `timeoutMs` is a local deadline for that call, and server-side waits have their own option (`waitTimeoutMs`, `resolveTimeoutMs`). A call without `timeoutMs` is abandoned after `defaultTimeoutMs`: 120 seconds, or the server-side wait it asked for plus 10 seconds when that is longer. Change it with `Browser.launch({ defaultTimeoutMs })`; `null` turns it off. An expired local deadline undoes nothing: `error.requestState` tells you whether the request was `not_sent` or `may_have_been_sent`.
75
+
76
+ ### Parallel calls
77
+
78
+ The sidecar accepts a limited number of requests at once (`browser.hello.limits.maxInFlight`). Calls beyond that limit wait inside the SDK and are sent as earlier ones finish, so `Promise.all` over many calls works. A waiting call still honors its `timeoutMs` and `signal`, and then rejects with `requestState: "not_sent"`.
79
+
80
+ ## Dialogs and stalled pages
81
+
82
+ An open JavaScript dialog (`alert`, `confirm`, `prompt` or a "leave this page?" prompt) and a navigation that is still waiting for its response both stop Chrome from answering anything else on that tab. Calls on such a tab reject promptly, say what is in the way and what to do next:
83
+
84
+ | `error.code` | What happened | Next step |
85
+ | --- | --- | --- |
86
+ | `DialogOpen` | The call was made on a tab that has a dialog open. | `page.ops.dialogAccept()` or `page.ops.dialogDismiss()` |
87
+ | `dialog_open` | An action's own input opened a dialog. The input was sent. | Clear the dialog, then check the page. |
88
+ | `NavigationPending` | The tab is waiting for a navigation that has not answered. | Wait, or navigate again with `page.goto(url)`. |
89
+ | `navigation_timeout` | A navigation got no response within its deadline. The load was stopped and the tab still shows the previous page. | Allow more time, or check the URL and network. |
90
+ | `PageUnresponsive` | The page answers nothing and neither cause is known. | Let it settle, or continue in `browser.newPage(url)`. |
91
+
92
+ The message keeps the server's own text, including the dialog's message or the pending URL, and ends with the next step. An action that was interrupted after its input was sent reports `navigation_pending` or `page_unresponsive` in the same way as `dialog_open`. All of this needs a server with the `pageBlockers` capability (`browser.hasCapability("pageBlockers")`); without it such calls run into their deadline instead.
93
+
94
+ ```js
95
+ try {
96
+ await page.click("#delete", {
97
+ actionOptions: { expect: { kind: "hidden", target: { query: { kind: "css", selector: "#row" } } } },
98
+ });
99
+ } catch (error) {
100
+ if (!(error instanceof EokaError) || error.code !== "dialog_open") throw error;
101
+ await page.ops.dialogAccept(); // { prompt_text: "Ada" } answers a prompt()
102
+ }
103
+ ```
104
+
105
+ On `DialogOpen` and `NavigationPending`, `error.blocker` describes the obstacle: `{ kind: "dialog", dialogType, message, url, elapsedMs }` or `{ kind: "navigation", url, elapsedMs }`. The action codes in `snake_case` come from the operation record, which carries the text but no `blocker`.
106
+
107
+ ```js
108
+ try {
109
+ console.log(await page.title());
110
+ } catch (error) {
111
+ if (!(error instanceof EokaError) || error.blocker === undefined) throw error;
112
+ if (error.blocker.kind === "dialog") {
113
+ console.log(error.blocker.dialogType, error.blocker.message);
114
+ await page.ops.dialogDismiss();
115
+ } else {
116
+ console.log("still waiting for", error.blocker.url);
117
+ await page.goto("https://example.com"); // or page.ops.reload() to return to the page still displayed
118
+ }
119
+ }
120
+ ```
121
+
48
122
  ## Shadow DOM and Turnstile
49
123
 
50
124
  `page.frames()` lists every frame, including cross-origin OOPIFs. `page.clickShadow(selector, { frameId?, resolveTimeoutMs? })` searches the frame's light DOM and every shadow root (closed roots included), maps the matched node's center to viewport coordinates, and clicks with human-like movement. `resolveTimeoutMs` bounds the server-side resolution; `CallOptions.timeoutMs` remains the RPC deadline and defaults to the resolution deadline plus 10 seconds when omitted:
@@ -98,7 +172,8 @@ await Browser.launch({
98
172
  download: "auto", // "never" fails when Chrome isn't cached
99
173
  browserCacheDir: "/opt/eoka/cache",
100
174
  viewport: { width: 1280, height: 720, deviceScaleFactor: 1 },
101
- timeoutMs: 30000,
175
+ timeoutMs: 30000, // deadline for the launch itself
176
+ defaultTimeoutMs: 120000, // default; for later calls without timeoutMs
102
177
  });
103
178
  ```
104
179
 
@@ -134,6 +209,8 @@ try {
134
209
  }
135
210
  ```
136
211
 
212
+ `error.stack` includes the line of your code that made the call. A failed action also carries `record`, `receipt` and, as `cause`, the server's own message. `error.requestState` says whether the request was `not_sent`, `may_have_been_sent` or `acknowledged`, and `error.blocker` is set when a dialog or a pending navigation is in the way (see [Dialogs and stalled pages](#dialogs-and-stalled-pages)).
213
+
137
214
  ## Linux and Docker
138
215
 
139
216
  Chrome needs its usual system libraries even in headless mode. On Debian:
@@ -168,4 +245,6 @@ npm run build
168
245
  npm test
169
246
  ```
170
247
 
248
+ [EVALS.md](https://github.com/shrimp-software/eoka-tools/blob/main/clients/node/EVALS.md) describes the real-browser suites that check caller mistakes, misbehaving pages and the examples in this README, and how to run them.
249
+
171
250
  Releases are automatic: merge a version bump to `main` and approve the `npm-prerelease` deployment.
@@ -0,0 +1,2 @@
1
+ import type { Action, Expectation, OperationRecord } from './generated/protocol.js';
2
+ export declare function actionFailureMessage(action: Action, expect: Expectation | null | undefined, timeoutMs: number | undefined, record: OperationRecord): string;
@@ -0,0 +1,99 @@
1
+ import { blockedPage, inspectBeforeContinuing, nodeNextStep } from './page-blockers.js';
2
+ const preparationReasons = ['target not found', 'target disconnected', 'target disabled', 'target hidden', 'target readonly or not editable', 'target moving', 'target covered'];
3
+ const notRolledBack = `The action was not rolled back; ${inspectBeforeContinuing}.`;
4
+ const interruptions = {
5
+ dialog: ['then a dialog blocked the page before the result could be verified', 'could not start because a dialog is open on the page'],
6
+ navigation: ['then a pending navigation blocked the page before the result could be verified', 'could not start because the page is waiting on a navigation'],
7
+ unresponsive: ['then the page stopped answering before the result could be verified', 'could not start because the page is not answering'],
8
+ };
9
+ function fields(value) {
10
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
11
+ }
12
+ function locatorLabel(target) {
13
+ const query = fields(fields(target)?.query);
14
+ if (!query)
15
+ return 'the target';
16
+ if (query.kind === 'css')
17
+ return `"${String(query.selector)}"`;
18
+ if (query.kind === 'role')
19
+ return `role "${String(query.role)}"`;
20
+ if (query.kind === 'text' || query.kind === 'placeholder')
21
+ return `${query.kind} "${String(query.text)}"`;
22
+ return `${String(query.kind)} ${String(query.id)}`;
23
+ }
24
+ function addressLabel(address) {
25
+ try {
26
+ const url = new URL(address);
27
+ return `"${`${url.origin === 'null' ? url.protocol : url.origin}${url.pathname}`.slice(0, 200)}"`;
28
+ }
29
+ catch {
30
+ return 'the requested URL';
31
+ }
32
+ }
33
+ function subject(action) {
34
+ const kind = String(action.kind);
35
+ if (action.target !== undefined)
36
+ return `${kind} ${locatorLabel(action.target)}`;
37
+ if (typeof action.key === 'string')
38
+ return `${kind} "${action.key}"`;
39
+ if (typeof action.url === 'string')
40
+ return `${kind} ${addressLabel(action.url)}`;
41
+ return kind;
42
+ }
43
+ function expectationLabel(expectation) {
44
+ const expect = fields(expectation);
45
+ if (!expect)
46
+ return 'the expectation';
47
+ const target = locatorLabel(expect.target);
48
+ switch (expect.kind) {
49
+ case 'url': return `url ${expect.contains === true ? 'contains' : 'equals'} "${String(expect.value)}"`;
50
+ case 'text': return `text of ${target} ${expect.contains === true ? 'contains' : 'equals'} "${String(expect.value)}"`;
51
+ case 'visible':
52
+ case 'hidden':
53
+ case 'focused': return `${target} is ${expect.kind}`;
54
+ case 'enabled': return `${target} is ${expect.enabled === false ? 'disabled' : 'enabled'}`;
55
+ case 'checked': return `${target} is ${expect.checked === false ? 'unchecked' : 'checked'}`;
56
+ case 'value': return `${target} has the expected value`;
57
+ case 'selected': return `${target} has the expected selection`;
58
+ case 'all': return Array.isArray(expect.conditions) ? expect.conditions.map(expectationLabel).join(' and ') : 'all conditions';
59
+ case 'document_ready': return 'the document is ready';
60
+ case 'download_started': return 'a download starts';
61
+ default: return String(expect.kind);
62
+ }
63
+ }
64
+ function submittedValues(action) {
65
+ return [action.value, action.text].filter((value) => typeof value === 'string' && value !== '');
66
+ }
67
+ export function actionFailureMessage(action, expect, timeoutMs, record) {
68
+ const detail = record.error;
69
+ if (record.state === 'running' || detail == null) {
70
+ return `Operation ${record.id} is ${record.state} with outcome ${record.outcome}; verified completion was not established.`;
71
+ }
72
+ const what = subject(action);
73
+ const dispatch = record.receipt?.dispatch ?? (record.dispatch_intent ? 'may_have_been_sent' : 'not_sent');
74
+ const dispatched = dispatch === 'acknowledged' ? 'was dispatched' : 'may have been dispatched';
75
+ const blocked = blockedPage(record.error_code, detail.code);
76
+ if (blocked !== undefined) {
77
+ const told = detail.message.trimEnd();
78
+ const report = `${told}${/[.!?]$/.test(told) ? '' : '.'} ${nodeNextStep(blocked)}`;
79
+ if (blocked === 'navigation_timeout') {
80
+ return dispatch === 'not_sent' ? `${what} did not complete. ${report}` : `${what} ${dispatched}, but the navigation got no response. ${report}`;
81
+ }
82
+ const [interrupted, refused] = interruptions[blocked];
83
+ return dispatch === 'not_sent' ? `${what} ${refused}. ${report} The page received no input.` : `${what} ${dispatched}, ${interrupted}. ${report} ${notRolledBack}`;
84
+ }
85
+ if (record.error_code !== 'action_timeout') {
86
+ const reason = detail.message.replace(/[.\s]+$/, '');
87
+ return dispatch === 'not_sent' ? `${what} failed: ${reason}. The page received no input.` : `${what} ${dispatched} and failed: ${reason}. ${notRolledBack}`;
88
+ }
89
+ const limit = timeoutMs === undefined ? 'its deadline' : `${timeoutMs} ms`;
90
+ if (dispatch !== 'not_sent') {
91
+ const unmet = expect == null ? 'its result was not verified' : `its expectation (${expectationLabel(expect)}) was not met`;
92
+ return `${what} ${dispatched}, but ${unmet} within ${limit}. ${notRolledBack}`;
93
+ }
94
+ const texts = [detail.message, ...submittedValues(action).map(value => detail.message.replaceAll('[redacted]', value))];
95
+ const mentions = (text) => texts.some(candidate => candidate.includes(text));
96
+ const reason = preparationReasons.find(mentions);
97
+ const waiting = reason !== undefined ? `: ${reason}` : mentions('queue admission') ? ' while waiting for earlier actions on this page' : '';
98
+ return `${what} timed out after ${limit}${waiting}. The page received no input.`;
99
+ }
package/dist/browser.d.ts CHANGED
@@ -11,6 +11,8 @@ export interface BrowserOptions {
11
11
  signal?: AbortSignal;
12
12
  timeoutMs?: number;
13
13
  shutdownTimeoutMs?: number;
14
+ /** Local deadline for each later call that passes no `timeoutMs`; `null` disables it. Defaults to 120000. */
15
+ defaultTimeoutMs?: number | null;
14
16
  /** Have the server watch every tab and solve full-page Cloudflare challenges. */
15
17
  autoSolveCloudflare?: boolean | CloudflareOptions;
16
18
  }
package/dist/browser.js CHANGED
@@ -2,11 +2,12 @@ import { access, chmod, mkdir, mkdtemp, rm, stat } from 'node:fs/promises';
2
2
  import { constants } from 'node:fs';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { join, resolve } from 'node:path';
5
+ import { traceCallSites, withCallSite } from './call-site.js';
5
6
  import { ConfigurationError, EokaError, ProtocolError, TransportError } from './errors.js';
6
7
  import { Operation } from './operations.js';
7
8
  import { Page } from './page.js';
8
9
  import { Recording } from './recording.js';
9
- import { SidecarTransport } from './transport.js';
10
+ import { SidecarTransport, defaultCallTimeoutMs } from './transport.js';
10
11
  import { installBrowser } from './browser-install.js';
11
12
  import { resolveCloudflareOptions } from './cloudflare.js';
12
13
  import { resolveServerBinary } from './server-binary.js';
@@ -61,6 +62,7 @@ function localOptions(options, deadline) {
61
62
  function lifecycleScope(options) {
62
63
  validateTimeout(options.timeoutMs, 'timeoutMs');
63
64
  validateTimeout(options.shutdownTimeoutMs, 'shutdownTimeoutMs');
65
+ validateTimeout(options.defaultTimeoutMs ?? undefined, 'defaultTimeoutMs');
64
66
  checkAbort(options.signal);
65
67
  const deadline = options.timeoutMs === undefined ? undefined : performance.now() + options.timeoutMs;
66
68
  const controller = new AbortController();
@@ -283,6 +285,7 @@ export class Browser {
283
285
  redactionValues,
284
286
  ...localOptions(options, deadline),
285
287
  ...(options.shutdownTimeoutMs === undefined ? {} : { shutdownTimeoutMs: options.shutdownTimeoutMs }),
288
+ ...(options.defaultTimeoutMs === undefined ? {} : { defaultTimeoutMs: options.defaultTimeoutMs }),
286
289
  ...(runtimeOwner === undefined ? {} : { onTransport: (transport) => { runtimeOwner.transport = transport; } }),
287
290
  });
288
291
  try {
@@ -295,7 +298,10 @@ export class Browser {
295
298
  throw new ConfigurationError('autoSolveCloudflare requires a server with the cloudflareAutoSolve capability');
296
299
  params = { ...params, autoSolveCloudflare: cloudflare };
297
300
  }
298
- const session = await transport.invoke(method, params, localOptions(options, deadline));
301
+ const sessionOptions = localOptions(options, deadline);
302
+ if (sessionOptions.timeoutMs === undefined && options.defaultTimeoutMs != null)
303
+ sessionOptions.timeoutMs = Math.max(options.defaultTimeoutMs, defaultCallTimeoutMs);
304
+ const session = await transport.invoke(method, params, sessionOptions);
299
305
  if (!session || !['owned', 'borrowed'].includes(session.ownership) || typeof session.browserVersion !== 'string' || !session.browserVersion.trim() || (method === 'browser.connect' && session.ownership !== 'borrowed')) {
300
306
  throw new ProtocolError('Invalid browser session ownership or browserVersion', { requestState: 'acknowledged' });
301
307
  }
@@ -419,7 +425,7 @@ export class Browser {
419
425
  }
420
426
  }
421
427
  close() {
422
- this.#closePromise ??= (async () => {
428
+ this.#closePromise ??= withCallSite(this.close, async () => {
423
429
  this.#transport.quiesce();
424
430
  await Promise.all(this.#pageOwners);
425
431
  let transportFailure;
@@ -445,8 +451,10 @@ export class Browser {
445
451
  throw transportFailure;
446
452
  if (failures.length)
447
453
  throw new AggregateError(failures, 'Browser disposal includes resource cleanup failures', { cause: failures[0] });
448
- })();
454
+ });
449
455
  return this.#closePromise;
450
456
  }
451
457
  [Symbol.asyncDispose]() { return this.close(); }
452
458
  }
459
+ traceCallSites(Browser);
460
+ traceCallSites(Browser.prototype, ['close']);
@@ -0,0 +1,5 @@
1
+ type Method = (this: never, ...args: never[]) => unknown;
2
+ export declare function withCallSite<T>(boundary: Method, run: () => Promise<T>): Promise<T>;
3
+ export declare function traced<F extends Method>(method: F): F;
4
+ export declare function traceCallSites(owner: object, skip?: readonly string[]): void;
5
+ export {};
@@ -0,0 +1,46 @@
1
+ const wrapperFrame = 'eokaTracedCall';
2
+ let depth = 0;
3
+ function capture(boundary) {
4
+ const site = {};
5
+ Error.captureStackTrace(site, boundary);
6
+ return site;
7
+ }
8
+ function extendStack(error, site) {
9
+ if (!(error instanceof Error) || typeof error.stack !== 'string' || typeof site.stack !== 'string')
10
+ return error;
11
+ const own = error.stack.split('\n').filter(line => !line.includes(wrapperFrame));
12
+ const caller = site.stack.split('\n').slice(1).filter(line => !line.includes(wrapperFrame) && !own.includes(line));
13
+ const stack = [...own, ...caller].join('\n');
14
+ if (stack !== error.stack)
15
+ error.stack = stack;
16
+ return error;
17
+ }
18
+ export function withCallSite(boundary, run) {
19
+ const site = capture(boundary);
20
+ return run().catch((error) => { throw extendStack(error, site); });
21
+ }
22
+ export function traced(method) {
23
+ const wrapper = function eokaTracedCall(...args) {
24
+ if (depth > 0)
25
+ return method.apply(this, args);
26
+ const site = capture(wrapper);
27
+ depth++;
28
+ let result;
29
+ try {
30
+ result = method.apply(this, args);
31
+ }
32
+ finally {
33
+ depth--;
34
+ }
35
+ return result instanceof Promise ? result.catch((error) => { throw extendStack(error, site); }) : result;
36
+ };
37
+ return wrapper;
38
+ }
39
+ export function traceCallSites(owner, skip = []) {
40
+ for (const name of Object.getOwnPropertyNames(owner)) {
41
+ const descriptor = Object.getOwnPropertyDescriptor(owner, name);
42
+ if (name === 'constructor' || skip.includes(name) || typeof descriptor?.value !== 'function')
43
+ continue;
44
+ Object.defineProperty(owner, name, { ...descriptor, value: traced(descriptor.value) });
45
+ }
46
+ }
@@ -0,0 +1,3 @@
1
+ export declare const maximumTimer = 2147483647;
2
+ export declare const serverGraceMs = 10000;
3
+ export declare function duration(value: number | undefined, fallback: number, name: string): number;
@@ -0,0 +1,10 @@
1
+ import { ConfigurationError } from './errors.js';
2
+ export const maximumTimer = 2_147_483_647;
3
+ export const serverGraceMs = 10_000;
4
+ export function duration(value, fallback, name) {
5
+ const result = value ?? fallback;
6
+ if (!Number.isFinite(result) || result < 0 || result > maximumTimer) {
7
+ throw new ConfigurationError(`${name} must be finite and between 0 and ${maximumTimer}`, { requestState: 'not_sent' });
8
+ }
9
+ return result;
10
+ }
package/dist/errors.d.ts CHANGED
@@ -1,10 +1,11 @@
1
- import type { ActionReceipt, ServerError } from './generated/protocol.js';
1
+ import type { ActionReceipt, PageBlocker, ServerError } from './generated/protocol.js';
2
2
  export type RequestState = 'not_sent' | 'may_have_been_sent' | 'acknowledged';
3
3
  export interface ErrorDetails {
4
4
  requestId?: number | undefined;
5
5
  operationId?: string | undefined;
6
6
  requestState?: RequestState | undefined;
7
7
  receipt?: ActionReceipt | undefined;
8
+ blocker?: PageBlocker | undefined;
8
9
  data?: unknown;
9
10
  stderr?: string | undefined;
10
11
  cause?: unknown;
@@ -15,6 +16,7 @@ export declare class EokaError extends Error {
15
16
  operationId?: string | undefined;
16
17
  requestState?: RequestState | undefined;
17
18
  receipt?: ActionReceipt | undefined;
19
+ blocker?: PageBlocker | undefined;
18
20
  data?: unknown;
19
21
  stderr?: string | undefined;
20
22
  constructor(code: string, message: string, details?: ErrorDetails);
package/dist/errors.js CHANGED
@@ -1,9 +1,11 @@
1
+ import { pageBlocker, withNodeNextStep } from './page-blockers.js';
1
2
  export class EokaError extends Error {
2
3
  code;
3
4
  requestId;
4
5
  operationId;
5
6
  requestState;
6
7
  receipt;
8
+ blocker;
7
9
  data;
8
10
  stderr;
9
11
  constructor(code, message, details = {}) {
@@ -14,6 +16,7 @@ export class EokaError extends Error {
14
16
  this.operationId = details.operationId;
15
17
  this.requestState = details.requestState;
16
18
  this.receipt = details.receipt;
19
+ this.blocker = details.blocker ?? pageBlocker(details.data);
17
20
  this.data = details.data;
18
21
  this.stderr = details.stderr;
19
22
  }
@@ -33,7 +36,7 @@ export class ProtocolError extends EokaError {
33
36
  export class ServerOperationError extends EokaError {
34
37
  wireError;
35
38
  constructor(wireError, details = {}) {
36
- super(wireError.code, wireError.message, {
39
+ super(wireError.code, withNodeNextStep(wireError.message, [wireError.code, wireError.data?.detail?.code], wireError.data), {
37
40
  ...details,
38
41
  data: wireError.data,
39
42
  operationId: wireError.data?.operation_id ?? details.operationId,
@@ -0,0 +1,102 @@
1
+ import type { CallOptions } from "../client.js";
2
+ import type { MethodParams, MethodResults } from "./protocol.js";
3
+ export declare const catalogMethods: readonly ["back", "captcha.datadome", "captcha.detect", "captcha.inject", "captcha.turnstile", "clear_cookies", "click", "click_shadow", "clone_from", "console", "content", "cookies", "delete_cookie", "dialog.accept", "dialog.dismiss", "double_click", "download.cancel", "download.get", "download.list", "download.start", "download.wait", "dump_storage", "emulate", "errors", "eval", "exec", "exists", "fake_camera", "fetch", "fill", "find", "forward", "frame_eval", "frames", "get_attribute", "get_text", "headers", "hover", "info", "intercept.add", "intercept.list", "intercept.log", "intercept.remove", "js.allow", "js.block", "js.list", "js.mode", "js.remove", "key", "key.down", "key.up", "load_state", "mouse.down", "mouse.move", "mouse.up", "network.clear", "network.export", "network.log", "network.record.start", "network.record.status", "network.record.stop", "network.show", "network.wait", "observe", "open", "release_all_inputs", "reload", "save_state", "screenshot", "scroll", "select", "set_cookie", "set_storage", "snapshot", "spa.info", "spa.navigate", "storage", "text", "wait", "wasm.find", "wasm.info", "wasm.read", "wasm.write"];
4
+ export type CatalogMethod = (typeof catalogMethods)[number];
5
+ /** The declared fields of a generated params type, without its index signature. */
6
+ type Declared<T> = {
7
+ [K in keyof T as string extends K ? never : number extends K ? never : K]: T[K];
8
+ };
9
+ /** An operation's input without the page ID, which the page supplies. */
10
+ export type CatalogInput<M extends CatalogMethod> = Omit<Declared<MethodParams[M]>, "pageId">;
11
+ export interface CatalogPage {
12
+ readonly id: string;
13
+ invoke<M extends CatalogMethod>(method: M, params: MethodParams[M], options?: CallOptions): Promise<MethodResults[M]>;
14
+ }
15
+ /** Every catalog operation as a method bound to one page. */
16
+ export declare function catalogOperations(page: CatalogPage): {
17
+ back: (input?: CatalogInput<"back">, options?: CallOptions) => Promise<unknown>;
18
+ captchaDatadome: (input?: CatalogInput<"captcha.datadome">, options?: CallOptions) => Promise<unknown>;
19
+ captchaDetect: (input?: CatalogInput<"captcha.detect">, options?: CallOptions) => Promise<unknown>;
20
+ captchaInject: (input: CatalogInput<"captcha.inject">, options?: CallOptions) => Promise<unknown>;
21
+ captchaTurnstile: (input?: CatalogInput<"captcha.turnstile">, options?: CallOptions) => Promise<unknown>;
22
+ clearCookies: (input?: CatalogInput<"clear_cookies">, options?: CallOptions) => Promise<unknown>;
23
+ click: (input: CatalogInput<"click">, options?: CallOptions) => Promise<unknown>;
24
+ clickShadow: (input: CatalogInput<"click_shadow">, options?: CallOptions) => Promise<unknown>;
25
+ cloneFrom: (input: CatalogInput<"clone_from">, options?: CallOptions) => Promise<unknown>;
26
+ console: (input?: CatalogInput<"console">, options?: CallOptions) => Promise<unknown>;
27
+ content: (input?: CatalogInput<"content">, options?: CallOptions) => Promise<unknown>;
28
+ cookies: (input?: CatalogInput<"cookies">, options?: CallOptions) => Promise<unknown>;
29
+ deleteCookie: (input: CatalogInput<"delete_cookie">, options?: CallOptions) => Promise<unknown>;
30
+ dialogAccept: (input?: CatalogInput<"dialog.accept">, options?: CallOptions) => Promise<unknown>;
31
+ dialogDismiss: (input?: CatalogInput<"dialog.dismiss">, options?: CallOptions) => Promise<unknown>;
32
+ doubleClick: (input: CatalogInput<"double_click">, options?: CallOptions) => Promise<unknown>;
33
+ downloadCancel: (input: CatalogInput<"download.cancel">, options?: CallOptions) => Promise<unknown>;
34
+ downloadGet: (input: CatalogInput<"download.get">, options?: CallOptions) => Promise<unknown>;
35
+ downloadList: (input?: CatalogInput<"download.list">, options?: CallOptions) => Promise<unknown>;
36
+ downloadStart: (input: CatalogInput<"download.start">, options?: CallOptions) => Promise<unknown>;
37
+ downloadWait: (input: CatalogInput<"download.wait">, options?: CallOptions) => Promise<unknown>;
38
+ dumpStorage: (input?: CatalogInput<"dump_storage">, options?: CallOptions) => Promise<unknown>;
39
+ emulate: (input?: CatalogInput<"emulate">, options?: CallOptions) => Promise<unknown>;
40
+ errors: (input?: CatalogInput<"errors">, options?: CallOptions) => Promise<unknown>;
41
+ eval: (input?: CatalogInput<"eval">, options?: CallOptions) => Promise<unknown>;
42
+ exec: (input?: CatalogInput<"exec">, options?: CallOptions) => Promise<unknown>;
43
+ exists: (input: CatalogInput<"exists">, options?: CallOptions) => Promise<unknown>;
44
+ fakeCamera: (input: CatalogInput<"fake_camera">, options?: CallOptions) => Promise<unknown>;
45
+ fetch: (input: CatalogInput<"fetch">, options?: CallOptions) => Promise<unknown>;
46
+ fill: (input: CatalogInput<"fill">, options?: CallOptions) => Promise<unknown>;
47
+ find: (input: CatalogInput<"find">, options?: CallOptions) => Promise<unknown>;
48
+ forward: (input?: CatalogInput<"forward">, options?: CallOptions) => Promise<unknown>;
49
+ frameEval: (input: CatalogInput<"frame_eval">, options?: CallOptions) => Promise<unknown>;
50
+ frames: (input?: CatalogInput<"frames">, options?: CallOptions) => Promise<unknown>;
51
+ getAttribute: (input: CatalogInput<"get_attribute">, options?: CallOptions) => Promise<unknown>;
52
+ getText: (input: CatalogInput<"get_text">, options?: CallOptions) => Promise<unknown>;
53
+ headers: (input: CatalogInput<"headers">, options?: CallOptions) => Promise<unknown>;
54
+ hover: (input: CatalogInput<"hover">, options?: CallOptions) => Promise<unknown>;
55
+ info: (input?: CatalogInput<"info">, options?: CallOptions) => Promise<unknown>;
56
+ interceptAdd: (input: CatalogInput<"intercept.add">, options?: CallOptions) => Promise<unknown>;
57
+ interceptList: (input?: CatalogInput<"intercept.list">, options?: CallOptions) => Promise<unknown>;
58
+ interceptLog: (input?: CatalogInput<"intercept.log">, options?: CallOptions) => Promise<unknown>;
59
+ interceptRemove: (input: CatalogInput<"intercept.remove">, options?: CallOptions) => Promise<unknown>;
60
+ jsAllow: (input: CatalogInput<"js.allow">, options?: CallOptions) => Promise<unknown>;
61
+ jsBlock: (input: CatalogInput<"js.block">, options?: CallOptions) => Promise<unknown>;
62
+ jsList: (input?: CatalogInput<"js.list">, options?: CallOptions) => Promise<unknown>;
63
+ jsMode: (input: CatalogInput<"js.mode">, options?: CallOptions) => Promise<unknown>;
64
+ jsRemove: (input: CatalogInput<"js.remove">, options?: CallOptions) => Promise<unknown>;
65
+ key: (input: CatalogInput<"key">, options?: CallOptions) => Promise<unknown>;
66
+ keyDown: (input: CatalogInput<"key.down">, options?: CallOptions) => Promise<unknown>;
67
+ keyUp: (input: CatalogInput<"key.up">, options?: CallOptions) => Promise<unknown>;
68
+ loadState: (input: CatalogInput<"load_state">, options?: CallOptions) => Promise<unknown>;
69
+ mouseDown: (input: CatalogInput<"mouse.down">, options?: CallOptions) => Promise<unknown>;
70
+ mouseMove: (input: CatalogInput<"mouse.move">, options?: CallOptions) => Promise<unknown>;
71
+ mouseUp: (input: CatalogInput<"mouse.up">, options?: CallOptions) => Promise<unknown>;
72
+ networkClear: (input?: CatalogInput<"network.clear">, options?: CallOptions) => Promise<unknown>;
73
+ networkExport: (input: CatalogInput<"network.export">, options?: CallOptions) => Promise<unknown>;
74
+ networkLog: (input?: CatalogInput<"network.log">, options?: CallOptions) => Promise<unknown>;
75
+ networkRecordStart: (input?: CatalogInput<"network.record.start">, options?: CallOptions) => Promise<unknown>;
76
+ networkRecordStatus: (input?: CatalogInput<"network.record.status">, options?: CallOptions) => Promise<unknown>;
77
+ networkRecordStop: (input?: CatalogInput<"network.record.stop">, options?: CallOptions) => Promise<unknown>;
78
+ networkShow: (input: CatalogInput<"network.show">, options?: CallOptions) => Promise<unknown>;
79
+ networkWait: (input?: CatalogInput<"network.wait">, options?: CallOptions) => Promise<unknown>;
80
+ observe: (input?: CatalogInput<"observe">, options?: CallOptions) => Promise<unknown>;
81
+ open: (input: CatalogInput<"open">, options?: CallOptions) => Promise<unknown>;
82
+ releaseAllInputs: (input?: CatalogInput<"release_all_inputs">, options?: CallOptions) => Promise<unknown>;
83
+ reload: (input?: CatalogInput<"reload">, options?: CallOptions) => Promise<unknown>;
84
+ saveState: (input: CatalogInput<"save_state">, options?: CallOptions) => Promise<unknown>;
85
+ screenshot: (input?: CatalogInput<"screenshot">, options?: CallOptions) => Promise<unknown>;
86
+ scroll: (input: CatalogInput<"scroll">, options?: CallOptions) => Promise<unknown>;
87
+ select: (input: CatalogInput<"select">, options?: CallOptions) => Promise<unknown>;
88
+ setCookie: (input: CatalogInput<"set_cookie">, options?: CallOptions) => Promise<unknown>;
89
+ setStorage: (input: CatalogInput<"set_storage">, options?: CallOptions) => Promise<unknown>;
90
+ snapshot: (input?: CatalogInput<"snapshot">, options?: CallOptions) => Promise<unknown>;
91
+ spaInfo: (input?: CatalogInput<"spa.info">, options?: CallOptions) => Promise<unknown>;
92
+ spaNavigate: (input: CatalogInput<"spa.navigate">, options?: CallOptions) => Promise<unknown>;
93
+ storage: (input?: CatalogInput<"storage">, options?: CallOptions) => Promise<unknown>;
94
+ text: (input?: CatalogInput<"text">, options?: CallOptions) => Promise<unknown>;
95
+ wait: (input?: CatalogInput<"wait">, options?: CallOptions) => Promise<unknown>;
96
+ wasmFind: (input: CatalogInput<"wasm.find">, options?: CallOptions) => Promise<unknown>;
97
+ wasmInfo: (input?: CatalogInput<"wasm.info">, options?: CallOptions) => Promise<unknown>;
98
+ wasmRead: (input: CatalogInput<"wasm.read">, options?: CallOptions) => Promise<unknown>;
99
+ wasmWrite: (input: CatalogInput<"wasm.write">, options?: CallOptions) => Promise<unknown>;
100
+ };
101
+ export type CatalogOperations = ReturnType<typeof catalogOperations>;
102
+ export {};