aboutsummaryrefslogtreecommitdiff
path: root/src/cdp/types.ts
blob: 6119b69bb49be0a1f74e994262bb14c9a6750fcc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import type { Result } from "../util/result";
import { isRecord } from "../util/guards";
import type { CdpError } from "./errors";

export type CdpEvent = {
  readonly method: string;
  readonly params: unknown;
  readonly sessionId?: string;
};

export type CdpRawMessage = {
  readonly id?: number;
  readonly method?: string;
  readonly params?: Record<string, unknown>;
  readonly result?: unknown;
  readonly error?: { readonly message: string; readonly code?: number };
  readonly sessionId?: string;
};

export type DialogInfo = {
  readonly type: "alert" | "confirm" | "prompt" | "beforeunload";
  readonly message: string;
  readonly defaultPrompt?: string;
};

export type TabInfo = {
  readonly targetId: string;
  readonly title: string;
  readonly url: string;
  readonly owned?: boolean;
};

export type PageInfo = {
  readonly url: string;
  readonly title: string;
  readonly width: number;
  readonly height: number;
  readonly scrollX: number;
  readonly scrollY: number;
  readonly pageWidth: number;
  readonly pageHeight: number;
};

export type DaemonStatus = {
  readonly alive: boolean;
  readonly sessionId: string | null;
  readonly namespace: string;
  readonly remoteBrowserId?: string;
};

export const isCdpRawMessage = (v: unknown): v is CdpRawMessage => {
  if (!isRecord(v)) return false;
  const id = v["id"];
  if (id !== undefined && typeof id !== "number") return false;
  const method = v["method"];
  if (method !== undefined && typeof method !== "string") return false;
  const sessionId = v["sessionId"];
  if (sessionId !== undefined && typeof sessionId !== "string") return false;
  const errVal = v["error"];
  if (errVal !== undefined) {
    if (!isRecord(errVal)) return false;
    if (typeof errVal["message"] !== "string") return false;
    const code = errVal["code"];
    if (code !== undefined && typeof code !== "number") return false;
  }
  return true;
};

export const DEFAULT_TIMEOUT_MS = 15_000;

export type CdpTransport = {
  connect(url: string, opts?: { timeoutMs?: number }): Promise<Result<void, CdpError>>;
  close(): Promise<void>;
  request(
    method: string,
    params: Record<string, unknown>,
    opts?: { sessionId?: string | null; timeoutMs?: number },
  ): Promise<Result<unknown, CdpError>>;
  events(): AsyncIterable<CdpEvent>;
  state(): "open" | "closed" | "connecting";
  onClose(cb: () => void): () => void;
};