diff --git a/extension/src/service_worker.ts b/extension/src/service_worker.ts index 954b81c..91dbc4a 100644 --- a/extension/src/service_worker.ts +++ b/extension/src/service_worker.ts @@ -2,252 +2,38 @@ import { ModCDPServer } from "../../js/src/server/ModCDPServer.js"; -const bridge = ModCDPServer as Record; const started_at = new Date().toISOString(); -const DEFAULT_REVERSEWS_URL = "ws://127.0.0.1:29292"; -const DEFAULT_REVERSEWS_RECONNECT_INTERVAL_MS = 2_000; -const DEFAULT_NATIVE_HOST_NAME = "com.modcdp.bridge"; -const DEFAULT_NATIVE_RECONNECT_INTERVAL_MS = 2_000; -const downstream_clients: Record = {}; -const upstream_servers: Record = {}; -const client_id_by_config_session = new Map(); -let active_downstream_client_id: string | null = null; -let next_downstream_client_id = 1; -let next_log_id = 1; -const self_transports: Record = {}; -const self_custom = { commands: new Set(), events: new Set() }; -const self_log: any[] = []; -const compact = (value: unknown) => { - try { - return JSON.parse(JSON.stringify(value ?? null)); - } catch (error) { - return { - unserializable: true, - error: error instanceof Error ? error.message : String(error), - }; - } -}; -const trimLog = (log: any[]) => (log.length = Math.min(log.length, 80)); -const routeFor = (method: string) => { - if (method.startsWith("Mod.") || method.startsWith("Custom.")) return "service_worker"; - const routes = (bridge.routes ?? {}) as Record; - const route = - routes[method] ?? - Object.entries(routes) - .filter(([pattern]) => pattern.endsWith(".*") && method.startsWith(pattern.slice(0, -1))) - .sort((a, b) => b[0].length - a[0].length)[0]?.[1] ?? - routes["*.*"] ?? - "chrome_debugger"; - if (route === "loopback_cdp") return "loopback"; - if (route === "chrome_debugger") return "debugger"; - if (route === "auto") return bridge.loopback_cdp_url ? "loopback" : "debugger"; - return route; -}; -const upstreamServer = (id: string) => - (upstream_servers[id] ??= { - id, - log: [], - }); -const configuredClient = (params: unknown, session_id?: string | null) => { - const at = new Date().toISOString(); - const id = - (session_id && client_id_by_config_session.get(session_id)) || `downstream_client_${next_downstream_client_id++}`; - if (session_id) client_id_by_config_session.set(session_id, id); - active_downstream_client_id = id; - const configure = compact(params); - const client = (downstream_clients[id] ??= { - id, - configured_at: at, - commands: 0, - events: 0, - sessions: {}, - recent: [], - }); - client.updated_at = at; - client.configure = configure; - client.downstream_transport = configure?.upstream?.upstream_mode ?? "unknown"; - client.route_config = { - upstream: configure?.upstream ?? {}, - client: configure?.client ?? {}, - server: configure?.server ?? {}, - }; - if (client.downstream_transport !== "reversews") { - bridge.stopReverseBridge?.("non-reverse downstream connected"); - } - return client; -}; -const downstreamClient = (session_id?: string | null) => { - const at = new Date().toISOString(); - const client_id = - (session_id && client_id_by_config_session.get(session_id)) || - active_downstream_client_id || - "unconfigured_downstream_client"; - const client = (downstream_clients[client_id] ??= { - id: client_id, - commands: 0, - events: 0, - sessions: {}, - recent: [], - first_seen: at, - last_seen: at, - }); - const id = session_id || "root"; - const session = (client.sessions[id] ??= { - id, - commands: 0, - events: 0, - first_seen: at, - last_seen: at, - }); - return { at, client_id, client, session }; -}; -const logTraffic = (direction: "command" | "event", name: string, payload: unknown, session_id?: string | null) => { - const { at, client_id, client, session } = downstreamClient(session_id); - const upstream = routeFor(name); - const from = direction === "command" ? client_id : upstream; - const to = direction === "command" ? upstream : client_id; - const route_path = from === "service_worker" || to === "service_worker" ? [from, to] : [from, "service_worker", to]; - const entry: any = { - id: `log_${next_log_id++}`, - at, - direction, - method: name, - payload: compact(payload), - route_path, - downstream_transport: client.downstream_transport ?? "unknown", - cdp_session_id: session_id ?? null, - }; - direction === "event" ? client.events++ : client.commands++; - direction === "event" ? session.events++ : session.commands++; - direction === "event" ? (session.last_event = name) : (session.last_command = name); - client.last_seen = at; - session.last_seen = at; - client.log ??= client.recent ?? []; - client.log.unshift(entry); - trimLog(client.log); - const endpointLog = upstream === "service_worker" ? self_log : upstreamServer(upstream).log; - endpointLog.unshift(entry); - trimLog(endpointLog); - return entry; -}; -if (bridge) { - const handleCommand = bridge.handleCommand?.bind(bridge); - if (handleCommand) { - bridge.handleCommand = async (method: string, params?: unknown, session_id?: string | null) => { - if (method === "Mod.configure") configuredClient(params, session_id); - const entry = logTraffic("command", method, params, session_id); - try { - const result = await handleCommand(method, params, session_id); - entry.result = compact(result); - entry.completed_at = new Date().toISOString(); - return result; - } catch (error) { - entry.error = error instanceof Error ? error.message : String(error); - entry.completed_at = new Date().toISOString(); - throw error; - } - }; - } - bridge.addEventListener?.((event: string, _payload: unknown, session_id?: string | null) => - logTraffic("event", event, _payload, session_id), - ); - for (const [method, key] of [ - ["startReverseBridge", "reverse"], - ["stopReverseBridge", "reverse"], - ["startNativeBridge", "native"], - ["startNatsBridge", "nats"], - ]) { - const start = bridge[method]?.bind(bridge); - if (start) { - bridge[method] = (...args: unknown[]) => { - const result = start(...args); - self_transports[key] = { - args: compact(args), - result: compact(result), - updated_at: new Date().toISOString(), - }; - return result; - }; - } - } - for (const [method, key] of [ - ["addCustomCommand", "commands"], - ["addCustomEvent", "events"], - ]) { - const add = bridge[method]?.bind(bridge); - if (add) { - bridge[method] = (name: string, ...args: unknown[]) => { - self_custom[key as "commands" | "events"].add(name); - return add(name, ...args); - }; - } - } +function startConfiguredTransports() { + void ModCDPServer.ensureOffscreenKeepAlive(); + ModCDPServer.startDownstreamTransports(); } -const startConfiguredTransports = () => { - bridge.startOffscreenKeepAlive?.(); - bridge.startReverseBridge?.(DEFAULT_REVERSEWS_URL, { - reconnect_interval_ms: DEFAULT_REVERSEWS_RECONNECT_INTERVAL_MS, - }); - bridge.startNativeBridge?.(DEFAULT_NATIVE_HOST_NAME, { - reconnect_interval_ms: DEFAULT_NATIVE_RECONNECT_INTERVAL_MS, - }); -}; - startConfiguredTransports(); chrome.runtime.onInstalled.addListener(startConfiguredTransports); chrome.runtime.onStartup.addListener(startConfiguredTransports); chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => { if (message?.type !== "modcdp.options.status") return false; - const self = { - id: "self", - runtime: { - extension_id: chrome.runtime.id, - service_worker_url: chrome.runtime.getURL("modcdp/service_worker.js"), - options_url: chrome.runtime.getURL("options.html"), - started_at, - }, - server: { - __ModCDPServerVersion: bridge.__ModCDPServerVersion, - routes: bridge.routes, - loopback_cdp_url: bridge.loopback_cdp_url, - browser_token: bridge.browser_token ? "set" : null, - cdp_send_timeout_ms: bridge.cdp_send_timeout_ms, - loopback_execution_context_timeout_ms: bridge.loopback_execution_context_timeout_ms, - ws_connect_error_settle_timeout_ms: bridge.ws_connect_error_settle_timeout_ms, - native_bridge_attempts: bridge.native_bridge_attempts, - native_bridge_connected: bridge.native_bridge_connected, - native_bridge_last_error: bridge.native_bridge_last_error, - }, - ...(Object.keys(self_transports).length ? { transports: self_transports } : {}), - custom: { - commands: [...self_custom.commands], - events: [...self_custom.events], - }, - log: self_log, - }; sendResponse({ now: new Date().toISOString(), - self, - downstream_clients, - upstream_servers: { - ...upstream_servers, - ...(bridge.loopback_cdp_url - ? { - loopback: { - ...upstream_servers.loopback, - id: "loopback", - url: bridge.loopback_cdp_url, - log: upstream_servers.loopback?.log ?? [], - }, - } - : {}), - debugger: { - ...upstream_servers.debugger, - id: "debugger", - log: upstream_servers.debugger?.log ?? [], + self: { + id: "self", + runtime: { + extension_id: chrome.runtime.id, + service_worker_url: chrome.runtime.getURL("modcdp/service_worker.js"), + options_url: chrome.runtime.getURL("options.html"), + started_at, + }, + server: { + __ModCDPServerVersion: ModCDPServer.__ModCDPServerVersion, + routes: ModCDPServer.routes, + loopback_cdp_url: ModCDPServer.loopback_cdp_url, + browser_token: ModCDPServer.browser_token ? "set" : null, + cdp_send_timeout_ms: ModCDPServer.cdp_send_timeout_ms, + loopback_execution_context_timeout_ms: ModCDPServer.loopback_execution_context_timeout_ms, + ws_connect_error_settle_timeout_ms: ModCDPServer.ws_connect_error_settle_timeout_ms, + downstream_transports: ModCDPServer.downstreamTransports(), }, }, }); diff --git a/go/examples/demo/main.go b/go/examples/demo/main.go index 27b010d..ab0606f 100644 --- a/go/examples/demo/main.go +++ b/go/examples/demo/main.go @@ -22,13 +22,14 @@ import ( "regexp" "runtime" "strings" - "sync" "time" modcdp "github.com/browserbase/modcdp/go/modcdp" "golang.org/x/term" ) +const demoCDPSendTimeoutMS = 60_000 +const demoExecutionContextTimeoutMS = 60_000 const reverseTransportWaitTimeoutMS = 60_000 func optionsFor(mode, upstreamMode, cdpURL, extensionPath string, launchOptions modcdp.LaunchOptions) modcdp.Options { @@ -46,19 +47,28 @@ func optionsFor(mode, upstreamMode, cdpURL, extensionPath string, launchOptions return modcdp.Options{ Launcher: modcdp.LauncherConfig{LauncherMode: map[bool]string{true: "remote", false: "local"}[cdpURL != ""], LauncherOptions: launchOptions}, Upstream: upstream, - Injector: modcdp.InjectorConfig{InjectorMode: "auto", InjectorExtensionPath: extensionPath}, - Client: modcdp.ClientConfig{ClientRoutes: clientRoutesFor(mode)}, + Injector: modcdp.InjectorConfig{ + InjectorMode: "auto", + InjectorExtensionPath: extensionPath, + InjectorExecutionContextTimeoutMS: demoExecutionContextTimeoutMS, + }, + Client: modcdp.ClientConfig{ClientRoutes: clientRoutesFor(mode), ClientCDPSendTimeoutMS: demoCDPSendTimeoutMS}, } } server := &modcdp.ServerConfig{ - ServerRoutes: serverRoutesFor(mode, upstreamMode), + ServerRoutes: serverRoutesFor(mode, upstreamMode), + ServerLoopbackExecutionContextTimeoutMS: demoExecutionContextTimeoutMS, } return modcdp.Options{ Launcher: modcdp.LauncherConfig{LauncherMode: map[bool]string{true: "remote", false: "local"}[cdpURL != ""], LauncherOptions: launchOptions}, Upstream: upstream, - Injector: modcdp.InjectorConfig{InjectorMode: "auto", InjectorExtensionPath: extensionPath}, - Client: modcdp.ClientConfig{ClientRoutes: clientRoutesFor(mode)}, - Server: server, + Injector: modcdp.InjectorConfig{ + InjectorMode: "auto", + InjectorExtensionPath: extensionPath, + InjectorExecutionContextTimeoutMS: demoExecutionContextTimeoutMS, + }, + Client: modcdp.ClientConfig{ClientRoutes: clientRoutesFor(mode), ClientCDPSendTimeoutMS: demoCDPSendTimeoutMS}, + Server: server, } } @@ -67,17 +77,17 @@ func clientRoutesFor(mode string) map[string]string { if mode == "direct" { route = "direct_cdp" } - return map[string]string{ - "Mod.*": "service_worker", - "Custom.*": "service_worker", - "*.*": route, - "Target.setDiscoverTargets": "direct_cdp", - "Target.createTarget": "direct_cdp", - "Target.activateTarget": "direct_cdp", + routes := map[string]string{ + "Mod.*": "service_worker", + "Custom.*": "service_worker", + "Runtime.*": "service_worker", + "*.*": route, } + return routes } func serverRoutesFor(mode, upstreamMode string) map[string]string { + _ = upstreamMode serverRoute := "auto" if mode == "loopback" { serverRoute = "loopback_cdp" @@ -89,11 +99,6 @@ func serverRoutesFor(mode, upstreamMode string) map[string]string { "Custom.*": "service_worker", "*.*": serverRoute, } - if mode == "loopback" || upstreamMode == "reversews" || upstreamMode == "nativemessaging" || upstreamMode == "nats" { - routes["Target.setDiscoverTargets"] = "loopback_cdp" - routes["Target.createTarget"] = "loopback_cdp" - routes["Target.activateTarget"] = "loopback_cdp" - } return routes } @@ -219,17 +224,6 @@ func main() { } cdp := modcdp.New(optionsFor(mode, upstreamMode, cdpURL, extensionPath, launchOptions)) - var ( - eventsMu sync.Mutex - targetCreatedEvents []modcdp.TargetTargetCreatedEvent - pageTargetEvents []map[string]any - ) - cdp.Target.On.TargetCreated(func(event modcdp.TargetTargetCreatedEvent) { - fmt.Printf("Target.targetCreated -> %s\n", event.TargetID()) - eventsMu.Lock() - targetCreatedEvents = append(targetCreatedEvents, event) - eventsMu.Unlock() - }) if err := cdp.Connect(); err != nil { log.Fatalf("connect: %v", err) @@ -241,7 +235,10 @@ func main() { fmt.Println("connect timing ->", string(b)) } - serverConfig := map[string]any{"server_routes": serverRoutesFor(mode, upstreamMode)} + serverConfig := map[string]any{ + "server_routes": serverRoutesFor(mode, upstreamMode), + "server_loopback_execution_context_timeout_ms": demoExecutionContextTimeoutMS, + } configureParams := map[string]any{ "upstream": map[string]any{"upstream_mode": upstreamMode}, "client": map[string]any{"client_routes": clientRoutesFor(mode)}, @@ -289,32 +286,6 @@ func main() { fmt.Println("ping latency ->", string(b)) } - if mode == "debugger" { - if version, err := cdp.Browser.GetVersion(); err == nil { - b, _ := json.Marshal(version) - fmt.Println("Browser.getVersion ->", string(b)) - } else { - fmt.Println("Browser.getVersion -> (debugger route rejected:", err, ")") - } - runtimeEval := mustMap(mustSend(cdp, "Runtime.evaluate", map[string]any{ - "expression": "(() => 42)()", - "returnByValue": true, - }), "Runtime.evaluate") - runtimeResult := mustMap(runtimeEval["result"], "Runtime.evaluate.result") - if runtimeResult["value"] != float64(42) && runtimeResult["value"] != 42 { - log.Fatalf("unexpected Runtime.evaluate result: %v", runtimeEval) - } - b, _ := json.Marshal(runtimeEval) - fmt.Println("Runtime.evaluate ->", string(b)) - } else { - version, err := cdp.Browser.GetVersion() - if err != nil { - log.Fatalf("Browser.getVersion: %v", err) - } - b, _ := json.Marshal(version) - fmt.Println("Browser.getVersion ->", string(b)) - } - if r, err := cdp.Mod.Evaluate(map[string]any{ "expression": "({ extension_id: chrome.runtime.id })", }); err != nil { @@ -329,6 +300,73 @@ func main() { fmt.Println("Mod.evaluate ->", string(b)) } + topologyChecked := false + if mode != "direct" { + topologyRaw, err := cdp.Mod.GetTopology(nil) + if err != nil { + log.Fatalf("Mod.getTopology: %v", err) + } + topology := mustMap(topologyRaw, "Mod.getTopology") + rootFrameID := mustString(topology["rootFrameId"], "Mod.getTopology.rootFrameId") + frames := mustMap(topology["frames"], "Mod.getTopology.frames") + roots := mustMap(topology["roots"], "Mod.getTopology.roots") + contexts := mustMap(topology["contexts"], "Mod.getTopology.contexts") + if _, ok := frames[rootFrameID]; !ok { + log.Fatalf("Mod.getTopology frames missing root frame %s: %v", rootFrameID, frames) + } + hasDocumentRoot := false + for _, root := range roots { + rootMap, ok := root.(map[string]any) + if ok && rootMap["kind"] == "document" { + hasDocumentRoot = true + } + } + hasPiercerContext := false + for _, context := range contexts { + contextMap, ok := context.(map[string]any) + if ok && contextMap["world"] == "piercer" { + hasPiercerContext = true + } + } + if !hasDocumentRoot || !hasPiercerContext { + log.Fatalf("unexpected Mod.getTopology result: %v", topology) + } + topologyChecked = true + b, _ := json.Marshal(map[string]any{ + "rootFrameId": rootFrameID, + "frames": len(frames), + "roots": len(roots), + "contexts": len(contexts), + }) + fmt.Println("Mod.getTopology ->", string(b)) + } + + responseMiddlewareRegistrationRaw, err := cdp.Mod.AddMiddleware(modcdp.CustomMiddleware{ + Name: "Custom.echo", + Phase: "response", + Expression: `async (payload, next) => next({ ...payload, responseMiddleware: "ok" })`, + }) + if err != nil { + log.Fatalf("Mod.addMiddleware response: %v", err) + } + responseMiddlewareRegistration := mustMap(responseMiddlewareRegistrationRaw, "Mod.addMiddleware response") + if responseMiddlewareRegistration["registered"] != true || responseMiddlewareRegistration["phase"] != "response" { + log.Fatalf("unexpected response middleware registration: %v", responseMiddlewareRegistration) + } + + eventMiddlewareRegistrationRaw, err := cdp.Mod.AddMiddleware(modcdp.CustomMiddleware{ + Name: "Custom.demoEvent", + Phase: "event", + Expression: `async (payload, next) => next({ ...payload, eventMiddleware: "ok" })`, + }) + if err != nil { + log.Fatalf("Mod.addMiddleware event: %v", err) + } + eventMiddlewareRegistration := mustMap(eventMiddlewareRegistrationRaw, "Mod.addMiddleware event") + if eventMiddlewareRegistration["registered"] != true || eventMiddlewareRegistration["phase"] != "event" { + log.Fatalf("unexpected event middleware registration: %v", eventMiddlewareRegistration) + } + echoRegistrationRaw, err := cdp.Mod.AddCustomCommand(modcdp.CustomCommand{ Name: "Custom.echo", Expression: `async (params, method) => ({ echoed: params.value, method })`, @@ -341,69 +379,11 @@ func main() { log.Fatalf("unexpected Custom.echo registration: %v", echoRegistration) } echoResult := mustMap(mustSend(cdp, "Custom.echo", map[string]any{"value": "custom-command-ok"}), "Custom.echo") - if echoResult["echoed"] != "custom-command-ok" || echoResult["method"] != "Custom.echo" { + if echoResult["echoed"] != "custom-command-ok" || echoResult["method"] != "Custom.echo" || echoResult["responseMiddleware"] != "ok" { log.Fatalf("unexpected Custom.echo result: %v", echoResult) } - b, _ := json.Marshal(echoResult) - fmt.Println("Custom.echo ->", string(b)) - - tabCommandRegistrationRaw, err := cdp.Mod.AddCustomCommand(modcdp.CustomCommand{ - Name: "Custom.TabIdFromTargetId", - Expression: `async ({ targetId }) => { - const targets = await chrome.debugger.getTargets(); - const target = targets.find(target => target.id === targetId); - return { tabId: target?.tabId ?? null }; - }`, - }) - if err != nil { - log.Fatalf("Mod.addCustomCommand Custom.TabIdFromTargetId: %v", err) - } - tabCommandRegistration := mustMap(tabCommandRegistrationRaw, "Mod.addCustomCommand Custom.TabIdFromTargetId") - if tabCommandRegistration["registered"] != true { - log.Fatalf("unexpected TabIdFromTargetId registration: %v", tabCommandRegistration) - } - targetCommandRegistrationRaw, err := cdp.Mod.AddCustomCommand(modcdp.CustomCommand{ - Name: "Custom.targetIdFromTabId", - Expression: `async ({ tabId }) => { - const targets = await chrome.debugger.getTargets(); - const target = targets.find(target => target.type === "page" && target.tabId === tabId); - return { targetId: target?.id ?? null }; - }`, - }) - if err != nil { - log.Fatalf("Mod.addCustomCommand Custom.targetIdFromTabId: %v", err) - } - targetCommandRegistration := mustMap(targetCommandRegistrationRaw, "Mod.addCustomCommand Custom.targetIdFromTabId") - if targetCommandRegistration["registered"] != true { - log.Fatalf("unexpected targetIdFromTabId registration: %v", targetCommandRegistration) - } - for _, phase := range []string{"response", "event"} { - middlewareRegistrationRaw, err := cdp.Mod.AddMiddleware(modcdp.CustomMiddleware{ - Name: "*", - Phase: phase, - Expression: `async (payload, next) => { - const seen = new WeakSet(); - const visit = async value => { - if (!value || typeof value !== "object" || seen.has(value)) return; - seen.add(value); - if (!Array.isArray(value) && typeof value.targetId === "string" && value.tabId == null) { - const { tabId } = await cdp.send("Custom.TabIdFromTargetId", { targetId: value.targetId }); - if (tabId != null) value.tabId = tabId; - } - for (const child of Array.isArray(value) ? value : Object.values(value)) await visit(child); - }; - await visit(payload); - return next(payload); - }`, - }) - if err != nil { - log.Fatalf("Mod.addMiddleware %s: %v", phase, err) - } - middlewareRegistration := mustMap(middlewareRegistrationRaw, "Mod.addMiddleware "+phase) - if middlewareRegistration["registered"] != true || middlewareRegistration["phase"] != phase { - log.Fatalf("unexpected %s middleware registration: %v", phase, middlewareRegistration) - } - } + echoJSON, _ := json.Marshal(echoResult) + fmt.Println("Custom.echo ->", string(echoJSON)) demoEventCh := make(chan map[string]any, 16) cdp.On("Custom.demoEvent", func(data any) { @@ -430,128 +410,26 @@ func main() { log.Fatalf("unexpected Custom.demoEvent emit result: %v", emitResult) } demoEvent := waitForEvent(demoEventCh, "Custom.demoEvent", func(event map[string]any) bool { - return event["value"] == "custom-event-ok" + return event["value"] == "custom-event-ok" && event["eventMiddleware"] == "ok" }) fmt.Println("Custom.demoEvent ->", demoEvent) - pageTargetEventRegistrationRaw, err := cdp.Mod.AddCustomEvent(modcdp.CustomEvent{Name: "Custom.pageTargetUpdated"}) - if err != nil { - log.Fatalf("Mod.addCustomEvent Custom.pageTargetUpdated: %v", err) - } - pageTargetEventRegistration := mustMap(pageTargetEventRegistrationRaw, "Mod.addCustomEvent Custom.pageTargetUpdated") - if pageTargetEventRegistration["registered"] != true { - log.Fatalf("unexpected page target event registration: %v", pageTargetEventRegistration) - } - cdp.On("Custom.pageTargetUpdated", func(p any) { - event, _ := p.(map[string]any) - fmt.Printf("Custom.pageTargetUpdated -> %v\n", event) - eventsMu.Lock() - pageTargetEvents = append(pageTargetEvents, event) - eventsMu.Unlock() - }) - - if _, err := cdp.Target.SetDiscoverTargets(modcdp.TargetSetDiscoverTargetsParams{Discover: true}); err != nil { - log.Fatal(err) + runtimeEval := mustMap(mustSend(cdp, "Runtime.evaluate", map[string]any{ + "expression": "(() => 42)()", + "returnByValue": true, + }), "Runtime.evaluate") + runtimeResult := mustMap(runtimeEval["result"], "Runtime.evaluate.result") + if runtimeResult["value"] != float64(42) && runtimeResult["value"] != 42 { + log.Fatalf("unexpected Runtime.evaluate result: %v", runtimeEval) } - createdTarget, err := cdp.Target.CreateTarget(modcdp.TargetCreateTargetParams{ - URL: "https://example.com", - Background: modcdp.Bool(true), - }) - if err != nil { - log.Fatalf("Target.createTarget: %v", err) - } - createdTargetID := string(createdTarget.TargetID) - if createdTargetID == "" { - log.Fatalf("Target.createTarget returned no targetId: %v", createdTarget) - } - deadline := time.Now().Add(3 * time.Second) - var matchedTargetEvent *modcdp.TargetTargetCreatedEvent - for time.Now().Before(deadline) { - eventsMu.Lock() - for i := range targetCreatedEvents { - if targetCreatedEvents[i].TargetID() == createdTargetID { - matchedTargetEvent = &targetCreatedEvents[i] - break - } - } - eventsMu.Unlock() - if matchedTargetEvent != nil { - break - } - time.Sleep(20 * time.Millisecond) - } - if matchedTargetEvent == nil { - log.Fatalf("expected Target.targetCreated for %s", createdTargetID) - } - fmt.Println("normal event matched ->", createdTargetID) + runtimeJSON, _ := json.Marshal(runtimeEval) + fmt.Println("Runtime.evaluate ->", string(runtimeJSON)) - tabFromTargetRaw, err := cdp.Send("Custom.TabIdFromTargetId", map[string]any{"targetId": createdTargetID}) - if err != nil { - log.Fatalf("Custom.TabIdFromTargetId: %v", err) - } - tabFromTarget, _ := tabFromTargetRaw.(map[string]any) - b, _ = json.Marshal(tabFromTarget) - fmt.Println("Custom.TabIdFromTargetId ->", string(b)) - - if _, err := cdp.Target.ActivateTarget(modcdp.TargetActivateTargetParams{TargetID: modcdp.TargetTargetID(createdTargetID)}); err != nil { - log.Fatalf("Target.activateTarget: %v", err) - } - pageTargetEmitRaw, err := cdp.Mod.Evaluate(map[string]any{ - "params": map[string]any{"targetId": createdTargetID}, - "expression": `async ({ targetId }) => { - const targets = await chrome.debugger.getTargets(); - const target = targets.find(target => target.id === targetId); - if (!target?.id) throw new Error(` + "`target ${targetId} not found`" + `); - await cdp.emit("Custom.pageTargetUpdated", { targetId: target.id, url: target.url ?? null }); - return { emitted: true, targetId: target.id }; - }`, - }) - if err != nil { - log.Fatalf("Custom.pageTargetUpdated emit: %v", err) - } - pageTargetEmit := mustMap(pageTargetEmitRaw, "Custom.pageTargetUpdated emit") - if pageTargetEmit["emitted"] != true || pageTargetEmit["targetId"] != createdTargetID { - log.Fatalf("unexpected Custom.pageTargetUpdated emit result: %v", pageTargetEmit) - } - deadline = time.Now().Add(3 * time.Second) - var pageTarget map[string]any - for time.Now().Before(deadline) { - eventsMu.Lock() - for _, event := range pageTargetEvents { - if event["targetId"] == createdTargetID { - pageTarget = event - break - } - } - eventsMu.Unlock() - if pageTarget != nil { - break - } - time.Sleep(20 * time.Millisecond) + topologyLabel := "" + if topologyChecked { + topologyLabel = "topology, " } - if pageTarget == nil { - log.Fatalf("expected Custom.pageTargetUpdated for %s", createdTargetID) - } - - pageTargetTabID, _ := pageTarget["tabId"].(float64) - tabID, _ := tabFromTarget["tabId"].(float64) - if tabID != pageTargetTabID { - log.Fatalf("unexpected Custom.TabIdFromTargetId result: %v", tabFromTarget) - } - - targetFromTabRaw, err := cdp.Send("Custom.targetIdFromTabId", map[string]any{"tabId": pageTarget["tabId"]}) - if err != nil { - log.Fatalf("Custom.targetIdFromTabId: %v", err) - } - targetFromTab, _ := targetFromTabRaw.(map[string]any) - middlewareTabID, _ := targetFromTab["tabId"].(float64) - if targetFromTab["targetId"] != createdTargetID || middlewareTabID != pageTargetTabID { - log.Fatalf("unexpected Custom.targetIdFromTabId/middleware result: %v", targetFromTab) - } - b, _ = json.Marshal(targetFromTab) - fmt.Println("Custom.targetIdFromTabId ->", string(b)) - - fmt.Printf("\nSUCCESS (%s/%s): normal command, normal event, custom commands, custom event, and middleware all passed\n", mode, upstreamMode) + fmt.Printf("\nSUCCESS (%s/%s): native command, %scustom commands, custom event, and middleware all passed\n", mode, upstreamMode, topologyLabel) // TTY-only REPL. Lets you poke at the live browser interactively; // subscribed events print as they arrive. Skip when stdin is not a tty @@ -622,7 +500,7 @@ func runRepl(cdp *modcdp.ModCDPClient, mode string) { fmt.Println("Enter commands as Domain.method({...JSON params...}). Examples:") fmt.Println(` Browser.getVersion({})`) fmt.Println(` Mod.evaluate({"expression": "chrome.tabs.query({active: true})"})`) - fmt.Println(` Custom.TabIdFromTargetId({"targetId": "..."})`) + fmt.Println(` Runtime.evaluate({"expression": "document.title", "returnByValue": true})`) fmt.Println("Type exit or quit to disconnect (browser keeps running).") cmdRE := regexp.MustCompile(`^([A-Za-z_]\w*\.[A-Za-z_]\w*)(?:\((.*)\))?$`) sc := bufio.NewScanner(os.Stdin) diff --git a/go/modcdp/client/ModCDPClient.go b/go/modcdp/client/ModCDPClient.go index 8d35d19..44895c1 100644 --- a/go/modcdp/client/ModCDPClient.go +++ b/go/modcdp/client/ModCDPClient.go @@ -70,7 +70,7 @@ type NoopBrowserLauncher = launcher.NoopBrowserLauncher type ExtensionInjectorConfig = types.ExtensionInjectorConfig type ExtensionInjectionResult = types.ExtensionInjectionResult type SendCDP = types.SendCDP -type AttachToTarget = types.AttachToTarget +type EnsureSessionForTarget = types.EnsureSessionForTarget type ExtensionInjector = injector.ExtensionInjector type DiscoveredExtensionInjector = injector.DiscoveredExtensionInjector type BBBrowserExtensionInjector = injector.BBBrowserExtensionInjector @@ -831,12 +831,7 @@ func (c *ModCDPClient) serverNeedsLoopbackCDP() bool { if c.Server == nil || c.Server.ServerLoopbackCDPURL != "" { return false } - for _, route := range c.Server.ServerRoutes { - if route == "loopback_cdp" { - return true - } - } - return false + return c.Server.ServerRoutes["*.*"] == "loopback_cdp" } func (c *ModCDPClient) ensureModCDPServerConfigured() error { @@ -1198,11 +1193,11 @@ func (c *ModCDPClient) validateEventData(event string, data any) (any, bool) { } func (c *ModCDPClient) Send(method string, params map[string]any, sessionID ...string) (any, error) { - targetSessionID := "" + cdpSessionID := "" if len(sessionID) > 0 { - targetSessionID = sessionID[0] + cdpSessionID = sessionID[0] } - return c.sendCommand(method, params, targetSessionID, true) + return c.sendCommand(method, params, cdpSessionID, true) } func (d ModDomain) Evaluate(params map[string]any) (any, error) { @@ -1250,7 +1245,11 @@ func (d ModDomain) Ping(params map[string]any) (any, error) { return d.client.Send("Mod.ping", params) } -func (c *ModCDPClient) sendCommand(method string, params map[string]any, targetSessionID string, validateSchema bool) (any, error) { +func (d ModDomain) GetTopology(params map[string]any) (any, error) { + return d.client.Send("Mod.getTopology", params) +} + +func (c *ModCDPClient) sendCommand(method string, params map[string]any, cdpSessionID string, validateSchema bool) (any, error) { startedAt := time.Now().UnixMilli() if params == nil { params = map[string]any{} @@ -1324,7 +1323,7 @@ func (c *ModCDPClient) sendCommand(method string, params map[string]any, targetS } return result, nil } - command, err := translate.WrapCommandIfNeeded(method, params, c.Client.ClientRoutes, c.ExtSessionID, targetSessionID) + command, err := translate.WrapCommandIfNeeded(method, params, c.Client.ClientRoutes, cdpSessionID) if err != nil { return nil, err } @@ -1355,11 +1354,11 @@ func (c *ModCDPClient) SendRaw(method string, params map[string]any, sessionID . if params == nil { params = map[string]any{} } - targetSessionID := "" + cdpSessionID := "" if len(sessionID) > 0 { - targetSessionID = sessionID[0] + cdpSessionID = sessionID[0] } - result, err := c.sendMessage(method, params, targetSessionID) + result, err := c.sendMessage(method, params, cdpSessionID) completedAt := time.Now().UnixMilli() c.LastRawTiming = map[string]any{ "method": method, @@ -1532,16 +1531,16 @@ func isKnownExtensionMode(mode string) bool { func (c *ModCDPClient) baseExtensionInjectorConfig(send SendCDP) ExtensionInjectorConfig { trustMatchedServiceWorker := c.trustServiceWorkerTarget() - var attachToTarget AttachToTarget + var ensureSessionForTarget EnsureSessionForTarget if send != nil { - attachToTarget = func(targetID string) string { - return c.ensureSessionIDForTarget(targetID, time.Duration(c.Injector.InjectorServiceWorkerProbeTimeoutMS)*time.Millisecond, true) + ensureSessionForTarget = func(targetID string, timeoutMS int, allowAttach bool) string { + return c.ensureSessionForTarget(targetID, time.Duration(timeoutMS)*time.Millisecond, allowAttach) } } return ExtensionInjectorConfig{ - Send: send, - SessionIDForTarget: func(targetID string) string { return c.autoSessions.SessionIDForTarget(targetID) }, - AttachToTarget: attachToTarget, + Send: send, + SessionId_from_targetId: c.autoSessions.SessionId_from_targetId, + EnsureSessionForTarget: ensureSessionForTarget, WaitForExecutionContext: func(sessionID string, timeoutMS int) int { contextID, _ := c.autoSessions.WaitForExecutionContext(sessionID, timeoutMS) return contextID @@ -1904,13 +1903,23 @@ func (c *ModCDPClient) trustServiceWorkerTarget() bool { return false } -func (c *ModCDPClient) sessionIDForTarget(targetID string, timeout time.Duration) string { +func (c *ModCDPClient) ensureSessionForTarget(targetID string, timeout time.Duration, allowAttach bool) string { + sessionID := c.autoSessions.SessionId_from_targetId[targetID] + if sessionID != "" { + return sessionID + } + if allowAttach { + attachedSessionID := c.autoSessions.AttachToTarget(targetID) + if attachedSessionID != "" { + return attachedSessionID + } + } if timeout <= 0 { - return c.autoSessions.SessionIDForTarget(targetID) + return c.autoSessions.SessionId_from_targetId[targetID] } deadline := time.Now().Add(timeout) for time.Now().Before(deadline.Add(time.Millisecond)) { - sessionID := c.autoSessions.SessionIDForTarget(targetID) + sessionID := c.autoSessions.SessionId_from_targetId[targetID] if sessionID != "" { return sessionID } @@ -1918,17 +1927,3 @@ func (c *ModCDPClient) sessionIDForTarget(targetID string, timeout time.Duration } return "" } - -func (c *ModCDPClient) ensureSessionIDForTarget(targetID string, timeout time.Duration, allowAttach bool) string { - sessionID := c.autoSessions.SessionIDForTarget(targetID) - if sessionID != "" { - return sessionID - } - if allowAttach { - attachedSessionID := c.autoSessions.AttachToTarget(targetID) - if attachedSessionID != "" { - return attachedSessionID - } - } - return c.sessionIDForTarget(targetID, timeout) -} diff --git a/go/modcdp/client/ModCDPClientRoutedDefaultOverrides_test.go b/go/modcdp/client/ModCDPClientRoutedDefaultOverrides_test.go index f91cb10..2b7e057 100644 --- a/go/modcdp/client/ModCDPClientRoutedDefaultOverrides_test.go +++ b/go/modcdp/client/ModCDPClientRoutedDefaultOverrides_test.go @@ -9,7 +9,7 @@ import ( const getTargetsOverride = ` async (params) => { const [upstream, tabs] = await Promise.all([ - ModCDP.sendLoopback("Target.getTargets", params), + cdp.upstream.send("Target.getTargets", params), chrome.tabs.query({}), ]); @@ -179,6 +179,52 @@ func TestModCDPClientRoutedDefaultOverrides(t *testing.T) { t.Fatal("expected at least one page target to be matched to a chrome.tabs tab id") } + topologyRaw, err := cdp.Mod.GetTopology(nil) + if err != nil { + t.Fatal(err) + } + topology, ok := topologyRaw.(map[string]any) + if !ok { + t.Fatalf("Mod.getTopology returned %T: %#v", topologyRaw, topologyRaw) + } + rootFrameID, ok := topology["rootFrameId"].(string) + if !ok || rootFrameID == "" { + t.Fatalf("Mod.getTopology rootFrameId = %#v", topology["rootFrameId"]) + } + frames, ok := topology["frames"].(map[string]any) + if !ok { + t.Fatalf("Mod.getTopology frames = %T: %#v", topology["frames"], topology["frames"]) + } + if _, ok := frames[rootFrameID]; !ok { + t.Fatalf("Mod.getTopology frames missing rootFrameId %q: %#v", rootFrameID, frames) + } + roots, ok := topology["roots"].(map[string]any) + if !ok { + t.Fatalf("Mod.getTopology roots = %T: %#v", topology["roots"], topology["roots"]) + } + hasDocumentRoot := false + for _, root := range roots { + if rootMap, ok := root.(map[string]any); ok && rootMap["kind"] == "document" { + hasDocumentRoot = true + } + } + if !hasDocumentRoot { + t.Fatalf("Mod.getTopology should include at least one document root: %#v", roots) + } + contexts, ok := topology["contexts"].(map[string]any) + if !ok { + t.Fatalf("Mod.getTopology contexts = %T: %#v", topology["contexts"], topology["contexts"]) + } + hasPiercerContext := false + for _, context := range contexts { + if contextMap, ok := context.(map[string]any); ok && contextMap["world"] == "piercer" { + hasPiercerContext = true + } + } + if !hasPiercerContext { + t.Fatalf("Mod.getTopology should include a piercer execution context: %#v", contexts) + } + if _, err := cdp.Mod.AddCustomEvent(CustomEvent{Name: "Target.targetCreated"}); err != nil { t.Fatal(err) } diff --git a/go/modcdp/client/ModCDPClient_test.go b/go/modcdp/client/ModCDPClient_test.go index 7dad078..d8ef008 100644 --- a/go/modcdp/client/ModCDPClient_test.go +++ b/go/modcdp/client/ModCDPClient_test.go @@ -524,14 +524,14 @@ func TestModCDPClientRejectsUnknownComponentModesAtTheirOwningFactoryBoundary(t } } -func TestModCDPClientOnlyExposesInjectorAttachAfterCDPSendIsAvailable(t *testing.T) { +func TestModCDPClientOnlyExposesInjectorEnsureAfterCDPSendIsAvailable(t *testing.T) { cdp := New(Options{}) disconnectedConfig := cdp.baseExtensionInjectorConfig(nil) if disconnectedConfig.Send != nil { t.Fatalf("disconnected Send = %#v", disconnectedConfig.Send) } - if disconnectedConfig.AttachToTarget != nil { - t.Fatalf("disconnected AttachToTarget = %#v", disconnectedConfig.AttachToTarget) + if disconnectedConfig.EnsureSessionForTarget != nil { + t.Fatalf("disconnected EnsureSessionForTarget = %#v", disconnectedConfig.EnsureSessionForTarget) } connectedConfig := cdp.baseExtensionInjectorConfig(func(method string, params map[string]any, sessionID string) (map[string]any, error) { @@ -540,8 +540,8 @@ func TestModCDPClientOnlyExposesInjectorAttachAfterCDPSendIsAvailable(t *testing if connectedConfig.Send == nil { t.Fatal("connected Send is nil") } - if connectedConfig.AttachToTarget == nil { - t.Fatal("connected AttachToTarget is nil") + if connectedConfig.EnsureSessionForTarget == nil { + t.Fatal("connected EnsureSessionForTarget is nil") } } diff --git a/go/modcdp/injector/BorrowedExtensionInjector.go b/go/modcdp/injector/BorrowedExtensionInjector.go index c6af6ec..59af908 100644 --- a/go/modcdp/injector/BorrowedExtensionInjector.go +++ b/go/modcdp/injector/BorrowedExtensionInjector.go @@ -73,7 +73,7 @@ func (i *BorrowedExtensionInjector) borrowVisibleServiceWorkers() (*ExtensionInj func (i *BorrowedExtensionInjector) bootstrapTarget(target map[string]any) (*ExtensionInjectionResult, error) { targetID, _ := target["targetId"].(string) targetURL, _ := target["url"].(string) - sessionID := i.ensureSessionIDForTarget(targetID, i.Options.InjectorServiceWorkerProbeTimeoutMS, true) + sessionID := i.ensureSessionForTarget(targetID, i.Options.InjectorServiceWorkerProbeTimeoutMS, true) if sessionID == "" { return nil, nil } diff --git a/go/modcdp/injector/ExtensionInjector.go b/go/modcdp/injector/ExtensionInjector.go index 7bfc8aa..f2ad954 100644 --- a/go/modcdp/injector/ExtensionInjector.go +++ b/go/modcdp/injector/ExtensionInjector.go @@ -36,8 +36,7 @@ var bundledExtensionZip []byte const modcdpReadyExpression = `Boolean(globalThis.ModCDP?.__ModCDPServerVersion >= 1 && globalThis.ModCDP?.handleCommand && globalThis.ModCDP?.addCustomEvent)` type SendCDP = types.SendCDP -type SessionIDForTarget = types.SessionIDForTarget -type AttachToTarget = types.AttachToTarget +type EnsureSessionForTarget = types.EnsureSessionForTarget type WaitForExecutionContext = types.WaitForExecutionContext type LaunchOptions = types.LaunchOptions type ExtensionInjectorConfig = types.ExtensionInjectorConfig @@ -79,11 +78,11 @@ func (i *ExtensionInjector) Update(config ExtensionInjectorConfig) *ExtensionInj if config.Send != nil { i.Options.Send = config.Send } - if config.SessionIDForTarget != nil { - i.Options.SessionIDForTarget = config.SessionIDForTarget + if config.SessionId_from_targetId != nil { + i.Options.SessionId_from_targetId = config.SessionId_from_targetId } - if config.AttachToTarget != nil { - i.Options.AttachToTarget = config.AttachToTarget + if config.EnsureSessionForTarget != nil { + i.Options.EnsureSessionForTarget = config.EnsureSessionForTarget } if config.WaitForExecutionContext != nil { i.Options.WaitForExecutionContext = config.WaitForExecutionContext @@ -213,33 +212,16 @@ func (i ExtensionInjector) SendWithTimeout(method string, params map[string]any, return i.sendWithTimeout(method, params, sessionID, timeoutMS) } -func (i ExtensionInjector) sessionIDForTarget(targetID string, timeoutMS int) string { - deadline := time.Now().Add(time.Duration(timeoutMS) * time.Millisecond) - for { - if i.Options.SessionIDForTarget != nil { - if sessionID := i.Options.SessionIDForTarget(targetID); sessionID != "" { - return sessionID - } - } - if timeoutMS <= 0 || time.Now().After(deadline) { - return "" - } - time.Sleep(time.Duration(i.Options.InjectorTargetSessionPollIntervalMS) * time.Millisecond) - } -} - -func (i ExtensionInjector) ensureSessionIDForTarget(targetID string, timeoutMS int, allowAttach bool) string { - if i.Options.SessionIDForTarget != nil { - if sessionID := i.Options.SessionIDForTarget(targetID); sessionID != "" { +func (i ExtensionInjector) ensureSessionForTarget(targetID string, timeoutMS int, allowAttach bool) string { + if i.Options.SessionId_from_targetId != nil { + if sessionID := i.Options.SessionId_from_targetId[targetID]; sessionID != "" { return sessionID } } - if allowAttach && i.Options.AttachToTarget != nil { - if sessionID := i.Options.AttachToTarget(targetID); sessionID != "" { - return sessionID - } + if i.Options.EnsureSessionForTarget == nil { + return "" } - return i.sessionIDForTarget(targetID, timeoutMS) + return i.Options.EnsureSessionForTarget(targetID, timeoutMS, allowAttach) } func (i ExtensionInjector) targetInfos() ([]map[string]any, error) { @@ -264,7 +246,7 @@ func (i ExtensionInjector) probeTarget(target map[string]any, sessionTimeoutMS i if targetID == "" || i.UnusableTargetIDs[targetID] { return nil, nil } - sessionID := i.ensureSessionIDForTarget(targetID, sessionTimeoutMS, allowAttach) + sessionID := i.ensureSessionForTarget(targetID, sessionTimeoutMS, allowAttach) if sessionID == "" { return nil, nil } diff --git a/go/modcdp/injector/extension.zip b/go/modcdp/injector/extension.zip index 8032e35..46f9d30 100644 Binary files a/go/modcdp/injector/extension.zip and b/go/modcdp/injector/extension.zip differ diff --git a/go/modcdp/modcdp.go b/go/modcdp/modcdp.go index e744b01..644d552 100644 --- a/go/modcdp/modcdp.go +++ b/go/modcdp/modcdp.go @@ -47,11 +47,6 @@ type NativeMessagingUpstreamTransportOptions = transport.NativeMessagingUpstream type NatsUpstreamTransport = transport.NatsUpstreamTransport type NatsUpstreamTransportOptions = transport.NatsUpstreamTransportOptions type AutoSessionRouter = client.AutoSessionRouter -type TargetTargetCreatedEvent = client.TargetTargetCreatedEvent -type TargetSetDiscoverTargetsParams = client.TargetSetDiscoverTargetsParams -type TargetCreateTargetParams = client.TargetCreateTargetParams -type TargetActivateTargetParams = client.TargetActivateTargetParams -type TargetTargetID = client.TargetTargetID var New = client.New var Bool = client.Bool diff --git a/go/modcdp/router/AutoSessionRouter.go b/go/modcdp/router/AutoSessionRouter.go index 525500c..54ce7ea 100644 --- a/go/modcdp/router/AutoSessionRouter.go +++ b/go/modcdp/router/AutoSessionRouter.go @@ -8,17 +8,13 @@ import ( type AutoSessionRouterSend func(method string, params map[string]any, sessionID string) (map[string]any, error) -const maxDetachedSessionGuards = 1024 - type AutoSessionRouter struct { - TargetSessions map[string]string - SessionTargets map[string]map[string]any - ExecutionContexts map[string]int + SessionId_from_targetId map[string]string + TargetId_from_sessionId map[string]string + Execution_contexts map[string]int send AutoSessionRouterSend defaultExecutionContextTimeoutMS func() int - executionContextWaiters map[string][]chan executionContextResult - detachedSessions map[string]bool - detachedSessionOrder []string + execution_context_waiters map[string][]chan executionContextResult mu sync.Mutex } @@ -29,33 +25,28 @@ type executionContextResult struct { func NewAutoSessionRouter(send AutoSessionRouterSend, defaultExecutionContextTimeoutMS func() int) *AutoSessionRouter { return &AutoSessionRouter{ - TargetSessions: map[string]string{}, - SessionTargets: map[string]map[string]any{}, - ExecutionContexts: map[string]int{}, + SessionId_from_targetId: map[string]string{}, + TargetId_from_sessionId: map[string]string{}, + Execution_contexts: map[string]int{}, send: send, defaultExecutionContextTimeoutMS: defaultExecutionContextTimeoutMS, - executionContextWaiters: map[string][]chan executionContextResult{}, - detachedSessions: map[string]bool{}, - detachedSessionOrder: []string{}, + execution_context_waiters: map[string][]chan executionContextResult{}, } } -func (r *AutoSessionRouter) SessionIDForTarget(targetID string) string { - r.mu.Lock() - defer r.mu.Unlock() - return r.TargetSessions[targetID] -} - func (r *AutoSessionRouter) AttachToTarget(targetID string) string { - if sessionID := r.SessionIDForTarget(targetID); sessionID != "" { + r.mu.Lock() + sessionID := r.SessionId_from_targetId[targetID] + r.mu.Unlock() + if sessionID != "" { return sessionID } result, err := r.send("Target.attachToTarget", map[string]any{"targetId": targetID, "flatten": true}, "") if err != nil { return "" } - sessionID, _ := result["sessionId"].(string) - return sessionID + attachedSessionID, _ := result["sessionId"].(string) + return attachedSessionID } func (r *AutoSessionRouter) RecordProtocolEvent(method string, data any, sessionID string) { @@ -73,9 +64,8 @@ func (r *AutoSessionRouter) RecordProtocolEvent(method string, data any, session targetID, _ := targetInfo["targetId"].(string) if attachedSessionID != "" && targetID != "" { r.mu.Lock() - r.clearDetachedSessionLocked(attachedSessionID) - r.TargetSessions[targetID] = attachedSessionID - r.SessionTargets[attachedSessionID] = targetInfo + r.SessionId_from_targetId[targetID] = attachedSessionID + r.TargetId_from_sessionId[attachedSessionID] = targetID r.mu.Unlock() } case "Runtime.executionContextCreated": @@ -103,12 +93,12 @@ func (r *AutoSessionRouter) WaitForExecutionContext(sessionID string, timeoutMS return 0, fmt.Errorf("cannot wait for a Runtime execution context without a session") } r.mu.Lock() - if contextID, ok := r.ExecutionContexts[sessionID]; ok { + if contextID, ok := r.Execution_contexts[sessionID]; ok { r.mu.Unlock() return contextID, nil } waiter := make(chan executionContextResult, 1) - r.executionContextWaiters[sessionID] = append(r.executionContextWaiters[sessionID], waiter) + r.execution_context_waiters[sessionID] = append(r.execution_context_waiters[sessionID], waiter) r.mu.Unlock() select { @@ -116,7 +106,7 @@ func (r *AutoSessionRouter) WaitForExecutionContext(sessionID string, timeoutMS return result.contextID, result.err case <-time.After(time.Duration(timeoutMS) * time.Millisecond): r.mu.Lock() - waiters := r.executionContextWaiters[sessionID] + waiters := r.execution_context_waiters[sessionID] filtered := waiters[:0] for _, candidate := range waiters { if candidate != waiter { @@ -124,9 +114,9 @@ func (r *AutoSessionRouter) WaitForExecutionContext(sessionID string, timeoutMS } } if len(filtered) == 0 { - delete(r.executionContextWaiters, sessionID) + delete(r.execution_context_waiters, sessionID) } else { - r.executionContextWaiters[sessionID] = filtered + r.execution_context_waiters[sessionID] = filtered } r.mu.Unlock() return 0, fmt.Errorf("timed out waiting for Runtime.executionContextCreated for session %s", sessionID) @@ -135,13 +125,13 @@ func (r *AutoSessionRouter) WaitForExecutionContext(sessionID string, timeoutMS func (r *AutoSessionRouter) recordExecutionContext(sessionID string, contextID int) { r.mu.Lock() - if r.detachedSessions[sessionID] { + if _, ok := r.TargetId_from_sessionId[sessionID]; !ok { r.mu.Unlock() return } - r.ExecutionContexts[sessionID] = contextID - waiters := r.executionContextWaiters[sessionID] - delete(r.executionContextWaiters, sessionID) + r.Execution_contexts[sessionID] = contextID + waiters := r.execution_context_waiters[sessionID] + delete(r.execution_context_waiters, sessionID) r.mu.Unlock() for _, waiter := range waiters { waiter <- executionContextResult{contextID: contextID} @@ -150,15 +140,14 @@ func (r *AutoSessionRouter) recordExecutionContext(sessionID string, contextID i func (r *AutoSessionRouter) forgetSession(sessionID string) { r.mu.Lock() - targetInfo := r.SessionTargets[sessionID] - delete(r.SessionTargets, sessionID) - if targetID, _ := targetInfo["targetId"].(string); targetID != "" { - delete(r.TargetSessions, targetID) - } - delete(r.ExecutionContexts, sessionID) - r.markDetachedSessionLocked(sessionID) - waiters := r.executionContextWaiters[sessionID] - delete(r.executionContextWaiters, sessionID) + targetID := r.TargetId_from_sessionId[sessionID] + delete(r.TargetId_from_sessionId, sessionID) + if targetID != "" { + delete(r.SessionId_from_targetId, targetID) + } + delete(r.Execution_contexts, sessionID) + waiters := r.execution_context_waiters[sessionID] + delete(r.execution_context_waiters, sessionID) r.mu.Unlock() err := fmt.Errorf("Runtime execution context wait cancelled because session %s detached", sessionID) for _, waiter := range waiters { @@ -166,29 +155,6 @@ func (r *AutoSessionRouter) forgetSession(sessionID string) { } } -func (r *AutoSessionRouter) markDetachedSessionLocked(sessionID string) { - if !r.detachedSessions[sessionID] { - r.detachedSessionOrder = append(r.detachedSessionOrder, sessionID) - } - r.detachedSessions[sessionID] = true - for len(r.detachedSessions) > maxDetachedSessionGuards && len(r.detachedSessionOrder) > 0 { - oldestSessionID := r.detachedSessionOrder[0] - r.detachedSessionOrder = r.detachedSessionOrder[1:] - delete(r.detachedSessions, oldestSessionID) - } -} - -func (r *AutoSessionRouter) clearDetachedSessionLocked(sessionID string) { - delete(r.detachedSessions, sessionID) - filtered := r.detachedSessionOrder[:0] - for _, candidateSessionID := range r.detachedSessionOrder { - if candidateSessionID != sessionID { - filtered = append(filtered, candidateSessionID) - } - } - r.detachedSessionOrder = filtered -} - func intFromAny(value any) (int, bool) { switch typed := value.(type) { case int: diff --git a/go/modcdp/router/AutoSessionRouter_test.go b/go/modcdp/router/AutoSessionRouter_test.go index 1ba7fe2..63cbe50 100644 --- a/go/modcdp/router/AutoSessionRouter_test.go +++ b/go/modcdp/router/AutoSessionRouter_test.go @@ -14,97 +14,6 @@ import ( "github.com/gobwas/ws/wsutil" ) -func TestAutoSessionRouterRejectsPendingExecutionContextWaitersWhenSessionDetaches(t *testing.T) { - router := NewAutoSessionRouter(func(string, map[string]any, string) (map[string]any, error) { - return map[string]any{}, nil - }, func() int { return 5000 }) - - result := make(chan error, 1) - go func() { - _, err := router.WaitForExecutionContext("detached-session", 5000) - result <- err - }() - waitForString(t, func() string { - router.mu.Lock() - defer router.mu.Unlock() - if len(router.executionContextWaiters["detached-session"]) > 0 { - return "waiting" - } - return "" - }) - router.RecordProtocolEvent("Target.attachedToTarget", map[string]any{ - "sessionId": "detached-session", - "targetInfo": map[string]any{"targetId": "target-1", "type": "page"}, - }, "") - router.RecordProtocolEvent("Target.detachedFromTarget", map[string]any{"sessionId": "detached-session"}, "") - router.RecordProtocolEvent("Runtime.executionContextCreated", map[string]any{"context": map[string]any{"id": 42}}, "detached-session") - - select { - case err := <-result: - if err == nil || !strings.Contains(err.Error(), "Runtime execution context wait cancelled because session detached-session detached") { - t.Fatalf("wait error = %v", err) - } - case <-time.After(time.Second): - t.Fatal("timed out waiting for detach error") - } - if sessionID := router.SessionIDForTarget("target-1"); sessionID != "" { - t.Fatalf("session id after detach = %q", sessionID) - } - if _, ok := router.ExecutionContexts["detached-session"]; ok { - t.Fatal("stale execution context was recorded after detach") - } -} - -func TestAutoSessionRouterBoundsDetachedSessionGuardsAndClearsThemWhenSessionReattaches(t *testing.T) { - router := NewAutoSessionRouter(func(string, map[string]any, string) (map[string]any, error) { - return map[string]any{}, nil - }, func() int { return 5000 }) - - for index := 0; index < 1034; index++ { - router.RecordProtocolEvent("Target.detachedFromTarget", map[string]any{"sessionId": fmt.Sprintf("detached-session-%d", index)}, "") - } - - router.mu.Lock() - detachedCount := len(router.detachedSessions) - detachedOrderCount := len(router.detachedSessionOrder) - router.mu.Unlock() - if detachedCount > maxDetachedSessionGuards { - t.Fatalf("detached session guard count = %d, want <= %d", detachedCount, maxDetachedSessionGuards) - } - if detachedOrderCount > maxDetachedSessionGuards { - t.Fatalf("detached session guard order count = %d, want <= %d", detachedOrderCount, maxDetachedSessionGuards) - } - - recentSessionID := "detached-session-1033" - router.RecordProtocolEvent("Runtime.executionContextCreated", map[string]any{"context": map[string]any{"id": 42}}, recentSessionID) - if _, ok := router.ExecutionContexts[recentSessionID]; ok { - t.Fatal("stale execution context was recorded for detached session") - } - - router.RecordProtocolEvent("Target.attachedToTarget", map[string]any{ - "sessionId": recentSessionID, - "targetInfo": map[string]any{"targetId": "target-reattached", "type": "page"}, - }, "") - router.RecordProtocolEvent("Runtime.executionContextCreated", map[string]any{"context": map[string]any{"id": 43}}, recentSessionID) - - if sessionID := router.SessionIDForTarget("target-reattached"); sessionID != recentSessionID { - t.Fatalf("session id = %q, want %q", sessionID, recentSessionID) - } - if contextID := router.ExecutionContexts[recentSessionID]; contextID != 43 { - t.Fatalf("context id = %d, want 43", contextID) - } - router.mu.Lock() - defer router.mu.Unlock() - if router.detachedSessions[recentSessionID] { - t.Fatal("reattached session was still marked detached") - } - for _, detachedSessionID := range router.detachedSessionOrder { - if detachedSessionID == recentSessionID { - t.Fatal("reattached session stayed in detached session order") - } - } -} - func TestAutoSessionRouterTracksRealTargetSessionsAndExecutionContexts(t *testing.T) { headless := true chrome, err := launcher.NewLocalBrowserLauncher(launcher.LaunchOptions{ @@ -195,10 +104,14 @@ func TestAutoSessionRouterTracksRealTargetSessionsAndExecutionContexts(t *testin }() var targetID string + var pendingTargetID string defer func() { if targetID != "" { _, _ = send("Target.closeTarget", map[string]any{"targetId": targetID}, "") } + if pendingTargetID != "" { + _, _ = send("Target.closeTarget", map[string]any{"targetId": pendingTargetID}, "") + } close(done) }() @@ -213,7 +126,7 @@ func TestAutoSessionRouterTracksRealTargetSessionsAndExecutionContexts(t *testin t.Fatal(err) } targetID, _ = created["targetId"].(string) - sessionID := waitForString(t, func() string { return router.SessionIDForTarget(targetID) }) + sessionID := waitForString(t, func() string { return router.SessionId_from_targetId[targetID] }) contextResult := make(chan int, 1) contextError := make(chan error, 1) go func() { @@ -241,11 +154,54 @@ func TestAutoSessionRouterTracksRealTargetSessionsAndExecutionContexts(t *testin t.Fatal(err) } waitForString(t, func() string { - if router.SessionIDForTarget(targetID) == "" { + if router.SessionId_from_targetId[targetID] == "" { return "detached" } return "" }) + if _, ok := router.Execution_contexts[sessionID]; ok { + t.Fatal("execution context remained after detach") + } + if _, err := send("Target.closeTarget", map[string]any{"targetId": targetID}, ""); err != nil { + t.Fatal(err) + } + targetID = "" + + pendingCreated, err := send("Target.createTarget", map[string]any{"url": "about:blank#modcdp-auto-session-router-pending-context"}, "") + if err != nil { + t.Fatal(err) + } + pendingTargetID, _ = pendingCreated["targetId"].(string) + pendingSessionID := waitForString(t, func() string { return router.SessionId_from_targetId[pendingTargetID] }) + pendingContextError := make(chan error, 1) + go func() { + _, err := router.WaitForExecutionContext(pendingSessionID, 30000) + pendingContextError <- err + }() + if _, err := send("Target.detachFromTarget", map[string]any{"sessionId": pendingSessionID}, ""); err != nil { + t.Fatal(err) + } + select { + case err := <-pendingContextError: + if err == nil || !strings.Contains(err.Error(), "Runtime execution context wait cancelled because session "+pendingSessionID+" detached") { + t.Fatalf("wait error = %v", err) + } + case <-time.After(35 * time.Second): + t.Fatal("timed out waiting for detach error") + } + waitForString(t, func() string { + if router.SessionId_from_targetId[pendingTargetID] == "" { + return "detached" + } + return "" + }) + if _, ok := router.Execution_contexts[pendingSessionID]; ok { + t.Fatal("execution context was recorded for detached pending session") + } + if _, err := send("Target.closeTarget", map[string]any{"targetId": pendingTargetID}, ""); err != nil { + t.Fatal(err) + } + pendingTargetID = "" } func waitForString(t *testing.T, fn func() string) string { diff --git a/go/modcdp/translate/translate.go b/go/modcdp/translate/translate.go index 12bde56..7550610 100644 --- a/go/modcdp/translate/translate.go +++ b/go/modcdp/translate/translate.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" "strings" - "time" ) const UpstreamEventBindingName = "__ModCDP_event_from_upstream__" @@ -134,31 +133,17 @@ func wrapModCDPAddMiddleware(params map[string]any) map[string]any { )) } -func wrapCustomCommand(method string, params map[string]any, sessionID string) map[string]any { +func wrapCustomCommand(method string, params map[string]any, sessionID any) map[string]any { p, _ := json.Marshal(params) runtimeParams := callFunctionParams(`async function(method, paramsJson, cdpSessionId) { return JSON.stringify(await globalThis.ModCDP.handleCommand(method, JSON.parse(paramsJson), cdpSessionId)); }`) runtimeParams["arguments"] = []map[string]any{{"value": method}, {"value": string(p)}, {"value": sessionID}} return runtimeParams } -func wrapServiceWorkerCommand(method string, params map[string]any, sessionID string, targetSessionID string) []rawStep { +func wrapServiceWorkerCommand(method string, params map[string]any, sessionID string) []rawStep { if params == nil { params = map[string]any{} } - if targetSessionID == "" { - targetSessionID = sessionID - } - if method == "Mod.ping" { - if _, ok := params["sent_at"]; !ok { - next := map[string]any{} - for key, value := range params { - next[key] = value - } - next["sent_at"] = time.Now().UnixMilli() - params = next - } - } - if method == "Mod.addCustomEvent" { return []rawStep{ {Method: "Runtime.callFunctionOn", Params: wrapModCDPAddCustomEvent(params), Unwrap: "runtime"}, @@ -168,15 +153,17 @@ func wrapServiceWorkerCommand(method string, params map[string]any, sessionID st unwrap := "runtime" switch method { case "Mod.evaluate": - runtimeParams = wrapModCDPEvaluate(params, targetSessionID) + runtimeParams = wrapModCDPEvaluate(params, sessionID) case "Mod.addCustomCommand": runtimeParams = wrapModCDPAddCustomCommand(params) case "Mod.addMiddleware": runtimeParams = wrapModCDPAddMiddleware(params) default: - cdpSessionID, _ := params["cdpSessionId"].(string) - if cdpSessionID == "" { - cdpSessionID = targetSessionID + var cdpSessionID any + if paramsSessionID, _ := params["cdpSessionId"].(string); paramsSessionID != "" { + cdpSessionID = paramsSessionID + } else if sessionID != "" { + cdpSessionID = sessionID } runtimeParams = wrapCustomCommand(method, params, cdpSessionID) unwrap = "runtime_json" @@ -184,17 +171,13 @@ func wrapServiceWorkerCommand(method string, params map[string]any, sessionID st return []rawStep{{Method: "Runtime.callFunctionOn", Params: runtimeParams, Unwrap: unwrap}} } -func WrapCommandIfNeeded(method string, params map[string]any, routes map[string]string, sessionID string, targetSessionID ...string) (rawCommand, error) { - targetSession := "" - if len(targetSessionID) > 0 { - targetSession = targetSessionID[0] - } +func WrapCommandIfNeeded(method string, params map[string]any, routes map[string]string, sessionID string) (rawCommand, error) { route := RouteFor(method, routes) if route == "direct_cdp" { - return rawCommand{Route: route, Target: "direct_cdp", Steps: []rawStep{{Method: method, Params: params, SessionID: targetSession}}}, nil + return rawCommand{Route: route, Target: "direct_cdp", Steps: []rawStep{{Method: method, Params: params, SessionID: sessionID}}}, nil } if route == "service_worker" { - return rawCommand{Route: route, Target: "service_worker", Steps: wrapServiceWorkerCommand(method, params, sessionID, targetSession)}, nil + return rawCommand{Route: route, Target: "service_worker", Steps: wrapServiceWorkerCommand(method, params, sessionID)}, nil } return rawCommand{}, fmt.Errorf("unsupported client route %q for %s", route, method) } diff --git a/go/modcdp/translate/translate_test.go b/go/modcdp/translate/translate_test.go index df05a5b..dc11cb8 100644 --- a/go/modcdp/translate/translate_test.go +++ b/go/modcdp/translate/translate_test.go @@ -52,6 +52,19 @@ func TestTranslateRoutesWrapsAndUnwrapsModCDPProtocolMessagesDeterministically(t t.Fatalf("configure unwrap = %q", configured.Steps[0].Unwrap) } + ping, err := wrapCommandIfNeeded("Mod.ping", map[string]any{}, DefaultClientRoutes(), "") + if err != nil { + t.Fatal(err) + } + pingArguments := ping.Steps[0].Params["arguments"].([]map[string]any) + var pingPayload map[string]any + if err := json.Unmarshal([]byte(pingArguments[1]["value"].(string)), &pingPayload); err != nil { + t.Fatal(err) + } + if len(pingPayload) != 0 { + t.Fatalf("ping params = %#v", pingPayload) + } + custom, err := wrapCommandIfNeeded( "Custom.echo", map[string]any{"secret": strings.Repeat("x", 100), "nested": map[string]any{"ok": true}}, @@ -83,6 +96,20 @@ func TestTranslateRoutesWrapsAndUnwrapsModCDPProtocolMessagesDeterministically(t t.Fatalf("session argument = %#v", customArguments[2]) } + customWithSession, err := wrapCommandIfNeeded( + "Custom.echo", + map[string]any{"secret": "targeted"}, + DefaultClientRoutes(), + "target-session-1", + ) + if err != nil { + t.Fatal(err) + } + customWithSessionArguments := customWithSession.Steps[0].Params["arguments"].([]map[string]any) + if customWithSessionArguments[2]["value"] != "target-session-1" { + t.Fatalf("target session argument = %#v", customWithSessionArguments[2]) + } + unwrapped, err := unwrapResponseIfNeeded(map[string]any{"result": map[string]any{"type": "object", "value": map[string]any{"ok": true}}}, "runtime") if err != nil { t.Fatal(err) diff --git a/go/modcdp/types/types.go b/go/modcdp/types/types.go index eb446f7..5e65ab7 100644 --- a/go/modcdp/types/types.go +++ b/go/modcdp/types/types.go @@ -28,14 +28,13 @@ type LaunchOptions struct { } type SendCDP func(method string, params map[string]any, sessionID string) (map[string]any, error) -type SessionIDForTarget func(targetID string) string -type AttachToTarget func(targetID string) string +type EnsureSessionForTarget func(targetID string, timeoutMS int, allowAttach bool) string type WaitForExecutionContext func(sessionID string, timeoutMS int) int type ExtensionInjectorConfig struct { Send SendCDP `json:"-"` - SessionIDForTarget SessionIDForTarget `json:"-"` - AttachToTarget AttachToTarget `json:"-"` + SessionId_from_targetId map[string]string `json:"-"` + EnsureSessionForTarget EnsureSessionForTarget `json:"-"` WaitForExecutionContext WaitForExecutionContext `json:"-"` InjectorExtensionPath string `json:"injector_extension_path,omitempty"` InjectorExtensionID string `json:"injector_extension_id,omitempty"` diff --git a/js/examples/demo.ts b/js/examples/demo.ts index f676383..50da47d 100644 --- a/js/examples/demo.ts +++ b/js/examples/demo.ts @@ -17,9 +17,9 @@ // reversews and nativemessaging use the fixed extension // defaults: ws://127.0.0.1:29292 and com.modcdp.bridge. // -// Valid CI/local demo combinations exercise the same surface: raw Browser.getVersion, raw -// Target.targetCreated event handling, Mod.evaluate, Custom.* commands, -// Custom.* events, and response middleware. +// Valid CI/local demo combinations exercise the same surface: a native Runtime +// command/event pair, Mod.evaluate, Custom.* commands, Custom.* events, and +// response/event middleware. import path from "node:path"; import { existsSync } from "node:fs"; @@ -28,26 +28,20 @@ import { fileURLToPath } from "node:url"; import { setTimeout as sleep } from "node:timers/promises"; import { createInterface } from "node:readline/promises"; import { spawn } from "node:child_process"; -import { z } from "zod"; import { ModCDPClient } from "../src/client/ModCDPClient.js"; -type TargetCreatedPayload = { - targetInfo?: { targetId?: string } & Record; -}; - const HERE = path.dirname(fileURLToPath(import.meta.url)); const EXTENSION_PATH = [path.resolve(HERE, "..", "..", "extension"), path.resolve(HERE, "..", "..", "dist", "extension")].find((candidate) => existsSync(path.join(candidate, "modcdp/service_worker.js")), ) ?? path.resolve(HERE, "..", "..", "extension"); const DEFAULT_DEMO_EVENT_TIMEOUT_MS = 10_000; +const DEFAULT_DEMO_CDP_SEND_TIMEOUT_MS = 60_000; +const DEFAULT_DEMO_EXECUTION_CONTEXT_TIMEOUT_MS = 60_000; const DEFAULT_REVERSE_TRANSPORT_WAIT_TIMEOUT_MS = 60_000; const DEFAULT_LIVE_CDP_POLL_INTERVAL_MS = 250; const DEFAULT_LIVE_CDP_ACTIVE_PORT_STALE_MS = 1_000; -const DEFAULT_TARGET_EVENT_TIMEOUT_MS = 10_000; -const DEFAULT_PAGE_TARGET_EVENT_TIMEOUT_MS = 10_000; -const DEFAULT_DEMO_EVENT_POLL_INTERVAL_MS = 20; const UPSTREAM_MODES = new Set(["ws", "pipe", "reversews", "nativemessaging", "nats"]); @@ -91,30 +85,20 @@ function parseArgs(argv) { } function serverRoutesFor(mode, upstream_mode) { - const routes = { + void upstream_mode; + return { "Mod.*": "service_worker", "Custom.*": "service_worker", "*.*": mode === "loopback" ? "loopback_cdp" : mode === "debugger" ? "chrome_debugger" : "auto", }; - if (mode === "loopback" || ["reversews", "nativemessaging", "nats"].includes(upstream_mode)) { - routes["Target.setDiscoverTargets"] = "loopback_cdp"; - routes["Target.createTarget"] = "loopback_cdp"; - routes["Target.activateTarget"] = "loopback_cdp"; - } - return routes; } function clientRoutesFor(mode) { - const directNormalEventRoutes = { - "Target.setDiscoverTargets": "direct_cdp", - "Target.createTarget": "direct_cdp", - "Target.activateTarget": "direct_cdp", - }; return { "Mod.*": "service_worker", "Custom.*": "service_worker", + "Runtime.*": "service_worker", "*.*": mode === "direct" ? "direct_cdp" : "service_worker", - ...directNormalEventRoutes, }; } @@ -137,6 +121,7 @@ function clientOptionsFor(mode, upstream_mode, cdp_url, launch_options = {}) { injector_mode: "auto" as const, injector_extension_path: EXTENSION_PATH, injector_service_worker_url_suffixes: ["/modcdp/service_worker.js"], + injector_execution_context_timeout_ms: DEFAULT_DEMO_EXECUTION_CONTEXT_TIMEOUT_MS, }; if (mode === "direct") { return { @@ -145,6 +130,7 @@ function clientOptionsFor(mode, upstream_mode, cdp_url, launch_options = {}) { injector, client: { client_routes: clientRoutesFor(mode), + client_cdp_send_timeout_ms: DEFAULT_DEMO_CDP_SEND_TIMEOUT_MS, }, }; } @@ -154,9 +140,11 @@ function clientOptionsFor(mode, upstream_mode, cdp_url, launch_options = {}) { injector, client: { client_routes: clientRoutesFor(mode), + client_cdp_send_timeout_ms: DEFAULT_DEMO_CDP_SEND_TIMEOUT_MS, }, server: { server_routes: serverRoutesFor(mode, upstream_mode), + server_loopback_execution_context_timeout_ms: DEFAULT_DEMO_EXECUTION_CONTEXT_TIMEOUT_MS, }, }; } @@ -168,12 +156,6 @@ function assertObject(value, label) { return value; } -function isTargetCreatedPayload(value: unknown): value is TargetCreatedPayload { - if (value == null || typeof value !== "object" || Array.isArray(value)) return false; - const targetInfo = (value as Record).targetInfo; - return targetInfo == null || (typeof targetInfo === "object" && !Array.isArray(targetInfo)); -} - async function waitForEvent(cdp, eventName, predicate = (_payload) => true, timeoutMs = DEFAULT_DEMO_EVENT_TIMEOUT_MS) { return await new Promise((resolve, reject) => { const timeout = setTimeout(() => { @@ -257,17 +239,10 @@ async function main() { } const cdp = new ModCDPClient(clientOptionsFor(mode, upstream_mode, cdp_url, launch_options)); - const pageTargetEvents = []; - const targetCreatedEvents: TargetCreatedPayload[] = []; try { await cdp.connect(); console.log("upstream cdp:", cdp.cdp_url); - cdp.on(cdp.Target.targetCreated, (payload) => { - const event = isTargetCreatedPayload(payload) ? payload : {}; - console.log("Target.targetCreated ->", event.targetInfo?.targetId); - targetCreatedEvents.push(event); - }); console.log("connected; ext", cdp.extension_id, "session", cdp.ext_session_id); console.log("connect timing ->", cdp.connect_timing); @@ -281,6 +256,7 @@ async function main() { }, server: { server_routes: serverRoutesFor(mode, upstream_mode), + server_loopback_execution_context_timeout_ms: DEFAULT_DEMO_EXECUTION_CONTEXT_TIMEOUT_MS, }, }), "Mod.configure", @@ -305,36 +281,6 @@ async function main() { return_path_ms: typeof pong.received_at === "number" ? ping_returned_at - pong.received_at : null, }); - // Browser.getVersion is browser-scoped and chrome.debugger is tab-scoped, - // so debugger mode asserts a positive raw CDP Runtime.evaluate instead. - if (mode === "debugger") { - try { - const version = assertObject(await cdp.Browser.getVersion(), "Browser.getVersion"); - if (typeof version.protocolVersion !== "string" || typeof version.product !== "string") { - throw new Error(`unexpected Browser.getVersion result ${JSON.stringify(version)}`); - } - console.log("Browser.getVersion ->", version); - } catch (e) { - console.log("Browser.getVersion -> (debugger route rejected:", e.message.replace(/\n/g, " "), ")"); - } - const runtimeEval = assertObject( - await cdp.Runtime.evaluate({ - expression: "(() => 42)()", - returnByValue: true, - }), - "Runtime.evaluate", - ); - if (runtimeEval.result?.value !== 42) - throw new Error(`unexpected Runtime.evaluate result ${JSON.stringify(runtimeEval)}`); - console.log("Runtime.evaluate ->", runtimeEval); - } else { - const version = assertObject(await cdp.Browser.getVersion(), "Browser.getVersion"); - if (typeof version.protocolVersion !== "string" || typeof version.product !== "string") { - throw new Error(`unexpected Browser.getVersion result ${JSON.stringify(version)}`); - } - console.log("Browser.getVersion ->", version); - } - const modcdpEval = (await cdp.Mod.evaluate({ expression: "({ extension_id: chrome.runtime.id })", })) as { @@ -347,81 +293,31 @@ async function main() { throw new Error(`unexpected Mod.evaluate result ${JSON.stringify(modcdpEval)}`); console.log("Mod.evaluate ->", modcdpEval); - const echoRegistration = assertObject( - await cdp.Mod.addCustomCommand({ - name: "Custom.echo", - expression: `async (params, method) => ({ echoed: params.value, method })`, - }), - "Mod.addCustomCommand Custom.echo", - ); - if (echoRegistration.registered !== true || echoRegistration.name !== "Custom.echo") { - throw new Error(`unexpected Custom.echo registration ${JSON.stringify(echoRegistration)}`); - } - const echoResult = assertObject(await cdp.send("Custom.echo", { value: "custom-command-ok" }), "Custom.echo"); - if (echoResult.echoed !== "custom-command-ok" || echoResult.method !== "Custom.echo") { - throw new Error(`unexpected Custom.echo result ${JSON.stringify(echoResult)}`); + let topologyChecked = false; + if (mode !== "direct") { + const topology = assertObject(await cdp.Mod.getTopology(), "Mod.getTopology"); + if ( + typeof topology.rootFrameId !== "string" || + !topology.frames?.[topology.rootFrameId] || + !Object.values(topology.roots || {}).some((root: any) => root?.kind === "document") || + !Object.values(topology.contexts || {}).some((context: any) => context?.world === "piercer") + ) { + throw new Error(`unexpected Mod.getTopology result ${JSON.stringify(topology)}`); + } + topologyChecked = true; + console.log("Mod.getTopology ->", { + rootFrameId: topology.rootFrameId, + frames: Object.keys(topology.frames || {}).length, + roots: Object.keys(topology.roots || {}).length, + contexts: Object.keys(topology.contexts || {}).length, + }); } - console.log("Custom.echo ->", echoResult); - const tabCommandRegistration = assertObject( - await cdp.Mod.addCustomCommand({ - name: "Custom.TabIdFromTargetId", - params_schema: { - targetId: cdp.types.zod.Target.TargetID, - }, - result_schema: { - tabId: z.number().nullable(), - }, - expression: `async ({ targetId }) => { - const targets = await chrome.debugger.getTargets(); - const target = targets.find(target => target.id === targetId); - return { tabId: target?.tabId ?? null }; - }`, - }), - "Mod.addCustomCommand Custom.TabIdFromTargetId", - ); - if (tabCommandRegistration.registered !== true) { - throw new Error(`unexpected TabIdFromTargetId registration ${JSON.stringify(tabCommandRegistration)}`); - } - const targetCommandRegistration = assertObject( - await cdp.Mod.addCustomCommand({ - name: "Custom.targetIdFromTabId", - params_schema: { - tabId: z.number(), - }, - result_schema: { - targetId: cdp.types.zod.Target.TargetID.nullable(), - tabId: z.number().optional(), - }, - expression: `async ({ tabId }) => { - const targets = await chrome.debugger.getTargets(); - const target = targets.find(target => target.type === "page" && target.tabId === tabId); - return { targetId: target?.id ?? null }; - }`, - }), - "Mod.addCustomCommand Custom.targetIdFromTabId", - ); - if (targetCommandRegistration.registered !== true) { - throw new Error(`unexpected targetIdFromTabId registration ${JSON.stringify(targetCommandRegistration)}`); - } const responseMiddlewareRegistration = assertObject( await cdp.Mod.addMiddleware({ - name: "*", + name: "Custom.echo", phase: cdp.RESPONSE, - expression: `async (payload, next) => { - const seen = new WeakSet(); - const visit = async value => { - if (!value || typeof value !== "object" || seen.has(value)) return; - seen.add(value); - if (!Array.isArray(value) && typeof value.targetId === "string" && value.tabId == null) { - const { tabId } = await cdp.send("Custom.TabIdFromTargetId", { targetId: value.targetId }); - if (tabId != null) value.tabId = tabId; - } - for (const child of Array.isArray(value) ? value : Object.values(value)) await visit(child); - }; - await visit(payload); - return next(payload); - }`, + expression: `async (payload, next) => next({ ...payload, responseMiddleware: "ok" })`, }), "Mod.addMiddleware response", ); @@ -431,22 +327,9 @@ async function main() { const eventMiddlewareRegistration = assertObject( await cdp.Mod.addMiddleware({ - name: "*", + name: "Custom.demoEvent", phase: cdp.EVENT, - expression: `async (payload, next) => { - const seen = new WeakSet(); - const visit = async value => { - if (!value || typeof value !== "object" || seen.has(value)) return; - seen.add(value); - if (!Array.isArray(value) && typeof value.targetId === "string" && value.tabId == null) { - const { tabId } = await cdp.send("Custom.TabIdFromTargetId", { targetId: value.targetId }); - if (tabId != null) value.tabId = tabId; - } - for (const child of Array.isArray(value) ? value : Object.values(value)) await visit(child); - }; - await visit(payload); - return next(payload); - }`, + expression: `async (payload, next) => next({ ...payload, eventMiddleware: "ok" })`, }), "Mod.addMiddleware event", ); @@ -454,6 +337,26 @@ async function main() { throw new Error(`unexpected event middleware registration ${JSON.stringify(eventMiddlewareRegistration)}`); } + const echoRegistration = assertObject( + await cdp.Mod.addCustomCommand({ + name: "Custom.echo", + expression: `async (params, method) => ({ echoed: params.value, method })`, + }), + "Mod.addCustomCommand Custom.echo", + ); + if (echoRegistration.registered !== true || echoRegistration.name !== "Custom.echo") { + throw new Error(`unexpected Custom.echo registration ${JSON.stringify(echoRegistration)}`); + } + const echoResult = assertObject(await cdp.send("Custom.echo", { value: "custom-command-ok" }), "Custom.echo"); + if ( + echoResult.echoed !== "custom-command-ok" || + echoResult.method !== "Custom.echo" || + echoResult.responseMiddleware !== "ok" + ) { + throw new Error(`unexpected Custom.echo result ${JSON.stringify(echoResult)}`); + } + console.log("Custom.echo ->", echoResult); + const demoEventRegistration = assertObject( await cdp.Mod.addCustomEvent({ name: "Custom.demoEvent" }), "Mod.addCustomEvent Custom.demoEvent", @@ -461,7 +364,11 @@ async function main() { if (demoEventRegistration.registered !== true || demoEventRegistration.name !== "Custom.demoEvent") { throw new Error(`unexpected Custom.demoEvent registration ${JSON.stringify(demoEventRegistration)}`); } - const demoEventPromise = waitForEvent(cdp, "Custom.demoEvent", (event) => event?.value === "custom-event-ok"); + const demoEventPromise = waitForEvent( + cdp, + "Custom.demoEvent", + (event) => event?.value === "custom-event-ok" && event?.eventMiddleware === "ok", + ); const emitResult = assertObject( await cdp.Mod.evaluate({ expression: `async () => await ModCDP.emit("Custom.demoEvent", { value: "custom-event-ok" })`, @@ -473,95 +380,20 @@ async function main() { const demoEvent = assertObject(await demoEventPromise, "Custom.demoEvent"); console.log("Custom.demoEvent ->", demoEvent); - const PageTargetUpdated = z - .object({ - targetId: cdp.types.zod.Target.TargetID, - tabId: z.number().optional(), - url: z.string().nullable().optional(), - }) - .passthrough() - .meta({ id: "Custom.pageTargetUpdated" }); - const pageTargetEventRegistration = assertObject( - await cdp.Mod.addCustomEvent(PageTargetUpdated), - "Mod.addCustomEvent Custom.pageTargetUpdated", - ); - if (pageTargetEventRegistration.registered !== true) { - throw new Error(`unexpected page target event registration ${JSON.stringify(pageTargetEventRegistration)}`); - } - cdp.on(PageTargetUpdated, (event) => { - console.log("Custom.pageTargetUpdated ->", event); - pageTargetEvents.push(event); - }); - - await cdp.Target.setDiscoverTargets({ discover: true }); - const createdTarget = await cdp.Target.createTarget({ - url: "https://example.com", - background: true, - }); - const targetDeadline = Date.now() + DEFAULT_TARGET_EVENT_TIMEOUT_MS; - while ( - !targetCreatedEvents.some((event) => event?.targetInfo?.targetId === createdTarget.targetId) && - Date.now() < targetDeadline - ) { - await sleep(DEFAULT_DEMO_EVENT_POLL_INTERVAL_MS); - } - if (!targetCreatedEvents.some((event) => event?.targetInfo?.targetId === createdTarget.targetId)) { - throw new Error(`expected Target.targetCreated for ${createdTarget.targetId}`); - } - console.log("normal event matched ->", createdTarget.targetId); - - const tabFromTarget = await cdp.send("Custom.TabIdFromTargetId", { - targetId: createdTarget.targetId, - }); - const tabFromTargetId = - typeof tabFromTarget === "number" - ? tabFromTarget - : tabFromTarget && typeof tabFromTarget === "object" - ? (tabFromTarget as { tabId?: unknown }).tabId - : null; - if (typeof tabFromTargetId !== "number") - throw new Error(`unexpected Custom.TabIdFromTargetId result ${JSON.stringify(tabFromTarget)}`); - console.log("Custom.TabIdFromTargetId ->", tabFromTarget); - - await cdp.Target.activateTarget({ targetId: createdTarget.targetId }); - const pageTargetEmitResult = assertObject( - await cdp.Mod.evaluate({ - params: { targetId: createdTarget.targetId }, - expression: `async ({ targetId }) => { - const targets = await chrome.debugger.getTargets(); - const target = targets.find(target => target.id === targetId); - if (!target?.id) throw new Error(\`target \${targetId} not found\`); - await cdp.emit("Custom.pageTargetUpdated", { targetId: target.id, url: target.url ?? null }); - return { emitted: true, targetId: target.id }; - }`, + const runtimeEval = assertObject( + await cdp.Runtime.evaluate({ + expression: "(() => 42)()", + returnByValue: true, }), - "Custom.pageTargetUpdated emit", + "Runtime.evaluate", ); - if (pageTargetEmitResult.emitted !== true || pageTargetEmitResult.targetId !== createdTarget.targetId) { - throw new Error(`unexpected Custom.pageTargetUpdated emit result ${JSON.stringify(pageTargetEmitResult)}`); - } - const pageTargetDeadline = Date.now() + DEFAULT_PAGE_TARGET_EVENT_TIMEOUT_MS; - while ( - !pageTargetEvents.some((event) => event.targetId === createdTarget.targetId) && - Date.now() < pageTargetDeadline - ) { - await sleep(DEFAULT_DEMO_EVENT_POLL_INTERVAL_MS); - } - const pageTarget = pageTargetEvents.find((event) => event.targetId === createdTarget.targetId); - if (!pageTarget) throw new Error(`expected Custom.pageTargetUpdated for ${createdTarget.targetId}`); - if (pageTarget.tabId !== tabFromTargetId) - throw new Error(`unexpected Custom.pageTargetUpdated result ${JSON.stringify(pageTarget)}`); - - const targetFromTab = await cdp.send("Custom.targetIdFromTabId", { - tabId: pageTarget.tabId, - }); - if (targetFromTab.targetId !== createdTarget.targetId || targetFromTab.tabId !== pageTarget.tabId) { - throw new Error(`unexpected Custom.targetIdFromTabId/middleware result ${JSON.stringify(targetFromTab)}`); + if (runtimeEval.result?.value !== 42) { + throw new Error(`unexpected Runtime.evaluate result ${JSON.stringify(runtimeEval)}`); } - console.log("Custom.targetIdFromTabId ->", targetFromTab); + console.log("Runtime.evaluate ->", runtimeEval); console.log( - `\nSUCCESS (${mode}/${upstream_mode}): normal command, normal event, custom commands, custom event, and middleware all passed`, + `\nSUCCESS (${mode}/${upstream_mode}): native command, ${topologyChecked ? "topology, " : ""}custom commands, custom event, and middleware all passed`, ); // Drop into an interactive prompt when stdin is a TTY. Lets you poke at @@ -582,7 +414,7 @@ async function runRepl(cdp, mode) { console.log("Enter commands as Domain.method({...JSON params...}). Examples:"); console.log(" Browser.getVersion({})"); console.log(' Mod.evaluate({"expression": "chrome.tabs.query({active: true})"})'); - console.log(' Custom.TabIdFromTargetId({"targetId": "..."})'); + console.log(' Runtime.evaluate({"expression": "document.title", "returnByValue": true})'); console.log("Type exit or quit to disconnect (browser keeps running)."); const rl = createInterface({ input: process.stdin, output: process.stdout }); diff --git a/js/src/client/ModCDPClient.ts b/js/src/client/ModCDPClient.ts index 295c188..609f631 100644 --- a/js/src/client/ModCDPClient.ts +++ b/js/src/client/ModCDPClient.ts @@ -15,6 +15,9 @@ import type { z } from "zod"; import { createCdpAliases, type CdpAliases } from "../types/generated/aliases.js"; export type { CdpAliases } from "../types/generated/aliases.js"; import { commands as nativeCommandSchemas, events as nativeEventSchemas } from "../types/generated/zod.js"; +import type { CdpNamedSchema } from "../types/generated/zod/helpers.js"; +import * as Runtime from "../types/generated/zod/Runtime.js"; +import * as Target from "../types/generated/zod/Target.js"; import { CUSTOM_EVENT_BINDING_NAME, DEFAULT_CLIENT_ROUTES, @@ -32,6 +35,7 @@ import { import type { BrowserLauncher, BrowserLaunchOptions, LaunchedBrowser } from "../launcher/BrowserLauncher.js"; import { type ExtensionInjectorConfig, type ExtensionInjector, type SendCDP } from "../injector/ExtensionInjector.js"; import { AutoSessionRouter } from "../router/AutoSessionRouter.js"; +import type { ServerUpstreamEventListener, ServerUpstreamTransport } from "../server/ServerUpstreamTransport.js"; import type { CdpCommandMessage, CdpError, @@ -40,7 +44,6 @@ import type { RuntimeBindingCalledEvent, ModCDPConfigureParams, ModCDPServerOptions, - ModCDPCustomPayload, ModCDPAddCustomCommandParams, ModCDPAddCustomEventObjectParams, ModCDPAddMiddlewareParams, @@ -188,11 +191,11 @@ export type ModCDPClientInstance< } & { on>( eventName: TName, - listener: (event: TEvents[TName]) => void, + listener: (event: TEvents[TName], sessionId: string | null) => void, ): ModCDPClient; once>( eventName: TName, - listener: (event: TEvents[TName]) => void, + listener: (event: TEvents[TName], sessionId: string | null) => void, ): ModCDPClient; }; @@ -402,6 +405,7 @@ export class ModCDPClient extends ModCDPEventEmitter { command_result_unwrap_keys: Map; cdp_aliases_hydrated: boolean; event_wait_cleanups: Set<() => void>; + upstream_event_listeners: Map, Set>; auto_sessions: AutoSessionRouter; heartbeat_timer: ReturnType | null; _injectors: ExtensionInjector[]; @@ -458,12 +462,46 @@ export class ModCDPClient extends ModCDPEventEmitter { this.command_result_unwrap_keys = new Map(); this.cdp_aliases_hydrated = false; this.event_wait_cleanups = new Set(); + this.upstream_event_listeners = new Map(); this.heartbeat_timer = null; - this.auto_sessions = new AutoSessionRouter( - (method, params = {}, session_id = null) => - this._sendMessage(method, params, session_id) as Promise, - () => this.injector.injector_execution_context_timeout_ms, - ); + const raw_upstream_transport: ServerUpstreamTransport = { + getTargets: async () => (await raw_upstream_transport.send(Target.GetTargetsCommand, {})).targetInfos, + resolveTargetId: async (params) => + typeof params.targetId === "string" && params.targetId.length > 0 ? params.targetId : null, + createTarget: async (url) => (await raw_upstream_transport.send(Target.CreateTargetCommand, { url })).targetId, + attachToTarget: async (targetId) => + (await raw_upstream_transport.send(Target.AttachToTargetCommand, { targetId, flatten: true })).sessionId, + detachFromTarget: async (sessionId) => { + await raw_upstream_transport.send(Target.DetachFromTargetCommand, { sessionId }); + }, + send: async (command, params, route = undefined) => { + if (route && route.sessionId == null) + throw new Error(`No CDP session is attached for targetId=${route.targetId}.`); + return command.result.parse( + await this._sendMessage(command.id, command.params.parse(params), route?.sessionId ?? null), + ); + }, + on: (event, listener) => { + const typed_listener: ServerUpstreamEventListener = (payload, targetId, sessionId) => { + listener(event.parse(payload), targetId, sessionId); + }; + const listeners = this.upstream_event_listeners.get(event); + if (listeners) listeners.add(typed_listener); + else this.upstream_event_listeners.set(event, new Set([typed_listener])); + return { + remove: () => { + const current_listeners = this.upstream_event_listeners.get(event); + current_listeners?.delete(typed_listener); + if (current_listeners?.size === 0) this.upstream_event_listeners.delete(event); + }, + }; + }, + }; + this.auto_sessions = new AutoSessionRouter({ + upstream: raw_upstream_transport, + loopback_execution_context_timeout_ms: this.injector.injector_execution_context_timeout_ms, + }); + this.auto_sessions.listen(); this._injectors = []; this._launched = null; @@ -533,12 +571,20 @@ export class ModCDPClient extends ModCDPEventEmitter { const ext_context = this.auto_sessions.waitForExecutionContext(this.ext_session_id, { timeout_ms: this.injector.injector_execution_context_timeout_ms, }); - await this._sendMessage("Runtime.enable", {}, this.ext_session_id); + await this._sendMessage(Runtime.EnableCommand.id, Runtime.EnableCommand.params.parse({}), this.ext_session_id); this.ext_execution_context_id = await ext_context; await Promise.all([ - this._sendMessage("Runtime.addBinding", { name: CUSTOM_EVENT_BINDING_NAME }, this.ext_session_id), + this._sendMessage( + Runtime.AddBindingCommand.id, + Runtime.AddBindingCommand.params.parse({ name: CUSTOM_EVENT_BINDING_NAME }), + this.ext_session_id, + ), this.client.client_mirror_upstream_events - ? this._sendMessage("Runtime.addBinding", { name: UPSTREAM_EVENT_BINDING_NAME }, this.ext_session_id) + ? this._sendMessage( + Runtime.AddBindingCommand.id, + Runtime.AddBindingCommand.params.parse({ name: UPSTREAM_EVENT_BINDING_NAME }), + this.ext_session_id, + ) : Promise.resolve(), ]); if (this.server !== null) { @@ -631,7 +677,7 @@ export class ModCDPClient extends ModCDPEventEmitter { } const command = wrapCommandIfNeeded(method, command_params as ProtocolParams, { routes: this.client.client_routes, - targetCdpSessionId: session_id, + cdpSessionId: session_id, }); const result = await this._sendRaw(command); const completed_at = Date.now(); @@ -704,6 +750,8 @@ export class ModCDPClient extends ModCDPEventEmitter { } this.command_params_schemas.set("Mod.evaluate", Mod.EvaluateParams); this.command_result_schemas.set("Mod.evaluate", Mod.EvaluateResponse); + this.command_params_schemas.set("Mod.getTopology", Mod.GetTopologyParams); + this.command_result_schemas.set("Mod.getTopology", Mod.GetTopologyResponse); this.command_params_schemas.set("Mod.addCustomCommand", Mod.AddCustomCommandParams); this.command_result_schemas.set("Mod.addCustomCommand", Mod.AddCustomCommandResponse); this.command_params_schemas.set("Mod.addCustomEvent", Mod.AddCustomEventParams); @@ -904,7 +952,7 @@ export class ModCDPClient extends ModCDPEventEmitter { _serverNeedsLoopbackCdp() { if (!this.server || this.server.server_loopback_cdp_url) return false; - return Object.values(this.server.server_routes ?? {}).includes("loopback_cdp"); + return this.server.server_routes?.["*.*"] === "loopback_cdp"; } _upstreamTransportConfig() { @@ -972,8 +1020,10 @@ export class ModCDPClient extends ModCDPEventEmitter { service_worker_url_suffixes.some((suffix) => suffix.split("/").filter(Boolean).length > 1); return { send, - sessionIdForTarget: (target_id) => this.auto_sessions.sessionIdForTarget(target_id), - attachToTarget: send ? (target_id) => this.auto_sessions.attachToTarget(target_id) : null, + sessionId_from_targetId: this.auto_sessions.sessionId_from_targetId, + ensureSessionForTarget: send + ? (target_id, timeout_ms, allow_attach) => this.ensureSessionForTarget(target_id, timeout_ms, allow_attach) + : null, waitForExecutionContext: (session_id, timeout_ms) => this.auto_sessions.waitForExecutionContext(session_id, { timeout_ms }), injector_extension_path: this.injector.injector_extension_path, @@ -993,6 +1043,19 @@ export class ModCDPClient extends ModCDPEventEmitter { }; } + private async ensureSessionForTarget(target_id: string, timeout_ms = 0, allow_attach = false) { + const session_id = this.auto_sessions.sessionId_from_targetId.get(target_id); + if (session_id) return session_id; + if (allow_attach) return await this.auto_sessions.ensureSessionForTarget(target_id); + const deadline = Date.now() + timeout_ms; + while (Date.now() <= deadline) { + const current_session_id = this.auto_sessions.sessionId_from_targetId.get(target_id); + if (current_session_id) return current_session_id; + await new Promise((resolve) => setTimeout(resolve, this.injector.injector_target_session_poll_interval_ms)); + } + return null; + } + async _runInjectors(send: SendCDP, injectors: ExtensionInjector[] | null = null) { injectors ??= await this._injectorsForConfig(); const errors: string[] = []; @@ -1016,12 +1079,18 @@ export class ModCDPClient extends ModCDPEventEmitter { async _initializeRawCDPTransport() { await Promise.all([ - this._sendMessage("Target.setAutoAttach", { - autoAttach: true, - waitForDebuggerOnStart: false, - flatten: true, - }), - this._sendMessage("Target.setDiscoverTargets", { discover: true }), + this._sendMessage( + Target.SetAutoAttachCommand.id, + Target.SetAutoAttachCommand.params.parse({ + autoAttach: true, + waitForDebuggerOnStart: false, + flatten: true, + }), + ), + this._sendMessage( + Target.SetDiscoverTargetsCommand.id, + Target.SetDiscoverTargetsCommand.params.parse({ discover: true }), + ), ]); } @@ -1054,11 +1123,11 @@ export class ModCDPClient extends ModCDPEventEmitter { on( event_name: TEvent, - listener: (event: ModCDPEventPayload) => void, + listener: (event: ModCDPEventPayload, sessionId: string | null) => void, ): this; on(event_name: string | symbol, listener: (...args: unknown[]) => void): this; - on(event_name: ModCDPEventNameInput, listener: (...args: unknown[]) => void): this; - on(event_name: ModCDPEventNameInput, listener: (...args: unknown[]) => void) { + on(event_name: ModCDPEventNameInput, listener: (...args: any[]) => void): this; + on(event_name: ModCDPEventNameInput, listener: (...args: any[]) => void) { if (typeof event_name !== "string" && typeof event_name !== "symbol") { const name = normalizeModCDPName(event_name); this.event_schemas.set(name, event_name); @@ -1069,11 +1138,11 @@ export class ModCDPClient extends ModCDPEventEmitter { once( event_name: TEvent, - listener: (event: ModCDPEventPayload) => void, + listener: (event: ModCDPEventPayload, sessionId: string | null) => void, ): this; once(event_name: string | symbol, listener: (...args: unknown[]) => void): this; - once(event_name: ModCDPEventNameInput, listener: (...args: unknown[]) => void): this; - once(event_name: ModCDPEventNameInput, listener: (...args: unknown[]) => void) { + once(event_name: ModCDPEventNameInput, listener: (...args: any[]) => void): this; + once(event_name: ModCDPEventNameInput, listener: (...args: any[]) => void) { if (typeof event_name !== "string" && typeof event_name !== "symbol") { const name = normalizeModCDPName(event_name); this.event_schemas.set(name, event_name); @@ -1084,11 +1153,11 @@ export class ModCDPClient extends ModCDPEventEmitter { off( event_name: TEvent, - listener: (event: ModCDPEventPayload) => void, + listener: (event: ModCDPEventPayload, sessionId: string | null) => void, ): this; off(event_name: string | symbol, listener: (...args: unknown[]) => void): this; - off(event_name: ModCDPEventNameInput, listener: (...args: unknown[]) => void): this; - off(event_name: ModCDPEventNameInput, listener: (...args: unknown[]) => void) { + off(event_name: ModCDPEventNameInput, listener: (...args: any[]) => void): this; + off(event_name: ModCDPEventNameInput, listener: (...args: any[]) => void) { if (typeof event_name !== "string" && typeof event_name !== "symbol") { return super.off(normalizeModCDPName(event_name), listener); } @@ -1158,7 +1227,9 @@ export class ModCDPClient extends ModCDPEventEmitter { let unwrap = null; for (const step of command.steps) { const step_params = - step.method === "Runtime.callFunctionOn" && step.params && !Object.hasOwn(step.params, "executionContextId") + step.method === Runtime.CallFunctionOnCommand.id && + step.params && + !Object.hasOwn(step.params, "executionContextId") ? { ...step.params, executionContextId: @@ -1254,43 +1325,30 @@ export class ModCDPClient extends ModCDPEventEmitter { return; } const event = CdpEventMessageSchema.parse(msg); + const eventParams = (event.params || {}) as ProtocolPayload; + for (const [upstream_event, listeners] of this.upstream_event_listeners) { + if (upstream_event.id !== event.method) continue; + for (const listener of listeners) listener(eventParams, null, event.sessionId || null); + } if (event.sessionId === this.ext_session_id) { - if (event.method === "Runtime.executionContextCreated") { - this.auto_sessions.recordProtocolEvent(event.method, event.params || {}, event.sessionId || null); - } - if (event.method !== "Runtime.bindingCalled") return; + if (event.method !== this.Runtime.bindingCalled.id) return; const u = unwrapEventIfNeeded( event.method, - (event.params || {}) as RuntimeBindingCalledEvent, + eventParams as RuntimeBindingCalledEvent, event.sessionId || null, this.ext_session_id, ); if (u) { const payload = this._parseEventPayload(u.event, u.data); - this.auto_sessions.recordProtocolEvent(u.event, payload as ProtocolPayload, u.sessionId); this.emit(u.event, payload, u.sessionId); } return; } if (event.method) { - const data = event.params || {}; - const payload = this._parseEventPayload(event.method, data); - this.auto_sessions.recordProtocolEvent(event.method, payload as ProtocolPayload, event.sessionId || null); + const payload = this._parseEventPayload(event.method, eventParams); this.emit(event.method, payload, event.sessionId || null); } } - - get auto_target_sessions() { - return this.auto_sessions.target_sessions; - } - - get auto_session_targets() { - return this.auto_sessions.session_targets; - } - - get runtime_execution_contexts() { - return this.auto_sessions.execution_contexts; - } } export interface ModCDPClient extends CdpAliases {} diff --git a/js/src/injector/BorrowedExtensionInjector.ts b/js/src/injector/BorrowedExtensionInjector.ts index 48f5cca..ea594bc 100644 --- a/js/src/injector/BorrowedExtensionInjector.ts +++ b/js/src/injector/BorrowedExtensionInjector.ts @@ -54,7 +54,7 @@ export class BorrowedExtensionInjector extends ExtensionInjector { } private async bootstrapTarget(target: TargetInfo): Promise { - const session_id = await this.ensureSessionIdForTarget( + const session_id = await this.ensureSessionForTarget( target.targetId, this.options.injector_service_worker_probe_timeout_ms, true, diff --git a/js/src/injector/ExtensionInjector.ts b/js/src/injector/ExtensionInjector.ts index 5acf392..b365b5c 100644 --- a/js/src/injector/ExtensionInjector.ts +++ b/js/src/injector/ExtensionInjector.ts @@ -24,8 +24,12 @@ export type TargetInfo = { targetId: string; type?: string; url?: string }; export type ExtensionInjectorConfig = { send?: SendCDP | null; - sessionIdForTarget?: ((target_id: string) => string | null | undefined) | null; - attachToTarget?: ((target_id: string) => Promise) | null; + sessionId_from_targetId?: Map | null; + ensureSessionForTarget?: ( + target_id: string, + timeout_ms: number, + allow_attach: boolean, + ) => Promise; waitForExecutionContext?: ((session_id: string, timeout_ms: number) => Promise) | null; injector_extension_path?: string | null; injector_extension_id?: string | null; @@ -147,8 +151,8 @@ export class ExtensionInjector { constructor(options: ExtensionInjectorConfig = {}) { this.options = { send: null, - sessionIdForTarget: null, - attachToTarget: null, + sessionId_from_targetId: null, + ensureSessionForTarget: null, waitForExecutionContext: null, injector_extension_path: null, injector_extension_id: null, @@ -234,24 +238,10 @@ export class ExtensionInjector { }); } - protected async sessionIdForTarget(target_id: string, timeout_ms = 0) { - const deadline = Date.now() + timeout_ms; - while (true) { - const session_id = this.options.sessionIdForTarget?.(target_id); - if (typeof session_id === "string" && session_id.length > 0) return session_id; - if (Date.now() >= deadline) return null; - await delay(this.options.injector_target_session_poll_interval_ms ?? DEFAULT_TARGET_SESSION_POLL_INTERVAL_MS); - } - } - - protected async ensureSessionIdForTarget(target_id: string, timeout_ms = 0, allow_attach = false) { - const session_id = this.options.sessionIdForTarget?.(target_id); + protected async ensureSessionForTarget(target_id: string, timeout_ms = 0, allow_attach = false) { + const session_id = this.options.sessionId_from_targetId?.get(target_id); if (typeof session_id === "string" && session_id.length > 0) return session_id; - if (allow_attach) { - const attached_session_id = await this.options.attachToTarget?.(target_id); - if (typeof attached_session_id === "string" && attached_session_id.length > 0) return attached_session_id; - } - return await this.sessionIdForTarget(target_id, timeout_ms); + return (await this.options.ensureSessionForTarget?.(target_id, timeout_ms, allow_attach)) ?? null; } protected async targetInfos() { @@ -264,7 +254,7 @@ export class ExtensionInjector { { allow_attach = false }: { allow_attach?: boolean } = {}, ): Promise { if (this.unusable_target_ids.has(target.targetId)) return null; - const session_id = await this.ensureSessionIdForTarget(target.targetId, session_timeout_ms, allow_attach); + const session_id = await this.ensureSessionForTarget(target.targetId, session_timeout_ms, allow_attach); if (session_id == null) return null; await this.sendWithTimeout("Runtime.enable", {}, session_id); const probe = RuntimeCommands["Runtime.evaluate"].result.parse( diff --git a/js/src/proxy/proxy.ts b/js/src/proxy/proxy.ts index 46186c7..c7d86ce 100644 --- a/js/src/proxy/proxy.ts +++ b/js/src/proxy/proxy.ts @@ -728,7 +728,7 @@ async function handleConnection( ext_execution_context_id: cdp.ext_execution_context_id, hidden_session_ids: new Set(), // sessions we attached for ourselves hidden_target_ids: new Set(), // SW target the client must never see - target_session_ids: cdp.auto_target_sessions, + target_session_ids: cdp.auto_sessions.sessionId_from_targetId, client_session_ids: new Set(), // session ids the client has attached forward_mirrored_upstream_events: forward_mirrored_upstream_events, bootstrapped: false, diff --git a/js/src/router/AutoSessionRouter.ts b/js/src/router/AutoSessionRouter.ts index 1315b2c..91b461c 100644 --- a/js/src/router/AutoSessionRouter.ts +++ b/js/src/router/AutoSessionRouter.ts @@ -1,124 +1,628 @@ -import type { ProtocolParams, ProtocolResult } from "../types/modcdp.js"; +import type { cdp } from "../types/generated/cdp.js"; +import { commands as nativeCommandSchemas } from "../types/generated/zod.js"; +import type { CdpCommandSchema } from "../types/generated/zod/helpers.js"; +import * as DOM from "../types/generated/zod/DOM.js"; +import * as Page from "../types/generated/zod/Page.js"; +import * as Runtime from "../types/generated/zod/Runtime.js"; +import * as Target from "../types/generated/zod/Target.js"; +import type { ServerUpstreamTransport, TargetRoute } from "../server/ServerUpstreamTransport.js"; +import { + CdpDebuggeeCommandParamsSchema, + type CdpDebuggeeCommandParams, + type ModCDPGetTopologyParams, + type ModCDPTopology, + type ModCDPTopologyDomRoot, + type ModCDPTopologyExecutionContext, + type ModCDPTopologyFrame, + type ModCDPTopologyTarget, + type ProtocolParams, + type ProtocolResult, +} from "../types/modcdp.js"; -type SendCDP = (method: string, params?: ProtocolParams, session_id?: string | null) => Promise; +type FrameTree = cdp.types.ts.Page.FrameTree; +type DomNode = cdp.types.ts.DOM.Node; +type TargetInfo = cdp.types.ts.Target.TargetInfo; +type ContextSelector = { + world: string; + worldName?: string; +}; type ExecutionContextWaiter = { - resolve: (context_id: number) => void; + resolve: (context: ModCDPTopologyExecutionContext) => void; reject: (error: Error) => void; timeout: ReturnType; + matches: (context: ModCDPTopologyExecutionContext) => boolean; }; -const max_detached_session_guards = 1024; +const topologyConcurrency = 8; +const piercerWorldName = "__modcdp_piercer__"; +const native_commands_by_id: ReadonlyMap = new Map( + Object.values(nativeCommandSchemas).map((command) => [command.id, command]), +); + +const targetAutoAttachParams = { + autoAttach: true, + waitForDebuggerOnStart: false, + flatten: true, +} satisfies cdp.types.ts.Target.SetAutoAttachParams; +/** + * Owns ModCDP's browser graph and target/session/context routing policy. + * + * AutoSessionRouter records Target/Page/Runtime events, maintains the current + * target-to-session graph, hydrates target routes on demand, creates execution + * contexts, and builds Mod.getTopology output. It does not know how commands + * are physically delivered. Loopback WebSocket request ids, chrome.debugger + * debuggee selection, native event source normalization, and upstream setup all + * live behind the ServerUpstreamTransport interface. + * + * State machine: + * 1. Target records arrive from Target.getTargets or target-info events. + * 2. ensureRouteForTarget attaches a target and records either a native session id + * or a sessionless attached target supplied by the upstream. + * 3. Runtime/Page events add or invalidate execution context records. + * 4. Frame detach, navigation, target detach, and target destroy events remove + * only the state affected by the browser event. + */ export class AutoSessionRouter { - readonly target_sessions = new Map(); - readonly session_targets = new Map>(); - readonly execution_contexts = new Map(); + // TargetID -> native flattened Target.SessionID. Updated by ensureRouteForTarget + // and Target.attachedToTarget events; read by routing, injectors, and topology. + readonly sessionId_from_targetId = new Map(); + + // Native flattened Target.SessionID -> TargetID. Updated with + // sessionId_from_targetId; read when events arrive with only a session id. + readonly targetId_from_sessionId = new Map(); + + // TargetID -> latest target metadata plus router-owned session metadata. + // Updated from target discovery/events; read by topology and target selection. + readonly targets = new Map(); + + // Context key -> execution context. The key is Chrome's uniqueId when present, + // otherwise target/session plus context id. Updated by Runtime events and by + // Page.createIsolatedWorld; read by waits, DOM root resolution, and topology. + readonly contexts = new Map(); + + // SessionID -> first Runtime execution context id observed for that session. + // Updated by Runtime.executionContextCreated; read by ModCDPClient injectors. + readonly execution_contexts = new Map(); + + // Context waiters keyed by native session id or by target id for sessionless + // upstreams. Added by waitForExecutionContextMatching and resolved/rejected by + // recordExecutionContext and invalidation methods. private readonly execution_context_waiters = new Map>(); - private readonly detached_sessions = new Map(); - constructor( - private readonly send: SendCDP, - private readonly defaultExecutionContextTimeoutMs: () => number, - ) {} + // Semantic upstream selected by the owner. The router calls methods on this + // object but never mutates transport-owned private state. + private readonly upstream: ServerUpstreamTransport; + + // Timeout in milliseconds for Runtime.executionContextCreated waits. Set once + // by the owner when constructing the router; read when installing a new + // execution-context waiter. + private readonly loopback_execution_context_timeout_ms: number; + + constructor({ + upstream, + loopback_execution_context_timeout_ms, + }: { + upstream: ServerUpstreamTransport; + loopback_execution_context_timeout_ms: number; + }) { + this.upstream = upstream; + this.loopback_execution_context_timeout_ms = loopback_execution_context_timeout_ms; + } + + /** Route a CDP command using router-owned target/session policy. */ + async send( + method: string, + params: ProtocolParams = {}, + requestedSessionId: cdp.types.ts.Target.SessionID | null = null, + ): Promise { + const command = native_commands_by_id.get(method); + if (!command) throw new Error(`AutoSessionRouter cannot route unknown CDP command ${method}.`); + const commandParams = command.params.parse(params); + const domain = command.id.split(".")[0] ?? ""; + if (domain === "Browser" || domain === "Target" || domain === "SystemInfo") + return await this.upstream.send(command, commandParams); + if (requestedSessionId != null) { + const targetId = this.targetId_from_sessionId.get(requestedSessionId); + if (!targetId) throw new Error(`No target is recorded for sessionId=${requestedSessionId}.`); + return await this.upstream.send(command, commandParams, { targetId, sessionId: requestedSessionId }); + } + const route = await this.ensureRouteForTarget( + await this.resolveTargetId(CdpDebuggeeCommandParamsSchema.parse(params)), + ); + return await this.upstream.send(command, commandParams, route); + } + + /** Ensure a target has a real native flattened CDP session id. */ + async ensureSessionForTarget(targetId: cdp.types.ts.Target.TargetID): Promise { + const route = await this.ensureRouteForTarget(targetId); + if (route.sessionId == null) throw new Error(`Upstream attached targetId=${targetId} without a CDP session id.`); + return route.sessionId; + } + + /** Ensure a target is addressable by the selected upstream. */ + async ensureRouteForTarget(targetId: cdp.types.ts.Target.TargetID | null): Promise { + targetId ??= await this.resolveTargetId(CdpDebuggeeCommandParamsSchema.parse({})); + const sessionId = targetId ? this.sessionId_from_targetId.get(targetId) : null; + if (targetId && sessionId != null) return { targetId, sessionId }; + const target = targetId ? this.targets.get(targetId) : null; + if (targetId && target?.sessionId === null) return { targetId, sessionId: null }; + targetId ??= await this.upstream.createTarget("about:blank#modcdp"); + const attachedSessionId = await this.upstream.attachToTarget(targetId); + if (attachedSessionId == null) { + this.recordTargetSessionlessAttachment(targetId); + return { targetId, sessionId: null }; + } + this.recordTargetSession(targetId, attachedSessionId, this.targets.get(targetId)); + return { targetId, sessionId: attachedSessionId }; + } + + /** Subscribe this router to the selected upstream's normalized CDP events. */ + listen(): { remove: () => void } { + const subscriptions = [ + this.upstream.on(Target.AttachedToTargetEvent, (event) => + this.recordTargetSession(event.targetInfo.targetId, event.sessionId, event.targetInfo), + ), + this.upstream.on(Target.DetachedFromTargetEvent, (event) => this.forgetSession(event.sessionId)), + this.upstream.on(Target.TargetInfoChangedEvent, (event) => this.recordTarget(event.targetInfo)), + this.upstream.on(Target.TargetDestroyedEvent, (event) => this.forgetTarget(event.targetId)), + this.upstream.on(Runtime.ExecutionContextCreatedEvent, (event, targetId, sessionId) => { + this.recordExecutionContext(targetId, sessionId, event.context); + }), + this.upstream.on(Runtime.ExecutionContextDestroyedEvent, (event, _targetId, sessionId) => { + if (sessionId) this.forgetExecutionContextById(sessionId, event.executionContextId); + }), + this.upstream.on(Runtime.ExecutionContextsClearedEvent, (_event, _targetId, sessionId) => { + if (sessionId) this.forgetExecutionContextsForRoute(sessionId); + }), + this.upstream.on(Page.FrameNavigatedEvent, (event, targetId, sessionId) => { + this.forgetExecutionContextsForFrame(sessionId, targetId, event.frame.id); + }), + this.upstream.on(Page.FrameDetachedEvent, (event, targetId, sessionId) => { + this.forgetExecutionContextsForFrame(sessionId, targetId, event.frameId); + }), + ]; + return { remove: () => subscriptions.forEach((subscription) => subscription.remove()) }; + } + + /** Wait for the first execution context associated with a real session id. */ + waitForExecutionContext(sessionId: string | null, { timeout_ms }: { timeout_ms?: number } = {}): Promise { + return this.waitForExecutionContextMatching( + (context) => context.sessionId === sessionId, + sessionId, + timeout_ms, + ).then((context) => context.id); + } + + /** Ensure the requested execution context exists for a frame. */ + async ensureExecutionContext( + frame: { frameId: cdp.types.ts.Page.FrameId; targetId: cdp.types.ts.Target.TargetID }, + selector: ContextSelector = { world: "main" }, + ): Promise { + const route = await this.ensureRouteForTarget(frame.targetId); + const existing = this.findExecutionContext(route.targetId, route.sessionId, frame.frameId, selector); + if (existing) return existing; + + await this.upstream.send(Runtime.EnableCommand, {}, route); + if (selector.world === "isolated" || selector.world === "piercer") { + const created = await this.upstream.send( + Page.CreateIsolatedWorldCommand, + { + frameId: frame.frameId, + worldName: selector.worldName ?? (selector.world === "piercer" ? piercerWorldName : undefined), + grantUniveralAccess: true, + }, + route, + ); + const createdContext = this.findExecutionContext(route.targetId, route.sessionId, frame.frameId, selector); + if (createdContext?.id === created.executionContextId) return createdContext; + const context: ModCDPTopologyExecutionContext = { + id: created.executionContextId, + sessionId: route.sessionId, + targetId: route.targetId, + frameId: frame.frameId, + world: selector.world === "piercer" ? "piercer" : selector.worldName || "isolated", + name: selector.worldName, + }; + this.contexts.set(this.contextKey(route.targetId, route.sessionId, context.id, context.uniqueId), context); + return context; + } + + return await this.waitForExecutionContextMatching( + (context) => + context.targetId === route.targetId && + context.sessionId === route.sessionId && + context.frameId === frame.frameId && + context.world === selector.world, + route.sessionId ?? route.targetId, + ); + } + + /** Build the current target/frame/DOM-root/execution-context topology. */ + async getTopology(params: ModCDPGetTopologyParams = {}): Promise { + const objectGroup = `modcdp-topology-${Date.now()}-${Math.random().toString(16).slice(2)}`; + const targetInfos = await this.upstream.getTargets(); + for (const targetInfo of targetInfos) this.recordTarget(targetInfo); + + const rootTarget = this.resolveRootTarget(params, targetInfos); + if (rootTarget == null) throw new Error("Mod.getTopology could not resolve a page target."); + const frames = new Map(); + const rootRoute = await this.enableTarget(rootTarget.targetId); + const rootTree = (await this.upstream.send(Page.GetFrameTreeCommand, {}, rootRoute)).frameTree; + const rootFrameId = rootTree.frame.id; + this.recordFrameTree(rootTree, rootTarget.targetId, null, frames); + + const oopifTargets = targetInfos.filter( + (target) => target.type === "iframe" && target.parentFrameId && !frames.has(target.targetId), + ); + await runTopologyQueue(oopifTargets, async (target) => { + const route = await this.enableTarget(target.targetId); + const frameTree = (await this.upstream.send(Page.GetFrameTreeCommand, {}, route)).frameTree; + this.recordFrameTree(frameTree, target.targetId, target.parentFrameId ?? null, frames); + }); + + await runTopologyQueue([...frames.entries()], async ([frameId, frame]) => { + if (!frame.parentFrameId) return; + const parent = frames.get(frame.parentFrameId); + if (!parent) return; + const parentRoute = await this.ensureRouteForTarget(parent.targetId); + const owner = await this.upstream.send(DOM.GetFrameOwnerCommand, { frameId }, parentRoute); + if (owner.backendNodeId != null) frame.outerBackendNodeId = owner.backendNodeId; + }); + + const contexts = new Map(); + const roots = new Map(); + await runTopologyQueue([...frames.entries()], async ([frameId, frame]) => { + const context = await this.ensureExecutionContext({ frameId, targetId: frame.targetId }, { world: "piercer" }); + contexts.set(this.contextKey(context.targetId, context.sessionId ?? null, context.id, context.uniqueId), context); + const rootObject = await this.upstream.send( + Runtime.EvaluateCommand, + { + expression: "document.documentElement", + objectGroup, + ...(context.uniqueId ? { uniqueContextId: context.uniqueId } : { contextId: context.id }), + }, + context, + ); + const objectId = rootObject.result.objectId; + if (!objectId) throw new Error(`Mod.getTopology could not resolve document root for frameId=${frameId}.`); + const node = ( + await this.upstream.send( + DOM.DescribeNodeCommand, + { + objectId, + }, + context, + ) + ).node; + roots.set(objectId, { + kind: "document", + frameId, + outerBackendNodeId: frame.outerBackendNodeId ?? null, + innerBackendNodeId: node.backendNodeId ?? null, + executionContextId: context.id, + ...(context.uniqueId ? { uniqueContextId: context.uniqueId } : {}), + }); + }); + + await runTopologyQueue([...new Set([...frames.values()].map((frame) => frame.targetId))], async (targetId) => { + const route = await this.ensureRouteForTarget(targetId); + const document = await this.upstream.send( + DOM.GetDocumentCommand, + { + depth: -1, + pierce: true, + }, + route, + ); + await this.recordShadowRoots(document.root, frames, roots, objectGroup); + }); + + for (const context of this.contexts.values()) { + if ([...frames.values()].some((frame) => frame.targetId === context.targetId)) { + contexts.set( + this.contextKey(context.targetId, context.sessionId ?? null, context.id, context.uniqueId), + context, + ); + } + } + + return { + objectGroup, + rootFrameId, + frames: Object.fromEntries(frames), + roots: Object.fromEntries(roots), + targets: Object.fromEntries( + [...this.targets].filter(([targetId]) => targetInfos.some((target) => target.targetId === targetId)), + ), + contexts: Object.fromEntries(contexts), + }; + } + + private resolveRootTarget(params: ModCDPGetTopologyParams, targetInfos: TargetInfo[]): TargetInfo | null { + const requestedTargetId = params.rootTargetId ?? params.targetId ?? null; + if (requestedTargetId) return targetInfos.find((target) => target.targetId === requestedTargetId) ?? null; + return targetInfos.find((target) => target.type === "page" && !target.url.startsWith("devtools://")) ?? null; + } + + private async resolveTargetId(params: CdpDebuggeeCommandParams): Promise { + const explicitTargetId = await this.upstream.resolveTargetId(params); + if (explicitTargetId) return explicitTargetId; + const targetInfos = await this.upstream.getTargets(); + for (const targetInfo of targetInfos) this.recordTarget(targetInfo); + return ( + targetInfos.find((target) => target.type === "page" && !target.url.startsWith("devtools://"))?.targetId ?? null + ); + } - sessionIdForTarget(target_id: string) { - return this.target_sessions.get(target_id) ?? null; + private async enableTarget(targetId: cdp.types.ts.Target.TargetID): Promise { + const route = await this.ensureRouteForTarget(targetId); + await Promise.all([ + this.upstream.send(Page.EnableCommand, {}, route), + this.upstream.send(DOM.EnableCommand, {}, route), + this.upstream.send(Runtime.EnableCommand, {}, route), + this.upstream.send(Target.SetAutoAttachCommand, targetAutoAttachParams, route).catch(() => ({})), + ]); + return route; } - async attachToTarget(target_id: string) { - const existing_session_id = this.sessionIdForTarget(target_id); - if (existing_session_id != null) return existing_session_id; - const result = await this.send("Target.attachToTarget", { - targetId: target_id, - flatten: true, + private recordFrameTree( + tree: FrameTree, + targetId: cdp.types.ts.Target.TargetID, + parentFrameId: cdp.types.ts.Page.FrameId | null, + frames: Map, + ): void { + const frameId = tree.frame.id; + frames.set(frameId, { + targetId, + url: tree.frame.url ?? null, + parentFrameId: tree.frame.parentId ?? parentFrameId ?? null, }); - const session_id = result && typeof result === "object" ? (result as Record).sessionId : null; - return typeof session_id === "string" && session_id.length > 0 ? session_id : null; - } - - recordProtocolEvent(method: string, data: unknown, session_id: string | null) { - const event_data = - data && typeof data === "object" && !Array.isArray(data) ? (data as Record) : {}; - if (method === "Target.attachedToTarget") { - const attached_session_id = typeof event_data.sessionId === "string" ? event_data.sessionId : session_id; - const target_info = - event_data.targetInfo && typeof event_data.targetInfo === "object" - ? (event_data.targetInfo as Record) + for (const child of tree.childFrames ?? []) this.recordFrameTree(child, targetId, frameId, frames); + } + + private async recordShadowRoots( + node: DomNode, + frames: Map, + roots: Map, + objectGroup: string, + frameId: cdp.types.ts.Page.FrameId | null = null, + hostBackendNodeId: cdp.types.ts.DOM.BackendNodeId | null = null, + ): Promise { + const currentFrameId = node.frameId ?? frameId; + for (const shadowRoot of node.shadowRoots ?? []) { + if (currentFrameId) { + const frame = frames.get(currentFrameId); + const context = frame + ? this.findExecutionContext(frame.targetId, null, currentFrameId, { world: "piercer" }) : null; - const target_id = typeof target_info?.targetId === "string" ? target_info.targetId : null; - if (attached_session_id && target_id && target_info) { - this.detached_sessions.delete(attached_session_id); - this.target_sessions.set(target_id, attached_session_id); - this.session_targets.set(attached_session_id, target_info); + if (frame && context) { + const objectId = ( + await this.upstream.send( + DOM.ResolveNodeCommand, + { + backendNodeId: shadowRoot.backendNodeId, + executionContextId: context.id, + objectGroup, + }, + context, + ) + ).object.objectId; + if (objectId) { + roots.set(objectId, { + kind: "shadow", + frameId: currentFrameId, + outerBackendNodeId: hostBackendNodeId ?? node.backendNodeId ?? null, + innerBackendNodeId: shadowRoot.backendNodeId ?? null, + mode: shadowRoot.shadowRootType, + executionContextId: context.id, + ...(context.uniqueId ? { uniqueContextId: context.uniqueId } : {}), + }); + } + } } - } else if (method === "Runtime.executionContextCreated") { - const context = event_data.context && typeof event_data.context === "object" ? event_data.context : null; - const context_id = context && "id" in context && typeof context.id === "number" ? context.id : null; - if (session_id && context_id != null) this.recordExecutionContext(session_id, context_id); - } else if (method === "Target.detachedFromTarget") { - const detached_session_id = typeof event_data.sessionId === "string" ? event_data.sessionId : session_id; - if (detached_session_id) this.forgetSession(detached_session_id); + await this.recordShadowRoots(shadowRoot, frames, roots, objectGroup, currentFrameId, node.backendNodeId ?? null); + } + for (const child of node.children ?? []) { + await this.recordShadowRoots(child, frames, roots, objectGroup, currentFrameId, hostBackendNodeId); + } + if (node.contentDocument) { + await this.recordShadowRoots( + node.contentDocument, + frames, + roots, + objectGroup, + node.contentDocument.frameId ?? currentFrameId, + hostBackendNodeId, + ); + } + } + + private recordTarget(targetInfo: TargetInfo): void { + const sessionId = this.sessionId_from_targetId.get(targetInfo.targetId); + const existing = this.targets.get(targetInfo.targetId); + const target: ModCDPTopologyTarget = { + ...targetInfo, + targetId: targetInfo.targetId, + type: targetInfo.type, + }; + if (sessionId !== undefined) target.sessionId = sessionId; + else if (existing?.sessionId === null) target.sessionId = null; + this.targets.set(targetInfo.targetId, target); + } + + private recordTargetSession( + targetId: cdp.types.ts.Target.TargetID, + sessionId: cdp.types.ts.Target.SessionID, + targetInfo: TargetInfo | ModCDPTopologyTarget | null | undefined, + ): void { + this.sessionId_from_targetId.set(targetId, sessionId); + this.targetId_from_sessionId.set(sessionId, targetId); + const target = targetInfo + ? { ...targetInfo, targetId, type: targetInfo.type, sessionId } + : { targetId, type: this.targets.get(targetId)?.type ?? "page", sessionId }; + this.targets.set(targetId, target); + } + + private recordTargetSessionlessAttachment(targetId: cdp.types.ts.Target.TargetID): void { + const existing = this.targets.get(targetId); + this.targets.set( + targetId, + existing ? { ...existing, sessionId: null } : { targetId, type: "page", sessionId: null }, + ); + } + + private recordExecutionContext( + eventTargetId: cdp.types.ts.Target.TargetID | null, + sessionId: cdp.types.ts.Target.SessionID | null, + context: cdp.types.ts.Runtime.ExecutionContextDescription, + ): void { + const targetId = eventTargetId ?? (sessionId ? (this.targetId_from_sessionId.get(sessionId) ?? null) : null); + if (!targetId) return; + if (sessionId && !this.execution_contexts.has(sessionId)) this.execution_contexts.set(sessionId, context.id); + const auxData = context.auxData && typeof context.auxData === "object" ? context.auxData : {}; + const frameId = typeof auxData.frameId === "string" ? auxData.frameId : null; + const topologyContext: ModCDPTopologyExecutionContext = { + ...context, + id: context.id, + sessionId, + targetId, + frameId, + world: + context.name === piercerWorldName + ? "piercer" + : auxData.type === "default" + ? "main" + : context.name || String(auxData.type ?? "isolated"), + }; + this.contexts.set(this.contextKey(targetId, sessionId, context.id, context.uniqueId), topologyContext); + const waiterKey = sessionId ?? targetId; + const waiters = this.execution_context_waiters.get(waiterKey); + if (!waiters) return; + for (const waiter of [...waiters]) { + if (!waiter.matches(topologyContext)) continue; + waiters.delete(waiter); + clearTimeout(waiter.timeout); + waiter.resolve(topologyContext); } + if (waiters.size === 0) this.execution_context_waiters.delete(waiterKey); } - waitForExecutionContext(session_id: string | null, { timeout_ms }: { timeout_ms?: number } = {}) { - const effective_timeout_ms = timeout_ms ?? this.defaultExecutionContextTimeoutMs(); - if (!session_id) return Promise.reject(new Error("Cannot wait for a Runtime execution context without a session.")); - const existing = this.execution_contexts.get(session_id); - if (existing != null) return Promise.resolve(existing); - return new Promise((resolve, reject) => { + private findExecutionContext( + targetId: cdp.types.ts.Target.TargetID, + sessionId: cdp.types.ts.Target.SessionID | null, + frameId: cdp.types.ts.Page.FrameId, + selector: ContextSelector, + ): ModCDPTopologyExecutionContext | null { + for (const context of this.contexts.values()) { + if (context.targetId !== targetId || context.frameId !== frameId) continue; + if (sessionId != null && context.sessionId !== sessionId) continue; + if (selector.world === "piercer" && context.world === "piercer") return context; + if (selector.world === "isolated" && context.name === selector.worldName) return context; + if (selector.world === "main" && context.world === "main") return context; + if (context.world === selector.world) return context; + } + return null; + } + + private waitForExecutionContextMatching( + matches: (context: ModCDPTopologyExecutionContext) => boolean, + waiterKey: string | null, + timeoutMs = this.loopback_execution_context_timeout_ms, + ): Promise { + for (const context of this.contexts.values()) { + if (matches(context)) return Promise.resolve(context); + } + if (!waiterKey) return Promise.reject(new Error("Cannot wait for a Runtime execution context without a route.")); + return new Promise((resolve, reject) => { const waiter: ExecutionContextWaiter = { resolve, reject, + matches, timeout: setTimeout(() => { - const waiters = this.execution_context_waiters.get(session_id); + const waiters = this.execution_context_waiters.get(waiterKey); waiters?.delete(waiter); - if (waiters?.size === 0) this.execution_context_waiters.delete(session_id); - reject(new Error(`Timed out waiting for Runtime.executionContextCreated for session ${session_id}.`)); - }, effective_timeout_ms), + if (waiters?.size === 0) this.execution_context_waiters.delete(waiterKey); + reject(new Error(`Timed out waiting for Runtime.executionContextCreated for route ${waiterKey}.`)); + }, timeoutMs), }; - const waiters = this.execution_context_waiters.get(session_id); + const waiters = this.execution_context_waiters.get(waiterKey); if (waiters) waiters.add(waiter); - else this.execution_context_waiters.set(session_id, new Set([waiter])); + else this.execution_context_waiters.set(waiterKey, new Set([waiter])); }); } - private recordExecutionContext(session_id: string, context_id: number) { - if (this.detached_sessions.has(session_id)) return; - this.execution_contexts.set(session_id, context_id); - const waiters = this.execution_context_waiters.get(session_id); - if (!waiters) return; - this.execution_context_waiters.delete(session_id); - for (const waiter of waiters) { - clearTimeout(waiter.timeout); - waiter.resolve(context_id); - } + private forgetTarget(targetId: cdp.types.ts.Target.TargetID): void { + const sessionId = this.sessionId_from_targetId.get(targetId); + if (sessionId) this.forgetSession(sessionId); + this.targets.delete(targetId); + this.forgetExecutionContextsForRoute(targetId); } - private forgetSession(session_id: string) { - const target_info = this.session_targets.get(session_id); - const target_id = typeof target_info?.targetId === "string" ? target_info.targetId : null; - if (target_id) this.target_sessions.delete(target_id); - this.session_targets.delete(session_id); - this.execution_contexts.delete(session_id); - this.markDetachedSession(session_id); - const waiters = this.execution_context_waiters.get(session_id); + private forgetSession(sessionId: cdp.types.ts.Target.SessionID): void { + const targetId = this.targetId_from_sessionId.get(sessionId); + if (targetId) this.sessionId_from_targetId.delete(targetId); + this.targetId_from_sessionId.delete(sessionId); + this.forgetExecutionContextsForRoute(sessionId); + const waiters = this.execution_context_waiters.get(sessionId); if (!waiters) return; - this.execution_context_waiters.delete(session_id); - const error = new Error(`Runtime execution context wait cancelled because session ${session_id} detached.`); + this.execution_context_waiters.delete(sessionId); + const error = new Error(`Runtime execution context wait cancelled because session ${sessionId} detached.`); for (const waiter of waiters) { clearTimeout(waiter.timeout); waiter.reject(error); } } - private markDetachedSession(session_id: string) { - this.detached_sessions.delete(session_id); - this.detached_sessions.set(session_id, true); - while (this.detached_sessions.size > max_detached_session_guards) { - const oldest_session_id = this.detached_sessions.keys().next().value; - if (!oldest_session_id) break; - this.detached_sessions.delete(oldest_session_id); + private forgetExecutionContextById( + routeKey: string, + executionContextId: cdp.types.ts.Runtime.ExecutionContextId, + ): void { + for (const [contextKey, context] of this.contexts) { + if ((context.sessionId === routeKey || context.targetId === routeKey) && context.id === executionContextId) { + this.contexts.delete(contextKey); + } + } + if (this.execution_contexts.get(routeKey) === executionContextId) this.execution_contexts.delete(routeKey); + } + + private forgetExecutionContextsForRoute(routeKey: string): void { + for (const [contextKey, context] of this.contexts) { + if (context.sessionId === routeKey || context.targetId === routeKey) this.contexts.delete(contextKey); + } + this.execution_contexts.delete(routeKey); + } + + private forgetExecutionContextsForFrame( + sessionId: cdp.types.ts.Target.SessionID | null, + targetId: cdp.types.ts.Target.TargetID | null, + frameId: cdp.types.ts.Page.FrameId, + ): void { + for (const [contextKey, context] of this.contexts) { + if (context.frameId !== frameId) continue; + if (sessionId != null && context.sessionId === sessionId) this.contexts.delete(contextKey); + else if (targetId != null && context.targetId === targetId) this.contexts.delete(contextKey); } } + + private contextKey( + targetId: cdp.types.ts.Target.TargetID, + sessionId: cdp.types.ts.Target.SessionID | null, + contextId: cdp.types.ts.Runtime.ExecutionContextId, + uniqueId: string | undefined, + ): string { + return uniqueId ?? `${sessionId ?? targetId}:${contextId}`; + } +} + +async function runTopologyQueue(items: Iterable, worker: (item: T) => Promise): Promise { + const queue = [...items]; + const workers = Array.from({ length: Math.min(topologyConcurrency, queue.length) }, async () => { + for (;;) { + const item = queue.shift(); + if (item == null) return; + await worker(item); + } + }); + await Promise.all(workers); } diff --git a/js/src/server/ChromeDebuggerTransport.ts b/js/src/server/ChromeDebuggerTransport.ts new file mode 100644 index 0000000..ffefdf9 --- /dev/null +++ b/js/src/server/ChromeDebuggerTransport.ts @@ -0,0 +1,256 @@ +import type { z } from "zod"; +import type { cdp } from "../types/generated/cdp.js"; +import type { CdpCommandSchema, CdpNamedSchema } from "../types/generated/zod/helpers.js"; +import * as Target from "../types/generated/zod/Target.js"; +import type { CdpDebuggeeCommandParams, ProtocolPayload, ProtocolResult } from "../types/modcdp.js"; +import type { ServerUpstreamEventListener, ServerUpstreamTransport, TargetRoute } from "./ServerUpstreamTransport.js"; + +const target_auto_attach_params = { + autoAttach: true, + waitForDebuggerOnStart: false, + flatten: true, +} satisfies cdp.types.ts.Target.SetAutoAttachParams; + +/** + * Owns server upstream traffic sent through chrome.debugger. + * + * This class owns chrome.debugger debuggee selection, attach lifecycle, + * chrome.debugger event normalization, and target/session bookkeeping needed by + * debugger routing. It does not choose ModCDP routes, manage custom command registries, run + * middleware, publish ModCDP events, or own loopback WebSocket state. + * + * Lifecycle: + * 1. The server constructs the transport with an extension service-worker + * global scope. + * 2. `getTargets()` reads chrome.debugger targets and refreshes tab-to-target + * facts. + * 3. `attachToTarget()` attaches the debuggee for the requested target and + * enables flattened auto-attach. + * 4. chrome.debugger events update debugger-local session maps and dispatch to + * typed `on(event, listener)` subscriptions. + */ +export class ChromeDebuggerTransport implements ServerUpstreamTransport { + // JSON(debuggee) values attached in this service worker. Updated by + // attachDebuggee/onDetach; read before attach to avoid duplicate native + // chrome.debugger.attach calls. + private readonly attached_debuggees = new Set(); + + // Normalized CDP event listeners registered by AutoSessionRouter and the + // server event publisher. Updated by on; read from installEventListener. + private readonly event_listeners = new Map, Set>(); + + // Native Target.SessionID -> TargetID from debugger Target.attachedToTarget + // events. Updated by installEventListener; read when sending a command that + // already carries a child session id. + private readonly targetId_from_sessionId = new Map(); + + // chrome.tabs tab id -> CDP TargetID. Refreshed by getTargets and + // Target.attachedToTarget events; read by resolveTargetId/createTarget. + private readonly targetId_from_tabId = new Map(); + + // TargetID -> chrome.debugger.Debuggee selected for that target. Updated by + // attachToTarget; read by send so subsequent commands use the same native + // debuggee shape. + private readonly debuggee_from_targetId = new Map(); + + // True once chrome.debugger.onEvent/onDetach listeners are installed in this + // service worker. Updated by installEventListener; read by getTargets. + private event_listener_installed = false; + + /** Register a typed listener for one native CDP event schema. */ + on>( + event: Event, + listener: ( + payload: z.output, + targetId: cdp.types.ts.Target.TargetID | null, + sessionId: cdp.types.ts.Target.SessionID | null, + ) => void, + ) { + const typed_listener: ServerUpstreamEventListener = (payload, targetId, sessionId) => { + listener(event.parse(payload), targetId, sessionId); + }; + const listeners = this.event_listeners.get(event); + if (listeners) listeners.add(typed_listener); + else this.event_listeners.set(event, new Set([typed_listener])); + return { + remove: () => { + const current_listeners = this.event_listeners.get(event); + current_listeners?.delete(typed_listener); + if (current_listeners?.size === 0) this.event_listeners.delete(event); + }, + }; + } + + /** Return current browser targets through chrome.debugger target discovery. */ + async getTargets() { + const chrome_api = globalThis.chrome; + this.installEventListener(); + if (!chrome_api?.debugger?.getTargets) throw new Error("chrome.debugger is unavailable."); + const targetInfos = (await chrome_api.debugger.getTargets()).map((target) => { + if (typeof target.tabId === "number") this.targetId_from_tabId.set(target.tabId, target.id); + return { + targetId: target.id, + type: target.type, + title: target.title, + url: target.url, + attached: target.attached, + canAccessOpener: false, + ...(typeof target.tabId === "number" ? { tabId: target.tabId } : {}), + }; + }); + return Target.GetTargetsResult.parse({ targetInfos }).targetInfos; + } + + /** Resolve a target id from target id, debuggee target id, or chrome tab id. */ + async resolveTargetId(params: CdpDebuggeeCommandParams) { + if (typeof params.targetId === "string" && params.targetId.length > 0) return params.targetId; + if (params.debuggee?.targetId) return params.debuggee.targetId; + if (typeof params.tabId === "number") { + await this.getTargets(); + return this.targetId_from_tabId.get(params.tabId) ?? null; + } + return null; + } + + /** Create a new foreground tab and return the corresponding CDP target id. */ + async createTarget(url: string) { + const tab = await globalThis.chrome.tabs.create({ url, active: true }); + if (!tab.id) throw new Error(`chrome_debugger could not create a tab for ${url}.`); + await this.getTargets(); + const targetId = this.targetId_from_tabId.get(tab.id); + if (!targetId) throw new Error(`chrome_debugger could not resolve target for created tab ${tab.id}.`); + return targetId; + } + + /** Attach chrome.debugger to a target; debugger transport has no native flattened session id for the parent. */ + async attachToTarget(targetId: cdp.types.ts.Target.TargetID) { + const debuggee = await this.debuggeeForTarget(targetId); + await this.attachDebuggee(debuggee); + this.debuggee_from_targetId.set(targetId, debuggee); + return null; + } + + /** Forget a debugger child-session mapping after detach. */ + async detachFromTarget(sessionId: cdp.types.ts.Target.SessionID) { + this.targetId_from_sessionId.delete(sessionId); + } + + /** Send one typed CDP command through chrome.debugger, optionally scoped to a target route. */ + async send< + Params extends z.ZodType>, + Result extends z.ZodType>, + Name extends string, + >( + command: CdpCommandSchema, + params?: z.input, + route: TargetRoute | undefined = undefined, + ): Promise> { + if (command.id === Target.GetTargetsCommand.id) + return command.result.parse({ targetInfos: await this.getTargets() }); + if (!route) { + const debuggee = await this.defaultDebuggee(); + await this.attachDebuggee(debuggee); + return command.result.parse(await this.sendToDebugger(debuggee, command.id, command.params.parse(params))); + } + const routedTargetId = route.sessionId + ? (this.targetId_from_sessionId.get(route.sessionId) ?? route.targetId) + : route.targetId; + const debuggee = this.debuggee_from_targetId.get(routedTargetId) ?? (await this.debuggeeForTarget(routedTargetId)); + await this.attachDebuggee(debuggee); + return command.result.parse(await this.sendToDebugger(debuggee, command.id, command.params.parse(params))); + } + + private async debuggeeForTarget(targetId: cdp.types.ts.Target.TargetID) { + const targets = await this.getTargets(); + const target = targets.find((candidate) => candidate.targetId === targetId); + if (!target) throw new Error(`chrome_debugger could not resolve targetId=${targetId}.`); + const tabId = typeof target.tabId === "number" ? target.tabId : null; + return tabId == null ? { targetId } : { tabId }; + } + + private async defaultDebuggee() { + const targetId = + (await this.resolveTargetId({})) ?? (await this.getTargets()).find((target) => target.type === "page")?.targetId; + if (!targetId) return await this.debuggeeForTarget(await this.createTarget("about:blank#modcdp")); + return await this.debuggeeForTarget(targetId); + } + + private async attachDebuggee(debuggee: chrome.debugger.Debuggee) { + const key = JSON.stringify(debuggee); + if (this.attached_debuggees.has(key)) return; + const chrome_api = globalThis.chrome; + await new Promise((resolve, reject) => + chrome_api.debugger.attach(debuggee, "1.3", () => { + const error = chrome_api.runtime.lastError; + if (!error || error.message?.includes("Another debugger is already attached")) resolve(); + else reject(new Error(error.message)); + }), + ); + await new Promise((resolve, reject) => + chrome_api.debugger.sendCommand( + debuggee, + Target.SetAutoAttachCommand.id, + Target.SetAutoAttachCommand.params.parse(target_auto_attach_params), + () => { + const error = chrome_api.runtime.lastError; + if (error) reject(new Error(error.message)); + else resolve(); + }, + ), + ); + this.attached_debuggees.add(key); + } + + private installEventListener() { + const chrome_api = globalThis.chrome; + if (this.event_listener_installed || !chrome_api?.debugger?.onEvent?.addListener) return; + chrome_api.debugger.onEvent.addListener((source, method, params) => { + const payload = (params ?? {}) as ProtocolPayload; + const sourceTargetId = + source.targetId ?? + (typeof source.tabId === "number" ? (this.targetId_from_tabId.get(source.tabId) ?? null) : null); + const cdpSessionId = source.sessionId ?? null; + if (method === Target.AttachedToTargetEvent.id) { + const attached = Target.AttachedToTargetEvent.parse(payload); + if (typeof source.tabId === "number") this.targetId_from_tabId.set(source.tabId, attached.targetInfo.targetId); + this.targetId_from_sessionId.set(attached.sessionId, attached.targetInfo.targetId); + } else if (method === Target.DetachedFromTargetEvent.id) { + const detached = Target.DetachedFromTargetEvent.parse(payload); + this.targetId_from_sessionId.delete(detached.sessionId); + } + for (const [event, listeners] of this.event_listeners) { + if (event.id !== method) continue; + for (const listener of listeners) listener(payload, sourceTargetId, cdpSessionId); + } + }); + chrome_api.debugger.onDetach?.addListener?.((source) => { + this.attached_debuggees.delete(JSON.stringify(this.compactDebuggee(source))); + }); + this.event_listener_installed = true; + } + + private compactDebuggee(input: { + [Key in keyof chrome.debugger.Debuggee]?: chrome.debugger.Debuggee[Key] | null; + }): chrome.debugger.Debuggee { + return { + ...(typeof input.tabId === "number" ? { tabId: input.tabId } : {}), + ...(typeof input.targetId === "string" ? { targetId: input.targetId } : {}), + ...(typeof input.extensionId === "string" ? { extensionId: input.extensionId } : {}), + }; + } + + private sendToDebugger( + debuggee: chrome.debugger.Debuggee, + method: string, + params: Record = {}, + ): Promise { + const chrome_api = globalThis.chrome; + return new Promise((resolve, reject) => + chrome_api.debugger.sendCommand(debuggee, method, params, (result) => { + const error = chrome_api.runtime.lastError; + if (error) reject(new Error(error.message)); + else resolve(result as ProtocolResult); + }), + ); + } +} diff --git a/js/src/server/LoopbackCdpTransport.ts b/js/src/server/LoopbackCdpTransport.ts new file mode 100644 index 0000000..d10fb38 --- /dev/null +++ b/js/src/server/LoopbackCdpTransport.ts @@ -0,0 +1,467 @@ +import type { z } from "zod"; +import type { cdp } from "../types/generated/cdp.js"; +import type { CdpCommandSchema, CdpNamedSchema } from "../types/generated/zod/helpers.js"; +import * as Runtime from "../types/generated/zod/Runtime.js"; +import * as Target from "../types/generated/zod/Target.js"; +import { + CdpEventMessageSchema, + CdpResponseMessageSchema, + type CdpDebuggeeCommandParams, + type ProtocolParams, + type ProtocolPayload, + type ProtocolResult, +} from "../types/modcdp.js"; +import type { ServerUpstreamEventListener, ServerUpstreamTransport, TargetRoute } from "./ServerUpstreamTransport.js"; + +type LoopbackCdpTransportOptions = { + loopback_cdp_url: string | null; + cdp_send_timeout_ms: number; + loopback_execution_context_timeout_ms: number; + ws_connect_error_settle_timeout_ms: number; +}; + +const target_auto_attach_params = { + autoAttach: true, + waitForDebuggerOnStart: false, + flatten: true, +} satisfies cdp.types.ts.Target.SetAutoAttachParams; + +/** + * Owns server upstream traffic sent through a loopback CDP WebSocket. + * + * This class owns loopback socket lifecycle, request id tracking, pending + * request rejection, loopback event listener dispatch, loopback execution + * context waits used by discovery, and loopback endpoint verification. It does + * not choose ModCDP routes, manage custom command registries, run middleware, + * publish Stagehand/ModCDP events, or interpret topology beyond the narrow + * discovery probe needed to verify the current service worker. + * + * Lifecycle: + * 1. The server constructs the transport with current config values. + * 2. `getTargets()` or `send()` opens the loopback WebSocket and initializes + * target auto-attach/discovery once per socket. + * 3. CDP socket event messages are normalized and dispatched to typed + * `on(event, listener)` subscriptions. + * 4. Socket error/close clears loopback execution-context facts and rejects + * pending CDP requests owned by this transport. + */ +export class LoopbackCdpTransport implements ServerUpstreamTransport { + // Monotonic WebSocket request id for loopback CDP messages. Written only by + // sendToLoopback; read only when matching WebSocket responses. + private next_loopback_id = 1; + + // CDP endpoint URL -> open WebSocket. Written by loopbackWS; read by + // loopbackWS and initializeLoopbackCDP so one socket is reused per endpoint. + private readonly loopback_sockets = new Map(); + + // CDP endpoint URL -> in-flight socket open promise. Written by loopbackWS; + // read by loopbackWS to coalesce concurrent connection attempts. + private readonly loopback_socket_promises = new Map>(); + + // Native Target.SessionID -> first Runtime execution context id observed + // during loopback discovery. Updated by Runtime.executionContextCreated; + // read by waitForLoopbackExecutionContext. + private readonly loopback_session_contexts = new Map(); + + // Native Target.SessionID -> waiters for the first Runtime execution context + // on that session. Written/read by waitForLoopbackExecutionContext and + // resolved by Runtime.executionContextCreated. + private readonly loopback_context_waiters = new Map void>>(); + + // Sockets that have received Target.setAutoAttach and Target.setDiscoverTargets. + // Written/read by initializeLoopbackCDP. + private readonly initialized_loopback_sockets = new WeakSet(); + + // Loopback CDP request id -> pending promise callbacks. Written by + // sendToLoopback; resolved/rejected by WebSocket response/error/close. + private readonly loopback_pending = new Map< + number, + { resolve: (value: ProtocolResult) => void; reject: (error: Error) => void } + >(); + + // Typed upstream event schema -> subscribers. Written by on; read by + // emitLoopbackUpstreamEvent from the WebSocket message handler. + private readonly event_listeners = new Map, Set>(); + + // Current loopback CDP endpoint owned by this transport instance. Written by + // discoverLoopbackCDP while probing; read by all loopback CDP sends. + private loopback_cdp_url: string | null; + + // Request timeout for loopback CDP sends. Set at construction from server + // config; read by sendToLoopback. + private readonly cdp_send_timeout_ms: number; + + // Runtime.executionContextCreated wait timeout for discovery. Set at + // construction from server config; read by waitForLoopbackExecutionContext. + private readonly loopback_execution_context_timeout_ms: number; + + // Delay used to let websocket close details arrive after an error event. Set + // at construction from server config; read by loopbackWS. + private readonly ws_connect_error_settle_timeout_ms: number; + + constructor(options: LoopbackCdpTransportOptions) { + this.loopback_cdp_url = options.loopback_cdp_url; + this.cdp_send_timeout_ms = options.cdp_send_timeout_ms; + this.loopback_execution_context_timeout_ms = options.loopback_execution_context_timeout_ms; + this.ws_connect_error_settle_timeout_ms = options.ws_connect_error_settle_timeout_ms; + this.on(Runtime.ExecutionContextCreatedEvent, (event, _targetId, sessionId) => { + if (sessionId == null) return; + this.loopback_session_contexts.set(sessionId, event.context.id); + const waiters = this.loopback_context_waiters.get(sessionId); + if (!waiters) return; + this.loopback_context_waiters.delete(sessionId); + for (const resolve of waiters) resolve(event.context.id); + }); + } + + /** Resolve an HTTP DevTools endpoint to a WebSocket endpoint, or return an existing WebSocket URL. */ + static async resolveEndpoint(endpoint: string | null) { + if (!endpoint || /^wss?:\/\//i.test(endpoint)) return endpoint; + if (!/^https?:\/\//i.test(endpoint)) { + throw new Error(`loopback_cdp_url must be a ws://, wss://, http://, or https:// CDP endpoint, got ${endpoint}.`); + } + const { webSocketDebuggerUrl } = await fetch(`${endpoint}/json/version`).then((r) => r.json()); + if (!webSocketDebuggerUrl) throw new Error(`loopback_cdp_url HTTP discovery returned no webSocketDebuggerUrl.`); + return webSocketDebuggerUrl; + } + + /** Register a typed listener for one native CDP event schema. */ + on>( + event: Event, + listener: ( + payload: z.output, + targetId: cdp.types.ts.Target.TargetID | null, + sessionId: cdp.types.ts.Target.SessionID | null, + ) => void, + ) { + const typed_listener: ServerUpstreamEventListener = (payload, targetId, sessionId) => { + listener(event.parse(payload), targetId, sessionId); + }; + const listeners = this.event_listeners.get(event); + if (listeners) listeners.add(typed_listener); + else this.event_listeners.set(event, new Set([typed_listener])); + return { + remove: () => { + const current_listeners = this.event_listeners.get(event); + current_listeners?.delete(typed_listener); + if (current_listeners?.size === 0) this.event_listeners.delete(event); + }, + }; + } + + /** Return current browser targets through the loopback CDP endpoint. */ + async getTargets() { + if (!this.loopback_cdp_url) throw new Error(`No loopback_cdp_url configured for Target.getTargets.`); + await this.initializeLoopbackCDP(); + return (await this.send(Target.GetTargetsCommand, {})).targetInfos; + } + + /** Resolve a target id from CDP debuggee-shaped params when possible. */ + async resolveTargetId(params: CdpDebuggeeCommandParams) { + const resolved_debuggee = params.debuggee ?? this.compactDebuggee(params); + if (resolved_debuggee.targetId) return resolved_debuggee.targetId; + const chrome_api = globalThis.chrome; + let resolved_tab_url: string | null = null; + if (resolved_debuggee.tabId && chrome_api?.tabs?.get) { + const tab = await chrome_api.tabs.get(resolved_debuggee.tabId).catch((): null => null); + resolved_tab_url = tab?.url || tab?.pendingUrl || null; + } + if (!resolved_tab_url) return null; + const targetInfos = await this.getTargets(); + return targetInfos.find((target) => target.type === "page" && target.url === resolved_tab_url)?.targetId ?? null; + } + + /** Create a new page target through loopback CDP. */ + async createTarget(url: string) { + return (await this.send(Target.CreateTargetCommand, { url })).targetId; + } + + /** Attach to a target through flattened loopback CDP and return the native session id. */ + async attachToTarget(targetId: cdp.types.ts.Target.TargetID) { + return (await this.send(Target.AttachToTargetCommand, { targetId, flatten: true })).sessionId; + } + + /** Detach a native loopback CDP session. */ + async detachFromTarget(sessionId: cdp.types.ts.Target.SessionID) { + await this.send(Target.DetachFromTargetCommand, { sessionId }); + } + + /** Send one typed CDP command through loopback CDP, optionally scoped to a target route. */ + async send< + Params extends z.ZodType>, + Result extends z.ZodType>, + Name extends string, + >( + command: CdpCommandSchema, + params?: z.input, + route: TargetRoute | undefined = undefined, + ): Promise> { + await this.initializeLoopbackCDP(); + if (!route) return command.result.parse(await this.sendToLoopback(command.id, command.params.parse(params))); + if (route.sessionId == null) + throw new Error(`loopback_cdp route for ${command.id} has no session for targetId=${route.targetId}.`); + await this.sendToLoopback( + Target.SetAutoAttachCommand.id, + Target.SetAutoAttachCommand.params.parse(target_auto_attach_params), + route.sessionId, + ); + return command.result.parse(await this.sendToLoopback(command.id, command.params.parse(params), route.sessionId)); + } + + /** Verify a local loopback CDP endpoint points at this ModCDP service worker. */ + async discoverLoopbackCDP({ + browserToken, + serviceWorkerUrl, + }: { + browserToken: string | null; + serviceWorkerUrl: string; + }): Promise<{ loopback_cdp_url: string | null; verified: boolean; version?: unknown }> { + if (!browserToken) return { loopback_cdp_url: null as null, verified: false }; + + const url = "http://127.0.0.1:9222"; + const previous_loopback_url = this.loopback_cdp_url; + const fail = (version?: unknown) => { + this.loopback_cdp_url = previous_loopback_url ?? null; + return { + loopback_cdp_url: null as null, + verified: false, + ...(version ? { version } : {}), + }; + }; + try { + const version = await fetch(`${url}/json/version`).then((response) => response.ok && response.json()); + if (!version?.webSocketDebuggerUrl) return fail(); + + this.loopback_cdp_url = version.webSocketDebuggerUrl; + const { targetInfos } = Target.GetTargetsCommand.result.parse( + await this.sendToLoopback(Target.GetTargetsCommand.id, Target.GetTargetsCommand.params.parse({})), + ); + const worker = targetInfos.find((target) => target.type === "service_worker" && target.url === serviceWorkerUrl); + if (!worker) return fail(version); + + const { sessionId } = Target.AttachToTargetCommand.result.parse( + await this.sendToLoopback( + Target.AttachToTargetCommand.id, + Target.AttachToTargetCommand.params.parse({ + targetId: worker.targetId, + flatten: true, + }), + ), + ); + const execution_context_ready = this.waitForLoopbackExecutionContext(sessionId); + await this.sendToLoopback(Runtime.EnableCommand.id, Runtime.EnableCommand.params.parse({}), sessionId); + const executionContextId = await execution_context_ready; + const result = Runtime.CallFunctionOnCommand.result.parse( + await this.sendToLoopback( + Runtime.CallFunctionOnCommand.id, + Runtime.CallFunctionOnCommand.params.parse({ + functionDeclaration: `function() { return globalThis.ModCDP?.browser_token === ${JSON.stringify(browserToken)}; }`, + executionContextId, + returnByValue: true, + }), + sessionId, + ), + ); + if (result.result?.value !== true) return fail(version); + + await this.initializeLoopbackCDP(); + return { + loopback_cdp_url: this.loopback_cdp_url, + verified: true, + version, + }; + } catch { + return fail(); + } + } + + private compactDebuggee(input: { + [Key in keyof chrome.debugger.Debuggee]?: chrome.debugger.Debuggee[Key] | null; + }): chrome.debugger.Debuggee { + return { + ...(typeof input.tabId === "number" ? { tabId: input.tabId } : {}), + ...(typeof input.targetId === "string" ? { targetId: input.targetId } : {}), + ...(typeof input.extensionId === "string" ? { extensionId: input.extensionId } : {}), + }; + } + + private emitLoopbackUpstreamEvent( + method: string, + payload: ProtocolPayload, + sessionId: cdp.types.ts.Target.SessionID | null, + ) { + for (const [event, listeners] of this.event_listeners) { + if (event.id !== method) continue; + for (const listener of listeners) listener(payload, null, sessionId); + } + } + + private async loopbackWS(endpoint: string): Promise { + const existing = this.loopback_sockets.get(endpoint); + if (existing?.readyState === WebSocket.OPEN) return existing; + const pending = this.loopback_socket_promises.get(endpoint); + if (pending) return pending; + + const next_socket = this.openCDPSocket(endpoint).then((ws) => { + this.loopback_sockets.set(endpoint, ws); + this.loopback_socket_promises.delete(endpoint); + ws.addEventListener("message", (event) => { + const msg = JSON.parse(event.data); + if (!("id" in msg)) { + const cdp_event = CdpEventMessageSchema.parse(msg); + this.emitLoopbackUpstreamEvent( + cdp_event.method, + (cdp_event.params ?? {}) as ProtocolPayload, + cdp_event.sessionId ?? null, + ); + return; + } + const response = CdpResponseMessageSchema.parse(msg); + const pending = this.loopback_pending.get(response.id); + if (!pending) return; + this.loopback_pending.delete(response.id); + if (response.error) pending.reject(new Error(response.error.message)); + else pending.resolve((response.result ?? {}) as ProtocolResult); + }); + ws.addEventListener("error", () => { + if (this.loopback_sockets.get(endpoint) === ws) this.loopback_sockets.delete(endpoint); + this.loopback_session_contexts.clear(); + this.rejectLoopbackPending(new Error(`CDP socket error ${endpoint}`)); + }); + ws.addEventListener("close", (event) => { + if (this.loopback_sockets.get(endpoint) === ws) this.loopback_sockets.delete(endpoint); + this.loopback_session_contexts.clear(); + this.rejectLoopbackPending( + new Error( + `CDP socket closed ${endpoint} close.code=${event.code} close.reason=${event.reason || ""} close.wasClean=${ + event.wasClean + }`, + ), + ); + }); + return ws; + }); + this.loopback_socket_promises.set(endpoint, next_socket); + return next_socket; + } + + private async openCDPSocket(endpoint: string): Promise { + if (!/^wss?:\/\//i.test(endpoint)) { + throw new Error(`loopback_cdp_url must be a ws:// or wss:// CDP websocket URL, got ${endpoint}.`); + } + return new Promise((resolve, reject) => { + const w = new WebSocket(endpoint); + let settled = false; + let error_event: Event | null = null; + const describe = (prefix: string, closeEvent?: CloseEvent) => { + const parts = [`${prefix} ${endpoint}`, `readyState=${w.readyState}`]; + if (error_event) parts.push(`error.type=${error_event.type}`); + if (closeEvent) { + parts.push(`close.code=${closeEvent.code}`); + parts.push(`close.reason=${closeEvent.reason || ""}`); + parts.push(`close.wasClean=${closeEvent.wasClean}`); + } + return parts.join(" "); + }; + const fail = (error: Error) => { + if (settled) return; + settled = true; + reject(error); + }; + w.addEventListener( + "open", + () => { + if (settled) return; + settled = true; + resolve(w); + }, + { once: true }, + ); + w.addEventListener( + "error", + (event) => { + error_event = event; + setTimeout(() => fail(new Error(describe("CDP socket error"))), this.ws_connect_error_settle_timeout_ms); + }, + { once: true }, + ); + w.addEventListener("close", (event) => fail(new Error(describe("CDP socket closed", event))), { once: true }); + }); + } + + private async sendToLoopback(method: string, params: ProtocolParams = {}, sessionId: string | null = null) { + const endpoint = this.loopback_cdp_url; + if (!endpoint) throw new Error(`No loopback_cdp_url configured for ${method}.`); + const ws = await this.loopbackWS(endpoint); + const id = this.next_loopback_id++; + const message: { + id: number; + method: string; + params: ProtocolParams; + sessionId?: string; + } = { + id, + method, + params, + }; + if (sessionId) message.sessionId = sessionId; + ws.send(JSON.stringify(message)); + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + if (!this.loopback_pending.delete(id)) return; + reject(new Error(`${method} timed out after ${this.cdp_send_timeout_ms}ms`)); + }, this.cdp_send_timeout_ms); + this.loopback_pending.set(id, { + resolve: (value) => { + clearTimeout(timeout); + resolve(value); + }, + reject: (error) => { + clearTimeout(timeout); + reject(error); + }, + }); + }); + } + + private async initializeLoopbackCDP() { + const endpoint = this.loopback_cdp_url; + if (!endpoint) return; + const ws = await this.loopbackWS(endpoint); + if (this.initialized_loopback_sockets.has(ws)) return; + await this.sendToLoopback( + Target.SetAutoAttachCommand.id, + Target.SetAutoAttachCommand.params.parse(target_auto_attach_params), + ); + await this.sendToLoopback( + Target.SetDiscoverTargetsCommand.id, + Target.SetDiscoverTargetsCommand.params.parse({ discover: true }), + ); + this.initialized_loopback_sockets.add(ws); + } + + private waitForLoopbackExecutionContext(sessionId: string, timeout_ms = this.loopback_execution_context_timeout_ms) { + const existing = this.loopback_session_contexts.get(sessionId); + if (existing != null) return Promise.resolve(existing); + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + const waiters = this.loopback_context_waiters.get(sessionId); + waiters?.delete(complete); + if (waiters?.size === 0) this.loopback_context_waiters.delete(sessionId); + reject(new Error(`Timed out waiting for Runtime.executionContextCreated for session ${sessionId}.`)); + }, timeout_ms); + const complete = (contextId: number) => { + clearTimeout(timeout); + resolve(contextId); + }; + const waiters = this.loopback_context_waiters.get(sessionId); + if (waiters) waiters.add(complete); + else this.loopback_context_waiters.set(sessionId, new Set([complete])); + }); + } + + private rejectLoopbackPending(error: Error) { + for (const pending of this.loopback_pending.values()) pending.reject(error); + this.loopback_pending.clear(); + } +} diff --git a/js/src/server/ModCDPServer.ts b/js/src/server/ModCDPServer.ts index 28de0f7..82940e0 100644 --- a/js/src/server/ModCDPServer.ts +++ b/js/src/server/ModCDPServer.ts @@ -6,13 +6,23 @@ // same server implementation into an already-running extension service worker // when Chrome refuses Extensions.loadUnpacked. -import type { cdp } from "../types/generated/cdp.js"; import { commands as nativeCommandSchemas, events as nativeEventSchemas } from "../types/generated/zod.js"; -import { normalizeModCDPPayloadSchema } from "../types/modcdp.js"; +import * as Browser from "../types/generated/zod/Browser.js"; +import * as Runtime from "../types/generated/zod/Runtime.js"; +import { ProtocolPayloadSchema, normalizeModCDPPayloadSchema } from "../types/modcdp.js"; +import { AutoSessionRouter } from "../router/AutoSessionRouter.js"; +import { ChromeDebuggerTransport } from "./ChromeDebuggerTransport.js"; +import { LoopbackCdpTransport } from "./LoopbackCdpTransport.js"; +import { NativeHostDownstreamTransport } from "./NativeHostDownstreamTransport.js"; +import { NATSDownstreamTransport } from "./NATSDownstreamTransport.js"; +import { ReverseWSDownstreamTransport } from "./ReverseWSDownstreamTransport.js"; +import type { + ServerDownstreamTransport, + ServerDownstreamTransportName, + ServerDownstreamTransportStatus, +} from "./ServerDownstreamTransport.js"; import type { - CdpCommandMessage, CdpEventMessage, - CdpDebuggeeCommandParams, ModCDPConfigureParams, ModCDPCustomCommandRegistration, ModCDPCustomEventRegistration, @@ -27,12 +37,16 @@ import type { export const DEFAULT_CDP_SEND_TIMEOUT_MS = 10_000; export const DEFAULT_LOOPBACK_EXECUTION_CONTEXT_TIMEOUT_MS = 10_000; export const DEFAULT_WS_CONNECT_ERROR_SETTLE_TIMEOUT_MS = 250; -export const DEFAULT_REVERSE_BRIDGE_RECONNECT_INTERVAL_MS = 2_000; -export const DEFAULT_NATIVE_BRIDGE_HOST_NAME = "com.modcdp.bridge"; -export const DEFAULT_NATIVE_BRIDGE_RECONNECT_INTERVAL_MS = 2_000; -export const DEFAULT_NATS_BRIDGE_RECONNECT_INTERVAL_MS = 2_000; -export const DEFAULT_NATS_BRIDGE_SUBJECT_PREFIX = "modcdp.default"; export const DEFAULT_DOWNSTREAM_CLIENT_TIMEOUT_MS = 1_000; +export { + DEFAULT_NATIVE_BRIDGE_HOST_NAME, + DEFAULT_NATIVE_BRIDGE_RECONNECT_INTERVAL_MS, +} from "./NativeHostDownstreamTransport.js"; +export { + DEFAULT_NATS_BRIDGE_RECONNECT_INTERVAL_MS, + DEFAULT_NATS_BRIDGE_SUBJECT_PREFIX, +} from "./NATSDownstreamTransport.js"; +export { DEFAULT_REVERSE_BRIDGE_RECONNECT_INTERVAL_MS } from "./ReverseWSDownstreamTransport.js"; type MiddlewarePhase = "request" | "response" | "event"; type ProtocolCommandSchema = { @@ -42,25 +56,71 @@ type ProtocolCommandSchema = { type ProtocolEventSchema = { parse(value: unknown): ProtocolPayload; }; +type SelectedServerUpstreamTransportName = "loopback_cdp" | "chrome_debugger"; +export type ModCDPSessionHandle = { + sessionId: string | null; + readonly types: (typeof import("../types/generated/zod.js"))["types"] | null; + readonly commands: (typeof import("../types/generated/zod.js"))["commands"] | null; + readonly events: (typeof import("../types/generated/zod.js"))["events"] | null; + readonly upstream: AutoSessionRouter; + send(method: string, params?: ProtocolParams): Promise; + emit(eventName: string, payload?: ProtocolPayload): Promise; +}; +export type ModCDPServerInstance = { + __ModCDPServerVersion: number; + routes: ModCDPRoutes; + loopback_cdp_url: string | null; + browser_token: string | null; + upstream: LoopbackCdpTransport | ChromeDebuggerTransport | null; + upstream_name: SelectedServerUpstreamTransportName | null; + router: AutoSessionRouter | null; + cdp_send_timeout_ms: number; + loopback_execution_context_timeout_ms: number; + ws_connect_error_settle_timeout_ms: number; + downstream_client_timeout_ms: number; + close_browser_on_downstream_disconnect: boolean; + types: (typeof import("../types/generated/zod.js"))["types"] | null; + commands: (typeof import("../types/generated/zod.js"))["commands"] | null; + events: (typeof import("../types/generated/zod.js"))["events"] | null; + startDownstreamTransports(): Record; + stopDownstreamTransports(reason?: string): Record; + downstreamTransports(): Record; + ensureOffscreenKeepAlive(): Promise; + loadTypes(): Promise; + configure(params?: ModCDPConfigureParams): Promise; + addCustomCommand(registration: ModCDPCustomCommandRegistration): ProtocolResult; + addCustomEvent(registration: ModCDPCustomEventRegistration): ProtocolResult; + addEventListener(listener: (event: string, data: ProtocolPayload, cdpSessionId: string | null) => void): { + remove: () => boolean; + }; + addMiddleware(registration: ModCDPMiddlewareRegistration): ProtocolResult; + runMiddleware( + phase: MiddlewarePhase, + name: string, + payload: ProtocolPayload, + context?: ProtocolPayload, + ): Promise; + handleCommand(method: string, params?: ProtocolParams, cdpSessionId?: string | null): Promise; + attachToSession(cdpSessionId?: string | null): ModCDPSessionHandle; + emit(eventName: string, payload?: ProtocolPayload, cdpSessionId?: string | null): Promise; + discoverLoopbackCDP(): Promise<{ + loopback_cdp_url: string | null; + verified: boolean; + version?: unknown; + }>; +}; type ModCDPGlobalScope = typeof globalThis & Record & { - ModCDP?: { - __ModCDPServerVersion?: number; - addCustomEvent?: unknown; - handleCommand?: unknown; - }; + ModCDP?: ModCDPServerInstance; }; -export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis as ModCDPGlobalScope) { +export function installModCDPServer( + globalScope: ModCDPGlobalScope = globalThis as ModCDPGlobalScope, +): ModCDPServerInstance { const MODCDP_SERVER_VERSION = 2; const DEFAULT_CDP_SEND_TIMEOUT_MS = 10_000; const DEFAULT_LOOPBACK_EXECUTION_CONTEXT_TIMEOUT_MS = 10_000; const DEFAULT_WS_CONNECT_ERROR_SETTLE_TIMEOUT_MS = 250; - const DEFAULT_REVERSE_BRIDGE_RECONNECT_INTERVAL_MS = 2_000; - const DEFAULT_NATIVE_BRIDGE_HOST_NAME = "com.modcdp.bridge"; - const DEFAULT_NATIVE_BRIDGE_RECONNECT_INTERVAL_MS = 2_000; - const DEFAULT_NATS_BRIDGE_RECONNECT_INTERVAL_MS = 2_000; - const DEFAULT_NATS_BRIDGE_SUBJECT_PREFIX = "modcdp.default"; if ( globalScope.ModCDP?.__ModCDPServerVersion === MODCDP_SERVER_VERSION && globalScope.ModCDP?.handleCommand && @@ -80,15 +140,14 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis cdpSessionId?: string | null; }) => JSON.stringify({ event, data, cdpSessionId }); - const commandHandlers = new Map(); - const eventBindings = new Map(); - const eventListeners = new Set<(event: string, data: ProtocolPayload, cdpSessionId: string | null) => void>(); + const command_handlers = new Map(); + const event_bindings = new Map(); + const event_listeners = new Set<(event: string, data: ProtocolPayload, cdpSessionId: string | null) => void>(); const middlewares: Record = { request: [], response: [], event: [], }; - const attachedDebuggees = new Set(); let runtime_types_promise: Promise | null = null; let downstream_client_registered = false; let downstream_client_lease: { @@ -119,7 +178,8 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis const expired = clearDownstreamClientLease(); if (!expired) return; if (ModCDPServer.close_browser_on_downstream_disconnect !== true) return; - void ModCDPServer.sendLoopback("Browser.close", {}, null).catch(() => {}); + if (!ModCDPServer.upstream) setupServerUpstreamTransport(); + void ModCDPServer.upstream?.send(Browser.CloseCommand, {}).catch(() => {}); }, timeout_ms); downstream_client_lease = { cdpSessionId, @@ -158,142 +218,77 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis event: { name: eventName, payload }, }); if (payload === undefined) return { event: eventName, emitted: false, reason: "middleware_dropped" }; - const event = registryMatch(eventBindings, eventName); + const event = registryMatch(event_bindings, eventName); payload = eventPayloadSchema(eventName, event)?.parse(payload) ?? payload; - for (const listener of eventListeners) { + for (const listener of event_listeners) { try { listener(eventName, payload, cdpSessionId); } catch (error) { console.error("[ModCDPServer] event listener failed", error); } } - let emittedThroughReverseBridge = false; - if (reverseBridgeSocket?.readyState === WebSocket.OPEN) { - const message: CdpEventMessage = { - method: eventName, - params: (payload ?? {}) as CdpEventMessage["params"], - }; - if (cdpSessionId) message.sessionId = cdpSessionId; - reverseBridgeSocket.send(JSON.stringify(message)); - emittedThroughReverseBridge = true; - } - let emittedThroughNativeBridge = false; - if (nativeBridgePort) { - const message: CdpEventMessage = { - method: eventName, - params: (payload ?? {}) as CdpEventMessage["params"], - }; - if (cdpSessionId) message.sessionId = cdpSessionId; - nativeBridgePort.postMessage(message); - emittedThroughNativeBridge = true; - } - let emittedThroughNatsBridge = false; - if (nats_bridge_socket?.readyState === WebSocket.OPEN) { - const message: CdpEventMessage = { - method: eventName, - params: (payload ?? {}) as CdpEventMessage["params"], - }; - if (cdpSessionId) message.sessionId = cdpSessionId; - publishNats(`${nats_bridge_subject_prefix}.browser_to_client`, { - type: "modcdp.nats.message", - message, - }); - emittedThroughNatsBridge = true; - } - - const isCustomEvent = registryMatch(eventBindings, eventName) != null; - let emittedThroughBinding = false; - if (isCustomEvent) { - const customBinding = globalScope[CUSTOM_EVENT_BINDING_NAME]; - if (typeof customBinding === "function") { - customBinding( + const message: CdpEventMessage = { + method: eventName, + params: (payload ?? {}) as CdpEventMessage["params"], + }; + if (cdpSessionId) message.sessionId = cdpSessionId; + const emitted_through_downstream = [...downstream_transports.values()].some((transport) => transport.emit(message)); + + const is_custom_event = registryMatch(event_bindings, eventName) != null; + let emitted_through_binding = false; + if (is_custom_event) { + const custom_binding = globalScope[CUSTOM_EVENT_BINDING_NAME]; + if (typeof custom_binding === "function") { + custom_binding( encodeBindingPayload({ event: eventName, data: payload, cdpSessionId, }), ); - emittedThroughBinding = true; + emitted_through_binding = true; } } else { - const mirrorBinding = globalScope[UPSTREAM_EVENT_BINDING_NAME]; - if (typeof mirrorBinding === "function") { - mirrorBinding( + const mirror_binding = globalScope[UPSTREAM_EVENT_BINDING_NAME]; + if (typeof mirror_binding === "function") { + mirror_binding( encodeBindingPayload({ event: eventName, data: payload, cdpSessionId, }), ); - emittedThroughBinding = true; + emitted_through_binding = true; } } - return emittedThroughBinding || - emittedThroughReverseBridge || - emittedThroughNativeBridge || - emittedThroughNatsBridge + return emitted_through_binding || emitted_through_downstream ? { event: eventName, emitted: true } : { event: eventName, emitted: false, reason: "binding_not_installed" }; } - const targetAutoAttachParams = { - autoAttach: true, - waitForDebuggerOnStart: false, - flatten: true, - } satisfies cdp.types.ts.Target.SetAutoAttachParams; - - const defaultRoutes = { + const default_routes = { "Mod.*": "service_worker", "Custom.*": "service_worker", "*.*": "auto", } satisfies ModCDPRoutes; - - const browserLevelDomains = new Set(["Browser", "Target", "SystemInfo"]); - - let nextLoopbackId = 1; - const loopbackSockets = new Map(); - const loopbackSocketPromises = new Map>(); - const loopbackTargetSessions = new Map(); - const loopbackSessionTargets = new Map(); - const loopbackSessionContexts = new Map(); - const loopbackContextWaiters = new Map void>>(); - const initializedLoopbackSockets = new WeakSet(); - const loopbackPending = new Map< - number, - { resolve: (value: ProtocolResult) => void; reject: (error: Error) => void } - >(); - let reverseBridgeSocket: WebSocket | null = null; - let reverseBridgeUrl: string | null = null; - let reverseBridgeReconnectIntervalMs = DEFAULT_REVERSE_BRIDGE_RECONNECT_INTERVAL_MS; - let reverseBridgeReconnectTimer: ReturnType | null = null; - let nativeBridgePort: chrome.runtime.Port | null = null; - let nativeBridgeHostName: string | null = null; - let nativeBridgeReconnectIntervalMs = DEFAULT_NATIVE_BRIDGE_RECONNECT_INTERVAL_MS; - let nativeBridgeReconnectTimer: ReturnType | null = null; - let nats_bridge_socket: WebSocket | null = null; - let nats_bridge_url: string | null = null; - let nats_bridge_subject_prefix = DEFAULT_NATS_BRIDGE_SUBJECT_PREFIX; - let nats_bridge_reconnect_interval_ms = DEFAULT_NATS_BRIDGE_RECONNECT_INTERVAL_MS; - let nats_bridge_reconnect_timer: ReturnType | null = null; - let nats_bridge_buffer = ""; - let selfDebuggee: chrome.debugger.Debuggee | null = null; - const offscreenKeepAlivePortName = "ModCDPOffscreenKeepAlive"; - const offscreenKeepAlivePath = "offscreen/keepalive.html"; - let creatingOffscreenKeepAlive: Promise | null = null; - let offscreenKeepAlivePort: chrome.runtime.Port | null = null; + let downstream_transports: Map; + const offscreen_keep_alive_port_name = "ModCDPOffscreenKeepAlive"; + const offscreen_keep_alive_path = "offscreen/keepalive.html"; + let creating_offscreen_keep_alive: Promise | null = null; + let offscreen_keep_alive_port: chrome.runtime.Port | null = null; function registryMatch(registry: Map, name: string): T | null { const exact = registry.get(name); if (exact) return exact; let match: T | null = null; - let matchPrefixLength = -1; + let match_prefix_length = -1; for (const [pattern, value] of registry) { if (!pattern.endsWith(".*")) continue; const prefix = pattern.slice(0, -1); - if (!name.startsWith(prefix) || prefix.length <= matchPrefixLength) continue; + if (!name.startsWith(prefix) || prefix.length <= match_prefix_length) continue; match = value; - matchPrefixLength = prefix.length; + match_prefix_length = prefix.length; } return match; } @@ -335,442 +330,9 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis return error instanceof Error ? error.message : String(error); } - function compactDebuggee(input: { - [Key in keyof chrome.debugger.Debuggee]?: chrome.debugger.Debuggee[Key] | null; - }): chrome.debugger.Debuggee { - return { - ...(typeof input.tabId === "number" ? { tabId: input.tabId } : {}), - ...(typeof input.targetId === "string" ? { targetId: input.targetId } : {}), - ...(typeof input.extensionId === "string" ? { extensionId: input.extensionId } : {}), - }; - } - - async function resolveCDPEndpoint(endpoint: string | null) { - if (!endpoint || /^wss?:\/\//i.test(endpoint)) return endpoint; - if (!/^https?:\/\//i.test(endpoint)) { - throw new Error(`loopback_cdp_url must be a ws://, wss://, http://, or https:// CDP endpoint, got ${endpoint}.`); - } - const { webSocketDebuggerUrl } = await fetch(`${endpoint}/json/version`).then((r) => r.json()); - if (!webSocketDebuggerUrl) throw new Error(`loopback_cdp_url HTTP discovery returned no webSocketDebuggerUrl.`); - return webSocketDebuggerUrl; - } - - async function openCDPSocket(endpoint: string): Promise { - if (!/^wss?:\/\//i.test(endpoint)) { - throw new Error(`loopback_cdp_url must be a ws:// or wss:// CDP websocket URL, got ${endpoint}.`); - } - return new Promise((resolve, reject) => { - const w = new WebSocket(endpoint); - let settled = false; - let errorEvent: Event | null = null; - const describe = (prefix: string, closeEvent?: CloseEvent) => { - const parts = [`${prefix} ${endpoint}`, `readyState=${w.readyState}`]; - if (errorEvent) parts.push(`error.type=${errorEvent.type}`); - if (closeEvent) { - parts.push(`close.code=${closeEvent.code}`); - parts.push(`close.reason=${closeEvent.reason || ""}`); - parts.push(`close.wasClean=${closeEvent.wasClean}`); - } - return parts.join(" "); - }; - const fail = (error: Error) => { - if (settled) return; - settled = true; - reject(error); - }; - w.addEventListener( - "open", - () => { - if (settled) return; - settled = true; - resolve(w); - }, - { once: true }, - ); - w.addEventListener( - "error", - (event) => { - errorEvent = event; - setTimeout( - () => fail(new Error(describe("CDP socket error"))), - ModCDPServer.ws_connect_error_settle_timeout_ms, - ); - }, - { once: true }, - ); - w.addEventListener("close", (event) => fail(new Error(describe("CDP socket closed", event))), { once: true }); - }); - } - - function startOffscreenKeepAlive() { - void ensureOffscreenKeepAlive().catch(() => {}); - } - - function rejectLoopbackPending(error: Error) { - for (const pending of loopbackPending.values()) pending.reject(error); - loopbackPending.clear(); - } - - function scheduleReverseBridgeReconnect(delayMs: number) { - if (!reverseBridgeUrl) return; - if (reverseBridgeReconnectTimer) return; - reverseBridgeReconnectTimer = setTimeout(() => { - reverseBridgeReconnectTimer = null; - void connectReverseBridge(reverseBridgeUrl).catch(() => {}); - }, delayMs); - } - - function stopReverseBridge(reason = "stopped") { - const upstream_reversews_url = reverseBridgeUrl; - reverseBridgeUrl = null; - if (reverseBridgeReconnectTimer) { - clearTimeout(reverseBridgeReconnectTimer); - reverseBridgeReconnectTimer = null; - } - const socket = reverseBridgeSocket; - reverseBridgeSocket = null; - if (socket?.readyState === WebSocket.OPEN || socket?.readyState === WebSocket.CONNECTING) { - socket.close(1000, reason); - } - return { upstream_reversews_url, stopped: true, reason }; - } - - function scheduleNativeBridgeReconnect(delayMs: number) { - if (!nativeBridgeHostName) return; - if (nativeBridgeReconnectTimer) return; - nativeBridgeReconnectTimer = setTimeout(() => { - nativeBridgeReconnectTimer = null; - connectNativeBridge(nativeBridgeHostName); - }, delayMs); - } - - function scheduleNatsBridgeReconnect(delayMs: number) { - if (!nats_bridge_url) return; - if (nats_bridge_reconnect_timer) return; - nats_bridge_reconnect_timer = setTimeout(() => { - nats_bridge_reconnect_timer = null; - void connectNatsBridge(nats_bridge_url).catch(() => {}); - }, delayMs); - } - - async function handleReverseBridgeMessage(ws: WebSocket, data: unknown) { - let message: CdpCommandMessage; - try { - const parsed = JSON.parse(typeof data === "string" ? data : String(data)); - if (typeof parsed?.id !== "number" || typeof parsed?.method !== "string") return; - message = parsed as CdpCommandMessage; - } catch { - return; - } - - try { - const result = await ModCDPServer.handleCommand(message.method, message.params ?? {}, message.sessionId ?? null); - ws.send(JSON.stringify({ id: message.id, result })); - } catch (error) { - ws.send( - JSON.stringify({ - id: message.id, - error: { - code: -32000, - message: errorMessage(error), - }, - }), - ); - } - } - - async function handleNativeBridgeMessage(port: chrome.runtime.Port, data: unknown) { - let message: CdpCommandMessage; - try { - if ( - typeof (data as CdpCommandMessage)?.id !== "number" || - typeof (data as CdpCommandMessage)?.method !== "string" - ) - return; - message = data as CdpCommandMessage; - } catch { - return; - } - - try { - const result = await ModCDPServer.handleCommand(message.method, message.params ?? {}, message.sessionId ?? null); - port.postMessage({ id: message.id, result }); - } catch (error) { - port.postMessage({ - id: message.id, - error: { - code: -32000, - message: errorMessage(error), - }, - }); - } - } - - async function handleNatsBridgePayload(payload: string) { - let parsed: unknown; - try { - parsed = JSON.parse(payload); - } catch { - return; - } - const record = parsed && typeof parsed === "object" ? (parsed as Record) : null; - if (record?.type === "modcdp.nats.hello") { - publishNats(`${nats_bridge_subject_prefix}.browser_to_client`, { - type: "modcdp.nats.hello", - role: "extension-service-worker", - version: 1, - extension_id: globalScope.chrome?.runtime?.id ?? null, - }); - return; - } - const candidate = record?.type === "modcdp.nats.message" ? record.message : parsed; - if ( - !candidate || - typeof candidate !== "object" || - typeof (candidate as CdpCommandMessage).id !== "number" || - typeof (candidate as CdpCommandMessage).method !== "string" - ) - return; - const message = candidate as CdpCommandMessage; - try { - const result = await ModCDPServer.handleCommand(message.method, message.params ?? {}, message.sessionId ?? null); - publishNats(`${nats_bridge_subject_prefix}.browser_to_client`, { - type: "modcdp.nats.message", - message: { id: message.id, result }, - }); - } catch (error) { - publishNats(`${nats_bridge_subject_prefix}.browser_to_client`, { - type: "modcdp.nats.message", - message: { - id: message.id, - error: { - code: -32000, - message: errorMessage(error), - }, - }, - }); - } - } - - async function connectReverseBridge(endpoint: string) { - if ( - reverseBridgeSocket?.readyState === WebSocket.OPEN || - reverseBridgeSocket?.readyState === WebSocket.CONNECTING - ) { - return { - upstream_reversews_url: endpoint, - connected: reverseBridgeSocket.readyState === WebSocket.OPEN, - }; - } - - const ws = new WebSocket(endpoint); - reverseBridgeSocket = ws; - ws.addEventListener("open", () => { - startOffscreenKeepAlive(); - ws.send( - JSON.stringify({ - type: "modcdp.reverse.hello", - role: "extension-service-worker", - version: 1, - extension_id: globalScope.chrome?.runtime?.id ?? null, - }), - ); - }); - ws.addEventListener("message", (event) => { - void handleReverseBridgeMessage(ws, event.data); - }); - ws.addEventListener("error", () => { - if (reverseBridgeSocket === ws) reverseBridgeSocket = null; - scheduleReverseBridgeReconnect(reverseBridgeReconnectIntervalMs); - }); - ws.addEventListener("close", () => { - if (reverseBridgeSocket === ws) reverseBridgeSocket = null; - scheduleReverseBridgeReconnect(reverseBridgeReconnectIntervalMs); - }); - return { upstream_reversews_url: endpoint, connected: false }; - } - - function connectNativeBridge(hostName: string) { - const chromeApi = globalScope.chrome; - if (!chromeApi?.runtime?.connectNative) { - scheduleNativeBridgeReconnect(nativeBridgeReconnectIntervalMs); - return { - upstream_nativemessaging_host_name: hostName, - connected: false, - reason: "native_messaging_unavailable", - }; - } - if (nativeBridgePort) return { upstream_nativemessaging_host_name: hostName, connected: true }; - try { - ModCDPServer.native_bridge_attempts += 1; - ModCDPServer.native_bridge_last_error = null; - const port = chromeApi.runtime.connectNative(hostName); - nativeBridgePort = port; - ModCDPServer.native_bridge_connected = true; - startOffscreenKeepAlive(); - port.postMessage({ - type: "modcdp.native.hello", - role: "extension-service-worker", - version: 1, - extension_id: globalScope.chrome?.runtime?.id ?? null, - }); - port.onMessage.addListener((message) => { - void handleNativeBridgeMessage(port, message); - }); - port.onDisconnect.addListener(() => { - if (nativeBridgePort === port) nativeBridgePort = null; - ModCDPServer.native_bridge_connected = false; - ModCDPServer.native_bridge_last_error = - chromeApi.runtime.lastError?.message ?? "Native messaging port disconnected."; - scheduleNativeBridgeReconnect(nativeBridgeReconnectIntervalMs); - }); - return { upstream_nativemessaging_host_name: hostName, connected: true }; - } catch (error) { - nativeBridgePort = null; - ModCDPServer.native_bridge_connected = false; - ModCDPServer.native_bridge_last_error = errorMessage(error); - scheduleNativeBridgeReconnect(nativeBridgeReconnectIntervalMs); - return { - upstream_nativemessaging_host_name: hostName, - connected: false, - reason: errorMessage(error), - }; - } - } - - async function connectNatsBridge(endpoint: string) { - if (!/^wss?:\/\//i.test(endpoint)) { - throw new Error(`nats bridge endpoint must be a ws:// or wss:// URL for extension transport, got ${endpoint}.`); - } - if (nats_bridge_socket?.readyState === WebSocket.OPEN || nats_bridge_socket?.readyState === WebSocket.CONNECTING) { - return { - upstream_nats_url: endpoint, - upstream_nats_subject_prefix: nats_bridge_subject_prefix, - connected: nats_bridge_socket.readyState === WebSocket.OPEN, - }; - } - const ws = new WebSocket(endpoint); - nats_bridge_socket = ws; - nats_bridge_buffer = ""; - ws.addEventListener("open", () => { - startOffscreenKeepAlive(); - writeNats(`CONNECT ${JSON.stringify(natsConnectOptions())}\r\nPING\r\n`); - writeNats(`SUB ${nats_bridge_subject_prefix}.client_to_browser 1\r\n`); - publishNats(`${nats_bridge_subject_prefix}.browser_to_client`, { - type: "modcdp.nats.hello", - role: "extension-service-worker", - version: 1, - extension_id: globalScope.chrome?.runtime?.id ?? null, - }); - }); - ws.addEventListener("message", (event) => { - void readNatsWebSocketData(event.data); - }); - ws.addEventListener("error", () => { - if (nats_bridge_socket === ws) nats_bridge_socket = null; - scheduleNatsBridgeReconnect(nats_bridge_reconnect_interval_ms); - }); - ws.addEventListener("close", () => { - if (nats_bridge_socket === ws) nats_bridge_socket = null; - scheduleNatsBridgeReconnect(nats_bridge_reconnect_interval_ms); - }); - return { - upstream_nats_url: endpoint, - upstream_nats_subject_prefix: nats_bridge_subject_prefix, - connected: false, - }; - } - - function writeNats(data: string) { - if (nats_bridge_socket?.readyState === WebSocket.OPEN) nats_bridge_socket.send(data); - } - - function publishNats(subject: string, message: unknown) { - const body = JSON.stringify(message); - writeNats(`PUB ${subject} ${new TextEncoder().encode(body).byteLength}\r\n${body}\r\n`); - } - - async function readNatsWebSocketData(data: unknown) { - if (typeof data === "string") nats_bridge_buffer += data; - else if (data instanceof ArrayBuffer) nats_bridge_buffer += new TextDecoder().decode(data); - else if (ArrayBuffer.isView(data)) nats_bridge_buffer += new TextDecoder().decode(data); - else if (typeof Blob !== "undefined" && data instanceof Blob) nats_bridge_buffer += await data.text(); - else return; - nats_bridge_buffer = consumeNatsProtocol(nats_bridge_buffer); - } - - function consumeNatsProtocol(buffer: string) { - for (;;) { - const lineEnd = buffer.indexOf("\r\n"); - if (lineEnd < 0) return buffer; - const line = buffer.slice(0, lineEnd); - const upper = line.toUpperCase(); - if (upper.startsWith("MSG ")) { - const parts = line.split(/\s+/); - const size = Number(parts[parts.length - 1]); - const payloadStart = lineEnd + 2; - const payloadEnd = payloadStart + size; - if (!Number.isInteger(size) || buffer.length < payloadEnd + 2) return buffer; - const payload = buffer.slice(payloadStart, payloadEnd); - buffer = buffer.slice(payloadEnd + 2); - void handleNatsBridgePayload(payload); - continue; - } - buffer = buffer.slice(lineEnd + 2); - if (upper === "PING") writeNats("PONG\r\n"); - } - } - - function natsConnectOptions() { - return { - verbose: false, - pedantic: false, - lang: "modcdp-extension", - version: "1", - protocol: 1, - }; - } - - function debuggerSendCommand( - debuggee: chrome.debugger.Debuggee, - method: string, - params: Record = {}, - ): Promise { - const chromeApi = globalScope.chrome; - return new Promise((resolve, reject) => - chromeApi.debugger.sendCommand(debuggee, method, params, (result) => { - const error = chromeApi.runtime.lastError; - if (error) reject(new Error(error.message)); - else resolve(result as ProtocolResult); - }), - ); - } - - async function getSelfDebuggee(): Promise { - if (selfDebuggee) return selfDebuggee; - const chromeApi = globalScope.chrome; - if (!chromeApi?.debugger?.getTargets || !chromeApi?.debugger?.attach) { - throw new Error("chrome.debugger is unavailable for reverse expression evaluation."); - } - const serviceWorkerUrl = currentServiceWorkerUrl(); - const targets = await chromeApi.debugger.getTargets(); - const target = targets.find((candidate) => candidate.url === serviceWorkerUrl); - if (!target?.id) throw new Error(`Could not find ModCDP service worker debugger target ${serviceWorkerUrl}.`); - const debuggee = { targetId: target.id }; - await new Promise((resolve, reject) => - chromeApi.debugger.attach(debuggee, "1.3", () => { - const error = chromeApi.runtime.lastError; - if (!error || error.message?.includes("Another debugger is already attached")) resolve(); - else reject(new Error(error.message)); - }), - ); - selfDebuggee = debuggee; - return debuggee; - } - function currentServiceWorkerUrl() { - const chromeApi = globalScope.chrome; - const manifest = chromeApi?.runtime?.getManifest?.(); + const chrome_api = globalScope.chrome; + const manifest = chrome_api?.runtime?.getManifest?.(); const service_worker = manifest && typeof manifest === "object" && "background" in manifest ? (manifest.background as { service_worker?: unknown } | undefined)?.service_worker @@ -779,19 +341,102 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis typeof service_worker === "string" && service_worker.length > 0 ? service_worker.replace(/^\//, "") : "modcdp/service_worker.js"; - return chromeApi.runtime.getURL(service_worker_path); + return chrome_api.runtime.getURL(service_worker_path); + } + + let active_server_upstream_subscription: { remove: () => void } | null = null; + + function setupServerUpstreamTransport(): LoopbackCdpTransport | ChromeDebuggerTransport; + function setupServerUpstreamTransport(name: "loopback_cdp"): LoopbackCdpTransport; + function setupServerUpstreamTransport(name: "chrome_debugger"): ChromeDebuggerTransport; + function setupServerUpstreamTransport( + name?: SelectedServerUpstreamTransportName, + ): LoopbackCdpTransport | ChromeDebuggerTransport; + function setupServerUpstreamTransport( + name?: SelectedServerUpstreamTransportName, + ): LoopbackCdpTransport | ChromeDebuggerTransport { + const selected_name = + name ?? ModCDPServer.upstream_name ?? (ModCDPServer.loopback_cdp_url ? "loopback_cdp" : "chrome_debugger"); + if (ModCDPServer.upstream_name === selected_name && ModCDPServer.upstream && ModCDPServer.router) { + return ModCDPServer.upstream; + } + active_server_upstream_subscription?.remove(); + const transport = + selected_name === "loopback_cdp" + ? new LoopbackCdpTransport({ + loopback_cdp_url: ModCDPServer.loopback_cdp_url, + cdp_send_timeout_ms: ModCDPServer.cdp_send_timeout_ms, + loopback_execution_context_timeout_ms: ModCDPServer.loopback_execution_context_timeout_ms, + ws_connect_error_settle_timeout_ms: ModCDPServer.ws_connect_error_settle_timeout_ms, + }) + : new ChromeDebuggerTransport(); + ModCDPServer.upstream_name = selected_name; + ModCDPServer.upstream = transport; + if (!ModCDPServer.upstream) throw new Error("ModCDP server upstream transport is not initialized."); + ModCDPServer.router = new AutoSessionRouter({ + upstream: ModCDPServer.upstream, + loopback_execution_context_timeout_ms: ModCDPServer.loopback_execution_context_timeout_ms, + }); + const auto_router_subscription = ModCDPServer.router.listen(); + const publish_subscriptions = Object.values(nativeEventSchemas).map((event) => + transport.on(event, (payload, _targetId, cdpSessionId) => { + void publishEvent(event.id, ProtocolPayloadSchema.parse(payload), cdpSessionId).catch((error) => + console.error("[ModCDPServer] upstream event listener failed", error), + ); + }), + ); + active_server_upstream_subscription = { + remove: () => { + auto_router_subscription?.remove(); + for (const subscription of publish_subscriptions) subscription.remove(); + }, + }; + return transport; } - async function evaluateInSelf(expression: string): Promise { - const debuggee = await getSelfDebuggee(); - const result = (await debuggerSendCommand(debuggee, "Runtime.evaluate", { - expression, - awaitPromise: true, - returnByValue: true, - })) as cdp.types.ts.Runtime.EvaluateResult; + async function evaluateInServiceWorker(expression: string): Promise { + if (!ModCDPServer.upstream) setupServerUpstreamTransport(); + if (!ModCDPServer.upstream) throw new Error("ModCDP server upstream transport is not initialized."); + if (!ModCDPServer.router) throw new Error("ModCDP autorouter is not initialized."); + + const service_worker_url = currentServiceWorkerUrl(); + const service_worker_target = (await ModCDPServer.upstream.getTargets()).find( + (target) => target.url === service_worker_url, + ); + if (!service_worker_target) { + throw new Error(`Could not find ModCDP service worker target ${service_worker_url}.`); + } + const route = await ModCDPServer.router.ensureRouteForTarget(service_worker_target.targetId); + + /* + * MV3 extension service workers cannot opt into arbitrary string eval with + * content_security_policy; Chrome rejects `eval`/`new Function` in extension + * service-worker JavaScript even when the manifest tries to loosen CSP. The + * user-facing Mod.evaluate/custom-command/middleware APIs intentionally take + * JavaScript source strings, so direct in-process execution is not viable. + * + * The workaround is to execute the source as a DevTools Protocol operation + * against this same service-worker target. CDP Runtime.evaluate runs in the + * browser's inspector/evaluation path instead of through service-worker JS + * string eval, so it can evaluate the supplied expression while still seeing + * `globalThis.ModCDP`, `chrome`, and the service-worker global scope. This + * must go through the currently configured server upstream transport + * (`loopback_cdp` or `chrome_debugger`) via the generic upstream interface; + * downstream transports and ModCDPServer must not hardcode either physical + * upstream implementation here. + */ + const result = await ModCDPServer.upstream.send( + Runtime.EvaluateCommand, + { + expression, + awaitPromise: true, + returnByValue: true, + }, + route, + ); if (result.exceptionDetails) { - const ex = result.exceptionDetails; - throw new Error(ex.exception?.description || ex.text || "Runtime evaluation failed"); + const exception = result.exceptionDetails; + throw new Error(exception.exception?.description || exception.text || "Runtime evaluation failed"); } return (result.result?.value ?? {}) as ProtocolResult; } @@ -807,7 +452,7 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis cdpSessionId?: string | null; method?: string | null; }): Promise { - return evaluateInSelf(` + return evaluateInServiceWorker(` (async () => { const params = ${JSON.stringify(params ?? {})}; const method = ${JSON.stringify(method)}; @@ -820,223 +465,45 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis `); } - async function loopbackWS(endpoint: string): Promise { - const existing = loopbackSockets.get(endpoint); - if (existing?.readyState === WebSocket.OPEN) return existing; - const pending = loopbackSocketPromises.get(endpoint); - if (pending) return pending; - - const nextSocket = openCDPSocket(endpoint).then((ws) => { - loopbackSockets.set(endpoint, ws); - loopbackSocketPromises.delete(endpoint); - ws.addEventListener("message", (event) => { - const msg = JSON.parse(event.data); - const id = typeof msg.id === "number" ? msg.id : null; - if (id == null) { - const method = typeof msg.method === "string" ? msg.method : null; - if (!method) return; - const payload = - msg.params && typeof msg.params === "object" && !Array.isArray(msg.params) - ? (msg.params as ProtocolPayload) - : {}; - const cdpSessionId = typeof msg.sessionId === "string" ? msg.sessionId : null; - const payloadRecord = payload as Record; - const targetInfo = - payloadRecord.targetInfo && - typeof payloadRecord.targetInfo === "object" && - !Array.isArray(payloadRecord.targetInfo) - ? (payloadRecord.targetInfo as Record) - : null; - const attachedSessionId = typeof payloadRecord.sessionId === "string" ? payloadRecord.sessionId : null; - const attachedTargetId = typeof targetInfo?.targetId === "string" ? targetInfo.targetId : null; - if (method === "Target.attachedToTarget" && attachedSessionId != null && attachedTargetId != null) { - loopbackTargetSessions.set(attachedTargetId, attachedSessionId); - loopbackSessionTargets.set(attachedSessionId, attachedTargetId); - } else if (method === "Target.detachedFromTarget") { - const detachedSessionId = - typeof payloadRecord.sessionId === "string" ? payloadRecord.sessionId : cdpSessionId; - const detachedTargetId = - typeof payloadRecord.targetId === "string" - ? payloadRecord.targetId - : detachedSessionId == null - ? null - : (loopbackSessionTargets.get(detachedSessionId) ?? null); - if (detachedTargetId != null) loopbackTargetSessions.delete(detachedTargetId); - if (detachedSessionId != null) loopbackSessionTargets.delete(detachedSessionId); - if (detachedSessionId != null) loopbackSessionContexts.delete(detachedSessionId); - } else if (method === "Runtime.executionContextCreated" && cdpSessionId != null) { - const context = payloadRecord.context; - const contextId = - context && typeof context === "object" && "id" in context && typeof context.id === "number" - ? context.id - : null; - if (contextId != null) { - loopbackSessionContexts.set(cdpSessionId, contextId); - const waiters = loopbackContextWaiters.get(cdpSessionId); - if (waiters) { - loopbackContextWaiters.delete(cdpSessionId); - for (const resolve of waiters) resolve(contextId); - } - } - } - void (async () => { - if ( - method === "Target.attachedToTarget" && - attachedSessionId != null && - (targetInfo?.type === "page" || targetInfo?.type === "iframe") - ) { - await ModCDPServer.handleCommand("Page.enable", {}, attachedSessionId).catch((error) => - console.error("[ModCDPServer] Page.enable failed for attached target", error), - ); - await ModCDPServer.handleCommand( - "Page.setLifecycleEventsEnabled", - { enabled: true }, - attachedSessionId, - ).catch((error) => - console.error("[ModCDPServer] Page.setLifecycleEventsEnabled failed for attached target", error), - ); - } - await publishEvent(method, payload, cdpSessionId); - })().catch((error) => console.error("[ModCDPServer] loopback event listener failed", error)); - return; - } - const pending = loopbackPending.get(id); - if (!pending) return; - loopbackPending.delete(id); - if (msg.error) pending.reject(new Error(msg.error.message)); - else pending.resolve(msg.result || {}); - }); - ws.addEventListener("error", () => { - if (loopbackSockets.get(endpoint) === ws) loopbackSockets.delete(endpoint); - loopbackTargetSessions.clear(); - loopbackSessionTargets.clear(); - loopbackSessionContexts.clear(); - rejectLoopbackPending(new Error(`CDP socket error ${endpoint}`)); - }); - ws.addEventListener("close", (event) => { - if (loopbackSockets.get(endpoint) === ws) loopbackSockets.delete(endpoint); - loopbackTargetSessions.clear(); - loopbackSessionTargets.clear(); - loopbackSessionContexts.clear(); - rejectLoopbackPending( - new Error( - `CDP socket closed ${endpoint} close.code=${event.code} close.reason=${event.reason || ""} close.wasClean=${ - event.wasClean - }`, - ), - ); - }); - return ws; - }); - loopbackSocketPromises.set(endpoint, nextSocket); - return nextSocket; - } - - async function callLoopbackWS(method: string, params: ProtocolParams = {}, sessionId: string | null = null) { - if (!ModCDPServer.loopback_cdp_url) throw new Error(`No loopback_cdp_url configured for ${method}.`); - const ws = await loopbackWS(ModCDPServer.loopback_cdp_url); - const id = nextLoopbackId++; - const message: { - id: number; - method: string; - params: ProtocolParams; - sessionId?: string; - } = { - id, - method, - params, - }; - if (sessionId) message.sessionId = sessionId; - ws.send(JSON.stringify(message)); - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - if (!loopbackPending.delete(id)) return; - reject(new Error(`${method} timed out after ${ModCDPServer.cdp_send_timeout_ms}ms`)); - }, ModCDPServer.cdp_send_timeout_ms); - loopbackPending.set(id, { - resolve: (value) => { - clearTimeout(timeout); - resolve(value); - }, - reject: (error) => { - clearTimeout(timeout); - reject(error); - }, - }); - }); - } - - async function initializeLoopbackCDP() { - if (!ModCDPServer.loopback_cdp_url) return; - const ws = await loopbackWS(ModCDPServer.loopback_cdp_url); - if (initializedLoopbackSockets.has(ws)) return; - await callLoopbackWS("Target.setAutoAttach", targetAutoAttachParams); - await callLoopbackWS("Target.setDiscoverTargets", { discover: true }); - initializedLoopbackSockets.add(ws); - } - - function waitForLoopbackExecutionContext( - sessionId: string, - timeoutMs = ModCDPServer.loopback_execution_context_timeout_ms, - ) { - const existing = loopbackSessionContexts.get(sessionId); - if (existing != null) return Promise.resolve(existing); - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - const waiters = loopbackContextWaiters.get(sessionId); - waiters?.delete(complete); - if (waiters?.size === 0) loopbackContextWaiters.delete(sessionId); - reject(new Error(`Timed out waiting for Runtime.executionContextCreated for session ${sessionId}.`)); - }, timeoutMs); - const complete = (contextId: number) => { - clearTimeout(timeout); - resolve(contextId); - }; - const waiters = loopbackContextWaiters.get(sessionId); - if (waiters) waiters.add(complete); - else loopbackContextWaiters.set(sessionId, new Set([complete])); - }); - } - async function ensureOffscreenKeepAlive() { - const chromeApi = globalScope.chrome; - const offscreen = chromeApi?.offscreen; - if (!offscreen || !chromeApi?.runtime?.getURL) return { started: false, reason: "offscreen_unavailable" }; + const chrome_api = globalScope.chrome; + const offscreen = chrome_api?.offscreen; + if (!offscreen || !chrome_api?.runtime?.getURL) return { started: false, reason: "offscreen_unavailable" }; - const offscreenUrl = chromeApi.runtime.getURL(offscreenKeepAlivePath); + const offscreen_url = chrome_api.runtime.getURL(offscreen_keep_alive_path); try { - const existingContexts = chromeApi.runtime.getContexts - ? await chromeApi.runtime.getContexts({ + const existing_contexts = chrome_api.runtime.getContexts + ? await chrome_api.runtime.getContexts({ contextTypes: ["OFFSCREEN_DOCUMENT"], - documentUrls: [offscreenUrl], + documentUrls: [offscreen_url], }) : []; - if (existingContexts.length > 0) return { started: true, existing: true }; + if (existing_contexts.length > 0) return { started: true, existing: true }; - creatingOffscreenKeepAlive ??= offscreen + creating_offscreen_keep_alive ??= offscreen .createDocument({ - url: offscreenKeepAlivePath, + url: offscreen_keep_alive_path, reasons: ["BLOBS"], justification: "Keep ModCDP service worker active while CDP clients route commands through it.", }) .finally(() => { - creatingOffscreenKeepAlive = null; + creating_offscreen_keep_alive = null; }); - await creatingOffscreenKeepAlive; + await creating_offscreen_keep_alive; return { started: true }; } catch (error) { return { started: false, reason: errorMessage(error) }; } } - const ModCDPServer = { + const ModCDPServer: ModCDPServerInstance = { __ModCDPServerVersion: MODCDP_SERVER_VERSION, - routes: { ...defaultRoutes }, + routes: { ...default_routes }, loopback_cdp_url: null as string | null, browser_token: null as string | null, - native_bridge_attempts: 0, - native_bridge_last_error: null as string | null, - native_bridge_connected: false, + upstream: null as LoopbackCdpTransport | ChromeDebuggerTransport | null, + upstream_name: null as SelectedServerUpstreamTransportName | null, + router: null as AutoSessionRouter | null, cdp_send_timeout_ms: DEFAULT_CDP_SEND_TIMEOUT_MS, loopback_execution_context_timeout_ms: DEFAULT_LOOPBACK_EXECUTION_CONTEXT_TIMEOUT_MS, ws_connect_error_settle_timeout_ms: DEFAULT_WS_CONNECT_ERROR_SETTLE_TIMEOUT_MS, @@ -1045,66 +512,26 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis types: null as (typeof import("../types/generated/zod.js"))["types"] | null, commands: null as (typeof import("../types/generated/zod.js"))["commands"] | null, events: null as (typeof import("../types/generated/zod.js"))["events"] | null, - startOffscreenKeepAlive, - startReverseBridge( - endpoint: string, - { - reconnect_interval_ms = DEFAULT_REVERSE_BRIDGE_RECONNECT_INTERVAL_MS, - }: { - reconnect_interval_ms?: number; - } = {}, - ) { - if (!/^wss?:\/\//i.test(endpoint)) { - throw new Error(`reverse proxy endpoint must be a ws:// or wss:// URL, got ${endpoint}.`); + startDownstreamTransports() { + const results: Record = {}; + for (const [name, transport] of downstream_transports) { + const result = transport.startDefault(); + if (result != null) results[name] = result; } - reverseBridgeUrl = endpoint; - reverseBridgeReconnectIntervalMs = reconnect_interval_ms; - void connectReverseBridge(endpoint).catch(() => { - scheduleReverseBridgeReconnect(reverseBridgeReconnectIntervalMs); - }); - return { - upstream_reversews_url: endpoint, - reconnect_interval_ms, - connecting: true, - }; + return results; }, - stopReverseBridge, - startNativeBridge( - hostName = DEFAULT_NATIVE_BRIDGE_HOST_NAME, - { - reconnect_interval_ms = DEFAULT_NATIVE_BRIDGE_RECONNECT_INTERVAL_MS, - }: { - reconnect_interval_ms?: number; - } = {}, - ) { - nativeBridgeHostName = hostName; - nativeBridgeReconnectIntervalMs = reconnect_interval_ms; - return connectNativeBridge(hostName); + stopDownstreamTransports(reason = "stopped") { + const results: Record = {}; + for (const [name, transport] of downstream_transports) { + const result = transport.stop(reason); + if (result != null) results[name] = result; + } + return results; }, - startNatsBridge( - endpoint: string, - { - upstream_nats_subject_prefix = DEFAULT_NATS_BRIDGE_SUBJECT_PREFIX, - reconnect_interval_ms = DEFAULT_NATS_BRIDGE_RECONNECT_INTERVAL_MS, - }: { - upstream_nats_subject_prefix?: string; - reconnect_interval_ms?: number; - } = {}, - ) { - if (!upstream_nats_subject_prefix || /[\s*>]/.test(upstream_nats_subject_prefix)) - throw new Error(`Invalid NATS subject prefix ${upstream_nats_subject_prefix}`); - nats_bridge_url = endpoint; - nats_bridge_subject_prefix = upstream_nats_subject_prefix; - nats_bridge_reconnect_interval_ms = reconnect_interval_ms; - void connectNatsBridge(endpoint).catch(() => { - scheduleNatsBridgeReconnect(nats_bridge_reconnect_interval_ms); - }); - return { - upstream_nats_url: endpoint, - upstream_nats_subject_prefix, - reconnect_interval_ms, - connecting: true, - }; + downstreamTransports() { + const status: Record = {}; + for (const [name, transport] of downstream_transports) status[name] = transport.status(); + return status; }, ensureOffscreenKeepAlive, @@ -1119,7 +546,6 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis }, async configure(params: ModCDPConfigureParams = {}) { - const upstream = params.upstream ?? {}; const server = params.server ?? {}; const { server_loopback_cdp_url = this.loopback_cdp_url, @@ -1132,27 +558,30 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis server_close_browser_on_downstream_disconnect = this.close_browser_on_downstream_disconnect, } = server; const { custom_commands = [], custom_events = [], custom_middlewares = [] } = params; - this.loopback_cdp_url = await resolveCDPEndpoint(server_loopback_cdp_url); + this.loopback_cdp_url = await LoopbackCdpTransport.resolveEndpoint(server_loopback_cdp_url); this.browser_token = server_browser_token; this.cdp_send_timeout_ms = server_cdp_send_timeout_ms; this.loopback_execution_context_timeout_ms = server_loopback_execution_context_timeout_ms; this.ws_connect_error_settle_timeout_ms = server_ws_connect_error_settle_timeout_ms; this.downstream_client_timeout_ms = server_downstream_client_timeout_ms; this.close_browser_on_downstream_disconnect = server_close_browser_on_downstream_disconnect; - if (upstream.upstream_mode === "nats" && upstream.upstream_nats_url) { - this.startNatsBridge(upstream.upstream_nats_url, { - upstream_nats_subject_prefix: upstream.upstream_nats_subject_prefix ?? DEFAULT_NATS_BRIDGE_SUBJECT_PREFIX, - }); - } - if (server_routes) this.routes = { ...defaultRoutes, ...server_routes }; + for (const transport of downstream_transports.values()) transport.configure(params); + if (server_routes) this.routes = { ...default_routes, ...server_routes }; else { - this.routes = { ...defaultRoutes }; + this.routes = { ...default_routes }; await this.discoverLoopbackCDP(); } + const default_server_route = server_routes?.["*.*"]; + setupServerUpstreamTransport( + default_server_route === "loopback_cdp" || default_server_route === "chrome_debugger" + ? default_server_route + : this.loopback_cdp_url + ? "loopback_cdp" + : "chrome_debugger", + ); for (const command of custom_commands) this.addCustomCommand(command as ModCDPCustomCommandRegistration); for (const event of custom_events) this.addCustomEvent(event as ModCDPCustomEventRegistration); for (const middleware of custom_middlewares) this.addMiddleware(middleware as ModCDPMiddlewareRegistration); - await initializeLoopbackCDP(); return { loopback_cdp_url: this.loopback_cdp_url, routes: this.routes }; }, @@ -1176,7 +605,7 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis }; } if (typeof handler !== "function") throw new Error(`Custom command ${name} was registered without a handler.`); - commandHandlers.set(name, { + command_handlers.set(name, { name, handler, params_schema: normalizeModCDPPayloadSchema(params_schema), @@ -1189,7 +618,7 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis addCustomEvent({ name, event_schema = null }: ModCDPCustomEventRegistration) { name = normalizeModCDPName(name); if (!/^[^.]+\.[^.]+$/.test(name)) throw new Error("name must be in Domain.event form."); - eventBindings.set(name, { + event_bindings.set(name, { name, event_schema: normalizeModCDPPayloadSchema(event_schema), }); @@ -1197,8 +626,8 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis }, addEventListener(listener: (event: string, data: ProtocolPayload, cdpSessionId: string | null) => void) { - eventListeners.add(listener); - return { remove: () => eventListeners.delete(listener) }; + event_listeners.add(listener); + return { remove: () => event_listeners.delete(listener) }; }, addMiddleware({ name = "*", phase, expression = null, handler }: ModCDPMiddlewareRegistration) { @@ -1210,7 +639,7 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis handler = async (payload: ProtocolPayload, next: unknown, context: ProtocolPayload = {}) => { const context_object = context && typeof context === "object" ? (context as Record) : {}; const cdpSessionId = typeof context_object.cdpSessionId === "string" ? context_object.cdpSessionId : null; - const result = (await evaluateInSelf(` + const result = (await evaluateInServiceWorker(` (async () => { const payload = ${JSON.stringify(payload ?? {})}; const context = ${JSON.stringify(context ?? {})}; @@ -1218,16 +647,16 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis const ModCDP = globalThis.ModCDP; const chrome = globalThis.chrome; const next = async (nextValue = payload) => ({ __ModCDP_middleware_next__: true, value: nextValue }); - const handler = (${expression}); - return await handler(payload, next, context); + const middleware = (${expression}); + return await middleware(payload, next, context); })() `)) as Record; if (result?.__ModCDP_middleware_next__ === true && typeof next === "function") { - const nextResult = await next(result.value); - const { __ModCDP_middleware_next__, value, ...overrides } = result; - if (Object.keys(overrides).length === 0) return nextResult; - return nextResult != null && typeof nextResult === "object" && !Array.isArray(nextResult) - ? { ...(nextResult as Record), ...overrides } + const next_result = await next(result.value); + const { __ModCDP_middleware_next__, value: _value, ...overrides } = result; + if (Object.keys(overrides).length === 0) return next_result; + return next_result != null && typeof next_result === "object" && !Array.isArray(next_result) + ? { ...(next_result as Record), ...overrides } : overrides; } return result; @@ -1247,11 +676,11 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis const dispatch = async (index: number, value: ProtocolPayload): Promise => { const middleware = matching[index]; if (!middleware) return value; - let nextCalled = false; + let next_called = false; const next = async (nextValue = value) => { - if (nextCalled) + if (next_called) throw new Error(`Middleware ${middleware.name}:${middleware.phase} called next() more than once.`); - nextCalled = true; + next_called = true; return dispatch(index + 1, nextValue); }; const ctx = context && typeof context === "object" ? context : {}; @@ -1264,11 +693,11 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis if (method === "Mod.configure") registerDownstreamClient(); touchDownstreamClientLease(cdpSessionId); const request = { method, params, cdpSessionId }; - const middlewareParams = await this.runMiddleware("request", method, params, { cdpSessionId, request }); - if (middlewareParams == null) throw new Error(`Request middleware for ${method} returned no params.`); - params = middlewareParams as ProtocolParams; + const middleware_params = await this.runMiddleware("request", method, params, { cdpSessionId, request }); + if (middleware_params == null) throw new Error(`Request middleware for ${method} returned no params.`); + params = middleware_params as ProtocolParams; - const command = registryMatch(commandHandlers, method); + const command = registryMatch(command_handlers, method); params = commandParamsSchema(method, command)?.parse(params) ?? params; let result; if (command) { @@ -1281,7 +710,7 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis return commandResultSchema(method, command)?.parse(result) ?? result; } - let upstream = "chrome_debugger"; + let upstream = "auto"; for (const [pattern, route] of Object.entries(this.routes || {}) as [string, string][]) { if (pattern === "*.*") { upstream = route; @@ -1297,19 +726,13 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis } } - if (upstream === "auto") { - if (this.loopback_cdp_url) { - try { - result = await this.sendLoopback(method, params, cdpSessionId); - } catch { - result = await this.sendChromeDebugger(method, params); - } - } else { - result = await this.sendChromeDebugger(method, params); - } - } else if (upstream === "loopback_cdp") result = await this.sendLoopback(method, params, cdpSessionId); - else if (upstream === "chrome_debugger") result = await this.sendChromeDebugger(method, params); - else throw new Error(`No ModCDP command registered for ${method}.`); + if (upstream === "service_worker") throw new Error(`No service-worker command registered for ${method}.`); + if (upstream !== "auto" && upstream !== "loopback_cdp" && upstream !== "chrome_debugger") + throw new Error(`No service-worker command registered for ${method}.`); + if (!ModCDPServer.upstream) setupServerUpstreamTransport(); + if (!ModCDPServer.upstream) throw new Error(`No ModCDP server upstream transport registered for ${method}.`); + if (!ModCDPServer.router) throw new Error("ModCDP autorouter is not initialized."); + result = await ModCDPServer.router.send(method, params, cdpSessionId); result = await this.runMiddleware("response", method, result, { cdpSessionId, @@ -1331,13 +754,18 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis get events() { return ModCDPServer.events; }, + get upstream() { + if (!ModCDPServer.router) setupServerUpstreamTransport(); + if (!ModCDPServer.router) throw new Error("ModCDP autorouter is not initialized."); + return ModCDPServer.router; + }, send: (method: string, params: ProtocolParams = {}) => this.handleCommand(method, params, cdpSessionId), emit: (eventName: string, payload: ProtocolPayload = {}) => this.emit(eventName, payload, cdpSessionId), }; }, async emit(eventName: string, payload: ProtocolPayload = {}, cdpSessionId: string | null = null) { - const event = registryMatch(eventBindings, eventName); + const event = registryMatch(event_bindings, eventName); if (!event) return { event: eventName, @@ -1345,12 +773,10 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis reason: "event_not_registered", }; payload = eventPayloadSchema(eventName, event)?.parse(payload) ?? payload; - const customBinding = globalScope[CUSTOM_EVENT_BINDING_NAME]; + const custom_binding = globalScope[CUSTOM_EVENT_BINDING_NAME]; if ( - typeof customBinding !== "function" && - reverseBridgeSocket?.readyState !== WebSocket.OPEN && - !nativeBridgePort && - nats_bridge_socket?.readyState !== WebSocket.OPEN + typeof custom_binding !== "function" && + ![...downstream_transports.values()].some((transport) => transport.status().connected) ) return { event: eventName, @@ -1365,203 +791,42 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis verified: boolean; version?: unknown; }> { - if (!this.browser_token) return { loopback_cdp_url: null as null, verified: false }; - - const url = "http://127.0.0.1:9222"; - const previousLoopbackUrl = this.loopback_cdp_url; - const fail = (version?: unknown) => { - this.loopback_cdp_url = previousLoopbackUrl ?? null; - return { - loopback_cdp_url: null as null, - verified: false, - ...(version ? { version } : {}), - }; - }; - try { - const version = await fetch(`${url}/json/version`).then((response) => response.ok && response.json()); - if (!version?.webSocketDebuggerUrl) return fail(); - - this.loopback_cdp_url = version.webSocketDebuggerUrl; - const { targetInfos } = (await callLoopbackWS("Target.getTargets")) as cdp.types.ts.Target.GetTargetsResult; - const serviceWorkerUrl = currentServiceWorkerUrl(); - const worker = targetInfos.find( - (target) => target.type === "service_worker" && target.url === serviceWorkerUrl, - ); - if (!worker) return fail(version); - - const { sessionId } = (await callLoopbackWS("Target.attachToTarget", { - targetId: worker.targetId, - flatten: true, - })) as cdp.types.ts.Target.AttachToTargetResult; - loopbackTargetSessions.set(worker.targetId, sessionId); - loopbackSessionTargets.set(sessionId, worker.targetId); - const contextIdPromise = waitForLoopbackExecutionContext(sessionId); - await callLoopbackWS("Runtime.enable", {}, sessionId); - const executionContextId = await contextIdPromise; - const result = (await callLoopbackWS( - "Runtime.callFunctionOn", - { - functionDeclaration: `function() { return globalThis.ModCDP?.browser_token === ${JSON.stringify(this.browser_token)}; }`, - executionContextId, - returnByValue: true, - }, - sessionId, - )) as cdp.types.ts.Runtime.EvaluateResult; - if (result.result?.value !== true) return fail(version); - - await initializeLoopbackCDP(); - return { - loopback_cdp_url: this.loopback_cdp_url, - verified: true, - version, - }; - } catch { - return fail(); - } - }, - - async sendLoopback(method: string, params: ProtocolParams = {}, cdpSessionId: string | null = null) { - if (!this.loopback_cdp_url) throw new Error(`No loopback_cdp_url configured for ${method}.`); - - await initializeLoopbackCDP(); - - const domain = method.split(".")[0] ?? ""; - if (browserLevelDomains.has(domain)) return await callLoopbackWS(method, params); - if (cdpSessionId) return await callLoopbackWS(method, params, cdpSessionId); - - const { - debuggee = null, - tabId = null, - targetId = null, - extensionId = null, - ...commandParams - } = params as CdpDebuggeeCommandParams; - const resolvedDebuggee = debuggee ?? compactDebuggee({ tabId, targetId, extensionId }); - - const chromeApi = globalScope.chrome; - let resolvedTargetId = resolvedDebuggee.targetId || null; - if (!resolvedTargetId) { - let resolvedTabId = resolvedDebuggee.tabId || null; - let resolvedTabUrl: string | null = null; - if (!resolvedTabId) { - const [tab] = chromeApi.tabs?.query - ? await chromeApi.tabs.query({ - active: true, - lastFocusedWindow: true, - }) - : []; - resolvedTabId = tab?.id || null; - resolvedTabUrl = tab?.url || tab?.pendingUrl || null; - } else if (chromeApi.tabs?.get) { - const tab = await chromeApi.tabs.get(resolvedTabId).catch((): null => null); - resolvedTabUrl = tab?.url || tab?.pendingUrl || null; - } - if (resolvedTabId && chromeApi.debugger?.getTargets) { - const targets = await chromeApi.debugger.getTargets(); - resolvedTargetId = - targets.find((target) => target.tabId === resolvedTabId && target.type === "page")?.id || null; - } - if (!resolvedTargetId) { - const { targetInfos } = (await callLoopbackWS("Target.getTargets")) as cdp.types.ts.Target.GetTargetsResult; - const pageTargets = targetInfos.filter((target) => target.type === "page"); - resolvedTargetId = - pageTargets.find((target) => resolvedTabUrl && target.url === resolvedTabUrl)?.targetId || - pageTargets[0]?.targetId || - null; - } - if (!resolvedTargetId) { - const created = (await callLoopbackWS("Target.createTarget", { - url: "about:blank#modcdp", - })) as cdp.types.ts.Target.CreateTargetResult; - resolvedTargetId = created.targetId || null; - } - } - if (!resolvedTargetId) throw new Error(`loopback_cdp route for ${method} could not resolve a page target.`); - - const existingSessionId = loopbackTargetSessions.get(resolvedTargetId); - if (existingSessionId) return await callLoopbackWS(method, commandParams, existingSessionId); - - const attached = (await callLoopbackWS("Target.attachToTarget", { - targetId: resolvedTargetId, - flatten: true, - })) as cdp.types.ts.Target.AttachToTargetResult; - const sessionId = attached.sessionId; - loopbackTargetSessions.set(resolvedTargetId, sessionId); - loopbackSessionTargets.set(sessionId, resolvedTargetId); - await callLoopbackWS("Target.setAutoAttach", targetAutoAttachParams, sessionId).catch(() => {}); - return await callLoopbackWS(method, commandParams, sessionId); - }, - - async sendChromeDebugger(method: string, params: ProtocolParams = {}) { - const chromeApi = globalScope.chrome; - if (!chromeApi?.debugger?.sendCommand) throw new Error("chrome.debugger is unavailable."); - - const { - debuggee = null, - tabId = null, - targetId = null, - extensionId = null, - ...commandParams - } = params as CdpDebuggeeCommandParams; - const resolvedDebuggee = debuggee ?? compactDebuggee({ tabId, targetId, extensionId }); - if (Object.keys(resolvedDebuggee).length === 0) { - let tab: chrome.tabs.Tab | undefined; - [tab] = await chromeApi.tabs.query({ - active: true, - lastFocusedWindow: true, - }); - if (!tab?.id) [tab] = await chromeApi.tabs.query({}); - if (!tab?.id) { - try { - tab = await chromeApi.tabs.create({ - url: "https://example.com/#modcdp", - active: true, - }); - } catch { - const win = await chromeApi.windows.create({ - url: "https://example.com/#modcdp", - focused: true, - }); - tab = win?.tabs?.[0]; - } - } - if (!tab?.id) throw new Error(`chrome_debugger route for ${method} could not find an active tab.`); - resolvedDebuggee.tabId = tab.id; - } - - const key = JSON.stringify(resolvedDebuggee); - if (!attachedDebuggees.has(key)) { - try { - await new Promise((resolve, reject) => - chromeApi.debugger.attach(resolvedDebuggee, "1.3", () => { - const error = chromeApi.runtime.lastError; - if (error) reject(new Error(error.message)); - else resolve(); - }), - ); - } catch (error) { - if (!errorMessage(error).includes("Another debugger is already attached")) throw error; - } - await new Promise((resolve, reject) => - chromeApi.debugger.sendCommand(resolvedDebuggee, "Target.setAutoAttach", targetAutoAttachParams, () => { - const error = chromeApi.runtime.lastError; - if (error) reject(new Error(error.message)); - else resolve(); - }), - ); - attachedDebuggees.add(key); - } - - return new Promise((resolve, reject) => - chromeApi.debugger.sendCommand(resolvedDebuggee, method, commandParams, (result) => { - const error = chromeApi.runtime.lastError; - if (error) reject(new Error(error.message)); - else resolve(result as ProtocolResult); - }), - ); + const transport = new LoopbackCdpTransport({ + loopback_cdp_url: ModCDPServer.loopback_cdp_url, + cdp_send_timeout_ms: ModCDPServer.cdp_send_timeout_ms, + loopback_execution_context_timeout_ms: ModCDPServer.loopback_execution_context_timeout_ms, + ws_connect_error_settle_timeout_ms: ModCDPServer.ws_connect_error_settle_timeout_ms, + }); + const result = await transport.discoverLoopbackCDP({ + browserToken: this.browser_token, + serviceWorkerUrl: currentServiceWorkerUrl(), + }); + this.loopback_cdp_url = result.loopback_cdp_url; + return result; }, }; + downstream_transports = new Map(); + for (const transport of [ + new ReverseWSDownstreamTransport({ + ensureOffscreenKeepAlive, + handleCommand: (message) => + ModCDPServer.handleCommand(message.method, message.params ?? {}, message.sessionId ?? null), + }), + new NativeHostDownstreamTransport({ + ensureOffscreenKeepAlive, + handleCommand: (message) => + ModCDPServer.handleCommand(message.method, message.params ?? {}, message.sessionId ?? null), + }), + new NATSDownstreamTransport({ + ensureOffscreenKeepAlive, + handleCommand: (message) => + ModCDPServer.handleCommand(message.method, message.params ?? {}, message.sessionId ?? null), + }), + ]) { + downstream_transports.set(transport.name, transport); + } + globalScope.ModCDP = ModCDPServer; ModCDPServer.addCustomEvent({ @@ -1603,6 +868,15 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis }, }); + ModCDPServer.addCustomCommand({ + name: "Mod.getTopology", + handler: async (params: ProtocolParams = {}) => { + if (!ModCDPServer.router) setupServerUpstreamTransport(); + if (!ModCDPServer.router) throw new Error("ModCDP autorouter is not initialized."); + return await ModCDPServer.router.getTopology(params as Record); + }, + }); + ModCDPServer.addCustomCommand({ name: "Mod.addCustomCommand", handler: async (params: ProtocolParams = {}) => @@ -1620,27 +894,27 @@ export function installModCDPServer(globalScope: ModCDPGlobalScope = globalThis handler: async (params: ProtocolParams = {}) => ModCDPServer.addMiddleware(params as ModCDPMiddlewareRegistration), }); - const chromeApi = globalScope.chrome; + const chrome_api = globalScope.chrome; try { - chromeApi?.runtime?.onStartup?.addListener(startOffscreenKeepAlive); + chrome_api?.runtime?.onStartup?.addListener(ensureOffscreenKeepAlive); } catch {} try { - chromeApi?.runtime?.onInstalled?.addListener(startOffscreenKeepAlive); + chrome_api?.runtime?.onInstalled?.addListener(ensureOffscreenKeepAlive); } catch {} try { - chromeApi?.tabs?.onCreated?.addListener(startOffscreenKeepAlive); + chrome_api?.tabs?.onCreated?.addListener(ensureOffscreenKeepAlive); } catch {} try { - chromeApi?.runtime?.onConnect?.addListener((port) => { - if (port.name !== offscreenKeepAlivePortName) return; - offscreenKeepAlivePort = port; + chrome_api?.runtime?.onConnect?.addListener((port) => { + if (port.name !== offscreen_keep_alive_port_name) return; + offscreen_keep_alive_port = port; port.onMessage.addListener(() => {}); port.onDisconnect.addListener(() => { - if (offscreenKeepAlivePort === port) offscreenKeepAlivePort = null; + if (offscreen_keep_alive_port === port) offscreen_keep_alive_port = null; }); }); } catch {} - startOffscreenKeepAlive(); + void ensureOffscreenKeepAlive(); return ModCDPServer; } diff --git a/js/src/server/NATSDownstreamTransport.ts b/js/src/server/NATSDownstreamTransport.ts new file mode 100644 index 0000000..421666d --- /dev/null +++ b/js/src/server/NATSDownstreamTransport.ts @@ -0,0 +1,309 @@ +import { + CdpCommandMessageSchema, + type CdpCommandMessage, + type CdpEventMessage, + type ModCDPConfigureParams, +} from "../types/modcdp.js"; +import type { ServerDownstreamTransport } from "./ServerDownstreamTransport.js"; + +export const DEFAULT_NATS_BRIDGE_RECONNECT_INTERVAL_MS = 2_000; +export const DEFAULT_NATS_BRIDGE_SUBJECT_PREFIX = "modcdp.default"; + +/** + * Owns the NATS-over-WebSocket downstream connection from the extension service + * worker to a ModCDP client/proxy. + * + * This class owns only NATS-specific lifecycle: WebSocket connection, reconnect + * scheduling, NATS CONNECT/SUB/PUB framing, protocol buffering, hello messages, + * command-message decoding, CDP response publishing, and event-message + * publishing. It does not own ModCDP command registration, routing, middleware, + * upstream target/session state, native messaging, or reversews handling. + * + * Lifecycle: + * 1. `start()` records the endpoint/subject/reconnect interval and opens one + * WebSocket if none is already open or connecting. + * 2. `open` sends NATS CONNECT/PING/SUB frames and publishes a browser hello. + * 3. `message` appends decoded bytes to the protocol buffer and consumes + * complete NATS frames. + * 4. `MSG` payloads are decoded as ModCDP command envelopes and delegated + * through the injected `handleCommand` callback. + * 5. `error`/`close` drops the socket and schedules reconnect while an endpoint + * is still configured. + */ +export class NATSDownstreamTransport implements ServerDownstreamTransport { + readonly name = "nats"; + + // Server-owned command executor. Read by NATS payload handling; this class + // never interprets routes, custom commands, or middleware itself. + private readonly handleCommand: (message: CdpCommandMessage) => Promise; + + // Server-owned keepalive hook. Called after the NATS WebSocket opens. + private readonly ensureOffscreenKeepAlive: () => unknown; + + // Configured NATS WebSocket URL. Set by start and read by reconnect handling. + private endpoint: string | null = null; + + // Configured NATS subject prefix. Set by start and read by SUB/PUB handling. + private subject_prefix = DEFAULT_NATS_BRIDGE_SUBJECT_PREFIX; + + // Reconnect interval currently configured for the endpoint. Set by start and + // read by error/close handlers. + private reconnect_interval_ms = DEFAULT_NATS_BRIDGE_RECONNECT_INTERVAL_MS; + + // Active NATS WebSocket. Set by connect, cleared by error/close, read by + // start/write/emit. + private socket: WebSocket | null = null; + + // Pending reconnect timer. Set by scheduleReconnect and cleared when it fires. + private reconnect_timer: ReturnType | null = null; + + // Unconsumed NATS protocol bytes decoded as text. Appended by readWebSocketData + // and replaced by consumeProtocol. + private buffer = ""; + + constructor({ + handleCommand, + ensureOffscreenKeepAlive, + }: { + handleCommand: (message: CdpCommandMessage) => Promise; + ensureOffscreenKeepAlive: () => unknown; + }) { + this.handleCommand = handleCommand; + this.ensureOffscreenKeepAlive = ensureOffscreenKeepAlive; + } + + /** True when the NATS WebSocket is open and can publish CDP event messages. */ + get connected() { + return this.socket?.readyState === WebSocket.OPEN; + } + + /** Configure and start the NATS downstream connection. */ + start( + endpoint: string, + { + upstream_nats_subject_prefix = DEFAULT_NATS_BRIDGE_SUBJECT_PREFIX, + reconnect_interval_ms = DEFAULT_NATS_BRIDGE_RECONNECT_INTERVAL_MS, + }: { + upstream_nats_subject_prefix?: string; + reconnect_interval_ms?: number; + } = {}, + ) { + if (!upstream_nats_subject_prefix || /[\s*>]/.test(upstream_nats_subject_prefix)) + throw new Error(`Invalid NATS subject prefix ${upstream_nats_subject_prefix}`); + this.endpoint = endpoint; + this.subject_prefix = upstream_nats_subject_prefix; + this.reconnect_interval_ms = reconnect_interval_ms; + void this.connect(endpoint).catch(() => { + this.scheduleReconnect(this.reconnect_interval_ms); + }); + return { + upstream_nats_url: endpoint, + upstream_nats_subject_prefix, + reconnect_interval_ms, + connecting: true, + }; + } + + /** NATS has no built-in extension default; it starts only from Mod.configure. */ + startDefault() { + return null; + } + + /** Start NATS when the downstream client configured the NATS transport. */ + configure(params: ModCDPConfigureParams) { + const upstream = params.upstream ?? {}; + if (upstream.upstream_mode !== "nats" || !upstream.upstream_nats_url) return null; + return this.start(upstream.upstream_nats_url, { + upstream_nats_subject_prefix: upstream.upstream_nats_subject_prefix ?? DEFAULT_NATS_BRIDGE_SUBJECT_PREFIX, + }); + } + + /** Stop reconnecting and close the active NATS socket. */ + stop(reason = "stopped") { + const upstream_nats_url = this.endpoint; + const upstream_nats_subject_prefix = this.subject_prefix; + this.endpoint = null; + if (this.reconnect_timer) { + clearTimeout(this.reconnect_timer); + this.reconnect_timer = null; + } + const socket = this.socket; + this.socket = null; + if (socket?.readyState === WebSocket.OPEN || socket?.readyState === WebSocket.CONNECTING) { + socket.close(1000, reason); + } + return { upstream_nats_url, upstream_nats_subject_prefix, stopped: true, reason }; + } + + /** Publish one CDP event message to the NATS browser-to-client subject. */ + emit(message: CdpEventMessage) { + if (this.socket?.readyState !== WebSocket.OPEN) return false; + this.publish(`${this.subject_prefix}.browser_to_client`, { + type: "modcdp.nats.message", + message, + }); + return true; + } + + /** Return generic status without exposing NATS lifecycle to ModCDPServer. */ + status() { + return { + connected: this.connected, + config: this.endpoint + ? { + upstream_nats_url: this.endpoint, + upstream_nats_subject_prefix: this.subject_prefix, + reconnect_interval_ms: this.reconnect_interval_ms, + } + : {}, + }; + } + + private scheduleReconnect(delay_ms: number) { + if (!this.endpoint) return; + if (this.reconnect_timer) return; + this.reconnect_timer = setTimeout(() => { + this.reconnect_timer = null; + if (!this.endpoint) return; + void this.connect(this.endpoint).catch(() => {}); + }, delay_ms); + } + + private async connect(endpoint: string) { + if (!/^wss?:\/\//i.test(endpoint)) { + throw new Error( + `NATS downstream endpoint must be a ws:// or wss:// URL for extension transport, got ${endpoint}.`, + ); + } + if (this.socket?.readyState === WebSocket.OPEN || this.socket?.readyState === WebSocket.CONNECTING) { + return { + upstream_nats_url: endpoint, + upstream_nats_subject_prefix: this.subject_prefix, + connected: this.socket.readyState === WebSocket.OPEN, + }; + } + const ws = new WebSocket(endpoint); + this.socket = ws; + this.buffer = ""; + ws.addEventListener("open", () => { + void this.ensureOffscreenKeepAlive(); + this.write(`CONNECT ${JSON.stringify(this.connectOptions())}\r\nPING\r\n`); + this.write(`SUB ${this.subject_prefix}.client_to_browser 1\r\n`); + this.publish(`${this.subject_prefix}.browser_to_client`, { + type: "modcdp.nats.hello", + role: "extension-service-worker", + version: 1, + extension_id: globalThis.chrome?.runtime?.id ?? null, + }); + }); + ws.addEventListener("message", (event) => { + void this.readWebSocketData(event.data); + }); + ws.addEventListener("error", () => { + if (this.socket === ws) this.socket = null; + this.scheduleReconnect(this.reconnect_interval_ms); + }); + ws.addEventListener("close", () => { + if (this.socket === ws) this.socket = null; + this.scheduleReconnect(this.reconnect_interval_ms); + }); + return { + upstream_nats_url: endpoint, + upstream_nats_subject_prefix: this.subject_prefix, + connected: false, + }; + } + + private write(data: string) { + if (this.socket?.readyState === WebSocket.OPEN) this.socket.send(data); + } + + private publish(subject: string, message: unknown) { + const body = JSON.stringify(message); + this.write(`PUB ${subject} ${new TextEncoder().encode(body).byteLength}\r\n${body}\r\n`); + } + + private async readWebSocketData(data: unknown) { + if (typeof data === "string") this.buffer += data; + else if (data instanceof ArrayBuffer) this.buffer += new TextDecoder().decode(data); + else if (ArrayBuffer.isView(data)) this.buffer += new TextDecoder().decode(data); + else if (typeof Blob !== "undefined" && data instanceof Blob) this.buffer += await data.text(); + else return; + this.buffer = this.consumeProtocol(this.buffer); + } + + private consumeProtocol(buffer: string) { + for (;;) { + const line_end = buffer.indexOf("\r\n"); + if (line_end < 0) return buffer; + const line = buffer.slice(0, line_end); + const upper = line.toUpperCase(); + if (upper.startsWith("MSG ")) { + const parts = line.split(/\s+/); + const size = Number(parts[parts.length - 1]); + const payload_start = line_end + 2; + const payload_end = payload_start + size; + if (!Number.isInteger(size) || buffer.length < payload_end + 2) return buffer; + const payload = buffer.slice(payload_start, payload_end); + buffer = buffer.slice(payload_end + 2); + void this.handlePayload(payload); + continue; + } + buffer = buffer.slice(line_end + 2); + if (upper === "PING") this.write("PONG\r\n"); + } + } + + private async handlePayload(payload: string) { + let parsed: unknown; + try { + parsed = JSON.parse(payload); + } catch { + return; + } + const record = parsed && typeof parsed === "object" ? (parsed as { type?: unknown; message?: unknown }) : null; + if (record?.type === "modcdp.nats.hello") { + this.publish(`${this.subject_prefix}.browser_to_client`, { + type: "modcdp.nats.hello", + role: "extension-service-worker", + version: 1, + extension_id: globalThis.chrome?.runtime?.id ?? null, + }); + return; + } + let message: CdpCommandMessage; + try { + message = CdpCommandMessageSchema.parse(record?.type === "modcdp.nats.message" ? record.message : parsed); + } catch { + return; + } + try { + const result = await this.handleCommand(message); + this.publish(`${this.subject_prefix}.browser_to_client`, { + type: "modcdp.nats.message", + message: { id: message.id, result }, + }); + } catch (error) { + this.publish(`${this.subject_prefix}.browser_to_client`, { + type: "modcdp.nats.message", + message: { + id: message.id, + error: { + code: -32000, + message: error instanceof Error ? error.message : String(error), + }, + }, + }); + } + } + + private connectOptions() { + return { + verbose: false, + pedantic: false, + lang: "modcdp-extension", + version: "1", + protocol: 1, + }; + } +} diff --git a/js/src/server/NativeHostDownstreamTransport.ts b/js/src/server/NativeHostDownstreamTransport.ts new file mode 100644 index 0000000..2b7d4f3 --- /dev/null +++ b/js/src/server/NativeHostDownstreamTransport.ts @@ -0,0 +1,213 @@ +import { + CdpCommandMessageSchema, + type CdpCommandMessage, + type CdpEventMessage, + type ModCDPConfigureParams, +} from "../types/modcdp.js"; +import type { ServerDownstreamTransport } from "./ServerDownstreamTransport.js"; + +export const DEFAULT_NATIVE_BRIDGE_HOST_NAME = "com.modcdp.bridge"; +export const DEFAULT_NATIVE_BRIDGE_RECONNECT_INTERVAL_MS = 2_000; + +/** + * Owns the native messaging downstream connection from the extension service + * worker to a native ModCDP host. + * + * This class owns only native-host lifecycle: chrome.runtime.connectNative, + * reconnect scheduling, port status, hello messages, command-message decoding, + * CDP response posting, and event-message forwarding. It does not own ModCDP + * command registration, routing, middleware, upstream target/session state, + * reversews, or NATS protocol handling. + * + * Lifecycle: + * 1. `start()` records the desired native host/reconnect interval and opens one + * native port if no port is currently connected. + * 2. Successful connection posts the native hello and marks the transport + * connected. + * 3. `onMessage` parses client CDP commands and delegates execution through + * the injected `handleCommand` callback. + * 4. `onDisconnect` clears the active port, stores the browser-provided error, + * and schedules reconnect while a host is still configured. + */ +export class NativeHostDownstreamTransport implements ServerDownstreamTransport { + readonly name = "native"; + + // Server-owned command executor. Read by port message handling; this class + // never interprets routes, custom commands, or middleware itself. + private readonly handleCommand: (message: CdpCommandMessage) => Promise; + + // Server-owned keepalive hook. Called after the native port connects. + private readonly ensureOffscreenKeepAlive: () => unknown; + + // Configured native host name. Set by start, read by reconnect scheduling. + private host_name: string | null = null; + + // Reconnect interval currently configured for the native host. Set by start + // and read by disconnect/error handling. + private reconnect_interval_ms = DEFAULT_NATIVE_BRIDGE_RECONNECT_INTERVAL_MS; + + // Active native messaging port. Set by connect, cleared by disconnect/error, + // read by start and emit. + private port: chrome.runtime.Port | null = null; + + // Pending reconnect timer. Set by scheduleReconnect and cleared when it fires. + private reconnect_timer: ReturnType | null = null; + + // Number of native connection attempts. Incremented by connect, read by the + // server status surface. + attempts = 0; + + // Last native messaging error. Updated by connect/disconnect, read by the + // server status surface. + last_error: string | null = null; + + constructor({ + handleCommand, + ensureOffscreenKeepAlive, + }: { + handleCommand: (message: CdpCommandMessage) => Promise; + ensureOffscreenKeepAlive: () => unknown; + }) { + this.handleCommand = handleCommand; + this.ensureOffscreenKeepAlive = ensureOffscreenKeepAlive; + } + + /** True when the native messaging port is connected and can receive events. */ + get connected() { + return this.port != null; + } + + /** Configure and start the native-host downstream connection. */ + start( + hostName = DEFAULT_NATIVE_BRIDGE_HOST_NAME, + { + reconnect_interval_ms = DEFAULT_NATIVE_BRIDGE_RECONNECT_INTERVAL_MS, + }: { + reconnect_interval_ms?: number; + } = {}, + ) { + this.host_name = hostName; + this.reconnect_interval_ms = reconnect_interval_ms; + return this.connect(hostName); + } + + /** Start the default native host configured into the shipped extension. */ + startDefault() { + return this.start(DEFAULT_NATIVE_BRIDGE_HOST_NAME, { + reconnect_interval_ms: DEFAULT_NATIVE_BRIDGE_RECONNECT_INTERVAL_MS, + }); + } + + /** Native host default lifecycle is not configured by Mod.configure. */ + configure(_params: ModCDPConfigureParams) { + return null; + } + + /** Stop reconnecting and disconnect the active native messaging port. */ + stop(reason = "stopped") { + const upstream_nativemessaging_host_name = this.host_name; + this.host_name = null; + if (this.reconnect_timer) { + clearTimeout(this.reconnect_timer); + this.reconnect_timer = null; + } + const port = this.port; + this.port = null; + try { + port?.disconnect(); + } catch {} + return { upstream_nativemessaging_host_name, stopped: true, reason }; + } + + /** Emit one CDP event message to the connected native host. */ + emit(message: CdpEventMessage) { + if (!this.port) return false; + this.port.postMessage(message); + return true; + } + + /** Return generic status without exposing native-host lifecycle to ModCDPServer. */ + status() { + return { + connected: this.connected, + attempts: this.attempts, + last_error: this.last_error, + config: this.host_name ? { upstream_nativemessaging_host_name: this.host_name } : {}, + }; + } + + private scheduleReconnect(delay_ms: number) { + if (!this.host_name) return; + if (this.reconnect_timer) return; + this.reconnect_timer = setTimeout(() => { + this.reconnect_timer = null; + if (this.host_name) this.connect(this.host_name); + }, delay_ms); + } + + private connect(hostName: string) { + const chrome_api = globalThis.chrome; + if (!chrome_api?.runtime?.connectNative) { + this.scheduleReconnect(this.reconnect_interval_ms); + return { + upstream_nativemessaging_host_name: hostName, + connected: false, + reason: "native_messaging_unavailable", + }; + } + if (this.port) return { upstream_nativemessaging_host_name: hostName, connected: true }; + try { + this.attempts += 1; + this.last_error = null; + const port = chrome_api.runtime.connectNative(hostName); + this.port = port; + void this.ensureOffscreenKeepAlive(); + port.postMessage({ + type: "modcdp.native.hello", + role: "extension-service-worker", + version: 1, + extension_id: globalThis.chrome?.runtime?.id ?? null, + }); + port.onMessage.addListener((message) => { + void this.handleMessage(port, message); + }); + port.onDisconnect.addListener(() => { + if (this.port === port) this.port = null; + this.last_error = chrome_api.runtime.lastError?.message ?? "Native messaging port disconnected."; + this.scheduleReconnect(this.reconnect_interval_ms); + }); + return { upstream_nativemessaging_host_name: hostName, connected: true }; + } catch (error) { + this.port = null; + this.last_error = error instanceof Error ? error.message : String(error); + this.scheduleReconnect(this.reconnect_interval_ms); + return { + upstream_nativemessaging_host_name: hostName, + connected: false, + reason: this.last_error, + }; + } + } + + private async handleMessage(port: chrome.runtime.Port, data: unknown) { + let message: CdpCommandMessage; + try { + message = CdpCommandMessageSchema.parse(data); + } catch { + return; + } + + try { + const result = await this.handleCommand(message); + port.postMessage({ id: message.id, result }); + } catch (error) { + port.postMessage({ + id: message.id, + error: { + code: -32000, + message: error instanceof Error ? error.message : String(error), + }, + }); + } + } +} diff --git a/js/src/server/ReverseWSDownstreamTransport.ts b/js/src/server/ReverseWSDownstreamTransport.ts new file mode 100644 index 0000000..470df94 --- /dev/null +++ b/js/src/server/ReverseWSDownstreamTransport.ts @@ -0,0 +1,210 @@ +import { + CdpCommandMessageSchema, + type CdpCommandMessage, + type CdpEventMessage, + type ModCDPConfigureParams, +} from "../types/modcdp.js"; +import type { ServerDownstreamTransport } from "./ServerDownstreamTransport.js"; + +export const DEFAULT_REVERSE_BRIDGE_RECONNECT_INTERVAL_MS = 2_000; + +/** + * Owns the reverse WebSocket downstream connection from the extension service + * worker back to a waiting ModCDP client/proxy. + * + * This class owns only reversews-specific lifecycle: socket creation, + * reconnect scheduling, hello messages, command-message decoding, CDP response + * writing, event-message forwarding, and stop semantics. It does not own + * ModCDP command registration, routing, middleware, upstream target/session + * state, native messaging, or NATS protocol handling. + * + * Lifecycle: + * 1. `start()` records the desired endpoint/reconnect interval and opens one + * WebSocket if none is already open or connecting. + * 2. `open` sends the reverse hello and asks the server to keep the extension + * service worker alive. + * 3. `message` parses client CDP commands and delegates execution through the + * injected `handleCommand` callback. + * 4. `error`/`close` drops the active socket reference and schedules reconnect + * while an endpoint is still configured. + * 5. `stop()` clears the endpoint and reconnect timer, then closes the socket. + */ +export class ReverseWSDownstreamTransport implements ServerDownstreamTransport { + readonly name = "reversews"; + + // Server-owned command executor. Read by message handling; this class never + // interprets routes, custom commands, or middleware itself. + private readonly handleCommand: (message: CdpCommandMessage) => Promise; + + // Server-owned keepalive hook. Called after the reverse socket opens. + private readonly ensureOffscreenKeepAlive: () => unknown; + + // Configured reversews endpoint. Set by start, cleared by stop, read by + // reconnect scheduling. + private endpoint: string | null = null; + + // Reconnect interval currently configured for the endpoint. Set by start and + // read by error/close handlers. + private reconnect_interval_ms = DEFAULT_REVERSE_BRIDGE_RECONNECT_INTERVAL_MS; + + // Active reversews socket. Set by connect, cleared by error/close/stop, read + // by start and emit. + private socket: WebSocket | null = null; + + // Pending reconnect timer. Set by scheduleReconnect, cleared by stop or when + // the timer fires. + private reconnect_timer: ReturnType | null = null; + + constructor({ + handleCommand, + ensureOffscreenKeepAlive, + }: { + handleCommand: (message: CdpCommandMessage) => Promise; + ensureOffscreenKeepAlive: () => unknown; + }) { + this.handleCommand = handleCommand; + this.ensureOffscreenKeepAlive = ensureOffscreenKeepAlive; + } + + /** True when the reversews socket is currently open and can receive events. */ + get connected() { + return this.socket?.readyState === WebSocket.OPEN; + } + + /** Configure and start the reversews downstream connection. */ + start( + endpoint: string, + { + reconnect_interval_ms = DEFAULT_REVERSE_BRIDGE_RECONNECT_INTERVAL_MS, + }: { + reconnect_interval_ms?: number; + } = {}, + ) { + if (!/^wss?:\/\//i.test(endpoint)) { + throw new Error(`reverse proxy endpoint must be a ws:// or wss:// URL, got ${endpoint}.`); + } + this.endpoint = endpoint; + this.reconnect_interval_ms = reconnect_interval_ms; + void this.connect(endpoint).catch(() => { + this.scheduleReconnect(this.reconnect_interval_ms); + }); + return { + upstream_reversews_url: endpoint, + reconnect_interval_ms, + connecting: true, + }; + } + + /** Start the default reversews listener configured into the shipped extension. */ + startDefault() { + return this.start("ws://127.0.0.1:29292", { reconnect_interval_ms: DEFAULT_REVERSE_BRIDGE_RECONNECT_INTERVAL_MS }); + } + + /** Keep reversews alive only for reversews clients; other clients use their own downstream. */ + configure(params: ModCDPConfigureParams) { + if (params.upstream?.upstream_mode === "reversews") return null; + return this.stop("non-reverse downstream connected"); + } + + /** Stop reconnecting and close the active reversews socket. */ + stop(reason = "stopped") { + const upstream_reversews_url = this.endpoint; + this.endpoint = null; + if (this.reconnect_timer) { + clearTimeout(this.reconnect_timer); + this.reconnect_timer = null; + } + const socket = this.socket; + this.socket = null; + if (socket?.readyState === WebSocket.OPEN || socket?.readyState === WebSocket.CONNECTING) { + socket.close(1000, reason); + } + return { upstream_reversews_url, stopped: true, reason }; + } + + /** Emit one CDP event message to the connected reversews client. */ + emit(message: CdpEventMessage) { + if (this.socket?.readyState !== WebSocket.OPEN) return false; + this.socket.send(JSON.stringify(message)); + return true; + } + + /** Return generic status without exposing reversews-specific state to ModCDPServer. */ + status() { + return { + connected: this.connected, + config: this.endpoint + ? { upstream_reversews_url: this.endpoint, reconnect_interval_ms: this.reconnect_interval_ms } + : {}, + }; + } + + private scheduleReconnect(delay_ms: number) { + if (!this.endpoint) return; + if (this.reconnect_timer) return; + this.reconnect_timer = setTimeout(() => { + this.reconnect_timer = null; + if (!this.endpoint) return; + void this.connect(this.endpoint).catch(() => {}); + }, delay_ms); + } + + private async connect(endpoint: string) { + if (this.socket?.readyState === WebSocket.OPEN || this.socket?.readyState === WebSocket.CONNECTING) { + return { + upstream_reversews_url: endpoint, + connected: this.socket.readyState === WebSocket.OPEN, + }; + } + + const ws = new WebSocket(endpoint); + this.socket = ws; + ws.addEventListener("open", () => { + void this.ensureOffscreenKeepAlive(); + ws.send( + JSON.stringify({ + type: "modcdp.reverse.hello", + role: "extension-service-worker", + version: 1, + extension_id: globalThis.chrome?.runtime?.id ?? null, + }), + ); + }); + ws.addEventListener("message", (event) => { + void this.handleMessage(ws, event.data); + }); + ws.addEventListener("error", () => { + if (this.socket === ws) this.socket = null; + this.scheduleReconnect(this.reconnect_interval_ms); + }); + ws.addEventListener("close", () => { + if (this.socket === ws) this.socket = null; + this.scheduleReconnect(this.reconnect_interval_ms); + }); + return { upstream_reversews_url: endpoint, connected: false }; + } + + private async handleMessage(ws: WebSocket, data: unknown) { + let message: CdpCommandMessage; + try { + message = CdpCommandMessageSchema.parse(JSON.parse(typeof data === "string" ? data : String(data))); + } catch { + return; + } + + try { + const result = await this.handleCommand(message); + ws.send(JSON.stringify({ id: message.id, result })); + } catch (error) { + ws.send( + JSON.stringify({ + id: message.id, + error: { + code: -32000, + message: error instanceof Error ? error.message : String(error), + }, + }), + ); + } + } +} diff --git a/js/src/server/ServerDownstreamTransport.ts b/js/src/server/ServerDownstreamTransport.ts new file mode 100644 index 0000000..d23b2c6 --- /dev/null +++ b/js/src/server/ServerDownstreamTransport.ts @@ -0,0 +1,45 @@ +import type { CdpEventMessage, ModCDPConfigureParams, ProtocolPayload } from "../types/modcdp.js"; + +export type ServerDownstreamTransportName = string; + +export type ServerDownstreamTransportStatus = { + connected: boolean; + last_error?: string | null; + attempts?: number; + config?: ProtocolPayload; +}; + +/** + * Generic server-side downstream transport contract. + * + * From ModCDPServer's point of view, downstream means the SDK/client-facing + * connection and upstream means the browser-target-facing connection. A + * downstream transport accepts CDP-shaped commands from a client, delegates + * execution to ModCDPServer, and sends CDP-shaped events/responses back to that + * same client path. + * + * Concrete implementations own all protocol-specific lifecycle and state for + * reverse WebSocket, native messaging, NATS, or any future downstream. + * ModCDPServer only calls these generic lifecycle methods, emits events, and + * reads generic status; it does not branch on downstream protocol names after + * construction. + */ +export type ServerDownstreamTransport = { + // Stable implementation name used only as the status-map key. + readonly name: ServerDownstreamTransportName; + + /** Start the transport's built-in extension-side default, when it has one. */ + startDefault(): ProtocolPayload | null; + + /** Apply a Mod.configure payload and perform any matching lifecycle update. */ + configure(params: ModCDPConfigureParams): ProtocolPayload | null; + + /** Stop accepting or reconnecting downstream clients for this transport. */ + stop(reason?: string): ProtocolPayload | null; + + /** Emit one CDP event to this downstream, returning whether it was sent. */ + emit(message: CdpEventMessage): boolean; + + /** Return protocol-agnostic status for UI/debug surfaces. */ + status(): ServerDownstreamTransportStatus; +}; diff --git a/js/src/server/ServerUpstreamTransport.ts b/js/src/server/ServerUpstreamTransport.ts new file mode 100644 index 0000000..d9b3ba9 --- /dev/null +++ b/js/src/server/ServerUpstreamTransport.ts @@ -0,0 +1,40 @@ +import type { z } from "zod"; +import type { cdp } from "../types/generated/cdp.js"; +import type { CdpCommandSchema, CdpNamedSchema } from "../types/generated/zod/helpers.js"; +import type { CdpDebuggeeCommandParams, ProtocolPayload } from "../types/modcdp.js"; + +export type TargetRoute = { + targetId: cdp.types.ts.Target.TargetID; + sessionId?: cdp.types.ts.Target.SessionID | null; +}; + +export type ServerUpstreamEventListener = ( + payload: ProtocolPayload, + targetId: cdp.types.ts.Target.TargetID | null, + sessionId: cdp.types.ts.Target.SessionID | null, +) => void; + +export type ServerUpstreamTransport = { + getTargets(): Promise; + resolveTargetId(params: CdpDebuggeeCommandParams): Promise; + createTarget(url: string): Promise; + attachToTarget(targetId: cdp.types.ts.Target.TargetID): Promise; + detachFromTarget(sessionId: cdp.types.ts.Target.SessionID): Promise; + send< + Params extends z.ZodType>, + Result extends z.ZodType>, + Name extends string, + >( + command: CdpCommandSchema, + params?: z.input, + route?: TargetRoute, + ): Promise>; + on>( + event: Event, + listener: ( + payload: z.output, + targetId: cdp.types.ts.Target.TargetID | null, + sessionId: cdp.types.ts.Target.SessionID | null, + ) => void, + ): { remove: () => void }; +}; diff --git a/js/src/translate/translate.ts b/js/src/translate/translate.ts index da94e2a..0d05c0d 100644 --- a/js/src/translate/translate.ts +++ b/js/src/translate/translate.ts @@ -10,7 +10,6 @@ import type { ModCDPBindingPayload, ModCDPCustomPayload, ModCDPEvaluateParams, - ModCDPPingParams, ModCDPRoutes, ProtocolParams, ProtocolResult, @@ -29,7 +28,7 @@ export const DEFAULT_CLIENT_ROUTES = { "*.*": "service_worker", } satisfies ModCDPRoutes; -type TranslateOptions = { routes?: ModCDPRoutes; cdpSessionId?: string | null; targetCdpSessionId?: string | null }; +type TranslateOptions = { routes?: ModCDPRoutes; cdpSessionId?: string | null }; function normalizeModCDPName( value: @@ -184,10 +183,6 @@ export function wrapCustomCommand( } function wrapServiceWorkerCommand(method: string, params: ProtocolParams = {}, cdpSessionId: string | null = null) { - if (method === "Mod.ping" && !Object.prototype.hasOwnProperty.call(params, "sent_at")) { - params = { ...(params as ModCDPPingParams), sent_at: Date.now() }; - } - if (method === "Mod.addCustomEvent") { const eventParams = params as { name: any }; const eventName = normalizeModCDPName(eventParams.name); @@ -233,7 +228,7 @@ function wrapServiceWorkerCommand(method: string, params: ProtocolParams = {}, c export function wrapCommandIfNeeded( method: string, params: ProtocolParams = {}, - { routes = DEFAULT_CLIENT_ROUTES, cdpSessionId = null, targetCdpSessionId = null }: TranslateOptions = {}, + { routes = DEFAULT_CLIENT_ROUTES, cdpSessionId = null }: TranslateOptions = {}, ): TranslatedCommand { params = params ?? {}; const route = routeFor(method, routes); @@ -241,7 +236,7 @@ export function wrapCommandIfNeeded( return { route, target: "direct_cdp", - steps: [{ method, params, ...(targetCdpSessionId ? { sessionId: targetCdpSessionId } : {}) }], + steps: [{ method, params, ...(cdpSessionId ? { sessionId: cdpSessionId } : {}) }], }; } if (route === "service_worker") { diff --git a/js/src/types/codegen.ts b/js/src/types/codegen.ts index b215024..e6b2fcd 100755 --- a/js/src/types/codegen.ts +++ b/js/src/types/codegen.ts @@ -174,7 +174,7 @@ for (const d of domains) { } aliases.push(` Mod: {`); for (const base of modcdpCommands) { - const optional = base === "Ping"; + const optional = base === "Ping" || base === "GetTopology"; if (base === "AddCustomCommand") { aliases.push( ` addCustomCommand(name: TName, options?: ModCustomCommandOptions): Promise;`, @@ -297,6 +297,7 @@ const zod_helper = [ `import type { z } from "zod";`, ``, `export type CdpNamedSchema = T & { readonly id: string; readonly name: string; readonly kind: string; meta(): { id: string; name: string; kind: string } };`, + `export type CdpCommandSchema> = z.ZodType>, Result extends z.ZodType> = z.ZodType>, Name extends string = string> = { readonly id: Name; readonly name: Name; readonly kind: "command"; readonly params: Params; readonly result: Result; meta(): { id: Name; name: Name; kind: "command" } };`, `export const withCdpMeta = (schema: T, id: string, kind: string, extra = {}): CdpNamedSchema => {`, ` const meta = { id, name: id, kind, ...extra };`, ` const named = schema.meta(meta);`, @@ -307,6 +308,17 @@ const zod_helper = [ ` });`, ` return named as CdpNamedSchema;`, `};`, + `export const withCdpCommand = >, Result extends z.ZodType>>(id: Name, params: Params, result: Result): CdpCommandSchema => {`, + ` const meta = { id, name: id, kind: "command" as const };`, + ` return {`, + ` id,`, + ` name: id,`, + ` kind: "command",`, + ` params,`, + ` result,`, + ` meta: () => meta,`, + ` };`, + `};`, ``, ]; fs.writeFileSync(path.join(zod_dir, "helpers.ts"), zod_helper.join("\n")); @@ -321,7 +333,7 @@ for (const d of domains) { `// Generated by types/codegen.ts from devtools-protocol@${meta.version}. Do not edit by hand.`, `// @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references.`, `import { z } from "zod";`, - `import { withCdpMeta } from "./helpers.js";`, + `import { withCdpCommand, withCdpMeta } from "./helpers.js";`, ]; for (const ref of [...refs].sort()) domain_zod.push(`import * as ${domain_file(ref)} from "./${domain_file(ref)}.js";`); @@ -343,6 +355,9 @@ for (const d of domains) { domain_zod.push( `export const ${local_name(result(x.name))} = withCdpMeta(${zobj(x.returns || [], d.domain)}, ${JSON.stringify(`${commandName}.result`)}, "commandResult", { method: ${JSON.stringify(commandName)} });`, ); + domain_zod.push( + `export const ${local_name(`${title(x.name)}Command`)} = withCdpCommand(${JSON.stringify(commandName)}, ${local_name(params(x.name))}, ${local_name(result(x.name))});`, + ); } for (const x of d.events || []) domain_zod.push( @@ -359,9 +374,7 @@ for (const d of domains) { for (const x of d.events || []) domain_zod.push(` ${word(event(x.name))}: ${local_name(event(x.name))},`); domain_zod.push(`} as const;`, `export const commands = {`); for (const x of d.commands || []) - domain_zod.push( - ` ${JSON.stringify(`${d.domain}.${x.name}`)}: { params: ${local_name(params(x.name))}, result: ${local_name(result(x.name))} },`, - ); + domain_zod.push(` ${JSON.stringify(`${d.domain}.${x.name}`)}: ${local_name(`${title(x.name)}Command`)},`); domain_zod.push(`} as const;`, `export const events = {`); for (const x of d.events || []) domain_zod.push(` ${JSON.stringify(`${d.domain}.${x.name}`)}: ${local_name(event(x.name))},`); diff --git a/js/src/types/generated/aliases.ts b/js/src/types/generated/aliases.ts index fe5a727..536673d 100644 --- a/js/src/types/generated/aliases.ts +++ b/js/src/types/generated/aliases.ts @@ -13,9 +13,6 @@ export type CdpAliasHooks = { onCustomCommand?: (name: string, params_schema?: z.ZodType | null, result_schema?: z.ZodType | null) => void; onCustomEvent?: (name: string, event_schema?: z.ZodType | null) => void; }; -type ModSchemaInfer = T extends z.ZodType ? TValue : T extends Record ? z.infer> : unknown; -type IsUnion = T extends unknown ? ([U] extends [T] ? false : true) : never; -type UnwrapSingleObject = T extends Record ? IsUnion extends true ? T : T[keyof T] : T; export type ModCustomCommandOptions = { params_schema?: TParamsSchema | null; result_schema?: TResultSchema | null; @@ -1047,19 +1044,14 @@ export type CdpAliases = { }; Mod: { evaluate(params: cdp.types.ts.Mod.EvaluateParams): Promise; - addCustomCommand( - name: TName, - options?: ModCustomCommandOptions, - ): Promise; + addCustomCommand(name: TName, options?: ModCustomCommandOptions): Promise; addCustomCommand(params: cdp.types.ts.Mod.AddCustomCommandParams): Promise; - addCustomEvent( - name: TName, - options?: { event_schema?: TEventSchema | null }, - ): Promise; + addCustomEvent(name: TName, options?: { event_schema?: TEventSchema | null }): Promise; addCustomEvent(params: cdp.types.ts.Mod.AddCustomEventParams): Promise; addMiddleware(params: cdp.types.ts.Mod.AddMiddlewareParams): Promise; configure(params: cdp.types.ts.Mod.ConfigureParams): Promise; ping(params?: cdp.types.ts.Mod.PingParams): Promise; + getTopology(params?: cdp.types.ts.Mod.GetTopologyParams): Promise; }; }; @@ -2103,14 +2095,7 @@ export function createCdpAliases(send: CdpAliasSend, hooks: CdpAliasHooks = {}): return Mod.EvaluateResponse.parse(await send("Mod.evaluate", parsed)); }, addCustomCommand: async (params_or_name?: unknown, options: Record = {}) => { - const input = typeof params_or_name === "string" - ? { - name: params_or_name, - expression: options.expression ?? null, - params_schema: options.params_schema ?? null, - result_schema: options.result_schema ?? null, - } - : params_or_name; + const input = typeof params_or_name === "string" ? { name: params_or_name, expression: options.expression ?? null, params_schema: options.params_schema ?? null, result_schema: options.result_schema ?? null } : params_or_name; const parsed = Mod.AddCustomCommandParams.parse(input ?? {}); const name = normalizeModCDPName(parsed.name); const params_schema = normalizeModCDPPayloadSchema(parsed.params_schema); @@ -2120,9 +2105,7 @@ export function createCdpAliases(send: CdpAliasSend, hooks: CdpAliasHooks = {}): return response; }, addCustomEvent: async (params_or_name?: unknown, options: Record = {}) => { - const input = typeof params_or_name === "string" - ? { name: params_or_name, event_schema: options.event_schema ?? null } - : params_or_name; + const input = typeof params_or_name === "string" ? { name: params_or_name, event_schema: options.event_schema ?? null } : params_or_name; const parsed = Mod.AddCustomEventParams.parse(input ?? {}); const directSchema = Mod.ZodType.safeParse(parsed); if (directSchema.success) { @@ -2152,6 +2135,10 @@ export function createCdpAliases(send: CdpAliasSend, hooks: CdpAliasHooks = {}): const parsed = Mod.PingParams.parse(params ?? {}); return Mod.PingResponse.parse(await send("Mod.ping", parsed)); }, + getTopology: async (params?: unknown) => { + const parsed = Mod.GetTopologyParams.parse(params ?? {}); + return Mod.GetTopologyResponse.parse(await send("Mod.getTopology", parsed)); + }, }, }; } diff --git a/js/src/types/generated/cdp.ts b/js/src/types/generated/cdp.ts index 5b536ab..422e293 100644 --- a/js/src/types/generated/cdp.ts +++ b/js/src/types/generated/cdp.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. import { zod, commands, events, types as runtimeTypes } from "./zod.js"; import type { z } from "zod"; -import type { ModCDPRoutes, ModCDPCustomPayload, ModCDPNamedValue, ModCDPName, ModCDPZodType, ModCDPPayloadShape, ModCDPPayloadSchemaSpec, ModCDPEvaluateParams, ModCDPAddCustomCommandParams, ModCDPAddCustomEventObjectParams, ModCDPAddCustomEventParams, ModCDPAddMiddlewareParams, ModCDPConfigureParams, ModCDPPingParams, ModCDPPongEvent, ModCDPPingLatency, ModCDPCommandParams, ModCDPCommandResult, ModCDPEvaluateResponse, ModCDPAddCustomCommandResponse, ModCDPAddCustomEventResponse, ModCDPAddMiddlewareResponse, ModCDPConfigureResponse, ModCDPPingResponse, ModCDPBindingPayload, ModCDPCustomCommandRegistration, ModCDPCustomEventRegistration, ModCDPMiddlewareRegistration } from "../modcdp.js"; +import type { ModCDPRoutes, ModCDPCustomPayload, ModCDPNamedValue, ModCDPName, ModCDPZodType, ModCDPPayloadShape, ModCDPPayloadSchemaSpec, ModCDPEvaluateParams, ModCDPAddCustomCommandParams, ModCDPAddCustomEventObjectParams, ModCDPAddCustomEventParams, ModCDPAddMiddlewareParams, ModCDPLauncherOptions, ModCDPUpstreamOptions, ModCDPClientOptions, ModCDPServerOptions, ModCDPConfigureParams, ModCDPPingParams, ModCDPPongEvent, ModCDPPingLatency, ModCDPGetTopologyParams, ModCDPTopologyFrame, ModCDPTopologyDomRoot, ModCDPTopologyTarget, ModCDPTopologyExecutionContext, ModCDPTopology, ModCDPCommandParams, ModCDPCommandResult, ModCDPEvaluateResponse, ModCDPGetTopologyResponse, ModCDPAddCustomCommandResponse, ModCDPAddCustomEventResponse, ModCDPAddMiddlewareResponse, ModCDPConfigureResponse, ModCDPPingResponse, ModCDPBindingPayload, ModCDPCustomCommandRegistration, ModCDPCustomEventRegistration, ModCDPMiddlewareRegistration } from "../modcdp.js"; export const REQUEST = "request" as const; export const RESPONSE = "response" as const; @@ -35,13 +35,24 @@ export namespace cdp { export type AddCustomEventObjectParams = ModCDPAddCustomEventObjectParams; export type AddCustomEventParams = ModCDPAddCustomEventParams; export type AddMiddlewareParams = ModCDPAddMiddlewareParams; + export type LauncherOptions = ModCDPLauncherOptions; + export type UpstreamOptions = ModCDPUpstreamOptions; + export type ClientOptions = ModCDPClientOptions; + export type ServerOptions = ModCDPServerOptions; export type ConfigureParams = ModCDPConfigureParams; export type PingParams = ModCDPPingParams; export type PongEvent = ModCDPPongEvent; export type PingLatency = ModCDPPingLatency; + export type GetTopologyParams = ModCDPGetTopologyParams; + export type TopologyFrame = ModCDPTopologyFrame; + export type TopologyDomRoot = ModCDPTopologyDomRoot; + export type TopologyTarget = ModCDPTopologyTarget; + export type TopologyExecutionContext = ModCDPTopologyExecutionContext; + export type Topology = ModCDPTopology; export type CommandParams = ModCDPCommandParams; export type CommandResult = ModCDPCommandResult; export type EvaluateResponse = ModCDPEvaluateResponse; + export type GetTopologyResponse = ModCDPGetTopologyResponse; export type AddCustomCommandResponse = ModCDPAddCustomCommandResponse; export type AddCustomEventResponse = ModCDPAddCustomEventResponse; export type AddMiddlewareResponse = ModCDPAddMiddlewareResponse; diff --git a/js/src/types/generated/zod/Accessibility.ts b/js/src/types/generated/zod/Accessibility.ts index 37f3806..9a92d90 100644 --- a/js/src/types/generated/zod/Accessibility.ts +++ b/js/src/types/generated/zod/Accessibility.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; import * as Page from "./Page.js"; import * as Runtime from "./Runtime.js"; @@ -18,20 +18,28 @@ export const AXPropertyName = withCdpMeta(z.enum(["actions", "busy", "disabled", export const AXNode = withCdpMeta(z.object({ "nodeId": z.lazy(() => AXNodeId), "ignored": z.boolean(), "ignoredReasons": z.array(z.lazy(() => AXProperty)).optional(), "role": z.lazy(() => AXValue).optional(), "chromeRole": z.lazy(() => AXValue).optional(), "name": z.lazy(() => AXValue).optional(), "description": z.lazy(() => AXValue).optional(), "value": z.lazy(() => AXValue).optional(), "properties": z.array(z.lazy(() => AXProperty)).optional(), "parentId": z.lazy(() => AXNodeId).optional(), "childIds": z.array(z.lazy(() => AXNodeId)).optional(), "backendDOMNodeId": z.lazy(() => DOM.BackendNodeId).optional(), "frameId": z.lazy(() => Page.FrameId).optional() }).passthrough(), "Accessibility.AXNode", "type"); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Accessibility.disable.params", "commandParams", { method: "Accessibility.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Accessibility.disable.result", "commandResult", { method: "Accessibility.disable" }); +export const DisableCommand = withCdpCommand("Accessibility.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "Accessibility.enable.params", "commandParams", { method: "Accessibility.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Accessibility.enable.result", "commandResult", { method: "Accessibility.enable" }); +export const EnableCommand = withCdpCommand("Accessibility.enable", EnableParams, EnableResult); export const GetPartialAXTreeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId).optional(), "backendNodeId": z.lazy(() => DOM.BackendNodeId).optional(), "objectId": z.lazy(() => Runtime.RemoteObjectId).optional(), "fetchRelatives": z.boolean().optional() }).passthrough(), "Accessibility.getPartialAXTree.params", "commandParams", { method: "Accessibility.getPartialAXTree" }); export const GetPartialAXTreeResult = withCdpMeta(z.object({ "nodes": z.array(z.lazy(() => AXNode)) }).passthrough(), "Accessibility.getPartialAXTree.result", "commandResult", { method: "Accessibility.getPartialAXTree" }); +export const GetPartialAXTreeCommand = withCdpCommand("Accessibility.getPartialAXTree", GetPartialAXTreeParams, GetPartialAXTreeResult); export const GetFullAXTreeParams = withCdpMeta(z.object({ "depth": z.number().int().optional(), "frameId": z.lazy(() => Page.FrameId).optional() }).passthrough(), "Accessibility.getFullAXTree.params", "commandParams", { method: "Accessibility.getFullAXTree" }); export const GetFullAXTreeResult = withCdpMeta(z.object({ "nodes": z.array(z.lazy(() => AXNode)) }).passthrough(), "Accessibility.getFullAXTree.result", "commandResult", { method: "Accessibility.getFullAXTree" }); +export const GetFullAXTreeCommand = withCdpCommand("Accessibility.getFullAXTree", GetFullAXTreeParams, GetFullAXTreeResult); export const GetRootAXNodeParams = withCdpMeta(z.object({ "frameId": z.lazy(() => Page.FrameId).optional() }).passthrough(), "Accessibility.getRootAXNode.params", "commandParams", { method: "Accessibility.getRootAXNode" }); export const GetRootAXNodeResult = withCdpMeta(z.object({ "node": z.lazy(() => AXNode) }).passthrough(), "Accessibility.getRootAXNode.result", "commandResult", { method: "Accessibility.getRootAXNode" }); +export const GetRootAXNodeCommand = withCdpCommand("Accessibility.getRootAXNode", GetRootAXNodeParams, GetRootAXNodeResult); export const GetAXNodeAndAncestorsParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId).optional(), "backendNodeId": z.lazy(() => DOM.BackendNodeId).optional(), "objectId": z.lazy(() => Runtime.RemoteObjectId).optional() }).passthrough(), "Accessibility.getAXNodeAndAncestors.params", "commandParams", { method: "Accessibility.getAXNodeAndAncestors" }); export const GetAXNodeAndAncestorsResult = withCdpMeta(z.object({ "nodes": z.array(z.lazy(() => AXNode)) }).passthrough(), "Accessibility.getAXNodeAndAncestors.result", "commandResult", { method: "Accessibility.getAXNodeAndAncestors" }); +export const GetAXNodeAndAncestorsCommand = withCdpCommand("Accessibility.getAXNodeAndAncestors", GetAXNodeAndAncestorsParams, GetAXNodeAndAncestorsResult); export const GetChildAXNodesParams = withCdpMeta(z.object({ "id": z.lazy(() => AXNodeId), "frameId": z.lazy(() => Page.FrameId).optional() }).passthrough(), "Accessibility.getChildAXNodes.params", "commandParams", { method: "Accessibility.getChildAXNodes" }); export const GetChildAXNodesResult = withCdpMeta(z.object({ "nodes": z.array(z.lazy(() => AXNode)) }).passthrough(), "Accessibility.getChildAXNodes.result", "commandResult", { method: "Accessibility.getChildAXNodes" }); +export const GetChildAXNodesCommand = withCdpCommand("Accessibility.getChildAXNodes", GetChildAXNodesParams, GetChildAXNodesResult); export const QueryAXTreeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId).optional(), "backendNodeId": z.lazy(() => DOM.BackendNodeId).optional(), "objectId": z.lazy(() => Runtime.RemoteObjectId).optional(), "accessibleName": z.string().optional(), "role": z.string().optional() }).passthrough(), "Accessibility.queryAXTree.params", "commandParams", { method: "Accessibility.queryAXTree" }); export const QueryAXTreeResult = withCdpMeta(z.object({ "nodes": z.array(z.lazy(() => AXNode)) }).passthrough(), "Accessibility.queryAXTree.result", "commandResult", { method: "Accessibility.queryAXTree" }); +export const QueryAXTreeCommand = withCdpCommand("Accessibility.queryAXTree", QueryAXTreeParams, QueryAXTreeResult); export const LoadCompleteEvent = withCdpMeta(z.object({ "root": z.lazy(() => AXNode) }).passthrough(), "Accessibility.loadComplete", "event", { phase: "event" }); export const NodesUpdatedEvent = withCdpMeta(z.object({ "nodes": z.array(z.lazy(() => AXNode)) }).passthrough(), "Accessibility.nodesUpdated", "event", { phase: "event" }); @@ -66,14 +74,14 @@ export const zod = { NodesUpdatedEvent: NodesUpdatedEvent, } as const; export const commands = { - "Accessibility.disable": { params: DisableParams, result: DisableResult }, - "Accessibility.enable": { params: EnableParams, result: EnableResult }, - "Accessibility.getPartialAXTree": { params: GetPartialAXTreeParams, result: GetPartialAXTreeResult }, - "Accessibility.getFullAXTree": { params: GetFullAXTreeParams, result: GetFullAXTreeResult }, - "Accessibility.getRootAXNode": { params: GetRootAXNodeParams, result: GetRootAXNodeResult }, - "Accessibility.getAXNodeAndAncestors": { params: GetAXNodeAndAncestorsParams, result: GetAXNodeAndAncestorsResult }, - "Accessibility.getChildAXNodes": { params: GetChildAXNodesParams, result: GetChildAXNodesResult }, - "Accessibility.queryAXTree": { params: QueryAXTreeParams, result: QueryAXTreeResult }, + "Accessibility.disable": DisableCommand, + "Accessibility.enable": EnableCommand, + "Accessibility.getPartialAXTree": GetPartialAXTreeCommand, + "Accessibility.getFullAXTree": GetFullAXTreeCommand, + "Accessibility.getRootAXNode": GetRootAXNodeCommand, + "Accessibility.getAXNodeAndAncestors": GetAXNodeAndAncestorsCommand, + "Accessibility.getChildAXNodes": GetChildAXNodesCommand, + "Accessibility.queryAXTree": QueryAXTreeCommand, } as const; export const events = { "Accessibility.loadComplete": LoadCompleteEvent, diff --git a/js/src/types/generated/zod/Animation.ts b/js/src/types/generated/zod/Animation.ts index b1726d7..e3af7a3 100644 --- a/js/src/types/generated/zod/Animation.ts +++ b/js/src/types/generated/zod/Animation.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; import * as Runtime from "./Runtime.js"; @@ -12,24 +12,34 @@ export const KeyframesRule = withCdpMeta(z.object({ "name": z.string().optional( export const KeyframeStyle = withCdpMeta(z.object({ "offset": z.string(), "easing": z.string() }).passthrough(), "Animation.KeyframeStyle", "type"); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Animation.disable.params", "commandParams", { method: "Animation.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Animation.disable.result", "commandResult", { method: "Animation.disable" }); +export const DisableCommand = withCdpCommand("Animation.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "Animation.enable.params", "commandParams", { method: "Animation.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Animation.enable.result", "commandResult", { method: "Animation.enable" }); +export const EnableCommand = withCdpCommand("Animation.enable", EnableParams, EnableResult); export const GetCurrentTimeParams = withCdpMeta(z.object({ "id": z.string() }).passthrough(), "Animation.getCurrentTime.params", "commandParams", { method: "Animation.getCurrentTime" }); export const GetCurrentTimeResult = withCdpMeta(z.object({ "currentTime": z.number() }).passthrough(), "Animation.getCurrentTime.result", "commandResult", { method: "Animation.getCurrentTime" }); +export const GetCurrentTimeCommand = withCdpCommand("Animation.getCurrentTime", GetCurrentTimeParams, GetCurrentTimeResult); export const GetPlaybackRateParams = withCdpMeta(z.object({ }).passthrough(), "Animation.getPlaybackRate.params", "commandParams", { method: "Animation.getPlaybackRate" }); export const GetPlaybackRateResult = withCdpMeta(z.object({ "playbackRate": z.number() }).passthrough(), "Animation.getPlaybackRate.result", "commandResult", { method: "Animation.getPlaybackRate" }); +export const GetPlaybackRateCommand = withCdpCommand("Animation.getPlaybackRate", GetPlaybackRateParams, GetPlaybackRateResult); export const ReleaseAnimationsParams = withCdpMeta(z.object({ "animations": z.array(z.string()) }).passthrough(), "Animation.releaseAnimations.params", "commandParams", { method: "Animation.releaseAnimations" }); export const ReleaseAnimationsResult = withCdpMeta(z.object({ }).passthrough(), "Animation.releaseAnimations.result", "commandResult", { method: "Animation.releaseAnimations" }); +export const ReleaseAnimationsCommand = withCdpCommand("Animation.releaseAnimations", ReleaseAnimationsParams, ReleaseAnimationsResult); export const ResolveAnimationParams = withCdpMeta(z.object({ "animationId": z.string() }).passthrough(), "Animation.resolveAnimation.params", "commandParams", { method: "Animation.resolveAnimation" }); export const ResolveAnimationResult = withCdpMeta(z.object({ "remoteObject": z.lazy(() => Runtime.RemoteObject) }).passthrough(), "Animation.resolveAnimation.result", "commandResult", { method: "Animation.resolveAnimation" }); +export const ResolveAnimationCommand = withCdpCommand("Animation.resolveAnimation", ResolveAnimationParams, ResolveAnimationResult); export const SeekAnimationsParams = withCdpMeta(z.object({ "animations": z.array(z.string()), "currentTime": z.number() }).passthrough(), "Animation.seekAnimations.params", "commandParams", { method: "Animation.seekAnimations" }); export const SeekAnimationsResult = withCdpMeta(z.object({ }).passthrough(), "Animation.seekAnimations.result", "commandResult", { method: "Animation.seekAnimations" }); +export const SeekAnimationsCommand = withCdpCommand("Animation.seekAnimations", SeekAnimationsParams, SeekAnimationsResult); export const SetPausedParams = withCdpMeta(z.object({ "animations": z.array(z.string()), "paused": z.boolean() }).passthrough(), "Animation.setPaused.params", "commandParams", { method: "Animation.setPaused" }); export const SetPausedResult = withCdpMeta(z.object({ }).passthrough(), "Animation.setPaused.result", "commandResult", { method: "Animation.setPaused" }); +export const SetPausedCommand = withCdpCommand("Animation.setPaused", SetPausedParams, SetPausedResult); export const SetPlaybackRateParams = withCdpMeta(z.object({ "playbackRate": z.number() }).passthrough(), "Animation.setPlaybackRate.params", "commandParams", { method: "Animation.setPlaybackRate" }); export const SetPlaybackRateResult = withCdpMeta(z.object({ }).passthrough(), "Animation.setPlaybackRate.result", "commandResult", { method: "Animation.setPlaybackRate" }); +export const SetPlaybackRateCommand = withCdpCommand("Animation.setPlaybackRate", SetPlaybackRateParams, SetPlaybackRateResult); export const SetTimingParams = withCdpMeta(z.object({ "animationId": z.string(), "duration": z.number(), "delay": z.number() }).passthrough(), "Animation.setTiming.params", "commandParams", { method: "Animation.setTiming" }); export const SetTimingResult = withCdpMeta(z.object({ }).passthrough(), "Animation.setTiming.result", "commandResult", { method: "Animation.setTiming" }); +export const SetTimingCommand = withCdpCommand("Animation.setTiming", SetTimingParams, SetTimingResult); export const AnimationCanceledEvent = withCdpMeta(z.object({ "id": z.string() }).passthrough(), "Animation.animationCanceled", "event", { phase: "event" }); export const AnimationCreatedEvent = withCdpMeta(z.object({ "id": z.string() }).passthrough(), "Animation.animationCreated", "event", { phase: "event" }); export const AnimationStartedEvent = withCdpMeta(z.object({ "animation": z.lazy(() => Animation) }).passthrough(), "Animation.animationStarted", "event", { phase: "event" }); @@ -67,16 +77,16 @@ export const zod = { AnimationUpdatedEvent: AnimationUpdatedEvent, } as const; export const commands = { - "Animation.disable": { params: DisableParams, result: DisableResult }, - "Animation.enable": { params: EnableParams, result: EnableResult }, - "Animation.getCurrentTime": { params: GetCurrentTimeParams, result: GetCurrentTimeResult }, - "Animation.getPlaybackRate": { params: GetPlaybackRateParams, result: GetPlaybackRateResult }, - "Animation.releaseAnimations": { params: ReleaseAnimationsParams, result: ReleaseAnimationsResult }, - "Animation.resolveAnimation": { params: ResolveAnimationParams, result: ResolveAnimationResult }, - "Animation.seekAnimations": { params: SeekAnimationsParams, result: SeekAnimationsResult }, - "Animation.setPaused": { params: SetPausedParams, result: SetPausedResult }, - "Animation.setPlaybackRate": { params: SetPlaybackRateParams, result: SetPlaybackRateResult }, - "Animation.setTiming": { params: SetTimingParams, result: SetTimingResult }, + "Animation.disable": DisableCommand, + "Animation.enable": EnableCommand, + "Animation.getCurrentTime": GetCurrentTimeCommand, + "Animation.getPlaybackRate": GetPlaybackRateCommand, + "Animation.releaseAnimations": ReleaseAnimationsCommand, + "Animation.resolveAnimation": ResolveAnimationCommand, + "Animation.seekAnimations": SeekAnimationsCommand, + "Animation.setPaused": SetPausedCommand, + "Animation.setPlaybackRate": SetPlaybackRateCommand, + "Animation.setTiming": SetTimingCommand, } as const; export const events = { "Animation.animationCanceled": AnimationCanceledEvent, diff --git a/js/src/types/generated/zod/Audits.ts b/js/src/types/generated/zod/Audits.ts index 7e41056..df57a82 100644 --- a/js/src/types/generated/zod/Audits.ts +++ b/js/src/types/generated/zod/Audits.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; import * as Network from "./Network.js"; import * as Page from "./Page.js"; @@ -75,12 +75,16 @@ export const IssueId = withCdpMeta(z.string(), "Audits.IssueId", "type"); export const InspectorIssue = withCdpMeta(z.object({ "code": z.lazy(() => InspectorIssueCode), "details": z.lazy(() => InspectorIssueDetails), "issueId": z.lazy(() => IssueId).optional() }).passthrough(), "Audits.InspectorIssue", "type"); export const GetEncodedResponseParams = withCdpMeta(z.object({ "requestId": z.lazy(() => Network.RequestId), "encoding": z.enum(["webp", "jpeg", "png"]), "quality": z.number().optional(), "sizeOnly": z.boolean().optional() }).passthrough(), "Audits.getEncodedResponse.params", "commandParams", { method: "Audits.getEncodedResponse" }); export const GetEncodedResponseResult = withCdpMeta(z.object({ "body": z.string().optional(), "originalSize": z.number().int(), "encodedSize": z.number().int() }).passthrough(), "Audits.getEncodedResponse.result", "commandResult", { method: "Audits.getEncodedResponse" }); +export const GetEncodedResponseCommand = withCdpCommand("Audits.getEncodedResponse", GetEncodedResponseParams, GetEncodedResponseResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Audits.disable.params", "commandParams", { method: "Audits.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Audits.disable.result", "commandResult", { method: "Audits.disable" }); +export const DisableCommand = withCdpCommand("Audits.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "Audits.enable.params", "commandParams", { method: "Audits.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Audits.enable.result", "commandResult", { method: "Audits.enable" }); +export const EnableCommand = withCdpCommand("Audits.enable", EnableParams, EnableResult); export const CheckFormsIssuesParams = withCdpMeta(z.object({ }).passthrough(), "Audits.checkFormsIssues.params", "commandParams", { method: "Audits.checkFormsIssues" }); export const CheckFormsIssuesResult = withCdpMeta(z.object({ "formIssues": z.array(z.lazy(() => GenericIssueDetails)) }).passthrough(), "Audits.checkFormsIssues.result", "commandResult", { method: "Audits.checkFormsIssues" }); +export const CheckFormsIssuesCommand = withCdpCommand("Audits.checkFormsIssues", CheckFormsIssuesParams, CheckFormsIssuesResult); export const IssueAddedEvent = withCdpMeta(z.object({ "issue": z.lazy(() => InspectorIssue) }).passthrough(), "Audits.issueAdded", "event", { phase: "event" }); export const zod = { @@ -161,10 +165,10 @@ export const zod = { IssueAddedEvent: IssueAddedEvent, } as const; export const commands = { - "Audits.getEncodedResponse": { params: GetEncodedResponseParams, result: GetEncodedResponseResult }, - "Audits.disable": { params: DisableParams, result: DisableResult }, - "Audits.enable": { params: EnableParams, result: EnableResult }, - "Audits.checkFormsIssues": { params: CheckFormsIssuesParams, result: CheckFormsIssuesResult }, + "Audits.getEncodedResponse": GetEncodedResponseCommand, + "Audits.disable": DisableCommand, + "Audits.enable": EnableCommand, + "Audits.checkFormsIssues": CheckFormsIssuesCommand, } as const; export const events = { "Audits.issueAdded": IssueAddedEvent, diff --git a/js/src/types/generated/zod/Autofill.ts b/js/src/types/generated/zod/Autofill.ts index 63d0d89..5de650e 100644 --- a/js/src/types/generated/zod/Autofill.ts +++ b/js/src/types/generated/zod/Autofill.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; import * as Page from "./Page.js"; @@ -14,12 +14,16 @@ export const FillingStrategy = withCdpMeta(z.enum(["autocompleteAttribute", "aut export const FilledField = withCdpMeta(z.object({ "htmlType": z.string(), "id": z.string(), "name": z.string(), "value": z.string(), "autofillType": z.string(), "fillingStrategy": z.lazy(() => FillingStrategy), "frameId": z.lazy(() => Page.FrameId), "fieldId": z.lazy(() => DOM.BackendNodeId) }).passthrough(), "Autofill.FilledField", "type"); export const TriggerParams = withCdpMeta(z.object({ "fieldId": z.lazy(() => DOM.BackendNodeId), "frameId": z.lazy(() => Page.FrameId).optional(), "card": z.lazy(() => CreditCard).optional(), "address": z.lazy(() => Address).optional() }).passthrough(), "Autofill.trigger.params", "commandParams", { method: "Autofill.trigger" }); export const TriggerResult = withCdpMeta(z.object({ }).passthrough(), "Autofill.trigger.result", "commandResult", { method: "Autofill.trigger" }); +export const TriggerCommand = withCdpCommand("Autofill.trigger", TriggerParams, TriggerResult); export const SetAddressesParams = withCdpMeta(z.object({ "addresses": z.array(z.lazy(() => Address)) }).passthrough(), "Autofill.setAddresses.params", "commandParams", { method: "Autofill.setAddresses" }); export const SetAddressesResult = withCdpMeta(z.object({ }).passthrough(), "Autofill.setAddresses.result", "commandResult", { method: "Autofill.setAddresses" }); +export const SetAddressesCommand = withCdpCommand("Autofill.setAddresses", SetAddressesParams, SetAddressesResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Autofill.disable.params", "commandParams", { method: "Autofill.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Autofill.disable.result", "commandResult", { method: "Autofill.disable" }); +export const DisableCommand = withCdpCommand("Autofill.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "Autofill.enable.params", "commandParams", { method: "Autofill.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Autofill.enable.result", "commandResult", { method: "Autofill.enable" }); +export const EnableCommand = withCdpCommand("Autofill.enable", EnableParams, EnableResult); export const AddressFormFilledEvent = withCdpMeta(z.object({ "filledFields": z.array(z.lazy(() => FilledField)), "addressUi": z.lazy(() => AddressUI) }).passthrough(), "Autofill.addressFormFilled", "event", { phase: "event" }); export const zod = { @@ -41,10 +45,10 @@ export const zod = { AddressFormFilledEvent: AddressFormFilledEvent, } as const; export const commands = { - "Autofill.trigger": { params: TriggerParams, result: TriggerResult }, - "Autofill.setAddresses": { params: SetAddressesParams, result: SetAddressesResult }, - "Autofill.disable": { params: DisableParams, result: DisableResult }, - "Autofill.enable": { params: EnableParams, result: EnableResult }, + "Autofill.trigger": TriggerCommand, + "Autofill.setAddresses": SetAddressesCommand, + "Autofill.disable": DisableCommand, + "Autofill.enable": EnableCommand, } as const; export const events = { "Autofill.addressFormFilled": AddressFormFilledEvent, diff --git a/js/src/types/generated/zod/BackgroundService.ts b/js/src/types/generated/zod/BackgroundService.ts index 1991f65..34659f4 100644 --- a/js/src/types/generated/zod/BackgroundService.ts +++ b/js/src/types/generated/zod/BackgroundService.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Network from "./Network.js"; import * as ServiceWorker from "./ServiceWorker.js"; @@ -10,12 +10,16 @@ export const EventMetadata = withCdpMeta(z.object({ "key": z.string(), "value": export const BackgroundServiceEvent = withCdpMeta(z.object({ "timestamp": z.lazy(() => Network.TimeSinceEpoch), "origin": z.string(), "serviceWorkerRegistrationId": z.lazy(() => ServiceWorker.RegistrationID), "service": z.lazy(() => ServiceName), "eventName": z.string(), "instanceId": z.string(), "eventMetadata": z.array(z.lazy(() => EventMetadata)), "storageKey": z.string() }).passthrough(), "BackgroundService.BackgroundServiceEvent", "type"); export const StartObservingParams = withCdpMeta(z.object({ "service": z.lazy(() => ServiceName) }).passthrough(), "BackgroundService.startObserving.params", "commandParams", { method: "BackgroundService.startObserving" }); export const StartObservingResult = withCdpMeta(z.object({ }).passthrough(), "BackgroundService.startObserving.result", "commandResult", { method: "BackgroundService.startObserving" }); +export const StartObservingCommand = withCdpCommand("BackgroundService.startObserving", StartObservingParams, StartObservingResult); export const StopObservingParams = withCdpMeta(z.object({ "service": z.lazy(() => ServiceName) }).passthrough(), "BackgroundService.stopObserving.params", "commandParams", { method: "BackgroundService.stopObserving" }); export const StopObservingResult = withCdpMeta(z.object({ }).passthrough(), "BackgroundService.stopObserving.result", "commandResult", { method: "BackgroundService.stopObserving" }); +export const StopObservingCommand = withCdpCommand("BackgroundService.stopObserving", StopObservingParams, StopObservingResult); export const SetRecordingParams = withCdpMeta(z.object({ "shouldRecord": z.boolean(), "service": z.lazy(() => ServiceName) }).passthrough(), "BackgroundService.setRecording.params", "commandParams", { method: "BackgroundService.setRecording" }); export const SetRecordingResult = withCdpMeta(z.object({ }).passthrough(), "BackgroundService.setRecording.result", "commandResult", { method: "BackgroundService.setRecording" }); +export const SetRecordingCommand = withCdpCommand("BackgroundService.setRecording", SetRecordingParams, SetRecordingResult); export const ClearEventsParams = withCdpMeta(z.object({ "service": z.lazy(() => ServiceName) }).passthrough(), "BackgroundService.clearEvents.params", "commandParams", { method: "BackgroundService.clearEvents" }); export const ClearEventsResult = withCdpMeta(z.object({ }).passthrough(), "BackgroundService.clearEvents.result", "commandResult", { method: "BackgroundService.clearEvents" }); +export const ClearEventsCommand = withCdpCommand("BackgroundService.clearEvents", ClearEventsParams, ClearEventsResult); export const RecordingStateChangedEvent = withCdpMeta(z.object({ "isRecording": z.boolean(), "service": z.lazy(() => ServiceName) }).passthrough(), "BackgroundService.recordingStateChanged", "event", { phase: "event" }); export const BackgroundServiceEventReceivedEvent = withCdpMeta(z.object({ "backgroundServiceEvent": z.lazy(() => BackgroundServiceEvent) }).passthrough(), "BackgroundService.backgroundServiceEventReceived", "event", { phase: "event" }); @@ -35,10 +39,10 @@ export const zod = { BackgroundServiceEventReceivedEvent: BackgroundServiceEventReceivedEvent, } as const; export const commands = { - "BackgroundService.startObserving": { params: StartObservingParams, result: StartObservingResult }, - "BackgroundService.stopObserving": { params: StopObservingParams, result: StopObservingResult }, - "BackgroundService.setRecording": { params: SetRecordingParams, result: SetRecordingResult }, - "BackgroundService.clearEvents": { params: ClearEventsParams, result: ClearEventsResult }, + "BackgroundService.startObserving": StartObservingCommand, + "BackgroundService.stopObserving": StopObservingCommand, + "BackgroundService.setRecording": SetRecordingCommand, + "BackgroundService.clearEvents": ClearEventsCommand, } as const; export const events = { "BackgroundService.recordingStateChanged": RecordingStateChangedEvent, diff --git a/js/src/types/generated/zod/BluetoothEmulation.ts b/js/src/types/generated/zod/BluetoothEmulation.ts index 53c0624..55fda5a 100644 --- a/js/src/types/generated/zod/BluetoothEmulation.ts +++ b/js/src/types/generated/zod/BluetoothEmulation.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const CentralState = withCdpMeta(z.enum(["absent", "powered-off", "powered-on"]), "BluetoothEmulation.CentralState", "type"); export const GATTOperationType = withCdpMeta(z.enum(["connection", "discovery"]), "BluetoothEmulation.GATTOperationType", "type"); @@ -14,34 +14,49 @@ export const ScanEntry = withCdpMeta(z.object({ "deviceAddress": z.string(), "rs export const CharacteristicProperties = withCdpMeta(z.object({ "broadcast": z.boolean().optional(), "read": z.boolean().optional(), "writeWithoutResponse": z.boolean().optional(), "write": z.boolean().optional(), "notify": z.boolean().optional(), "indicate": z.boolean().optional(), "authenticatedSignedWrites": z.boolean().optional(), "extendedProperties": z.boolean().optional() }).passthrough(), "BluetoothEmulation.CharacteristicProperties", "type"); export const EnableParams = withCdpMeta(z.object({ "state": z.lazy(() => CentralState), "leSupported": z.boolean() }).passthrough(), "BluetoothEmulation.enable.params", "commandParams", { method: "BluetoothEmulation.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "BluetoothEmulation.enable.result", "commandResult", { method: "BluetoothEmulation.enable" }); +export const EnableCommand = withCdpCommand("BluetoothEmulation.enable", EnableParams, EnableResult); export const SetSimulatedCentralStateParams = withCdpMeta(z.object({ "state": z.lazy(() => CentralState) }).passthrough(), "BluetoothEmulation.setSimulatedCentralState.params", "commandParams", { method: "BluetoothEmulation.setSimulatedCentralState" }); export const SetSimulatedCentralStateResult = withCdpMeta(z.object({ }).passthrough(), "BluetoothEmulation.setSimulatedCentralState.result", "commandResult", { method: "BluetoothEmulation.setSimulatedCentralState" }); +export const SetSimulatedCentralStateCommand = withCdpCommand("BluetoothEmulation.setSimulatedCentralState", SetSimulatedCentralStateParams, SetSimulatedCentralStateResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "BluetoothEmulation.disable.params", "commandParams", { method: "BluetoothEmulation.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "BluetoothEmulation.disable.result", "commandResult", { method: "BluetoothEmulation.disable" }); +export const DisableCommand = withCdpCommand("BluetoothEmulation.disable", DisableParams, DisableResult); export const SimulatePreconnectedPeripheralParams = withCdpMeta(z.object({ "address": z.string(), "name": z.string(), "manufacturerData": z.array(z.lazy(() => ManufacturerData)), "knownServiceUuids": z.array(z.string()) }).passthrough(), "BluetoothEmulation.simulatePreconnectedPeripheral.params", "commandParams", { method: "BluetoothEmulation.simulatePreconnectedPeripheral" }); export const SimulatePreconnectedPeripheralResult = withCdpMeta(z.object({ }).passthrough(), "BluetoothEmulation.simulatePreconnectedPeripheral.result", "commandResult", { method: "BluetoothEmulation.simulatePreconnectedPeripheral" }); +export const SimulatePreconnectedPeripheralCommand = withCdpCommand("BluetoothEmulation.simulatePreconnectedPeripheral", SimulatePreconnectedPeripheralParams, SimulatePreconnectedPeripheralResult); export const SimulateAdvertisementParams = withCdpMeta(z.object({ "entry": z.lazy(() => ScanEntry) }).passthrough(), "BluetoothEmulation.simulateAdvertisement.params", "commandParams", { method: "BluetoothEmulation.simulateAdvertisement" }); export const SimulateAdvertisementResult = withCdpMeta(z.object({ }).passthrough(), "BluetoothEmulation.simulateAdvertisement.result", "commandResult", { method: "BluetoothEmulation.simulateAdvertisement" }); +export const SimulateAdvertisementCommand = withCdpCommand("BluetoothEmulation.simulateAdvertisement", SimulateAdvertisementParams, SimulateAdvertisementResult); export const SimulateGATTOperationResponseParams = withCdpMeta(z.object({ "address": z.string(), "type": z.lazy(() => GATTOperationType), "code": z.number().int() }).passthrough(), "BluetoothEmulation.simulateGATTOperationResponse.params", "commandParams", { method: "BluetoothEmulation.simulateGATTOperationResponse" }); export const SimulateGATTOperationResponseResult = withCdpMeta(z.object({ }).passthrough(), "BluetoothEmulation.simulateGATTOperationResponse.result", "commandResult", { method: "BluetoothEmulation.simulateGATTOperationResponse" }); +export const SimulateGATTOperationResponseCommand = withCdpCommand("BluetoothEmulation.simulateGATTOperationResponse", SimulateGATTOperationResponseParams, SimulateGATTOperationResponseResult); export const SimulateCharacteristicOperationResponseParams = withCdpMeta(z.object({ "characteristicId": z.string(), "type": z.lazy(() => CharacteristicOperationType), "code": z.number().int(), "data": z.string().optional() }).passthrough(), "BluetoothEmulation.simulateCharacteristicOperationResponse.params", "commandParams", { method: "BluetoothEmulation.simulateCharacteristicOperationResponse" }); export const SimulateCharacteristicOperationResponseResult = withCdpMeta(z.object({ }).passthrough(), "BluetoothEmulation.simulateCharacteristicOperationResponse.result", "commandResult", { method: "BluetoothEmulation.simulateCharacteristicOperationResponse" }); +export const SimulateCharacteristicOperationResponseCommand = withCdpCommand("BluetoothEmulation.simulateCharacteristicOperationResponse", SimulateCharacteristicOperationResponseParams, SimulateCharacteristicOperationResponseResult); export const SimulateDescriptorOperationResponseParams = withCdpMeta(z.object({ "descriptorId": z.string(), "type": z.lazy(() => DescriptorOperationType), "code": z.number().int(), "data": z.string().optional() }).passthrough(), "BluetoothEmulation.simulateDescriptorOperationResponse.params", "commandParams", { method: "BluetoothEmulation.simulateDescriptorOperationResponse" }); export const SimulateDescriptorOperationResponseResult = withCdpMeta(z.object({ }).passthrough(), "BluetoothEmulation.simulateDescriptorOperationResponse.result", "commandResult", { method: "BluetoothEmulation.simulateDescriptorOperationResponse" }); +export const SimulateDescriptorOperationResponseCommand = withCdpCommand("BluetoothEmulation.simulateDescriptorOperationResponse", SimulateDescriptorOperationResponseParams, SimulateDescriptorOperationResponseResult); export const AddServiceParams = withCdpMeta(z.object({ "address": z.string(), "serviceUuid": z.string() }).passthrough(), "BluetoothEmulation.addService.params", "commandParams", { method: "BluetoothEmulation.addService" }); export const AddServiceResult = withCdpMeta(z.object({ "serviceId": z.string() }).passthrough(), "BluetoothEmulation.addService.result", "commandResult", { method: "BluetoothEmulation.addService" }); +export const AddServiceCommand = withCdpCommand("BluetoothEmulation.addService", AddServiceParams, AddServiceResult); export const RemoveServiceParams = withCdpMeta(z.object({ "serviceId": z.string() }).passthrough(), "BluetoothEmulation.removeService.params", "commandParams", { method: "BluetoothEmulation.removeService" }); export const RemoveServiceResult = withCdpMeta(z.object({ }).passthrough(), "BluetoothEmulation.removeService.result", "commandResult", { method: "BluetoothEmulation.removeService" }); +export const RemoveServiceCommand = withCdpCommand("BluetoothEmulation.removeService", RemoveServiceParams, RemoveServiceResult); export const AddCharacteristicParams = withCdpMeta(z.object({ "serviceId": z.string(), "characteristicUuid": z.string(), "properties": z.lazy(() => CharacteristicProperties) }).passthrough(), "BluetoothEmulation.addCharacteristic.params", "commandParams", { method: "BluetoothEmulation.addCharacteristic" }); export const AddCharacteristicResult = withCdpMeta(z.object({ "characteristicId": z.string() }).passthrough(), "BluetoothEmulation.addCharacteristic.result", "commandResult", { method: "BluetoothEmulation.addCharacteristic" }); +export const AddCharacteristicCommand = withCdpCommand("BluetoothEmulation.addCharacteristic", AddCharacteristicParams, AddCharacteristicResult); export const RemoveCharacteristicParams = withCdpMeta(z.object({ "characteristicId": z.string() }).passthrough(), "BluetoothEmulation.removeCharacteristic.params", "commandParams", { method: "BluetoothEmulation.removeCharacteristic" }); export const RemoveCharacteristicResult = withCdpMeta(z.object({ }).passthrough(), "BluetoothEmulation.removeCharacteristic.result", "commandResult", { method: "BluetoothEmulation.removeCharacteristic" }); +export const RemoveCharacteristicCommand = withCdpCommand("BluetoothEmulation.removeCharacteristic", RemoveCharacteristicParams, RemoveCharacteristicResult); export const AddDescriptorParams = withCdpMeta(z.object({ "characteristicId": z.string(), "descriptorUuid": z.string() }).passthrough(), "BluetoothEmulation.addDescriptor.params", "commandParams", { method: "BluetoothEmulation.addDescriptor" }); export const AddDescriptorResult = withCdpMeta(z.object({ "descriptorId": z.string() }).passthrough(), "BluetoothEmulation.addDescriptor.result", "commandResult", { method: "BluetoothEmulation.addDescriptor" }); +export const AddDescriptorCommand = withCdpCommand("BluetoothEmulation.addDescriptor", AddDescriptorParams, AddDescriptorResult); export const RemoveDescriptorParams = withCdpMeta(z.object({ "descriptorId": z.string() }).passthrough(), "BluetoothEmulation.removeDescriptor.params", "commandParams", { method: "BluetoothEmulation.removeDescriptor" }); export const RemoveDescriptorResult = withCdpMeta(z.object({ }).passthrough(), "BluetoothEmulation.removeDescriptor.result", "commandResult", { method: "BluetoothEmulation.removeDescriptor" }); +export const RemoveDescriptorCommand = withCdpCommand("BluetoothEmulation.removeDescriptor", RemoveDescriptorParams, RemoveDescriptorResult); export const SimulateGATTDisconnectionParams = withCdpMeta(z.object({ "address": z.string() }).passthrough(), "BluetoothEmulation.simulateGATTDisconnection.params", "commandParams", { method: "BluetoothEmulation.simulateGATTDisconnection" }); export const SimulateGATTDisconnectionResult = withCdpMeta(z.object({ }).passthrough(), "BluetoothEmulation.simulateGATTDisconnection.result", "commandResult", { method: "BluetoothEmulation.simulateGATTDisconnection" }); +export const SimulateGATTDisconnectionCommand = withCdpCommand("BluetoothEmulation.simulateGATTDisconnection", SimulateGATTDisconnectionParams, SimulateGATTDisconnectionResult); export const GattOperationReceivedEvent = withCdpMeta(z.object({ "address": z.string(), "type": z.lazy(() => GATTOperationType) }).passthrough(), "BluetoothEmulation.gattOperationReceived", "event", { phase: "event" }); export const CharacteristicOperationReceivedEvent = withCdpMeta(z.object({ "characteristicId": z.string(), "type": z.lazy(() => CharacteristicOperationType), "data": z.string().optional(), "writeType": z.lazy(() => CharacteristicWriteType).optional() }).passthrough(), "BluetoothEmulation.characteristicOperationReceived", "event", { phase: "event" }); export const DescriptorOperationReceivedEvent = withCdpMeta(z.object({ "descriptorId": z.string(), "type": z.lazy(() => DescriptorOperationType), "data": z.string().optional() }).passthrough(), "BluetoothEmulation.descriptorOperationReceived", "event", { phase: "event" }); @@ -91,21 +106,21 @@ export const zod = { DescriptorOperationReceivedEvent: DescriptorOperationReceivedEvent, } as const; export const commands = { - "BluetoothEmulation.enable": { params: EnableParams, result: EnableResult }, - "BluetoothEmulation.setSimulatedCentralState": { params: SetSimulatedCentralStateParams, result: SetSimulatedCentralStateResult }, - "BluetoothEmulation.disable": { params: DisableParams, result: DisableResult }, - "BluetoothEmulation.simulatePreconnectedPeripheral": { params: SimulatePreconnectedPeripheralParams, result: SimulatePreconnectedPeripheralResult }, - "BluetoothEmulation.simulateAdvertisement": { params: SimulateAdvertisementParams, result: SimulateAdvertisementResult }, - "BluetoothEmulation.simulateGATTOperationResponse": { params: SimulateGATTOperationResponseParams, result: SimulateGATTOperationResponseResult }, - "BluetoothEmulation.simulateCharacteristicOperationResponse": { params: SimulateCharacteristicOperationResponseParams, result: SimulateCharacteristicOperationResponseResult }, - "BluetoothEmulation.simulateDescriptorOperationResponse": { params: SimulateDescriptorOperationResponseParams, result: SimulateDescriptorOperationResponseResult }, - "BluetoothEmulation.addService": { params: AddServiceParams, result: AddServiceResult }, - "BluetoothEmulation.removeService": { params: RemoveServiceParams, result: RemoveServiceResult }, - "BluetoothEmulation.addCharacteristic": { params: AddCharacteristicParams, result: AddCharacteristicResult }, - "BluetoothEmulation.removeCharacteristic": { params: RemoveCharacteristicParams, result: RemoveCharacteristicResult }, - "BluetoothEmulation.addDescriptor": { params: AddDescriptorParams, result: AddDescriptorResult }, - "BluetoothEmulation.removeDescriptor": { params: RemoveDescriptorParams, result: RemoveDescriptorResult }, - "BluetoothEmulation.simulateGATTDisconnection": { params: SimulateGATTDisconnectionParams, result: SimulateGATTDisconnectionResult }, + "BluetoothEmulation.enable": EnableCommand, + "BluetoothEmulation.setSimulatedCentralState": SetSimulatedCentralStateCommand, + "BluetoothEmulation.disable": DisableCommand, + "BluetoothEmulation.simulatePreconnectedPeripheral": SimulatePreconnectedPeripheralCommand, + "BluetoothEmulation.simulateAdvertisement": SimulateAdvertisementCommand, + "BluetoothEmulation.simulateGATTOperationResponse": SimulateGATTOperationResponseCommand, + "BluetoothEmulation.simulateCharacteristicOperationResponse": SimulateCharacteristicOperationResponseCommand, + "BluetoothEmulation.simulateDescriptorOperationResponse": SimulateDescriptorOperationResponseCommand, + "BluetoothEmulation.addService": AddServiceCommand, + "BluetoothEmulation.removeService": RemoveServiceCommand, + "BluetoothEmulation.addCharacteristic": AddCharacteristicCommand, + "BluetoothEmulation.removeCharacteristic": RemoveCharacteristicCommand, + "BluetoothEmulation.addDescriptor": AddDescriptorCommand, + "BluetoothEmulation.removeDescriptor": RemoveDescriptorCommand, + "BluetoothEmulation.simulateGATTDisconnection": SimulateGATTDisconnectionCommand, } as const; export const events = { "BluetoothEmulation.gattOperationReceived": GattOperationReceivedEvent, diff --git a/js/src/types/generated/zod/Browser.ts b/js/src/types/generated/zod/Browser.ts index 026a2d7..126339c 100644 --- a/js/src/types/generated/zod/Browser.ts +++ b/js/src/types/generated/zod/Browser.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Page from "./Page.js"; import * as Target from "./Target.js"; @@ -18,44 +18,64 @@ export const Histogram = withCdpMeta(z.object({ "name": z.string(), "sum": z.num export const PrivacySandboxAPI = withCdpMeta(z.enum(["BiddingAndAuctionServices", "TrustedKeyValue"]), "Browser.PrivacySandboxAPI", "type"); export const SetPermissionParams = withCdpMeta(z.object({ "permission": z.lazy(() => PermissionDescriptor), "setting": z.lazy(() => PermissionSetting), "origin": z.string().optional(), "embeddedOrigin": z.string().optional(), "browserContextId": z.lazy(() => BrowserContextID).optional() }).passthrough(), "Browser.setPermission.params", "commandParams", { method: "Browser.setPermission" }); export const SetPermissionResult = withCdpMeta(z.object({ }).passthrough(), "Browser.setPermission.result", "commandResult", { method: "Browser.setPermission" }); +export const SetPermissionCommand = withCdpCommand("Browser.setPermission", SetPermissionParams, SetPermissionResult); export const GrantPermissionsParams = withCdpMeta(z.object({ "permissions": z.array(z.lazy(() => PermissionType)), "origin": z.string().optional(), "browserContextId": z.lazy(() => BrowserContextID).optional() }).passthrough(), "Browser.grantPermissions.params", "commandParams", { method: "Browser.grantPermissions" }); export const GrantPermissionsResult = withCdpMeta(z.object({ }).passthrough(), "Browser.grantPermissions.result", "commandResult", { method: "Browser.grantPermissions" }); +export const GrantPermissionsCommand = withCdpCommand("Browser.grantPermissions", GrantPermissionsParams, GrantPermissionsResult); export const ResetPermissionsParams = withCdpMeta(z.object({ "browserContextId": z.lazy(() => BrowserContextID).optional() }).passthrough(), "Browser.resetPermissions.params", "commandParams", { method: "Browser.resetPermissions" }); export const ResetPermissionsResult = withCdpMeta(z.object({ }).passthrough(), "Browser.resetPermissions.result", "commandResult", { method: "Browser.resetPermissions" }); +export const ResetPermissionsCommand = withCdpCommand("Browser.resetPermissions", ResetPermissionsParams, ResetPermissionsResult); export const SetDownloadBehaviorParams = withCdpMeta(z.object({ "behavior": z.enum(["deny", "allow", "allowAndName", "default"]), "browserContextId": z.lazy(() => BrowserContextID).optional(), "downloadPath": z.string().optional(), "eventsEnabled": z.boolean().optional() }).passthrough(), "Browser.setDownloadBehavior.params", "commandParams", { method: "Browser.setDownloadBehavior" }); export const SetDownloadBehaviorResult = withCdpMeta(z.object({ }).passthrough(), "Browser.setDownloadBehavior.result", "commandResult", { method: "Browser.setDownloadBehavior" }); +export const SetDownloadBehaviorCommand = withCdpCommand("Browser.setDownloadBehavior", SetDownloadBehaviorParams, SetDownloadBehaviorResult); export const CancelDownloadParams = withCdpMeta(z.object({ "guid": z.string(), "browserContextId": z.lazy(() => BrowserContextID).optional() }).passthrough(), "Browser.cancelDownload.params", "commandParams", { method: "Browser.cancelDownload" }); export const CancelDownloadResult = withCdpMeta(z.object({ }).passthrough(), "Browser.cancelDownload.result", "commandResult", { method: "Browser.cancelDownload" }); +export const CancelDownloadCommand = withCdpCommand("Browser.cancelDownload", CancelDownloadParams, CancelDownloadResult); export const CloseParams = withCdpMeta(z.object({ }).passthrough(), "Browser.close.params", "commandParams", { method: "Browser.close" }); export const CloseResult = withCdpMeta(z.object({ }).passthrough(), "Browser.close.result", "commandResult", { method: "Browser.close" }); +export const CloseCommand = withCdpCommand("Browser.close", CloseParams, CloseResult); export const CrashParams = withCdpMeta(z.object({ }).passthrough(), "Browser.crash.params", "commandParams", { method: "Browser.crash" }); export const CrashResult = withCdpMeta(z.object({ }).passthrough(), "Browser.crash.result", "commandResult", { method: "Browser.crash" }); +export const CrashCommand = withCdpCommand("Browser.crash", CrashParams, CrashResult); export const CrashGpuProcessParams = withCdpMeta(z.object({ }).passthrough(), "Browser.crashGpuProcess.params", "commandParams", { method: "Browser.crashGpuProcess" }); export const CrashGpuProcessResult = withCdpMeta(z.object({ }).passthrough(), "Browser.crashGpuProcess.result", "commandResult", { method: "Browser.crashGpuProcess" }); +export const CrashGpuProcessCommand = withCdpCommand("Browser.crashGpuProcess", CrashGpuProcessParams, CrashGpuProcessResult); export const GetVersionParams = withCdpMeta(z.object({ }).passthrough(), "Browser.getVersion.params", "commandParams", { method: "Browser.getVersion" }); export const GetVersionResult = withCdpMeta(z.object({ "protocolVersion": z.string(), "product": z.string(), "revision": z.string(), "userAgent": z.string(), "jsVersion": z.string() }).passthrough(), "Browser.getVersion.result", "commandResult", { method: "Browser.getVersion" }); +export const GetVersionCommand = withCdpCommand("Browser.getVersion", GetVersionParams, GetVersionResult); export const GetBrowserCommandLineParams = withCdpMeta(z.object({ }).passthrough(), "Browser.getBrowserCommandLine.params", "commandParams", { method: "Browser.getBrowserCommandLine" }); export const GetBrowserCommandLineResult = withCdpMeta(z.object({ "arguments": z.array(z.string()) }).passthrough(), "Browser.getBrowserCommandLine.result", "commandResult", { method: "Browser.getBrowserCommandLine" }); +export const GetBrowserCommandLineCommand = withCdpCommand("Browser.getBrowserCommandLine", GetBrowserCommandLineParams, GetBrowserCommandLineResult); export const GetHistogramsParams = withCdpMeta(z.object({ "query": z.string().optional(), "delta": z.boolean().optional() }).passthrough(), "Browser.getHistograms.params", "commandParams", { method: "Browser.getHistograms" }); export const GetHistogramsResult = withCdpMeta(z.object({ "histograms": z.array(z.lazy(() => Histogram)) }).passthrough(), "Browser.getHistograms.result", "commandResult", { method: "Browser.getHistograms" }); +export const GetHistogramsCommand = withCdpCommand("Browser.getHistograms", GetHistogramsParams, GetHistogramsResult); export const GetHistogramParams = withCdpMeta(z.object({ "name": z.string(), "delta": z.boolean().optional() }).passthrough(), "Browser.getHistogram.params", "commandParams", { method: "Browser.getHistogram" }); export const GetHistogramResult = withCdpMeta(z.object({ "histogram": z.lazy(() => Histogram) }).passthrough(), "Browser.getHistogram.result", "commandResult", { method: "Browser.getHistogram" }); +export const GetHistogramCommand = withCdpCommand("Browser.getHistogram", GetHistogramParams, GetHistogramResult); export const GetWindowBoundsParams = withCdpMeta(z.object({ "windowId": z.lazy(() => WindowID) }).passthrough(), "Browser.getWindowBounds.params", "commandParams", { method: "Browser.getWindowBounds" }); export const GetWindowBoundsResult = withCdpMeta(z.object({ "bounds": z.lazy(() => Bounds) }).passthrough(), "Browser.getWindowBounds.result", "commandResult", { method: "Browser.getWindowBounds" }); +export const GetWindowBoundsCommand = withCdpCommand("Browser.getWindowBounds", GetWindowBoundsParams, GetWindowBoundsResult); export const GetWindowForTargetParams = withCdpMeta(z.object({ "targetId": z.lazy(() => Target.TargetID).optional() }).passthrough(), "Browser.getWindowForTarget.params", "commandParams", { method: "Browser.getWindowForTarget" }); export const GetWindowForTargetResult = withCdpMeta(z.object({ "windowId": z.lazy(() => WindowID), "bounds": z.lazy(() => Bounds) }).passthrough(), "Browser.getWindowForTarget.result", "commandResult", { method: "Browser.getWindowForTarget" }); +export const GetWindowForTargetCommand = withCdpCommand("Browser.getWindowForTarget", GetWindowForTargetParams, GetWindowForTargetResult); export const SetWindowBoundsParams = withCdpMeta(z.object({ "windowId": z.lazy(() => WindowID), "bounds": z.lazy(() => Bounds) }).passthrough(), "Browser.setWindowBounds.params", "commandParams", { method: "Browser.setWindowBounds" }); export const SetWindowBoundsResult = withCdpMeta(z.object({ }).passthrough(), "Browser.setWindowBounds.result", "commandResult", { method: "Browser.setWindowBounds" }); +export const SetWindowBoundsCommand = withCdpCommand("Browser.setWindowBounds", SetWindowBoundsParams, SetWindowBoundsResult); export const SetContentsSizeParams = withCdpMeta(z.object({ "windowId": z.lazy(() => WindowID), "width": z.number().int().optional(), "height": z.number().int().optional() }).passthrough(), "Browser.setContentsSize.params", "commandParams", { method: "Browser.setContentsSize" }); export const SetContentsSizeResult = withCdpMeta(z.object({ }).passthrough(), "Browser.setContentsSize.result", "commandResult", { method: "Browser.setContentsSize" }); +export const SetContentsSizeCommand = withCdpCommand("Browser.setContentsSize", SetContentsSizeParams, SetContentsSizeResult); export const SetDockTileParams = withCdpMeta(z.object({ "badgeLabel": z.string().optional(), "image": z.string().optional() }).passthrough(), "Browser.setDockTile.params", "commandParams", { method: "Browser.setDockTile" }); export const SetDockTileResult = withCdpMeta(z.object({ }).passthrough(), "Browser.setDockTile.result", "commandResult", { method: "Browser.setDockTile" }); +export const SetDockTileCommand = withCdpCommand("Browser.setDockTile", SetDockTileParams, SetDockTileResult); export const ExecuteBrowserCommandParams = withCdpMeta(z.object({ "commandId": z.lazy(() => BrowserCommandId) }).passthrough(), "Browser.executeBrowserCommand.params", "commandParams", { method: "Browser.executeBrowserCommand" }); export const ExecuteBrowserCommandResult = withCdpMeta(z.object({ }).passthrough(), "Browser.executeBrowserCommand.result", "commandResult", { method: "Browser.executeBrowserCommand" }); +export const ExecuteBrowserCommandCommand = withCdpCommand("Browser.executeBrowserCommand", ExecuteBrowserCommandParams, ExecuteBrowserCommandResult); export const AddPrivacySandboxEnrollmentOverrideParams = withCdpMeta(z.object({ "url": z.string() }).passthrough(), "Browser.addPrivacySandboxEnrollmentOverride.params", "commandParams", { method: "Browser.addPrivacySandboxEnrollmentOverride" }); export const AddPrivacySandboxEnrollmentOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Browser.addPrivacySandboxEnrollmentOverride.result", "commandResult", { method: "Browser.addPrivacySandboxEnrollmentOverride" }); +export const AddPrivacySandboxEnrollmentOverrideCommand = withCdpCommand("Browser.addPrivacySandboxEnrollmentOverride", AddPrivacySandboxEnrollmentOverrideParams, AddPrivacySandboxEnrollmentOverrideResult); export const AddPrivacySandboxCoordinatorKeyConfigParams = withCdpMeta(z.object({ "api": z.lazy(() => PrivacySandboxAPI), "coordinatorOrigin": z.string(), "keyConfig": z.string(), "browserContextId": z.lazy(() => BrowserContextID).optional() }).passthrough(), "Browser.addPrivacySandboxCoordinatorKeyConfig.params", "commandParams", { method: "Browser.addPrivacySandboxCoordinatorKeyConfig" }); export const AddPrivacySandboxCoordinatorKeyConfigResult = withCdpMeta(z.object({ }).passthrough(), "Browser.addPrivacySandboxCoordinatorKeyConfig.result", "commandResult", { method: "Browser.addPrivacySandboxCoordinatorKeyConfig" }); +export const AddPrivacySandboxCoordinatorKeyConfigCommand = withCdpCommand("Browser.addPrivacySandboxCoordinatorKeyConfig", AddPrivacySandboxCoordinatorKeyConfigParams, AddPrivacySandboxCoordinatorKeyConfigResult); export const DownloadWillBeginEvent = withCdpMeta(z.object({ "frameId": z.lazy(() => Page.FrameId), "guid": z.string(), "url": z.string(), "suggestedFilename": z.string() }).passthrough(), "Browser.downloadWillBegin", "event", { phase: "event" }); export const DownloadProgressEvent = withCdpMeta(z.object({ "guid": z.string(), "totalBytes": z.number(), "receivedBytes": z.number(), "state": z.enum(["inProgress", "completed", "canceled"]), "filePath": z.string().optional() }).passthrough(), "Browser.downloadProgress", "event", { phase: "event" }); @@ -115,26 +135,26 @@ export const zod = { DownloadProgressEvent: DownloadProgressEvent, } as const; export const commands = { - "Browser.setPermission": { params: SetPermissionParams, result: SetPermissionResult }, - "Browser.grantPermissions": { params: GrantPermissionsParams, result: GrantPermissionsResult }, - "Browser.resetPermissions": { params: ResetPermissionsParams, result: ResetPermissionsResult }, - "Browser.setDownloadBehavior": { params: SetDownloadBehaviorParams, result: SetDownloadBehaviorResult }, - "Browser.cancelDownload": { params: CancelDownloadParams, result: CancelDownloadResult }, - "Browser.close": { params: CloseParams, result: CloseResult }, - "Browser.crash": { params: CrashParams, result: CrashResult }, - "Browser.crashGpuProcess": { params: CrashGpuProcessParams, result: CrashGpuProcessResult }, - "Browser.getVersion": { params: GetVersionParams, result: GetVersionResult }, - "Browser.getBrowserCommandLine": { params: GetBrowserCommandLineParams, result: GetBrowserCommandLineResult }, - "Browser.getHistograms": { params: GetHistogramsParams, result: GetHistogramsResult }, - "Browser.getHistogram": { params: GetHistogramParams, result: GetHistogramResult }, - "Browser.getWindowBounds": { params: GetWindowBoundsParams, result: GetWindowBoundsResult }, - "Browser.getWindowForTarget": { params: GetWindowForTargetParams, result: GetWindowForTargetResult }, - "Browser.setWindowBounds": { params: SetWindowBoundsParams, result: SetWindowBoundsResult }, - "Browser.setContentsSize": { params: SetContentsSizeParams, result: SetContentsSizeResult }, - "Browser.setDockTile": { params: SetDockTileParams, result: SetDockTileResult }, - "Browser.executeBrowserCommand": { params: ExecuteBrowserCommandParams, result: ExecuteBrowserCommandResult }, - "Browser.addPrivacySandboxEnrollmentOverride": { params: AddPrivacySandboxEnrollmentOverrideParams, result: AddPrivacySandboxEnrollmentOverrideResult }, - "Browser.addPrivacySandboxCoordinatorKeyConfig": { params: AddPrivacySandboxCoordinatorKeyConfigParams, result: AddPrivacySandboxCoordinatorKeyConfigResult }, + "Browser.setPermission": SetPermissionCommand, + "Browser.grantPermissions": GrantPermissionsCommand, + "Browser.resetPermissions": ResetPermissionsCommand, + "Browser.setDownloadBehavior": SetDownloadBehaviorCommand, + "Browser.cancelDownload": CancelDownloadCommand, + "Browser.close": CloseCommand, + "Browser.crash": CrashCommand, + "Browser.crashGpuProcess": CrashGpuProcessCommand, + "Browser.getVersion": GetVersionCommand, + "Browser.getBrowserCommandLine": GetBrowserCommandLineCommand, + "Browser.getHistograms": GetHistogramsCommand, + "Browser.getHistogram": GetHistogramCommand, + "Browser.getWindowBounds": GetWindowBoundsCommand, + "Browser.getWindowForTarget": GetWindowForTargetCommand, + "Browser.setWindowBounds": SetWindowBoundsCommand, + "Browser.setContentsSize": SetContentsSizeCommand, + "Browser.setDockTile": SetDockTileCommand, + "Browser.executeBrowserCommand": ExecuteBrowserCommandCommand, + "Browser.addPrivacySandboxEnrollmentOverride": AddPrivacySandboxEnrollmentOverrideCommand, + "Browser.addPrivacySandboxCoordinatorKeyConfig": AddPrivacySandboxCoordinatorKeyConfigCommand, } as const; export const events = { "Browser.downloadWillBegin": DownloadWillBeginEvent, diff --git a/js/src/types/generated/zod/CSS.ts b/js/src/types/generated/zod/CSS.ts index 0b99333..dd64dd6 100644 --- a/js/src/types/generated/zod/CSS.ts +++ b/js/src/types/generated/zod/CSS.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; import * as Page from "./Page.js"; @@ -52,80 +52,118 @@ export const CSSKeyframeRule = withCdpMeta(z.object({ "styleSheetId": z.lazy(() export const StyleDeclarationEdit = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId), "range": z.lazy(() => SourceRange), "text": z.string() }).passthrough(), "CSS.StyleDeclarationEdit", "type"); export const AddRuleParams = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId), "ruleText": z.string(), "location": z.lazy(() => SourceRange), "nodeForPropertySyntaxValidation": z.lazy(() => DOM.NodeId).optional() }).passthrough(), "CSS.addRule.params", "commandParams", { method: "CSS.addRule" }); export const AddRuleResult = withCdpMeta(z.object({ "rule": z.lazy(() => CSSRule) }).passthrough(), "CSS.addRule.result", "commandResult", { method: "CSS.addRule" }); +export const AddRuleCommand = withCdpCommand("CSS.addRule", AddRuleParams, AddRuleResult); export const CollectClassNamesParams = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId) }).passthrough(), "CSS.collectClassNames.params", "commandParams", { method: "CSS.collectClassNames" }); export const CollectClassNamesResult = withCdpMeta(z.object({ "classNames": z.array(z.string()) }).passthrough(), "CSS.collectClassNames.result", "commandResult", { method: "CSS.collectClassNames" }); +export const CollectClassNamesCommand = withCdpCommand("CSS.collectClassNames", CollectClassNamesParams, CollectClassNamesResult); export const CreateStyleSheetParams = withCdpMeta(z.object({ "frameId": z.lazy(() => Page.FrameId), "force": z.boolean().optional() }).passthrough(), "CSS.createStyleSheet.params", "commandParams", { method: "CSS.createStyleSheet" }); export const CreateStyleSheetResult = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId) }).passthrough(), "CSS.createStyleSheet.result", "commandResult", { method: "CSS.createStyleSheet" }); +export const CreateStyleSheetCommand = withCdpCommand("CSS.createStyleSheet", CreateStyleSheetParams, CreateStyleSheetResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "CSS.disable.params", "commandParams", { method: "CSS.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "CSS.disable.result", "commandResult", { method: "CSS.disable" }); +export const DisableCommand = withCdpCommand("CSS.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "CSS.enable.params", "commandParams", { method: "CSS.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "CSS.enable.result", "commandResult", { method: "CSS.enable" }); +export const EnableCommand = withCdpCommand("CSS.enable", EnableParams, EnableResult); export const ForcePseudoStateParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId), "forcedPseudoClasses": z.array(z.string()) }).passthrough(), "CSS.forcePseudoState.params", "commandParams", { method: "CSS.forcePseudoState" }); export const ForcePseudoStateResult = withCdpMeta(z.object({ }).passthrough(), "CSS.forcePseudoState.result", "commandResult", { method: "CSS.forcePseudoState" }); +export const ForcePseudoStateCommand = withCdpCommand("CSS.forcePseudoState", ForcePseudoStateParams, ForcePseudoStateResult); export const ForceStartingStyleParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId), "forced": z.boolean() }).passthrough(), "CSS.forceStartingStyle.params", "commandParams", { method: "CSS.forceStartingStyle" }); export const ForceStartingStyleResult = withCdpMeta(z.object({ }).passthrough(), "CSS.forceStartingStyle.result", "commandResult", { method: "CSS.forceStartingStyle" }); +export const ForceStartingStyleCommand = withCdpCommand("CSS.forceStartingStyle", ForceStartingStyleParams, ForceStartingStyleResult); export const GetBackgroundColorsParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId) }).passthrough(), "CSS.getBackgroundColors.params", "commandParams", { method: "CSS.getBackgroundColors" }); export const GetBackgroundColorsResult = withCdpMeta(z.object({ "backgroundColors": z.array(z.string()).optional(), "computedFontSize": z.string().optional(), "computedFontWeight": z.string().optional() }).passthrough(), "CSS.getBackgroundColors.result", "commandResult", { method: "CSS.getBackgroundColors" }); +export const GetBackgroundColorsCommand = withCdpCommand("CSS.getBackgroundColors", GetBackgroundColorsParams, GetBackgroundColorsResult); export const GetComputedStyleForNodeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId) }).passthrough(), "CSS.getComputedStyleForNode.params", "commandParams", { method: "CSS.getComputedStyleForNode" }); export const GetComputedStyleForNodeResult = withCdpMeta(z.object({ "computedStyle": z.array(z.lazy(() => CSSComputedStyleProperty)), "extraFields": z.lazy(() => ComputedStyleExtraFields) }).passthrough(), "CSS.getComputedStyleForNode.result", "commandResult", { method: "CSS.getComputedStyleForNode" }); +export const GetComputedStyleForNodeCommand = withCdpCommand("CSS.getComputedStyleForNode", GetComputedStyleForNodeParams, GetComputedStyleForNodeResult); export const ResolveValuesParams = withCdpMeta(z.object({ "values": z.array(z.string()), "nodeId": z.lazy(() => DOM.NodeId), "propertyName": z.string().optional(), "pseudoType": z.lazy(() => DOM.PseudoType).optional(), "pseudoIdentifier": z.string().optional() }).passthrough(), "CSS.resolveValues.params", "commandParams", { method: "CSS.resolveValues" }); export const ResolveValuesResult = withCdpMeta(z.object({ "results": z.array(z.string()) }).passthrough(), "CSS.resolveValues.result", "commandResult", { method: "CSS.resolveValues" }); +export const ResolveValuesCommand = withCdpCommand("CSS.resolveValues", ResolveValuesParams, ResolveValuesResult); export const GetLonghandPropertiesParams = withCdpMeta(z.object({ "shorthandName": z.string(), "value": z.string() }).passthrough(), "CSS.getLonghandProperties.params", "commandParams", { method: "CSS.getLonghandProperties" }); export const GetLonghandPropertiesResult = withCdpMeta(z.object({ "longhandProperties": z.array(z.lazy(() => CSSProperty)) }).passthrough(), "CSS.getLonghandProperties.result", "commandResult", { method: "CSS.getLonghandProperties" }); +export const GetLonghandPropertiesCommand = withCdpCommand("CSS.getLonghandProperties", GetLonghandPropertiesParams, GetLonghandPropertiesResult); export const GetInlineStylesForNodeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId) }).passthrough(), "CSS.getInlineStylesForNode.params", "commandParams", { method: "CSS.getInlineStylesForNode" }); export const GetInlineStylesForNodeResult = withCdpMeta(z.object({ "inlineStyle": z.lazy(() => CSSStyle).optional(), "attributesStyle": z.lazy(() => CSSStyle).optional() }).passthrough(), "CSS.getInlineStylesForNode.result", "commandResult", { method: "CSS.getInlineStylesForNode" }); +export const GetInlineStylesForNodeCommand = withCdpCommand("CSS.getInlineStylesForNode", GetInlineStylesForNodeParams, GetInlineStylesForNodeResult); export const GetAnimatedStylesForNodeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId) }).passthrough(), "CSS.getAnimatedStylesForNode.params", "commandParams", { method: "CSS.getAnimatedStylesForNode" }); export const GetAnimatedStylesForNodeResult = withCdpMeta(z.object({ "animationStyles": z.array(z.lazy(() => CSSAnimationStyle)).optional(), "transitionsStyle": z.lazy(() => CSSStyle).optional(), "inherited": z.array(z.lazy(() => InheritedAnimatedStyleEntry)).optional() }).passthrough(), "CSS.getAnimatedStylesForNode.result", "commandResult", { method: "CSS.getAnimatedStylesForNode" }); +export const GetAnimatedStylesForNodeCommand = withCdpCommand("CSS.getAnimatedStylesForNode", GetAnimatedStylesForNodeParams, GetAnimatedStylesForNodeResult); export const GetMatchedStylesForNodeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId) }).passthrough(), "CSS.getMatchedStylesForNode.params", "commandParams", { method: "CSS.getMatchedStylesForNode" }); export const GetMatchedStylesForNodeResult = withCdpMeta(z.object({ "inlineStyle": z.lazy(() => CSSStyle).optional(), "attributesStyle": z.lazy(() => CSSStyle).optional(), "matchedCSSRules": z.array(z.lazy(() => RuleMatch)).optional(), "pseudoElements": z.array(z.lazy(() => PseudoElementMatches)).optional(), "inherited": z.array(z.lazy(() => InheritedStyleEntry)).optional(), "inheritedPseudoElements": z.array(z.lazy(() => InheritedPseudoElementMatches)).optional(), "cssKeyframesRules": z.array(z.lazy(() => CSSKeyframesRule)).optional(), "cssPositionTryRules": z.array(z.lazy(() => CSSPositionTryRule)).optional(), "activePositionFallbackIndex": z.number().int().optional(), "cssPropertyRules": z.array(z.lazy(() => CSSPropertyRule)).optional(), "cssPropertyRegistrations": z.array(z.lazy(() => CSSPropertyRegistration)).optional(), "cssAtRules": z.array(z.lazy(() => CSSAtRule)).optional(), "parentLayoutNodeId": z.lazy(() => DOM.NodeId).optional(), "cssFunctionRules": z.array(z.lazy(() => CSSFunctionRule)).optional() }).passthrough(), "CSS.getMatchedStylesForNode.result", "commandResult", { method: "CSS.getMatchedStylesForNode" }); +export const GetMatchedStylesForNodeCommand = withCdpCommand("CSS.getMatchedStylesForNode", GetMatchedStylesForNodeParams, GetMatchedStylesForNodeResult); export const GetEnvironmentVariablesParams = withCdpMeta(z.object({ }).passthrough(), "CSS.getEnvironmentVariables.params", "commandParams", { method: "CSS.getEnvironmentVariables" }); export const GetEnvironmentVariablesResult = withCdpMeta(z.object({ "environmentVariables": z.record(z.string(), z.unknown()) }).passthrough(), "CSS.getEnvironmentVariables.result", "commandResult", { method: "CSS.getEnvironmentVariables" }); +export const GetEnvironmentVariablesCommand = withCdpCommand("CSS.getEnvironmentVariables", GetEnvironmentVariablesParams, GetEnvironmentVariablesResult); export const GetMediaQueriesParams = withCdpMeta(z.object({ }).passthrough(), "CSS.getMediaQueries.params", "commandParams", { method: "CSS.getMediaQueries" }); export const GetMediaQueriesResult = withCdpMeta(z.object({ "medias": z.array(z.lazy(() => CSSMedia)) }).passthrough(), "CSS.getMediaQueries.result", "commandResult", { method: "CSS.getMediaQueries" }); +export const GetMediaQueriesCommand = withCdpCommand("CSS.getMediaQueries", GetMediaQueriesParams, GetMediaQueriesResult); export const GetPlatformFontsForNodeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId) }).passthrough(), "CSS.getPlatformFontsForNode.params", "commandParams", { method: "CSS.getPlatformFontsForNode" }); export const GetPlatformFontsForNodeResult = withCdpMeta(z.object({ "fonts": z.array(z.lazy(() => PlatformFontUsage)) }).passthrough(), "CSS.getPlatformFontsForNode.result", "commandResult", { method: "CSS.getPlatformFontsForNode" }); +export const GetPlatformFontsForNodeCommand = withCdpCommand("CSS.getPlatformFontsForNode", GetPlatformFontsForNodeParams, GetPlatformFontsForNodeResult); export const GetStyleSheetTextParams = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId) }).passthrough(), "CSS.getStyleSheetText.params", "commandParams", { method: "CSS.getStyleSheetText" }); export const GetStyleSheetTextResult = withCdpMeta(z.object({ "text": z.string() }).passthrough(), "CSS.getStyleSheetText.result", "commandResult", { method: "CSS.getStyleSheetText" }); +export const GetStyleSheetTextCommand = withCdpCommand("CSS.getStyleSheetText", GetStyleSheetTextParams, GetStyleSheetTextResult); export const GetLayersForNodeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId) }).passthrough(), "CSS.getLayersForNode.params", "commandParams", { method: "CSS.getLayersForNode" }); export const GetLayersForNodeResult = withCdpMeta(z.object({ "rootLayer": z.lazy(() => CSSLayerData) }).passthrough(), "CSS.getLayersForNode.result", "commandResult", { method: "CSS.getLayersForNode" }); +export const GetLayersForNodeCommand = withCdpCommand("CSS.getLayersForNode", GetLayersForNodeParams, GetLayersForNodeResult); export const GetLocationForSelectorParams = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId), "selectorText": z.string() }).passthrough(), "CSS.getLocationForSelector.params", "commandParams", { method: "CSS.getLocationForSelector" }); export const GetLocationForSelectorResult = withCdpMeta(z.object({ "ranges": z.array(z.lazy(() => SourceRange)) }).passthrough(), "CSS.getLocationForSelector.result", "commandResult", { method: "CSS.getLocationForSelector" }); +export const GetLocationForSelectorCommand = withCdpCommand("CSS.getLocationForSelector", GetLocationForSelectorParams, GetLocationForSelectorResult); export const TrackComputedStyleUpdatesForNodeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId).optional() }).passthrough(), "CSS.trackComputedStyleUpdatesForNode.params", "commandParams", { method: "CSS.trackComputedStyleUpdatesForNode" }); export const TrackComputedStyleUpdatesForNodeResult = withCdpMeta(z.object({ }).passthrough(), "CSS.trackComputedStyleUpdatesForNode.result", "commandResult", { method: "CSS.trackComputedStyleUpdatesForNode" }); +export const TrackComputedStyleUpdatesForNodeCommand = withCdpCommand("CSS.trackComputedStyleUpdatesForNode", TrackComputedStyleUpdatesForNodeParams, TrackComputedStyleUpdatesForNodeResult); export const TrackComputedStyleUpdatesParams = withCdpMeta(z.object({ "propertiesToTrack": z.array(z.lazy(() => CSSComputedStyleProperty)) }).passthrough(), "CSS.trackComputedStyleUpdates.params", "commandParams", { method: "CSS.trackComputedStyleUpdates" }); export const TrackComputedStyleUpdatesResult = withCdpMeta(z.object({ }).passthrough(), "CSS.trackComputedStyleUpdates.result", "commandResult", { method: "CSS.trackComputedStyleUpdates" }); +export const TrackComputedStyleUpdatesCommand = withCdpCommand("CSS.trackComputedStyleUpdates", TrackComputedStyleUpdatesParams, TrackComputedStyleUpdatesResult); export const TakeComputedStyleUpdatesParams = withCdpMeta(z.object({ }).passthrough(), "CSS.takeComputedStyleUpdates.params", "commandParams", { method: "CSS.takeComputedStyleUpdates" }); export const TakeComputedStyleUpdatesResult = withCdpMeta(z.object({ "nodeIds": z.array(z.lazy(() => DOM.NodeId)) }).passthrough(), "CSS.takeComputedStyleUpdates.result", "commandResult", { method: "CSS.takeComputedStyleUpdates" }); +export const TakeComputedStyleUpdatesCommand = withCdpCommand("CSS.takeComputedStyleUpdates", TakeComputedStyleUpdatesParams, TakeComputedStyleUpdatesResult); export const SetEffectivePropertyValueForNodeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId), "propertyName": z.string(), "value": z.string() }).passthrough(), "CSS.setEffectivePropertyValueForNode.params", "commandParams", { method: "CSS.setEffectivePropertyValueForNode" }); export const SetEffectivePropertyValueForNodeResult = withCdpMeta(z.object({ }).passthrough(), "CSS.setEffectivePropertyValueForNode.result", "commandResult", { method: "CSS.setEffectivePropertyValueForNode" }); +export const SetEffectivePropertyValueForNodeCommand = withCdpCommand("CSS.setEffectivePropertyValueForNode", SetEffectivePropertyValueForNodeParams, SetEffectivePropertyValueForNodeResult); export const SetPropertyRulePropertyNameParams = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId), "range": z.lazy(() => SourceRange), "propertyName": z.string() }).passthrough(), "CSS.setPropertyRulePropertyName.params", "commandParams", { method: "CSS.setPropertyRulePropertyName" }); export const SetPropertyRulePropertyNameResult = withCdpMeta(z.object({ "propertyName": z.lazy(() => Value) }).passthrough(), "CSS.setPropertyRulePropertyName.result", "commandResult", { method: "CSS.setPropertyRulePropertyName" }); +export const SetPropertyRulePropertyNameCommand = withCdpCommand("CSS.setPropertyRulePropertyName", SetPropertyRulePropertyNameParams, SetPropertyRulePropertyNameResult); export const SetKeyframeKeyParams = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId), "range": z.lazy(() => SourceRange), "keyText": z.string() }).passthrough(), "CSS.setKeyframeKey.params", "commandParams", { method: "CSS.setKeyframeKey" }); export const SetKeyframeKeyResult = withCdpMeta(z.object({ "keyText": z.lazy(() => Value) }).passthrough(), "CSS.setKeyframeKey.result", "commandResult", { method: "CSS.setKeyframeKey" }); +export const SetKeyframeKeyCommand = withCdpCommand("CSS.setKeyframeKey", SetKeyframeKeyParams, SetKeyframeKeyResult); export const SetMediaTextParams = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId), "range": z.lazy(() => SourceRange), "text": z.string() }).passthrough(), "CSS.setMediaText.params", "commandParams", { method: "CSS.setMediaText" }); export const SetMediaTextResult = withCdpMeta(z.object({ "media": z.lazy(() => CSSMedia) }).passthrough(), "CSS.setMediaText.result", "commandResult", { method: "CSS.setMediaText" }); +export const SetMediaTextCommand = withCdpCommand("CSS.setMediaText", SetMediaTextParams, SetMediaTextResult); export const SetContainerQueryTextParams = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId), "range": z.lazy(() => SourceRange), "text": z.string() }).passthrough(), "CSS.setContainerQueryText.params", "commandParams", { method: "CSS.setContainerQueryText" }); export const SetContainerQueryTextResult = withCdpMeta(z.object({ "containerQuery": z.lazy(() => CSSContainerQuery) }).passthrough(), "CSS.setContainerQueryText.result", "commandResult", { method: "CSS.setContainerQueryText" }); +export const SetContainerQueryTextCommand = withCdpCommand("CSS.setContainerQueryText", SetContainerQueryTextParams, SetContainerQueryTextResult); export const SetSupportsTextParams = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId), "range": z.lazy(() => SourceRange), "text": z.string() }).passthrough(), "CSS.setSupportsText.params", "commandParams", { method: "CSS.setSupportsText" }); export const SetSupportsTextResult = withCdpMeta(z.object({ "supports": z.lazy(() => CSSSupports) }).passthrough(), "CSS.setSupportsText.result", "commandResult", { method: "CSS.setSupportsText" }); +export const SetSupportsTextCommand = withCdpCommand("CSS.setSupportsText", SetSupportsTextParams, SetSupportsTextResult); export const SetNavigationTextParams = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId), "range": z.lazy(() => SourceRange), "text": z.string() }).passthrough(), "CSS.setNavigationText.params", "commandParams", { method: "CSS.setNavigationText" }); export const SetNavigationTextResult = withCdpMeta(z.object({ "navigation": z.lazy(() => CSSNavigation) }).passthrough(), "CSS.setNavigationText.result", "commandResult", { method: "CSS.setNavigationText" }); +export const SetNavigationTextCommand = withCdpCommand("CSS.setNavigationText", SetNavigationTextParams, SetNavigationTextResult); export const SetScopeTextParams = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId), "range": z.lazy(() => SourceRange), "text": z.string() }).passthrough(), "CSS.setScopeText.params", "commandParams", { method: "CSS.setScopeText" }); export const SetScopeTextResult = withCdpMeta(z.object({ "scope": z.lazy(() => CSSScope) }).passthrough(), "CSS.setScopeText.result", "commandResult", { method: "CSS.setScopeText" }); +export const SetScopeTextCommand = withCdpCommand("CSS.setScopeText", SetScopeTextParams, SetScopeTextResult); export const SetRuleSelectorParams = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId), "range": z.lazy(() => SourceRange), "selector": z.string() }).passthrough(), "CSS.setRuleSelector.params", "commandParams", { method: "CSS.setRuleSelector" }); export const SetRuleSelectorResult = withCdpMeta(z.object({ "selectorList": z.lazy(() => SelectorList) }).passthrough(), "CSS.setRuleSelector.result", "commandResult", { method: "CSS.setRuleSelector" }); +export const SetRuleSelectorCommand = withCdpCommand("CSS.setRuleSelector", SetRuleSelectorParams, SetRuleSelectorResult); export const SetStyleSheetTextParams = withCdpMeta(z.object({ "styleSheetId": z.lazy(() => DOM.StyleSheetId), "text": z.string() }).passthrough(), "CSS.setStyleSheetText.params", "commandParams", { method: "CSS.setStyleSheetText" }); export const SetStyleSheetTextResult = withCdpMeta(z.object({ "sourceMapURL": z.string().optional() }).passthrough(), "CSS.setStyleSheetText.result", "commandResult", { method: "CSS.setStyleSheetText" }); +export const SetStyleSheetTextCommand = withCdpCommand("CSS.setStyleSheetText", SetStyleSheetTextParams, SetStyleSheetTextResult); export const SetStyleTextsParams = withCdpMeta(z.object({ "edits": z.array(z.lazy(() => StyleDeclarationEdit)), "nodeForPropertySyntaxValidation": z.lazy(() => DOM.NodeId).optional() }).passthrough(), "CSS.setStyleTexts.params", "commandParams", { method: "CSS.setStyleTexts" }); export const SetStyleTextsResult = withCdpMeta(z.object({ "styles": z.array(z.lazy(() => CSSStyle)) }).passthrough(), "CSS.setStyleTexts.result", "commandResult", { method: "CSS.setStyleTexts" }); +export const SetStyleTextsCommand = withCdpCommand("CSS.setStyleTexts", SetStyleTextsParams, SetStyleTextsResult); export const StartRuleUsageTrackingParams = withCdpMeta(z.object({ }).passthrough(), "CSS.startRuleUsageTracking.params", "commandParams", { method: "CSS.startRuleUsageTracking" }); export const StartRuleUsageTrackingResult = withCdpMeta(z.object({ }).passthrough(), "CSS.startRuleUsageTracking.result", "commandResult", { method: "CSS.startRuleUsageTracking" }); +export const StartRuleUsageTrackingCommand = withCdpCommand("CSS.startRuleUsageTracking", StartRuleUsageTrackingParams, StartRuleUsageTrackingResult); export const StopRuleUsageTrackingParams = withCdpMeta(z.object({ }).passthrough(), "CSS.stopRuleUsageTracking.params", "commandParams", { method: "CSS.stopRuleUsageTracking" }); export const StopRuleUsageTrackingResult = withCdpMeta(z.object({ "ruleUsage": z.array(z.lazy(() => RuleUsage)) }).passthrough(), "CSS.stopRuleUsageTracking.result", "commandResult", { method: "CSS.stopRuleUsageTracking" }); +export const StopRuleUsageTrackingCommand = withCdpCommand("CSS.stopRuleUsageTracking", StopRuleUsageTrackingParams, StopRuleUsageTrackingResult); export const TakeCoverageDeltaParams = withCdpMeta(z.object({ }).passthrough(), "CSS.takeCoverageDelta.params", "commandParams", { method: "CSS.takeCoverageDelta" }); export const TakeCoverageDeltaResult = withCdpMeta(z.object({ "coverage": z.array(z.lazy(() => RuleUsage)), "timestamp": z.number() }).passthrough(), "CSS.takeCoverageDelta.result", "commandResult", { method: "CSS.takeCoverageDelta" }); +export const TakeCoverageDeltaCommand = withCdpCommand("CSS.takeCoverageDelta", TakeCoverageDeltaParams, TakeCoverageDeltaResult); export const SetLocalFontsEnabledParams = withCdpMeta(z.object({ "enabled": z.boolean() }).passthrough(), "CSS.setLocalFontsEnabled.params", "commandParams", { method: "CSS.setLocalFontsEnabled" }); export const SetLocalFontsEnabledResult = withCdpMeta(z.object({ }).passthrough(), "CSS.setLocalFontsEnabled.result", "commandResult", { method: "CSS.setLocalFontsEnabled" }); +export const SetLocalFontsEnabledCommand = withCdpCommand("CSS.setLocalFontsEnabled", SetLocalFontsEnabledParams, SetLocalFontsEnabledResult); export const FontsUpdatedEvent = withCdpMeta(z.object({ "font": z.lazy(() => FontFace).optional() }).passthrough(), "CSS.fontsUpdated", "event", { phase: "event" }); export const MediaQueryResultChangedEvent = withCdpMeta(z.object({ }).passthrough(), "CSS.mediaQueryResultChanged", "event", { phase: "event" }); export const StyleSheetAddedEvent = withCdpMeta(z.object({ "header": z.lazy(() => CSSStyleSheetHeader) }).passthrough(), "CSS.styleSheetAdded", "event", { phase: "event" }); @@ -263,44 +301,44 @@ export const zod = { ComputedStyleUpdatedEvent: ComputedStyleUpdatedEvent, } as const; export const commands = { - "CSS.addRule": { params: AddRuleParams, result: AddRuleResult }, - "CSS.collectClassNames": { params: CollectClassNamesParams, result: CollectClassNamesResult }, - "CSS.createStyleSheet": { params: CreateStyleSheetParams, result: CreateStyleSheetResult }, - "CSS.disable": { params: DisableParams, result: DisableResult }, - "CSS.enable": { params: EnableParams, result: EnableResult }, - "CSS.forcePseudoState": { params: ForcePseudoStateParams, result: ForcePseudoStateResult }, - "CSS.forceStartingStyle": { params: ForceStartingStyleParams, result: ForceStartingStyleResult }, - "CSS.getBackgroundColors": { params: GetBackgroundColorsParams, result: GetBackgroundColorsResult }, - "CSS.getComputedStyleForNode": { params: GetComputedStyleForNodeParams, result: GetComputedStyleForNodeResult }, - "CSS.resolveValues": { params: ResolveValuesParams, result: ResolveValuesResult }, - "CSS.getLonghandProperties": { params: GetLonghandPropertiesParams, result: GetLonghandPropertiesResult }, - "CSS.getInlineStylesForNode": { params: GetInlineStylesForNodeParams, result: GetInlineStylesForNodeResult }, - "CSS.getAnimatedStylesForNode": { params: GetAnimatedStylesForNodeParams, result: GetAnimatedStylesForNodeResult }, - "CSS.getMatchedStylesForNode": { params: GetMatchedStylesForNodeParams, result: GetMatchedStylesForNodeResult }, - "CSS.getEnvironmentVariables": { params: GetEnvironmentVariablesParams, result: GetEnvironmentVariablesResult }, - "CSS.getMediaQueries": { params: GetMediaQueriesParams, result: GetMediaQueriesResult }, - "CSS.getPlatformFontsForNode": { params: GetPlatformFontsForNodeParams, result: GetPlatformFontsForNodeResult }, - "CSS.getStyleSheetText": { params: GetStyleSheetTextParams, result: GetStyleSheetTextResult }, - "CSS.getLayersForNode": { params: GetLayersForNodeParams, result: GetLayersForNodeResult }, - "CSS.getLocationForSelector": { params: GetLocationForSelectorParams, result: GetLocationForSelectorResult }, - "CSS.trackComputedStyleUpdatesForNode": { params: TrackComputedStyleUpdatesForNodeParams, result: TrackComputedStyleUpdatesForNodeResult }, - "CSS.trackComputedStyleUpdates": { params: TrackComputedStyleUpdatesParams, result: TrackComputedStyleUpdatesResult }, - "CSS.takeComputedStyleUpdates": { params: TakeComputedStyleUpdatesParams, result: TakeComputedStyleUpdatesResult }, - "CSS.setEffectivePropertyValueForNode": { params: SetEffectivePropertyValueForNodeParams, result: SetEffectivePropertyValueForNodeResult }, - "CSS.setPropertyRulePropertyName": { params: SetPropertyRulePropertyNameParams, result: SetPropertyRulePropertyNameResult }, - "CSS.setKeyframeKey": { params: SetKeyframeKeyParams, result: SetKeyframeKeyResult }, - "CSS.setMediaText": { params: SetMediaTextParams, result: SetMediaTextResult }, - "CSS.setContainerQueryText": { params: SetContainerQueryTextParams, result: SetContainerQueryTextResult }, - "CSS.setSupportsText": { params: SetSupportsTextParams, result: SetSupportsTextResult }, - "CSS.setNavigationText": { params: SetNavigationTextParams, result: SetNavigationTextResult }, - "CSS.setScopeText": { params: SetScopeTextParams, result: SetScopeTextResult }, - "CSS.setRuleSelector": { params: SetRuleSelectorParams, result: SetRuleSelectorResult }, - "CSS.setStyleSheetText": { params: SetStyleSheetTextParams, result: SetStyleSheetTextResult }, - "CSS.setStyleTexts": { params: SetStyleTextsParams, result: SetStyleTextsResult }, - "CSS.startRuleUsageTracking": { params: StartRuleUsageTrackingParams, result: StartRuleUsageTrackingResult }, - "CSS.stopRuleUsageTracking": { params: StopRuleUsageTrackingParams, result: StopRuleUsageTrackingResult }, - "CSS.takeCoverageDelta": { params: TakeCoverageDeltaParams, result: TakeCoverageDeltaResult }, - "CSS.setLocalFontsEnabled": { params: SetLocalFontsEnabledParams, result: SetLocalFontsEnabledResult }, + "CSS.addRule": AddRuleCommand, + "CSS.collectClassNames": CollectClassNamesCommand, + "CSS.createStyleSheet": CreateStyleSheetCommand, + "CSS.disable": DisableCommand, + "CSS.enable": EnableCommand, + "CSS.forcePseudoState": ForcePseudoStateCommand, + "CSS.forceStartingStyle": ForceStartingStyleCommand, + "CSS.getBackgroundColors": GetBackgroundColorsCommand, + "CSS.getComputedStyleForNode": GetComputedStyleForNodeCommand, + "CSS.resolveValues": ResolveValuesCommand, + "CSS.getLonghandProperties": GetLonghandPropertiesCommand, + "CSS.getInlineStylesForNode": GetInlineStylesForNodeCommand, + "CSS.getAnimatedStylesForNode": GetAnimatedStylesForNodeCommand, + "CSS.getMatchedStylesForNode": GetMatchedStylesForNodeCommand, + "CSS.getEnvironmentVariables": GetEnvironmentVariablesCommand, + "CSS.getMediaQueries": GetMediaQueriesCommand, + "CSS.getPlatformFontsForNode": GetPlatformFontsForNodeCommand, + "CSS.getStyleSheetText": GetStyleSheetTextCommand, + "CSS.getLayersForNode": GetLayersForNodeCommand, + "CSS.getLocationForSelector": GetLocationForSelectorCommand, + "CSS.trackComputedStyleUpdatesForNode": TrackComputedStyleUpdatesForNodeCommand, + "CSS.trackComputedStyleUpdates": TrackComputedStyleUpdatesCommand, + "CSS.takeComputedStyleUpdates": TakeComputedStyleUpdatesCommand, + "CSS.setEffectivePropertyValueForNode": SetEffectivePropertyValueForNodeCommand, + "CSS.setPropertyRulePropertyName": SetPropertyRulePropertyNameCommand, + "CSS.setKeyframeKey": SetKeyframeKeyCommand, + "CSS.setMediaText": SetMediaTextCommand, + "CSS.setContainerQueryText": SetContainerQueryTextCommand, + "CSS.setSupportsText": SetSupportsTextCommand, + "CSS.setNavigationText": SetNavigationTextCommand, + "CSS.setScopeText": SetScopeTextCommand, + "CSS.setRuleSelector": SetRuleSelectorCommand, + "CSS.setStyleSheetText": SetStyleSheetTextCommand, + "CSS.setStyleTexts": SetStyleTextsCommand, + "CSS.startRuleUsageTracking": StartRuleUsageTrackingCommand, + "CSS.stopRuleUsageTracking": StopRuleUsageTrackingCommand, + "CSS.takeCoverageDelta": TakeCoverageDeltaCommand, + "CSS.setLocalFontsEnabled": SetLocalFontsEnabledCommand, } as const; export const events = { "CSS.fontsUpdated": FontsUpdatedEvent, diff --git a/js/src/types/generated/zod/CacheStorage.ts b/js/src/types/generated/zod/CacheStorage.ts index 817a252..ea4fef1 100644 --- a/js/src/types/generated/zod/CacheStorage.ts +++ b/js/src/types/generated/zod/CacheStorage.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Storage from "./Storage.js"; export const CacheId = withCdpMeta(z.string(), "CacheStorage.CacheId", "type"); @@ -12,14 +12,19 @@ export const Header = withCdpMeta(z.object({ "name": z.string(), "value": z.stri export const CachedResponse = withCdpMeta(z.object({ "body": z.string() }).passthrough(), "CacheStorage.CachedResponse", "type"); export const DeleteCacheParams = withCdpMeta(z.object({ "cacheId": z.lazy(() => CacheId) }).passthrough(), "CacheStorage.deleteCache.params", "commandParams", { method: "CacheStorage.deleteCache" }); export const DeleteCacheResult = withCdpMeta(z.object({ }).passthrough(), "CacheStorage.deleteCache.result", "commandResult", { method: "CacheStorage.deleteCache" }); +export const DeleteCacheCommand = withCdpCommand("CacheStorage.deleteCache", DeleteCacheParams, DeleteCacheResult); export const DeleteEntryParams = withCdpMeta(z.object({ "cacheId": z.lazy(() => CacheId), "request": z.string() }).passthrough(), "CacheStorage.deleteEntry.params", "commandParams", { method: "CacheStorage.deleteEntry" }); export const DeleteEntryResult = withCdpMeta(z.object({ }).passthrough(), "CacheStorage.deleteEntry.result", "commandResult", { method: "CacheStorage.deleteEntry" }); +export const DeleteEntryCommand = withCdpCommand("CacheStorage.deleteEntry", DeleteEntryParams, DeleteEntryResult); export const RequestCacheNamesParams = withCdpMeta(z.object({ "securityOrigin": z.string().optional(), "storageKey": z.string().optional(), "storageBucket": z.lazy(() => Storage.StorageBucket).optional() }).passthrough().refine((value) => [value.securityOrigin, value.storageKey, value.storageBucket].filter((item) => item !== undefined).length === 1, { message: "Exactly one of securityOrigin, storageKey, or storageBucket must be provided." }), "CacheStorage.requestCacheNames.params", "commandParams", { method: "CacheStorage.requestCacheNames" }); export const RequestCacheNamesResult = withCdpMeta(z.object({ "caches": z.array(z.lazy(() => Cache)) }).passthrough(), "CacheStorage.requestCacheNames.result", "commandResult", { method: "CacheStorage.requestCacheNames" }); +export const RequestCacheNamesCommand = withCdpCommand("CacheStorage.requestCacheNames", RequestCacheNamesParams, RequestCacheNamesResult); export const RequestCachedResponseParams = withCdpMeta(z.object({ "cacheId": z.lazy(() => CacheId), "requestURL": z.string(), "requestHeaders": z.array(z.lazy(() => Header)) }).passthrough(), "CacheStorage.requestCachedResponse.params", "commandParams", { method: "CacheStorage.requestCachedResponse" }); export const RequestCachedResponseResult = withCdpMeta(z.object({ "response": z.lazy(() => CachedResponse) }).passthrough(), "CacheStorage.requestCachedResponse.result", "commandResult", { method: "CacheStorage.requestCachedResponse" }); +export const RequestCachedResponseCommand = withCdpCommand("CacheStorage.requestCachedResponse", RequestCachedResponseParams, RequestCachedResponseResult); export const RequestEntriesParams = withCdpMeta(z.object({ "cacheId": z.lazy(() => CacheId), "skipCount": z.number().int().optional(), "pageSize": z.number().int().optional(), "pathFilter": z.string().optional() }).passthrough(), "CacheStorage.requestEntries.params", "commandParams", { method: "CacheStorage.requestEntries" }); export const RequestEntriesResult = withCdpMeta(z.object({ "cacheDataEntries": z.array(z.lazy(() => DataEntry)), "returnCount": z.number() }).passthrough(), "CacheStorage.requestEntries.result", "commandResult", { method: "CacheStorage.requestEntries" }); +export const RequestEntriesCommand = withCdpCommand("CacheStorage.requestEntries", RequestEntriesParams, RequestEntriesResult); export const zod = { CacheId: CacheId, @@ -40,11 +45,11 @@ export const zod = { RequestEntriesResult: RequestEntriesResult, } as const; export const commands = { - "CacheStorage.deleteCache": { params: DeleteCacheParams, result: DeleteCacheResult }, - "CacheStorage.deleteEntry": { params: DeleteEntryParams, result: DeleteEntryResult }, - "CacheStorage.requestCacheNames": { params: RequestCacheNamesParams, result: RequestCacheNamesResult }, - "CacheStorage.requestCachedResponse": { params: RequestCachedResponseParams, result: RequestCachedResponseResult }, - "CacheStorage.requestEntries": { params: RequestEntriesParams, result: RequestEntriesResult }, + "CacheStorage.deleteCache": DeleteCacheCommand, + "CacheStorage.deleteEntry": DeleteEntryCommand, + "CacheStorage.requestCacheNames": RequestCacheNamesCommand, + "CacheStorage.requestCachedResponse": RequestCachedResponseCommand, + "CacheStorage.requestEntries": RequestEntriesCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/Cast.ts b/js/src/types/generated/zod/Cast.ts index e9f25dd..49c54af 100644 --- a/js/src/types/generated/zod/Cast.ts +++ b/js/src/types/generated/zod/Cast.ts @@ -1,21 +1,27 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const Sink = withCdpMeta(z.object({ "name": z.string(), "id": z.string(), "session": z.string().optional() }).passthrough(), "Cast.Sink", "type"); export const EnableParams = withCdpMeta(z.object({ "presentationUrl": z.string().optional() }).passthrough(), "Cast.enable.params", "commandParams", { method: "Cast.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Cast.enable.result", "commandResult", { method: "Cast.enable" }); +export const EnableCommand = withCdpCommand("Cast.enable", EnableParams, EnableResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Cast.disable.params", "commandParams", { method: "Cast.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Cast.disable.result", "commandResult", { method: "Cast.disable" }); +export const DisableCommand = withCdpCommand("Cast.disable", DisableParams, DisableResult); export const SetSinkToUseParams = withCdpMeta(z.object({ "sinkName": z.string() }).passthrough(), "Cast.setSinkToUse.params", "commandParams", { method: "Cast.setSinkToUse" }); export const SetSinkToUseResult = withCdpMeta(z.object({ }).passthrough(), "Cast.setSinkToUse.result", "commandResult", { method: "Cast.setSinkToUse" }); +export const SetSinkToUseCommand = withCdpCommand("Cast.setSinkToUse", SetSinkToUseParams, SetSinkToUseResult); export const StartDesktopMirroringParams = withCdpMeta(z.object({ "sinkName": z.string() }).passthrough(), "Cast.startDesktopMirroring.params", "commandParams", { method: "Cast.startDesktopMirroring" }); export const StartDesktopMirroringResult = withCdpMeta(z.object({ }).passthrough(), "Cast.startDesktopMirroring.result", "commandResult", { method: "Cast.startDesktopMirroring" }); +export const StartDesktopMirroringCommand = withCdpCommand("Cast.startDesktopMirroring", StartDesktopMirroringParams, StartDesktopMirroringResult); export const StartTabMirroringParams = withCdpMeta(z.object({ "sinkName": z.string() }).passthrough(), "Cast.startTabMirroring.params", "commandParams", { method: "Cast.startTabMirroring" }); export const StartTabMirroringResult = withCdpMeta(z.object({ }).passthrough(), "Cast.startTabMirroring.result", "commandResult", { method: "Cast.startTabMirroring" }); +export const StartTabMirroringCommand = withCdpCommand("Cast.startTabMirroring", StartTabMirroringParams, StartTabMirroringResult); export const StopCastingParams = withCdpMeta(z.object({ "sinkName": z.string() }).passthrough(), "Cast.stopCasting.params", "commandParams", { method: "Cast.stopCasting" }); export const StopCastingResult = withCdpMeta(z.object({ }).passthrough(), "Cast.stopCasting.result", "commandResult", { method: "Cast.stopCasting" }); +export const StopCastingCommand = withCdpCommand("Cast.stopCasting", StopCastingParams, StopCastingResult); export const SinksUpdatedEvent = withCdpMeta(z.object({ "sinks": z.array(z.lazy(() => Sink)) }).passthrough(), "Cast.sinksUpdated", "event", { phase: "event" }); export const IssueUpdatedEvent = withCdpMeta(z.object({ "issueMessage": z.string() }).passthrough(), "Cast.issueUpdated", "event", { phase: "event" }); @@ -37,12 +43,12 @@ export const zod = { IssueUpdatedEvent: IssueUpdatedEvent, } as const; export const commands = { - "Cast.enable": { params: EnableParams, result: EnableResult }, - "Cast.disable": { params: DisableParams, result: DisableResult }, - "Cast.setSinkToUse": { params: SetSinkToUseParams, result: SetSinkToUseResult }, - "Cast.startDesktopMirroring": { params: StartDesktopMirroringParams, result: StartDesktopMirroringResult }, - "Cast.startTabMirroring": { params: StartTabMirroringParams, result: StartTabMirroringResult }, - "Cast.stopCasting": { params: StopCastingParams, result: StopCastingResult }, + "Cast.enable": EnableCommand, + "Cast.disable": DisableCommand, + "Cast.setSinkToUse": SetSinkToUseCommand, + "Cast.startDesktopMirroring": StartDesktopMirroringCommand, + "Cast.startTabMirroring": StartTabMirroringCommand, + "Cast.stopCasting": StopCastingCommand, } as const; export const events = { "Cast.sinksUpdated": SinksUpdatedEvent, diff --git a/js/src/types/generated/zod/Console.ts b/js/src/types/generated/zod/Console.ts index d957942..723be27 100644 --- a/js/src/types/generated/zod/Console.ts +++ b/js/src/types/generated/zod/Console.ts @@ -1,15 +1,18 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const ConsoleMessage = withCdpMeta(z.object({ "source": z.enum(["xml", "javascript", "network", "console-api", "storage", "appcache", "rendering", "security", "other", "deprecation", "worker"]), "level": z.enum(["log", "warning", "error", "debug", "info"]), "text": z.string(), "url": z.string().optional(), "line": z.number().int().optional(), "column": z.number().int().optional() }).passthrough(), "Console.ConsoleMessage", "type"); export const ClearMessagesParams = withCdpMeta(z.object({ }).passthrough(), "Console.clearMessages.params", "commandParams", { method: "Console.clearMessages" }); export const ClearMessagesResult = withCdpMeta(z.object({ }).passthrough(), "Console.clearMessages.result", "commandResult", { method: "Console.clearMessages" }); +export const ClearMessagesCommand = withCdpCommand("Console.clearMessages", ClearMessagesParams, ClearMessagesResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Console.disable.params", "commandParams", { method: "Console.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Console.disable.result", "commandResult", { method: "Console.disable" }); +export const DisableCommand = withCdpCommand("Console.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "Console.enable.params", "commandParams", { method: "Console.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Console.enable.result", "commandResult", { method: "Console.enable" }); +export const EnableCommand = withCdpCommand("Console.enable", EnableParams, EnableResult); export const MessageAddedEvent = withCdpMeta(z.object({ "message": z.lazy(() => ConsoleMessage) }).passthrough(), "Console.messageAdded", "event", { phase: "event" }); export const zod = { @@ -23,9 +26,9 @@ export const zod = { MessageAddedEvent: MessageAddedEvent, } as const; export const commands = { - "Console.clearMessages": { params: ClearMessagesParams, result: ClearMessagesResult }, - "Console.disable": { params: DisableParams, result: DisableResult }, - "Console.enable": { params: EnableParams, result: EnableResult }, + "Console.clearMessages": ClearMessagesCommand, + "Console.disable": DisableCommand, + "Console.enable": EnableCommand, } as const; export const events = { "Console.messageAdded": MessageAddedEvent, diff --git a/js/src/types/generated/zod/CrashReportContext.ts b/js/src/types/generated/zod/CrashReportContext.ts index 75dc013..965715f 100644 --- a/js/src/types/generated/zod/CrashReportContext.ts +++ b/js/src/types/generated/zod/CrashReportContext.ts @@ -1,12 +1,13 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Page from "./Page.js"; export const CrashReportContextEntry = withCdpMeta(z.object({ "key": z.string(), "value": z.string(), "frameId": z.lazy(() => Page.FrameId) }).passthrough(), "CrashReportContext.CrashReportContextEntry", "type"); export const GetEntriesParams = withCdpMeta(z.object({ }).passthrough(), "CrashReportContext.getEntries.params", "commandParams", { method: "CrashReportContext.getEntries" }); export const GetEntriesResult = withCdpMeta(z.object({ "entries": z.array(z.lazy(() => CrashReportContextEntry)) }).passthrough(), "CrashReportContext.getEntries.result", "commandResult", { method: "CrashReportContext.getEntries" }); +export const GetEntriesCommand = withCdpCommand("CrashReportContext.getEntries", GetEntriesParams, GetEntriesResult); export const zod = { CrashReportContextEntry: CrashReportContextEntry, @@ -14,7 +15,7 @@ export const zod = { GetEntriesResult: GetEntriesResult, } as const; export const commands = { - "CrashReportContext.getEntries": { params: GetEntriesParams, result: GetEntriesResult }, + "CrashReportContext.getEntries": GetEntriesCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/DOM.ts b/js/src/types/generated/zod/DOM.ts index 0058ad5..72f2db8 100644 --- a/js/src/types/generated/zod/DOM.ts +++ b/js/src/types/generated/zod/DOM.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Network from "./Network.js"; import * as Page from "./Page.js"; import * as Runtime from "./Runtime.js"; @@ -26,110 +26,163 @@ export const Rect = withCdpMeta(z.object({ "x": z.number(), "y": z.number(), "wi export const CSSComputedStyleProperty = withCdpMeta(z.object({ "name": z.string(), "value": z.string() }).passthrough(), "DOM.CSSComputedStyleProperty", "type"); export const CollectClassNamesFromSubtreeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.collectClassNamesFromSubtree.params", "commandParams", { method: "DOM.collectClassNamesFromSubtree" }); export const CollectClassNamesFromSubtreeResult = withCdpMeta(z.object({ "classNames": z.array(z.string()) }).passthrough(), "DOM.collectClassNamesFromSubtree.result", "commandResult", { method: "DOM.collectClassNamesFromSubtree" }); +export const CollectClassNamesFromSubtreeCommand = withCdpCommand("DOM.collectClassNamesFromSubtree", CollectClassNamesFromSubtreeParams, CollectClassNamesFromSubtreeResult); export const CopyToParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "targetNodeId": z.lazy(() => NodeId), "insertBeforeNodeId": z.lazy(() => NodeId).optional() }).passthrough(), "DOM.copyTo.params", "commandParams", { method: "DOM.copyTo" }); export const CopyToResult = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.copyTo.result", "commandResult", { method: "DOM.copyTo" }); +export const CopyToCommand = withCdpCommand("DOM.copyTo", CopyToParams, CopyToResult); export const DescribeNodeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId).optional(), "backendNodeId": z.lazy(() => BackendNodeId).optional(), "objectId": z.lazy(() => Runtime.RemoteObjectId).optional(), "depth": z.number().int().optional(), "pierce": z.boolean().optional() }).passthrough(), "DOM.describeNode.params", "commandParams", { method: "DOM.describeNode" }); export const DescribeNodeResult = withCdpMeta(z.object({ "node": z.lazy(() => Node) }).passthrough(), "DOM.describeNode.result", "commandResult", { method: "DOM.describeNode" }); +export const DescribeNodeCommand = withCdpCommand("DOM.describeNode", DescribeNodeParams, DescribeNodeResult); export const ScrollIntoViewIfNeededParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId).optional(), "backendNodeId": z.lazy(() => BackendNodeId).optional(), "objectId": z.lazy(() => Runtime.RemoteObjectId).optional(), "rect": z.lazy(() => Rect).optional() }).passthrough(), "DOM.scrollIntoViewIfNeeded.params", "commandParams", { method: "DOM.scrollIntoViewIfNeeded" }); export const ScrollIntoViewIfNeededResult = withCdpMeta(z.object({ }).passthrough(), "DOM.scrollIntoViewIfNeeded.result", "commandResult", { method: "DOM.scrollIntoViewIfNeeded" }); +export const ScrollIntoViewIfNeededCommand = withCdpCommand("DOM.scrollIntoViewIfNeeded", ScrollIntoViewIfNeededParams, ScrollIntoViewIfNeededResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "DOM.disable.params", "commandParams", { method: "DOM.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "DOM.disable.result", "commandResult", { method: "DOM.disable" }); +export const DisableCommand = withCdpCommand("DOM.disable", DisableParams, DisableResult); export const DiscardSearchResultsParams = withCdpMeta(z.object({ "searchId": z.string() }).passthrough(), "DOM.discardSearchResults.params", "commandParams", { method: "DOM.discardSearchResults" }); export const DiscardSearchResultsResult = withCdpMeta(z.object({ }).passthrough(), "DOM.discardSearchResults.result", "commandResult", { method: "DOM.discardSearchResults" }); +export const DiscardSearchResultsCommand = withCdpCommand("DOM.discardSearchResults", DiscardSearchResultsParams, DiscardSearchResultsResult); export const EnableParams = withCdpMeta(z.object({ "includeWhitespace": z.enum(["none", "all"]).optional() }).passthrough(), "DOM.enable.params", "commandParams", { method: "DOM.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "DOM.enable.result", "commandResult", { method: "DOM.enable" }); +export const EnableCommand = withCdpCommand("DOM.enable", EnableParams, EnableResult); export const FocusParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId).optional(), "backendNodeId": z.lazy(() => BackendNodeId).optional(), "objectId": z.lazy(() => Runtime.RemoteObjectId).optional() }).passthrough(), "DOM.focus.params", "commandParams", { method: "DOM.focus" }); export const FocusResult = withCdpMeta(z.object({ }).passthrough(), "DOM.focus.result", "commandResult", { method: "DOM.focus" }); +export const FocusCommand = withCdpCommand("DOM.focus", FocusParams, FocusResult); export const GetAttributesParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.getAttributes.params", "commandParams", { method: "DOM.getAttributes" }); export const GetAttributesResult = withCdpMeta(z.object({ "attributes": z.array(z.string()) }).passthrough(), "DOM.getAttributes.result", "commandResult", { method: "DOM.getAttributes" }); +export const GetAttributesCommand = withCdpCommand("DOM.getAttributes", GetAttributesParams, GetAttributesResult); export const GetBoxModelParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId).optional(), "backendNodeId": z.lazy(() => BackendNodeId).optional(), "objectId": z.lazy(() => Runtime.RemoteObjectId).optional() }).passthrough(), "DOM.getBoxModel.params", "commandParams", { method: "DOM.getBoxModel" }); export const GetBoxModelResult = withCdpMeta(z.object({ "model": z.lazy(() => BoxModel) }).passthrough(), "DOM.getBoxModel.result", "commandResult", { method: "DOM.getBoxModel" }); +export const GetBoxModelCommand = withCdpCommand("DOM.getBoxModel", GetBoxModelParams, GetBoxModelResult); export const GetContentQuadsParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId).optional(), "backendNodeId": z.lazy(() => BackendNodeId).optional(), "objectId": z.lazy(() => Runtime.RemoteObjectId).optional() }).passthrough(), "DOM.getContentQuads.params", "commandParams", { method: "DOM.getContentQuads" }); export const GetContentQuadsResult = withCdpMeta(z.object({ "quads": z.array(z.lazy(() => Quad)) }).passthrough(), "DOM.getContentQuads.result", "commandResult", { method: "DOM.getContentQuads" }); +export const GetContentQuadsCommand = withCdpCommand("DOM.getContentQuads", GetContentQuadsParams, GetContentQuadsResult); export const GetDocumentParams = withCdpMeta(z.object({ "depth": z.number().int().optional(), "pierce": z.boolean().optional() }).passthrough(), "DOM.getDocument.params", "commandParams", { method: "DOM.getDocument" }); export const GetDocumentResult = withCdpMeta(z.object({ "root": z.lazy(() => Node) }).passthrough(), "DOM.getDocument.result", "commandResult", { method: "DOM.getDocument" }); +export const GetDocumentCommand = withCdpCommand("DOM.getDocument", GetDocumentParams, GetDocumentResult); export const GetFlattenedDocumentParams = withCdpMeta(z.object({ "depth": z.number().int().optional(), "pierce": z.boolean().optional() }).passthrough(), "DOM.getFlattenedDocument.params", "commandParams", { method: "DOM.getFlattenedDocument" }); export const GetFlattenedDocumentResult = withCdpMeta(z.object({ "nodes": z.array(z.lazy(() => Node)) }).passthrough(), "DOM.getFlattenedDocument.result", "commandResult", { method: "DOM.getFlattenedDocument" }); +export const GetFlattenedDocumentCommand = withCdpCommand("DOM.getFlattenedDocument", GetFlattenedDocumentParams, GetFlattenedDocumentResult); export const GetNodesForSubtreeByStyleParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "computedStyles": z.array(z.lazy(() => CSSComputedStyleProperty)), "pierce": z.boolean().optional() }).passthrough(), "DOM.getNodesForSubtreeByStyle.params", "commandParams", { method: "DOM.getNodesForSubtreeByStyle" }); export const GetNodesForSubtreeByStyleResult = withCdpMeta(z.object({ "nodeIds": z.array(z.lazy(() => NodeId)) }).passthrough(), "DOM.getNodesForSubtreeByStyle.result", "commandResult", { method: "DOM.getNodesForSubtreeByStyle" }); +export const GetNodesForSubtreeByStyleCommand = withCdpCommand("DOM.getNodesForSubtreeByStyle", GetNodesForSubtreeByStyleParams, GetNodesForSubtreeByStyleResult); export const GetNodeForLocationParams = withCdpMeta(z.object({ "x": z.number().int(), "y": z.number().int(), "includeUserAgentShadowDOM": z.boolean().optional(), "ignorePointerEventsNone": z.boolean().optional() }).passthrough(), "DOM.getNodeForLocation.params", "commandParams", { method: "DOM.getNodeForLocation" }); export const GetNodeForLocationResult = withCdpMeta(z.object({ "backendNodeId": z.lazy(() => BackendNodeId), "frameId": z.lazy(() => Page.FrameId), "nodeId": z.lazy(() => NodeId).optional() }).passthrough(), "DOM.getNodeForLocation.result", "commandResult", { method: "DOM.getNodeForLocation" }); +export const GetNodeForLocationCommand = withCdpCommand("DOM.getNodeForLocation", GetNodeForLocationParams, GetNodeForLocationResult); export const GetOuterHTMLParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId).optional(), "backendNodeId": z.lazy(() => BackendNodeId).optional(), "objectId": z.lazy(() => Runtime.RemoteObjectId).optional(), "includeShadowDOM": z.boolean().optional() }).passthrough(), "DOM.getOuterHTML.params", "commandParams", { method: "DOM.getOuterHTML" }); export const GetOuterHTMLResult = withCdpMeta(z.object({ "outerHTML": z.string() }).passthrough(), "DOM.getOuterHTML.result", "commandResult", { method: "DOM.getOuterHTML" }); +export const GetOuterHTMLCommand = withCdpCommand("DOM.getOuterHTML", GetOuterHTMLParams, GetOuterHTMLResult); export const GetRelayoutBoundaryParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.getRelayoutBoundary.params", "commandParams", { method: "DOM.getRelayoutBoundary" }); export const GetRelayoutBoundaryResult = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.getRelayoutBoundary.result", "commandResult", { method: "DOM.getRelayoutBoundary" }); +export const GetRelayoutBoundaryCommand = withCdpCommand("DOM.getRelayoutBoundary", GetRelayoutBoundaryParams, GetRelayoutBoundaryResult); export const GetSearchResultsParams = withCdpMeta(z.object({ "searchId": z.string(), "fromIndex": z.number().int(), "toIndex": z.number().int() }).passthrough(), "DOM.getSearchResults.params", "commandParams", { method: "DOM.getSearchResults" }); export const GetSearchResultsResult = withCdpMeta(z.object({ "nodeIds": z.array(z.lazy(() => NodeId)) }).passthrough(), "DOM.getSearchResults.result", "commandResult", { method: "DOM.getSearchResults" }); +export const GetSearchResultsCommand = withCdpCommand("DOM.getSearchResults", GetSearchResultsParams, GetSearchResultsResult); export const HideHighlightParams = withCdpMeta(z.object({ }).passthrough(), "DOM.hideHighlight.params", "commandParams", { method: "DOM.hideHighlight" }); export const HideHighlightResult = withCdpMeta(z.object({ }).passthrough(), "DOM.hideHighlight.result", "commandResult", { method: "DOM.hideHighlight" }); +export const HideHighlightCommand = withCdpCommand("DOM.hideHighlight", HideHighlightParams, HideHighlightResult); export const HighlightNodeParams = withCdpMeta(z.object({ }).passthrough(), "DOM.highlightNode.params", "commandParams", { method: "DOM.highlightNode" }); export const HighlightNodeResult = withCdpMeta(z.object({ }).passthrough(), "DOM.highlightNode.result", "commandResult", { method: "DOM.highlightNode" }); +export const HighlightNodeCommand = withCdpCommand("DOM.highlightNode", HighlightNodeParams, HighlightNodeResult); export const HighlightRectParams = withCdpMeta(z.object({ }).passthrough(), "DOM.highlightRect.params", "commandParams", { method: "DOM.highlightRect" }); export const HighlightRectResult = withCdpMeta(z.object({ }).passthrough(), "DOM.highlightRect.result", "commandResult", { method: "DOM.highlightRect" }); +export const HighlightRectCommand = withCdpCommand("DOM.highlightRect", HighlightRectParams, HighlightRectResult); export const MarkUndoableStateParams = withCdpMeta(z.object({ }).passthrough(), "DOM.markUndoableState.params", "commandParams", { method: "DOM.markUndoableState" }); export const MarkUndoableStateResult = withCdpMeta(z.object({ }).passthrough(), "DOM.markUndoableState.result", "commandResult", { method: "DOM.markUndoableState" }); +export const MarkUndoableStateCommand = withCdpCommand("DOM.markUndoableState", MarkUndoableStateParams, MarkUndoableStateResult); export const MoveToParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "targetNodeId": z.lazy(() => NodeId), "insertBeforeNodeId": z.lazy(() => NodeId).optional() }).passthrough(), "DOM.moveTo.params", "commandParams", { method: "DOM.moveTo" }); export const MoveToResult = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.moveTo.result", "commandResult", { method: "DOM.moveTo" }); +export const MoveToCommand = withCdpCommand("DOM.moveTo", MoveToParams, MoveToResult); export const PerformSearchParams = withCdpMeta(z.object({ "query": z.string(), "includeUserAgentShadowDOM": z.boolean().optional() }).passthrough(), "DOM.performSearch.params", "commandParams", { method: "DOM.performSearch" }); export const PerformSearchResult = withCdpMeta(z.object({ "searchId": z.string(), "resultCount": z.number().int() }).passthrough(), "DOM.performSearch.result", "commandResult", { method: "DOM.performSearch" }); +export const PerformSearchCommand = withCdpCommand("DOM.performSearch", PerformSearchParams, PerformSearchResult); export const PushNodeByPathToFrontendParams = withCdpMeta(z.object({ "path": z.string() }).passthrough(), "DOM.pushNodeByPathToFrontend.params", "commandParams", { method: "DOM.pushNodeByPathToFrontend" }); export const PushNodeByPathToFrontendResult = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.pushNodeByPathToFrontend.result", "commandResult", { method: "DOM.pushNodeByPathToFrontend" }); +export const PushNodeByPathToFrontendCommand = withCdpCommand("DOM.pushNodeByPathToFrontend", PushNodeByPathToFrontendParams, PushNodeByPathToFrontendResult); export const PushNodesByBackendIdsToFrontendParams = withCdpMeta(z.object({ "backendNodeIds": z.array(z.lazy(() => BackendNodeId)) }).passthrough(), "DOM.pushNodesByBackendIdsToFrontend.params", "commandParams", { method: "DOM.pushNodesByBackendIdsToFrontend" }); export const PushNodesByBackendIdsToFrontendResult = withCdpMeta(z.object({ "nodeIds": z.array(z.lazy(() => NodeId)) }).passthrough(), "DOM.pushNodesByBackendIdsToFrontend.result", "commandResult", { method: "DOM.pushNodesByBackendIdsToFrontend" }); +export const PushNodesByBackendIdsToFrontendCommand = withCdpCommand("DOM.pushNodesByBackendIdsToFrontend", PushNodesByBackendIdsToFrontendParams, PushNodesByBackendIdsToFrontendResult); export const QuerySelectorParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "selector": z.string() }).passthrough(), "DOM.querySelector.params", "commandParams", { method: "DOM.querySelector" }); export const QuerySelectorResult = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.querySelector.result", "commandResult", { method: "DOM.querySelector" }); +export const QuerySelectorCommand = withCdpCommand("DOM.querySelector", QuerySelectorParams, QuerySelectorResult); export const QuerySelectorAllParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "selector": z.string() }).passthrough(), "DOM.querySelectorAll.params", "commandParams", { method: "DOM.querySelectorAll" }); export const QuerySelectorAllResult = withCdpMeta(z.object({ "nodeIds": z.array(z.lazy(() => NodeId)) }).passthrough(), "DOM.querySelectorAll.result", "commandResult", { method: "DOM.querySelectorAll" }); +export const QuerySelectorAllCommand = withCdpCommand("DOM.querySelectorAll", QuerySelectorAllParams, QuerySelectorAllResult); export const GetTopLayerElementsParams = withCdpMeta(z.object({ }).passthrough(), "DOM.getTopLayerElements.params", "commandParams", { method: "DOM.getTopLayerElements" }); export const GetTopLayerElementsResult = withCdpMeta(z.object({ "nodeIds": z.array(z.lazy(() => NodeId)) }).passthrough(), "DOM.getTopLayerElements.result", "commandResult", { method: "DOM.getTopLayerElements" }); +export const GetTopLayerElementsCommand = withCdpCommand("DOM.getTopLayerElements", GetTopLayerElementsParams, GetTopLayerElementsResult); export const GetElementByRelationParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "relation": z.enum(["PopoverTarget", "InterestTarget", "CommandFor"]) }).passthrough(), "DOM.getElementByRelation.params", "commandParams", { method: "DOM.getElementByRelation" }); export const GetElementByRelationResult = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.getElementByRelation.result", "commandResult", { method: "DOM.getElementByRelation" }); +export const GetElementByRelationCommand = withCdpCommand("DOM.getElementByRelation", GetElementByRelationParams, GetElementByRelationResult); export const RedoParams = withCdpMeta(z.object({ }).passthrough(), "DOM.redo.params", "commandParams", { method: "DOM.redo" }); export const RedoResult = withCdpMeta(z.object({ }).passthrough(), "DOM.redo.result", "commandResult", { method: "DOM.redo" }); +export const RedoCommand = withCdpCommand("DOM.redo", RedoParams, RedoResult); export const RemoveAttributeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "name": z.string() }).passthrough(), "DOM.removeAttribute.params", "commandParams", { method: "DOM.removeAttribute" }); export const RemoveAttributeResult = withCdpMeta(z.object({ }).passthrough(), "DOM.removeAttribute.result", "commandResult", { method: "DOM.removeAttribute" }); +export const RemoveAttributeCommand = withCdpCommand("DOM.removeAttribute", RemoveAttributeParams, RemoveAttributeResult); export const RemoveNodeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.removeNode.params", "commandParams", { method: "DOM.removeNode" }); export const RemoveNodeResult = withCdpMeta(z.object({ }).passthrough(), "DOM.removeNode.result", "commandResult", { method: "DOM.removeNode" }); +export const RemoveNodeCommand = withCdpCommand("DOM.removeNode", RemoveNodeParams, RemoveNodeResult); export const RequestChildNodesParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "depth": z.number().int().optional(), "pierce": z.boolean().optional() }).passthrough(), "DOM.requestChildNodes.params", "commandParams", { method: "DOM.requestChildNodes" }); export const RequestChildNodesResult = withCdpMeta(z.object({ }).passthrough(), "DOM.requestChildNodes.result", "commandResult", { method: "DOM.requestChildNodes" }); +export const RequestChildNodesCommand = withCdpCommand("DOM.requestChildNodes", RequestChildNodesParams, RequestChildNodesResult); export const RequestNodeParams = withCdpMeta(z.object({ "objectId": z.lazy(() => Runtime.RemoteObjectId) }).passthrough(), "DOM.requestNode.params", "commandParams", { method: "DOM.requestNode" }); export const RequestNodeResult = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.requestNode.result", "commandResult", { method: "DOM.requestNode" }); +export const RequestNodeCommand = withCdpCommand("DOM.requestNode", RequestNodeParams, RequestNodeResult); export const ResolveNodeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId).optional(), "backendNodeId": z.lazy(() => BackendNodeId).optional(), "objectGroup": z.string().optional(), "executionContextId": z.lazy(() => Runtime.ExecutionContextId).optional() }).passthrough(), "DOM.resolveNode.params", "commandParams", { method: "DOM.resolveNode" }); export const ResolveNodeResult = withCdpMeta(z.object({ "object": z.lazy(() => Runtime.RemoteObject) }).passthrough(), "DOM.resolveNode.result", "commandResult", { method: "DOM.resolveNode" }); +export const ResolveNodeCommand = withCdpCommand("DOM.resolveNode", ResolveNodeParams, ResolveNodeResult); export const SetAttributeValueParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "name": z.string(), "value": z.string() }).passthrough(), "DOM.setAttributeValue.params", "commandParams", { method: "DOM.setAttributeValue" }); export const SetAttributeValueResult = withCdpMeta(z.object({ }).passthrough(), "DOM.setAttributeValue.result", "commandResult", { method: "DOM.setAttributeValue" }); +export const SetAttributeValueCommand = withCdpCommand("DOM.setAttributeValue", SetAttributeValueParams, SetAttributeValueResult); export const SetAttributesAsTextParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "text": z.string(), "name": z.string().optional() }).passthrough(), "DOM.setAttributesAsText.params", "commandParams", { method: "DOM.setAttributesAsText" }); export const SetAttributesAsTextResult = withCdpMeta(z.object({ }).passthrough(), "DOM.setAttributesAsText.result", "commandResult", { method: "DOM.setAttributesAsText" }); +export const SetAttributesAsTextCommand = withCdpCommand("DOM.setAttributesAsText", SetAttributesAsTextParams, SetAttributesAsTextResult); export const SetFileInputFilesParams = withCdpMeta(z.object({ "files": z.array(z.string()), "nodeId": z.lazy(() => NodeId).optional(), "backendNodeId": z.lazy(() => BackendNodeId).optional(), "objectId": z.lazy(() => Runtime.RemoteObjectId).optional() }).passthrough(), "DOM.setFileInputFiles.params", "commandParams", { method: "DOM.setFileInputFiles" }); export const SetFileInputFilesResult = withCdpMeta(z.object({ }).passthrough(), "DOM.setFileInputFiles.result", "commandResult", { method: "DOM.setFileInputFiles" }); +export const SetFileInputFilesCommand = withCdpCommand("DOM.setFileInputFiles", SetFileInputFilesParams, SetFileInputFilesResult); export const SetNodeStackTracesEnabledParams = withCdpMeta(z.object({ "enable": z.boolean() }).passthrough(), "DOM.setNodeStackTracesEnabled.params", "commandParams", { method: "DOM.setNodeStackTracesEnabled" }); export const SetNodeStackTracesEnabledResult = withCdpMeta(z.object({ }).passthrough(), "DOM.setNodeStackTracesEnabled.result", "commandResult", { method: "DOM.setNodeStackTracesEnabled" }); +export const SetNodeStackTracesEnabledCommand = withCdpCommand("DOM.setNodeStackTracesEnabled", SetNodeStackTracesEnabledParams, SetNodeStackTracesEnabledResult); export const GetNodeStackTracesParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.getNodeStackTraces.params", "commandParams", { method: "DOM.getNodeStackTraces" }); export const GetNodeStackTracesResult = withCdpMeta(z.object({ "creation": z.lazy(() => Runtime.StackTrace).optional() }).passthrough(), "DOM.getNodeStackTraces.result", "commandResult", { method: "DOM.getNodeStackTraces" }); +export const GetNodeStackTracesCommand = withCdpCommand("DOM.getNodeStackTraces", GetNodeStackTracesParams, GetNodeStackTracesResult); export const GetFileInfoParams = withCdpMeta(z.object({ "objectId": z.lazy(() => Runtime.RemoteObjectId) }).passthrough(), "DOM.getFileInfo.params", "commandParams", { method: "DOM.getFileInfo" }); export const GetFileInfoResult = withCdpMeta(z.object({ "path": z.string() }).passthrough(), "DOM.getFileInfo.result", "commandResult", { method: "DOM.getFileInfo" }); +export const GetFileInfoCommand = withCdpCommand("DOM.getFileInfo", GetFileInfoParams, GetFileInfoResult); export const GetDetachedDomNodesParams = withCdpMeta(z.object({ }).passthrough(), "DOM.getDetachedDomNodes.params", "commandParams", { method: "DOM.getDetachedDomNodes" }); export const GetDetachedDomNodesResult = withCdpMeta(z.object({ "detachedNodes": z.array(z.lazy(() => DetachedElementInfo)) }).passthrough(), "DOM.getDetachedDomNodes.result", "commandResult", { method: "DOM.getDetachedDomNodes" }); +export const GetDetachedDomNodesCommand = withCdpCommand("DOM.getDetachedDomNodes", GetDetachedDomNodesParams, GetDetachedDomNodesResult); export const SetInspectedNodeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.setInspectedNode.params", "commandParams", { method: "DOM.setInspectedNode" }); export const SetInspectedNodeResult = withCdpMeta(z.object({ }).passthrough(), "DOM.setInspectedNode.result", "commandResult", { method: "DOM.setInspectedNode" }); +export const SetInspectedNodeCommand = withCdpCommand("DOM.setInspectedNode", SetInspectedNodeParams, SetInspectedNodeResult); export const SetNodeNameParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "name": z.string() }).passthrough(), "DOM.setNodeName.params", "commandParams", { method: "DOM.setNodeName" }); export const SetNodeNameResult = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.setNodeName.result", "commandResult", { method: "DOM.setNodeName" }); +export const SetNodeNameCommand = withCdpCommand("DOM.setNodeName", SetNodeNameParams, SetNodeNameResult); export const SetNodeValueParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "value": z.string() }).passthrough(), "DOM.setNodeValue.params", "commandParams", { method: "DOM.setNodeValue" }); export const SetNodeValueResult = withCdpMeta(z.object({ }).passthrough(), "DOM.setNodeValue.result", "commandResult", { method: "DOM.setNodeValue" }); +export const SetNodeValueCommand = withCdpCommand("DOM.setNodeValue", SetNodeValueParams, SetNodeValueResult); export const SetOuterHTMLParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "outerHTML": z.string() }).passthrough(), "DOM.setOuterHTML.params", "commandParams", { method: "DOM.setOuterHTML" }); export const SetOuterHTMLResult = withCdpMeta(z.object({ }).passthrough(), "DOM.setOuterHTML.result", "commandResult", { method: "DOM.setOuterHTML" }); +export const SetOuterHTMLCommand = withCdpCommand("DOM.setOuterHTML", SetOuterHTMLParams, SetOuterHTMLResult); export const UndoParams = withCdpMeta(z.object({ }).passthrough(), "DOM.undo.params", "commandParams", { method: "DOM.undo" }); export const UndoResult = withCdpMeta(z.object({ }).passthrough(), "DOM.undo.result", "commandResult", { method: "DOM.undo" }); +export const UndoCommand = withCdpCommand("DOM.undo", UndoParams, UndoResult); export const GetFrameOwnerParams = withCdpMeta(z.object({ "frameId": z.lazy(() => Page.FrameId) }).passthrough(), "DOM.getFrameOwner.params", "commandParams", { method: "DOM.getFrameOwner" }); export const GetFrameOwnerResult = withCdpMeta(z.object({ "backendNodeId": z.lazy(() => BackendNodeId), "nodeId": z.lazy(() => NodeId).optional() }).passthrough(), "DOM.getFrameOwner.result", "commandResult", { method: "DOM.getFrameOwner" }); +export const GetFrameOwnerCommand = withCdpCommand("DOM.getFrameOwner", GetFrameOwnerParams, GetFrameOwnerResult); export const GetContainerForNodeParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "containerName": z.string().optional(), "physicalAxes": z.lazy(() => PhysicalAxes).optional(), "logicalAxes": z.lazy(() => LogicalAxes).optional(), "queriesScrollState": z.boolean().optional(), "queriesAnchored": z.boolean().optional() }).passthrough(), "DOM.getContainerForNode.params", "commandParams", { method: "DOM.getContainerForNode" }); export const GetContainerForNodeResult = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId).optional() }).passthrough(), "DOM.getContainerForNode.result", "commandResult", { method: "DOM.getContainerForNode" }); +export const GetContainerForNodeCommand = withCdpCommand("DOM.getContainerForNode", GetContainerForNodeParams, GetContainerForNodeResult); export const GetQueryingDescendantsForContainerParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.getQueryingDescendantsForContainer.params", "commandParams", { method: "DOM.getQueryingDescendantsForContainer" }); export const GetQueryingDescendantsForContainerResult = withCdpMeta(z.object({ "nodeIds": z.array(z.lazy(() => NodeId)) }).passthrough(), "DOM.getQueryingDescendantsForContainer.result", "commandResult", { method: "DOM.getQueryingDescendantsForContainer" }); +export const GetQueryingDescendantsForContainerCommand = withCdpCommand("DOM.getQueryingDescendantsForContainer", GetQueryingDescendantsForContainerParams, GetQueryingDescendantsForContainerResult); export const GetAnchorElementParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "anchorSpecifier": z.string().optional() }).passthrough(), "DOM.getAnchorElement.params", "commandParams", { method: "DOM.getAnchorElement" }); export const GetAnchorElementResult = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId) }).passthrough(), "DOM.getAnchorElement.result", "commandResult", { method: "DOM.getAnchorElement" }); +export const GetAnchorElementCommand = withCdpCommand("DOM.getAnchorElement", GetAnchorElementParams, GetAnchorElementResult); export const ForceShowPopoverParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "enable": z.boolean() }).passthrough(), "DOM.forceShowPopover.params", "commandParams", { method: "DOM.forceShowPopover" }); export const ForceShowPopoverResult = withCdpMeta(z.object({ "nodeIds": z.array(z.lazy(() => NodeId)) }).passthrough(), "DOM.forceShowPopover.result", "commandResult", { method: "DOM.forceShowPopover" }); +export const ForceShowPopoverCommand = withCdpCommand("DOM.forceShowPopover", ForceShowPopoverParams, ForceShowPopoverResult); export const AttributeModifiedEvent = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "name": z.string(), "value": z.string() }).passthrough(), "DOM.attributeModified", "event", { phase: "event" }); export const AdoptedStyleSheetsModifiedEvent = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "adoptedStyleSheets": z.array(z.lazy(() => StyleSheetId)) }).passthrough(), "DOM.adoptedStyleSheetsModified", "event", { phase: "event" }); export const AttributeRemovedEvent = withCdpMeta(z.object({ "nodeId": z.lazy(() => NodeId), "name": z.string() }).passthrough(), "DOM.attributeRemoved", "event", { phase: "event" }); @@ -296,59 +349,59 @@ export const zod = { ShadowRootPushedEvent: ShadowRootPushedEvent, } as const; export const commands = { - "DOM.collectClassNamesFromSubtree": { params: CollectClassNamesFromSubtreeParams, result: CollectClassNamesFromSubtreeResult }, - "DOM.copyTo": { params: CopyToParams, result: CopyToResult }, - "DOM.describeNode": { params: DescribeNodeParams, result: DescribeNodeResult }, - "DOM.scrollIntoViewIfNeeded": { params: ScrollIntoViewIfNeededParams, result: ScrollIntoViewIfNeededResult }, - "DOM.disable": { params: DisableParams, result: DisableResult }, - "DOM.discardSearchResults": { params: DiscardSearchResultsParams, result: DiscardSearchResultsResult }, - "DOM.enable": { params: EnableParams, result: EnableResult }, - "DOM.focus": { params: FocusParams, result: FocusResult }, - "DOM.getAttributes": { params: GetAttributesParams, result: GetAttributesResult }, - "DOM.getBoxModel": { params: GetBoxModelParams, result: GetBoxModelResult }, - "DOM.getContentQuads": { params: GetContentQuadsParams, result: GetContentQuadsResult }, - "DOM.getDocument": { params: GetDocumentParams, result: GetDocumentResult }, - "DOM.getFlattenedDocument": { params: GetFlattenedDocumentParams, result: GetFlattenedDocumentResult }, - "DOM.getNodesForSubtreeByStyle": { params: GetNodesForSubtreeByStyleParams, result: GetNodesForSubtreeByStyleResult }, - "DOM.getNodeForLocation": { params: GetNodeForLocationParams, result: GetNodeForLocationResult }, - "DOM.getOuterHTML": { params: GetOuterHTMLParams, result: GetOuterHTMLResult }, - "DOM.getRelayoutBoundary": { params: GetRelayoutBoundaryParams, result: GetRelayoutBoundaryResult }, - "DOM.getSearchResults": { params: GetSearchResultsParams, result: GetSearchResultsResult }, - "DOM.hideHighlight": { params: HideHighlightParams, result: HideHighlightResult }, - "DOM.highlightNode": { params: HighlightNodeParams, result: HighlightNodeResult }, - "DOM.highlightRect": { params: HighlightRectParams, result: HighlightRectResult }, - "DOM.markUndoableState": { params: MarkUndoableStateParams, result: MarkUndoableStateResult }, - "DOM.moveTo": { params: MoveToParams, result: MoveToResult }, - "DOM.performSearch": { params: PerformSearchParams, result: PerformSearchResult }, - "DOM.pushNodeByPathToFrontend": { params: PushNodeByPathToFrontendParams, result: PushNodeByPathToFrontendResult }, - "DOM.pushNodesByBackendIdsToFrontend": { params: PushNodesByBackendIdsToFrontendParams, result: PushNodesByBackendIdsToFrontendResult }, - "DOM.querySelector": { params: QuerySelectorParams, result: QuerySelectorResult }, - "DOM.querySelectorAll": { params: QuerySelectorAllParams, result: QuerySelectorAllResult }, - "DOM.getTopLayerElements": { params: GetTopLayerElementsParams, result: GetTopLayerElementsResult }, - "DOM.getElementByRelation": { params: GetElementByRelationParams, result: GetElementByRelationResult }, - "DOM.redo": { params: RedoParams, result: RedoResult }, - "DOM.removeAttribute": { params: RemoveAttributeParams, result: RemoveAttributeResult }, - "DOM.removeNode": { params: RemoveNodeParams, result: RemoveNodeResult }, - "DOM.requestChildNodes": { params: RequestChildNodesParams, result: RequestChildNodesResult }, - "DOM.requestNode": { params: RequestNodeParams, result: RequestNodeResult }, - "DOM.resolveNode": { params: ResolveNodeParams, result: ResolveNodeResult }, - "DOM.setAttributeValue": { params: SetAttributeValueParams, result: SetAttributeValueResult }, - "DOM.setAttributesAsText": { params: SetAttributesAsTextParams, result: SetAttributesAsTextResult }, - "DOM.setFileInputFiles": { params: SetFileInputFilesParams, result: SetFileInputFilesResult }, - "DOM.setNodeStackTracesEnabled": { params: SetNodeStackTracesEnabledParams, result: SetNodeStackTracesEnabledResult }, - "DOM.getNodeStackTraces": { params: GetNodeStackTracesParams, result: GetNodeStackTracesResult }, - "DOM.getFileInfo": { params: GetFileInfoParams, result: GetFileInfoResult }, - "DOM.getDetachedDomNodes": { params: GetDetachedDomNodesParams, result: GetDetachedDomNodesResult }, - "DOM.setInspectedNode": { params: SetInspectedNodeParams, result: SetInspectedNodeResult }, - "DOM.setNodeName": { params: SetNodeNameParams, result: SetNodeNameResult }, - "DOM.setNodeValue": { params: SetNodeValueParams, result: SetNodeValueResult }, - "DOM.setOuterHTML": { params: SetOuterHTMLParams, result: SetOuterHTMLResult }, - "DOM.undo": { params: UndoParams, result: UndoResult }, - "DOM.getFrameOwner": { params: GetFrameOwnerParams, result: GetFrameOwnerResult }, - "DOM.getContainerForNode": { params: GetContainerForNodeParams, result: GetContainerForNodeResult }, - "DOM.getQueryingDescendantsForContainer": { params: GetQueryingDescendantsForContainerParams, result: GetQueryingDescendantsForContainerResult }, - "DOM.getAnchorElement": { params: GetAnchorElementParams, result: GetAnchorElementResult }, - "DOM.forceShowPopover": { params: ForceShowPopoverParams, result: ForceShowPopoverResult }, + "DOM.collectClassNamesFromSubtree": CollectClassNamesFromSubtreeCommand, + "DOM.copyTo": CopyToCommand, + "DOM.describeNode": DescribeNodeCommand, + "DOM.scrollIntoViewIfNeeded": ScrollIntoViewIfNeededCommand, + "DOM.disable": DisableCommand, + "DOM.discardSearchResults": DiscardSearchResultsCommand, + "DOM.enable": EnableCommand, + "DOM.focus": FocusCommand, + "DOM.getAttributes": GetAttributesCommand, + "DOM.getBoxModel": GetBoxModelCommand, + "DOM.getContentQuads": GetContentQuadsCommand, + "DOM.getDocument": GetDocumentCommand, + "DOM.getFlattenedDocument": GetFlattenedDocumentCommand, + "DOM.getNodesForSubtreeByStyle": GetNodesForSubtreeByStyleCommand, + "DOM.getNodeForLocation": GetNodeForLocationCommand, + "DOM.getOuterHTML": GetOuterHTMLCommand, + "DOM.getRelayoutBoundary": GetRelayoutBoundaryCommand, + "DOM.getSearchResults": GetSearchResultsCommand, + "DOM.hideHighlight": HideHighlightCommand, + "DOM.highlightNode": HighlightNodeCommand, + "DOM.highlightRect": HighlightRectCommand, + "DOM.markUndoableState": MarkUndoableStateCommand, + "DOM.moveTo": MoveToCommand, + "DOM.performSearch": PerformSearchCommand, + "DOM.pushNodeByPathToFrontend": PushNodeByPathToFrontendCommand, + "DOM.pushNodesByBackendIdsToFrontend": PushNodesByBackendIdsToFrontendCommand, + "DOM.querySelector": QuerySelectorCommand, + "DOM.querySelectorAll": QuerySelectorAllCommand, + "DOM.getTopLayerElements": GetTopLayerElementsCommand, + "DOM.getElementByRelation": GetElementByRelationCommand, + "DOM.redo": RedoCommand, + "DOM.removeAttribute": RemoveAttributeCommand, + "DOM.removeNode": RemoveNodeCommand, + "DOM.requestChildNodes": RequestChildNodesCommand, + "DOM.requestNode": RequestNodeCommand, + "DOM.resolveNode": ResolveNodeCommand, + "DOM.setAttributeValue": SetAttributeValueCommand, + "DOM.setAttributesAsText": SetAttributesAsTextCommand, + "DOM.setFileInputFiles": SetFileInputFilesCommand, + "DOM.setNodeStackTracesEnabled": SetNodeStackTracesEnabledCommand, + "DOM.getNodeStackTraces": GetNodeStackTracesCommand, + "DOM.getFileInfo": GetFileInfoCommand, + "DOM.getDetachedDomNodes": GetDetachedDomNodesCommand, + "DOM.setInspectedNode": SetInspectedNodeCommand, + "DOM.setNodeName": SetNodeNameCommand, + "DOM.setNodeValue": SetNodeValueCommand, + "DOM.setOuterHTML": SetOuterHTMLCommand, + "DOM.undo": UndoCommand, + "DOM.getFrameOwner": GetFrameOwnerCommand, + "DOM.getContainerForNode": GetContainerForNodeCommand, + "DOM.getQueryingDescendantsForContainer": GetQueryingDescendantsForContainerCommand, + "DOM.getAnchorElement": GetAnchorElementCommand, + "DOM.forceShowPopover": ForceShowPopoverCommand, } as const; export const events = { "DOM.attributeModified": AttributeModifiedEvent, diff --git a/js/src/types/generated/zod/DOMDebugger.ts b/js/src/types/generated/zod/DOMDebugger.ts index b307386..617961b 100644 --- a/js/src/types/generated/zod/DOMDebugger.ts +++ b/js/src/types/generated/zod/DOMDebugger.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; import * as Runtime from "./Runtime.js"; @@ -10,24 +10,34 @@ export const CSPViolationType = withCdpMeta(z.enum(["trustedtype-sink-violation" export const EventListener = withCdpMeta(z.object({ "type": z.string(), "useCapture": z.boolean(), "passive": z.boolean(), "once": z.boolean(), "scriptId": z.lazy(() => Runtime.ScriptId), "lineNumber": z.number().int(), "columnNumber": z.number().int(), "handler": z.lazy(() => Runtime.RemoteObject).optional(), "originalHandler": z.lazy(() => Runtime.RemoteObject).optional(), "backendNodeId": z.lazy(() => DOM.BackendNodeId).optional() }).passthrough(), "DOMDebugger.EventListener", "type"); export const GetEventListenersParams = withCdpMeta(z.object({ "objectId": z.lazy(() => Runtime.RemoteObjectId), "depth": z.number().int().optional(), "pierce": z.boolean().optional() }).passthrough(), "DOMDebugger.getEventListeners.params", "commandParams", { method: "DOMDebugger.getEventListeners" }); export const GetEventListenersResult = withCdpMeta(z.object({ "listeners": z.array(z.lazy(() => EventListener)) }).passthrough(), "DOMDebugger.getEventListeners.result", "commandResult", { method: "DOMDebugger.getEventListeners" }); +export const GetEventListenersCommand = withCdpCommand("DOMDebugger.getEventListeners", GetEventListenersParams, GetEventListenersResult); export const RemoveDOMBreakpointParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId), "type": z.lazy(() => DOMBreakpointType) }).passthrough(), "DOMDebugger.removeDOMBreakpoint.params", "commandParams", { method: "DOMDebugger.removeDOMBreakpoint" }); export const RemoveDOMBreakpointResult = withCdpMeta(z.object({ }).passthrough(), "DOMDebugger.removeDOMBreakpoint.result", "commandResult", { method: "DOMDebugger.removeDOMBreakpoint" }); +export const RemoveDOMBreakpointCommand = withCdpCommand("DOMDebugger.removeDOMBreakpoint", RemoveDOMBreakpointParams, RemoveDOMBreakpointResult); export const RemoveEventListenerBreakpointParams = withCdpMeta(z.object({ "eventName": z.string(), "targetName": z.string().optional() }).passthrough(), "DOMDebugger.removeEventListenerBreakpoint.params", "commandParams", { method: "DOMDebugger.removeEventListenerBreakpoint" }); export const RemoveEventListenerBreakpointResult = withCdpMeta(z.object({ }).passthrough(), "DOMDebugger.removeEventListenerBreakpoint.result", "commandResult", { method: "DOMDebugger.removeEventListenerBreakpoint" }); +export const RemoveEventListenerBreakpointCommand = withCdpCommand("DOMDebugger.removeEventListenerBreakpoint", RemoveEventListenerBreakpointParams, RemoveEventListenerBreakpointResult); export const RemoveInstrumentationBreakpointParams = withCdpMeta(z.object({ "eventName": z.string() }).passthrough(), "DOMDebugger.removeInstrumentationBreakpoint.params", "commandParams", { method: "DOMDebugger.removeInstrumentationBreakpoint" }); export const RemoveInstrumentationBreakpointResult = withCdpMeta(z.object({ }).passthrough(), "DOMDebugger.removeInstrumentationBreakpoint.result", "commandResult", { method: "DOMDebugger.removeInstrumentationBreakpoint" }); +export const RemoveInstrumentationBreakpointCommand = withCdpCommand("DOMDebugger.removeInstrumentationBreakpoint", RemoveInstrumentationBreakpointParams, RemoveInstrumentationBreakpointResult); export const RemoveXHRBreakpointParams = withCdpMeta(z.object({ "url": z.string() }).passthrough(), "DOMDebugger.removeXHRBreakpoint.params", "commandParams", { method: "DOMDebugger.removeXHRBreakpoint" }); export const RemoveXHRBreakpointResult = withCdpMeta(z.object({ }).passthrough(), "DOMDebugger.removeXHRBreakpoint.result", "commandResult", { method: "DOMDebugger.removeXHRBreakpoint" }); +export const RemoveXHRBreakpointCommand = withCdpCommand("DOMDebugger.removeXHRBreakpoint", RemoveXHRBreakpointParams, RemoveXHRBreakpointResult); export const SetBreakOnCSPViolationParams = withCdpMeta(z.object({ "violationTypes": z.array(z.lazy(() => CSPViolationType)) }).passthrough(), "DOMDebugger.setBreakOnCSPViolation.params", "commandParams", { method: "DOMDebugger.setBreakOnCSPViolation" }); export const SetBreakOnCSPViolationResult = withCdpMeta(z.object({ }).passthrough(), "DOMDebugger.setBreakOnCSPViolation.result", "commandResult", { method: "DOMDebugger.setBreakOnCSPViolation" }); +export const SetBreakOnCSPViolationCommand = withCdpCommand("DOMDebugger.setBreakOnCSPViolation", SetBreakOnCSPViolationParams, SetBreakOnCSPViolationResult); export const SetDOMBreakpointParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId), "type": z.lazy(() => DOMBreakpointType) }).passthrough(), "DOMDebugger.setDOMBreakpoint.params", "commandParams", { method: "DOMDebugger.setDOMBreakpoint" }); export const SetDOMBreakpointResult = withCdpMeta(z.object({ }).passthrough(), "DOMDebugger.setDOMBreakpoint.result", "commandResult", { method: "DOMDebugger.setDOMBreakpoint" }); +export const SetDOMBreakpointCommand = withCdpCommand("DOMDebugger.setDOMBreakpoint", SetDOMBreakpointParams, SetDOMBreakpointResult); export const SetEventListenerBreakpointParams = withCdpMeta(z.object({ "eventName": z.string(), "targetName": z.string().optional() }).passthrough(), "DOMDebugger.setEventListenerBreakpoint.params", "commandParams", { method: "DOMDebugger.setEventListenerBreakpoint" }); export const SetEventListenerBreakpointResult = withCdpMeta(z.object({ }).passthrough(), "DOMDebugger.setEventListenerBreakpoint.result", "commandResult", { method: "DOMDebugger.setEventListenerBreakpoint" }); +export const SetEventListenerBreakpointCommand = withCdpCommand("DOMDebugger.setEventListenerBreakpoint", SetEventListenerBreakpointParams, SetEventListenerBreakpointResult); export const SetInstrumentationBreakpointParams = withCdpMeta(z.object({ "eventName": z.string() }).passthrough(), "DOMDebugger.setInstrumentationBreakpoint.params", "commandParams", { method: "DOMDebugger.setInstrumentationBreakpoint" }); export const SetInstrumentationBreakpointResult = withCdpMeta(z.object({ }).passthrough(), "DOMDebugger.setInstrumentationBreakpoint.result", "commandResult", { method: "DOMDebugger.setInstrumentationBreakpoint" }); +export const SetInstrumentationBreakpointCommand = withCdpCommand("DOMDebugger.setInstrumentationBreakpoint", SetInstrumentationBreakpointParams, SetInstrumentationBreakpointResult); export const SetXHRBreakpointParams = withCdpMeta(z.object({ "url": z.string() }).passthrough(), "DOMDebugger.setXHRBreakpoint.params", "commandParams", { method: "DOMDebugger.setXHRBreakpoint" }); export const SetXHRBreakpointResult = withCdpMeta(z.object({ }).passthrough(), "DOMDebugger.setXHRBreakpoint.result", "commandResult", { method: "DOMDebugger.setXHRBreakpoint" }); +export const SetXHRBreakpointCommand = withCdpCommand("DOMDebugger.setXHRBreakpoint", SetXHRBreakpointParams, SetXHRBreakpointResult); export const zod = { DOMBreakpointType: DOMBreakpointType, @@ -55,16 +65,16 @@ export const zod = { SetXHRBreakpointResult: SetXHRBreakpointResult, } as const; export const commands = { - "DOMDebugger.getEventListeners": { params: GetEventListenersParams, result: GetEventListenersResult }, - "DOMDebugger.removeDOMBreakpoint": { params: RemoveDOMBreakpointParams, result: RemoveDOMBreakpointResult }, - "DOMDebugger.removeEventListenerBreakpoint": { params: RemoveEventListenerBreakpointParams, result: RemoveEventListenerBreakpointResult }, - "DOMDebugger.removeInstrumentationBreakpoint": { params: RemoveInstrumentationBreakpointParams, result: RemoveInstrumentationBreakpointResult }, - "DOMDebugger.removeXHRBreakpoint": { params: RemoveXHRBreakpointParams, result: RemoveXHRBreakpointResult }, - "DOMDebugger.setBreakOnCSPViolation": { params: SetBreakOnCSPViolationParams, result: SetBreakOnCSPViolationResult }, - "DOMDebugger.setDOMBreakpoint": { params: SetDOMBreakpointParams, result: SetDOMBreakpointResult }, - "DOMDebugger.setEventListenerBreakpoint": { params: SetEventListenerBreakpointParams, result: SetEventListenerBreakpointResult }, - "DOMDebugger.setInstrumentationBreakpoint": { params: SetInstrumentationBreakpointParams, result: SetInstrumentationBreakpointResult }, - "DOMDebugger.setXHRBreakpoint": { params: SetXHRBreakpointParams, result: SetXHRBreakpointResult }, + "DOMDebugger.getEventListeners": GetEventListenersCommand, + "DOMDebugger.removeDOMBreakpoint": RemoveDOMBreakpointCommand, + "DOMDebugger.removeEventListenerBreakpoint": RemoveEventListenerBreakpointCommand, + "DOMDebugger.removeInstrumentationBreakpoint": RemoveInstrumentationBreakpointCommand, + "DOMDebugger.removeXHRBreakpoint": RemoveXHRBreakpointCommand, + "DOMDebugger.setBreakOnCSPViolation": SetBreakOnCSPViolationCommand, + "DOMDebugger.setDOMBreakpoint": SetDOMBreakpointCommand, + "DOMDebugger.setEventListenerBreakpoint": SetEventListenerBreakpointCommand, + "DOMDebugger.setInstrumentationBreakpoint": SetInstrumentationBreakpointCommand, + "DOMDebugger.setXHRBreakpoint": SetXHRBreakpointCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/DOMSnapshot.ts b/js/src/types/generated/zod/DOMSnapshot.ts index 1b855c2..636a957 100644 --- a/js/src/types/generated/zod/DOMSnapshot.ts +++ b/js/src/types/generated/zod/DOMSnapshot.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; import * as DOMDebugger from "./DOMDebugger.js"; import * as Page from "./Page.js"; @@ -23,12 +23,16 @@ export const LayoutTreeSnapshot = withCdpMeta(z.object({ "nodeIndex": z.array(z. export const TextBoxSnapshot = withCdpMeta(z.object({ "layoutIndex": z.array(z.number().int()), "bounds": z.array(z.lazy(() => Rectangle)), "start": z.array(z.number().int()), "length": z.array(z.number().int()) }).passthrough(), "DOMSnapshot.TextBoxSnapshot", "type"); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "DOMSnapshot.disable.params", "commandParams", { method: "DOMSnapshot.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "DOMSnapshot.disable.result", "commandResult", { method: "DOMSnapshot.disable" }); +export const DisableCommand = withCdpCommand("DOMSnapshot.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "DOMSnapshot.enable.params", "commandParams", { method: "DOMSnapshot.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "DOMSnapshot.enable.result", "commandResult", { method: "DOMSnapshot.enable" }); +export const EnableCommand = withCdpCommand("DOMSnapshot.enable", EnableParams, EnableResult); export const GetSnapshotParams = withCdpMeta(z.object({ "computedStyleWhitelist": z.array(z.string()), "includeEventListeners": z.boolean().optional(), "includePaintOrder": z.boolean().optional(), "includeUserAgentShadowTree": z.boolean().optional() }).passthrough(), "DOMSnapshot.getSnapshot.params", "commandParams", { method: "DOMSnapshot.getSnapshot" }); export const GetSnapshotResult = withCdpMeta(z.object({ "domNodes": z.array(z.lazy(() => DOMNode)), "layoutTreeNodes": z.array(z.lazy(() => LayoutTreeNode)), "computedStyles": z.array(z.lazy(() => ComputedStyle)) }).passthrough(), "DOMSnapshot.getSnapshot.result", "commandResult", { method: "DOMSnapshot.getSnapshot" }); +export const GetSnapshotCommand = withCdpCommand("DOMSnapshot.getSnapshot", GetSnapshotParams, GetSnapshotResult); export const CaptureSnapshotParams = withCdpMeta(z.object({ "computedStyles": z.array(z.string()), "includePaintOrder": z.boolean().optional(), "includeDOMRects": z.boolean().optional(), "includeBlendedBackgroundColors": z.boolean().optional(), "includeTextColorOpacities": z.boolean().optional() }).passthrough(), "DOMSnapshot.captureSnapshot.params", "commandParams", { method: "DOMSnapshot.captureSnapshot" }); export const CaptureSnapshotResult = withCdpMeta(z.object({ "documents": z.array(z.lazy(() => DocumentSnapshot)), "strings": z.array(z.string()) }).passthrough(), "DOMSnapshot.captureSnapshot.result", "commandResult", { method: "DOMSnapshot.captureSnapshot" }); +export const CaptureSnapshotCommand = withCdpCommand("DOMSnapshot.captureSnapshot", CaptureSnapshotParams, CaptureSnapshotResult); export const zod = { DOMNode: DOMNode, @@ -56,10 +60,10 @@ export const zod = { CaptureSnapshotResult: CaptureSnapshotResult, } as const; export const commands = { - "DOMSnapshot.disable": { params: DisableParams, result: DisableResult }, - "DOMSnapshot.enable": { params: EnableParams, result: EnableResult }, - "DOMSnapshot.getSnapshot": { params: GetSnapshotParams, result: GetSnapshotResult }, - "DOMSnapshot.captureSnapshot": { params: CaptureSnapshotParams, result: CaptureSnapshotResult }, + "DOMSnapshot.disable": DisableCommand, + "DOMSnapshot.enable": EnableCommand, + "DOMSnapshot.getSnapshot": GetSnapshotCommand, + "DOMSnapshot.captureSnapshot": CaptureSnapshotCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/DOMStorage.ts b/js/src/types/generated/zod/DOMStorage.ts index 43c5909..5f999cb 100644 --- a/js/src/types/generated/zod/DOMStorage.ts +++ b/js/src/types/generated/zod/DOMStorage.ts @@ -1,23 +1,29 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const SerializedStorageKey = withCdpMeta(z.string(), "DOMStorage.SerializedStorageKey", "type"); export const StorageId = withCdpMeta(z.object({ "securityOrigin": z.string().optional(), "storageKey": z.lazy(() => SerializedStorageKey).optional(), "isLocalStorage": z.boolean() }).passthrough(), "DOMStorage.StorageId", "type"); export const Item = withCdpMeta(z.array(z.string()), "DOMStorage.Item", "type"); export const ClearParams = withCdpMeta(z.object({ "storageId": z.lazy(() => StorageId) }).passthrough(), "DOMStorage.clear.params", "commandParams", { method: "DOMStorage.clear" }); export const ClearResult = withCdpMeta(z.object({ }).passthrough(), "DOMStorage.clear.result", "commandResult", { method: "DOMStorage.clear" }); +export const ClearCommand = withCdpCommand("DOMStorage.clear", ClearParams, ClearResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "DOMStorage.disable.params", "commandParams", { method: "DOMStorage.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "DOMStorage.disable.result", "commandResult", { method: "DOMStorage.disable" }); +export const DisableCommand = withCdpCommand("DOMStorage.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "DOMStorage.enable.params", "commandParams", { method: "DOMStorage.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "DOMStorage.enable.result", "commandResult", { method: "DOMStorage.enable" }); +export const EnableCommand = withCdpCommand("DOMStorage.enable", EnableParams, EnableResult); export const GetDOMStorageItemsParams = withCdpMeta(z.object({ "storageId": z.lazy(() => StorageId) }).passthrough(), "DOMStorage.getDOMStorageItems.params", "commandParams", { method: "DOMStorage.getDOMStorageItems" }); export const GetDOMStorageItemsResult = withCdpMeta(z.object({ "entries": z.array(z.lazy(() => Item)) }).passthrough(), "DOMStorage.getDOMStorageItems.result", "commandResult", { method: "DOMStorage.getDOMStorageItems" }); +export const GetDOMStorageItemsCommand = withCdpCommand("DOMStorage.getDOMStorageItems", GetDOMStorageItemsParams, GetDOMStorageItemsResult); export const RemoveDOMStorageItemParams = withCdpMeta(z.object({ "storageId": z.lazy(() => StorageId), "key": z.string() }).passthrough(), "DOMStorage.removeDOMStorageItem.params", "commandParams", { method: "DOMStorage.removeDOMStorageItem" }); export const RemoveDOMStorageItemResult = withCdpMeta(z.object({ }).passthrough(), "DOMStorage.removeDOMStorageItem.result", "commandResult", { method: "DOMStorage.removeDOMStorageItem" }); +export const RemoveDOMStorageItemCommand = withCdpCommand("DOMStorage.removeDOMStorageItem", RemoveDOMStorageItemParams, RemoveDOMStorageItemResult); export const SetDOMStorageItemParams = withCdpMeta(z.object({ "storageId": z.lazy(() => StorageId), "key": z.string(), "value": z.string() }).passthrough(), "DOMStorage.setDOMStorageItem.params", "commandParams", { method: "DOMStorage.setDOMStorageItem" }); export const SetDOMStorageItemResult = withCdpMeta(z.object({ }).passthrough(), "DOMStorage.setDOMStorageItem.result", "commandResult", { method: "DOMStorage.setDOMStorageItem" }); +export const SetDOMStorageItemCommand = withCdpCommand("DOMStorage.setDOMStorageItem", SetDOMStorageItemParams, SetDOMStorageItemResult); export const DomStorageItemAddedEvent = withCdpMeta(z.object({ "storageId": z.lazy(() => StorageId), "key": z.string(), "newValue": z.string() }).passthrough(), "DOMStorage.domStorageItemAdded", "event", { phase: "event" }); export const DomStorageItemRemovedEvent = withCdpMeta(z.object({ "storageId": z.lazy(() => StorageId), "key": z.string() }).passthrough(), "DOMStorage.domStorageItemRemoved", "event", { phase: "event" }); export const DomStorageItemUpdatedEvent = withCdpMeta(z.object({ "storageId": z.lazy(() => StorageId), "key": z.string(), "oldValue": z.string(), "newValue": z.string() }).passthrough(), "DOMStorage.domStorageItemUpdated", "event", { phase: "event" }); @@ -45,12 +51,12 @@ export const zod = { DomStorageItemsClearedEvent: DomStorageItemsClearedEvent, } as const; export const commands = { - "DOMStorage.clear": { params: ClearParams, result: ClearResult }, - "DOMStorage.disable": { params: DisableParams, result: DisableResult }, - "DOMStorage.enable": { params: EnableParams, result: EnableResult }, - "DOMStorage.getDOMStorageItems": { params: GetDOMStorageItemsParams, result: GetDOMStorageItemsResult }, - "DOMStorage.removeDOMStorageItem": { params: RemoveDOMStorageItemParams, result: RemoveDOMStorageItemResult }, - "DOMStorage.setDOMStorageItem": { params: SetDOMStorageItemParams, result: SetDOMStorageItemResult }, + "DOMStorage.clear": ClearCommand, + "DOMStorage.disable": DisableCommand, + "DOMStorage.enable": EnableCommand, + "DOMStorage.getDOMStorageItems": GetDOMStorageItemsCommand, + "DOMStorage.removeDOMStorageItem": RemoveDOMStorageItemCommand, + "DOMStorage.setDOMStorageItem": SetDOMStorageItemCommand, } as const; export const events = { "DOMStorage.domStorageItemAdded": DomStorageItemAddedEvent, diff --git a/js/src/types/generated/zod/Debugger.ts b/js/src/types/generated/zod/Debugger.ts index 0dd8c5f..7bfa306 100644 --- a/js/src/types/generated/zod/Debugger.ts +++ b/js/src/types/generated/zod/Debugger.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Runtime from "./Runtime.js"; export const BreakpointId = withCdpMeta(z.string(), "Debugger.BreakpointId", "type"); @@ -19,70 +19,103 @@ export const DebugSymbols = withCdpMeta(z.object({ "type": z.enum(["SourceMap", export const ResolvedBreakpoint = withCdpMeta(z.object({ "breakpointId": z.lazy(() => BreakpointId), "location": z.lazy(() => Location) }).passthrough(), "Debugger.ResolvedBreakpoint", "type"); export const ContinueToLocationParams = withCdpMeta(z.object({ "location": z.lazy(() => Location), "targetCallFrames": z.enum(["any", "current"]).optional() }).passthrough(), "Debugger.continueToLocation.params", "commandParams", { method: "Debugger.continueToLocation" }); export const ContinueToLocationResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.continueToLocation.result", "commandResult", { method: "Debugger.continueToLocation" }); +export const ContinueToLocationCommand = withCdpCommand("Debugger.continueToLocation", ContinueToLocationParams, ContinueToLocationResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Debugger.disable.params", "commandParams", { method: "Debugger.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.disable.result", "commandResult", { method: "Debugger.disable" }); +export const DisableCommand = withCdpCommand("Debugger.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ "maxScriptsCacheSize": z.number().optional() }).passthrough(), "Debugger.enable.params", "commandParams", { method: "Debugger.enable" }); export const EnableResult = withCdpMeta(z.object({ "debuggerId": z.lazy(() => Runtime.UniqueDebuggerId) }).passthrough(), "Debugger.enable.result", "commandResult", { method: "Debugger.enable" }); +export const EnableCommand = withCdpCommand("Debugger.enable", EnableParams, EnableResult); export const EvaluateOnCallFrameParams = withCdpMeta(z.object({ "callFrameId": z.lazy(() => CallFrameId), "expression": z.string(), "objectGroup": z.string().optional(), "includeCommandLineAPI": z.boolean().optional(), "silent": z.boolean().optional(), "returnByValue": z.boolean().optional(), "generatePreview": z.boolean().optional(), "throwOnSideEffect": z.boolean().optional(), "timeout": z.lazy(() => Runtime.TimeDelta).optional() }).passthrough(), "Debugger.evaluateOnCallFrame.params", "commandParams", { method: "Debugger.evaluateOnCallFrame" }); export const EvaluateOnCallFrameResult = withCdpMeta(z.object({ "result": z.lazy(() => Runtime.RemoteObject), "exceptionDetails": z.lazy(() => Runtime.ExceptionDetails).optional() }).passthrough(), "Debugger.evaluateOnCallFrame.result", "commandResult", { method: "Debugger.evaluateOnCallFrame" }); +export const EvaluateOnCallFrameCommand = withCdpCommand("Debugger.evaluateOnCallFrame", EvaluateOnCallFrameParams, EvaluateOnCallFrameResult); export const GetPossibleBreakpointsParams = withCdpMeta(z.object({ "start": z.lazy(() => Location), "end": z.lazy(() => Location).optional(), "restrictToFunction": z.boolean().optional() }).passthrough(), "Debugger.getPossibleBreakpoints.params", "commandParams", { method: "Debugger.getPossibleBreakpoints" }); export const GetPossibleBreakpointsResult = withCdpMeta(z.object({ "locations": z.array(z.lazy(() => BreakLocation)) }).passthrough(), "Debugger.getPossibleBreakpoints.result", "commandResult", { method: "Debugger.getPossibleBreakpoints" }); +export const GetPossibleBreakpointsCommand = withCdpCommand("Debugger.getPossibleBreakpoints", GetPossibleBreakpointsParams, GetPossibleBreakpointsResult); export const GetScriptSourceParams = withCdpMeta(z.object({ "scriptId": z.lazy(() => Runtime.ScriptId) }).passthrough(), "Debugger.getScriptSource.params", "commandParams", { method: "Debugger.getScriptSource" }); export const GetScriptSourceResult = withCdpMeta(z.object({ "scriptSource": z.string(), "bytecode": z.string().optional() }).passthrough(), "Debugger.getScriptSource.result", "commandResult", { method: "Debugger.getScriptSource" }); +export const GetScriptSourceCommand = withCdpCommand("Debugger.getScriptSource", GetScriptSourceParams, GetScriptSourceResult); export const DisassembleWasmModuleParams = withCdpMeta(z.object({ "scriptId": z.lazy(() => Runtime.ScriptId) }).passthrough(), "Debugger.disassembleWasmModule.params", "commandParams", { method: "Debugger.disassembleWasmModule" }); export const DisassembleWasmModuleResult = withCdpMeta(z.object({ "streamId": z.string().optional(), "totalNumberOfLines": z.number().int(), "functionBodyOffsets": z.array(z.number().int()), "chunk": z.lazy(() => WasmDisassemblyChunk) }).passthrough(), "Debugger.disassembleWasmModule.result", "commandResult", { method: "Debugger.disassembleWasmModule" }); +export const DisassembleWasmModuleCommand = withCdpCommand("Debugger.disassembleWasmModule", DisassembleWasmModuleParams, DisassembleWasmModuleResult); export const NextWasmDisassemblyChunkParams = withCdpMeta(z.object({ "streamId": z.string() }).passthrough(), "Debugger.nextWasmDisassemblyChunk.params", "commandParams", { method: "Debugger.nextWasmDisassemblyChunk" }); export const NextWasmDisassemblyChunkResult = withCdpMeta(z.object({ "chunk": z.lazy(() => WasmDisassemblyChunk) }).passthrough(), "Debugger.nextWasmDisassemblyChunk.result", "commandResult", { method: "Debugger.nextWasmDisassemblyChunk" }); +export const NextWasmDisassemblyChunkCommand = withCdpCommand("Debugger.nextWasmDisassemblyChunk", NextWasmDisassemblyChunkParams, NextWasmDisassemblyChunkResult); export const GetWasmBytecodeParams = withCdpMeta(z.object({ "scriptId": z.lazy(() => Runtime.ScriptId) }).passthrough(), "Debugger.getWasmBytecode.params", "commandParams", { method: "Debugger.getWasmBytecode" }); export const GetWasmBytecodeResult = withCdpMeta(z.object({ "bytecode": z.string() }).passthrough(), "Debugger.getWasmBytecode.result", "commandResult", { method: "Debugger.getWasmBytecode" }); +export const GetWasmBytecodeCommand = withCdpCommand("Debugger.getWasmBytecode", GetWasmBytecodeParams, GetWasmBytecodeResult); export const GetStackTraceParams = withCdpMeta(z.object({ "stackTraceId": z.lazy(() => Runtime.StackTraceId) }).passthrough(), "Debugger.getStackTrace.params", "commandParams", { method: "Debugger.getStackTrace" }); export const GetStackTraceResult = withCdpMeta(z.object({ "stackTrace": z.lazy(() => Runtime.StackTrace) }).passthrough(), "Debugger.getStackTrace.result", "commandResult", { method: "Debugger.getStackTrace" }); +export const GetStackTraceCommand = withCdpCommand("Debugger.getStackTrace", GetStackTraceParams, GetStackTraceResult); export const PauseParams = withCdpMeta(z.object({ }).passthrough(), "Debugger.pause.params", "commandParams", { method: "Debugger.pause" }); export const PauseResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.pause.result", "commandResult", { method: "Debugger.pause" }); +export const PauseCommand = withCdpCommand("Debugger.pause", PauseParams, PauseResult); export const PauseOnAsyncCallParams = withCdpMeta(z.object({ "parentStackTraceId": z.lazy(() => Runtime.StackTraceId) }).passthrough(), "Debugger.pauseOnAsyncCall.params", "commandParams", { method: "Debugger.pauseOnAsyncCall" }); export const PauseOnAsyncCallResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.pauseOnAsyncCall.result", "commandResult", { method: "Debugger.pauseOnAsyncCall" }); +export const PauseOnAsyncCallCommand = withCdpCommand("Debugger.pauseOnAsyncCall", PauseOnAsyncCallParams, PauseOnAsyncCallResult); export const RemoveBreakpointParams = withCdpMeta(z.object({ "breakpointId": z.lazy(() => BreakpointId) }).passthrough(), "Debugger.removeBreakpoint.params", "commandParams", { method: "Debugger.removeBreakpoint" }); export const RemoveBreakpointResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.removeBreakpoint.result", "commandResult", { method: "Debugger.removeBreakpoint" }); +export const RemoveBreakpointCommand = withCdpCommand("Debugger.removeBreakpoint", RemoveBreakpointParams, RemoveBreakpointResult); export const RestartFrameParams = withCdpMeta(z.object({ "callFrameId": z.lazy(() => CallFrameId), "mode": z.enum(["StepInto"]).optional() }).passthrough(), "Debugger.restartFrame.params", "commandParams", { method: "Debugger.restartFrame" }); export const RestartFrameResult = withCdpMeta(z.object({ "callFrames": z.array(z.lazy(() => CallFrame)), "asyncStackTrace": z.lazy(() => Runtime.StackTrace).optional(), "asyncStackTraceId": z.lazy(() => Runtime.StackTraceId).optional() }).passthrough(), "Debugger.restartFrame.result", "commandResult", { method: "Debugger.restartFrame" }); +export const RestartFrameCommand = withCdpCommand("Debugger.restartFrame", RestartFrameParams, RestartFrameResult); export const ResumeParams = withCdpMeta(z.object({ "terminateOnResume": z.boolean().optional() }).passthrough(), "Debugger.resume.params", "commandParams", { method: "Debugger.resume" }); export const ResumeResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.resume.result", "commandResult", { method: "Debugger.resume" }); +export const ResumeCommand = withCdpCommand("Debugger.resume", ResumeParams, ResumeResult); export const SearchInContentParams = withCdpMeta(z.object({ "scriptId": z.lazy(() => Runtime.ScriptId), "query": z.string(), "caseSensitive": z.boolean().optional(), "isRegex": z.boolean().optional() }).passthrough(), "Debugger.searchInContent.params", "commandParams", { method: "Debugger.searchInContent" }); export const SearchInContentResult = withCdpMeta(z.object({ "result": z.array(z.lazy(() => SearchMatch)) }).passthrough(), "Debugger.searchInContent.result", "commandResult", { method: "Debugger.searchInContent" }); +export const SearchInContentCommand = withCdpCommand("Debugger.searchInContent", SearchInContentParams, SearchInContentResult); export const SetAsyncCallStackDepthParams = withCdpMeta(z.object({ "maxDepth": z.number().int() }).passthrough(), "Debugger.setAsyncCallStackDepth.params", "commandParams", { method: "Debugger.setAsyncCallStackDepth" }); export const SetAsyncCallStackDepthResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.setAsyncCallStackDepth.result", "commandResult", { method: "Debugger.setAsyncCallStackDepth" }); +export const SetAsyncCallStackDepthCommand = withCdpCommand("Debugger.setAsyncCallStackDepth", SetAsyncCallStackDepthParams, SetAsyncCallStackDepthResult); export const SetBlackboxExecutionContextsParams = withCdpMeta(z.object({ "uniqueIds": z.array(z.string()) }).passthrough(), "Debugger.setBlackboxExecutionContexts.params", "commandParams", { method: "Debugger.setBlackboxExecutionContexts" }); export const SetBlackboxExecutionContextsResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.setBlackboxExecutionContexts.result", "commandResult", { method: "Debugger.setBlackboxExecutionContexts" }); +export const SetBlackboxExecutionContextsCommand = withCdpCommand("Debugger.setBlackboxExecutionContexts", SetBlackboxExecutionContextsParams, SetBlackboxExecutionContextsResult); export const SetBlackboxPatternsParams = withCdpMeta(z.object({ "patterns": z.array(z.string()), "skipAnonymous": z.boolean().optional() }).passthrough(), "Debugger.setBlackboxPatterns.params", "commandParams", { method: "Debugger.setBlackboxPatterns" }); export const SetBlackboxPatternsResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.setBlackboxPatterns.result", "commandResult", { method: "Debugger.setBlackboxPatterns" }); +export const SetBlackboxPatternsCommand = withCdpCommand("Debugger.setBlackboxPatterns", SetBlackboxPatternsParams, SetBlackboxPatternsResult); export const SetBlackboxedRangesParams = withCdpMeta(z.object({ "scriptId": z.lazy(() => Runtime.ScriptId), "positions": z.array(z.lazy(() => ScriptPosition)) }).passthrough(), "Debugger.setBlackboxedRanges.params", "commandParams", { method: "Debugger.setBlackboxedRanges" }); export const SetBlackboxedRangesResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.setBlackboxedRanges.result", "commandResult", { method: "Debugger.setBlackboxedRanges" }); +export const SetBlackboxedRangesCommand = withCdpCommand("Debugger.setBlackboxedRanges", SetBlackboxedRangesParams, SetBlackboxedRangesResult); export const SetBreakpointParams = withCdpMeta(z.object({ "location": z.lazy(() => Location), "condition": z.string().optional() }).passthrough(), "Debugger.setBreakpoint.params", "commandParams", { method: "Debugger.setBreakpoint" }); export const SetBreakpointResult = withCdpMeta(z.object({ "breakpointId": z.lazy(() => BreakpointId), "actualLocation": z.lazy(() => Location) }).passthrough(), "Debugger.setBreakpoint.result", "commandResult", { method: "Debugger.setBreakpoint" }); +export const SetBreakpointCommand = withCdpCommand("Debugger.setBreakpoint", SetBreakpointParams, SetBreakpointResult); export const SetInstrumentationBreakpointParams = withCdpMeta(z.object({ "instrumentation": z.enum(["beforeScriptExecution", "beforeScriptWithSourceMapExecution"]) }).passthrough(), "Debugger.setInstrumentationBreakpoint.params", "commandParams", { method: "Debugger.setInstrumentationBreakpoint" }); export const SetInstrumentationBreakpointResult = withCdpMeta(z.object({ "breakpointId": z.lazy(() => BreakpointId) }).passthrough(), "Debugger.setInstrumentationBreakpoint.result", "commandResult", { method: "Debugger.setInstrumentationBreakpoint" }); +export const SetInstrumentationBreakpointCommand = withCdpCommand("Debugger.setInstrumentationBreakpoint", SetInstrumentationBreakpointParams, SetInstrumentationBreakpointResult); export const SetBreakpointByUrlParams = withCdpMeta(z.object({ "lineNumber": z.number().int(), "url": z.string().optional(), "urlRegex": z.string().optional(), "scriptHash": z.string().optional(), "columnNumber": z.number().int().optional(), "condition": z.string().optional() }).passthrough(), "Debugger.setBreakpointByUrl.params", "commandParams", { method: "Debugger.setBreakpointByUrl" }); export const SetBreakpointByUrlResult = withCdpMeta(z.object({ "breakpointId": z.lazy(() => BreakpointId), "locations": z.array(z.lazy(() => Location)) }).passthrough(), "Debugger.setBreakpointByUrl.result", "commandResult", { method: "Debugger.setBreakpointByUrl" }); +export const SetBreakpointByUrlCommand = withCdpCommand("Debugger.setBreakpointByUrl", SetBreakpointByUrlParams, SetBreakpointByUrlResult); export const SetBreakpointOnFunctionCallParams = withCdpMeta(z.object({ "objectId": z.lazy(() => Runtime.RemoteObjectId), "condition": z.string().optional() }).passthrough(), "Debugger.setBreakpointOnFunctionCall.params", "commandParams", { method: "Debugger.setBreakpointOnFunctionCall" }); export const SetBreakpointOnFunctionCallResult = withCdpMeta(z.object({ "breakpointId": z.lazy(() => BreakpointId) }).passthrough(), "Debugger.setBreakpointOnFunctionCall.result", "commandResult", { method: "Debugger.setBreakpointOnFunctionCall" }); +export const SetBreakpointOnFunctionCallCommand = withCdpCommand("Debugger.setBreakpointOnFunctionCall", SetBreakpointOnFunctionCallParams, SetBreakpointOnFunctionCallResult); export const SetBreakpointsActiveParams = withCdpMeta(z.object({ "active": z.boolean() }).passthrough(), "Debugger.setBreakpointsActive.params", "commandParams", { method: "Debugger.setBreakpointsActive" }); export const SetBreakpointsActiveResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.setBreakpointsActive.result", "commandResult", { method: "Debugger.setBreakpointsActive" }); +export const SetBreakpointsActiveCommand = withCdpCommand("Debugger.setBreakpointsActive", SetBreakpointsActiveParams, SetBreakpointsActiveResult); export const SetPauseOnExceptionsParams = withCdpMeta(z.object({ "state": z.enum(["none", "caught", "uncaught", "all"]) }).passthrough(), "Debugger.setPauseOnExceptions.params", "commandParams", { method: "Debugger.setPauseOnExceptions" }); export const SetPauseOnExceptionsResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.setPauseOnExceptions.result", "commandResult", { method: "Debugger.setPauseOnExceptions" }); +export const SetPauseOnExceptionsCommand = withCdpCommand("Debugger.setPauseOnExceptions", SetPauseOnExceptionsParams, SetPauseOnExceptionsResult); export const SetReturnValueParams = withCdpMeta(z.object({ "newValue": z.lazy(() => Runtime.CallArgument) }).passthrough(), "Debugger.setReturnValue.params", "commandParams", { method: "Debugger.setReturnValue" }); export const SetReturnValueResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.setReturnValue.result", "commandResult", { method: "Debugger.setReturnValue" }); +export const SetReturnValueCommand = withCdpCommand("Debugger.setReturnValue", SetReturnValueParams, SetReturnValueResult); export const SetScriptSourceParams = withCdpMeta(z.object({ "scriptId": z.lazy(() => Runtime.ScriptId), "scriptSource": z.string(), "dryRun": z.boolean().optional(), "allowTopFrameEditing": z.boolean().optional() }).passthrough(), "Debugger.setScriptSource.params", "commandParams", { method: "Debugger.setScriptSource" }); export const SetScriptSourceResult = withCdpMeta(z.object({ "callFrames": z.array(z.lazy(() => CallFrame)).optional(), "stackChanged": z.boolean().optional(), "asyncStackTrace": z.lazy(() => Runtime.StackTrace).optional(), "asyncStackTraceId": z.lazy(() => Runtime.StackTraceId).optional(), "status": z.enum(["Ok", "CompileError", "BlockedByActiveGenerator", "BlockedByActiveFunction", "BlockedByTopLevelEsModuleChange"]), "exceptionDetails": z.lazy(() => Runtime.ExceptionDetails).optional() }).passthrough(), "Debugger.setScriptSource.result", "commandResult", { method: "Debugger.setScriptSource" }); +export const SetScriptSourceCommand = withCdpCommand("Debugger.setScriptSource", SetScriptSourceParams, SetScriptSourceResult); export const SetSkipAllPausesParams = withCdpMeta(z.object({ "skip": z.boolean() }).passthrough(), "Debugger.setSkipAllPauses.params", "commandParams", { method: "Debugger.setSkipAllPauses" }); export const SetSkipAllPausesResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.setSkipAllPauses.result", "commandResult", { method: "Debugger.setSkipAllPauses" }); +export const SetSkipAllPausesCommand = withCdpCommand("Debugger.setSkipAllPauses", SetSkipAllPausesParams, SetSkipAllPausesResult); export const SetVariableValueParams = withCdpMeta(z.object({ "scopeNumber": z.number().int(), "variableName": z.string(), "newValue": z.lazy(() => Runtime.CallArgument), "callFrameId": z.lazy(() => CallFrameId) }).passthrough(), "Debugger.setVariableValue.params", "commandParams", { method: "Debugger.setVariableValue" }); export const SetVariableValueResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.setVariableValue.result", "commandResult", { method: "Debugger.setVariableValue" }); +export const SetVariableValueCommand = withCdpCommand("Debugger.setVariableValue", SetVariableValueParams, SetVariableValueResult); export const StepIntoParams = withCdpMeta(z.object({ "breakOnAsyncCall": z.boolean().optional(), "skipList": z.array(z.lazy(() => LocationRange)).optional() }).passthrough(), "Debugger.stepInto.params", "commandParams", { method: "Debugger.stepInto" }); export const StepIntoResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.stepInto.result", "commandResult", { method: "Debugger.stepInto" }); +export const StepIntoCommand = withCdpCommand("Debugger.stepInto", StepIntoParams, StepIntoResult); export const StepOutParams = withCdpMeta(z.object({ }).passthrough(), "Debugger.stepOut.params", "commandParams", { method: "Debugger.stepOut" }); export const StepOutResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.stepOut.result", "commandResult", { method: "Debugger.stepOut" }); +export const StepOutCommand = withCdpCommand("Debugger.stepOut", StepOutParams, StepOutResult); export const StepOverParams = withCdpMeta(z.object({ "skipList": z.array(z.lazy(() => LocationRange)).optional() }).passthrough(), "Debugger.stepOver.params", "commandParams", { method: "Debugger.stepOver" }); export const StepOverResult = withCdpMeta(z.object({ }).passthrough(), "Debugger.stepOver.result", "commandResult", { method: "Debugger.stepOver" }); +export const StepOverCommand = withCdpCommand("Debugger.stepOver", StepOverParams, StepOverResult); export const BreakpointResolvedEvent = withCdpMeta(z.object({ "breakpointId": z.lazy(() => BreakpointId), "location": z.lazy(() => Location) }).passthrough(), "Debugger.breakpointResolved", "event", { phase: "event" }); export const PausedEvent = withCdpMeta(z.object({ "callFrames": z.array(z.lazy(() => CallFrame)), "reason": z.enum(["ambiguous", "assert", "CSPViolation", "debugCommand", "DOM", "EventListener", "exception", "instrumentation", "OOM", "other", "promiseRejection", "XHR", "step"]), "data": z.record(z.string(), z.unknown()).optional(), "hitBreakpoints": z.array(z.string()).optional(), "asyncStackTrace": z.lazy(() => Runtime.StackTrace).optional(), "asyncStackTraceId": z.lazy(() => Runtime.StackTraceId).optional(), "asyncCallStackTraceId": z.lazy(() => Runtime.StackTraceId).optional() }).passthrough(), "Debugger.paused", "event", { phase: "event" }); export const ResumedEvent = withCdpMeta(z.object({ }).passthrough(), "Debugger.resumed", "event", { phase: "event" }); @@ -176,39 +209,39 @@ export const zod = { ScriptParsedEvent: ScriptParsedEvent, } as const; export const commands = { - "Debugger.continueToLocation": { params: ContinueToLocationParams, result: ContinueToLocationResult }, - "Debugger.disable": { params: DisableParams, result: DisableResult }, - "Debugger.enable": { params: EnableParams, result: EnableResult }, - "Debugger.evaluateOnCallFrame": { params: EvaluateOnCallFrameParams, result: EvaluateOnCallFrameResult }, - "Debugger.getPossibleBreakpoints": { params: GetPossibleBreakpointsParams, result: GetPossibleBreakpointsResult }, - "Debugger.getScriptSource": { params: GetScriptSourceParams, result: GetScriptSourceResult }, - "Debugger.disassembleWasmModule": { params: DisassembleWasmModuleParams, result: DisassembleWasmModuleResult }, - "Debugger.nextWasmDisassemblyChunk": { params: NextWasmDisassemblyChunkParams, result: NextWasmDisassemblyChunkResult }, - "Debugger.getWasmBytecode": { params: GetWasmBytecodeParams, result: GetWasmBytecodeResult }, - "Debugger.getStackTrace": { params: GetStackTraceParams, result: GetStackTraceResult }, - "Debugger.pause": { params: PauseParams, result: PauseResult }, - "Debugger.pauseOnAsyncCall": { params: PauseOnAsyncCallParams, result: PauseOnAsyncCallResult }, - "Debugger.removeBreakpoint": { params: RemoveBreakpointParams, result: RemoveBreakpointResult }, - "Debugger.restartFrame": { params: RestartFrameParams, result: RestartFrameResult }, - "Debugger.resume": { params: ResumeParams, result: ResumeResult }, - "Debugger.searchInContent": { params: SearchInContentParams, result: SearchInContentResult }, - "Debugger.setAsyncCallStackDepth": { params: SetAsyncCallStackDepthParams, result: SetAsyncCallStackDepthResult }, - "Debugger.setBlackboxExecutionContexts": { params: SetBlackboxExecutionContextsParams, result: SetBlackboxExecutionContextsResult }, - "Debugger.setBlackboxPatterns": { params: SetBlackboxPatternsParams, result: SetBlackboxPatternsResult }, - "Debugger.setBlackboxedRanges": { params: SetBlackboxedRangesParams, result: SetBlackboxedRangesResult }, - "Debugger.setBreakpoint": { params: SetBreakpointParams, result: SetBreakpointResult }, - "Debugger.setInstrumentationBreakpoint": { params: SetInstrumentationBreakpointParams, result: SetInstrumentationBreakpointResult }, - "Debugger.setBreakpointByUrl": { params: SetBreakpointByUrlParams, result: SetBreakpointByUrlResult }, - "Debugger.setBreakpointOnFunctionCall": { params: SetBreakpointOnFunctionCallParams, result: SetBreakpointOnFunctionCallResult }, - "Debugger.setBreakpointsActive": { params: SetBreakpointsActiveParams, result: SetBreakpointsActiveResult }, - "Debugger.setPauseOnExceptions": { params: SetPauseOnExceptionsParams, result: SetPauseOnExceptionsResult }, - "Debugger.setReturnValue": { params: SetReturnValueParams, result: SetReturnValueResult }, - "Debugger.setScriptSource": { params: SetScriptSourceParams, result: SetScriptSourceResult }, - "Debugger.setSkipAllPauses": { params: SetSkipAllPausesParams, result: SetSkipAllPausesResult }, - "Debugger.setVariableValue": { params: SetVariableValueParams, result: SetVariableValueResult }, - "Debugger.stepInto": { params: StepIntoParams, result: StepIntoResult }, - "Debugger.stepOut": { params: StepOutParams, result: StepOutResult }, - "Debugger.stepOver": { params: StepOverParams, result: StepOverResult }, + "Debugger.continueToLocation": ContinueToLocationCommand, + "Debugger.disable": DisableCommand, + "Debugger.enable": EnableCommand, + "Debugger.evaluateOnCallFrame": EvaluateOnCallFrameCommand, + "Debugger.getPossibleBreakpoints": GetPossibleBreakpointsCommand, + "Debugger.getScriptSource": GetScriptSourceCommand, + "Debugger.disassembleWasmModule": DisassembleWasmModuleCommand, + "Debugger.nextWasmDisassemblyChunk": NextWasmDisassemblyChunkCommand, + "Debugger.getWasmBytecode": GetWasmBytecodeCommand, + "Debugger.getStackTrace": GetStackTraceCommand, + "Debugger.pause": PauseCommand, + "Debugger.pauseOnAsyncCall": PauseOnAsyncCallCommand, + "Debugger.removeBreakpoint": RemoveBreakpointCommand, + "Debugger.restartFrame": RestartFrameCommand, + "Debugger.resume": ResumeCommand, + "Debugger.searchInContent": SearchInContentCommand, + "Debugger.setAsyncCallStackDepth": SetAsyncCallStackDepthCommand, + "Debugger.setBlackboxExecutionContexts": SetBlackboxExecutionContextsCommand, + "Debugger.setBlackboxPatterns": SetBlackboxPatternsCommand, + "Debugger.setBlackboxedRanges": SetBlackboxedRangesCommand, + "Debugger.setBreakpoint": SetBreakpointCommand, + "Debugger.setInstrumentationBreakpoint": SetInstrumentationBreakpointCommand, + "Debugger.setBreakpointByUrl": SetBreakpointByUrlCommand, + "Debugger.setBreakpointOnFunctionCall": SetBreakpointOnFunctionCallCommand, + "Debugger.setBreakpointsActive": SetBreakpointsActiveCommand, + "Debugger.setPauseOnExceptions": SetPauseOnExceptionsCommand, + "Debugger.setReturnValue": SetReturnValueCommand, + "Debugger.setScriptSource": SetScriptSourceCommand, + "Debugger.setSkipAllPauses": SetSkipAllPausesCommand, + "Debugger.setVariableValue": SetVariableValueCommand, + "Debugger.stepInto": StepIntoCommand, + "Debugger.stepOut": StepOutCommand, + "Debugger.stepOver": StepOverCommand, } as const; export const events = { "Debugger.breakpointResolved": BreakpointResolvedEvent, diff --git a/js/src/types/generated/zod/DeviceAccess.ts b/js/src/types/generated/zod/DeviceAccess.ts index 5d860a8..8a69d34 100644 --- a/js/src/types/generated/zod/DeviceAccess.ts +++ b/js/src/types/generated/zod/DeviceAccess.ts @@ -1,19 +1,23 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const RequestId = withCdpMeta(z.string(), "DeviceAccess.RequestId", "type"); export const DeviceId = withCdpMeta(z.string(), "DeviceAccess.DeviceId", "type"); export const PromptDevice = withCdpMeta(z.object({ "id": z.lazy(() => DeviceId), "name": z.string() }).passthrough(), "DeviceAccess.PromptDevice", "type"); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "DeviceAccess.enable.params", "commandParams", { method: "DeviceAccess.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "DeviceAccess.enable.result", "commandResult", { method: "DeviceAccess.enable" }); +export const EnableCommand = withCdpCommand("DeviceAccess.enable", EnableParams, EnableResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "DeviceAccess.disable.params", "commandParams", { method: "DeviceAccess.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "DeviceAccess.disable.result", "commandResult", { method: "DeviceAccess.disable" }); +export const DisableCommand = withCdpCommand("DeviceAccess.disable", DisableParams, DisableResult); export const SelectPromptParams = withCdpMeta(z.object({ "id": z.lazy(() => RequestId), "deviceId": z.lazy(() => DeviceId) }).passthrough(), "DeviceAccess.selectPrompt.params", "commandParams", { method: "DeviceAccess.selectPrompt" }); export const SelectPromptResult = withCdpMeta(z.object({ }).passthrough(), "DeviceAccess.selectPrompt.result", "commandResult", { method: "DeviceAccess.selectPrompt" }); +export const SelectPromptCommand = withCdpCommand("DeviceAccess.selectPrompt", SelectPromptParams, SelectPromptResult); export const CancelPromptParams = withCdpMeta(z.object({ "id": z.lazy(() => RequestId) }).passthrough(), "DeviceAccess.cancelPrompt.params", "commandParams", { method: "DeviceAccess.cancelPrompt" }); export const CancelPromptResult = withCdpMeta(z.object({ }).passthrough(), "DeviceAccess.cancelPrompt.result", "commandResult", { method: "DeviceAccess.cancelPrompt" }); +export const CancelPromptCommand = withCdpCommand("DeviceAccess.cancelPrompt", CancelPromptParams, CancelPromptResult); export const DeviceRequestPromptedEvent = withCdpMeta(z.object({ "id": z.lazy(() => RequestId), "devices": z.array(z.lazy(() => PromptDevice)) }).passthrough(), "DeviceAccess.deviceRequestPrompted", "event", { phase: "event" }); export const zod = { @@ -31,10 +35,10 @@ export const zod = { DeviceRequestPromptedEvent: DeviceRequestPromptedEvent, } as const; export const commands = { - "DeviceAccess.enable": { params: EnableParams, result: EnableResult }, - "DeviceAccess.disable": { params: DisableParams, result: DisableResult }, - "DeviceAccess.selectPrompt": { params: SelectPromptParams, result: SelectPromptResult }, - "DeviceAccess.cancelPrompt": { params: CancelPromptParams, result: CancelPromptResult }, + "DeviceAccess.enable": EnableCommand, + "DeviceAccess.disable": DisableCommand, + "DeviceAccess.selectPrompt": SelectPromptCommand, + "DeviceAccess.cancelPrompt": CancelPromptCommand, } as const; export const events = { "DeviceAccess.deviceRequestPrompted": DeviceRequestPromptedEvent, diff --git a/js/src/types/generated/zod/DeviceOrientation.ts b/js/src/types/generated/zod/DeviceOrientation.ts index 3f06e14..af297fb 100644 --- a/js/src/types/generated/zod/DeviceOrientation.ts +++ b/js/src/types/generated/zod/DeviceOrientation.ts @@ -1,12 +1,14 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const ClearDeviceOrientationOverrideParams = withCdpMeta(z.object({ }).passthrough(), "DeviceOrientation.clearDeviceOrientationOverride.params", "commandParams", { method: "DeviceOrientation.clearDeviceOrientationOverride" }); export const ClearDeviceOrientationOverrideResult = withCdpMeta(z.object({ }).passthrough(), "DeviceOrientation.clearDeviceOrientationOverride.result", "commandResult", { method: "DeviceOrientation.clearDeviceOrientationOverride" }); +export const ClearDeviceOrientationOverrideCommand = withCdpCommand("DeviceOrientation.clearDeviceOrientationOverride", ClearDeviceOrientationOverrideParams, ClearDeviceOrientationOverrideResult); export const SetDeviceOrientationOverrideParams = withCdpMeta(z.object({ "alpha": z.number(), "beta": z.number(), "gamma": z.number() }).passthrough(), "DeviceOrientation.setDeviceOrientationOverride.params", "commandParams", { method: "DeviceOrientation.setDeviceOrientationOverride" }); export const SetDeviceOrientationOverrideResult = withCdpMeta(z.object({ }).passthrough(), "DeviceOrientation.setDeviceOrientationOverride.result", "commandResult", { method: "DeviceOrientation.setDeviceOrientationOverride" }); +export const SetDeviceOrientationOverrideCommand = withCdpCommand("DeviceOrientation.setDeviceOrientationOverride", SetDeviceOrientationOverrideParams, SetDeviceOrientationOverrideResult); export const zod = { ClearDeviceOrientationOverrideParams: ClearDeviceOrientationOverrideParams, @@ -15,8 +17,8 @@ export const zod = { SetDeviceOrientationOverrideResult: SetDeviceOrientationOverrideResult, } as const; export const commands = { - "DeviceOrientation.clearDeviceOrientationOverride": { params: ClearDeviceOrientationOverrideParams, result: ClearDeviceOrientationOverrideResult }, - "DeviceOrientation.setDeviceOrientationOverride": { params: SetDeviceOrientationOverrideParams, result: SetDeviceOrientationOverrideResult }, + "DeviceOrientation.clearDeviceOrientationOverride": ClearDeviceOrientationOverrideCommand, + "DeviceOrientation.setDeviceOrientationOverride": SetDeviceOrientationOverrideCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/Emulation.ts b/js/src/types/generated/zod/Emulation.ts index 00cfea6..6c26da7 100644 --- a/js/src/types/generated/zod/Emulation.ts +++ b/js/src/types/generated/zod/Emulation.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; import * as Network from "./Network.js"; import * as Page from "./Page.js"; @@ -29,100 +29,148 @@ export const ScreenInfo = withCdpMeta(z.object({ "left": z.number().int(), "top" export const DisabledImageType = withCdpMeta(z.enum(["avif", "jxl", "webp"]), "Emulation.DisabledImageType", "type"); export const CanEmulateParams = withCdpMeta(z.object({ }).passthrough(), "Emulation.canEmulate.params", "commandParams", { method: "Emulation.canEmulate" }); export const CanEmulateResult = withCdpMeta(z.object({ "result": z.boolean() }).passthrough(), "Emulation.canEmulate.result", "commandResult", { method: "Emulation.canEmulate" }); +export const CanEmulateCommand = withCdpCommand("Emulation.canEmulate", CanEmulateParams, CanEmulateResult); export const ClearDeviceMetricsOverrideParams = withCdpMeta(z.object({ }).passthrough(), "Emulation.clearDeviceMetricsOverride.params", "commandParams", { method: "Emulation.clearDeviceMetricsOverride" }); export const ClearDeviceMetricsOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.clearDeviceMetricsOverride.result", "commandResult", { method: "Emulation.clearDeviceMetricsOverride" }); +export const ClearDeviceMetricsOverrideCommand = withCdpCommand("Emulation.clearDeviceMetricsOverride", ClearDeviceMetricsOverrideParams, ClearDeviceMetricsOverrideResult); export const ClearGeolocationOverrideParams = withCdpMeta(z.object({ }).passthrough(), "Emulation.clearGeolocationOverride.params", "commandParams", { method: "Emulation.clearGeolocationOverride" }); export const ClearGeolocationOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.clearGeolocationOverride.result", "commandResult", { method: "Emulation.clearGeolocationOverride" }); +export const ClearGeolocationOverrideCommand = withCdpCommand("Emulation.clearGeolocationOverride", ClearGeolocationOverrideParams, ClearGeolocationOverrideResult); export const ResetPageScaleFactorParams = withCdpMeta(z.object({ }).passthrough(), "Emulation.resetPageScaleFactor.params", "commandParams", { method: "Emulation.resetPageScaleFactor" }); export const ResetPageScaleFactorResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.resetPageScaleFactor.result", "commandResult", { method: "Emulation.resetPageScaleFactor" }); +export const ResetPageScaleFactorCommand = withCdpCommand("Emulation.resetPageScaleFactor", ResetPageScaleFactorParams, ResetPageScaleFactorResult); export const SetFocusEmulationEnabledParams = withCdpMeta(z.object({ "enabled": z.boolean() }).passthrough(), "Emulation.setFocusEmulationEnabled.params", "commandParams", { method: "Emulation.setFocusEmulationEnabled" }); export const SetFocusEmulationEnabledResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setFocusEmulationEnabled.result", "commandResult", { method: "Emulation.setFocusEmulationEnabled" }); +export const SetFocusEmulationEnabledCommand = withCdpCommand("Emulation.setFocusEmulationEnabled", SetFocusEmulationEnabledParams, SetFocusEmulationEnabledResult); export const SetAutoDarkModeOverrideParams = withCdpMeta(z.object({ "enabled": z.boolean().optional() }).passthrough(), "Emulation.setAutoDarkModeOverride.params", "commandParams", { method: "Emulation.setAutoDarkModeOverride" }); export const SetAutoDarkModeOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setAutoDarkModeOverride.result", "commandResult", { method: "Emulation.setAutoDarkModeOverride" }); +export const SetAutoDarkModeOverrideCommand = withCdpCommand("Emulation.setAutoDarkModeOverride", SetAutoDarkModeOverrideParams, SetAutoDarkModeOverrideResult); export const SetCPUThrottlingRateParams = withCdpMeta(z.object({ "rate": z.number() }).passthrough(), "Emulation.setCPUThrottlingRate.params", "commandParams", { method: "Emulation.setCPUThrottlingRate" }); export const SetCPUThrottlingRateResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setCPUThrottlingRate.result", "commandResult", { method: "Emulation.setCPUThrottlingRate" }); +export const SetCPUThrottlingRateCommand = withCdpCommand("Emulation.setCPUThrottlingRate", SetCPUThrottlingRateParams, SetCPUThrottlingRateResult); export const SetDefaultBackgroundColorOverrideParams = withCdpMeta(z.object({ "color": z.lazy(() => DOM.RGBA).optional() }).passthrough(), "Emulation.setDefaultBackgroundColorOverride.params", "commandParams", { method: "Emulation.setDefaultBackgroundColorOverride" }); export const SetDefaultBackgroundColorOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setDefaultBackgroundColorOverride.result", "commandResult", { method: "Emulation.setDefaultBackgroundColorOverride" }); +export const SetDefaultBackgroundColorOverrideCommand = withCdpCommand("Emulation.setDefaultBackgroundColorOverride", SetDefaultBackgroundColorOverrideParams, SetDefaultBackgroundColorOverrideResult); export const SetSafeAreaInsetsOverrideParams = withCdpMeta(z.object({ "insets": z.lazy(() => SafeAreaInsets) }).passthrough(), "Emulation.setSafeAreaInsetsOverride.params", "commandParams", { method: "Emulation.setSafeAreaInsetsOverride" }); export const SetSafeAreaInsetsOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setSafeAreaInsetsOverride.result", "commandResult", { method: "Emulation.setSafeAreaInsetsOverride" }); +export const SetSafeAreaInsetsOverrideCommand = withCdpCommand("Emulation.setSafeAreaInsetsOverride", SetSafeAreaInsetsOverrideParams, SetSafeAreaInsetsOverrideResult); export const SetDeviceMetricsOverrideParams = withCdpMeta(z.object({ "width": z.number().int(), "height": z.number().int(), "deviceScaleFactor": z.number(), "mobile": z.boolean(), "scale": z.number().optional(), "screenWidth": z.number().int().optional(), "screenHeight": z.number().int().optional(), "positionX": z.number().int().optional(), "positionY": z.number().int().optional(), "dontSetVisibleSize": z.boolean().optional(), "screenOrientation": z.lazy(() => ScreenOrientation).optional(), "viewport": z.lazy(() => Page.Viewport).optional(), "displayFeature": z.lazy(() => DisplayFeature).optional(), "devicePosture": z.lazy(() => DevicePosture).optional(), "scrollbarType": z.enum(["overlay", "default"]).optional(), "screenOrientationLockEmulation": z.boolean().optional() }).passthrough(), "Emulation.setDeviceMetricsOverride.params", "commandParams", { method: "Emulation.setDeviceMetricsOverride" }); export const SetDeviceMetricsOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setDeviceMetricsOverride.result", "commandResult", { method: "Emulation.setDeviceMetricsOverride" }); +export const SetDeviceMetricsOverrideCommand = withCdpCommand("Emulation.setDeviceMetricsOverride", SetDeviceMetricsOverrideParams, SetDeviceMetricsOverrideResult); export const SetDevicePostureOverrideParams = withCdpMeta(z.object({ "posture": z.lazy(() => DevicePosture) }).passthrough(), "Emulation.setDevicePostureOverride.params", "commandParams", { method: "Emulation.setDevicePostureOverride" }); export const SetDevicePostureOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setDevicePostureOverride.result", "commandResult", { method: "Emulation.setDevicePostureOverride" }); +export const SetDevicePostureOverrideCommand = withCdpCommand("Emulation.setDevicePostureOverride", SetDevicePostureOverrideParams, SetDevicePostureOverrideResult); export const ClearDevicePostureOverrideParams = withCdpMeta(z.object({ }).passthrough(), "Emulation.clearDevicePostureOverride.params", "commandParams", { method: "Emulation.clearDevicePostureOverride" }); export const ClearDevicePostureOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.clearDevicePostureOverride.result", "commandResult", { method: "Emulation.clearDevicePostureOverride" }); +export const ClearDevicePostureOverrideCommand = withCdpCommand("Emulation.clearDevicePostureOverride", ClearDevicePostureOverrideParams, ClearDevicePostureOverrideResult); export const SetDisplayFeaturesOverrideParams = withCdpMeta(z.object({ "features": z.array(z.lazy(() => DisplayFeature)) }).passthrough(), "Emulation.setDisplayFeaturesOverride.params", "commandParams", { method: "Emulation.setDisplayFeaturesOverride" }); export const SetDisplayFeaturesOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setDisplayFeaturesOverride.result", "commandResult", { method: "Emulation.setDisplayFeaturesOverride" }); +export const SetDisplayFeaturesOverrideCommand = withCdpCommand("Emulation.setDisplayFeaturesOverride", SetDisplayFeaturesOverrideParams, SetDisplayFeaturesOverrideResult); export const ClearDisplayFeaturesOverrideParams = withCdpMeta(z.object({ }).passthrough(), "Emulation.clearDisplayFeaturesOverride.params", "commandParams", { method: "Emulation.clearDisplayFeaturesOverride" }); export const ClearDisplayFeaturesOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.clearDisplayFeaturesOverride.result", "commandResult", { method: "Emulation.clearDisplayFeaturesOverride" }); +export const ClearDisplayFeaturesOverrideCommand = withCdpCommand("Emulation.clearDisplayFeaturesOverride", ClearDisplayFeaturesOverrideParams, ClearDisplayFeaturesOverrideResult); export const SetScrollbarsHiddenParams = withCdpMeta(z.object({ "hidden": z.boolean() }).passthrough(), "Emulation.setScrollbarsHidden.params", "commandParams", { method: "Emulation.setScrollbarsHidden" }); export const SetScrollbarsHiddenResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setScrollbarsHidden.result", "commandResult", { method: "Emulation.setScrollbarsHidden" }); +export const SetScrollbarsHiddenCommand = withCdpCommand("Emulation.setScrollbarsHidden", SetScrollbarsHiddenParams, SetScrollbarsHiddenResult); export const SetDocumentCookieDisabledParams = withCdpMeta(z.object({ "disabled": z.boolean() }).passthrough(), "Emulation.setDocumentCookieDisabled.params", "commandParams", { method: "Emulation.setDocumentCookieDisabled" }); export const SetDocumentCookieDisabledResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setDocumentCookieDisabled.result", "commandResult", { method: "Emulation.setDocumentCookieDisabled" }); +export const SetDocumentCookieDisabledCommand = withCdpCommand("Emulation.setDocumentCookieDisabled", SetDocumentCookieDisabledParams, SetDocumentCookieDisabledResult); export const SetEmitTouchEventsForMouseParams = withCdpMeta(z.object({ "enabled": z.boolean(), "configuration": z.enum(["mobile", "desktop"]).optional() }).passthrough(), "Emulation.setEmitTouchEventsForMouse.params", "commandParams", { method: "Emulation.setEmitTouchEventsForMouse" }); export const SetEmitTouchEventsForMouseResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setEmitTouchEventsForMouse.result", "commandResult", { method: "Emulation.setEmitTouchEventsForMouse" }); +export const SetEmitTouchEventsForMouseCommand = withCdpCommand("Emulation.setEmitTouchEventsForMouse", SetEmitTouchEventsForMouseParams, SetEmitTouchEventsForMouseResult); export const SetEmulatedMediaParams = withCdpMeta(z.object({ "media": z.string().optional(), "features": z.array(z.lazy(() => MediaFeature)).optional() }).passthrough(), "Emulation.setEmulatedMedia.params", "commandParams", { method: "Emulation.setEmulatedMedia" }); export const SetEmulatedMediaResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setEmulatedMedia.result", "commandResult", { method: "Emulation.setEmulatedMedia" }); +export const SetEmulatedMediaCommand = withCdpCommand("Emulation.setEmulatedMedia", SetEmulatedMediaParams, SetEmulatedMediaResult); export const SetEmulatedVisionDeficiencyParams = withCdpMeta(z.object({ "type": z.enum(["none", "blurredVision", "reducedContrast", "achromatopsia", "deuteranopia", "protanopia", "tritanopia"]) }).passthrough(), "Emulation.setEmulatedVisionDeficiency.params", "commandParams", { method: "Emulation.setEmulatedVisionDeficiency" }); export const SetEmulatedVisionDeficiencyResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setEmulatedVisionDeficiency.result", "commandResult", { method: "Emulation.setEmulatedVisionDeficiency" }); +export const SetEmulatedVisionDeficiencyCommand = withCdpCommand("Emulation.setEmulatedVisionDeficiency", SetEmulatedVisionDeficiencyParams, SetEmulatedVisionDeficiencyResult); export const SetEmulatedOSTextScaleParams = withCdpMeta(z.object({ "scale": z.number().optional() }).passthrough(), "Emulation.setEmulatedOSTextScale.params", "commandParams", { method: "Emulation.setEmulatedOSTextScale" }); export const SetEmulatedOSTextScaleResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setEmulatedOSTextScale.result", "commandResult", { method: "Emulation.setEmulatedOSTextScale" }); +export const SetEmulatedOSTextScaleCommand = withCdpCommand("Emulation.setEmulatedOSTextScale", SetEmulatedOSTextScaleParams, SetEmulatedOSTextScaleResult); export const SetGeolocationOverrideParams = withCdpMeta(z.object({ "latitude": z.number().optional(), "longitude": z.number().optional(), "accuracy": z.number().optional(), "altitude": z.number().optional(), "altitudeAccuracy": z.number().optional(), "heading": z.number().optional(), "speed": z.number().optional() }).passthrough(), "Emulation.setGeolocationOverride.params", "commandParams", { method: "Emulation.setGeolocationOverride" }); export const SetGeolocationOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setGeolocationOverride.result", "commandResult", { method: "Emulation.setGeolocationOverride" }); +export const SetGeolocationOverrideCommand = withCdpCommand("Emulation.setGeolocationOverride", SetGeolocationOverrideParams, SetGeolocationOverrideResult); export const GetOverriddenSensorInformationParams = withCdpMeta(z.object({ "type": z.lazy(() => SensorType) }).passthrough(), "Emulation.getOverriddenSensorInformation.params", "commandParams", { method: "Emulation.getOverriddenSensorInformation" }); export const GetOverriddenSensorInformationResult = withCdpMeta(z.object({ "requestedSamplingFrequency": z.number() }).passthrough(), "Emulation.getOverriddenSensorInformation.result", "commandResult", { method: "Emulation.getOverriddenSensorInformation" }); +export const GetOverriddenSensorInformationCommand = withCdpCommand("Emulation.getOverriddenSensorInformation", GetOverriddenSensorInformationParams, GetOverriddenSensorInformationResult); export const SetSensorOverrideEnabledParams = withCdpMeta(z.object({ "enabled": z.boolean(), "type": z.lazy(() => SensorType), "metadata": z.lazy(() => SensorMetadata).optional() }).passthrough(), "Emulation.setSensorOverrideEnabled.params", "commandParams", { method: "Emulation.setSensorOverrideEnabled" }); export const SetSensorOverrideEnabledResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setSensorOverrideEnabled.result", "commandResult", { method: "Emulation.setSensorOverrideEnabled" }); +export const SetSensorOverrideEnabledCommand = withCdpCommand("Emulation.setSensorOverrideEnabled", SetSensorOverrideEnabledParams, SetSensorOverrideEnabledResult); export const SetSensorOverrideReadingsParams = withCdpMeta(z.object({ "type": z.lazy(() => SensorType), "reading": z.lazy(() => SensorReading) }).passthrough(), "Emulation.setSensorOverrideReadings.params", "commandParams", { method: "Emulation.setSensorOverrideReadings" }); export const SetSensorOverrideReadingsResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setSensorOverrideReadings.result", "commandResult", { method: "Emulation.setSensorOverrideReadings" }); +export const SetSensorOverrideReadingsCommand = withCdpCommand("Emulation.setSensorOverrideReadings", SetSensorOverrideReadingsParams, SetSensorOverrideReadingsResult); export const SetPressureSourceOverrideEnabledParams = withCdpMeta(z.object({ "enabled": z.boolean(), "source": z.lazy(() => PressureSource), "metadata": z.lazy(() => PressureMetadata).optional() }).passthrough(), "Emulation.setPressureSourceOverrideEnabled.params", "commandParams", { method: "Emulation.setPressureSourceOverrideEnabled" }); export const SetPressureSourceOverrideEnabledResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setPressureSourceOverrideEnabled.result", "commandResult", { method: "Emulation.setPressureSourceOverrideEnabled" }); +export const SetPressureSourceOverrideEnabledCommand = withCdpCommand("Emulation.setPressureSourceOverrideEnabled", SetPressureSourceOverrideEnabledParams, SetPressureSourceOverrideEnabledResult); export const SetPressureStateOverrideParams = withCdpMeta(z.object({ "source": z.lazy(() => PressureSource), "state": z.lazy(() => PressureState) }).passthrough(), "Emulation.setPressureStateOverride.params", "commandParams", { method: "Emulation.setPressureStateOverride" }); export const SetPressureStateOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setPressureStateOverride.result", "commandResult", { method: "Emulation.setPressureStateOverride" }); +export const SetPressureStateOverrideCommand = withCdpCommand("Emulation.setPressureStateOverride", SetPressureStateOverrideParams, SetPressureStateOverrideResult); export const SetPressureDataOverrideParams = withCdpMeta(z.object({ "source": z.lazy(() => PressureSource), "state": z.lazy(() => PressureState), "ownContributionEstimate": z.number().optional() }).passthrough(), "Emulation.setPressureDataOverride.params", "commandParams", { method: "Emulation.setPressureDataOverride" }); export const SetPressureDataOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setPressureDataOverride.result", "commandResult", { method: "Emulation.setPressureDataOverride" }); +export const SetPressureDataOverrideCommand = withCdpCommand("Emulation.setPressureDataOverride", SetPressureDataOverrideParams, SetPressureDataOverrideResult); export const SetIdleOverrideParams = withCdpMeta(z.object({ "isUserActive": z.boolean(), "isScreenUnlocked": z.boolean() }).passthrough(), "Emulation.setIdleOverride.params", "commandParams", { method: "Emulation.setIdleOverride" }); export const SetIdleOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setIdleOverride.result", "commandResult", { method: "Emulation.setIdleOverride" }); +export const SetIdleOverrideCommand = withCdpCommand("Emulation.setIdleOverride", SetIdleOverrideParams, SetIdleOverrideResult); export const ClearIdleOverrideParams = withCdpMeta(z.object({ }).passthrough(), "Emulation.clearIdleOverride.params", "commandParams", { method: "Emulation.clearIdleOverride" }); export const ClearIdleOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.clearIdleOverride.result", "commandResult", { method: "Emulation.clearIdleOverride" }); +export const ClearIdleOverrideCommand = withCdpCommand("Emulation.clearIdleOverride", ClearIdleOverrideParams, ClearIdleOverrideResult); export const SetNavigatorOverridesParams = withCdpMeta(z.object({ "platform": z.string() }).passthrough(), "Emulation.setNavigatorOverrides.params", "commandParams", { method: "Emulation.setNavigatorOverrides" }); export const SetNavigatorOverridesResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setNavigatorOverrides.result", "commandResult", { method: "Emulation.setNavigatorOverrides" }); +export const SetNavigatorOverridesCommand = withCdpCommand("Emulation.setNavigatorOverrides", SetNavigatorOverridesParams, SetNavigatorOverridesResult); export const SetPageScaleFactorParams = withCdpMeta(z.object({ "pageScaleFactor": z.number() }).passthrough(), "Emulation.setPageScaleFactor.params", "commandParams", { method: "Emulation.setPageScaleFactor" }); export const SetPageScaleFactorResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setPageScaleFactor.result", "commandResult", { method: "Emulation.setPageScaleFactor" }); +export const SetPageScaleFactorCommand = withCdpCommand("Emulation.setPageScaleFactor", SetPageScaleFactorParams, SetPageScaleFactorResult); export const SetScriptExecutionDisabledParams = withCdpMeta(z.object({ "value": z.boolean() }).passthrough(), "Emulation.setScriptExecutionDisabled.params", "commandParams", { method: "Emulation.setScriptExecutionDisabled" }); export const SetScriptExecutionDisabledResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setScriptExecutionDisabled.result", "commandResult", { method: "Emulation.setScriptExecutionDisabled" }); +export const SetScriptExecutionDisabledCommand = withCdpCommand("Emulation.setScriptExecutionDisabled", SetScriptExecutionDisabledParams, SetScriptExecutionDisabledResult); export const SetTouchEmulationEnabledParams = withCdpMeta(z.object({ "enabled": z.boolean(), "maxTouchPoints": z.number().int().optional() }).passthrough(), "Emulation.setTouchEmulationEnabled.params", "commandParams", { method: "Emulation.setTouchEmulationEnabled" }); export const SetTouchEmulationEnabledResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setTouchEmulationEnabled.result", "commandResult", { method: "Emulation.setTouchEmulationEnabled" }); +export const SetTouchEmulationEnabledCommand = withCdpCommand("Emulation.setTouchEmulationEnabled", SetTouchEmulationEnabledParams, SetTouchEmulationEnabledResult); export const SetVirtualTimePolicyParams = withCdpMeta(z.object({ "policy": z.lazy(() => VirtualTimePolicy), "budget": z.number().optional(), "maxVirtualTimeTaskStarvationCount": z.number().int().optional(), "initialVirtualTime": z.lazy(() => Network.TimeSinceEpoch).optional() }).passthrough(), "Emulation.setVirtualTimePolicy.params", "commandParams", { method: "Emulation.setVirtualTimePolicy" }); export const SetVirtualTimePolicyResult = withCdpMeta(z.object({ "virtualTimeTicksBase": z.number() }).passthrough(), "Emulation.setVirtualTimePolicy.result", "commandResult", { method: "Emulation.setVirtualTimePolicy" }); +export const SetVirtualTimePolicyCommand = withCdpCommand("Emulation.setVirtualTimePolicy", SetVirtualTimePolicyParams, SetVirtualTimePolicyResult); export const SetLocaleOverrideParams = withCdpMeta(z.object({ "locale": z.string().optional() }).passthrough(), "Emulation.setLocaleOverride.params", "commandParams", { method: "Emulation.setLocaleOverride" }); export const SetLocaleOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setLocaleOverride.result", "commandResult", { method: "Emulation.setLocaleOverride" }); +export const SetLocaleOverrideCommand = withCdpCommand("Emulation.setLocaleOverride", SetLocaleOverrideParams, SetLocaleOverrideResult); export const SetTimezoneOverrideParams = withCdpMeta(z.object({ "timezoneId": z.string() }).passthrough(), "Emulation.setTimezoneOverride.params", "commandParams", { method: "Emulation.setTimezoneOverride" }); export const SetTimezoneOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setTimezoneOverride.result", "commandResult", { method: "Emulation.setTimezoneOverride" }); +export const SetTimezoneOverrideCommand = withCdpCommand("Emulation.setTimezoneOverride", SetTimezoneOverrideParams, SetTimezoneOverrideResult); export const SetVisibleSizeParams = withCdpMeta(z.object({ "width": z.number().int(), "height": z.number().int() }).passthrough(), "Emulation.setVisibleSize.params", "commandParams", { method: "Emulation.setVisibleSize" }); export const SetVisibleSizeResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setVisibleSize.result", "commandResult", { method: "Emulation.setVisibleSize" }); +export const SetVisibleSizeCommand = withCdpCommand("Emulation.setVisibleSize", SetVisibleSizeParams, SetVisibleSizeResult); export const SetDisabledImageTypesParams = withCdpMeta(z.object({ "imageTypes": z.array(z.lazy(() => DisabledImageType)) }).passthrough(), "Emulation.setDisabledImageTypes.params", "commandParams", { method: "Emulation.setDisabledImageTypes" }); export const SetDisabledImageTypesResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setDisabledImageTypes.result", "commandResult", { method: "Emulation.setDisabledImageTypes" }); +export const SetDisabledImageTypesCommand = withCdpCommand("Emulation.setDisabledImageTypes", SetDisabledImageTypesParams, SetDisabledImageTypesResult); export const SetDataSaverOverrideParams = withCdpMeta(z.object({ "dataSaverEnabled": z.boolean().optional() }).passthrough(), "Emulation.setDataSaverOverride.params", "commandParams", { method: "Emulation.setDataSaverOverride" }); export const SetDataSaverOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setDataSaverOverride.result", "commandResult", { method: "Emulation.setDataSaverOverride" }); +export const SetDataSaverOverrideCommand = withCdpCommand("Emulation.setDataSaverOverride", SetDataSaverOverrideParams, SetDataSaverOverrideResult); export const SetHardwareConcurrencyOverrideParams = withCdpMeta(z.object({ "hardwareConcurrency": z.number().int() }).passthrough(), "Emulation.setHardwareConcurrencyOverride.params", "commandParams", { method: "Emulation.setHardwareConcurrencyOverride" }); export const SetHardwareConcurrencyOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setHardwareConcurrencyOverride.result", "commandResult", { method: "Emulation.setHardwareConcurrencyOverride" }); +export const SetHardwareConcurrencyOverrideCommand = withCdpCommand("Emulation.setHardwareConcurrencyOverride", SetHardwareConcurrencyOverrideParams, SetHardwareConcurrencyOverrideResult); export const SetUserAgentOverrideParams = withCdpMeta(z.object({ "userAgent": z.string(), "acceptLanguage": z.string().optional(), "platform": z.string().optional(), "userAgentMetadata": z.lazy(() => UserAgentMetadata).optional() }).passthrough(), "Emulation.setUserAgentOverride.params", "commandParams", { method: "Emulation.setUserAgentOverride" }); export const SetUserAgentOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setUserAgentOverride.result", "commandResult", { method: "Emulation.setUserAgentOverride" }); +export const SetUserAgentOverrideCommand = withCdpCommand("Emulation.setUserAgentOverride", SetUserAgentOverrideParams, SetUserAgentOverrideResult); export const SetAutomationOverrideParams = withCdpMeta(z.object({ "enabled": z.boolean() }).passthrough(), "Emulation.setAutomationOverride.params", "commandParams", { method: "Emulation.setAutomationOverride" }); export const SetAutomationOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setAutomationOverride.result", "commandResult", { method: "Emulation.setAutomationOverride" }); +export const SetAutomationOverrideCommand = withCdpCommand("Emulation.setAutomationOverride", SetAutomationOverrideParams, SetAutomationOverrideResult); export const SetSmallViewportHeightDifferenceOverrideParams = withCdpMeta(z.object({ "difference": z.number().int() }).passthrough(), "Emulation.setSmallViewportHeightDifferenceOverride.params", "commandParams", { method: "Emulation.setSmallViewportHeightDifferenceOverride" }); export const SetSmallViewportHeightDifferenceOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setSmallViewportHeightDifferenceOverride.result", "commandResult", { method: "Emulation.setSmallViewportHeightDifferenceOverride" }); +export const SetSmallViewportHeightDifferenceOverrideCommand = withCdpCommand("Emulation.setSmallViewportHeightDifferenceOverride", SetSmallViewportHeightDifferenceOverrideParams, SetSmallViewportHeightDifferenceOverrideResult); export const GetScreenInfosParams = withCdpMeta(z.object({ }).passthrough(), "Emulation.getScreenInfos.params", "commandParams", { method: "Emulation.getScreenInfos" }); export const GetScreenInfosResult = withCdpMeta(z.object({ "screenInfos": z.array(z.lazy(() => ScreenInfo)) }).passthrough(), "Emulation.getScreenInfos.result", "commandResult", { method: "Emulation.getScreenInfos" }); +export const GetScreenInfosCommand = withCdpCommand("Emulation.getScreenInfos", GetScreenInfosParams, GetScreenInfosResult); export const AddScreenParams = withCdpMeta(z.object({ "left": z.number().int(), "top": z.number().int(), "width": z.number().int(), "height": z.number().int(), "workAreaInsets": z.lazy(() => WorkAreaInsets).optional(), "devicePixelRatio": z.number().optional(), "rotation": z.number().int().optional(), "colorDepth": z.number().int().optional(), "label": z.string().optional(), "isInternal": z.boolean().optional() }).passthrough(), "Emulation.addScreen.params", "commandParams", { method: "Emulation.addScreen" }); export const AddScreenResult = withCdpMeta(z.object({ "screenInfo": z.lazy(() => ScreenInfo) }).passthrough(), "Emulation.addScreen.result", "commandResult", { method: "Emulation.addScreen" }); +export const AddScreenCommand = withCdpCommand("Emulation.addScreen", AddScreenParams, AddScreenResult); export const UpdateScreenParams = withCdpMeta(z.object({ "screenId": z.lazy(() => ScreenId), "left": z.number().int().optional(), "top": z.number().int().optional(), "width": z.number().int().optional(), "height": z.number().int().optional(), "workAreaInsets": z.lazy(() => WorkAreaInsets).optional(), "devicePixelRatio": z.number().optional(), "rotation": z.number().int().optional(), "colorDepth": z.number().int().optional(), "label": z.string().optional(), "isInternal": z.boolean().optional() }).passthrough(), "Emulation.updateScreen.params", "commandParams", { method: "Emulation.updateScreen" }); export const UpdateScreenResult = withCdpMeta(z.object({ "screenInfo": z.lazy(() => ScreenInfo) }).passthrough(), "Emulation.updateScreen.result", "commandResult", { method: "Emulation.updateScreen" }); +export const UpdateScreenCommand = withCdpCommand("Emulation.updateScreen", UpdateScreenParams, UpdateScreenResult); export const RemoveScreenParams = withCdpMeta(z.object({ "screenId": z.lazy(() => ScreenId) }).passthrough(), "Emulation.removeScreen.params", "commandParams", { method: "Emulation.removeScreen" }); export const RemoveScreenResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.removeScreen.result", "commandResult", { method: "Emulation.removeScreen" }); +export const RemoveScreenCommand = withCdpCommand("Emulation.removeScreen", RemoveScreenParams, RemoveScreenResult); export const SetPrimaryScreenParams = withCdpMeta(z.object({ "screenId": z.lazy(() => ScreenId) }).passthrough(), "Emulation.setPrimaryScreen.params", "commandParams", { method: "Emulation.setPrimaryScreen" }); export const SetPrimaryScreenResult = withCdpMeta(z.object({ }).passthrough(), "Emulation.setPrimaryScreen.result", "commandResult", { method: "Emulation.setPrimaryScreen" }); +export const SetPrimaryScreenCommand = withCdpCommand("Emulation.setPrimaryScreen", SetPrimaryScreenParams, SetPrimaryScreenResult); export const VirtualTimeBudgetExpiredEvent = withCdpMeta(z.object({ }).passthrough(), "Emulation.virtualTimeBudgetExpired", "event", { phase: "event" }); export const ScreenOrientationLockChangedEvent = withCdpMeta(z.object({ "locked": z.boolean(), "orientation": z.lazy(() => ScreenOrientation).optional() }).passthrough(), "Emulation.screenOrientationLockChanged", "event", { phase: "event" }); @@ -248,54 +296,54 @@ export const zod = { ScreenOrientationLockChangedEvent: ScreenOrientationLockChangedEvent, } as const; export const commands = { - "Emulation.canEmulate": { params: CanEmulateParams, result: CanEmulateResult }, - "Emulation.clearDeviceMetricsOverride": { params: ClearDeviceMetricsOverrideParams, result: ClearDeviceMetricsOverrideResult }, - "Emulation.clearGeolocationOverride": { params: ClearGeolocationOverrideParams, result: ClearGeolocationOverrideResult }, - "Emulation.resetPageScaleFactor": { params: ResetPageScaleFactorParams, result: ResetPageScaleFactorResult }, - "Emulation.setFocusEmulationEnabled": { params: SetFocusEmulationEnabledParams, result: SetFocusEmulationEnabledResult }, - "Emulation.setAutoDarkModeOverride": { params: SetAutoDarkModeOverrideParams, result: SetAutoDarkModeOverrideResult }, - "Emulation.setCPUThrottlingRate": { params: SetCPUThrottlingRateParams, result: SetCPUThrottlingRateResult }, - "Emulation.setDefaultBackgroundColorOverride": { params: SetDefaultBackgroundColorOverrideParams, result: SetDefaultBackgroundColorOverrideResult }, - "Emulation.setSafeAreaInsetsOverride": { params: SetSafeAreaInsetsOverrideParams, result: SetSafeAreaInsetsOverrideResult }, - "Emulation.setDeviceMetricsOverride": { params: SetDeviceMetricsOverrideParams, result: SetDeviceMetricsOverrideResult }, - "Emulation.setDevicePostureOverride": { params: SetDevicePostureOverrideParams, result: SetDevicePostureOverrideResult }, - "Emulation.clearDevicePostureOverride": { params: ClearDevicePostureOverrideParams, result: ClearDevicePostureOverrideResult }, - "Emulation.setDisplayFeaturesOverride": { params: SetDisplayFeaturesOverrideParams, result: SetDisplayFeaturesOverrideResult }, - "Emulation.clearDisplayFeaturesOverride": { params: ClearDisplayFeaturesOverrideParams, result: ClearDisplayFeaturesOverrideResult }, - "Emulation.setScrollbarsHidden": { params: SetScrollbarsHiddenParams, result: SetScrollbarsHiddenResult }, - "Emulation.setDocumentCookieDisabled": { params: SetDocumentCookieDisabledParams, result: SetDocumentCookieDisabledResult }, - "Emulation.setEmitTouchEventsForMouse": { params: SetEmitTouchEventsForMouseParams, result: SetEmitTouchEventsForMouseResult }, - "Emulation.setEmulatedMedia": { params: SetEmulatedMediaParams, result: SetEmulatedMediaResult }, - "Emulation.setEmulatedVisionDeficiency": { params: SetEmulatedVisionDeficiencyParams, result: SetEmulatedVisionDeficiencyResult }, - "Emulation.setEmulatedOSTextScale": { params: SetEmulatedOSTextScaleParams, result: SetEmulatedOSTextScaleResult }, - "Emulation.setGeolocationOverride": { params: SetGeolocationOverrideParams, result: SetGeolocationOverrideResult }, - "Emulation.getOverriddenSensorInformation": { params: GetOverriddenSensorInformationParams, result: GetOverriddenSensorInformationResult }, - "Emulation.setSensorOverrideEnabled": { params: SetSensorOverrideEnabledParams, result: SetSensorOverrideEnabledResult }, - "Emulation.setSensorOverrideReadings": { params: SetSensorOverrideReadingsParams, result: SetSensorOverrideReadingsResult }, - "Emulation.setPressureSourceOverrideEnabled": { params: SetPressureSourceOverrideEnabledParams, result: SetPressureSourceOverrideEnabledResult }, - "Emulation.setPressureStateOverride": { params: SetPressureStateOverrideParams, result: SetPressureStateOverrideResult }, - "Emulation.setPressureDataOverride": { params: SetPressureDataOverrideParams, result: SetPressureDataOverrideResult }, - "Emulation.setIdleOverride": { params: SetIdleOverrideParams, result: SetIdleOverrideResult }, - "Emulation.clearIdleOverride": { params: ClearIdleOverrideParams, result: ClearIdleOverrideResult }, - "Emulation.setNavigatorOverrides": { params: SetNavigatorOverridesParams, result: SetNavigatorOverridesResult }, - "Emulation.setPageScaleFactor": { params: SetPageScaleFactorParams, result: SetPageScaleFactorResult }, - "Emulation.setScriptExecutionDisabled": { params: SetScriptExecutionDisabledParams, result: SetScriptExecutionDisabledResult }, - "Emulation.setTouchEmulationEnabled": { params: SetTouchEmulationEnabledParams, result: SetTouchEmulationEnabledResult }, - "Emulation.setVirtualTimePolicy": { params: SetVirtualTimePolicyParams, result: SetVirtualTimePolicyResult }, - "Emulation.setLocaleOverride": { params: SetLocaleOverrideParams, result: SetLocaleOverrideResult }, - "Emulation.setTimezoneOverride": { params: SetTimezoneOverrideParams, result: SetTimezoneOverrideResult }, - "Emulation.setVisibleSize": { params: SetVisibleSizeParams, result: SetVisibleSizeResult }, - "Emulation.setDisabledImageTypes": { params: SetDisabledImageTypesParams, result: SetDisabledImageTypesResult }, - "Emulation.setDataSaverOverride": { params: SetDataSaverOverrideParams, result: SetDataSaverOverrideResult }, - "Emulation.setHardwareConcurrencyOverride": { params: SetHardwareConcurrencyOverrideParams, result: SetHardwareConcurrencyOverrideResult }, - "Emulation.setUserAgentOverride": { params: SetUserAgentOverrideParams, result: SetUserAgentOverrideResult }, - "Emulation.setAutomationOverride": { params: SetAutomationOverrideParams, result: SetAutomationOverrideResult }, - "Emulation.setSmallViewportHeightDifferenceOverride": { params: SetSmallViewportHeightDifferenceOverrideParams, result: SetSmallViewportHeightDifferenceOverrideResult }, - "Emulation.getScreenInfos": { params: GetScreenInfosParams, result: GetScreenInfosResult }, - "Emulation.addScreen": { params: AddScreenParams, result: AddScreenResult }, - "Emulation.updateScreen": { params: UpdateScreenParams, result: UpdateScreenResult }, - "Emulation.removeScreen": { params: RemoveScreenParams, result: RemoveScreenResult }, - "Emulation.setPrimaryScreen": { params: SetPrimaryScreenParams, result: SetPrimaryScreenResult }, + "Emulation.canEmulate": CanEmulateCommand, + "Emulation.clearDeviceMetricsOverride": ClearDeviceMetricsOverrideCommand, + "Emulation.clearGeolocationOverride": ClearGeolocationOverrideCommand, + "Emulation.resetPageScaleFactor": ResetPageScaleFactorCommand, + "Emulation.setFocusEmulationEnabled": SetFocusEmulationEnabledCommand, + "Emulation.setAutoDarkModeOverride": SetAutoDarkModeOverrideCommand, + "Emulation.setCPUThrottlingRate": SetCPUThrottlingRateCommand, + "Emulation.setDefaultBackgroundColorOverride": SetDefaultBackgroundColorOverrideCommand, + "Emulation.setSafeAreaInsetsOverride": SetSafeAreaInsetsOverrideCommand, + "Emulation.setDeviceMetricsOverride": SetDeviceMetricsOverrideCommand, + "Emulation.setDevicePostureOverride": SetDevicePostureOverrideCommand, + "Emulation.clearDevicePostureOverride": ClearDevicePostureOverrideCommand, + "Emulation.setDisplayFeaturesOverride": SetDisplayFeaturesOverrideCommand, + "Emulation.clearDisplayFeaturesOverride": ClearDisplayFeaturesOverrideCommand, + "Emulation.setScrollbarsHidden": SetScrollbarsHiddenCommand, + "Emulation.setDocumentCookieDisabled": SetDocumentCookieDisabledCommand, + "Emulation.setEmitTouchEventsForMouse": SetEmitTouchEventsForMouseCommand, + "Emulation.setEmulatedMedia": SetEmulatedMediaCommand, + "Emulation.setEmulatedVisionDeficiency": SetEmulatedVisionDeficiencyCommand, + "Emulation.setEmulatedOSTextScale": SetEmulatedOSTextScaleCommand, + "Emulation.setGeolocationOverride": SetGeolocationOverrideCommand, + "Emulation.getOverriddenSensorInformation": GetOverriddenSensorInformationCommand, + "Emulation.setSensorOverrideEnabled": SetSensorOverrideEnabledCommand, + "Emulation.setSensorOverrideReadings": SetSensorOverrideReadingsCommand, + "Emulation.setPressureSourceOverrideEnabled": SetPressureSourceOverrideEnabledCommand, + "Emulation.setPressureStateOverride": SetPressureStateOverrideCommand, + "Emulation.setPressureDataOverride": SetPressureDataOverrideCommand, + "Emulation.setIdleOverride": SetIdleOverrideCommand, + "Emulation.clearIdleOverride": ClearIdleOverrideCommand, + "Emulation.setNavigatorOverrides": SetNavigatorOverridesCommand, + "Emulation.setPageScaleFactor": SetPageScaleFactorCommand, + "Emulation.setScriptExecutionDisabled": SetScriptExecutionDisabledCommand, + "Emulation.setTouchEmulationEnabled": SetTouchEmulationEnabledCommand, + "Emulation.setVirtualTimePolicy": SetVirtualTimePolicyCommand, + "Emulation.setLocaleOverride": SetLocaleOverrideCommand, + "Emulation.setTimezoneOverride": SetTimezoneOverrideCommand, + "Emulation.setVisibleSize": SetVisibleSizeCommand, + "Emulation.setDisabledImageTypes": SetDisabledImageTypesCommand, + "Emulation.setDataSaverOverride": SetDataSaverOverrideCommand, + "Emulation.setHardwareConcurrencyOverride": SetHardwareConcurrencyOverrideCommand, + "Emulation.setUserAgentOverride": SetUserAgentOverrideCommand, + "Emulation.setAutomationOverride": SetAutomationOverrideCommand, + "Emulation.setSmallViewportHeightDifferenceOverride": SetSmallViewportHeightDifferenceOverrideCommand, + "Emulation.getScreenInfos": GetScreenInfosCommand, + "Emulation.addScreen": AddScreenCommand, + "Emulation.updateScreen": UpdateScreenCommand, + "Emulation.removeScreen": RemoveScreenCommand, + "Emulation.setPrimaryScreen": SetPrimaryScreenCommand, } as const; export const events = { "Emulation.virtualTimeBudgetExpired": VirtualTimeBudgetExpiredEvent, diff --git a/js/src/types/generated/zod/EventBreakpoints.ts b/js/src/types/generated/zod/EventBreakpoints.ts index 6f9da15..88f03f0 100644 --- a/js/src/types/generated/zod/EventBreakpoints.ts +++ b/js/src/types/generated/zod/EventBreakpoints.ts @@ -1,14 +1,17 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const SetInstrumentationBreakpointParams = withCdpMeta(z.object({ "eventName": z.string() }).passthrough(), "EventBreakpoints.setInstrumentationBreakpoint.params", "commandParams", { method: "EventBreakpoints.setInstrumentationBreakpoint" }); export const SetInstrumentationBreakpointResult = withCdpMeta(z.object({ }).passthrough(), "EventBreakpoints.setInstrumentationBreakpoint.result", "commandResult", { method: "EventBreakpoints.setInstrumentationBreakpoint" }); +export const SetInstrumentationBreakpointCommand = withCdpCommand("EventBreakpoints.setInstrumentationBreakpoint", SetInstrumentationBreakpointParams, SetInstrumentationBreakpointResult); export const RemoveInstrumentationBreakpointParams = withCdpMeta(z.object({ "eventName": z.string() }).passthrough(), "EventBreakpoints.removeInstrumentationBreakpoint.params", "commandParams", { method: "EventBreakpoints.removeInstrumentationBreakpoint" }); export const RemoveInstrumentationBreakpointResult = withCdpMeta(z.object({ }).passthrough(), "EventBreakpoints.removeInstrumentationBreakpoint.result", "commandResult", { method: "EventBreakpoints.removeInstrumentationBreakpoint" }); +export const RemoveInstrumentationBreakpointCommand = withCdpCommand("EventBreakpoints.removeInstrumentationBreakpoint", RemoveInstrumentationBreakpointParams, RemoveInstrumentationBreakpointResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "EventBreakpoints.disable.params", "commandParams", { method: "EventBreakpoints.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "EventBreakpoints.disable.result", "commandResult", { method: "EventBreakpoints.disable" }); +export const DisableCommand = withCdpCommand("EventBreakpoints.disable", DisableParams, DisableResult); export const zod = { SetInstrumentationBreakpointParams: SetInstrumentationBreakpointParams, @@ -19,9 +22,9 @@ export const zod = { DisableResult: DisableResult, } as const; export const commands = { - "EventBreakpoints.setInstrumentationBreakpoint": { params: SetInstrumentationBreakpointParams, result: SetInstrumentationBreakpointResult }, - "EventBreakpoints.removeInstrumentationBreakpoint": { params: RemoveInstrumentationBreakpointParams, result: RemoveInstrumentationBreakpointResult }, - "EventBreakpoints.disable": { params: DisableParams, result: DisableResult }, + "EventBreakpoints.setInstrumentationBreakpoint": SetInstrumentationBreakpointCommand, + "EventBreakpoints.removeInstrumentationBreakpoint": RemoveInstrumentationBreakpointCommand, + "EventBreakpoints.disable": DisableCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/Extensions.ts b/js/src/types/generated/zod/Extensions.ts index 8cd2332..9552320 100644 --- a/js/src/types/generated/zod/Extensions.ts +++ b/js/src/types/generated/zod/Extensions.ts @@ -1,26 +1,34 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const StorageArea = withCdpMeta(z.enum(["session", "local", "sync", "managed"]), "Extensions.StorageArea", "type"); export const ExtensionInfo = withCdpMeta(z.object({ "id": z.string(), "name": z.string(), "version": z.string(), "path": z.string(), "enabled": z.boolean() }).passthrough(), "Extensions.ExtensionInfo", "type"); export const TriggerActionParams = withCdpMeta(z.object({ "id": z.string(), "targetId": z.string() }).passthrough(), "Extensions.triggerAction.params", "commandParams", { method: "Extensions.triggerAction" }); export const TriggerActionResult = withCdpMeta(z.object({ }).passthrough(), "Extensions.triggerAction.result", "commandResult", { method: "Extensions.triggerAction" }); +export const TriggerActionCommand = withCdpCommand("Extensions.triggerAction", TriggerActionParams, TriggerActionResult); export const LoadUnpackedParams = withCdpMeta(z.object({ "path": z.string(), "enableInIncognito": z.boolean().optional() }).passthrough(), "Extensions.loadUnpacked.params", "commandParams", { method: "Extensions.loadUnpacked" }); export const LoadUnpackedResult = withCdpMeta(z.object({ "id": z.string() }).passthrough(), "Extensions.loadUnpacked.result", "commandResult", { method: "Extensions.loadUnpacked" }); +export const LoadUnpackedCommand = withCdpCommand("Extensions.loadUnpacked", LoadUnpackedParams, LoadUnpackedResult); export const GetExtensionsParams = withCdpMeta(z.object({ }).passthrough(), "Extensions.getExtensions.params", "commandParams", { method: "Extensions.getExtensions" }); export const GetExtensionsResult = withCdpMeta(z.object({ "extensions": z.array(z.lazy(() => ExtensionInfo)) }).passthrough(), "Extensions.getExtensions.result", "commandResult", { method: "Extensions.getExtensions" }); +export const GetExtensionsCommand = withCdpCommand("Extensions.getExtensions", GetExtensionsParams, GetExtensionsResult); export const UninstallParams = withCdpMeta(z.object({ "id": z.string() }).passthrough(), "Extensions.uninstall.params", "commandParams", { method: "Extensions.uninstall" }); export const UninstallResult = withCdpMeta(z.object({ }).passthrough(), "Extensions.uninstall.result", "commandResult", { method: "Extensions.uninstall" }); +export const UninstallCommand = withCdpCommand("Extensions.uninstall", UninstallParams, UninstallResult); export const GetStorageItemsParams = withCdpMeta(z.object({ "id": z.string(), "storageArea": z.lazy(() => StorageArea), "keys": z.array(z.string()).optional() }).passthrough(), "Extensions.getStorageItems.params", "commandParams", { method: "Extensions.getStorageItems" }); export const GetStorageItemsResult = withCdpMeta(z.object({ "data": z.record(z.string(), z.unknown()) }).passthrough(), "Extensions.getStorageItems.result", "commandResult", { method: "Extensions.getStorageItems" }); +export const GetStorageItemsCommand = withCdpCommand("Extensions.getStorageItems", GetStorageItemsParams, GetStorageItemsResult); export const RemoveStorageItemsParams = withCdpMeta(z.object({ "id": z.string(), "storageArea": z.lazy(() => StorageArea), "keys": z.array(z.string()) }).passthrough(), "Extensions.removeStorageItems.params", "commandParams", { method: "Extensions.removeStorageItems" }); export const RemoveStorageItemsResult = withCdpMeta(z.object({ }).passthrough(), "Extensions.removeStorageItems.result", "commandResult", { method: "Extensions.removeStorageItems" }); +export const RemoveStorageItemsCommand = withCdpCommand("Extensions.removeStorageItems", RemoveStorageItemsParams, RemoveStorageItemsResult); export const ClearStorageItemsParams = withCdpMeta(z.object({ "id": z.string(), "storageArea": z.lazy(() => StorageArea) }).passthrough(), "Extensions.clearStorageItems.params", "commandParams", { method: "Extensions.clearStorageItems" }); export const ClearStorageItemsResult = withCdpMeta(z.object({ }).passthrough(), "Extensions.clearStorageItems.result", "commandResult", { method: "Extensions.clearStorageItems" }); +export const ClearStorageItemsCommand = withCdpCommand("Extensions.clearStorageItems", ClearStorageItemsParams, ClearStorageItemsResult); export const SetStorageItemsParams = withCdpMeta(z.object({ "id": z.string(), "storageArea": z.lazy(() => StorageArea), "values": z.record(z.string(), z.unknown()) }).passthrough(), "Extensions.setStorageItems.params", "commandParams", { method: "Extensions.setStorageItems" }); export const SetStorageItemsResult = withCdpMeta(z.object({ }).passthrough(), "Extensions.setStorageItems.result", "commandResult", { method: "Extensions.setStorageItems" }); +export const SetStorageItemsCommand = withCdpCommand("Extensions.setStorageItems", SetStorageItemsParams, SetStorageItemsResult); export const zod = { StorageArea: StorageArea, @@ -43,14 +51,14 @@ export const zod = { SetStorageItemsResult: SetStorageItemsResult, } as const; export const commands = { - "Extensions.triggerAction": { params: TriggerActionParams, result: TriggerActionResult }, - "Extensions.loadUnpacked": { params: LoadUnpackedParams, result: LoadUnpackedResult }, - "Extensions.getExtensions": { params: GetExtensionsParams, result: GetExtensionsResult }, - "Extensions.uninstall": { params: UninstallParams, result: UninstallResult }, - "Extensions.getStorageItems": { params: GetStorageItemsParams, result: GetStorageItemsResult }, - "Extensions.removeStorageItems": { params: RemoveStorageItemsParams, result: RemoveStorageItemsResult }, - "Extensions.clearStorageItems": { params: ClearStorageItemsParams, result: ClearStorageItemsResult }, - "Extensions.setStorageItems": { params: SetStorageItemsParams, result: SetStorageItemsResult }, + "Extensions.triggerAction": TriggerActionCommand, + "Extensions.loadUnpacked": LoadUnpackedCommand, + "Extensions.getExtensions": GetExtensionsCommand, + "Extensions.uninstall": UninstallCommand, + "Extensions.getStorageItems": GetStorageItemsCommand, + "Extensions.removeStorageItems": RemoveStorageItemsCommand, + "Extensions.clearStorageItems": ClearStorageItemsCommand, + "Extensions.setStorageItems": SetStorageItemsCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/FedCm.ts b/js/src/types/generated/zod/FedCm.ts index a39f549..daa5ecf 100644 --- a/js/src/types/generated/zod/FedCm.ts +++ b/js/src/types/generated/zod/FedCm.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const LoginState = withCdpMeta(z.enum(["SignIn", "SignUp"]), "FedCm.LoginState", "type"); export const DialogType = withCdpMeta(z.enum(["AccountChooser", "AutoReauthn", "ConfirmIdpLogin", "Error"]), "FedCm.DialogType", "type"); @@ -10,18 +10,25 @@ export const AccountUrlType = withCdpMeta(z.enum(["TermsOfService", "PrivacyPoli export const Account = withCdpMeta(z.object({ "accountId": z.string(), "email": z.string(), "name": z.string(), "givenName": z.string(), "pictureUrl": z.string(), "idpConfigUrl": z.string(), "idpLoginUrl": z.string(), "loginState": z.lazy(() => LoginState), "termsOfServiceUrl": z.string().optional(), "privacyPolicyUrl": z.string().optional() }).passthrough(), "FedCm.Account", "type"); export const EnableParams = withCdpMeta(z.object({ "disableRejectionDelay": z.boolean().optional() }).passthrough(), "FedCm.enable.params", "commandParams", { method: "FedCm.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "FedCm.enable.result", "commandResult", { method: "FedCm.enable" }); +export const EnableCommand = withCdpCommand("FedCm.enable", EnableParams, EnableResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "FedCm.disable.params", "commandParams", { method: "FedCm.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "FedCm.disable.result", "commandResult", { method: "FedCm.disable" }); +export const DisableCommand = withCdpCommand("FedCm.disable", DisableParams, DisableResult); export const SelectAccountParams = withCdpMeta(z.object({ "dialogId": z.string(), "accountIndex": z.number().int() }).passthrough(), "FedCm.selectAccount.params", "commandParams", { method: "FedCm.selectAccount" }); export const SelectAccountResult = withCdpMeta(z.object({ }).passthrough(), "FedCm.selectAccount.result", "commandResult", { method: "FedCm.selectAccount" }); +export const SelectAccountCommand = withCdpCommand("FedCm.selectAccount", SelectAccountParams, SelectAccountResult); export const ClickDialogButtonParams = withCdpMeta(z.object({ "dialogId": z.string(), "dialogButton": z.lazy(() => DialogButton) }).passthrough(), "FedCm.clickDialogButton.params", "commandParams", { method: "FedCm.clickDialogButton" }); export const ClickDialogButtonResult = withCdpMeta(z.object({ }).passthrough(), "FedCm.clickDialogButton.result", "commandResult", { method: "FedCm.clickDialogButton" }); +export const ClickDialogButtonCommand = withCdpCommand("FedCm.clickDialogButton", ClickDialogButtonParams, ClickDialogButtonResult); export const OpenUrlParams = withCdpMeta(z.object({ "dialogId": z.string(), "accountIndex": z.number().int(), "accountUrlType": z.lazy(() => AccountUrlType) }).passthrough(), "FedCm.openUrl.params", "commandParams", { method: "FedCm.openUrl" }); export const OpenUrlResult = withCdpMeta(z.object({ }).passthrough(), "FedCm.openUrl.result", "commandResult", { method: "FedCm.openUrl" }); +export const OpenUrlCommand = withCdpCommand("FedCm.openUrl", OpenUrlParams, OpenUrlResult); export const DismissDialogParams = withCdpMeta(z.object({ "dialogId": z.string(), "triggerCooldown": z.boolean().optional() }).passthrough(), "FedCm.dismissDialog.params", "commandParams", { method: "FedCm.dismissDialog" }); export const DismissDialogResult = withCdpMeta(z.object({ }).passthrough(), "FedCm.dismissDialog.result", "commandResult", { method: "FedCm.dismissDialog" }); +export const DismissDialogCommand = withCdpCommand("FedCm.dismissDialog", DismissDialogParams, DismissDialogResult); export const ResetCooldownParams = withCdpMeta(z.object({ }).passthrough(), "FedCm.resetCooldown.params", "commandParams", { method: "FedCm.resetCooldown" }); export const ResetCooldownResult = withCdpMeta(z.object({ }).passthrough(), "FedCm.resetCooldown.result", "commandResult", { method: "FedCm.resetCooldown" }); +export const ResetCooldownCommand = withCdpCommand("FedCm.resetCooldown", ResetCooldownParams, ResetCooldownResult); export const DialogShownEvent = withCdpMeta(z.object({ "dialogId": z.string(), "dialogType": z.lazy(() => DialogType), "accounts": z.array(z.lazy(() => Account)), "title": z.string(), "subtitle": z.string().optional() }).passthrough(), "FedCm.dialogShown", "event", { phase: "event" }); export const DialogClosedEvent = withCdpMeta(z.object({ "dialogId": z.string() }).passthrough(), "FedCm.dialogClosed", "event", { phase: "event" }); @@ -49,13 +56,13 @@ export const zod = { DialogClosedEvent: DialogClosedEvent, } as const; export const commands = { - "FedCm.enable": { params: EnableParams, result: EnableResult }, - "FedCm.disable": { params: DisableParams, result: DisableResult }, - "FedCm.selectAccount": { params: SelectAccountParams, result: SelectAccountResult }, - "FedCm.clickDialogButton": { params: ClickDialogButtonParams, result: ClickDialogButtonResult }, - "FedCm.openUrl": { params: OpenUrlParams, result: OpenUrlResult }, - "FedCm.dismissDialog": { params: DismissDialogParams, result: DismissDialogResult }, - "FedCm.resetCooldown": { params: ResetCooldownParams, result: ResetCooldownResult }, + "FedCm.enable": EnableCommand, + "FedCm.disable": DisableCommand, + "FedCm.selectAccount": SelectAccountCommand, + "FedCm.clickDialogButton": ClickDialogButtonCommand, + "FedCm.openUrl": OpenUrlCommand, + "FedCm.dismissDialog": DismissDialogCommand, + "FedCm.resetCooldown": ResetCooldownCommand, } as const; export const events = { "FedCm.dialogShown": DialogShownEvent, diff --git a/js/src/types/generated/zod/Fetch.ts b/js/src/types/generated/zod/Fetch.ts index f87b181..29ee458 100644 --- a/js/src/types/generated/zod/Fetch.ts +++ b/js/src/types/generated/zod/Fetch.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as IO from "./IO.js"; import * as Network from "./Network.js"; import * as Page from "./Page.js"; @@ -14,22 +14,31 @@ export const AuthChallenge = withCdpMeta(z.object({ "source": z.enum(["Server", export const AuthChallengeResponse = withCdpMeta(z.object({ "response": z.enum(["Default", "CancelAuth", "ProvideCredentials"]), "username": z.string().optional(), "password": z.string().optional() }).passthrough(), "Fetch.AuthChallengeResponse", "type"); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Fetch.disable.params", "commandParams", { method: "Fetch.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Fetch.disable.result", "commandResult", { method: "Fetch.disable" }); +export const DisableCommand = withCdpCommand("Fetch.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ "patterns": z.array(z.lazy(() => RequestPattern)).optional(), "handleAuthRequests": z.boolean().optional() }).passthrough(), "Fetch.enable.params", "commandParams", { method: "Fetch.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Fetch.enable.result", "commandResult", { method: "Fetch.enable" }); +export const EnableCommand = withCdpCommand("Fetch.enable", EnableParams, EnableResult); export const FailRequestParams = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId), "errorReason": z.lazy(() => Network.ErrorReason) }).passthrough(), "Fetch.failRequest.params", "commandParams", { method: "Fetch.failRequest" }); export const FailRequestResult = withCdpMeta(z.object({ }).passthrough(), "Fetch.failRequest.result", "commandResult", { method: "Fetch.failRequest" }); +export const FailRequestCommand = withCdpCommand("Fetch.failRequest", FailRequestParams, FailRequestResult); export const FulfillRequestParams = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId), "responseCode": z.number().int(), "responseHeaders": z.array(z.lazy(() => HeaderEntry)).optional(), "binaryResponseHeaders": z.string().optional(), "body": z.string().optional(), "responsePhrase": z.string().optional() }).passthrough(), "Fetch.fulfillRequest.params", "commandParams", { method: "Fetch.fulfillRequest" }); export const FulfillRequestResult = withCdpMeta(z.object({ }).passthrough(), "Fetch.fulfillRequest.result", "commandResult", { method: "Fetch.fulfillRequest" }); +export const FulfillRequestCommand = withCdpCommand("Fetch.fulfillRequest", FulfillRequestParams, FulfillRequestResult); export const ContinueRequestParams = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId), "url": z.string().optional(), "method": z.string().optional(), "postData": z.string().optional(), "headers": z.array(z.lazy(() => HeaderEntry)).optional(), "interceptResponse": z.boolean().optional() }).passthrough(), "Fetch.continueRequest.params", "commandParams", { method: "Fetch.continueRequest" }); export const ContinueRequestResult = withCdpMeta(z.object({ }).passthrough(), "Fetch.continueRequest.result", "commandResult", { method: "Fetch.continueRequest" }); +export const ContinueRequestCommand = withCdpCommand("Fetch.continueRequest", ContinueRequestParams, ContinueRequestResult); export const ContinueWithAuthParams = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId), "authChallengeResponse": z.lazy(() => AuthChallengeResponse) }).passthrough(), "Fetch.continueWithAuth.params", "commandParams", { method: "Fetch.continueWithAuth" }); export const ContinueWithAuthResult = withCdpMeta(z.object({ }).passthrough(), "Fetch.continueWithAuth.result", "commandResult", { method: "Fetch.continueWithAuth" }); +export const ContinueWithAuthCommand = withCdpCommand("Fetch.continueWithAuth", ContinueWithAuthParams, ContinueWithAuthResult); export const ContinueResponseParams = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId), "responseCode": z.number().int().optional(), "responsePhrase": z.string().optional(), "responseHeaders": z.array(z.lazy(() => HeaderEntry)).optional(), "binaryResponseHeaders": z.string().optional() }).passthrough(), "Fetch.continueResponse.params", "commandParams", { method: "Fetch.continueResponse" }); export const ContinueResponseResult = withCdpMeta(z.object({ }).passthrough(), "Fetch.continueResponse.result", "commandResult", { method: "Fetch.continueResponse" }); +export const ContinueResponseCommand = withCdpCommand("Fetch.continueResponse", ContinueResponseParams, ContinueResponseResult); export const GetResponseBodyParams = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId) }).passthrough(), "Fetch.getResponseBody.params", "commandParams", { method: "Fetch.getResponseBody" }); export const GetResponseBodyResult = withCdpMeta(z.object({ "body": z.string(), "base64Encoded": z.boolean() }).passthrough(), "Fetch.getResponseBody.result", "commandResult", { method: "Fetch.getResponseBody" }); +export const GetResponseBodyCommand = withCdpCommand("Fetch.getResponseBody", GetResponseBodyParams, GetResponseBodyResult); export const TakeResponseBodyAsStreamParams = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId) }).passthrough(), "Fetch.takeResponseBodyAsStream.params", "commandParams", { method: "Fetch.takeResponseBodyAsStream" }); export const TakeResponseBodyAsStreamResult = withCdpMeta(z.object({ "stream": z.lazy(() => IO.StreamHandle) }).passthrough(), "Fetch.takeResponseBodyAsStream.result", "commandResult", { method: "Fetch.takeResponseBodyAsStream" }); +export const TakeResponseBodyAsStreamCommand = withCdpCommand("Fetch.takeResponseBodyAsStream", TakeResponseBodyAsStreamParams, TakeResponseBodyAsStreamResult); export const RequestPausedEvent = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId), "request": z.lazy(() => Network.Request), "frameId": z.lazy(() => Page.FrameId), "resourceType": z.lazy(() => Network.ResourceType), "responseErrorReason": z.lazy(() => Network.ErrorReason).optional(), "responseStatusCode": z.number().int().optional(), "responseStatusText": z.string().optional(), "responseHeaders": z.array(z.lazy(() => HeaderEntry)).optional(), "networkId": z.lazy(() => Network.RequestId).optional(), "redirectedRequestId": z.lazy(() => RequestId).optional() }).passthrough(), "Fetch.requestPaused", "event", { phase: "event" }); export const AuthRequiredEvent = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId), "request": z.lazy(() => Network.Request), "frameId": z.lazy(() => Page.FrameId), "resourceType": z.lazy(() => Network.ResourceType), "authChallenge": z.lazy(() => AuthChallenge) }).passthrough(), "Fetch.authRequired", "event", { phase: "event" }); @@ -62,15 +71,15 @@ export const zod = { AuthRequiredEvent: AuthRequiredEvent, } as const; export const commands = { - "Fetch.disable": { params: DisableParams, result: DisableResult }, - "Fetch.enable": { params: EnableParams, result: EnableResult }, - "Fetch.failRequest": { params: FailRequestParams, result: FailRequestResult }, - "Fetch.fulfillRequest": { params: FulfillRequestParams, result: FulfillRequestResult }, - "Fetch.continueRequest": { params: ContinueRequestParams, result: ContinueRequestResult }, - "Fetch.continueWithAuth": { params: ContinueWithAuthParams, result: ContinueWithAuthResult }, - "Fetch.continueResponse": { params: ContinueResponseParams, result: ContinueResponseResult }, - "Fetch.getResponseBody": { params: GetResponseBodyParams, result: GetResponseBodyResult }, - "Fetch.takeResponseBodyAsStream": { params: TakeResponseBodyAsStreamParams, result: TakeResponseBodyAsStreamResult }, + "Fetch.disable": DisableCommand, + "Fetch.enable": EnableCommand, + "Fetch.failRequest": FailRequestCommand, + "Fetch.fulfillRequest": FulfillRequestCommand, + "Fetch.continueRequest": ContinueRequestCommand, + "Fetch.continueWithAuth": ContinueWithAuthCommand, + "Fetch.continueResponse": ContinueResponseCommand, + "Fetch.getResponseBody": GetResponseBodyCommand, + "Fetch.takeResponseBodyAsStream": TakeResponseBodyAsStreamCommand, } as const; export const events = { "Fetch.requestPaused": RequestPausedEvent, diff --git a/js/src/types/generated/zod/FileSystem.ts b/js/src/types/generated/zod/FileSystem.ts index 9e15cc4..21403f5 100644 --- a/js/src/types/generated/zod/FileSystem.ts +++ b/js/src/types/generated/zod/FileSystem.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Network from "./Network.js"; import * as Storage from "./Storage.js"; @@ -10,6 +10,7 @@ export const Directory = withCdpMeta(z.object({ "name": z.string(), "nestedDirec export const BucketFileSystemLocator = withCdpMeta(z.object({ "storageKey": z.lazy(() => Storage.SerializedStorageKey), "bucketName": z.string().optional(), "pathComponents": z.array(z.string()) }).passthrough(), "FileSystem.BucketFileSystemLocator", "type"); export const GetDirectoryParams = withCdpMeta(z.object({ "bucketFileSystemLocator": z.lazy(() => BucketFileSystemLocator) }).passthrough(), "FileSystem.getDirectory.params", "commandParams", { method: "FileSystem.getDirectory" }); export const GetDirectoryResult = withCdpMeta(z.object({ "directory": z.lazy(() => Directory) }).passthrough(), "FileSystem.getDirectory.result", "commandResult", { method: "FileSystem.getDirectory" }); +export const GetDirectoryCommand = withCdpCommand("FileSystem.getDirectory", GetDirectoryParams, GetDirectoryResult); export const zod = { File: File, @@ -19,7 +20,7 @@ export const zod = { GetDirectoryResult: GetDirectoryResult, } as const; export const commands = { - "FileSystem.getDirectory": { params: GetDirectoryParams, result: GetDirectoryResult }, + "FileSystem.getDirectory": GetDirectoryCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/HeadlessExperimental.ts b/js/src/types/generated/zod/HeadlessExperimental.ts index e0f017b..4fc8a99 100644 --- a/js/src/types/generated/zod/HeadlessExperimental.ts +++ b/js/src/types/generated/zod/HeadlessExperimental.ts @@ -1,15 +1,18 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const ScreenshotParams = withCdpMeta(z.object({ "format": z.enum(["jpeg", "png", "webp"]).optional(), "quality": z.number().int().optional(), "optimizeForSpeed": z.boolean().optional() }).passthrough(), "HeadlessExperimental.ScreenshotParams", "type"); export const BeginFrameParams = withCdpMeta(z.object({ "frameTimeTicks": z.number().optional(), "interval": z.number().optional(), "noDisplayUpdates": z.boolean().optional(), "screenshot": z.lazy(() => ScreenshotParams).optional() }).passthrough(), "HeadlessExperimental.beginFrame.params", "commandParams", { method: "HeadlessExperimental.beginFrame" }); export const BeginFrameResult = withCdpMeta(z.object({ "hasDamage": z.boolean(), "screenshotData": z.string().optional() }).passthrough(), "HeadlessExperimental.beginFrame.result", "commandResult", { method: "HeadlessExperimental.beginFrame" }); +export const BeginFrameCommand = withCdpCommand("HeadlessExperimental.beginFrame", BeginFrameParams, BeginFrameResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "HeadlessExperimental.disable.params", "commandParams", { method: "HeadlessExperimental.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "HeadlessExperimental.disable.result", "commandResult", { method: "HeadlessExperimental.disable" }); +export const DisableCommand = withCdpCommand("HeadlessExperimental.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "HeadlessExperimental.enable.params", "commandParams", { method: "HeadlessExperimental.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "HeadlessExperimental.enable.result", "commandResult", { method: "HeadlessExperimental.enable" }); +export const EnableCommand = withCdpCommand("HeadlessExperimental.enable", EnableParams, EnableResult); export const zod = { ScreenshotParams: ScreenshotParams, @@ -21,9 +24,9 @@ export const zod = { EnableResult: EnableResult, } as const; export const commands = { - "HeadlessExperimental.beginFrame": { params: BeginFrameParams, result: BeginFrameResult }, - "HeadlessExperimental.disable": { params: DisableParams, result: DisableResult }, - "HeadlessExperimental.enable": { params: EnableParams, result: EnableResult }, + "HeadlessExperimental.beginFrame": BeginFrameCommand, + "HeadlessExperimental.disable": DisableCommand, + "HeadlessExperimental.enable": EnableCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/HeapProfiler.ts b/js/src/types/generated/zod/HeapProfiler.ts index a88e018..027ae99 100644 --- a/js/src/types/generated/zod/HeapProfiler.ts +++ b/js/src/types/generated/zod/HeapProfiler.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Runtime from "./Runtime.js"; export const HeapSnapshotObjectId = withCdpMeta(z.string(), "HeapProfiler.HeapSnapshotObjectId", "type"); @@ -10,28 +10,40 @@ export const SamplingHeapProfileSample = withCdpMeta(z.object({ "size": z.number export const SamplingHeapProfile = withCdpMeta(z.object({ "head": z.lazy(() => SamplingHeapProfileNode), "samples": z.array(z.lazy(() => SamplingHeapProfileSample)) }).passthrough(), "HeapProfiler.SamplingHeapProfile", "type"); export const AddInspectedHeapObjectParams = withCdpMeta(z.object({ "heapObjectId": z.lazy(() => HeapSnapshotObjectId) }).passthrough(), "HeapProfiler.addInspectedHeapObject.params", "commandParams", { method: "HeapProfiler.addInspectedHeapObject" }); export const AddInspectedHeapObjectResult = withCdpMeta(z.object({ }).passthrough(), "HeapProfiler.addInspectedHeapObject.result", "commandResult", { method: "HeapProfiler.addInspectedHeapObject" }); +export const AddInspectedHeapObjectCommand = withCdpCommand("HeapProfiler.addInspectedHeapObject", AddInspectedHeapObjectParams, AddInspectedHeapObjectResult); export const CollectGarbageParams = withCdpMeta(z.object({ }).passthrough(), "HeapProfiler.collectGarbage.params", "commandParams", { method: "HeapProfiler.collectGarbage" }); export const CollectGarbageResult = withCdpMeta(z.object({ }).passthrough(), "HeapProfiler.collectGarbage.result", "commandResult", { method: "HeapProfiler.collectGarbage" }); +export const CollectGarbageCommand = withCdpCommand("HeapProfiler.collectGarbage", CollectGarbageParams, CollectGarbageResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "HeapProfiler.disable.params", "commandParams", { method: "HeapProfiler.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "HeapProfiler.disable.result", "commandResult", { method: "HeapProfiler.disable" }); +export const DisableCommand = withCdpCommand("HeapProfiler.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "HeapProfiler.enable.params", "commandParams", { method: "HeapProfiler.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "HeapProfiler.enable.result", "commandResult", { method: "HeapProfiler.enable" }); +export const EnableCommand = withCdpCommand("HeapProfiler.enable", EnableParams, EnableResult); export const GetHeapObjectIdParams = withCdpMeta(z.object({ "objectId": z.lazy(() => Runtime.RemoteObjectId) }).passthrough(), "HeapProfiler.getHeapObjectId.params", "commandParams", { method: "HeapProfiler.getHeapObjectId" }); export const GetHeapObjectIdResult = withCdpMeta(z.object({ "heapSnapshotObjectId": z.lazy(() => HeapSnapshotObjectId) }).passthrough(), "HeapProfiler.getHeapObjectId.result", "commandResult", { method: "HeapProfiler.getHeapObjectId" }); +export const GetHeapObjectIdCommand = withCdpCommand("HeapProfiler.getHeapObjectId", GetHeapObjectIdParams, GetHeapObjectIdResult); export const GetObjectByHeapObjectIdParams = withCdpMeta(z.object({ "objectId": z.lazy(() => HeapSnapshotObjectId), "objectGroup": z.string().optional() }).passthrough(), "HeapProfiler.getObjectByHeapObjectId.params", "commandParams", { method: "HeapProfiler.getObjectByHeapObjectId" }); export const GetObjectByHeapObjectIdResult = withCdpMeta(z.object({ "result": z.lazy(() => Runtime.RemoteObject) }).passthrough(), "HeapProfiler.getObjectByHeapObjectId.result", "commandResult", { method: "HeapProfiler.getObjectByHeapObjectId" }); +export const GetObjectByHeapObjectIdCommand = withCdpCommand("HeapProfiler.getObjectByHeapObjectId", GetObjectByHeapObjectIdParams, GetObjectByHeapObjectIdResult); export const GetSamplingProfileParams = withCdpMeta(z.object({ }).passthrough(), "HeapProfiler.getSamplingProfile.params", "commandParams", { method: "HeapProfiler.getSamplingProfile" }); export const GetSamplingProfileResult = withCdpMeta(z.object({ "profile": z.lazy(() => SamplingHeapProfile) }).passthrough(), "HeapProfiler.getSamplingProfile.result", "commandResult", { method: "HeapProfiler.getSamplingProfile" }); +export const GetSamplingProfileCommand = withCdpCommand("HeapProfiler.getSamplingProfile", GetSamplingProfileParams, GetSamplingProfileResult); export const StartSamplingParams = withCdpMeta(z.object({ "samplingInterval": z.number().optional(), "stackDepth": z.number().optional(), "includeObjectsCollectedByMajorGC": z.boolean().optional(), "includeObjectsCollectedByMinorGC": z.boolean().optional() }).passthrough(), "HeapProfiler.startSampling.params", "commandParams", { method: "HeapProfiler.startSampling" }); export const StartSamplingResult = withCdpMeta(z.object({ }).passthrough(), "HeapProfiler.startSampling.result", "commandResult", { method: "HeapProfiler.startSampling" }); +export const StartSamplingCommand = withCdpCommand("HeapProfiler.startSampling", StartSamplingParams, StartSamplingResult); export const StartTrackingHeapObjectsParams = withCdpMeta(z.object({ "trackAllocations": z.boolean().optional() }).passthrough(), "HeapProfiler.startTrackingHeapObjects.params", "commandParams", { method: "HeapProfiler.startTrackingHeapObjects" }); export const StartTrackingHeapObjectsResult = withCdpMeta(z.object({ }).passthrough(), "HeapProfiler.startTrackingHeapObjects.result", "commandResult", { method: "HeapProfiler.startTrackingHeapObjects" }); +export const StartTrackingHeapObjectsCommand = withCdpCommand("HeapProfiler.startTrackingHeapObjects", StartTrackingHeapObjectsParams, StartTrackingHeapObjectsResult); export const StopSamplingParams = withCdpMeta(z.object({ }).passthrough(), "HeapProfiler.stopSampling.params", "commandParams", { method: "HeapProfiler.stopSampling" }); export const StopSamplingResult = withCdpMeta(z.object({ "profile": z.lazy(() => SamplingHeapProfile) }).passthrough(), "HeapProfiler.stopSampling.result", "commandResult", { method: "HeapProfiler.stopSampling" }); +export const StopSamplingCommand = withCdpCommand("HeapProfiler.stopSampling", StopSamplingParams, StopSamplingResult); export const StopTrackingHeapObjectsParams = withCdpMeta(z.object({ "reportProgress": z.boolean().optional(), "treatGlobalObjectsAsRoots": z.boolean().optional(), "captureNumericValue": z.boolean().optional(), "exposeInternals": z.boolean().optional() }).passthrough(), "HeapProfiler.stopTrackingHeapObjects.params", "commandParams", { method: "HeapProfiler.stopTrackingHeapObjects" }); export const StopTrackingHeapObjectsResult = withCdpMeta(z.object({ }).passthrough(), "HeapProfiler.stopTrackingHeapObjects.result", "commandResult", { method: "HeapProfiler.stopTrackingHeapObjects" }); +export const StopTrackingHeapObjectsCommand = withCdpCommand("HeapProfiler.stopTrackingHeapObjects", StopTrackingHeapObjectsParams, StopTrackingHeapObjectsResult); export const TakeHeapSnapshotParams = withCdpMeta(z.object({ "reportProgress": z.boolean().optional(), "treatGlobalObjectsAsRoots": z.boolean().optional(), "captureNumericValue": z.boolean().optional(), "exposeInternals": z.boolean().optional() }).passthrough(), "HeapProfiler.takeHeapSnapshot.params", "commandParams", { method: "HeapProfiler.takeHeapSnapshot" }); export const TakeHeapSnapshotResult = withCdpMeta(z.object({ }).passthrough(), "HeapProfiler.takeHeapSnapshot.result", "commandResult", { method: "HeapProfiler.takeHeapSnapshot" }); +export const TakeHeapSnapshotCommand = withCdpCommand("HeapProfiler.takeHeapSnapshot", TakeHeapSnapshotParams, TakeHeapSnapshotResult); export const AddHeapSnapshotChunkEvent = withCdpMeta(z.object({ "chunk": z.string() }).passthrough(), "HeapProfiler.addHeapSnapshotChunk", "event", { phase: "event" }); export const HeapStatsUpdateEvent = withCdpMeta(z.object({ "statsUpdate": z.array(z.number().int()) }).passthrough(), "HeapProfiler.heapStatsUpdate", "event", { phase: "event" }); export const LastSeenObjectIdEvent = withCdpMeta(z.object({ "lastSeenObjectId": z.number().int(), "timestamp": z.number() }).passthrough(), "HeapProfiler.lastSeenObjectId", "event", { phase: "event" }); @@ -74,18 +86,18 @@ export const zod = { ResetProfilesEvent: ResetProfilesEvent, } as const; export const commands = { - "HeapProfiler.addInspectedHeapObject": { params: AddInspectedHeapObjectParams, result: AddInspectedHeapObjectResult }, - "HeapProfiler.collectGarbage": { params: CollectGarbageParams, result: CollectGarbageResult }, - "HeapProfiler.disable": { params: DisableParams, result: DisableResult }, - "HeapProfiler.enable": { params: EnableParams, result: EnableResult }, - "HeapProfiler.getHeapObjectId": { params: GetHeapObjectIdParams, result: GetHeapObjectIdResult }, - "HeapProfiler.getObjectByHeapObjectId": { params: GetObjectByHeapObjectIdParams, result: GetObjectByHeapObjectIdResult }, - "HeapProfiler.getSamplingProfile": { params: GetSamplingProfileParams, result: GetSamplingProfileResult }, - "HeapProfiler.startSampling": { params: StartSamplingParams, result: StartSamplingResult }, - "HeapProfiler.startTrackingHeapObjects": { params: StartTrackingHeapObjectsParams, result: StartTrackingHeapObjectsResult }, - "HeapProfiler.stopSampling": { params: StopSamplingParams, result: StopSamplingResult }, - "HeapProfiler.stopTrackingHeapObjects": { params: StopTrackingHeapObjectsParams, result: StopTrackingHeapObjectsResult }, - "HeapProfiler.takeHeapSnapshot": { params: TakeHeapSnapshotParams, result: TakeHeapSnapshotResult }, + "HeapProfiler.addInspectedHeapObject": AddInspectedHeapObjectCommand, + "HeapProfiler.collectGarbage": CollectGarbageCommand, + "HeapProfiler.disable": DisableCommand, + "HeapProfiler.enable": EnableCommand, + "HeapProfiler.getHeapObjectId": GetHeapObjectIdCommand, + "HeapProfiler.getObjectByHeapObjectId": GetObjectByHeapObjectIdCommand, + "HeapProfiler.getSamplingProfile": GetSamplingProfileCommand, + "HeapProfiler.startSampling": StartSamplingCommand, + "HeapProfiler.startTrackingHeapObjects": StartTrackingHeapObjectsCommand, + "HeapProfiler.stopSampling": StopSamplingCommand, + "HeapProfiler.stopTrackingHeapObjects": StopTrackingHeapObjectsCommand, + "HeapProfiler.takeHeapSnapshot": TakeHeapSnapshotCommand, } as const; export const events = { "HeapProfiler.addHeapSnapshotChunk": AddHeapSnapshotChunkEvent, diff --git a/js/src/types/generated/zod/IO.ts b/js/src/types/generated/zod/IO.ts index 90b40e1..48b25ed 100644 --- a/js/src/types/generated/zod/IO.ts +++ b/js/src/types/generated/zod/IO.ts @@ -1,16 +1,19 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Runtime from "./Runtime.js"; export const StreamHandle = withCdpMeta(z.string(), "IO.StreamHandle", "type"); export const CloseParams = withCdpMeta(z.object({ "handle": z.lazy(() => StreamHandle) }).passthrough(), "IO.close.params", "commandParams", { method: "IO.close" }); export const CloseResult = withCdpMeta(z.object({ }).passthrough(), "IO.close.result", "commandResult", { method: "IO.close" }); +export const CloseCommand = withCdpCommand("IO.close", CloseParams, CloseResult); export const ReadParams = withCdpMeta(z.object({ "handle": z.lazy(() => StreamHandle), "offset": z.number().int().optional(), "size": z.number().int().optional() }).passthrough(), "IO.read.params", "commandParams", { method: "IO.read" }); export const ReadResult = withCdpMeta(z.object({ "base64Encoded": z.boolean().optional(), "data": z.string(), "eof": z.boolean() }).passthrough(), "IO.read.result", "commandResult", { method: "IO.read" }); +export const ReadCommand = withCdpCommand("IO.read", ReadParams, ReadResult); export const ResolveBlobParams = withCdpMeta(z.object({ "objectId": z.lazy(() => Runtime.RemoteObjectId) }).passthrough(), "IO.resolveBlob.params", "commandParams", { method: "IO.resolveBlob" }); export const ResolveBlobResult = withCdpMeta(z.object({ "uuid": z.string() }).passthrough(), "IO.resolveBlob.result", "commandResult", { method: "IO.resolveBlob" }); +export const ResolveBlobCommand = withCdpCommand("IO.resolveBlob", ResolveBlobParams, ResolveBlobResult); export const zod = { StreamHandle: StreamHandle, @@ -22,9 +25,9 @@ export const zod = { ResolveBlobResult: ResolveBlobResult, } as const; export const commands = { - "IO.close": { params: CloseParams, result: CloseResult }, - "IO.read": { params: ReadParams, result: ReadResult }, - "IO.resolveBlob": { params: ResolveBlobParams, result: ResolveBlobResult }, + "IO.close": CloseCommand, + "IO.read": ReadCommand, + "IO.resolveBlob": ResolveBlobCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/IndexedDB.ts b/js/src/types/generated/zod/IndexedDB.ts index 3d484ce..877eff7 100644 --- a/js/src/types/generated/zod/IndexedDB.ts +++ b/js/src/types/generated/zod/IndexedDB.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Runtime from "./Runtime.js"; import * as Storage from "./Storage.js"; @@ -14,22 +14,31 @@ export const DataEntry = withCdpMeta(z.object({ "key": z.lazy(() => Runtime.Remo export const KeyPath = withCdpMeta(z.object({ "type": z.enum(["null", "string", "array"]), "string": z.string().optional(), "array": z.array(z.string()).optional() }).passthrough(), "IndexedDB.KeyPath", "type"); export const ClearObjectStoreParams = withCdpMeta(z.object({ "securityOrigin": z.string().optional(), "storageKey": z.string().optional(), "storageBucket": z.lazy(() => Storage.StorageBucket).optional(), "databaseName": z.string(), "objectStoreName": z.string() }).passthrough(), "IndexedDB.clearObjectStore.params", "commandParams", { method: "IndexedDB.clearObjectStore" }); export const ClearObjectStoreResult = withCdpMeta(z.object({ }).passthrough(), "IndexedDB.clearObjectStore.result", "commandResult", { method: "IndexedDB.clearObjectStore" }); +export const ClearObjectStoreCommand = withCdpCommand("IndexedDB.clearObjectStore", ClearObjectStoreParams, ClearObjectStoreResult); export const DeleteDatabaseParams = withCdpMeta(z.object({ "securityOrigin": z.string().optional(), "storageKey": z.string().optional(), "storageBucket": z.lazy(() => Storage.StorageBucket).optional(), "databaseName": z.string() }).passthrough(), "IndexedDB.deleteDatabase.params", "commandParams", { method: "IndexedDB.deleteDatabase" }); export const DeleteDatabaseResult = withCdpMeta(z.object({ }).passthrough(), "IndexedDB.deleteDatabase.result", "commandResult", { method: "IndexedDB.deleteDatabase" }); +export const DeleteDatabaseCommand = withCdpCommand("IndexedDB.deleteDatabase", DeleteDatabaseParams, DeleteDatabaseResult); export const DeleteObjectStoreEntriesParams = withCdpMeta(z.object({ "securityOrigin": z.string().optional(), "storageKey": z.string().optional(), "storageBucket": z.lazy(() => Storage.StorageBucket).optional(), "databaseName": z.string(), "objectStoreName": z.string(), "keyRange": z.lazy(() => KeyRange) }).passthrough(), "IndexedDB.deleteObjectStoreEntries.params", "commandParams", { method: "IndexedDB.deleteObjectStoreEntries" }); export const DeleteObjectStoreEntriesResult = withCdpMeta(z.object({ }).passthrough(), "IndexedDB.deleteObjectStoreEntries.result", "commandResult", { method: "IndexedDB.deleteObjectStoreEntries" }); +export const DeleteObjectStoreEntriesCommand = withCdpCommand("IndexedDB.deleteObjectStoreEntries", DeleteObjectStoreEntriesParams, DeleteObjectStoreEntriesResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "IndexedDB.disable.params", "commandParams", { method: "IndexedDB.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "IndexedDB.disable.result", "commandResult", { method: "IndexedDB.disable" }); +export const DisableCommand = withCdpCommand("IndexedDB.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "IndexedDB.enable.params", "commandParams", { method: "IndexedDB.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "IndexedDB.enable.result", "commandResult", { method: "IndexedDB.enable" }); +export const EnableCommand = withCdpCommand("IndexedDB.enable", EnableParams, EnableResult); export const RequestDataParams = withCdpMeta(z.object({ "securityOrigin": z.string().optional(), "storageKey": z.string().optional(), "storageBucket": z.lazy(() => Storage.StorageBucket).optional(), "databaseName": z.string(), "objectStoreName": z.string(), "indexName": z.string().optional(), "skipCount": z.number().int(), "pageSize": z.number().int(), "keyRange": z.lazy(() => KeyRange).optional() }).passthrough(), "IndexedDB.requestData.params", "commandParams", { method: "IndexedDB.requestData" }); export const RequestDataResult = withCdpMeta(z.object({ "objectStoreDataEntries": z.array(z.lazy(() => DataEntry)), "hasMore": z.boolean() }).passthrough(), "IndexedDB.requestData.result", "commandResult", { method: "IndexedDB.requestData" }); +export const RequestDataCommand = withCdpCommand("IndexedDB.requestData", RequestDataParams, RequestDataResult); export const GetMetadataParams = withCdpMeta(z.object({ "securityOrigin": z.string().optional(), "storageKey": z.string().optional(), "storageBucket": z.lazy(() => Storage.StorageBucket).optional(), "databaseName": z.string(), "objectStoreName": z.string() }).passthrough(), "IndexedDB.getMetadata.params", "commandParams", { method: "IndexedDB.getMetadata" }); export const GetMetadataResult = withCdpMeta(z.object({ "entriesCount": z.number(), "keyGeneratorValue": z.number() }).passthrough(), "IndexedDB.getMetadata.result", "commandResult", { method: "IndexedDB.getMetadata" }); +export const GetMetadataCommand = withCdpCommand("IndexedDB.getMetadata", GetMetadataParams, GetMetadataResult); export const RequestDatabaseParams = withCdpMeta(z.object({ "securityOrigin": z.string().optional(), "storageKey": z.string().optional(), "storageBucket": z.lazy(() => Storage.StorageBucket).optional(), "databaseName": z.string() }).passthrough(), "IndexedDB.requestDatabase.params", "commandParams", { method: "IndexedDB.requestDatabase" }); export const RequestDatabaseResult = withCdpMeta(z.object({ "databaseWithObjectStores": z.lazy(() => DatabaseWithObjectStores) }).passthrough(), "IndexedDB.requestDatabase.result", "commandResult", { method: "IndexedDB.requestDatabase" }); +export const RequestDatabaseCommand = withCdpCommand("IndexedDB.requestDatabase", RequestDatabaseParams, RequestDatabaseResult); export const RequestDatabaseNamesParams = withCdpMeta(z.object({ "securityOrigin": z.string().optional(), "storageKey": z.string().optional(), "storageBucket": z.lazy(() => Storage.StorageBucket).optional() }).passthrough(), "IndexedDB.requestDatabaseNames.params", "commandParams", { method: "IndexedDB.requestDatabaseNames" }); export const RequestDatabaseNamesResult = withCdpMeta(z.object({ "databaseNames": z.array(z.string()) }).passthrough(), "IndexedDB.requestDatabaseNames.result", "commandResult", { method: "IndexedDB.requestDatabaseNames" }); +export const RequestDatabaseNamesCommand = withCdpCommand("IndexedDB.requestDatabaseNames", RequestDatabaseNamesParams, RequestDatabaseNamesResult); export const zod = { DatabaseWithObjectStores: DatabaseWithObjectStores, @@ -59,15 +68,15 @@ export const zod = { RequestDatabaseNamesResult: RequestDatabaseNamesResult, } as const; export const commands = { - "IndexedDB.clearObjectStore": { params: ClearObjectStoreParams, result: ClearObjectStoreResult }, - "IndexedDB.deleteDatabase": { params: DeleteDatabaseParams, result: DeleteDatabaseResult }, - "IndexedDB.deleteObjectStoreEntries": { params: DeleteObjectStoreEntriesParams, result: DeleteObjectStoreEntriesResult }, - "IndexedDB.disable": { params: DisableParams, result: DisableResult }, - "IndexedDB.enable": { params: EnableParams, result: EnableResult }, - "IndexedDB.requestData": { params: RequestDataParams, result: RequestDataResult }, - "IndexedDB.getMetadata": { params: GetMetadataParams, result: GetMetadataResult }, - "IndexedDB.requestDatabase": { params: RequestDatabaseParams, result: RequestDatabaseResult }, - "IndexedDB.requestDatabaseNames": { params: RequestDatabaseNamesParams, result: RequestDatabaseNamesResult }, + "IndexedDB.clearObjectStore": ClearObjectStoreCommand, + "IndexedDB.deleteDatabase": DeleteDatabaseCommand, + "IndexedDB.deleteObjectStoreEntries": DeleteObjectStoreEntriesCommand, + "IndexedDB.disable": DisableCommand, + "IndexedDB.enable": EnableCommand, + "IndexedDB.requestData": RequestDataCommand, + "IndexedDB.getMetadata": GetMetadataCommand, + "IndexedDB.requestDatabase": RequestDatabaseCommand, + "IndexedDB.requestDatabaseNames": RequestDatabaseNamesCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/Input.ts b/js/src/types/generated/zod/Input.ts index e751355..ec1174d 100644 --- a/js/src/types/generated/zod/Input.ts +++ b/js/src/types/generated/zod/Input.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const TouchPoint = withCdpMeta(z.object({ "x": z.number(), "y": z.number(), "radiusX": z.number().optional(), "radiusY": z.number().optional(), "rotationAngle": z.number().optional(), "force": z.number().optional(), "tangentialPressure": z.number().optional(), "tiltX": z.number().optional(), "tiltY": z.number().optional(), "twist": z.number().int().optional(), "id": z.number().optional() }).passthrough(), "Input.TouchPoint", "type"); export const GestureSourceType = withCdpMeta(z.enum(["default", "touch", "mouse"]), "Input.GestureSourceType", "type"); @@ -11,30 +11,43 @@ export const DragDataItem = withCdpMeta(z.object({ "mimeType": z.string(), "data export const DragData = withCdpMeta(z.object({ "items": z.array(z.lazy(() => DragDataItem)), "files": z.array(z.string()).optional(), "dragOperationsMask": z.number().int() }).passthrough(), "Input.DragData", "type"); export const DispatchDragEventParams = withCdpMeta(z.object({ "type": z.enum(["dragEnter", "dragOver", "drop", "dragCancel"]), "x": z.number(), "y": z.number(), "data": z.lazy(() => DragData), "modifiers": z.number().int().optional() }).passthrough(), "Input.dispatchDragEvent.params", "commandParams", { method: "Input.dispatchDragEvent" }); export const DispatchDragEventResult = withCdpMeta(z.object({ }).passthrough(), "Input.dispatchDragEvent.result", "commandResult", { method: "Input.dispatchDragEvent" }); +export const DispatchDragEventCommand = withCdpCommand("Input.dispatchDragEvent", DispatchDragEventParams, DispatchDragEventResult); export const DispatchKeyEventParams = withCdpMeta(z.object({ "type": z.enum(["keyDown", "keyUp", "rawKeyDown", "char"]), "modifiers": z.number().int().optional(), "timestamp": z.lazy(() => TimeSinceEpoch).optional(), "text": z.string().optional(), "unmodifiedText": z.string().optional(), "keyIdentifier": z.string().optional(), "code": z.string().optional(), "key": z.string().optional(), "windowsVirtualKeyCode": z.number().int().optional(), "nativeVirtualKeyCode": z.number().int().optional(), "autoRepeat": z.boolean().optional(), "isKeypad": z.boolean().optional(), "isSystemKey": z.boolean().optional(), "location": z.number().int().optional(), "commands": z.array(z.string()).optional() }).passthrough(), "Input.dispatchKeyEvent.params", "commandParams", { method: "Input.dispatchKeyEvent" }); export const DispatchKeyEventResult = withCdpMeta(z.object({ }).passthrough(), "Input.dispatchKeyEvent.result", "commandResult", { method: "Input.dispatchKeyEvent" }); +export const DispatchKeyEventCommand = withCdpCommand("Input.dispatchKeyEvent", DispatchKeyEventParams, DispatchKeyEventResult); export const InsertTextParams = withCdpMeta(z.object({ "text": z.string() }).passthrough(), "Input.insertText.params", "commandParams", { method: "Input.insertText" }); export const InsertTextResult = withCdpMeta(z.object({ }).passthrough(), "Input.insertText.result", "commandResult", { method: "Input.insertText" }); +export const InsertTextCommand = withCdpCommand("Input.insertText", InsertTextParams, InsertTextResult); export const ImeSetCompositionParams = withCdpMeta(z.object({ "text": z.string(), "selectionStart": z.number().int(), "selectionEnd": z.number().int(), "replacementStart": z.number().int().optional(), "replacementEnd": z.number().int().optional() }).passthrough(), "Input.imeSetComposition.params", "commandParams", { method: "Input.imeSetComposition" }); export const ImeSetCompositionResult = withCdpMeta(z.object({ }).passthrough(), "Input.imeSetComposition.result", "commandResult", { method: "Input.imeSetComposition" }); +export const ImeSetCompositionCommand = withCdpCommand("Input.imeSetComposition", ImeSetCompositionParams, ImeSetCompositionResult); export const DispatchMouseEventParams = withCdpMeta(z.object({ "type": z.enum(["mousePressed", "mouseReleased", "mouseMoved", "mouseWheel"]), "x": z.number(), "y": z.number(), "modifiers": z.number().int().optional(), "timestamp": z.lazy(() => TimeSinceEpoch).optional(), "button": z.lazy(() => MouseButton).optional(), "buttons": z.number().int().optional(), "clickCount": z.number().int().optional(), "force": z.number().optional(), "tangentialPressure": z.number().optional(), "tiltX": z.number().optional(), "tiltY": z.number().optional(), "twist": z.number().int().optional(), "deltaX": z.number().optional(), "deltaY": z.number().optional(), "pointerType": z.enum(["mouse", "pen"]).optional() }).passthrough(), "Input.dispatchMouseEvent.params", "commandParams", { method: "Input.dispatchMouseEvent" }); export const DispatchMouseEventResult = withCdpMeta(z.object({ }).passthrough(), "Input.dispatchMouseEvent.result", "commandResult", { method: "Input.dispatchMouseEvent" }); +export const DispatchMouseEventCommand = withCdpCommand("Input.dispatchMouseEvent", DispatchMouseEventParams, DispatchMouseEventResult); export const DispatchTouchEventParams = withCdpMeta(z.object({ "type": z.enum(["touchStart", "touchEnd", "touchMove", "touchCancel"]), "touchPoints": z.array(z.lazy(() => TouchPoint)), "modifiers": z.number().int().optional(), "timestamp": z.lazy(() => TimeSinceEpoch).optional() }).passthrough(), "Input.dispatchTouchEvent.params", "commandParams", { method: "Input.dispatchTouchEvent" }); export const DispatchTouchEventResult = withCdpMeta(z.object({ }).passthrough(), "Input.dispatchTouchEvent.result", "commandResult", { method: "Input.dispatchTouchEvent" }); +export const DispatchTouchEventCommand = withCdpCommand("Input.dispatchTouchEvent", DispatchTouchEventParams, DispatchTouchEventResult); export const CancelDraggingParams = withCdpMeta(z.object({ }).passthrough(), "Input.cancelDragging.params", "commandParams", { method: "Input.cancelDragging" }); export const CancelDraggingResult = withCdpMeta(z.object({ }).passthrough(), "Input.cancelDragging.result", "commandResult", { method: "Input.cancelDragging" }); +export const CancelDraggingCommand = withCdpCommand("Input.cancelDragging", CancelDraggingParams, CancelDraggingResult); export const EmulateTouchFromMouseEventParams = withCdpMeta(z.object({ "type": z.enum(["mousePressed", "mouseReleased", "mouseMoved", "mouseWheel"]), "x": z.number().int(), "y": z.number().int(), "button": z.lazy(() => MouseButton), "timestamp": z.lazy(() => TimeSinceEpoch).optional(), "deltaX": z.number().optional(), "deltaY": z.number().optional(), "modifiers": z.number().int().optional(), "clickCount": z.number().int().optional() }).passthrough(), "Input.emulateTouchFromMouseEvent.params", "commandParams", { method: "Input.emulateTouchFromMouseEvent" }); export const EmulateTouchFromMouseEventResult = withCdpMeta(z.object({ }).passthrough(), "Input.emulateTouchFromMouseEvent.result", "commandResult", { method: "Input.emulateTouchFromMouseEvent" }); +export const EmulateTouchFromMouseEventCommand = withCdpCommand("Input.emulateTouchFromMouseEvent", EmulateTouchFromMouseEventParams, EmulateTouchFromMouseEventResult); export const SetIgnoreInputEventsParams = withCdpMeta(z.object({ "ignore": z.boolean() }).passthrough(), "Input.setIgnoreInputEvents.params", "commandParams", { method: "Input.setIgnoreInputEvents" }); export const SetIgnoreInputEventsResult = withCdpMeta(z.object({ }).passthrough(), "Input.setIgnoreInputEvents.result", "commandResult", { method: "Input.setIgnoreInputEvents" }); +export const SetIgnoreInputEventsCommand = withCdpCommand("Input.setIgnoreInputEvents", SetIgnoreInputEventsParams, SetIgnoreInputEventsResult); export const SetInterceptDragsParams = withCdpMeta(z.object({ "enabled": z.boolean() }).passthrough(), "Input.setInterceptDrags.params", "commandParams", { method: "Input.setInterceptDrags" }); export const SetInterceptDragsResult = withCdpMeta(z.object({ }).passthrough(), "Input.setInterceptDrags.result", "commandResult", { method: "Input.setInterceptDrags" }); +export const SetInterceptDragsCommand = withCdpCommand("Input.setInterceptDrags", SetInterceptDragsParams, SetInterceptDragsResult); export const SynthesizePinchGestureParams = withCdpMeta(z.object({ "x": z.number(), "y": z.number(), "scaleFactor": z.number(), "relativeSpeed": z.number().int().optional(), "gestureSourceType": z.lazy(() => GestureSourceType).optional() }).passthrough(), "Input.synthesizePinchGesture.params", "commandParams", { method: "Input.synthesizePinchGesture" }); export const SynthesizePinchGestureResult = withCdpMeta(z.object({ }).passthrough(), "Input.synthesizePinchGesture.result", "commandResult", { method: "Input.synthesizePinchGesture" }); +export const SynthesizePinchGestureCommand = withCdpCommand("Input.synthesizePinchGesture", SynthesizePinchGestureParams, SynthesizePinchGestureResult); export const SynthesizeScrollGestureParams = withCdpMeta(z.object({ "x": z.number(), "y": z.number(), "xDistance": z.number().optional(), "yDistance": z.number().optional(), "xOverscroll": z.number().optional(), "yOverscroll": z.number().optional(), "preventFling": z.boolean().optional(), "speed": z.number().int().optional(), "gestureSourceType": z.lazy(() => GestureSourceType).optional(), "repeatCount": z.number().int().optional(), "repeatDelayMs": z.number().int().optional(), "interactionMarkerName": z.string().optional() }).passthrough(), "Input.synthesizeScrollGesture.params", "commandParams", { method: "Input.synthesizeScrollGesture" }); export const SynthesizeScrollGestureResult = withCdpMeta(z.object({ }).passthrough(), "Input.synthesizeScrollGesture.result", "commandResult", { method: "Input.synthesizeScrollGesture" }); +export const SynthesizeScrollGestureCommand = withCdpCommand("Input.synthesizeScrollGesture", SynthesizeScrollGestureParams, SynthesizeScrollGestureResult); export const SynthesizeTapGestureParams = withCdpMeta(z.object({ "x": z.number(), "y": z.number(), "duration": z.number().int().optional(), "tapCount": z.number().int().optional(), "gestureSourceType": z.lazy(() => GestureSourceType).optional() }).passthrough(), "Input.synthesizeTapGesture.params", "commandParams", { method: "Input.synthesizeTapGesture" }); export const SynthesizeTapGestureResult = withCdpMeta(z.object({ }).passthrough(), "Input.synthesizeTapGesture.result", "commandResult", { method: "Input.synthesizeTapGesture" }); +export const SynthesizeTapGestureCommand = withCdpCommand("Input.synthesizeTapGesture", SynthesizeTapGestureParams, SynthesizeTapGestureResult); export const DragInterceptedEvent = withCdpMeta(z.object({ "data": z.lazy(() => DragData) }).passthrough(), "Input.dragIntercepted", "event", { phase: "event" }); export const zod = { @@ -73,19 +86,19 @@ export const zod = { DragInterceptedEvent: DragInterceptedEvent, } as const; export const commands = { - "Input.dispatchDragEvent": { params: DispatchDragEventParams, result: DispatchDragEventResult }, - "Input.dispatchKeyEvent": { params: DispatchKeyEventParams, result: DispatchKeyEventResult }, - "Input.insertText": { params: InsertTextParams, result: InsertTextResult }, - "Input.imeSetComposition": { params: ImeSetCompositionParams, result: ImeSetCompositionResult }, - "Input.dispatchMouseEvent": { params: DispatchMouseEventParams, result: DispatchMouseEventResult }, - "Input.dispatchTouchEvent": { params: DispatchTouchEventParams, result: DispatchTouchEventResult }, - "Input.cancelDragging": { params: CancelDraggingParams, result: CancelDraggingResult }, - "Input.emulateTouchFromMouseEvent": { params: EmulateTouchFromMouseEventParams, result: EmulateTouchFromMouseEventResult }, - "Input.setIgnoreInputEvents": { params: SetIgnoreInputEventsParams, result: SetIgnoreInputEventsResult }, - "Input.setInterceptDrags": { params: SetInterceptDragsParams, result: SetInterceptDragsResult }, - "Input.synthesizePinchGesture": { params: SynthesizePinchGestureParams, result: SynthesizePinchGestureResult }, - "Input.synthesizeScrollGesture": { params: SynthesizeScrollGestureParams, result: SynthesizeScrollGestureResult }, - "Input.synthesizeTapGesture": { params: SynthesizeTapGestureParams, result: SynthesizeTapGestureResult }, + "Input.dispatchDragEvent": DispatchDragEventCommand, + "Input.dispatchKeyEvent": DispatchKeyEventCommand, + "Input.insertText": InsertTextCommand, + "Input.imeSetComposition": ImeSetCompositionCommand, + "Input.dispatchMouseEvent": DispatchMouseEventCommand, + "Input.dispatchTouchEvent": DispatchTouchEventCommand, + "Input.cancelDragging": CancelDraggingCommand, + "Input.emulateTouchFromMouseEvent": EmulateTouchFromMouseEventCommand, + "Input.setIgnoreInputEvents": SetIgnoreInputEventsCommand, + "Input.setInterceptDrags": SetInterceptDragsCommand, + "Input.synthesizePinchGesture": SynthesizePinchGestureCommand, + "Input.synthesizeScrollGesture": SynthesizeScrollGestureCommand, + "Input.synthesizeTapGesture": SynthesizeTapGestureCommand, } as const; export const events = { "Input.dragIntercepted": DragInterceptedEvent, diff --git a/js/src/types/generated/zod/Inspector.ts b/js/src/types/generated/zod/Inspector.ts index 821520e..0e5dbed 100644 --- a/js/src/types/generated/zod/Inspector.ts +++ b/js/src/types/generated/zod/Inspector.ts @@ -1,12 +1,14 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Inspector.disable.params", "commandParams", { method: "Inspector.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Inspector.disable.result", "commandResult", { method: "Inspector.disable" }); +export const DisableCommand = withCdpCommand("Inspector.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "Inspector.enable.params", "commandParams", { method: "Inspector.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Inspector.enable.result", "commandResult", { method: "Inspector.enable" }); +export const EnableCommand = withCdpCommand("Inspector.enable", EnableParams, EnableResult); export const DetachedEvent = withCdpMeta(z.object({ "reason": z.string() }).passthrough(), "Inspector.detached", "event", { phase: "event" }); export const TargetCrashedEvent = withCdpMeta(z.object({ }).passthrough(), "Inspector.targetCrashed", "event", { phase: "event" }); export const TargetReloadedAfterCrashEvent = withCdpMeta(z.object({ }).passthrough(), "Inspector.targetReloadedAfterCrash", "event", { phase: "event" }); @@ -23,8 +25,8 @@ export const zod = { WorkerScriptLoadedEvent: WorkerScriptLoadedEvent, } as const; export const commands = { - "Inspector.disable": { params: DisableParams, result: DisableResult }, - "Inspector.enable": { params: EnableParams, result: EnableResult }, + "Inspector.disable": DisableCommand, + "Inspector.enable": EnableCommand, } as const; export const events = { "Inspector.detached": DetachedEvent, diff --git a/js/src/types/generated/zod/LayerTree.ts b/js/src/types/generated/zod/LayerTree.ts index 4bd592c..a748807 100644 --- a/js/src/types/generated/zod/LayerTree.ts +++ b/js/src/types/generated/zod/LayerTree.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; export const LayerId = withCdpMeta(z.string(), "LayerTree.LayerId", "type"); @@ -13,22 +13,31 @@ export const Layer = withCdpMeta(z.object({ "layerId": z.lazy(() => LayerId), "p export const PaintProfile = withCdpMeta(z.array(z.number()), "LayerTree.PaintProfile", "type"); export const CompositingReasonsParams = withCdpMeta(z.object({ "layerId": z.lazy(() => LayerId) }).passthrough(), "LayerTree.compositingReasons.params", "commandParams", { method: "LayerTree.compositingReasons" }); export const CompositingReasonsResult = withCdpMeta(z.object({ "compositingReasons": z.array(z.string()), "compositingReasonIds": z.array(z.string()) }).passthrough(), "LayerTree.compositingReasons.result", "commandResult", { method: "LayerTree.compositingReasons" }); +export const CompositingReasonsCommand = withCdpCommand("LayerTree.compositingReasons", CompositingReasonsParams, CompositingReasonsResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "LayerTree.disable.params", "commandParams", { method: "LayerTree.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "LayerTree.disable.result", "commandResult", { method: "LayerTree.disable" }); +export const DisableCommand = withCdpCommand("LayerTree.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "LayerTree.enable.params", "commandParams", { method: "LayerTree.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "LayerTree.enable.result", "commandResult", { method: "LayerTree.enable" }); +export const EnableCommand = withCdpCommand("LayerTree.enable", EnableParams, EnableResult); export const LoadSnapshotParams = withCdpMeta(z.object({ "tiles": z.array(z.lazy(() => PictureTile)) }).passthrough(), "LayerTree.loadSnapshot.params", "commandParams", { method: "LayerTree.loadSnapshot" }); export const LoadSnapshotResult = withCdpMeta(z.object({ "snapshotId": z.lazy(() => SnapshotId) }).passthrough(), "LayerTree.loadSnapshot.result", "commandResult", { method: "LayerTree.loadSnapshot" }); +export const LoadSnapshotCommand = withCdpCommand("LayerTree.loadSnapshot", LoadSnapshotParams, LoadSnapshotResult); export const MakeSnapshotParams = withCdpMeta(z.object({ "layerId": z.lazy(() => LayerId) }).passthrough(), "LayerTree.makeSnapshot.params", "commandParams", { method: "LayerTree.makeSnapshot" }); export const MakeSnapshotResult = withCdpMeta(z.object({ "snapshotId": z.lazy(() => SnapshotId) }).passthrough(), "LayerTree.makeSnapshot.result", "commandResult", { method: "LayerTree.makeSnapshot" }); +export const MakeSnapshotCommand = withCdpCommand("LayerTree.makeSnapshot", MakeSnapshotParams, MakeSnapshotResult); export const ProfileSnapshotParams = withCdpMeta(z.object({ "snapshotId": z.lazy(() => SnapshotId), "minRepeatCount": z.number().int().optional(), "minDuration": z.number().optional(), "clipRect": z.lazy(() => DOM.Rect).optional() }).passthrough(), "LayerTree.profileSnapshot.params", "commandParams", { method: "LayerTree.profileSnapshot" }); export const ProfileSnapshotResult = withCdpMeta(z.object({ "timings": z.array(z.lazy(() => PaintProfile)) }).passthrough(), "LayerTree.profileSnapshot.result", "commandResult", { method: "LayerTree.profileSnapshot" }); +export const ProfileSnapshotCommand = withCdpCommand("LayerTree.profileSnapshot", ProfileSnapshotParams, ProfileSnapshotResult); export const ReleaseSnapshotParams = withCdpMeta(z.object({ "snapshotId": z.lazy(() => SnapshotId) }).passthrough(), "LayerTree.releaseSnapshot.params", "commandParams", { method: "LayerTree.releaseSnapshot" }); export const ReleaseSnapshotResult = withCdpMeta(z.object({ }).passthrough(), "LayerTree.releaseSnapshot.result", "commandResult", { method: "LayerTree.releaseSnapshot" }); +export const ReleaseSnapshotCommand = withCdpCommand("LayerTree.releaseSnapshot", ReleaseSnapshotParams, ReleaseSnapshotResult); export const ReplaySnapshotParams = withCdpMeta(z.object({ "snapshotId": z.lazy(() => SnapshotId), "fromStep": z.number().int().optional(), "toStep": z.number().int().optional(), "scale": z.number().optional() }).passthrough(), "LayerTree.replaySnapshot.params", "commandParams", { method: "LayerTree.replaySnapshot" }); export const ReplaySnapshotResult = withCdpMeta(z.object({ "dataURL": z.string() }).passthrough(), "LayerTree.replaySnapshot.result", "commandResult", { method: "LayerTree.replaySnapshot" }); +export const ReplaySnapshotCommand = withCdpCommand("LayerTree.replaySnapshot", ReplaySnapshotParams, ReplaySnapshotResult); export const SnapshotCommandLogParams = withCdpMeta(z.object({ "snapshotId": z.lazy(() => SnapshotId) }).passthrough(), "LayerTree.snapshotCommandLog.params", "commandParams", { method: "LayerTree.snapshotCommandLog" }); export const SnapshotCommandLogResult = withCdpMeta(z.object({ "commandLog": z.array(z.record(z.string(), z.unknown())) }).passthrough(), "LayerTree.snapshotCommandLog.result", "commandResult", { method: "LayerTree.snapshotCommandLog" }); +export const SnapshotCommandLogCommand = withCdpCommand("LayerTree.snapshotCommandLog", SnapshotCommandLogParams, SnapshotCommandLogResult); export const LayerPaintedEvent = withCdpMeta(z.object({ "layerId": z.lazy(() => LayerId), "clip": z.lazy(() => DOM.Rect) }).passthrough(), "LayerTree.layerPainted", "event", { phase: "event" }); export const LayerTreeDidChangeEvent = withCdpMeta(z.object({ "layers": z.array(z.lazy(() => Layer)).optional() }).passthrough(), "LayerTree.layerTreeDidChange", "event", { phase: "event" }); @@ -62,15 +71,15 @@ export const zod = { LayerTreeDidChangeEvent: LayerTreeDidChangeEvent, } as const; export const commands = { - "LayerTree.compositingReasons": { params: CompositingReasonsParams, result: CompositingReasonsResult }, - "LayerTree.disable": { params: DisableParams, result: DisableResult }, - "LayerTree.enable": { params: EnableParams, result: EnableResult }, - "LayerTree.loadSnapshot": { params: LoadSnapshotParams, result: LoadSnapshotResult }, - "LayerTree.makeSnapshot": { params: MakeSnapshotParams, result: MakeSnapshotResult }, - "LayerTree.profileSnapshot": { params: ProfileSnapshotParams, result: ProfileSnapshotResult }, - "LayerTree.releaseSnapshot": { params: ReleaseSnapshotParams, result: ReleaseSnapshotResult }, - "LayerTree.replaySnapshot": { params: ReplaySnapshotParams, result: ReplaySnapshotResult }, - "LayerTree.snapshotCommandLog": { params: SnapshotCommandLogParams, result: SnapshotCommandLogResult }, + "LayerTree.compositingReasons": CompositingReasonsCommand, + "LayerTree.disable": DisableCommand, + "LayerTree.enable": EnableCommand, + "LayerTree.loadSnapshot": LoadSnapshotCommand, + "LayerTree.makeSnapshot": MakeSnapshotCommand, + "LayerTree.profileSnapshot": ProfileSnapshotCommand, + "LayerTree.releaseSnapshot": ReleaseSnapshotCommand, + "LayerTree.replaySnapshot": ReplaySnapshotCommand, + "LayerTree.snapshotCommandLog": SnapshotCommandLogCommand, } as const; export const events = { "LayerTree.layerPainted": LayerPaintedEvent, diff --git a/js/src/types/generated/zod/Log.ts b/js/src/types/generated/zod/Log.ts index e8131fe..ac8726e 100644 --- a/js/src/types/generated/zod/Log.ts +++ b/js/src/types/generated/zod/Log.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Network from "./Network.js"; import * as Runtime from "./Runtime.js"; @@ -9,14 +9,19 @@ export const LogEntry = withCdpMeta(z.object({ "source": z.enum(["xml", "javascr export const ViolationSetting = withCdpMeta(z.object({ "name": z.enum(["longTask", "longLayout", "blockedEvent", "blockedParser", "discouragedAPIUse", "handler", "recurringHandler"]), "threshold": z.number() }).passthrough(), "Log.ViolationSetting", "type"); export const ClearParams = withCdpMeta(z.object({ }).passthrough(), "Log.clear.params", "commandParams", { method: "Log.clear" }); export const ClearResult = withCdpMeta(z.object({ }).passthrough(), "Log.clear.result", "commandResult", { method: "Log.clear" }); +export const ClearCommand = withCdpCommand("Log.clear", ClearParams, ClearResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Log.disable.params", "commandParams", { method: "Log.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Log.disable.result", "commandResult", { method: "Log.disable" }); +export const DisableCommand = withCdpCommand("Log.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "Log.enable.params", "commandParams", { method: "Log.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Log.enable.result", "commandResult", { method: "Log.enable" }); +export const EnableCommand = withCdpCommand("Log.enable", EnableParams, EnableResult); export const StartViolationsReportParams = withCdpMeta(z.object({ "config": z.array(z.lazy(() => ViolationSetting)) }).passthrough(), "Log.startViolationsReport.params", "commandParams", { method: "Log.startViolationsReport" }); export const StartViolationsReportResult = withCdpMeta(z.object({ }).passthrough(), "Log.startViolationsReport.result", "commandResult", { method: "Log.startViolationsReport" }); +export const StartViolationsReportCommand = withCdpCommand("Log.startViolationsReport", StartViolationsReportParams, StartViolationsReportResult); export const StopViolationsReportParams = withCdpMeta(z.object({ }).passthrough(), "Log.stopViolationsReport.params", "commandParams", { method: "Log.stopViolationsReport" }); export const StopViolationsReportResult = withCdpMeta(z.object({ }).passthrough(), "Log.stopViolationsReport.result", "commandResult", { method: "Log.stopViolationsReport" }); +export const StopViolationsReportCommand = withCdpCommand("Log.stopViolationsReport", StopViolationsReportParams, StopViolationsReportResult); export const EntryAddedEvent = withCdpMeta(z.object({ "entry": z.lazy(() => LogEntry) }).passthrough(), "Log.entryAdded", "event", { phase: "event" }); export const zod = { @@ -35,11 +40,11 @@ export const zod = { EntryAddedEvent: EntryAddedEvent, } as const; export const commands = { - "Log.clear": { params: ClearParams, result: ClearResult }, - "Log.disable": { params: DisableParams, result: DisableResult }, - "Log.enable": { params: EnableParams, result: EnableResult }, - "Log.startViolationsReport": { params: StartViolationsReportParams, result: StartViolationsReportResult }, - "Log.stopViolationsReport": { params: StopViolationsReportParams, result: StopViolationsReportResult }, + "Log.clear": ClearCommand, + "Log.disable": DisableCommand, + "Log.enable": EnableCommand, + "Log.startViolationsReport": StartViolationsReportCommand, + "Log.stopViolationsReport": StopViolationsReportCommand, } as const; export const events = { "Log.entryAdded": EntryAddedEvent, diff --git a/js/src/types/generated/zod/Media.ts b/js/src/types/generated/zod/Media.ts index 05841be..d3a6a35 100644 --- a/js/src/types/generated/zod/Media.ts +++ b/js/src/types/generated/zod/Media.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; export const PlayerId = withCdpMeta(z.string(), "Media.PlayerId", "type"); @@ -14,8 +14,10 @@ export const PlayerError = withCdpMeta(z.object({ "errorType": z.string(), "code export const Player = withCdpMeta(z.object({ "playerId": z.lazy(() => PlayerId), "domNodeId": z.lazy(() => DOM.BackendNodeId).optional() }).passthrough(), "Media.Player", "type"); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "Media.enable.params", "commandParams", { method: "Media.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Media.enable.result", "commandResult", { method: "Media.enable" }); +export const EnableCommand = withCdpCommand("Media.enable", EnableParams, EnableResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Media.disable.params", "commandParams", { method: "Media.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Media.disable.result", "commandResult", { method: "Media.disable" }); +export const DisableCommand = withCdpCommand("Media.disable", DisableParams, DisableResult); export const PlayerPropertiesChangedEvent = withCdpMeta(z.object({ "playerId": z.lazy(() => PlayerId), "properties": z.array(z.lazy(() => PlayerProperty)) }).passthrough(), "Media.playerPropertiesChanged", "event", { phase: "event" }); export const PlayerEventsAddedEvent = withCdpMeta(z.object({ "playerId": z.lazy(() => PlayerId), "events": z.array(z.lazy(() => PlayerEvent)) }).passthrough(), "Media.playerEventsAdded", "event", { phase: "event" }); export const PlayerMessagesLoggedEvent = withCdpMeta(z.object({ "playerId": z.lazy(() => PlayerId), "messages": z.array(z.lazy(() => PlayerMessage)) }).passthrough(), "Media.playerMessagesLogged", "event", { phase: "event" }); @@ -42,8 +44,8 @@ export const zod = { PlayerCreatedEvent: PlayerCreatedEvent, } as const; export const commands = { - "Media.enable": { params: EnableParams, result: EnableResult }, - "Media.disable": { params: DisableParams, result: DisableResult }, + "Media.enable": EnableCommand, + "Media.disable": DisableCommand, } as const; export const events = { "Media.playerPropertiesChanged": PlayerPropertiesChangedEvent, diff --git a/js/src/types/generated/zod/Memory.ts b/js/src/types/generated/zod/Memory.ts index 8a7e097..8acb014 100644 --- a/js/src/types/generated/zod/Memory.ts +++ b/js/src/types/generated/zod/Memory.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const PressureLevel = withCdpMeta(z.enum(["moderate", "critical"]), "Memory.PressureLevel", "type"); export const SamplingProfileNode = withCdpMeta(z.object({ "size": z.number(), "total": z.number(), "stack": z.array(z.string()) }).passthrough(), "Memory.SamplingProfileNode", "type"); @@ -10,26 +10,37 @@ export const Module = withCdpMeta(z.object({ "name": z.string(), "uuid": z.strin export const DOMCounter = withCdpMeta(z.object({ "name": z.string(), "count": z.number().int() }).passthrough(), "Memory.DOMCounter", "type"); export const GetDOMCountersParams = withCdpMeta(z.object({ }).passthrough(), "Memory.getDOMCounters.params", "commandParams", { method: "Memory.getDOMCounters" }); export const GetDOMCountersResult = withCdpMeta(z.object({ "documents": z.number().int(), "nodes": z.number().int(), "jsEventListeners": z.number().int() }).passthrough(), "Memory.getDOMCounters.result", "commandResult", { method: "Memory.getDOMCounters" }); +export const GetDOMCountersCommand = withCdpCommand("Memory.getDOMCounters", GetDOMCountersParams, GetDOMCountersResult); export const GetDOMCountersForLeakDetectionParams = withCdpMeta(z.object({ }).passthrough(), "Memory.getDOMCountersForLeakDetection.params", "commandParams", { method: "Memory.getDOMCountersForLeakDetection" }); export const GetDOMCountersForLeakDetectionResult = withCdpMeta(z.object({ "counters": z.array(z.lazy(() => DOMCounter)) }).passthrough(), "Memory.getDOMCountersForLeakDetection.result", "commandResult", { method: "Memory.getDOMCountersForLeakDetection" }); +export const GetDOMCountersForLeakDetectionCommand = withCdpCommand("Memory.getDOMCountersForLeakDetection", GetDOMCountersForLeakDetectionParams, GetDOMCountersForLeakDetectionResult); export const PrepareForLeakDetectionParams = withCdpMeta(z.object({ }).passthrough(), "Memory.prepareForLeakDetection.params", "commandParams", { method: "Memory.prepareForLeakDetection" }); export const PrepareForLeakDetectionResult = withCdpMeta(z.object({ }).passthrough(), "Memory.prepareForLeakDetection.result", "commandResult", { method: "Memory.prepareForLeakDetection" }); +export const PrepareForLeakDetectionCommand = withCdpCommand("Memory.prepareForLeakDetection", PrepareForLeakDetectionParams, PrepareForLeakDetectionResult); export const ForciblyPurgeJavaScriptMemoryParams = withCdpMeta(z.object({ }).passthrough(), "Memory.forciblyPurgeJavaScriptMemory.params", "commandParams", { method: "Memory.forciblyPurgeJavaScriptMemory" }); export const ForciblyPurgeJavaScriptMemoryResult = withCdpMeta(z.object({ }).passthrough(), "Memory.forciblyPurgeJavaScriptMemory.result", "commandResult", { method: "Memory.forciblyPurgeJavaScriptMemory" }); +export const ForciblyPurgeJavaScriptMemoryCommand = withCdpCommand("Memory.forciblyPurgeJavaScriptMemory", ForciblyPurgeJavaScriptMemoryParams, ForciblyPurgeJavaScriptMemoryResult); export const SetPressureNotificationsSuppressedParams = withCdpMeta(z.object({ "suppressed": z.boolean() }).passthrough(), "Memory.setPressureNotificationsSuppressed.params", "commandParams", { method: "Memory.setPressureNotificationsSuppressed" }); export const SetPressureNotificationsSuppressedResult = withCdpMeta(z.object({ }).passthrough(), "Memory.setPressureNotificationsSuppressed.result", "commandResult", { method: "Memory.setPressureNotificationsSuppressed" }); +export const SetPressureNotificationsSuppressedCommand = withCdpCommand("Memory.setPressureNotificationsSuppressed", SetPressureNotificationsSuppressedParams, SetPressureNotificationsSuppressedResult); export const SimulatePressureNotificationParams = withCdpMeta(z.object({ "level": z.lazy(() => PressureLevel) }).passthrough(), "Memory.simulatePressureNotification.params", "commandParams", { method: "Memory.simulatePressureNotification" }); export const SimulatePressureNotificationResult = withCdpMeta(z.object({ }).passthrough(), "Memory.simulatePressureNotification.result", "commandResult", { method: "Memory.simulatePressureNotification" }); +export const SimulatePressureNotificationCommand = withCdpCommand("Memory.simulatePressureNotification", SimulatePressureNotificationParams, SimulatePressureNotificationResult); export const StartSamplingParams = withCdpMeta(z.object({ "samplingInterval": z.number().int().optional(), "suppressRandomness": z.boolean().optional() }).passthrough(), "Memory.startSampling.params", "commandParams", { method: "Memory.startSampling" }); export const StartSamplingResult = withCdpMeta(z.object({ }).passthrough(), "Memory.startSampling.result", "commandResult", { method: "Memory.startSampling" }); +export const StartSamplingCommand = withCdpCommand("Memory.startSampling", StartSamplingParams, StartSamplingResult); export const StopSamplingParams = withCdpMeta(z.object({ }).passthrough(), "Memory.stopSampling.params", "commandParams", { method: "Memory.stopSampling" }); export const StopSamplingResult = withCdpMeta(z.object({ }).passthrough(), "Memory.stopSampling.result", "commandResult", { method: "Memory.stopSampling" }); +export const StopSamplingCommand = withCdpCommand("Memory.stopSampling", StopSamplingParams, StopSamplingResult); export const GetAllTimeSamplingProfileParams = withCdpMeta(z.object({ }).passthrough(), "Memory.getAllTimeSamplingProfile.params", "commandParams", { method: "Memory.getAllTimeSamplingProfile" }); export const GetAllTimeSamplingProfileResult = withCdpMeta(z.object({ "profile": z.lazy(() => SamplingProfile) }).passthrough(), "Memory.getAllTimeSamplingProfile.result", "commandResult", { method: "Memory.getAllTimeSamplingProfile" }); +export const GetAllTimeSamplingProfileCommand = withCdpCommand("Memory.getAllTimeSamplingProfile", GetAllTimeSamplingProfileParams, GetAllTimeSamplingProfileResult); export const GetBrowserSamplingProfileParams = withCdpMeta(z.object({ }).passthrough(), "Memory.getBrowserSamplingProfile.params", "commandParams", { method: "Memory.getBrowserSamplingProfile" }); export const GetBrowserSamplingProfileResult = withCdpMeta(z.object({ "profile": z.lazy(() => SamplingProfile) }).passthrough(), "Memory.getBrowserSamplingProfile.result", "commandResult", { method: "Memory.getBrowserSamplingProfile" }); +export const GetBrowserSamplingProfileCommand = withCdpCommand("Memory.getBrowserSamplingProfile", GetBrowserSamplingProfileParams, GetBrowserSamplingProfileResult); export const GetSamplingProfileParams = withCdpMeta(z.object({ }).passthrough(), "Memory.getSamplingProfile.params", "commandParams", { method: "Memory.getSamplingProfile" }); export const GetSamplingProfileResult = withCdpMeta(z.object({ "profile": z.lazy(() => SamplingProfile) }).passthrough(), "Memory.getSamplingProfile.result", "commandResult", { method: "Memory.getSamplingProfile" }); +export const GetSamplingProfileCommand = withCdpCommand("Memory.getSamplingProfile", GetSamplingProfileParams, GetSamplingProfileResult); export const zod = { PressureLevel: PressureLevel, @@ -61,17 +72,17 @@ export const zod = { GetSamplingProfileResult: GetSamplingProfileResult, } as const; export const commands = { - "Memory.getDOMCounters": { params: GetDOMCountersParams, result: GetDOMCountersResult }, - "Memory.getDOMCountersForLeakDetection": { params: GetDOMCountersForLeakDetectionParams, result: GetDOMCountersForLeakDetectionResult }, - "Memory.prepareForLeakDetection": { params: PrepareForLeakDetectionParams, result: PrepareForLeakDetectionResult }, - "Memory.forciblyPurgeJavaScriptMemory": { params: ForciblyPurgeJavaScriptMemoryParams, result: ForciblyPurgeJavaScriptMemoryResult }, - "Memory.setPressureNotificationsSuppressed": { params: SetPressureNotificationsSuppressedParams, result: SetPressureNotificationsSuppressedResult }, - "Memory.simulatePressureNotification": { params: SimulatePressureNotificationParams, result: SimulatePressureNotificationResult }, - "Memory.startSampling": { params: StartSamplingParams, result: StartSamplingResult }, - "Memory.stopSampling": { params: StopSamplingParams, result: StopSamplingResult }, - "Memory.getAllTimeSamplingProfile": { params: GetAllTimeSamplingProfileParams, result: GetAllTimeSamplingProfileResult }, - "Memory.getBrowserSamplingProfile": { params: GetBrowserSamplingProfileParams, result: GetBrowserSamplingProfileResult }, - "Memory.getSamplingProfile": { params: GetSamplingProfileParams, result: GetSamplingProfileResult }, + "Memory.getDOMCounters": GetDOMCountersCommand, + "Memory.getDOMCountersForLeakDetection": GetDOMCountersForLeakDetectionCommand, + "Memory.prepareForLeakDetection": PrepareForLeakDetectionCommand, + "Memory.forciblyPurgeJavaScriptMemory": ForciblyPurgeJavaScriptMemoryCommand, + "Memory.setPressureNotificationsSuppressed": SetPressureNotificationsSuppressedCommand, + "Memory.simulatePressureNotification": SimulatePressureNotificationCommand, + "Memory.startSampling": StartSamplingCommand, + "Memory.stopSampling": StopSamplingCommand, + "Memory.getAllTimeSamplingProfile": GetAllTimeSamplingProfileCommand, + "Memory.getBrowserSamplingProfile": GetBrowserSamplingProfileCommand, + "Memory.getSamplingProfile": GetSamplingProfileCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/Network.ts b/js/src/types/generated/zod/Network.ts index 249626a..e9c2f87 100644 --- a/js/src/types/generated/zod/Network.ts +++ b/js/src/types/generated/zod/Network.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Debugger from "./Debugger.js"; import * as Emulation from "./Emulation.js"; import * as IO from "./IO.js"; @@ -104,86 +104,127 @@ export const LoadNetworkResourcePageResult = withCdpMeta(z.object({ "success": z export const LoadNetworkResourceOptions = withCdpMeta(z.object({ "disableCache": z.boolean(), "includeCredentials": z.boolean() }).passthrough(), "Network.LoadNetworkResourceOptions", "type"); export const SetAcceptedEncodingsParams = withCdpMeta(z.object({ "encodings": z.array(z.lazy(() => ContentEncoding)) }).passthrough(), "Network.setAcceptedEncodings.params", "commandParams", { method: "Network.setAcceptedEncodings" }); export const SetAcceptedEncodingsResult = withCdpMeta(z.object({ }).passthrough(), "Network.setAcceptedEncodings.result", "commandResult", { method: "Network.setAcceptedEncodings" }); +export const SetAcceptedEncodingsCommand = withCdpCommand("Network.setAcceptedEncodings", SetAcceptedEncodingsParams, SetAcceptedEncodingsResult); export const ClearAcceptedEncodingsOverrideParams = withCdpMeta(z.object({ }).passthrough(), "Network.clearAcceptedEncodingsOverride.params", "commandParams", { method: "Network.clearAcceptedEncodingsOverride" }); export const ClearAcceptedEncodingsOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Network.clearAcceptedEncodingsOverride.result", "commandResult", { method: "Network.clearAcceptedEncodingsOverride" }); +export const ClearAcceptedEncodingsOverrideCommand = withCdpCommand("Network.clearAcceptedEncodingsOverride", ClearAcceptedEncodingsOverrideParams, ClearAcceptedEncodingsOverrideResult); export const CanClearBrowserCacheParams = withCdpMeta(z.object({ }).passthrough(), "Network.canClearBrowserCache.params", "commandParams", { method: "Network.canClearBrowserCache" }); export const CanClearBrowserCacheResult = withCdpMeta(z.object({ "result": z.boolean() }).passthrough(), "Network.canClearBrowserCache.result", "commandResult", { method: "Network.canClearBrowserCache" }); +export const CanClearBrowserCacheCommand = withCdpCommand("Network.canClearBrowserCache", CanClearBrowserCacheParams, CanClearBrowserCacheResult); export const CanClearBrowserCookiesParams = withCdpMeta(z.object({ }).passthrough(), "Network.canClearBrowserCookies.params", "commandParams", { method: "Network.canClearBrowserCookies" }); export const CanClearBrowserCookiesResult = withCdpMeta(z.object({ "result": z.boolean() }).passthrough(), "Network.canClearBrowserCookies.result", "commandResult", { method: "Network.canClearBrowserCookies" }); +export const CanClearBrowserCookiesCommand = withCdpCommand("Network.canClearBrowserCookies", CanClearBrowserCookiesParams, CanClearBrowserCookiesResult); export const CanEmulateNetworkConditionsParams = withCdpMeta(z.object({ }).passthrough(), "Network.canEmulateNetworkConditions.params", "commandParams", { method: "Network.canEmulateNetworkConditions" }); export const CanEmulateNetworkConditionsResult = withCdpMeta(z.object({ "result": z.boolean() }).passthrough(), "Network.canEmulateNetworkConditions.result", "commandResult", { method: "Network.canEmulateNetworkConditions" }); +export const CanEmulateNetworkConditionsCommand = withCdpCommand("Network.canEmulateNetworkConditions", CanEmulateNetworkConditionsParams, CanEmulateNetworkConditionsResult); export const ClearBrowserCacheParams = withCdpMeta(z.object({ }).passthrough(), "Network.clearBrowserCache.params", "commandParams", { method: "Network.clearBrowserCache" }); export const ClearBrowserCacheResult = withCdpMeta(z.object({ }).passthrough(), "Network.clearBrowserCache.result", "commandResult", { method: "Network.clearBrowserCache" }); +export const ClearBrowserCacheCommand = withCdpCommand("Network.clearBrowserCache", ClearBrowserCacheParams, ClearBrowserCacheResult); export const ClearBrowserCookiesParams = withCdpMeta(z.object({ }).passthrough(), "Network.clearBrowserCookies.params", "commandParams", { method: "Network.clearBrowserCookies" }); export const ClearBrowserCookiesResult = withCdpMeta(z.object({ }).passthrough(), "Network.clearBrowserCookies.result", "commandResult", { method: "Network.clearBrowserCookies" }); +export const ClearBrowserCookiesCommand = withCdpCommand("Network.clearBrowserCookies", ClearBrowserCookiesParams, ClearBrowserCookiesResult); export const ContinueInterceptedRequestParams = withCdpMeta(z.object({ "interceptionId": z.lazy(() => InterceptionId), "errorReason": z.lazy(() => ErrorReason).optional(), "rawResponse": z.string().optional(), "url": z.string().optional(), "method": z.string().optional(), "postData": z.string().optional(), "headers": z.lazy(() => Headers).optional(), "authChallengeResponse": z.lazy(() => AuthChallengeResponse).optional() }).passthrough(), "Network.continueInterceptedRequest.params", "commandParams", { method: "Network.continueInterceptedRequest" }); export const ContinueInterceptedRequestResult = withCdpMeta(z.object({ }).passthrough(), "Network.continueInterceptedRequest.result", "commandResult", { method: "Network.continueInterceptedRequest" }); +export const ContinueInterceptedRequestCommand = withCdpCommand("Network.continueInterceptedRequest", ContinueInterceptedRequestParams, ContinueInterceptedRequestResult); export const DeleteCookiesParams = withCdpMeta(z.object({ "name": z.string(), "url": z.string().optional(), "domain": z.string().optional(), "path": z.string().optional(), "partitionKey": z.lazy(() => CookiePartitionKey).optional() }).passthrough(), "Network.deleteCookies.params", "commandParams", { method: "Network.deleteCookies" }); export const DeleteCookiesResult = withCdpMeta(z.object({ }).passthrough(), "Network.deleteCookies.result", "commandResult", { method: "Network.deleteCookies" }); +export const DeleteCookiesCommand = withCdpCommand("Network.deleteCookies", DeleteCookiesParams, DeleteCookiesResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Network.disable.params", "commandParams", { method: "Network.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Network.disable.result", "commandResult", { method: "Network.disable" }); +export const DisableCommand = withCdpCommand("Network.disable", DisableParams, DisableResult); export const EmulateNetworkConditionsParams = withCdpMeta(z.object({ "offline": z.boolean(), "latency": z.number(), "downloadThroughput": z.number(), "uploadThroughput": z.number(), "connectionType": z.lazy(() => ConnectionType).optional(), "packetLoss": z.number().optional(), "packetQueueLength": z.number().int().optional(), "packetReordering": z.boolean().optional() }).passthrough(), "Network.emulateNetworkConditions.params", "commandParams", { method: "Network.emulateNetworkConditions" }); export const EmulateNetworkConditionsResult = withCdpMeta(z.object({ }).passthrough(), "Network.emulateNetworkConditions.result", "commandResult", { method: "Network.emulateNetworkConditions" }); +export const EmulateNetworkConditionsCommand = withCdpCommand("Network.emulateNetworkConditions", EmulateNetworkConditionsParams, EmulateNetworkConditionsResult); export const EmulateNetworkConditionsByRuleParams = withCdpMeta(z.object({ "offline": z.boolean().optional(), "emulateOfflineServiceWorker": z.boolean().optional(), "matchedNetworkConditions": z.array(z.lazy(() => NetworkConditions)) }).passthrough(), "Network.emulateNetworkConditionsByRule.params", "commandParams", { method: "Network.emulateNetworkConditionsByRule" }); export const EmulateNetworkConditionsByRuleResult = withCdpMeta(z.object({ "ruleIds": z.array(z.string()) }).passthrough(), "Network.emulateNetworkConditionsByRule.result", "commandResult", { method: "Network.emulateNetworkConditionsByRule" }); +export const EmulateNetworkConditionsByRuleCommand = withCdpCommand("Network.emulateNetworkConditionsByRule", EmulateNetworkConditionsByRuleParams, EmulateNetworkConditionsByRuleResult); export const OverrideNetworkStateParams = withCdpMeta(z.object({ "offline": z.boolean(), "latency": z.number(), "downloadThroughput": z.number(), "uploadThroughput": z.number(), "connectionType": z.lazy(() => ConnectionType).optional() }).passthrough(), "Network.overrideNetworkState.params", "commandParams", { method: "Network.overrideNetworkState" }); export const OverrideNetworkStateResult = withCdpMeta(z.object({ }).passthrough(), "Network.overrideNetworkState.result", "commandResult", { method: "Network.overrideNetworkState" }); +export const OverrideNetworkStateCommand = withCdpCommand("Network.overrideNetworkState", OverrideNetworkStateParams, OverrideNetworkStateResult); export const EnableParams = withCdpMeta(z.object({ "maxTotalBufferSize": z.number().int().optional(), "maxResourceBufferSize": z.number().int().optional(), "maxPostDataSize": z.number().int().optional(), "reportDirectSocketTraffic": z.boolean().optional(), "enableDurableMessages": z.boolean().optional() }).passthrough(), "Network.enable.params", "commandParams", { method: "Network.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Network.enable.result", "commandResult", { method: "Network.enable" }); +export const EnableCommand = withCdpCommand("Network.enable", EnableParams, EnableResult); export const ConfigureDurableMessagesParams = withCdpMeta(z.object({ "maxTotalBufferSize": z.number().int().optional(), "maxResourceBufferSize": z.number().int().optional() }).passthrough(), "Network.configureDurableMessages.params", "commandParams", { method: "Network.configureDurableMessages" }); export const ConfigureDurableMessagesResult = withCdpMeta(z.object({ }).passthrough(), "Network.configureDurableMessages.result", "commandResult", { method: "Network.configureDurableMessages" }); +export const ConfigureDurableMessagesCommand = withCdpCommand("Network.configureDurableMessages", ConfigureDurableMessagesParams, ConfigureDurableMessagesResult); export const GetAllCookiesParams = withCdpMeta(z.object({ }).passthrough(), "Network.getAllCookies.params", "commandParams", { method: "Network.getAllCookies" }); export const GetAllCookiesResult = withCdpMeta(z.object({ "cookies": z.array(z.lazy(() => Cookie)) }).passthrough(), "Network.getAllCookies.result", "commandResult", { method: "Network.getAllCookies" }); +export const GetAllCookiesCommand = withCdpCommand("Network.getAllCookies", GetAllCookiesParams, GetAllCookiesResult); export const GetCertificateParams = withCdpMeta(z.object({ "origin": z.string() }).passthrough(), "Network.getCertificate.params", "commandParams", { method: "Network.getCertificate" }); export const GetCertificateResult = withCdpMeta(z.object({ "tableNames": z.array(z.string()) }).passthrough(), "Network.getCertificate.result", "commandResult", { method: "Network.getCertificate" }); +export const GetCertificateCommand = withCdpCommand("Network.getCertificate", GetCertificateParams, GetCertificateResult); export const GetCookiesParams = withCdpMeta(z.object({ "urls": z.array(z.string()).optional() }).passthrough(), "Network.getCookies.params", "commandParams", { method: "Network.getCookies" }); export const GetCookiesResult = withCdpMeta(z.object({ "cookies": z.array(z.lazy(() => Cookie)) }).passthrough(), "Network.getCookies.result", "commandResult", { method: "Network.getCookies" }); +export const GetCookiesCommand = withCdpCommand("Network.getCookies", GetCookiesParams, GetCookiesResult); export const GetResponseBodyParams = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId) }).passthrough(), "Network.getResponseBody.params", "commandParams", { method: "Network.getResponseBody" }); export const GetResponseBodyResult = withCdpMeta(z.object({ "body": z.string(), "base64Encoded": z.boolean() }).passthrough(), "Network.getResponseBody.result", "commandResult", { method: "Network.getResponseBody" }); +export const GetResponseBodyCommand = withCdpCommand("Network.getResponseBody", GetResponseBodyParams, GetResponseBodyResult); export const GetRequestPostDataParams = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId) }).passthrough(), "Network.getRequestPostData.params", "commandParams", { method: "Network.getRequestPostData" }); export const GetRequestPostDataResult = withCdpMeta(z.object({ "postData": z.string(), "base64Encoded": z.boolean() }).passthrough(), "Network.getRequestPostData.result", "commandResult", { method: "Network.getRequestPostData" }); +export const GetRequestPostDataCommand = withCdpCommand("Network.getRequestPostData", GetRequestPostDataParams, GetRequestPostDataResult); export const GetResponseBodyForInterceptionParams = withCdpMeta(z.object({ "interceptionId": z.lazy(() => InterceptionId) }).passthrough(), "Network.getResponseBodyForInterception.params", "commandParams", { method: "Network.getResponseBodyForInterception" }); export const GetResponseBodyForInterceptionResult = withCdpMeta(z.object({ "body": z.string(), "base64Encoded": z.boolean() }).passthrough(), "Network.getResponseBodyForInterception.result", "commandResult", { method: "Network.getResponseBodyForInterception" }); +export const GetResponseBodyForInterceptionCommand = withCdpCommand("Network.getResponseBodyForInterception", GetResponseBodyForInterceptionParams, GetResponseBodyForInterceptionResult); export const TakeResponseBodyForInterceptionAsStreamParams = withCdpMeta(z.object({ "interceptionId": z.lazy(() => InterceptionId) }).passthrough(), "Network.takeResponseBodyForInterceptionAsStream.params", "commandParams", { method: "Network.takeResponseBodyForInterceptionAsStream" }); export const TakeResponseBodyForInterceptionAsStreamResult = withCdpMeta(z.object({ "stream": z.lazy(() => IO.StreamHandle) }).passthrough(), "Network.takeResponseBodyForInterceptionAsStream.result", "commandResult", { method: "Network.takeResponseBodyForInterceptionAsStream" }); +export const TakeResponseBodyForInterceptionAsStreamCommand = withCdpCommand("Network.takeResponseBodyForInterceptionAsStream", TakeResponseBodyForInterceptionAsStreamParams, TakeResponseBodyForInterceptionAsStreamResult); export const ReplayXHRParams = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId) }).passthrough(), "Network.replayXHR.params", "commandParams", { method: "Network.replayXHR" }); export const ReplayXHRResult = withCdpMeta(z.object({ }).passthrough(), "Network.replayXHR.result", "commandResult", { method: "Network.replayXHR" }); +export const ReplayXHRCommand = withCdpCommand("Network.replayXHR", ReplayXHRParams, ReplayXHRResult); export const SearchInResponseBodyParams = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId), "query": z.string(), "caseSensitive": z.boolean().optional(), "isRegex": z.boolean().optional() }).passthrough(), "Network.searchInResponseBody.params", "commandParams", { method: "Network.searchInResponseBody" }); export const SearchInResponseBodyResult = withCdpMeta(z.object({ "result": z.array(z.lazy(() => Debugger.SearchMatch)) }).passthrough(), "Network.searchInResponseBody.result", "commandResult", { method: "Network.searchInResponseBody" }); +export const SearchInResponseBodyCommand = withCdpCommand("Network.searchInResponseBody", SearchInResponseBodyParams, SearchInResponseBodyResult); export const SetBlockedURLsParams = withCdpMeta(z.object({ "urlPatterns": z.array(z.lazy(() => BlockPattern)).optional(), "urls": z.array(z.string()).optional() }).passthrough(), "Network.setBlockedURLs.params", "commandParams", { method: "Network.setBlockedURLs" }); export const SetBlockedURLsResult = withCdpMeta(z.object({ }).passthrough(), "Network.setBlockedURLs.result", "commandResult", { method: "Network.setBlockedURLs" }); +export const SetBlockedURLsCommand = withCdpCommand("Network.setBlockedURLs", SetBlockedURLsParams, SetBlockedURLsResult); export const SetBypassServiceWorkerParams = withCdpMeta(z.object({ "bypass": z.boolean() }).passthrough(), "Network.setBypassServiceWorker.params", "commandParams", { method: "Network.setBypassServiceWorker" }); export const SetBypassServiceWorkerResult = withCdpMeta(z.object({ }).passthrough(), "Network.setBypassServiceWorker.result", "commandResult", { method: "Network.setBypassServiceWorker" }); +export const SetBypassServiceWorkerCommand = withCdpCommand("Network.setBypassServiceWorker", SetBypassServiceWorkerParams, SetBypassServiceWorkerResult); export const SetCacheDisabledParams = withCdpMeta(z.object({ "cacheDisabled": z.boolean() }).passthrough(), "Network.setCacheDisabled.params", "commandParams", { method: "Network.setCacheDisabled" }); export const SetCacheDisabledResult = withCdpMeta(z.object({ }).passthrough(), "Network.setCacheDisabled.result", "commandResult", { method: "Network.setCacheDisabled" }); +export const SetCacheDisabledCommand = withCdpCommand("Network.setCacheDisabled", SetCacheDisabledParams, SetCacheDisabledResult); export const SetCookieParams = withCdpMeta(z.object({ "name": z.string(), "value": z.string(), "url": z.string().optional(), "domain": z.string().optional(), "path": z.string().optional(), "secure": z.boolean().optional(), "httpOnly": z.boolean().optional(), "sameSite": z.lazy(() => CookieSameSite).optional(), "expires": z.lazy(() => TimeSinceEpoch).optional(), "priority": z.lazy(() => CookiePriority).optional(), "sourceScheme": z.lazy(() => CookieSourceScheme).optional(), "sourcePort": z.number().int().optional(), "partitionKey": z.lazy(() => CookiePartitionKey).optional() }).passthrough(), "Network.setCookie.params", "commandParams", { method: "Network.setCookie" }); export const SetCookieResult = withCdpMeta(z.object({ "success": z.boolean() }).passthrough(), "Network.setCookie.result", "commandResult", { method: "Network.setCookie" }); +export const SetCookieCommand = withCdpCommand("Network.setCookie", SetCookieParams, SetCookieResult); export const SetCookiesParams = withCdpMeta(z.object({ "cookies": z.array(z.lazy(() => CookieParam)) }).passthrough(), "Network.setCookies.params", "commandParams", { method: "Network.setCookies" }); export const SetCookiesResult = withCdpMeta(z.object({ }).passthrough(), "Network.setCookies.result", "commandResult", { method: "Network.setCookies" }); +export const SetCookiesCommand = withCdpCommand("Network.setCookies", SetCookiesParams, SetCookiesResult); export const SetExtraHTTPHeadersParams = withCdpMeta(z.object({ "headers": z.lazy(() => Headers) }).passthrough(), "Network.setExtraHTTPHeaders.params", "commandParams", { method: "Network.setExtraHTTPHeaders" }); export const SetExtraHTTPHeadersResult = withCdpMeta(z.object({ }).passthrough(), "Network.setExtraHTTPHeaders.result", "commandResult", { method: "Network.setExtraHTTPHeaders" }); +export const SetExtraHTTPHeadersCommand = withCdpCommand("Network.setExtraHTTPHeaders", SetExtraHTTPHeadersParams, SetExtraHTTPHeadersResult); export const SetAttachDebugStackParams = withCdpMeta(z.object({ "enabled": z.boolean() }).passthrough(), "Network.setAttachDebugStack.params", "commandParams", { method: "Network.setAttachDebugStack" }); export const SetAttachDebugStackResult = withCdpMeta(z.object({ }).passthrough(), "Network.setAttachDebugStack.result", "commandResult", { method: "Network.setAttachDebugStack" }); +export const SetAttachDebugStackCommand = withCdpCommand("Network.setAttachDebugStack", SetAttachDebugStackParams, SetAttachDebugStackResult); export const SetRequestInterceptionParams = withCdpMeta(z.object({ "patterns": z.array(z.lazy(() => RequestPattern)) }).passthrough(), "Network.setRequestInterception.params", "commandParams", { method: "Network.setRequestInterception" }); export const SetRequestInterceptionResult = withCdpMeta(z.object({ }).passthrough(), "Network.setRequestInterception.result", "commandResult", { method: "Network.setRequestInterception" }); +export const SetRequestInterceptionCommand = withCdpCommand("Network.setRequestInterception", SetRequestInterceptionParams, SetRequestInterceptionResult); export const SetUserAgentOverrideParams = withCdpMeta(z.object({ "userAgent": z.string(), "acceptLanguage": z.string().optional(), "platform": z.string().optional(), "userAgentMetadata": z.lazy(() => Emulation.UserAgentMetadata).optional() }).passthrough(), "Network.setUserAgentOverride.params", "commandParams", { method: "Network.setUserAgentOverride" }); export const SetUserAgentOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Network.setUserAgentOverride.result", "commandResult", { method: "Network.setUserAgentOverride" }); +export const SetUserAgentOverrideCommand = withCdpCommand("Network.setUserAgentOverride", SetUserAgentOverrideParams, SetUserAgentOverrideResult); export const StreamResourceContentParams = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId) }).passthrough(), "Network.streamResourceContent.params", "commandParams", { method: "Network.streamResourceContent" }); export const StreamResourceContentResult = withCdpMeta(z.object({ "bufferedData": z.string() }).passthrough(), "Network.streamResourceContent.result", "commandResult", { method: "Network.streamResourceContent" }); +export const StreamResourceContentCommand = withCdpCommand("Network.streamResourceContent", StreamResourceContentParams, StreamResourceContentResult); export const GetSecurityIsolationStatusParams = withCdpMeta(z.object({ "frameId": z.lazy(() => Page.FrameId).optional() }).passthrough(), "Network.getSecurityIsolationStatus.params", "commandParams", { method: "Network.getSecurityIsolationStatus" }); export const GetSecurityIsolationStatusResult = withCdpMeta(z.object({ "status": z.lazy(() => SecurityIsolationStatus) }).passthrough(), "Network.getSecurityIsolationStatus.result", "commandResult", { method: "Network.getSecurityIsolationStatus" }); +export const GetSecurityIsolationStatusCommand = withCdpCommand("Network.getSecurityIsolationStatus", GetSecurityIsolationStatusParams, GetSecurityIsolationStatusResult); export const EnableReportingApiParams = withCdpMeta(z.object({ "enable": z.boolean() }).passthrough(), "Network.enableReportingApi.params", "commandParams", { method: "Network.enableReportingApi" }); export const EnableReportingApiResult = withCdpMeta(z.object({ }).passthrough(), "Network.enableReportingApi.result", "commandResult", { method: "Network.enableReportingApi" }); +export const EnableReportingApiCommand = withCdpCommand("Network.enableReportingApi", EnableReportingApiParams, EnableReportingApiResult); export const EnableDeviceBoundSessionsParams = withCdpMeta(z.object({ "enable": z.boolean() }).passthrough(), "Network.enableDeviceBoundSessions.params", "commandParams", { method: "Network.enableDeviceBoundSessions" }); export const EnableDeviceBoundSessionsResult = withCdpMeta(z.object({ }).passthrough(), "Network.enableDeviceBoundSessions.result", "commandResult", { method: "Network.enableDeviceBoundSessions" }); +export const EnableDeviceBoundSessionsCommand = withCdpCommand("Network.enableDeviceBoundSessions", EnableDeviceBoundSessionsParams, EnableDeviceBoundSessionsResult); export const DeleteDeviceBoundSessionParams = withCdpMeta(z.object({ "key": z.lazy(() => DeviceBoundSessionKey) }).passthrough(), "Network.deleteDeviceBoundSession.params", "commandParams", { method: "Network.deleteDeviceBoundSession" }); export const DeleteDeviceBoundSessionResult = withCdpMeta(z.object({ }).passthrough(), "Network.deleteDeviceBoundSession.result", "commandResult", { method: "Network.deleteDeviceBoundSession" }); +export const DeleteDeviceBoundSessionCommand = withCdpCommand("Network.deleteDeviceBoundSession", DeleteDeviceBoundSessionParams, DeleteDeviceBoundSessionResult); export const FetchSchemefulSiteParams = withCdpMeta(z.object({ "origin": z.string() }).passthrough(), "Network.fetchSchemefulSite.params", "commandParams", { method: "Network.fetchSchemefulSite" }); export const FetchSchemefulSiteResult = withCdpMeta(z.object({ "schemefulSite": z.string() }).passthrough(), "Network.fetchSchemefulSite.result", "commandResult", { method: "Network.fetchSchemefulSite" }); +export const FetchSchemefulSiteCommand = withCdpCommand("Network.fetchSchemefulSite", FetchSchemefulSiteParams, FetchSchemefulSiteResult); export const LoadNetworkResourceParams = withCdpMeta(z.object({ "frameId": z.lazy(() => Page.FrameId).optional(), "url": z.string(), "options": z.lazy(() => LoadNetworkResourceOptions) }).passthrough(), "Network.loadNetworkResource.params", "commandParams", { method: "Network.loadNetworkResource" }); export const LoadNetworkResourceResult = withCdpMeta(z.object({ "resource": z.lazy(() => LoadNetworkResourcePageResult) }).passthrough(), "Network.loadNetworkResource.result", "commandResult", { method: "Network.loadNetworkResource" }); +export const LoadNetworkResourceCommand = withCdpCommand("Network.loadNetworkResource", LoadNetworkResourceParams, LoadNetworkResourceResult); export const SetCookieControlsParams = withCdpMeta(z.object({ "enableThirdPartyCookieRestriction": z.boolean() }).passthrough(), "Network.setCookieControls.params", "commandParams", { method: "Network.setCookieControls" }); export const SetCookieControlsResult = withCdpMeta(z.object({ }).passthrough(), "Network.setCookieControls.result", "commandResult", { method: "Network.setCookieControls" }); +export const SetCookieControlsCommand = withCdpCommand("Network.setCookieControls", SetCookieControlsParams, SetCookieControlsResult); export const DataReceivedEvent = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId), "timestamp": z.lazy(() => MonotonicTime), "dataLength": z.number().int(), "encodedDataLength": z.number().int(), "data": z.string().optional() }).passthrough(), "Network.dataReceived", "event", { phase: "event" }); export const EventSourceMessageReceivedEvent = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId), "timestamp": z.lazy(() => MonotonicTime), "eventName": z.string(), "eventId": z.string(), "data": z.string() }).passthrough(), "Network.eventSourceMessageReceived", "event", { phase: "event" }); export const LoadingFailedEvent = withCdpMeta(z.object({ "requestId": z.lazy(() => RequestId), "timestamp": z.lazy(() => MonotonicTime), "type": z.lazy(() => ResourceType), "errorText": z.string(), "canceled": z.boolean().optional(), "blockedReason": z.lazy(() => BlockedReason).optional(), "corsErrorStatus": z.lazy(() => CorsErrorStatus).optional() }).passthrough(), "Network.loadingFailed", "event", { phase: "event" }); @@ -451,47 +492,47 @@ export const zod = { DeviceBoundSessionEventOccurredEvent: DeviceBoundSessionEventOccurredEvent, } as const; export const commands = { - "Network.setAcceptedEncodings": { params: SetAcceptedEncodingsParams, result: SetAcceptedEncodingsResult }, - "Network.clearAcceptedEncodingsOverride": { params: ClearAcceptedEncodingsOverrideParams, result: ClearAcceptedEncodingsOverrideResult }, - "Network.canClearBrowserCache": { params: CanClearBrowserCacheParams, result: CanClearBrowserCacheResult }, - "Network.canClearBrowserCookies": { params: CanClearBrowserCookiesParams, result: CanClearBrowserCookiesResult }, - "Network.canEmulateNetworkConditions": { params: CanEmulateNetworkConditionsParams, result: CanEmulateNetworkConditionsResult }, - "Network.clearBrowserCache": { params: ClearBrowserCacheParams, result: ClearBrowserCacheResult }, - "Network.clearBrowserCookies": { params: ClearBrowserCookiesParams, result: ClearBrowserCookiesResult }, - "Network.continueInterceptedRequest": { params: ContinueInterceptedRequestParams, result: ContinueInterceptedRequestResult }, - "Network.deleteCookies": { params: DeleteCookiesParams, result: DeleteCookiesResult }, - "Network.disable": { params: DisableParams, result: DisableResult }, - "Network.emulateNetworkConditions": { params: EmulateNetworkConditionsParams, result: EmulateNetworkConditionsResult }, - "Network.emulateNetworkConditionsByRule": { params: EmulateNetworkConditionsByRuleParams, result: EmulateNetworkConditionsByRuleResult }, - "Network.overrideNetworkState": { params: OverrideNetworkStateParams, result: OverrideNetworkStateResult }, - "Network.enable": { params: EnableParams, result: EnableResult }, - "Network.configureDurableMessages": { params: ConfigureDurableMessagesParams, result: ConfigureDurableMessagesResult }, - "Network.getAllCookies": { params: GetAllCookiesParams, result: GetAllCookiesResult }, - "Network.getCertificate": { params: GetCertificateParams, result: GetCertificateResult }, - "Network.getCookies": { params: GetCookiesParams, result: GetCookiesResult }, - "Network.getResponseBody": { params: GetResponseBodyParams, result: GetResponseBodyResult }, - "Network.getRequestPostData": { params: GetRequestPostDataParams, result: GetRequestPostDataResult }, - "Network.getResponseBodyForInterception": { params: GetResponseBodyForInterceptionParams, result: GetResponseBodyForInterceptionResult }, - "Network.takeResponseBodyForInterceptionAsStream": { params: TakeResponseBodyForInterceptionAsStreamParams, result: TakeResponseBodyForInterceptionAsStreamResult }, - "Network.replayXHR": { params: ReplayXHRParams, result: ReplayXHRResult }, - "Network.searchInResponseBody": { params: SearchInResponseBodyParams, result: SearchInResponseBodyResult }, - "Network.setBlockedURLs": { params: SetBlockedURLsParams, result: SetBlockedURLsResult }, - "Network.setBypassServiceWorker": { params: SetBypassServiceWorkerParams, result: SetBypassServiceWorkerResult }, - "Network.setCacheDisabled": { params: SetCacheDisabledParams, result: SetCacheDisabledResult }, - "Network.setCookie": { params: SetCookieParams, result: SetCookieResult }, - "Network.setCookies": { params: SetCookiesParams, result: SetCookiesResult }, - "Network.setExtraHTTPHeaders": { params: SetExtraHTTPHeadersParams, result: SetExtraHTTPHeadersResult }, - "Network.setAttachDebugStack": { params: SetAttachDebugStackParams, result: SetAttachDebugStackResult }, - "Network.setRequestInterception": { params: SetRequestInterceptionParams, result: SetRequestInterceptionResult }, - "Network.setUserAgentOverride": { params: SetUserAgentOverrideParams, result: SetUserAgentOverrideResult }, - "Network.streamResourceContent": { params: StreamResourceContentParams, result: StreamResourceContentResult }, - "Network.getSecurityIsolationStatus": { params: GetSecurityIsolationStatusParams, result: GetSecurityIsolationStatusResult }, - "Network.enableReportingApi": { params: EnableReportingApiParams, result: EnableReportingApiResult }, - "Network.enableDeviceBoundSessions": { params: EnableDeviceBoundSessionsParams, result: EnableDeviceBoundSessionsResult }, - "Network.deleteDeviceBoundSession": { params: DeleteDeviceBoundSessionParams, result: DeleteDeviceBoundSessionResult }, - "Network.fetchSchemefulSite": { params: FetchSchemefulSiteParams, result: FetchSchemefulSiteResult }, - "Network.loadNetworkResource": { params: LoadNetworkResourceParams, result: LoadNetworkResourceResult }, - "Network.setCookieControls": { params: SetCookieControlsParams, result: SetCookieControlsResult }, + "Network.setAcceptedEncodings": SetAcceptedEncodingsCommand, + "Network.clearAcceptedEncodingsOverride": ClearAcceptedEncodingsOverrideCommand, + "Network.canClearBrowserCache": CanClearBrowserCacheCommand, + "Network.canClearBrowserCookies": CanClearBrowserCookiesCommand, + "Network.canEmulateNetworkConditions": CanEmulateNetworkConditionsCommand, + "Network.clearBrowserCache": ClearBrowserCacheCommand, + "Network.clearBrowserCookies": ClearBrowserCookiesCommand, + "Network.continueInterceptedRequest": ContinueInterceptedRequestCommand, + "Network.deleteCookies": DeleteCookiesCommand, + "Network.disable": DisableCommand, + "Network.emulateNetworkConditions": EmulateNetworkConditionsCommand, + "Network.emulateNetworkConditionsByRule": EmulateNetworkConditionsByRuleCommand, + "Network.overrideNetworkState": OverrideNetworkStateCommand, + "Network.enable": EnableCommand, + "Network.configureDurableMessages": ConfigureDurableMessagesCommand, + "Network.getAllCookies": GetAllCookiesCommand, + "Network.getCertificate": GetCertificateCommand, + "Network.getCookies": GetCookiesCommand, + "Network.getResponseBody": GetResponseBodyCommand, + "Network.getRequestPostData": GetRequestPostDataCommand, + "Network.getResponseBodyForInterception": GetResponseBodyForInterceptionCommand, + "Network.takeResponseBodyForInterceptionAsStream": TakeResponseBodyForInterceptionAsStreamCommand, + "Network.replayXHR": ReplayXHRCommand, + "Network.searchInResponseBody": SearchInResponseBodyCommand, + "Network.setBlockedURLs": SetBlockedURLsCommand, + "Network.setBypassServiceWorker": SetBypassServiceWorkerCommand, + "Network.setCacheDisabled": SetCacheDisabledCommand, + "Network.setCookie": SetCookieCommand, + "Network.setCookies": SetCookiesCommand, + "Network.setExtraHTTPHeaders": SetExtraHTTPHeadersCommand, + "Network.setAttachDebugStack": SetAttachDebugStackCommand, + "Network.setRequestInterception": SetRequestInterceptionCommand, + "Network.setUserAgentOverride": SetUserAgentOverrideCommand, + "Network.streamResourceContent": StreamResourceContentCommand, + "Network.getSecurityIsolationStatus": GetSecurityIsolationStatusCommand, + "Network.enableReportingApi": EnableReportingApiCommand, + "Network.enableDeviceBoundSessions": EnableDeviceBoundSessionsCommand, + "Network.deleteDeviceBoundSession": DeleteDeviceBoundSessionCommand, + "Network.fetchSchemefulSite": FetchSchemefulSiteCommand, + "Network.loadNetworkResource": LoadNetworkResourceCommand, + "Network.setCookieControls": SetCookieControlsCommand, } as const; export const events = { "Network.dataReceived": DataReceivedEvent, diff --git a/js/src/types/generated/zod/Overlay.ts b/js/src/types/generated/zod/Overlay.ts index 74eb92b..abbad66 100644 --- a/js/src/types/generated/zod/Overlay.ts +++ b/js/src/types/generated/zod/Overlay.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; import * as Page from "./Page.js"; import * as Runtime from "./Runtime.js"; @@ -29,64 +29,94 @@ export const InspectMode = withCdpMeta(z.enum(["searchForNode", "searchForUAShad export const InspectedElementAnchorConfig = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId).optional(), "backendNodeId": z.lazy(() => DOM.BackendNodeId).optional() }).passthrough(), "Overlay.InspectedElementAnchorConfig", "type"); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Overlay.disable.params", "commandParams", { method: "Overlay.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.disable.result", "commandResult", { method: "Overlay.disable" }); +export const DisableCommand = withCdpCommand("Overlay.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "Overlay.enable.params", "commandParams", { method: "Overlay.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.enable.result", "commandResult", { method: "Overlay.enable" }); +export const EnableCommand = withCdpCommand("Overlay.enable", EnableParams, EnableResult); export const GetHighlightObjectForTestParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId), "includeDistance": z.boolean().optional(), "includeStyle": z.boolean().optional(), "colorFormat": z.lazy(() => ColorFormat).optional(), "showAccessibilityInfo": z.boolean().optional() }).passthrough(), "Overlay.getHighlightObjectForTest.params", "commandParams", { method: "Overlay.getHighlightObjectForTest" }); export const GetHighlightObjectForTestResult = withCdpMeta(z.object({ "highlight": z.record(z.string(), z.unknown()) }).passthrough(), "Overlay.getHighlightObjectForTest.result", "commandResult", { method: "Overlay.getHighlightObjectForTest" }); +export const GetHighlightObjectForTestCommand = withCdpCommand("Overlay.getHighlightObjectForTest", GetHighlightObjectForTestParams, GetHighlightObjectForTestResult); export const GetGridHighlightObjectsForTestParams = withCdpMeta(z.object({ "nodeIds": z.array(z.lazy(() => DOM.NodeId)) }).passthrough(), "Overlay.getGridHighlightObjectsForTest.params", "commandParams", { method: "Overlay.getGridHighlightObjectsForTest" }); export const GetGridHighlightObjectsForTestResult = withCdpMeta(z.object({ "highlights": z.record(z.string(), z.unknown()) }).passthrough(), "Overlay.getGridHighlightObjectsForTest.result", "commandResult", { method: "Overlay.getGridHighlightObjectsForTest" }); +export const GetGridHighlightObjectsForTestCommand = withCdpCommand("Overlay.getGridHighlightObjectsForTest", GetGridHighlightObjectsForTestParams, GetGridHighlightObjectsForTestResult); export const GetSourceOrderHighlightObjectForTestParams = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId) }).passthrough(), "Overlay.getSourceOrderHighlightObjectForTest.params", "commandParams", { method: "Overlay.getSourceOrderHighlightObjectForTest" }); export const GetSourceOrderHighlightObjectForTestResult = withCdpMeta(z.object({ "highlight": z.record(z.string(), z.unknown()) }).passthrough(), "Overlay.getSourceOrderHighlightObjectForTest.result", "commandResult", { method: "Overlay.getSourceOrderHighlightObjectForTest" }); +export const GetSourceOrderHighlightObjectForTestCommand = withCdpCommand("Overlay.getSourceOrderHighlightObjectForTest", GetSourceOrderHighlightObjectForTestParams, GetSourceOrderHighlightObjectForTestResult); export const HideHighlightParams = withCdpMeta(z.object({ }).passthrough(), "Overlay.hideHighlight.params", "commandParams", { method: "Overlay.hideHighlight" }); export const HideHighlightResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.hideHighlight.result", "commandResult", { method: "Overlay.hideHighlight" }); +export const HideHighlightCommand = withCdpCommand("Overlay.hideHighlight", HideHighlightParams, HideHighlightResult); export const HighlightFrameParams = withCdpMeta(z.object({ "frameId": z.lazy(() => Page.FrameId), "contentColor": z.lazy(() => DOM.RGBA).optional(), "contentOutlineColor": z.lazy(() => DOM.RGBA).optional() }).passthrough(), "Overlay.highlightFrame.params", "commandParams", { method: "Overlay.highlightFrame" }); export const HighlightFrameResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.highlightFrame.result", "commandResult", { method: "Overlay.highlightFrame" }); +export const HighlightFrameCommand = withCdpCommand("Overlay.highlightFrame", HighlightFrameParams, HighlightFrameResult); export const HighlightNodeParams = withCdpMeta(z.object({ "highlightConfig": z.lazy(() => HighlightConfig), "nodeId": z.lazy(() => DOM.NodeId).optional(), "backendNodeId": z.lazy(() => DOM.BackendNodeId).optional(), "objectId": z.lazy(() => Runtime.RemoteObjectId).optional(), "selector": z.string().optional() }).passthrough(), "Overlay.highlightNode.params", "commandParams", { method: "Overlay.highlightNode" }); export const HighlightNodeResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.highlightNode.result", "commandResult", { method: "Overlay.highlightNode" }); +export const HighlightNodeCommand = withCdpCommand("Overlay.highlightNode", HighlightNodeParams, HighlightNodeResult); export const HighlightQuadParams = withCdpMeta(z.object({ "quad": z.lazy(() => DOM.Quad), "color": z.lazy(() => DOM.RGBA).optional(), "outlineColor": z.lazy(() => DOM.RGBA).optional() }).passthrough(), "Overlay.highlightQuad.params", "commandParams", { method: "Overlay.highlightQuad" }); export const HighlightQuadResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.highlightQuad.result", "commandResult", { method: "Overlay.highlightQuad" }); +export const HighlightQuadCommand = withCdpCommand("Overlay.highlightQuad", HighlightQuadParams, HighlightQuadResult); export const HighlightRectParams = withCdpMeta(z.object({ "x": z.number().int(), "y": z.number().int(), "width": z.number().int(), "height": z.number().int(), "color": z.lazy(() => DOM.RGBA).optional(), "outlineColor": z.lazy(() => DOM.RGBA).optional() }).passthrough(), "Overlay.highlightRect.params", "commandParams", { method: "Overlay.highlightRect" }); export const HighlightRectResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.highlightRect.result", "commandResult", { method: "Overlay.highlightRect" }); +export const HighlightRectCommand = withCdpCommand("Overlay.highlightRect", HighlightRectParams, HighlightRectResult); export const HighlightSourceOrderParams = withCdpMeta(z.object({ "sourceOrderConfig": z.lazy(() => SourceOrderConfig), "nodeId": z.lazy(() => DOM.NodeId).optional(), "backendNodeId": z.lazy(() => DOM.BackendNodeId).optional(), "objectId": z.lazy(() => Runtime.RemoteObjectId).optional() }).passthrough(), "Overlay.highlightSourceOrder.params", "commandParams", { method: "Overlay.highlightSourceOrder" }); export const HighlightSourceOrderResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.highlightSourceOrder.result", "commandResult", { method: "Overlay.highlightSourceOrder" }); +export const HighlightSourceOrderCommand = withCdpCommand("Overlay.highlightSourceOrder", HighlightSourceOrderParams, HighlightSourceOrderResult); export const SetInspectModeParams = withCdpMeta(z.object({ "mode": z.lazy(() => InspectMode), "highlightConfig": z.lazy(() => HighlightConfig).optional() }).passthrough(), "Overlay.setInspectMode.params", "commandParams", { method: "Overlay.setInspectMode" }); export const SetInspectModeResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setInspectMode.result", "commandResult", { method: "Overlay.setInspectMode" }); +export const SetInspectModeCommand = withCdpCommand("Overlay.setInspectMode", SetInspectModeParams, SetInspectModeResult); export const SetShowAdHighlightsParams = withCdpMeta(z.object({ "show": z.boolean() }).passthrough(), "Overlay.setShowAdHighlights.params", "commandParams", { method: "Overlay.setShowAdHighlights" }); export const SetShowAdHighlightsResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowAdHighlights.result", "commandResult", { method: "Overlay.setShowAdHighlights" }); +export const SetShowAdHighlightsCommand = withCdpCommand("Overlay.setShowAdHighlights", SetShowAdHighlightsParams, SetShowAdHighlightsResult); export const SetPausedInDebuggerMessageParams = withCdpMeta(z.object({ "message": z.string().optional() }).passthrough(), "Overlay.setPausedInDebuggerMessage.params", "commandParams", { method: "Overlay.setPausedInDebuggerMessage" }); export const SetPausedInDebuggerMessageResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setPausedInDebuggerMessage.result", "commandResult", { method: "Overlay.setPausedInDebuggerMessage" }); +export const SetPausedInDebuggerMessageCommand = withCdpCommand("Overlay.setPausedInDebuggerMessage", SetPausedInDebuggerMessageParams, SetPausedInDebuggerMessageResult); export const SetShowDebugBordersParams = withCdpMeta(z.object({ "show": z.boolean() }).passthrough(), "Overlay.setShowDebugBorders.params", "commandParams", { method: "Overlay.setShowDebugBorders" }); export const SetShowDebugBordersResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowDebugBorders.result", "commandResult", { method: "Overlay.setShowDebugBorders" }); +export const SetShowDebugBordersCommand = withCdpCommand("Overlay.setShowDebugBorders", SetShowDebugBordersParams, SetShowDebugBordersResult); export const SetShowFPSCounterParams = withCdpMeta(z.object({ "show": z.boolean() }).passthrough(), "Overlay.setShowFPSCounter.params", "commandParams", { method: "Overlay.setShowFPSCounter" }); export const SetShowFPSCounterResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowFPSCounter.result", "commandResult", { method: "Overlay.setShowFPSCounter" }); +export const SetShowFPSCounterCommand = withCdpCommand("Overlay.setShowFPSCounter", SetShowFPSCounterParams, SetShowFPSCounterResult); export const SetShowGridOverlaysParams = withCdpMeta(z.object({ "gridNodeHighlightConfigs": z.array(z.lazy(() => GridNodeHighlightConfig)) }).passthrough(), "Overlay.setShowGridOverlays.params", "commandParams", { method: "Overlay.setShowGridOverlays" }); export const SetShowGridOverlaysResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowGridOverlays.result", "commandResult", { method: "Overlay.setShowGridOverlays" }); +export const SetShowGridOverlaysCommand = withCdpCommand("Overlay.setShowGridOverlays", SetShowGridOverlaysParams, SetShowGridOverlaysResult); export const SetShowFlexOverlaysParams = withCdpMeta(z.object({ "flexNodeHighlightConfigs": z.array(z.lazy(() => FlexNodeHighlightConfig)) }).passthrough(), "Overlay.setShowFlexOverlays.params", "commandParams", { method: "Overlay.setShowFlexOverlays" }); export const SetShowFlexOverlaysResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowFlexOverlays.result", "commandResult", { method: "Overlay.setShowFlexOverlays" }); +export const SetShowFlexOverlaysCommand = withCdpCommand("Overlay.setShowFlexOverlays", SetShowFlexOverlaysParams, SetShowFlexOverlaysResult); export const SetShowScrollSnapOverlaysParams = withCdpMeta(z.object({ "scrollSnapHighlightConfigs": z.array(z.lazy(() => ScrollSnapHighlightConfig)) }).passthrough(), "Overlay.setShowScrollSnapOverlays.params", "commandParams", { method: "Overlay.setShowScrollSnapOverlays" }); export const SetShowScrollSnapOverlaysResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowScrollSnapOverlays.result", "commandResult", { method: "Overlay.setShowScrollSnapOverlays" }); +export const SetShowScrollSnapOverlaysCommand = withCdpCommand("Overlay.setShowScrollSnapOverlays", SetShowScrollSnapOverlaysParams, SetShowScrollSnapOverlaysResult); export const SetShowContainerQueryOverlaysParams = withCdpMeta(z.object({ "containerQueryHighlightConfigs": z.array(z.lazy(() => ContainerQueryHighlightConfig)) }).passthrough(), "Overlay.setShowContainerQueryOverlays.params", "commandParams", { method: "Overlay.setShowContainerQueryOverlays" }); export const SetShowContainerQueryOverlaysResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowContainerQueryOverlays.result", "commandResult", { method: "Overlay.setShowContainerQueryOverlays" }); +export const SetShowContainerQueryOverlaysCommand = withCdpCommand("Overlay.setShowContainerQueryOverlays", SetShowContainerQueryOverlaysParams, SetShowContainerQueryOverlaysResult); export const SetShowInspectedElementAnchorParams = withCdpMeta(z.object({ "inspectedElementAnchorConfig": z.lazy(() => InspectedElementAnchorConfig) }).passthrough(), "Overlay.setShowInspectedElementAnchor.params", "commandParams", { method: "Overlay.setShowInspectedElementAnchor" }); export const SetShowInspectedElementAnchorResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowInspectedElementAnchor.result", "commandResult", { method: "Overlay.setShowInspectedElementAnchor" }); +export const SetShowInspectedElementAnchorCommand = withCdpCommand("Overlay.setShowInspectedElementAnchor", SetShowInspectedElementAnchorParams, SetShowInspectedElementAnchorResult); export const SetShowPaintRectsParams = withCdpMeta(z.object({ "result": z.boolean() }).passthrough(), "Overlay.setShowPaintRects.params", "commandParams", { method: "Overlay.setShowPaintRects" }); export const SetShowPaintRectsResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowPaintRects.result", "commandResult", { method: "Overlay.setShowPaintRects" }); +export const SetShowPaintRectsCommand = withCdpCommand("Overlay.setShowPaintRects", SetShowPaintRectsParams, SetShowPaintRectsResult); export const SetShowLayoutShiftRegionsParams = withCdpMeta(z.object({ "result": z.boolean() }).passthrough(), "Overlay.setShowLayoutShiftRegions.params", "commandParams", { method: "Overlay.setShowLayoutShiftRegions" }); export const SetShowLayoutShiftRegionsResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowLayoutShiftRegions.result", "commandResult", { method: "Overlay.setShowLayoutShiftRegions" }); +export const SetShowLayoutShiftRegionsCommand = withCdpCommand("Overlay.setShowLayoutShiftRegions", SetShowLayoutShiftRegionsParams, SetShowLayoutShiftRegionsResult); export const SetShowScrollBottleneckRectsParams = withCdpMeta(z.object({ "show": z.boolean() }).passthrough(), "Overlay.setShowScrollBottleneckRects.params", "commandParams", { method: "Overlay.setShowScrollBottleneckRects" }); export const SetShowScrollBottleneckRectsResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowScrollBottleneckRects.result", "commandResult", { method: "Overlay.setShowScrollBottleneckRects" }); +export const SetShowScrollBottleneckRectsCommand = withCdpCommand("Overlay.setShowScrollBottleneckRects", SetShowScrollBottleneckRectsParams, SetShowScrollBottleneckRectsResult); export const SetShowHitTestBordersParams = withCdpMeta(z.object({ "show": z.boolean() }).passthrough(), "Overlay.setShowHitTestBorders.params", "commandParams", { method: "Overlay.setShowHitTestBorders" }); export const SetShowHitTestBordersResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowHitTestBorders.result", "commandResult", { method: "Overlay.setShowHitTestBorders" }); +export const SetShowHitTestBordersCommand = withCdpCommand("Overlay.setShowHitTestBorders", SetShowHitTestBordersParams, SetShowHitTestBordersResult); export const SetShowWebVitalsParams = withCdpMeta(z.object({ "show": z.boolean() }).passthrough(), "Overlay.setShowWebVitals.params", "commandParams", { method: "Overlay.setShowWebVitals" }); export const SetShowWebVitalsResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowWebVitals.result", "commandResult", { method: "Overlay.setShowWebVitals" }); +export const SetShowWebVitalsCommand = withCdpCommand("Overlay.setShowWebVitals", SetShowWebVitalsParams, SetShowWebVitalsResult); export const SetShowViewportSizeOnResizeParams = withCdpMeta(z.object({ "show": z.boolean() }).passthrough(), "Overlay.setShowViewportSizeOnResize.params", "commandParams", { method: "Overlay.setShowViewportSizeOnResize" }); export const SetShowViewportSizeOnResizeResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowViewportSizeOnResize.result", "commandResult", { method: "Overlay.setShowViewportSizeOnResize" }); +export const SetShowViewportSizeOnResizeCommand = withCdpCommand("Overlay.setShowViewportSizeOnResize", SetShowViewportSizeOnResizeParams, SetShowViewportSizeOnResizeResult); export const SetShowHingeParams = withCdpMeta(z.object({ "hingeConfig": z.lazy(() => HingeConfig).optional() }).passthrough(), "Overlay.setShowHinge.params", "commandParams", { method: "Overlay.setShowHinge" }); export const SetShowHingeResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowHinge.result", "commandResult", { method: "Overlay.setShowHinge" }); +export const SetShowHingeCommand = withCdpCommand("Overlay.setShowHinge", SetShowHingeParams, SetShowHingeResult); export const SetShowIsolatedElementsParams = withCdpMeta(z.object({ "isolatedElementHighlightConfigs": z.array(z.lazy(() => IsolatedElementHighlightConfig)) }).passthrough(), "Overlay.setShowIsolatedElements.params", "commandParams", { method: "Overlay.setShowIsolatedElements" }); export const SetShowIsolatedElementsResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowIsolatedElements.result", "commandResult", { method: "Overlay.setShowIsolatedElements" }); +export const SetShowIsolatedElementsCommand = withCdpCommand("Overlay.setShowIsolatedElements", SetShowIsolatedElementsParams, SetShowIsolatedElementsResult); export const SetShowWindowControlsOverlayParams = withCdpMeta(z.object({ "windowControlsOverlayConfig": z.lazy(() => WindowControlsOverlayConfig).optional() }).passthrough(), "Overlay.setShowWindowControlsOverlay.params", "commandParams", { method: "Overlay.setShowWindowControlsOverlay" }); export const SetShowWindowControlsOverlayResult = withCdpMeta(z.object({ }).passthrough(), "Overlay.setShowWindowControlsOverlay.result", "commandResult", { method: "Overlay.setShowWindowControlsOverlay" }); +export const SetShowWindowControlsOverlayCommand = withCdpCommand("Overlay.setShowWindowControlsOverlay", SetShowWindowControlsOverlayParams, SetShowWindowControlsOverlayResult); export const InspectNodeRequestedEvent = withCdpMeta(z.object({ "backendNodeId": z.lazy(() => DOM.BackendNodeId) }).passthrough(), "Overlay.inspectNodeRequested", "event", { phase: "event" }); export const NodeHighlightRequestedEvent = withCdpMeta(z.object({ "nodeId": z.lazy(() => DOM.NodeId) }).passthrough(), "Overlay.nodeHighlightRequested", "event", { phase: "event" }); export const ScreenshotRequestedEvent = withCdpMeta(z.object({ "viewport": z.lazy(() => Page.Viewport) }).passthrough(), "Overlay.screenshotRequested", "event", { phase: "event" }); @@ -184,36 +214,36 @@ export const zod = { InspectModeCanceledEvent: InspectModeCanceledEvent, } as const; export const commands = { - "Overlay.disable": { params: DisableParams, result: DisableResult }, - "Overlay.enable": { params: EnableParams, result: EnableResult }, - "Overlay.getHighlightObjectForTest": { params: GetHighlightObjectForTestParams, result: GetHighlightObjectForTestResult }, - "Overlay.getGridHighlightObjectsForTest": { params: GetGridHighlightObjectsForTestParams, result: GetGridHighlightObjectsForTestResult }, - "Overlay.getSourceOrderHighlightObjectForTest": { params: GetSourceOrderHighlightObjectForTestParams, result: GetSourceOrderHighlightObjectForTestResult }, - "Overlay.hideHighlight": { params: HideHighlightParams, result: HideHighlightResult }, - "Overlay.highlightFrame": { params: HighlightFrameParams, result: HighlightFrameResult }, - "Overlay.highlightNode": { params: HighlightNodeParams, result: HighlightNodeResult }, - "Overlay.highlightQuad": { params: HighlightQuadParams, result: HighlightQuadResult }, - "Overlay.highlightRect": { params: HighlightRectParams, result: HighlightRectResult }, - "Overlay.highlightSourceOrder": { params: HighlightSourceOrderParams, result: HighlightSourceOrderResult }, - "Overlay.setInspectMode": { params: SetInspectModeParams, result: SetInspectModeResult }, - "Overlay.setShowAdHighlights": { params: SetShowAdHighlightsParams, result: SetShowAdHighlightsResult }, - "Overlay.setPausedInDebuggerMessage": { params: SetPausedInDebuggerMessageParams, result: SetPausedInDebuggerMessageResult }, - "Overlay.setShowDebugBorders": { params: SetShowDebugBordersParams, result: SetShowDebugBordersResult }, - "Overlay.setShowFPSCounter": { params: SetShowFPSCounterParams, result: SetShowFPSCounterResult }, - "Overlay.setShowGridOverlays": { params: SetShowGridOverlaysParams, result: SetShowGridOverlaysResult }, - "Overlay.setShowFlexOverlays": { params: SetShowFlexOverlaysParams, result: SetShowFlexOverlaysResult }, - "Overlay.setShowScrollSnapOverlays": { params: SetShowScrollSnapOverlaysParams, result: SetShowScrollSnapOverlaysResult }, - "Overlay.setShowContainerQueryOverlays": { params: SetShowContainerQueryOverlaysParams, result: SetShowContainerQueryOverlaysResult }, - "Overlay.setShowInspectedElementAnchor": { params: SetShowInspectedElementAnchorParams, result: SetShowInspectedElementAnchorResult }, - "Overlay.setShowPaintRects": { params: SetShowPaintRectsParams, result: SetShowPaintRectsResult }, - "Overlay.setShowLayoutShiftRegions": { params: SetShowLayoutShiftRegionsParams, result: SetShowLayoutShiftRegionsResult }, - "Overlay.setShowScrollBottleneckRects": { params: SetShowScrollBottleneckRectsParams, result: SetShowScrollBottleneckRectsResult }, - "Overlay.setShowHitTestBorders": { params: SetShowHitTestBordersParams, result: SetShowHitTestBordersResult }, - "Overlay.setShowWebVitals": { params: SetShowWebVitalsParams, result: SetShowWebVitalsResult }, - "Overlay.setShowViewportSizeOnResize": { params: SetShowViewportSizeOnResizeParams, result: SetShowViewportSizeOnResizeResult }, - "Overlay.setShowHinge": { params: SetShowHingeParams, result: SetShowHingeResult }, - "Overlay.setShowIsolatedElements": { params: SetShowIsolatedElementsParams, result: SetShowIsolatedElementsResult }, - "Overlay.setShowWindowControlsOverlay": { params: SetShowWindowControlsOverlayParams, result: SetShowWindowControlsOverlayResult }, + "Overlay.disable": DisableCommand, + "Overlay.enable": EnableCommand, + "Overlay.getHighlightObjectForTest": GetHighlightObjectForTestCommand, + "Overlay.getGridHighlightObjectsForTest": GetGridHighlightObjectsForTestCommand, + "Overlay.getSourceOrderHighlightObjectForTest": GetSourceOrderHighlightObjectForTestCommand, + "Overlay.hideHighlight": HideHighlightCommand, + "Overlay.highlightFrame": HighlightFrameCommand, + "Overlay.highlightNode": HighlightNodeCommand, + "Overlay.highlightQuad": HighlightQuadCommand, + "Overlay.highlightRect": HighlightRectCommand, + "Overlay.highlightSourceOrder": HighlightSourceOrderCommand, + "Overlay.setInspectMode": SetInspectModeCommand, + "Overlay.setShowAdHighlights": SetShowAdHighlightsCommand, + "Overlay.setPausedInDebuggerMessage": SetPausedInDebuggerMessageCommand, + "Overlay.setShowDebugBorders": SetShowDebugBordersCommand, + "Overlay.setShowFPSCounter": SetShowFPSCounterCommand, + "Overlay.setShowGridOverlays": SetShowGridOverlaysCommand, + "Overlay.setShowFlexOverlays": SetShowFlexOverlaysCommand, + "Overlay.setShowScrollSnapOverlays": SetShowScrollSnapOverlaysCommand, + "Overlay.setShowContainerQueryOverlays": SetShowContainerQueryOverlaysCommand, + "Overlay.setShowInspectedElementAnchor": SetShowInspectedElementAnchorCommand, + "Overlay.setShowPaintRects": SetShowPaintRectsCommand, + "Overlay.setShowLayoutShiftRegions": SetShowLayoutShiftRegionsCommand, + "Overlay.setShowScrollBottleneckRects": SetShowScrollBottleneckRectsCommand, + "Overlay.setShowHitTestBorders": SetShowHitTestBordersCommand, + "Overlay.setShowWebVitals": SetShowWebVitalsCommand, + "Overlay.setShowViewportSizeOnResize": SetShowViewportSizeOnResizeCommand, + "Overlay.setShowHinge": SetShowHingeCommand, + "Overlay.setShowIsolatedElements": SetShowIsolatedElementsCommand, + "Overlay.setShowWindowControlsOverlay": SetShowWindowControlsOverlayCommand, } as const; export const events = { "Overlay.inspectNodeRequested": InspectNodeRequestedEvent, diff --git a/js/src/types/generated/zod/PWA.ts b/js/src/types/generated/zod/PWA.ts index 7723159..73f87e8 100644 --- a/js/src/types/generated/zod/PWA.ts +++ b/js/src/types/generated/zod/PWA.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Target from "./Target.js"; export const FileHandlerAccept = withCdpMeta(z.object({ "mediaType": z.string(), "fileExtensions": z.array(z.string()) }).passthrough(), "PWA.FileHandlerAccept", "type"); @@ -9,18 +9,25 @@ export const FileHandler = withCdpMeta(z.object({ "action": z.string(), "accepts export const DisplayMode = withCdpMeta(z.enum(["standalone", "browser"]), "PWA.DisplayMode", "type"); export const GetOsAppStateParams = withCdpMeta(z.object({ "manifestId": z.string() }).passthrough(), "PWA.getOsAppState.params", "commandParams", { method: "PWA.getOsAppState" }); export const GetOsAppStateResult = withCdpMeta(z.object({ "badgeCount": z.number().int(), "fileHandlers": z.array(z.lazy(() => FileHandler)) }).passthrough(), "PWA.getOsAppState.result", "commandResult", { method: "PWA.getOsAppState" }); +export const GetOsAppStateCommand = withCdpCommand("PWA.getOsAppState", GetOsAppStateParams, GetOsAppStateResult); export const InstallParams = withCdpMeta(z.object({ "manifestId": z.string(), "installUrlOrBundleUrl": z.string().optional() }).passthrough(), "PWA.install.params", "commandParams", { method: "PWA.install" }); export const InstallResult = withCdpMeta(z.object({ }).passthrough(), "PWA.install.result", "commandResult", { method: "PWA.install" }); +export const InstallCommand = withCdpCommand("PWA.install", InstallParams, InstallResult); export const UninstallParams = withCdpMeta(z.object({ "manifestId": z.string() }).passthrough(), "PWA.uninstall.params", "commandParams", { method: "PWA.uninstall" }); export const UninstallResult = withCdpMeta(z.object({ }).passthrough(), "PWA.uninstall.result", "commandResult", { method: "PWA.uninstall" }); +export const UninstallCommand = withCdpCommand("PWA.uninstall", UninstallParams, UninstallResult); export const LaunchParams = withCdpMeta(z.object({ "manifestId": z.string(), "url": z.string().optional() }).passthrough(), "PWA.launch.params", "commandParams", { method: "PWA.launch" }); export const LaunchResult = withCdpMeta(z.object({ "targetId": z.lazy(() => Target.TargetID) }).passthrough(), "PWA.launch.result", "commandResult", { method: "PWA.launch" }); +export const LaunchCommand = withCdpCommand("PWA.launch", LaunchParams, LaunchResult); export const LaunchFilesInAppParams = withCdpMeta(z.object({ "manifestId": z.string(), "files": z.array(z.string()) }).passthrough(), "PWA.launchFilesInApp.params", "commandParams", { method: "PWA.launchFilesInApp" }); export const LaunchFilesInAppResult = withCdpMeta(z.object({ "targetIds": z.array(z.lazy(() => Target.TargetID)) }).passthrough(), "PWA.launchFilesInApp.result", "commandResult", { method: "PWA.launchFilesInApp" }); +export const LaunchFilesInAppCommand = withCdpCommand("PWA.launchFilesInApp", LaunchFilesInAppParams, LaunchFilesInAppResult); export const OpenCurrentPageInAppParams = withCdpMeta(z.object({ "manifestId": z.string() }).passthrough(), "PWA.openCurrentPageInApp.params", "commandParams", { method: "PWA.openCurrentPageInApp" }); export const OpenCurrentPageInAppResult = withCdpMeta(z.object({ }).passthrough(), "PWA.openCurrentPageInApp.result", "commandResult", { method: "PWA.openCurrentPageInApp" }); +export const OpenCurrentPageInAppCommand = withCdpCommand("PWA.openCurrentPageInApp", OpenCurrentPageInAppParams, OpenCurrentPageInAppResult); export const ChangeAppUserSettingsParams = withCdpMeta(z.object({ "manifestId": z.string(), "linkCapturing": z.boolean().optional(), "displayMode": z.lazy(() => DisplayMode).optional() }).passthrough(), "PWA.changeAppUserSettings.params", "commandParams", { method: "PWA.changeAppUserSettings" }); export const ChangeAppUserSettingsResult = withCdpMeta(z.object({ }).passthrough(), "PWA.changeAppUserSettings.result", "commandResult", { method: "PWA.changeAppUserSettings" }); +export const ChangeAppUserSettingsCommand = withCdpCommand("PWA.changeAppUserSettings", ChangeAppUserSettingsParams, ChangeAppUserSettingsResult); export const zod = { FileHandlerAccept: FileHandlerAccept, @@ -42,13 +49,13 @@ export const zod = { ChangeAppUserSettingsResult: ChangeAppUserSettingsResult, } as const; export const commands = { - "PWA.getOsAppState": { params: GetOsAppStateParams, result: GetOsAppStateResult }, - "PWA.install": { params: InstallParams, result: InstallResult }, - "PWA.uninstall": { params: UninstallParams, result: UninstallResult }, - "PWA.launch": { params: LaunchParams, result: LaunchResult }, - "PWA.launchFilesInApp": { params: LaunchFilesInAppParams, result: LaunchFilesInAppResult }, - "PWA.openCurrentPageInApp": { params: OpenCurrentPageInAppParams, result: OpenCurrentPageInAppResult }, - "PWA.changeAppUserSettings": { params: ChangeAppUserSettingsParams, result: ChangeAppUserSettingsResult }, + "PWA.getOsAppState": GetOsAppStateCommand, + "PWA.install": InstallCommand, + "PWA.uninstall": UninstallCommand, + "PWA.launch": LaunchCommand, + "PWA.launchFilesInApp": LaunchFilesInAppCommand, + "PWA.openCurrentPageInApp": OpenCurrentPageInAppCommand, + "PWA.changeAppUserSettings": ChangeAppUserSettingsCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/Page.ts b/js/src/types/generated/zod/Page.ts index 75d3bf4..3a4facf 100644 --- a/js/src/types/generated/zod/Page.ts +++ b/js/src/types/generated/zod/Page.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; import * as Debugger from "./Debugger.js"; import * as Emulation from "./Emulation.js"; @@ -69,126 +69,187 @@ export const BackForwardCacheNotRestoredExplanation = withCdpMeta(z.object({ "ty export const BackForwardCacheNotRestoredExplanationTree = withCdpMeta(z.object({ "url": z.string(), "explanations": z.array(z.lazy(() => BackForwardCacheNotRestoredExplanation)), "children": z.array(z.lazy(() => BackForwardCacheNotRestoredExplanationTree)) }).passthrough(), "Page.BackForwardCacheNotRestoredExplanationTree", "type"); export const AddScriptToEvaluateOnLoadParams = withCdpMeta(z.object({ "scriptSource": z.string() }).passthrough(), "Page.addScriptToEvaluateOnLoad.params", "commandParams", { method: "Page.addScriptToEvaluateOnLoad" }); export const AddScriptToEvaluateOnLoadResult = withCdpMeta(z.object({ "identifier": z.lazy(() => ScriptIdentifier) }).passthrough(), "Page.addScriptToEvaluateOnLoad.result", "commandResult", { method: "Page.addScriptToEvaluateOnLoad" }); +export const AddScriptToEvaluateOnLoadCommand = withCdpCommand("Page.addScriptToEvaluateOnLoad", AddScriptToEvaluateOnLoadParams, AddScriptToEvaluateOnLoadResult); export const AddScriptToEvaluateOnNewDocumentParams = withCdpMeta(z.object({ "source": z.string(), "worldName": z.string().optional(), "includeCommandLineAPI": z.boolean().optional(), "runImmediately": z.boolean().optional() }).passthrough(), "Page.addScriptToEvaluateOnNewDocument.params", "commandParams", { method: "Page.addScriptToEvaluateOnNewDocument" }); export const AddScriptToEvaluateOnNewDocumentResult = withCdpMeta(z.object({ "identifier": z.lazy(() => ScriptIdentifier) }).passthrough(), "Page.addScriptToEvaluateOnNewDocument.result", "commandResult", { method: "Page.addScriptToEvaluateOnNewDocument" }); +export const AddScriptToEvaluateOnNewDocumentCommand = withCdpCommand("Page.addScriptToEvaluateOnNewDocument", AddScriptToEvaluateOnNewDocumentParams, AddScriptToEvaluateOnNewDocumentResult); export const BringToFrontParams = withCdpMeta(z.object({ }).passthrough(), "Page.bringToFront.params", "commandParams", { method: "Page.bringToFront" }); export const BringToFrontResult = withCdpMeta(z.object({ }).passthrough(), "Page.bringToFront.result", "commandResult", { method: "Page.bringToFront" }); +export const BringToFrontCommand = withCdpCommand("Page.bringToFront", BringToFrontParams, BringToFrontResult); export const CaptureScreenshotParams = withCdpMeta(z.object({ "format": z.enum(["jpeg", "png", "webp"]).optional(), "quality": z.number().int().optional(), "clip": z.lazy(() => Viewport).optional(), "fromSurface": z.boolean().optional(), "captureBeyondViewport": z.boolean().optional(), "optimizeForSpeed": z.boolean().optional() }).passthrough(), "Page.captureScreenshot.params", "commandParams", { method: "Page.captureScreenshot" }); export const CaptureScreenshotResult = withCdpMeta(z.object({ "data": z.string() }).passthrough(), "Page.captureScreenshot.result", "commandResult", { method: "Page.captureScreenshot" }); +export const CaptureScreenshotCommand = withCdpCommand("Page.captureScreenshot", CaptureScreenshotParams, CaptureScreenshotResult); export const CaptureSnapshotParams = withCdpMeta(z.object({ "format": z.enum(["mhtml"]).optional() }).passthrough(), "Page.captureSnapshot.params", "commandParams", { method: "Page.captureSnapshot" }); export const CaptureSnapshotResult = withCdpMeta(z.object({ "data": z.string() }).passthrough(), "Page.captureSnapshot.result", "commandResult", { method: "Page.captureSnapshot" }); +export const CaptureSnapshotCommand = withCdpCommand("Page.captureSnapshot", CaptureSnapshotParams, CaptureSnapshotResult); export const ClearDeviceMetricsOverrideParams = withCdpMeta(z.object({ }).passthrough(), "Page.clearDeviceMetricsOverride.params", "commandParams", { method: "Page.clearDeviceMetricsOverride" }); export const ClearDeviceMetricsOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Page.clearDeviceMetricsOverride.result", "commandResult", { method: "Page.clearDeviceMetricsOverride" }); +export const ClearDeviceMetricsOverrideCommand = withCdpCommand("Page.clearDeviceMetricsOverride", ClearDeviceMetricsOverrideParams, ClearDeviceMetricsOverrideResult); export const ClearDeviceOrientationOverrideParams = withCdpMeta(z.object({ }).passthrough(), "Page.clearDeviceOrientationOverride.params", "commandParams", { method: "Page.clearDeviceOrientationOverride" }); export const ClearDeviceOrientationOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Page.clearDeviceOrientationOverride.result", "commandResult", { method: "Page.clearDeviceOrientationOverride" }); +export const ClearDeviceOrientationOverrideCommand = withCdpCommand("Page.clearDeviceOrientationOverride", ClearDeviceOrientationOverrideParams, ClearDeviceOrientationOverrideResult); export const ClearGeolocationOverrideParams = withCdpMeta(z.object({ }).passthrough(), "Page.clearGeolocationOverride.params", "commandParams", { method: "Page.clearGeolocationOverride" }); export const ClearGeolocationOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Page.clearGeolocationOverride.result", "commandResult", { method: "Page.clearGeolocationOverride" }); +export const ClearGeolocationOverrideCommand = withCdpCommand("Page.clearGeolocationOverride", ClearGeolocationOverrideParams, ClearGeolocationOverrideResult); export const CreateIsolatedWorldParams = withCdpMeta(z.object({ "frameId": z.lazy(() => FrameId), "worldName": z.string().optional(), "grantUniveralAccess": z.boolean().optional() }).passthrough(), "Page.createIsolatedWorld.params", "commandParams", { method: "Page.createIsolatedWorld" }); export const CreateIsolatedWorldResult = withCdpMeta(z.object({ "executionContextId": z.lazy(() => Runtime.ExecutionContextId) }).passthrough(), "Page.createIsolatedWorld.result", "commandResult", { method: "Page.createIsolatedWorld" }); +export const CreateIsolatedWorldCommand = withCdpCommand("Page.createIsolatedWorld", CreateIsolatedWorldParams, CreateIsolatedWorldResult); export const DeleteCookieParams = withCdpMeta(z.object({ "cookieName": z.string(), "url": z.string() }).passthrough(), "Page.deleteCookie.params", "commandParams", { method: "Page.deleteCookie" }); export const DeleteCookieResult = withCdpMeta(z.object({ }).passthrough(), "Page.deleteCookie.result", "commandResult", { method: "Page.deleteCookie" }); +export const DeleteCookieCommand = withCdpCommand("Page.deleteCookie", DeleteCookieParams, DeleteCookieResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Page.disable.params", "commandParams", { method: "Page.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Page.disable.result", "commandResult", { method: "Page.disable" }); +export const DisableCommand = withCdpCommand("Page.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ "enableFileChooserOpenedEvent": z.boolean().optional() }).passthrough(), "Page.enable.params", "commandParams", { method: "Page.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Page.enable.result", "commandResult", { method: "Page.enable" }); +export const EnableCommand = withCdpCommand("Page.enable", EnableParams, EnableResult); export const GetAppManifestParams = withCdpMeta(z.object({ "manifestId": z.string().optional() }).passthrough(), "Page.getAppManifest.params", "commandParams", { method: "Page.getAppManifest" }); export const GetAppManifestResult = withCdpMeta(z.object({ "url": z.string(), "errors": z.array(z.lazy(() => AppManifestError)), "data": z.string().optional(), "parsed": z.lazy(() => AppManifestParsedProperties).optional(), "manifest": z.lazy(() => WebAppManifest) }).passthrough(), "Page.getAppManifest.result", "commandResult", { method: "Page.getAppManifest" }); +export const GetAppManifestCommand = withCdpCommand("Page.getAppManifest", GetAppManifestParams, GetAppManifestResult); export const GetInstallabilityErrorsParams = withCdpMeta(z.object({ }).passthrough(), "Page.getInstallabilityErrors.params", "commandParams", { method: "Page.getInstallabilityErrors" }); export const GetInstallabilityErrorsResult = withCdpMeta(z.object({ "installabilityErrors": z.array(z.lazy(() => InstallabilityError)) }).passthrough(), "Page.getInstallabilityErrors.result", "commandResult", { method: "Page.getInstallabilityErrors" }); +export const GetInstallabilityErrorsCommand = withCdpCommand("Page.getInstallabilityErrors", GetInstallabilityErrorsParams, GetInstallabilityErrorsResult); export const GetManifestIconsParams = withCdpMeta(z.object({ }).passthrough(), "Page.getManifestIcons.params", "commandParams", { method: "Page.getManifestIcons" }); export const GetManifestIconsResult = withCdpMeta(z.object({ "primaryIcon": z.string().optional() }).passthrough(), "Page.getManifestIcons.result", "commandResult", { method: "Page.getManifestIcons" }); +export const GetManifestIconsCommand = withCdpCommand("Page.getManifestIcons", GetManifestIconsParams, GetManifestIconsResult); export const GetAppIdParams = withCdpMeta(z.object({ }).passthrough(), "Page.getAppId.params", "commandParams", { method: "Page.getAppId" }); export const GetAppIdResult = withCdpMeta(z.object({ "appId": z.string().optional(), "recommendedId": z.string().optional() }).passthrough(), "Page.getAppId.result", "commandResult", { method: "Page.getAppId" }); +export const GetAppIdCommand = withCdpCommand("Page.getAppId", GetAppIdParams, GetAppIdResult); export const GetAdScriptAncestryParams = withCdpMeta(z.object({ "frameId": z.lazy(() => FrameId) }).passthrough(), "Page.getAdScriptAncestry.params", "commandParams", { method: "Page.getAdScriptAncestry" }); export const GetAdScriptAncestryResult = withCdpMeta(z.object({ "adScriptAncestry": z.lazy(() => Network.AdAncestry).optional() }).passthrough(), "Page.getAdScriptAncestry.result", "commandResult", { method: "Page.getAdScriptAncestry" }); +export const GetAdScriptAncestryCommand = withCdpCommand("Page.getAdScriptAncestry", GetAdScriptAncestryParams, GetAdScriptAncestryResult); export const GetFrameTreeParams = withCdpMeta(z.object({ }).passthrough(), "Page.getFrameTree.params", "commandParams", { method: "Page.getFrameTree" }); export const GetFrameTreeResult = withCdpMeta(z.object({ "frameTree": z.lazy(() => FrameTree) }).passthrough(), "Page.getFrameTree.result", "commandResult", { method: "Page.getFrameTree" }); +export const GetFrameTreeCommand = withCdpCommand("Page.getFrameTree", GetFrameTreeParams, GetFrameTreeResult); export const GetLayoutMetricsParams = withCdpMeta(z.object({ }).passthrough(), "Page.getLayoutMetrics.params", "commandParams", { method: "Page.getLayoutMetrics" }); export const GetLayoutMetricsResult = withCdpMeta(z.object({ "layoutViewport": z.lazy(() => LayoutViewport), "visualViewport": z.lazy(() => VisualViewport), "contentSize": z.lazy(() => DOM.Rect), "cssLayoutViewport": z.lazy(() => LayoutViewport), "cssVisualViewport": z.lazy(() => VisualViewport), "cssContentSize": z.lazy(() => DOM.Rect) }).passthrough(), "Page.getLayoutMetrics.result", "commandResult", { method: "Page.getLayoutMetrics" }); +export const GetLayoutMetricsCommand = withCdpCommand("Page.getLayoutMetrics", GetLayoutMetricsParams, GetLayoutMetricsResult); export const GetNavigationHistoryParams = withCdpMeta(z.object({ }).passthrough(), "Page.getNavigationHistory.params", "commandParams", { method: "Page.getNavigationHistory" }); export const GetNavigationHistoryResult = withCdpMeta(z.object({ "currentIndex": z.number().int(), "entries": z.array(z.lazy(() => NavigationEntry)) }).passthrough(), "Page.getNavigationHistory.result", "commandResult", { method: "Page.getNavigationHistory" }); +export const GetNavigationHistoryCommand = withCdpCommand("Page.getNavigationHistory", GetNavigationHistoryParams, GetNavigationHistoryResult); export const ResetNavigationHistoryParams = withCdpMeta(z.object({ }).passthrough(), "Page.resetNavigationHistory.params", "commandParams", { method: "Page.resetNavigationHistory" }); export const ResetNavigationHistoryResult = withCdpMeta(z.object({ }).passthrough(), "Page.resetNavigationHistory.result", "commandResult", { method: "Page.resetNavigationHistory" }); +export const ResetNavigationHistoryCommand = withCdpCommand("Page.resetNavigationHistory", ResetNavigationHistoryParams, ResetNavigationHistoryResult); export const GetResourceContentParams = withCdpMeta(z.object({ "frameId": z.lazy(() => FrameId), "url": z.string() }).passthrough(), "Page.getResourceContent.params", "commandParams", { method: "Page.getResourceContent" }); export const GetResourceContentResult = withCdpMeta(z.object({ "content": z.string(), "base64Encoded": z.boolean() }).passthrough(), "Page.getResourceContent.result", "commandResult", { method: "Page.getResourceContent" }); +export const GetResourceContentCommand = withCdpCommand("Page.getResourceContent", GetResourceContentParams, GetResourceContentResult); export const GetResourceTreeParams = withCdpMeta(z.object({ }).passthrough(), "Page.getResourceTree.params", "commandParams", { method: "Page.getResourceTree" }); export const GetResourceTreeResult = withCdpMeta(z.object({ "frameTree": z.lazy(() => FrameResourceTree) }).passthrough(), "Page.getResourceTree.result", "commandResult", { method: "Page.getResourceTree" }); +export const GetResourceTreeCommand = withCdpCommand("Page.getResourceTree", GetResourceTreeParams, GetResourceTreeResult); export const HandleJavaScriptDialogParams = withCdpMeta(z.object({ "accept": z.boolean(), "promptText": z.string().optional() }).passthrough(), "Page.handleJavaScriptDialog.params", "commandParams", { method: "Page.handleJavaScriptDialog" }); export const HandleJavaScriptDialogResult = withCdpMeta(z.object({ }).passthrough(), "Page.handleJavaScriptDialog.result", "commandResult", { method: "Page.handleJavaScriptDialog" }); +export const HandleJavaScriptDialogCommand = withCdpCommand("Page.handleJavaScriptDialog", HandleJavaScriptDialogParams, HandleJavaScriptDialogResult); export const NavigateParams = withCdpMeta(z.object({ "url": z.string(), "referrer": z.string().optional(), "transitionType": z.lazy(() => TransitionType).optional(), "frameId": z.lazy(() => FrameId).optional(), "referrerPolicy": z.lazy(() => ReferrerPolicy).optional() }).passthrough(), "Page.navigate.params", "commandParams", { method: "Page.navigate" }); export const NavigateResult = withCdpMeta(z.object({ "frameId": z.lazy(() => FrameId), "loaderId": z.lazy(() => Network.LoaderId).optional(), "errorText": z.string().optional(), "isDownload": z.boolean().optional() }).passthrough(), "Page.navigate.result", "commandResult", { method: "Page.navigate" }); +export const NavigateCommand = withCdpCommand("Page.navigate", NavigateParams, NavigateResult); export const NavigateToHistoryEntryParams = withCdpMeta(z.object({ "entryId": z.number().int() }).passthrough(), "Page.navigateToHistoryEntry.params", "commandParams", { method: "Page.navigateToHistoryEntry" }); export const NavigateToHistoryEntryResult = withCdpMeta(z.object({ }).passthrough(), "Page.navigateToHistoryEntry.result", "commandResult", { method: "Page.navigateToHistoryEntry" }); +export const NavigateToHistoryEntryCommand = withCdpCommand("Page.navigateToHistoryEntry", NavigateToHistoryEntryParams, NavigateToHistoryEntryResult); export const PrintToPDFParams = withCdpMeta(z.object({ "landscape": z.boolean().optional(), "displayHeaderFooter": z.boolean().optional(), "printBackground": z.boolean().optional(), "scale": z.number().optional(), "paperWidth": z.number().optional(), "paperHeight": z.number().optional(), "marginTop": z.number().optional(), "marginBottom": z.number().optional(), "marginLeft": z.number().optional(), "marginRight": z.number().optional(), "pageRanges": z.string().optional(), "headerTemplate": z.string().optional(), "footerTemplate": z.string().optional(), "preferCSSPageSize": z.boolean().optional(), "transferMode": z.enum(["ReturnAsBase64", "ReturnAsStream"]).optional(), "generateTaggedPDF": z.boolean().optional(), "generateDocumentOutline": z.boolean().optional() }).passthrough(), "Page.printToPDF.params", "commandParams", { method: "Page.printToPDF" }); export const PrintToPDFResult = withCdpMeta(z.object({ "data": z.string(), "stream": z.lazy(() => IO.StreamHandle).optional() }).passthrough(), "Page.printToPDF.result", "commandResult", { method: "Page.printToPDF" }); +export const PrintToPDFCommand = withCdpCommand("Page.printToPDF", PrintToPDFParams, PrintToPDFResult); export const ReloadParams = withCdpMeta(z.object({ "ignoreCache": z.boolean().optional(), "scriptToEvaluateOnLoad": z.string().optional(), "loaderId": z.lazy(() => Network.LoaderId).optional() }).passthrough(), "Page.reload.params", "commandParams", { method: "Page.reload" }); export const ReloadResult = withCdpMeta(z.object({ }).passthrough(), "Page.reload.result", "commandResult", { method: "Page.reload" }); +export const ReloadCommand = withCdpCommand("Page.reload", ReloadParams, ReloadResult); export const RemoveScriptToEvaluateOnLoadParams = withCdpMeta(z.object({ "identifier": z.lazy(() => ScriptIdentifier) }).passthrough(), "Page.removeScriptToEvaluateOnLoad.params", "commandParams", { method: "Page.removeScriptToEvaluateOnLoad" }); export const RemoveScriptToEvaluateOnLoadResult = withCdpMeta(z.object({ }).passthrough(), "Page.removeScriptToEvaluateOnLoad.result", "commandResult", { method: "Page.removeScriptToEvaluateOnLoad" }); +export const RemoveScriptToEvaluateOnLoadCommand = withCdpCommand("Page.removeScriptToEvaluateOnLoad", RemoveScriptToEvaluateOnLoadParams, RemoveScriptToEvaluateOnLoadResult); export const RemoveScriptToEvaluateOnNewDocumentParams = withCdpMeta(z.object({ "identifier": z.lazy(() => ScriptIdentifier) }).passthrough(), "Page.removeScriptToEvaluateOnNewDocument.params", "commandParams", { method: "Page.removeScriptToEvaluateOnNewDocument" }); export const RemoveScriptToEvaluateOnNewDocumentResult = withCdpMeta(z.object({ }).passthrough(), "Page.removeScriptToEvaluateOnNewDocument.result", "commandResult", { method: "Page.removeScriptToEvaluateOnNewDocument" }); +export const RemoveScriptToEvaluateOnNewDocumentCommand = withCdpCommand("Page.removeScriptToEvaluateOnNewDocument", RemoveScriptToEvaluateOnNewDocumentParams, RemoveScriptToEvaluateOnNewDocumentResult); export const ScreencastFrameAckParams = withCdpMeta(z.object({ "sessionId": z.number().int() }).passthrough(), "Page.screencastFrameAck.params", "commandParams", { method: "Page.screencastFrameAck" }); export const ScreencastFrameAckResult = withCdpMeta(z.object({ }).passthrough(), "Page.screencastFrameAck.result", "commandResult", { method: "Page.screencastFrameAck" }); +export const ScreencastFrameAckCommand = withCdpCommand("Page.screencastFrameAck", ScreencastFrameAckParams, ScreencastFrameAckResult); export const SearchInResourceParams = withCdpMeta(z.object({ "frameId": z.lazy(() => FrameId), "url": z.string(), "query": z.string(), "caseSensitive": z.boolean().optional(), "isRegex": z.boolean().optional() }).passthrough(), "Page.searchInResource.params", "commandParams", { method: "Page.searchInResource" }); export const SearchInResourceResult = withCdpMeta(z.object({ "result": z.array(z.lazy(() => Debugger.SearchMatch)) }).passthrough(), "Page.searchInResource.result", "commandResult", { method: "Page.searchInResource" }); +export const SearchInResourceCommand = withCdpCommand("Page.searchInResource", SearchInResourceParams, SearchInResourceResult); export const SetAdBlockingEnabledParams = withCdpMeta(z.object({ "enabled": z.boolean() }).passthrough(), "Page.setAdBlockingEnabled.params", "commandParams", { method: "Page.setAdBlockingEnabled" }); export const SetAdBlockingEnabledResult = withCdpMeta(z.object({ }).passthrough(), "Page.setAdBlockingEnabled.result", "commandResult", { method: "Page.setAdBlockingEnabled" }); +export const SetAdBlockingEnabledCommand = withCdpCommand("Page.setAdBlockingEnabled", SetAdBlockingEnabledParams, SetAdBlockingEnabledResult); export const SetBypassCSPParams = withCdpMeta(z.object({ "enabled": z.boolean() }).passthrough(), "Page.setBypassCSP.params", "commandParams", { method: "Page.setBypassCSP" }); export const SetBypassCSPResult = withCdpMeta(z.object({ }).passthrough(), "Page.setBypassCSP.result", "commandResult", { method: "Page.setBypassCSP" }); +export const SetBypassCSPCommand = withCdpCommand("Page.setBypassCSP", SetBypassCSPParams, SetBypassCSPResult); export const GetPermissionsPolicyStateParams = withCdpMeta(z.object({ "frameId": z.lazy(() => FrameId) }).passthrough(), "Page.getPermissionsPolicyState.params", "commandParams", { method: "Page.getPermissionsPolicyState" }); export const GetPermissionsPolicyStateResult = withCdpMeta(z.object({ "states": z.array(z.lazy(() => PermissionsPolicyFeatureState)) }).passthrough(), "Page.getPermissionsPolicyState.result", "commandResult", { method: "Page.getPermissionsPolicyState" }); +export const GetPermissionsPolicyStateCommand = withCdpCommand("Page.getPermissionsPolicyState", GetPermissionsPolicyStateParams, GetPermissionsPolicyStateResult); export const GetOriginTrialsParams = withCdpMeta(z.object({ "frameId": z.lazy(() => FrameId) }).passthrough(), "Page.getOriginTrials.params", "commandParams", { method: "Page.getOriginTrials" }); export const GetOriginTrialsResult = withCdpMeta(z.object({ "originTrials": z.array(z.lazy(() => OriginTrial)) }).passthrough(), "Page.getOriginTrials.result", "commandResult", { method: "Page.getOriginTrials" }); +export const GetOriginTrialsCommand = withCdpCommand("Page.getOriginTrials", GetOriginTrialsParams, GetOriginTrialsResult); export const SetDeviceMetricsOverrideParams = withCdpMeta(z.object({ "width": z.number().int(), "height": z.number().int(), "deviceScaleFactor": z.number(), "mobile": z.boolean(), "scale": z.number().optional(), "screenWidth": z.number().int().optional(), "screenHeight": z.number().int().optional(), "positionX": z.number().int().optional(), "positionY": z.number().int().optional(), "dontSetVisibleSize": z.boolean().optional(), "screenOrientation": z.lazy(() => Emulation.ScreenOrientation).optional(), "viewport": z.lazy(() => Viewport).optional() }).passthrough(), "Page.setDeviceMetricsOverride.params", "commandParams", { method: "Page.setDeviceMetricsOverride" }); export const SetDeviceMetricsOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Page.setDeviceMetricsOverride.result", "commandResult", { method: "Page.setDeviceMetricsOverride" }); +export const SetDeviceMetricsOverrideCommand = withCdpCommand("Page.setDeviceMetricsOverride", SetDeviceMetricsOverrideParams, SetDeviceMetricsOverrideResult); export const SetDeviceOrientationOverrideParams = withCdpMeta(z.object({ "alpha": z.number(), "beta": z.number(), "gamma": z.number() }).passthrough(), "Page.setDeviceOrientationOverride.params", "commandParams", { method: "Page.setDeviceOrientationOverride" }); export const SetDeviceOrientationOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Page.setDeviceOrientationOverride.result", "commandResult", { method: "Page.setDeviceOrientationOverride" }); +export const SetDeviceOrientationOverrideCommand = withCdpCommand("Page.setDeviceOrientationOverride", SetDeviceOrientationOverrideParams, SetDeviceOrientationOverrideResult); export const SetFontFamiliesParams = withCdpMeta(z.object({ "fontFamilies": z.lazy(() => FontFamilies), "forScripts": z.array(z.lazy(() => ScriptFontFamilies)).optional() }).passthrough(), "Page.setFontFamilies.params", "commandParams", { method: "Page.setFontFamilies" }); export const SetFontFamiliesResult = withCdpMeta(z.object({ }).passthrough(), "Page.setFontFamilies.result", "commandResult", { method: "Page.setFontFamilies" }); +export const SetFontFamiliesCommand = withCdpCommand("Page.setFontFamilies", SetFontFamiliesParams, SetFontFamiliesResult); export const SetFontSizesParams = withCdpMeta(z.object({ "fontSizes": z.lazy(() => FontSizes) }).passthrough(), "Page.setFontSizes.params", "commandParams", { method: "Page.setFontSizes" }); export const SetFontSizesResult = withCdpMeta(z.object({ }).passthrough(), "Page.setFontSizes.result", "commandResult", { method: "Page.setFontSizes" }); +export const SetFontSizesCommand = withCdpCommand("Page.setFontSizes", SetFontSizesParams, SetFontSizesResult); export const SetDocumentContentParams = withCdpMeta(z.object({ "frameId": z.lazy(() => FrameId), "html": z.string() }).passthrough(), "Page.setDocumentContent.params", "commandParams", { method: "Page.setDocumentContent" }); export const SetDocumentContentResult = withCdpMeta(z.object({ }).passthrough(), "Page.setDocumentContent.result", "commandResult", { method: "Page.setDocumentContent" }); +export const SetDocumentContentCommand = withCdpCommand("Page.setDocumentContent", SetDocumentContentParams, SetDocumentContentResult); export const SetDownloadBehaviorParams = withCdpMeta(z.object({ "behavior": z.enum(["deny", "allow", "default"]), "downloadPath": z.string().optional() }).passthrough(), "Page.setDownloadBehavior.params", "commandParams", { method: "Page.setDownloadBehavior" }); export const SetDownloadBehaviorResult = withCdpMeta(z.object({ }).passthrough(), "Page.setDownloadBehavior.result", "commandResult", { method: "Page.setDownloadBehavior" }); +export const SetDownloadBehaviorCommand = withCdpCommand("Page.setDownloadBehavior", SetDownloadBehaviorParams, SetDownloadBehaviorResult); export const SetGeolocationOverrideParams = withCdpMeta(z.object({ "latitude": z.number().optional(), "longitude": z.number().optional(), "accuracy": z.number().optional() }).passthrough(), "Page.setGeolocationOverride.params", "commandParams", { method: "Page.setGeolocationOverride" }); export const SetGeolocationOverrideResult = withCdpMeta(z.object({ }).passthrough(), "Page.setGeolocationOverride.result", "commandResult", { method: "Page.setGeolocationOverride" }); +export const SetGeolocationOverrideCommand = withCdpCommand("Page.setGeolocationOverride", SetGeolocationOverrideParams, SetGeolocationOverrideResult); export const SetLifecycleEventsEnabledParams = withCdpMeta(z.object({ "enabled": z.boolean() }).passthrough(), "Page.setLifecycleEventsEnabled.params", "commandParams", { method: "Page.setLifecycleEventsEnabled" }); export const SetLifecycleEventsEnabledResult = withCdpMeta(z.object({ }).passthrough(), "Page.setLifecycleEventsEnabled.result", "commandResult", { method: "Page.setLifecycleEventsEnabled" }); +export const SetLifecycleEventsEnabledCommand = withCdpCommand("Page.setLifecycleEventsEnabled", SetLifecycleEventsEnabledParams, SetLifecycleEventsEnabledResult); export const SetTouchEmulationEnabledParams = withCdpMeta(z.object({ "enabled": z.boolean(), "configuration": z.enum(["mobile", "desktop"]).optional() }).passthrough(), "Page.setTouchEmulationEnabled.params", "commandParams", { method: "Page.setTouchEmulationEnabled" }); export const SetTouchEmulationEnabledResult = withCdpMeta(z.object({ }).passthrough(), "Page.setTouchEmulationEnabled.result", "commandResult", { method: "Page.setTouchEmulationEnabled" }); +export const SetTouchEmulationEnabledCommand = withCdpCommand("Page.setTouchEmulationEnabled", SetTouchEmulationEnabledParams, SetTouchEmulationEnabledResult); export const StartScreencastParams = withCdpMeta(z.object({ "format": z.enum(["jpeg", "png"]).optional(), "quality": z.number().int().optional(), "maxWidth": z.number().int().optional(), "maxHeight": z.number().int().optional(), "everyNthFrame": z.number().int().optional() }).passthrough(), "Page.startScreencast.params", "commandParams", { method: "Page.startScreencast" }); export const StartScreencastResult = withCdpMeta(z.object({ }).passthrough(), "Page.startScreencast.result", "commandResult", { method: "Page.startScreencast" }); +export const StartScreencastCommand = withCdpCommand("Page.startScreencast", StartScreencastParams, StartScreencastResult); export const StopLoadingParams = withCdpMeta(z.object({ }).passthrough(), "Page.stopLoading.params", "commandParams", { method: "Page.stopLoading" }); export const StopLoadingResult = withCdpMeta(z.object({ }).passthrough(), "Page.stopLoading.result", "commandResult", { method: "Page.stopLoading" }); +export const StopLoadingCommand = withCdpCommand("Page.stopLoading", StopLoadingParams, StopLoadingResult); export const CrashParams = withCdpMeta(z.object({ }).passthrough(), "Page.crash.params", "commandParams", { method: "Page.crash" }); export const CrashResult = withCdpMeta(z.object({ }).passthrough(), "Page.crash.result", "commandResult", { method: "Page.crash" }); +export const CrashCommand = withCdpCommand("Page.crash", CrashParams, CrashResult); export const CloseParams = withCdpMeta(z.object({ }).passthrough(), "Page.close.params", "commandParams", { method: "Page.close" }); export const CloseResult = withCdpMeta(z.object({ }).passthrough(), "Page.close.result", "commandResult", { method: "Page.close" }); +export const CloseCommand = withCdpCommand("Page.close", CloseParams, CloseResult); export const SetWebLifecycleStateParams = withCdpMeta(z.object({ "state": z.enum(["frozen", "active"]) }).passthrough(), "Page.setWebLifecycleState.params", "commandParams", { method: "Page.setWebLifecycleState" }); export const SetWebLifecycleStateResult = withCdpMeta(z.object({ }).passthrough(), "Page.setWebLifecycleState.result", "commandResult", { method: "Page.setWebLifecycleState" }); +export const SetWebLifecycleStateCommand = withCdpCommand("Page.setWebLifecycleState", SetWebLifecycleStateParams, SetWebLifecycleStateResult); export const StopScreencastParams = withCdpMeta(z.object({ }).passthrough(), "Page.stopScreencast.params", "commandParams", { method: "Page.stopScreencast" }); export const StopScreencastResult = withCdpMeta(z.object({ }).passthrough(), "Page.stopScreencast.result", "commandResult", { method: "Page.stopScreencast" }); +export const StopScreencastCommand = withCdpCommand("Page.stopScreencast", StopScreencastParams, StopScreencastResult); export const ProduceCompilationCacheParams = withCdpMeta(z.object({ "scripts": z.array(z.lazy(() => CompilationCacheParams)) }).passthrough(), "Page.produceCompilationCache.params", "commandParams", { method: "Page.produceCompilationCache" }); export const ProduceCompilationCacheResult = withCdpMeta(z.object({ }).passthrough(), "Page.produceCompilationCache.result", "commandResult", { method: "Page.produceCompilationCache" }); +export const ProduceCompilationCacheCommand = withCdpCommand("Page.produceCompilationCache", ProduceCompilationCacheParams, ProduceCompilationCacheResult); export const AddCompilationCacheParams = withCdpMeta(z.object({ "url": z.string(), "data": z.string() }).passthrough(), "Page.addCompilationCache.params", "commandParams", { method: "Page.addCompilationCache" }); export const AddCompilationCacheResult = withCdpMeta(z.object({ }).passthrough(), "Page.addCompilationCache.result", "commandResult", { method: "Page.addCompilationCache" }); +export const AddCompilationCacheCommand = withCdpCommand("Page.addCompilationCache", AddCompilationCacheParams, AddCompilationCacheResult); export const ClearCompilationCacheParams = withCdpMeta(z.object({ }).passthrough(), "Page.clearCompilationCache.params", "commandParams", { method: "Page.clearCompilationCache" }); export const ClearCompilationCacheResult = withCdpMeta(z.object({ }).passthrough(), "Page.clearCompilationCache.result", "commandResult", { method: "Page.clearCompilationCache" }); +export const ClearCompilationCacheCommand = withCdpCommand("Page.clearCompilationCache", ClearCompilationCacheParams, ClearCompilationCacheResult); export const SetSPCTransactionModeParams = withCdpMeta(z.object({ "mode": z.enum(["none", "autoAccept", "autoChooseToAuthAnotherWay", "autoReject", "autoOptOut"]) }).passthrough(), "Page.setSPCTransactionMode.params", "commandParams", { method: "Page.setSPCTransactionMode" }); export const SetSPCTransactionModeResult = withCdpMeta(z.object({ }).passthrough(), "Page.setSPCTransactionMode.result", "commandResult", { method: "Page.setSPCTransactionMode" }); +export const SetSPCTransactionModeCommand = withCdpCommand("Page.setSPCTransactionMode", SetSPCTransactionModeParams, SetSPCTransactionModeResult); export const SetRPHRegistrationModeParams = withCdpMeta(z.object({ "mode": z.enum(["none", "autoAccept", "autoReject"]) }).passthrough(), "Page.setRPHRegistrationMode.params", "commandParams", { method: "Page.setRPHRegistrationMode" }); export const SetRPHRegistrationModeResult = withCdpMeta(z.object({ }).passthrough(), "Page.setRPHRegistrationMode.result", "commandResult", { method: "Page.setRPHRegistrationMode" }); +export const SetRPHRegistrationModeCommand = withCdpCommand("Page.setRPHRegistrationMode", SetRPHRegistrationModeParams, SetRPHRegistrationModeResult); export const GenerateTestReportParams = withCdpMeta(z.object({ "message": z.string(), "group": z.string().optional() }).passthrough(), "Page.generateTestReport.params", "commandParams", { method: "Page.generateTestReport" }); export const GenerateTestReportResult = withCdpMeta(z.object({ }).passthrough(), "Page.generateTestReport.result", "commandResult", { method: "Page.generateTestReport" }); +export const GenerateTestReportCommand = withCdpCommand("Page.generateTestReport", GenerateTestReportParams, GenerateTestReportResult); export const WaitForDebuggerParams = withCdpMeta(z.object({ }).passthrough(), "Page.waitForDebugger.params", "commandParams", { method: "Page.waitForDebugger" }); export const WaitForDebuggerResult = withCdpMeta(z.object({ }).passthrough(), "Page.waitForDebugger.result", "commandResult", { method: "Page.waitForDebugger" }); +export const WaitForDebuggerCommand = withCdpCommand("Page.waitForDebugger", WaitForDebuggerParams, WaitForDebuggerResult); export const SetInterceptFileChooserDialogParams = withCdpMeta(z.object({ "enabled": z.boolean(), "cancel": z.boolean().optional() }).passthrough(), "Page.setInterceptFileChooserDialog.params", "commandParams", { method: "Page.setInterceptFileChooserDialog" }); export const SetInterceptFileChooserDialogResult = withCdpMeta(z.object({ }).passthrough(), "Page.setInterceptFileChooserDialog.result", "commandResult", { method: "Page.setInterceptFileChooserDialog" }); +export const SetInterceptFileChooserDialogCommand = withCdpCommand("Page.setInterceptFileChooserDialog", SetInterceptFileChooserDialogParams, SetInterceptFileChooserDialogResult); export const SetPrerenderingAllowedParams = withCdpMeta(z.object({ "isAllowed": z.boolean() }).passthrough(), "Page.setPrerenderingAllowed.params", "commandParams", { method: "Page.setPrerenderingAllowed" }); export const SetPrerenderingAllowedResult = withCdpMeta(z.object({ }).passthrough(), "Page.setPrerenderingAllowed.result", "commandResult", { method: "Page.setPrerenderingAllowed" }); +export const SetPrerenderingAllowedCommand = withCdpCommand("Page.setPrerenderingAllowed", SetPrerenderingAllowedParams, SetPrerenderingAllowedResult); export const GetAnnotatedPageContentParams = withCdpMeta(z.object({ "includeActionableInformation": z.boolean().optional() }).passthrough(), "Page.getAnnotatedPageContent.params", "commandParams", { method: "Page.getAnnotatedPageContent" }); export const GetAnnotatedPageContentResult = withCdpMeta(z.object({ "content": z.string() }).passthrough(), "Page.getAnnotatedPageContent.result", "commandResult", { method: "Page.getAnnotatedPageContent" }); +export const GetAnnotatedPageContentCommand = withCdpCommand("Page.getAnnotatedPageContent", GetAnnotatedPageContentParams, GetAnnotatedPageContentResult); export const DomContentEventFiredEvent = withCdpMeta(z.object({ "timestamp": z.lazy(() => Network.MonotonicTime) }).passthrough(), "Page.domContentEventFired", "event", { phase: "event" }); export const FileChooserOpenedEvent = withCdpMeta(z.object({ "frameId": z.lazy(() => FrameId), "mode": z.enum(["selectSingle", "selectMultiple"]), "backendNodeId": z.lazy(() => DOM.BackendNodeId).optional() }).passthrough(), "Page.fileChooserOpened", "event", { phase: "event" }); export const FrameAttachedEvent = withCdpMeta(z.object({ "frameId": z.lazy(() => FrameId), "parentFrameId": z.lazy(() => FrameId), "stack": z.lazy(() => Runtime.StackTrace).optional() }).passthrough(), "Page.frameAttached", "event", { phase: "event" }); @@ -429,67 +490,67 @@ export const zod = { CompilationCacheProducedEvent: CompilationCacheProducedEvent, } as const; export const commands = { - "Page.addScriptToEvaluateOnLoad": { params: AddScriptToEvaluateOnLoadParams, result: AddScriptToEvaluateOnLoadResult }, - "Page.addScriptToEvaluateOnNewDocument": { params: AddScriptToEvaluateOnNewDocumentParams, result: AddScriptToEvaluateOnNewDocumentResult }, - "Page.bringToFront": { params: BringToFrontParams, result: BringToFrontResult }, - "Page.captureScreenshot": { params: CaptureScreenshotParams, result: CaptureScreenshotResult }, - "Page.captureSnapshot": { params: CaptureSnapshotParams, result: CaptureSnapshotResult }, - "Page.clearDeviceMetricsOverride": { params: ClearDeviceMetricsOverrideParams, result: ClearDeviceMetricsOverrideResult }, - "Page.clearDeviceOrientationOverride": { params: ClearDeviceOrientationOverrideParams, result: ClearDeviceOrientationOverrideResult }, - "Page.clearGeolocationOverride": { params: ClearGeolocationOverrideParams, result: ClearGeolocationOverrideResult }, - "Page.createIsolatedWorld": { params: CreateIsolatedWorldParams, result: CreateIsolatedWorldResult }, - "Page.deleteCookie": { params: DeleteCookieParams, result: DeleteCookieResult }, - "Page.disable": { params: DisableParams, result: DisableResult }, - "Page.enable": { params: EnableParams, result: EnableResult }, - "Page.getAppManifest": { params: GetAppManifestParams, result: GetAppManifestResult }, - "Page.getInstallabilityErrors": { params: GetInstallabilityErrorsParams, result: GetInstallabilityErrorsResult }, - "Page.getManifestIcons": { params: GetManifestIconsParams, result: GetManifestIconsResult }, - "Page.getAppId": { params: GetAppIdParams, result: GetAppIdResult }, - "Page.getAdScriptAncestry": { params: GetAdScriptAncestryParams, result: GetAdScriptAncestryResult }, - "Page.getFrameTree": { params: GetFrameTreeParams, result: GetFrameTreeResult }, - "Page.getLayoutMetrics": { params: GetLayoutMetricsParams, result: GetLayoutMetricsResult }, - "Page.getNavigationHistory": { params: GetNavigationHistoryParams, result: GetNavigationHistoryResult }, - "Page.resetNavigationHistory": { params: ResetNavigationHistoryParams, result: ResetNavigationHistoryResult }, - "Page.getResourceContent": { params: GetResourceContentParams, result: GetResourceContentResult }, - "Page.getResourceTree": { params: GetResourceTreeParams, result: GetResourceTreeResult }, - "Page.handleJavaScriptDialog": { params: HandleJavaScriptDialogParams, result: HandleJavaScriptDialogResult }, - "Page.navigate": { params: NavigateParams, result: NavigateResult }, - "Page.navigateToHistoryEntry": { params: NavigateToHistoryEntryParams, result: NavigateToHistoryEntryResult }, - "Page.printToPDF": { params: PrintToPDFParams, result: PrintToPDFResult }, - "Page.reload": { params: ReloadParams, result: ReloadResult }, - "Page.removeScriptToEvaluateOnLoad": { params: RemoveScriptToEvaluateOnLoadParams, result: RemoveScriptToEvaluateOnLoadResult }, - "Page.removeScriptToEvaluateOnNewDocument": { params: RemoveScriptToEvaluateOnNewDocumentParams, result: RemoveScriptToEvaluateOnNewDocumentResult }, - "Page.screencastFrameAck": { params: ScreencastFrameAckParams, result: ScreencastFrameAckResult }, - "Page.searchInResource": { params: SearchInResourceParams, result: SearchInResourceResult }, - "Page.setAdBlockingEnabled": { params: SetAdBlockingEnabledParams, result: SetAdBlockingEnabledResult }, - "Page.setBypassCSP": { params: SetBypassCSPParams, result: SetBypassCSPResult }, - "Page.getPermissionsPolicyState": { params: GetPermissionsPolicyStateParams, result: GetPermissionsPolicyStateResult }, - "Page.getOriginTrials": { params: GetOriginTrialsParams, result: GetOriginTrialsResult }, - "Page.setDeviceMetricsOverride": { params: SetDeviceMetricsOverrideParams, result: SetDeviceMetricsOverrideResult }, - "Page.setDeviceOrientationOverride": { params: SetDeviceOrientationOverrideParams, result: SetDeviceOrientationOverrideResult }, - "Page.setFontFamilies": { params: SetFontFamiliesParams, result: SetFontFamiliesResult }, - "Page.setFontSizes": { params: SetFontSizesParams, result: SetFontSizesResult }, - "Page.setDocumentContent": { params: SetDocumentContentParams, result: SetDocumentContentResult }, - "Page.setDownloadBehavior": { params: SetDownloadBehaviorParams, result: SetDownloadBehaviorResult }, - "Page.setGeolocationOverride": { params: SetGeolocationOverrideParams, result: SetGeolocationOverrideResult }, - "Page.setLifecycleEventsEnabled": { params: SetLifecycleEventsEnabledParams, result: SetLifecycleEventsEnabledResult }, - "Page.setTouchEmulationEnabled": { params: SetTouchEmulationEnabledParams, result: SetTouchEmulationEnabledResult }, - "Page.startScreencast": { params: StartScreencastParams, result: StartScreencastResult }, - "Page.stopLoading": { params: StopLoadingParams, result: StopLoadingResult }, - "Page.crash": { params: CrashParams, result: CrashResult }, - "Page.close": { params: CloseParams, result: CloseResult }, - "Page.setWebLifecycleState": { params: SetWebLifecycleStateParams, result: SetWebLifecycleStateResult }, - "Page.stopScreencast": { params: StopScreencastParams, result: StopScreencastResult }, - "Page.produceCompilationCache": { params: ProduceCompilationCacheParams, result: ProduceCompilationCacheResult }, - "Page.addCompilationCache": { params: AddCompilationCacheParams, result: AddCompilationCacheResult }, - "Page.clearCompilationCache": { params: ClearCompilationCacheParams, result: ClearCompilationCacheResult }, - "Page.setSPCTransactionMode": { params: SetSPCTransactionModeParams, result: SetSPCTransactionModeResult }, - "Page.setRPHRegistrationMode": { params: SetRPHRegistrationModeParams, result: SetRPHRegistrationModeResult }, - "Page.generateTestReport": { params: GenerateTestReportParams, result: GenerateTestReportResult }, - "Page.waitForDebugger": { params: WaitForDebuggerParams, result: WaitForDebuggerResult }, - "Page.setInterceptFileChooserDialog": { params: SetInterceptFileChooserDialogParams, result: SetInterceptFileChooserDialogResult }, - "Page.setPrerenderingAllowed": { params: SetPrerenderingAllowedParams, result: SetPrerenderingAllowedResult }, - "Page.getAnnotatedPageContent": { params: GetAnnotatedPageContentParams, result: GetAnnotatedPageContentResult }, + "Page.addScriptToEvaluateOnLoad": AddScriptToEvaluateOnLoadCommand, + "Page.addScriptToEvaluateOnNewDocument": AddScriptToEvaluateOnNewDocumentCommand, + "Page.bringToFront": BringToFrontCommand, + "Page.captureScreenshot": CaptureScreenshotCommand, + "Page.captureSnapshot": CaptureSnapshotCommand, + "Page.clearDeviceMetricsOverride": ClearDeviceMetricsOverrideCommand, + "Page.clearDeviceOrientationOverride": ClearDeviceOrientationOverrideCommand, + "Page.clearGeolocationOverride": ClearGeolocationOverrideCommand, + "Page.createIsolatedWorld": CreateIsolatedWorldCommand, + "Page.deleteCookie": DeleteCookieCommand, + "Page.disable": DisableCommand, + "Page.enable": EnableCommand, + "Page.getAppManifest": GetAppManifestCommand, + "Page.getInstallabilityErrors": GetInstallabilityErrorsCommand, + "Page.getManifestIcons": GetManifestIconsCommand, + "Page.getAppId": GetAppIdCommand, + "Page.getAdScriptAncestry": GetAdScriptAncestryCommand, + "Page.getFrameTree": GetFrameTreeCommand, + "Page.getLayoutMetrics": GetLayoutMetricsCommand, + "Page.getNavigationHistory": GetNavigationHistoryCommand, + "Page.resetNavigationHistory": ResetNavigationHistoryCommand, + "Page.getResourceContent": GetResourceContentCommand, + "Page.getResourceTree": GetResourceTreeCommand, + "Page.handleJavaScriptDialog": HandleJavaScriptDialogCommand, + "Page.navigate": NavigateCommand, + "Page.navigateToHistoryEntry": NavigateToHistoryEntryCommand, + "Page.printToPDF": PrintToPDFCommand, + "Page.reload": ReloadCommand, + "Page.removeScriptToEvaluateOnLoad": RemoveScriptToEvaluateOnLoadCommand, + "Page.removeScriptToEvaluateOnNewDocument": RemoveScriptToEvaluateOnNewDocumentCommand, + "Page.screencastFrameAck": ScreencastFrameAckCommand, + "Page.searchInResource": SearchInResourceCommand, + "Page.setAdBlockingEnabled": SetAdBlockingEnabledCommand, + "Page.setBypassCSP": SetBypassCSPCommand, + "Page.getPermissionsPolicyState": GetPermissionsPolicyStateCommand, + "Page.getOriginTrials": GetOriginTrialsCommand, + "Page.setDeviceMetricsOverride": SetDeviceMetricsOverrideCommand, + "Page.setDeviceOrientationOverride": SetDeviceOrientationOverrideCommand, + "Page.setFontFamilies": SetFontFamiliesCommand, + "Page.setFontSizes": SetFontSizesCommand, + "Page.setDocumentContent": SetDocumentContentCommand, + "Page.setDownloadBehavior": SetDownloadBehaviorCommand, + "Page.setGeolocationOverride": SetGeolocationOverrideCommand, + "Page.setLifecycleEventsEnabled": SetLifecycleEventsEnabledCommand, + "Page.setTouchEmulationEnabled": SetTouchEmulationEnabledCommand, + "Page.startScreencast": StartScreencastCommand, + "Page.stopLoading": StopLoadingCommand, + "Page.crash": CrashCommand, + "Page.close": CloseCommand, + "Page.setWebLifecycleState": SetWebLifecycleStateCommand, + "Page.stopScreencast": StopScreencastCommand, + "Page.produceCompilationCache": ProduceCompilationCacheCommand, + "Page.addCompilationCache": AddCompilationCacheCommand, + "Page.clearCompilationCache": ClearCompilationCacheCommand, + "Page.setSPCTransactionMode": SetSPCTransactionModeCommand, + "Page.setRPHRegistrationMode": SetRPHRegistrationModeCommand, + "Page.generateTestReport": GenerateTestReportCommand, + "Page.waitForDebugger": WaitForDebuggerCommand, + "Page.setInterceptFileChooserDialog": SetInterceptFileChooserDialogCommand, + "Page.setPrerenderingAllowed": SetPrerenderingAllowedCommand, + "Page.getAnnotatedPageContent": GetAnnotatedPageContentCommand, } as const; export const events = { "Page.domContentEventFired": DomContentEventFiredEvent, diff --git a/js/src/types/generated/zod/Performance.ts b/js/src/types/generated/zod/Performance.ts index 1374ed8..19f1775 100644 --- a/js/src/types/generated/zod/Performance.ts +++ b/js/src/types/generated/zod/Performance.ts @@ -1,17 +1,21 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const Metric = withCdpMeta(z.object({ "name": z.string(), "value": z.number() }).passthrough(), "Performance.Metric", "type"); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Performance.disable.params", "commandParams", { method: "Performance.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Performance.disable.result", "commandResult", { method: "Performance.disable" }); +export const DisableCommand = withCdpCommand("Performance.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ "timeDomain": z.enum(["timeTicks", "threadTicks"]).optional() }).passthrough(), "Performance.enable.params", "commandParams", { method: "Performance.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Performance.enable.result", "commandResult", { method: "Performance.enable" }); +export const EnableCommand = withCdpCommand("Performance.enable", EnableParams, EnableResult); export const SetTimeDomainParams = withCdpMeta(z.object({ "timeDomain": z.enum(["timeTicks", "threadTicks"]) }).passthrough(), "Performance.setTimeDomain.params", "commandParams", { method: "Performance.setTimeDomain" }); export const SetTimeDomainResult = withCdpMeta(z.object({ }).passthrough(), "Performance.setTimeDomain.result", "commandResult", { method: "Performance.setTimeDomain" }); +export const SetTimeDomainCommand = withCdpCommand("Performance.setTimeDomain", SetTimeDomainParams, SetTimeDomainResult); export const GetMetricsParams = withCdpMeta(z.object({ }).passthrough(), "Performance.getMetrics.params", "commandParams", { method: "Performance.getMetrics" }); export const GetMetricsResult = withCdpMeta(z.object({ "metrics": z.array(z.lazy(() => Metric)) }).passthrough(), "Performance.getMetrics.result", "commandResult", { method: "Performance.getMetrics" }); +export const GetMetricsCommand = withCdpCommand("Performance.getMetrics", GetMetricsParams, GetMetricsResult); export const MetricsEvent = withCdpMeta(z.object({ "metrics": z.array(z.lazy(() => Metric)), "title": z.string() }).passthrough(), "Performance.metrics", "event", { phase: "event" }); export const zod = { @@ -27,10 +31,10 @@ export const zod = { MetricsEvent: MetricsEvent, } as const; export const commands = { - "Performance.disable": { params: DisableParams, result: DisableResult }, - "Performance.enable": { params: EnableParams, result: EnableResult }, - "Performance.setTimeDomain": { params: SetTimeDomainParams, result: SetTimeDomainResult }, - "Performance.getMetrics": { params: GetMetricsParams, result: GetMetricsResult }, + "Performance.disable": DisableCommand, + "Performance.enable": EnableCommand, + "Performance.setTimeDomain": SetTimeDomainCommand, + "Performance.getMetrics": GetMetricsCommand, } as const; export const events = { "Performance.metrics": MetricsEvent, diff --git a/js/src/types/generated/zod/PerformanceTimeline.ts b/js/src/types/generated/zod/PerformanceTimeline.ts index efe9bde..d79df17 100644 --- a/js/src/types/generated/zod/PerformanceTimeline.ts +++ b/js/src/types/generated/zod/PerformanceTimeline.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; import * as Network from "./Network.js"; import * as Page from "./Page.js"; @@ -12,6 +12,7 @@ export const LayoutShift = withCdpMeta(z.object({ "value": z.number(), "hadRecen export const TimelineEvent = withCdpMeta(z.object({ "frameId": z.lazy(() => Page.FrameId), "type": z.string(), "name": z.string(), "time": z.lazy(() => Network.TimeSinceEpoch), "duration": z.number().optional(), "lcpDetails": z.lazy(() => LargestContentfulPaint).optional(), "layoutShiftDetails": z.lazy(() => LayoutShift).optional() }).passthrough(), "PerformanceTimeline.TimelineEvent", "type"); export const EnableParams = withCdpMeta(z.object({ "eventTypes": z.array(z.string()) }).passthrough(), "PerformanceTimeline.enable.params", "commandParams", { method: "PerformanceTimeline.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "PerformanceTimeline.enable.result", "commandResult", { method: "PerformanceTimeline.enable" }); +export const EnableCommand = withCdpCommand("PerformanceTimeline.enable", EnableParams, EnableResult); export const TimelineEventAddedEvent = withCdpMeta(z.object({ "event": z.lazy(() => TimelineEvent) }).passthrough(), "PerformanceTimeline.timelineEventAdded", "event", { phase: "event" }); export const zod = { @@ -24,7 +25,7 @@ export const zod = { TimelineEventAddedEvent: TimelineEventAddedEvent, } as const; export const commands = { - "PerformanceTimeline.enable": { params: EnableParams, result: EnableResult }, + "PerformanceTimeline.enable": EnableCommand, } as const; export const events = { "PerformanceTimeline.timelineEventAdded": TimelineEventAddedEvent, diff --git a/js/src/types/generated/zod/Preload.ts b/js/src/types/generated/zod/Preload.ts index 277bf93..87bf43f 100644 --- a/js/src/types/generated/zod/Preload.ts +++ b/js/src/types/generated/zod/Preload.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; import * as Network from "./Network.js"; import * as Page from "./Page.js"; @@ -20,8 +20,10 @@ export const PrefetchStatus = withCdpMeta(z.enum(["PrefetchAllowed", "PrefetchFa export const PrerenderMismatchedHeaders = withCdpMeta(z.object({ "headerName": z.string(), "initialValue": z.string().optional(), "activationValue": z.string().optional() }).passthrough(), "Preload.PrerenderMismatchedHeaders", "type"); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "Preload.enable.params", "commandParams", { method: "Preload.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Preload.enable.result", "commandResult", { method: "Preload.enable" }); +export const EnableCommand = withCdpCommand("Preload.enable", EnableParams, EnableResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Preload.disable.params", "commandParams", { method: "Preload.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Preload.disable.result", "commandResult", { method: "Preload.disable" }); +export const DisableCommand = withCdpCommand("Preload.disable", DisableParams, DisableResult); export const RuleSetUpdatedEvent = withCdpMeta(z.object({ "ruleSet": z.lazy(() => RuleSet) }).passthrough(), "Preload.ruleSetUpdated", "event", { phase: "event" }); export const RuleSetRemovedEvent = withCdpMeta(z.object({ "id": z.lazy(() => RuleSetId) }).passthrough(), "Preload.ruleSetRemoved", "event", { phase: "event" }); export const PreloadEnabledStateUpdatedEvent = withCdpMeta(z.object({ "disabledByPreference": z.boolean(), "disabledByDataSaver": z.boolean(), "disabledByBatterySaver": z.boolean(), "disabledByHoldbackPrefetchSpeculationRules": z.boolean(), "disabledByHoldbackPrerenderSpeculationRules": z.boolean() }).passthrough(), "Preload.preloadEnabledStateUpdated", "event", { phase: "event" }); @@ -54,8 +56,8 @@ export const zod = { PreloadingAttemptSourcesUpdatedEvent: PreloadingAttemptSourcesUpdatedEvent, } as const; export const commands = { - "Preload.enable": { params: EnableParams, result: EnableResult }, - "Preload.disable": { params: DisableParams, result: DisableResult }, + "Preload.enable": EnableCommand, + "Preload.disable": DisableCommand, } as const; export const events = { "Preload.ruleSetUpdated": RuleSetUpdatedEvent, diff --git a/js/src/types/generated/zod/Profiler.ts b/js/src/types/generated/zod/Profiler.ts index 48a0f9d..713f045 100644 --- a/js/src/types/generated/zod/Profiler.ts +++ b/js/src/types/generated/zod/Profiler.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Debugger from "./Debugger.js"; import * as Runtime from "./Runtime.js"; @@ -13,22 +13,31 @@ export const FunctionCoverage = withCdpMeta(z.object({ "functionName": z.string( export const ScriptCoverage = withCdpMeta(z.object({ "scriptId": z.lazy(() => Runtime.ScriptId), "url": z.string(), "functions": z.array(z.lazy(() => FunctionCoverage)) }).passthrough(), "Profiler.ScriptCoverage", "type"); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Profiler.disable.params", "commandParams", { method: "Profiler.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Profiler.disable.result", "commandResult", { method: "Profiler.disable" }); +export const DisableCommand = withCdpCommand("Profiler.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "Profiler.enable.params", "commandParams", { method: "Profiler.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Profiler.enable.result", "commandResult", { method: "Profiler.enable" }); +export const EnableCommand = withCdpCommand("Profiler.enable", EnableParams, EnableResult); export const GetBestEffortCoverageParams = withCdpMeta(z.object({ }).passthrough(), "Profiler.getBestEffortCoverage.params", "commandParams", { method: "Profiler.getBestEffortCoverage" }); export const GetBestEffortCoverageResult = withCdpMeta(z.object({ "result": z.array(z.lazy(() => ScriptCoverage)) }).passthrough(), "Profiler.getBestEffortCoverage.result", "commandResult", { method: "Profiler.getBestEffortCoverage" }); +export const GetBestEffortCoverageCommand = withCdpCommand("Profiler.getBestEffortCoverage", GetBestEffortCoverageParams, GetBestEffortCoverageResult); export const SetSamplingIntervalParams = withCdpMeta(z.object({ "interval": z.number().int() }).passthrough(), "Profiler.setSamplingInterval.params", "commandParams", { method: "Profiler.setSamplingInterval" }); export const SetSamplingIntervalResult = withCdpMeta(z.object({ }).passthrough(), "Profiler.setSamplingInterval.result", "commandResult", { method: "Profiler.setSamplingInterval" }); +export const SetSamplingIntervalCommand = withCdpCommand("Profiler.setSamplingInterval", SetSamplingIntervalParams, SetSamplingIntervalResult); export const StartParams = withCdpMeta(z.object({ }).passthrough(), "Profiler.start.params", "commandParams", { method: "Profiler.start" }); export const StartResult = withCdpMeta(z.object({ }).passthrough(), "Profiler.start.result", "commandResult", { method: "Profiler.start" }); +export const StartCommand = withCdpCommand("Profiler.start", StartParams, StartResult); export const StartPreciseCoverageParams = withCdpMeta(z.object({ "callCount": z.boolean().optional(), "detailed": z.boolean().optional(), "allowTriggeredUpdates": z.boolean().optional() }).passthrough(), "Profiler.startPreciseCoverage.params", "commandParams", { method: "Profiler.startPreciseCoverage" }); export const StartPreciseCoverageResult = withCdpMeta(z.object({ "timestamp": z.number() }).passthrough(), "Profiler.startPreciseCoverage.result", "commandResult", { method: "Profiler.startPreciseCoverage" }); +export const StartPreciseCoverageCommand = withCdpCommand("Profiler.startPreciseCoverage", StartPreciseCoverageParams, StartPreciseCoverageResult); export const StopParams = withCdpMeta(z.object({ }).passthrough(), "Profiler.stop.params", "commandParams", { method: "Profiler.stop" }); export const StopResult = withCdpMeta(z.object({ "profile": z.lazy(() => Profile) }).passthrough(), "Profiler.stop.result", "commandResult", { method: "Profiler.stop" }); +export const StopCommand = withCdpCommand("Profiler.stop", StopParams, StopResult); export const StopPreciseCoverageParams = withCdpMeta(z.object({ }).passthrough(), "Profiler.stopPreciseCoverage.params", "commandParams", { method: "Profiler.stopPreciseCoverage" }); export const StopPreciseCoverageResult = withCdpMeta(z.object({ }).passthrough(), "Profiler.stopPreciseCoverage.result", "commandResult", { method: "Profiler.stopPreciseCoverage" }); +export const StopPreciseCoverageCommand = withCdpCommand("Profiler.stopPreciseCoverage", StopPreciseCoverageParams, StopPreciseCoverageResult); export const TakePreciseCoverageParams = withCdpMeta(z.object({ }).passthrough(), "Profiler.takePreciseCoverage.params", "commandParams", { method: "Profiler.takePreciseCoverage" }); export const TakePreciseCoverageResult = withCdpMeta(z.object({ "result": z.array(z.lazy(() => ScriptCoverage)), "timestamp": z.number() }).passthrough(), "Profiler.takePreciseCoverage.result", "commandResult", { method: "Profiler.takePreciseCoverage" }); +export const TakePreciseCoverageCommand = withCdpCommand("Profiler.takePreciseCoverage", TakePreciseCoverageParams, TakePreciseCoverageResult); export const ConsoleProfileFinishedEvent = withCdpMeta(z.object({ "id": z.string(), "location": z.lazy(() => Debugger.Location), "profile": z.lazy(() => Profile), "title": z.string().optional() }).passthrough(), "Profiler.consoleProfileFinished", "event", { phase: "event" }); export const ConsoleProfileStartedEvent = withCdpMeta(z.object({ "id": z.string(), "location": z.lazy(() => Debugger.Location), "title": z.string().optional() }).passthrough(), "Profiler.consoleProfileStarted", "event", { phase: "event" }); export const PreciseCoverageDeltaUpdateEvent = withCdpMeta(z.object({ "timestamp": z.number(), "occasion": z.string(), "result": z.array(z.lazy(() => ScriptCoverage)) }).passthrough(), "Profiler.preciseCoverageDeltaUpdate", "event", { phase: "event" }); @@ -63,15 +72,15 @@ export const zod = { PreciseCoverageDeltaUpdateEvent: PreciseCoverageDeltaUpdateEvent, } as const; export const commands = { - "Profiler.disable": { params: DisableParams, result: DisableResult }, - "Profiler.enable": { params: EnableParams, result: EnableResult }, - "Profiler.getBestEffortCoverage": { params: GetBestEffortCoverageParams, result: GetBestEffortCoverageResult }, - "Profiler.setSamplingInterval": { params: SetSamplingIntervalParams, result: SetSamplingIntervalResult }, - "Profiler.start": { params: StartParams, result: StartResult }, - "Profiler.startPreciseCoverage": { params: StartPreciseCoverageParams, result: StartPreciseCoverageResult }, - "Profiler.stop": { params: StopParams, result: StopResult }, - "Profiler.stopPreciseCoverage": { params: StopPreciseCoverageParams, result: StopPreciseCoverageResult }, - "Profiler.takePreciseCoverage": { params: TakePreciseCoverageParams, result: TakePreciseCoverageResult }, + "Profiler.disable": DisableCommand, + "Profiler.enable": EnableCommand, + "Profiler.getBestEffortCoverage": GetBestEffortCoverageCommand, + "Profiler.setSamplingInterval": SetSamplingIntervalCommand, + "Profiler.start": StartCommand, + "Profiler.startPreciseCoverage": StartPreciseCoverageCommand, + "Profiler.stop": StopCommand, + "Profiler.stopPreciseCoverage": StopPreciseCoverageCommand, + "Profiler.takePreciseCoverage": TakePreciseCoverageCommand, } as const; export const events = { "Profiler.consoleProfileFinished": ConsoleProfileFinishedEvent, diff --git a/js/src/types/generated/zod/Runtime.ts b/js/src/types/generated/zod/Runtime.ts index 11a6f11..1a567fe 100644 --- a/js/src/types/generated/zod/Runtime.ts +++ b/js/src/types/generated/zod/Runtime.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const ScriptId = withCdpMeta(z.string(), "Runtime.ScriptId", "type"); export const SerializationOptions = withCdpMeta(z.object({ "serialization": z.enum(["deep", "json", "idOnly"]), "maxDepth": z.number().int().optional(), "additionalParameters": z.record(z.string(), z.unknown()).optional() }).passthrough(), "Runtime.SerializationOptions", "type"); @@ -28,50 +28,73 @@ export const UniqueDebuggerId = withCdpMeta(z.string(), "Runtime.UniqueDebuggerI export const StackTraceId = withCdpMeta(z.object({ "id": z.string(), "debuggerId": z.lazy(() => UniqueDebuggerId).optional() }).passthrough(), "Runtime.StackTraceId", "type"); export const AwaitPromiseParams = withCdpMeta(z.object({ "promiseObjectId": z.lazy(() => RemoteObjectId), "returnByValue": z.boolean().optional(), "generatePreview": z.boolean().optional() }).passthrough(), "Runtime.awaitPromise.params", "commandParams", { method: "Runtime.awaitPromise" }); export const AwaitPromiseResult = withCdpMeta(z.object({ "result": z.lazy(() => RemoteObject), "exceptionDetails": z.lazy(() => ExceptionDetails).optional() }).passthrough(), "Runtime.awaitPromise.result", "commandResult", { method: "Runtime.awaitPromise" }); +export const AwaitPromiseCommand = withCdpCommand("Runtime.awaitPromise", AwaitPromiseParams, AwaitPromiseResult); export const CallFunctionOnParams = withCdpMeta(z.object({ "functionDeclaration": z.string(), "objectId": z.lazy(() => RemoteObjectId).optional(), "arguments": z.array(z.lazy(() => CallArgument)).optional(), "silent": z.boolean().optional(), "returnByValue": z.boolean().optional(), "generatePreview": z.boolean().optional(), "userGesture": z.boolean().optional(), "awaitPromise": z.boolean().optional(), "executionContextId": z.lazy(() => ExecutionContextId).optional(), "objectGroup": z.string().optional(), "throwOnSideEffect": z.boolean().optional(), "uniqueContextId": z.string().optional(), "serializationOptions": z.lazy(() => SerializationOptions).optional() }).passthrough(), "Runtime.callFunctionOn.params", "commandParams", { method: "Runtime.callFunctionOn" }); export const CallFunctionOnResult = withCdpMeta(z.object({ "result": z.lazy(() => RemoteObject), "exceptionDetails": z.lazy(() => ExceptionDetails).optional() }).passthrough(), "Runtime.callFunctionOn.result", "commandResult", { method: "Runtime.callFunctionOn" }); +export const CallFunctionOnCommand = withCdpCommand("Runtime.callFunctionOn", CallFunctionOnParams, CallFunctionOnResult); export const CompileScriptParams = withCdpMeta(z.object({ "expression": z.string(), "sourceURL": z.string(), "persistScript": z.boolean(), "executionContextId": z.lazy(() => ExecutionContextId).optional() }).passthrough(), "Runtime.compileScript.params", "commandParams", { method: "Runtime.compileScript" }); export const CompileScriptResult = withCdpMeta(z.object({ "scriptId": z.lazy(() => ScriptId).optional(), "exceptionDetails": z.lazy(() => ExceptionDetails).optional() }).passthrough(), "Runtime.compileScript.result", "commandResult", { method: "Runtime.compileScript" }); +export const CompileScriptCommand = withCdpCommand("Runtime.compileScript", CompileScriptParams, CompileScriptResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Runtime.disable.params", "commandParams", { method: "Runtime.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Runtime.disable.result", "commandResult", { method: "Runtime.disable" }); +export const DisableCommand = withCdpCommand("Runtime.disable", DisableParams, DisableResult); export const DiscardConsoleEntriesParams = withCdpMeta(z.object({ }).passthrough(), "Runtime.discardConsoleEntries.params", "commandParams", { method: "Runtime.discardConsoleEntries" }); export const DiscardConsoleEntriesResult = withCdpMeta(z.object({ }).passthrough(), "Runtime.discardConsoleEntries.result", "commandResult", { method: "Runtime.discardConsoleEntries" }); +export const DiscardConsoleEntriesCommand = withCdpCommand("Runtime.discardConsoleEntries", DiscardConsoleEntriesParams, DiscardConsoleEntriesResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "Runtime.enable.params", "commandParams", { method: "Runtime.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Runtime.enable.result", "commandResult", { method: "Runtime.enable" }); +export const EnableCommand = withCdpCommand("Runtime.enable", EnableParams, EnableResult); export const EvaluateParams = withCdpMeta(z.object({ "expression": z.string(), "objectGroup": z.string().optional(), "includeCommandLineAPI": z.boolean().optional(), "silent": z.boolean().optional(), "contextId": z.lazy(() => ExecutionContextId).optional(), "returnByValue": z.boolean().optional(), "generatePreview": z.boolean().optional(), "userGesture": z.boolean().optional(), "awaitPromise": z.boolean().optional(), "throwOnSideEffect": z.boolean().optional(), "timeout": z.lazy(() => TimeDelta).optional(), "disableBreaks": z.boolean().optional(), "replMode": z.boolean().optional(), "allowUnsafeEvalBlockedByCSP": z.boolean().optional(), "uniqueContextId": z.string().optional(), "serializationOptions": z.lazy(() => SerializationOptions).optional() }).passthrough(), "Runtime.evaluate.params", "commandParams", { method: "Runtime.evaluate" }); export const EvaluateResult = withCdpMeta(z.object({ "result": z.lazy(() => RemoteObject), "exceptionDetails": z.lazy(() => ExceptionDetails).optional() }).passthrough(), "Runtime.evaluate.result", "commandResult", { method: "Runtime.evaluate" }); +export const EvaluateCommand = withCdpCommand("Runtime.evaluate", EvaluateParams, EvaluateResult); export const GetIsolateIdParams = withCdpMeta(z.object({ }).passthrough(), "Runtime.getIsolateId.params", "commandParams", { method: "Runtime.getIsolateId" }); export const GetIsolateIdResult = withCdpMeta(z.object({ "id": z.string() }).passthrough(), "Runtime.getIsolateId.result", "commandResult", { method: "Runtime.getIsolateId" }); +export const GetIsolateIdCommand = withCdpCommand("Runtime.getIsolateId", GetIsolateIdParams, GetIsolateIdResult); export const GetHeapUsageParams = withCdpMeta(z.object({ }).passthrough(), "Runtime.getHeapUsage.params", "commandParams", { method: "Runtime.getHeapUsage" }); export const GetHeapUsageResult = withCdpMeta(z.object({ "usedSize": z.number(), "totalSize": z.number(), "embedderHeapUsedSize": z.number(), "backingStorageSize": z.number() }).passthrough(), "Runtime.getHeapUsage.result", "commandResult", { method: "Runtime.getHeapUsage" }); +export const GetHeapUsageCommand = withCdpCommand("Runtime.getHeapUsage", GetHeapUsageParams, GetHeapUsageResult); export const GetPropertiesParams = withCdpMeta(z.object({ "objectId": z.lazy(() => RemoteObjectId), "ownProperties": z.boolean().optional(), "accessorPropertiesOnly": z.boolean().optional(), "generatePreview": z.boolean().optional(), "nonIndexedPropertiesOnly": z.boolean().optional() }).passthrough(), "Runtime.getProperties.params", "commandParams", { method: "Runtime.getProperties" }); export const GetPropertiesResult = withCdpMeta(z.object({ "result": z.array(z.lazy(() => PropertyDescriptor)), "internalProperties": z.array(z.lazy(() => InternalPropertyDescriptor)).optional(), "privateProperties": z.array(z.lazy(() => PrivatePropertyDescriptor)).optional(), "exceptionDetails": z.lazy(() => ExceptionDetails).optional() }).passthrough(), "Runtime.getProperties.result", "commandResult", { method: "Runtime.getProperties" }); +export const GetPropertiesCommand = withCdpCommand("Runtime.getProperties", GetPropertiesParams, GetPropertiesResult); export const GlobalLexicalScopeNamesParams = withCdpMeta(z.object({ "executionContextId": z.lazy(() => ExecutionContextId).optional() }).passthrough(), "Runtime.globalLexicalScopeNames.params", "commandParams", { method: "Runtime.globalLexicalScopeNames" }); export const GlobalLexicalScopeNamesResult = withCdpMeta(z.object({ "names": z.array(z.string()) }).passthrough(), "Runtime.globalLexicalScopeNames.result", "commandResult", { method: "Runtime.globalLexicalScopeNames" }); +export const GlobalLexicalScopeNamesCommand = withCdpCommand("Runtime.globalLexicalScopeNames", GlobalLexicalScopeNamesParams, GlobalLexicalScopeNamesResult); export const QueryObjectsParams = withCdpMeta(z.object({ "prototypeObjectId": z.lazy(() => RemoteObjectId), "objectGroup": z.string().optional() }).passthrough(), "Runtime.queryObjects.params", "commandParams", { method: "Runtime.queryObjects" }); export const QueryObjectsResult = withCdpMeta(z.object({ "objects": z.lazy(() => RemoteObject) }).passthrough(), "Runtime.queryObjects.result", "commandResult", { method: "Runtime.queryObjects" }); +export const QueryObjectsCommand = withCdpCommand("Runtime.queryObjects", QueryObjectsParams, QueryObjectsResult); export const ReleaseObjectParams = withCdpMeta(z.object({ "objectId": z.lazy(() => RemoteObjectId) }).passthrough(), "Runtime.releaseObject.params", "commandParams", { method: "Runtime.releaseObject" }); export const ReleaseObjectResult = withCdpMeta(z.object({ }).passthrough(), "Runtime.releaseObject.result", "commandResult", { method: "Runtime.releaseObject" }); +export const ReleaseObjectCommand = withCdpCommand("Runtime.releaseObject", ReleaseObjectParams, ReleaseObjectResult); export const ReleaseObjectGroupParams = withCdpMeta(z.object({ "objectGroup": z.string() }).passthrough(), "Runtime.releaseObjectGroup.params", "commandParams", { method: "Runtime.releaseObjectGroup" }); export const ReleaseObjectGroupResult = withCdpMeta(z.object({ }).passthrough(), "Runtime.releaseObjectGroup.result", "commandResult", { method: "Runtime.releaseObjectGroup" }); +export const ReleaseObjectGroupCommand = withCdpCommand("Runtime.releaseObjectGroup", ReleaseObjectGroupParams, ReleaseObjectGroupResult); export const RunIfWaitingForDebuggerParams = withCdpMeta(z.object({ }).passthrough(), "Runtime.runIfWaitingForDebugger.params", "commandParams", { method: "Runtime.runIfWaitingForDebugger" }); export const RunIfWaitingForDebuggerResult = withCdpMeta(z.object({ }).passthrough(), "Runtime.runIfWaitingForDebugger.result", "commandResult", { method: "Runtime.runIfWaitingForDebugger" }); +export const RunIfWaitingForDebuggerCommand = withCdpCommand("Runtime.runIfWaitingForDebugger", RunIfWaitingForDebuggerParams, RunIfWaitingForDebuggerResult); export const RunScriptParams = withCdpMeta(z.object({ "scriptId": z.lazy(() => ScriptId), "executionContextId": z.lazy(() => ExecutionContextId).optional(), "objectGroup": z.string().optional(), "silent": z.boolean().optional(), "includeCommandLineAPI": z.boolean().optional(), "returnByValue": z.boolean().optional(), "generatePreview": z.boolean().optional(), "awaitPromise": z.boolean().optional() }).passthrough(), "Runtime.runScript.params", "commandParams", { method: "Runtime.runScript" }); export const RunScriptResult = withCdpMeta(z.object({ "result": z.lazy(() => RemoteObject), "exceptionDetails": z.lazy(() => ExceptionDetails).optional() }).passthrough(), "Runtime.runScript.result", "commandResult", { method: "Runtime.runScript" }); +export const RunScriptCommand = withCdpCommand("Runtime.runScript", RunScriptParams, RunScriptResult); export const SetAsyncCallStackDepthParams = withCdpMeta(z.object({ "maxDepth": z.number().int() }).passthrough(), "Runtime.setAsyncCallStackDepth.params", "commandParams", { method: "Runtime.setAsyncCallStackDepth" }); export const SetAsyncCallStackDepthResult = withCdpMeta(z.object({ }).passthrough(), "Runtime.setAsyncCallStackDepth.result", "commandResult", { method: "Runtime.setAsyncCallStackDepth" }); +export const SetAsyncCallStackDepthCommand = withCdpCommand("Runtime.setAsyncCallStackDepth", SetAsyncCallStackDepthParams, SetAsyncCallStackDepthResult); export const SetCustomObjectFormatterEnabledParams = withCdpMeta(z.object({ "enabled": z.boolean() }).passthrough(), "Runtime.setCustomObjectFormatterEnabled.params", "commandParams", { method: "Runtime.setCustomObjectFormatterEnabled" }); export const SetCustomObjectFormatterEnabledResult = withCdpMeta(z.object({ }).passthrough(), "Runtime.setCustomObjectFormatterEnabled.result", "commandResult", { method: "Runtime.setCustomObjectFormatterEnabled" }); +export const SetCustomObjectFormatterEnabledCommand = withCdpCommand("Runtime.setCustomObjectFormatterEnabled", SetCustomObjectFormatterEnabledParams, SetCustomObjectFormatterEnabledResult); export const SetMaxCallStackSizeToCaptureParams = withCdpMeta(z.object({ "size": z.number().int() }).passthrough(), "Runtime.setMaxCallStackSizeToCapture.params", "commandParams", { method: "Runtime.setMaxCallStackSizeToCapture" }); export const SetMaxCallStackSizeToCaptureResult = withCdpMeta(z.object({ }).passthrough(), "Runtime.setMaxCallStackSizeToCapture.result", "commandResult", { method: "Runtime.setMaxCallStackSizeToCapture" }); +export const SetMaxCallStackSizeToCaptureCommand = withCdpCommand("Runtime.setMaxCallStackSizeToCapture", SetMaxCallStackSizeToCaptureParams, SetMaxCallStackSizeToCaptureResult); export const TerminateExecutionParams = withCdpMeta(z.object({ }).passthrough(), "Runtime.terminateExecution.params", "commandParams", { method: "Runtime.terminateExecution" }); export const TerminateExecutionResult = withCdpMeta(z.object({ }).passthrough(), "Runtime.terminateExecution.result", "commandResult", { method: "Runtime.terminateExecution" }); +export const TerminateExecutionCommand = withCdpCommand("Runtime.terminateExecution", TerminateExecutionParams, TerminateExecutionResult); export const AddBindingParams = withCdpMeta(z.object({ "name": z.string(), "executionContextId": z.lazy(() => ExecutionContextId).optional(), "executionContextName": z.string().optional() }).passthrough(), "Runtime.addBinding.params", "commandParams", { method: "Runtime.addBinding" }); export const AddBindingResult = withCdpMeta(z.object({ }).passthrough(), "Runtime.addBinding.result", "commandResult", { method: "Runtime.addBinding" }); +export const AddBindingCommand = withCdpCommand("Runtime.addBinding", AddBindingParams, AddBindingResult); export const RemoveBindingParams = withCdpMeta(z.object({ "name": z.string() }).passthrough(), "Runtime.removeBinding.params", "commandParams", { method: "Runtime.removeBinding" }); export const RemoveBindingResult = withCdpMeta(z.object({ }).passthrough(), "Runtime.removeBinding.result", "commandResult", { method: "Runtime.removeBinding" }); +export const RemoveBindingCommand = withCdpCommand("Runtime.removeBinding", RemoveBindingParams, RemoveBindingResult); export const GetExceptionDetailsParams = withCdpMeta(z.object({ "errorObjectId": z.lazy(() => RemoteObjectId) }).passthrough(), "Runtime.getExceptionDetails.params", "commandParams", { method: "Runtime.getExceptionDetails" }); export const GetExceptionDetailsResult = withCdpMeta(z.object({ "exceptionDetails": z.lazy(() => ExceptionDetails).optional() }).passthrough(), "Runtime.getExceptionDetails.result", "commandResult", { method: "Runtime.getExceptionDetails" }); +export const GetExceptionDetailsCommand = withCdpCommand("Runtime.getExceptionDetails", GetExceptionDetailsParams, GetExceptionDetailsResult); export const BindingCalledEvent = withCdpMeta(z.object({ "name": z.string(), "payload": z.string(), "executionContextId": z.lazy(() => ExecutionContextId) }).passthrough(), "Runtime.bindingCalled", "event", { phase: "event" }); export const ConsoleAPICalledEvent = withCdpMeta(z.object({ "type": z.enum(["log", "debug", "info", "error", "warning", "dir", "dirxml", "table", "trace", "clear", "startGroup", "startGroupCollapsed", "endGroup", "assert", "profile", "profileEnd", "count", "timeEnd"]), "args": z.array(z.lazy(() => RemoteObject)), "executionContextId": z.lazy(() => ExecutionContextId), "timestamp": z.lazy(() => Timestamp), "stackTrace": z.lazy(() => StackTrace).optional(), "context": z.string().optional() }).passthrough(), "Runtime.consoleAPICalled", "event", { phase: "event" }); export const ExceptionRevokedEvent = withCdpMeta(z.object({ "reason": z.string(), "exceptionId": z.number().int() }).passthrough(), "Runtime.exceptionRevoked", "event", { phase: "event" }); @@ -161,29 +184,29 @@ export const zod = { InspectRequestedEvent: InspectRequestedEvent, } as const; export const commands = { - "Runtime.awaitPromise": { params: AwaitPromiseParams, result: AwaitPromiseResult }, - "Runtime.callFunctionOn": { params: CallFunctionOnParams, result: CallFunctionOnResult }, - "Runtime.compileScript": { params: CompileScriptParams, result: CompileScriptResult }, - "Runtime.disable": { params: DisableParams, result: DisableResult }, - "Runtime.discardConsoleEntries": { params: DiscardConsoleEntriesParams, result: DiscardConsoleEntriesResult }, - "Runtime.enable": { params: EnableParams, result: EnableResult }, - "Runtime.evaluate": { params: EvaluateParams, result: EvaluateResult }, - "Runtime.getIsolateId": { params: GetIsolateIdParams, result: GetIsolateIdResult }, - "Runtime.getHeapUsage": { params: GetHeapUsageParams, result: GetHeapUsageResult }, - "Runtime.getProperties": { params: GetPropertiesParams, result: GetPropertiesResult }, - "Runtime.globalLexicalScopeNames": { params: GlobalLexicalScopeNamesParams, result: GlobalLexicalScopeNamesResult }, - "Runtime.queryObjects": { params: QueryObjectsParams, result: QueryObjectsResult }, - "Runtime.releaseObject": { params: ReleaseObjectParams, result: ReleaseObjectResult }, - "Runtime.releaseObjectGroup": { params: ReleaseObjectGroupParams, result: ReleaseObjectGroupResult }, - "Runtime.runIfWaitingForDebugger": { params: RunIfWaitingForDebuggerParams, result: RunIfWaitingForDebuggerResult }, - "Runtime.runScript": { params: RunScriptParams, result: RunScriptResult }, - "Runtime.setAsyncCallStackDepth": { params: SetAsyncCallStackDepthParams, result: SetAsyncCallStackDepthResult }, - "Runtime.setCustomObjectFormatterEnabled": { params: SetCustomObjectFormatterEnabledParams, result: SetCustomObjectFormatterEnabledResult }, - "Runtime.setMaxCallStackSizeToCapture": { params: SetMaxCallStackSizeToCaptureParams, result: SetMaxCallStackSizeToCaptureResult }, - "Runtime.terminateExecution": { params: TerminateExecutionParams, result: TerminateExecutionResult }, - "Runtime.addBinding": { params: AddBindingParams, result: AddBindingResult }, - "Runtime.removeBinding": { params: RemoveBindingParams, result: RemoveBindingResult }, - "Runtime.getExceptionDetails": { params: GetExceptionDetailsParams, result: GetExceptionDetailsResult }, + "Runtime.awaitPromise": AwaitPromiseCommand, + "Runtime.callFunctionOn": CallFunctionOnCommand, + "Runtime.compileScript": CompileScriptCommand, + "Runtime.disable": DisableCommand, + "Runtime.discardConsoleEntries": DiscardConsoleEntriesCommand, + "Runtime.enable": EnableCommand, + "Runtime.evaluate": EvaluateCommand, + "Runtime.getIsolateId": GetIsolateIdCommand, + "Runtime.getHeapUsage": GetHeapUsageCommand, + "Runtime.getProperties": GetPropertiesCommand, + "Runtime.globalLexicalScopeNames": GlobalLexicalScopeNamesCommand, + "Runtime.queryObjects": QueryObjectsCommand, + "Runtime.releaseObject": ReleaseObjectCommand, + "Runtime.releaseObjectGroup": ReleaseObjectGroupCommand, + "Runtime.runIfWaitingForDebugger": RunIfWaitingForDebuggerCommand, + "Runtime.runScript": RunScriptCommand, + "Runtime.setAsyncCallStackDepth": SetAsyncCallStackDepthCommand, + "Runtime.setCustomObjectFormatterEnabled": SetCustomObjectFormatterEnabledCommand, + "Runtime.setMaxCallStackSizeToCapture": SetMaxCallStackSizeToCaptureCommand, + "Runtime.terminateExecution": TerminateExecutionCommand, + "Runtime.addBinding": AddBindingCommand, + "Runtime.removeBinding": RemoveBindingCommand, + "Runtime.getExceptionDetails": GetExceptionDetailsCommand, } as const; export const events = { "Runtime.bindingCalled": BindingCalledEvent, diff --git a/js/src/types/generated/zod/Schema.ts b/js/src/types/generated/zod/Schema.ts index bbc668b..907e2fc 100644 --- a/js/src/types/generated/zod/Schema.ts +++ b/js/src/types/generated/zod/Schema.ts @@ -1,11 +1,12 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const Domain = withCdpMeta(z.object({ "name": z.string(), "version": z.string() }).passthrough(), "Schema.Domain", "type"); export const GetDomainsParams = withCdpMeta(z.object({ }).passthrough(), "Schema.getDomains.params", "commandParams", { method: "Schema.getDomains" }); export const GetDomainsResult = withCdpMeta(z.object({ "domains": z.array(z.lazy(() => Domain)) }).passthrough(), "Schema.getDomains.result", "commandResult", { method: "Schema.getDomains" }); +export const GetDomainsCommand = withCdpCommand("Schema.getDomains", GetDomainsParams, GetDomainsResult); export const zod = { Domain: Domain, @@ -13,7 +14,7 @@ export const zod = { GetDomainsResult: GetDomainsResult, } as const; export const commands = { - "Schema.getDomains": { params: GetDomainsParams, result: GetDomainsResult }, + "Schema.getDomains": GetDomainsCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/Security.ts b/js/src/types/generated/zod/Security.ts index 3c6c4e2..bec165f 100644 --- a/js/src/types/generated/zod/Security.ts +++ b/js/src/types/generated/zod/Security.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Network from "./Network.js"; export const CertificateId = withCdpMeta(z.number().int(), "Security.CertificateId", "type"); @@ -16,14 +16,19 @@ export const InsecureContentStatus = withCdpMeta(z.object({ "ranMixedContent": z export const CertificateErrorAction = withCdpMeta(z.enum(["continue", "cancel"]), "Security.CertificateErrorAction", "type"); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "Security.disable.params", "commandParams", { method: "Security.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "Security.disable.result", "commandResult", { method: "Security.disable" }); +export const DisableCommand = withCdpCommand("Security.disable", DisableParams, DisableResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "Security.enable.params", "commandParams", { method: "Security.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "Security.enable.result", "commandResult", { method: "Security.enable" }); +export const EnableCommand = withCdpCommand("Security.enable", EnableParams, EnableResult); export const SetIgnoreCertificateErrorsParams = withCdpMeta(z.object({ "ignore": z.boolean() }).passthrough(), "Security.setIgnoreCertificateErrors.params", "commandParams", { method: "Security.setIgnoreCertificateErrors" }); export const SetIgnoreCertificateErrorsResult = withCdpMeta(z.object({ }).passthrough(), "Security.setIgnoreCertificateErrors.result", "commandResult", { method: "Security.setIgnoreCertificateErrors" }); +export const SetIgnoreCertificateErrorsCommand = withCdpCommand("Security.setIgnoreCertificateErrors", SetIgnoreCertificateErrorsParams, SetIgnoreCertificateErrorsResult); export const HandleCertificateErrorParams = withCdpMeta(z.object({ "eventId": z.number().int(), "action": z.lazy(() => CertificateErrorAction) }).passthrough(), "Security.handleCertificateError.params", "commandParams", { method: "Security.handleCertificateError" }); export const HandleCertificateErrorResult = withCdpMeta(z.object({ }).passthrough(), "Security.handleCertificateError.result", "commandResult", { method: "Security.handleCertificateError" }); +export const HandleCertificateErrorCommand = withCdpCommand("Security.handleCertificateError", HandleCertificateErrorParams, HandleCertificateErrorResult); export const SetOverrideCertificateErrorsParams = withCdpMeta(z.object({ "override": z.boolean() }).passthrough(), "Security.setOverrideCertificateErrors.params", "commandParams", { method: "Security.setOverrideCertificateErrors" }); export const SetOverrideCertificateErrorsResult = withCdpMeta(z.object({ }).passthrough(), "Security.setOverrideCertificateErrors.result", "commandResult", { method: "Security.setOverrideCertificateErrors" }); +export const SetOverrideCertificateErrorsCommand = withCdpCommand("Security.setOverrideCertificateErrors", SetOverrideCertificateErrorsParams, SetOverrideCertificateErrorsResult); export const CertificateErrorEvent = withCdpMeta(z.object({ "eventId": z.number().int(), "errorType": z.string(), "requestURL": z.string() }).passthrough(), "Security.certificateError", "event", { phase: "event" }); export const VisibleSecurityStateChangedEvent = withCdpMeta(z.object({ "visibleSecurityState": z.lazy(() => VisibleSecurityState) }).passthrough(), "Security.visibleSecurityStateChanged", "event", { phase: "event" }); export const SecurityStateChangedEvent = withCdpMeta(z.object({ "securityState": z.lazy(() => SecurityState), "schemeIsCryptographic": z.boolean(), "explanations": z.array(z.lazy(() => SecurityStateExplanation)), "insecureContentStatus": z.lazy(() => InsecureContentStatus), "summary": z.string().optional() }).passthrough(), "Security.securityStateChanged", "event", { phase: "event" }); @@ -54,11 +59,11 @@ export const zod = { SecurityStateChangedEvent: SecurityStateChangedEvent, } as const; export const commands = { - "Security.disable": { params: DisableParams, result: DisableResult }, - "Security.enable": { params: EnableParams, result: EnableResult }, - "Security.setIgnoreCertificateErrors": { params: SetIgnoreCertificateErrorsParams, result: SetIgnoreCertificateErrorsResult }, - "Security.handleCertificateError": { params: HandleCertificateErrorParams, result: HandleCertificateErrorResult }, - "Security.setOverrideCertificateErrors": { params: SetOverrideCertificateErrorsParams, result: SetOverrideCertificateErrorsResult }, + "Security.disable": DisableCommand, + "Security.enable": EnableCommand, + "Security.setIgnoreCertificateErrors": SetIgnoreCertificateErrorsCommand, + "Security.handleCertificateError": HandleCertificateErrorCommand, + "Security.setOverrideCertificateErrors": SetOverrideCertificateErrorsCommand, } as const; export const events = { "Security.certificateError": CertificateErrorEvent, diff --git a/js/src/types/generated/zod/ServiceWorker.ts b/js/src/types/generated/zod/ServiceWorker.ts index 636a776..d508970 100644 --- a/js/src/types/generated/zod/ServiceWorker.ts +++ b/js/src/types/generated/zod/ServiceWorker.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Target from "./Target.js"; export const RegistrationID = withCdpMeta(z.string(), "ServiceWorker.RegistrationID", "type"); @@ -12,28 +12,40 @@ export const ServiceWorkerVersion = withCdpMeta(z.object({ "versionId": z.string export const ServiceWorkerErrorMessage = withCdpMeta(z.object({ "errorMessage": z.string(), "registrationId": z.lazy(() => RegistrationID), "versionId": z.string(), "sourceURL": z.string(), "lineNumber": z.number().int(), "columnNumber": z.number().int() }).passthrough(), "ServiceWorker.ServiceWorkerErrorMessage", "type"); export const DeliverPushMessageParams = withCdpMeta(z.object({ "origin": z.string(), "registrationId": z.lazy(() => RegistrationID), "data": z.string() }).passthrough(), "ServiceWorker.deliverPushMessage.params", "commandParams", { method: "ServiceWorker.deliverPushMessage" }); export const DeliverPushMessageResult = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.deliverPushMessage.result", "commandResult", { method: "ServiceWorker.deliverPushMessage" }); +export const DeliverPushMessageCommand = withCdpCommand("ServiceWorker.deliverPushMessage", DeliverPushMessageParams, DeliverPushMessageResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.disable.params", "commandParams", { method: "ServiceWorker.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.disable.result", "commandResult", { method: "ServiceWorker.disable" }); +export const DisableCommand = withCdpCommand("ServiceWorker.disable", DisableParams, DisableResult); export const DispatchSyncEventParams = withCdpMeta(z.object({ "origin": z.string(), "registrationId": z.lazy(() => RegistrationID), "tag": z.string(), "lastChance": z.boolean() }).passthrough(), "ServiceWorker.dispatchSyncEvent.params", "commandParams", { method: "ServiceWorker.dispatchSyncEvent" }); export const DispatchSyncEventResult = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.dispatchSyncEvent.result", "commandResult", { method: "ServiceWorker.dispatchSyncEvent" }); +export const DispatchSyncEventCommand = withCdpCommand("ServiceWorker.dispatchSyncEvent", DispatchSyncEventParams, DispatchSyncEventResult); export const DispatchPeriodicSyncEventParams = withCdpMeta(z.object({ "origin": z.string(), "registrationId": z.lazy(() => RegistrationID), "tag": z.string() }).passthrough(), "ServiceWorker.dispatchPeriodicSyncEvent.params", "commandParams", { method: "ServiceWorker.dispatchPeriodicSyncEvent" }); export const DispatchPeriodicSyncEventResult = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.dispatchPeriodicSyncEvent.result", "commandResult", { method: "ServiceWorker.dispatchPeriodicSyncEvent" }); +export const DispatchPeriodicSyncEventCommand = withCdpCommand("ServiceWorker.dispatchPeriodicSyncEvent", DispatchPeriodicSyncEventParams, DispatchPeriodicSyncEventResult); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.enable.params", "commandParams", { method: "ServiceWorker.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.enable.result", "commandResult", { method: "ServiceWorker.enable" }); +export const EnableCommand = withCdpCommand("ServiceWorker.enable", EnableParams, EnableResult); export const SetForceUpdateOnPageLoadParams = withCdpMeta(z.object({ "forceUpdateOnPageLoad": z.boolean() }).passthrough(), "ServiceWorker.setForceUpdateOnPageLoad.params", "commandParams", { method: "ServiceWorker.setForceUpdateOnPageLoad" }); export const SetForceUpdateOnPageLoadResult = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.setForceUpdateOnPageLoad.result", "commandResult", { method: "ServiceWorker.setForceUpdateOnPageLoad" }); +export const SetForceUpdateOnPageLoadCommand = withCdpCommand("ServiceWorker.setForceUpdateOnPageLoad", SetForceUpdateOnPageLoadParams, SetForceUpdateOnPageLoadResult); export const SkipWaitingParams = withCdpMeta(z.object({ "scopeURL": z.string() }).passthrough(), "ServiceWorker.skipWaiting.params", "commandParams", { method: "ServiceWorker.skipWaiting" }); export const SkipWaitingResult = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.skipWaiting.result", "commandResult", { method: "ServiceWorker.skipWaiting" }); +export const SkipWaitingCommand = withCdpCommand("ServiceWorker.skipWaiting", SkipWaitingParams, SkipWaitingResult); export const StartWorkerParams = withCdpMeta(z.object({ "scopeURL": z.string() }).passthrough(), "ServiceWorker.startWorker.params", "commandParams", { method: "ServiceWorker.startWorker" }); export const StartWorkerResult = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.startWorker.result", "commandResult", { method: "ServiceWorker.startWorker" }); +export const StartWorkerCommand = withCdpCommand("ServiceWorker.startWorker", StartWorkerParams, StartWorkerResult); export const StopAllWorkersParams = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.stopAllWorkers.params", "commandParams", { method: "ServiceWorker.stopAllWorkers" }); export const StopAllWorkersResult = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.stopAllWorkers.result", "commandResult", { method: "ServiceWorker.stopAllWorkers" }); +export const StopAllWorkersCommand = withCdpCommand("ServiceWorker.stopAllWorkers", StopAllWorkersParams, StopAllWorkersResult); export const StopWorkerParams = withCdpMeta(z.object({ "versionId": z.string() }).passthrough(), "ServiceWorker.stopWorker.params", "commandParams", { method: "ServiceWorker.stopWorker" }); export const StopWorkerResult = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.stopWorker.result", "commandResult", { method: "ServiceWorker.stopWorker" }); +export const StopWorkerCommand = withCdpCommand("ServiceWorker.stopWorker", StopWorkerParams, StopWorkerResult); export const UnregisterParams = withCdpMeta(z.object({ "scopeURL": z.string() }).passthrough(), "ServiceWorker.unregister.params", "commandParams", { method: "ServiceWorker.unregister" }); export const UnregisterResult = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.unregister.result", "commandResult", { method: "ServiceWorker.unregister" }); +export const UnregisterCommand = withCdpCommand("ServiceWorker.unregister", UnregisterParams, UnregisterResult); export const UpdateRegistrationParams = withCdpMeta(z.object({ "scopeURL": z.string() }).passthrough(), "ServiceWorker.updateRegistration.params", "commandParams", { method: "ServiceWorker.updateRegistration" }); export const UpdateRegistrationResult = withCdpMeta(z.object({ }).passthrough(), "ServiceWorker.updateRegistration.result", "commandResult", { method: "ServiceWorker.updateRegistration" }); +export const UpdateRegistrationCommand = withCdpCommand("ServiceWorker.updateRegistration", UpdateRegistrationParams, UpdateRegistrationResult); export const WorkerErrorReportedEvent = withCdpMeta(z.object({ "errorMessage": z.lazy(() => ServiceWorkerErrorMessage) }).passthrough(), "ServiceWorker.workerErrorReported", "event", { phase: "event" }); export const WorkerRegistrationUpdatedEvent = withCdpMeta(z.object({ "registrations": z.array(z.lazy(() => ServiceWorkerRegistration)) }).passthrough(), "ServiceWorker.workerRegistrationUpdated", "event", { phase: "event" }); export const WorkerVersionUpdatedEvent = withCdpMeta(z.object({ "versions": z.array(z.lazy(() => ServiceWorkerVersion)) }).passthrough(), "ServiceWorker.workerVersionUpdated", "event", { phase: "event" }); @@ -74,18 +86,18 @@ export const zod = { WorkerVersionUpdatedEvent: WorkerVersionUpdatedEvent, } as const; export const commands = { - "ServiceWorker.deliverPushMessage": { params: DeliverPushMessageParams, result: DeliverPushMessageResult }, - "ServiceWorker.disable": { params: DisableParams, result: DisableResult }, - "ServiceWorker.dispatchSyncEvent": { params: DispatchSyncEventParams, result: DispatchSyncEventResult }, - "ServiceWorker.dispatchPeriodicSyncEvent": { params: DispatchPeriodicSyncEventParams, result: DispatchPeriodicSyncEventResult }, - "ServiceWorker.enable": { params: EnableParams, result: EnableResult }, - "ServiceWorker.setForceUpdateOnPageLoad": { params: SetForceUpdateOnPageLoadParams, result: SetForceUpdateOnPageLoadResult }, - "ServiceWorker.skipWaiting": { params: SkipWaitingParams, result: SkipWaitingResult }, - "ServiceWorker.startWorker": { params: StartWorkerParams, result: StartWorkerResult }, - "ServiceWorker.stopAllWorkers": { params: StopAllWorkersParams, result: StopAllWorkersResult }, - "ServiceWorker.stopWorker": { params: StopWorkerParams, result: StopWorkerResult }, - "ServiceWorker.unregister": { params: UnregisterParams, result: UnregisterResult }, - "ServiceWorker.updateRegistration": { params: UpdateRegistrationParams, result: UpdateRegistrationResult }, + "ServiceWorker.deliverPushMessage": DeliverPushMessageCommand, + "ServiceWorker.disable": DisableCommand, + "ServiceWorker.dispatchSyncEvent": DispatchSyncEventCommand, + "ServiceWorker.dispatchPeriodicSyncEvent": DispatchPeriodicSyncEventCommand, + "ServiceWorker.enable": EnableCommand, + "ServiceWorker.setForceUpdateOnPageLoad": SetForceUpdateOnPageLoadCommand, + "ServiceWorker.skipWaiting": SkipWaitingCommand, + "ServiceWorker.startWorker": StartWorkerCommand, + "ServiceWorker.stopAllWorkers": StopAllWorkersCommand, + "ServiceWorker.stopWorker": StopWorkerCommand, + "ServiceWorker.unregister": UnregisterCommand, + "ServiceWorker.updateRegistration": UpdateRegistrationCommand, } as const; export const events = { "ServiceWorker.workerErrorReported": WorkerErrorReportedEvent, diff --git a/js/src/types/generated/zod/SmartCardEmulation.ts b/js/src/types/generated/zod/SmartCardEmulation.ts index 946008e..255d057 100644 --- a/js/src/types/generated/zod/SmartCardEmulation.ts +++ b/js/src/types/generated/zod/SmartCardEmulation.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const ResultCode = withCdpMeta(z.enum(["success", "removed-card", "reset-card", "unpowered-card", "unresponsive-card", "unsupported-card", "reader-unavailable", "sharing-violation", "not-transacted", "no-smartcard", "proto-mismatch", "system-cancelled", "not-ready", "cancelled", "insufficient-buffer", "invalid-handle", "invalid-parameter", "invalid-value", "no-memory", "timeout", "unknown-reader", "unsupported-feature", "no-readers-available", "service-stopped", "no-service", "comm-error", "internal-error", "server-too-busy", "unexpected", "shutdown", "unknown-card", "unknown"]), "SmartCardEmulation.ResultCode", "type"); export const ShareMode = withCdpMeta(z.enum(["shared", "exclusive", "direct"]), "SmartCardEmulation.ShareMode", "type"); @@ -14,28 +14,40 @@ export const ReaderStateIn = withCdpMeta(z.object({ "reader": z.string(), "curre export const ReaderStateOut = withCdpMeta(z.object({ "reader": z.string(), "eventState": z.lazy(() => ReaderStateFlags), "eventCount": z.number().int(), "atr": z.string() }).passthrough(), "SmartCardEmulation.ReaderStateOut", "type"); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.enable.params", "commandParams", { method: "SmartCardEmulation.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.enable.result", "commandResult", { method: "SmartCardEmulation.enable" }); +export const EnableCommand = withCdpCommand("SmartCardEmulation.enable", EnableParams, EnableResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.disable.params", "commandParams", { method: "SmartCardEmulation.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.disable.result", "commandResult", { method: "SmartCardEmulation.disable" }); +export const DisableCommand = withCdpCommand("SmartCardEmulation.disable", DisableParams, DisableResult); export const ReportEstablishContextResultParams = withCdpMeta(z.object({ "requestId": z.string(), "contextId": z.number().int() }).passthrough(), "SmartCardEmulation.reportEstablishContextResult.params", "commandParams", { method: "SmartCardEmulation.reportEstablishContextResult" }); export const ReportEstablishContextResultResult = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.reportEstablishContextResult.result", "commandResult", { method: "SmartCardEmulation.reportEstablishContextResult" }); +export const ReportEstablishContextResultCommand = withCdpCommand("SmartCardEmulation.reportEstablishContextResult", ReportEstablishContextResultParams, ReportEstablishContextResultResult); export const ReportReleaseContextResultParams = withCdpMeta(z.object({ "requestId": z.string() }).passthrough(), "SmartCardEmulation.reportReleaseContextResult.params", "commandParams", { method: "SmartCardEmulation.reportReleaseContextResult" }); export const ReportReleaseContextResultResult = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.reportReleaseContextResult.result", "commandResult", { method: "SmartCardEmulation.reportReleaseContextResult" }); +export const ReportReleaseContextResultCommand = withCdpCommand("SmartCardEmulation.reportReleaseContextResult", ReportReleaseContextResultParams, ReportReleaseContextResultResult); export const ReportListReadersResultParams = withCdpMeta(z.object({ "requestId": z.string(), "readers": z.array(z.string()) }).passthrough(), "SmartCardEmulation.reportListReadersResult.params", "commandParams", { method: "SmartCardEmulation.reportListReadersResult" }); export const ReportListReadersResultResult = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.reportListReadersResult.result", "commandResult", { method: "SmartCardEmulation.reportListReadersResult" }); +export const ReportListReadersResultCommand = withCdpCommand("SmartCardEmulation.reportListReadersResult", ReportListReadersResultParams, ReportListReadersResultResult); export const ReportGetStatusChangeResultParams = withCdpMeta(z.object({ "requestId": z.string(), "readerStates": z.array(z.lazy(() => ReaderStateOut)) }).passthrough(), "SmartCardEmulation.reportGetStatusChangeResult.params", "commandParams", { method: "SmartCardEmulation.reportGetStatusChangeResult" }); export const ReportGetStatusChangeResultResult = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.reportGetStatusChangeResult.result", "commandResult", { method: "SmartCardEmulation.reportGetStatusChangeResult" }); +export const ReportGetStatusChangeResultCommand = withCdpCommand("SmartCardEmulation.reportGetStatusChangeResult", ReportGetStatusChangeResultParams, ReportGetStatusChangeResultResult); export const ReportBeginTransactionResultParams = withCdpMeta(z.object({ "requestId": z.string(), "handle": z.number().int() }).passthrough(), "SmartCardEmulation.reportBeginTransactionResult.params", "commandParams", { method: "SmartCardEmulation.reportBeginTransactionResult" }); export const ReportBeginTransactionResultResult = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.reportBeginTransactionResult.result", "commandResult", { method: "SmartCardEmulation.reportBeginTransactionResult" }); +export const ReportBeginTransactionResultCommand = withCdpCommand("SmartCardEmulation.reportBeginTransactionResult", ReportBeginTransactionResultParams, ReportBeginTransactionResultResult); export const ReportPlainResultParams = withCdpMeta(z.object({ "requestId": z.string() }).passthrough(), "SmartCardEmulation.reportPlainResult.params", "commandParams", { method: "SmartCardEmulation.reportPlainResult" }); export const ReportPlainResultResult = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.reportPlainResult.result", "commandResult", { method: "SmartCardEmulation.reportPlainResult" }); +export const ReportPlainResultCommand = withCdpCommand("SmartCardEmulation.reportPlainResult", ReportPlainResultParams, ReportPlainResultResult); export const ReportConnectResultParams = withCdpMeta(z.object({ "requestId": z.string(), "handle": z.number().int(), "activeProtocol": z.lazy(() => Protocol).optional() }).passthrough(), "SmartCardEmulation.reportConnectResult.params", "commandParams", { method: "SmartCardEmulation.reportConnectResult" }); export const ReportConnectResultResult = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.reportConnectResult.result", "commandResult", { method: "SmartCardEmulation.reportConnectResult" }); +export const ReportConnectResultCommand = withCdpCommand("SmartCardEmulation.reportConnectResult", ReportConnectResultParams, ReportConnectResultResult); export const ReportDataResultParams = withCdpMeta(z.object({ "requestId": z.string(), "data": z.string() }).passthrough(), "SmartCardEmulation.reportDataResult.params", "commandParams", { method: "SmartCardEmulation.reportDataResult" }); export const ReportDataResultResult = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.reportDataResult.result", "commandResult", { method: "SmartCardEmulation.reportDataResult" }); +export const ReportDataResultCommand = withCdpCommand("SmartCardEmulation.reportDataResult", ReportDataResultParams, ReportDataResultResult); export const ReportStatusResultParams = withCdpMeta(z.object({ "requestId": z.string(), "readerName": z.string(), "state": z.lazy(() => ConnectionState), "atr": z.string(), "protocol": z.lazy(() => Protocol).optional() }).passthrough(), "SmartCardEmulation.reportStatusResult.params", "commandParams", { method: "SmartCardEmulation.reportStatusResult" }); export const ReportStatusResultResult = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.reportStatusResult.result", "commandResult", { method: "SmartCardEmulation.reportStatusResult" }); +export const ReportStatusResultCommand = withCdpCommand("SmartCardEmulation.reportStatusResult", ReportStatusResultParams, ReportStatusResultResult); export const ReportErrorParams = withCdpMeta(z.object({ "requestId": z.string(), "resultCode": z.lazy(() => ResultCode) }).passthrough(), "SmartCardEmulation.reportError.params", "commandParams", { method: "SmartCardEmulation.reportError" }); export const ReportErrorResult = withCdpMeta(z.object({ }).passthrough(), "SmartCardEmulation.reportError.result", "commandResult", { method: "SmartCardEmulation.reportError" }); +export const ReportErrorCommand = withCdpCommand("SmartCardEmulation.reportError", ReportErrorParams, ReportErrorResult); export const EstablishContextRequestedEvent = withCdpMeta(z.object({ "requestId": z.string() }).passthrough(), "SmartCardEmulation.establishContextRequested", "event", { phase: "event" }); export const ReleaseContextRequestedEvent = withCdpMeta(z.object({ "requestId": z.string(), "contextId": z.number().int() }).passthrough(), "SmartCardEmulation.releaseContextRequested", "event", { phase: "event" }); export const ListReadersRequestedEvent = withCdpMeta(z.object({ "requestId": z.string(), "contextId": z.number().int() }).passthrough(), "SmartCardEmulation.listReadersRequested", "event", { phase: "event" }); @@ -101,18 +113,18 @@ export const zod = { EndTransactionRequestedEvent: EndTransactionRequestedEvent, } as const; export const commands = { - "SmartCardEmulation.enable": { params: EnableParams, result: EnableResult }, - "SmartCardEmulation.disable": { params: DisableParams, result: DisableResult }, - "SmartCardEmulation.reportEstablishContextResult": { params: ReportEstablishContextResultParams, result: ReportEstablishContextResultResult }, - "SmartCardEmulation.reportReleaseContextResult": { params: ReportReleaseContextResultParams, result: ReportReleaseContextResultResult }, - "SmartCardEmulation.reportListReadersResult": { params: ReportListReadersResultParams, result: ReportListReadersResultResult }, - "SmartCardEmulation.reportGetStatusChangeResult": { params: ReportGetStatusChangeResultParams, result: ReportGetStatusChangeResultResult }, - "SmartCardEmulation.reportBeginTransactionResult": { params: ReportBeginTransactionResultParams, result: ReportBeginTransactionResultResult }, - "SmartCardEmulation.reportPlainResult": { params: ReportPlainResultParams, result: ReportPlainResultResult }, - "SmartCardEmulation.reportConnectResult": { params: ReportConnectResultParams, result: ReportConnectResultResult }, - "SmartCardEmulation.reportDataResult": { params: ReportDataResultParams, result: ReportDataResultResult }, - "SmartCardEmulation.reportStatusResult": { params: ReportStatusResultParams, result: ReportStatusResultResult }, - "SmartCardEmulation.reportError": { params: ReportErrorParams, result: ReportErrorResult }, + "SmartCardEmulation.enable": EnableCommand, + "SmartCardEmulation.disable": DisableCommand, + "SmartCardEmulation.reportEstablishContextResult": ReportEstablishContextResultCommand, + "SmartCardEmulation.reportReleaseContextResult": ReportReleaseContextResultCommand, + "SmartCardEmulation.reportListReadersResult": ReportListReadersResultCommand, + "SmartCardEmulation.reportGetStatusChangeResult": ReportGetStatusChangeResultCommand, + "SmartCardEmulation.reportBeginTransactionResult": ReportBeginTransactionResultCommand, + "SmartCardEmulation.reportPlainResult": ReportPlainResultCommand, + "SmartCardEmulation.reportConnectResult": ReportConnectResultCommand, + "SmartCardEmulation.reportDataResult": ReportDataResultCommand, + "SmartCardEmulation.reportStatusResult": ReportStatusResultCommand, + "SmartCardEmulation.reportError": ReportErrorCommand, } as const; export const events = { "SmartCardEmulation.establishContextRequested": EstablishContextRequestedEvent, diff --git a/js/src/types/generated/zod/Storage.ts b/js/src/types/generated/zod/Storage.ts index 637aafb..14dc233 100644 --- a/js/src/types/generated/zod/Storage.ts +++ b/js/src/types/generated/zod/Storage.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Browser from "./Browser.js"; import * as Network from "./Network.js"; import * as Page from "./Page.js"; @@ -29,72 +29,106 @@ export const StorageBucketInfo = withCdpMeta(z.object({ "bucket": z.lazy(() => S export const RelatedWebsiteSet = withCdpMeta(z.object({ "primarySites": z.array(z.string()), "associatedSites": z.array(z.string()), "serviceSites": z.array(z.string()) }).passthrough(), "Storage.RelatedWebsiteSet", "type"); export const GetStorageKeyForFrameParams = withCdpMeta(z.object({ "frameId": z.lazy(() => Page.FrameId) }).passthrough(), "Storage.getStorageKeyForFrame.params", "commandParams", { method: "Storage.getStorageKeyForFrame" }); export const GetStorageKeyForFrameResult = withCdpMeta(z.object({ "storageKey": z.lazy(() => SerializedStorageKey) }).passthrough(), "Storage.getStorageKeyForFrame.result", "commandResult", { method: "Storage.getStorageKeyForFrame" }); +export const GetStorageKeyForFrameCommand = withCdpCommand("Storage.getStorageKeyForFrame", GetStorageKeyForFrameParams, GetStorageKeyForFrameResult); export const GetStorageKeyParams = withCdpMeta(z.object({ "frameId": z.lazy(() => Page.FrameId).optional() }).passthrough(), "Storage.getStorageKey.params", "commandParams", { method: "Storage.getStorageKey" }); export const GetStorageKeyResult = withCdpMeta(z.object({ "storageKey": z.lazy(() => SerializedStorageKey) }).passthrough(), "Storage.getStorageKey.result", "commandResult", { method: "Storage.getStorageKey" }); +export const GetStorageKeyCommand = withCdpCommand("Storage.getStorageKey", GetStorageKeyParams, GetStorageKeyResult); export const ClearDataForOriginParams = withCdpMeta(z.object({ "origin": z.string(), "storageTypes": z.string() }).passthrough(), "Storage.clearDataForOrigin.params", "commandParams", { method: "Storage.clearDataForOrigin" }); export const ClearDataForOriginResult = withCdpMeta(z.object({ }).passthrough(), "Storage.clearDataForOrigin.result", "commandResult", { method: "Storage.clearDataForOrigin" }); +export const ClearDataForOriginCommand = withCdpCommand("Storage.clearDataForOrigin", ClearDataForOriginParams, ClearDataForOriginResult); export const ClearDataForStorageKeyParams = withCdpMeta(z.object({ "storageKey": z.string(), "storageTypes": z.string() }).passthrough(), "Storage.clearDataForStorageKey.params", "commandParams", { method: "Storage.clearDataForStorageKey" }); export const ClearDataForStorageKeyResult = withCdpMeta(z.object({ }).passthrough(), "Storage.clearDataForStorageKey.result", "commandResult", { method: "Storage.clearDataForStorageKey" }); +export const ClearDataForStorageKeyCommand = withCdpCommand("Storage.clearDataForStorageKey", ClearDataForStorageKeyParams, ClearDataForStorageKeyResult); export const GetCookiesParams = withCdpMeta(z.object({ "browserContextId": z.lazy(() => Browser.BrowserContextID).optional() }).passthrough(), "Storage.getCookies.params", "commandParams", { method: "Storage.getCookies" }); export const GetCookiesResult = withCdpMeta(z.object({ "cookies": z.array(z.lazy(() => Network.Cookie)) }).passthrough(), "Storage.getCookies.result", "commandResult", { method: "Storage.getCookies" }); +export const GetCookiesCommand = withCdpCommand("Storage.getCookies", GetCookiesParams, GetCookiesResult); export const SetCookiesParams = withCdpMeta(z.object({ "cookies": z.array(z.lazy(() => Network.CookieParam)), "browserContextId": z.lazy(() => Browser.BrowserContextID).optional() }).passthrough(), "Storage.setCookies.params", "commandParams", { method: "Storage.setCookies" }); export const SetCookiesResult = withCdpMeta(z.object({ }).passthrough(), "Storage.setCookies.result", "commandResult", { method: "Storage.setCookies" }); +export const SetCookiesCommand = withCdpCommand("Storage.setCookies", SetCookiesParams, SetCookiesResult); export const ClearCookiesParams = withCdpMeta(z.object({ "browserContextId": z.lazy(() => Browser.BrowserContextID).optional() }).passthrough(), "Storage.clearCookies.params", "commandParams", { method: "Storage.clearCookies" }); export const ClearCookiesResult = withCdpMeta(z.object({ }).passthrough(), "Storage.clearCookies.result", "commandResult", { method: "Storage.clearCookies" }); +export const ClearCookiesCommand = withCdpCommand("Storage.clearCookies", ClearCookiesParams, ClearCookiesResult); export const GetUsageAndQuotaParams = withCdpMeta(z.object({ "origin": z.string() }).passthrough(), "Storage.getUsageAndQuota.params", "commandParams", { method: "Storage.getUsageAndQuota" }); export const GetUsageAndQuotaResult = withCdpMeta(z.object({ "usage": z.number(), "quota": z.number(), "overrideActive": z.boolean(), "usageBreakdown": z.array(z.lazy(() => UsageForType)) }).passthrough(), "Storage.getUsageAndQuota.result", "commandResult", { method: "Storage.getUsageAndQuota" }); +export const GetUsageAndQuotaCommand = withCdpCommand("Storage.getUsageAndQuota", GetUsageAndQuotaParams, GetUsageAndQuotaResult); export const OverrideQuotaForOriginParams = withCdpMeta(z.object({ "origin": z.string(), "quotaSize": z.number().optional() }).passthrough(), "Storage.overrideQuotaForOrigin.params", "commandParams", { method: "Storage.overrideQuotaForOrigin" }); export const OverrideQuotaForOriginResult = withCdpMeta(z.object({ }).passthrough(), "Storage.overrideQuotaForOrigin.result", "commandResult", { method: "Storage.overrideQuotaForOrigin" }); +export const OverrideQuotaForOriginCommand = withCdpCommand("Storage.overrideQuotaForOrigin", OverrideQuotaForOriginParams, OverrideQuotaForOriginResult); export const TrackCacheStorageForOriginParams = withCdpMeta(z.object({ "origin": z.string() }).passthrough(), "Storage.trackCacheStorageForOrigin.params", "commandParams", { method: "Storage.trackCacheStorageForOrigin" }); export const TrackCacheStorageForOriginResult = withCdpMeta(z.object({ }).passthrough(), "Storage.trackCacheStorageForOrigin.result", "commandResult", { method: "Storage.trackCacheStorageForOrigin" }); +export const TrackCacheStorageForOriginCommand = withCdpCommand("Storage.trackCacheStorageForOrigin", TrackCacheStorageForOriginParams, TrackCacheStorageForOriginResult); export const TrackCacheStorageForStorageKeyParams = withCdpMeta(z.object({ "storageKey": z.string() }).passthrough(), "Storage.trackCacheStorageForStorageKey.params", "commandParams", { method: "Storage.trackCacheStorageForStorageKey" }); export const TrackCacheStorageForStorageKeyResult = withCdpMeta(z.object({ }).passthrough(), "Storage.trackCacheStorageForStorageKey.result", "commandResult", { method: "Storage.trackCacheStorageForStorageKey" }); +export const TrackCacheStorageForStorageKeyCommand = withCdpCommand("Storage.trackCacheStorageForStorageKey", TrackCacheStorageForStorageKeyParams, TrackCacheStorageForStorageKeyResult); export const TrackIndexedDBForOriginParams = withCdpMeta(z.object({ "origin": z.string() }).passthrough(), "Storage.trackIndexedDBForOrigin.params", "commandParams", { method: "Storage.trackIndexedDBForOrigin" }); export const TrackIndexedDBForOriginResult = withCdpMeta(z.object({ }).passthrough(), "Storage.trackIndexedDBForOrigin.result", "commandResult", { method: "Storage.trackIndexedDBForOrigin" }); +export const TrackIndexedDBForOriginCommand = withCdpCommand("Storage.trackIndexedDBForOrigin", TrackIndexedDBForOriginParams, TrackIndexedDBForOriginResult); export const TrackIndexedDBForStorageKeyParams = withCdpMeta(z.object({ "storageKey": z.string() }).passthrough(), "Storage.trackIndexedDBForStorageKey.params", "commandParams", { method: "Storage.trackIndexedDBForStorageKey" }); export const TrackIndexedDBForStorageKeyResult = withCdpMeta(z.object({ }).passthrough(), "Storage.trackIndexedDBForStorageKey.result", "commandResult", { method: "Storage.trackIndexedDBForStorageKey" }); +export const TrackIndexedDBForStorageKeyCommand = withCdpCommand("Storage.trackIndexedDBForStorageKey", TrackIndexedDBForStorageKeyParams, TrackIndexedDBForStorageKeyResult); export const UntrackCacheStorageForOriginParams = withCdpMeta(z.object({ "origin": z.string() }).passthrough(), "Storage.untrackCacheStorageForOrigin.params", "commandParams", { method: "Storage.untrackCacheStorageForOrigin" }); export const UntrackCacheStorageForOriginResult = withCdpMeta(z.object({ }).passthrough(), "Storage.untrackCacheStorageForOrigin.result", "commandResult", { method: "Storage.untrackCacheStorageForOrigin" }); +export const UntrackCacheStorageForOriginCommand = withCdpCommand("Storage.untrackCacheStorageForOrigin", UntrackCacheStorageForOriginParams, UntrackCacheStorageForOriginResult); export const UntrackCacheStorageForStorageKeyParams = withCdpMeta(z.object({ "storageKey": z.string() }).passthrough(), "Storage.untrackCacheStorageForStorageKey.params", "commandParams", { method: "Storage.untrackCacheStorageForStorageKey" }); export const UntrackCacheStorageForStorageKeyResult = withCdpMeta(z.object({ }).passthrough(), "Storage.untrackCacheStorageForStorageKey.result", "commandResult", { method: "Storage.untrackCacheStorageForStorageKey" }); +export const UntrackCacheStorageForStorageKeyCommand = withCdpCommand("Storage.untrackCacheStorageForStorageKey", UntrackCacheStorageForStorageKeyParams, UntrackCacheStorageForStorageKeyResult); export const UntrackIndexedDBForOriginParams = withCdpMeta(z.object({ "origin": z.string() }).passthrough(), "Storage.untrackIndexedDBForOrigin.params", "commandParams", { method: "Storage.untrackIndexedDBForOrigin" }); export const UntrackIndexedDBForOriginResult = withCdpMeta(z.object({ }).passthrough(), "Storage.untrackIndexedDBForOrigin.result", "commandResult", { method: "Storage.untrackIndexedDBForOrigin" }); +export const UntrackIndexedDBForOriginCommand = withCdpCommand("Storage.untrackIndexedDBForOrigin", UntrackIndexedDBForOriginParams, UntrackIndexedDBForOriginResult); export const UntrackIndexedDBForStorageKeyParams = withCdpMeta(z.object({ "storageKey": z.string() }).passthrough(), "Storage.untrackIndexedDBForStorageKey.params", "commandParams", { method: "Storage.untrackIndexedDBForStorageKey" }); export const UntrackIndexedDBForStorageKeyResult = withCdpMeta(z.object({ }).passthrough(), "Storage.untrackIndexedDBForStorageKey.result", "commandResult", { method: "Storage.untrackIndexedDBForStorageKey" }); +export const UntrackIndexedDBForStorageKeyCommand = withCdpCommand("Storage.untrackIndexedDBForStorageKey", UntrackIndexedDBForStorageKeyParams, UntrackIndexedDBForStorageKeyResult); export const GetTrustTokensParams = withCdpMeta(z.object({ }).passthrough(), "Storage.getTrustTokens.params", "commandParams", { method: "Storage.getTrustTokens" }); export const GetTrustTokensResult = withCdpMeta(z.object({ "tokens": z.array(z.lazy(() => TrustTokens)) }).passthrough(), "Storage.getTrustTokens.result", "commandResult", { method: "Storage.getTrustTokens" }); +export const GetTrustTokensCommand = withCdpCommand("Storage.getTrustTokens", GetTrustTokensParams, GetTrustTokensResult); export const ClearTrustTokensParams = withCdpMeta(z.object({ "issuerOrigin": z.string() }).passthrough(), "Storage.clearTrustTokens.params", "commandParams", { method: "Storage.clearTrustTokens" }); export const ClearTrustTokensResult = withCdpMeta(z.object({ "didDeleteTokens": z.boolean() }).passthrough(), "Storage.clearTrustTokens.result", "commandResult", { method: "Storage.clearTrustTokens" }); +export const ClearTrustTokensCommand = withCdpCommand("Storage.clearTrustTokens", ClearTrustTokensParams, ClearTrustTokensResult); export const GetInterestGroupDetailsParams = withCdpMeta(z.object({ "ownerOrigin": z.string(), "name": z.string() }).passthrough(), "Storage.getInterestGroupDetails.params", "commandParams", { method: "Storage.getInterestGroupDetails" }); export const GetInterestGroupDetailsResult = withCdpMeta(z.object({ "details": z.record(z.string(), z.unknown()) }).passthrough(), "Storage.getInterestGroupDetails.result", "commandResult", { method: "Storage.getInterestGroupDetails" }); +export const GetInterestGroupDetailsCommand = withCdpCommand("Storage.getInterestGroupDetails", GetInterestGroupDetailsParams, GetInterestGroupDetailsResult); export const SetInterestGroupTrackingParams = withCdpMeta(z.object({ "enable": z.boolean() }).passthrough(), "Storage.setInterestGroupTracking.params", "commandParams", { method: "Storage.setInterestGroupTracking" }); export const SetInterestGroupTrackingResult = withCdpMeta(z.object({ }).passthrough(), "Storage.setInterestGroupTracking.result", "commandResult", { method: "Storage.setInterestGroupTracking" }); +export const SetInterestGroupTrackingCommand = withCdpCommand("Storage.setInterestGroupTracking", SetInterestGroupTrackingParams, SetInterestGroupTrackingResult); export const SetInterestGroupAuctionTrackingParams = withCdpMeta(z.object({ "enable": z.boolean() }).passthrough(), "Storage.setInterestGroupAuctionTracking.params", "commandParams", { method: "Storage.setInterestGroupAuctionTracking" }); export const SetInterestGroupAuctionTrackingResult = withCdpMeta(z.object({ }).passthrough(), "Storage.setInterestGroupAuctionTracking.result", "commandResult", { method: "Storage.setInterestGroupAuctionTracking" }); +export const SetInterestGroupAuctionTrackingCommand = withCdpCommand("Storage.setInterestGroupAuctionTracking", SetInterestGroupAuctionTrackingParams, SetInterestGroupAuctionTrackingResult); export const GetSharedStorageMetadataParams = withCdpMeta(z.object({ "ownerOrigin": z.string() }).passthrough(), "Storage.getSharedStorageMetadata.params", "commandParams", { method: "Storage.getSharedStorageMetadata" }); export const GetSharedStorageMetadataResult = withCdpMeta(z.object({ "metadata": z.lazy(() => SharedStorageMetadata) }).passthrough(), "Storage.getSharedStorageMetadata.result", "commandResult", { method: "Storage.getSharedStorageMetadata" }); +export const GetSharedStorageMetadataCommand = withCdpCommand("Storage.getSharedStorageMetadata", GetSharedStorageMetadataParams, GetSharedStorageMetadataResult); export const GetSharedStorageEntriesParams = withCdpMeta(z.object({ "ownerOrigin": z.string() }).passthrough(), "Storage.getSharedStorageEntries.params", "commandParams", { method: "Storage.getSharedStorageEntries" }); export const GetSharedStorageEntriesResult = withCdpMeta(z.object({ "entries": z.array(z.lazy(() => SharedStorageEntry)) }).passthrough(), "Storage.getSharedStorageEntries.result", "commandResult", { method: "Storage.getSharedStorageEntries" }); +export const GetSharedStorageEntriesCommand = withCdpCommand("Storage.getSharedStorageEntries", GetSharedStorageEntriesParams, GetSharedStorageEntriesResult); export const SetSharedStorageEntryParams = withCdpMeta(z.object({ "ownerOrigin": z.string(), "key": z.string(), "value": z.string(), "ignoreIfPresent": z.boolean().optional() }).passthrough(), "Storage.setSharedStorageEntry.params", "commandParams", { method: "Storage.setSharedStorageEntry" }); export const SetSharedStorageEntryResult = withCdpMeta(z.object({ }).passthrough(), "Storage.setSharedStorageEntry.result", "commandResult", { method: "Storage.setSharedStorageEntry" }); +export const SetSharedStorageEntryCommand = withCdpCommand("Storage.setSharedStorageEntry", SetSharedStorageEntryParams, SetSharedStorageEntryResult); export const DeleteSharedStorageEntryParams = withCdpMeta(z.object({ "ownerOrigin": z.string(), "key": z.string() }).passthrough(), "Storage.deleteSharedStorageEntry.params", "commandParams", { method: "Storage.deleteSharedStorageEntry" }); export const DeleteSharedStorageEntryResult = withCdpMeta(z.object({ }).passthrough(), "Storage.deleteSharedStorageEntry.result", "commandResult", { method: "Storage.deleteSharedStorageEntry" }); +export const DeleteSharedStorageEntryCommand = withCdpCommand("Storage.deleteSharedStorageEntry", DeleteSharedStorageEntryParams, DeleteSharedStorageEntryResult); export const ClearSharedStorageEntriesParams = withCdpMeta(z.object({ "ownerOrigin": z.string() }).passthrough(), "Storage.clearSharedStorageEntries.params", "commandParams", { method: "Storage.clearSharedStorageEntries" }); export const ClearSharedStorageEntriesResult = withCdpMeta(z.object({ }).passthrough(), "Storage.clearSharedStorageEntries.result", "commandResult", { method: "Storage.clearSharedStorageEntries" }); +export const ClearSharedStorageEntriesCommand = withCdpCommand("Storage.clearSharedStorageEntries", ClearSharedStorageEntriesParams, ClearSharedStorageEntriesResult); export const ResetSharedStorageBudgetParams = withCdpMeta(z.object({ "ownerOrigin": z.string() }).passthrough(), "Storage.resetSharedStorageBudget.params", "commandParams", { method: "Storage.resetSharedStorageBudget" }); export const ResetSharedStorageBudgetResult = withCdpMeta(z.object({ }).passthrough(), "Storage.resetSharedStorageBudget.result", "commandResult", { method: "Storage.resetSharedStorageBudget" }); +export const ResetSharedStorageBudgetCommand = withCdpCommand("Storage.resetSharedStorageBudget", ResetSharedStorageBudgetParams, ResetSharedStorageBudgetResult); export const SetSharedStorageTrackingParams = withCdpMeta(z.object({ "enable": z.boolean() }).passthrough(), "Storage.setSharedStorageTracking.params", "commandParams", { method: "Storage.setSharedStorageTracking" }); export const SetSharedStorageTrackingResult = withCdpMeta(z.object({ }).passthrough(), "Storage.setSharedStorageTracking.result", "commandResult", { method: "Storage.setSharedStorageTracking" }); +export const SetSharedStorageTrackingCommand = withCdpCommand("Storage.setSharedStorageTracking", SetSharedStorageTrackingParams, SetSharedStorageTrackingResult); export const SetStorageBucketTrackingParams = withCdpMeta(z.object({ "storageKey": z.string(), "enable": z.boolean() }).passthrough(), "Storage.setStorageBucketTracking.params", "commandParams", { method: "Storage.setStorageBucketTracking" }); export const SetStorageBucketTrackingResult = withCdpMeta(z.object({ }).passthrough(), "Storage.setStorageBucketTracking.result", "commandResult", { method: "Storage.setStorageBucketTracking" }); +export const SetStorageBucketTrackingCommand = withCdpCommand("Storage.setStorageBucketTracking", SetStorageBucketTrackingParams, SetStorageBucketTrackingResult); export const DeleteStorageBucketParams = withCdpMeta(z.object({ "bucket": z.lazy(() => StorageBucket) }).passthrough(), "Storage.deleteStorageBucket.params", "commandParams", { method: "Storage.deleteStorageBucket" }); export const DeleteStorageBucketResult = withCdpMeta(z.object({ }).passthrough(), "Storage.deleteStorageBucket.result", "commandResult", { method: "Storage.deleteStorageBucket" }); +export const DeleteStorageBucketCommand = withCdpCommand("Storage.deleteStorageBucket", DeleteStorageBucketParams, DeleteStorageBucketResult); export const RunBounceTrackingMitigationsParams = withCdpMeta(z.object({ }).passthrough(), "Storage.runBounceTrackingMitigations.params", "commandParams", { method: "Storage.runBounceTrackingMitigations" }); export const RunBounceTrackingMitigationsResult = withCdpMeta(z.object({ "deletedSites": z.array(z.string()) }).passthrough(), "Storage.runBounceTrackingMitigations.result", "commandResult", { method: "Storage.runBounceTrackingMitigations" }); +export const RunBounceTrackingMitigationsCommand = withCdpCommand("Storage.runBounceTrackingMitigations", RunBounceTrackingMitigationsParams, RunBounceTrackingMitigationsResult); export const GetRelatedWebsiteSetsParams = withCdpMeta(z.object({ }).passthrough(), "Storage.getRelatedWebsiteSets.params", "commandParams", { method: "Storage.getRelatedWebsiteSets" }); export const GetRelatedWebsiteSetsResult = withCdpMeta(z.object({ "sets": z.array(z.lazy(() => RelatedWebsiteSet)) }).passthrough(), "Storage.getRelatedWebsiteSets.result", "commandResult", { method: "Storage.getRelatedWebsiteSets" }); +export const GetRelatedWebsiteSetsCommand = withCdpCommand("Storage.getRelatedWebsiteSets", GetRelatedWebsiteSetsParams, GetRelatedWebsiteSetsResult); export const SetProtectedAudienceKAnonymityParams = withCdpMeta(z.object({ "owner": z.string(), "name": z.string(), "hashes": z.array(z.string()) }).passthrough(), "Storage.setProtectedAudienceKAnonymity.params", "commandParams", { method: "Storage.setProtectedAudienceKAnonymity" }); export const SetProtectedAudienceKAnonymityResult = withCdpMeta(z.object({ }).passthrough(), "Storage.setProtectedAudienceKAnonymity.result", "commandResult", { method: "Storage.setProtectedAudienceKAnonymity" }); +export const SetProtectedAudienceKAnonymityCommand = withCdpCommand("Storage.setProtectedAudienceKAnonymity", SetProtectedAudienceKAnonymityParams, SetProtectedAudienceKAnonymityResult); export const CacheStorageContentUpdatedEvent = withCdpMeta(z.object({ "origin": z.string(), "storageKey": z.string(), "bucketId": z.string(), "cacheName": z.string() }).passthrough(), "Storage.cacheStorageContentUpdated", "event", { phase: "event" }); export const CacheStorageListUpdatedEvent = withCdpMeta(z.object({ "origin": z.string(), "storageKey": z.string(), "bucketId": z.string() }).passthrough(), "Storage.cacheStorageListUpdated", "event", { phase: "event" }); export const IndexedDBContentUpdatedEvent = withCdpMeta(z.object({ "origin": z.string(), "storageKey": z.string(), "bucketId": z.string(), "databaseName": z.string(), "objectStoreName": z.string() }).passthrough(), "Storage.indexedDBContentUpdated", "event", { phase: "event" }); @@ -209,40 +243,40 @@ export const zod = { StorageBucketDeletedEvent: StorageBucketDeletedEvent, } as const; export const commands = { - "Storage.getStorageKeyForFrame": { params: GetStorageKeyForFrameParams, result: GetStorageKeyForFrameResult }, - "Storage.getStorageKey": { params: GetStorageKeyParams, result: GetStorageKeyResult }, - "Storage.clearDataForOrigin": { params: ClearDataForOriginParams, result: ClearDataForOriginResult }, - "Storage.clearDataForStorageKey": { params: ClearDataForStorageKeyParams, result: ClearDataForStorageKeyResult }, - "Storage.getCookies": { params: GetCookiesParams, result: GetCookiesResult }, - "Storage.setCookies": { params: SetCookiesParams, result: SetCookiesResult }, - "Storage.clearCookies": { params: ClearCookiesParams, result: ClearCookiesResult }, - "Storage.getUsageAndQuota": { params: GetUsageAndQuotaParams, result: GetUsageAndQuotaResult }, - "Storage.overrideQuotaForOrigin": { params: OverrideQuotaForOriginParams, result: OverrideQuotaForOriginResult }, - "Storage.trackCacheStorageForOrigin": { params: TrackCacheStorageForOriginParams, result: TrackCacheStorageForOriginResult }, - "Storage.trackCacheStorageForStorageKey": { params: TrackCacheStorageForStorageKeyParams, result: TrackCacheStorageForStorageKeyResult }, - "Storage.trackIndexedDBForOrigin": { params: TrackIndexedDBForOriginParams, result: TrackIndexedDBForOriginResult }, - "Storage.trackIndexedDBForStorageKey": { params: TrackIndexedDBForStorageKeyParams, result: TrackIndexedDBForStorageKeyResult }, - "Storage.untrackCacheStorageForOrigin": { params: UntrackCacheStorageForOriginParams, result: UntrackCacheStorageForOriginResult }, - "Storage.untrackCacheStorageForStorageKey": { params: UntrackCacheStorageForStorageKeyParams, result: UntrackCacheStorageForStorageKeyResult }, - "Storage.untrackIndexedDBForOrigin": { params: UntrackIndexedDBForOriginParams, result: UntrackIndexedDBForOriginResult }, - "Storage.untrackIndexedDBForStorageKey": { params: UntrackIndexedDBForStorageKeyParams, result: UntrackIndexedDBForStorageKeyResult }, - "Storage.getTrustTokens": { params: GetTrustTokensParams, result: GetTrustTokensResult }, - "Storage.clearTrustTokens": { params: ClearTrustTokensParams, result: ClearTrustTokensResult }, - "Storage.getInterestGroupDetails": { params: GetInterestGroupDetailsParams, result: GetInterestGroupDetailsResult }, - "Storage.setInterestGroupTracking": { params: SetInterestGroupTrackingParams, result: SetInterestGroupTrackingResult }, - "Storage.setInterestGroupAuctionTracking": { params: SetInterestGroupAuctionTrackingParams, result: SetInterestGroupAuctionTrackingResult }, - "Storage.getSharedStorageMetadata": { params: GetSharedStorageMetadataParams, result: GetSharedStorageMetadataResult }, - "Storage.getSharedStorageEntries": { params: GetSharedStorageEntriesParams, result: GetSharedStorageEntriesResult }, - "Storage.setSharedStorageEntry": { params: SetSharedStorageEntryParams, result: SetSharedStorageEntryResult }, - "Storage.deleteSharedStorageEntry": { params: DeleteSharedStorageEntryParams, result: DeleteSharedStorageEntryResult }, - "Storage.clearSharedStorageEntries": { params: ClearSharedStorageEntriesParams, result: ClearSharedStorageEntriesResult }, - "Storage.resetSharedStorageBudget": { params: ResetSharedStorageBudgetParams, result: ResetSharedStorageBudgetResult }, - "Storage.setSharedStorageTracking": { params: SetSharedStorageTrackingParams, result: SetSharedStorageTrackingResult }, - "Storage.setStorageBucketTracking": { params: SetStorageBucketTrackingParams, result: SetStorageBucketTrackingResult }, - "Storage.deleteStorageBucket": { params: DeleteStorageBucketParams, result: DeleteStorageBucketResult }, - "Storage.runBounceTrackingMitigations": { params: RunBounceTrackingMitigationsParams, result: RunBounceTrackingMitigationsResult }, - "Storage.getRelatedWebsiteSets": { params: GetRelatedWebsiteSetsParams, result: GetRelatedWebsiteSetsResult }, - "Storage.setProtectedAudienceKAnonymity": { params: SetProtectedAudienceKAnonymityParams, result: SetProtectedAudienceKAnonymityResult }, + "Storage.getStorageKeyForFrame": GetStorageKeyForFrameCommand, + "Storage.getStorageKey": GetStorageKeyCommand, + "Storage.clearDataForOrigin": ClearDataForOriginCommand, + "Storage.clearDataForStorageKey": ClearDataForStorageKeyCommand, + "Storage.getCookies": GetCookiesCommand, + "Storage.setCookies": SetCookiesCommand, + "Storage.clearCookies": ClearCookiesCommand, + "Storage.getUsageAndQuota": GetUsageAndQuotaCommand, + "Storage.overrideQuotaForOrigin": OverrideQuotaForOriginCommand, + "Storage.trackCacheStorageForOrigin": TrackCacheStorageForOriginCommand, + "Storage.trackCacheStorageForStorageKey": TrackCacheStorageForStorageKeyCommand, + "Storage.trackIndexedDBForOrigin": TrackIndexedDBForOriginCommand, + "Storage.trackIndexedDBForStorageKey": TrackIndexedDBForStorageKeyCommand, + "Storage.untrackCacheStorageForOrigin": UntrackCacheStorageForOriginCommand, + "Storage.untrackCacheStorageForStorageKey": UntrackCacheStorageForStorageKeyCommand, + "Storage.untrackIndexedDBForOrigin": UntrackIndexedDBForOriginCommand, + "Storage.untrackIndexedDBForStorageKey": UntrackIndexedDBForStorageKeyCommand, + "Storage.getTrustTokens": GetTrustTokensCommand, + "Storage.clearTrustTokens": ClearTrustTokensCommand, + "Storage.getInterestGroupDetails": GetInterestGroupDetailsCommand, + "Storage.setInterestGroupTracking": SetInterestGroupTrackingCommand, + "Storage.setInterestGroupAuctionTracking": SetInterestGroupAuctionTrackingCommand, + "Storage.getSharedStorageMetadata": GetSharedStorageMetadataCommand, + "Storage.getSharedStorageEntries": GetSharedStorageEntriesCommand, + "Storage.setSharedStorageEntry": SetSharedStorageEntryCommand, + "Storage.deleteSharedStorageEntry": DeleteSharedStorageEntryCommand, + "Storage.clearSharedStorageEntries": ClearSharedStorageEntriesCommand, + "Storage.resetSharedStorageBudget": ResetSharedStorageBudgetCommand, + "Storage.setSharedStorageTracking": SetSharedStorageTrackingCommand, + "Storage.setStorageBucketTracking": SetStorageBucketTrackingCommand, + "Storage.deleteStorageBucket": DeleteStorageBucketCommand, + "Storage.runBounceTrackingMitigations": RunBounceTrackingMitigationsCommand, + "Storage.getRelatedWebsiteSets": GetRelatedWebsiteSetsCommand, + "Storage.setProtectedAudienceKAnonymity": SetProtectedAudienceKAnonymityCommand, } as const; export const events = { "Storage.cacheStorageContentUpdated": CacheStorageContentUpdatedEvent, diff --git a/js/src/types/generated/zod/SystemInfo.ts b/js/src/types/generated/zod/SystemInfo.ts index d66b96a..b3d7883 100644 --- a/js/src/types/generated/zod/SystemInfo.ts +++ b/js/src/types/generated/zod/SystemInfo.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const GPUDevice = withCdpMeta(z.object({ "vendorId": z.number(), "deviceId": z.number(), "subSysId": z.number().optional(), "revision": z.number().optional(), "vendorString": z.string(), "deviceString": z.string(), "driverVendor": z.string(), "driverVersion": z.string() }).passthrough(), "SystemInfo.GPUDevice", "type"); export const Size = withCdpMeta(z.object({ "width": z.number().int(), "height": z.number().int() }).passthrough(), "SystemInfo.Size", "type"); @@ -13,10 +13,13 @@ export const GPUInfo = withCdpMeta(z.object({ "devices": z.array(z.lazy(() => GP export const ProcessInfo = withCdpMeta(z.object({ "type": z.string(), "id": z.number().int(), "cpuTime": z.number() }).passthrough(), "SystemInfo.ProcessInfo", "type"); export const GetInfoParams = withCdpMeta(z.object({ }).passthrough(), "SystemInfo.getInfo.params", "commandParams", { method: "SystemInfo.getInfo" }); export const GetInfoResult = withCdpMeta(z.object({ "gpu": z.lazy(() => GPUInfo), "modelName": z.string(), "modelVersion": z.string(), "commandLine": z.string() }).passthrough(), "SystemInfo.getInfo.result", "commandResult", { method: "SystemInfo.getInfo" }); +export const GetInfoCommand = withCdpCommand("SystemInfo.getInfo", GetInfoParams, GetInfoResult); export const GetFeatureStateParams = withCdpMeta(z.object({ "featureState": z.string() }).passthrough(), "SystemInfo.getFeatureState.params", "commandParams", { method: "SystemInfo.getFeatureState" }); export const GetFeatureStateResult = withCdpMeta(z.object({ "featureEnabled": z.boolean() }).passthrough(), "SystemInfo.getFeatureState.result", "commandResult", { method: "SystemInfo.getFeatureState" }); +export const GetFeatureStateCommand = withCdpCommand("SystemInfo.getFeatureState", GetFeatureStateParams, GetFeatureStateResult); export const GetProcessInfoParams = withCdpMeta(z.object({ }).passthrough(), "SystemInfo.getProcessInfo.params", "commandParams", { method: "SystemInfo.getProcessInfo" }); export const GetProcessInfoResult = withCdpMeta(z.object({ "processInfo": z.array(z.lazy(() => ProcessInfo)) }).passthrough(), "SystemInfo.getProcessInfo.result", "commandResult", { method: "SystemInfo.getProcessInfo" }); +export const GetProcessInfoCommand = withCdpCommand("SystemInfo.getProcessInfo", GetProcessInfoParams, GetProcessInfoResult); export const zod = { GPUDevice: GPUDevice, @@ -35,9 +38,9 @@ export const zod = { GetProcessInfoResult: GetProcessInfoResult, } as const; export const commands = { - "SystemInfo.getInfo": { params: GetInfoParams, result: GetInfoResult }, - "SystemInfo.getFeatureState": { params: GetFeatureStateParams, result: GetFeatureStateResult }, - "SystemInfo.getProcessInfo": { params: GetProcessInfoParams, result: GetProcessInfoResult }, + "SystemInfo.getInfo": GetInfoCommand, + "SystemInfo.getFeatureState": GetFeatureStateCommand, + "SystemInfo.getProcessInfo": GetProcessInfoCommand, } as const; export const events = { } as const; diff --git a/js/src/types/generated/zod/Target.ts b/js/src/types/generated/zod/Target.ts index baeb0c2..45232c1 100644 --- a/js/src/types/generated/zod/Target.ts +++ b/js/src/types/generated/zod/Target.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as Browser from "./Browser.js"; import * as Page from "./Page.js"; @@ -14,42 +14,61 @@ export const RemoteLocation = withCdpMeta(z.object({ "host": z.string(), "port": export const WindowState = withCdpMeta(z.enum(["normal", "minimized", "maximized", "fullscreen"]), "Target.WindowState", "type"); export const ActivateTargetParams = withCdpMeta(z.object({ "targetId": z.lazy(() => TargetID) }).passthrough(), "Target.activateTarget.params", "commandParams", { method: "Target.activateTarget" }); export const ActivateTargetResult = withCdpMeta(z.object({ }).passthrough(), "Target.activateTarget.result", "commandResult", { method: "Target.activateTarget" }); +export const ActivateTargetCommand = withCdpCommand("Target.activateTarget", ActivateTargetParams, ActivateTargetResult); export const AttachToTargetParams = withCdpMeta(z.object({ "targetId": z.lazy(() => TargetID), "flatten": z.boolean().optional() }).passthrough(), "Target.attachToTarget.params", "commandParams", { method: "Target.attachToTarget" }); export const AttachToTargetResult = withCdpMeta(z.object({ "sessionId": z.lazy(() => SessionID) }).passthrough(), "Target.attachToTarget.result", "commandResult", { method: "Target.attachToTarget" }); +export const AttachToTargetCommand = withCdpCommand("Target.attachToTarget", AttachToTargetParams, AttachToTargetResult); export const AttachToBrowserTargetParams = withCdpMeta(z.object({ }).passthrough(), "Target.attachToBrowserTarget.params", "commandParams", { method: "Target.attachToBrowserTarget" }); export const AttachToBrowserTargetResult = withCdpMeta(z.object({ "sessionId": z.lazy(() => SessionID) }).passthrough(), "Target.attachToBrowserTarget.result", "commandResult", { method: "Target.attachToBrowserTarget" }); +export const AttachToBrowserTargetCommand = withCdpCommand("Target.attachToBrowserTarget", AttachToBrowserTargetParams, AttachToBrowserTargetResult); export const CloseTargetParams = withCdpMeta(z.object({ "targetId": z.lazy(() => TargetID) }).passthrough(), "Target.closeTarget.params", "commandParams", { method: "Target.closeTarget" }); export const CloseTargetResult = withCdpMeta(z.object({ "success": z.boolean() }).passthrough(), "Target.closeTarget.result", "commandResult", { method: "Target.closeTarget" }); +export const CloseTargetCommand = withCdpCommand("Target.closeTarget", CloseTargetParams, CloseTargetResult); export const ExposeDevToolsProtocolParams = withCdpMeta(z.object({ "targetId": z.lazy(() => TargetID), "bindingName": z.string().optional(), "inheritPermissions": z.boolean().optional() }).passthrough(), "Target.exposeDevToolsProtocol.params", "commandParams", { method: "Target.exposeDevToolsProtocol" }); export const ExposeDevToolsProtocolResult = withCdpMeta(z.object({ }).passthrough(), "Target.exposeDevToolsProtocol.result", "commandResult", { method: "Target.exposeDevToolsProtocol" }); +export const ExposeDevToolsProtocolCommand = withCdpCommand("Target.exposeDevToolsProtocol", ExposeDevToolsProtocolParams, ExposeDevToolsProtocolResult); export const CreateBrowserContextParams = withCdpMeta(z.object({ "disposeOnDetach": z.boolean().optional(), "proxyServer": z.string().optional(), "proxyBypassList": z.string().optional(), "originsWithUniversalNetworkAccess": z.array(z.string()).optional() }).passthrough(), "Target.createBrowserContext.params", "commandParams", { method: "Target.createBrowserContext" }); export const CreateBrowserContextResult = withCdpMeta(z.object({ "browserContextId": z.lazy(() => Browser.BrowserContextID) }).passthrough(), "Target.createBrowserContext.result", "commandResult", { method: "Target.createBrowserContext" }); +export const CreateBrowserContextCommand = withCdpCommand("Target.createBrowserContext", CreateBrowserContextParams, CreateBrowserContextResult); export const GetBrowserContextsParams = withCdpMeta(z.object({ }).passthrough(), "Target.getBrowserContexts.params", "commandParams", { method: "Target.getBrowserContexts" }); export const GetBrowserContextsResult = withCdpMeta(z.object({ "browserContextIds": z.array(z.lazy(() => Browser.BrowserContextID)), "defaultBrowserContextId": z.lazy(() => Browser.BrowserContextID).optional() }).passthrough(), "Target.getBrowserContexts.result", "commandResult", { method: "Target.getBrowserContexts" }); +export const GetBrowserContextsCommand = withCdpCommand("Target.getBrowserContexts", GetBrowserContextsParams, GetBrowserContextsResult); export const CreateTargetParams = withCdpMeta(z.object({ "url": z.string(), "left": z.number().int().optional(), "top": z.number().int().optional(), "width": z.number().int().optional(), "height": z.number().int().optional(), "windowState": z.lazy(() => WindowState).optional(), "browserContextId": z.lazy(() => Browser.BrowserContextID).optional(), "enableBeginFrameControl": z.boolean().optional(), "newWindow": z.boolean().optional(), "background": z.boolean().optional(), "forTab": z.boolean().optional(), "hidden": z.boolean().optional(), "focus": z.boolean().optional() }).passthrough(), "Target.createTarget.params", "commandParams", { method: "Target.createTarget" }); export const CreateTargetResult = withCdpMeta(z.object({ "targetId": z.lazy(() => TargetID) }).passthrough(), "Target.createTarget.result", "commandResult", { method: "Target.createTarget" }); +export const CreateTargetCommand = withCdpCommand("Target.createTarget", CreateTargetParams, CreateTargetResult); export const DetachFromTargetParams = withCdpMeta(z.object({ "sessionId": z.lazy(() => SessionID).optional(), "targetId": z.lazy(() => TargetID).optional() }).passthrough(), "Target.detachFromTarget.params", "commandParams", { method: "Target.detachFromTarget" }); export const DetachFromTargetResult = withCdpMeta(z.object({ }).passthrough(), "Target.detachFromTarget.result", "commandResult", { method: "Target.detachFromTarget" }); +export const DetachFromTargetCommand = withCdpCommand("Target.detachFromTarget", DetachFromTargetParams, DetachFromTargetResult); export const DisposeBrowserContextParams = withCdpMeta(z.object({ "browserContextId": z.lazy(() => Browser.BrowserContextID) }).passthrough(), "Target.disposeBrowserContext.params", "commandParams", { method: "Target.disposeBrowserContext" }); export const DisposeBrowserContextResult = withCdpMeta(z.object({ }).passthrough(), "Target.disposeBrowserContext.result", "commandResult", { method: "Target.disposeBrowserContext" }); +export const DisposeBrowserContextCommand = withCdpCommand("Target.disposeBrowserContext", DisposeBrowserContextParams, DisposeBrowserContextResult); export const GetTargetInfoParams = withCdpMeta(z.object({ "targetId": z.lazy(() => TargetID).optional() }).passthrough(), "Target.getTargetInfo.params", "commandParams", { method: "Target.getTargetInfo" }); export const GetTargetInfoResult = withCdpMeta(z.object({ "targetInfo": z.lazy(() => TargetInfo) }).passthrough(), "Target.getTargetInfo.result", "commandResult", { method: "Target.getTargetInfo" }); +export const GetTargetInfoCommand = withCdpCommand("Target.getTargetInfo", GetTargetInfoParams, GetTargetInfoResult); export const GetTargetsParams = withCdpMeta(z.object({ "filter": z.lazy(() => TargetFilter).optional() }).passthrough(), "Target.getTargets.params", "commandParams", { method: "Target.getTargets" }); export const GetTargetsResult = withCdpMeta(z.object({ "targetInfos": z.array(z.lazy(() => TargetInfo)) }).passthrough(), "Target.getTargets.result", "commandResult", { method: "Target.getTargets" }); +export const GetTargetsCommand = withCdpCommand("Target.getTargets", GetTargetsParams, GetTargetsResult); export const SendMessageToTargetParams = withCdpMeta(z.object({ "message": z.string(), "sessionId": z.lazy(() => SessionID).optional(), "targetId": z.lazy(() => TargetID).optional() }).passthrough(), "Target.sendMessageToTarget.params", "commandParams", { method: "Target.sendMessageToTarget" }); export const SendMessageToTargetResult = withCdpMeta(z.object({ }).passthrough(), "Target.sendMessageToTarget.result", "commandResult", { method: "Target.sendMessageToTarget" }); +export const SendMessageToTargetCommand = withCdpCommand("Target.sendMessageToTarget", SendMessageToTargetParams, SendMessageToTargetResult); export const SetAutoAttachParams = withCdpMeta(z.object({ "autoAttach": z.boolean(), "waitForDebuggerOnStart": z.boolean(), "flatten": z.boolean().optional(), "filter": z.lazy(() => TargetFilter).optional() }).passthrough(), "Target.setAutoAttach.params", "commandParams", { method: "Target.setAutoAttach" }); export const SetAutoAttachResult = withCdpMeta(z.object({ }).passthrough(), "Target.setAutoAttach.result", "commandResult", { method: "Target.setAutoAttach" }); +export const SetAutoAttachCommand = withCdpCommand("Target.setAutoAttach", SetAutoAttachParams, SetAutoAttachResult); export const AutoAttachRelatedParams = withCdpMeta(z.object({ "targetId": z.lazy(() => TargetID), "waitForDebuggerOnStart": z.boolean(), "filter": z.lazy(() => TargetFilter).optional() }).passthrough(), "Target.autoAttachRelated.params", "commandParams", { method: "Target.autoAttachRelated" }); export const AutoAttachRelatedResult = withCdpMeta(z.object({ }).passthrough(), "Target.autoAttachRelated.result", "commandResult", { method: "Target.autoAttachRelated" }); +export const AutoAttachRelatedCommand = withCdpCommand("Target.autoAttachRelated", AutoAttachRelatedParams, AutoAttachRelatedResult); export const SetDiscoverTargetsParams = withCdpMeta(z.object({ "discover": z.boolean(), "filter": z.lazy(() => TargetFilter).optional() }).passthrough(), "Target.setDiscoverTargets.params", "commandParams", { method: "Target.setDiscoverTargets" }); export const SetDiscoverTargetsResult = withCdpMeta(z.object({ }).passthrough(), "Target.setDiscoverTargets.result", "commandResult", { method: "Target.setDiscoverTargets" }); +export const SetDiscoverTargetsCommand = withCdpCommand("Target.setDiscoverTargets", SetDiscoverTargetsParams, SetDiscoverTargetsResult); export const SetRemoteLocationsParams = withCdpMeta(z.object({ "locations": z.array(z.lazy(() => RemoteLocation)) }).passthrough(), "Target.setRemoteLocations.params", "commandParams", { method: "Target.setRemoteLocations" }); export const SetRemoteLocationsResult = withCdpMeta(z.object({ }).passthrough(), "Target.setRemoteLocations.result", "commandResult", { method: "Target.setRemoteLocations" }); +export const SetRemoteLocationsCommand = withCdpCommand("Target.setRemoteLocations", SetRemoteLocationsParams, SetRemoteLocationsResult); export const GetDevToolsTargetParams = withCdpMeta(z.object({ "targetId": z.lazy(() => TargetID) }).passthrough(), "Target.getDevToolsTarget.params", "commandParams", { method: "Target.getDevToolsTarget" }); export const GetDevToolsTargetResult = withCdpMeta(z.object({ "targetId": z.lazy(() => TargetID).optional() }).passthrough(), "Target.getDevToolsTarget.result", "commandResult", { method: "Target.getDevToolsTarget" }); +export const GetDevToolsTargetCommand = withCdpCommand("Target.getDevToolsTarget", GetDevToolsTargetParams, GetDevToolsTargetResult); export const OpenDevToolsParams = withCdpMeta(z.object({ "targetId": z.lazy(() => TargetID), "panelId": z.string().optional() }).passthrough(), "Target.openDevTools.params", "commandParams", { method: "Target.openDevTools" }); export const OpenDevToolsResult = withCdpMeta(z.object({ "targetId": z.lazy(() => TargetID) }).passthrough(), "Target.openDevTools.result", "commandResult", { method: "Target.openDevTools" }); +export const OpenDevToolsCommand = withCdpCommand("Target.openDevTools", OpenDevToolsParams, OpenDevToolsResult); export const AttachedToTargetEvent = withCdpMeta(z.object({ "sessionId": z.lazy(() => SessionID), "targetInfo": z.lazy(() => TargetInfo), "waitingForDebugger": z.boolean() }).passthrough(), "Target.attachedToTarget", "event", { phase: "event" }); export const DetachedFromTargetEvent = withCdpMeta(z.object({ "sessionId": z.lazy(() => SessionID), "targetId": z.lazy(() => TargetID).optional() }).passthrough(), "Target.detachedFromTarget", "event", { phase: "event" }); export const ReceivedMessageFromTargetEvent = withCdpMeta(z.object({ "sessionId": z.lazy(() => SessionID), "message": z.string(), "targetId": z.lazy(() => TargetID).optional() }).passthrough(), "Target.receivedMessageFromTarget", "event", { phase: "event" }); @@ -113,25 +132,25 @@ export const zod = { TargetInfoChangedEvent: TargetInfoChangedEvent, } as const; export const commands = { - "Target.activateTarget": { params: ActivateTargetParams, result: ActivateTargetResult }, - "Target.attachToTarget": { params: AttachToTargetParams, result: AttachToTargetResult }, - "Target.attachToBrowserTarget": { params: AttachToBrowserTargetParams, result: AttachToBrowserTargetResult }, - "Target.closeTarget": { params: CloseTargetParams, result: CloseTargetResult }, - "Target.exposeDevToolsProtocol": { params: ExposeDevToolsProtocolParams, result: ExposeDevToolsProtocolResult }, - "Target.createBrowserContext": { params: CreateBrowserContextParams, result: CreateBrowserContextResult }, - "Target.getBrowserContexts": { params: GetBrowserContextsParams, result: GetBrowserContextsResult }, - "Target.createTarget": { params: CreateTargetParams, result: CreateTargetResult }, - "Target.detachFromTarget": { params: DetachFromTargetParams, result: DetachFromTargetResult }, - "Target.disposeBrowserContext": { params: DisposeBrowserContextParams, result: DisposeBrowserContextResult }, - "Target.getTargetInfo": { params: GetTargetInfoParams, result: GetTargetInfoResult }, - "Target.getTargets": { params: GetTargetsParams, result: GetTargetsResult }, - "Target.sendMessageToTarget": { params: SendMessageToTargetParams, result: SendMessageToTargetResult }, - "Target.setAutoAttach": { params: SetAutoAttachParams, result: SetAutoAttachResult }, - "Target.autoAttachRelated": { params: AutoAttachRelatedParams, result: AutoAttachRelatedResult }, - "Target.setDiscoverTargets": { params: SetDiscoverTargetsParams, result: SetDiscoverTargetsResult }, - "Target.setRemoteLocations": { params: SetRemoteLocationsParams, result: SetRemoteLocationsResult }, - "Target.getDevToolsTarget": { params: GetDevToolsTargetParams, result: GetDevToolsTargetResult }, - "Target.openDevTools": { params: OpenDevToolsParams, result: OpenDevToolsResult }, + "Target.activateTarget": ActivateTargetCommand, + "Target.attachToTarget": AttachToTargetCommand, + "Target.attachToBrowserTarget": AttachToBrowserTargetCommand, + "Target.closeTarget": CloseTargetCommand, + "Target.exposeDevToolsProtocol": ExposeDevToolsProtocolCommand, + "Target.createBrowserContext": CreateBrowserContextCommand, + "Target.getBrowserContexts": GetBrowserContextsCommand, + "Target.createTarget": CreateTargetCommand, + "Target.detachFromTarget": DetachFromTargetCommand, + "Target.disposeBrowserContext": DisposeBrowserContextCommand, + "Target.getTargetInfo": GetTargetInfoCommand, + "Target.getTargets": GetTargetsCommand, + "Target.sendMessageToTarget": SendMessageToTargetCommand, + "Target.setAutoAttach": SetAutoAttachCommand, + "Target.autoAttachRelated": AutoAttachRelatedCommand, + "Target.setDiscoverTargets": SetDiscoverTargetsCommand, + "Target.setRemoteLocations": SetRemoteLocationsCommand, + "Target.getDevToolsTarget": GetDevToolsTargetCommand, + "Target.openDevTools": OpenDevToolsCommand, } as const; export const events = { "Target.attachedToTarget": AttachedToTargetEvent, diff --git a/js/src/types/generated/zod/Tethering.ts b/js/src/types/generated/zod/Tethering.ts index 4ae9eaf..a18e0fd 100644 --- a/js/src/types/generated/zod/Tethering.ts +++ b/js/src/types/generated/zod/Tethering.ts @@ -1,12 +1,14 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const BindParams = withCdpMeta(z.object({ "port": z.number().int() }).passthrough(), "Tethering.bind.params", "commandParams", { method: "Tethering.bind" }); export const BindResult = withCdpMeta(z.object({ }).passthrough(), "Tethering.bind.result", "commandResult", { method: "Tethering.bind" }); +export const BindCommand = withCdpCommand("Tethering.bind", BindParams, BindResult); export const UnbindParams = withCdpMeta(z.object({ "port": z.number().int() }).passthrough(), "Tethering.unbind.params", "commandParams", { method: "Tethering.unbind" }); export const UnbindResult = withCdpMeta(z.object({ }).passthrough(), "Tethering.unbind.result", "commandResult", { method: "Tethering.unbind" }); +export const UnbindCommand = withCdpCommand("Tethering.unbind", UnbindParams, UnbindResult); export const AcceptedEvent = withCdpMeta(z.object({ "port": z.number().int(), "connectionId": z.string() }).passthrough(), "Tethering.accepted", "event", { phase: "event" }); export const zod = { @@ -17,8 +19,8 @@ export const zod = { AcceptedEvent: AcceptedEvent, } as const; export const commands = { - "Tethering.bind": { params: BindParams, result: BindResult }, - "Tethering.unbind": { params: UnbindParams, result: UnbindResult }, + "Tethering.bind": BindCommand, + "Tethering.unbind": UnbindCommand, } as const; export const events = { "Tethering.accepted": AcceptedEvent, diff --git a/js/src/types/generated/zod/Tracing.ts b/js/src/types/generated/zod/Tracing.ts index ec4c11c..8634c26 100644 --- a/js/src/types/generated/zod/Tracing.ts +++ b/js/src/types/generated/zod/Tracing.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as IO from "./IO.js"; export const MemoryDumpConfig = withCdpMeta(z.record(z.string(), z.unknown()), "Tracing.MemoryDumpConfig", "type"); @@ -12,16 +12,22 @@ export const MemoryDumpLevelOfDetail = withCdpMeta(z.enum(["background", "light" export const TracingBackend = withCdpMeta(z.enum(["auto", "chrome", "system"]), "Tracing.TracingBackend", "type"); export const EndParams = withCdpMeta(z.object({ }).passthrough(), "Tracing.end.params", "commandParams", { method: "Tracing.end" }); export const EndResult = withCdpMeta(z.object({ }).passthrough(), "Tracing.end.result", "commandResult", { method: "Tracing.end" }); +export const EndCommand = withCdpCommand("Tracing.end", EndParams, EndResult); export const GetCategoriesParams = withCdpMeta(z.object({ }).passthrough(), "Tracing.getCategories.params", "commandParams", { method: "Tracing.getCategories" }); export const GetCategoriesResult = withCdpMeta(z.object({ "categories": z.array(z.string()) }).passthrough(), "Tracing.getCategories.result", "commandResult", { method: "Tracing.getCategories" }); +export const GetCategoriesCommand = withCdpCommand("Tracing.getCategories", GetCategoriesParams, GetCategoriesResult); export const GetTrackEventDescriptorParams = withCdpMeta(z.object({ }).passthrough(), "Tracing.getTrackEventDescriptor.params", "commandParams", { method: "Tracing.getTrackEventDescriptor" }); export const GetTrackEventDescriptorResult = withCdpMeta(z.object({ "descriptor": z.string() }).passthrough(), "Tracing.getTrackEventDescriptor.result", "commandResult", { method: "Tracing.getTrackEventDescriptor" }); +export const GetTrackEventDescriptorCommand = withCdpCommand("Tracing.getTrackEventDescriptor", GetTrackEventDescriptorParams, GetTrackEventDescriptorResult); export const RecordClockSyncMarkerParams = withCdpMeta(z.object({ "syncId": z.string() }).passthrough(), "Tracing.recordClockSyncMarker.params", "commandParams", { method: "Tracing.recordClockSyncMarker" }); export const RecordClockSyncMarkerResult = withCdpMeta(z.object({ }).passthrough(), "Tracing.recordClockSyncMarker.result", "commandResult", { method: "Tracing.recordClockSyncMarker" }); +export const RecordClockSyncMarkerCommand = withCdpCommand("Tracing.recordClockSyncMarker", RecordClockSyncMarkerParams, RecordClockSyncMarkerResult); export const RequestMemoryDumpParams = withCdpMeta(z.object({ "deterministic": z.boolean().optional(), "levelOfDetail": z.lazy(() => MemoryDumpLevelOfDetail).optional() }).passthrough(), "Tracing.requestMemoryDump.params", "commandParams", { method: "Tracing.requestMemoryDump" }); export const RequestMemoryDumpResult = withCdpMeta(z.object({ "dumpGuid": z.string(), "success": z.boolean() }).passthrough(), "Tracing.requestMemoryDump.result", "commandResult", { method: "Tracing.requestMemoryDump" }); +export const RequestMemoryDumpCommand = withCdpCommand("Tracing.requestMemoryDump", RequestMemoryDumpParams, RequestMemoryDumpResult); export const StartParams = withCdpMeta(z.object({ "categories": z.string().optional(), "options": z.string().optional(), "bufferUsageReportingInterval": z.number().optional(), "transferMode": z.enum(["ReportEvents", "ReturnAsStream"]).optional(), "streamFormat": z.lazy(() => StreamFormat).optional(), "streamCompression": z.lazy(() => StreamCompression).optional(), "traceConfig": z.lazy(() => TraceConfig).optional(), "perfettoConfig": z.string().optional(), "tracingBackend": z.lazy(() => TracingBackend).optional() }).passthrough(), "Tracing.start.params", "commandParams", { method: "Tracing.start" }); export const StartResult = withCdpMeta(z.object({ }).passthrough(), "Tracing.start.result", "commandResult", { method: "Tracing.start" }); +export const StartCommand = withCdpCommand("Tracing.start", StartParams, StartResult); export const BufferUsageEvent = withCdpMeta(z.object({ "percentFull": z.number().optional(), "eventCount": z.number().optional(), "value": z.number().optional() }).passthrough(), "Tracing.bufferUsage", "event", { phase: "event" }); export const DataCollectedEvent = withCdpMeta(z.object({ "value": z.array(z.record(z.string(), z.unknown())) }).passthrough(), "Tracing.dataCollected", "event", { phase: "event" }); export const TracingCompleteEvent = withCdpMeta(z.object({ "dataLossOccurred": z.boolean(), "stream": z.lazy(() => IO.StreamHandle).optional(), "traceFormat": z.lazy(() => StreamFormat).optional(), "streamCompression": z.lazy(() => StreamCompression).optional() }).passthrough(), "Tracing.tracingComplete", "event", { phase: "event" }); @@ -50,12 +56,12 @@ export const zod = { TracingCompleteEvent: TracingCompleteEvent, } as const; export const commands = { - "Tracing.end": { params: EndParams, result: EndResult }, - "Tracing.getCategories": { params: GetCategoriesParams, result: GetCategoriesResult }, - "Tracing.getTrackEventDescriptor": { params: GetTrackEventDescriptorParams, result: GetTrackEventDescriptorResult }, - "Tracing.recordClockSyncMarker": { params: RecordClockSyncMarkerParams, result: RecordClockSyncMarkerResult }, - "Tracing.requestMemoryDump": { params: RequestMemoryDumpParams, result: RequestMemoryDumpResult }, - "Tracing.start": { params: StartParams, result: StartResult }, + "Tracing.end": EndCommand, + "Tracing.getCategories": GetCategoriesCommand, + "Tracing.getTrackEventDescriptor": GetTrackEventDescriptorCommand, + "Tracing.recordClockSyncMarker": RecordClockSyncMarkerCommand, + "Tracing.requestMemoryDump": RequestMemoryDumpCommand, + "Tracing.start": StartCommand, } as const; export const events = { "Tracing.bufferUsage": BufferUsageEvent, diff --git a/js/src/types/generated/zod/WebAudio.ts b/js/src/types/generated/zod/WebAudio.ts index 3169347..f67e3bd 100644 --- a/js/src/types/generated/zod/WebAudio.ts +++ b/js/src/types/generated/zod/WebAudio.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const GraphObjectId = withCdpMeta(z.string(), "WebAudio.GraphObjectId", "type"); export const ContextType = withCdpMeta(z.enum(["realtime", "offline"]), "WebAudio.ContextType", "type"); @@ -18,10 +18,13 @@ export const AudioNode = withCdpMeta(z.object({ "nodeId": z.lazy(() => GraphObje export const AudioParam = withCdpMeta(z.object({ "paramId": z.lazy(() => GraphObjectId), "nodeId": z.lazy(() => GraphObjectId), "contextId": z.lazy(() => GraphObjectId), "paramType": z.lazy(() => ParamType), "rate": z.lazy(() => AutomationRate), "defaultValue": z.number(), "minValue": z.number(), "maxValue": z.number() }).passthrough(), "WebAudio.AudioParam", "type"); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "WebAudio.enable.params", "commandParams", { method: "WebAudio.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "WebAudio.enable.result", "commandResult", { method: "WebAudio.enable" }); +export const EnableCommand = withCdpCommand("WebAudio.enable", EnableParams, EnableResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "WebAudio.disable.params", "commandParams", { method: "WebAudio.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "WebAudio.disable.result", "commandResult", { method: "WebAudio.disable" }); +export const DisableCommand = withCdpCommand("WebAudio.disable", DisableParams, DisableResult); export const GetRealtimeDataParams = withCdpMeta(z.object({ "contextId": z.lazy(() => GraphObjectId) }).passthrough(), "WebAudio.getRealtimeData.params", "commandParams", { method: "WebAudio.getRealtimeData" }); export const GetRealtimeDataResult = withCdpMeta(z.object({ "realtimeData": z.lazy(() => ContextRealtimeData) }).passthrough(), "WebAudio.getRealtimeData.result", "commandResult", { method: "WebAudio.getRealtimeData" }); +export const GetRealtimeDataCommand = withCdpCommand("WebAudio.getRealtimeData", GetRealtimeDataParams, GetRealtimeDataResult); export const ContextCreatedEvent = withCdpMeta(z.object({ "context": z.lazy(() => BaseAudioContext) }).passthrough(), "WebAudio.contextCreated", "event", { phase: "event" }); export const ContextWillBeDestroyedEvent = withCdpMeta(z.object({ "contextId": z.lazy(() => GraphObjectId) }).passthrough(), "WebAudio.contextWillBeDestroyed", "event", { phase: "event" }); export const ContextChangedEvent = withCdpMeta(z.object({ "context": z.lazy(() => BaseAudioContext) }).passthrough(), "WebAudio.contextChanged", "event", { phase: "event" }); @@ -71,9 +74,9 @@ export const zod = { NodeParamDisconnectedEvent: NodeParamDisconnectedEvent, } as const; export const commands = { - "WebAudio.enable": { params: EnableParams, result: EnableResult }, - "WebAudio.disable": { params: DisableParams, result: DisableResult }, - "WebAudio.getRealtimeData": { params: GetRealtimeDataParams, result: GetRealtimeDataResult }, + "WebAudio.enable": EnableCommand, + "WebAudio.disable": DisableCommand, + "WebAudio.getRealtimeData": GetRealtimeDataCommand, } as const; export const events = { "WebAudio.contextCreated": ContextCreatedEvent, diff --git a/js/src/types/generated/zod/WebAuthn.ts b/js/src/types/generated/zod/WebAuthn.ts index 76755a9..dc4fb32 100644 --- a/js/src/types/generated/zod/WebAuthn.ts +++ b/js/src/types/generated/zod/WebAuthn.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; export const AuthenticatorId = withCdpMeta(z.string(), "WebAuthn.AuthenticatorId", "type"); export const AuthenticatorProtocol = withCdpMeta(z.enum(["u2f", "ctap2"]), "WebAuthn.AuthenticatorProtocol", "type"); @@ -11,30 +11,43 @@ export const VirtualAuthenticatorOptions = withCdpMeta(z.object({ "protocol": z. export const Credential = withCdpMeta(z.object({ "credentialId": z.string(), "isResidentCredential": z.boolean(), "rpId": z.string().optional(), "privateKey": z.string(), "userHandle": z.string().optional(), "signCount": z.number().int(), "largeBlob": z.string().optional(), "backupEligibility": z.boolean().optional(), "backupState": z.boolean().optional(), "userName": z.string().optional(), "userDisplayName": z.string().optional() }).passthrough(), "WebAuthn.Credential", "type"); export const EnableParams = withCdpMeta(z.object({ "enableUI": z.boolean().optional() }).passthrough(), "WebAuthn.enable.params", "commandParams", { method: "WebAuthn.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "WebAuthn.enable.result", "commandResult", { method: "WebAuthn.enable" }); +export const EnableCommand = withCdpCommand("WebAuthn.enable", EnableParams, EnableResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "WebAuthn.disable.params", "commandParams", { method: "WebAuthn.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "WebAuthn.disable.result", "commandResult", { method: "WebAuthn.disable" }); +export const DisableCommand = withCdpCommand("WebAuthn.disable", DisableParams, DisableResult); export const AddVirtualAuthenticatorParams = withCdpMeta(z.object({ "options": z.lazy(() => VirtualAuthenticatorOptions) }).passthrough(), "WebAuthn.addVirtualAuthenticator.params", "commandParams", { method: "WebAuthn.addVirtualAuthenticator" }); export const AddVirtualAuthenticatorResult = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId) }).passthrough(), "WebAuthn.addVirtualAuthenticator.result", "commandResult", { method: "WebAuthn.addVirtualAuthenticator" }); +export const AddVirtualAuthenticatorCommand = withCdpCommand("WebAuthn.addVirtualAuthenticator", AddVirtualAuthenticatorParams, AddVirtualAuthenticatorResult); export const SetResponseOverrideBitsParams = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId), "isBogusSignature": z.boolean().optional(), "isBadUV": z.boolean().optional(), "isBadUP": z.boolean().optional() }).passthrough(), "WebAuthn.setResponseOverrideBits.params", "commandParams", { method: "WebAuthn.setResponseOverrideBits" }); export const SetResponseOverrideBitsResult = withCdpMeta(z.object({ }).passthrough(), "WebAuthn.setResponseOverrideBits.result", "commandResult", { method: "WebAuthn.setResponseOverrideBits" }); +export const SetResponseOverrideBitsCommand = withCdpCommand("WebAuthn.setResponseOverrideBits", SetResponseOverrideBitsParams, SetResponseOverrideBitsResult); export const RemoveVirtualAuthenticatorParams = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId) }).passthrough(), "WebAuthn.removeVirtualAuthenticator.params", "commandParams", { method: "WebAuthn.removeVirtualAuthenticator" }); export const RemoveVirtualAuthenticatorResult = withCdpMeta(z.object({ }).passthrough(), "WebAuthn.removeVirtualAuthenticator.result", "commandResult", { method: "WebAuthn.removeVirtualAuthenticator" }); +export const RemoveVirtualAuthenticatorCommand = withCdpCommand("WebAuthn.removeVirtualAuthenticator", RemoveVirtualAuthenticatorParams, RemoveVirtualAuthenticatorResult); export const AddCredentialParams = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId), "credential": z.lazy(() => Credential) }).passthrough(), "WebAuthn.addCredential.params", "commandParams", { method: "WebAuthn.addCredential" }); export const AddCredentialResult = withCdpMeta(z.object({ }).passthrough(), "WebAuthn.addCredential.result", "commandResult", { method: "WebAuthn.addCredential" }); +export const AddCredentialCommand = withCdpCommand("WebAuthn.addCredential", AddCredentialParams, AddCredentialResult); export const GetCredentialParams = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId), "credentialId": z.string() }).passthrough(), "WebAuthn.getCredential.params", "commandParams", { method: "WebAuthn.getCredential" }); export const GetCredentialResult = withCdpMeta(z.object({ "credential": z.lazy(() => Credential) }).passthrough(), "WebAuthn.getCredential.result", "commandResult", { method: "WebAuthn.getCredential" }); +export const GetCredentialCommand = withCdpCommand("WebAuthn.getCredential", GetCredentialParams, GetCredentialResult); export const GetCredentialsParams = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId) }).passthrough(), "WebAuthn.getCredentials.params", "commandParams", { method: "WebAuthn.getCredentials" }); export const GetCredentialsResult = withCdpMeta(z.object({ "credentials": z.array(z.lazy(() => Credential)) }).passthrough(), "WebAuthn.getCredentials.result", "commandResult", { method: "WebAuthn.getCredentials" }); +export const GetCredentialsCommand = withCdpCommand("WebAuthn.getCredentials", GetCredentialsParams, GetCredentialsResult); export const RemoveCredentialParams = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId), "credentialId": z.string() }).passthrough(), "WebAuthn.removeCredential.params", "commandParams", { method: "WebAuthn.removeCredential" }); export const RemoveCredentialResult = withCdpMeta(z.object({ }).passthrough(), "WebAuthn.removeCredential.result", "commandResult", { method: "WebAuthn.removeCredential" }); +export const RemoveCredentialCommand = withCdpCommand("WebAuthn.removeCredential", RemoveCredentialParams, RemoveCredentialResult); export const ClearCredentialsParams = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId) }).passthrough(), "WebAuthn.clearCredentials.params", "commandParams", { method: "WebAuthn.clearCredentials" }); export const ClearCredentialsResult = withCdpMeta(z.object({ }).passthrough(), "WebAuthn.clearCredentials.result", "commandResult", { method: "WebAuthn.clearCredentials" }); +export const ClearCredentialsCommand = withCdpCommand("WebAuthn.clearCredentials", ClearCredentialsParams, ClearCredentialsResult); export const SetUserVerifiedParams = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId), "isUserVerified": z.boolean() }).passthrough(), "WebAuthn.setUserVerified.params", "commandParams", { method: "WebAuthn.setUserVerified" }); export const SetUserVerifiedResult = withCdpMeta(z.object({ }).passthrough(), "WebAuthn.setUserVerified.result", "commandResult", { method: "WebAuthn.setUserVerified" }); +export const SetUserVerifiedCommand = withCdpCommand("WebAuthn.setUserVerified", SetUserVerifiedParams, SetUserVerifiedResult); export const SetAutomaticPresenceSimulationParams = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId), "enabled": z.boolean() }).passthrough(), "WebAuthn.setAutomaticPresenceSimulation.params", "commandParams", { method: "WebAuthn.setAutomaticPresenceSimulation" }); export const SetAutomaticPresenceSimulationResult = withCdpMeta(z.object({ }).passthrough(), "WebAuthn.setAutomaticPresenceSimulation.result", "commandResult", { method: "WebAuthn.setAutomaticPresenceSimulation" }); +export const SetAutomaticPresenceSimulationCommand = withCdpCommand("WebAuthn.setAutomaticPresenceSimulation", SetAutomaticPresenceSimulationParams, SetAutomaticPresenceSimulationResult); export const SetCredentialPropertiesParams = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId), "credentialId": z.string(), "backupEligibility": z.boolean().optional(), "backupState": z.boolean().optional() }).passthrough(), "WebAuthn.setCredentialProperties.params", "commandParams", { method: "WebAuthn.setCredentialProperties" }); export const SetCredentialPropertiesResult = withCdpMeta(z.object({ }).passthrough(), "WebAuthn.setCredentialProperties.result", "commandResult", { method: "WebAuthn.setCredentialProperties" }); +export const SetCredentialPropertiesCommand = withCdpCommand("WebAuthn.setCredentialProperties", SetCredentialPropertiesParams, SetCredentialPropertiesResult); export const CredentialAddedEvent = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId), "credential": z.lazy(() => Credential) }).passthrough(), "WebAuthn.credentialAdded", "event", { phase: "event" }); export const CredentialDeletedEvent = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId), "credentialId": z.string() }).passthrough(), "WebAuthn.credentialDeleted", "event", { phase: "event" }); export const CredentialUpdatedEvent = withCdpMeta(z.object({ "authenticatorId": z.lazy(() => AuthenticatorId), "credential": z.lazy(() => Credential) }).passthrough(), "WebAuthn.credentialUpdated", "event", { phase: "event" }); @@ -79,19 +92,19 @@ export const zod = { CredentialAssertedEvent: CredentialAssertedEvent, } as const; export const commands = { - "WebAuthn.enable": { params: EnableParams, result: EnableResult }, - "WebAuthn.disable": { params: DisableParams, result: DisableResult }, - "WebAuthn.addVirtualAuthenticator": { params: AddVirtualAuthenticatorParams, result: AddVirtualAuthenticatorResult }, - "WebAuthn.setResponseOverrideBits": { params: SetResponseOverrideBitsParams, result: SetResponseOverrideBitsResult }, - "WebAuthn.removeVirtualAuthenticator": { params: RemoveVirtualAuthenticatorParams, result: RemoveVirtualAuthenticatorResult }, - "WebAuthn.addCredential": { params: AddCredentialParams, result: AddCredentialResult }, - "WebAuthn.getCredential": { params: GetCredentialParams, result: GetCredentialResult }, - "WebAuthn.getCredentials": { params: GetCredentialsParams, result: GetCredentialsResult }, - "WebAuthn.removeCredential": { params: RemoveCredentialParams, result: RemoveCredentialResult }, - "WebAuthn.clearCredentials": { params: ClearCredentialsParams, result: ClearCredentialsResult }, - "WebAuthn.setUserVerified": { params: SetUserVerifiedParams, result: SetUserVerifiedResult }, - "WebAuthn.setAutomaticPresenceSimulation": { params: SetAutomaticPresenceSimulationParams, result: SetAutomaticPresenceSimulationResult }, - "WebAuthn.setCredentialProperties": { params: SetCredentialPropertiesParams, result: SetCredentialPropertiesResult }, + "WebAuthn.enable": EnableCommand, + "WebAuthn.disable": DisableCommand, + "WebAuthn.addVirtualAuthenticator": AddVirtualAuthenticatorCommand, + "WebAuthn.setResponseOverrideBits": SetResponseOverrideBitsCommand, + "WebAuthn.removeVirtualAuthenticator": RemoveVirtualAuthenticatorCommand, + "WebAuthn.addCredential": AddCredentialCommand, + "WebAuthn.getCredential": GetCredentialCommand, + "WebAuthn.getCredentials": GetCredentialsCommand, + "WebAuthn.removeCredential": RemoveCredentialCommand, + "WebAuthn.clearCredentials": ClearCredentialsCommand, + "WebAuthn.setUserVerified": SetUserVerifiedCommand, + "WebAuthn.setAutomaticPresenceSimulation": SetAutomaticPresenceSimulationCommand, + "WebAuthn.setCredentialProperties": SetCredentialPropertiesCommand, } as const; export const events = { "WebAuthn.credentialAdded": CredentialAddedEvent, diff --git a/js/src/types/generated/zod/WebMCP.ts b/js/src/types/generated/zod/WebMCP.ts index 0ca06d3..5fe6bd0 100644 --- a/js/src/types/generated/zod/WebMCP.ts +++ b/js/src/types/generated/zod/WebMCP.ts @@ -1,7 +1,7 @@ // Generated by types/codegen.ts from devtools-protocol@0.0.1621552. Do not edit by hand. // @ts-nocheck -- recursive protocol schemas intentionally use lazy self/cross references. import { z } from "zod"; -import { withCdpMeta } from "./helpers.js"; +import { withCdpCommand, withCdpMeta } from "./helpers.js"; import * as DOM from "./DOM.js"; import * as Page from "./Page.js"; import * as Runtime from "./Runtime.js"; @@ -12,12 +12,16 @@ export const Tool = withCdpMeta(z.object({ "name": z.string(), "description": z. export const RemovedTool = withCdpMeta(z.object({ "name": z.string(), "frameId": z.lazy(() => Page.FrameId) }).passthrough(), "WebMCP.RemovedTool", "type"); export const EnableParams = withCdpMeta(z.object({ }).passthrough(), "WebMCP.enable.params", "commandParams", { method: "WebMCP.enable" }); export const EnableResult = withCdpMeta(z.object({ }).passthrough(), "WebMCP.enable.result", "commandResult", { method: "WebMCP.enable" }); +export const EnableCommand = withCdpCommand("WebMCP.enable", EnableParams, EnableResult); export const DisableParams = withCdpMeta(z.object({ }).passthrough(), "WebMCP.disable.params", "commandParams", { method: "WebMCP.disable" }); export const DisableResult = withCdpMeta(z.object({ }).passthrough(), "WebMCP.disable.result", "commandResult", { method: "WebMCP.disable" }); +export const DisableCommand = withCdpCommand("WebMCP.disable", DisableParams, DisableResult); export const InvokeToolParams = withCdpMeta(z.object({ "frameId": z.lazy(() => Page.FrameId), "toolName": z.string(), "input": z.record(z.string(), z.unknown()) }).passthrough(), "WebMCP.invokeTool.params", "commandParams", { method: "WebMCP.invokeTool" }); export const InvokeToolResult = withCdpMeta(z.object({ "invocationId": z.string() }).passthrough(), "WebMCP.invokeTool.result", "commandResult", { method: "WebMCP.invokeTool" }); +export const InvokeToolCommand = withCdpCommand("WebMCP.invokeTool", InvokeToolParams, InvokeToolResult); export const CancelInvocationParams = withCdpMeta(z.object({ "invocationId": z.string() }).passthrough(), "WebMCP.cancelInvocation.params", "commandParams", { method: "WebMCP.cancelInvocation" }); export const CancelInvocationResult = withCdpMeta(z.object({ }).passthrough(), "WebMCP.cancelInvocation.result", "commandResult", { method: "WebMCP.cancelInvocation" }); +export const CancelInvocationCommand = withCdpCommand("WebMCP.cancelInvocation", CancelInvocationParams, CancelInvocationResult); export const ToolsAddedEvent = withCdpMeta(z.object({ "tools": z.array(z.lazy(() => Tool)) }).passthrough(), "WebMCP.toolsAdded", "event", { phase: "event" }); export const ToolsRemovedEvent = withCdpMeta(z.object({ "tools": z.array(z.lazy(() => RemovedTool)) }).passthrough(), "WebMCP.toolsRemoved", "event", { phase: "event" }); export const ToolInvokedEvent = withCdpMeta(z.object({ "toolName": z.string(), "frameId": z.lazy(() => Page.FrameId), "invocationId": z.string(), "input": z.string() }).passthrough(), "WebMCP.toolInvoked", "event", { phase: "event" }); @@ -42,10 +46,10 @@ export const zod = { ToolRespondedEvent: ToolRespondedEvent, } as const; export const commands = { - "WebMCP.enable": { params: EnableParams, result: EnableResult }, - "WebMCP.disable": { params: DisableParams, result: DisableResult }, - "WebMCP.invokeTool": { params: InvokeToolParams, result: InvokeToolResult }, - "WebMCP.cancelInvocation": { params: CancelInvocationParams, result: CancelInvocationResult }, + "WebMCP.enable": EnableCommand, + "WebMCP.disable": DisableCommand, + "WebMCP.invokeTool": InvokeToolCommand, + "WebMCP.cancelInvocation": CancelInvocationCommand, } as const; export const events = { "WebMCP.toolsAdded": ToolsAddedEvent, diff --git a/js/src/types/generated/zod/helpers.ts b/js/src/types/generated/zod/helpers.ts index 805339a..a73fe65 100644 --- a/js/src/types/generated/zod/helpers.ts +++ b/js/src/types/generated/zod/helpers.ts @@ -2,6 +2,7 @@ import type { z } from "zod"; export type CdpNamedSchema = T & { readonly id: string; readonly name: string; readonly kind: string; meta(): { id: string; name: string; kind: string } }; +export type CdpCommandSchema> = z.ZodType>, Result extends z.ZodType> = z.ZodType>, Name extends string = string> = { readonly id: Name; readonly name: Name; readonly kind: "command"; readonly params: Params; readonly result: Result; meta(): { id: Name; name: Name; kind: "command" } }; export const withCdpMeta = (schema: T, id: string, kind: string, extra = {}): CdpNamedSchema => { const meta = { id, name: id, kind, ...extra }; const named = schema.meta(meta); @@ -12,3 +13,14 @@ export const withCdpMeta = (schema: T, id: string, kind: st }); return named as CdpNamedSchema; }; +export const withCdpCommand = >, Result extends z.ZodType>>(id: Name, params: Params, result: Result): CdpCommandSchema => { + const meta = { id, name: id, kind: "command" as const }; + return { + id, + name: id, + kind: "command", + params, + result, + meta: () => meta, + }; +}; diff --git a/js/src/types/modcdp.ts b/js/src/types/modcdp.ts index b19e85a..09476c6 100644 --- a/js/src/types/modcdp.ts +++ b/js/src/types/modcdp.ts @@ -221,8 +221,82 @@ export const ModCDPPingLatencySchema = z.object({ }); export type ModCDPPingLatency = z.infer; +export const ModCDPGetTopologyParamsSchema = z + .object({ + rootTargetId: z.string().optional(), + targetId: z.string().optional(), + active: z.boolean().optional(), + }) + .passthrough(); +export type ModCDPGetTopologyParams = z.infer; + +export const ModCDPTopologyFrameSchema = z + .object({ + targetId: z.string(), + url: z.string().nullable().optional(), + parentFrameId: z.string().nullable().optional(), + outerBackendNodeId: z.number().int().nullable().optional(), + }) + .passthrough(); +export type ModCDPTopologyFrame = z.infer; + +export const ModCDPTopologyDomRootSchema = z + .object({ + kind: z.enum(["document", "shadow"]), + frameId: z.string(), + outerBackendNodeId: z.number().int().nullable().optional(), + innerBackendNodeId: z.number().int().nullable().optional(), + mode: z.enum(["open", "closed", "user-agent"]).optional(), + executionContextId: z.number().int().optional(), + uniqueContextId: z.string().optional(), + }) + .passthrough(); +export type ModCDPTopologyDomRoot = z.infer; + +export const ModCDPTopologyTargetSchema = z + .object({ + targetId: z.string(), + type: z.string(), + title: z.string().optional(), + url: z.string().optional(), + attached: z.boolean().optional(), + parentId: z.string().optional(), + parentFrameId: z.string().optional(), + sessionId: z.string().nullable().optional(), + }) + .passthrough(); +export type ModCDPTopologyTarget = z.infer; + +export const ModCDPTopologyExecutionContextSchema = z + .object({ + id: z.number().int(), + origin: z.string().optional(), + name: z.string().optional(), + uniqueId: z.string().optional(), + auxData: z.record(z.string(), z.unknown()).optional(), + sessionId: z.string().nullable(), + targetId: z.string(), + frameId: z.string().nullable().optional(), + world: z.string(), + }) + .passthrough(); +export type ModCDPTopologyExecutionContext = z.infer; + +export const ModCDPTopologySchema = z + .object({ + objectGroup: z.string(), + rootFrameId: z.string(), + frames: z.record(z.string(), ModCDPTopologyFrameSchema), + roots: z.record(z.string(), ModCDPTopologyDomRootSchema), + targets: z.record(z.string(), ModCDPTopologyTargetSchema), + contexts: z.record(z.string(), ModCDPTopologyExecutionContextSchema), + }) + .passthrough(); +export type ModCDPTopology = z.infer; + export const ModCDPCommandParamsSchema = z.union([ ModCDPEvaluateParamsSchema, + ModCDPGetTopologyParamsSchema, ModCDPAddCustomCommandParamsSchema, ModCDPAddCustomEventParamsSchema, ModCDPAddMiddlewareParamsSchema, @@ -241,6 +315,9 @@ export type ModCDPCommandResult = z.infer; export const ModCDPEvaluateResponseSchema = z.unknown(); export type ModCDPEvaluateResponse = z.infer; +export const ModCDPGetTopologyResponseSchema = ModCDPTopologySchema; +export type ModCDPGetTopologyResponse = z.infer; + export const ModCDPAddCustomCommandResponseSchema = z .object({ name: z.string(), @@ -420,6 +497,7 @@ export const Mod = { PayloadShape: ModCDPPayloadShapeSchema, PayloadSchemaSpec: ModCDPPayloadSchemaSpecSchema, EvaluateParams: ModCDPEvaluateParamsSchema, + GetTopologyParams: ModCDPGetTopologyParamsSchema, AddCustomCommandParams: ModCDPAddCustomCommandParamsSchema, AddCustomEventObjectParams: ModCDPAddCustomEventObjectParamsSchema, AddCustomEventParams: ModCDPAddCustomEventParamsSchema, @@ -432,9 +510,15 @@ export const Mod = { PingParams: ModCDPPingParamsSchema, PongEvent: ModCDPPongEventSchema, PingLatency: ModCDPPingLatencySchema, + TopologyFrame: ModCDPTopologyFrameSchema, + TopologyDomRoot: ModCDPTopologyDomRootSchema, + TopologyTarget: ModCDPTopologyTargetSchema, + TopologyExecutionContext: ModCDPTopologyExecutionContextSchema, + Topology: ModCDPTopologySchema, CommandParams: ModCDPCommandParamsSchema, CommandResult: ModCDPCommandResultSchema, EvaluateResponse: ModCDPEvaluateResponseSchema, + GetTopologyResponse: ModCDPGetTopologyResponseSchema, AddCustomCommandResponse: ModCDPAddCustomCommandResponseSchema, AddCustomEventResponse: ModCDPAddCustomEventResponseSchema, AddMiddlewareResponse: ModCDPAddMiddlewareResponseSchema, diff --git a/js/test/test.AutoSessionRouter.ts b/js/test/test.AutoSessionRouter.ts index b5e7414..41537c3 100644 --- a/js/test/test.AutoSessionRouter.ts +++ b/js/test/test.AutoSessionRouter.ts @@ -1,142 +1,104 @@ -import { once } from "node:events"; -import WebSocket from "ws"; -import { expect, test } from "vitest"; +import assert from "node:assert/strict"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { test } from "vitest"; -import { LocalBrowserLauncher } from "../src/launcher/LocalBrowserLauncher.js"; -import { AutoSessionRouter } from "../src/router/AutoSessionRouter.js"; +import { ModCDPClient } from "../src/client/ModCDPClient.js"; -test("AutoSessionRouter rejects pending execution context waiters when a session detaches", async () => { - const router = new AutoSessionRouter( - async () => ({}), - () => 5_000, - ); - const wait = router.waitForExecutionContext("detached-session", { - timeout_ms: 5_000, - }); +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const EXTENSION_PATH = path.resolve(HERE, "..", "..", "dist", "extension"); - router.recordProtocolEvent( - "Target.attachedToTarget", - { - sessionId: "detached-session", - targetInfo: { targetId: "target-1", type: "page" }, +test("AutoSessionRouter tracks real target sessions and execution contexts from live CDP events", async () => { + const cdp = new ModCDPClient({ + launcher: { + launcher_mode: "local", + launcher_options: { headless: true }, }, - null, - ); - router.recordProtocolEvent("Target.detachedFromTarget", { sessionId: "detached-session" }, null); - router.recordProtocolEvent("Runtime.executionContextCreated", { context: { id: 42 } }, "detached-session"); - - await expect(wait).rejects.toThrow( - "Runtime execution context wait cancelled because session detached-session detached.", - ); - expect(router.sessionIdForTarget("target-1")).toBeNull(); - expect(router.execution_contexts.get("detached-session")).toBeUndefined(); -}, 5_000); - -test("AutoSessionRouter bounds detached session guards and clears them when a session reattaches", () => { - const router = new AutoSessionRouter( - async () => ({}), - () => 5_000, - ); - - for (let index = 0; index < 1034; index += 1) { - router.recordProtocolEvent("Target.detachedFromTarget", { sessionId: `detached-session-${index}` }, null); - } - - const detached_sessions = (router as unknown as { detached_sessions: Map }).detached_sessions; - expect(detached_sessions.size).toBeLessThanOrEqual(1024); - - const recent_session_id = "detached-session-1033"; - router.recordProtocolEvent("Runtime.executionContextCreated", { context: { id: 42 } }, recent_session_id); - expect(router.execution_contexts.get(recent_session_id)).toBeUndefined(); - - router.recordProtocolEvent( - "Target.attachedToTarget", - { - sessionId: recent_session_id, - targetInfo: { targetId: "target-reattached", type: "page" }, + upstream: { upstream_mode: "ws" }, + injector: { + injector_mode: "auto", + injector_extension_path: EXTENSION_PATH, + injector_service_worker_url_suffixes: ["/modcdp/service_worker.js"], + injector_trust_service_worker_target: true, + }, + client: { + client_routes: { + "Mod.*": "service_worker", + "Custom.*": "service_worker", + "*.*": "direct_cdp", + }, }, - null, - ); - router.recordProtocolEvent("Runtime.executionContextCreated", { context: { id: 43 } }, recent_session_id); - - expect(router.sessionIdForTarget("target-reattached")).toBe(recent_session_id); - expect(router.execution_contexts.get(recent_session_id)).toBe(43); -}); - -test("AutoSessionRouter tracks real target sessions and execution contexts", async () => { - const chrome = await new LocalBrowserLauncher({ - headless: true, - }).launch(); - const ws = new WebSocket(chrome.cdp_url!); - await once(ws, "open"); - let next_id = 1; - const pending = new Map) => void>(); - const router = new AutoSessionRouter( - (method, params = {}, session_id = null) => - send(method, params as Record, session_id) as Promise>, - () => 30_000, - ); - - function send(method: string, params: Record = {}, session_id: string | null = null) { - const id = next_id++; - ws.send( - JSON.stringify({ - id, - method, - params, - ...(session_id ? { sessionId: session_id } : {}), - }), - ); - return new Promise>((resolve, reject) => { - pending.set(id, (message) => { - if (message.error) reject(new Error(JSON.stringify(message.error))); - else resolve((message.result ?? {}) as Record); - }); - }); - } - - ws.on("message", (data) => { - const message = JSON.parse(data.toString()) as Record; - if (typeof message.id === "number") { - pending.get(message.id)?.(message); - pending.delete(message.id); - return; - } - if (typeof message.method !== "string") return; - router.recordProtocolEvent( - message.method, - message.params, - typeof message.sessionId === "string" ? message.sessionId : null, - ); }); + let targetId: string | null = null; + let pendingTargetId: string | null = null; try { - await send("Target.setAutoAttach", { - autoAttach: true, - waitForDebuggerOnStart: false, - flatten: true, - }); - await send("Target.setDiscoverTargets", { discover: true }); - const created = await send("Target.createTarget", { - url: "about:blank#modcdp-auto-session-router", + await cdp.connect(); + const created = await cdp.Target.createTarget({ url: "about:blank#modcdp-auto-session-router" }); + targetId = created.targetId; + await expectEventually(() => { + assert.equal(typeof cdp.auto_sessions.sessionId_from_targetId.get(targetId!), "string"); }); - const target_id = created.targetId as string; - await expect.poll(() => router.sessionIdForTarget(target_id), { timeout: 5_000 }).toEqual(expect.any(String)); - const session_id = router.sessionIdForTarget(target_id)!; + const sessionId = cdp.auto_sessions.sessionId_from_targetId.get(targetId); + assert.equal(typeof sessionId, "string"); - const context_promise = router.waitForExecutionContext(session_id, { + const contextPromise = cdp.auto_sessions.waitForExecutionContext(sessionId, { timeout_ms: 30_000, }); - await send("Runtime.enable", {}, session_id); - await expect(context_promise).resolves.toEqual(expect.any(Number)); - expect(router.execution_contexts.get(session_id)).toEqual(expect.any(Number)); + await cdp.send("Runtime.enable", {}, sessionId); + const contextId = await contextPromise; + assert.equal(typeof contextId, "number"); + assert.equal(cdp.auto_sessions.execution_contexts.get(sessionId), contextId); + + await cdp.Target.detachFromTarget({ sessionId }); + await expectEventually(() => { + assert.equal(cdp.auto_sessions.sessionId_from_targetId.get(targetId!), undefined); + }); + assert.equal(cdp.auto_sessions.execution_contexts.get(sessionId), undefined); + await cdp.Target.closeTarget({ targetId }).catch(() => ({})); + targetId = null; - await send("Target.detachFromTarget", { sessionId: session_id }); - await expect.poll(() => router.sessionIdForTarget(target_id), { timeout: 5_000 }).toBeNull(); - await send("Target.closeTarget", { targetId: target_id }).catch(() => ({})); + const pendingCreated = await cdp.Target.createTarget({ + url: "about:blank#modcdp-auto-session-router-pending-context", + }); + pendingTargetId = pendingCreated.targetId; + await expectEventually(() => { + assert.equal(typeof cdp.auto_sessions.sessionId_from_targetId.get(pendingTargetId!), "string"); + }); + const pendingSessionId = cdp.auto_sessions.sessionId_from_targetId.get(pendingTargetId); + assert.equal(typeof pendingSessionId, "string"); + const cancelledContextPromise = cdp.auto_sessions.waitForExecutionContext(pendingSessionId, { + timeout_ms: 30_000, + }); + const cancelledContextAssertion = assert.rejects( + cancelledContextPromise, + new RegExp(`Runtime execution context wait cancelled because session ${pendingSessionId} detached\\.`), + ); + await cdp.Target.detachFromTarget({ sessionId: pendingSessionId }); + await cancelledContextAssertion; + await expectEventually(() => { + assert.equal(cdp.auto_sessions.sessionId_from_targetId.get(pendingTargetId!), undefined); + }); + await cdp.Target.closeTarget({ targetId: pendingTargetId }).catch(() => ({})); + pendingTargetId = null; } finally { - ws.close(); - await once(ws, "close").catch(() => {}); - await chrome.close(); + if (targetId) await cdp.Target.closeTarget({ targetId }).catch(() => ({})); + if (pendingTargetId) await cdp.Target.closeTarget({ targetId: pendingTargetId }).catch(() => ({})); + await cdp.close(); } }, 60_000); + +async function expectEventually(assertion: () => void, timeoutMs = 10_000) { + const deadline = Date.now() + timeoutMs; + let lastError: unknown = null; + while (Date.now() < deadline) { + try { + assertion(); + return; + } catch (error) { + lastError = error; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + } + throw lastError instanceof Error ? lastError : new Error(String(lastError)); +} diff --git a/js/test/test.ModCDPClient.ts b/js/test/test.ModCDPClient.ts index afb40e6..085bce6 100644 --- a/js/test/test.ModCDPClient.ts +++ b/js/test/test.ModCDPClient.ts @@ -106,8 +106,8 @@ test("ModCDPClient normalizes nested config owners", () => { test("ModCDPClient dispatches root events before extension session is attached", () => { const cdp = new ModCDPClient(); const seen: string[] = []; - cdp.on("Target.targetCreated", (payload: { targetInfo?: { targetId?: string } }) => { - seen.push(String(payload.targetInfo?.targetId)); + cdp.on(cdp.Target.targetCreated, (payload) => { + seen.push(payload.targetInfo.targetId); }); cdp._onRecv({ @@ -130,10 +130,10 @@ test("ModCDPClient dispatches root events before extension session is attached", test("ModCDPClient event dispatch snapshots handlers when once removes itself", () => { const cdp = new ModCDPClient(); const seen: string[] = []; - cdp.once("Target.targetCreated", () => { + cdp.once(cdp.Target.targetCreated, () => { seen.push("once"); }); - cdp.on("Target.targetCreated", () => { + cdp.on(cdp.Target.targetCreated, () => { seen.push("persistent"); }); @@ -196,6 +196,7 @@ test("ModCDPClient connects with nested launch/upstream/extension/client/server launcher_mode: "local", launcher_options: { headless: true, + chrome_ready_timeout_ms: 60_000, }, }, upstream: { upstream_mode: "ws" }, @@ -407,15 +408,15 @@ test("ModCDPClient preserves explicit null server config", () => { assert.equal(cdp.server, null); }); -test("ModCDPClient only exposes injector attach after CDP send is available", () => { +test("ModCDPClient only exposes injector ensure after CDP send is available", () => { const cdp = new ModCDPClient(); const disconnected_config = cdp._baseInjectorConfig(null); assert.equal(disconnected_config.send, null); - assert.equal(disconnected_config.attachToTarget, null); + assert.equal(disconnected_config.ensureSessionForTarget, null); const connected_config = cdp._baseInjectorConfig(async () => ({})); assert.equal(typeof connected_config.send, "function"); - assert.equal(typeof connected_config.attachToTarget, "function"); + assert.equal(typeof connected_config.ensureSessionForTarget, "function"); }); test("ModCDPClient defaults launched ModCDP-server upstreams to extension auto", () => { diff --git a/js/test/test.ModCDPClientRoutedDefaultOverrides.ts b/js/test/test.ModCDPClientRoutedDefaultOverrides.ts index 24ba83a..c13022f 100644 --- a/js/test/test.ModCDPClientRoutedDefaultOverrides.ts +++ b/js/test/test.ModCDPClientRoutedDefaultOverrides.ts @@ -4,22 +4,16 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { ModCDPClient } from "../src/client/ModCDPClient.js"; -import { events } from "../src/types/generated/zod.js"; +import type { cdp } from "../src/types/generated/cdp.js"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const EXTENSION_PATH = path.resolve(HERE, "..", "..", "dist", "extension"); const DEFAULT_ROUTED_OVERRIDES_TEST_TIMEOUT_MS = 45_000; -function hasTargetInfo(value: unknown): value is { targetInfo: Record } { - if (value == null || typeof value !== "object" || Array.isArray(value)) return false; - const targetInfo = (value as Record).targetInfo; - return targetInfo != null && typeof targetInfo === "object" && !Array.isArray(targetInfo); -} - const getTargetsOverride = String.raw` async (params) => { const [upstream, tabs] = await Promise.all([ - ModCDP.sendLoopback("Target.getTargets", params), + cdp.upstream.send("Target.getTargets", params), chrome.tabs.query({}), ]); @@ -164,11 +158,22 @@ test( "expected at least one page target to be matched to a chrome.tabs tab id", ); + const topology = await cdp.Mod.getTopology(); + assert.equal(typeof topology.rootFrameId, "string"); + assert.ok(topology.frames[topology.rootFrameId], "Mod.getTopology should include its root frame"); + assert.ok( + Object.values(topology.roots).some((root) => root.kind === "document"), + "Mod.getTopology should include at least one document root", + ); + assert.ok( + Object.values(topology.contexts).some((context) => context.world === "piercer"), + "Mod.getTopology should include a piercer execution context", + ); + await cdp.Mod.addCustomEvent({ name: cdp.Target.targetCreated }); - const transformedEvents: unknown[] = []; - cdp.on("Target.targetCreated", (params) => { - if (!hasTargetInfo(params)) return; + const transformedEvents: cdp.types.ts.Target.TargetCreatedEvent[] = []; + cdp.on(cdp.Target.targetCreated, (params) => { if (!Object.hasOwn(params.targetInfo || {}, "tabId")) return; transformedEvents.push(params); }); @@ -181,16 +186,15 @@ test( const createdTarget = await cdp.Target.createTarget({ url: "about:blank#modcdp-target-created" }); await cdp.Target.getTargets(); assert.ok( - transformedEvents.some((params) => { - if (!hasTargetInfo(params)) return; - return params.targetInfo.targetId === createdTarget.targetId; - }), + transformedEvents.some((event) => event.targetInfo.targetId === createdTarget.targetId), `expected transformed Target.targetCreated for ${createdTarget.targetId}`, ); } - const event = events["Target.targetCreated"].parse(transformedEvents[0]); - assert.ok(Object.hasOwn(event.targetInfo, "tabId"), "transformed event targetInfo should include tabId"); + assert.ok( + transformedEvents.some((event) => Object.hasOwn(event.targetInfo, "tabId")), + "transformed event targetInfo should include tabId", + ); } finally { try { await cdp.Target.setDiscoverTargets({ discover: false }); diff --git a/js/test/test.ServerUpstreamTransport.ts b/js/test/test.ServerUpstreamTransport.ts new file mode 100644 index 0000000..f542fe7 --- /dev/null +++ b/js/test/test.ServerUpstreamTransport.ts @@ -0,0 +1,186 @@ +import assert from "node:assert/strict"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { test } from "vitest"; + +import { ModCDPClient } from "../src/client/ModCDPClient.js"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const EXTENSION_PATH = path.resolve(HERE, "..", "..", "dist", "extension"); + +test("loopback server upstream routes commands, events, and topology through one transport", async () => { + const owner = new ModCDPClient({ + launcher: { + launcher_mode: "local", + launcher_options: { headless: true }, + }, + upstream: { upstream_mode: "ws" }, + injector: { + injector_mode: "auto", + injector_extension_path: EXTENSION_PATH, + injector_service_worker_url_suffixes: ["/modcdp/service_worker.js"], + injector_trust_service_worker_target: true, + }, + }); + await owner.connect(); + + const cdp = new ModCDPClient({ + launcher: { launcher_mode: "remote" }, + upstream: { upstream_mode: "ws", upstream_cdp_url: owner.cdp_url }, + injector: { + injector_mode: "discover", + injector_service_worker_url_suffixes: ["/modcdp/service_worker.js"], + injector_trust_service_worker_target: true, + }, + server: { + server_loopback_cdp_url: owner.cdp_url, + server_routes: { "*.*": "loopback_cdp" }, + }, + }); + + let targetId: string | null = null; + try { + await cdp.connect(); + const created = (await cdp.send("Target.createTarget", { url: topologyTestUrl("loopback") })) as { + targetId?: string; + }; + assert.equal(typeof created.targetId, "string"); + targetId = created.targetId; + await assertPageMarker(cdp, targetId, "loopback"); + + const topology = await cdp.Mod.getTopology({ targetId }); + assertTopology(topology, targetId); + assert.equal( + Object.values(topology.targets).some((target) => target.sessionId), + true, + ); + } finally { + if (targetId) await cdp.send("Target.closeTarget", { targetId }).catch(() => ({})); + await cdp.close(); + await owner.close(); + } +}, 90_000); + +test("chrome.debugger server upstream routes commands, events, and topology through one transport", async () => { + const owner = new ModCDPClient({ + launcher: { + launcher_mode: "local", + launcher_options: { headless: true }, + }, + upstream: { upstream_mode: "ws" }, + injector: { + injector_mode: "auto", + injector_extension_path: EXTENSION_PATH, + injector_service_worker_url_suffixes: ["/modcdp/service_worker.js"], + injector_trust_service_worker_target: true, + }, + }); + await owner.connect(); + + const cdp = new ModCDPClient({ + launcher: { launcher_mode: "remote" }, + upstream: { upstream_mode: "ws", upstream_cdp_url: owner.cdp_url }, + injector: { + injector_mode: "discover", + injector_service_worker_url_suffixes: ["/modcdp/service_worker.js"], + injector_trust_service_worker_target: true, + }, + server: { + server_routes: { "*.*": "chrome_debugger" }, + }, + }); + + let targetId: string | null = null; + try { + await cdp.connect(); + const created = (await cdp.send("Target.createTarget", { url: topologyTestUrl("debugger") })) as { + targetId?: string; + }; + assert.equal(typeof created.targetId, "string"); + targetId = created.targetId; + await assertPageMarker(cdp, targetId, "debugger"); + + const topology = await cdp.Mod.getTopology({ targetId }); + assertTopology(topology, targetId); + assert.equal( + Object.values(topology.targets).some((target) => target.targetId === targetId && target.sessionId == null), + true, + ); + } finally { + if (targetId) await cdp.send("Target.closeTarget", { targetId }).catch(() => ({})); + await cdp.close(); + await owner.close(); + } +}, 90_000); + +async function assertPageMarker(cdp: ModCDPClient, targetId: string, label: string) { + await assert.doesNotReject(async () => { + await expectEventually(async () => { + const evaluated = (await cdp.send("Runtime.evaluate", { + targetId, + expression: "document.body?.dataset.modcdpMarker", + returnByValue: true, + })) as { result?: { value?: unknown } }; + assert.equal(evaluated.result?.value, label); + }); + }); +} + +function assertTopology(topology: Awaited>, targetId: string) { + assert.equal(typeof topology.objectGroup, "string"); + assert.equal(typeof topology.rootFrameId, "string"); + assert.ok(topology.frames[topology.rootFrameId], "topology should include the root frame"); + assert.equal(topology.frames[topology.rootFrameId]?.targetId, targetId); + assert.ok(topology.targets[targetId], "topology should include the requested page target"); + + const contexts = Object.values(topology.contexts); + assert.ok( + contexts.some((context) => context.frameId === topology.rootFrameId && context.world === "piercer"), + "topology should include a piercer execution context for the root frame", + ); + + const roots = Object.values(topology.roots); + assert.ok( + roots.some((root) => root.kind === "document" && root.frameId === topology.rootFrameId), + "topology should include the root document", + ); + assert.ok( + roots.some((root) => root.kind === "shadow" && root.mode === "open"), + "topology should include open shadow roots", + ); + assert.ok( + roots.some((root) => root.kind === "shadow" && root.mode === "closed"), + "topology should include closed shadow roots", + ); +} + +function topologyTestUrl(label: string) { + const html = ` + + +
+
+ + + + `; + return `data:text/html,${encodeURIComponent(html)}`; +} + +async function expectEventually(assertion: () => Promise | void, timeoutMs = 10_000) { + const deadline = Date.now() + timeoutMs; + let lastError: unknown = null; + while (Date.now() < deadline) { + try { + await assertion(); + return; + } catch (error) { + lastError = error; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + } + throw lastError instanceof Error ? lastError : new Error(String(lastError)); +} diff --git a/js/test/test.translate.ts b/js/test/test.translate.ts index df9981f..30d2a02 100644 --- a/js/test/test.translate.ts +++ b/js/test/test.translate.ts @@ -32,6 +32,10 @@ test("translate routes, wraps, and unwraps ModCDP protocol messages deterministi const configured = wrapCommandIfNeeded("Mod.configure", { server: { server_routes: { "*.*": "loopback_cdp" } } }); assert.equal(configured.steps[0]?.unwrap, "runtime_json"); + const ping = wrapCommandIfNeeded("Mod.ping", {}); + const ping_step_params = ping.steps[0]?.params as { arguments?: Array<{ value?: unknown }> } | undefined; + assert.deepEqual(JSON.parse(String(ping_step_params?.arguments?.[1]?.value)), {}); + const custom = wrapCommandIfNeeded( "Custom.echo", { secret: "x".repeat(100), nested: { ok: true } }, @@ -49,6 +53,16 @@ test("translate routes, wraps, and unwraps ModCDP protocol messages deterministi }); assert.equal(custom_step_params?.arguments?.[2]?.value, "session-1"); + const customWithSession = wrapCommandIfNeeded( + "Custom.echo", + { secret: "targeted" }, + { cdpSessionId: "target-session-1" }, + ); + const custom_with_session_params = customWithSession.steps[0]?.params as + | { arguments?: Array<{ value?: unknown }> } + | undefined; + assert.equal(custom_with_session_params?.arguments?.[2]?.value, "target-session-1"); + assert.deepEqual(unwrapResponseIfNeeded({ result: { type: "object", value: { ok: true } } }, "runtime"), { ok: true, }); diff --git a/python/examples/demo.py b/python/examples/demo.py index 6718ce9..dad81bc 100644 --- a/python/examples/demo.py +++ b/python/examples/demo.py @@ -18,16 +18,17 @@ import sys import threading import time -import urllib.request from pathlib import Path from typing import cast sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from modcdp import ModCDPClient -from modcdp.types import JsonValue, ProtocolPayload +from modcdp.types import ProtocolPayload ROOT = Path(__file__).resolve().parent.parent.parent EXTENSION_PATH = ROOT / "dist" / "extension" +DEMO_CDP_SEND_TIMEOUT_MS = 60_000 +DEMO_EXECUTION_CONTEXT_TIMEOUT_MS = 60_000 REVERSE_TRANSPORT_WAIT_TIMEOUT_MS = 60_000 LIVE_DEVTOOLS_ACTIVE_PORTS = [ Path.home() / "Library" / "Application Support" / "Google" / "Chrome" / "DevToolsActivePort", @@ -45,17 +46,13 @@ def expect_object(value: object, label: str) -> ProtocolPayload: def server_routes_for(mode: str, upstream_mode: str) -> ProtocolPayload: + del upstream_mode route = "loopback_cdp" if mode == "loopback" else "chrome_debugger" if mode == "debugger" else "auto" - routes: ProtocolPayload = { + return { "Mod.*": "service_worker", "Custom.*": "service_worker", "*.*": route, } - if mode == "loopback" or upstream_mode in {"reversews", "nativemessaging", "nats"}: - routes["Target.setDiscoverTargets"] = "loopback_cdp" - routes["Target.createTarget"] = "loopback_cdp" - routes["Target.activateTarget"] = "loopback_cdp" - return routes def client_routes_for(mode: str) -> ProtocolPayload: @@ -63,10 +60,8 @@ def client_routes_for(mode: str) -> ProtocolPayload: "Mod.*": "service_worker", "Custom.*": "service_worker", "*.*": "direct_cdp" if mode == "direct" else "service_worker", - "Target.setDiscoverTargets": "direct_cdp", - "Target.createTarget": "direct_cdp", - "Target.activateTarget": "direct_cdp", } + routes["Runtime.*"] = "service_worker" return routes @@ -111,17 +106,26 @@ def client_options_for(mode, upstream_mode, cdp_url, launch_options=None): return { "launcher": {"launcher_mode": "remote" if cdp_url else "local", "launcher_options": launch_options or {}}, "upstream": upstream, - "injector": {"injector_mode": "auto", "injector_extension_path": str(EXTENSION_PATH)}, - "client": {"client_routes": client_routes_for(mode)}, + "injector": { + "injector_mode": "auto", + "injector_extension_path": str(EXTENSION_PATH), + "injector_execution_context_timeout_ms": DEMO_EXECUTION_CONTEXT_TIMEOUT_MS, + }, + "client": {"client_routes": client_routes_for(mode), "client_cdp_send_timeout_ms": DEMO_CDP_SEND_TIMEOUT_MS}, } server = { "server_routes": server_routes_for(mode, upstream_mode), + "server_loopback_execution_context_timeout_ms": DEMO_EXECUTION_CONTEXT_TIMEOUT_MS, } return { "launcher": {"launcher_mode": "remote" if cdp_url else "local", "launcher_options": launch_options or {}}, "upstream": upstream, - "injector": {"injector_mode": "auto", "injector_extension_path": str(EXTENSION_PATH)}, - "client": {"client_routes": client_routes_for(mode)}, + "injector": { + "injector_mode": "auto", + "injector_extension_path": str(EXTENSION_PATH), + "injector_execution_context_timeout_ms": DEMO_EXECUTION_CONTEXT_TIMEOUT_MS, + }, + "client": {"client_routes": client_routes_for(mode), "client_cdp_send_timeout_ms": DEMO_CDP_SEND_TIMEOUT_MS}, "server": server, } @@ -165,28 +169,16 @@ def main(): launch_options["executable_path"] = os.environ["CHROME_PATH"] cdp = ModCDPClient(**client_options_for(mode, upstream_mode, cdp_url, launch_options)) - page_target_events = [] - target_created_events = [] - events_lock = threading.Lock() - - def on_target_created(payload, *_): - print(f"Target.targetCreated -> {payload.get('targetInfo', {}).get('targetId')}") - with events_lock: - target_created_events.append(payload) - - def on_page_target_updated(payload, *_): - print(f"Custom.pageTargetUpdated -> {payload}") - with events_lock: - page_target_events.append(payload) - - cdp.on("Target.targetCreated", on_target_created) cdp.connect() print(f"upstream cdp: {cdp.cdp_url}") print(f"connected; ext {cdp.extension_id} session {cdp.ext_session_id}") print(f"connect timing -> {cdp.connect_timing}") - server_config: ProtocolPayload = {"server_routes": server_routes_for(mode, upstream_mode)} + server_config: ProtocolPayload = { + "server_routes": server_routes_for(mode, upstream_mode), + "server_loopback_execution_context_timeout_ms": DEMO_EXECUTION_CONTEXT_TIMEOUT_MS, + } configure_params: ProtocolPayload = { "upstream": {"upstream_mode": upstream_mode}, "client": {"client_routes": client_routes_for(mode)}, @@ -226,30 +218,44 @@ def on_pong(payload, *_): } print(f"ping latency -> {ping_latency}") - if mode == "debugger": - try: - version = expect_object(cdp.send("Browser.getVersion"), "Browser.getVersion") - if not isinstance(version.get("protocolVersion"), str) or not isinstance(version.get("product"), str): - raise RuntimeError(f"unexpected Browser.getVersion result {version}") - print(f"Browser.getVersion -> {version}") - except Exception as e: - print(f"Browser.getVersion -> (debugger route rejected: {str(e).splitlines()[0]} )") - runtime_eval = expect_object(cdp.send("Runtime.evaluate", {"expression": "(() => 42)()", "returnByValue": True}), "Runtime.evaluate") - result = expect_object(runtime_eval.get("result"), "Runtime.evaluate.result") - if result.get("value") != 42: - raise RuntimeError(f"unexpected Runtime.evaluate result {runtime_eval}") - print(f"Runtime.evaluate -> {runtime_eval}") - else: - version = expect_object(cdp.send("Browser.getVersion"), "Browser.getVersion") - if not isinstance(version.get("protocolVersion"), str) or not isinstance(version.get("product"), str): - raise RuntimeError(f"unexpected Browser.getVersion result {version}") - print(f"Browser.getVersion -> {version}") - modcdp_eval = expect_object(cdp.send("Mod.evaluate", {"expression": "({ extension_id: chrome.runtime.id })"}), "Mod.evaluate") if not isinstance(modcdp_eval.get("extension_id"), str) or (cdp.extension_id and modcdp_eval.get("extension_id") != cdp.extension_id): raise RuntimeError(f"unexpected Mod.evaluate result {modcdp_eval}") print(f"Mod.evaluate -> {modcdp_eval}") + topology_checked = False + if mode != "direct": + topology = expect_object(cdp.Mod.getTopology(), "Mod.getTopology") + root_frame_id = topology.get("rootFrameId") + frames = expect_object(topology.get("frames"), "Mod.getTopology.frames") + roots = expect_object(topology.get("roots"), "Mod.getTopology.roots") + contexts = expect_object(topology.get("contexts"), "Mod.getTopology.contexts") + if ( + not isinstance(root_frame_id, str) + or root_frame_id not in frames + or not any(isinstance(root, dict) and root.get("kind") == "document" for root in roots.values()) + or not any(isinstance(context, dict) and context.get("world") == "piercer" for context in contexts.values()) + ): + raise RuntimeError(f"unexpected Mod.getTopology result {topology}") + topology_checked = True + print(f"Mod.getTopology -> {{'rootFrameId': {root_frame_id!r}, 'frames': {len(frames)}, 'roots': {len(roots)}, 'contexts': {len(contexts)}}}") + + response_middleware_registration = expect_object(cdp.send("Mod.addMiddleware", { + "name": "Custom.echo", + "phase": "response", + "expression": '''async (payload, next) => next({ ...payload, responseMiddleware: "ok" })''', + }), "Mod.addMiddleware response") + if response_middleware_registration.get("registered") is not True or response_middleware_registration.get("phase") != "response": + raise RuntimeError(f"unexpected response middleware registration {response_middleware_registration}") + + event_middleware_registration = expect_object(cdp.send("Mod.addMiddleware", { + "name": "Custom.demoEvent", + "phase": "event", + "expression": '''async (payload, next) => next({ ...payload, eventMiddleware: "ok" })''', + }), "Mod.addMiddleware event") + if event_middleware_registration.get("registered") is not True or event_middleware_registration.get("phase") != "event": + raise RuntimeError(f"unexpected event middleware registration {event_middleware_registration}") + echo_registration = expect_object(cdp.send("Mod.addCustomCommand", { "name": "Custom.echo", "expression": "async (params, method) => ({ echoed: params.value, method })", @@ -257,56 +263,14 @@ def on_pong(payload, *_): if echo_registration.get("registered") is not True or echo_registration.get("name") != "Custom.echo": raise RuntimeError(f"unexpected Custom.echo registration {echo_registration}") echo_result = expect_object(cdp.send("Custom.echo", {"value": "custom-command-ok"}), "Custom.echo") - if echo_result.get("echoed") != "custom-command-ok" or echo_result.get("method") != "Custom.echo": + if ( + echo_result.get("echoed") != "custom-command-ok" + or echo_result.get("method") != "Custom.echo" + or echo_result.get("responseMiddleware") != "ok" + ): raise RuntimeError(f"unexpected Custom.echo result {echo_result}") print(f"Custom.echo -> {echo_result}") - tab_command_registration = expect_object(cdp.send("Mod.addCustomCommand", { - "name": "Custom.TabIdFromTargetId", - "expression": '''async ({ targetId }) => { - const targets = await chrome.debugger.getTargets(); - const target = targets.find(target => target.id === targetId); - return { tabId: target?.tabId ?? null }; - }''', - }), "Mod.addCustomCommand Custom.TabIdFromTargetId") - if tab_command_registration.get("registered") is not True: - raise RuntimeError(f"unexpected TabIdFromTargetId registration {tab_command_registration}") - target_command_registration = expect_object(cdp.send("Mod.addCustomCommand", { - "name": "Custom.targetIdFromTabId", - "expression": '''async ({ tabId }) => { - const targets = await chrome.debugger.getTargets(); - const target = targets.find(target => target.type === "page" && target.tabId === tabId); - return { targetId: target?.id ?? null }; - }''', - }), "Mod.addCustomCommand Custom.targetIdFromTabId") - if target_command_registration.get("registered") is not True: - raise RuntimeError(f"unexpected targetIdFromTabId registration {target_command_registration}") - middleware_registered = False - for phase in ("response", "event"): - middleware_registration = expect_object(cdp.send("Mod.addMiddleware", { - "name": "*", - "phase": phase, - "expression": '''async (payload, next) => { - const seen = new WeakSet(); - const visit = async value => { - if (!value || typeof value !== "object" || seen.has(value)) return; - seen.add(value); - if (!Array.isArray(value) && typeof value.targetId === "string" && value.tabId == null) { - const { tabId } = await cdp.send("Custom.TabIdFromTargetId", { targetId: value.targetId }); - if (tabId != null) value.tabId = tabId; - } - for (const child of Array.isArray(value) ? value : Object.values(value)) await visit(child); - }; - await visit(payload); - return next(payload); - }''', - }), f"Mod.addMiddleware {phase}") - if middleware_registration.get("registered") is not True or middleware_registration.get("phase") != phase: - raise RuntimeError(f"unexpected {phase} middleware registration {middleware_registration}") - middleware_registered = True - if not middleware_registered: - raise RuntimeError("middleware registration loop did not run") - demo_events = [] demo_lock = threading.Lock() @@ -324,7 +288,7 @@ def on_demo_event(payload, *_): deadline = time.monotonic() + 3.0 while True: with demo_lock: - demo_event = next((event for event in demo_events if event.get("value") == "custom-event-ok"), None) + demo_event = next((event for event in demo_events if event.get("value") == "custom-event-ok" and event.get("eventMiddleware") == "ok"), None) if demo_event or time.monotonic() >= deadline: break time.sleep(0.02) @@ -332,63 +296,14 @@ def on_demo_event(payload, *_): raise RuntimeError("expected Custom.demoEvent") print(f"Custom.demoEvent -> {demo_event}") - page_target_event_registration = expect_object(cdp.send("Mod.addCustomEvent", {"name": "Custom.pageTargetUpdated"}), "Mod.addCustomEvent Custom.pageTargetUpdated") - if page_target_event_registration.get("registered") is not True: - raise RuntimeError(f"unexpected page target event registration {page_target_event_registration}") - cdp.on("Custom.pageTargetUpdated", on_page_target_updated) - - cdp.send("Target.setDiscoverTargets", {"discover": True}) - created_target = expect_object(cdp.send("Target.createTarget", {"url": "https://example.com", "background": True}), "Target.createTarget") - created_target_id = created_target.get("targetId") - if not created_target_id: - raise RuntimeError(f"Target.createTarget returned no targetId: {created_target}") - deadline = time.monotonic() + 3.0 - while True: - with events_lock: - matched_target_event = next((event for event in target_created_events if event.get("targetInfo", {}).get("targetId") == created_target_id), None) - if matched_target_event or time.monotonic() >= deadline: - break - time.sleep(0.02) - if not matched_target_event: - raise RuntimeError(f"expected Target.targetCreated for {created_target_id}") - print(f"normal event matched -> {created_target_id}") - - tab_from_target = expect_object(cdp.send("Custom.TabIdFromTargetId", {"targetId": created_target_id}), "Custom.TabIdFromTargetId") - if not isinstance(tab_from_target.get("tabId"), int | float): - raise RuntimeError(f"unexpected Custom.TabIdFromTargetId result {tab_from_target}") - print(f"Custom.TabIdFromTargetId -> {tab_from_target}") - - cdp.send("Target.activateTarget", {"targetId": created_target_id}) - page_target_emit_result = expect_object(cdp.send("Mod.evaluate", { - "params": {"targetId": created_target_id}, - "expression": '''async ({ targetId }) => { - const targets = await chrome.debugger.getTargets(); - const target = targets.find(target => target.id === targetId); - if (!target?.id) throw new Error(`target ${targetId} not found`); - await cdp.emit("Custom.pageTargetUpdated", { targetId: target.id, url: target.url ?? null }); - return { emitted: true, targetId: target.id }; - }''', - }), "Custom.pageTargetUpdated emit") - if page_target_emit_result.get("emitted") is not True or page_target_emit_result.get("targetId") != created_target_id: - raise RuntimeError(f"unexpected Custom.pageTargetUpdated emit result {page_target_emit_result}") - deadline = time.monotonic() + 3.0 - while True: - with events_lock: - page_target = next((event for event in page_target_events if event.get("targetId") == created_target_id), None) - if page_target or time.monotonic() >= deadline: - break - time.sleep(0.02) - if not page_target: - raise RuntimeError(f"expected Custom.pageTargetUpdated for {created_target_id}") - if tab_from_target.get("tabId") != page_target.get("tabId"): - raise RuntimeError(f"unexpected Custom.pageTargetUpdated result {page_target}") - - target_from_tab = expect_object(cdp.send("Custom.targetIdFromTabId", {"tabId": page_target["tabId"]}), "Custom.targetIdFromTabId") - if target_from_tab.get("targetId") != created_target_id or target_from_tab.get("tabId") != page_target.get("tabId"): - raise RuntimeError(f"unexpected Custom.targetIdFromTabId/middleware result {target_from_tab}") - print(f"Custom.targetIdFromTabId -> {target_from_tab}") + runtime_eval = expect_object(cdp.send("Runtime.evaluate", {"expression": "(() => 42)()", "returnByValue": True}), "Runtime.evaluate") + result = expect_object(runtime_eval.get("result"), "Runtime.evaluate.result") + if result.get("value") != 42: + raise RuntimeError(f"unexpected Runtime.evaluate result {runtime_eval}") + print(f"Runtime.evaluate -> {runtime_eval}") - print(f"\nSUCCESS ({mode}/{upstream_mode}): normal command, normal event, custom commands, custom event, and middleware all passed") + topology_label = "topology, " if topology_checked else "" + print(f"\nSUCCESS ({mode}/{upstream_mode}): native command, {topology_label}custom commands, custom event, and middleware all passed") # TTY-only: drop into a REPL where you can send live commands and # watch events as they print. Skip when run non-interactively so the @@ -410,7 +325,7 @@ def run_repl(cdp, mode): print("Enter commands as Domain.method({...JSON params...}). Examples:") print(' Browser.getVersion({})') print(' Mod.evaluate({"expression": "chrome.tabs.query({active: true})"})') - print(' Custom.TabIdFromTargetId({"targetId": "..."})') + print(' Runtime.evaluate({"expression": "document.title", "returnByValue": true})') print("Type exit or quit to disconnect (browser keeps running).") cmd_re = re.compile(r"^([A-Za-z_]\w*\.[A-Za-z_]\w*)(?:\((.*)\))?$") while True: diff --git a/python/modcdp/client/ModCDPClient.py b/python/modcdp/client/ModCDPClient.py index 6a0be9d..f34d364 100644 --- a/python/modcdp/client/ModCDPClient.py +++ b/python/modcdp/client/ModCDPClient.py @@ -174,6 +174,9 @@ def configure(self, **params: Any) -> AwaitableDict | AwaitableValue: def ping(self, **params: Any) -> AwaitableDict | AwaitableValue: return self._client._send_command("Mod.ping", params) + def getTopology(self, **params: Any) -> AwaitableDict | AwaitableValue: + return self._client._send_command("Mod.getTopology", params) + MODCDP_READY_EXPRESSION = ( "Boolean(globalThis.ModCDP?.__ModCDPServerVersion >= 1 && " "globalThis.ModCDP?.handleCommand && globalThis.ModCDP?.addCustomEvent)" @@ -505,8 +508,7 @@ def _send_command( method, command_params, routes=cast(ModCDPRoutes, self.client["client_routes"]), - cdp_session_id=self.ext_session_id, - target_cdp_session_id=session_id, + cdp_session_id=session_id, ) result = self._send_raw(command) if should_validate_result and method != "Mod.addCustomCommand": @@ -718,27 +720,24 @@ def _stop_heartbeat(self) -> None: stop.set() self._heartbeat_thread = None - def _session_id_for_target(self, target_id: str, timeout: float = 0) -> str | None: + def _ensureSessionForTarget(self, target_id: str, timeout: float = 0, allow_attach: bool = False) -> str | None: + session_id = self.auto_sessions.sessionId_from_targetId.get(target_id) + if session_id: + return session_id + if allow_attach: + attached_session_id = self.auto_sessions.attachToTarget(target_id) + if attached_session_id: + return attached_session_id if timeout <= 0: - return self.auto_sessions.sessionIdForTarget(target_id) + return self.auto_sessions.sessionId_from_targetId.get(target_id) deadline = time.time() + timeout while time.time() <= deadline: - session_id = self.auto_sessions.sessionIdForTarget(target_id) + session_id = self.auto_sessions.sessionId_from_targetId.get(target_id) if session_id: return session_id time.sleep(self.injector["injector_target_session_poll_interval_ms"] / 1000) return None - def _ensure_session_id_for_target(self, target_id: str, timeout: float = 0, allow_attach: bool = False) -> str | None: - session_id = self.auto_sessions.sessionIdForTarget(target_id) - if session_id: - return session_id - if allow_attach: - attached_session_id = self.auto_sessions.attachToTarget(target_id) - if attached_session_id: - return attached_session_id - return self._session_id_for_target(target_id, timeout=timeout) - def _browser_launcher(self): if self.launcher.get("launcher_mode") == "local": return LocalBrowserLauncher(self._launch_options()) @@ -826,7 +825,7 @@ def _connect_upstream_transport(self) -> None: def _server_needs_loopback_cdp(self) -> bool: if self.server is None or self.server.get("server_loopback_cdp_url"): return False - return "loopback_cdp" in set((self.server.get("server_routes") or {}).values()) + return (self.server.get("server_routes") or {}).get("*.*") == "loopback_cdp" def _upstream_transport_config(self) -> dict[str, Any]: return { @@ -907,17 +906,17 @@ def send_cdp(method: str, params: ProtocolParams | None = None, session_id: str timeout=self.client["client_cdp_send_timeout_ms"] / 1000, ) - def attach_to_target(target_id: str) -> str | None: - return self._ensure_session_id_for_target( + def ensure_session_for_target(target_id: str, timeout_ms: int, allow_attach: bool) -> str | None: + return self._ensureSessionForTarget( target_id, - timeout=self.injector["injector_service_worker_probe_timeout_ms"] / 1000, - allow_attach=True, + timeout=timeout_ms / 1000, + allow_attach=allow_attach, ) return { "send": send_cdp if send is not None else None, - "sessionIdForTarget": self.auto_sessions.sessionIdForTarget, - "attachToTarget": attach_to_target if send is not None else None, + "sessionId_from_targetId": self.auto_sessions.sessionId_from_targetId, + "ensureSessionForTarget": ensure_session_for_target if send is not None else None, "waitForExecutionContext": self.auto_sessions.waitForExecutionContext, "injector_extension_path": cast(str | None, self.injector.get("injector_extension_path")), "injector_extension_id": cast(str | None, self.injector.get("injector_extension_id")), diff --git a/python/modcdp/extension.zip b/python/modcdp/extension.zip index 8032e35..46f9d30 100644 Binary files a/python/modcdp/extension.zip and b/python/modcdp/extension.zip differ diff --git a/python/modcdp/injector/BorrowedExtensionInjector.py b/python/modcdp/injector/BorrowedExtensionInjector.py index 326b624..e7783f3 100644 --- a/python/modcdp/injector/BorrowedExtensionInjector.py +++ b/python/modcdp/injector/BorrowedExtensionInjector.py @@ -42,7 +42,7 @@ def _borrowVisibleServiceWorkers(self) -> ExtensionInjectionResult | None: return borrowed[0] if borrowed else None def _bootstrapTarget(self, target) -> ExtensionInjectionResult | None: - session_id = self._ensureSessionIdForTarget( + session_id = self._ensureSessionForTarget( target["targetId"], self.options.get("injector_service_worker_probe_timeout_ms") or DEFAULT_SERVICE_WORKER_PROBE_TIMEOUT_MS, True, diff --git a/python/modcdp/injector/ExtensionInjector.py b/python/modcdp/injector/ExtensionInjector.py index 510abb3..f4fe81f 100644 --- a/python/modcdp/injector/ExtensionInjector.py +++ b/python/modcdp/injector/ExtensionInjector.py @@ -33,15 +33,14 @@ DEFAULT_TARGET_SESSION_POLL_INTERVAL_MS = 20 SendCDP = Callable[[str, ProtocolParams | None, str | None], ProtocolResult] -SessionIdForTarget = Callable[[str], str | None] -AttachToTarget = Callable[[str], str | None] +EnsureSessionForTarget = Callable[[str, int, bool], str | None] WaitForExecutionContext = Callable[[str, int], int] class ExtensionInjectorConfig(TypedDict, total=False): send: SendCDP | None - sessionIdForTarget: SessionIdForTarget | None - attachToTarget: AttachToTarget | None + sessionId_from_targetId: dict[str, str] | None + ensureSessionForTarget: EnsureSessionForTarget | None waitForExecutionContext: WaitForExecutionContext | None injector_extension_path: str | None injector_extension_id: str | None @@ -131,8 +130,8 @@ class ExtensionInjector: def __init__(self, options: ExtensionInjectorConfig | None = None) -> None: self.options = cast(ExtensionInjectorConfig, { "send": None, - "sessionIdForTarget": None, - "attachToTarget": None, + "sessionId_from_targetId": None, + "ensureSessionForTarget": None, "waitForExecutionContext": None, "injector_extension_path": None, "injector_extension_id": None, @@ -235,31 +234,16 @@ def runSend() -> None: raise error return result or {} - def _sessionIdForTarget(self, target_id: str, timeout_ms: int = 0) -> str | None: - deadline = time.monotonic() + timeout_ms / 1000 - while True: - session_id = self.options.get("sessionIdForTarget") - if session_id is not None: - value = session_id(target_id) - if value: - return value - if time.monotonic() >= deadline: - return None - time.sleep(_defaulted(self.options.get("injector_target_session_poll_interval_ms"), DEFAULT_TARGET_SESSION_POLL_INTERVAL_MS) / 1000) - - def _ensureSessionIdForTarget(self, target_id: str, timeout_ms: int = 0, allow_attach: bool = False) -> str | None: - session_id = self.options.get("sessionIdForTarget") - if session_id is not None: - value = session_id(target_id) - if value: - return value - if allow_attach: - attach_to_target = self.options.get("attachToTarget") - if attach_to_target is not None: - attached_session_id = attach_to_target(target_id) - if attached_session_id: - return attached_session_id - return self._sessionIdForTarget(target_id, timeout_ms) + def _ensureSessionForTarget(self, target_id: str, timeout_ms: int = 0, allow_attach: bool = False) -> str | None: + sessionId_from_targetId = self.options.get("sessionId_from_targetId") + if sessionId_from_targetId is not None: + session_id = sessionId_from_targetId.get(target_id) + if session_id: + return session_id + ensure_session_for_target = self.options.get("ensureSessionForTarget") + if ensure_session_for_target is None: + return None + return ensure_session_for_target(target_id, timeout_ms, allow_attach) def _targetInfos(self) -> list[TargetInfo]: result = self._sendWithTimeout("Target.getTargets") @@ -287,7 +271,7 @@ def _probeTarget( target_id = target["targetId"] if target_id in self.unusable_target_ids: return None - session_id = self._ensureSessionIdForTarget(target_id, session_timeout_ms, allow_attach) + session_id = self._ensureSessionForTarget(target_id, session_timeout_ms, allow_attach) if session_id is None: return None self._sendWithTimeout("Runtime.enable", {}, session_id) diff --git a/python/modcdp/router/AutoSessionRouter.py b/python/modcdp/router/AutoSessionRouter.py index adcc616..64db2c0 100644 --- a/python/modcdp/router/AutoSessionRouter.py +++ b/python/modcdp/router/AutoSessionRouter.py @@ -6,28 +6,23 @@ SendCDP = Callable[[str, dict[str, Any], str | None], dict[str, Any]] -max_detached_session_guards = 1024 class AutoSessionRouter: def __init__(self, send: SendCDP, defaultExecutionContextTimeoutMs: Callable[[], int]) -> None: self.send = send self.defaultExecutionContextTimeoutMs = defaultExecutionContextTimeoutMs - self.target_sessions: dict[str, str] = {} - self.session_targets: dict[str, dict[str, Any]] = {} + self.sessionId_from_targetId: dict[str, str] = {} + self.targetId_from_sessionId: dict[str, str] = {} self.execution_contexts: dict[str, int] = {} self._execution_context_waiters: dict[str, list[tuple[threading.Event, dict[str, Any]]]] = {} - self._detached_sessions: dict[str, None] = {} self._lock = threading.RLock() - def sessionIdForTarget(self, target_id: str) -> str | None: - with self._lock: - return self.target_sessions.get(target_id) - def attachToTarget(self, target_id: str) -> str | None: - existing_session_id = self.sessionIdForTarget(target_id) - if existing_session_id is not None: - return existing_session_id + with self._lock: + session_id = self.sessionId_from_targetId.get(target_id) + if session_id is not None: + return session_id result = self.send("Target.attachToTarget", {"targetId": target_id, "flatten": True}, None) session_id = result.get("sessionId") return session_id if isinstance(session_id, str) and session_id else None @@ -41,9 +36,8 @@ def recordProtocolEvent(self, method: str, data: object, session_id: str | None) target_id = target_info.get("targetId") if target_info else None if isinstance(attached_session_id, str) and isinstance(target_id, str) and target_info: with self._lock: - self._detached_sessions.pop(attached_session_id, None) - self.target_sessions[target_id] = attached_session_id - self.session_targets[attached_session_id] = target_info + self.sessionId_from_targetId[target_id] = attached_session_id + self.targetId_from_sessionId[attached_session_id] = target_id elif method == "Runtime.executionContextCreated": raw_context = event_data.get("context") context = raw_context if isinstance(raw_context, Mapping) else None @@ -80,7 +74,7 @@ def waitForExecutionContext(self, session_id: str | None, timeout_ms: int | None def _recordExecutionContext(self, session_id: str, context_id: int) -> None: with self._lock: - if session_id in self._detached_sessions: + if session_id not in self.targetId_from_sessionId: return self.execution_contexts[session_id] = context_id waiters = self._execution_context_waiters.pop(session_id, []) @@ -90,23 +84,12 @@ def _recordExecutionContext(self, session_id: str, context_id: int) -> None: def _forgetSession(self, session_id: str) -> None: with self._lock: - target_info = self.session_targets.pop(session_id, None) - target_id = target_info.get("targetId") if target_info else None - if isinstance(target_id, str): - self.target_sessions.pop(target_id, None) + target_id = self.targetId_from_sessionId.pop(session_id, None) + if target_id is not None: + self.sessionId_from_targetId.pop(target_id, None) self.execution_contexts.pop(session_id, None) - self._markDetachedSession(session_id) waiters = self._execution_context_waiters.pop(session_id, []) error = RuntimeError(f"Runtime execution context wait cancelled because session {session_id} detached.") for event, result in waiters: result["error"] = error event.set() - - def _markDetachedSession(self, session_id: str) -> None: - self._detached_sessions.pop(session_id, None) - self._detached_sessions[session_id] = None - while len(self._detached_sessions) > max_detached_session_guards: - oldest_session_id = next(iter(self._detached_sessions), None) - if oldest_session_id is None: - break - self._detached_sessions.pop(oldest_session_id, None) diff --git a/python/modcdp/translate/translate.py b/python/modcdp/translate/translate.py index 648ba16..594b1b6 100644 --- a/python/modcdp/translate/translate.py +++ b/python/modcdp/translate/translate.py @@ -1,7 +1,6 @@ """Pure ModCDP <-> CDP translation helpers for the Python client.""" import json -import time from typing import cast from ..types.modcdp import ( @@ -77,16 +76,15 @@ def _call_function_params(function_declaration: str) -> RuntimeCallFunctionOnPar def _wrap_modcdp_evaluate( params: ProtocolParams, - session_id: str, - target_session_id: str | None = None, + cdp_session_id: str | None = None, ) -> RuntimeCallFunctionOnParams: expression = _required_string(params, "expression") user_params = params.get("params", {}) - cdp_session_id = target_session_id or _optional_string(params, "cdpSessionId") or session_id + resolved_cdp_session_id = _optional_string(params, "cdpSessionId") or cdp_session_id return _call_function_params( "async function() {\n" f" const params = {json.dumps(user_params)};\n" - f" const cdp = globalThis.ModCDP.attachToSession({json.dumps(cdp_session_id)});\n" + f" const cdp = globalThis.ModCDP.attachToSession({json.dumps(resolved_cdp_session_id)});\n" " const ModCDP = globalThis.ModCDP;\n" " const chrome = globalThis.chrome;\n" f" const value = ({expression});\n" @@ -151,7 +149,7 @@ def _wrap_modcdp_add_middleware(params: ProtocolParams) -> RuntimeCallFunctionOn ) -def _wrap_custom_command(method: str, params: ProtocolParams, session_id: str) -> RuntimeCallFunctionOnParams: +def _wrap_custom_command(method: str, params: ProtocolParams, session_id: str | None) -> RuntimeCallFunctionOnParams: runtime_params = _call_function_params( "async function(method, paramsJson, cdpSessionId) { " "return JSON.stringify(await globalThis.ModCDP.handleCommand(method, JSON.parse(paramsJson), cdpSessionId)); " @@ -164,12 +162,8 @@ def _wrap_custom_command(method: str, params: ProtocolParams, session_id: str) - def _wrap_service_worker_command( method: str, params: ProtocolParams, - session_id: str, - target_session_id: str | None = None, + cdp_session_id: str | None = None, ) -> list[TranslatedStep]: - if method == "Mod.ping" and "sent_at" not in params: - params = {**params, "sent_at": int(time.time() * 1000)} - if method == "Mod.addCustomEvent": return [ { @@ -180,13 +174,13 @@ def _wrap_service_worker_command( ] unwrap = "runtime" if method == "Mod.evaluate": - runtime_params = _wrap_modcdp_evaluate(params, session_id, target_session_id) + runtime_params = _wrap_modcdp_evaluate(params, cdp_session_id) elif method == "Mod.addCustomCommand": runtime_params = _wrap_modcdp_add_custom_command(params) elif method == "Mod.addMiddleware": runtime_params = _wrap_modcdp_add_middleware(params) else: - runtime_params = _wrap_custom_command(method, params, target_session_id or _optional_string(params, "cdpSessionId") or session_id) + runtime_params = _wrap_custom_command(method, params, _optional_string(params, "cdpSessionId") or cdp_session_id) unwrap = "runtime_json" return [{"method": "Runtime.callFunctionOn", "params": runtime_params, "unwrap": unwrap}] @@ -197,22 +191,19 @@ def wrap_command_if_needed( *, routes: ModCDPRoutes | None = None, cdp_session_id: str | None = None, - target_cdp_session_id: str | None = None, ) -> TranslatedCommand: params = params or {} route = route_for(method, routes or DEFAULT_CLIENT_ROUTES) if route == "direct_cdp": step: TranslatedStep = {"method": method, "params": params} - if target_cdp_session_id: - step["sessionId"] = target_cdp_session_id + if cdp_session_id: + step["sessionId"] = cdp_session_id return {"route": route, "target": "direct_cdp", "steps": [step]} if route == "service_worker": - if cdp_session_id is None: - raise RuntimeError(f"service_worker route requires a CDP session id for {method}") return { "route": route, "target": "service_worker", - "steps": _wrap_service_worker_command(method, params, cdp_session_id, target_cdp_session_id), + "steps": _wrap_service_worker_command(method, params, cdp_session_id), } raise RuntimeError(f"Unsupported client route '{route}' for {method}") diff --git a/python/modcdp/types/modcdp.py b/python/modcdp/types/modcdp.py index 1641785..3851b64 100644 --- a/python/modcdp/types/modcdp.py +++ b/python/modcdp/types/modcdp.py @@ -56,6 +56,61 @@ class ModCDPPingLatency(TypedDict): return_path_ms: int | float | None +class ModCDPGetTopologyParams(TypedDict, total=False): + rootTargetId: str + targetId: str + active: bool + + +class ModCDPTopologyFrame(TypedDict, total=False): + targetId: str + url: str | None + parentFrameId: str | None + outerBackendNodeId: int | None + + +class ModCDPTopologyDomRoot(TypedDict, total=False): + kind: Literal["document", "shadow"] + frameId: str + outerBackendNodeId: int | None + innerBackendNodeId: int | None + mode: Literal["open", "closed", "user-agent"] + executionContextId: int + uniqueContextId: str + + +class ModCDPTopologyTarget(TypedDict, total=False): + targetId: str + type: str + title: str + url: str + attached: bool + parentId: str + parentFrameId: str + sessionId: str | None + + +class ModCDPTopologyExecutionContext(TypedDict, total=False): + id: int + origin: str + name: str + uniqueId: str + auxData: dict[str, object] + sessionId: str | None + targetId: str + frameId: str | None + world: str + + +class ModCDPTopology(TypedDict): + objectGroup: str + rootFrameId: str + frames: dict[str, ModCDPTopologyFrame] + roots: dict[str, ModCDPTopologyDomRoot] + targets: dict[str, ModCDPTopologyTarget] + contexts: dict[str, ModCDPTopologyExecutionContext] + + class ModCDPConnectTiming(TypedDict): started_at: int upstream_mode: str | None diff --git a/python/tests/test_AutoSessionRouter.py b/python/tests/test_AutoSessionRouter.py index 0b9cd57..219a7f4 100644 --- a/python/tests/test_AutoSessionRouter.py +++ b/python/tests/test_AutoSessionRouter.py @@ -13,54 +13,6 @@ class AutoSessionRouterTests(unittest.TestCase): - def test_rejects_pending_execution_context_waiters_when_session_detaches(self) -> None: - router = AutoSessionRouter(lambda _method, _params, _session_id: {}, lambda: 5_000) - result: Queue[int | BaseException] = Queue() - threading.Thread( - target=lambda: _put_result(result, lambda: router.waitForExecutionContext("detached-session", 5_000)), - daemon=True, - ).start() - - router.recordProtocolEvent( - "Target.attachedToTarget", - {"sessionId": "detached-session", "targetInfo": {"targetId": "target-1", "type": "page"}}, - None, - ) - router.recordProtocolEvent("Target.detachedFromTarget", {"sessionId": "detached-session"}, None) - router.recordProtocolEvent( - "Runtime.executionContextCreated", - {"context": {"id": 42}}, - "detached-session", - ) - - error = result.get(timeout=1) - self.assertIsInstance(error, RuntimeError) - self.assertIn("Runtime execution context wait cancelled because session detached-session detached.", str(error)) - self.assertIsNone(router.sessionIdForTarget("target-1")) - self.assertNotIn("detached-session", router.execution_contexts) - - def test_bounds_detached_session_guards_and_clears_them_when_session_reattaches(self) -> None: - router = AutoSessionRouter(lambda _method, _params, _session_id: {}, lambda: 5_000) - - for index in range(1034): - router.recordProtocolEvent("Target.detachedFromTarget", {"sessionId": f"detached-session-{index}"}, None) - - self.assertLessEqual(len(router._detached_sessions), 1024) - - recent_session_id = "detached-session-1033" - router.recordProtocolEvent("Runtime.executionContextCreated", {"context": {"id": 42}}, recent_session_id) - self.assertNotIn(recent_session_id, router.execution_contexts) - - router.recordProtocolEvent( - "Target.attachedToTarget", - {"sessionId": recent_session_id, "targetInfo": {"targetId": "target-reattached", "type": "page"}}, - None, - ) - router.recordProtocolEvent("Runtime.executionContextCreated", {"context": {"id": 43}}, recent_session_id) - - self.assertEqual(router.sessionIdForTarget("target-reattached"), recent_session_id) - self.assertEqual(router.execution_contexts[recent_session_id], 43) - def test_tracks_real_target_sessions_and_execution_contexts(self) -> None: chrome = LocalBrowserLauncher({"headless": True}).launch() ws = create_connection(str(chrome["cdp_url"]), timeout=10) @@ -113,12 +65,14 @@ def reader() -> None: thread = threading.Thread(target=reader, daemon=True) thread.start() target_id: str | None = None + pending_target_id: str | None = None try: send("Target.setAutoAttach", {"autoAttach": True, "waitForDebuggerOnStart": False, "flatten": True}) send("Target.setDiscoverTargets", {"discover": True}) created = send("Target.createTarget", {"url": "about:blank#modcdp-auto-session-router"}) - target_id = str(created["targetId"]) - session_id = _wait_for(lambda: router.sessionIdForTarget(target_id)) + created_target_id = str(created["targetId"]) + target_id = created_target_id + session_id = _wait_for(lambda: router.sessionId_from_targetId.get(created_target_id)) context_result: Queue[int | BaseException] = Queue() threading.Thread( target=lambda: _put_result(context_result, lambda: router.waitForExecutionContext(session_id, 30_000)), @@ -132,13 +86,45 @@ def reader() -> None: self.assertEqual(router.execution_contexts[session_id], context_id) send("Target.detachFromTarget", {"sessionId": session_id}) - _wait_for(lambda: None if router.sessionIdForTarget(target_id) else "detached") + _wait_for(lambda: None if router.sessionId_from_targetId.get(created_target_id) else "detached") + self.assertNotIn(session_id, router.execution_contexts) + send("Target.closeTarget", {"targetId": created_target_id}) + target_id = None + + pending_created = send("Target.createTarget", {"url": "about:blank#modcdp-auto-session-router-pending-context"}) + created_pending_target_id = str(pending_created["targetId"]) + pending_target_id = created_pending_target_id + pending_session_id = _wait_for(lambda: router.sessionId_from_targetId.get(created_pending_target_id)) + pending_result: Queue[int | BaseException] = Queue() + threading.Thread( + target=lambda: _put_result( + pending_result, + lambda: router.waitForExecutionContext(pending_session_id, 30_000), + ), + daemon=True, + ).start() + send("Target.detachFromTarget", {"sessionId": pending_session_id}) + pending_error = pending_result.get(timeout=35) + self.assertIsInstance(pending_error, RuntimeError) + self.assertIn( + f"Runtime execution context wait cancelled because session {pending_session_id} detached.", + str(pending_error), + ) + _wait_for(lambda: None if router.sessionId_from_targetId.get(created_pending_target_id) else "detached") + self.assertNotIn(pending_session_id, router.execution_contexts) + send("Target.closeTarget", {"targetId": created_pending_target_id}) + pending_target_id = None finally: if target_id: try: send("Target.closeTarget", {"targetId": target_id}) except Exception: pass + if pending_target_id: + try: + send("Target.closeTarget", {"targetId": pending_target_id}) + except Exception: + pass closed = True ws.close() chrome["close"]() diff --git a/python/tests/test_ModCDPClient.py b/python/tests/test_ModCDPClient.py index cd2060c..ac7364d 100644 --- a/python/tests/test_ModCDPClient.py +++ b/python/tests/test_ModCDPClient.py @@ -159,15 +159,15 @@ def test_preserves_explicit_none_server_config(self) -> None: self.assertIsNone(cdp.server) - def test_only_exposes_injector_attach_after_cdp_send_is_available(self) -> None: + def test_only_exposes_injector_ensure_after_cdp_send_is_available(self) -> None: cdp = ModCDPClient() disconnected_config = cdp._base_extension_injector_config(None) self.assertIsNone(disconnected_config.get("send")) - self.assertIsNone(disconnected_config.get("attachToTarget")) + self.assertIsNone(disconnected_config.get("ensureSessionForTarget")) connected_config = cdp._base_extension_injector_config(lambda method, params=None, session_id=None: {}) self.assertTrue(callable(connected_config.get("send"))) - self.assertTrue(callable(connected_config.get("attachToTarget"))) + self.assertTrue(callable(connected_config.get("ensureSessionForTarget"))) def test_defaults_launched_modcdp_server_upstreams_to_extension_auto(self) -> None: for mode in ("nativemessaging", "reversews", "nats"): diff --git a/python/tests/test_ModCDPClientRoutedDefaultOverrides.py b/python/tests/test_ModCDPClientRoutedDefaultOverrides.py index 24db6c3..90c89d6 100644 --- a/python/tests/test_ModCDPClientRoutedDefaultOverrides.py +++ b/python/tests/test_ModCDPClientRoutedDefaultOverrides.py @@ -14,7 +14,7 @@ GET_TARGETS_OVERRIDE = r""" async (params) => { const [upstream, tabs] = await Promise.all([ - ModCDP.sendLoopback("Target.getTargets", params), + cdp.upstream.send("Target.getTargets", params), chrome.tabs.query({}), ]); @@ -139,6 +139,16 @@ def test_service_worker_routed_standard_cdp_commands_and_events_can_be_transform ) ) + topology = cast(dict[str, Any], cdp.Mod.getTopology()) + root_frame_id = topology.get("rootFrameId") + frames = cast(dict[str, Any], topology.get("frames")) + roots = cast(dict[str, dict[str, Any]], topology.get("roots")) + contexts = cast(dict[str, dict[str, Any]], topology.get("contexts")) + self.assertIsInstance(root_frame_id, str) + self.assertIn(root_frame_id, frames) + self.assertTrue(any(root.get("kind") == "document" for root in roots.values())) + self.assertTrue(any(context.get("world") == "piercer" for context in contexts.values())) + cdp.Mod.addCustomEvent("Target.targetCreated") transformed_events: Queue[dict] = Queue() diff --git a/python/tests/test_translate.py b/python/tests/test_translate.py index fd9ff1c..e3b08bc 100644 --- a/python/tests/test_translate.py +++ b/python/tests/test_translate.py @@ -39,6 +39,10 @@ def test_routes_wraps_and_unwraps_modcdp_protocol_messages_deterministically(sel ) self.assertEqual(configured["steps"][0].get("unwrap"), "runtime_json") + ping = wrap_command_if_needed("Mod.ping", {}) + ping_arguments = cast("list[dict[str, object]]", ping["steps"][0].get("params", {}).get("arguments", [])) + self.assertEqual(json.loads(str(ping_arguments[1].get("value"))), {}) + custom = wrap_command_if_needed( "Custom.echo", {"secret": "x" * 100, "nested": {"ok": True}}, @@ -52,6 +56,14 @@ def test_routes_wraps_and_unwraps_modcdp_protocol_messages_deterministically(sel self.assertEqual(json.loads(str(custom_arguments[1].get("value"))), {"secret": "x" * 100, "nested": {"ok": True}}) self.assertEqual(custom_arguments[2].get("value"), "session-1") + custom_with_session = wrap_command_if_needed( + "Custom.echo", + {"secret": "targeted"}, + cdp_session_id="target-session-1", + ) + custom_with_session_arguments = cast("list[dict[str, object]]", custom_with_session["steps"][0].get("params", {}).get("arguments", [])) + self.assertEqual(custom_with_session_arguments[2].get("value"), "target-session-1") + self.assertEqual(unwrap_response_if_needed({"result": {"type": "object", "value": {"ok": True}}}, "runtime"), {"ok": True}) self.assertEqual(unwrap_response_if_needed({"product": "Chrome/1"}, None), {"product": "Chrome/1"})