The one and only agent harness for complex codebases. Project memory, planning, execution, and verified completion inside Codex.
JavaScript aiai-agentsclaudeclaude-codeclicodexdeveloper-toolslazylazycodexoh-my-openagentomoopenaiorchestrationtypescript
chore: sync Codex marketplace v5.1.54
YeonGyu-Kim7b577b50495c
diff --git a/plugins/omo/.codex-plugin/plugin.json b/plugins/omo/.codex-plugin/plugin.jsonindex 6ea532c8..978ec030 100644--- a/plugins/omo/.codex-plugin/plugin.json+++ b/plugins/omo/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "omo",- "version": "5.1.51",+ "version": "5.1.54","description": "One Codex plugin namespace for Yeongyu's local Codex components.","author": {"name": "Yeongyu Kim",diff --git a/plugins/omo/components/bootstrap/dist/cli.js b/plugins/omo/components/bootstrap/dist/cli.jsindex 9ef7652f..021c658a 100755--- a/plugins/omo/components/bootstrap/dist/cli.js+++ b/plugins/omo/components/bootstrap/dist/cli.js@@ -7274,8 +7274,8 @@ var OmoMemoryWriteNoticeLayerSchema = object({enabled: boolean2().optional()}).strict();var OmoMemoryProjectionSchema = object({- max_entries_per_directory: number2().int().min(0).default(40),- max_bytes: number2().int().min(0).default(24576)+ max_entries_per_directory: number2().int().min(0).default(0),+ max_bytes: number2().int().min(0).default(40960)}).strict();var OmoMemoryProjectionLayerSchema = object({max_entries_per_directory: number2().int().min(0).optional(),@@ -7339,7 +7339,7 @@ var OmoMemorySettingsSchema = object({query_expansion: false}),project_scope: OmoMemoryProjectScopeSchema.default({ nudge: true, recall: true }),- projection: OmoMemoryProjectionSchema.default({ max_entries_per_directory: 40, max_bytes: 24576 }),+ projection: OmoMemoryProjectionSchema.default({ max_entries_per_directory: 0, max_bytes: 40960 }),compile_warn_tokens: number2().int().positive().default(30000),agents: record(string2(), OmoMemoryAgentOverridesSchema).default({})}).strict();@@ -7380,6 +7380,17 @@ var OmoModelCatalogEntryLayerInputSchema = OmoModelCatalogEntryInputSchema.partivar OmoModelCatalogEntryLayerSchema = preprocess((value) => isRecord5(value) ? normalizeLegacyModelFields(value) : value, OmoModelCatalogEntryLayerInputSchema);var OmoModelCatalogLayerSchema = record(string2(), OmoModelCatalogEntryLayerSchema);+// ../../omo-config-core/src/schema/model-pad.ts+var OmoModelPadLabelsSchema = object({+ daily: string2().optional(),+ geeky: string2().optional(),+ normal: string2().optional(),+ heavy: string2().optional()+}).strict();+var OmoModelPadSchema = object({+ labels: OmoModelPadLabelsSchema.optional()+}).strict();+// ../../omo-config-core/src/schema/model-profile.tsfunction isRecord6(value) {return typeof value === "object" && value !== null && !Array.isArray(value);@@ -7677,6 +7688,7 @@ var OmoTypedHarnessConfigSchema = object({models: OmoModelCatalogLayerSchema.optional(),model_profiles: OmoModelProfilesLayerSchema.optional(),model_profile: string2().optional(),+ model_pad: OmoModelPadSchema.optional(),memory: OmoMemorySettingsLayerSchema.optional(),telemetry: OmoTelemetrySettingsLayerSchema.optional(),side_panel: OmoSidePanelSettingsLayerSchema.optional(),@@ -7695,6 +7707,7 @@ var OmoConfigProfileSchema = object({models: OmoModelCatalogLayerSchema.optional(),model_profiles: OmoModelProfilesLayerSchema.optional(),model_profile: string2().optional(),+ model_pad: OmoModelPadSchema.optional(),memory: OmoMemorySettingsLayerSchema.optional(),telemetry: OmoTelemetrySettingsLayerSchema.optional(),side_panel: OmoSidePanelSettingsLayerSchema.optional(),@@ -7718,6 +7731,7 @@ var OmoConfigSchema = object({models: OmoModelCatalogSchema.optional(),model_profiles: OmoModelProfilesSchema.optional(),model_profile: string2().optional(),+ model_pad: OmoModelPadSchema.optional(),memory: OmoMemorySettingsSchema.optional(),telemetry: OmoTelemetrySettingsSchema.optional(),side_panel: OmoSidePanelSettingsSchema.optional(),@@ -7744,6 +7758,7 @@ var OmoConfigLayerSchema = object({models: OmoModelCatalogLayerSchema.optional(),model_profiles: OmoModelProfilesLayerSchema.optional(),model_profile: string2().optional(),+ model_pad: OmoModelPadSchema.optional(),memory: OmoMemorySettingsLayerSchema.optional(),telemetry: OmoTelemetrySettingsLayerSchema.optional(),side_panel: OmoSidePanelSettingsLayerSchema.optional(),@@ -10008,7 +10023,8 @@ var LATEST_MODEL_BY_FAMILY = {gptLunaFast: "gpt-6-luna-fast",glm: "glm-5.3",glmFlash: "glm-5.3-flash",- kimi: "kimi-k3",+ kimi: "kimi-k3.1-pro",+ kimiK3: "kimi-k3",geminiPro: "gemini-4-argon"};diff --git a/plugins/omo/components/bootstrap/hooks/hooks.json b/plugins/omo/components/bootstrap/hooks/hooks.jsonindex 9832974e..e99168d3 100644--- a/plugins/omo/components/bootstrap/hooks/hooks.json+++ b/plugins/omo/components/bootstrap/hooks/hooks.json@@ -8,7 +8,7 @@"command": "node \"${PLUGIN_ROOT}/components/bootstrap/dist/cli.js\" hook session-start","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\bootstrap.ps1\"","timeout": 30,- "statusMessage": "(OmO 5.1.51) Checking Bootstrap Provisioning"+ "statusMessage": "(OmO 5.1.54) Checking Bootstrap Provisioning"}]}diff --git a/plugins/omo/components/bootstrap/package.json b/plugins/omo/components/bootstrap/package.jsonindex cb9b99cc..ca0f8650 100644--- a/plugins/omo/components/bootstrap/package.json+++ b/plugins/omo/components/bootstrap/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/codex-bootstrap",- "version": "5.1.51",+ "version": "5.1.54","description": "Codex SessionStart bootstrap component that provisions LazyCodex runtime dependencies from a detached worker.","type": "module","private": true,diff --git a/plugins/omo/components/comment-checker/hooks/hooks.json b/plugins/omo/components/comment-checker/hooks/hooks.jsonindex 475e87a1..9a08a63d 100644--- a/plugins/omo/components/comment-checker/hooks/hooks.json+++ b/plugins/omo/components/comment-checker/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 30,- "statusMessage": "(OmO 5.1.51) Checking Comments"+ "statusMessage": "(OmO 5.1.54) Checking Comments"}]}diff --git a/plugins/omo/components/comment-checker/package.json b/plugins/omo/components/comment-checker/package.jsonindex 8ccf7127..dc219d9d 100644--- a/plugins/omo/components/comment-checker/package.json+++ b/plugins/omo/components/comment-checker/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-comment-checker",- "version": "5.1.51",+ "version": "5.1.54","description": "Codex plugin that runs comment-checker after edit-like PostToolUse hooks.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/git-bash/hooks/hooks.json b/plugins/omo/components/git-bash/hooks/hooks.jsonindex b9158015..afde7034 100644--- a/plugins/omo/components/git-bash/hooks/hooks.json+++ b/plugins/omo/components/git-bash/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "(OmO 5.1.51) Recommending Git Bash MCP"+ "statusMessage": "(OmO 5.1.54) Recommending Git Bash MCP"}]}@@ -20,7 +20,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "(OmO 5.1.51) Resetting Git Bash MCP Reminder"+ "statusMessage": "(OmO 5.1.54) Resetting Git Bash MCP Reminder"}]}diff --git a/plugins/omo/components/git-bash/package.json b/plugins/omo/components/git-bash/package.jsonindex 7a61367c..30f1e4a2 100644--- a/plugins/omo/components/git-bash/package.json+++ b/plugins/omo/components/git-bash/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/codex-git-bash-hook",- "version": "5.1.51",+ "version": "5.1.54","description": "Codex hook component that reminds Windows sessions to prefer the OMO git_bash MCP.","type": "module","private": true,diff --git a/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json b/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.jsonindex 4430ecbb..bfac6790 100644--- a/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json+++ b/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/lazycodex-executor-verify/dist/cli.js\" hook subagent-stop","timeout": 10,- "statusMessage": "(OmO 5.1.51) Verifying LazyCodex Executor Evidence"+ "statusMessage": "(OmO 5.1.54) Verifying LazyCodex Executor Evidence"}]}diff --git a/plugins/omo/components/lazycodex-executor-verify/package.json b/plugins/omo/components/lazycodex-executor-verify/package.jsonindex 0fd5afea..e1f1e7a3 100644--- a/plugins/omo/components/lazycodex-executor-verify/package.json+++ b/plugins/omo/components/lazycodex-executor-verify/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-lazycodex-executor-verify",- "version": "5.1.51",+ "version": "5.1.54","description": "Codex SubagentStop evidence verifier for LazyCodex executor completions.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/lsp-daemon/dist/cli.js b/plugins/omo/components/lsp-daemon/dist/cli.jsindex 714cd089..8679f8df 100644--- a/plugins/omo/components/lsp-daemon/dist/cli.js+++ b/plugins/omo/components/lsp-daemon/dist/cli.js@@ -445,7 +445,7 @@ function parseEndpoint(value) {}// src/proxy.ts-import { existsSync as existsSync15, realpathSync as realpathSync6 } from "node:fs";+import { existsSync as existsSync15, realpathSync as realpathSync7 } from "node:fs";import { basename as basename4, delimiter as delimiter4, dirname as dirname14, isAbsolute as isAbsolute6 } from "node:path";// ../mcp-stdio-core/src/responses.tsfunction successResponse(id, result) {@@ -756,7 +756,7 @@ function createIdleTimer(idleTimeoutMs, log, onTimeout) {};}// ../lsp-core/src/lsp/client-wrapper.ts-import { existsSync as existsSync11, realpathSync as realpathSync5, statSync as statSync4 } from "node:fs";+import { existsSync as existsSync11, realpathSync as realpathSync6, statSync as statSync4 } from "node:fs";import { basename as basename3, dirname as dirname11, join as join5, resolve as resolve8 } from "node:path";// ../lsp-core/src/request-context.ts@@ -4197,10 +4197,15 @@ var LSP_LOCAL_INSTALL_HINTS = {ty: "uv add --dev ty","ruby-lsp": "bundle add ruby-lsp --group development"};+var TYPESCRIPT_SERVER_INITIALIZATION = {+ tsserver: { useSyntaxServer: "never" },+ disableAutomaticTypingAcquisition: true+};var BUILTIN_SERVERS = {typescript: {command: ["typescript-language-server", "--stdio"],- extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"]+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],+ initialization: TYPESCRIPT_SERVER_INITIALIZATION},deno: { command: ["deno", "lsp"], extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"] },vue: { command: ["vue-language-server", "--stdio"], extensions: [".vue"] },@@ -4418,7 +4423,8 @@ function getMergedServers() {command: config.command,extensions: config.extensions,priority: -100,- source: "builtin"+ source: "builtin",+ ...config.initialization === undefined ? {} : { initialization: config.initialization }});}return servers.sort((a, b) => {@@ -4445,8 +4451,9 @@ function createServerFromEntry(id, entry, source) {priority: entry.priority ?? 0,source});- if (entry.initialization !== undefined) {- server.initialization = entry.initialization;+ const initialization = mergeInitialization(builtin.initialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;}return server;}@@ -4471,8 +4478,20 @@ function createServerFromEntry(id, entry, source) {source});applyOptionalServerFields(server, entry);+ const builtinInitialization = entry.command === undefined ? builtin.initialization : undefined;+ const initialization = mergeInitialization(builtinInitialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;+ }return server;}+function mergeInitialization(builtin, entry) {+ if (builtin === undefined)+ return entry;+ if (entry === undefined)+ return builtin;+ return { ...builtin, ...entry };+}function createServer(input) {const server = {id: input.id,@@ -4543,6 +4562,49 @@ function getDisabledServerIds() {return disabled;}+// ../lsp-core/src/lsp/host-js-runtime.ts+import { closeSync as closeSync3, openSync as openSync3, readSync, realpathSync as realpathSync5 } from "node:fs";+var HOST_RUNTIME_SERVER_IDS = new Set(["typescript"]);+var JS_ENTRY = /\.[cm]?js$/;+var NODE_SHEBANG = /^#![^\n]*\bnode\b/;+function currentHostJsRuntime() {+ return { bunExecPath: process.versions["bun"] === undefined ? undefined : process.execPath };+}+function withHostJsRuntime(serverId, command, host = currentHostJsRuntime()) {+ if (host.bunExecPath === undefined || !HOST_RUNTIME_SERVER_IDS.has(serverId))+ return command;+ const [binary, ...args] = command;+ if (binary === undefined)+ return command;+ const script = nodeScriptPath(binary);+ return script === undefined ? command : [host.bunExecPath, script, ...args];+}+function nodeScriptPath(binary) {+ let real;+ try {+ real = realpathSync5(binary);+ } catch {+ return;+ }+ if (JS_ENTRY.test(real))+ return real;+ try {+ return NODE_SHEBANG.test(readHead(real)) ? real : undefined;+ } catch {+ return;+ }+}+function readHead(path) {+ const fd = openSync3(path, "r");+ try {+ const buffer = Buffer.alloc(128);+ const bytes = readSync(fd, buffer, 0, buffer.length, 0);+ return buffer.toString("utf8", 0, bytes);+ } finally {+ closeSync3(fd);+ }+}+// ../lsp-core/src/lsp/server-installation.tsimport { existsSync as existsSync10 } from "node:fs";import { delimiter as delimiter3, dirname as dirname10, isAbsolute as isAbsolute3, join as join4, resolve as resolve7 } from "node:path";@@ -4682,6 +4744,10 @@ function isServerInstalled(command, workingDirectory, options = {}) {function withResolvedCommand(command, binaryPath) {return [binaryPath, ...command.slice(1)];}+function usesBuiltinCommand(id, command) {+ const builtin = BUILTIN_SERVERS[id]?.command;+ return builtin !== undefined && builtin.length === command.length && builtin.every((part, index) => part === command[index]);+}function findServerForExtension(ext) {const servers = getMergedServers();const workingDirectory = contextCwd();@@ -4692,7 +4758,7 @@ function findServerForExtension(ext) {if (binaryPath !== null) {const resolvedServer = {id: server.id,- command: withResolvedCommand(server.command, binaryPath),+ command: usesBuiltinCommand(server.id, server.command) ? withHostJsRuntime(server.id, withResolvedCommand(server.command, binaryPath)) : withResolvedCommand(server.command, binaryPath),extensions: server.extensions,priority: server.priority};@@ -4833,7 +4899,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {const suffix = [];while (true) {if (existsSync11(current)) {- const canonical = realpathSync5(current);+ const canonical = realpathSync6(current);if (isPathInside(cwd, canonical))return suffix.length === 0 ? canonical : join5(canonical, ...suffix);}@@ -4847,7 +4913,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {function existingDirectoryInsideContext(directory, cwd) {if (!existsSync11(directory))return;- const canonical = realpathSync5(directory);+ const canonical = realpathSync6(directory);if (!statSync4(canonical).isDirectory())return;return isPathInside(cwd, canonical) ? canonical : undefined;@@ -6441,7 +6507,7 @@ function errorText(error) {// src/ensure-daemon.tsimport { spawn as spawn3 } from "node:child_process";-import { closeSync as closeSync3, existsSync as existsSync14, mkdirSync as mkdirSync4, openSync as openSync3, writeSync as writeSync3 } from "node:fs";+import { closeSync as closeSync4, existsSync as existsSync14, mkdirSync as mkdirSync4, openSync as openSync4, writeSync as writeSync3 } from "node:fs";import { Socket } from "node:net";import { dirname as dirname13, isAbsolute as isAbsolute5 } from "node:path";import { argv0, execPath } from "node:process";@@ -6725,7 +6791,7 @@ function pingDaemon(paths, token, timeoutMs = PROBE_TIMEOUT_MS2, signal) {}function spawnDaemonProcess(paths, deps = {}) {mkdirSync4(dirname13(paths.log), { recursive: true });- const logFd = openSync3(paths.log, "a");+ const logFd = openSync4(paths.log, "a");try {const spawnDaemonChild = deps.spawn ?? spawn3;const executable = deps.resolveExecutable?.() ?? resolveDaemonNodeExecutable();@@ -6735,15 +6801,15 @@ function spawnDaemonProcess(paths, deps = {}) {windowsHide: true,env: { ...process.env, BUN_BE_BUN: "1" }});- child.once("spawn", () => closeSync3(logFd));+ child.once("spawn", () => closeSync4(logFd));child.once("error", (error) => {writeSync3(logFd, `[lsp-daemon] failed to spawn daemon: ${error.message}`);- closeSync3(logFd);+ closeSync4(logFd);});child.unref();} catch (error) {- closeSync3(logFd);+ closeSync4(logFd);throw error;}}@@ -7247,7 +7313,7 @@ function canonicalizePathList(value) {function canonicalizePath(value) {if (value === undefined || !isAbsolute6(value) || !existsSync15(value))return value;- return realpathSync6(value);+ return realpathSync7(value);}function projectRootFromOpenCodeConfigPath(path) {if (basename4(path) !== "lsp.json" && basename4(path) !== "lsp-client.json")diff --git a/plugins/omo/components/lsp-daemon/dist/client.js b/plugins/omo/components/lsp-daemon/dist/client.jsindex 1b9360cd..4395960a 100644--- a/plugins/omo/components/lsp-daemon/dist/client.js+++ b/plugins/omo/components/lsp-daemon/dist/client.js@@ -1160,7 +1160,7 @@ function createIdleTimer(idleTimeoutMs, log, onTimeout) {};}// ../lsp-core/src/lsp/client-wrapper.ts-import { existsSync as existsSync11, realpathSync as realpathSync5, statSync as statSync4 } from "node:fs";+import { existsSync as existsSync11, realpathSync as realpathSync6, statSync as statSync4 } from "node:fs";import { basename as basename3, dirname as dirname10, join as join5, resolve as resolve8 } from "node:path";// ../lsp-core/src/lsp/effective-extension.ts@@ -4433,10 +4433,15 @@ var LSP_LOCAL_INSTALL_HINTS = {ty: "uv add --dev ty","ruby-lsp": "bundle add ruby-lsp --group development"};+var TYPESCRIPT_SERVER_INITIALIZATION = {+ tsserver: { useSyntaxServer: "never" },+ disableAutomaticTypingAcquisition: true+};var BUILTIN_SERVERS = {typescript: {command: ["typescript-language-server", "--stdio"],- extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"]+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],+ initialization: TYPESCRIPT_SERVER_INITIALIZATION},deno: { command: ["deno", "lsp"], extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"] },vue: { command: ["vue-language-server", "--stdio"], extensions: [".vue"] },@@ -4654,7 +4659,8 @@ function getMergedServers() {command: config.command,extensions: config.extensions,priority: -100,- source: "builtin"+ source: "builtin",+ ...config.initialization === undefined ? {} : { initialization: config.initialization }});}return servers.sort((a, b) => {@@ -4681,8 +4687,9 @@ function createServerFromEntry(id, entry, source) {priority: entry.priority ?? 0,source});- if (entry.initialization !== undefined) {- server.initialization = entry.initialization;+ const initialization = mergeInitialization(builtin.initialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;}return server;}@@ -4707,8 +4714,20 @@ function createServerFromEntry(id, entry, source) {source});applyOptionalServerFields(server, entry);+ const builtinInitialization = entry.command === undefined ? builtin.initialization : undefined;+ const initialization = mergeInitialization(builtinInitialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;+ }return server;}+function mergeInitialization(builtin, entry) {+ if (builtin === undefined)+ return entry;+ if (entry === undefined)+ return builtin;+ return { ...builtin, ...entry };+}function createServer(input) {const server = {id: input.id,@@ -4779,6 +4798,49 @@ function getDisabledServerIds() {return disabled;}+// ../lsp-core/src/lsp/host-js-runtime.ts+import { closeSync as closeSync3, openSync as openSync3, readSync, realpathSync as realpathSync5 } from "node:fs";+var HOST_RUNTIME_SERVER_IDS = new Set(["typescript"]);+var JS_ENTRY = /\.[cm]?js$/;+var NODE_SHEBANG = /^#![^\n]*\bnode\b/;+function currentHostJsRuntime() {+ return { bunExecPath: process.versions["bun"] === undefined ? undefined : process.execPath };+}+function withHostJsRuntime(serverId, command, host = currentHostJsRuntime()) {+ if (host.bunExecPath === undefined || !HOST_RUNTIME_SERVER_IDS.has(serverId))+ return command;+ const [binary, ...args] = command;+ if (binary === undefined)+ return command;+ const script = nodeScriptPath(binary);+ return script === undefined ? command : [host.bunExecPath, script, ...args];+}+function nodeScriptPath(binary) {+ let real;+ try {+ real = realpathSync5(binary);+ } catch {+ return;+ }+ if (JS_ENTRY.test(real))+ return real;+ try {+ return NODE_SHEBANG.test(readHead(real)) ? real : undefined;+ } catch {+ return;+ }+}+function readHead(path) {+ const fd = openSync3(path, "r");+ try {+ const buffer = Buffer.alloc(128);+ const bytes = readSync(fd, buffer, 0, buffer.length, 0);+ return buffer.toString("utf8", 0, bytes);+ } finally {+ closeSync3(fd);+ }+}+// ../lsp-core/src/lsp/server-installation.tsimport { existsSync as existsSync10 } from "node:fs";import { delimiter as delimiter3, dirname as dirname9, isAbsolute as isAbsolute5, join as join4, resolve as resolve7 } from "node:path";@@ -4918,6 +4980,10 @@ function isServerInstalled(command, workingDirectory, options = {}) {function withResolvedCommand(command, binaryPath) {return [binaryPath, ...command.slice(1)];}+function usesBuiltinCommand(id, command) {+ const builtin = BUILTIN_SERVERS[id]?.command;+ return builtin !== undefined && builtin.length === command.length && builtin.every((part, index) => part === command[index]);+}function findServerForExtension(ext) {const servers = getMergedServers();const workingDirectory = contextCwd();@@ -4928,7 +4994,7 @@ function findServerForExtension(ext) {if (binaryPath !== null) {const resolvedServer = {id: server.id,- command: withResolvedCommand(server.command, binaryPath),+ command: usesBuiltinCommand(server.id, server.command) ? withHostJsRuntime(server.id, withResolvedCommand(server.command, binaryPath)) : withResolvedCommand(server.command, binaryPath),extensions: server.extensions,priority: server.priority};@@ -5069,7 +5135,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {const suffix = [];while (true) {if (existsSync11(current)) {- const canonical = realpathSync5(current);+ const canonical = realpathSync6(current);if (isPathInside(cwd, canonical))return suffix.length === 0 ? canonical : join5(canonical, ...suffix);}@@ -5083,7 +5149,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {function existingDirectoryInsideContext(directory, cwd) {if (!existsSync11(directory))return;- const canonical = realpathSync5(directory);+ const canonical = realpathSync6(directory);if (!statSync4(canonical).isDirectory())return;return isPathInside(cwd, canonical) ? canonical : undefined;diff --git a/plugins/omo/components/lsp-daemon/dist/index.js b/plugins/omo/components/lsp-daemon/dist/index.jsindex 6de34b96..af2073be 100644--- a/plugins/omo/components/lsp-daemon/dist/index.js+++ b/plugins/omo/components/lsp-daemon/dist/index.js@@ -4314,7 +4314,7 @@ function createIdleTimer(idleTimeoutMs, log, onTimeout) {};}// ../lsp-core/src/lsp/client-wrapper.ts-import { existsSync as existsSync11, realpathSync as realpathSync5, statSync as statSync4 } from "node:fs";+import { existsSync as existsSync11, realpathSync as realpathSync6, statSync as statSync4 } from "node:fs";import { basename as basename3, dirname as dirname10, join as join5, resolve as resolve8 } from "node:path";// ../lsp-core/src/lsp/outside-context-workspace.ts@@ -4428,10 +4428,15 @@ var LSP_LOCAL_INSTALL_HINTS = {ty: "uv add --dev ty","ruby-lsp": "bundle add ruby-lsp --group development"};+var TYPESCRIPT_SERVER_INITIALIZATION = {+ tsserver: { useSyntaxServer: "never" },+ disableAutomaticTypingAcquisition: true+};var BUILTIN_SERVERS = {typescript: {command: ["typescript-language-server", "--stdio"],- extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"]+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],+ initialization: TYPESCRIPT_SERVER_INITIALIZATION},deno: { command: ["deno", "lsp"], extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"] },vue: { command: ["vue-language-server", "--stdio"], extensions: [".vue"] },@@ -4649,7 +4654,8 @@ function getMergedServers() {command: config.command,extensions: config.extensions,priority: -100,- source: "builtin"+ source: "builtin",+ ...config.initialization === undefined ? {} : { initialization: config.initialization }});}return servers.sort((a, b) => {@@ -4676,8 +4682,9 @@ function createServerFromEntry(id, entry, source) {priority: entry.priority ?? 0,source});- if (entry.initialization !== undefined) {- server.initialization = entry.initialization;+ const initialization = mergeInitialization(builtin.initialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;}return server;}@@ -4702,8 +4709,20 @@ function createServerFromEntry(id, entry, source) {source});applyOptionalServerFields(server, entry);+ const builtinInitialization = entry.command === undefined ? builtin.initialization : undefined;+ const initialization = mergeInitialization(builtinInitialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;+ }return server;}+function mergeInitialization(builtin, entry) {+ if (builtin === undefined)+ return entry;+ if (entry === undefined)+ return builtin;+ return { ...builtin, ...entry };+}function createServer(input) {const server = {id: input.id,@@ -4774,6 +4793,49 @@ function getDisabledServerIds() {return disabled;}+// ../lsp-core/src/lsp/host-js-runtime.ts+import { closeSync as closeSync3, openSync as openSync3, readSync, realpathSync as realpathSync5 } from "node:fs";+var HOST_RUNTIME_SERVER_IDS = new Set(["typescript"]);+var JS_ENTRY = /\.[cm]?js$/;+var NODE_SHEBANG = /^#![^\n]*\bnode\b/;+function currentHostJsRuntime() {+ return { bunExecPath: process.versions["bun"] === undefined ? undefined : process.execPath };+}+function withHostJsRuntime(serverId, command, host = currentHostJsRuntime()) {+ if (host.bunExecPath === undefined || !HOST_RUNTIME_SERVER_IDS.has(serverId))+ return command;+ const [binary, ...args] = command;+ if (binary === undefined)+ return command;+ const script = nodeScriptPath(binary);+ return script === undefined ? command : [host.bunExecPath, script, ...args];+}+function nodeScriptPath(binary) {+ let real;+ try {+ real = realpathSync5(binary);+ } catch {+ return;+ }+ if (JS_ENTRY.test(real))+ return real;+ try {+ return NODE_SHEBANG.test(readHead(real)) ? real : undefined;+ } catch {+ return;+ }+}+function readHead(path) {+ const fd = openSync3(path, "r");+ try {+ const buffer = Buffer.alloc(128);+ const bytes = readSync(fd, buffer, 0, buffer.length, 0);+ return buffer.toString("utf8", 0, bytes);+ } finally {+ closeSync3(fd);+ }+}+// ../lsp-core/src/lsp/server-installation.tsimport { existsSync as existsSync10 } from "node:fs";import { delimiter as delimiter3, dirname as dirname9, isAbsolute as isAbsolute5, join as join4, resolve as resolve7 } from "node:path";@@ -4913,6 +4975,10 @@ function isServerInstalled(command, workingDirectory, options = {}) {function withResolvedCommand(command, binaryPath) {return [binaryPath, ...command.slice(1)];}+function usesBuiltinCommand(id, command) {+ const builtin = BUILTIN_SERVERS[id]?.command;+ return builtin !== undefined && builtin.length === command.length && builtin.every((part, index) => part === command[index]);+}function findServerForExtension(ext) {const servers = getMergedServers();const workingDirectory = contextCwd();@@ -4923,7 +4989,7 @@ function findServerForExtension(ext) {if (binaryPath !== null) {const resolvedServer = {id: server.id,- command: withResolvedCommand(server.command, binaryPath),+ command: usesBuiltinCommand(server.id, server.command) ? withHostJsRuntime(server.id, withResolvedCommand(server.command, binaryPath)) : withResolvedCommand(server.command, binaryPath),extensions: server.extensions,priority: server.priority};@@ -5064,7 +5130,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {const suffix = [];while (true) {if (existsSync11(current)) {- const canonical = realpathSync5(current);+ const canonical = realpathSync6(current);if (isPathInside(cwd, canonical))return suffix.length === 0 ? canonical : join5(canonical, ...suffix);}@@ -5078,7 +5144,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {function existingDirectoryInsideContext(directory, cwd) {if (!existsSync11(directory))return;- const canonical = realpathSync5(directory);+ const canonical = realpathSync6(directory);if (!statSync4(canonical).isDirectory())return;return isPathInside(cwd, canonical) ? canonical : undefined;@@ -6871,7 +6937,7 @@ function isRetryableTool(name) {return name !== "rename" && name !== "lsp_rename";}// src/proxy.ts-import { existsSync as existsSync14, realpathSync as realpathSync6 } from "node:fs";+import { existsSync as existsSync14, realpathSync as realpathSync7 } from "node:fs";import { basename as basename4, delimiter as delimiter4, dirname as dirname12, isAbsolute as isAbsolute6 } from "node:path";var DEFAULT_STARTUP_TIMEOUT_MS = 1e4;async function runMcpStdioProxy(options = {}) {@@ -6997,7 +7063,7 @@ function canonicalizePathList(value) {function canonicalizePath(value) {if (value === undefined || !isAbsolute6(value) || !existsSync14(value))return value;- return realpathSync6(value);+ return realpathSync7(value);}function projectRootFromOpenCodeConfigPath(path) {if (basename4(path) !== "lsp.json" && basename4(path) !== "lsp-client.json")diff --git a/plugins/omo/components/lsp-tools-mcp/dist/cli.js b/plugins/omo/components/lsp-tools-mcp/dist/cli.jsindex 9d2e7f91..1885ca8b 100755--- a/plugins/omo/components/lsp-tools-mcp/dist/cli.js+++ b/plugins/omo/components/lsp-tools-mcp/dist/cli.js@@ -3474,7 +3474,7 @@ function createIdleTimer(idleTimeoutMs, log, onTimeout) {};}// ../lsp-core/src/lsp/client-wrapper.ts-import { existsSync as existsSync10, realpathSync as realpathSync5, statSync as statSync3 } from "node:fs";+import { existsSync as existsSync10, realpathSync as realpathSync6, statSync as statSync3 } from "node:fs";import { basename as basename3, dirname as dirname8, join as join5, resolve as resolve8 } from "node:path";// ../lsp-core/src/request-context.ts@@ -3766,10 +3766,15 @@ var LSP_LOCAL_INSTALL_HINTS = {ty: "uv add --dev ty","ruby-lsp": "bundle add ruby-lsp --group development"};+var TYPESCRIPT_SERVER_INITIALIZATION = {+ tsserver: { useSyntaxServer: "never" },+ disableAutomaticTypingAcquisition: true+};var BUILTIN_SERVERS = {typescript: {command: ["typescript-language-server", "--stdio"],- extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"]+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],+ initialization: TYPESCRIPT_SERVER_INITIALIZATION},deno: { command: ["deno", "lsp"], extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"] },vue: { command: ["vue-language-server", "--stdio"], extensions: [".vue"] },@@ -3987,7 +3992,8 @@ function getMergedServers() {command: config.command,extensions: config.extensions,priority: -100,- source: "builtin"+ source: "builtin",+ ...config.initialization === undefined ? {} : { initialization: config.initialization }});}return servers.sort((a, b) => {@@ -4014,8 +4020,9 @@ function createServerFromEntry(id, entry, source) {priority: entry.priority ?? 0,source});- if (entry.initialization !== undefined) {- server.initialization = entry.initialization;+ const initialization = mergeInitialization(builtin.initialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;}return server;}@@ -4040,8 +4047,20 @@ function createServerFromEntry(id, entry, source) {source});applyOptionalServerFields(server, entry);+ const builtinInitialization = entry.command === undefined ? builtin.initialization : undefined;+ const initialization = mergeInitialization(builtinInitialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;+ }return server;}+function mergeInitialization(builtin, entry) {+ if (builtin === undefined)+ return entry;+ if (entry === undefined)+ return builtin;+ return { ...builtin, ...entry };+}function createServer(input) {const server = {id: input.id,@@ -4112,6 +4131,49 @@ function getDisabledServerIds() {return disabled;}+// ../lsp-core/src/lsp/host-js-runtime.ts+import { closeSync, openSync, readSync, realpathSync as realpathSync5 } from "node:fs";+var HOST_RUNTIME_SERVER_IDS = new Set(["typescript"]);+var JS_ENTRY = /\.[cm]?js$/;+var NODE_SHEBANG = /^#![^\n]*\bnode\b/;+function currentHostJsRuntime() {+ return { bunExecPath: process.versions["bun"] === undefined ? undefined : process.execPath };+}+function withHostJsRuntime(serverId, command, host = currentHostJsRuntime()) {+ if (host.bunExecPath === undefined || !HOST_RUNTIME_SERVER_IDS.has(serverId))+ return command;+ const [binary, ...args] = command;+ if (binary === undefined)+ return command;+ const script = nodeScriptPath(binary);+ return script === undefined ? command : [host.bunExecPath, script, ...args];+}+function nodeScriptPath(binary) {+ let real;+ try {+ real = realpathSync5(binary);+ } catch {+ return;+ }+ if (JS_ENTRY.test(real))+ return real;+ try {+ return NODE_SHEBANG.test(readHead(real)) ? real : undefined;+ } catch {+ return;+ }+}+function readHead(path) {+ const fd = openSync(path, "r");+ try {+ const buffer = Buffer.alloc(128);+ const bytes = readSync(fd, buffer, 0, buffer.length, 0);+ return buffer.toString("utf8", 0, bytes);+ } finally {+ closeSync(fd);+ }+}+// ../lsp-core/src/lsp/server-installation.tsimport { existsSync as existsSync9 } from "node:fs";import { delimiter as delimiter3, dirname as dirname7, isAbsolute as isAbsolute3, join as join4, resolve as resolve7 } from "node:path";@@ -4251,6 +4313,10 @@ function isServerInstalled(command, workingDirectory, options = {}) {function withResolvedCommand(command, binaryPath) {return [binaryPath, ...command.slice(1)];}+function usesBuiltinCommand(id, command) {+ const builtin = BUILTIN_SERVERS[id]?.command;+ return builtin !== undefined && builtin.length === command.length && builtin.every((part, index) => part === command[index]);+}function findServerForExtension(ext) {const servers = getMergedServers();const workingDirectory = contextCwd();@@ -4261,7 +4327,7 @@ function findServerForExtension(ext) {if (binaryPath !== null) {const resolvedServer = {id: server.id,- command: withResolvedCommand(server.command, binaryPath),+ command: usesBuiltinCommand(server.id, server.command) ? withHostJsRuntime(server.id, withResolvedCommand(server.command, binaryPath)) : withResolvedCommand(server.command, binaryPath),extensions: server.extensions,priority: server.priority};@@ -4402,7 +4468,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {const suffix = [];while (true) {if (existsSync10(current)) {- const canonical = realpathSync5(current);+ const canonical = realpathSync6(current);if (isPathInside(cwd, canonical))return suffix.length === 0 ? canonical : join5(canonical, ...suffix);}@@ -4416,7 +4482,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {function existingDirectoryInsideContext(directory, cwd) {if (!existsSync10(directory))return;- const canonical = realpathSync5(directory);+ const canonical = realpathSync6(directory);if (!statSync3(canonical).isDirectory())return;return isPathInside(cwd, canonical) ? canonical : undefined;diff --git a/plugins/omo/components/lsp-tools-mcp/dist/mcp.js b/plugins/omo/components/lsp-tools-mcp/dist/mcp.jsindex 3c5e55b8..266c0626 100644--- a/plugins/omo/components/lsp-tools-mcp/dist/mcp.js+++ b/plugins/omo/components/lsp-tools-mcp/dist/mcp.js@@ -311,7 +311,7 @@ function createIdleTimer(idleTimeoutMs, log, onTimeout) {};}// ../lsp-core/src/lsp/client-wrapper.ts-import { existsSync as existsSync10, realpathSync as realpathSync5, statSync as statSync3 } from "node:fs";+import { existsSync as existsSync10, realpathSync as realpathSync6, statSync as statSync3 } from "node:fs";import { basename as basename3, dirname as dirname8, join as join5, resolve as resolve8 } from "node:path";// ../lsp-core/src/request-context.ts@@ -3762,10 +3762,15 @@ var LSP_LOCAL_INSTALL_HINTS = {ty: "uv add --dev ty","ruby-lsp": "bundle add ruby-lsp --group development"};+var TYPESCRIPT_SERVER_INITIALIZATION = {+ tsserver: { useSyntaxServer: "never" },+ disableAutomaticTypingAcquisition: true+};var BUILTIN_SERVERS = {typescript: {command: ["typescript-language-server", "--stdio"],- extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"]+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],+ initialization: TYPESCRIPT_SERVER_INITIALIZATION},deno: { command: ["deno", "lsp"], extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"] },vue: { command: ["vue-language-server", "--stdio"], extensions: [".vue"] },@@ -3983,7 +3988,8 @@ function getMergedServers() {command: config.command,extensions: config.extensions,priority: -100,- source: "builtin"+ source: "builtin",+ ...config.initialization === undefined ? {} : { initialization: config.initialization }});}return servers.sort((a, b) => {@@ -4010,8 +4016,9 @@ function createServerFromEntry(id, entry, source) {priority: entry.priority ?? 0,source});- if (entry.initialization !== undefined) {- server.initialization = entry.initialization;+ const initialization = mergeInitialization(builtin.initialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;}return server;}@@ -4036,8 +4043,20 @@ function createServerFromEntry(id, entry, source) {source});applyOptionalServerFields(server, entry);+ const builtinInitialization = entry.command === undefined ? builtin.initialization : undefined;+ const initialization = mergeInitialization(builtinInitialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;+ }return server;}+function mergeInitialization(builtin, entry) {+ if (builtin === undefined)+ return entry;+ if (entry === undefined)+ return builtin;+ return { ...builtin, ...entry };+}function createServer(input) {const server = {id: input.id,@@ -4108,6 +4127,49 @@ function getDisabledServerIds() {return disabled;}+// ../lsp-core/src/lsp/host-js-runtime.ts+import { closeSync, openSync, readSync, realpathSync as realpathSync5 } from "node:fs";+var HOST_RUNTIME_SERVER_IDS = new Set(["typescript"]);+var JS_ENTRY = /\.[cm]?js$/;+var NODE_SHEBANG = /^#![^\n]*\bnode\b/;+function currentHostJsRuntime() {+ return { bunExecPath: process.versions["bun"] === undefined ? undefined : process.execPath };+}+function withHostJsRuntime(serverId, command, host = currentHostJsRuntime()) {+ if (host.bunExecPath === undefined || !HOST_RUNTIME_SERVER_IDS.has(serverId))+ return command;+ const [binary, ...args] = command;+ if (binary === undefined)+ return command;+ const script = nodeScriptPath(binary);+ return script === undefined ? command : [host.bunExecPath, script, ...args];+}+function nodeScriptPath(binary) {+ let real;+ try {+ real = realpathSync5(binary);+ } catch {+ return;+ }+ if (JS_ENTRY.test(real))+ return real;+ try {+ return NODE_SHEBANG.test(readHead(real)) ? real : undefined;+ } catch {+ return;+ }+}+function readHead(path) {+ const fd = openSync(path, "r");+ try {+ const buffer = Buffer.alloc(128);+ const bytes = readSync(fd, buffer, 0, buffer.length, 0);+ return buffer.toString("utf8", 0, bytes);+ } finally {+ closeSync(fd);+ }+}+// ../lsp-core/src/lsp/server-installation.tsimport { existsSync as existsSync9 } from "node:fs";import { delimiter as delimiter3, dirname as dirname7, isAbsolute as isAbsolute3, join as join4, resolve as resolve7 } from "node:path";@@ -4247,6 +4309,10 @@ function isServerInstalled(command, workingDirectory, options = {}) {function withResolvedCommand(command, binaryPath) {return [binaryPath, ...command.slice(1)];}+function usesBuiltinCommand(id, command) {+ const builtin = BUILTIN_SERVERS[id]?.command;+ return builtin !== undefined && builtin.length === command.length && builtin.every((part, index) => part === command[index]);+}function findServerForExtension(ext) {const servers = getMergedServers();const workingDirectory = contextCwd();@@ -4257,7 +4323,7 @@ function findServerForExtension(ext) {if (binaryPath !== null) {const resolvedServer = {id: server.id,- command: withResolvedCommand(server.command, binaryPath),+ command: usesBuiltinCommand(server.id, server.command) ? withHostJsRuntime(server.id, withResolvedCommand(server.command, binaryPath)) : withResolvedCommand(server.command, binaryPath),extensions: server.extensions,priority: server.priority};@@ -4398,7 +4464,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {const suffix = [];while (true) {if (existsSync10(current)) {- const canonical = realpathSync5(current);+ const canonical = realpathSync6(current);if (isPathInside(cwd, canonical))return suffix.length === 0 ? canonical : join5(canonical, ...suffix);}@@ -4412,7 +4478,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {function existingDirectoryInsideContext(directory, cwd) {if (!existsSync10(directory))return;- const canonical = realpathSync5(directory);+ const canonical = realpathSync6(directory);if (!statSync3(canonical).isDirectory())return;return isPathInside(cwd, canonical) ? canonical : undefined;diff --git a/plugins/omo/components/lsp-tools-mcp/dist/tools.js b/plugins/omo/components/lsp-tools-mcp/dist/tools.jsindex 5484984f..61896e78 100644--- a/plugins/omo/components/lsp-tools-mcp/dist/tools.js+++ b/plugins/omo/components/lsp-tools-mcp/dist/tools.js@@ -1,5 +1,5 @@// ../lsp-core/src/lsp/client-wrapper.ts-import { existsSync as existsSync10, realpathSync as realpathSync5, statSync as statSync3 } from "node:fs";+import { existsSync as existsSync10, realpathSync as realpathSync6, statSync as statSync3 } from "node:fs";import { basename as basename3, dirname as dirname8, join as join5, resolve as resolve8 } from "node:path";// ../lsp-core/src/request-context.ts@@ -3450,10 +3450,15 @@ var LSP_LOCAL_INSTALL_HINTS = {ty: "uv add --dev ty","ruby-lsp": "bundle add ruby-lsp --group development"};+var TYPESCRIPT_SERVER_INITIALIZATION = {+ tsserver: { useSyntaxServer: "never" },+ disableAutomaticTypingAcquisition: true+};var BUILTIN_SERVERS = {typescript: {command: ["typescript-language-server", "--stdio"],- extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"]+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],+ initialization: TYPESCRIPT_SERVER_INITIALIZATION},deno: { command: ["deno", "lsp"], extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"] },vue: { command: ["vue-language-server", "--stdio"], extensions: [".vue"] },@@ -3671,7 +3676,8 @@ function getMergedServers() {command: config.command,extensions: config.extensions,priority: -100,- source: "builtin"+ source: "builtin",+ ...config.initialization === undefined ? {} : { initialization: config.initialization }});}return servers.sort((a, b) => {@@ -3698,8 +3704,9 @@ function createServerFromEntry(id, entry, source) {priority: entry.priority ?? 0,source});- if (entry.initialization !== undefined) {- server.initialization = entry.initialization;+ const initialization = mergeInitialization(builtin.initialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;}return server;}@@ -3724,8 +3731,20 @@ function createServerFromEntry(id, entry, source) {source});applyOptionalServerFields(server, entry);+ const builtinInitialization = entry.command === undefined ? builtin.initialization : undefined;+ const initialization = mergeInitialization(builtinInitialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;+ }return server;}+function mergeInitialization(builtin, entry) {+ if (builtin === undefined)+ return entry;+ if (entry === undefined)+ return builtin;+ return { ...builtin, ...entry };+}function createServer(input) {const server = {id: input.id,@@ -3796,6 +3815,49 @@ function getDisabledServerIds() {return disabled;}+// ../lsp-core/src/lsp/host-js-runtime.ts+import { closeSync, openSync, readSync, realpathSync as realpathSync5 } from "node:fs";+var HOST_RUNTIME_SERVER_IDS = new Set(["typescript"]);+var JS_ENTRY = /\.[cm]?js$/;+var NODE_SHEBANG = /^#![^\n]*\bnode\b/;+function currentHostJsRuntime() {+ return { bunExecPath: process.versions["bun"] === undefined ? undefined : process.execPath };+}+function withHostJsRuntime(serverId, command, host = currentHostJsRuntime()) {+ if (host.bunExecPath === undefined || !HOST_RUNTIME_SERVER_IDS.has(serverId))+ return command;+ const [binary, ...args] = command;+ if (binary === undefined)+ return command;+ const script = nodeScriptPath(binary);+ return script === undefined ? command : [host.bunExecPath, script, ...args];+}+function nodeScriptPath(binary) {+ let real;+ try {+ real = realpathSync5(binary);+ } catch {+ return;+ }+ if (JS_ENTRY.test(real))+ return real;+ try {+ return NODE_SHEBANG.test(readHead(real)) ? real : undefined;+ } catch {+ return;+ }+}+function readHead(path) {+ const fd = openSync(path, "r");+ try {+ const buffer = Buffer.alloc(128);+ const bytes = readSync(fd, buffer, 0, buffer.length, 0);+ return buffer.toString("utf8", 0, bytes);+ } finally {+ closeSync(fd);+ }+}+// ../lsp-core/src/lsp/server-installation.tsimport { existsSync as existsSync9 } from "node:fs";import { delimiter as delimiter3, dirname as dirname7, isAbsolute as isAbsolute3, join as join4, resolve as resolve7 } from "node:path";@@ -3935,6 +3997,10 @@ function isServerInstalled(command, workingDirectory, options = {}) {function withResolvedCommand(command, binaryPath) {return [binaryPath, ...command.slice(1)];}+function usesBuiltinCommand(id, command) {+ const builtin = BUILTIN_SERVERS[id]?.command;+ return builtin !== undefined && builtin.length === command.length && builtin.every((part, index) => part === command[index]);+}function findServerForExtension(ext) {const servers = getMergedServers();const workingDirectory = contextCwd();@@ -3945,7 +4011,7 @@ function findServerForExtension(ext) {if (binaryPath !== null) {const resolvedServer = {id: server.id,- command: withResolvedCommand(server.command, binaryPath),+ command: usesBuiltinCommand(server.id, server.command) ? withHostJsRuntime(server.id, withResolvedCommand(server.command, binaryPath)) : withResolvedCommand(server.command, binaryPath),extensions: server.extensions,priority: server.priority};@@ -4086,7 +4152,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {const suffix = [];while (true) {if (existsSync10(current)) {- const canonical = realpathSync5(current);+ const canonical = realpathSync6(current);if (isPathInside(cwd, canonical))return suffix.length === 0 ? canonical : join5(canonical, ...suffix);}@@ -4100,7 +4166,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {function existingDirectoryInsideContext(directory, cwd) {if (!existsSync10(directory))return;- const canonical = realpathSync5(directory);+ const canonical = realpathSync6(directory);if (!statSync3(canonical).isDirectory())return;return isPathInside(cwd, canonical) ? canonical : undefined;diff --git a/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json b/plugins/omo/components/lsp/dist/.omo-runtime-manifest.jsonindex acc59c2a..01770428 100644--- a/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json+++ b/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json@@ -1,7 +1,7 @@{"schemaVersion": 1,- "version": "5.1.51",- "inputDigest": "sha256:39638ec3ebc26f2042f36d305d73e0414c185f68ab8cf5120a82774b425697ec",+ "version": "5.1.54",+ "inputDigest": "sha256:697a2c789b11bcef3067ffa642529c4ec64469117934d7cc53fae09b1e77822d","outputs": [{"path": "cli.d.ts",@@ -9,7 +9,7 @@},{"path": "cli.js",- "sha256": "93e248d2fb5ccb0bdc1a01e2ac7c6e05184a919093dd3ab979a1a48af27b8dcd"+ "sha256": "0d10efe6a0c981e5b7b2f3e98876abc198456463d522338f175f3e9d55ab3caa"},{"path": "codex-hook-cli.d.ts",diff --git a/plugins/omo/components/lsp/dist/cli.js b/plugins/omo/components/lsp/dist/cli.jsindex ad199327..922fdfd0 100644--- a/plugins/omo/components/lsp/dist/cli.js+++ b/plugins/omo/components/lsp/dist/cli.js@@ -8,7 +8,7 @@ import { argv, execPath as execPath2, stderr } from "node:process";import { stdin as processStdin } from "node:process";// src/codex-hook.ts-import { readFileSync as readFileSync10, realpathSync as realpathSync7 } from "node:fs";+import { readFileSync as readFileSync10, realpathSync as realpathSync8 } from "node:fs";import { homedir as homedir4 } from "node:os";import { join as join12, resolve as resolve13 } from "node:path";@@ -45,7 +45,7 @@ import * as path from "node:path";import { fileURLToPath } from "node:url";import { statSync as statSync2 } from "node:fs";import { isAbsolute as isAbsolute2 } from "node:path";-import { existsSync as existsSync11, realpathSync as realpathSync5, statSync as statSync4 } from "node:fs";+import { existsSync as existsSync11, realpathSync as realpathSync6, statSync as statSync4 } from "node:fs";import { basename as basename3, dirname as dirname10, join as join5, resolve as resolve8 } from "node:path";import { basename as basename2, extname } from "node:path";import { resolve as resolve6 } from "node:path";@@ -70,6 +70,7 @@ import { dirname as dirname7, join as join3 } from "node:path";import { existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";import { dirname as dirname8 } from "node:path";import { existsSync as existsSync9, readFileSync as readFileSync5 } from "node:fs";+import { closeSync as closeSync3, openSync as openSync3, readSync, realpathSync as realpathSync5 } from "node:fs";import { existsSync as existsSync10 } from "node:fs";import { delimiter as delimiter3, dirname as dirname9, isAbsolute as isAbsolute5, join as join4, resolve as resolve7 } from "node:path";import { existsSync as existsSync12, lstatSync as lstatSync5, readdirSync as readdirSync3 } from "node:fs";@@ -3872,10 +3873,15 @@ var LSP_LOCAL_INSTALL_HINTS = {ty: "uv add --dev ty","ruby-lsp": "bundle add ruby-lsp --group development"};+var TYPESCRIPT_SERVER_INITIALIZATION = {+ tsserver: { useSyntaxServer: "never" },+ disableAutomaticTypingAcquisition: true+};var BUILTIN_SERVERS = {typescript: {command: ["typescript-language-server", "--stdio"],- extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"]+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],+ initialization: TYPESCRIPT_SERVER_INITIALIZATION},deno: { command: ["deno", "lsp"], extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"] },vue: { command: ["vue-language-server", "--stdio"], extensions: [".vue"] },@@ -4086,7 +4092,8 @@ function getMergedServers() {command: config.command,extensions: config.extensions,priority: -100,- source: "builtin"+ source: "builtin",+ ...config.initialization === undefined ? {} : { initialization: config.initialization }});}return servers.sort((a, b) => {@@ -4113,8 +4120,9 @@ function createServerFromEntry(id, entry, source) {priority: entry.priority ?? 0,source});- if (entry.initialization !== undefined) {- server.initialization = entry.initialization;+ const initialization = mergeInitialization(builtin.initialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;}return server;}@@ -4139,8 +4147,20 @@ function createServerFromEntry(id, entry, source) {source});applyOptionalServerFields(server, entry);+ const builtinInitialization = entry.command === undefined ? builtin.initialization : undefined;+ const initialization = mergeInitialization(builtinInitialization, entry.initialization);+ if (initialization !== undefined) {+ server.initialization = initialization;+ }return server;}+function mergeInitialization(builtin, entry) {+ if (builtin === undefined)+ return entry;+ if (entry === undefined)+ return builtin;+ return { ...builtin, ...entry };+}function createServer(input) {const server = {id: input.id,@@ -4210,6 +4230,46 @@ function getDisabledServerIds() {}return disabled;}+var HOST_RUNTIME_SERVER_IDS = new Set(["typescript"]);+var JS_ENTRY = /\.[cm]?js$/;+var NODE_SHEBANG = /^#![^\n]*\bnode\b/;+function currentHostJsRuntime() {+ return { bunExecPath: process.versions["bun"] === undefined ? undefined : process.execPath };+}+function withHostJsRuntime(serverId, command, host = currentHostJsRuntime()) {+ if (host.bunExecPath === undefined || !HOST_RUNTIME_SERVER_IDS.has(serverId))+ return command;+ const [binary, ...args] = command;+ if (binary === undefined)+ return command;+ const script = nodeScriptPath(binary);+ return script === undefined ? command : [host.bunExecPath, script, ...args];+}+function nodeScriptPath(binary) {+ let real;+ try {+ real = realpathSync5(binary);+ } catch {+ return;+ }+ if (JS_ENTRY.test(real))+ return real;+ try {+ return NODE_SHEBANG.test(readHead(real)) ? real : undefined;+ } catch {+ return;+ }+}+function readHead(path) {+ const fd = openSync3(path, "r");+ try {+ const buffer = Buffer.alloc(128);+ const bytes = readSync(fd, buffer, 0, buffer.length, 0);+ return buffer.toString("utf8", 0, bytes);+ } finally {+ closeSync3(fd);+ }+}var LOCAL_BIN_RULES = [{markers: ["package.json", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock", "pnpm-lock.yaml"],@@ -4344,6 +4404,10 @@ function isServerInstalled(command, workingDirectory, options = {}) {function withResolvedCommand(command, binaryPath) {return [binaryPath, ...command.slice(1)];}+function usesBuiltinCommand(id, command) {+ const builtin = BUILTIN_SERVERS[id]?.command;+ return builtin !== undefined && builtin.length === command.length && builtin.every((part, index) => part === command[index]);+}function findServerForExtension(ext) {const servers = getMergedServers();const workingDirectory = contextCwd();@@ -4354,7 +4418,7 @@ function findServerForExtension(ext) {if (binaryPath !== null) {const resolvedServer = {id: server.id,- command: withResolvedCommand(server.command, binaryPath),+ command: usesBuiltinCommand(server.id, server.command) ? withHostJsRuntime(server.id, withResolvedCommand(server.command, binaryPath)) : withResolvedCommand(server.command, binaryPath),extensions: server.extensions,priority: server.priority};@@ -4493,7 +4557,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {const suffix = [];while (true) {if (existsSync11(current)) {- const canonical = realpathSync5(current);+ const canonical = realpathSync6(current);if (isPathInside(cwd, canonical))return suffix.length === 0 ? canonical : join5(canonical, ...suffix);}@@ -4507,7 +4571,7 @@ function rebaseThroughCanonicalAncestor(path, cwd) {function existingDirectoryInsideContext(directory, cwd) {if (!existsSync11(directory))return;- const canonical = realpathSync5(directory);+ const canonical = realpathSync6(directory);if (!statSync4(canonical).isDirectory())return;return isPathInside(cwd, canonical) ? canonical : undefined;@@ -6129,7 +6193,7 @@ var WORKSPACE_MARKERS2 = [GIT_WORKSPACE_MARKER2, ...PROJECT_WORKSPACE_MARKERS2];// ../../../../lsp-core/src/request-context.tsimport { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";-import { existsSync as existsSync14, realpathSync as realpathSync6, statSync as statSync7 } from "node:fs";+import { existsSync as existsSync14, realpathSync as realpathSync7, statSync as statSync7 } from "node:fs";import { basename as basename4, delimiter as delimiter4, dirname as dirname2, isAbsolute as isAbsolute7, join as join9, relative as relative5, resolve as resolve12 } from "node:path";class LspRequestContextParseError2 extends Error {@@ -6175,14 +6239,14 @@ function canonicalCwd2(cwd) {if (!existsSync14(resolved) || !statSync7(resolved).isDirectory()) {throw new LspRequestContextParseError2("invalid_cwd", `LSP request cwd must be an existing directory: ${cwd}`);}- return realpathSync6(resolved);+ return realpathSync7(resolved);}function canonicalizeExistingOrNearestAncestor2(path) {let current = resolve12(path);const suffix = [];while (true) {try {- const existing = realpathSync6(current);+ const existing = realpathSync7(current);return suffix.length === 0 ? existing : join9(existing, ...suffix);} catch (error) {if (!isMissingPathError2(error))@@ -6642,7 +6706,7 @@ function notInstalledOutcome(availability, text) {return decision === "declined" || decision === "allowed" ? { ...base, decision } : base;}function codexLspRequestContext(env = process.env, cwd = process.cwd()) {- const canonicalCwd = realpathSync7(resolve13(cwd));+ const canonicalCwd = realpathSync8(resolve13(cwd));const codexHome = resolve13(env["CODEX_HOME"]?.trim() || join12(homedir4(), ".codex"));return parseLspRequestContext2({cwd: canonicalCwd,diff --git a/plugins/omo/components/lsp/hooks/hooks.json b/plugins/omo/components/lsp/hooks/hooks.jsonindex 10f13ae2..5849218f 100644--- a/plugins/omo/components/lsp/hooks/hooks.json+++ b/plugins/omo/components/lsp/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 60,- "statusMessage": "(OmO 5.1.51) Checking LSP Diagnostics"+ "statusMessage": "(OmO 5.1.54) Checking LSP Diagnostics"}]}@@ -21,7 +21,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "(OmO 5.1.51) Resetting LSP Diagnostics Cache"+ "statusMessage": "(OmO 5.1.54) Resetting LSP Diagnostics Cache"}]}diff --git a/plugins/omo/components/lsp/package.json b/plugins/omo/components/lsp/package.jsonindex 0e6ed0a6..462b6af0 100644--- a/plugins/omo/components/lsp/package.json+++ b/plugins/omo/components/lsp/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-lsp",- "version": "5.1.51",+ "version": "5.1.54","description": "Codex plugin that exposes Language Server Protocol tools and post-edit diagnostics.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/rules/hooks/hooks.json b/plugins/omo/components/rules/hooks/hooks.jsonindex 7bdde5e1..c3d0f02c 100644--- a/plugins/omo/components/rules/hooks/hooks.json+++ b/plugins/omo/components/rules/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start","timeout": 10,- "statusMessage": "(OmO 5.1.51) Loading Project Rules"+ "statusMessage": "(OmO 5.1.54) Loading Project Rules"}]}@@ -19,7 +19,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "(OmO 5.1.51) Loading Project Rules"+ "statusMessage": "(OmO 5.1.54) Loading Project Rules"}]}@@ -32,7 +32,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "(OmO 5.1.51) Matching Project Rules"+ "statusMessage": "(OmO 5.1.54) Matching Project Rules"}]}@@ -45,7 +45,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact","timeout": 10,- "statusMessage": "(OmO 5.1.51) Resetting Project Rule Cache"+ "statusMessage": "(OmO 5.1.54) Resetting Project Rule Cache"}]}diff --git a/plugins/omo/components/rules/package.json b/plugins/omo/components/rules/package.jsonindex 8a1820b9..61a4ef53 100644--- a/plugins/omo/components/rules/package.json+++ b/plugins/omo/components/rules/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-rules",- "version": "5.1.51",+ "version": "5.1.54","description": "Codex plugin that injects project rule files into model context through lifecycle hooks.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/teammode/hooks/hooks.json b/plugins/omo/components/teammode/hooks/hooks.jsonindex 08e3c541..d83ada42 100644--- a/plugins/omo/components/teammode/hooks/hooks.json+++ b/plugins/omo/components/teammode/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "(OmO 5.1.51) Checking Thread Title Hygiene"+ "statusMessage": "(OmO 5.1.54) Checking Thread Title Hygiene"}]}diff --git a/plugins/omo/components/teammode/package.json b/plugins/omo/components/teammode/package.jsonindex bb6abc87..90352330 100644--- a/plugins/omo/components/teammode/package.json+++ b/plugins/omo/components/teammode/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/codex-teammode",- "version": "5.1.51",+ "version": "5.1.54","description": "Codex team-mode hook component that keeps background thread titles descriptive after create_thread.","type": "module","private": true,diff --git a/plugins/omo/components/telemetry/dist/cli.js b/plugins/omo/components/telemetry/dist/cli.jsindex d4e29292..5a5d98c7 100755--- a/plugins/omo/components/telemetry/dist/cli.js+++ b/plugins/omo/components/telemetry/dist/cli.js@@ -469,6 +469,34 @@ function getDefaultTelemetryOsProvider() {return os2;}+// ../../telemetry-core/src/terminal-program.ts+var KNOWN_TERMINAL_PROGRAMS = [+ "Apple_Terminal",+ "iTerm.app",+ "vscode",+ "cursor",+ "windsurf",+ "zed",+ "WezTerm",+ "ghostty",+ "tmux",+ "Hyper",+ "WarpTerminal",+ "kitty",+ "alacritty",+ "Tabby",+ "rio",+ "mintty"+];+function isKnownTerminalProgram(value) {+ return KNOWN_TERMINAL_PROGRAMS.some((known) => known === value);+}+function toTelemetryTerminalProgram(termProgram) {+ if (termProgram === undefined || termProgram === "")+ return;+ return isKnownTerminalProgram(termProgram) ? termProgram : "other";+}+// ../../telemetry-core/src/injected-client.tsvar NO_OP_CLIENT = {enabled: false,@@ -583,12 +611,16 @@ function getSharedProperties(input) {total_memory_gb: Math.round(osProvider.totalmem() / 1024 / 1024 / 1024),locale: Intl.DateTimeFormat().resolvedOptions().locale,timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,- shell: process.env.SHELL,+ shell: getShellName(process.env.SHELL),ci: Boolean(process.env.CI),- terminal: process.env.TERM_PROGRAM,+ terminal: toTelemetryTerminalProgram(process.env.TERM_PROGRAM),...input.product.additionalProperties};}+function getShellName(shellPath) {+ const name = shellPath?.split(/[\\/]/).pop()?.replace(/\.exe$/i, "");+ return name ? name : undefined;+}function getSafeCpuInfo(osProvider, input) {try {const cpuInfo = osProvider.cpus();diff --git a/plugins/omo/components/telemetry/dist/posthog.js b/plugins/omo/components/telemetry/dist/posthog.jsindex 08003198..e40e2b97 100644--- a/plugins/omo/components/telemetry/dist/posthog.js+++ b/plugins/omo/components/telemetry/dist/posthog.js@@ -465,6 +465,34 @@ function getDefaultTelemetryOsProvider() {return os2;}+// ../../../../telemetry-core/src/terminal-program.ts+var KNOWN_TERMINAL_PROGRAMS = [+ "Apple_Terminal",+ "iTerm.app",+ "vscode",+ "cursor",+ "windsurf",+ "zed",+ "WezTerm",+ "ghostty",+ "tmux",+ "Hyper",+ "WarpTerminal",+ "kitty",+ "alacritty",+ "Tabby",+ "rio",+ "mintty"+];+function isKnownTerminalProgram(value) {+ return KNOWN_TERMINAL_PROGRAMS.some((known) => known === value);+}+function toTelemetryTerminalProgram(termProgram) {+ if (termProgram === undefined || termProgram === "")+ return;+ return isKnownTerminalProgram(termProgram) ? termProgram : "other";+}+// ../../../../telemetry-core/src/injected-client.tsvar NO_OP_CLIENT = {enabled: false,@@ -579,12 +607,16 @@ function getSharedProperties(input) {total_memory_gb: Math.round(osProvider.totalmem() / 1024 / 1024 / 1024),locale: Intl.DateTimeFormat().resolvedOptions().locale,timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,- shell: process.env.SHELL,+ shell: getShellName(process.env.SHELL),ci: Boolean(process.env.CI),- terminal: process.env.TERM_PROGRAM,+ terminal: toTelemetryTerminalProgram(process.env.TERM_PROGRAM),...input.product.additionalProperties};}+function getShellName(shellPath) {+ const name = shellPath?.split(/[\\/]/).pop()?.replace(/\.exe$/i, "");+ return name ? name : undefined;+}function getSafeCpuInfo(osProvider, input) {try {const cpuInfo = osProvider.cpus();diff --git a/plugins/omo/components/telemetry/hooks/hooks.json b/plugins/omo/components/telemetry/hooks/hooks.jsonindex 7fe11939..8dcc5bc2 100644--- a/plugins/omo/components/telemetry/hooks/hooks.json+++ b/plugins/omo/components/telemetry/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start","timeout": 5,- "statusMessage": "(OmO 5.1.51) Recording Session Telemetry"+ "statusMessage": "(OmO 5.1.54) Recording Session Telemetry"}]}diff --git a/plugins/omo/components/telemetry/package.json b/plugins/omo/components/telemetry/package.jsonindex f284354d..46f9220c 100644--- a/plugins/omo/components/telemetry/package.json+++ b/plugins/omo/components/telemetry/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-telemetry",- "version": "5.1.51",+ "version": "5.1.54","description": "Codex plugin component that emits omo-codex anonymous daily-active telemetry on SessionStart.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/ultrawork/hooks/hooks.json b/plugins/omo/components/ultrawork/hooks/hooks.jsonindex 31f24c53..20470551 100644--- a/plugins/omo/components/ultrawork/hooks/hooks.json+++ b/plugins/omo/components/ultrawork/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit","timeout": 5,- "statusMessage": "(OmO 5.1.51) Checking Ultrawork Trigger"+ "statusMessage": "(OmO 5.1.54) Checking Ultrawork Trigger"}]}diff --git a/plugins/omo/components/ultrawork/package.json b/plugins/omo/components/ultrawork/package.jsonindex 82e892ba..dbd8e0b7 100644--- a/plugins/omo/components/ultrawork/package.json+++ b/plugins/omo/components/ultrawork/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-ultrawork",- "version": "5.1.51",+ "version": "5.1.54","description": "Codex plugin that injects the ultrawork orchestration directive and ships LazyCodex planning, review, QA, and gate agent roles.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json b/plugins/omo/components/ulw-execute-continuation/hooks/hooks.jsonindex 67cb5223..42141fac 100644--- a/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json+++ b/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-execute-continuation/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "(OmO 5.1.51) Checking Ulw-Execute Continuation"+ "statusMessage": "(OmO 5.1.54) Checking Ulw-Execute Continuation"}]}diff --git a/plugins/omo/components/ulw-execute-continuation/package.json b/plugins/omo/components/ulw-execute-continuation/package.jsonindex 7ae0a617..abe1835e 100644--- a/plugins/omo/components/ulw-execute-continuation/package.json+++ b/plugins/omo/components/ulw-execute-continuation/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-ulw-execute-continuation",- "version": "5.1.51",+ "version": "5.1.54","description": "Codex Stop hook continuation injector for omo-codex ulw-execute plans.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/ulw-loop/hooks/hooks.json b/plugins/omo/components/ulw-loop/hooks/hooks.jsonindex f6274d52..88b2bbd1 100644--- a/plugins/omo/components/ulw-loop/hooks/hooks.json+++ b/plugins/omo/components/ulw-loop/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit --with-ultrawork","timeout": 10,- "statusMessage": "(OmO 5.1.51) Checking Ulw-Loop Steering"+ "statusMessage": "(OmO 5.1.54) Checking Ulw-Loop Steering"}]}@@ -20,7 +20,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use-spawn","timeout": 5,- "statusMessage": "(OmO 5.1.51) Recording Spawn Admission"+ "statusMessage": "(OmO 5.1.54) Recording Spawn Admission"}]}@@ -33,7 +33,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "(OmO 5.1.51) Enforcing Unlimited Ulw-Loop Budget"+ "statusMessage": "(OmO 5.1.54) Enforcing Unlimited Ulw-Loop Budget"}]},@@ -44,7 +44,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use-spawn","timeout": 5,- "statusMessage": "(OmO 5.1.51) Guarding Ulw-Loop Spawns"+ "statusMessage": "(OmO 5.1.54) Guarding Ulw-Loop Spawns"}]}@@ -56,7 +56,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "(OmO 5.1.51) Checking Ulw-Loop Resume"+ "statusMessage": "(OmO 5.1.54) Checking Ulw-Loop Resume"}]}diff --git a/plugins/omo/components/ulw-loop/package.json b/plugins/omo/components/ulw-loop/package.jsonindex 9a6e5dd2..7b1d2dee 100644--- a/plugins/omo/components/ulw-loop/package.json+++ b/plugins/omo/components/ulw-loop/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-ulw-loop",- "version": "5.1.51",+ "version": "5.1.54","description": "Codex plugin: durable repo-native multi-goal orchestration with embedded success criteria and observable evidence audit.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/dist/cli-node/index.js b/plugins/omo/dist/cli-node/index.jsindex 254bd3a6..c96b85da 100755--- a/plugins/omo/dist/cli-node/index.js+++ b/plugins/omo/dist/cli-node/index.js@@ -2133,7 +2133,7 @@ var package_default;var init_package = __esm(() => {package_default = {name: "oh-my-opencode",- version: "5.1.51",+ version: "5.1.54",description: "The Best AI Agent Harness - Batteries-Included OpenCode Plugin with Multi-Model Orchestration, Parallel Background Agents, and Crafted LSP/AST Tools",main: "./dist/index.js",types: "dist/index.d.ts",@@ -2275,14 +2275,15 @@ var init_package = __esm(() => {prepublishOnly: "bun run clean && bun run build:lsp-tools-mcp && bun run build:lsp-daemon && bun run build","test:model-capabilities": "bun test --timeout 20000 packages/model-core/src/model-capability-aliases.test.ts packages/model-core/src/model-capability-guardrails.test.ts packages/model-core/src/model-capabilities.test.ts packages/omo-opencode/src/cli/doctor/checks/model-resolution.test.ts --bail","check:copy": "bun script/check-copy.ts",- typecheck: "bun run check:copy && tsgo --noEmit && bun run typecheck:script && bun run typecheck:packages",- "typecheck:packages": "tsgo --noEmit -p packages/rules-engine/tsconfig.json && tsgo --noEmit -p packages/delegate-core/tsconfig.json && tsgo --noEmit -p packages/mcp-stdio-core/tsconfig.json && tsgo --noEmit -p packages/mcp-client-core/tsconfig.json && tsgo --noEmit -p packages/git-bash-mcp/tsconfig.json && tsgo --noEmit -p packages/ast-grep-mcp/tsconfig.json && tsgo --noEmit -p packages/lsp-core/tsconfig.json && tsgo --noEmit -p packages/utils/tsconfig.json && tsgo --noEmit -p packages/model-core/tsconfig.json && tsgo --noEmit -p packages/omo-config-core/tsconfig.json && tsgo --noEmit -p packages/prompts-core/tsconfig.json && tsgo --noEmit -p packages/comment-checker-core/tsconfig.json && tsgo --noEmit -p packages/hashline-core/tsconfig.json && tsgo --noEmit -p packages/tmux-core/tsconfig.json && tsgo --noEmit -p packages/team-core/tsconfig.json && tsgo --noEmit -p packages/openclaw-core/tsconfig.json && tsgo --noEmit -p packages/boulder-state/tsconfig.json && tsgo --noEmit -p packages/isolation-core/tsconfig.json && tsgo --noEmit -p packages/memory-core/tsconfig.json && tsgo --noEmit -p packages/telemetry-core/tsconfig.json && tsgo --noEmit -p packages/claude-code-compat-core/tsconfig.json && tsgo --noEmit -p packages/skills-loader-core/tsconfig.json && tsgo --noEmit -p packages/agents-md-core/tsconfig.json && tsgo --noEmit -p packages/omo-codex/plugin/shared/tsconfig.json && tsgo --noEmit -p packages/omo-codex/tsconfig.json && tsgo --noEmit -p packages/omo-senpi/tsconfig.json && tsgo --noEmit -p packages/senpi-task/tsconfig.json && tsgo --noEmit -p packages/omo-opencode/tsconfig.json && tsgo --noEmit -p packages/omo-native/tsconfig.json && tsgo --noEmit -p packages/senpi-desktop-protocol/tsconfig.json && tsgo --noEmit -p packages/senpi-desktop-engine/tsconfig.json && tsgo --noEmit -p packages/senpi-desktop-prelude/tsconfig.json && tsgo --noEmit -p packages/senpi-desktop-service/tsconfig.json && tsgo --noEmit -p packages/senpi-desktop-tool/tsconfig.json",- "typecheck:script": "tsgo --noEmit -p script/tsconfig.json",+ typecheck: "bun run check:copy && bun check --no-script --all -p tsconfig.json && bun run typecheck:script && bun run typecheck:packages && bun run typecheck:skill-scripts",+ "typecheck:skill-scripts": "bun check --no-script --all -p packages/shared-skills/skills/frontend/scripts/detect/tsconfig.json",+ "typecheck:packages": "bun check --no-script --all -p packages/rules-engine/tsconfig.json && bun check --no-script --all -p packages/delegate-core/tsconfig.json && bun check --no-script --all -p packages/mcp-stdio-core/tsconfig.json && bun check --no-script --all -p packages/mcp-client-core/tsconfig.json && bun check --no-script --all -p packages/git-bash-mcp/tsconfig.json && bun check --no-script --all -p packages/ast-grep-mcp/tsconfig.json && bun check --no-script --all -p packages/lsp-core/tsconfig.json && bun check --no-script --all -p packages/utils/tsconfig.json && bun check --no-script --all -p packages/model-core/tsconfig.json && bun check --no-script --all -p packages/omo-config-core/tsconfig.json && bun check --no-script --all -p packages/prompts-core/tsconfig.json && bun check --no-script --all -p packages/comment-checker-core/tsconfig.json && bun check --no-script --all -p packages/hashline-core/tsconfig.json && bun check --no-script --all -p packages/tmux-core/tsconfig.json && bun check --no-script --all -p packages/team-core/tsconfig.json && bun check --no-script --all -p packages/openclaw-core/tsconfig.json && bun check --no-script --all -p packages/boulder-state/tsconfig.json && bun check --no-script --all -p packages/isolation-core/tsconfig.json && bun check --no-script --all -p packages/memory-core/tsconfig.json && bun check --no-script --all -p packages/telemetry-core/tsconfig.json && bun check --no-script --all -p packages/claude-code-compat-core/tsconfig.json && bun check --no-script --all -p packages/skills-loader-core/tsconfig.json && bun check --no-script --all -p packages/agents-md-core/tsconfig.json && bun check --no-script --all -p packages/omo-codex/plugin/shared/tsconfig.json && bun check --no-script --all -p packages/omo-codex/tsconfig.json && bun check --no-script --all -p packages/omo-senpi/tsconfig.json && bun check --no-script --all -p packages/senpi-task/tsconfig.json && bun check --no-script --all -p packages/omo-opencode/tsconfig.json && bun check --no-script --all -p packages/omo-native/tsconfig.json && bun check --no-script --all -p packages/senpi-desktop-protocol/tsconfig.json && bun check --no-script --all -p packages/senpi-desktop-engine/tsconfig.json && bun check --no-script --all -p packages/senpi-desktop-prelude/tsconfig.json && bun check --no-script --all -p packages/senpi-desktop-service/tsconfig.json && bun check --no-script --all -p packages/senpi-desktop-tool/tsconfig.json",+ "typecheck:script": "bun check --no-script --all -p script/tsconfig.json",test: "bun test --timeout 20000","changelog:section": "bun script/changelog-section.ts","test:codex": "bun run build:codex-install && bun run build:git-bash-mcp && bun run build:lsp-tools-mcp && bun run build:lsp-daemon && npm --prefix packages/lsp-tools-mcp test && npm --prefix packages/omo-codex/plugin ci && npm --prefix packages/omo-codex/plugin/components/ulw-loop test && bun run --cwd packages/omo-codex/plugin build && node scripts/check-third-party-notices.mjs --ship && bun test --timeout 20000 packages/omo-opencode/src/cli/cli-installer.platform.test.ts packages/omo-codex/src/install/codex-cache.test.ts packages/omo-codex/src/install/codex-cleanup.test.ts packages/omo-codex/src/install/codex-config-agent-cleanup.test.ts packages/omo-codex/src/install/codex-config-autonomous-features.test.ts packages/omo-codex/src/install/codex-config-reasoning.test.ts packages/omo-codex/src/install/codex-config-toml.test.ts packages/omo-codex/src/install/codex-project-local-cleanup.test.ts packages/omo-codex/src/install/install-codex-project-local-cleanup.test.ts packages/omo-codex/src/install/install-codex.test.ts packages/omo-codex/src/install/install-codex-packaged.test.ts packages/omo-codex/src/install/link-cached-plugin-agents.test.ts packages/omo-codex/src/**/*.test.ts packages/utils/src/jsonc-parser.test.ts packages/utils/src/frontmatter.test.ts packages/hashline-core/src/hash-computation.test.ts packages/hashline-core/src/smoke-untested-modules.test.ts packages/rules-engine/src/index.test.ts packages/rules-engine/src/security-boundary.test.ts packages/agents-md-core/src/injector.test.ts packages/omo-codex/plugin/components/lsp/test/package-smoke.test.ts && node --test packages/omo-codex/plugin/test/*.test.mjs packages/omo-codex/scripts/install-cache-copy.test.mjs packages/omo-codex/scripts/install-cli-args.test.mjs packages/omo-codex/scripts/install-delegated-command.test.mjs packages/omo-codex/scripts/install-config-autonomous-features.test.mjs packages/omo-codex/scripts/install-config-autonomous.test.mjs packages/omo-codex/scripts/install-config-reasoning.test.mjs packages/omo-codex/scripts/install-config.test.mjs packages/omo-codex/scripts/install-hook-targets.test.mjs packages/omo-codex/scripts/install-project-local-cleanup.test.mjs packages/omo-codex/scripts/install-lazycodex-version-stamp.test.mjs packages/omo-codex/scripts/install-local-entrypoint.test.mjs packages/omo-codex/scripts/install-local-git-bash-preflight.test.mjs packages/omo-codex/scripts/install-local.test.mjs packages/omo-codex/scripts/install-marketplace-cache.test.mjs packages/omo-codex/scripts/install-mcp-context7-runtime.test.mjs packages/omo-codex/scripts/install-mcp-runtime.test.mjs packages/omo-codex/scripts/install-packaged-local.test.mjs packages/omo-codex/scripts/install-generated-bundle.test.mjs packages/omo-codex/scripts/install-agent-links.test.mjs packages/omo-codex/scripts/install-bin-links.test.mjs","test:fast": "bun run script/test-fast.ts",- "test:senpi": "bun run build:senpi-plugin && tsgo --noEmit -p packages/omo-senpi/tsconfig.json && bun test --timeout 20000 packages/omo-senpi && bun test ./.agents/skills/senpi-qa/scripts/resolve-evidence-dir.test.mjs",+ "test:senpi": "bun run build:senpi-plugin && bun check --no-script --all -p packages/omo-senpi/tsconfig.json && bun test --timeout 20000 packages/omo-senpi && bun test ./.agents/skills/senpi-qa/scripts/resolve-evidence-dir.test.mjs","test:windows-codex": "bun run test:codex","build:git-bash-mcp": "bun run --cwd packages/git-bash-mcp build","build:ast-grep-mcp": "bun run --cwd packages/ast-grep-mcp build",@@ -2318,7 +2319,7 @@ var init_package = __esm(() => {},devDependencies: {"@clack/prompts": "^1.8.1",- "@code-yeongyu/senpi": "2026.10.27-1",+ "@code-yeongyu/senpi": "2026.10.30-1","@modelcontextprotocol/sdk": "^1.30.0","@oh-my-opencode/agents-md-core": "workspace:*","@oh-my-opencode/ast-grep-mcp": "workspace:*",@@ -2372,7 +2373,7 @@ var init_package = __esm(() => {"jsonc-parser": "^3.3.1",knip: "6.43.0","node-pty": "^1.1.0",- omowright: "github:code-yeongyu/omowright#f87ef4d63fe7b56fe117dbab246c8ad88dd8a780",+ omowright: "github:code-yeongyu/omowright#c06d20337ad942b09dea8757a45f6c848008a68d","oxc-parser": "0.148.0",oxlint: "1.89.0",picocolors: "^1.1.1",@@ -2382,18 +2383,18 @@ var init_package = __esm(() => {typescript: "^7.0.2"},optionalDependencies: {- "oh-my-opencode-darwin-arm64": "5.1.51",- "oh-my-opencode-darwin-x64": "5.1.51",- "oh-my-opencode-darwin-x64-baseline": "5.1.51",- "oh-my-opencode-linux-arm64": "5.1.51",- "oh-my-opencode-linux-arm64-musl": "5.1.51",- "oh-my-opencode-linux-x64": "5.1.51",- "oh-my-opencode-linux-x64-baseline": "5.1.51",- "oh-my-opencode-linux-x64-musl": "5.1.51",- "oh-my-opencode-linux-x64-musl-baseline": "5.1.51",- "oh-my-opencode-windows-arm64": "5.1.51",- "oh-my-opencode-windows-x64": "5.1.51",- "oh-my-opencode-windows-x64-baseline": "5.1.51"+ "oh-my-opencode-darwin-arm64": "5.1.54",+ "oh-my-opencode-darwin-x64": "5.1.54",+ "oh-my-opencode-darwin-x64-baseline": "5.1.54",+ "oh-my-opencode-linux-arm64": "5.1.54",+ "oh-my-opencode-linux-arm64-musl": "5.1.54",+ "oh-my-opencode-linux-x64": "5.1.54",+ "oh-my-opencode-linux-x64-baseline": "5.1.54",+ "oh-my-opencode-linux-x64-musl": "5.1.54",+ "oh-my-opencode-linux-x64-musl-baseline": "5.1.54",+ "oh-my-opencode-windows-arm64": "5.1.54",+ "oh-my-opencode-windows-x64": "5.1.54",+ "oh-my-opencode-windows-x64-baseline": "5.1.54"},overrides: {hono: "^4.13.8",@@ -8056,7 +8057,8 @@ var init_latest_models = __esm(() => {gptLunaFast: "gpt-6-luna-fast",glm: "glm-5.3",glmFlash: "glm-5.3-flash",- kimi: "kimi-k3",+ kimi: "kimi-k3.1-pro",+ kimiK3: "kimi-k3",geminiPro: "gemini-4-argon"};});@@ -9379,9 +9381,13 @@ var init_agent_model_requirements = __esm(() => {variant: "max"},{- providers: ["opencode-go", "kimi-for-coding", "moonshotai", "opencode", "bailian-coding-plan", "moonshotai-cn", "firmware", "ollama-cloud", "aihubmix"],+ providers: ["opencode-go", "kimi-for-coding", "moonshotai", "moonshotai-cn"],model: LATEST_MODEL_BY_FAMILY.kimi},+ {+ providers: ["opencode", "bailian-coding-plan", "firmware", "ollama-cloud", "aihubmix"],+ model: LATEST_MODEL_BY_FAMILY.kimiK3+ },{providers: ["openai", "chatgpt-subscription", "github-copilot", "opencode"],model: "gpt-5.6-sol",@@ -9476,10 +9482,11 @@ var init_agent_model_requirements = __esm(() => {variant: "max"},{- providers: ["opencode-go", "kimi-for-coding", "moonshotai", "opencode"],+ providers: ["opencode-go", "kimi-for-coding", "moonshotai"],model: LATEST_MODEL_BY_FAMILY.kimi,variant: "max"- }+ },+ { providers: ["opencode"], model: LATEST_MODEL_BY_FAMILY.kimiK3, variant: "max" }])},metis: {@@ -9500,10 +9507,11 @@ var init_agent_model_requirements = __esm(() => {variant: "max"},{- providers: ["opencode-go", "kimi-for-coding", "moonshotai", "opencode"],+ providers: ["opencode-go", "kimi-for-coding", "moonshotai"],model: LATEST_MODEL_BY_FAMILY.kimi,variant: "max"- }+ },+ { providers: ["opencode"], model: LATEST_MODEL_BY_FAMILY.kimiK3, variant: "max" }])},momus: {@@ -9586,10 +9594,11 @@ var init_category_model_requirements = __esm(() => {variant: "max"},{- providers: ["kimi-for-coding", "moonshotai", "opencode-go", "opencode"],+ providers: ["kimi-for-coding", "moonshotai", "opencode-go"],model: LATEST_MODEL_BY_FAMILY.kimi,variant: "max"- }+ },+ { providers: ["opencode"], model: LATEST_MODEL_BY_FAMILY.kimiK3, variant: "max" }])},ultrabrain: {@@ -9641,10 +9650,11 @@ var init_category_model_requirements = __esm(() => {variant: "max"},{- providers: ["kimi-for-coding", "moonshotai", "opencode-go", "opencode"],+ providers: ["kimi-for-coding", "moonshotai", "opencode-go"],model: LATEST_MODEL_BY_FAMILY.kimi,variant: "max"- }+ },+ { providers: ["opencode"], model: LATEST_MODEL_BY_FAMILY.kimiK3, variant: "max" }])},quick: {@@ -9707,10 +9717,11 @@ var init_category_model_requirements = __esm(() => {},{ providers: ["zai-coding-plan", "opencode-go"], model: LATEST_MODEL_BY_FAMILY.glm, variant: "max" },{- providers: ["kimi-for-coding", "moonshotai", "opencode-go", "opencode"],+ providers: ["kimi-for-coding", "moonshotai", "opencode-go"],model: LATEST_MODEL_BY_FAMILY.kimi,variant: "max"- }+ },+ { providers: ["opencode"], model: LATEST_MODEL_BY_FAMILY.kimiK3, variant: "max" }]},writing: {@@ -10274,7 +10285,7 @@ function transformModelForProviderDisplay(provider, model) {var CLAUDE_VERSION_DOT, GEMINI_31_PRO_PREVIEW, GEMINI_3_FLASH_PREVIEW;var init_provider_model_id_transform = __esm(() => {CLAUDE_VERSION_DOT = /claude-(\w+)-(\d+)-(\d+)/g;- GEMINI_31_PRO_PREVIEW = /gemini-3\.1-pro(?!-)/g;+ GEMINI_31_PRO_PREVIEW = /(?<!antigravity-)gemini-3\.1-pro(?!-)/g;GEMINI_3_FLASH_PREVIEW = /(?<!antigravity-)gemini-3-flash(?!-)/g;});@@ -10348,6 +10359,36 @@ var init_supplemental_entries = __esm(() => {output: 262144}},+ "kimi-k3.1-pro": {+ id: "kimi-k3.1-pro",+ family: "kimi",+ reasoning: true,+ temperature: true,+ toolCall: true,+ modalities: {+ input: ["text", "image", "video"],+ output: ["text"]+ },+ limit: {+ context: 1048576,+ output: 1048576+ }+ },+ "kimi-k3.1-pro-highspeed": {+ id: "kimi-k3.1-pro-highspeed",+ family: "kimi",+ reasoning: true,+ temperature: true,+ toolCall: true,+ modalities: {+ input: ["text", "image", "video"],+ output: ["text"]+ },+ limit: {+ context: 1048576,+ output: 1048576+ }+ },"kimi-k2.6": {id: "kimi-k2.6",family: "kimi",@@ -12432,6 +12473,33 @@ function createJsonFileCacheStore(options) {});}}+ function writeIfChanged(value) {+ ensureCacheDir();+ const cacheFile = getCacheFilePath();+ const serialized = options.serialize?.(value) ?? JSON.stringify(value, null, 2);+ try {+ const existing = existsSync10(cacheFile) ? readFileSync3(cacheFile, "utf-8") : undefined;+ const unchanged = existing !== undefined && (existing === serialized || options.comparable !== undefined && JSON.stringify(options.comparable(JSON.parse(existing))) === JSON.stringify(options.comparable(value)));+ if (unchanged) {+ memoryValue = value;+ writtenInCurrentProcess = true;+ log2(`[${options.logPrefix}] ${options.cacheLabel} unchanged; skipped write`, options.describe(value));+ return false;+ }+ } catch {}+ try {+ writeFileSync4(cacheFile, serialized);+ memoryValue = value;+ writtenInCurrentProcess = true;+ log2(`[${options.logPrefix}] ${options.cacheLabel} written`, options.describe(value));+ return true;+ } catch (error) {+ log2(`[${options.logPrefix}] Error writing ${toLogLabel(options.cacheLabel)}`, {+ error: String(error)+ });+ return false;+ }+ }function resetMemory() {memoryValue = undefined;writtenInCurrentProcess = false;@@ -12440,6 +12508,7 @@ function createJsonFileCacheStore(options) {read,has,write,+ writeIfChanged,resetMemory};}@@ -67504,7 +67573,8 @@ function createModelCapabilitiesCacheStore(getCacheDir = getOmoOpenCodeCacheDir)generatedAt: snapshot.generatedAt}),serialize: (snapshot) => `${JSON.stringify(snapshot, null, 2)}-`+`,+ comparable: ({ generatedAt: _generatedAt, ...catalog }) => catalog});function readModelCapabilitiesCache() {return snapshotCacheStore.read();@@ -67517,7 +67587,7 @@ function createModelCapabilitiesCacheStore(getCacheDir = getOmoOpenCodeCacheDir)}async function refreshModelCapabilitiesCache(args = {}) {const snapshot = await fetchModelCapabilitiesSnapshot(args);- writeModelCapabilitiesCache(snapshot);+ snapshotCacheStore.writeIfChanged(snapshot);return snapshot;}return {@@ -77232,8 +77302,8 @@ var init_memory = __esm(() => {enabled: boolean2().optional()}).strict();OmoMemoryProjectionSchema = object({- max_entries_per_directory: number2().int().min(0).default(40),- max_bytes: number2().int().min(0).default(24576)+ max_entries_per_directory: number2().int().min(0).default(0),+ max_bytes: number2().int().min(0).default(40960)}).strict();OmoMemoryProjectionLayerSchema = object({max_entries_per_directory: number2().int().min(0).optional(),@@ -77297,7 +77367,7 @@ var init_memory = __esm(() => {query_expansion: false}),project_scope: OmoMemoryProjectScopeSchema.default({ nudge: true, recall: true }),- projection: OmoMemoryProjectionSchema.default({ max_entries_per_directory: 40, max_bytes: 24576 }),+ projection: OmoMemoryProjectionSchema.default({ max_entries_per_directory: 0, max_bytes: 40960 }),compile_warn_tokens: number2().int().positive().default(30000),agents: record(string2(), OmoMemoryAgentOverridesSchema).default({})}).strict();@@ -77345,6 +77415,21 @@ var init_model_catalog = __esm(() => {OmoModelCatalogLayerSchema = record(string2(), OmoModelCatalogEntryLayerSchema);});+// packages/omo-config-core/src/schema/model-pad.ts+var OmoModelPadLabelsSchema, OmoModelPadSchema;+var init_model_pad = __esm(() => {+ init_zod();+ OmoModelPadLabelsSchema = object({+ daily: string2().optional(),+ geeky: string2().optional(),+ normal: string2().optional(),+ heavy: string2().optional()+ }).strict();+ OmoModelPadSchema = object({+ labels: OmoModelPadLabelsSchema.optional()+ }).strict();+});+// packages/omo-config-core/src/schema/model-profile.tsfunction isRecord8(value) {return typeof value === "object" && value !== null && !Array.isArray(value);@@ -77665,6 +77750,7 @@ var init_config = __esm(() => {init_git_master();init_memory();init_model_catalog();+ init_model_pad();init_model_profile();init_side_panel();init_task();@@ -77686,6 +77772,7 @@ var init_config = __esm(() => {models: OmoModelCatalogLayerSchema.optional(),model_profiles: OmoModelProfilesLayerSchema.optional(),model_profile: string2().optional(),+ model_pad: OmoModelPadSchema.optional(),memory: OmoMemorySettingsLayerSchema.optional(),telemetry: OmoTelemetrySettingsLayerSchema.optional(),side_panel: OmoSidePanelSettingsLayerSchema.optional(),@@ -77704,6 +77791,7 @@ var init_config = __esm(() => {models: OmoModelCatalogLayerSchema.optional(),model_profiles: OmoModelProfilesLayerSchema.optional(),model_profile: string2().optional(),+ model_pad: OmoModelPadSchema.optional(),memory: OmoMemorySettingsLayerSchema.optional(),telemetry: OmoTelemetrySettingsLayerSchema.optional(),side_panel: OmoSidePanelSettingsLayerSchema.optional(),@@ -77727,6 +77815,7 @@ var init_config = __esm(() => {models: OmoModelCatalogSchema.optional(),model_profiles: OmoModelProfilesSchema.optional(),model_profile: string2().optional(),+ model_pad: OmoModelPadSchema.optional(),memory: OmoMemorySettingsSchema.optional(),telemetry: OmoTelemetrySettingsSchema.optional(),side_panel: OmoSidePanelSettingsSchema.optional(),@@ -77753,6 +77842,7 @@ var init_config = __esm(() => {models: OmoModelCatalogLayerSchema.optional(),model_profiles: OmoModelProfilesLayerSchema.optional(),model_profile: string2().optional(),+ model_pad: OmoModelPadSchema.optional(),memory: OmoMemorySettingsLayerSchema.optional(),telemetry: OmoTelemetrySettingsLayerSchema.optional(),side_panel: OmoSidePanelSettingsLayerSchema.optional(),@@ -77898,6 +77988,7 @@ var init_schema = __esm(() => {init_legacy_harness_names();init_memory();init_model_catalog();+ init_model_pad();init_model_profile();init_model_ref();init_provenance();@@ -82918,6 +83009,37 @@ function getDefaultTelemetryOsProvider() {}var init_machine_id = () => {};+// packages/telemetry-core/src/terminal-program.ts+function isKnownTerminalProgram(value) {+ return KNOWN_TERMINAL_PROGRAMS.some((known) => known === value);+}+function toTelemetryTerminalProgram(termProgram) {+ if (termProgram === undefined || termProgram === "")+ return;+ return isKnownTerminalProgram(termProgram) ? termProgram : "other";+}+var KNOWN_TERMINAL_PROGRAMS;+var init_terminal_program = __esm(() => {+ KNOWN_TERMINAL_PROGRAMS = [+ "Apple_Terminal",+ "iTerm.app",+ "vscode",+ "cursor",+ "windsurf",+ "zed",+ "WezTerm",+ "ghostty",+ "tmux",+ "Hyper",+ "WarpTerminal",+ "kitty",+ "alacritty",+ "Tabby",+ "rio",+ "mintty"+ ];+});+// packages/telemetry-core/src/injected-client.tsfunction isTelemetryClientEnabled(input) {const env = input.env ?? process.env;@@ -83020,12 +83142,16 @@ function getSharedProperties(input) {total_memory_gb: Math.round(osProvider.totalmem() / 1024 / 1024 / 1024),locale: Intl.DateTimeFormat().resolvedOptions().locale,timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,- shell: process.env.SHELL,+ shell: getShellName(process.env.SHELL),ci: Boolean(process.env.CI),- terminal: process.env.TERM_PROGRAM,+ terminal: toTelemetryTerminalProgram(process.env.TERM_PROGRAM),...input.product.additionalProperties};}+function getShellName(shellPath) {+ const name = shellPath?.split(/[\\/]/).pop()?.replace(/\.exe$/i, "");+ return name ? name : undefined;+}function getSafeCpuInfo(osProvider, input) {try {const cpuInfo = osProvider.cpus();@@ -83050,6 +83176,7 @@ var NO_OP_CLIENT;var init_injected_client = __esm(() => {init_env();init_machine_id();+ init_terminal_program();NO_OP_CLIENT = {enabled: false,trackActive: () => {@@ -92629,7 +92756,7 @@ var package_default2;var init_package2 = __esm(() => {package_default2 = {name: "@oh-my-opencode/omo-codex",- version: "5.1.51",+ version: "5.1.54",type: "module",private: true,description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",@@ -93837,11 +93964,22 @@ init_commander();// packages/omo-opencode/src/cli/install.tsinit_package();+// packages/omo-opencode/src/cli/cli-installer.ts+import { createInterface as createInterface2 } from "node:readline/promises";++// packages/telemetry-core/src/install-disclosure.ts+var TELEMETRY_PRIVACY_POLICY_URL = "https://github.com/code-yeongyu/oh-my-openagent/blob/dev/docs/legal/privacy-policy.md";+var TELEMETRY_INSTALL_DISCLOSURE_LINES = [+ "OmO sends anonymous usage telemetry (no prompts, code, file paths, or account data) to improve the product.",+ "The data goes to PostHog in the United States.",+ "Turn it off with DO_NOT_TRACK=1 (or OMO_DISABLE_TELEMETRY=1).",+ `Details: ${TELEMETRY_PRIVACY_POLICY_URL}`+];+// packages/omo-opencode/src/cli/cli-installer.tsinit_shared();init_config_manager();var import_picocolors3 = __toESM(require_picocolors(), 1);-import { createInterface as createInterface2 } from "node:readline/promises";// packages/omo-opencode/src/cli/install-validators.tsvar import_picocolors = __toESM(require_picocolors(), 1);@@ -100002,6 +100140,7 @@ var REQUIRED_PLUGIN_ARTIFACTS = [join66("extensions", "omo-thread-client.js"),join66("extensions", "omo-telemetry-recovery.js"),join66("extensions", "omo-feedback.js"),+ join66("extensions", "omo-desktop-toolkit.js"),join66("extensions", "omo-claim-receipt.js"),join66("extensions", "assets.generated.json"),join66("extensions", "omo-member.js"),@@ -101280,8 +101419,8 @@ async function runCliInstaller(args, version) {}console.log();}- printInfo("Anonymous telemetry is enabled by default. Disable it with OMO_SEND_ANONYMOUS_TELEMETRY=0 or OMO_DISABLE_POSTHOG=1.");- printInfo("Docs: docs/legal/privacy-policy.md and docs/legal/terms-of-service.md");+ for (const line of TELEMETRY_INSTALL_DISCLOSURE_LINES)+ printInfo(line);console.log();printBox(`${import_picocolors3.default.bold("Pro Tip:")} Include ${import_picocolors3.default.cyan("ultrawork")} (or ${import_picocolors3.default.cyan("ulw")}) in your prompt.` + `All features work like magic-parallel agents, background tasks,@@ -102577,7 +102716,7 @@ async function promptInstallConfig(detected, platform, codexAutonomousOverride)message: "Do you have a Kimi For Coding subscription?",options: [{ value: "no", label: "No", hint: "Will use other configured providers" },- { value: "yes", label: "Yes", hint: "Kimi K3 for Sisyphus/Prometheus fallback" }+ { value: "yes", label: "Yes", hint: "Kimi K3.1 Pro for Sisyphus/Prometheus fallback" }],initialValue: initial.kimiForCoding});@@ -102836,8 +102975,8 @@ async function runTuiInstaller(args, version) {if (config.hasOpenCode) {log4.message(`Run ${import_picocolors4.default.cyan("opencode")} to start!`);}- log4.info("Anonymous telemetry is enabled by default. Disable it with OMO_SEND_ANONYMOUS_TELEMETRY=0 or OMO_DISABLE_POSTHOG=1.");- log4.info("Docs: docs/legal/privacy-policy.md and docs/legal/terms-of-service.md");+ log4.info(TELEMETRY_INSTALL_DISCLOSURE_LINES.join(`+`));note(`Include ${import_picocolors4.default.cyan("ultrawork")} (or ${import_picocolors4.default.cyan("ulw")}) in your prompt.` + `All features work like magic-parallel agents, background tasks,` + `deep exploration, and relentless execution until completion.`, "The Magic Word");@@ -109374,6 +109513,8 @@ var package_default3 = {},dependencies: {"@clack/prompts": "^1.8.1",+ "@code-yeongyu/senpi": "2026.10.30-1",+ "@earendil-works/pi-ai": "npm:@code-yeongyu/[email protected]","@modelcontextprotocol/sdk": "^1.30.0","@oh-my-opencode/agents-md-core": "workspace:*","@oh-my-opencode/boulder-state": "workspace:*",@@ -110682,6 +110823,8 @@ function isOAuthTokenData(value) {if (typeof value !== "object" || value === null || Array.isArray(value))return false;const record = value;+ if (record["issuer"] !== undefined && typeof record["issuer"] !== "string")+ return false;if (typeof record["accessToken"] !== "string")return false;const refreshToken = record["refreshToken"];@@ -110696,6 +110839,8 @@ function isOAuthTokenData(value) {if (typeof clientInfo !== "object" || clientInfo === null || Array.isArray(clientInfo))return false;const clientRecord = clientInfo;+ if (clientRecord["issuer"] !== undefined && typeof clientRecord["issuer"] !== "string")+ return false;if (typeof clientRecord["clientId"] !== "string")return false;const clientSecret = clientRecord["clientSecret"];@@ -110764,7 +110909,9 @@ function deleteToken(serverHost, resource) {return deleteLegacyToken(serverHost, resource);try {unlinkSync9(filePath);- return deleteTokenIndexEntry(getMcpOauthStorageDir(), getMcpOauthServerHash(serverHost, resource));+ const indexDeleted = deleteTokenIndexEntry(getMcpOauthStorageDir(), getMcpOauthServerHash(serverHost, resource));+ const legacyDeleted = deleteLegacyToken(serverHost, resource);+ return indexDeleted && legacyDeleted;} catch (deleteError) {if (!(deleteError instanceof Error))throw deleteError;@@ -110874,19 +111021,26 @@ async function fetchMetadata(url) {}return { ok: true, json };}-function parseMetadataFields(json, resource) {+function parseMetadataFields(json, resource, expectedIssuer) {+ const issuer = readStringField(json, "issuer");+ parseHttpsUrl(issuer, "issuer");+ if (issuer !== expectedIssuer) {+ throw new Error("OAuth metadata issuer mismatch");+ }const authorizationEndpoint = parseHttpsUrl(readStringField(json, "authorization_endpoint"), "authorization_endpoint").toString();const tokenEndpoint = parseHttpsUrl(readStringField(json, "token_endpoint"), "token_endpoint").toString();const registrationEndpointValue = json.registration_endpoint;const registrationEndpoint = typeof registrationEndpointValue === "string" && registrationEndpointValue.length > 0 ? parseHttpsUrl(registrationEndpointValue, "registration_endpoint").toString() : undefined;return {+ issuer,+ ...json.authorization_response_iss_parameter_supported === true ? { authorizationResponseIssParameterSupported: true } : {},authorizationEndpoint,tokenEndpoint,registrationEndpoint,resource};}-async function fetchAuthorizationServerMetadata(issuer, resource) {+async function fetchAuthorizationServerMetadata(issuer, resource, allowOriginFallback = false) {const issuerUrl = parseHttpsUrl(issuer, "Authorization server URL");const issuerPath = issuerUrl.pathname.replace(/\/+$/, "");const metadataUrl = new URL(`/.well-known/oauth-authorization-server${issuerPath}`, issuerUrl).toString();@@ -110896,7 +111050,7 @@ async function fetchAuthorizationServerMetadata(issuer, resource) {const rootMetadataUrl = new URL("/.well-known/oauth-authorization-server", issuerUrl).toString();const rootMetadata = await fetchMetadata(rootMetadataUrl);if (rootMetadata.ok) {- return parseMetadataFields(rootMetadata.json, resource);+ return parseMetadataFields(rootMetadata.json, resource, allowOriginFallback ? issuerUrl.origin : issuer);}}if (metadata.status === 404) {@@ -110904,7 +111058,7 @@ async function fetchAuthorizationServerMetadata(issuer, resource) {}throw new Error(`OAuth authorization server metadata fetch failed (${metadata.status})`);}- return parseMetadataFields(metadata.json, resource);+ return parseMetadataFields(metadata.json, resource, issuer);}function parseAuthorizationServers(metadata) {const servers = metadata.authorization_servers;@@ -110912,11 +111066,11 @@ function parseAuthorizationServers(metadata) {return [];return servers.filter((server) => typeof server === "string" && server.length > 0);}-async function discoverOAuthServerMetadata(resource) {+async function discoverOAuthServerMetadata(resource, forceRefresh = false) {const resourceUrl = parseHttpsUrl(resource, "Resource server URL");const resourceKey = resourceUrl.toString();const cached = discoveryCache.get(resourceKey);- if (cached)+ if (cached && !forceRefresh)return cached;const pending = pendingDiscovery.get(resourceKey);if (pending)@@ -110934,7 +111088,7 @@ async function discoverOAuthServerMetadata(resource) {if (prmResponse.status !== 404) {throw new Error(`OAuth protected resource metadata fetch failed (${prmResponse.status})`);}- return fetchAuthorizationServerMetadata(resourceKey, resource);+ return fetchAuthorizationServerMetadata(resource.replace(/\/+$/, ""), resource, true);})();pendingDiscovery.set(resourceKey, discoveryPromise);try {@@ -110958,6 +111112,10 @@ async function getOrRegisterClient(options) {}const fetchImpl = options.fetch ?? globalThis.fetch;const request = {+ application_type: options.redirectUris.some((uri) => {+ const url = new URL(uri);+ return (url.protocol === "http:" || url.protocol === "https:") && !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);+ }) ? "web" : "native",redirect_uris: options.redirectUris,client_name: options.clientName,grant_types: ["authorization_code", "refresh_token"],@@ -111034,12 +111192,20 @@ function buildAuthorizationUrl(authorizationEndpoint, options) {return url.toString();}var CALLBACK_TIMEOUT_MS = 5 * 60 * 1000;-function startCallbackServer(port) {+function startCallbackServer(port, validation) {return new Promise((resolve, reject) => {let timeoutId;const server = createServer2((request, response) => {clearTimeout(timeoutId);const requestUrl = new URL(request.url ?? "/", `http://localhost:${port}`);+ const issuer = requestUrl.searchParams.get("iss");+ if (validation && (issuer !== null && issuer !== validation.issuer || issuer === null && validation.authorizationResponseIssParameterSupported)) {+ response.writeHead(400, { "content-type": "text/html" });+ response.end("<html><body><h1>Authorization failed</h1></body></html>");+ server.close();+ reject(new Error("OAuth authorization response issuer mismatch or missing issuer"));+ return;+ }const code = requestUrl.searchParams.get("code");const state = requestUrl.searchParams.get("state");const error = requestUrl.searchParams.get("error");@@ -111109,7 +111275,7 @@ async function runAuthorizationCodeRedirect(options) {scopes: options.scopes,resource: options.resource});- const callbackPromise = startCallbackServer(options.callbackPort);+ const callbackPromise = startCallbackServer(options.callbackPort, options);openBrowser(authorizationUrl);const result = await callbackPromise;if (result.state !== state) {@@ -111144,10 +111310,12 @@ function buildOAuthTokenData(tokenData, clientInfo, fallbackRefreshToken) {throw new Error("Token response missing access_token");}return {+ ...clientInfo.issuer ? { issuer: clientInfo.issuer } : {},accessToken,refreshToken: typeof tokenData["refresh_token"] === "string" ? tokenData["refresh_token"] : fallbackRefreshToken,expiresAt: typeof tokenData["expires_in"] === "number" ? Math.floor(Date.now() / 1000) + tokenData["expires_in"] : undefined,clientInfo: {+ ...clientInfo.issuer ? { issuer: clientInfo.issuer } : {},clientId: clientInfo.clientId,...clientInfo.clientSecret ? { clientSecret: clientInfo.clientSecret } : {}}@@ -111161,6 +111329,7 @@ class McpOAuthProvider {storedCodeVerifier = null;storedClientInfo = null;callbackPort = null;+ issuer;constructor(options) {this.serverUrl = options.serverUrl;this.configClientId = options.clientId;@@ -111170,7 +111339,32 @@ class McpOAuthProvider {return loadToken(this.serverUrl, this.serverUrl);}saveTokens(tokenData) {- return saveToken(this.serverUrl, this.serverUrl, tokenData);+ const issuer = tokenData.issuer ?? this.issuer;+ return saveToken(this.serverUrl, this.serverUrl, issuer ? {+ ...tokenData,+ issuer,+ ...tokenData.clientInfo ? { clientInfo: { ...tokenData.clientInfo, issuer: tokenData.clientInfo.issuer ?? issuer } } : {}+ } : tokenData);+ }+ bindIssuer(issuer) {+ const token = this.tokens();+ const stamps = [token?.issuer, token?.clientInfo?.issuer, this.storedClientInfo?.issuer, this.issuer];+ const changed = stamps.some((stamp) => stamp !== undefined && stamp !== issuer);+ if (changed) {+ this.storedClientInfo = null;+ this.storedCodeVerifier = null;+ if (!deleteToken(this.serverUrl, this.serverUrl)) {+ throw new Error("Unable to discard credentials for the previous OAuth issuer");+ }+ }+ this.issuer = issuer;+ if (!changed && token && !this.saveTokens(token)) {+ throw new Error("Unable to stamp stored OAuth credentials with their issuer");+ }+ const clientInfo = this.clientInformation();+ if (clientInfo)+ this.storedClientInfo = { ...clientInfo, issuer };+ return changed;}clientInformation() {if (this.storedClientInfo)@@ -111200,6 +111394,8 @@ class McpOAuthProvider {this.callbackPort = await findAvailablePort2();}const result = await runAuthorizationCodeRedirect({+ issuer: metadata.issuer,+ authorizationResponseIssParameterSupported: metadata.authorizationResponseIssParameterSupported,authorizationEndpoint: metadata.authorizationEndpoint,callbackPort: this.callbackPort,clientId: clientInfo.clientId,@@ -111211,16 +111407,19 @@ class McpOAuthProvider {return { code: result.code };}async login() {- const metadata = await discoverOAuthServerMetadata(this.serverUrl);+ const metadata = await discoverOAuthServerMetadata(this.serverUrl, true);+ this.bindIssuer(metadata.issuer);+ if (this.callbackPort === null)+ this.callbackPort = await findAvailablePort2();const clientRegistrationStorage = {getClientRegistration: () => this.storedClientInfo,setClientRegistration: (_serverIdentifier, credentials) => {- this.storedClientInfo = credentials;+ this.storedClientInfo = { ...credentials, issuer: metadata.issuer };}};const clientInfo = await getOrRegisterClient({...metadata.registrationEndpoint ? { registrationEndpoint: metadata.registrationEndpoint } : {},- serverIdentifier: this.serverUrl,+ serverIdentifier: metadata.issuer,clientName: PLUGIN_NAME4,redirectUris: [this.redirectUrl()],tokenEndpointAuthMethod: "none",@@ -111230,7 +111429,7 @@ class McpOAuthProvider {if (!clientInfo) {throw new Error("Failed to obtain client credentials. Provide a clientId or ensure the server supports DCR.");}- this.storedClientInfo = clientInfo;+ this.storedClientInfo = { ...clientInfo, issuer: metadata.issuer };const { code } = await this.redirectToAuthorization(metadata);const verifier = this.codeVerifier();if (!verifier) {@@ -111249,12 +111448,14 @@ class McpOAuthProvider {}).toString()});const tokenData = await parseTokenResponse(tokenResponse);- const oauthTokenData = buildOAuthTokenData(tokenData, clientInfo);+ const oauthTokenData = buildOAuthTokenData(tokenData, { ...clientInfo, issuer: metadata.issuer });this.saveTokens(oauthTokenData);return oauthTokenData;}async refresh(refreshToken) {- const metadata = await discoverOAuthServerMetadata(this.serverUrl);+ const metadata = await discoverOAuthServerMetadata(this.serverUrl, true);+ if (this.bindIssuer(metadata.issuer))+ return this.login();const clientInfo = this.clientInformation();const clientId = clientInfo?.clientId ?? this.configClientId;if (!clientId) {@@ -111274,6 +111475,7 @@ class McpOAuthProvider {const tokenData = await parseTokenResponse(tokenResponse);const oauthTokenData = buildOAuthTokenData(tokenData, {clientId,+ issuer: metadata.issuer,...clientInfo?.clientSecret ? { clientSecret: clientInfo.clientSecret } : {}}, refreshToken);this.saveTokens(oauthTokenData);@@ -112121,6 +112323,17 @@ import { hostname } from "node:os";// packages/omo-opencode/src/cli/service-auth/protocol.tsinit_zod();+// packages/omo-opencode/src/cli/service-auth/credential-owner.ts+init_zod();+var identity = string2().regex(/^[A-Za-z0-9_-]{1,128}$/);+var credentialOwnerSchema = object({+ accountId: identity,+ deviceId: identity,+ familyId: identity,+ generation: number2().int().positive().safe(),+ ownerHandle: string2().regex(/^[\x21-\x7e]{1,4096}$/)+});+// packages/omo-opencode/src/cli/service-auth/terminal-text.tsimport { stripVTControlCharacters as stripVTControlCharacters4 } from "node:util";function terminalText(value) {@@ -112139,9 +112352,19 @@ class SignInError extends Error {class RequestFailure extends SignInError {notSent;- constructor(notSent) {+ responseStatus;+ constructor(notSent, responseStatus) {super("Unable to complete the service request. Check the connection and retry.", true);this.notSent = notSent;+ this.responseStatus = responseStatus;+ }+}++class InvalidApiResponse extends SignInError {+ status;+ constructor(status) {+ super("The service returned an invalid error response.");+ this.status = status;}}var platformSchema = _enum(["macos", "linux", "windows"]);@@ -112154,12 +112377,18 @@ var tokenSchema = object({});var grantSchema = tokenSchema.extend({device: object({ id: nonempty, name: nonempty }),- offlineGrant: nonempty.optional()+ offlineGrant: nonempty.optional(),+ owner: credentialOwnerSchema.optional(),+ writerFloor: union([literal(1), literal(2)]).optional(),+ freshAuthorizationProof: nonempty.optional()});var credentialSchema = grantSchema.extend({signingPrivateKey: nonempty,sealingPrivateKey: nonempty,- refreshState: literal("uncertain").optional()+ refreshState: literal("uncertain").optional(),+ credentialGeneration: nonempty.optional(),+ accountId: nonempty.optional(),+ refreshAttempt: unknown().optional()});var deviceCodeSchema = object({deviceCode: string2().regex(/^dc\.[A-Za-z0-9_-]{43}$/),@@ -112187,6 +112416,9 @@ var limitSchema = object({var deviceListSchema = object({devices: array(object({ id: nonempty, name: nonempty, revokedAt: timestamp.nullable() }))});+var currentDeviceListSchema = object({+ devices: array(object({ id: nonempty, current: boolean2(), revokedAt: timestamp.nullable() }))+});var REFUSAL_CODES = ["unauthorized","account_deleted",@@ -112203,7 +112435,11 @@ var REFUSAL_CODES = ["unavailable","forbidden","invalid_request",- "not_found"+ "not_found",+ "client_upgrade_required",+ "writer_floor_mismatch",+ "service_upgrade_required",+ "refresh_recovery_expired"];var isKnownRefusal = (code) => REFUSAL_CODES.includes(code);function refusalGuidance(code, status) {@@ -112230,6 +112466,10 @@ function refusalGuidance(code, status) {case "access_denied":case "authorization_pending":return "account_refused";+ case "client_upgrade_required":+ case "writer_floor_mismatch":+ case "service_upgrade_required":+ case "refresh_recovery_expired":case "unknown":if (status === 401)return "sign_in_again";@@ -112340,13 +112580,13 @@ async function requestApi(api, path, init, signal) {try {body = await response.json();} catch {- throw new RequestFailure(false);+ throw new RequestFailure(false, response.status);}if (response.ok)return body;const envelope = envelopeSchema.safeParse(body);if (!envelope.success)- throw new SignInError("The service returned an invalid error response.");+ throw new InvalidApiResponse(response.status);const error = envelope.data.error;const detail = limitSchema.safeParse(error.detail);throw new ApiRefusal(error.code, response.status, error.code === "entitlement_required" && detail.success ? detail.data : undefined, response.headers.get("retry-after"));@@ -112450,7 +112690,7 @@ async function loginDevice(session, options) {}// packages/omo-opencode/src/cli/service-auth/keystore.ts-import { createHash as createHash10 } from "node:crypto";+import { createHash as createHash12, randomUUID as randomUUID7 } from "node:crypto";import { basename as basename15 } from "node:path";// packages/omo-opencode/src/cli/service-auth/secret-service-lock.ts@@ -112494,289 +112734,490 @@ var probeSecretServiceLock = () => new Promise((resolve) => {});});-// packages/omo-opencode/src/cli/service-auth/keystore.ts-class CredentialStoreError extends SignInError {-}+// packages/omo-opencode/src/cli/service-auth/credential-lock.ts+import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";+import { createHash as createHash11 } from "node:crypto";+import { mkdir as mkdir11 } from "node:fs/promises";+import { homedir as homedir31 } from "node:os";+import { join as join106 } from "node:path";-class KeychainLockedError extends CredentialStoreError {+// packages/team-core/src/team-state-store/lock-publish.ts+import { access as access4, open as open3, unlink as unlink3 } from "node:fs/promises";+import { dirname as dirname42 } from "node:path";++// packages/team-core/src/team-state-store/lock-record.ts+import { randomUUID as randomUUID6 } from "node:crypto";+import { readFile as readFile34, stat as stat9 } from "node:fs/promises";++// packages/memory-core/src/locks/process-identity.ts+import { execFile as execFile7 } from "node:child_process";++// packages/memory-core/src/fs/resilient.ts+import * as fsSync from "node:fs";+import * as fsp from "node:fs/promises";++// packages/memory-core/src/fs/retry.ts+var EINTR_RETRY_CAP = 128;+function fsErrorCode(error) {+ if (!(error instanceof Error) || !("code" in error))+ return;+ return typeof error.code === "string" ? error.code : undefined;}-class InvalidCredentialState extends SignInError {+async function retryOnEintr(operation) {+ for (let attempt = 0;; attempt += 1) {+ try {+ return await operation();+ } catch (error) {+ if (fsErrorCode(error) !== "EINTR" || attempt >= EINTR_RETRY_CAP)+ throw error;+ }+ }+}+function retryOnEintrSync(operation) {+ for (let attempt = 0;; attempt += 1) {+ try {+ return operation();+ } catch (error) {+ if (fsErrorCode(error) !== "EINTR" || attempt >= EINTR_RETRY_CAP)+ throw error;+ }+ }}-class KeychainApprovalPendingError extends CredentialStoreError {+// packages/memory-core/src/fs/rename-contention.ts+var CONTENTION_CODES = new Set(["EPERM", "EBUSY", "EACCES"]);++// packages/memory-core/src/fs/resilient.ts+function isFunction2(value) {+ return typeof value === "function";}-var SESSION_READ_WAIT = { kind: "bounded", deadlineMs: 5000 };-var INTERACTIVE_READ_WAIT = {- kind: "interactive",- noticeAfterMs: 2000,- notice: (message) => process.stderr.write(`${message}-`)-};-var processReads = new WeakMap;-var LOCKED = /-25308|errSecInteractionNotAllowed|interaction is not allowed|locked collection/i;-var UNLOCKED_REUSE_MS = 30000;-var fallbackNoticed = false;-var stderrNoticeOncePerProcess = (message) => {- if (fallbackNoticed)+function withAsyncRetry(operation) {+ return (...args) => retryOnEintr(async () => operation(...args));+}+function withSyncRetry(operation) {+ return (...args) => retryOnEintrSync(() => operation(...args));+}+function resilientNamespace(namespace, kind) {+ const wrapFunction = kind === "async" ? withAsyncRetry : withSyncRetry;+ const cache = new Map;+ return new Proxy(namespace, {+ get(target, property) {+ if (cache.has(property))+ return cache.get(property);+ const value = Reflect.get(target, property);+ if (!isFunction2(value))+ return value;+ const wrapped = wrapFunction(value);+ const native = Reflect.get(value, "native");+ if (isFunction2(native))+ Object.assign(wrapped, { native: wrapFunction(native) });+ cache.set(property, wrapped);+ return wrapped;+ }+ });+}+var IDEMPOTENT_HANDLE_METHODS = new Set(["stat", "sync", "datasync", "chmod", "chown", "utimes", "truncate"]);+var promises = resilientNamespace(fsp, "async");+var sync = resilientNamespace(fsSync, "sync");+var {+ access: access3,+ chmod: chmod2,+ copyFile: copyFile4,+ cp: cp5,+ link,+ lstat: lstat18,+ mkdir: mkdir10,+ mkdtemp: mkdtemp2,+ readFile: readFile33,+ readdir: readdir17,+ readlink: readlink7,+ realpath: realpath2,+ rm: rm16,+ rmdir: rmdir2,+ stat: stat8,+ statfs,+ unlink: unlink2+} = promises;+var {+ accessSync: accessSync5,+ chmodSync: chmodSync7,+ fsyncSync: fsyncSync3,+ linkSync,+ lstatSync: lstatSync5,+ mkdirSync: mkdirSync19,+ readFileSync: readFileSync44,+ readdirSync: readdirSync14,+ realpathSync: realpathSync13,+ statSync: statSync8,+ unlinkSync: unlinkSync10,+ writeFileSync: writeFileSync17,+ writeSync+} = sync;++// packages/memory-core/src/locks/process-start-time.ts+var PROC_PIDTBSDINFO = 3;+var PROC_BSDINFO_SIZE = 136;+var START_TVSEC_OFFSET = 120;+var procPidInfoLookup = null;+async function openProcPidInfo() {+ if (process.platform !== "darwin")+ return null;+ try {+ const { dlopen, FFIType } = await import("bun:ffi");+ const library = dlopen("/usr/lib/libSystem.B.dylib", {+ proc_pidinfo: {+ args: [FFIType.i32, FFIType.i32, FFIType.u64, FFIType.ptr, FFIType.i32],+ returns: FFIType.i32+ }+ });+ return (pid, flavor, arg, buffer, size) => Number(library.symbols.proc_pidinfo(pid, flavor, arg, buffer, size));+ } catch {+ return null;+ }+}+function loadProcPidInfo() {+ procPidInfoLookup ??= openProcPidInfo();+ return procPidInfoLookup;+}+async function readDarwinProcessStartSeconds(pid) {+ if (process.platform !== "darwin")+ return null;+ if (!Number.isSafeInteger(pid) || pid <= 0)+ return null;+ const procPidInfo = await loadProcPidInfo();+ if (procPidInfo === null)+ return null;+ const buffer = new Uint8Array(PROC_BSDINFO_SIZE);+ let written = 0;+ try {+ written = procPidInfo(pid, PROC_PIDTBSDINFO, 0n, buffer, PROC_BSDINFO_SIZE);+ } catch {+ return null;+ }+ if (written !== PROC_BSDINFO_SIZE)+ return null;+ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);+ const startSeconds = Number(view.getBigUint64(START_TVSEC_OFFSET, true));+ return startSeconds > 0 ? startSeconds : null;+}+var PROCESS_QUERY_LIMITED_INFORMATION = 4096;+var kernel32Lookup = null;+async function openKernel32() {+ if (process.platform !== "win32")+ return null;+ try {+ const { dlopen, FFIType } = await import("bun:ffi");+ const library = dlopen("kernel32.dll", {+ OpenProcess: { args: [FFIType.u32, FFIType.i32, FFIType.u32], returns: FFIType.ptr },+ GetProcessTimes: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 },+ CloseHandle: { args: [FFIType.ptr], returns: FFIType.i32 }+ });+ return library.symbols;+ } catch {+ return null;+ }+}+async function readWin32ProcessCreationFiletime(pid) {+ if (process.platform !== "win32")+ return null;+ if (!Number.isSafeInteger(pid) || pid <= 0)+ return null;+ kernel32Lookup ??= openKernel32();+ const kernel32 = await kernel32Lookup;+ if (kernel32 === null)+ return null;+ const handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);+ if (handle === null || handle === 0 || handle === 0n)+ return null;+ try {+ const creation = new BigUint64Array(1);+ const ok = kernel32.GetProcessTimes(handle, creation, new BigUint64Array(1), new BigUint64Array(1), new BigUint64Array(1));+ const filetime = creation[0] ?? 0n;+ return ok === 0 || filetime === 0n ? null : filetime;+ } finally {+ kernel32.CloseHandle(handle);+ }+}++// packages/memory-core/src/locks/process-identity.ts+function errorCode(error) {+ if (!(error instanceof Error) || !("code" in error))return;- fallbackNoticed = true;- process.stderr.write(`${message}-`);-};-var isLocked = (error) => error instanceof Error && (LOCKED.test(error.message) || LOCKED.test(String(error.code ?? "")));-function credentialId(api) {- return createHash10("sha256").update(serviceOrigin(api)).digest("hex");+ return typeof error.code === "string" ? error.code : undefined;}-function createCredentialStore(api, options = {}) {- return createSealedStore(api, "omo-cli", credentialSchema, options.secrets, options.platform, options.lockProbe, options.notice, options.wait);+async function execFileText(command, args) {+ return await new Promise((resolve) => {+ execFile7(command, args, { encoding: "utf8", timeout: 2000, windowsHide: true }, (error, stdout) => {+ if (error !== null) {+ resolve(null);+ return;+ }+ const value = stdout.trim();+ resolve(value.length > 0 ? value : null);+ });+ });}-function createSealedStore(api, namespace, schema, secrets = typeof Bun === "undefined" ? null : Bun.secrets, platform = process.platform, lockProbe = probeSecretServiceLock, notice = stderrNoticeOncePerProcess, wait = SESSION_READ_WAIT) {- if (!secrets)- throw new SignInError("OmO sign-in needs Bun 1.4 or newer with OS credential storage. No file fallback is available.");- const platformName = platform === "darwin" ? "macOS Keychain" : platform === "linux" ? "Linux Secret Service (libsecret and an unlocked keyring)" : platform === "win32" ? "Windows Credential Manager" : null;- if (platformName === null)- throw new SignInError("This platform has no supported OS credential store.");- const key = { service: namespace, name: credentialId(api) };- const slot = `${key.service}-${key.name}`;- const readsOf = (api) => {- const known = processReads.get(api);- if (known !== undefined)- return known;- const created = new Map;- processReads.set(api, created);- return created;- };- const forget = (api) => {- readsOf(api).delete(slot);- };- const sharedRead = (api) => {- const reads = readsOf(api);- const pending = reads.get(slot);- if (pending !== undefined)- return pending;- const read = Promise.resolve().then(() => api.get(key));- const done = () => {- if (reads.get(slot) === read)- reads.delete(slot);- };- read.then(done, done);- reads.set(slot, read);- return read;+async function readLinuxStartIdentity(pid) {+ try {+ const stat = await readFile33(`/proc/${pid}/stat`, "utf8");+ const commandEnd = stat.lastIndexOf(")");+ if (commandEnd < 0)+ return null;+ const fieldsAfterCommand = stat.slice(commandEnd + 2).trim().split(/\s+/);+ const startTicks = fieldsAfterCommand[19];+ return startTicks === undefined ? null : `linux-proc-start-ticks:${startTicks}`;+ } catch {+ return null;+ }+}+async function readWin32StartIdentity(pid) {+ if (getPidLiveness(pid) === "dead")+ return null;+ const creationFiletime = await readWin32ProcessCreationFiletime(pid);+ if (creationFiletime !== null)+ return `win32-creation-filetime:${creationFiletime}`;+ const value = await execFileText("powershell.exe", [+ "-NoProfile",+ "-Command",+ `(Get-Process -Id ${pid} -ErrorAction SilentlyContinue).StartTime.ToUniversalTime().ToString('o')`+ ]);+ return value === null ? null : `win32-creation-date:${value}`;+}+function createProcessStartIdentityReader(read, ownPid) {+ let ownIdentity;+ return (pid) => {+ if (pid !== ownPid)+ return read(pid);+ ownIdentity ??= read(pid).then((identity) => {+ if (identity === null)+ ownIdentity = undefined;+ return identity;+ }, (error) => {+ ownIdentity = undefined;+ throw error;+ });+ return ownIdentity;};- const waiting = platform === "darwin" ? `macOS Keychain is waiting for your approval: answer the "${basename15(process.execPath)} wants to access key ${namespace}" dialog ("Always Allow" stops it asking again)` : `${platformName} has not answered; it may be waiting for your approval or an unlock in a system dialog`;- const answered = async (api) => {- const read = sharedRead(api);- let timer;- try {- if (wait.kind === "interactive") {- timer = setTimeout(() => wait.notice(`omo: ${waiting}.`), wait.noticeAfterMs);- return await read;- }- const expired = new Promise((_, reject) => {- timer = setTimeout(() => reject(new KeychainApprovalPendingError(`${waiting}, then try again. Credentials are never saved to a file.`)), wait.deadlineMs);- });- return await Promise.race([read, expired]);- } finally {- clearTimeout(timer);- }+}+var getProcessStartIdentity = createProcessStartIdentityReader(readProcessStartIdentity, process.pid);+async function readProcessStartIdentity(pid) {+ if (process.platform === "linux")+ return await readLinuxStartIdentity(pid);+ if (process.platform === "darwin" || process.platform === "freebsd") {+ if (getPidLiveness(pid) === "dead")+ return null;+ const startSeconds = await readDarwinProcessStartSeconds(pid);+ if (startSeconds !== null)+ return `proc-start-epoch:${startSeconds}`;+ const value = await execFileText("/bin/ps", ["-o", "lstart=", "-p", String(pid)]);+ return value === null ? null : `ps-lstart:${value.replace(/\s+/g, " ")}`;+ }+ if (process.platform === "win32")+ return await readWin32StartIdentity(pid);+ return null;+}+function identityScheme(identity) {+ const separator = identity.indexOf(":");+ return separator <= 0 ? null : identity.slice(0, separator);+}+function startIdentitiesConflict(recorded, actual) {+ const recordedScheme = identityScheme(recorded);+ if (recordedScheme === null || recordedScheme !== identityScheme(actual))+ return false;+ return recorded !== actual;+}+function getPidLiveness(pid) {+ try {+ process.kill(pid, 0);+ return "alive";+ } catch (error) {+ const code = errorCode(error);+ if (code === "ESRCH")+ return "dead";+ if (code === "EPERM")+ return "alive";+ return "unknown";+ }+}++// packages/team-core/src/team-state-store/lock-worker-lifetime.ts+init_zod();+import { randomUUID as randomUUID5 } from "node:crypto";+import { BroadcastChannel, parentPort, threadId } from "node:worker_threads";+var Registration = object({+ kind: literal("omo-team-lock-register-v1"),+ incarnation: string2(),+ challenge: string2()+});+var Message = discriminatedUnion("kind", [+ object({ kind: literal("query"), id: string2(), incarnation: string2(), record: string2() }),+ object({ kind: literal("answer"), id: string2(), released: boolean2() }),+ object({ kind: literal("hello"), threadId: number2() }),+ object({ kind: literal("register"), threadId: number2(), challenge: string2() })+]);+function createState() {+ const channel = new BroadcastChannel(`omo-team-lock-lifetime-v1-${process.pid}`);+ channel.unref();+ const state = {+ incarnation: randomUUID5(),+ records: new Map,+ exited: new Set,+ observed: new WeakSet,+ observing: new Map,+ pending: new Map,+ channel,+ installed: false,+ registered: parentPort === null,+ registration: undefined,+ onRegistered: undefined};- const unavailable = (error) => isLocked(error) ? new KeychainLockedError(`${platformName} is locked. Unlock it, then try again. Credentials are never saved to a file.`) : new CredentialStoreError(`Cannot access ${platformName}. Unlock or enable the OS credential store and try again. Credentials are never saved to a file.`);- let unlockedUntil = 0;- let noticed = false;- const assertUsable = async () => {- if (platform !== "linux" || Date.now() < unlockedUntil)- return;- const lock = await lockProbe();- if (lock === "locked")- throw new KeychainLockedError(`${platformName} is locked. Unlock it, then try again. Credentials are never saved to a file.`);- if (lock === "unlocked") {- unlockedUntil = Date.now() + UNLOCKED_REUSE_MS;+ channel.onmessage = (event) => {+ const parsed = Message.safeParse(event.data);+ if (!parsed.success)return;- }- if (!noticed) {- noticed = true;- notice("omo: could not check whether the keyring is locked (gdbus or the Secret Service did not answer); using libsecret directly.");- }- };- return {- async read() {- await assertUsable();- let value;- try {- value = await answered(secrets);- } catch (error) {- if (error instanceof KeychainApprovalPendingError)- throw error;- throw unavailable(error);- }- if (value === null)- return null;- try {- return schema.parse(JSON.parse(value));- } catch {- throw new InvalidCredentialState(signInRoute() === "cli" ? "Stored sign-in data is invalid. Run omo logout, then omo login." : "The OmO sign-in saved on this computer can't be read, and it can't be reset from the terminal yet.");+ const message = parsed.data;+ switch (message.kind) {+ case "hello": {+ const observed = state.observing.get(message.threadId);+ if (observed !== undefined) {+ channel.postMessage({ kind: "register", threadId: message.threadId, challenge: observed.challenge });+ }+ return;}- },- async write(value) {- await assertUsable();- try {- await secrets.set({ ...key, value: JSON.stringify(schema.parse(value)) });- } catch (error) {- throw unavailable(error);+ case "register":+ if (message.threadId === threadId) {+ parentPort?.postMessage({+ kind: "omo-team-lock-register-v1",+ incarnation: state.incarnation,+ challenge: message.challenge+ });+ state.registered = true;+ state.onRegistered?.();+ }+ return;+ case "answer":+ state.pending.get(message.id)?.(message.released);+ return;+ case "query": {+ const status = message.incarnation === state.incarnation ? state.records.get(message.record) : undefined;+ if (status !== undefined || state.exited.has(message.incarnation)) {+ channel.postMessage({+ kind: "answer",+ id: message.id,+ released: status === "released" || state.exited.has(message.incarnation)+ });+ }+ return;}- forget(secrets);- },- async clear() {- await assertUsable();- try {- await secrets.delete(key);- } catch (error) {- throw unavailable(error);+ default: {+ const unexpected = message;+ throw new Error(`Unexpected lock lifetime message: ${unexpected}`);}- forget(secrets);}};+ return state;}--// packages/omo-opencode/src/cli/service-auth/loopback.ts-import { createHash as createHash11, randomBytes as randomBytes5, timingSafeEqual } from "node:crypto";-import { createServer as createServer3 } from "node:http";-class BrowserUnavailable extends SignInError {-}-async function authorize(options) {- const verifier = randomBytes5(32).toString("base64url");- const state = randomBytes5(32).toString("base64url");- const answer = Promise.withResolvers();- const abort = () => answer.reject(new SignInError("Browser sign-in cancelled or timed out."));- let accepted = false;- let origin = "";- const server = createServer3((request, response) => {- response.setHeader("cache-control", "no-store");- response.setHeader("referrer-policy", "no-referrer");- response.setHeader("content-type", "text/plain; charset=utf-8");- const url = new URL(request.url ?? "/", origin);- if (request.method !== "GET" || request.headers.host !== new URL(origin).host || url.origin !== origin || url.pathname !== "/callback" || request.headers.forwarded || request.headers["x-forwarded-for"]) {- response.writeHead(404).end("Not found");- return;- }- const code = url.searchParams.get("code");- const suppliedState = Buffer.from(url.searchParams.get("state") ?? "");- const expectedState = Buffer.from(state);- if (accepted || url.searchParams.getAll("state").length !== 1 || suppliedState.length !== expectedState.length || !timingSafeEqual(suppliedState, expectedState) || url.searchParams.getAll("code").length !== 1 || !code) {- response.writeHead(400).end("Invalid sign-in response");+var state2 = globalThis.__omoTeamLockLifetimeV1 ??= createState();+var lockOwnerInstanceId = state2.incarnation;+function attachWorker(worker) {+ if (state2.observed.has(worker))+ return;+ state2.observed.add(worker);+ const id = worker.threadId;+ const challenge = randomUUID5();+ state2.observing.set(id, { worker, challenge });+ const incarnations = new Set;+ let exited = false;+ worker.on("message", (message) => {+ const parsed = Registration.safeParse(message);+ if (!parsed.success || parsed.data.challenge !== challenge)return;- }- accepted = true;- response.writeHead(200).end("Return to the terminal to finish signing in.");- answer.resolve(code);+ incarnations.add(parsed.data.incarnation);+ if (exited)+ state2.exited.add(parsed.data.incarnation);});- try {- await new Promise((resolve, reject) => {- server.once("error", reject);- server.listen(0, "127.0.0.1", () => {- server.off("error", reject);- resolve();- });- });- const address = server.address();- if (!address || typeof address === "string")- throw new SignInError("Unable to start the sign-in callback.");- origin = `http://127.0.0.1:${address.port}`;- const url = new URL(serviceOrigin(options.accounts));- url.search = new URLSearchParams({- redirect_uri: `${origin}/callback`,- code_challenge: createHash11("sha256").update(verifier).digest("base64url"),- code_challenge_method: "S256",- state- }).toString();- const timer = setTimeout(abort, 5 * 60000);- options.signal?.addEventListener("abort", abort, { once: true });- try {- options.signal?.throwIfAborted();- const openerFailed = () => {- if (!accepted)- throw new BrowserUnavailable("No browser is available; use device sign-in.");- };- const [code] = await Promise.all([- answer.promise,- options.open(url.href).then((opened) => {- if (!opened)- openerFailed();- }, openerFailed)- ]);- return { code, codeVerifier: verifier };- } finally {+ worker.once("exit", () => {+ exited = true;+ if (state2.observing.get(id)?.worker === worker)+ state2.observing.delete(id);+ for (const incarnation of incarnations)+ state2.exited.add(incarnation);+ });+}+function installLockWorkerObserver() {+ if (state2.installed)+ return;+ state2.installed = true;+ process.on("worker", attachWorker);+ state2.channel.postMessage({ kind: "hello", threadId });+}+installLockWorkerObserver();+async function registerLockWorker() {+ if (state2.registered)+ return;+ state2.registration ??= new Promise((resolve) => {+ const finish = () => {clearTimeout(timer);- options.signal?.removeEventListener("abort", abort);- }- } finally {- server.closeAllConnections();- await new Promise((resolve) => server.close(() => resolve()));- }+ state2.onRegistered = undefined;+ resolve();+ };+ const timer = setTimeout(finish, 250);+ state2.onRegistered = finish;+ state2.channel.postMessage({ kind: "hello", threadId });+ });+ await state2.registration;}-async function loginLoopback(session, options) {- await session.ready();- const keys = generateDeviceKeys();- for (;; ) {- const authorization = await authorize({ accounts: options.accounts, open: options.open, signal: session.signal });- try {- const grant = parseReply(grantSchema, await session.request("/v1/session/exchange", jsonRequest({- ...authorization,- kind: "cli",- deviceName: options.name,- platform: options.platform,- ...keys.public- })));- await session.save({ ...grant, ...keys.private });- return;- } catch (error) {- if (await session.removeForLimit(error, options.chooseDevice))- continue;- throw new SignInError("Sign-in cancelled. No device was removed.");- }- }+function markLockRecordHeld(record) {+ state2.records.set(record, "held");+}+function markLockRecordReleased(record) {+ if (state2.records.has(record))+ state2.records.set(record, "released");+}+function forgetLockRecord(record) {+ state2.records.delete(record);+}+async function isWorkerLockReleased(incarnation, record) {+ if (state2.exited.has(incarnation))+ return true;+ if (incarnation === state2.incarnation)+ return state2.records.get(record) === "released";+ const id = randomUUID5();+ return await new Promise((resolve) => {+ const finish = (released) => {+ clearTimeout(timer);+ state2.pending.delete(id);+ resolve(released);+ };+ const timer = setTimeout(() => finish(false), 250);+ state2.pending.set(id, finish);+ state2.channel.postMessage({ kind: "query", id, incarnation, record });+ });}--// packages/omo-opencode/src/cli/service-auth/session.ts-import { mkdir as mkdir11 } from "node:fs/promises";-import { homedir as homedir31 } from "node:os";-import { join as join107 } from "node:path";--// packages/team-core/src/team-state-store/lock-publish.ts-import { access as access3, open as open2, unlink as unlink2 } from "node:fs/promises";-import { dirname as dirname42 } from "node:path";// packages/team-core/src/team-state-store/lock-record.ts-import { randomUUID as randomUUID5 } from "node:crypto";-import { readFile as readFile33, stat as stat8 } from "node:fs/promises";-var lockOwnerInstanceId = randomUUID5();-var heldLockRecords = new Set;-function buildLockRecord(ownerTag) {- return `${ownerTag} ${randomUUID5()}+async function buildLockRecord(ownerTag) {+ await registerLockWorker();+ const processStart = await getProcessStartIdentity(process.pid);+ return `${ownerTag} ${randomUUID6()}${process.pid}${Date.now()}${lockOwnerInstanceId}+${processStart ?? "unavailable"}`;}-function markLockRecordHeld(content) {- heldLockRecords.add(content);-}-function markLockRecordReleased(content) {- heldLockRecords.delete(content);-}-function errorCode(error) {+function errorCode2(error) {if (!(error instanceof Error) || !("code" in error))return null;return typeof error.code === "string" ? error.code : null;}function isPathAbsenceError(error) {- const code = errorCode(error);+ const code = errorCode2(error);return code === "ENOENT" || code === "ENOTDIR";}function parseLockOwner(content) {const lines = content.split(/\r?\n/).filter((line) => line.length > 0);- if (lines.length !== 3 && lines.length !== 4)+ if (lines.length !== 3 && lines.length !== 4 && lines.length !== 5)return null;const ownerPid = Number.parseInt(lines[1] ?? "", 10);const acquiredAtEpochMs = Number.parseInt(lines[2] ?? "", 10);@@ -112787,24 +113228,14 @@ function parseLockOwner(content) {return {ownerPid,acquiredAtEpochMs,- instanceId: lines.length === 4 ? lines[3] ?? null : null+ instanceId: lines[3] ?? null,+ processStart: lines[4] ?? null};}-function isPidAlive(pid) {- try {- process.kill(pid, 0);- return true;- } catch (error) {- if (!(error instanceof Error)) {- throw error;- }- return false;- }-}async function readLockRecord(lockPath) {try {- const content = await readFile33(lockPath, "utf8");- const { mtimeMs } = await stat8(lockPath);+ const content = await readFile34(lockPath, "utf8");+ const { mtimeMs } = await stat9(lockPath);return { content, modifiedAtEpochMs: mtimeMs };} catch (error) {if (!(error instanceof Error))@@ -112812,23 +113243,30 @@ async function readLockRecord(lockPath) {return null;}}-function isLockRecordStale(record, staleAfterMs) {+async function isLockRecordStale(record, staleAfterMs) {const owner = parseLockOwner(record.content);if (owner === null)return Date.now() - record.modifiedAtEpochMs > staleAfterMs;- if (owner.instanceId !== null && owner.ownerPid === process.pid) {- return owner.instanceId !== lockOwnerInstanceId || !heldLockRecords.has(record.content);+ const liveness = getPidLiveness(owner.ownerPid);+ if (liveness === "dead") {+ return owner.instanceId !== null || Date.now() - owner.acquiredAtEpochMs > staleAfterMs;}- if (isPidAlive(owner.ownerPid))+ if (liveness === "unknown")return false;- if (owner.instanceId !== null)- return true;- return Date.now() - owner.acquiredAtEpochMs > staleAfterMs;+ if (owner.processStart !== null) {+ const actual = await getProcessStartIdentity(owner.ownerPid);+ if (actual !== null && startIdentitiesConflict(owner.processStart, actual))+ return true;+ }+ if (owner.instanceId !== null && owner.ownerPid === process.pid) {+ return await isWorkerLockReleased(owner.instanceId, record.content);+ }+ return false;}// packages/team-core/src/team-state-store/lock-publish.tsasync function pathMayExist(path, deps = {}) {- const accessPath = deps.access ?? access3;+ const accessPath = deps.access ?? access4;try {await accessPath(path);return true;@@ -112839,7 +113277,7 @@ async function pathMayExist(path, deps = {}) {}}async function assertRetryableLockOpenError(lockPath, error, deps) {- const code = errorCode(error);+ const code = errorCode2(error);if (code === "EEXIST")return;if (code === "EPERM") {@@ -112854,9 +113292,9 @@ async function publishLockRecord(lockPath, record) {markLockRecordHeld(record);let fileHandle;try {- fileHandle = await open2(lockPath, "wx");+ fileHandle = await open3(lockPath, "wx");} catch (error) {- markLockRecordReleased(record);+ forgetLockRecord(record);await assertRetryableLockOpenError(lockPath, error);return false;}@@ -112865,7 +113303,7 @@ async function publishLockRecord(lockPath, record) {} catch (error) {markLockRecordReleased(record);await fileHandle.close();- await unlink2(lockPath).catch(() => {+ await unlink3(lockPath).catch(() => {return;});throw error;@@ -112875,8 +113313,8 @@ async function publishLockRecord(lockPath, record) {}// packages/team-core/src/team-state-store/lock-reclaim.ts-import { createHash as createHash12 } from "node:crypto";-import { unlink as unlink3 } from "node:fs/promises";+import { createHash as createHash10 } from "node:crypto";+import { unlink as unlink4 } from "node:fs/promises";var RECLAIM_UNLINK_ATTEMPTS = 3;var RECLAIM_UNLINK_RETRY_MS = 25;function delay2(ms) {@@ -112885,11 +113323,11 @@ function delay2(ms) {});}function reclaimGuardPath(lockPath, record) {- return `${lockPath}.reclaim-${createHash12("sha256").update(record).digest("hex").slice(0, 16)}`;+ return `${lockPath}.reclaim-${createHash10("sha256").update(record).digest("hex").slice(0, 16)}`;}async function unlinkWithRetry(path, deps) {const wait = deps.delay ?? delay2;- const unlinkFile = deps.unlink ?? unlink3;+ const unlinkFile = deps.unlink ?? unlink4;for (let attempt = 1;; attempt += 1) {try {await unlinkFile(path);@@ -112899,7 +113337,7 @@ async function unlinkWithRetry(path, deps) {throw error;if (isPathAbsenceError(error))return "absent";- const code = errorCode(error);+ const code = errorCode2(error);if (code !== "EPERM" && code !== "EBUSY" || attempt === RECLAIM_UNLINK_ATTEMPTS)return "stuck";await wait(RECLAIM_UNLINK_RETRY_MS);@@ -112908,10 +113346,10 @@ async function unlinkWithRetry(path, deps) {}async function removeLockRecordIfUnchanged(lockPath, expectedRecord, staleAfterMs, deps = {}) {const guardPath = reclaimGuardPath(lockPath, expectedRecord);- const guardRecord = buildLockRecord("lock-reclaim");+ const guardRecord = await buildLockRecord("lock-reclaim");if (!await publishLockRecord(guardPath, guardRecord)) {const guard = await readLockRecord(guardPath);- if (guard !== null && isLockRecordStale(guard, staleAfterMs)) {+ if (guard !== null && await isLockRecordStale(guard, staleAfterMs)) {await removeLockRecordIfUnchanged(guardPath, guard.content, staleAfterMs, deps);}return "busy";@@ -112920,13 +113358,16 @@ async function removeLockRecordIfUnchanged(lockPath, expectedRecord, staleAfterMconst current = await readLockRecord(lockPath);if (current === null)return "absent";- if (current.content !== expectedRecord || !isLockRecordStale(current, staleAfterMs))+ if (current.content !== expectedRecord || !await isLockRecordStale(current, staleAfterMs))return "changed";const unlinked = await unlinkWithRetry(lockPath, deps);+ if (unlinked !== "stuck")+ forgetLockRecord(expectedRecord);return unlinked === "absent" ? "absent" : unlinked;} finally {markLockRecordReleased(guardRecord);- await unlinkWithRetry(guardPath, deps);+ if (await unlinkWithRetry(guardPath, deps) !== "stuck")+ forgetLockRecord(guardRecord);}}@@ -112945,7 +113386,7 @@ async function acquireLock(lockPath, ownerTag, staleAfterMs) {if (Date.now() - startedAt > LOCK_WAIT_TIMEOUT_MS) {throw new Error(`Timed out acquiring lock: ${lockPath}`);}- const record = buildLockRecord(ownerTag);+ const record = await buildLockRecord(ownerTag);if (await publishLockRecord(lockPath, record))return record;const outcome = await reapStaleLock(lockPath, staleAfterMs);@@ -112962,26 +113403,327 @@ async function withLock(lockPath, fn, opts) {return await fn();} finally {markLockRecordReleased(record);- await removeLockRecordIfUnchanged(lockPath, record, staleAfterMs);+ const outcome = await removeLockRecordIfUnchanged(lockPath, record, staleAfterMs);+ if (outcome === "removed" || outcome === "absent" || outcome === "changed")+ forgetLockRecord(record);}}async function reapStaleLock(lockPath, staleAfterMs = DEFAULT_STALE_AFTER_MS, deps = {}) {const observed = await readLockRecord(lockPath);if (observed === null)return "absent";- if (!isLockRecordStale(observed, staleAfterMs))+ if (!await isLockRecordStale(observed, staleAfterMs))return "changed";return await removeLockRecordIfUnchanged(lockPath, observed.content, staleAfterMs, deps);}+// packages/omo-opencode/src/cli/service-auth/credential-lock.ts+var held = new AsyncLocalStorage3;+function credentialLockPaths(api, home = homedir31()) {+ const id = createHash11("sha256").update(serviceOrigin(api)).digest("hex");+ const directory = join106(home, ".omo", "session-locks");+ return { directory, lock: join106(directory, `${id}.lock`), desktopRecord: join106(directory, `${id}.desktop-generation.json`) };+}+async function withCredentialLock(api, action, home = homedir31(), ownerTag = "cli-session") {+ const { directory, lock } = credentialLockPaths(api, home);+ const owned = held.getStore();+ if (owned?.has(lock))+ return action();+ await mkdir11(directory, { recursive: true, mode: 448 });+ return withLock(lock, () => held.run(new Set([...owned ?? [], lock]), action), {+ ownerTag,+ staleAfterMs: Number.POSITIVE_INFINITY+ });+}++// packages/omo-opencode/src/cli/service-auth/keystore.ts+class CredentialStoreError extends SignInError {+}++class KeychainLockedError extends CredentialStoreError {+}+class InvalidCredentialState extends SignInError {+}++class CredentialIdentityChanged extends Error {+ constructor() {+ super("The stored sign-in changed; the captured account is no longer current.");+ }+}++class KeychainApprovalPendingError extends CredentialStoreError {+}+var SESSION_READ_WAIT = { kind: "bounded", deadlineMs: 5000 };+var INTERACTIVE_READ_WAIT = {+ kind: "interactive",+ noticeAfterMs: 2000,+ notice: (message) => process.stderr.write(`${message}+`)+};+var processReads = new WeakMap;+var LOCKED = /-25308|errSecInteractionNotAllowed|interaction is not allowed|locked collection/i;+var UNLOCKED_REUSE_MS = 30000;+var fallbackNoticed = false;+var stderrNoticeOncePerProcess = (message) => {+ if (fallbackNoticed)+ return;+ fallbackNoticed = true;+ process.stderr.write(`${message}+`);+};+var isLocked = (error) => error instanceof Error && (LOCKED.test(error.message) || LOCKED.test(String(error.code ?? "")));+function credentialId(api) {+ return createHash12("sha256").update(serviceOrigin(api)).digest("hex");+}+function createCredentialStore(api, options = {}) {+ const store = createSealedStore(api, "omo-cli", credentialSchema, options.secrets, options.platform, options.lockProbe, options.notice, options.wait, (current, value) => {+ const sameIdentity = current !== null && current.device.id === value.device.id && current.signingPrivateKey === value.signingPrivateKey && current.sealingPrivateKey === value.sealingPrivateKey && (value.accountId === undefined || current.accountId === undefined || current.accountId === value.accountId);+ const accountId = value.accountId ?? (sameIdentity ? current?.accountId : undefined);+ return {+ ...value,+ ...accountId === undefined ? {} : { accountId },+ credentialGeneration: sameIdentity ? current?.credentialGeneration ?? randomUUID7() : randomUUID7()+ };+ });+ return {+ read: store.read,+ readAuthoritative: store.readAuthoritative,+ write: (value) => withCredentialLock(api, () => store.write(value), options.home),+ clear: () => withCredentialLock(api, store.clear, options.home)+ };+}+function createSealedStore(api, namespace, schema, secrets = typeof Bun === "undefined" ? null : Bun.secrets, platform = process.platform, lockProbe = probeSecretServiceLock, notice = stderrNoticeOncePerProcess, wait = SESSION_READ_WAIT, amendWrite) {+ if (!secrets)+ throw new SignInError("OmO sign-in needs Bun 1.4 or newer with OS credential storage. No file fallback is available.");+ const platformName = platform === "darwin" ? "macOS Keychain" : platform === "linux" ? "Linux Secret Service (libsecret and an unlocked keyring)" : platform === "win32" ? "Windows Credential Manager" : null;+ if (platformName === null)+ throw new SignInError("This platform has no supported OS credential store.");+ const key = { service: namespace, name: credentialId(api) };+ const slot = `${key.service}+${key.name}`;+ const readsOf = (api) => {+ const known = processReads.get(api);+ if (known !== undefined)+ return known;+ const created = new Map;+ processReads.set(api, created);+ return created;+ };+ const forget = (api) => {+ readsOf(api).delete(slot);+ };+ const sharedRead = (api) => {+ const reads = readsOf(api);+ const pending = reads.get(slot);+ if (pending !== undefined)+ return pending;+ const read = Promise.resolve().then(() => api.get(key));+ const done = () => {+ if (reads.get(slot) === read)+ reads.delete(slot);+ };+ read.then(done, done);+ reads.set(slot, read);+ return read;+ };+ const waiting = platform === "darwin" ? `macOS Keychain is waiting for your approval: answer the "${basename15(process.execPath)} wants to access key ${namespace}" dialog ("Always Allow" stops it asking again)` : `${platformName} has not answered; it may be waiting for your approval or an unlock in a system dialog`;+ const answered = async (api, fresh = false) => {+ const read = fresh ? Promise.resolve().then(() => api.get(key)) : sharedRead(api);+ let timer;+ try {+ if (wait.kind === "interactive") {+ timer = setTimeout(() => wait.notice(`omo: ${waiting}.`), wait.noticeAfterMs);+ return await read;+ }+ const expired = new Promise((_, reject) => {+ timer = setTimeout(() => reject(new KeychainApprovalPendingError(`${waiting}, then try again. Credentials are never saved to a file.`)), wait.deadlineMs);+ });+ return await Promise.race([read, expired]);+ } finally {+ clearTimeout(timer);+ }+ };+ const unavailable = (error) => isLocked(error) ? new KeychainLockedError(`${platformName} is locked. Unlock it, then try again. Credentials are never saved to a file.`) : new CredentialStoreError(`Cannot access ${platformName}. Unlock or enable the OS credential store and try again. Credentials are never saved to a file.`);+ let unlockedUntil = 0;+ let noticed = false;+ const assertUsable = async () => {+ if (platform !== "linux" || Date.now() < unlockedUntil)+ return;+ const lock = await lockProbe();+ if (lock === "locked")+ throw new KeychainLockedError(`${platformName} is locked. Unlock it, then try again. Credentials are never saved to a file.`);+ if (lock === "unlocked") {+ unlockedUntil = Date.now() + UNLOCKED_REUSE_MS;+ return;+ }+ if (!noticed) {+ noticed = true;+ notice("omo: could not check whether the keyring is locked (gdbus or the Secret Service did not answer); using libsecret directly.");+ }+ };+ const parsedRead = async (fresh) => {+ await assertUsable();+ let value;+ try {+ value = await answered(secrets, fresh);+ } catch (error) {+ if (error instanceof KeychainApprovalPendingError)+ throw error;+ throw unavailable(error);+ }+ if (value === null)+ return null;+ try {+ return schema.parse(JSON.parse(value));+ } catch {+ throw new InvalidCredentialState(signInRoute() === "cli" ? "Stored sign-in data is invalid. Run omo account forget, then omo login." : "The OmO sign-in saved on this computer can't be read. Run omo account forget to remove it, then sign in again in the desktop app.");+ }+ };+ return {+ read: () => parsedRead(false),+ readAuthoritative: () => parsedRead(true),+ async write(value) {+ await assertUsable();+ try {+ let next = value;+ if (amendWrite !== undefined) {+ const raw = await answered(secrets, true);+ let previous = null;+ if (raw !== null) {+ try {+ previous = schema.parse(JSON.parse(raw));+ } catch {}+ }+ next = amendWrite(previous, value);+ }+ await secrets.set({ ...key, value: JSON.stringify(schema.parse(next)) });+ } catch (error) {+ throw unavailable(error);+ }+ forget(secrets);+ },+ async clear() {+ await assertUsable();+ try {+ await secrets.delete(key);+ } catch (error) {+ throw unavailable(error);+ }+ forget(secrets);+ }+ };+}++// packages/omo-opencode/src/cli/service-auth/loopback.ts+import { createHash as createHash13, randomBytes as randomBytes5, timingSafeEqual } from "node:crypto";+import { createServer as createServer3 } from "node:http";+class BrowserUnavailable extends SignInError {+}+async function authorize(options) {+ const verifier = randomBytes5(32).toString("base64url");+ const state = randomBytes5(32).toString("base64url");+ const answer = Promise.withResolvers();+ const abort = () => answer.reject(new SignInError("Browser sign-in cancelled or timed out."));+ let accepted = false;+ let origin = "";+ const server = createServer3((request, response) => {+ response.setHeader("cache-control", "no-store");+ response.setHeader("referrer-policy", "no-referrer");+ response.setHeader("content-type", "text/plain; charset=utf-8");+ const url = new URL(request.url ?? "/", origin);+ if (request.method !== "GET" || request.headers.host !== new URL(origin).host || url.origin !== origin || url.pathname !== "/callback" || request.headers.forwarded || request.headers["x-forwarded-for"]) {+ response.writeHead(404).end("Not found");+ return;+ }+ const code = url.searchParams.get("code");+ const suppliedState = Buffer.from(url.searchParams.get("state") ?? "");+ const expectedState = Buffer.from(state);+ if (accepted || url.searchParams.getAll("state").length !== 1 || suppliedState.length !== expectedState.length || !timingSafeEqual(suppliedState, expectedState) || url.searchParams.getAll("code").length !== 1 || !code) {+ response.writeHead(400).end("Invalid sign-in response");+ return;+ }+ accepted = true;+ response.writeHead(200).end("Return to the terminal to finish signing in.");+ answer.resolve(code);+ });+ try {+ await new Promise((resolve, reject) => {+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => {+ server.off("error", reject);+ resolve();+ });+ });+ const address = server.address();+ if (!address || typeof address === "string")+ throw new SignInError("Unable to start the sign-in callback.");+ origin = `http://127.0.0.1:${address.port}`;+ const url = new URL(serviceOrigin(options.accounts));+ url.search = new URLSearchParams({+ redirect_uri: `${origin}/callback`,+ code_challenge: createHash13("sha256").update(verifier).digest("base64url"),+ code_challenge_method: "S256",+ state+ }).toString();+ const timer = setTimeout(abort, 5 * 60000);+ options.signal?.addEventListener("abort", abort, { once: true });+ try {+ options.signal?.throwIfAborted();+ const openerFailed = () => {+ if (!accepted)+ throw new BrowserUnavailable("No browser is available; use device sign-in.");+ };+ const [code] = await Promise.all([+ answer.promise,+ options.open(url.href).then((opened) => {+ if (!opened)+ openerFailed();+ }, openerFailed)+ ]);+ return { code, codeVerifier: verifier };+ } finally {+ clearTimeout(timer);+ options.signal?.removeEventListener("abort", abort);+ }+ } finally {+ server.closeAllConnections();+ await new Promise((resolve) => server.close(() => resolve()));+ }+}+async function loginLoopback(session, options) {+ await session.ready();+ const keys = generateDeviceKeys();+ for (;; ) {+ const authorization = await authorize({ accounts: options.accounts, open: options.open, signal: session.signal });+ try {+ const grant = parseReply(grantSchema, await session.request("/v1/session/exchange", jsonRequest({+ ...authorization,+ kind: "cli",+ deviceName: options.name,+ platform: options.platform,+ ...keys.public+ })));+ await session.save({ ...grant, ...keys.private });+ return;+ } catch (error) {+ if (await session.removeForLimit(error, options.chooseDevice))+ continue;+ throw new SignInError("Sign-in cancelled. No device was removed.");+ }+ }+}++// packages/omo-opencode/src/cli/service-auth/session.ts+import { homedir as homedir32 } from "node:os";+// packages/omo-opencode/src/cli/service-auth/signed-out-marker.tsinit_zod();-import { mkdir as mkdir10, readFile as readFile34, rename as rename7, rm as rm16, writeFile as writeFile16 } from "node:fs/promises";-import { dirname as dirname43, join as join106 } from "node:path";+import { mkdir as mkdir12, readFile as readFile35, rename as rename8, rm as rm17, writeFile as writeFile17 } from "node:fs/promises";+import { dirname as dirname43, join as join107 } from "node:path";var markerSchema = object({ device: string2().nullable(), at: string2() });-var signedOutMarkerPath = (home, credential) => join106(home, ".omo", "account-state", `${credential}.signed-out.json`);+var signedOutMarkerPath = (home, credential) => join107(home, ".omo", "account-state", `${credential}.signed-out.json`);async function readSignedOutMarker(path) {- const text = await readFile34(path, "utf8").catch(() => null);+ const text = await readFile35(path, "utf8").catch(() => null);if (text === null)return null;let value;@@ -112994,12 +113736,12 @@ async function readSignedOutMarker(path) {return parsed.success ? parsed.data : null;}async function writeSignedOutMarker(path, device) {- await mkdir10(dirname43(path), { recursive: true, mode: 448 });+ await mkdir12(dirname43(path), { recursive: true, mode: 448 });const staging = `${path}.${process.pid}.tmp`;- await writeFile16(staging, JSON.stringify({ device, at: new Date().toISOString() }), { mode: 384 });- await rename7(staging, path);+ await writeFile17(staging, JSON.stringify({ device, at: new Date().toISOString() }), { mode: 384 });+ await rename8(staging, path);}-var clearSignedOutMarker = (path) => rm16(path, { force: true });+var clearSignedOutMarker = (path) => rm17(path, { force: true });// packages/omo-opencode/src/cli/service-auth/session.tsclass SessionEnded extends SignInError {@@ -113014,30 +113756,29 @@ class SessionEnded extends SignInError {var DEVICE_REVOKING_REFUSALS = new Set(["account_deleted", "reauth_required", "device_revoked"]);function createSession(options) {const api = serviceOrigin(options.api);+ const now = options.now ?? Date.now;const { store, signal } = options;- const directory = join107(options.home ?? homedir31(), ".omo", "session-locks");- const lockPath = join107(directory, `${credentialId(api)}.lock`);- const markerPath = signedOutMarkerPath(options.home ?? homedir31(), credentialId(api));+ const markerPath = signedOutMarkerPath(options.home ?? homedir32(), credentialId(api));async function locked(action) {- await mkdir11(directory, { recursive: true, mode: 448 });signal?.throwIfAborted();- return withLock(lockPath, async () => {+ return withCredentialLock(api, async () => {signal?.throwIfAborted();return action();- }, { ownerTag: "cli-session", staleAfterMs: Number.POSITIVE_INFINITY });+ }, options.home);}const request = (path, init) => requestApi(api, path, init, signal);- const uncertain = () => new SignInError(`The refresh outcome is unknown. Saved credentials and keys were retained, but this refresh token will not be sent again. ${signInHint("again")}`, true);- async function refreshedAccess(current) {- if (current.refreshState === "uncertain")- throw uncertain();- if (Date.parse(current.accessTokenExpiresAt) > Date.now() + 30000)- return current.accessToken;+ async function refreshed(current) {+ if (current.refreshState === "uncertain" || current.refreshAttempt !== undefined) {+ throw new SessionEnded(`Refresh recovery can no longer be proved safe. ${signInHint("again")}`, false, "refresh_recovery_expired");+ }+ if (Date.parse(current.accessTokenExpiresAt) > now() + 30000)+ return current;await store.write({ ...current, refreshState: "uncertain" });try {const tokens = parseReply(tokenSchema, await request("/v1/session/refresh", jsonRequest({ refreshToken: current.refreshToken })));- await store.write({ ...current, ...tokens });- return tokens.accessToken;+ const successor = { ...current, ...tokens };+ await store.write(successor);+ return successor;} catch (error) {if (error instanceof CredentialStoreError)throw error;@@ -113049,12 +113790,19 @@ function createSession(options) {await store.write(current);throw error;}- throw uncertain();+ throw new SessionEnded(`The refresh outcome is unknown. Saved credentials and keys were retained. ${signInHint("again")}`, false, "refresh_recovery_expired");}}+ async function snapshot() {+ return locked(async () => {+ const current = await store.read();+ return current === null ? null : refreshed(current);+ });+ }return {request,signal,+ transaction: locked,async ready() {await store.read();},@@ -113066,18 +113814,32 @@ function createSession(options) {},signedOutMarker: () => readSignedOutMarker(markerPath),clearSignedOutMarker: () => clearSignedOutMarker(markerPath),- async update(action) {- return locked(async () => action(await store.read()));+ async update(action, options = {}) {+ return locked(async () => {+ let current;+ try {+ current = await store.readAuthoritative();+ } catch (error) {+ if (!options.replaceInvalid || !(error instanceof InvalidCredentialState))+ throw error;+ current = null;+ }+ return action(current);+ });},+ async forget() {+ await locked(() => store.clear());+ },+ accessSnapshot: snapshot,async logout() {return locked(async () => {let current = null;try {- current = await store.read();+ current = await store.readAuthoritative();if (current !== null) {if (current.refreshState === "uncertain")return false;- const access = Date.parse(current.accessTokenExpiresAt) <= Date.now() ? await refreshedAccess(current) : current.accessToken;+ const access = Date.parse(current.accessTokenExpiresAt) <= now() ? (await refreshed(current)).accessToken : current.accessToken;await request(`/v1/devices/${encodeURIComponent(current.device.id)}`, {method: "DELETE",headers: { authorization: `Bearer ${access}` }@@ -113096,12 +113858,19 @@ function createSession(options) {}});},- async accessToken() {+ async accessToken(expect) {+ signal?.throwIfAborted();+ const snapshot = await store.read();+ signal?.throwIfAborted();+ if (snapshot !== null && snapshot.refreshState !== "uncertain" && snapshot.refreshAttempt === undefined && Date.parse(snapshot.accessTokenExpiresAt) > now() + 30000 && (expect === undefined || expect(snapshot)))+ return snapshot.accessToken;return locked(async () => {- const current = await store.read();+ const current = await store.readAuthoritative();if (current === null)throw new SignInError(`Not signed in. ${signInHint("first")}`);- return refreshedAccess(current);+ if (expect !== undefined && !expect(current))+ throw new CredentialIdentityChanged;+ return (await refreshed(current)).accessToken;});},async removeForLimit(error, choose) {@@ -113430,12 +114199,12 @@ async function boulder(options) {}// packages/omo-opencode/src/cli/codex-ulw-loop.tsimport { spawn as spawn6 } from "node:child_process";-import { existsSync as existsSync67, readFileSync as readFileSync44, realpathSync as realpathSync13 } from "node:fs";-import { homedir as homedir32 } from "node:os";+import { existsSync as existsSync67, readFileSync as readFileSync45, realpathSync as realpathSync14 } from "node:fs";+import { homedir as homedir33 } from "node:os";var ULW_LOOP_DELEGATION_SENTINEL = "OMO_ULW_LOOP_DELEGATED";function resolveCodexUlwLoopCommand(input = {}) {const env = input.env ?? process.env;- const homeDir = input.homeDir ?? homedir32();+ const homeDir = input.homeDir ?? homedir33();const localComponentBin = resolveLocalUlwLoopBin(env, homeDir);if (localComponentBin !== null)return { executable: localComponentBin, argsPrefix: [] };@@ -113480,7 +114249,7 @@ function resolveLegacyLocalOmoBin(env, homeDir, currentExecutablePaths) {}function isGeneratedRuntimeWrapper(candidate) {try {- return readFileSync44(candidate, "utf8").includes(RUNTIME_WRAPPER_MARKER);+ return readFileSync45(candidate, "utf8").includes(RUNTIME_WRAPPER_MARKER);} catch (error) {if (error instanceof Error)return false;@@ -113493,7 +114262,7 @@ function isCurrentExecutable(candidate, currentExecutablePaths) {}function realpathOrSelf2(path) {try {- return realpathSync13(path);+ return realpathSync14(path);} catch (error) {if (error instanceof Error)return path;@@ -113678,7 +114447,7 @@ function linkedWorktrees(records) {}// packages/omo-opencode/src/cli/worktree-sweep/sweep.tsimport { existsSync as existsSync68 } from "node:fs";-import { stat as stat9 } from "node:fs/promises";+import { stat as stat10 } from "node:fs/promises";import os7 from "node:os";import { normalize as normalize2 } from "node:path";@@ -113761,7 +114530,7 @@ async function isOlderThan(worktreePath, days, now) {if (days <= 0)return false;try {- const stats = await stat9(worktreePath);+ const stats = await stat10(worktreePath);return now - stats.mtimeMs > days * DAY_MS;} catch {return false;@@ -114008,7 +114777,7 @@ Model Providers (Priority: Native > Copilot > OpenCode Zen > Z.ai > Kimi > BailiCopilot github-copilot/ models (fallback)OpenCode Zen opencode/ models (opencode/claude-opus-5, etc.)Z.ai zai-coding-plan/glm-5.2 (visual-engineering fallback)- Kimi kimi-for-coding/kimi-k3 (Sisyphus/Prometheus fallback)+ Kimi kimi-for-coding/kimi-k3.1-pro (Sisyphus/Prometheus fallback)Bailian bailian-coding-plan/ models (Qwen, GLM, Kimi fallback)MiniMax minimax-coding-plan/MiniMax-M3 (utility fallback)MiniMax CN minimax-cn-coding-plan/MiniMax-M3 (utility fallback)diff --git a/plugins/omo/dist/cli/index.js b/plugins/omo/dist/cli/index.jsindex 666db1b1..19cc3f7c 100755--- a/plugins/omo/dist/cli/index.js+++ b/plugins/omo/dist/cli/index.js@@ -2132,7 +2132,7 @@ var package_default;var init_package = __esm(() => {package_default = {name: "oh-my-opencode",- version: "5.1.51",+ version: "5.1.54",description: "The Best AI Agent Harness - Batteries-Included OpenCode Plugin with Multi-Model Orchestration, Parallel Background Agents, and Crafted LSP/AST Tools",main: "./dist/index.js",types: "dist/index.d.ts",@@ -2274,14 +2274,15 @@ var init_package = __esm(() => {prepublishOnly: "bun run clean && bun run build:lsp-tools-mcp && bun run build:lsp-daemon && bun run build","test:model-capabilities": "bun test --timeout 20000 packages/model-core/src/model-capability-aliases.test.ts packages/model-core/src/model-capability-guardrails.test.ts packages/model-core/src/model-capabilities.test.ts packages/omo-opencode/src/cli/doctor/checks/model-resolution.test.ts --bail","check:copy": "bun script/check-copy.ts",- typecheck: "bun run check:copy && tsgo --noEmit && bun run typecheck:script && bun run typecheck:packages",- "typecheck:packages": "tsgo --noEmit -p packages/rules-engine/tsconfig.json && tsgo --noEmit -p packages/delegate-core/tsconfig.json && tsgo --noEmit -p packages/mcp-stdio-core/tsconfig.json && tsgo --noEmit -p packages/mcp-client-core/tsconfig.json && tsgo --noEmit -p packages/git-bash-mcp/tsconfig.json && tsgo --noEmit -p packages/ast-grep-mcp/tsconfig.json && tsgo --noEmit -p packages/lsp-core/tsconfig.json && tsgo --noEmit -p packages/utils/tsconfig.json && tsgo --noEmit -p packages/model-core/tsconfig.json && tsgo --noEmit -p packages/omo-config-core/tsconfig.json && tsgo --noEmit -p packages/prompts-core/tsconfig.json && tsgo --noEmit -p packages/comment-checker-core/tsconfig.json && tsgo --noEmit -p packages/hashline-core/tsconfig.json && tsgo --noEmit -p packages/tmux-core/tsconfig.json && tsgo --noEmit -p packages/team-core/tsconfig.json && tsgo --noEmit -p packages/openclaw-core/tsconfig.json && tsgo --noEmit -p packages/boulder-state/tsconfig.json && tsgo --noEmit -p packages/isolation-core/tsconfig.json && tsgo --noEmit -p packages/memory-core/tsconfig.json && tsgo --noEmit -p packages/telemetry-core/tsconfig.json && tsgo --noEmit -p packages/claude-code-compat-core/tsconfig.json && tsgo --noEmit -p packages/skills-loader-core/tsconfig.json && tsgo --noEmit -p packages/agents-md-core/tsconfig.json && tsgo --noEmit -p packages/omo-codex/plugin/shared/tsconfig.json && tsgo --noEmit -p packages/omo-codex/tsconfig.json && tsgo --noEmit -p packages/omo-senpi/tsconfig.json && tsgo --noEmit -p packages/senpi-task/tsconfig.json && tsgo --noEmit -p packages/omo-opencode/tsconfig.json && tsgo --noEmit -p packages/omo-native/tsconfig.json && tsgo --noEmit -p packages/senpi-desktop-protocol/tsconfig.json && tsgo --noEmit -p packages/senpi-desktop-engine/tsconfig.json && tsgo --noEmit -p packages/senpi-desktop-prelude/tsconfig.json && tsgo --noEmit -p packages/senpi-desktop-service/tsconfig.json && tsgo --noEmit -p packages/senpi-desktop-tool/tsconfig.json",- "typecheck:script": "tsgo --noEmit -p script/tsconfig.json",+ typecheck: "bun run check:copy && bun check --no-script --all -p tsconfig.json && bun run typecheck:script && bun run typecheck:packages && bun run typecheck:skill-scripts",+ "typecheck:skill-scripts": "bun check --no-script --all -p packages/shared-skills/skills/frontend/scripts/detect/tsconfig.json",+ "typecheck:packages": "bun check --no-script --all -p packages/rules-engine/tsconfig.json && bun check --no-script --all -p packages/delegate-core/tsconfig.json && bun check --no-script --all -p packages/mcp-stdio-core/tsconfig.json && bun check --no-script --all -p packages/mcp-client-core/tsconfig.json && bun check --no-script --all -p packages/git-bash-mcp/tsconfig.json && bun check --no-script --all -p packages/ast-grep-mcp/tsconfig.json && bun check --no-script --all -p packages/lsp-core/tsconfig.json && bun check --no-script --all -p packages/utils/tsconfig.json && bun check --no-script --all -p packages/model-core/tsconfig.json && bun check --no-script --all -p packages/omo-config-core/tsconfig.json && bun check --no-script --all -p packages/prompts-core/tsconfig.json && bun check --no-script --all -p packages/comment-checker-core/tsconfig.json && bun check --no-script --all -p packages/hashline-core/tsconfig.json && bun check --no-script --all -p packages/tmux-core/tsconfig.json && bun check --no-script --all -p packages/team-core/tsconfig.json && bun check --no-script --all -p packages/openclaw-core/tsconfig.json && bun check --no-script --all -p packages/boulder-state/tsconfig.json && bun check --no-script --all -p packages/isolation-core/tsconfig.json && bun check --no-script --all -p packages/memory-core/tsconfig.json && bun check --no-script --all -p packages/telemetry-core/tsconfig.json && bun check --no-script --all -p packages/claude-code-compat-core/tsconfig.json && bun check --no-script --all -p packages/skills-loader-core/tsconfig.json && bun check --no-script --all -p packages/agents-md-core/tsconfig.json && bun check --no-script --all -p packages/omo-codex/plugin/shared/tsconfig.json && bun check --no-script --all -p packages/omo-codex/tsconfig.json && bun check --no-script --all -p packages/omo-senpi/tsconfig.json && bun check --no-script --all -p packages/senpi-task/tsconfig.json && bun check --no-script --all -p packages/omo-opencode/tsconfig.json && bun check --no-script --all -p packages/omo-native/tsconfig.json && bun check --no-script --all -p packages/senpi-desktop-protocol/tsconfig.json && bun check --no-script --all -p packages/senpi-desktop-engine/tsconfig.json && bun check --no-script --all -p packages/senpi-desktop-prelude/tsconfig.json && bun check --no-script --all -p packages/senpi-desktop-service/tsconfig.json && bun check --no-script --all -p packages/senpi-desktop-tool/tsconfig.json",+ "typecheck:script": "bun check --no-script --all -p script/tsconfig.json",test: "bun test --timeout 20000","changelog:section": "bun script/changelog-section.ts","test:codex": "bun run build:codex-install && bun run build:git-bash-mcp && bun run build:lsp-tools-mcp && bun run build:lsp-daemon && npm --prefix packages/lsp-tools-mcp test && npm --prefix packages/omo-codex/plugin ci && npm --prefix packages/omo-codex/plugin/components/ulw-loop test && bun run --cwd packages/omo-codex/plugin build && node scripts/check-third-party-notices.mjs --ship && bun test --timeout 20000 packages/omo-opencode/src/cli/cli-installer.platform.test.ts packages/omo-codex/src/install/codex-cache.test.ts packages/omo-codex/src/install/codex-cleanup.test.ts packages/omo-codex/src/install/codex-config-agent-cleanup.test.ts packages/omo-codex/src/install/codex-config-autonomous-features.test.ts packages/omo-codex/src/install/codex-config-reasoning.test.ts packages/omo-codex/src/install/codex-config-toml.test.ts packages/omo-codex/src/install/codex-project-local-cleanup.test.ts packages/omo-codex/src/install/install-codex-project-local-cleanup.test.ts packages/omo-codex/src/install/install-codex.test.ts packages/omo-codex/src/install/install-codex-packaged.test.ts packages/omo-codex/src/install/link-cached-plugin-agents.test.ts packages/omo-codex/src/**/*.test.ts packages/utils/src/jsonc-parser.test.ts packages/utils/src/frontmatter.test.ts packages/hashline-core/src/hash-computation.test.ts packages/hashline-core/src/smoke-untested-modules.test.ts packages/rules-engine/src/index.test.ts packages/rules-engine/src/security-boundary.test.ts packages/agents-md-core/src/injector.test.ts packages/omo-codex/plugin/components/lsp/test/package-smoke.test.ts && node --test packages/omo-codex/plugin/test/*.test.mjs packages/omo-codex/scripts/install-cache-copy.test.mjs packages/omo-codex/scripts/install-cli-args.test.mjs packages/omo-codex/scripts/install-delegated-command.test.mjs packages/omo-codex/scripts/install-config-autonomous-features.test.mjs packages/omo-codex/scripts/install-config-autonomous.test.mjs packages/omo-codex/scripts/install-config-reasoning.test.mjs packages/omo-codex/scripts/install-config.test.mjs packages/omo-codex/scripts/install-hook-targets.test.mjs packages/omo-codex/scripts/install-project-local-cleanup.test.mjs packages/omo-codex/scripts/install-lazycodex-version-stamp.test.mjs packages/omo-codex/scripts/install-local-entrypoint.test.mjs packages/omo-codex/scripts/install-local-git-bash-preflight.test.mjs packages/omo-codex/scripts/install-local.test.mjs packages/omo-codex/scripts/install-marketplace-cache.test.mjs packages/omo-codex/scripts/install-mcp-context7-runtime.test.mjs packages/omo-codex/scripts/install-mcp-runtime.test.mjs packages/omo-codex/scripts/install-packaged-local.test.mjs packages/omo-codex/scripts/install-generated-bundle.test.mjs packages/omo-codex/scripts/install-agent-links.test.mjs packages/omo-codex/scripts/install-bin-links.test.mjs","test:fast": "bun run script/test-fast.ts",- "test:senpi": "bun run build:senpi-plugin && tsgo --noEmit -p packages/omo-senpi/tsconfig.json && bun test --timeout 20000 packages/omo-senpi && bun test ./.agents/skills/senpi-qa/scripts/resolve-evidence-dir.test.mjs",+ "test:senpi": "bun run build:senpi-plugin && bun check --no-script --all -p packages/omo-senpi/tsconfig.json && bun test --timeout 20000 packages/omo-senpi && bun test ./.agents/skills/senpi-qa/scripts/resolve-evidence-dir.test.mjs","test:windows-codex": "bun run test:codex","build:git-bash-mcp": "bun run --cwd packages/git-bash-mcp build","build:ast-grep-mcp": "bun run --cwd packages/ast-grep-mcp build",@@ -2317,7 +2318,7 @@ var init_package = __esm(() => {},devDependencies: {"@clack/prompts": "^1.8.1",- "@code-yeongyu/senpi": "2026.10.27-1",+ "@code-yeongyu/senpi": "2026.10.30-1","@modelcontextprotocol/sdk": "^1.30.0","@oh-my-opencode/agents-md-core": "workspace:*","@oh-my-opencode/ast-grep-mcp": "workspace:*",@@ -2371,7 +2372,7 @@ var init_package = __esm(() => {"jsonc-parser": "^3.3.1",knip: "6.43.0","node-pty": "^1.1.0",- omowright: "github:code-yeongyu/omowright#f87ef4d63fe7b56fe117dbab246c8ad88dd8a780",+ omowright: "github:code-yeongyu/omowright#c06d20337ad942b09dea8757a45f6c848008a68d","oxc-parser": "0.148.0",oxlint: "1.89.0",picocolors: "^1.1.1",@@ -2381,18 +2382,18 @@ var init_package = __esm(() => {typescript: "^7.0.2"},optionalDependencies: {- "oh-my-opencode-darwin-arm64": "5.1.51",- "oh-my-opencode-darwin-x64": "5.1.51",- "oh-my-opencode-darwin-x64-baseline": "5.1.51",- "oh-my-opencode-linux-arm64": "5.1.51",- "oh-my-opencode-linux-arm64-musl": "5.1.51",- "oh-my-opencode-linux-x64": "5.1.51",- "oh-my-opencode-linux-x64-baseline": "5.1.51",- "oh-my-opencode-linux-x64-musl": "5.1.51",- "oh-my-opencode-linux-x64-musl-baseline": "5.1.51",- "oh-my-opencode-windows-arm64": "5.1.51",- "oh-my-opencode-windows-x64": "5.1.51",- "oh-my-opencode-windows-x64-baseline": "5.1.51"+ "oh-my-opencode-darwin-arm64": "5.1.54",+ "oh-my-opencode-darwin-x64": "5.1.54",+ "oh-my-opencode-darwin-x64-baseline": "5.1.54",+ "oh-my-opencode-linux-arm64": "5.1.54",+ "oh-my-opencode-linux-arm64-musl": "5.1.54",+ "oh-my-opencode-linux-x64": "5.1.54",+ "oh-my-opencode-linux-x64-baseline": "5.1.54",+ "oh-my-opencode-linux-x64-musl": "5.1.54",+ "oh-my-opencode-linux-x64-musl-baseline": "5.1.54",+ "oh-my-opencode-windows-arm64": "5.1.54",+ "oh-my-opencode-windows-x64": "5.1.54",+ "oh-my-opencode-windows-x64-baseline": "5.1.54"},overrides: {hono: "^4.13.8",@@ -8055,7 +8056,8 @@ var init_latest_models = __esm(() => {gptLunaFast: "gpt-6-luna-fast",glm: "glm-5.3",glmFlash: "glm-5.3-flash",- kimi: "kimi-k3",+ kimi: "kimi-k3.1-pro",+ kimiK3: "kimi-k3",geminiPro: "gemini-4-argon"};});@@ -9378,9 +9380,13 @@ var init_agent_model_requirements = __esm(() => {variant: "max"},{- providers: ["opencode-go", "kimi-for-coding", "moonshotai", "opencode", "bailian-coding-plan", "moonshotai-cn", "firmware", "ollama-cloud", "aihubmix"],+ providers: ["opencode-go", "kimi-for-coding", "moonshotai", "moonshotai-cn"],model: LATEST_MODEL_BY_FAMILY.kimi},+ {+ providers: ["opencode", "bailian-coding-plan", "firmware", "ollama-cloud", "aihubmix"],+ model: LATEST_MODEL_BY_FAMILY.kimiK3+ },{providers: ["openai", "chatgpt-subscription", "github-copilot", "opencode"],model: "gpt-5.6-sol",@@ -9475,10 +9481,11 @@ var init_agent_model_requirements = __esm(() => {variant: "max"},{- providers: ["opencode-go", "kimi-for-coding", "moonshotai", "opencode"],+ providers: ["opencode-go", "kimi-for-coding", "moonshotai"],model: LATEST_MODEL_BY_FAMILY.kimi,variant: "max"- }+ },+ { providers: ["opencode"], model: LATEST_MODEL_BY_FAMILY.kimiK3, variant: "max" }])},metis: {@@ -9499,10 +9506,11 @@ var init_agent_model_requirements = __esm(() => {variant: "max"},{- providers: ["opencode-go", "kimi-for-coding", "moonshotai", "opencode"],+ providers: ["opencode-go", "kimi-for-coding", "moonshotai"],model: LATEST_MODEL_BY_FAMILY.kimi,variant: "max"- }+ },+ { providers: ["opencode"], model: LATEST_MODEL_BY_FAMILY.kimiK3, variant: "max" }])},momus: {@@ -9585,10 +9593,11 @@ var init_category_model_requirements = __esm(() => {variant: "max"},{- providers: ["kimi-for-coding", "moonshotai", "opencode-go", "opencode"],+ providers: ["kimi-for-coding", "moonshotai", "opencode-go"],model: LATEST_MODEL_BY_FAMILY.kimi,variant: "max"- }+ },+ { providers: ["opencode"], model: LATEST_MODEL_BY_FAMILY.kimiK3, variant: "max" }])},ultrabrain: {@@ -9640,10 +9649,11 @@ var init_category_model_requirements = __esm(() => {variant: "max"},{- providers: ["kimi-for-coding", "moonshotai", "opencode-go", "opencode"],+ providers: ["kimi-for-coding", "moonshotai", "opencode-go"],model: LATEST_MODEL_BY_FAMILY.kimi,variant: "max"- }+ },+ { providers: ["opencode"], model: LATEST_MODEL_BY_FAMILY.kimiK3, variant: "max" }])},quick: {@@ -9706,10 +9716,11 @@ var init_category_model_requirements = __esm(() => {},{ providers: ["zai-coding-plan", "opencode-go"], model: LATEST_MODEL_BY_FAMILY.glm, variant: "max" },{- providers: ["kimi-for-coding", "moonshotai", "opencode-go", "opencode"],+ providers: ["kimi-for-coding", "moonshotai", "opencode-go"],model: LATEST_MODEL_BY_FAMILY.kimi,variant: "max"- }+ },+ { providers: ["opencode"], model: LATEST_MODEL_BY_FAMILY.kimiK3, variant: "max" }]},writing: {@@ -10273,7 +10284,7 @@ function transformModelForProviderDisplay(provider, model) {var CLAUDE_VERSION_DOT, GEMINI_31_PRO_PREVIEW, GEMINI_3_FLASH_PREVIEW;var init_provider_model_id_transform = __esm(() => {CLAUDE_VERSION_DOT = /claude-(\w+)-(\d+)-(\d+)/g;- GEMINI_31_PRO_PREVIEW = /gemini-3\.1-pro(?!-)/g;+ GEMINI_31_PRO_PREVIEW = /(?<!antigravity-)gemini-3\.1-pro(?!-)/g;GEMINI_3_FLASH_PREVIEW = /(?<!antigravity-)gemini-3-flash(?!-)/g;});@@ -10347,6 +10358,36 @@ var init_supplemental_entries = __esm(() => {output: 262144}},+ "kimi-k3.1-pro": {+ id: "kimi-k3.1-pro",+ family: "kimi",+ reasoning: true,+ temperature: true,+ toolCall: true,+ modalities: {+ input: ["text", "image", "video"],+ output: ["text"]+ },+ limit: {+ context: 1048576,+ output: 1048576+ }+ },+ "kimi-k3.1-pro-highspeed": {+ id: "kimi-k3.1-pro-highspeed",+ family: "kimi",+ reasoning: true,+ temperature: true,+ toolCall: true,+ modalities: {+ input: ["text", "image", "video"],+ output: ["text"]+ },+ limit: {+ context: 1048576,+ output: 1048576+ }+ },"kimi-k2.6": {id: "kimi-k2.6",family: "kimi",@@ -12431,6 +12472,33 @@ function createJsonFileCacheStore(options) {});}}+ function writeIfChanged(value) {+ ensureCacheDir();+ const cacheFile = getCacheFilePath();+ const serialized = options.serialize?.(value) ?? JSON.stringify(value, null, 2);+ try {+ const existing = existsSync10(cacheFile) ? readFileSync3(cacheFile, "utf-8") : undefined;+ const unchanged = existing !== undefined && (existing === serialized || options.comparable !== undefined && JSON.stringify(options.comparable(JSON.parse(existing))) === JSON.stringify(options.comparable(value)));+ if (unchanged) {+ memoryValue = value;+ writtenInCurrentProcess = true;+ log2(`[${options.logPrefix}] ${options.cacheLabel} unchanged; skipped write`, options.describe(value));+ return false;+ }+ } catch {}+ try {+ writeFileSync4(cacheFile, serialized);+ memoryValue = value;+ writtenInCurrentProcess = true;+ log2(`[${options.logPrefix}] ${options.cacheLabel} written`, options.describe(value));+ return true;+ } catch (error) {+ log2(`[${options.logPrefix}] Error writing ${toLogLabel(options.cacheLabel)}`, {+ error: String(error)+ });+ return false;+ }+ }function resetMemory() {memoryValue = undefined;writtenInCurrentProcess = false;@@ -12439,6 +12507,7 @@ function createJsonFileCacheStore(options) {read,has,write,+ writeIfChanged,resetMemory};}@@ -67503,7 +67572,8 @@ function createModelCapabilitiesCacheStore(getCacheDir = getOmoOpenCodeCacheDir)generatedAt: snapshot.generatedAt}),serialize: (snapshot) => `${JSON.stringify(snapshot, null, 2)}-`+`,+ comparable: ({ generatedAt: _generatedAt, ...catalog }) => catalog});function readModelCapabilitiesCache() {return snapshotCacheStore.read();@@ -67516,7 +67586,7 @@ function createModelCapabilitiesCacheStore(getCacheDir = getOmoOpenCodeCacheDir)}async function refreshModelCapabilitiesCache(args = {}) {const snapshot = await fetchModelCapabilitiesSnapshot(args);- writeModelCapabilitiesCache(snapshot);+ snapshotCacheStore.writeIfChanged(snapshot);return snapshot;}return {@@ -77153,8 +77223,8 @@ var init_memory = __esm(() => {enabled: boolean2().optional()}).strict();OmoMemoryProjectionSchema = object({- max_entries_per_directory: number2().int().min(0).default(40),- max_bytes: number2().int().min(0).default(24576)+ max_entries_per_directory: number2().int().min(0).default(0),+ max_bytes: number2().int().min(0).default(40960)}).strict();OmoMemoryProjectionLayerSchema = object({max_entries_per_directory: number2().int().min(0).optional(),@@ -77218,7 +77288,7 @@ var init_memory = __esm(() => {query_expansion: false}),project_scope: OmoMemoryProjectScopeSchema.default({ nudge: true, recall: true }),- projection: OmoMemoryProjectionSchema.default({ max_entries_per_directory: 40, max_bytes: 24576 }),+ projection: OmoMemoryProjectionSchema.default({ max_entries_per_directory: 0, max_bytes: 40960 }),compile_warn_tokens: number2().int().positive().default(30000),agents: record(string2(), OmoMemoryAgentOverridesSchema).default({})}).strict();@@ -77266,6 +77336,21 @@ var init_model_catalog = __esm(() => {OmoModelCatalogLayerSchema = record(string2(), OmoModelCatalogEntryLayerSchema);});+// packages/omo-config-core/src/schema/model-pad.ts+var OmoModelPadLabelsSchema, OmoModelPadSchema;+var init_model_pad = __esm(() => {+ init_zod();+ OmoModelPadLabelsSchema = object({+ daily: string2().optional(),+ geeky: string2().optional(),+ normal: string2().optional(),+ heavy: string2().optional()+ }).strict();+ OmoModelPadSchema = object({+ labels: OmoModelPadLabelsSchema.optional()+ }).strict();+});+// packages/omo-config-core/src/schema/model-profile.tsfunction isRecord8(value) {return typeof value === "object" && value !== null && !Array.isArray(value);@@ -77586,6 +77671,7 @@ var init_config = __esm(() => {init_git_master();init_memory();init_model_catalog();+ init_model_pad();init_model_profile();init_side_panel();init_task();@@ -77607,6 +77693,7 @@ var init_config = __esm(() => {models: OmoModelCatalogLayerSchema.optional(),model_profiles: OmoModelProfilesLayerSchema.optional(),model_profile: string2().optional(),+ model_pad: OmoModelPadSchema.optional(),memory: OmoMemorySettingsLayerSchema.optional(),telemetry: OmoTelemetrySettingsLayerSchema.optional(),side_panel: OmoSidePanelSettingsLayerSchema.optional(),@@ -77625,6 +77712,7 @@ var init_config = __esm(() => {models: OmoModelCatalogLayerSchema.optional(),model_profiles: OmoModelProfilesLayerSchema.optional(),model_profile: string2().optional(),+ model_pad: OmoModelPadSchema.optional(),memory: OmoMemorySettingsLayerSchema.optional(),telemetry: OmoTelemetrySettingsLayerSchema.optional(),side_panel: OmoSidePanelSettingsLayerSchema.optional(),@@ -77648,6 +77736,7 @@ var init_config = __esm(() => {models: OmoModelCatalogSchema.optional(),model_profiles: OmoModelProfilesSchema.optional(),model_profile: string2().optional(),+ model_pad: OmoModelPadSchema.optional(),memory: OmoMemorySettingsSchema.optional(),telemetry: OmoTelemetrySettingsSchema.optional(),side_panel: OmoSidePanelSettingsSchema.optional(),@@ -77674,6 +77763,7 @@ var init_config = __esm(() => {models: OmoModelCatalogLayerSchema.optional(),model_profiles: OmoModelProfilesLayerSchema.optional(),model_profile: string2().optional(),+ model_pad: OmoModelPadSchema.optional(),memory: OmoMemorySettingsLayerSchema.optional(),telemetry: OmoTelemetrySettingsLayerSchema.optional(),side_panel: OmoSidePanelSettingsLayerSchema.optional(),@@ -77819,6 +77909,7 @@ var init_schema = __esm(() => {init_legacy_harness_names();init_memory();init_model_catalog();+ init_model_pad();init_model_profile();init_model_ref();init_provenance();@@ -82839,6 +82930,37 @@ function getDefaultTelemetryOsProvider() {}var init_machine_id = () => {};+// packages/telemetry-core/src/terminal-program.ts+function isKnownTerminalProgram(value) {+ return KNOWN_TERMINAL_PROGRAMS.some((known) => known === value);+}+function toTelemetryTerminalProgram(termProgram) {+ if (termProgram === undefined || termProgram === "")+ return;+ return isKnownTerminalProgram(termProgram) ? termProgram : "other";+}+var KNOWN_TERMINAL_PROGRAMS;+var init_terminal_program = __esm(() => {+ KNOWN_TERMINAL_PROGRAMS = [+ "Apple_Terminal",+ "iTerm.app",+ "vscode",+ "cursor",+ "windsurf",+ "zed",+ "WezTerm",+ "ghostty",+ "tmux",+ "Hyper",+ "WarpTerminal",+ "kitty",+ "alacritty",+ "Tabby",+ "rio",+ "mintty"+ ];+});+// packages/telemetry-core/src/injected-client.tsfunction isTelemetryClientEnabled(input) {const env = input.env ?? process.env;@@ -82941,12 +83063,16 @@ function getSharedProperties(input) {total_memory_gb: Math.round(osProvider.totalmem() / 1024 / 1024 / 1024),locale: Intl.DateTimeFormat().resolvedOptions().locale,timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,- shell: process.env.SHELL,+ shell: getShellName(process.env.SHELL),ci: Boolean(process.env.CI),- terminal: process.env.TERM_PROGRAM,+ terminal: toTelemetryTerminalProgram(process.env.TERM_PROGRAM),...input.product.additionalProperties};}+function getShellName(shellPath) {+ const name = shellPath?.split(/[\\/]/).pop()?.replace(/\.exe$/i, "");+ return name ? name : undefined;+}function getSafeCpuInfo(osProvider, input) {try {const cpuInfo = osProvider.cpus();@@ -82971,6 +83097,7 @@ var NO_OP_CLIENT;var init_injected_client = __esm(() => {init_env();init_machine_id();+ init_terminal_program();NO_OP_CLIENT = {enabled: false,trackActive: () => {@@ -92550,7 +92677,7 @@ var package_default2;var init_package2 = __esm(() => {package_default2 = {name: "@oh-my-opencode/omo-codex",- version: "5.1.51",+ version: "5.1.54",type: "module",private: true,description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",@@ -93758,11 +93885,22 @@ init_commander();// packages/omo-opencode/src/cli/install.tsinit_package();+// packages/omo-opencode/src/cli/cli-installer.ts+import { createInterface as createInterface2 } from "readline/promises";++// packages/telemetry-core/src/install-disclosure.ts+var TELEMETRY_PRIVACY_POLICY_URL = "https://github.com/code-yeongyu/oh-my-openagent/blob/dev/docs/legal/privacy-policy.md";+var TELEMETRY_INSTALL_DISCLOSURE_LINES = [+ "OmO sends anonymous usage telemetry (no prompts, code, file paths, or account data) to improve the product.",+ "The data goes to PostHog in the United States.",+ "Turn it off with DO_NOT_TRACK=1 (or OMO_DISABLE_TELEMETRY=1).",+ `Details: ${TELEMETRY_PRIVACY_POLICY_URL}`+];+// packages/omo-opencode/src/cli/cli-installer.tsinit_shared();init_config_manager();var import_picocolors3 = __toESM(require_picocolors(), 1);-import { createInterface as createInterface2 } from "readline/promises";// packages/omo-opencode/src/cli/install-validators.tsvar import_picocolors = __toESM(require_picocolors(), 1);@@ -99923,6 +100061,7 @@ var REQUIRED_PLUGIN_ARTIFACTS = [join66("extensions", "omo-thread-client.js"),join66("extensions", "omo-telemetry-recovery.js"),join66("extensions", "omo-feedback.js"),+ join66("extensions", "omo-desktop-toolkit.js"),join66("extensions", "omo-claim-receipt.js"),join66("extensions", "assets.generated.json"),join66("extensions", "omo-member.js"),@@ -101201,8 +101340,8 @@ async function runCliInstaller(args, version) {}console.log();}- printInfo("Anonymous telemetry is enabled by default. Disable it with OMO_SEND_ANONYMOUS_TELEMETRY=0 or OMO_DISABLE_POSTHOG=1.");- printInfo("Docs: docs/legal/privacy-policy.md and docs/legal/terms-of-service.md");+ for (const line of TELEMETRY_INSTALL_DISCLOSURE_LINES)+ printInfo(line);console.log();printBox(`${import_picocolors3.default.bold("Pro Tip:")} Include ${import_picocolors3.default.cyan("ultrawork")} (or ${import_picocolors3.default.cyan("ulw")}) in your prompt.` + `All features work like magic-parallel agents, background tasks,@@ -102498,7 +102637,7 @@ async function promptInstallConfig(detected, platform, codexAutonomousOverride)message: "Do you have a Kimi For Coding subscription?",options: [{ value: "no", label: "No", hint: "Will use other configured providers" },- { value: "yes", label: "Yes", hint: "Kimi K3 for Sisyphus/Prometheus fallback" }+ { value: "yes", label: "Yes", hint: "Kimi K3.1 Pro for Sisyphus/Prometheus fallback" }],initialValue: initial.kimiForCoding});@@ -102757,8 +102896,8 @@ async function runTuiInstaller(args, version) {if (config.hasOpenCode) {log4.message(`Run ${import_picocolors4.default.cyan("opencode")} to start!`);}- log4.info("Anonymous telemetry is enabled by default. Disable it with OMO_SEND_ANONYMOUS_TELEMETRY=0 or OMO_DISABLE_POSTHOG=1.");- log4.info("Docs: docs/legal/privacy-policy.md and docs/legal/terms-of-service.md");+ log4.info(TELEMETRY_INSTALL_DISCLOSURE_LINES.join(`+`));note(`Include ${import_picocolors4.default.cyan("ultrawork")} (or ${import_picocolors4.default.cyan("ulw")}) in your prompt.` + `All features work like magic-parallel agents, background tasks,` + `deep exploration, and relentless execution until completion.`, "The Magic Word");@@ -109295,6 +109434,8 @@ var package_default3 = {},dependencies: {"@clack/prompts": "^1.8.1",+ "@code-yeongyu/senpi": "2026.10.30-1",+ "@earendil-works/pi-ai": "npm:@code-yeongyu/[email protected]","@modelcontextprotocol/sdk": "^1.30.0","@oh-my-opencode/agents-md-core": "workspace:*","@oh-my-opencode/boulder-state": "workspace:*",@@ -110603,6 +110744,8 @@ function isOAuthTokenData(value) {if (typeof value !== "object" || value === null || Array.isArray(value))return false;const record = value;+ if (record["issuer"] !== undefined && typeof record["issuer"] !== "string")+ return false;if (typeof record["accessToken"] !== "string")return false;const refreshToken = record["refreshToken"];@@ -110617,6 +110760,8 @@ function isOAuthTokenData(value) {if (typeof clientInfo !== "object" || clientInfo === null || Array.isArray(clientInfo))return false;const clientRecord = clientInfo;+ if (clientRecord["issuer"] !== undefined && typeof clientRecord["issuer"] !== "string")+ return false;if (typeof clientRecord["clientId"] !== "string")return false;const clientSecret = clientRecord["clientSecret"];@@ -110685,7 +110830,9 @@ function deleteToken(serverHost, resource) {return deleteLegacyToken(serverHost, resource);try {unlinkSync9(filePath);- return deleteTokenIndexEntry(getMcpOauthStorageDir(), getMcpOauthServerHash(serverHost, resource));+ const indexDeleted = deleteTokenIndexEntry(getMcpOauthStorageDir(), getMcpOauthServerHash(serverHost, resource));+ const legacyDeleted = deleteLegacyToken(serverHost, resource);+ return indexDeleted && legacyDeleted;} catch (deleteError) {if (!(deleteError instanceof Error))throw deleteError;@@ -110795,19 +110942,26 @@ async function fetchMetadata(url) {}return { ok: true, json };}-function parseMetadataFields(json, resource) {+function parseMetadataFields(json, resource, expectedIssuer) {+ const issuer = readStringField(json, "issuer");+ parseHttpsUrl(issuer, "issuer");+ if (issuer !== expectedIssuer) {+ throw new Error("OAuth metadata issuer mismatch");+ }const authorizationEndpoint = parseHttpsUrl(readStringField(json, "authorization_endpoint"), "authorization_endpoint").toString();const tokenEndpoint = parseHttpsUrl(readStringField(json, "token_endpoint"), "token_endpoint").toString();const registrationEndpointValue = json.registration_endpoint;const registrationEndpoint = typeof registrationEndpointValue === "string" && registrationEndpointValue.length > 0 ? parseHttpsUrl(registrationEndpointValue, "registration_endpoint").toString() : undefined;return {+ issuer,+ ...json.authorization_response_iss_parameter_supported === true ? { authorizationResponseIssParameterSupported: true } : {},authorizationEndpoint,tokenEndpoint,registrationEndpoint,resource};}-async function fetchAuthorizationServerMetadata(issuer, resource) {+async function fetchAuthorizationServerMetadata(issuer, resource, allowOriginFallback = false) {const issuerUrl = parseHttpsUrl(issuer, "Authorization server URL");const issuerPath = issuerUrl.pathname.replace(/\/+$/, "");const metadataUrl = new URL(`/.well-known/oauth-authorization-server${issuerPath}`, issuerUrl).toString();@@ -110817,7 +110971,7 @@ async function fetchAuthorizationServerMetadata(issuer, resource) {const rootMetadataUrl = new URL("/.well-known/oauth-authorization-server", issuerUrl).toString();const rootMetadata = await fetchMetadata(rootMetadataUrl);if (rootMetadata.ok) {- return parseMetadataFields(rootMetadata.json, resource);+ return parseMetadataFields(rootMetadata.json, resource, allowOriginFallback ? issuerUrl.origin : issuer);}}if (metadata.status === 404) {@@ -110825,7 +110979,7 @@ async function fetchAuthorizationServerMetadata(issuer, resource) {}throw new Error(`OAuth authorization server metadata fetch failed (${metadata.status})`);}- return parseMetadataFields(metadata.json, resource);+ return parseMetadataFields(metadata.json, resource, issuer);}function parseAuthorizationServers(metadata) {const servers = metadata.authorization_servers;@@ -110833,11 +110987,11 @@ function parseAuthorizationServers(metadata) {return [];return servers.filter((server) => typeof server === "string" && server.length > 0);}-async function discoverOAuthServerMetadata(resource) {+async function discoverOAuthServerMetadata(resource, forceRefresh = false) {const resourceUrl = parseHttpsUrl(resource, "Resource server URL");const resourceKey = resourceUrl.toString();const cached = discoveryCache.get(resourceKey);- if (cached)+ if (cached && !forceRefresh)return cached;const pending = pendingDiscovery.get(resourceKey);if (pending)@@ -110855,7 +111009,7 @@ async function discoverOAuthServerMetadata(resource) {if (prmResponse.status !== 404) {throw new Error(`OAuth protected resource metadata fetch failed (${prmResponse.status})`);}- return fetchAuthorizationServerMetadata(resourceKey, resource);+ return fetchAuthorizationServerMetadata(resource.replace(/\/+$/, ""), resource, true);})();pendingDiscovery.set(resourceKey, discoveryPromise);try {@@ -110879,6 +111033,10 @@ async function getOrRegisterClient(options) {}const fetchImpl = options.fetch ?? globalThis.fetch;const request = {+ application_type: options.redirectUris.some((uri) => {+ const url = new URL(uri);+ return (url.protocol === "http:" || url.protocol === "https:") && !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);+ }) ? "web" : "native",redirect_uris: options.redirectUris,client_name: options.clientName,grant_types: ["authorization_code", "refresh_token"],@@ -110955,12 +111113,20 @@ function buildAuthorizationUrl(authorizationEndpoint, options) {return url.toString();}var CALLBACK_TIMEOUT_MS = 5 * 60 * 1000;-function startCallbackServer(port) {+function startCallbackServer(port, validation) {return new Promise((resolve, reject) => {let timeoutId;const server = createServer2((request, response) => {clearTimeout(timeoutId);const requestUrl = new URL(request.url ?? "/", `http://localhost:${port}`);+ const issuer = requestUrl.searchParams.get("iss");+ if (validation && (issuer !== null && issuer !== validation.issuer || issuer === null && validation.authorizationResponseIssParameterSupported)) {+ response.writeHead(400, { "content-type": "text/html" });+ response.end("<html><body><h1>Authorization failed</h1></body></html>");+ server.close();+ reject(new Error("OAuth authorization response issuer mismatch or missing issuer"));+ return;+ }const code = requestUrl.searchParams.get("code");const state = requestUrl.searchParams.get("state");const error = requestUrl.searchParams.get("error");@@ -111030,7 +111196,7 @@ async function runAuthorizationCodeRedirect(options) {scopes: options.scopes,resource: options.resource});- const callbackPromise = startCallbackServer(options.callbackPort);+ const callbackPromise = startCallbackServer(options.callbackPort, options);openBrowser(authorizationUrl);const result = await callbackPromise;if (result.state !== state) {@@ -111065,10 +111231,12 @@ function buildOAuthTokenData(tokenData, clientInfo, fallbackRefreshToken) {throw new Error("Token response missing access_token");}return {+ ...clientInfo.issuer ? { issuer: clientInfo.issuer } : {},accessToken,refreshToken: typeof tokenData["refresh_token"] === "string" ? tokenData["refresh_token"] : fallbackRefreshToken,expiresAt: typeof tokenData["expires_in"] === "number" ? Math.floor(Date.now() / 1000) + tokenData["expires_in"] : undefined,clientInfo: {+ ...clientInfo.issuer ? { issuer: clientInfo.issuer } : {},clientId: clientInfo.clientId,...clientInfo.clientSecret ? { clientSecret: clientInfo.clientSecret } : {}}@@ -111082,6 +111250,7 @@ class McpOAuthProvider {storedCodeVerifier = null;storedClientInfo = null;callbackPort = null;+ issuer;constructor(options) {this.serverUrl = options.serverUrl;this.configClientId = options.clientId;@@ -111091,7 +111260,32 @@ class McpOAuthProvider {return loadToken(this.serverUrl, this.serverUrl);}saveTokens(tokenData) {- return saveToken(this.serverUrl, this.serverUrl, tokenData);+ const issuer = tokenData.issuer ?? this.issuer;+ return saveToken(this.serverUrl, this.serverUrl, issuer ? {+ ...tokenData,+ issuer,+ ...tokenData.clientInfo ? { clientInfo: { ...tokenData.clientInfo, issuer: tokenData.clientInfo.issuer ?? issuer } } : {}+ } : tokenData);+ }+ bindIssuer(issuer) {+ const token = this.tokens();+ const stamps = [token?.issuer, token?.clientInfo?.issuer, this.storedClientInfo?.issuer, this.issuer];+ const changed = stamps.some((stamp) => stamp !== undefined && stamp !== issuer);+ if (changed) {+ this.storedClientInfo = null;+ this.storedCodeVerifier = null;+ if (!deleteToken(this.serverUrl, this.serverUrl)) {+ throw new Error("Unable to discard credentials for the previous OAuth issuer");+ }+ }+ this.issuer = issuer;+ if (!changed && token && !this.saveTokens(token)) {+ throw new Error("Unable to stamp stored OAuth credentials with their issuer");+ }+ const clientInfo = this.clientInformation();+ if (clientInfo)+ this.storedClientInfo = { ...clientInfo, issuer };+ return changed;}clientInformation() {if (this.storedClientInfo)@@ -111121,6 +111315,8 @@ class McpOAuthProvider {this.callbackPort = await findAvailablePort2();}const result = await runAuthorizationCodeRedirect({+ issuer: metadata.issuer,+ authorizationResponseIssParameterSupported: metadata.authorizationResponseIssParameterSupported,authorizationEndpoint: metadata.authorizationEndpoint,callbackPort: this.callbackPort,clientId: clientInfo.clientId,@@ -111132,16 +111328,19 @@ class McpOAuthProvider {return { code: result.code };}async login() {- const metadata = await discoverOAuthServerMetadata(this.serverUrl);+ const metadata = await discoverOAuthServerMetadata(this.serverUrl, true);+ this.bindIssuer(metadata.issuer);+ if (this.callbackPort === null)+ this.callbackPort = await findAvailablePort2();const clientRegistrationStorage = {getClientRegistration: () => this.storedClientInfo,setClientRegistration: (_serverIdentifier, credentials) => {- this.storedClientInfo = credentials;+ this.storedClientInfo = { ...credentials, issuer: metadata.issuer };}};const clientInfo = await getOrRegisterClient({...metadata.registrationEndpoint ? { registrationEndpoint: metadata.registrationEndpoint } : {},- serverIdentifier: this.serverUrl,+ serverIdentifier: metadata.issuer,clientName: PLUGIN_NAME4,redirectUris: [this.redirectUrl()],tokenEndpointAuthMethod: "none",@@ -111151,7 +111350,7 @@ class McpOAuthProvider {if (!clientInfo) {throw new Error("Failed to obtain client credentials. Provide a clientId or ensure the server supports DCR.");}- this.storedClientInfo = clientInfo;+ this.storedClientInfo = { ...clientInfo, issuer: metadata.issuer };const { code } = await this.redirectToAuthorization(metadata);const verifier = this.codeVerifier();if (!verifier) {@@ -111170,12 +111369,14 @@ class McpOAuthProvider {}).toString()});const tokenData = await parseTokenResponse(tokenResponse);- const oauthTokenData = buildOAuthTokenData(tokenData, clientInfo);+ const oauthTokenData = buildOAuthTokenData(tokenData, { ...clientInfo, issuer: metadata.issuer });this.saveTokens(oauthTokenData);return oauthTokenData;}async refresh(refreshToken) {- const metadata = await discoverOAuthServerMetadata(this.serverUrl);+ const metadata = await discoverOAuthServerMetadata(this.serverUrl, true);+ if (this.bindIssuer(metadata.issuer))+ return this.login();const clientInfo = this.clientInformation();const clientId = clientInfo?.clientId ?? this.configClientId;if (!clientId) {@@ -111195,6 +111396,7 @@ class McpOAuthProvider {const tokenData = await parseTokenResponse(tokenResponse);const oauthTokenData = buildOAuthTokenData(tokenData, {clientId,+ issuer: metadata.issuer,...clientInfo?.clientSecret ? { clientSecret: clientInfo.clientSecret } : {}}, refreshToken);this.saveTokens(oauthTokenData);@@ -112042,6 +112244,17 @@ import { hostname } from "os";// packages/omo-opencode/src/cli/service-auth/protocol.tsinit_zod();+// packages/omo-opencode/src/cli/service-auth/credential-owner.ts+init_zod();+var identity = string2().regex(/^[A-Za-z0-9_-]{1,128}$/);+var credentialOwnerSchema = object({+ accountId: identity,+ deviceId: identity,+ familyId: identity,+ generation: number2().int().positive().safe(),+ ownerHandle: string2().regex(/^[\x21-\x7e]{1,4096}$/)+});+// packages/omo-opencode/src/cli/service-auth/terminal-text.tsimport { stripVTControlCharacters as stripVTControlCharacters4 } from "util";function terminalText(value) {@@ -112060,9 +112273,19 @@ class SignInError extends Error {class RequestFailure extends SignInError {notSent;- constructor(notSent) {+ responseStatus;+ constructor(notSent, responseStatus) {super("Unable to complete the service request. Check the connection and retry.", true);this.notSent = notSent;+ this.responseStatus = responseStatus;+ }+}++class InvalidApiResponse extends SignInError {+ status;+ constructor(status) {+ super("The service returned an invalid error response.");+ this.status = status;}}var platformSchema = _enum(["macos", "linux", "windows"]);@@ -112075,12 +112298,18 @@ var tokenSchema = object({});var grantSchema = tokenSchema.extend({device: object({ id: nonempty, name: nonempty }),- offlineGrant: nonempty.optional()+ offlineGrant: nonempty.optional(),+ owner: credentialOwnerSchema.optional(),+ writerFloor: union([literal(1), literal(2)]).optional(),+ freshAuthorizationProof: nonempty.optional()});var credentialSchema = grantSchema.extend({signingPrivateKey: nonempty,sealingPrivateKey: nonempty,- refreshState: literal("uncertain").optional()+ refreshState: literal("uncertain").optional(),+ credentialGeneration: nonempty.optional(),+ accountId: nonempty.optional(),+ refreshAttempt: unknown().optional()});var deviceCodeSchema = object({deviceCode: string2().regex(/^dc\.[A-Za-z0-9_-]{43}$/),@@ -112108,6 +112337,9 @@ var limitSchema = object({var deviceListSchema = object({devices: array(object({ id: nonempty, name: nonempty, revokedAt: timestamp.nullable() }))});+var currentDeviceListSchema = object({+ devices: array(object({ id: nonempty, current: boolean2(), revokedAt: timestamp.nullable() }))+});var REFUSAL_CODES = ["unauthorized","account_deleted",@@ -112124,7 +112356,11 @@ var REFUSAL_CODES = ["unavailable","forbidden","invalid_request",- "not_found"+ "not_found",+ "client_upgrade_required",+ "writer_floor_mismatch",+ "service_upgrade_required",+ "refresh_recovery_expired"];var isKnownRefusal = (code) => REFUSAL_CODES.includes(code);function refusalGuidance(code, status) {@@ -112151,6 +112387,10 @@ function refusalGuidance(code, status) {case "access_denied":case "authorization_pending":return "account_refused";+ case "client_upgrade_required":+ case "writer_floor_mismatch":+ case "service_upgrade_required":+ case "refresh_recovery_expired":case "unknown":if (status === 401)return "sign_in_again";@@ -112261,13 +112501,13 @@ async function requestApi(api, path, init, signal) {try {body = await response.json();} catch {- throw new RequestFailure(false);+ throw new RequestFailure(false, response.status);}if (response.ok)return body;const envelope = envelopeSchema.safeParse(body);if (!envelope.success)- throw new SignInError("The service returned an invalid error response.");+ throw new InvalidApiResponse(response.status);const error = envelope.data.error;const detail = limitSchema.safeParse(error.detail);throw new ApiRefusal(error.code, response.status, error.code === "entitlement_required" && detail.success ? detail.data : undefined, response.headers.get("retry-after"));@@ -112371,7 +112611,7 @@ async function loginDevice(session, options) {}// packages/omo-opencode/src/cli/service-auth/keystore.ts-import { createHash as createHash10 } from "crypto";+import { createHash as createHash12, randomUUID as randomUUID7 } from "crypto";import { basename as basename15 } from "path";// packages/omo-opencode/src/cli/service-auth/secret-service-lock.ts@@ -112415,289 +112655,490 @@ var probeSecretServiceLock = () => new Promise((resolve) => {});});-// packages/omo-opencode/src/cli/service-auth/keystore.ts-class CredentialStoreError extends SignInError {-}+// packages/omo-opencode/src/cli/service-auth/credential-lock.ts+import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";+import { createHash as createHash11 } from "crypto";+import { mkdir as mkdir11 } from "fs/promises";+import { homedir as homedir31 } from "os";+import { join as join106 } from "path";-class KeychainLockedError extends CredentialStoreError {+// packages/team-core/src/team-state-store/lock-publish.ts+import { access as access4, open as open3, unlink as unlink3 } from "fs/promises";+import { dirname as dirname42 } from "path";++// packages/team-core/src/team-state-store/lock-record.ts+import { randomUUID as randomUUID6 } from "crypto";+import { readFile as readFile34, stat as stat9 } from "fs/promises";++// packages/memory-core/src/locks/process-identity.ts+import { execFile as execFile7 } from "child_process";++// packages/memory-core/src/fs/resilient.ts+import * as fsSync from "fs";+import * as fsp from "fs/promises";++// packages/memory-core/src/fs/retry.ts+var EINTR_RETRY_CAP = 128;+function fsErrorCode(error) {+ if (!(error instanceof Error) || !("code" in error))+ return;+ return typeof error.code === "string" ? error.code : undefined;}-class InvalidCredentialState extends SignInError {+async function retryOnEintr(operation) {+ for (let attempt = 0;; attempt += 1) {+ try {+ return await operation();+ } catch (error) {+ if (fsErrorCode(error) !== "EINTR" || attempt >= EINTR_RETRY_CAP)+ throw error;+ }+ }+}+function retryOnEintrSync(operation) {+ for (let attempt = 0;; attempt += 1) {+ try {+ return operation();+ } catch (error) {+ if (fsErrorCode(error) !== "EINTR" || attempt >= EINTR_RETRY_CAP)+ throw error;+ }+ }}-class KeychainApprovalPendingError extends CredentialStoreError {+// packages/memory-core/src/fs/rename-contention.ts+var CONTENTION_CODES = new Set(["EPERM", "EBUSY", "EACCES"]);++// packages/memory-core/src/fs/resilient.ts+function isFunction2(value) {+ return typeof value === "function";}-var SESSION_READ_WAIT = { kind: "bounded", deadlineMs: 5000 };-var INTERACTIVE_READ_WAIT = {- kind: "interactive",- noticeAfterMs: 2000,- notice: (message) => process.stderr.write(`${message}-`)-};-var processReads = new WeakMap;-var LOCKED = /-25308|errSecInteractionNotAllowed|interaction is not allowed|locked collection/i;-var UNLOCKED_REUSE_MS = 30000;-var fallbackNoticed = false;-var stderrNoticeOncePerProcess = (message) => {- if (fallbackNoticed)+function withAsyncRetry(operation) {+ return (...args) => retryOnEintr(async () => operation(...args));+}+function withSyncRetry(operation) {+ return (...args) => retryOnEintrSync(() => operation(...args));+}+function resilientNamespace(namespace, kind) {+ const wrapFunction = kind === "async" ? withAsyncRetry : withSyncRetry;+ const cache = new Map;+ return new Proxy(namespace, {+ get(target, property) {+ if (cache.has(property))+ return cache.get(property);+ const value = Reflect.get(target, property);+ if (!isFunction2(value))+ return value;+ const wrapped = wrapFunction(value);+ const native = Reflect.get(value, "native");+ if (isFunction2(native))+ Object.assign(wrapped, { native: wrapFunction(native) });+ cache.set(property, wrapped);+ return wrapped;+ }+ });+}+var IDEMPOTENT_HANDLE_METHODS = new Set(["stat", "sync", "datasync", "chmod", "chown", "utimes", "truncate"]);+var promises = resilientNamespace(fsp, "async");+var sync = resilientNamespace(fsSync, "sync");+var {+ access: access3,+ chmod: chmod2,+ copyFile: copyFile4,+ cp: cp5,+ link,+ lstat: lstat18,+ mkdir: mkdir10,+ mkdtemp: mkdtemp2,+ readFile: readFile33,+ readdir: readdir17,+ readlink: readlink7,+ realpath: realpath2,+ rm: rm16,+ rmdir: rmdir2,+ stat: stat8,+ statfs,+ unlink: unlink2+} = promises;+var {+ accessSync: accessSync5,+ chmodSync: chmodSync7,+ fsyncSync: fsyncSync3,+ linkSync,+ lstatSync: lstatSync5,+ mkdirSync: mkdirSync19,+ readFileSync: readFileSync44,+ readdirSync: readdirSync14,+ realpathSync: realpathSync13,+ statSync: statSync8,+ unlinkSync: unlinkSync10,+ writeFileSync: writeFileSync17,+ writeSync+} = sync;++// packages/memory-core/src/locks/process-start-time.ts+var PROC_PIDTBSDINFO = 3;+var PROC_BSDINFO_SIZE = 136;+var START_TVSEC_OFFSET = 120;+var procPidInfoLookup = null;+async function openProcPidInfo() {+ if (process.platform !== "darwin")+ return null;+ try {+ const { dlopen, FFIType } = await import("bun:ffi");+ const library = dlopen("/usr/lib/libSystem.B.dylib", {+ proc_pidinfo: {+ args: [FFIType.i32, FFIType.i32, FFIType.u64, FFIType.ptr, FFIType.i32],+ returns: FFIType.i32+ }+ });+ return (pid, flavor, arg, buffer, size) => Number(library.symbols.proc_pidinfo(pid, flavor, arg, buffer, size));+ } catch {+ return null;+ }+}+function loadProcPidInfo() {+ procPidInfoLookup ??= openProcPidInfo();+ return procPidInfoLookup;+}+async function readDarwinProcessStartSeconds(pid) {+ if (process.platform !== "darwin")+ return null;+ if (!Number.isSafeInteger(pid) || pid <= 0)+ return null;+ const procPidInfo = await loadProcPidInfo();+ if (procPidInfo === null)+ return null;+ const buffer = new Uint8Array(PROC_BSDINFO_SIZE);+ let written = 0;+ try {+ written = procPidInfo(pid, PROC_PIDTBSDINFO, 0n, buffer, PROC_BSDINFO_SIZE);+ } catch {+ return null;+ }+ if (written !== PROC_BSDINFO_SIZE)+ return null;+ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);+ const startSeconds = Number(view.getBigUint64(START_TVSEC_OFFSET, true));+ return startSeconds > 0 ? startSeconds : null;+}+var PROCESS_QUERY_LIMITED_INFORMATION = 4096;+var kernel32Lookup = null;+async function openKernel32() {+ if (process.platform !== "win32")+ return null;+ try {+ const { dlopen, FFIType } = await import("bun:ffi");+ const library = dlopen("kernel32.dll", {+ OpenProcess: { args: [FFIType.u32, FFIType.i32, FFIType.u32], returns: FFIType.ptr },+ GetProcessTimes: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 },+ CloseHandle: { args: [FFIType.ptr], returns: FFIType.i32 }+ });+ return library.symbols;+ } catch {+ return null;+ }+}+async function readWin32ProcessCreationFiletime(pid) {+ if (process.platform !== "win32")+ return null;+ if (!Number.isSafeInteger(pid) || pid <= 0)+ return null;+ kernel32Lookup ??= openKernel32();+ const kernel32 = await kernel32Lookup;+ if (kernel32 === null)+ return null;+ const handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);+ if (handle === null || handle === 0 || handle === 0n)+ return null;+ try {+ const creation = new BigUint64Array(1);+ const ok = kernel32.GetProcessTimes(handle, creation, new BigUint64Array(1), new BigUint64Array(1), new BigUint64Array(1));+ const filetime = creation[0] ?? 0n;+ return ok === 0 || filetime === 0n ? null : filetime;+ } finally {+ kernel32.CloseHandle(handle);+ }+}++// packages/memory-core/src/locks/process-identity.ts+function errorCode(error) {+ if (!(error instanceof Error) || !("code" in error))return;- fallbackNoticed = true;- process.stderr.write(`${message}-`);-};-var isLocked = (error) => error instanceof Error && (LOCKED.test(error.message) || LOCKED.test(String(error.code ?? "")));-function credentialId(api) {- return createHash10("sha256").update(serviceOrigin(api)).digest("hex");+ return typeof error.code === "string" ? error.code : undefined;}-function createCredentialStore(api, options = {}) {- return createSealedStore(api, "omo-cli", credentialSchema, options.secrets, options.platform, options.lockProbe, options.notice, options.wait);+async function execFileText(command, args) {+ return await new Promise((resolve) => {+ execFile7(command, args, { encoding: "utf8", timeout: 2000, windowsHide: true }, (error, stdout) => {+ if (error !== null) {+ resolve(null);+ return;+ }+ const value = stdout.trim();+ resolve(value.length > 0 ? value : null);+ });+ });}-function createSealedStore(api, namespace, schema, secrets = typeof Bun === "undefined" ? null : Bun.secrets, platform = process.platform, lockProbe = probeSecretServiceLock, notice = stderrNoticeOncePerProcess, wait = SESSION_READ_WAIT) {- if (!secrets)- throw new SignInError("OmO sign-in needs Bun 1.4 or newer with OS credential storage. No file fallback is available.");- const platformName = platform === "darwin" ? "macOS Keychain" : platform === "linux" ? "Linux Secret Service (libsecret and an unlocked keyring)" : platform === "win32" ? "Windows Credential Manager" : null;- if (platformName === null)- throw new SignInError("This platform has no supported OS credential store.");- const key = { service: namespace, name: credentialId(api) };- const slot = `${key.service}-${key.name}`;- const readsOf = (api) => {- const known = processReads.get(api);- if (known !== undefined)- return known;- const created = new Map;- processReads.set(api, created);- return created;- };- const forget = (api) => {- readsOf(api).delete(slot);- };- const sharedRead = (api) => {- const reads = readsOf(api);- const pending = reads.get(slot);- if (pending !== undefined)- return pending;- const read = Promise.resolve().then(() => api.get(key));- const done = () => {- if (reads.get(slot) === read)- reads.delete(slot);- };- read.then(done, done);- reads.set(slot, read);- return read;+async function readLinuxStartIdentity(pid) {+ try {+ const stat = await readFile33(`/proc/${pid}/stat`, "utf8");+ const commandEnd = stat.lastIndexOf(")");+ if (commandEnd < 0)+ return null;+ const fieldsAfterCommand = stat.slice(commandEnd + 2).trim().split(/\s+/);+ const startTicks = fieldsAfterCommand[19];+ return startTicks === undefined ? null : `linux-proc-start-ticks:${startTicks}`;+ } catch {+ return null;+ }+}+async function readWin32StartIdentity(pid) {+ if (getPidLiveness(pid) === "dead")+ return null;+ const creationFiletime = await readWin32ProcessCreationFiletime(pid);+ if (creationFiletime !== null)+ return `win32-creation-filetime:${creationFiletime}`;+ const value = await execFileText("powershell.exe", [+ "-NoProfile",+ "-Command",+ `(Get-Process -Id ${pid} -ErrorAction SilentlyContinue).StartTime.ToUniversalTime().ToString('o')`+ ]);+ return value === null ? null : `win32-creation-date:${value}`;+}+function createProcessStartIdentityReader(read, ownPid) {+ let ownIdentity;+ return (pid) => {+ if (pid !== ownPid)+ return read(pid);+ ownIdentity ??= read(pid).then((identity) => {+ if (identity === null)+ ownIdentity = undefined;+ return identity;+ }, (error) => {+ ownIdentity = undefined;+ throw error;+ });+ return ownIdentity;};- const waiting = platform === "darwin" ? `macOS Keychain is waiting for your approval: answer the "${basename15(process.execPath)} wants to access key ${namespace}" dialog ("Always Allow" stops it asking again)` : `${platformName} has not answered; it may be waiting for your approval or an unlock in a system dialog`;- const answered = async (api) => {- const read = sharedRead(api);- let timer;- try {- if (wait.kind === "interactive") {- timer = setTimeout(() => wait.notice(`omo: ${waiting}.`), wait.noticeAfterMs);- return await read;- }- const expired = new Promise((_, reject) => {- timer = setTimeout(() => reject(new KeychainApprovalPendingError(`${waiting}, then try again. Credentials are never saved to a file.`)), wait.deadlineMs);- });- return await Promise.race([read, expired]);- } finally {- clearTimeout(timer);- }+}+var getProcessStartIdentity = createProcessStartIdentityReader(readProcessStartIdentity, process.pid);+async function readProcessStartIdentity(pid) {+ if (process.platform === "linux")+ return await readLinuxStartIdentity(pid);+ if (process.platform === "darwin" || process.platform === "freebsd") {+ if (getPidLiveness(pid) === "dead")+ return null;+ const startSeconds = await readDarwinProcessStartSeconds(pid);+ if (startSeconds !== null)+ return `proc-start-epoch:${startSeconds}`;+ const value = await execFileText("/bin/ps", ["-o", "lstart=", "-p", String(pid)]);+ return value === null ? null : `ps-lstart:${value.replace(/\s+/g, " ")}`;+ }+ if (process.platform === "win32")+ return await readWin32StartIdentity(pid);+ return null;+}+function identityScheme(identity) {+ const separator = identity.indexOf(":");+ return separator <= 0 ? null : identity.slice(0, separator);+}+function startIdentitiesConflict(recorded, actual) {+ const recordedScheme = identityScheme(recorded);+ if (recordedScheme === null || recordedScheme !== identityScheme(actual))+ return false;+ return recorded !== actual;+}+function getPidLiveness(pid) {+ try {+ process.kill(pid, 0);+ return "alive";+ } catch (error) {+ const code = errorCode(error);+ if (code === "ESRCH")+ return "dead";+ if (code === "EPERM")+ return "alive";+ return "unknown";+ }+}++// packages/team-core/src/team-state-store/lock-worker-lifetime.ts+init_zod();+import { randomUUID as randomUUID5 } from "crypto";+import { BroadcastChannel, parentPort, threadId } from "worker_threads";+var Registration = object({+ kind: literal("omo-team-lock-register-v1"),+ incarnation: string2(),+ challenge: string2()+});+var Message = discriminatedUnion("kind", [+ object({ kind: literal("query"), id: string2(), incarnation: string2(), record: string2() }),+ object({ kind: literal("answer"), id: string2(), released: boolean2() }),+ object({ kind: literal("hello"), threadId: number2() }),+ object({ kind: literal("register"), threadId: number2(), challenge: string2() })+]);+function createState() {+ const channel = new BroadcastChannel(`omo-team-lock-lifetime-v1-${process.pid}`);+ channel.unref();+ const state = {+ incarnation: randomUUID5(),+ records: new Map,+ exited: new Set,+ observed: new WeakSet,+ observing: new Map,+ pending: new Map,+ channel,+ installed: false,+ registered: parentPort === null,+ registration: undefined,+ onRegistered: undefined};- const unavailable = (error) => isLocked(error) ? new KeychainLockedError(`${platformName} is locked. Unlock it, then try again. Credentials are never saved to a file.`) : new CredentialStoreError(`Cannot access ${platformName}. Unlock or enable the OS credential store and try again. Credentials are never saved to a file.`);- let unlockedUntil = 0;- let noticed = false;- const assertUsable = async () => {- if (platform !== "linux" || Date.now() < unlockedUntil)- return;- const lock = await lockProbe();- if (lock === "locked")- throw new KeychainLockedError(`${platformName} is locked. Unlock it, then try again. Credentials are never saved to a file.`);- if (lock === "unlocked") {- unlockedUntil = Date.now() + UNLOCKED_REUSE_MS;+ channel.onmessage = (event) => {+ const parsed = Message.safeParse(event.data);+ if (!parsed.success)return;- }- if (!noticed) {- noticed = true;- notice("omo: could not check whether the keyring is locked (gdbus or the Secret Service did not answer); using libsecret directly.");- }- };- return {- async read() {- await assertUsable();- let value;- try {- value = await answered(secrets);- } catch (error) {- if (error instanceof KeychainApprovalPendingError)- throw error;- throw unavailable(error);- }- if (value === null)- return null;- try {- return schema.parse(JSON.parse(value));- } catch {- throw new InvalidCredentialState(signInRoute() === "cli" ? "Stored sign-in data is invalid. Run omo logout, then omo login." : "The OmO sign-in saved on this computer can't be read, and it can't be reset from the terminal yet.");+ const message = parsed.data;+ switch (message.kind) {+ case "hello": {+ const observed = state.observing.get(message.threadId);+ if (observed !== undefined) {+ channel.postMessage({ kind: "register", threadId: message.threadId, challenge: observed.challenge });+ }+ return;}- },- async write(value) {- await assertUsable();- try {- await secrets.set({ ...key, value: JSON.stringify(schema.parse(value)) });- } catch (error) {- throw unavailable(error);+ case "register":+ if (message.threadId === threadId) {+ parentPort?.postMessage({+ kind: "omo-team-lock-register-v1",+ incarnation: state.incarnation,+ challenge: message.challenge+ });+ state.registered = true;+ state.onRegistered?.();+ }+ return;+ case "answer":+ state.pending.get(message.id)?.(message.released);+ return;+ case "query": {+ const status = message.incarnation === state.incarnation ? state.records.get(message.record) : undefined;+ if (status !== undefined || state.exited.has(message.incarnation)) {+ channel.postMessage({+ kind: "answer",+ id: message.id,+ released: status === "released" || state.exited.has(message.incarnation)+ });+ }+ return;}- forget(secrets);- },- async clear() {- await assertUsable();- try {- await secrets.delete(key);- } catch (error) {- throw unavailable(error);+ default: {+ const unexpected = message;+ throw new Error(`Unexpected lock lifetime message: ${unexpected}`);}- forget(secrets);}};+ return state;}--// packages/omo-opencode/src/cli/service-auth/loopback.ts-import { createHash as createHash11, randomBytes as randomBytes5, timingSafeEqual } from "crypto";-import { createServer as createServer3 } from "http";-class BrowserUnavailable extends SignInError {-}-async function authorize(options) {- const verifier = randomBytes5(32).toString("base64url");- const state = randomBytes5(32).toString("base64url");- const answer = Promise.withResolvers();- const abort = () => answer.reject(new SignInError("Browser sign-in cancelled or timed out."));- let accepted = false;- let origin = "";- const server = createServer3((request, response) => {- response.setHeader("cache-control", "no-store");- response.setHeader("referrer-policy", "no-referrer");- response.setHeader("content-type", "text/plain; charset=utf-8");- const url = new URL(request.url ?? "/", origin);- if (request.method !== "GET" || request.headers.host !== new URL(origin).host || url.origin !== origin || url.pathname !== "/callback" || request.headers.forwarded || request.headers["x-forwarded-for"]) {- response.writeHead(404).end("Not found");- return;- }- const code = url.searchParams.get("code");- const suppliedState = Buffer.from(url.searchParams.get("state") ?? "");- const expectedState = Buffer.from(state);- if (accepted || url.searchParams.getAll("state").length !== 1 || suppliedState.length !== expectedState.length || !timingSafeEqual(suppliedState, expectedState) || url.searchParams.getAll("code").length !== 1 || !code) {- response.writeHead(400).end("Invalid sign-in response");+var state2 = globalThis.__omoTeamLockLifetimeV1 ??= createState();+var lockOwnerInstanceId = state2.incarnation;+function attachWorker(worker) {+ if (state2.observed.has(worker))+ return;+ state2.observed.add(worker);+ const id = worker.threadId;+ const challenge = randomUUID5();+ state2.observing.set(id, { worker, challenge });+ const incarnations = new Set;+ let exited = false;+ worker.on("message", (message) => {+ const parsed = Registration.safeParse(message);+ if (!parsed.success || parsed.data.challenge !== challenge)return;- }- accepted = true;- response.writeHead(200).end("Return to the terminal to finish signing in.");- answer.resolve(code);+ incarnations.add(parsed.data.incarnation);+ if (exited)+ state2.exited.add(parsed.data.incarnation);});- try {- await new Promise((resolve, reject) => {- server.once("error", reject);- server.listen(0, "127.0.0.1", () => {- server.off("error", reject);- resolve();- });- });- const address = server.address();- if (!address || typeof address === "string")- throw new SignInError("Unable to start the sign-in callback.");- origin = `http://127.0.0.1:${address.port}`;- const url = new URL(serviceOrigin(options.accounts));- url.search = new URLSearchParams({- redirect_uri: `${origin}/callback`,- code_challenge: createHash11("sha256").update(verifier).digest("base64url"),- code_challenge_method: "S256",- state- }).toString();- const timer = setTimeout(abort, 5 * 60000);- options.signal?.addEventListener("abort", abort, { once: true });- try {- options.signal?.throwIfAborted();- const openerFailed = () => {- if (!accepted)- throw new BrowserUnavailable("No browser is available; use device sign-in.");- };- const [code] = await Promise.all([- answer.promise,- options.open(url.href).then((opened) => {- if (!opened)- openerFailed();- }, openerFailed)- ]);- return { code, codeVerifier: verifier };- } finally {+ worker.once("exit", () => {+ exited = true;+ if (state2.observing.get(id)?.worker === worker)+ state2.observing.delete(id);+ for (const incarnation of incarnations)+ state2.exited.add(incarnation);+ });+}+function installLockWorkerObserver() {+ if (state2.installed)+ return;+ state2.installed = true;+ process.on("worker", attachWorker);+ state2.channel.postMessage({ kind: "hello", threadId });+}+installLockWorkerObserver();+async function registerLockWorker() {+ if (state2.registered)+ return;+ state2.registration ??= new Promise((resolve) => {+ const finish = () => {clearTimeout(timer);- options.signal?.removeEventListener("abort", abort);- }- } finally {- server.closeAllConnections();- await new Promise((resolve) => server.close(() => resolve()));- }+ state2.onRegistered = undefined;+ resolve();+ };+ const timer = setTimeout(finish, 250);+ state2.onRegistered = finish;+ state2.channel.postMessage({ kind: "hello", threadId });+ });+ await state2.registration;}-async function loginLoopback(session, options) {- await session.ready();- const keys = generateDeviceKeys();- for (;; ) {- const authorization = await authorize({ accounts: options.accounts, open: options.open, signal: session.signal });- try {- const grant = parseReply(grantSchema, await session.request("/v1/session/exchange", jsonRequest({- ...authorization,- kind: "cli",- deviceName: options.name,- platform: options.platform,- ...keys.public- })));- await session.save({ ...grant, ...keys.private });- return;- } catch (error) {- if (await session.removeForLimit(error, options.chooseDevice))- continue;- throw new SignInError("Sign-in cancelled. No device was removed.");- }- }+function markLockRecordHeld(record) {+ state2.records.set(record, "held");+}+function markLockRecordReleased(record) {+ if (state2.records.has(record))+ state2.records.set(record, "released");+}+function forgetLockRecord(record) {+ state2.records.delete(record);+}+async function isWorkerLockReleased(incarnation, record) {+ if (state2.exited.has(incarnation))+ return true;+ if (incarnation === state2.incarnation)+ return state2.records.get(record) === "released";+ const id = randomUUID5();+ return await new Promise((resolve) => {+ const finish = (released) => {+ clearTimeout(timer);+ state2.pending.delete(id);+ resolve(released);+ };+ const timer = setTimeout(() => finish(false), 250);+ state2.pending.set(id, finish);+ state2.channel.postMessage({ kind: "query", id, incarnation, record });+ });}--// packages/omo-opencode/src/cli/service-auth/session.ts-import { mkdir as mkdir11 } from "fs/promises";-import { homedir as homedir31 } from "os";-import { join as join107 } from "path";--// packages/team-core/src/team-state-store/lock-publish.ts-import { access as access3, open as open2, unlink as unlink2 } from "fs/promises";-import { dirname as dirname42 } from "path";// packages/team-core/src/team-state-store/lock-record.ts-import { randomUUID as randomUUID5 } from "crypto";-import { readFile as readFile33, stat as stat8 } from "fs/promises";-var lockOwnerInstanceId = randomUUID5();-var heldLockRecords = new Set;-function buildLockRecord(ownerTag) {- return `${ownerTag} ${randomUUID5()}+async function buildLockRecord(ownerTag) {+ await registerLockWorker();+ const processStart = await getProcessStartIdentity(process.pid);+ return `${ownerTag} ${randomUUID6()}${process.pid}${Date.now()}${lockOwnerInstanceId}+${processStart ?? "unavailable"}`;}-function markLockRecordHeld(content) {- heldLockRecords.add(content);-}-function markLockRecordReleased(content) {- heldLockRecords.delete(content);-}-function errorCode(error) {+function errorCode2(error) {if (!(error instanceof Error) || !("code" in error))return null;return typeof error.code === "string" ? error.code : null;}function isPathAbsenceError(error) {- const code = errorCode(error);+ const code = errorCode2(error);return code === "ENOENT" || code === "ENOTDIR";}function parseLockOwner(content) {const lines = content.split(/\r?\n/).filter((line) => line.length > 0);- if (lines.length !== 3 && lines.length !== 4)+ if (lines.length !== 3 && lines.length !== 4 && lines.length !== 5)return null;const ownerPid = Number.parseInt(lines[1] ?? "", 10);const acquiredAtEpochMs = Number.parseInt(lines[2] ?? "", 10);@@ -112708,24 +113149,14 @@ function parseLockOwner(content) {return {ownerPid,acquiredAtEpochMs,- instanceId: lines.length === 4 ? lines[3] ?? null : null+ instanceId: lines[3] ?? null,+ processStart: lines[4] ?? null};}-function isPidAlive(pid) {- try {- process.kill(pid, 0);- return true;- } catch (error) {- if (!(error instanceof Error)) {- throw error;- }- return false;- }-}async function readLockRecord(lockPath) {try {- const content = await readFile33(lockPath, "utf8");- const { mtimeMs } = await stat8(lockPath);+ const content = await readFile34(lockPath, "utf8");+ const { mtimeMs } = await stat9(lockPath);return { content, modifiedAtEpochMs: mtimeMs };} catch (error) {if (!(error instanceof Error))@@ -112733,23 +113164,30 @@ async function readLockRecord(lockPath) {return null;}}-function isLockRecordStale(record, staleAfterMs) {+async function isLockRecordStale(record, staleAfterMs) {const owner = parseLockOwner(record.content);if (owner === null)return Date.now() - record.modifiedAtEpochMs > staleAfterMs;- if (owner.instanceId !== null && owner.ownerPid === process.pid) {- return owner.instanceId !== lockOwnerInstanceId || !heldLockRecords.has(record.content);+ const liveness = getPidLiveness(owner.ownerPid);+ if (liveness === "dead") {+ return owner.instanceId !== null || Date.now() - owner.acquiredAtEpochMs > staleAfterMs;}- if (isPidAlive(owner.ownerPid))+ if (liveness === "unknown")return false;- if (owner.instanceId !== null)- return true;- return Date.now() - owner.acquiredAtEpochMs > staleAfterMs;+ if (owner.processStart !== null) {+ const actual = await getProcessStartIdentity(owner.ownerPid);+ if (actual !== null && startIdentitiesConflict(owner.processStart, actual))+ return true;+ }+ if (owner.instanceId !== null && owner.ownerPid === process.pid) {+ return await isWorkerLockReleased(owner.instanceId, record.content);+ }+ return false;}// packages/team-core/src/team-state-store/lock-publish.tsasync function pathMayExist(path, deps = {}) {- const accessPath = deps.access ?? access3;+ const accessPath = deps.access ?? access4;try {await accessPath(path);return true;@@ -112760,7 +113198,7 @@ async function pathMayExist(path, deps = {}) {}}async function assertRetryableLockOpenError(lockPath, error, deps) {- const code = errorCode(error);+ const code = errorCode2(error);if (code === "EEXIST")return;if (code === "EPERM") {@@ -112775,9 +113213,9 @@ async function publishLockRecord(lockPath, record) {markLockRecordHeld(record);let fileHandle;try {- fileHandle = await open2(lockPath, "wx");+ fileHandle = await open3(lockPath, "wx");} catch (error) {- markLockRecordReleased(record);+ forgetLockRecord(record);await assertRetryableLockOpenError(lockPath, error);return false;}@@ -112786,7 +113224,7 @@ async function publishLockRecord(lockPath, record) {} catch (error) {markLockRecordReleased(record);await fileHandle.close();- await unlink2(lockPath).catch(() => {+ await unlink3(lockPath).catch(() => {return;});throw error;@@ -112796,8 +113234,8 @@ async function publishLockRecord(lockPath, record) {}// packages/team-core/src/team-state-store/lock-reclaim.ts-import { createHash as createHash12 } from "crypto";-import { unlink as unlink3 } from "fs/promises";+import { createHash as createHash10 } from "crypto";+import { unlink as unlink4 } from "fs/promises";var RECLAIM_UNLINK_ATTEMPTS = 3;var RECLAIM_UNLINK_RETRY_MS = 25;function delay2(ms) {@@ -112806,11 +113244,11 @@ function delay2(ms) {});}function reclaimGuardPath(lockPath, record) {- return `${lockPath}.reclaim-${createHash12("sha256").update(record).digest("hex").slice(0, 16)}`;+ return `${lockPath}.reclaim-${createHash10("sha256").update(record).digest("hex").slice(0, 16)}`;}async function unlinkWithRetry(path, deps) {const wait = deps.delay ?? delay2;- const unlinkFile = deps.unlink ?? unlink3;+ const unlinkFile = deps.unlink ?? unlink4;for (let attempt = 1;; attempt += 1) {try {await unlinkFile(path);@@ -112820,7 +113258,7 @@ async function unlinkWithRetry(path, deps) {throw error;if (isPathAbsenceError(error))return "absent";- const code = errorCode(error);+ const code = errorCode2(error);if (code !== "EPERM" && code !== "EBUSY" || attempt === RECLAIM_UNLINK_ATTEMPTS)return "stuck";await wait(RECLAIM_UNLINK_RETRY_MS);@@ -112829,10 +113267,10 @@ async function unlinkWithRetry(path, deps) {}async function removeLockRecordIfUnchanged(lockPath, expectedRecord, staleAfterMs, deps = {}) {const guardPath = reclaimGuardPath(lockPath, expectedRecord);- const guardRecord = buildLockRecord("lock-reclaim");+ const guardRecord = await buildLockRecord("lock-reclaim");if (!await publishLockRecord(guardPath, guardRecord)) {const guard = await readLockRecord(guardPath);- if (guard !== null && isLockRecordStale(guard, staleAfterMs)) {+ if (guard !== null && await isLockRecordStale(guard, staleAfterMs)) {await removeLockRecordIfUnchanged(guardPath, guard.content, staleAfterMs, deps);}return "busy";@@ -112841,13 +113279,16 @@ async function removeLockRecordIfUnchanged(lockPath, expectedRecord, staleAfterMconst current = await readLockRecord(lockPath);if (current === null)return "absent";- if (current.content !== expectedRecord || !isLockRecordStale(current, staleAfterMs))+ if (current.content !== expectedRecord || !await isLockRecordStale(current, staleAfterMs))return "changed";const unlinked = await unlinkWithRetry(lockPath, deps);+ if (unlinked !== "stuck")+ forgetLockRecord(expectedRecord);return unlinked === "absent" ? "absent" : unlinked;} finally {markLockRecordReleased(guardRecord);- await unlinkWithRetry(guardPath, deps);+ if (await unlinkWithRetry(guardPath, deps) !== "stuck")+ forgetLockRecord(guardRecord);}}@@ -112866,7 +113307,7 @@ async function acquireLock(lockPath, ownerTag, staleAfterMs) {if (Date.now() - startedAt > LOCK_WAIT_TIMEOUT_MS) {throw new Error(`Timed out acquiring lock: ${lockPath}`);}- const record = buildLockRecord(ownerTag);+ const record = await buildLockRecord(ownerTag);if (await publishLockRecord(lockPath, record))return record;const outcome = await reapStaleLock(lockPath, staleAfterMs);@@ -112883,26 +113324,327 @@ async function withLock(lockPath, fn, opts) {return await fn();} finally {markLockRecordReleased(record);- await removeLockRecordIfUnchanged(lockPath, record, staleAfterMs);+ const outcome = await removeLockRecordIfUnchanged(lockPath, record, staleAfterMs);+ if (outcome === "removed" || outcome === "absent" || outcome === "changed")+ forgetLockRecord(record);}}async function reapStaleLock(lockPath, staleAfterMs = DEFAULT_STALE_AFTER_MS, deps = {}) {const observed = await readLockRecord(lockPath);if (observed === null)return "absent";- if (!isLockRecordStale(observed, staleAfterMs))+ if (!await isLockRecordStale(observed, staleAfterMs))return "changed";return await removeLockRecordIfUnchanged(lockPath, observed.content, staleAfterMs, deps);}+// packages/omo-opencode/src/cli/service-auth/credential-lock.ts+var held = new AsyncLocalStorage3;+function credentialLockPaths(api, home = homedir31()) {+ const id = createHash11("sha256").update(serviceOrigin(api)).digest("hex");+ const directory = join106(home, ".omo", "session-locks");+ return { directory, lock: join106(directory, `${id}.lock`), desktopRecord: join106(directory, `${id}.desktop-generation.json`) };+}+async function withCredentialLock(api, action, home = homedir31(), ownerTag = "cli-session") {+ const { directory, lock } = credentialLockPaths(api, home);+ const owned = held.getStore();+ if (owned?.has(lock))+ return action();+ await mkdir11(directory, { recursive: true, mode: 448 });+ return withLock(lock, () => held.run(new Set([...owned ?? [], lock]), action), {+ ownerTag,+ staleAfterMs: Number.POSITIVE_INFINITY+ });+}++// packages/omo-opencode/src/cli/service-auth/keystore.ts+class CredentialStoreError extends SignInError {+}++class KeychainLockedError extends CredentialStoreError {+}+class InvalidCredentialState extends SignInError {+}++class CredentialIdentityChanged extends Error {+ constructor() {+ super("The stored sign-in changed; the captured account is no longer current.");+ }+}++class KeychainApprovalPendingError extends CredentialStoreError {+}+var SESSION_READ_WAIT = { kind: "bounded", deadlineMs: 5000 };+var INTERACTIVE_READ_WAIT = {+ kind: "interactive",+ noticeAfterMs: 2000,+ notice: (message) => process.stderr.write(`${message}+`)+};+var processReads = new WeakMap;+var LOCKED = /-25308|errSecInteractionNotAllowed|interaction is not allowed|locked collection/i;+var UNLOCKED_REUSE_MS = 30000;+var fallbackNoticed = false;+var stderrNoticeOncePerProcess = (message) => {+ if (fallbackNoticed)+ return;+ fallbackNoticed = true;+ process.stderr.write(`${message}+`);+};+var isLocked = (error) => error instanceof Error && (LOCKED.test(error.message) || LOCKED.test(String(error.code ?? "")));+function credentialId(api) {+ return createHash12("sha256").update(serviceOrigin(api)).digest("hex");+}+function createCredentialStore(api, options = {}) {+ const store = createSealedStore(api, "omo-cli", credentialSchema, options.secrets, options.platform, options.lockProbe, options.notice, options.wait, (current, value) => {+ const sameIdentity = current !== null && current.device.id === value.device.id && current.signingPrivateKey === value.signingPrivateKey && current.sealingPrivateKey === value.sealingPrivateKey && (value.accountId === undefined || current.accountId === undefined || current.accountId === value.accountId);+ const accountId = value.accountId ?? (sameIdentity ? current?.accountId : undefined);+ return {+ ...value,+ ...accountId === undefined ? {} : { accountId },+ credentialGeneration: sameIdentity ? current?.credentialGeneration ?? randomUUID7() : randomUUID7()+ };+ });+ return {+ read: store.read,+ readAuthoritative: store.readAuthoritative,+ write: (value) => withCredentialLock(api, () => store.write(value), options.home),+ clear: () => withCredentialLock(api, store.clear, options.home)+ };+}+function createSealedStore(api, namespace, schema, secrets = typeof Bun === "undefined" ? null : Bun.secrets, platform = process.platform, lockProbe = probeSecretServiceLock, notice = stderrNoticeOncePerProcess, wait = SESSION_READ_WAIT, amendWrite) {+ if (!secrets)+ throw new SignInError("OmO sign-in needs Bun 1.4 or newer with OS credential storage. No file fallback is available.");+ const platformName = platform === "darwin" ? "macOS Keychain" : platform === "linux" ? "Linux Secret Service (libsecret and an unlocked keyring)" : platform === "win32" ? "Windows Credential Manager" : null;+ if (platformName === null)+ throw new SignInError("This platform has no supported OS credential store.");+ const key = { service: namespace, name: credentialId(api) };+ const slot = `${key.service}+${key.name}`;+ const readsOf = (api) => {+ const known = processReads.get(api);+ if (known !== undefined)+ return known;+ const created = new Map;+ processReads.set(api, created);+ return created;+ };+ const forget = (api) => {+ readsOf(api).delete(slot);+ };+ const sharedRead = (api) => {+ const reads = readsOf(api);+ const pending = reads.get(slot);+ if (pending !== undefined)+ return pending;+ const read = Promise.resolve().then(() => api.get(key));+ const done = () => {+ if (reads.get(slot) === read)+ reads.delete(slot);+ };+ read.then(done, done);+ reads.set(slot, read);+ return read;+ };+ const waiting = platform === "darwin" ? `macOS Keychain is waiting for your approval: answer the "${basename15(process.execPath)} wants to access key ${namespace}" dialog ("Always Allow" stops it asking again)` : `${platformName} has not answered; it may be waiting for your approval or an unlock in a system dialog`;+ const answered = async (api, fresh = false) => {+ const read = fresh ? Promise.resolve().then(() => api.get(key)) : sharedRead(api);+ let timer;+ try {+ if (wait.kind === "interactive") {+ timer = setTimeout(() => wait.notice(`omo: ${waiting}.`), wait.noticeAfterMs);+ return await read;+ }+ const expired = new Promise((_, reject) => {+ timer = setTimeout(() => reject(new KeychainApprovalPendingError(`${waiting}, then try again. Credentials are never saved to a file.`)), wait.deadlineMs);+ });+ return await Promise.race([read, expired]);+ } finally {+ clearTimeout(timer);+ }+ };+ const unavailable = (error) => isLocked(error) ? new KeychainLockedError(`${platformName} is locked. Unlock it, then try again. Credentials are never saved to a file.`) : new CredentialStoreError(`Cannot access ${platformName}. Unlock or enable the OS credential store and try again. Credentials are never saved to a file.`);+ let unlockedUntil = 0;+ let noticed = false;+ const assertUsable = async () => {+ if (platform !== "linux" || Date.now() < unlockedUntil)+ return;+ const lock = await lockProbe();+ if (lock === "locked")+ throw new KeychainLockedError(`${platformName} is locked. Unlock it, then try again. Credentials are never saved to a file.`);+ if (lock === "unlocked") {+ unlockedUntil = Date.now() + UNLOCKED_REUSE_MS;+ return;+ }+ if (!noticed) {+ noticed = true;+ notice("omo: could not check whether the keyring is locked (gdbus or the Secret Service did not answer); using libsecret directly.");+ }+ };+ const parsedRead = async (fresh) => {+ await assertUsable();+ let value;+ try {+ value = await answered(secrets, fresh);+ } catch (error) {+ if (error instanceof KeychainApprovalPendingError)+ throw error;+ throw unavailable(error);+ }+ if (value === null)+ return null;+ try {+ return schema.parse(JSON.parse(value));+ } catch {+ throw new InvalidCredentialState(signInRoute() === "cli" ? "Stored sign-in data is invalid. Run omo account forget, then omo login." : "The OmO sign-in saved on this computer can't be read. Run omo account forget to remove it, then sign in again in the desktop app.");+ }+ };+ return {+ read: () => parsedRead(false),+ readAuthoritative: () => parsedRead(true),+ async write(value) {+ await assertUsable();+ try {+ let next = value;+ if (amendWrite !== undefined) {+ const raw = await answered(secrets, true);+ let previous = null;+ if (raw !== null) {+ try {+ previous = schema.parse(JSON.parse(raw));+ } catch {}+ }+ next = amendWrite(previous, value);+ }+ await secrets.set({ ...key, value: JSON.stringify(schema.parse(next)) });+ } catch (error) {+ throw unavailable(error);+ }+ forget(secrets);+ },+ async clear() {+ await assertUsable();+ try {+ await secrets.delete(key);+ } catch (error) {+ throw unavailable(error);+ }+ forget(secrets);+ }+ };+}++// packages/omo-opencode/src/cli/service-auth/loopback.ts+import { createHash as createHash13, randomBytes as randomBytes5, timingSafeEqual } from "crypto";+import { createServer as createServer3 } from "http";+class BrowserUnavailable extends SignInError {+}+async function authorize(options) {+ const verifier = randomBytes5(32).toString("base64url");+ const state = randomBytes5(32).toString("base64url");+ const answer = Promise.withResolvers();+ const abort = () => answer.reject(new SignInError("Browser sign-in cancelled or timed out."));+ let accepted = false;+ let origin = "";+ const server = createServer3((request, response) => {+ response.setHeader("cache-control", "no-store");+ response.setHeader("referrer-policy", "no-referrer");+ response.setHeader("content-type", "text/plain; charset=utf-8");+ const url = new URL(request.url ?? "/", origin);+ if (request.method !== "GET" || request.headers.host !== new URL(origin).host || url.origin !== origin || url.pathname !== "/callback" || request.headers.forwarded || request.headers["x-forwarded-for"]) {+ response.writeHead(404).end("Not found");+ return;+ }+ const code = url.searchParams.get("code");+ const suppliedState = Buffer.from(url.searchParams.get("state") ?? "");+ const expectedState = Buffer.from(state);+ if (accepted || url.searchParams.getAll("state").length !== 1 || suppliedState.length !== expectedState.length || !timingSafeEqual(suppliedState, expectedState) || url.searchParams.getAll("code").length !== 1 || !code) {+ response.writeHead(400).end("Invalid sign-in response");+ return;+ }+ accepted = true;+ response.writeHead(200).end("Return to the terminal to finish signing in.");+ answer.resolve(code);+ });+ try {+ await new Promise((resolve, reject) => {+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => {+ server.off("error", reject);+ resolve();+ });+ });+ const address = server.address();+ if (!address || typeof address === "string")+ throw new SignInError("Unable to start the sign-in callback.");+ origin = `http://127.0.0.1:${address.port}`;+ const url = new URL(serviceOrigin(options.accounts));+ url.search = new URLSearchParams({+ redirect_uri: `${origin}/callback`,+ code_challenge: createHash13("sha256").update(verifier).digest("base64url"),+ code_challenge_method: "S256",+ state+ }).toString();+ const timer = setTimeout(abort, 5 * 60000);+ options.signal?.addEventListener("abort", abort, { once: true });+ try {+ options.signal?.throwIfAborted();+ const openerFailed = () => {+ if (!accepted)+ throw new BrowserUnavailable("No browser is available; use device sign-in.");+ };+ const [code] = await Promise.all([+ answer.promise,+ options.open(url.href).then((opened) => {+ if (!opened)+ openerFailed();+ }, openerFailed)+ ]);+ return { code, codeVerifier: verifier };+ } finally {+ clearTimeout(timer);+ options.signal?.removeEventListener("abort", abort);+ }+ } finally {+ server.closeAllConnections();+ await new Promise((resolve) => server.close(() => resolve()));+ }+}+async function loginLoopback(session, options) {+ await session.ready();+ const keys = generateDeviceKeys();+ for (;; ) {+ const authorization = await authorize({ accounts: options.accounts, open: options.open, signal: session.signal });+ try {+ const grant = parseReply(grantSchema, await session.request("/v1/session/exchange", jsonRequest({+ ...authorization,+ kind: "cli",+ deviceName: options.name,+ platform: options.platform,+ ...keys.public+ })));+ await session.save({ ...grant, ...keys.private });+ return;+ } catch (error) {+ if (await session.removeForLimit(error, options.chooseDevice))+ continue;+ throw new SignInError("Sign-in cancelled. No device was removed.");+ }+ }+}++// packages/omo-opencode/src/cli/service-auth/session.ts+import { homedir as homedir32 } from "os";+// packages/omo-opencode/src/cli/service-auth/signed-out-marker.tsinit_zod();-import { mkdir as mkdir10, readFile as readFile34, rename as rename7, rm as rm16, writeFile as writeFile16 } from "fs/promises";-import { dirname as dirname43, join as join106 } from "path";+import { mkdir as mkdir12, readFile as readFile35, rename as rename8, rm as rm17, writeFile as writeFile17 } from "fs/promises";+import { dirname as dirname43, join as join107 } from "path";var markerSchema = object({ device: string2().nullable(), at: string2() });-var signedOutMarkerPath = (home, credential) => join106(home, ".omo", "account-state", `${credential}.signed-out.json`);+var signedOutMarkerPath = (home, credential) => join107(home, ".omo", "account-state", `${credential}.signed-out.json`);async function readSignedOutMarker(path) {- const text = await readFile34(path, "utf8").catch(() => null);+ const text = await readFile35(path, "utf8").catch(() => null);if (text === null)return null;let value;@@ -112915,12 +113657,12 @@ async function readSignedOutMarker(path) {return parsed.success ? parsed.data : null;}async function writeSignedOutMarker(path, device) {- await mkdir10(dirname43(path), { recursive: true, mode: 448 });+ await mkdir12(dirname43(path), { recursive: true, mode: 448 });const staging = `${path}.${process.pid}.tmp`;- await writeFile16(staging, JSON.stringify({ device, at: new Date().toISOString() }), { mode: 384 });- await rename7(staging, path);+ await writeFile17(staging, JSON.stringify({ device, at: new Date().toISOString() }), { mode: 384 });+ await rename8(staging, path);}-var clearSignedOutMarker = (path) => rm16(path, { force: true });+var clearSignedOutMarker = (path) => rm17(path, { force: true });// packages/omo-opencode/src/cli/service-auth/session.tsclass SessionEnded extends SignInError {@@ -112935,30 +113677,29 @@ class SessionEnded extends SignInError {var DEVICE_REVOKING_REFUSALS = new Set(["account_deleted", "reauth_required", "device_revoked"]);function createSession(options) {const api = serviceOrigin(options.api);+ const now = options.now ?? Date.now;const { store, signal } = options;- const directory = join107(options.home ?? homedir31(), ".omo", "session-locks");- const lockPath = join107(directory, `${credentialId(api)}.lock`);- const markerPath = signedOutMarkerPath(options.home ?? homedir31(), credentialId(api));+ const markerPath = signedOutMarkerPath(options.home ?? homedir32(), credentialId(api));async function locked(action) {- await mkdir11(directory, { recursive: true, mode: 448 });signal?.throwIfAborted();- return withLock(lockPath, async () => {+ return withCredentialLock(api, async () => {signal?.throwIfAborted();return action();- }, { ownerTag: "cli-session", staleAfterMs: Number.POSITIVE_INFINITY });+ }, options.home);}const request = (path, init) => requestApi(api, path, init, signal);- const uncertain = () => new SignInError(`The refresh outcome is unknown. Saved credentials and keys were retained, but this refresh token will not be sent again. ${signInHint("again")}`, true);- async function refreshedAccess(current) {- if (current.refreshState === "uncertain")- throw uncertain();- if (Date.parse(current.accessTokenExpiresAt) > Date.now() + 30000)- return current.accessToken;+ async function refreshed(current) {+ if (current.refreshState === "uncertain" || current.refreshAttempt !== undefined) {+ throw new SessionEnded(`Refresh recovery can no longer be proved safe. ${signInHint("again")}`, false, "refresh_recovery_expired");+ }+ if (Date.parse(current.accessTokenExpiresAt) > now() + 30000)+ return current;await store.write({ ...current, refreshState: "uncertain" });try {const tokens = parseReply(tokenSchema, await request("/v1/session/refresh", jsonRequest({ refreshToken: current.refreshToken })));- await store.write({ ...current, ...tokens });- return tokens.accessToken;+ const successor = { ...current, ...tokens };+ await store.write(successor);+ return successor;} catch (error) {if (error instanceof CredentialStoreError)throw error;@@ -112970,12 +113711,19 @@ function createSession(options) {await store.write(current);throw error;}- throw uncertain();+ throw new SessionEnded(`The refresh outcome is unknown. Saved credentials and keys were retained. ${signInHint("again")}`, false, "refresh_recovery_expired");}}+ async function snapshot() {+ return locked(async () => {+ const current = await store.read();+ return current === null ? null : refreshed(current);+ });+ }return {request,signal,+ transaction: locked,async ready() {await store.read();},@@ -112987,18 +113735,32 @@ function createSession(options) {},signedOutMarker: () => readSignedOutMarker(markerPath),clearSignedOutMarker: () => clearSignedOutMarker(markerPath),- async update(action) {- return locked(async () => action(await store.read()));+ async update(action, options = {}) {+ return locked(async () => {+ let current;+ try {+ current = await store.readAuthoritative();+ } catch (error) {+ if (!options.replaceInvalid || !(error instanceof InvalidCredentialState))+ throw error;+ current = null;+ }+ return action(current);+ });},+ async forget() {+ await locked(() => store.clear());+ },+ accessSnapshot: snapshot,async logout() {return locked(async () => {let current = null;try {- current = await store.read();+ current = await store.readAuthoritative();if (current !== null) {if (current.refreshState === "uncertain")return false;- const access = Date.parse(current.accessTokenExpiresAt) <= Date.now() ? await refreshedAccess(current) : current.accessToken;+ const access = Date.parse(current.accessTokenExpiresAt) <= now() ? (await refreshed(current)).accessToken : current.accessToken;await request(`/v1/devices/${encodeURIComponent(current.device.id)}`, {method: "DELETE",headers: { authorization: `Bearer ${access}` }@@ -113017,12 +113779,19 @@ function createSession(options) {}});},- async accessToken() {+ async accessToken(expect) {+ signal?.throwIfAborted();+ const snapshot = await store.read();+ signal?.throwIfAborted();+ if (snapshot !== null && snapshot.refreshState !== "uncertain" && snapshot.refreshAttempt === undefined && Date.parse(snapshot.accessTokenExpiresAt) > now() + 30000 && (expect === undefined || expect(snapshot)))+ return snapshot.accessToken;return locked(async () => {- const current = await store.read();+ const current = await store.readAuthoritative();if (current === null)throw new SignInError(`Not signed in. ${signInHint("first")}`);- return refreshedAccess(current);+ if (expect !== undefined && !expect(current))+ throw new CredentialIdentityChanged;+ return (await refreshed(current)).accessToken;});},async removeForLimit(error, choose) {@@ -113351,12 +114120,12 @@ async function boulder(options) {}// packages/omo-opencode/src/cli/codex-ulw-loop.tsimport { spawn as spawn6 } from "child_process";-import { existsSync as existsSync67, readFileSync as readFileSync44, realpathSync as realpathSync13 } from "fs";-import { homedir as homedir32 } from "os";+import { existsSync as existsSync67, readFileSync as readFileSync45, realpathSync as realpathSync14 } from "fs";+import { homedir as homedir33 } from "os";var ULW_LOOP_DELEGATION_SENTINEL = "OMO_ULW_LOOP_DELEGATED";function resolveCodexUlwLoopCommand(input = {}) {const env = input.env ?? process.env;- const homeDir = input.homeDir ?? homedir32();+ const homeDir = input.homeDir ?? homedir33();const localComponentBin = resolveLocalUlwLoopBin(env, homeDir);if (localComponentBin !== null)return { executable: localComponentBin, argsPrefix: [] };@@ -113401,7 +114170,7 @@ function resolveLegacyLocalOmoBin(env, homeDir, currentExecutablePaths) {}function isGeneratedRuntimeWrapper(candidate) {try {- return readFileSync44(candidate, "utf8").includes(RUNTIME_WRAPPER_MARKER);+ return readFileSync45(candidate, "utf8").includes(RUNTIME_WRAPPER_MARKER);} catch (error) {if (error instanceof Error)return false;@@ -113414,7 +114183,7 @@ function isCurrentExecutable(candidate, currentExecutablePaths) {}function realpathOrSelf2(path) {try {- return realpathSync13(path);+ return realpathSync14(path);} catch (error) {if (error instanceof Error)return path;@@ -113599,7 +114368,7 @@ function linkedWorktrees(records) {}// packages/omo-opencode/src/cli/worktree-sweep/sweep.tsimport { existsSync as existsSync68 } from "fs";-import { stat as stat9 } from "fs/promises";+import { stat as stat10 } from "fs/promises";import os7 from "os";import { normalize as normalize2 } from "path";@@ -113682,7 +114451,7 @@ async function isOlderThan(worktreePath, days, now) {if (days <= 0)return false;try {- const stats = await stat9(worktreePath);+ const stats = await stat10(worktreePath);return now - stats.mtimeMs > days * DAY_MS;} catch {return false;@@ -113929,7 +114698,7 @@ Model Providers (Priority: Native > Copilot > OpenCode Zen > Z.ai > Kimi > BailiCopilot github-copilot/ models (fallback)OpenCode Zen opencode/ models (opencode/claude-opus-5, etc.)Z.ai zai-coding-plan/glm-5.2 (visual-engineering fallback)- Kimi kimi-for-coding/kimi-k3 (Sisyphus/Prometheus fallback)+ Kimi kimi-for-coding/kimi-k3.1-pro (Sisyphus/Prometheus fallback)Bailian bailian-coding-plan/ models (Qwen, GLM, Kimi fallback)MiniMax minimax-coding-plan/MiniMax-M3 (utility fallback)MiniMax CN minimax-cn-coding-plan/MiniMax-M3 (utility fallback)diff --git a/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json b/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.jsonindex 38c3873e..c6841061 100644--- a/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json+++ b/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "(OmO 5.1.51) Resetting Git Bash MCP Reminder",+ "statusMessage": "(OmO 5.1.54) Resetting Git Bash MCP Reminder","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\git-bash\\dist\\cli.js\" hook post-compact"}],diff --git a/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json b/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.jsonindex 7fc2da84..3caac2f9 100644--- a/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json+++ b/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "(OmO 5.1.51) Resetting LSP Diagnostics Cache",+ "statusMessage": "(OmO 5.1.54) Resetting LSP Diagnostics Cache","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lsp\\dist\\cli.js\" hook post-compact"}],diff --git a/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json b/plugins/omo/hooks/post-compact-resetting-project-rule-cache.jsonindex 9c0115ea..8abcc356 100644--- a/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json+++ b/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-compact","timeout": 10,- "statusMessage": "(OmO 5.1.51) Resetting Project Rule Cache",+ "statusMessage": "(OmO 5.1.54) Resetting Project Rule Cache","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook post-compact"}],diff --git a/plugins/omo/hooks/post-tool-use-checking-comments.json b/plugins/omo/hooks/post-tool-use-checking-comments.jsonindex 30e21470..19149ef6 100644--- a/plugins/omo/hooks/post-tool-use-checking-comments.json+++ b/plugins/omo/hooks/post-tool-use-checking-comments.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/comment-checker/dist/cli.js\" hook post-tool-use","timeout": 30,- "statusMessage": "(OmO 5.1.51) Checking Comments",+ "statusMessage": "(OmO 5.1.54) Checking Comments","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\comment-checker\\dist\\cli.js\" hook post-tool-use"}],diff --git a/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json b/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.jsonindex 022a776c..e95c5d75 100644--- a/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json+++ b/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-tool-use","timeout": 60,- "statusMessage": "(OmO 5.1.51) Checking LSP Diagnostics",+ "statusMessage": "(OmO 5.1.54) Checking LSP Diagnostics","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lsp\\dist\\cli.js\" hook post-tool-use"}],diff --git a/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json b/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.jsonindex 34d8c3ca..fbe82de9 100644--- a/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json+++ b/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/teammode/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "(OmO 5.1.51) Checking Thread Title Hygiene",+ "statusMessage": "(OmO 5.1.54) Checking Thread Title Hygiene","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\teammode\\dist\\cli.js\" hook post-tool-use"}]diff --git a/plugins/omo/hooks/post-tool-use-matching-project-rules.json b/plugins/omo/hooks/post-tool-use-matching-project-rules.jsonindex daf54252..81bfe79a 100644--- a/plugins/omo/hooks/post-tool-use-matching-project-rules.json+++ b/plugins/omo/hooks/post-tool-use-matching-project-rules.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "(OmO 5.1.51) Matching Project Rules",+ "statusMessage": "(OmO 5.1.54) Matching Project Rules","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook post-tool-use"}],diff --git a/plugins/omo/hooks/post-tool-use-recording-spawn-admission.json b/plugins/omo/hooks/post-tool-use-recording-spawn-admission.jsonindex efc8aba7..cc098881 100644--- a/plugins/omo/hooks/post-tool-use-recording-spawn-admission.json+++ b/plugins/omo/hooks/post-tool-use-recording-spawn-admission.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook post-tool-use-spawn","timeout": 5,- "statusMessage": "(OmO 5.1.51) Recording Spawn Admission",+ "statusMessage": "(OmO 5.1.54) Recording Spawn Admission","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook post-tool-use-spawn"}]diff --git a/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json b/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.jsonindex 2ddb4c7d..68fcfef2 100644--- a/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json+++ b/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "(OmO 5.1.51) Enforcing Unlimited Goal Budget",+ "statusMessage": "(OmO 5.1.54) Enforcing Unlimited Goal Budget","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook pre-tool-use"}],diff --git a/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json b/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.jsonindex 94c9638b..c9959466 100644--- a/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json+++ b/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook pre-tool-use-spawn","timeout": 5,- "statusMessage": "(OmO 5.1.51) Guarding Ulw-Loop Spawns",+ "statusMessage": "(OmO 5.1.54) Guarding Ulw-Loop Spawns","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook pre-tool-use-spawn"}]diff --git a/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json b/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.jsonindex 444a2a04..d90cad12 100644--- a/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json+++ b/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "(OmO 5.1.51) Recommending Git Bash MCP",+ "statusMessage": "(OmO 5.1.54) Recommending Git Bash MCP","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\git-bash\\dist\\cli.js\" hook pre-tool-use"}],diff --git a/plugins/omo/hooks/session-start-checking-auto-update.json b/plugins/omo/hooks/session-start-checking-auto-update.jsonindex 612b45eb..9d1631bb 100644--- a/plugins/omo/hooks/session-start-checking-auto-update.json+++ b/plugins/omo/hooks/session-start-checking-auto-update.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/scripts/auto-update.mjs\" hook session-start","timeout": 15,- "statusMessage": "(OmO 5.1.51) Checking Auto Update",+ "statusMessage": "(OmO 5.1.54) Checking Auto Update","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\scripts\\auto-update.mjs\" hook session-start"}],diff --git a/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json b/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.jsonindex 9832974e..e99168d3 100644--- a/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json+++ b/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json@@ -8,7 +8,7 @@"command": "node \"${PLUGIN_ROOT}/components/bootstrap/dist/cli.js\" hook session-start","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\bootstrap.ps1\"","timeout": 30,- "statusMessage": "(OmO 5.1.51) Checking Bootstrap Provisioning"+ "statusMessage": "(OmO 5.1.54) Checking Bootstrap Provisioning"}]}diff --git a/plugins/omo/hooks/session-start-loading-project-rules.json b/plugins/omo/hooks/session-start-loading-project-rules.jsonindex 05b7efae..c55c0460 100644--- a/plugins/omo/hooks/session-start-loading-project-rules.json+++ b/plugins/omo/hooks/session-start-loading-project-rules.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook session-start","timeout": 10,- "statusMessage": "(OmO 5.1.51) Loading Project Rules",+ "statusMessage": "(OmO 5.1.54) Loading Project Rules","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook session-start"}]diff --git a/plugins/omo/hooks/session-start-recording-session-telemetry.json b/plugins/omo/hooks/session-start-recording-session-telemetry.jsonindex a040c4a8..f333c524 100644--- a/plugins/omo/hooks/session-start-recording-session-telemetry.json+++ b/plugins/omo/hooks/session-start-recording-session-telemetry.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/telemetry/dist/cli.js\" hook session-start","timeout": 15,- "statusMessage": "(OmO 5.1.51) Recording Session Telemetry",+ "statusMessage": "(OmO 5.1.54) Recording Session Telemetry","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\telemetry\\dist\\cli.js\" hook session-start"}]diff --git a/plugins/omo/hooks/stop-checking-ulw-execute-continuation.json b/plugins/omo/hooks/stop-checking-ulw-execute-continuation.jsonindex 4c24f71a..5b13f3f4 100644--- a/plugins/omo/hooks/stop-checking-ulw-execute-continuation.json+++ b/plugins/omo/hooks/stop-checking-ulw-execute-continuation.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-execute-continuation/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "(OmO 5.1.51) Checking Ulw-Execute Continuation",+ "statusMessage": "(OmO 5.1.54) Checking Ulw-Execute Continuation","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-execute-continuation\\dist\\cli.js\" hook stop"}]diff --git a/plugins/omo/hooks/stop-checking-ulw-loop-resume.json b/plugins/omo/hooks/stop-checking-ulw-loop-resume.jsonindex e80c6be4..91554cf7 100644--- a/plugins/omo/hooks/stop-checking-ulw-loop-resume.json+++ b/plugins/omo/hooks/stop-checking-ulw-loop-resume.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "(OmO 5.1.51) Checking Ulw-Loop Resume",+ "statusMessage": "(OmO 5.1.54) Checking Ulw-Loop Resume","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook stop"}]diff --git a/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json b/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.jsonindex 97d8dfb2..ed11c263 100644--- a/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json+++ b/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/lazycodex-executor-verify/dist/cli.js\" hook subagent-stop","timeout": 10,- "statusMessage": "(OmO 5.1.51) Verifying LazyCodex Executor Evidence",+ "statusMessage": "(OmO 5.1.54) Verifying LazyCodex Executor Evidence","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lazycodex-executor-verify\\dist\\cli.js\" hook subagent-stop"}],diff --git a/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json b/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.jsonindex d419c681..40452f6c 100644--- a/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json+++ b/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ultrawork/dist/cli.js\" hook user-prompt-submit","timeout": 5,- "statusMessage": "(OmO 5.1.51) Checking Ultrawork Trigger",+ "statusMessage": "(OmO 5.1.54) Checking Ultrawork Trigger","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ultrawork\\dist\\cli.js\" hook user-prompt-submit"}]diff --git a/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json b/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.jsonindex 93bfa374..28c1c808 100644--- a/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json+++ b/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "(OmO 5.1.51) Checking Ulw-Loop Steering",+ "statusMessage": "(OmO 5.1.54) Checking Ulw-Loop Steering","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook user-prompt-submit"}]diff --git a/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json b/plugins/omo/hooks/user-prompt-submit-loading-project-rules.jsonindex ffee2b49..1bc1de2f 100644--- a/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json+++ b/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "(OmO 5.1.51) Loading Project Rules",+ "statusMessage": "(OmO 5.1.54) Loading Project Rules","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook user-prompt-submit"}]diff --git a/plugins/omo/package-lock.json b/plugins/omo/package-lock.jsonindex ba3fab2b..2c5df898 100644--- a/plugins/omo/package-lock.json+++ b/plugins/omo/package-lock.json@@ -1,12 +1,12 @@{"name": "@sisyphuslabs/omo-codex-plugin",- "version": "5.1.51",+ "version": "5.1.54","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@sisyphuslabs/omo-codex-plugin",- "version": "5.1.51",+ "version": "5.1.54","workspaces": ["components/comment-checker","components/git-bash",@@ -100,7 +100,7 @@},"components/comment-checker": {"name": "@code-yeongyu/codex-comment-checker",- "version": "5.1.51",+ "version": "5.1.54","license": "MIT","bin": {"omo-comment-checker": "dist/cli.js"@@ -122,7 +122,7 @@},"components/git-bash": {"name": "@sisyphuslabs/codex-git-bash-hook",- "version": "5.1.51",+ "version": "5.1.54","bin": {"omo-git-bash-hook": "dist/cli.js"},@@ -136,7 +136,7 @@},"components/lazycodex-executor-verify": {"name": "@code-yeongyu/codex-lazycodex-executor-verify",- "version": "5.1.51",+ "version": "5.1.54","license": "MIT","bin": {"lazycodex-executor-verify": "dist/cli.js"@@ -154,7 +154,7 @@},"components/lsp": {"name": "@code-yeongyu/codex-lsp",- "version": "5.1.51",+ "version": "5.1.54","license": "MIT","dependencies": {"@code-yeongyu/lsp-daemon": "file:../../../../lsp-daemon",@@ -176,7 +176,7 @@},"components/rules": {"name": "@code-yeongyu/codex-rules",- "version": "5.1.51",+ "version": "5.1.54","license": "MIT","dependencies": {"picomatch": "^4.0.7"@@ -199,7 +199,7 @@},"components/teammode": {"name": "@sisyphuslabs/codex-teammode",- "version": "5.1.51",+ "version": "5.1.54","devDependencies": {"@types/node": "^26.6.2","@vitest/coverage-v8": "5.0.1",@@ -213,7 +213,7 @@},"components/telemetry": {"name": "@code-yeongyu/codex-telemetry",- "version": "5.1.51",+ "version": "5.1.54","license": "MIT","bin": {"omo-telemetry": "dist/cli.js"@@ -232,7 +232,7 @@},"components/ultrawork": {"name": "@code-yeongyu/codex-ultrawork",- "version": "5.1.51",+ "version": "5.1.54","license": "MIT","bin": {"omo-ultrawork": "dist/cli.js"@@ -251,7 +251,7 @@},"components/ulw-execute-continuation": {"name": "@code-yeongyu/codex-ulw-execute-continuation",- "version": "5.1.51",+ "version": "5.1.54","license": "MIT","bin": {"omo-ulw-execute-continuation": "dist/cli.js"@@ -269,7 +269,7 @@},"components/ulw-loop": {"name": "@code-yeongyu/codex-ulw-loop",- "version": "5.1.51",+ "version": "5.1.54","license": "MIT","bin": {"omo-ulw-loop": "dist/cli.js",diff --git a/plugins/omo/package.json b/plugins/omo/package.jsonindex b129d5c6..da823627 100644--- a/plugins/omo/package.json+++ b/plugins/omo/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/omo-codex-plugin",- "version": "5.1.51",+ "version": "5.1.54","description": "Aggregate Codex plugin root for OMO components.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/scripts/auto-update-plan.mjs b/plugins/omo/scripts/auto-update-plan.mjsindex 140c5730..3ba49fb0 100644--- a/plugins/omo/scripts/auto-update-plan.mjs+++ b/plugins/omo/scripts/auto-update-plan.mjs@@ -5,6 +5,7 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";import { fileURLToPath } from "node:url";import { detectInstallFlow, resolveInstallSnapshotPath } from "./install-flow.mjs";+import { findTomlSection } from "./migrate-codex-config/toml-section-editor.mjs";import { resolveSpawnInvocation } from "./spawn-command.mjs";const DEFAULT_UPDATE_COMMAND = "npx";@@ -59,7 +60,7 @@ export function detectMarketplaceLocalRepair(env = {}) {const codexHome = resolveCodexHome(env);const marketplaceRoot = join(codexHome, "plugins", "cache", SISYPHUS_MARKETPLACE_NAME);const reasons = [- ...missingCachedMarketplaceSources(marketplaceRoot),+ ...(configuredMarketplaceSourceType(codexHome) === "git" ? [] : missingCachedMarketplaceSources(marketplaceRoot)),...missingManagedBinTargets({ env, marketplaceRoot }),];return { needsRepair: reasons.length > 0, reasons };@@ -165,6 +166,20 @@ function resolveInstallerBinDir(env, codexHome) {return resolvedCodexHome === defaultCodexHome ? resolve(home, ".local", "bin") : join(resolvedCodexHome, "bin");}+// Codex reads a Git marketplace from its own clone, so a cache-root manifest an earlier local install wrote is never read.+function configuredMarketplaceSourceType(codexHome) {+ let config;+ try {+ config = readFileSync(join(codexHome, "config.toml"), "utf8");+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return undefined;+ throw error;+ }+ const section = findTomlSection(config, `[marketplaces.${SISYPHUS_MARKETPLACE_NAME}]`);+ if (section === null) return undefined;+ return /^\s*source_type\s*=\s*["']([^"']+)["']/m.exec(section.text)?.[1];+}+function missingCachedMarketplaceSources(marketplaceRoot) {const manifest = readJsonObject(join(marketplaceRoot, ".agents", "plugins", "marketplace.json"));if (manifest === undefined || !Array.isArray(manifest.plugins)) return [];diff --git a/plugins/omo/skills/browser/runtime/omowright/index.js b/plugins/omo/skills/browser/runtime/omowright/index.jsindex 0141b37e..453d6860 100644--- a/plugins/omo/skills/browser/runtime/omowright/index.js+++ b/plugins/omo/skills/browser/runtime/omowright/index.js@@ -63,7 +63,7 @@ ${content.join(``);const fullCode=options?.debug?constantNames.length>0?`// Constants: ${constantNames.join(", ")}${code}`:code:"";const F=Function;const factoryCode=`return (input) => {${code}-}`;let fn;try{const factory=new F(...constantNames,factoryCode);fn=factory(...constantValues)}catch(err){throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`)}if(options?.debug){fn.code=fullCode}fn.definite=ctx.definite;return fn}function addConstant(ctx,value){for(const[name,v]of ctx.constants){if(v===value)return name}const name=`c${ctx.constantCounter++}`;ctx.constants.set(name,value);return name}function addUserConstant(ctx,fn){ctx.definite=false;return addConstant(ctx,fn)}function newVar(ctx){return`v${ctx.varCounter++}`}function runtimeRun(schema,value){const result=schema._zod.run({value,issues:[]},{});if(result&&typeof result.then==="function")return INVALID;const r=result;return r.issues.length===0?r.value:INVALID}function compileChild(doc,ctx,schema,accessor,needsValue=true){const contentLen=doc.content.length;const constantCount=ctx.constants.size;const constantCounter=ctx.constantCounter;const varCounter=ctx.varCounter;try{return generateCheck(doc,ctx,schema,accessor,needsValue)}catch(err){if(!(err instanceof ZodCompileUnsupportedError)||!err.islandable)throw err;doc.content.length=contentLen;if(ctx.constants.size>constantCount){const trailing=Array.from(ctx.constants.keys()).slice(constantCount);for(const k of trailing)ctx.constants.delete(k)}ctx.constantCounter=constantCounter;ctx.varCounter=varCounter;return emitRuntimeIsland(doc,ctx,schema,accessor)}}function emitRuntimeIsland(doc,ctx,schema,accessor){ctx.definite=false;const schemaConst=addConstant(ctx,schema);const runConst=addConstant(ctx,runtimeRun);const outVar=newVar(ctx);doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`);doc.write(`if (${outVar} === INVALID) return INVALID;`);return outVar}var WHEN_DEFAULTED_CHECKS=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function generateChecks(doc,ctx,schema,accessor){const schemaChecks=schema._zod.def.checks;if(!schemaChecks||schemaChecks.length===0)return accessor;let currentAccessor=accessor;for(const check of schemaChecks){const def=check._zod.def;if(def.when&&!WHEN_DEFAULTED_CHECKS.has(def.check)){throw new ZodCompileUnsupportedError(`check with a custom "when" condition`)}switch(def.check){case"greater_than":generateGreaterThanCheck(doc,ctx,def,currentAccessor);break;case"less_than":generateLessThanCheck(doc,ctx,def,currentAccessor);break;case"multiple_of":generateMultipleOfCheck(doc,ctx,def,currentAccessor);break;case"number_format":generateNumberFormatCheck(doc,def,currentAccessor);break;case"min_length":{const min=numericOperand(def.minimum,"min_length");const len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum*2}`);doc.write(`if (${len} < ${min}) return INVALID;`);break}case"max_length":{const max=numericOperand(def.maximum,"max_length");const len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length > ${max}`);doc.write(`if (${len} > ${max}) return INVALID;`);break}case"length_equals":{const exact=numericOperand(def.length,"length_equals");const len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length*2}`);doc.write(`if (${len} !== ${exact}) return INVALID;`);break}case"min_size":doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum,"min_size")}) return INVALID;`);break;case"max_size":doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum,"max_size")}) return INVALID;`);break;case"size_equals":doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size,"size_equals")}) return INVALID;`);break;case"string_format":currentAccessor=generateStringFormatCheck(doc,ctx,def,currentAccessor);break;case"custom":currentAccessor=generateCustomRefineCheck(doc,ctx,check,currentAccessor);break;case"bigint_format":generateBigIntFormatCheck(doc,def,currentAccessor);break;case"mime_type":generateMimeTypeCheck(doc,ctx,def,currentAccessor);break;case"property":generatePropertyCheck(doc,ctx,def,currentAccessor);break;case"properties":generatePropertiesChecks(doc,ctx,def,currentAccessor);break;case"overwrite":{const newAccessor=newVar(ctx);generateOverwriteCheck(doc,ctx,check,currentAccessor,newAccessor);currentAccessor=newAccessor;break}default:{throw new ZodCompileUnsupportedError(`check type ${def.check}`)}}}return currentAccessor}function codePointLengthVar(doc,ctx,accessor,inDoubt){const cpLen=addConstant(ctx,codePointLength);const v=newVar(ctx);doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`);return v}function numericOperand(value,label){if(typeof value!=="number"||!Number.isFinite(value)){throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`)}return`${value}`}function comparisonOperand(ctx,value){if(typeof value==="bigint")return`${value}n`;if(typeof value==="number"){if(Number.isNaN(value))throw new ZodCompileUnsupportedError("comparison check with NaN bound");return`${value}`}if(value instanceof Date){if(Number.isNaN(value.getTime())){throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound")}return addConstant(ctx,value)}throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`)}function generateGreaterThanCheck(doc,ctx,def,accessor){const op=def.inclusive?"<":"<=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateLessThanCheck(doc,ctx,def,accessor){const op=def.inclusive?">":">=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateMultipleOfCheck(doc,ctx,def,accessor){if(typeof def.value==="bigint"){if(def.value===BigInt(0))throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor");doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`)}else{const remainder=addConstant(ctx,floatSafeRemainder);doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value,"multiple_of")}) !== 0) return INVALID;`)}}function generateNumberFormatCheck(doc,def,accessor){const format=def.format;switch(format){case"safeint":doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`);break;case"int32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`);break;case"uint32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`);break;case"float32":doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`);break;case"float64":doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`);break;default:{throw new ZodCompileUnsupportedError(`number format ${format}`)}}}function generateBigIntFormatCheck(doc,def,accessor){const format=def.format;if(!format)return;switch(format){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break;default:{throw new ZodCompileUnsupportedError(`bigint format ${format}`)}}}function generateMimeTypeCheck(doc,ctx,def,accessor){const mimeTypes=def.mime;if(mimeTypes&&mimeTypes.length>0){const mimeSet=addConstant(ctx,new Set(mimeTypes));doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`)}}function generatePropertiesChecks(doc,ctx,def,accessor){if(def.when){throw new ZodCompileUnsupportedError(`check with a custom "when" condition`)}doc.write(`if (${accessor} == null) return INVALID;`);const shape=def.shape;for(const key of Reflect.ownKeys(shape)){const keyExpr=typeof key==="symbol"?addConstant(ctx,key):esc(key);const inputVar=newVar(ctx);doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`);compileChild(doc,ctx,shape[key],inputVar,false)}}function generatePropertyCheck(doc,ctx,def,accessor){const propAccessor=`${accessor}[${JSON.stringify(def.property)}]`;generateCheck(doc,ctx,def.schema,propAccessor)}function generateOverwriteCheck(doc,ctx,check,currentAccessor,newAccessor){const tx=check._zod.def.tx;if(!tx){throw new ZodCompileUnsupportedError("overwrite check without a transform function")}if(isAsyncFunction(tx)){throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported")}const txConst=addConstant(ctx,tx);doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`)}function throwAsync(){throw new $ZodAsyncError}function pushIssue(issue){this.issues.push(issue)}function generateCustomRefineCheck(doc,ctx,check,accessor){const def=check._zod.def;if(def.fn){if(isAsyncFunction(def.fn)){throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported")}const fnConst=addUserConstant(ctx,def.fn);const throwAsyncConst=addConstant(ctx,throwAsync);const resVar=newVar(ctx);doc.write(`const ${resVar} = ${fnConst}(${accessor});`);doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);doc.write(`if (!${resVar}) return INVALID;`);return accessor}if(check._zod.check){if(isAsyncFunction(check._zod.check)){throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported")}const checkFn=check._zod.check;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=checkFn(fakePayload);if(result instanceof Promise)throwAsync();return fakePayload.issues.length===0?fakePayload.value:INVALID};const helperConst=addUserConstant(ctx,helperFn);const outVar=newVar(ctx);doc.write(`const ${outVar} = ${helperConst}(${accessor});`);doc.write(`if (${outVar} === INVALID) return INVALID;`);return outVar}throw new ZodCompileUnsupportedError("custom check without a predicate or check function")}var PATTERN_IS_COMPLETE=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function generateStringFormatCheck(doc,ctx,def,accessor,needsValue=true){const fmt=def.format;if(fmt==="base64"){const validator=addConstant(ctx,isValidBase64);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="base64url"){const validator=addConstant(ctx,isValidBase64URL);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="jwt"){const validator=addConstant(ctx,isValidJWT);const alg=addConstant(ctx,def.alg??null);doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`);return accessor}if(fmt==="ipv6"){const validator=addConstant(ctx,isValidIPv6);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="cidrv6"){const validator=addConstant(ctx,isValidCIDRv6);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="credit_card"){const validator=addConstant(ctx,isValidCreditCard);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="iban"){const validator=addConstant(ctx,isValidIBAN);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}const formatDef=def;if(fmt==="url"||fmt==="httpurl"||formatDef.normalize||formatDef.hostname!==undefined||formatDef.protocol!==undefined){const parseConst=addConstant(ctx,validateURL);const defConst=addConstant(ctx,def);const trimVar=newVar(ctx);const urlVar=newVar(ctx);doc.write(`const ${trimVar} = ${accessor}.trim();`);doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`);doc.write(`if (typeof ${urlVar} === "number") return INVALID;`);if(formatDef.hostname!==undefined){const hostnameConst=addConstant(ctx,urlHostnameOk);doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`)}if(formatDef.protocol!==undefined){const protocolConst=addConstant(ctx,urlProtocolOk);doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`)}if(!needsValue)return null;const outputVar=newVar(ctx);const outputExpr=formatDef.normalize?`${urlVar}.href`:`${addConstant(ctx,stripTabAndNewline)}(${trimVar})`;doc.write(`const ${outputVar} = ${outputExpr};`);return outputVar}const customFn=def.fn;if(customFn){if(isAsyncFunction(customFn))throw new ZodCompileUnsupportedError(`async string format ${fmt}`);const fnConst=addConstant(ctx,customFn);doc.write(`if (!${fnConst}(${accessor})) return INVALID;`);return accessor}if(PATTERN_IS_COMPLETE.has(fmt)&&def.pattern){const patternConst=addConstant(ctx,def.pattern);doc.write(`${patternConst}.lastIndex = 0;`);doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`);return accessor}const format=def.format;switch(format){case"regex":throw new ZodCompileUnsupportedError("regex format without a pattern");case"lowercase":doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`);break;case"uppercase":doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`);break;case"includes":doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`);break;case"starts_with":{const prefix=def.prefix;doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`);break}case"ends_with":{const suffix=def.suffix;doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`);break}default:{throw new ZodCompileUnsupportedError(`string format ${format}`)}}return accessor}function generateCheck(doc,ctx,schema,accessor,needsValue=true){const def=schema._zod.def;const type=def.type;if(def.coerce){throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`)}const buildsValue=needsValue||!!def.checks?.length;let typeAccessor;switch(type){case"string":typeAccessor=generateStringCheck(doc,ctx,schema,accessor,buildsValue);break;case"number":typeAccessor=generateNumberCheck(doc,schema,accessor);break;case"boolean":typeAccessor=generateBooleanCheck(doc,accessor);break;case"bigint":typeAccessor=generateBigIntCheck(doc,schema,accessor);break;case"symbol":typeAccessor=generateSymbolCheck(doc,accessor);break;case"undefined":typeAccessor=generateUndefinedCheck(doc,accessor);break;case"null":typeAccessor=generateNullCheck(doc,accessor);break;case"any":case"unknown":typeAccessor=accessor;break;case"never":doc.write("return INVALID;");typeAccessor=accessor;break;case"void":typeAccessor=generateVoidCheck(doc,accessor);break;case"nan":typeAccessor=generateNaNCheck(doc,accessor);break;case"date":typeAccessor=generateDateCheck(doc,accessor);break;case"object":typeAccessor=generateObjectCheck(doc,ctx,schema,accessor,buildsValue);break;case"optional":typeAccessor=generateOptionalCheck(doc,ctx,schema,accessor,buildsValue);break;case"nullable":typeAccessor=generateNullableCheck(doc,ctx,schema,accessor,buildsValue);break;case"array":typeAccessor=generateArrayCheck(doc,ctx,schema,accessor,buildsValue);break;case"literal":typeAccessor=generateLiteralCheck(doc,ctx,schema,accessor);break;case"enum":typeAccessor=generateEnumCheck(doc,ctx,schema,accessor);break;case"readonly":{const innerOut=generateWrapperCheck(doc,ctx,schema,accessor);const frozenVar=newVar(ctx);doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`);typeAccessor=frozenVar;break}case"success":generateWrapperCheck(doc,ctx,schema,accessor);typeAccessor="true";break;case"default":case"prefault":typeAccessor=generateDefaultCheck(doc,ctx,schema,accessor);break;case"nonoptional":typeAccessor=generateNonOptionalCheck(doc,ctx,schema,accessor);break;case"tuple":typeAccessor=generateTupleCheck(doc,ctx,schema,accessor);break;case"union":typeAccessor=generateUnionCheck(doc,ctx,schema,accessor);break;case"intersection":typeAccessor=generateIntersectionCheck(doc,ctx,schema,accessor);break;case"record":typeAccessor=generateRecordCheck(doc,ctx,schema,accessor);break;case"map":typeAccessor=generateMapCheck(doc,ctx,schema,accessor);break;case"set":typeAccessor=generateSetCheck(doc,ctx,schema,accessor);break;case"file":typeAccessor=generateFileCheck(doc,accessor);break;case"template_literal":typeAccessor=generateTemplateLiteralCheck(doc,ctx,schema,accessor);break;case"lazy":typeAccessor=generateLazyCheck(doc,ctx,schema,accessor);break;case"pipe":typeAccessor=generatePipeCheck(doc,ctx,schema,accessor);break;case"custom":typeAccessor=generateCustomCheck(doc,ctx,schema,accessor);break;case"transform":typeAccessor=generateTransformCheck(doc,ctx,schema,accessor);break;case"catch":typeAccessor=generateCatchCheck(doc,ctx,schema,accessor);break;default:{throw new ZodCompileUnsupportedError(`schema type ${type}`)}}if(typeAccessor===null)return null;return generateChecks(doc,ctx,schema,typeAccessor)}function generateStringCheck(doc,ctx,schema,accessor,needsValue=true){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);const def=schema._zod.def;if(def.format===undefined)return accessor;return generateStringFormatCheck(doc,ctx,def,accessor,needsValue)}function generateNumberCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`);const def=schema._zod.def;if(def.check==="number_format"&&def.format){generateNumberFormatCheck(doc,{format:def.format},accessor)}return accessor}function generateBooleanCheck(doc,accessor){doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`);return accessor}function generateBigIntCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`);const def=schema._zod.def;if(def.format){switch(def.format){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break}}return accessor}function generateSymbolCheck(doc,accessor){doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`);return accessor}function generateUndefinedCheck(doc,accessor){doc.write(`if (${accessor} !== undefined) return INVALID;`);return accessor}function generateNullCheck(doc,accessor){doc.write(`if (${accessor} !== null) return INVALID;`);return accessor}function generateVoidCheck(doc,accessor){doc.write(`if (${accessor} !== undefined) return INVALID;`);return accessor}function generateNaNCheck(doc,accessor){doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`);return accessor}function generateDateCheck(doc,accessor){doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`);return accessor}function generateObjectCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`);const shape=def.shape;const keys=Object.keys(shape);const symbolKeys=Object.getOwnPropertySymbols(shape);const allKeys=symbolKeys.length?[...keys,...symbolKeys]:keys;const keyExpr=(k)=>typeof k==="symbol"?addConstant(ctx,k):esc(k);const propKey=(k)=>typeof k==="symbol"?`[${keyExpr(k)}]`:esc(k);const propShape=shape;if(keys.includes("__proto__")){throw new ZodCompileUnsupportedError('object shape key "__proto__"')}const propOutputs=new Map;for(const key of allKeys){const propSchema=propShape[key];const kx=keyExpr(key);const inputVar=newVar(ctx);doc.write(`const ${inputVar} = ${accessor}[${kx}];`);if(propSchema._zod.optin!==undefined){const outputVar=newVar(ctx);doc.write(`let ${outputVar} = (() => {`);doc.indented((d)=>{const outputAccessor=compileChild(d,ctx,propSchema,inputVar);d.write(`return ${outputAccessor};`)});doc.write(`})();`);if(propSchema._zod.optout==="optional"){doc.write(`if (${outputVar} === INVALID) {`);doc.indented((d)=>{d.write(`if (${kx} in ${accessor}) return INVALID;`);d.write(`${outputVar} = undefined;`)});doc.write(`}`)}else{doc.write(`if (${outputVar} === INVALID) return INVALID;`)}propOutputs.set(key,outputVar)}else{if(requiresPresenceCheck(propSchema)){doc.write(`if (!(${kx} in ${accessor})) return INVALID;`)}const outputAccessor=compileChild(doc,ctx,propSchema,inputVar,buildsValue);if(outputAccessor!==null)propOutputs.set(key,outputAccessor)}}const catchall=def.catchall;let unknownKeysMode="none";if(catchall){const catchallType=catchall._zod.def.type;if(catchallType==="never"){const condition=keys.map((k)=>`k !== ${esc(k)}`).join(" && ")||"true";doc.write(`for (const k in ${accessor}) {`);doc.indented((d)=>{d.write(`if (${condition}) return INVALID;`)});doc.write(`}`)}else if((catchallType==="unknown"||catchallType==="any")&&!catchall._zod.def.checks?.length){unknownKeysMode="passthrough"}else{unknownKeysMode="schema"}}const outputVar=newVar(ctx);const hasConditionalKeys=allKeys.some((k)=>mayOmitUndefined(propShape[k])||dropsWhenAbsent(propShape[k]));if(!buildsValue){if(unknownKeysMode==="schema"){const knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`);doc.indented((d)=>{d.write(`if (k === "__proto__") continue;`);if(knownSet)d.write(`if (${knownSet}.has(k)) continue;`);const valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`);compileChild(d,ctx,catchall,valVar,false)});doc.write(`}`)}return null}if(!hasConditionalKeys){const propLiterals=allKeys.map((k)=>`${propKey(k)}: ${propOutputs.get(k)}`).join(", ");doc.write(`const ${outputVar} = { ${propLiterals} };`)}else{doc.write(`const ${outputVar} = {};`);for(const k of allKeys){const kx=keyExpr(k);const out=propOutputs.get(k);if(dropsWhenAbsent(propShape[k])){doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`)}else if(mayOmitUndefined(propShape[k])){doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`)}else{doc.write(`${outputVar}[${kx}] = ${out};`)}}}if(unknownKeysMode!=="none"){const knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`);doc.indented((d)=>{d.write(`if (k === "__proto__") continue;`);if(knownSet)d.write(`if (${knownSet}.has(k)) continue;`);if(unknownKeysMode==="passthrough"){d.write(`${outputVar}[k] = ${accessor}[k];`)}else{const valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`);const catchallOut=compileChild(d,ctx,catchall,valVar);d.write(`${outputVar}[k] = ${catchallOut};`)}});doc.write(`}`)}return outputVar}function generateOptionalCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;if(isExactOptional(schema)){return generateCheck(doc,ctx,def.innerType,accessor,buildsValue)}if(def.innerType._zod.optin==="defaulted"){const outputVar=newVar(ctx);const branchVar=newVar(ctx);doc.write(`let ${outputVar};`);doc.write(`if (${accessor} === undefined) {`);doc.indented((d)=>{d.write(`const ${branchVar} = (() => {`);d.indented((d2)=>{const innerOutput=generateCheck(d2,ctx,def.innerType,accessor);d2.write(`return ${innerOutput};`)});d.write(`})();`);d.write(`if (${branchVar} !== INVALID) ${outputVar} = ${branchVar};`)});doc.write(`} else {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`);return outputVar}const outputVar=buildsValue?newVar(ctx):null;if(outputVar)doc.write(`let ${outputVar};`);doc.write(`if (${accessor} !== undefined) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);if(outputVar&&innerOutput!==null)d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`);return outputVar}function isExactOptional(schema){return schema._zod.traits?.has("$ZodExactOptional")===true}function requiresPresenceCheck(schema){return schema._zod.optin===undefined&&fastPathAcceptsAbsence(schema)}function fastPathAcceptsAbsence(schema){if(schema._zod.def.coerce)return true;const def=schema._zod.def;switch(def.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return true;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return false;case"nonoptional":return def.innerType?fastPathAcceptsAbsence(def.innerType):false;case"literal":return!!def.values?.includes(undefined);case"enum":return!!schema._zod.values?.has(undefined);case"optional":case"nullable":case"readonly":case"success":return def.innerType?fastPathAcceptsAbsence(def.innerType):true;case"catch":return true;case"union":return def.options?def.options.some(fastPathAcceptsAbsence):true;case"intersection":if(!def.left||!def.right)return true;return fastPathAcceptsAbsence(def.left)&&fastPathAcceptsAbsence(def.right);case"pipe":return def.in?fastPathAcceptsAbsence(def.in):true;default:return true}}function dropsWhenAbsent(schema){return schema._zod.optin==="optional"&&schema._zod.optout==="optional"}function mayOmitUndefined(schema){return(schema._zod.optin!=="defaulted"||schema._zod.optout==="optional")&&mayOutputUndefined(schema)}function mayOutputUndefined(schema){const def=schema._zod.def;switch(def.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return false;case"literal":return!!def.values?.includes(undefined);case"enum":return!!schema._zod.values?.has(undefined);case"optional":return true;case"nullable":case"readonly":case"nonoptional":return def.innerType?mayOutputUndefined(def.innerType):true;case"union":return def.options?def.options.some(mayOutputUndefined):true;case"intersection":return!def.left||!def.right||mayOutputUndefined(def.left)||mayOutputUndefined(def.right);case"pipe":return def.out?mayOutputUndefined(def.out):true;default:return true}}function generateNullableCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;const outputVar=buildsValue?newVar(ctx):null;if(outputVar)doc.write(`let ${outputVar} = null;`);doc.write(`if (${accessor} !== null) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);if(outputVar&&innerOutput!==null)d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`);return outputVar}function generateArrayCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);const outputVar=buildsValue?newVar(ctx):null;const iVar=newVar(ctx);const elemVar=newVar(ctx);if(outputVar)doc.write(`const ${outputVar} = new Array(${accessor}.length);`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);const elemOutput=compileChild(d,ctx,def.element,elemVar,buildsValue);if(outputVar&&elemOutput!==null)d.write(`${outputVar}[${iVar}] = ${elemOutput};`)});doc.write(`}`);return outputVar}function generateLiteralCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const values=def.values;if(values.length!==1){const literalSet=addConstant(ctx,new Set(values));doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);return accessor}const value=values[0];if(typeof value==="number"&&Number.isNaN(value)){const literalSet=addConstant(ctx,new Set(values));doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);return accessor}if(typeof value==="string"){doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`)}else if(typeof value==="number"||typeof value==="boolean"){doc.write(`if (${accessor} !== ${value}) return INVALID;`)}else if(value===null){doc.write(`if (${accessor} !== null) return INVALID;`)}else if(value===undefined){doc.write(`if (${accessor} !== undefined) return INVALID;`)}else if(typeof value==="bigint"){doc.write(`if (${accessor} !== ${value}n) return INVALID;`)}else{throw new ZodCompileUnsupportedError(`literal type ${typeof value}`)}return accessor}function generateEnumCheck(doc,ctx,schema,accessor){const values=schema._zod.values;if(!values){throw new ZodCompileUnsupportedError("enum schema without enumerated values")}const enumSet=addConstant(ctx,values);doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`);return accessor}function generateWrapperCheck(doc,ctx,schema,accessor){const def=schema._zod.def;return generateCheck(doc,ctx,def.innerType,accessor)}function generateDefaultCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const descriptor=Object.getOwnPropertyDescriptor(schema._zod.def,"defaultValue");const defaultGetter=descriptor?()=>schema._zod.def.defaultValue:undefined;if(schema._zod.def.type==="prefault"){if(!defaultGetter){return generateCheck(doc,ctx,def.innerType,accessor)}const defaultFn=addConstant(ctx,defaultGetter);const inputVar=newVar(ctx);doc.write(`let ${inputVar} = ${accessor};`);doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`);return generateCheck(doc,ctx,def.innerType,inputVar)}const outputVar=newVar(ctx);if(defaultGetter){const defaultFn=addConstant(ctx,defaultGetter);const cloneFn=addConstant(ctx,shallowClone);doc.write(`let ${outputVar};`);doc.write(`if (${accessor} === undefined) {`);doc.indented((d)=>{d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`)});doc.write(`} else {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`)});doc.write(`}`)}else{doc.write(`let ${outputVar};`);doc.write(`if (${accessor} !== undefined) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`)}return outputVar}function generateNonOptionalCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const innerOutput=generateCheck(doc,ctx,def.innerType,accessor);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${innerOutput};`);doc.write(`if (${outputVar} === undefined) return INVALID;`);return outputVar}function generateTupleCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const items=def.items;const rest=def.rest;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);const optinStart=getTupleOptStart2(items,"optin");const optoutStart=getTupleOptStart2(items,"optout");if(rest){doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`)}else{doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`)}const outputVar=newVar(ctx);doc.write(`const ${outputVar} = [];`);for(let i=0;i<items.length;i++){const itemSchema=items[i];if(i>=optoutStart){doc.write(`if (${outputVar}.length === ${i}) {`);doc.indented((d)=>{d.write(`if (${i} < ${accessor}.length) {`);d.indented((d2)=>{const elemVar=newVar(ctx);d2.write(`const ${elemVar} = ${accessor}[${i}];`);const elemOutput=compileChild(d2,ctx,itemSchema,elemVar);d2.write(`${outputVar}[${i}] = ${elemOutput};`)});d.write(`} else {`);d.indented((d2)=>{if(dropsWhenAbsent(itemSchema)){d2.write(`${outputVar}.length = ${i};`);return}const elemVar=newVar(ctx);const branchVar=newVar(ctx);d2.write(`const ${elemVar} = undefined;`);d2.write(`const ${branchVar} = (() => {`);d2.indented((d3)=>{const elemOutput=compileChild(d3,ctx,itemSchema,elemVar);d3.write(`return ${elemOutput};`)});d2.write(`})();`);d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`);d2.write(`else ${outputVar}[${i}] = ${branchVar};`)});d.write(`}`)});doc.write(`}`)}else{const elemVar=newVar(ctx);doc.write(`const ${elemVar} = ${accessor}[${i}];`);const elemOutput=compileChild(doc,ctx,itemSchema,elemVar);doc.write(`${outputVar}[${i}] = ${elemOutput};`)}}if(rest){const iVar=newVar(ctx);const elemVar=newVar(ctx);doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);const elemOutput=compileChild(d,ctx,rest,elemVar);d.write(`${outputVar}[${iVar}] = ${elemOutput};`)});doc.write(`}`)}return outputVar}function getTupleOptStart2(items,key){for(let i=items.length-1;i>=0;i--){const omittable=key==="optin"?items[i]._zod.optin!==undefined:items[i]._zod.optout==="optional";if(!omittable)return i+1}return 0}function generateUnionCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const options=def.options;if(def.discriminator){return generateDiscriminatedUnionCheck(doc,ctx,def,accessor)}if(def.inclusive===false){throw new ZodCompileUnsupportedError("exclusive unions (z.xor)")}if(options.length===0){doc.write("return INVALID;");return accessor}if(options.length===1){return generateCheck(doc,ctx,options[0],accessor)}const allLiterals=options.every((opt)=>opt._zod.def.type==="literal"&&!opt._zod.def.checks?.length);if(allLiterals){const values=new Set(options.flatMap((opt)=>opt._zod.def.values));const valuesConst=addConstant(ctx,values);doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`);return accessor}const outputVar=newVar(ctx);doc.write(`let ${outputVar};`);for(let i=0;i<options.length;i++){const opt=options[i];if(i===0){doc.write(`${outputVar} = (() => {`)}else{doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`)}doc.indented((d)=>{const branchOutput=generateCheck(d,ctx,opt,accessor);d.write(`return ${branchOutput};`)});doc.write(`})();`)}doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}function generateDiscriminatedUnionCheck(doc,ctx,def,accessor){if(def.unionFallback){throw new ZodCompileUnsupportedError("discriminated union with unionFallback")}if(def.options.length===0){doc.write("return INVALID;");return accessor}const discVar=newVar(ctx);const outputVar=newVar(ctx);doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`);doc.write(`let ${outputVar};`);let firstBranch=true;const claimed=new Set;for(const option of def.options){const values=option._zod.propValues?.[def.discriminator];if(!values||values.size===0){throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values")}for(const value of values){if(claimed.has(value)){throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`)}claimed.add(value)}const conditions=Array.from(values,(value)=>literalEquality(ctx,discVar,value));const prefix=firstBranch?"if":"else if";doc.write(`${prefix} (${conditions.join(" || ")}) {`);doc.indented((d)=>{const branchOutput=generateCheck(d,ctx,option,accessor);d.write(`${outputVar} = ${branchOutput};`)});doc.write(`}`);firstBranch=false}doc.write(`else { return INVALID; }`);return outputVar}function literalEquality(ctx,accessor,value){if(typeof value==="string")return`${accessor} === ${esc(value)}`;if(typeof value==="number"){if(Number.isNaN(value))return`Number.isNaN(${accessor})`;return`${accessor} === ${value}`}if(typeof value==="boolean")return`${accessor} === ${value}`;if(value===null)return`${accessor} === null`;if(value===undefined)return`${accessor} === undefined`;if(typeof value==="bigint")return`${accessor} === ${value}n`;if(typeof value==="symbol"){const symbolConst=addConstant(ctx,value);return`${accessor} === ${symbolConst}`}throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`)}function generateIntersectionCheck(doc,ctx,schema,accessor){const def=schema._zod.def;ctx.definite=false;const leftOutput=compileChild(doc,ctx,def.left,accessor);const rightOutput=compileChild(doc,ctx,def.right,accessor);const mergeConst=addConstant(ctx,mergeValues);const mergedVar=newVar(ctx);doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`);doc.write(`if (!${mergedVar}.valid) return INVALID;`);return`${mergedVar}.data`}function generateRecordCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const isPlainObjectConst=addConstant(ctx,isPlainObject);doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`);const outputVar=newVar(ctx);const kVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = {};`);const recordDef=def;const keyValues=recordDef.partial?undefined:def.keyType._zod.values;if(keyValues){const inputKeys=[];for(const key of keyValues){if(!(typeof key==="string"||typeof key==="number"||typeof key==="symbol")){throw new ZodCompileUnsupportedError(`record key value ${String(key)}`)}const inputKey=typeof key==="number"?key.toString():key;if(inputKey==="__proto__"){throw new ZodCompileUnsupportedError('record key "__proto__"')}inputKeys.push(inputKey);const keyConst=addConstant(ctx,key);const outKey=generateCheck(doc,ctx,def.keyType,keyConst);const valueVar=newVar(ctx);doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx,inputKey)}];`);const valOutput=compileChild(doc,ctx,def.valueType,valueVar);doc.write(`${outputVar}[${outKey}] = ${valOutput};`)}const knownKeysConst=addConstant(ctx,new Set(inputKeys));doc.write(`for (const ${kVar} in ${accessor}) {`);doc.indented((d)=>{d.write(`if (${knownKeysConst}.has(${kVar})) continue;`);if(recordDef.mode==="loose"){d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`)}else{d.write(`return INVALID;`)}});doc.write(`}`);return outputVar}const keyDef=def.keyType._zod.def;const keyIsBareString=keyDef.type==="string"&&keyDef.format===undefined&&!keyDef.coerce&&(keyDef.checks?.length??0)===0;if(!keyIsBareString){const isLoose=def.mode==="loose";const keyFn=compileFn(def.keyType);if(keyFn.definite===false)ctx.definite=false;const keyFast=addConstant(ctx,keyFn);const numericConst=addConstant(ctx,number);const outKeyVar=newVar(ctx);emitOwnKeys(doc,ctx,accessor,kVar,(d)=>{d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`);d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`);if(isLoose){d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`)}else{d.write(`if (${outKeyVar} === INVALID) return INVALID;`)}d.write(`if (${outKeyVar} === "__proto__") continue;`);const valueVar=newVar(ctx);d.write(`const ${valueVar} = ${accessor}[${kVar}];`);const valOutput=compileChild(d,ctx,def.valueType,valueVar);d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`)});return outputVar}emitOwnKeys(doc,ctx,accessor,kVar,(d)=>{d.write(`const ${valVar} = ${accessor}[${kVar}];`);const valOutput=compileChild(d,ctx,def.valueType,valVar);d.write(`${outputVar}[${kVar}] = ${valOutput};`)},`return INVALID;`);return outputVar}function emitOwnKeys(doc,ctx,accessor,kVar,body,onSymbol){const propIsEnumerableConst=addConstant(ctx,Object.prototype.propertyIsEnumerable);const symsVar=newVar(ctx);const keysVar=newVar(ctx);const iVar=newVar(ctx);doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`);doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${kVar} = ${keysVar}[${iVar}];`);d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);body(d)});doc.write(`}`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${kVar} = ${symsVar}[${iVar}];`);d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);if(onSymbol)d.write(onSymbol);else body(d)});doc.write(`}`)}function literalPropertyKey(ctx,key){if(typeof key==="string")return esc(key);return addConstant(ctx,key)}function generateMapCheck(doc,ctx,schema,accessor){const def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`);const outputVar=newVar(ctx);const kVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = new Map();`);doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`);doc.indented((d)=>{const keyOutput=generateCheck(d,ctx,def.keyType,kVar);const valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`)});doc.write(`}`);return outputVar}function generateSetCheck(doc,ctx,schema,accessor){const def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`);const outputVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = new Set();`);doc.write(`for (const ${valVar} of ${accessor}) {`);doc.indented((d)=>{const valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.add(${valOutput});`)});doc.write(`}`);return outputVar}function generateFileCheck(doc,accessor){doc.write(`if (!(${accessor} instanceof File)) return INVALID;`);return accessor}function generateTemplateLiteralCheck(doc,ctx,schema,accessor){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);const pattern=schema._zod.pattern;if(pattern){const patternConst=addConstant(ctx,pattern);doc.write(`${patternConst}.lastIndex = 0;`);doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`)}return accessor}function generateLazyCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const getterConst=addUserConstant(ctx,def.getter);const cacheConst=addConstant(ctx,{parser:null});doc.write(`if (!${cacheConst}.parser) {`);doc.indented((d)=>{d.write(`const inner = ${getterConst}();`);d.write(`${cacheConst}.parser = function(input) {`);d.indented((d2)=>{d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`);d2.write(`return result.issues.length === 0 ? result.value : INVALID;`)});d.write(`};`)});doc.write(`}`);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`);doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}function generatePipeCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const inputOutput=generateCheck(doc,ctx,def.in,accessor);if(def.transform){if(isAsyncFunction(def.transform)){throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported")}const transformFn=def.transform;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=transformFn(value,fakePayload);if(result instanceof Promise)return INVALID;return fakePayload.issues.length===0?result:INVALID};const helperConst=addUserConstant(ctx,helperFn);const transformedVar=newVar(ctx);doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`);doc.write(`if (${transformedVar} === INVALID) return INVALID;`);return generateCheck(doc,ctx,def.out,transformedVar)}else{return generateCheck(doc,ctx,def.out,inputOutput)}}function isAsyncFunction(fn){return typeof fn==="function"&&(fn.constructor.name==="AsyncFunction"||fn[Symbol.toStringTag]==="AsyncFunction")}function generateCustomCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(def.fn){if(isAsyncFunction(def.fn)){throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported")}const fnConst=addUserConstant(ctx,def.fn);const throwAsyncConst=addConstant(ctx,throwAsync);const resVar=newVar(ctx);doc.write(`const ${resVar} = ${fnConst}(${accessor});`);doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);doc.write(`if (!${resVar}) return INVALID;`)}else{throw new ZodCompileUnsupportedError("custom schema without a predicate function")}return accessor}function runtimeCatch(innerSchema,catchValue,value){const result=innerSchema._zod.run({value,issues:[]},{});if(result&&typeof result.then==="function")return INVALID;const r=result;if(r.issues.length===0)return r.value;return catchValue()}function generateCatchCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(!def.catchValue[CONSTANT_CATCH]){throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)",false)}const outputVar=newVar(ctx);doc.write(`let ${outputVar} = (() => {`);doc.indented((d)=>{const innerOut=compileChild(d,ctx,def.innerType,accessor);d.write(`return ${innerOut};`)});doc.write(`})();`);const innerConst=addConstant(ctx,def.innerType);const catchConst=addUserConstant(ctx,def.catchValue);const catchHelperConst=addConstant(ctx,runtimeCatch);doc.write(`if (${outputVar} === INVALID) {`);doc.indented((d)=>{d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`);d.write(`if (${outputVar} === INVALID) return INVALID;`)});doc.write(`}`);return outputVar}function generateTransformCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(def.transform){if(isAsyncFunction(def.transform)){throw new ZodCompileAsyncError("z.compile: async transforms are not supported")}const transformFn=def.transform;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=transformFn(value,fakePayload);if(result instanceof Promise)return INVALID;return fakePayload.issues.length===0?result:INVALID};const helperConst=addUserConstant(ctx,helperFn);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${helperConst}(${accessor});`);doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}return accessor}function snapshotChecks(def){if(def.checks)def.checks=[...def.checks];return def}function _string(Class,params){return new Class(snapshotChecks({type:"string",...normalizeParams(params)}))}function _coercedString(Class,params){return new Class(snapshotChecks({type:"string",coerce:true,...normalizeParams(params)}))}function _email(Class,params){return new Class({type:"string",format:"email",check:"string_format",abort:false,...normalizeParams(params)})}function _guid(Class,params){return new Class({type:"string",format:"guid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuid(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuidv4(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v4",...normalizeParams(params)})}function _uuidv6(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v6",...normalizeParams(params)})}function _uuidv7(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v7",...normalizeParams(params)})}function _url(Class,params){return new Class({type:"string",format:"url",check:"string_format",abort:false,...normalizeParams(params)})}function _emoji2(Class,params){return new Class({type:"string",format:"emoji",check:"string_format",abort:false,...normalizeParams(params)})}function _nanoid(Class,params){return new Class({type:"string",format:"nanoid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid(Class,params){return new Class({type:"string",format:"cuid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid2(Class,params){return new Class({type:"string",format:"cuid2",check:"string_format",abort:false,...normalizeParams(params)})}function _ulid(Class,params){return new Class({type:"string",format:"ulid",check:"string_format",abort:false,...normalizeParams(params)})}function _xid(Class,params){return new Class({type:"string",format:"xid",check:"string_format",abort:false,...normalizeParams(params)})}function _ksuid(Class,params){return new Class({type:"string",format:"ksuid",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv4(Class,params){return new Class({type:"string",format:"ipv4",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv6(Class,params){return new Class({type:"string",format:"ipv6",check:"string_format",abort:false,...normalizeParams(params)})}function _mac(Class,params){return new Class({type:"string",format:"mac",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv4(Class,params){return new Class({type:"string",format:"cidrv4",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv6(Class,params){return new Class({type:"string",format:"cidrv6",check:"string_format",abort:false,...normalizeParams(params)})}function _base64(Class,params){return new Class({type:"string",format:"base64",check:"string_format",abort:false,...normalizeParams(params)})}function _base64url(Class,params){return new Class({type:"string",format:"base64url",check:"string_format",abort:false,...normalizeParams(params)})}function _e164(Class,params){return new Class({type:"string",format:"e164",check:"string_format",abort:false,...normalizeParams(params)})}function _creditCard(Class,params){return new Class({type:"string",format:"credit_card",check:"string_format",abort:false,...normalizeParams(params)})}function _iban(Class,params){return new Class({type:"string",format:"iban",check:"string_format",abort:false,...normalizeParams(params)})}function _jwt(Class,params){return new Class({type:"string",format:"jwt",check:"string_format",abort:false,...normalizeParams(params)})}var TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function _isoDateTime(Class,params){return new Class({type:"string",format:"datetime",check:"string_format",offset:false,local:false,precision:null,...normalizeParams(params)})}function _isoDate(Class,params){return new Class({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class,params){return new Class({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class,params){return new Class({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class,params){return new Class(snapshotChecks({type:"number",checks:[],...normalizeParams(params)}))}function _coercedNumber(Class,params){return new Class(snapshotChecks({type:"number",coerce:true,checks:[],...normalizeParams(params)}))}function _int(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"safeint",...normalizeParams(params)})}function _float32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"float32",...normalizeParams(params)})}function _float64(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"float64",...normalizeParams(params)})}function _int32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"int32",...normalizeParams(params)})}function _uint32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"uint32",...normalizeParams(params)})}function _boolean(Class,params){return new Class({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class,params){return new Class({type:"boolean",coerce:true,...normalizeParams(params)})}function _bigint(Class,params){return new Class({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class,params){return new Class({type:"bigint",coerce:true,...normalizeParams(params)})}function _int64(Class,params){return new Class({type:"bigint",check:"bigint_format",abort:false,format:"int64",...normalizeParams(params)})}function _uint64(Class,params){return new Class({type:"bigint",check:"bigint_format",abort:false,format:"uint64",...normalizeParams(params)})}function _symbol(Class,params){return new Class({type:"symbol",...normalizeParams(params)})}function _undefined2(Class,params){return new Class({type:"undefined",...normalizeParams(params)})}function _null2(Class,params){return new Class({type:"null",...normalizeParams(params)})}function _any(Class){return new Class({type:"any"})}function _unknown(Class){return new Class({type:"unknown"})}function _never(Class,params){return new Class({type:"never",...normalizeParams(params)})}function _void(Class,params){return new Class({type:"void",...normalizeParams(params)})}function _date(Class,params){return new Class({type:"date",...normalizeParams(params)})}function _coercedDate(Class,params){return new Class({type:"date",coerce:true,...normalizeParams(params)})}function _nan(Class,params){return new Class({type:"nan",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:false})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:true})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:false})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:true})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size})}function _maxLength(maximum,params){const ch=new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum});return ch}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _properties(shape,params){return new $ZodCheckProperties({check:"properties",shape,...normalizeParams(params)})}function _mime(types,params){return new $ZodCheckMimeType({check:"mime_type",mime:types,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite((input)=>input.normalize(form))}function _trim(){return _overwrite((input)=>input.trim())}function _toLowerCase(){return _overwrite((input)=>input.toLowerCase())}function _toUpperCase(){return _overwrite((input)=>input.toUpperCase())}function _slugify(){return _overwrite((input)=>slugify(input))}function _array(Class,element,params){return new Class({type:"array",element,...normalizeParams(params)})}function _union(Class,options,params){return new Class({type:"union",options,...normalizeParams(params)})}function _xor(Class,options,params){return new Class({type:"union",options,inclusive:false,...normalizeParams(params)})}function _discriminatedUnion(Class,discriminator,options,params){return new Class({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class,left,right){return new Class({type:"intersection",left,right})}function _tuple(Class,items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new Class({type:"tuple",items,rest,...normalizeParams(params)})}function _record(Class,keyType,valueType,params){return new Class({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class,keyType,valueType,params){return new Class({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class,valueType,params){return new Class({type:"set",valueType,...normalizeParams(params)})}function _enum(Class,values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new Class({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class,entries,params){return new Class({type:"enum",entries,...normalizeParams(params)})}function _literal(Class,value,params){return new Class({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function _file(Class,params){return new Class({type:"file",...normalizeParams(params)})}function _transform(Class,fn){return new Class({type:"transform",transform:fn})}function _optional(Class,innerType){return new Class({type:"optional",innerType})}function _nullable(Class,innerType){return new Class({type:"nullable",innerType})}function _default(Class,innerType,defaultValue){return new Class({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class,innerType,params){return new Class({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class,innerType){return new Class({type:"success",innerType})}function _catch(Class,innerType,catchValue){return new Class({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}function _pipe(Class,in_,out){return new Class({type:"pipe",in:in_,out})}function _readonly(Class,innerType){return new Class({type:"readonly",innerType})}function _templateLiteral(Class,parts,params){return new Class({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class,getter){return new Class({type:"lazy",getter})}function _promise(Class,innerType){return new Class({type:"promise",innerType})}function _custom(Class,fn,_params){const norm=normalizeParams(_params);norm.abort??(norm.abort=true);const schema=new Class({type:"custom",check:"custom",fn,...norm});return schema}function _refine(Class,fn,_params){const schema=new Class({type:"custom",check:"custom",fn,...normalizeParams(_params)});return schema}function _superRefine(fn,params){const ch=_check((payload)=>{payload.addIssue=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,ch._zod.def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");if(!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=ch);_issue.continue??(_issue.continue=!ch._zod.def.abort);payload.issues.push(issue(_issue))}};return fn(payload.value,payload)},params);return ch}function _check(fn,params){const ch=new $ZodCheck({check:"custom",...normalizeParams(params)});ch._zod.check=fn;return ch}function describe(description){const ch=new $ZodCheck({check:"describe"});ch._zod.onattach=[(inst)=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}];ch._zod.check=()=>{};return ch}function meta(metadata){const ch=new $ZodCheck({check:"meta"});ch._zod.onattach=[(inst)=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}];ch._zod.check=()=>{};return ch}function _stringbool(Classes,_params){const params=normalizeParams(_params);let truthyArray=params.truthy??["true","1","yes","on","y","enabled"];let falsyArray=params.falsy??["false","0","no","off","n","disabled"];if(params.case!=="sensitive"){truthyArray=truthyArray.map((v)=>typeof v==="string"?v.toLowerCase():v);falsyArray=falsyArray.map((v)=>typeof v==="string"?v.toLowerCase():v)}const truthySet=new Set(truthyArray);const falsySet=new Set(falsyArray);const _Codec=Classes.Codec??$ZodCodec;const _Boolean=Classes.Boolean??$ZodBoolean;const _String=Classes.String??$ZodString;const stringSchema=new _String({type:"string",error:params.error});const booleanSchema=new _Boolean({type:"boolean",error:params.error});const codec=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:(input,payload)=>{let data=input;if(params.case!=="sensitive")data=data.toLowerCase();if(truthySet.has(data)){return true}else if(falsySet.has(data)){return false}else{payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec,continue:false});return{}}},reverseTransform:(input,_payload)=>{if(input===true){return truthyArray[0]||"true"}else{return falsyArray[0]||"false"}},error:params.error});codec._zod.bag.truthy=truthyArray;codec._zod.bag.falsy=falsyArray;codec._zod.bag.case=params.case??"insensitive";return codec}function _stringFormat(Class,format,fnOrRegex,_params={}){const params=normalizeParams(_params);const def={check:"string_format",type:"string",format,fn:typeof fnOrRegex==="function"?fnOrRegex:(val)=>fnOrRegex.test(val),...params};if(fnOrRegex instanceof RegExp){def.pattern=fnOrRegex}const inst=new Class(def);return inst}function assignProps(target,...sources){for(const source of sources){for(const key of Reflect.ownKeys(source)){if(Object.prototype.propertyIsEnumerable.call(source,key)){assignProp(target,key,source[key])}}}return target}function initializeContext(params){let target=params?.target??"draft-2020-12";if(target==="draft-4")target="draft-04";if(target==="draft-7")target="draft-07";return{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:undefined,sharedEmitDoneFor:undefined,cycles:params?.cycles??"ref",reused:params?.reused??"inline",intersections:[],deferred:[],external:params?.external??undefined}}function handleUnrepresentable(schema,ctx,json,params,message){const result=typeof ctx.unrepresentable==="function"?ctx.unrepresentable({zodSchema:schema,path:params.path,message}):ctx.unrepresentable;if(result==="any")return false;if(result===undefined||result==="throw")throw new Error(message);Object.assign(json,result);return true}function processSchema(schema,ctx,_params={path:[],schemaPath:[]}){var _a;const def=schema._zod.def;const seen=ctx.seen.get(schema);if(seen){seen.count++;const isCycle=_params.schemaPath.includes(schema);if(isCycle){seen.cycle=_params.path}return seen.schema}const result={schema:{},count:1,cycle:undefined,path:_params.path};ctx.seen.set(schema,result);ctx.sharedDefsExtractedFor=undefined;ctx.sharedEmitDoneFor=undefined;const overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema){result.schema=overrideSchema}else{const params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema){schema._zod.processJSONSchema(ctx,result.schema,params)}else{const _json=result.schema;const processor=ctx.processors[def.type];if(!processor){throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`)}processor(schema,ctx,_json,params)}const parent=schema._zod.parent;if(parent){if(!result.ref)result.ref=parent;processSchema(parent,ctx,params);ctx.seen.get(parent).isParent=true}}const meta=ctx.metadataRegistry.get(schema);if(meta)assignProps(result.schema,meta);if(ctx.io==="input"&&isTransforming(schema)){delete result.schema.examples;delete result.schema.default}if(ctx.io==="input"&&"_prefault"in result.schema)(_a=result.schema).default??(_a.default=result.schema._prefault);delete result.schema._prefault;const _result=ctx.seen.get(schema);return _result.schema}function encodeJSONPointerSegment(segment){return segment.replace(/~/g,"~0").replace(/\//g,"~1")}function extractDefs(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");if(ctx.external&&ctx.sharedDefsExtractedFor===ctx.external)return;const idToSchema=new Map;for(const entry of ctx.seen.entries()){const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){const existing=idToSchema.get(id);if(existing&&existing!==entry[0]){throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`)}idToSchema.set(id,entry[0])}}const makeURI=(entry)=>{const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){const externalId=ctx.external.registry.get(entry[0])?.id;const uriGenerator=ctx.external.uri??((id)=>id);if(externalId){return{ref:uriGenerator(externalId)}}const id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;entry[1].defId=id;return{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}`}}const uriPrefix=`#`;const defUriPrefix=`${uriPrefix}/${defsSegment}/`;if(entry[1]===root&&!entry[1].schema.id){return{ref:uriPrefix}}const defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+encodeJSONPointerSegment(defId)}};const extractToDef=(entry)=>{if(entry[1].schema.$ref){return}const seen=entry[1];const{ref,defId}=makeURI(entry);seen.def={...seen.schema};if(defId)seen.defId=defId;const schema=seen.schema;for(const key in schema){delete schema[key]}schema.$ref=ref};if(ctx.cycles==="throw"){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.cycle){throw new Error("Cycle detected: "+`#/${seen.cycle?.join("/")}/<root>`+'\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.')}}}for(const entry of ctx.seen.entries()){const seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){const ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry)}}}if(ctx.external)ctx.sharedDefsExtractedFor=ctx.external}function compactTypeUnion(schema){const options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==undefined)return;const types=[];for(const option of options){if(!option||typeof option!=="object")return;compactTypeUnion(option);const keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;const type=option.type;for(const member of Array.isArray(type)?type:[type]){if(typeof member!=="string")return;if(!types.includes(member))types.push(member)}}delete schema.anyOf;schema.type=types.length===1?types[0]:types}var FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]);var UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){const extra=member.additionalProperties;if(extra===undefined||extra===false||typeof extra!=="object"||extra===null)return null;return Object.keys(extra).length?extra:null}function foldObjects(members){const objects=[];for(const member of members){if(typeof member!=="object"||member.type!=="object")return null;for(const key in member){if(!FOLDABLE_KEYS.has(key))return null}objects.push(member)}const properties={};const required=new Set;for(const object of objects){for(const key in object.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;const parts=[];for(const other of objects){const part=other.properties?.[key]??undeclaredConstraint(other);if(part===null||part===undefined)continue;if(!parts.some((seen)=>JSON.stringify(seen)===JSON.stringify(part)))parts.push(part)}const merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(const key of object.required??[])required.add(key)}const folded={type:"object",properties};if(required.size)folded.required=[...required];if(objects.every((object)=>object.additionalProperties===false)){folded.additionalProperties=false}else{const constraints=[];for(const object of objects){const constraint=undeclaredConstraint(object);if(constraint&&!constraints.some((seen)=>JSON.stringify(seen)===JSON.stringify(constraint)))constraints.push(constraint)}if(constraints.length===1)folded.additionalProperties=constraints[0];else if(constraints.length>1)folded.additionalProperties={allOf:constraints}}return folded}function foldIntersection(json){const allOf=json.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(const key of FOLDABLE_KEYS)if(key in json)return;const unions=allOf.filter((m)=>UNION_KEYS.some((k)=>Array.isArray(m[k])));let folded=null;if(!unions.length){folded=foldObjects(allOf)}else{const union=unions[0];const keyword=UNION_KEYS.find((k)=>Array.isArray(union[k]));if(Object.keys(union).length!==1)return;const rest=allOf.filter((m)=>m!==union);const branches=union[keyword].map((branch)=>foldObjects([...rest,branch]));if(branches.some((b)=>!b))return;folded={[keyword]:branches}}if(!folded)return;delete json.allOf;assignProps(json,folded)}function finalize(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");const flattenRef=(zodSchema)=>{const seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;const schema=seen.def??seen.schema;const _cached={...schema};const ref=seen.ref;seen.ref=null;if(ref){flattenRef(ref);const refSeen=ctx.seen.get(ref);const refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")){schema.allOf=schema.allOf??[];schema.allOf.push(refSchema)}else{assignProps(schema,refSchema)}assignProps(schema,_cached);const isParentRef=zodSchema._zod.parent===ref;if(isParentRef){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached)){delete schema[key]}}}if(refSchema.$ref&&refSeen.def){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema[key])===JSON.stringify(refSeen.def[key])){delete schema[key]}}}}const parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);const parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){schema.$ref=parentSeen.schema.$ref;if(parentSeen.def){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema[key])===JSON.stringify(parentSeen.def[key])){delete schema[key]}}}}}ctx.override({zodSchema,jsonSchema:schema,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(const entry of[...ctx.seen.entries()].reverse()){flattenRef(entry[0])}if(ctx.target!=="openapi-3.0"){for(const entry of ctx.seen.entries()){compactTypeUnion(entry[1].def??entry[1].schema)}}for(const rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){const carriers=new Map;for(const seen of ctx.seen.values()){for(const json of[seen.schema,seen.def]){const allOf=json?.allOf;if(!Array.isArray(allOf))continue;const existing=carriers.get(allOf);if(existing)existing.push(json);else carriers.set(allOf,[json])}}for(const allOf of ctx.intersections){for(const json of carriers.get(allOf)??[])foldIntersection(json)}}}const result={};if(ctx.target==="draft-2020-12"){result.$schema="https://json-schema.org/draft/2020-12/schema"}else if(ctx.target==="draft-07"){result.$schema="http://json-schema.org/draft-07/schema#"}else if(ctx.target==="draft-04"){result.$schema="http://json-schema.org/draft-04/schema#"}else if(ctx.target==="openapi-3.0"){}if(ctx.external?.uri){const id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);const rootMetaId=ctx.metadataRegistry.get(schema)?.id;if(rootMetaId!==undefined&&result.id===rootMetaId)delete result.id;const defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.def&&seen.defId){if(seen.def.id===seen.defId)delete seen.def.id;assignProp(defs,seen.defId,seen.def)}}}if(ctx.external)ctx.sharedEmitDoneFor=ctx.external;if(ctx.external){}else{if(Object.keys(defs).length>0){if(ctx.target==="draft-2020-12"){result.$defs=defs}else{result.definitions=defs}}}try{const finalized=JSON.parse(JSON.stringify(result));Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:false,writable:false});return finalized}catch(_err){throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){const ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return false;ctx.seen.add(_schema);const def=_schema._zod.def;if(def.type==="transform")return true;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch"){return isTransforming(def.innerType,ctx)}if(def.type==="intersection"){return isTransforming(def.left,ctx)||isTransforming(def.right,ctx)}if(def.type==="record"||def.type==="map"){return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx)}if(def.type==="pipe"){if(_schema._zod.traits.has("$ZodCodec"))return true;return isTransforming(def.in,ctx)||isTransforming(def.out,ctx)}if(def.type==="object"){for(const key in def.shape){if(isTransforming(def.shape[key],ctx))return true}return false}if(def.type==="union"){for(const option of def.options){if(isTransforming(option,ctx))return true}return false}if(def.type==="tuple"){for(const item of def.items){if(isTransforming(item,ctx))return true}if(def.rest&&isTransforming(def.rest,ctx))return true;return false}return false}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{const ctx=initializeContext({...params,processors});processSchema(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{const{libraryOptions,target}=params??{};const ctx=initializeContext({...libraryOptions??{},target,io,processors});processSchema(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var narrowMin=(agg,key,value)=>{if(agg[key]===undefined||value>agg[key])agg[key]=value};var narrowMax=(agg,key,value)=>{if(agg[key]===undefined||value<agg[key])agg[key]=value};var narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value);narrowMax(agg,"maximum",value)};var addDivisor=(agg,value)=>{agg.multipleOf??(agg.multipleOf=[]);if(!agg.multipleOf.includes(value))agg.multipleOf.push(value)};var addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set);agg.patterns.add(pattern)};var intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter((m)=>mime.includes(m)):[...mime]};var setFormat=(agg,format)=>{agg.format=format;if(format.includes("int"))agg.isInt=true};var minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum);var maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum);var formatContributor=(ranges)=>(agg,def)=>{setFormat(agg,def.format);const[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum);narrowMax(agg,"maximum",maximum)};var contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format);if(def.pattern)addPattern(agg,def.pattern);if(def.format==="base64"||def.format==="base64url")agg.contentEncoding=def.format;if(def.local||def.precision===-1)agg.laxFormat=true},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){const agg={};const def=schema._zod.def;const list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(const ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);const bag=schema._zod.bag;if(bag.minimum!==undefined)narrowMin(agg,"minimum",bag.minimum);if(bag.exclusiveMinimum!==undefined)narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum);if(bag.maximum!==undefined)narrowMax(agg,"maximum",bag.maximum);if(bag.exclusiveMaximum!==undefined)narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum);if(bag.multipleOf!==undefined)addDivisor(agg,bag.multipleOf);if(bag.format!==undefined){agg.format??(agg.format=bag.format);if(bag.format.includes("int"))agg.isInt=true}if(bag.mime)intersectMime(agg,bag.mime);for(const pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""};var exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]);var exactPattern=(p)=>exactPatterns.get(p)??p;var stringProcessor=(schema,ctx,_json,_params)=>{const json=_json;json.type="string";const{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){json.format=formatMap[format]??format;if(json.format==="")delete json.format;if(format==="time"||laxFormat){delete json.format}}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){const patternList=[...patterns].map(exactPattern);if(patternList.length===1)json.pattern=patternList[0].source;else if(patternList.length>1){json.allOf=[...patternList.map((regex)=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}}};var numberProcessor=(schema,ctx,_json,params)=>{const json=_json;const{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json.type=isInt?"integer":"number";const exMin=typeof exclusiveMinimum==="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY);const exMax=typeof exclusiveMaximum==="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY);const legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin){if(legacy){json.minimum=exclusiveMinimum;json.exclusiveMinimum=true}else{json.exclusiveMinimum=exclusiveMinimum}}else if(typeof minimum==="number"){json.minimum=minimum}if(exMax){if(legacy){json.maximum=exclusiveMaximum;json.exclusiveMaximum=true}else{json.exclusiveMaximum=exclusiveMaximum}}else if(typeof maximum==="number"){json.maximum=maximum}if(multipleOf){const divisors=new Set;for(const divisor of multipleOf){if(Number.isFinite(divisor)&&divisor!==0)divisors.add(Math.abs(divisor));else handleUnrepresentable(schema,ctx,json,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`)}const[first,...rest]=divisors;if(first!==undefined)json.multipleOf=first;if(rest.length)json.allOf=[...json.allOf??[],...rest.map((m)=>({multipleOf:m}))]}};var booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var bigintProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"BigInt cannot be represented in JSON Schema")};var symbolProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Symbols cannot be represented in JSON Schema")};var nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0"){json.type="string";json.nullable=true;json.enum=[null]}else{json.type="null"}};var undefinedProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Undefined cannot be represented in JSON Schema")};var voidProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Void cannot be represented in JSON Schema")};var neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}};var anyProcessor=(_schema,_ctx,_json,_params)=>{};var unknownProcessor=(_schema,_ctx,_json,_params)=>{};var dateProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Date cannot be represented in JSON Schema")};var enumProcessor=(schema,_ctx,json,_params)=>{const def=schema._zod.def;const values=getEnumValues(def.entries);if(values.length===0){json.not={};return}if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values};var literalProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;if(def.values.length===0){json.not={};return}const vals=[];for(const val of def.values){if(val===undefined){if(handleUnrepresentable(schema,ctx,json,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val==="bigint"){if(handleUnrepresentable(schema,ctx,json,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else{vals.push(val)}}if(vals.length===0){}else if(vals.length===1){const val=vals[0];json.type=val===null?"null":typeof val;if(ctx.target==="draft-04"||ctx.target==="openapi-3.0"){json.enum=[val]}else{json.const=val}}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}};var nanProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"NaN cannot be represented in JSON Schema")};var templateLiteralProcessor=(schema,_ctx,json,_params)=>{const _json=json;const pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string";_json.pattern=pattern.source};var fileProcessor=(schema,_ctx,json,_params)=>{const _json=json;_json.type="string";_json.format="binary";_json.contentEncoding="binary";const{minimum,maximum,mime}=aggregateChecks(schema);if(minimum!==undefined)_json.minLength=minimum;if(maximum!==undefined)_json.maxLength=maximum;if(!mime)return;if(mime.length===0)_json.not={};else if(mime.length===1)_json.contentMediaType=mime[0];else _json.anyOf=mime.map((m)=>({contentMediaType:m}))};var successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var customProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Custom types cannot be represented in JSON Schema")};var functionProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Function types cannot be represented in JSON Schema")};var transformProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Transforms cannot be represented in JSON Schema")};var mapProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Map cannot be represented in JSON Schema")};var setProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Set cannot be represented in JSON Schema")};var arrayProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;const{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array";json.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};function inputOptin(schema){const def=schema._zod.def;if(def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")){return inputOptin(def.out)}if(def.type==="catch"){return inputOptin(def.innerType)}return schema._zod.optin}var objectProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;const shape=def.shape;const symbolKeys=Object.getOwnPropertySymbols(shape);if(symbolKeys.length&&handleUnrepresentable(schema,ctx,json,params,"Symbol keys cannot be represented in JSON Schema")){return}json.type="object";json.properties={};for(const key in shape){assignProp(json.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}))}const requiredKeys=[];for(const key of Object.keys(shape)){const field=def.shape[key];if(ctx.io==="input"?inputOptin(field)===undefined:field._zod.optout===undefined){requiredKeys.push(key)}}if(requiredKeys.length>0){json.required=requiredKeys}if(def.catchall?._zod.def.type==="never"){json.additionalProperties=false}else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=false}else if(def.catchall){json.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})}};var unionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const isExclusive=def.inclusive===false;const options=def.options.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive){json.oneOf=options}else{json.anyOf=options}};var intersectionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]});const b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]});const isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1;const allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf;ctx.intersections.push(allOf)};var tupleProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="array";const prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items";const restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems";const prefixItems=def.items.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,prefixPath,i]}));const rest=def.rest?processSchema(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;let minItems=def.items.length;while(minItems>0){const item=def.items[minItems-1];const optional=ctx.io==="input"?inputOptin(item)!==undefined:item._zod.optout==="optional";if(!optional)break;minItems--}const maxItems=def.items.length;const isClosed=!def.rest;if(ctx.target==="draft-2020-12"){json.prefixItems=prefixItems;if(isClosed){json.items=false}else if(rest){json.items=rest}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else if(ctx.target==="openapi-3.0"){json.items={anyOf:prefixItems};if(rest){json.items.anyOf.push(rest)}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else{json.items=prefixItems;if(isClosed){json.additionalItems=false}else if(rest){json.additionalItems=rest}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}const{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum};function stringifyKeyNames(bySchema,json,visited){if(json.$ref){if(visited.has(json))return json;visited.add(json);const def=bySchema.get(json)?.def;if(!def)return json;const inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json:inlined}for(const keyword of["anyOf","oneOf"]){const branches=json[keyword];if(!Array.isArray(branches))continue;const mapped=branches.map((branch)=>stringifyKeyNames(bySchema,branch,visited));if(mapped.some((branch,i)=>branch!==branches[i]))json={...json,[keyword]:mapped}}const types=Array.isArray(json.type)?json.type:[json.type];const numericType=!types.includes("string")&&types.some((t)=>t==="number"||t==="integer");const values=json.enum??(json.const!==undefined?[json.const]:undefined);if(!numericType&&!values?.some((v)=>typeof v==="number"))return json;const{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json;if(rest.enum)rest.enum=rest.enum.map((v)=>typeof v==="number"?String(v):v);else if(typeof rest.const==="number")rest.const=String(rest.const);if(!numericType)return rest;rest.type="string";if(!values)rest.pattern=(types.includes("number")?number:integer).source;return rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){const bySchema=new Map;for(const entry of ctx.seen.values()){if(entry.def&&!bySchema.has(entry.schema))bySchema.set(entry.schema,entry)}const rewrites=new Map;for(const record of pendingRecords.get(ctx)??[]){const seen=ctx.seen.get(record);const names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===true||rewrites.has(names))continue;const rewritten=stringifyKeyNames(bySchema,names,new Set);if(rewritten!==names)rewrites.set(names,rewritten)}if(!rewrites.size)return;for(const entry of ctx.seen.values()){for(const carrier of[entry.schema,entry.def]){const rewritten=carrier&&rewrites.get(carrier.propertyNames);if(rewritten)carrier.propertyNames=rewritten}}}var recordProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="object";const keyType=def.keyType;const patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){const valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(const pattern of patterns){assignProp(json.patternProperties,exactPattern(pattern).source,valueSchema)}}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending=pendingRecords.get(ctx);if(!pending){pending=[];pendingRecords.set(ctx,pending);ctx.deferred.push(()=>rewriteKeyNames(ctx))}pending.push(schema)}json.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}const keyValues=keyType._zod.values;const omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==undefined;if(keyValues&&!def.partial&&!omittableOnInput){const validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0){json.required=validKeyValues.map(String)}}};var nullableProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const inner=processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0"){seen.ref=def.innerType;json.nullable=true}else{json.anyOf=[inner,{type:"null"}]}};var nonoptionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value,schema,ctx,json,params){let unrepresentable=false;const serialized=JSON.stringify(value,(_,val)=>{if(typeof val!=="bigint")return val;unrepresentable=true;return null});if(!unrepresentable)return JSON.parse(serialized);handleUnrepresentable(schema,ctx,json,params,"BigInt defaults cannot be represented in JSON Schema");return UNREPRESENTABLE_DEFAULT}var defaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;const value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json.default=value};var prefaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;if(ctx.io!=="input")return;const value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json._prefault=value};var catchProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(undefined)}catch{handleUnrepresentable(schema,ctx,json,params,"Dynamic catch values are not supported in JSON Schema");return}json.default=catchValue};var pipeProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;const inIsTransform=def.in._zod.traits.has("$ZodTransform");const innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};var readonlyProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json.readOnly=true};var promiseProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var optionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var lazyProcessor=(schema,ctx,_json,params)=>{const innerType=schema._zod.innerType;processSchema(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};var allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(input,params){if("_idmap"in input){const registry=input;const ctx=initializeContext({...params,processors:allProcessors});const defs={};for(const entry of registry._idmap.entries()){const[_,schema]=entry;processSchema(schema,ctx)}const schemas={};const external={registry,uri:params?.uri,defs};ctx.external=external;for(const entry of registry._idmap.entries()){const[key,schema]=entry;extractDefs(ctx,schema);assignProp(schemas,key,finalize(ctx,schema))}if(Object.keys(defs).length>0){const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}const ctx=initializeContext({...params,processors:allProcessors});processSchema(input,ctx);extractDefs(ctx,input);return finalize(ctx,input)}class JSONSchemaGenerator{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return processSchema(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}this.ctx.sharedDefsExtractedFor=undefined;this.ctx.sharedEmitDoneFor=undefined;extractDefs(this.ctx,schema);const result=finalize(this.ctx,schema);const{"~standard":_,...plainResult}=result;return plainResult}}var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:true,enumerable:false,get(){const value=make(this);Object.defineProperty(this,key,{value,configurable:true,writable:true});return value},set(value){Object.defineProperty(this,key,{value,configurable:true,writable:true})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues);inst.name="ZodError";const proto=Object.getPrototypeOf(inst);if(_installedErrorProtos.has(proto))return;_installedErrorProtos.add(proto);_lazyMethod(proto,"format",(self)=>(mapper)=>formatError(self,mapper));_lazyMethod(proto,"flatten",(self)=>(mapper)=>flattenError(self,mapper));_lazyMethod(proto,"addIssue",(self)=>(issue)=>{self.issues.push(issue);self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)});_lazyMethod(proto,"addIssues",(self)=>(issues)=>{self.issues.push(...issues);self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)});Object.defineProperty(proto,"isEmpty",{configurable:true,enumerable:false,get(){return this.issues.length===0}})};var ZodError=$constructor("ZodError",initializer2);var ZodRealError=$constructor("ZodError",initializer2,undefined,{Parent:Error});var parse3=_parse(ZodRealError);var parseAsync2=_parseAsync(ZodRealError);var safeParse2=_safeParse(ZodRealError);var safeParseAsync2=_safeParseAsync(ZodRealError);var encode2=_encode(ZodRealError);var decode2=_decode(ZodRealError);var encodeAsync2=_encodeAsync(ZodRealError);var decodeAsync2=_decodeAsync(ZodRealError);var safeEncode2=_safeEncode(ZodRealError);var safeDecode2=_safeDecode(ZodRealError);var safeEncodeAsync2=_safeEncodeAsync(ZodRealError);var safeDecodeAsync2=_safeDecodeAsync(ZodRealError);function _ensureDefaultLocale(){if(!globalConfig.localeError)config(en_default())}function _ensureDefaultMemoizer(){if(!globalConfig.memoizer)config({memoizer:memoizer()})}var ZodType=$constructor("ZodType",(inst,def)=>{_ensureDefaultLocale();$ZodType.init(inst,def);inst.def=def;inst.type=def.type;return inst},{check(...chks){const def=this.def;return this.clone(mergeDefs(def,{checks:[...def.checks??[],...chks.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:true})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta){reg.add(this,meta);return this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){const cl=this.clone();globalRegistry.add(cl,{description});return cl},meta(...args){if(args.length===0)return globalRegistry.get(this);const cl=this.clone();globalRegistry.add(cl,args[0]);return cl},isOptional(){return this.safeParse(undefined).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get "~standard"(){return hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set "~standard"(value){own(this,"~standard",value)},parse:function _parse(data,params){return parse3(this,data,params,{callee:_parse})},parseAsync:async function _parseAsync(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value){own(this,"spa",value)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode(data,params){return encode2(this,data,params,{callee:_encode})},decode:function _decode(data,params){return decode2(this,data,params,{callee:_decode})},encodeAsync:async function _encodeAsync(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}});var _ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params)},derived({format:(inst)=>aggregateChecks(inst).format??null,minLength:(inst)=>aggregateChecks(inst).minimum??null,maxLength:(inst)=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}}));var ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def);_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def);_ZodString.init(inst,def)});var ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def);ZodStringFormat.init(inst,def)});var ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def);ZodStringFormat.init(inst,def)});function email2(params){return _email(ZodEmail,params)}var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def);ZodStringFormat.init(inst,def)});function guid2(params){return _guid(ZodGUID,params)}var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def);ZodStringFormat.init(inst,def)});function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def);ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:httpProtocol,hostname:domain,...normalizeParams(params)})}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def);ZodStringFormat.init(inst,def)});function emoji2(params){return _emoji2(ZodEmoji,params)}var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def);ZodStringFormat.init(inst,def)});function nanoid2(params){return _nanoid(ZodNanoID,params)}var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def);ZodStringFormat.init(inst,def)});function cuid3(params){return _cuid(ZodCUID,params)}var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def);ZodStringFormat.init(inst,def)});function cuid22(params){return _cuid2(ZodCUID2,params)}var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def);ZodStringFormat.init(inst,def)});function ulid2(params){return _ulid(ZodULID,params)}var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def);ZodStringFormat.init(inst,def)});function xid2(params){return _xid(ZodXID,params)}var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def);ZodStringFormat.init(inst,def)});function ksuid2(params){return _ksuid(ZodKSUID,params)}var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def);ZodStringFormat.init(inst,def)});function ipv42(params){return _ipv4(ZodIPv4,params)}var ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def);ZodStringFormat.init(inst,def)});function mac2(params){return _mac(ZodMAC,params)}var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def);ZodStringFormat.init(inst,def)});function ipv62(params){return _ipv6(ZodIPv6,params)}var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def);ZodStringFormat.init(inst,def)});function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def);ZodStringFormat.init(inst,def)});function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def);ZodStringFormat.init(inst,def)});function base642(params){return _base64(ZodBase64,params)}var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def);ZodStringFormat.init(inst,def)});function base64url2(params){return _base64url(ZodBase64URL,params)}var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def);ZodStringFormat.init(inst,def)});function e1642(params){return _e164(ZodE164,params)}var ZodCreditCard=$constructor("ZodCreditCard",(inst,def)=>{$ZodCreditCard.init(inst,def);ZodStringFormat.init(inst,def)});function creditCard2(params){return _creditCard(ZodCreditCard,params)}var ZodIBAN=$constructor("ZodIBAN",(inst,def)=>{$ZodIBAN.init(inst,def);ZodStringFormat.init(inst,def)});function iban2(params){return _iban(ZodIBAN,params)}var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def);ZodStringFormat.init(inst,def)});function jwt(params){return _jwt(ZodJWT,params)}var ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def);ZodStringFormat.init(inst,def)});function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",hex,_params)}function currencyCode2(_params){return _stringFormat(ZodCustomStringFormat,"currency_code",currencyCode,_params)}function hash(alg,params){const enc=params?.enc??"hex";const format=`${alg}_${enc}`;const regex=exports_regexes[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params);inst.isFinite=true},derived({minValue:(inst)=>{const{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:(inst)=>{const{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:(inst)=>{const{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:(inst)=>aggregateChecks(inst).format??null},{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}}));function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def);ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params)},derived({minValue:(inst)=>aggregateChecks(inst).minimum??null,maxValue:(inst)=>aggregateChecks(inst).maximum??null,format:(inst)=>aggregateChecks(inst).format??null},{gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},gt(value,params){return this.check(_gt(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},positive(params){return this.check(_gt(BigInt(0),params))},negative(params){return this.check(_lt(BigInt(0),params))},nonpositive(params){return this.check(_lte(BigInt(0),params))},nonnegative(params){return this.check(_gte(BigInt(0),params))},multipleOf(value,params){return this.check(_multipleOf(value,params))}}));function bigint2(params){return _bigint(ZodBigInt,params)}var ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def);ZodBigInt.init(inst,def)});function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}var ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});function symbol(params){return _symbol(ZodSymbol,params)}var ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});function _undefined3(params){return _undefined2(ZodUndefined,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});function _null3(params){return _null2(ZodNull,params)}var ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});function any(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});function never(params){return _never(ZodNever,params)}var ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});function _void2(params){return _void(ZodVoid,params)}var ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params);inst.min=(value,params)=>inst.check(_gte(value,params));inst.max=(value,params)=>inst.check(_lte(value,params))},derived({minDate:(inst)=>{const{minimum}=aggregateChecks(inst);return minimum?new Date(minimum):null},maxDate:(inst)=>{const{maximum}=aggregateChecks(inst);return maximum?new Date(maximum):null}},{}));function date2(params){return _date(ZodDate,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer();$ZodArray.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params);inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){const shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer();$ZodObjectJIT.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params);installLazyProp(inst,"shape",(self)=>self._zod.def.shape,false)},{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(mergeDefs(this._zod.def,{catchall:undefined}))},extend(incoming){return extend(this,incoming)},safeExtend(incoming){return safeExtend(this,incoming)},merge(other){return merge(this,other)},pick(mask){return pick(this,mask)},omit(mask){return omit(this,mask)},partial(...args){return partial(ZodOptional,this,args[0])},exactPartial(...args){return partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return required(ZodNonOptional,this,args[0])}});function object(shape,params){const def={type:"object",shape:shape??{},...normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...normalizeParams(params)})}var ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def);$ZodXor.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});function xor(options,params){return new ZodXor({type:"union",options,inclusive:false,...normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def);$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodTuple=$constructor("ZodTuple",(inst,def)=>{_ensureDefaultMemoizer();$ZodTuple.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params)},{rest(rest){return this.clone({...this._zod.def,rest})},partial(){const def=this._zod.def;if(def.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...def,items:def.items.map((item)=>new ZodOptional({type:"optional",innerType:item}))})}});function tuple(items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...normalizeParams(params)})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer();$ZodRecord.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType});function record(keyType,valueType,params){if(!valueType||!valueType._zod){return new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...normalizeParams(valueType)})}return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params)})}function partialRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params),partial:true})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...normalizeParams(params)})}var ZodMap=$constructor("ZodMap",(inst,def)=>{_ensureDefaultMemoizer();$ZodMap.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType;inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=(params)=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...normalizeParams(params)})}var ZodSet=$constructor("ZodSet",(inst,def)=>{_ensureDefaultMemoizer();$ZodSet.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params);inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=(params)=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});function set(valueType,params){return new ZodSet({type:"set",valueType,...normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params);inst.enum=def.entries;inst.options=[...inst._zod.values];const keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{const newEntries={};for(const value of values){if(keys.has(value)){newEntries[value]=def.entries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})};inst.exclude=(values,params)=>{const newEntries={...def.entries};for(const value of values){if(keys.has(value)){delete newEntries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})}});function _enum2(values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params);inst.values=new Set(def.values);Object.defineProperty(inst,"value",{get(){if(def.values.length>1){throw new Error("This schema contains multiple valid literal values. Use `.values` instead.")}return def.values[0]}})});function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}var ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params);inst.min=(size,params)=>inst.check(_minSize(size,params));inst.max=(size,params)=>inst.check(_maxSize(size,params));inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});function file(params){return _file(ZodFile,params)}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer();$ZodTransform.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params);inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward"){throw new $ZodEncodeError(inst.constructor.name)}payload.addIssue=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");if(!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=inst);payload.issues.push(issue(_issue))}};const output=def.transform(payload.value,payload);if(output instanceof Promise){return output.then((output)=>{payload.value=output;return payload})}payload.value=output;return payload}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeDefault=inst.unwrap});function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...normalizeParams(params)})}var ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function success(innerType){return new ZodSuccess({type:"success",innerType})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeCatch=inst.unwrap});function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}var ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});function nan(params){return _nan(ZodNaN,params)}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params);inst.in=def.in;inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def);$ZodCodec.init(inst,def)});function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){const def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def);$ZodPreprocess.init(inst,def)});var ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...normalizeParams(params)})}var ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.getter()});function lazy(getter){return new ZodLazy({type:"lazy",getter})}var ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function promise(innerType){return new ZodPromise({type:"promise",innerType})}var ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});function check(fn){const ch=new $ZodCheck({check:"custom"});ch._zod.check=fn;return ch}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>true),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}var describe2=describe;var meta2=meta;var ZodInstanceOf=$constructor("ZodInstanceOf",(inst,def)=>{ZodCustom.init(inst,def)},{properties(shape,params){return this.check(_properties(shape,params))}});function _instanceof(cls,params={}){const inst=new ZodInstanceOf({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:true,...normalizeParams(params)});inst._zod.bag.Class=cls;inst._zod.check=(payload)=>{if(!(payload.value instanceof cls)){payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})}};return inst}var stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args);function json(params){const jsonSchema=lazy(()=>{return union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function setErrorMap(map){config({customError:map})}function getErrorMap(){return config().customError}var ZodFirstPartyTypeKind;(function(ZodFirstPartyTypeKind){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date3(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var z={...exports_schemas2,...exports_checks2,iso:exports_iso};var RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function detectVersion(schema,defaultTarget){const $schema=schema.$schema;if($schema==="https://json-schema.org/draft/2020-12/schema"){return"draft-2020-12"}if($schema==="http://json-schema.org/draft-07/schema#"){return"draft-7"}if($schema==="http://json-schema.org/draft-04/schema#"){return"draft-4"}return defaultTarget??"draft-2020-12"}function applyMinItems(items,minItems){return items.map((item,index)=>index<minItems?item:item.optional())}function decodeJSONPointerSegment(segment){return segment.replace(/~1/g,"/").replace(/~0/g,"~")}function resolveRef(ref,ctx){if(!ref.startsWith("#")){throw new Error("External $ref is not supported, only local refs (#/...) are allowed")}const path=ref.slice(1).split("/").filter(Boolean);if(path.length===0){return ctx.rootSchema}const defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path[0]===defsKey){const key=path[1]===undefined?undefined:decodeJSONPointerSegment(path[1]);if(!key||!ctx.defs[key]){throw new Error(`Reference not found: ${ref}`)}return ctx.defs[key]}throw new Error(`Reference not found: ${ref}`)}function checkObjectGuards(objectSchema,guards){const guard=z.transform((value)=>value).check((payload)=>{const value=payload.value;if(typeof value!=="object"||value===null||Array.isArray(value))return;const keys=Object.getOwnPropertyNames(value);if(guards.minProperties!==undefined&&keys.length<guards.minProperties){payload.issues.push({origin:"object",code:"too_small",minimum:guards.minProperties,inclusive:true,message:`Too small: expected object to have >=${guards.minProperties} properties`,input:value,inst:objectSchema,continue:true})}if(guards.maxProperties!==undefined&&keys.length>guards.maxProperties){payload.issues.push({origin:"object",code:"too_big",maximum:guards.maxProperties,inclusive:true,message:`Too big: expected object to have <=${guards.maxProperties} properties`,input:value,inst:objectSchema,continue:true})}if(guards.keySchema){for(const key of keys){const result=guards.keySchema.safeParse(key);if(result.success)continue;payload.issues.push({code:"invalid_key",origin:"record",issues:result.error.issues,input:key,path:[key],continue:true})}}});return guard.pipe(objectSchema)}function canonicalKey(value,seen){if(value===null)return"z";const type=typeof value;if(type!=="object"){if(type==="number"&&Number.isNaN(value))return null;const raw=String(value);return`${type[0]}${raw.length}:${raw}`}if(seen.has(value))return null;seen.add(value);try{if(Array.isArray(value)){const parts=[];for(const item of value){const key=canonicalKey(item,seen);if(key===null)return null;parts.push(key)}return`a${parts.length}:[${parts.join(",")}]`}const keys=Object.keys(value).sort();const parts=[];for(const k of keys){const key=canonicalKey(value[k],seen);if(key===null)return null;parts.push(`${k.length}:${k}=${key}`)}return`o${parts.length}:{${parts.join(",")}}`}finally{seen.delete(value)}}var SCHEMA_KEYWORDS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]);var SCHEMA_MAP_KEYWORDS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function containsRef(value){if(typeof value!=="object"||value===null)return false;if(Array.isArray(value))return value.some(containsRef);if(typeof value.$ref==="string")return true;return Object.entries(value).some(([key,sub])=>{if(SCHEMA_KEYWORDS.has(key))return containsRef(sub);if(!SCHEMA_MAP_KEYWORDS.has(key)||typeof sub!=="object"||sub===null)return false;return Object.values(sub).some(containsRef)})}function plural(n){return n===1?"element":"elements"}function checkArrayGuards(arraySchema,guards){const guard=z.transform((value)=>value).check((payload)=>{const items=payload.value;if(!Array.isArray(items))return;if(guards.uniqueItems===true){const firstSeen=new Map;for(let i=0;i<items.length;i++){const key=canonicalKey(items[i],new Set);if(key===null)continue;const first=firstSeen.get(key);if(first===undefined){firstSeen.set(key,i);continue}payload.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${first}`,input:items,path:[i],continue:true})}}if(guards.containsSchema){const minContains=guards.minContains??1;const ceiling=guards.maxContains!==undefined?guards.maxContains+1:Number.POSITIVE_INFINITY;let matches=0;for(const item of items){if(guards.containsSchema.safeParse(item).success&&++matches>=ceiling)break}if(matches<minContains){payload.issues.push({code:"custom",message:`Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,input:items,continue:true})}if(guards.maxContains!==undefined&&matches>guards.maxContains){payload.issues.push({code:"custom",message:`Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,input:items,continue:true})}}});return guard.pipe(arraySchema)}function getTupleRest(restSchema,ctx){if(restSchema===false){return}if(restSchema===undefined||restSchema===true){return z.any()}return convertSchema(restSchema,ctx)}var fullTime=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function convertBaseSchema(schema,ctx){if(schema.not!==undefined){if(typeof schema.not==="object"&&Object.keys(schema.not).length===0){return z.never()}throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==undefined){throw new Error("unevaluatedItems is not supported")}if(schema.unevaluatedProperties!==undefined){throw new Error("unevaluatedProperties is not supported")}if(schema.if!==undefined||schema.then!==undefined||schema.else!==undefined){throw new Error("Conditional schemas (if/then/else) are not supported")}if(schema.dependentSchemas!==undefined||schema.dependentRequired!==undefined){throw new Error("dependentSchemas and dependentRequired are not supported")}if(schema.$ref){const refPath=schema.$ref;if(ctx.refs.has(refPath)){return ctx.refs.get(refPath)}if(ctx.processing.has(refPath)){return z.lazy(()=>{if(!ctx.refs.has(refPath)){throw new Error(`Circular reference not resolved: ${refPath}`)}return ctx.refs.get(refPath)})}ctx.processing.add(refPath);const resolved=resolveRef(refPath,ctx);const zodSchema=convertSchema(resolved,ctx);ctx.refs.set(refPath,zodSchema);ctx.processing.delete(refPath);return zodSchema}if(schema.enum!==undefined){const enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===true&&enumValues.length===1&&enumValues[0]===null){return z.null()}if(enumValues.length===0){return z.never()}if(enumValues.length===1){return z.literal(enumValues[0])}if(enumValues.every((v)=>typeof v==="string")){return z.enum(enumValues)}const literalSchemas=enumValues.map((v)=>z.literal(v));if(literalSchemas.length<2){return literalSchemas[0]}return z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==undefined){return z.literal(schema.const)}const type=schema.type;if(Array.isArray(type)){const typeSchemas=type.map((t)=>{const typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});if(typeSchemas.length===0){return z.never()}if(typeSchemas.length===1){return typeSchemas[0]}return z.union(typeSchemas)}if(!type){return z.any()}let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){const format=schema.format;if(format==="email"){stringSchema=stringSchema.check(z.email())}else if(format==="uri"||format==="uri-reference"){stringSchema=stringSchema.check(z.url())}else if(format==="uuid"||format==="guid"){stringSchema=stringSchema.check(z.uuid())}else if(format==="date-time"){stringSchema=stringSchema.check(z.iso.datetime({offset:true}))}else if(format==="date"){stringSchema=stringSchema.check(z.iso.date())}else if(format==="time"){stringSchema=stringSchema.check(z.regex(fullTime))}else if(format==="duration"){stringSchema=stringSchema.check(z.iso.duration())}else if(format==="hostname"){stringSchema=stringSchema.check(z.hostname())}else if(format==="ipv4"){stringSchema=stringSchema.check(z.ipv4())}else if(format==="ipv6"){stringSchema=stringSchema.check(z.ipv6())}else if(format==="mac"){stringSchema=stringSchema.check(z.mac())}else if(format==="cidr"){stringSchema=stringSchema.check(z.cidrv4())}else if(format==="cidr-v6"){stringSchema=stringSchema.check(z.cidrv6())}else if(format==="base64"){stringSchema=stringSchema.check(z.base64())}else if(format==="base64url"){stringSchema=stringSchema.check(z.base64url())}else if(format==="e164"){stringSchema=stringSchema.check(z.e164())}else if(format==="credit_card"){stringSchema=stringSchema.check(z.creditCard())}else if(format==="iban"){stringSchema=stringSchema.check(z.iban())}else if(format==="jwt"){stringSchema=stringSchema.check(z.jwt())}else if(format==="emoji"){stringSchema=stringSchema.check(z.emoji())}else if(format==="nanoid"){stringSchema=stringSchema.check(z.nanoid())}else if(format==="cuid"){stringSchema=stringSchema.check(z.cuid())}else if(format==="cuid2"){stringSchema=stringSchema.check(z.cuid2())}else if(format==="ulid"){stringSchema=stringSchema.check(z.ulid())}else if(format==="xid"){stringSchema=stringSchema.check(z.xid())}else if(format==="ksuid"){stringSchema=stringSchema.check(z.ksuid())}}if(typeof schema.minLength==="number"){stringSchema=stringSchema.min(schema.minLength)}if(typeof schema.maxLength==="number"){stringSchema=stringSchema.max(schema.maxLength)}if(schema.pattern){stringSchema=stringSchema.regex(new RegExp(schema.pattern))}zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();if(typeof schema.minimum==="number"&&schema.exclusiveMinimum!==true){numberSchema=numberSchema.min(schema.minimum)}if(typeof schema.maximum==="number"&&schema.exclusiveMaximum!==true){numberSchema=numberSchema.max(schema.maximum)}if(typeof schema.exclusiveMinimum==="number"){numberSchema=numberSchema.gt(schema.exclusiveMinimum)}else if(schema.exclusiveMinimum===true&&typeof schema.minimum==="number"){numberSchema=numberSchema.gt(schema.minimum)}if(typeof schema.exclusiveMaximum==="number"){numberSchema=numberSchema.lt(schema.exclusiveMaximum)}else if(schema.exclusiveMaximum===true&&typeof schema.maximum==="number"){numberSchema=numberSchema.lt(schema.maximum)}if(typeof schema.multipleOf==="number"){numberSchema=numberSchema.multipleOf(schema.multipleOf)}zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{const shape={};const properties=schema.properties||{};const requiredSet=new Set(schema.required||[]);const additionalSchema=typeof schema.additionalProperties==="object"?convertSchema(schema.additionalProperties,ctx):undefined;for(const[key,propSchema]of Object.entries(properties)){const propZodSchema=convertSchema(propSchema,ctx);assignProp(shape,key,requiredSet.has(key)?propZodSchema:propZodSchema.optional())}if(schema.patternProperties){const patternProps=schema.patternProperties;const patternKeys=Object.keys(patternProps);const looseRecords=[];for(const pattern of patternKeys){const patternValue=convertSchema(patternProps[pattern],ctx);const keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}const schemasToIntersect=[];if(Object.keys(shape).length>0){schemasToIntersect.push(z.object(shape).passthrough())}schemasToIntersect.push(...looseRecords);if(schemasToIntersect.length===0){zodSchema=z.object({}).passthrough()}else if(schemasToIntersect.length===1){zodSchema=schemasToIntersect[0]}else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++){result=z.intersection(result,schemasToIntersect[i])}zodSchema=result}if(schema.additionalProperties===false){const propertyKeys=Object.keys(shape);const patterns=patternKeys.map((p)=>new RegExp(p));const basePatternSchema=zodSchema;zodSchema=zodSchema.check((payload)=>{if(!isPlainObject(payload.value))return;const unrecognized=[];for(const key of Object.keys(payload.value)){if(propertyKeys.includes(key))continue;if(patterns.some((regex)=>regex.test(key)))continue;unrecognized.push(key)}if(unrecognized.length){payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input:payload.value,inst:basePatternSchema})}})}}else{const objectSchema=z.object(shape);if(schema.additionalProperties===false){zodSchema=objectSchema.strict()}else if(additionalSchema){zodSchema=objectSchema.catchall(additionalSchema)}else{zodSchema=objectSchema.passthrough()}}const hasKeyGuard=schema.propertyNames!==undefined&&schema.propertyNames!==true;const minProperties=typeof schema.minProperties==="number"?schema.minProperties:undefined;const maxProperties=typeof schema.maxProperties==="number"?schema.maxProperties:undefined;if(hasKeyGuard||minProperties!==undefined||maxProperties!==undefined){let keySchema;if(hasKeyGuard){const keyJSONSchema=typeof schema.propertyNames==="object"&&schema.propertyNames.type===undefined?{type:"string",...schema.propertyNames}:schema.propertyNames;keySchema=convertSchema(keyJSONSchema,ctx)}zodSchema=checkObjectGuards(zodSchema,{keySchema,minProperties,maxProperties})}break}case"array":{const prefixItems=schema.prefixItems;const items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){const minItems=typeof schema.minItems==="number"?schema.minItems:0;const tupleItems=prefixItems.map((item)=>convertSchema(item,ctx));const positionalItems=applyMinItems(tupleItems,minItems);const rest=!Array.isArray(items)?getTupleRest(items,ctx):undefined;const tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema;if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(Array.isArray(items)){const minItems=typeof schema.minItems==="number"?schema.minItems:0;const tupleItems=items.map((item)=>convertSchema(item,ctx));const positionalItems=applyMinItems(tupleItems,minItems);const rest=getTupleRest(schema.additionalItems,ctx);const tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema;if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(items!==undefined){const element=convertSchema(items,ctx);let arraySchema=z.array(element);if(typeof schema.minItems==="number"){arraySchema=arraySchema.min(schema.minItems)}if(typeof schema.maxItems==="number"){arraySchema=arraySchema.max(schema.maxItems)}zodSchema=arraySchema}else{zodSchema=z.array(z.any())}if(schema.uniqueItems===true||schema.contains!==undefined){zodSchema=checkArrayGuards(zodSchema,{uniqueItems:schema.uniqueItems===true,containsSchema:schema.contains!==undefined?convertSchema(schema.contains,ctx):undefined,minContains:typeof schema.minContains==="number"?schema.minContains:undefined,maxContains:typeof schema.maxContains==="number"?schema.maxContains:undefined})}break}default:throw new Error(`Unsupported type: ${type}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema==="boolean"){return schema?z.any():z.never()}let baseSchema=convertBaseSchema(schema,ctx);const hasExplicitType=schema.type||schema.enum!==undefined||schema.const!==undefined;if(schema.anyOf&&Array.isArray(schema.anyOf)){const options=schema.anyOf.map((s)=>convertSchema(s,ctx));const anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){const options=schema.oneOf.map((s)=>convertSchema(s,ctx));const oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf)){if(schema.allOf.length===0){baseSchema=hasExplicitType?baseSchema:z.any()}else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx);const startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++){result=z.intersection(result,convertSchema(schema.allOf[i],ctx))}baseSchema=result}}if(schema.nullable===true&&ctx.version==="openapi-3.0"){baseSchema=z.nullable(baseSchema)}if(schema.readOnly===true){baseSchema=z.readonly(baseSchema)}if(schema.default!==undefined){baseSchema=baseSchema.default(schema.default)}const extraMeta={};const coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const key of coreMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}const contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(const key of contentMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}if(schema.type==="object"&&schema.$ref===undefined){if(schema.propertyNames!==undefined&&!containsRef(schema.propertyNames)){extraMeta.propertyNames=schema.propertyNames}for(const key of["minProperties","maxProperties"]){if(schema[key]!==undefined)extraMeta[key]=schema[key]}}if(schema.type==="array"&&schema.$ref===undefined){if(schema.contains!==undefined&&!containsRef(schema.contains)){extraMeta.contains=schema.contains}for(const key of["uniqueItems","minContains","maxContains"]){if(schema[key]!==undefined)extraMeta[key]=schema[key]}}for(const key of Object.keys(schema)){if(!RECOGNIZED_KEYS.has(key)){assignProp(extraMeta,key,schema[key])}}if(Object.keys(extraMeta).length>0){ctx.registry.add(baseSchema,extraMeta)}if(schema.description){baseSchema=baseSchema.describe(schema.description)}return baseSchema}function fromJSONSchema(schema,params){if(typeof schema==="boolean"){return schema?z.any():z.never()}let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}const version=detectVersion(normalized,params?.defaultTarget);const defs=normalized.$defs||normalized.definitions||{};const ctx={version,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var RESOLVING=Symbol("z.visit/resolving");function visit(schema,fnOrHandlers){const fn=typeof fnOrHandlers==="function"?fnOrHandlers:(node,rewritten)=>{const h=fnOrHandlers[node._zod.def.type];return h?h(node,rewritten):node};const cache=new Map;function run(s){const cached=cache.get(s);if(cached===RESOLVING){return new $ZodLazy({type:"lazy",getter:()=>cache.get(s)})}if(cached!==undefined)return cached;cache.set(s,RESOLVING);const inner=mapInner(s);const mapped=fn(inner,inner!==s);cache.set(s,mapped);return mapped}function mapInner(s){const def=s._zod.def;const kind=def.type;switch(kind){case"object":{const oldShape=def.shape;const keys=Object.keys(oldShape);let changed=false;const newShape={};for(const k of keys){const mapped=run(oldShape[k]);if(mapped!==oldShape[k])changed=true;newShape[k]=mapped}let newCatchall=def.catchall;if(def.catchall){newCatchall=run(def.catchall);if(newCatchall!==def.catchall)changed=true}return changed?clone(s,{...def,shape:newShape,catchall:newCatchall}):s}case"array":{const mapped=run(def.element);return mapped===def.element?s:clone(s,{...def,element:mapped})}case"tuple":{const oldItems=def.items;let changed=false;const newItems=[];for(const item of oldItems){const mapped=run(item);if(mapped!==item)changed=true;newItems.push(mapped)}let newRest=def.rest;if(def.rest){newRest=run(def.rest);if(newRest!==def.rest)changed=true}return changed?clone(s,{...def,items:newItems,rest:newRest}):s}case"record":case"map":{const newKey=run(def.keyType);const newVal=run(def.valueType);return newKey===def.keyType&&newVal===def.valueType?s:clone(s,{...def,keyType:newKey,valueType:newVal})}case"set":{const newVal=run(def.valueType);return newVal===def.valueType?s:clone(s,{...def,valueType:newVal})}case"union":{const oldOptions=def.options;let changed=false;const newOptions=[];for(const opt of oldOptions){const mapped=run(opt);if(mapped!==opt)changed=true;newOptions.push(mapped)}return changed?clone(s,{...def,options:newOptions}):s}case"intersection":{const newLeft=run(def.left);const newRight=run(def.right);return newLeft===def.left&&newRight===def.right?s:clone(s,{...def,left:newLeft,right:newRight})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{const newInner=run(def.innerType);return newInner===def.innerType?s:clone(s,{...def,innerType:newInner})}case"pipe":{const newIn=run(def.in);const newOut=run(def.out);return newIn===def.in&&newOut===def.out?s:clone(s,{...def,in:newIn,out:newOut})}case"function":{const newInput=run(def.input);const newOutput=run(def.output);return newInput===def.input&&newOutput===def.output?s:clone(s,{...def,input:newInput,output:newOutput})}case"lazy":{const original=def.getter;const{_cachedInner,...rest}=def;return clone(s,{...rest,getter:()=>run(original())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:{return s}}}return run(schema)}function deepPartial(schema){return visit(schema,{object:(s)=>s.partial(),union:(s)=>{const def=s._zod.def;return def.discriminator===undefined?s:union(def.options)}})}function withChecks(side,checks){if(!checks?.length)return side;const def=side._zod.def;return clone(side,mergeDefs(def,{checks:[...def.checks??[],...checks]}),{parent:true})}function outSide(def){return withChecks(def.out,def.checks)}function inSide(def){return def.in._zod.traits.has("$ZodTransform")?outSide(def):def.in}function input(schema){return visit(schema,{pipe:(s)=>inSide(s._zod.def),default:(s,rewritten)=>rewritten?optional(s._zod.def.innerType):s,catch:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function output(schema){return visit(schema,{pipe:(s)=>outSide(s._zod.def),prefault:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}import path from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{createReadStream}from"node:fs";import{tmpdir}from"node:os";import{readFileSync}from"node:fs";var pageBundle=readFileSync(new URL("./page-bundle.js",import.meta.url),"utf8");init_internal_capability();var __defProp2=Object.defineProperty;var __exportAll=(definitions,namespace)=>{const exports={};for(const name in definitions)__defProp2(exports,name,{get:definitions[name],enumerable:true});if(!namespace)__defProp2(exports,Symbol.toStringTag,{value:"Module"});return exports};var __esmMin=(factory,value,error)=>()=>{if(error)throw error[0];try{return factory&&(value=factory(factory=0)),value}catch(caught){error=[caught];throw caught}};if(!Promise.withResolvers){Promise.withResolvers=()=>{let resolve,reject;const promise=new Promise((res,rej)=>{resolve=res;reject=rej});return{promise,resolve,reject}}}class Emittery{#listeners=new Map;on(name,listener){const listeners=this.#listeners.get(name)??new Set;listeners.add(listener);this.#listeners.set(name,listeners);return()=>{listeners.delete(listener)}}async emit(name,data){const event={data,eventName:name};await Promise.all([...this.#listeners.get(name)??[]].map((listener)=>listener(event)))}clearListeners(){this.#listeners.clear()}}var{object:object2,string:string$2,number:number$2,array:array2,union:union$1,unknown:unknown$1,null:_null4}=exports_zod;var OMOWRIGHT_BROWSER_CDP_HOST="127.0.0.1:9222";var SESSION_ARTIFACTS_DIR=path.join(tmpdir(),"omowright-artifacts");var noop=()=>{};var init_emittery=noop;var init_zod=noop;var init_context=noop;var init_utils$13=noop;var init_config=noop;var init_extension_bridge=noop;var init_commands$1=noop;var init_directory=noop;var init_process=noop;var init_event_bus=noop;var init_state_db=noop;var init_schema=noop;var init_store$1=noop;var init_drizzle_orm=noop;var init_types$8=noop;var init_agent_session_server=noop;var init_nanoid=noop;function sleep$12(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted)return reject(signal.reason??Error("Aborted"));const onAbort=()=>{clearTimeout(timer);reject(signal.reason??Error("Aborted"))};const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);signal?.addEventListener("abort",onAbort,{once:true})})}function getCurrentReplAbortSignal(){return}function getCurrentReplToolCallId(){return}function hasActiveReplContext(){return false}function withCurrentReplAbort(fn){return fn()}function withoutReplContext(fn){return fn()}function replPrint(...values){console.warn(...values)}async function sendCommandToExtension(command){throw new UnsupportedOperationError(`Extension command is unavailable: ${command.method}`)}class UnsupportedOperationError extends Error{constructor(message){super(message);this.name="UnsupportedOperationError"}}function nanoid3(){return crypto.randomUUID()}var EventBus={emit:async()=>{}};var SessionStore={get:()=>{return},update:()=>{return}};var stateDb=()=>{throw new UnsupportedOperationError("Daemon persistence is unavailable")};var NotificationGrantTable={};function resolveSessionPath(_session,value){return path.resolve(String(value))}function getSessionStorageDir(){return process.cwd()}function getSharedSessionStorageDir(){return process.cwd()}function spawnCommand(){throw new UnsupportedOperationError("Video recording is unavailable")}async function waitForExitCode(){return 1}function isWebSocketUrl(xn){return xn.startsWith(`ws://`)||xn.startsWith(`wss://`)}function isAuthorizationError(xn){let jn=xn instanceof Error?xn.message:String(xn),Vn=xn;return jn.includes(`401`)||jn.includes(`403`)||jn.includes(`Missing or invalid Authorization header.`)||jn.includes(`Unauthorized`)||jn.includes(`Forbidden`)||typeof Vn.status==`number`&&(Vn.status===401||Vn.status===403)||typeof Vn.response?.status==`number`&&(Vn.response.status===401||Vn.response.status===403)||typeof Vn.error?.status==`number`&&(Vn.error.status===401||Vn.error.status===403)||typeof Vn.cause?.status==`number`&&(Vn.cause.status===401||Vn.cause.status===403)||String(Vn.error?.message??``).includes(`Missing or invalid Authorization header.`)||String(Vn.cause?.message??``).includes(`Missing or invalid Authorization header.`)}function normalizeBaseUrl(xn){return xn.replace(/\/$/,``)}function createAbortError$1(){let xn=Error(`Operation aborted`);return xn.name=`AbortError`,xn}var DEFAULT_COMMAND_TIMEOUT_MS;var DEFAULT_RECONNECT_DELAYS_MS;var jsonVersionSchema;var jsonTargetSchema;var cdpWireMessageSchema;var BrowserCdpCommandError;var CdpClient;var init_client$6=__esmMin(()=>{init_emittery(),init_zod(),init_context(),init_utils$13(),init_config(),init_extension_bridge(),init_commands$1(),DEFAULT_COMMAND_TIMEOUT_MS=30000,DEFAULT_RECONNECT_DELAYS_MS=[0,250,750,1500,3000],jsonVersionSchema=object2({Browser:string$2().optional(),"Protocol-Version":string$2().optional(),"User-Agent":string$2().optional(),"V8-Version":string$2().optional(),"WebKit-Version":string$2().optional(),webSocketDebuggerUrl:string$2()}).loose(),jsonTargetSchema=object2({description:string$2().optional(),devtoolsFrontendUrl:string$2().optional(),faviconUrl:string$2().optional(),id:string$2(),parentId:string$2().optional(),title:string$2().default(``),type:string$2(),url:string$2().default(``),webSocketDebuggerUrl:string$2().optional()}).loose(),cdpWireMessageSchema=union$1([object2({id:number$2(),sessionId:string$2().optional(),error:object2({code:number$2().optional(),data:unknown$1().optional(),message:string$2()}).loose().optional(),result:unknown$1().optional()}).loose(),object2({method:string$2(),params:unknown$1().optional(),sessionId:string$2().optional()}).loose(),_null4()]),BrowserCdpCommandError=class extends Error{method;code;data;constructor(xn,jn,Vn,qn){super(qn??`CDP command failed: ${xn}`),this.method=xn,this.code=jn,this.data=Vn}},CdpClient=class{cdpUrl;logId;#e;#t;#n;#r=null;#i=null;#a=null;#o=false;#s=1;#c=new Map;#l=new Emittery;#u=false;transportEvents=new Emittery;constructor(xn={}){this.cdpUrl=normalizeBaseUrl(xn.cdpUrl??`http://${OMOWRIGHT_BROWSER_CDP_HOST}`),this.logId=xn.logId??`cdp-${Date.now()}`,this.#e=xn.authorizer,this.#t=xn.commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS,this.#n=xn.reconnectDelaysMs??DEFAULT_RECONNECT_DELAYS_MS}get isConnected(){return this.#r?.readyState===wrapper_default.OPEN}start(){this.#o||(this.#o=true,this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] Initial CDP connect failed`,xn),this.#b()}))}async discoverVersion(xn={}){return await this.#f(this.#d(`/json/version`),jsonVersionSchema,xn)}async discoverTargets(xn={}){return await this.#f(this.#d(`/json/list`),array2(jsonTargetSchema),xn)}async ensureConnected(){if(this.#o=true,this.isConnected)return;if(this.#i){await this.#i;return}let xn=this.#g();this.#i=xn;try{await xn}finally{this.#i===xn&&(this.#i=null)}}async send(xn,jn,Vn,qn={}){if(xn===`Target.createTarget`&&qn.capability!==targetCreationCapability)throw Error(`Target.createTarget is reserved for createAgentTabs`);let Jn=getCurrentReplAbortSignal();if(Jn?.aborted)throw createAbortError$1();if(xn.startsWith(`OmO.`)){let Vn=await sendCommandToExtension({method:xn,params:jn},{...qn.extensionBridge,signal:Jn});if(Jn?.aborted)throw createAbortError$1();return Vn}await this.ensureConnected();let Yn=this.#r;if(!Yn||Yn.readyState!==wrapper_default.OPEN)throw Error(`CDP websocket is not connected`);let Zn=this.#s++,Qn={id:Zn,method:xn};jn!==undefined&&(Qn.params=jn),Vn&&(Qn.sessionId=Vn);let{promise:ei,reject:ti,resolve:ni}=Promise.withResolvers(),ri=qn.timeoutMs??this.#t,ii=ri>0?setTimeout(()=>{this.#c.delete(Zn),ti(Error(`CDP command timeout: ${String(xn)}`))},ri):undefined,ai=Jn?()=>{ii&&clearTimeout(ii),this.#c.delete(Zn),ti(createAbortError$1())}:undefined;if(this.#c.set(Zn,{method:String(xn),reject:ti,resolve:ni,timeout:ii}),Jn?.addEventListener(`abort`,ai,{once:true}),Jn?.aborted)return ai?.(),await ei;try{Yn.send(JSON.stringify(Qn))}catch(xn){throw ii&&clearTimeout(ii),this.#c.delete(Zn),ai&&Jn?.removeEventListener(`abort`,ai),xn instanceof Error?xn:Error(String(xn))}try{return await ei}finally{ai&&Jn?.removeEventListener(`abort`,ai)}}on(xn,jn){return this.#l.on(xn,({data:xn})=>jn(xn.payload,xn.meta))}async close(){this.#o=false,this.#a&&=(clearTimeout(this.#a),null);let xn=this.#r;if(this.#r=null,this.#x(Error(`CDP client closed`)),xn&&xn.readyState<=wrapper_default.OPEN)try{xn.close(1000,`client closing`)}catch{}}#d(xn){let jn=new URL(this.cdpUrl);return isWebSocketUrl(this.cdpUrl)?(jn.protocol=jn.protocol===`wss:`?`https:`:`http:`,jn.pathname=xn,jn.search=``,jn.toString()):(jn.pathname=xn,jn.search=``,jn.toString())}async#f(xn,jn,Vn={}){let qn=await this.#p(Vn),Jn=await fetch(xn,{headers:qn});if((Jn.status===401||Jn.status===403)&&this.#e&&!Vn.forceRefresh)return await this.#f(xn,jn,{forceRefresh:true});if(!Jn.ok)throw Error(`CDP discovery request failed (${Jn.status} ${Jn.statusText})`);return jn.parse(await Jn.json())}async#p(xn={}){return this.#e?{Authorization:await this.#e.resolveAuthorization(xn)}:{}}async#m(xn={}){let jn=await this.#p(xn);return isWebSocketUrl(this.cdpUrl)?{headers:jn,wsUrl:this.cdpUrl}:{headers:jn,wsUrl:(await this.discoverVersion(xn)).webSocketDebuggerUrl}}#h(){return this.cdpUrl!==`http://${OMOWRIGHT_BROWSER_CDP_HOST}`}async#g(){let xn=null,jn=false;for(let Vn of this.#n){Vn>0&&await sleep$12(Vn);try{await this.#_({forceRefresh:jn});return}catch(Vn){let qn=Vn??Error(`Unknown error`);xn=qn,isAuthorizationError(qn)&&(jn=true)}}throw xn instanceof Error?xn:Error(String(xn??`Failed to connect CDP websocket`))}async#_(xn={}){let{headers:jn,wsUrl:Vn}=await this.#m(xn);await new Promise((xn,qn)=>{let Jn=new wrapper_default(Vn,{headers:jn}),Yn=false,Zn=(xn)=>{Yn||(Yn=true,qn(xn))};Jn.addEventListener(`open`,()=>{Yn||(Yn=true,this.#v(Jn),xn())}),Jn.addEventListener(`message`,(xn)=>{this.#r===Jn&&this.#S(xn.data).catch(()=>{})}),Jn.addEventListener(`close`,(xn)=>{this.#r===Jn&&this.#y(Jn),Yn||Zn(Error(`CDP websocket closed during connect (${xn.code} ${xn.reason||`no reason`})`))}),Jn.addEventListener(`error`,()=>{Zn(Error(`Failed to connect CDP websocket: ${Vn}`))})})}#v(xn){this.#a&&=(clearTimeout(this.#a),null);let jn=this.#r;if(this.#r=xn,this.send(`Target.setDiscoverTargets`,{discover:true}).catch(()=>{}),this.transportEvents.emit(this.#u?`reconnected`:`connected`).catch((xn)=>{console.warn(`[${this.logId}] CDP transport listener failed`,xn)}),this.#u=true,jn&&jn!==xn&&jn.readyState<=wrapper_default.OPEN)try{jn.close(1000,`replaced`)}catch{}}#y(xn){this.#r===xn&&(this.#r=null,this.#x(Error(`CDP websocket disconnected`)),this.transportEvents.emit(`disconnected`).catch((xn)=>{console.warn(`[${this.logId}] CDP disconnect listener failed`,xn)}),this.#o&&this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] CDP reconnect failed`,xn),this.#b()}))}#b(){if(!this.#o||this.isConnected||this.#i||this.#a)return;let xn=this.#n[this.#n.length-1]??3000;this.#a=setTimeout(()=>{this.#a=null,this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] Scheduled CDP reconnect failed`,xn),this.#b()})},xn)}#x(xn){for(let jn of this.#c.values())jn.timeout&&clearTimeout(jn.timeout),jn.reject(xn);this.#c.clear()}async#S(xn){let jn=typeof xn==`string`?xn:xn instanceof Blob?await xn.text():new TextDecoder().decode(xn),{data:Vn}=cdpWireMessageSchema.safeParse(JSON.parse(jn));if(Vn){if(typeof Vn.id==`number`){let xn=this.#c.get(Vn.id);if(!xn)return;if(this.#c.delete(Vn.id),xn.timeout&&clearTimeout(xn.timeout),Vn.error){let jn=Vn.error;xn.reject(new BrowserCdpCommandError(xn.method,jn.code,jn.data,jn.message??`CDP command failed: ${xn.method}`));return}xn.resolve(Vn.result);return}if(typeof Vn.method==`string`){let xn=Vn.method;if(xn===`Page.javascriptDialogOpening`&&Vn.sessionId){let xn=this.#r;xn?.readyState===wrapper_default.OPEN&&xn.send(JSON.stringify({id:this.#s++,method:`Page.handleJavaScriptDialog`,params:{accept:true},sessionId:Vn.sessionId}))}let jn={payload:Vn.params,meta:{sessionId:Vn.sessionId}};this.#l.emit(xn,jn).catch((jn)=>{console.warn(`[${this.logId}] CDP event listener failed for ${xn}`,jn)})}}}}});var SessionManager;var init_session_manager=__esmMin(()=>{init_client$6(),SessionManager=class{#e;#t=new Map;#n=new Map;#r=new Map;#i=new Set;#a;constructor(xn){this.#e=xn,this.#a=[this.#e.on(`Target.attachedToTarget`,(xn)=>{let jn=xn.targetInfo.targetId;jn&&this.#s(jn,xn.sessionId)}),this.#e.on(`Target.detachedFromTarget`,(xn)=>{let jn=xn.targetId??this.#n.get(xn.sessionId);this.#n.delete(xn.sessionId),jn&&this.#t.get(jn)===xn.sessionId&&this.#t.delete(jn)})]}clear(){this.#t.clear(),this.#n.clear(),this.#r.clear()}async dispose(){for(let xn of this.#a)xn();await Promise.allSettled([...this.#i].map((xn)=>this.#e.send(`Target.detachFromTarget`,{sessionId:xn}).catch(()=>{}))),this.#i.clear(),this.clear()}async discoverTargets(){return await this.#e.discoverTargets()}async getPageTarget(xn){return(await this.discoverTargets()).find((jn)=>jn.id===xn&&jn.type===`page`)??null}hasTargetSession(xn,jn){return this.#t.get(xn)===jn}getTargetSession(xn){return this.#t.get(xn)}async resolvePageSession(xn,jn){if(jn&&this.hasTargetSession(xn,jn))return jn;let Vn=this.#t.get(xn);if(Vn)return Vn;let qn=this.#r.get(xn);if(qn)return await qn;let Jn=this.#o(xn).finally(()=>{this.#r.delete(xn)});return this.#r.set(xn,Jn),await Jn}async#o(xn){if(!await this.getPageTarget(xn))throw Error(`Tab ${xn} is no longer available.`);let jn=await this.#e.send(`Target.attachToTarget`,{targetId:xn,flatten:true});return this.#i.add(jn.sessionId),this.#s(xn,jn.sessionId),jn.sessionId}#s(xn,jn){this.#t.set(xn,jn),this.#n.set(jn,xn)}}});var globalCdpClient;var init_cdp=__esmMin(()=>{init_client$6(),init_session_manager(),globalCdpClient=new CdpClient});var BUNDLE$1;var init_omowright_world_bundle=__esmMin(()=>{BUNDLE$1=pageBundle});var MAX_BUFFER_SIZE;var CONSOLE_INTERCEPTOR_SCRIPT;var PageConsole;var init_console_capture=__esmMin(()=>{MAX_BUFFER_SIZE=1000,CONSOLE_INTERCEPTOR_SCRIPT=`(function(){+}`;let fn;try{const factory=new F(...constantNames,factoryCode);fn=factory(...constantValues)}catch(err){throw new ZodCompileUnsupportedError(`this schema (generated code failed to evaluate: ${err.message})`)}if(options?.debug){fn.code=fullCode}fn.definite=ctx.definite;return fn}function addConstant(ctx,value){for(const[name,v]of ctx.constants){if(v===value)return name}const name=`c${ctx.constantCounter++}`;ctx.constants.set(name,value);return name}function addUserConstant(ctx,fn){ctx.definite=false;return addConstant(ctx,fn)}function newVar(ctx){return`v${ctx.varCounter++}`}function runtimeRun(schema,value){const result=schema._zod.run({value,issues:[]},{});if(result&&typeof result.then==="function")return INVALID;const r=result;return r.issues.length===0?r.value:INVALID}function compileChild(doc,ctx,schema,accessor,needsValue=true){const contentLen=doc.content.length;const constantCount=ctx.constants.size;const constantCounter=ctx.constantCounter;const varCounter=ctx.varCounter;try{return generateCheck(doc,ctx,schema,accessor,needsValue)}catch(err){if(!(err instanceof ZodCompileUnsupportedError)||!err.islandable)throw err;doc.content.length=contentLen;if(ctx.constants.size>constantCount){const trailing=Array.from(ctx.constants.keys()).slice(constantCount);for(const k of trailing)ctx.constants.delete(k)}ctx.constantCounter=constantCounter;ctx.varCounter=varCounter;return emitRuntimeIsland(doc,ctx,schema,accessor)}}function emitRuntimeIsland(doc,ctx,schema,accessor){ctx.definite=false;const schemaConst=addConstant(ctx,schema);const runConst=addConstant(ctx,runtimeRun);const outVar=newVar(ctx);doc.write(`const ${outVar} = ${runConst}(${schemaConst}, ${accessor});`);doc.write(`if (${outVar} === INVALID) return INVALID;`);return outVar}var WHEN_DEFAULTED_CHECKS=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function generateChecks(doc,ctx,schema,accessor){const schemaChecks=schema._zod.def.checks;if(!schemaChecks||schemaChecks.length===0)return accessor;let currentAccessor=accessor;for(const check of schemaChecks){const def=check._zod.def;if(def.when&&!WHEN_DEFAULTED_CHECKS.has(def.check)){throw new ZodCompileUnsupportedError(`check with a custom "when" condition`)}switch(def.check){case"greater_than":generateGreaterThanCheck(doc,ctx,def,currentAccessor);break;case"less_than":generateLessThanCheck(doc,ctx,def,currentAccessor);break;case"multiple_of":generateMultipleOfCheck(doc,ctx,def,currentAccessor);break;case"number_format":generateNumberFormatCheck(doc,def,currentAccessor);break;case"min_length":{const min=numericOperand(def.minimum,"min_length");const len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${min} && ${currentAccessor}.length < ${def.minimum*2}`);doc.write(`if (${len} < ${min}) return INVALID;`);break}case"max_length":{const max=numericOperand(def.maximum,"max_length");const len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length > ${max}`);doc.write(`if (${len} > ${max}) return INVALID;`);break}case"length_equals":{const exact=numericOperand(def.length,"length_equals");const len=codePointLengthVar(doc,ctx,currentAccessor,`${currentAccessor}.length >= ${exact} && ${currentAccessor}.length <= ${def.length*2}`);doc.write(`if (${len} !== ${exact}) return INVALID;`);break}case"min_size":doc.write(`if (${currentAccessor}.size < ${numericOperand(def.minimum,"min_size")}) return INVALID;`);break;case"max_size":doc.write(`if (${currentAccessor}.size > ${numericOperand(def.maximum,"max_size")}) return INVALID;`);break;case"size_equals":doc.write(`if (${currentAccessor}.size !== ${numericOperand(def.size,"size_equals")}) return INVALID;`);break;case"string_format":currentAccessor=generateStringFormatCheck(doc,ctx,def,currentAccessor);break;case"custom":currentAccessor=generateCustomRefineCheck(doc,ctx,check,currentAccessor);break;case"bigint_format":generateBigIntFormatCheck(doc,def,currentAccessor);break;case"mime_type":generateMimeTypeCheck(doc,ctx,def,currentAccessor);break;case"property":generatePropertyCheck(doc,ctx,def,currentAccessor);break;case"properties":generatePropertiesChecks(doc,ctx,def,currentAccessor);break;case"overwrite":{const newAccessor=newVar(ctx);generateOverwriteCheck(doc,ctx,check,currentAccessor,newAccessor);currentAccessor=newAccessor;break}default:{throw new ZodCompileUnsupportedError(`check type ${def.check}`)}}}return currentAccessor}function codePointLengthVar(doc,ctx,accessor,inDoubt){const cpLen=addConstant(ctx,codePointLength);const v=newVar(ctx);doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`);return v}function numericOperand(value,label){if(typeof value!=="number"||!Number.isFinite(value)){throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`)}return`${value}`}function comparisonOperand(ctx,value){if(typeof value==="bigint")return`${value}n`;if(typeof value==="number"){if(Number.isNaN(value))throw new ZodCompileUnsupportedError("comparison check with NaN bound");return`${value}`}if(value instanceof Date){if(Number.isNaN(value.getTime())){throw new ZodCompileUnsupportedError("comparison check with Invalid Date bound")}return addConstant(ctx,value)}throw new ZodCompileUnsupportedError(`comparison check bound of type ${typeof value}`)}function generateGreaterThanCheck(doc,ctx,def,accessor){const op=def.inclusive?"<":"<=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateLessThanCheck(doc,ctx,def,accessor){const op=def.inclusive?">":">=";doc.write(`if (${accessor} ${op} ${comparisonOperand(ctx,def.value)}) return INVALID;`)}function generateMultipleOfCheck(doc,ctx,def,accessor){if(typeof def.value==="bigint"){if(def.value===BigInt(0))throw new ZodCompileUnsupportedError("multiple_of check with a zero divisor");doc.write(`if (${accessor} % ${def.value}n !== 0n) return INVALID;`)}else{const remainder=addConstant(ctx,floatSafeRemainder);doc.write(`if (${remainder}(${accessor}, ${numericOperand(def.value,"multiple_of")}) !== 0) return INVALID;`)}}function generateNumberFormatCheck(doc,def,accessor){const format=def.format;switch(format){case"safeint":doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`);break;case"int32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < -2147483648 || ${accessor} > 2147483647) return INVALID;`);break;case"uint32":doc.write(`if (!Number.isInteger(${accessor}) || ${accessor} < 0 || ${accessor} > 4294967295) return INVALID;`);break;case"float32":doc.write(`if (!Number.isFinite(${accessor}) || ${accessor} < -3.4028234663852886e38 || ${accessor} > 3.4028234663852886e38) return INVALID;`);break;case"float64":doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`);break;default:{throw new ZodCompileUnsupportedError(`number format ${format}`)}}}function generateBigIntFormatCheck(doc,def,accessor){const format=def.format;if(!format)return;switch(format){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break;default:{throw new ZodCompileUnsupportedError(`bigint format ${format}`)}}}function generateMimeTypeCheck(doc,ctx,def,accessor){const mimeTypes=def.mime;if(mimeTypes&&mimeTypes.length>0){const mimeSet=addConstant(ctx,new Set(mimeTypes));doc.write(`if (!${mimeSet}.has(${accessor}.type)) return INVALID;`)}}function generatePropertiesChecks(doc,ctx,def,accessor){if(def.when){throw new ZodCompileUnsupportedError(`check with a custom "when" condition`)}doc.write(`if (${accessor} == null) return INVALID;`);const shape=def.shape;for(const key of Reflect.ownKeys(shape)){const keyExpr=typeof key==="symbol"?addConstant(ctx,key):esc(key);const inputVar=newVar(ctx);doc.write(`const ${inputVar} = ${accessor}[${keyExpr}];`);compileChild(doc,ctx,shape[key],inputVar,false)}}function generatePropertyCheck(doc,ctx,def,accessor){const propAccessor=`${accessor}[${JSON.stringify(def.property)}]`;generateCheck(doc,ctx,def.schema,propAccessor)}function generateOverwriteCheck(doc,ctx,check,currentAccessor,newAccessor){const tx=check._zod.def.tx;if(!tx){throw new ZodCompileUnsupportedError("overwrite check without a transform function")}if(isAsyncFunction(tx)){throw new ZodCompileAsyncError("z.compile: async overwrite transforms are not supported")}const txConst=addConstant(ctx,tx);doc.write(`const ${newAccessor} = ${txConst}(${currentAccessor});`)}function throwAsync(){throw new $ZodAsyncError}function pushIssue(issue){this.issues.push(issue)}function generateCustomRefineCheck(doc,ctx,check,accessor){const def=check._zod.def;if(def.fn){if(isAsyncFunction(def.fn)){throw new ZodCompileAsyncError("z.compile: async .refine() predicates are not supported")}const fnConst=addUserConstant(ctx,def.fn);const throwAsyncConst=addConstant(ctx,throwAsync);const resVar=newVar(ctx);doc.write(`const ${resVar} = ${fnConst}(${accessor});`);doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);doc.write(`if (!${resVar}) return INVALID;`);return accessor}if(check._zod.check){if(isAsyncFunction(check._zod.check)){throw new ZodCompileAsyncError("z.compile: async .superRefine() / check functions are not supported")}const checkFn=check._zod.check;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=checkFn(fakePayload);if(result instanceof Promise)throwAsync();return fakePayload.issues.length===0?fakePayload.value:INVALID};const helperConst=addUserConstant(ctx,helperFn);const outVar=newVar(ctx);doc.write(`const ${outVar} = ${helperConst}(${accessor});`);doc.write(`if (${outVar} === INVALID) return INVALID;`);return outVar}throw new ZodCompileUnsupportedError("custom check without a predicate or check function")}var PATTERN_IS_COMPLETE=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function generateStringFormatCheck(doc,ctx,def,accessor,needsValue=true){const fmt=def.format;if(fmt==="base64"){const validator=addConstant(ctx,isValidBase64);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="base64url"){const validator=addConstant(ctx,isValidBase64URL);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="jwt"){const validator=addConstant(ctx,isValidJWT);const alg=addConstant(ctx,def.alg??null);doc.write(`if (!${validator}(${accessor}, ${alg})) return INVALID;`);return accessor}if(fmt==="ipv6"){const validator=addConstant(ctx,isValidIPv6);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="cidrv6"){const validator=addConstant(ctx,isValidCIDRv6);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="credit_card"){const validator=addConstant(ctx,isValidCreditCard);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}if(fmt==="iban"){const validator=addConstant(ctx,isValidIBAN);doc.write(`if (!${validator}(${accessor})) return INVALID;`);return accessor}const formatDef=def;if(fmt==="url"||fmt==="httpurl"||formatDef.normalize||formatDef.hostname!==undefined||formatDef.protocol!==undefined){const parseConst=addConstant(ctx,validateURL);const defConst=addConstant(ctx,def);const trimVar=newVar(ctx);const urlVar=newVar(ctx);doc.write(`const ${trimVar} = ${accessor}.trim();`);doc.write(`const ${urlVar} = ${parseConst}(${trimVar}, ${defConst});`);doc.write(`if (typeof ${urlVar} === "number") return INVALID;`);if(formatDef.hostname!==undefined){const hostnameConst=addConstant(ctx,urlHostnameOk);doc.write(`if (!${hostnameConst}(${urlVar}, ${defConst}.hostname)) return INVALID;`)}if(formatDef.protocol!==undefined){const protocolConst=addConstant(ctx,urlProtocolOk);doc.write(`if (!${protocolConst}(${urlVar}, ${defConst}.protocol)) return INVALID;`)}if(!needsValue)return null;const outputVar=newVar(ctx);const outputExpr=formatDef.normalize?`${urlVar}.href`:`${addConstant(ctx,stripTabAndNewline)}(${trimVar})`;doc.write(`const ${outputVar} = ${outputExpr};`);return outputVar}const customFn=def.fn;if(customFn){if(isAsyncFunction(customFn))throw new ZodCompileUnsupportedError(`async string format ${fmt}`);const fnConst=addConstant(ctx,customFn);doc.write(`if (!${fnConst}(${accessor})) return INVALID;`);return accessor}if(PATTERN_IS_COMPLETE.has(fmt)&&def.pattern){const patternConst=addConstant(ctx,def.pattern);doc.write(`${patternConst}.lastIndex = 0;`);doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`);return accessor}const format=def.format;switch(format){case"regex":throw new ZodCompileUnsupportedError("regex format without a pattern");case"lowercase":doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`);break;case"uppercase":doc.write(`if (${accessor} !== ${accessor}.toUpperCase()) return INVALID;`);break;case"includes":doc.write(`if (!${accessor}.includes(${esc(def.includes)})) return INVALID;`);break;case"starts_with":{const prefix=def.prefix;doc.write(`if (${accessor}.slice(0, ${prefix.length}) !== ${esc(prefix)}) return INVALID;`);break}case"ends_with":{const suffix=def.suffix;doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc(suffix)}) return INVALID;`);break}default:{throw new ZodCompileUnsupportedError(`string format ${format}`)}}return accessor}function generateCheck(doc,ctx,schema,accessor,needsValue=true){const def=schema._zod.def;const type=def.type;if(def.coerce){throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`)}const buildsValue=needsValue||!!def.checks?.length;let typeAccessor;switch(type){case"string":typeAccessor=generateStringCheck(doc,ctx,schema,accessor,buildsValue);break;case"number":typeAccessor=generateNumberCheck(doc,schema,accessor);break;case"boolean":typeAccessor=generateBooleanCheck(doc,accessor);break;case"bigint":typeAccessor=generateBigIntCheck(doc,schema,accessor);break;case"symbol":typeAccessor=generateSymbolCheck(doc,accessor);break;case"undefined":typeAccessor=generateUndefinedCheck(doc,accessor);break;case"null":typeAccessor=generateNullCheck(doc,accessor);break;case"any":case"unknown":typeAccessor=accessor;break;case"never":doc.write("return INVALID;");typeAccessor=accessor;break;case"void":typeAccessor=generateVoidCheck(doc,accessor);break;case"nan":typeAccessor=generateNaNCheck(doc,accessor);break;case"date":typeAccessor=generateDateCheck(doc,accessor);break;case"object":typeAccessor=generateObjectCheck(doc,ctx,schema,accessor,buildsValue);break;case"optional":typeAccessor=generateOptionalCheck(doc,ctx,schema,accessor,buildsValue);break;case"nullable":typeAccessor=generateNullableCheck(doc,ctx,schema,accessor,buildsValue);break;case"array":typeAccessor=generateArrayCheck(doc,ctx,schema,accessor,buildsValue);break;case"literal":typeAccessor=generateLiteralCheck(doc,ctx,schema,accessor);break;case"enum":typeAccessor=generateEnumCheck(doc,ctx,schema,accessor);break;case"readonly":{const innerOut=generateWrapperCheck(doc,ctx,schema,accessor);const frozenVar=newVar(ctx);doc.write(`const ${frozenVar} = Object.freeze(${innerOut});`);typeAccessor=frozenVar;break}case"success":generateWrapperCheck(doc,ctx,schema,accessor);typeAccessor="true";break;case"default":case"prefault":typeAccessor=generateDefaultCheck(doc,ctx,schema,accessor);break;case"nonoptional":typeAccessor=generateNonOptionalCheck(doc,ctx,schema,accessor);break;case"tuple":typeAccessor=generateTupleCheck(doc,ctx,schema,accessor);break;case"union":typeAccessor=generateUnionCheck(doc,ctx,schema,accessor);break;case"intersection":typeAccessor=generateIntersectionCheck(doc,ctx,schema,accessor);break;case"record":typeAccessor=generateRecordCheck(doc,ctx,schema,accessor);break;case"map":typeAccessor=generateMapCheck(doc,ctx,schema,accessor);break;case"set":typeAccessor=generateSetCheck(doc,ctx,schema,accessor);break;case"file":typeAccessor=generateFileCheck(doc,accessor);break;case"template_literal":typeAccessor=generateTemplateLiteralCheck(doc,ctx,schema,accessor);break;case"lazy":typeAccessor=generateLazyCheck(doc,ctx,schema,accessor);break;case"pipe":typeAccessor=generatePipeCheck(doc,ctx,schema,accessor);break;case"custom":typeAccessor=generateCustomCheck(doc,ctx,schema,accessor);break;case"transform":typeAccessor=generateTransformCheck(doc,ctx,schema,accessor);break;case"catch":typeAccessor=generateCatchCheck(doc,ctx,schema,accessor);break;default:{throw new ZodCompileUnsupportedError(`schema type ${type}`)}}if(typeAccessor===null)return null;return generateChecks(doc,ctx,schema,typeAccessor)}function generateStringCheck(doc,ctx,schema,accessor,needsValue=true){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);const def=schema._zod.def;if(def.format===undefined)return accessor;return generateStringFormatCheck(doc,ctx,def,accessor,needsValue)}function generateNumberCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "number" || !Number.isFinite(${accessor})) return INVALID;`);const def=schema._zod.def;if(def.check==="number_format"&&def.format){generateNumberFormatCheck(doc,{format:def.format},accessor)}return accessor}function generateBooleanCheck(doc,accessor){doc.write(`if (typeof ${accessor} !== "boolean") return INVALID;`);return accessor}function generateBigIntCheck(doc,schema,accessor){doc.write(`if (typeof ${accessor} !== "bigint") return INVALID;`);const def=schema._zod.def;if(def.format){switch(def.format){case"int64":doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);break;case"uint64":doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);break}}return accessor}function generateSymbolCheck(doc,accessor){doc.write(`if (typeof ${accessor} !== "symbol") return INVALID;`);return accessor}function generateUndefinedCheck(doc,accessor){doc.write(`if (${accessor} !== undefined) return INVALID;`);return accessor}function generateNullCheck(doc,accessor){doc.write(`if (${accessor} !== null) return INVALID;`);return accessor}function generateVoidCheck(doc,accessor){doc.write(`if (${accessor} !== undefined) return INVALID;`);return accessor}function generateNaNCheck(doc,accessor){doc.write(`if (typeof ${accessor} !== "number" || !Number.isNaN(${accessor})) return INVALID;`);return accessor}function generateDateCheck(doc,accessor){doc.write(`if (!(${accessor} instanceof Date) || Number.isNaN(${accessor}.getTime())) return INVALID;`);return accessor}function generateObjectCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;doc.write(`if (typeof ${accessor} !== "object" || ${accessor} === null || Array.isArray(${accessor})) return INVALID;`);const shape=def.shape;const keys=Object.keys(shape);const symbolKeys=Object.getOwnPropertySymbols(shape);const allKeys=symbolKeys.length?[...keys,...symbolKeys]:keys;const keyExpr=(k)=>typeof k==="symbol"?addConstant(ctx,k):esc(k);const propKey=(k)=>typeof k==="symbol"?`[${keyExpr(k)}]`:esc(k);const propShape=shape;if(keys.includes("__proto__")){throw new ZodCompileUnsupportedError('object shape key "__proto__"')}const propOutputs=new Map;for(const key of allKeys){const propSchema=propShape[key];const kx=keyExpr(key);const inputVar=newVar(ctx);doc.write(`const ${inputVar} = ${accessor}[${kx}];`);if(propSchema._zod.optin!==undefined){const outputVar=newVar(ctx);doc.write(`let ${outputVar} = (() => {`);doc.indented((d)=>{const outputAccessor=compileChild(d,ctx,propSchema,inputVar);d.write(`return ${outputAccessor};`)});doc.write(`})();`);if(propSchema._zod.optout==="optional"){doc.write(`if (${outputVar} === INVALID) {`);doc.indented((d)=>{d.write(`if (${kx} in ${accessor}) return INVALID;`);d.write(`${outputVar} = undefined;`)});doc.write(`}`)}else{doc.write(`if (${outputVar} === INVALID) return INVALID;`)}propOutputs.set(key,outputVar)}else{if(requiresPresenceCheck(propSchema)){doc.write(`if (!(${kx} in ${accessor})) return INVALID;`)}const outputAccessor=compileChild(doc,ctx,propSchema,inputVar,buildsValue);if(outputAccessor!==null)propOutputs.set(key,outputAccessor)}}const catchall=def.catchall;let unknownKeysMode="none";if(catchall){const catchallType=catchall._zod.def.type;if(catchallType==="never"){const condition=keys.map((k)=>`k !== ${esc(k)}`).join(" && ")||"true";doc.write(`for (const k in ${accessor}) {`);doc.indented((d)=>{d.write(`if (${condition}) return INVALID;`)});doc.write(`}`)}else if((catchallType==="unknown"||catchallType==="any")&&!catchall._zod.def.checks?.length){unknownKeysMode="passthrough"}else{unknownKeysMode="schema"}}const outputVar=newVar(ctx);const hasConditionalKeys=allKeys.some((k)=>mayOmitUndefined(propShape[k])||dropsWhenAbsent(propShape[k]));if(!buildsValue){if(unknownKeysMode==="schema"){const knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`);doc.indented((d)=>{d.write(`if (k === "__proto__") continue;`);if(knownSet)d.write(`if (${knownSet}.has(k)) continue;`);const valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`);compileChild(d,ctx,catchall,valVar,false)});doc.write(`}`)}return null}if(!hasConditionalKeys){const propLiterals=allKeys.map((k)=>`${propKey(k)}: ${propOutputs.get(k)}`).join(", ");doc.write(`const ${outputVar} = { ${propLiterals} };`)}else{doc.write(`const ${outputVar} = {};`);for(const k of allKeys){const kx=keyExpr(k);const out=propOutputs.get(k);if(dropsWhenAbsent(propShape[k])){doc.write(`if (${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`)}else if(mayOmitUndefined(propShape[k])){doc.write(`if (${out} !== undefined || ${kx} in ${accessor}) ${outputVar}[${kx}] = ${out};`)}else{doc.write(`${outputVar}[${kx}] = ${out};`)}}}if(unknownKeysMode!=="none"){const knownSet=keys.length>0?addConstant(ctx,new Set(keys)):null;doc.write(`for (const k in ${accessor}) {`);doc.indented((d)=>{d.write(`if (k === "__proto__") continue;`);if(knownSet)d.write(`if (${knownSet}.has(k)) continue;`);if(unknownKeysMode==="passthrough"){d.write(`${outputVar}[k] = ${accessor}[k];`)}else{const valVar=newVar(ctx);d.write(`const ${valVar} = ${accessor}[k];`);const catchallOut=compileChild(d,ctx,catchall,valVar);d.write(`${outputVar}[k] = ${catchallOut};`)}});doc.write(`}`)}return outputVar}function generateOptionalCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;if(isExactOptional(schema)){return generateCheck(doc,ctx,def.innerType,accessor,buildsValue)}if(def.innerType._zod.optin==="defaulted"){const outputVar=newVar(ctx);const branchVar=newVar(ctx);doc.write(`let ${outputVar};`);doc.write(`if (${accessor} === undefined) {`);doc.indented((d)=>{d.write(`const ${branchVar} = (() => {`);d.indented((d2)=>{const innerOutput=generateCheck(d2,ctx,def.innerType,accessor);d2.write(`return ${innerOutput};`)});d.write(`})();`);d.write(`if (${branchVar} !== INVALID) ${outputVar} = ${branchVar};`)});doc.write(`} else {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`);return outputVar}const outputVar=buildsValue?newVar(ctx):null;if(outputVar)doc.write(`let ${outputVar};`);doc.write(`if (${accessor} !== undefined) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);if(outputVar&&innerOutput!==null)d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`);return outputVar}function isExactOptional(schema){return schema._zod.traits?.has("$ZodExactOptional")===true}function requiresPresenceCheck(schema){return schema._zod.optin===undefined&&fastPathAcceptsAbsence(schema)}function fastPathAcceptsAbsence(schema){if(schema._zod.def.coerce)return true;const def=schema._zod.def;switch(def.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return true;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return false;case"nonoptional":return def.innerType?fastPathAcceptsAbsence(def.innerType):false;case"literal":return!!def.values?.includes(undefined);case"enum":return!!schema._zod.values?.has(undefined);case"optional":case"nullable":case"readonly":case"success":return def.innerType?fastPathAcceptsAbsence(def.innerType):true;case"catch":return true;case"union":return def.options?def.options.some(fastPathAcceptsAbsence):true;case"intersection":if(!def.left||!def.right)return true;return fastPathAcceptsAbsence(def.left)&&fastPathAcceptsAbsence(def.right);case"pipe":return def.in?fastPathAcceptsAbsence(def.in):true;default:return true}}function dropsWhenAbsent(schema){return schema._zod.optin==="optional"&&schema._zod.optout==="optional"}function mayOmitUndefined(schema){return(schema._zod.optin!=="defaulted"||schema._zod.optout==="optional")&&mayOutputUndefined(schema)}function mayOutputUndefined(schema){const def=schema._zod.def;switch(def.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return false;case"literal":return!!def.values?.includes(undefined);case"enum":return!!schema._zod.values?.has(undefined);case"optional":return true;case"nullable":case"readonly":case"nonoptional":return def.innerType?mayOutputUndefined(def.innerType):true;case"union":return def.options?def.options.some(mayOutputUndefined):true;case"intersection":return!def.left||!def.right||mayOutputUndefined(def.left)||mayOutputUndefined(def.right);case"pipe":return def.out?mayOutputUndefined(def.out):true;default:return true}}function generateNullableCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;const outputVar=buildsValue?newVar(ctx):null;if(outputVar)doc.write(`let ${outputVar} = null;`);doc.write(`if (${accessor} !== null) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor,buildsValue);if(outputVar&&innerOutput!==null)d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`);return outputVar}function generateArrayCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);const outputVar=buildsValue?newVar(ctx):null;const iVar=newVar(ctx);const elemVar=newVar(ctx);if(outputVar)doc.write(`const ${outputVar} = new Array(${accessor}.length);`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);const elemOutput=compileChild(d,ctx,def.element,elemVar,buildsValue);if(outputVar&&elemOutput!==null)d.write(`${outputVar}[${iVar}] = ${elemOutput};`)});doc.write(`}`);return outputVar}function generateLiteralCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const values=def.values;if(values.length!==1){const literalSet=addConstant(ctx,new Set(values));doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);return accessor}const value=values[0];if(typeof value==="number"&&Number.isNaN(value)){const literalSet=addConstant(ctx,new Set(values));doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);return accessor}if(typeof value==="string"){doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`)}else if(typeof value==="number"||typeof value==="boolean"){doc.write(`if (${accessor} !== ${value}) return INVALID;`)}else if(value===null){doc.write(`if (${accessor} !== null) return INVALID;`)}else if(value===undefined){doc.write(`if (${accessor} !== undefined) return INVALID;`)}else if(typeof value==="bigint"){doc.write(`if (${accessor} !== ${value}n) return INVALID;`)}else{throw new ZodCompileUnsupportedError(`literal type ${typeof value}`)}return accessor}function generateEnumCheck(doc,ctx,schema,accessor){const values=schema._zod.values;if(!values){throw new ZodCompileUnsupportedError("enum schema without enumerated values")}const enumSet=addConstant(ctx,values);doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`);return accessor}function generateWrapperCheck(doc,ctx,schema,accessor){const def=schema._zod.def;return generateCheck(doc,ctx,def.innerType,accessor)}function generateDefaultCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const descriptor=Object.getOwnPropertyDescriptor(schema._zod.def,"defaultValue");const defaultGetter=descriptor?()=>schema._zod.def.defaultValue:undefined;if(schema._zod.def.type==="prefault"){if(!defaultGetter){return generateCheck(doc,ctx,def.innerType,accessor)}const defaultFn=addConstant(ctx,defaultGetter);const inputVar=newVar(ctx);doc.write(`let ${inputVar} = ${accessor};`);doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`);return generateCheck(doc,ctx,def.innerType,inputVar)}const outputVar=newVar(ctx);if(defaultGetter){const defaultFn=addConstant(ctx,defaultGetter);const cloneFn=addConstant(ctx,shallowClone);doc.write(`let ${outputVar};`);doc.write(`if (${accessor} === undefined) {`);doc.indented((d)=>{d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`)});doc.write(`} else {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`)});doc.write(`}`)}else{doc.write(`let ${outputVar};`);doc.write(`if (${accessor} !== undefined) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`)}return outputVar}function generateNonOptionalCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const innerOutput=generateCheck(doc,ctx,def.innerType,accessor);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${innerOutput};`);doc.write(`if (${outputVar} === undefined) return INVALID;`);return outputVar}function generateTupleCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const items=def.items;const rest=def.rest;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);const optinStart=getTupleOptStart2(items,"optin");const optoutStart=getTupleOptStart2(items,"optout");if(rest){doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`)}else{doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`)}const outputVar=newVar(ctx);doc.write(`const ${outputVar} = [];`);for(let i=0;i<items.length;i++){const itemSchema=items[i];if(i>=optoutStart){doc.write(`if (${outputVar}.length === ${i}) {`);doc.indented((d)=>{d.write(`if (${i} < ${accessor}.length) {`);d.indented((d2)=>{const elemVar=newVar(ctx);d2.write(`const ${elemVar} = ${accessor}[${i}];`);const elemOutput=compileChild(d2,ctx,itemSchema,elemVar);d2.write(`${outputVar}[${i}] = ${elemOutput};`)});d.write(`} else {`);d.indented((d2)=>{if(dropsWhenAbsent(itemSchema)){d2.write(`${outputVar}.length = ${i};`);return}const elemVar=newVar(ctx);const branchVar=newVar(ctx);d2.write(`const ${elemVar} = undefined;`);d2.write(`const ${branchVar} = (() => {`);d2.indented((d3)=>{const elemOutput=compileChild(d3,ctx,itemSchema,elemVar);d3.write(`return ${elemOutput};`)});d2.write(`})();`);d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`);d2.write(`else ${outputVar}[${i}] = ${branchVar};`)});d.write(`}`)});doc.write(`}`)}else{const elemVar=newVar(ctx);doc.write(`const ${elemVar} = ${accessor}[${i}];`);const elemOutput=compileChild(doc,ctx,itemSchema,elemVar);doc.write(`${outputVar}[${i}] = ${elemOutput};`)}}if(rest){const iVar=newVar(ctx);const elemVar=newVar(ctx);doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);const elemOutput=compileChild(d,ctx,rest,elemVar);d.write(`${outputVar}[${iVar}] = ${elemOutput};`)});doc.write(`}`)}return outputVar}function getTupleOptStart2(items,key){for(let i=items.length-1;i>=0;i--){const omittable=key==="optin"?items[i]._zod.optin!==undefined:items[i]._zod.optout==="optional";if(!omittable)return i+1}return 0}function generateUnionCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const options=def.options;if(def.discriminator){return generateDiscriminatedUnionCheck(doc,ctx,def,accessor)}if(def.inclusive===false){throw new ZodCompileUnsupportedError("exclusive unions (z.xor)")}if(options.length===0){doc.write("return INVALID;");return accessor}if(options.length===1){return generateCheck(doc,ctx,options[0],accessor)}const allLiterals=options.every((opt)=>opt._zod.def.type==="literal"&&!opt._zod.def.checks?.length);if(allLiterals){const values=new Set(options.flatMap((opt)=>opt._zod.def.values));const valuesConst=addConstant(ctx,values);doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`);return accessor}const outputVar=newVar(ctx);doc.write(`let ${outputVar};`);for(let i=0;i<options.length;i++){const opt=options[i];if(i===0){doc.write(`${outputVar} = (() => {`)}else{doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`)}doc.indented((d)=>{const branchOutput=generateCheck(d,ctx,opt,accessor);d.write(`return ${branchOutput};`)});doc.write(`})();`)}doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}function generateDiscriminatedUnionCheck(doc,ctx,def,accessor){if(def.unionFallback){throw new ZodCompileUnsupportedError("discriminated union with unionFallback")}if(def.options.length===0){doc.write("return INVALID;");return accessor}const discVar=newVar(ctx);const outputVar=newVar(ctx);doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`);doc.write(`let ${outputVar};`);let firstBranch=true;const claimed=new Set;for(const option of def.options){const values=option._zod.propValues?.[def.discriminator];if(!values||values.size===0){throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values")}for(const value of values){if(claimed.has(value)){throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`)}claimed.add(value)}const conditions=Array.from(values,(value)=>literalEquality(ctx,discVar,value));const prefix=firstBranch?"if":"else if";doc.write(`${prefix} (${conditions.join(" || ")}) {`);doc.indented((d)=>{const branchOutput=generateCheck(d,ctx,option,accessor);d.write(`${outputVar} = ${branchOutput};`)});doc.write(`}`);firstBranch=false}doc.write(`else { return INVALID; }`);return outputVar}function literalEquality(ctx,accessor,value){if(typeof value==="string")return`${accessor} === ${esc(value)}`;if(typeof value==="number"){if(Number.isNaN(value))return`Number.isNaN(${accessor})`;return`${accessor} === ${value}`}if(typeof value==="boolean")return`${accessor} === ${value}`;if(value===null)return`${accessor} === null`;if(value===undefined)return`${accessor} === undefined`;if(typeof value==="bigint")return`${accessor} === ${value}n`;if(typeof value==="symbol"){const symbolConst=addConstant(ctx,value);return`${accessor} === ${symbolConst}`}throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`)}function generateIntersectionCheck(doc,ctx,schema,accessor){const def=schema._zod.def;ctx.definite=false;const leftOutput=compileChild(doc,ctx,def.left,accessor);const rightOutput=compileChild(doc,ctx,def.right,accessor);const mergeConst=addConstant(ctx,mergeValues);const mergedVar=newVar(ctx);doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`);doc.write(`if (!${mergedVar}.valid) return INVALID;`);return`${mergedVar}.data`}function generateRecordCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const isPlainObjectConst=addConstant(ctx,isPlainObject);doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`);const outputVar=newVar(ctx);const kVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = {};`);const recordDef=def;const keyValues=recordDef.partial?undefined:def.keyType._zod.values;if(keyValues){const inputKeys=[];for(const key of keyValues){if(!(typeof key==="string"||typeof key==="number"||typeof key==="symbol")){throw new ZodCompileUnsupportedError(`record key value ${String(key)}`)}const inputKey=typeof key==="number"?key.toString():key;if(inputKey==="__proto__"){throw new ZodCompileUnsupportedError('record key "__proto__"')}inputKeys.push(inputKey);const keyConst=addConstant(ctx,key);const outKey=generateCheck(doc,ctx,def.keyType,keyConst);const valueVar=newVar(ctx);doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx,inputKey)}];`);const valOutput=compileChild(doc,ctx,def.valueType,valueVar);doc.write(`${outputVar}[${outKey}] = ${valOutput};`)}const knownKeysConst=addConstant(ctx,new Set(inputKeys));doc.write(`for (const ${kVar} in ${accessor}) {`);doc.indented((d)=>{d.write(`if (${knownKeysConst}.has(${kVar})) continue;`);if(recordDef.mode==="loose"){d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`)}else{d.write(`return INVALID;`)}});doc.write(`}`);return outputVar}const keyDef=def.keyType._zod.def;const keyIsBareString=keyDef.type==="string"&&keyDef.format===undefined&&!keyDef.coerce&&(keyDef.checks?.length??0)===0;if(!keyIsBareString){const isLoose=def.mode==="loose";const keyFn=compileFn(def.keyType);if(keyFn.definite===false)ctx.definite=false;const keyFast=addConstant(ctx,keyFn);const numericConst=addConstant(ctx,number);const outKeyVar=newVar(ctx);emitOwnKeys(doc,ctx,accessor,kVar,(d)=>{d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`);d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`);if(isLoose){d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`)}else{d.write(`if (${outKeyVar} === INVALID) return INVALID;`)}d.write(`if (${outKeyVar} === "__proto__") continue;`);const valueVar=newVar(ctx);d.write(`const ${valueVar} = ${accessor}[${kVar}];`);const valOutput=compileChild(d,ctx,def.valueType,valueVar);d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`)});return outputVar}emitOwnKeys(doc,ctx,accessor,kVar,(d)=>{d.write(`const ${valVar} = ${accessor}[${kVar}];`);const valOutput=compileChild(d,ctx,def.valueType,valVar);d.write(`${outputVar}[${kVar}] = ${valOutput};`)},`return INVALID;`);return outputVar}function emitOwnKeys(doc,ctx,accessor,kVar,body,onSymbol){const propIsEnumerableConst=addConstant(ctx,Object.prototype.propertyIsEnumerable);const symsVar=newVar(ctx);const keysVar=newVar(ctx);const iVar=newVar(ctx);doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`);doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${kVar} = ${keysVar}[${iVar}];`);d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);body(d)});doc.write(`}`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${kVar} = ${symsVar}[${iVar}];`);d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);if(onSymbol)d.write(onSymbol);else body(d)});doc.write(`}`)}function literalPropertyKey(ctx,key){if(typeof key==="string")return esc(key);return addConstant(ctx,key)}function generateMapCheck(doc,ctx,schema,accessor){const def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`);const outputVar=newVar(ctx);const kVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = new Map();`);doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`);doc.indented((d)=>{const keyOutput=generateCheck(d,ctx,def.keyType,kVar);const valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`)});doc.write(`}`);return outputVar}function generateSetCheck(doc,ctx,schema,accessor){const def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`);const outputVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = new Set();`);doc.write(`for (const ${valVar} of ${accessor}) {`);doc.indented((d)=>{const valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.add(${valOutput});`)});doc.write(`}`);return outputVar}function generateFileCheck(doc,accessor){doc.write(`if (!(${accessor} instanceof File)) return INVALID;`);return accessor}function generateTemplateLiteralCheck(doc,ctx,schema,accessor){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);const pattern=schema._zod.pattern;if(pattern){const patternConst=addConstant(ctx,pattern);doc.write(`${patternConst}.lastIndex = 0;`);doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`)}return accessor}function generateLazyCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const getterConst=addUserConstant(ctx,def.getter);const cacheConst=addConstant(ctx,{parser:null});doc.write(`if (!${cacheConst}.parser) {`);doc.indented((d)=>{d.write(`const inner = ${getterConst}();`);d.write(`${cacheConst}.parser = function(input) {`);d.indented((d2)=>{d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`);d2.write(`return result.issues.length === 0 ? result.value : INVALID;`)});d.write(`};`)});doc.write(`}`);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`);doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}function generatePipeCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const inputOutput=generateCheck(doc,ctx,def.in,accessor);if(def.transform){if(isAsyncFunction(def.transform)){throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported")}const transformFn=def.transform;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=transformFn(value,fakePayload);if(result instanceof Promise)return INVALID;return fakePayload.issues.length===0?result:INVALID};const helperConst=addUserConstant(ctx,helperFn);const transformedVar=newVar(ctx);doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`);doc.write(`if (${transformedVar} === INVALID) return INVALID;`);return generateCheck(doc,ctx,def.out,transformedVar)}else{return generateCheck(doc,ctx,def.out,inputOutput)}}function isAsyncFunction(fn){return typeof fn==="function"&&(fn.constructor.name==="AsyncFunction"||fn[Symbol.toStringTag]==="AsyncFunction")}function generateCustomCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(def.fn){if(isAsyncFunction(def.fn)){throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported")}const fnConst=addUserConstant(ctx,def.fn);const throwAsyncConst=addConstant(ctx,throwAsync);const resVar=newVar(ctx);doc.write(`const ${resVar} = ${fnConst}(${accessor});`);doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);doc.write(`if (!${resVar}) return INVALID;`)}else{throw new ZodCompileUnsupportedError("custom schema without a predicate function")}return accessor}function runtimeCatch(innerSchema,catchValue,value){const result=innerSchema._zod.run({value,issues:[]},{});if(result&&typeof result.then==="function")return INVALID;const r=result;if(r.issues.length===0)return r.value;return catchValue()}function generateCatchCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(!def.catchValue[CONSTANT_CATCH]){throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)",false)}const outputVar=newVar(ctx);doc.write(`let ${outputVar} = (() => {`);doc.indented((d)=>{const innerOut=compileChild(d,ctx,def.innerType,accessor);d.write(`return ${innerOut};`)});doc.write(`})();`);const innerConst=addConstant(ctx,def.innerType);const catchConst=addUserConstant(ctx,def.catchValue);const catchHelperConst=addConstant(ctx,runtimeCatch);doc.write(`if (${outputVar} === INVALID) {`);doc.indented((d)=>{d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`);d.write(`if (${outputVar} === INVALID) return INVALID;`)});doc.write(`}`);return outputVar}function generateTransformCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(def.transform){if(isAsyncFunction(def.transform)){throw new ZodCompileAsyncError("z.compile: async transforms are not supported")}const transformFn=def.transform;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=transformFn(value,fakePayload);if(result instanceof Promise)return INVALID;return fakePayload.issues.length===0?result:INVALID};const helperConst=addUserConstant(ctx,helperFn);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${helperConst}(${accessor});`);doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}return accessor}function snapshotChecks(def){if(def.checks)def.checks=[...def.checks];return def}function _string(Class,params){return new Class(snapshotChecks({type:"string",...normalizeParams(params)}))}function _coercedString(Class,params){return new Class(snapshotChecks({type:"string",coerce:true,...normalizeParams(params)}))}function _email(Class,params){return new Class({type:"string",format:"email",check:"string_format",abort:false,...normalizeParams(params)})}function _guid(Class,params){return new Class({type:"string",format:"guid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuid(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuidv4(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v4",...normalizeParams(params)})}function _uuidv6(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v6",...normalizeParams(params)})}function _uuidv7(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v7",...normalizeParams(params)})}function _url(Class,params){return new Class({type:"string",format:"url",check:"string_format",abort:false,...normalizeParams(params)})}function _emoji2(Class,params){return new Class({type:"string",format:"emoji",check:"string_format",abort:false,...normalizeParams(params)})}function _nanoid(Class,params){return new Class({type:"string",format:"nanoid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid(Class,params){return new Class({type:"string",format:"cuid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid2(Class,params){return new Class({type:"string",format:"cuid2",check:"string_format",abort:false,...normalizeParams(params)})}function _ulid(Class,params){return new Class({type:"string",format:"ulid",check:"string_format",abort:false,...normalizeParams(params)})}function _xid(Class,params){return new Class({type:"string",format:"xid",check:"string_format",abort:false,...normalizeParams(params)})}function _ksuid(Class,params){return new Class({type:"string",format:"ksuid",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv4(Class,params){return new Class({type:"string",format:"ipv4",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv6(Class,params){return new Class({type:"string",format:"ipv6",check:"string_format",abort:false,...normalizeParams(params)})}function _mac(Class,params){return new Class({type:"string",format:"mac",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv4(Class,params){return new Class({type:"string",format:"cidrv4",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv6(Class,params){return new Class({type:"string",format:"cidrv6",check:"string_format",abort:false,...normalizeParams(params)})}function _base64(Class,params){return new Class({type:"string",format:"base64",check:"string_format",abort:false,...normalizeParams(params)})}function _base64url(Class,params){return new Class({type:"string",format:"base64url",check:"string_format",abort:false,...normalizeParams(params)})}function _e164(Class,params){return new Class({type:"string",format:"e164",check:"string_format",abort:false,...normalizeParams(params)})}function _creditCard(Class,params){return new Class({type:"string",format:"credit_card",check:"string_format",abort:false,...normalizeParams(params)})}function _iban(Class,params){return new Class({type:"string",format:"iban",check:"string_format",abort:false,...normalizeParams(params)})}function _jwt(Class,params){return new Class({type:"string",format:"jwt",check:"string_format",abort:false,...normalizeParams(params)})}var TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function _isoDateTime(Class,params){return new Class({type:"string",format:"datetime",check:"string_format",offset:false,local:false,precision:null,...normalizeParams(params)})}function _isoDate(Class,params){return new Class({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class,params){return new Class({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class,params){return new Class({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class,params){return new Class(snapshotChecks({type:"number",checks:[],...normalizeParams(params)}))}function _coercedNumber(Class,params){return new Class(snapshotChecks({type:"number",coerce:true,checks:[],...normalizeParams(params)}))}function _int(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"safeint",...normalizeParams(params)})}function _float32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"float32",...normalizeParams(params)})}function _float64(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"float64",...normalizeParams(params)})}function _int32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"int32",...normalizeParams(params)})}function _uint32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"uint32",...normalizeParams(params)})}function _boolean(Class,params){return new Class({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class,params){return new Class({type:"boolean",coerce:true,...normalizeParams(params)})}function _bigint(Class,params){return new Class({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class,params){return new Class({type:"bigint",coerce:true,...normalizeParams(params)})}function _int64(Class,params){return new Class({type:"bigint",check:"bigint_format",abort:false,format:"int64",...normalizeParams(params)})}function _uint64(Class,params){return new Class({type:"bigint",check:"bigint_format",abort:false,format:"uint64",...normalizeParams(params)})}function _symbol(Class,params){return new Class({type:"symbol",...normalizeParams(params)})}function _undefined2(Class,params){return new Class({type:"undefined",...normalizeParams(params)})}function _null2(Class,params){return new Class({type:"null",...normalizeParams(params)})}function _any(Class){return new Class({type:"any"})}function _unknown(Class){return new Class({type:"unknown"})}function _never(Class,params){return new Class({type:"never",...normalizeParams(params)})}function _void(Class,params){return new Class({type:"void",...normalizeParams(params)})}function _date(Class,params){return new Class({type:"date",...normalizeParams(params)})}function _coercedDate(Class,params){return new Class({type:"date",coerce:true,...normalizeParams(params)})}function _nan(Class,params){return new Class({type:"nan",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:false})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:true})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:false})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:true})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size})}function _maxLength(maximum,params){const ch=new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum});return ch}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _properties(shape,params){return new $ZodCheckProperties({check:"properties",shape,...normalizeParams(params)})}function _mime(types,params){return new $ZodCheckMimeType({check:"mime_type",mime:types,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite((input)=>input.normalize(form))}function _trim(){return _overwrite((input)=>input.trim())}function _toLowerCase(){return _overwrite((input)=>input.toLowerCase())}function _toUpperCase(){return _overwrite((input)=>input.toUpperCase())}function _slugify(){return _overwrite((input)=>slugify(input))}function _array(Class,element,params){return new Class({type:"array",element,...normalizeParams(params)})}function _union(Class,options,params){return new Class({type:"union",options,...normalizeParams(params)})}function _xor(Class,options,params){return new Class({type:"union",options,inclusive:false,...normalizeParams(params)})}function _discriminatedUnion(Class,discriminator,options,params){return new Class({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class,left,right){return new Class({type:"intersection",left,right})}function _tuple(Class,items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new Class({type:"tuple",items,rest,...normalizeParams(params)})}function _record(Class,keyType,valueType,params){return new Class({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class,keyType,valueType,params){return new Class({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class,valueType,params){return new Class({type:"set",valueType,...normalizeParams(params)})}function _enum(Class,values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new Class({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class,entries,params){return new Class({type:"enum",entries,...normalizeParams(params)})}function _literal(Class,value,params){return new Class({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function _file(Class,params){return new Class({type:"file",...normalizeParams(params)})}function _transform(Class,fn){return new Class({type:"transform",transform:fn})}function _optional(Class,innerType){return new Class({type:"optional",innerType})}function _nullable(Class,innerType){return new Class({type:"nullable",innerType})}function _default(Class,innerType,defaultValue){return new Class({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class,innerType,params){return new Class({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class,innerType){return new Class({type:"success",innerType})}function _catch(Class,innerType,catchValue){return new Class({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}function _pipe(Class,in_,out){return new Class({type:"pipe",in:in_,out})}function _readonly(Class,innerType){return new Class({type:"readonly",innerType})}function _templateLiteral(Class,parts,params){return new Class({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class,getter){return new Class({type:"lazy",getter})}function _promise(Class,innerType){return new Class({type:"promise",innerType})}function _custom(Class,fn,_params){const norm=normalizeParams(_params);norm.abort??(norm.abort=true);const schema=new Class({type:"custom",check:"custom",fn,...norm});return schema}function _refine(Class,fn,_params){const schema=new Class({type:"custom",check:"custom",fn,...normalizeParams(_params)});return schema}function _superRefine(fn,params){const ch=_check((payload)=>{payload.addIssue=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,ch._zod.def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");if(!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=ch);_issue.continue??(_issue.continue=!ch._zod.def.abort);payload.issues.push(issue(_issue))}};return fn(payload.value,payload)},params);return ch}function _check(fn,params){const ch=new $ZodCheck({check:"custom",...normalizeParams(params)});ch._zod.check=fn;return ch}function describe(description){const ch=new $ZodCheck({check:"describe"});ch._zod.onattach=[(inst)=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}];ch._zod.check=()=>{};return ch}function meta(metadata){const ch=new $ZodCheck({check:"meta"});ch._zod.onattach=[(inst)=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}];ch._zod.check=()=>{};return ch}function _stringbool(Classes,_params){const params=normalizeParams(_params);let truthyArray=params.truthy??["true","1","yes","on","y","enabled"];let falsyArray=params.falsy??["false","0","no","off","n","disabled"];if(params.case!=="sensitive"){truthyArray=truthyArray.map((v)=>typeof v==="string"?v.toLowerCase():v);falsyArray=falsyArray.map((v)=>typeof v==="string"?v.toLowerCase():v)}const truthySet=new Set(truthyArray);const falsySet=new Set(falsyArray);const _Codec=Classes.Codec??$ZodCodec;const _Boolean=Classes.Boolean??$ZodBoolean;const _String=Classes.String??$ZodString;const stringSchema=new _String({type:"string",error:params.error});const booleanSchema=new _Boolean({type:"boolean",error:params.error});const codec=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:(input,payload)=>{let data=input;if(params.case!=="sensitive")data=data.toLowerCase();if(truthySet.has(data)){return true}else if(falsySet.has(data)){return false}else{payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec,continue:false});return{}}},reverseTransform:(input,_payload)=>{if(input===true){return truthyArray[0]||"true"}else{return falsyArray[0]||"false"}},error:params.error});codec._zod.bag.truthy=truthyArray;codec._zod.bag.falsy=falsyArray;codec._zod.bag.case=params.case??"insensitive";return codec}function _stringFormat(Class,format,fnOrRegex,_params={}){const params=normalizeParams(_params);const def={check:"string_format",type:"string",format,fn:typeof fnOrRegex==="function"?fnOrRegex:(val)=>fnOrRegex.test(val),...params};if(fnOrRegex instanceof RegExp){def.pattern=fnOrRegex}const inst=new Class(def);return inst}function assignProps(target,...sources){for(const source of sources){for(const key of Reflect.ownKeys(source)){if(Object.prototype.propertyIsEnumerable.call(source,key)){assignProp(target,key,source[key])}}}return target}function initializeContext(params){let target=params?.target??"draft-2020-12";if(target==="draft-4")target="draft-04";if(target==="draft-7")target="draft-07";return{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:undefined,sharedEmitDoneFor:undefined,cycles:params?.cycles??"ref",reused:params?.reused??"inline",intersections:[],deferred:[],external:params?.external??undefined}}function handleUnrepresentable(schema,ctx,json,params,message){const result=typeof ctx.unrepresentable==="function"?ctx.unrepresentable({zodSchema:schema,path:params.path,message}):ctx.unrepresentable;if(result==="any")return false;if(result===undefined||result==="throw")throw new Error(message);Object.assign(json,result);return true}function processSchema(schema,ctx,_params={path:[],schemaPath:[]}){var _a;const def=schema._zod.def;const seen=ctx.seen.get(schema);if(seen){seen.count++;const isCycle=_params.schemaPath.includes(schema);if(isCycle){seen.cycle=_params.path}return seen.schema}const result={schema:{},count:1,cycle:undefined,path:_params.path};ctx.seen.set(schema,result);ctx.sharedDefsExtractedFor=undefined;ctx.sharedEmitDoneFor=undefined;const overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema){result.schema=overrideSchema}else{const params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema){schema._zod.processJSONSchema(ctx,result.schema,params)}else{const _json=result.schema;const processor=ctx.processors[def.type];if(!processor){throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`)}processor(schema,ctx,_json,params)}const parent=schema._zod.parent;if(parent){if(!result.ref)result.ref=parent;processSchema(parent,ctx,params);ctx.seen.get(parent).isParent=true}}const meta=ctx.metadataRegistry.get(schema);if(meta)assignProps(result.schema,meta);if(ctx.io==="input"&&isTransforming(schema)){delete result.schema.examples;delete result.schema.default}if(ctx.io==="input"&&"_prefault"in result.schema)(_a=result.schema).default??(_a.default=result.schema._prefault);delete result.schema._prefault;const _result=ctx.seen.get(schema);return _result.schema}function encodeJSONPointerSegment(segment){return segment.replace(/~/g,"~0").replace(/\//g,"~1")}function extractDefs(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");if(ctx.external&&ctx.sharedDefsExtractedFor===ctx.external)return;const idToSchema=new Map;for(const entry of ctx.seen.entries()){const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){const existing=idToSchema.get(id);if(existing&&existing!==entry[0]){throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`)}idToSchema.set(id,entry[0])}}const makeURI=(entry)=>{const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){const externalId=ctx.external.registry.get(entry[0])?.id;const uriGenerator=ctx.external.uri??((id)=>id);if(externalId){return{ref:uriGenerator(externalId)}}const id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;entry[1].defId=id;return{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}`}}const uriPrefix=`#`;const defUriPrefix=`${uriPrefix}/${defsSegment}/`;if(entry[1]===root&&!entry[1].schema.id){return{ref:uriPrefix}}const defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+encodeJSONPointerSegment(defId)}};const extractToDef=(entry)=>{if(entry[1].schema.$ref){return}const seen=entry[1];const{ref,defId}=makeURI(entry);seen.def={...seen.schema};if(defId)seen.defId=defId;const schema=seen.schema;for(const key in schema){delete schema[key]}schema.$ref=ref};if(ctx.cycles==="throw"){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.cycle){throw new Error("Cycle detected: "+`#/${seen.cycle?.join("/")}/<root>`+'\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.')}}}for(const entry of ctx.seen.entries()){const seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){const ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry)}}}if(ctx.external)ctx.sharedDefsExtractedFor=ctx.external}function compactTypeUnion(schema){const options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==undefined)return;const types=[];for(const option of options){if(!option||typeof option!=="object")return;compactTypeUnion(option);const keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;const type=option.type;for(const member of Array.isArray(type)?type:[type]){if(typeof member!=="string")return;if(!types.includes(member))types.push(member)}}delete schema.anyOf;schema.type=types.length===1?types[0]:types}var FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]);var UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){const extra=member.additionalProperties;if(extra===undefined||extra===false||typeof extra!=="object"||extra===null)return null;return Object.keys(extra).length?extra:null}function foldObjects(members){const objects=[];for(const member of members){if(typeof member!=="object"||member.type!=="object")return null;for(const key in member){if(!FOLDABLE_KEYS.has(key))return null}objects.push(member)}const properties={};const required=new Set;for(const object of objects){for(const key in object.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;const parts=[];for(const other of objects){const part=other.properties?.[key]??undeclaredConstraint(other);if(part===null||part===undefined)continue;if(!parts.some((seen)=>JSON.stringify(seen)===JSON.stringify(part)))parts.push(part)}const merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(const key of object.required??[])required.add(key)}const folded={type:"object",properties};if(required.size)folded.required=[...required];if(objects.every((object)=>object.additionalProperties===false)){folded.additionalProperties=false}else{const constraints=[];for(const object of objects){const constraint=undeclaredConstraint(object);if(constraint&&!constraints.some((seen)=>JSON.stringify(seen)===JSON.stringify(constraint)))constraints.push(constraint)}if(constraints.length===1)folded.additionalProperties=constraints[0];else if(constraints.length>1)folded.additionalProperties={allOf:constraints}}return folded}function foldIntersection(json){const allOf=json.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(const key of FOLDABLE_KEYS)if(key in json)return;const unions=allOf.filter((m)=>UNION_KEYS.some((k)=>Array.isArray(m[k])));let folded=null;if(!unions.length){folded=foldObjects(allOf)}else{const union=unions[0];const keyword=UNION_KEYS.find((k)=>Array.isArray(union[k]));if(Object.keys(union).length!==1)return;const rest=allOf.filter((m)=>m!==union);const branches=union[keyword].map((branch)=>foldObjects([...rest,branch]));if(branches.some((b)=>!b))return;folded={[keyword]:branches}}if(!folded)return;delete json.allOf;assignProps(json,folded)}function finalize(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");const flattenRef=(zodSchema)=>{const seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;const schema=seen.def??seen.schema;const _cached={...schema};const ref=seen.ref;seen.ref=null;if(ref){flattenRef(ref);const refSeen=ctx.seen.get(ref);const refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")){schema.allOf=schema.allOf??[];schema.allOf.push(refSchema)}else{assignProps(schema,refSchema)}assignProps(schema,_cached);const isParentRef=zodSchema._zod.parent===ref;if(isParentRef){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached)){delete schema[key]}}}if(refSchema.$ref&&refSeen.def){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema[key])===JSON.stringify(refSeen.def[key])){delete schema[key]}}}}const parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);const parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){schema.$ref=parentSeen.schema.$ref;if(parentSeen.def){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema[key])===JSON.stringify(parentSeen.def[key])){delete schema[key]}}}}}ctx.override({zodSchema,jsonSchema:schema,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(const entry of[...ctx.seen.entries()].reverse()){flattenRef(entry[0])}if(ctx.target!=="openapi-3.0"){for(const entry of ctx.seen.entries()){compactTypeUnion(entry[1].def??entry[1].schema)}}for(const rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){const carriers=new Map;for(const seen of ctx.seen.values()){for(const json of[seen.schema,seen.def]){const allOf=json?.allOf;if(!Array.isArray(allOf))continue;const existing=carriers.get(allOf);if(existing)existing.push(json);else carriers.set(allOf,[json])}}for(const allOf of ctx.intersections){for(const json of carriers.get(allOf)??[])foldIntersection(json)}}}const result={};if(ctx.target==="draft-2020-12"){result.$schema="https://json-schema.org/draft/2020-12/schema"}else if(ctx.target==="draft-07"){result.$schema="http://json-schema.org/draft-07/schema#"}else if(ctx.target==="draft-04"){result.$schema="http://json-schema.org/draft-04/schema#"}else if(ctx.target==="openapi-3.0"){}if(ctx.external?.uri){const id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);const rootMetaId=ctx.metadataRegistry.get(schema)?.id;if(rootMetaId!==undefined&&result.id===rootMetaId)delete result.id;const defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.def&&seen.defId){if(seen.def.id===seen.defId)delete seen.def.id;assignProp(defs,seen.defId,seen.def)}}}if(ctx.external)ctx.sharedEmitDoneFor=ctx.external;if(ctx.external){}else{if(Object.keys(defs).length>0){if(ctx.target==="draft-2020-12"){result.$defs=defs}else{result.definitions=defs}}}try{const finalized=JSON.parse(JSON.stringify(result));Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:false,writable:false});return finalized}catch(_err){throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){const ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return false;ctx.seen.add(_schema);const def=_schema._zod.def;if(def.type==="transform")return true;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch"){return isTransforming(def.innerType,ctx)}if(def.type==="intersection"){return isTransforming(def.left,ctx)||isTransforming(def.right,ctx)}if(def.type==="record"||def.type==="map"){return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx)}if(def.type==="pipe"){if(_schema._zod.traits.has("$ZodCodec"))return true;return isTransforming(def.in,ctx)||isTransforming(def.out,ctx)}if(def.type==="object"){for(const key in def.shape){if(isTransforming(def.shape[key],ctx))return true}return false}if(def.type==="union"){for(const option of def.options){if(isTransforming(option,ctx))return true}return false}if(def.type==="tuple"){for(const item of def.items){if(isTransforming(item,ctx))return true}if(def.rest&&isTransforming(def.rest,ctx))return true;return false}return false}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{const ctx=initializeContext({...params,processors});processSchema(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{const{libraryOptions,target}=params??{};const ctx=initializeContext({...libraryOptions??{},target,io,processors});processSchema(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var narrowMin=(agg,key,value)=>{if(agg[key]===undefined||value>agg[key])agg[key]=value};var narrowMax=(agg,key,value)=>{if(agg[key]===undefined||value<agg[key])agg[key]=value};var narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value);narrowMax(agg,"maximum",value)};var addDivisor=(agg,value)=>{agg.multipleOf??(agg.multipleOf=[]);if(!agg.multipleOf.includes(value))agg.multipleOf.push(value)};var addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set);agg.patterns.add(pattern)};var intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter((m)=>mime.includes(m)):[...mime]};var setFormat=(agg,format)=>{agg.format=format;if(format.includes("int"))agg.isInt=true};var minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum);var maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum);var formatContributor=(ranges)=>(agg,def)=>{setFormat(agg,def.format);const[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum);narrowMax(agg,"maximum",maximum)};var contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format);if(def.pattern)addPattern(agg,def.pattern);if(def.format==="base64"||def.format==="base64url")agg.contentEncoding=def.format;if(def.local||def.precision===-1)agg.laxFormat=true},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){const agg={};const def=schema._zod.def;const list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(const ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);const bag=schema._zod.bag;if(bag.minimum!==undefined)narrowMin(agg,"minimum",bag.minimum);if(bag.exclusiveMinimum!==undefined)narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum);if(bag.maximum!==undefined)narrowMax(agg,"maximum",bag.maximum);if(bag.exclusiveMaximum!==undefined)narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum);if(bag.multipleOf!==undefined)addDivisor(agg,bag.multipleOf);if(bag.format!==undefined){agg.format??(agg.format=bag.format);if(bag.format.includes("int"))agg.isInt=true}if(bag.mime)intersectMime(agg,bag.mime);for(const pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""};var exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]);var exactPattern=(p)=>exactPatterns.get(p)??p;var stringProcessor=(schema,ctx,_json,_params)=>{const json=_json;json.type="string";const{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){json.format=formatMap[format]??format;if(json.format==="")delete json.format;if(format==="time"||laxFormat){delete json.format}}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){const patternList=[...patterns].map(exactPattern);if(patternList.length===1)json.pattern=patternList[0].source;else if(patternList.length>1){json.allOf=[...patternList.map((regex)=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}}};var numberProcessor=(schema,ctx,_json,params)=>{const json=_json;const{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json.type=isInt?"integer":"number";const exMin=typeof exclusiveMinimum==="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY);const exMax=typeof exclusiveMaximum==="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY);const legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin){if(legacy){json.minimum=exclusiveMinimum;json.exclusiveMinimum=true}else{json.exclusiveMinimum=exclusiveMinimum}}else if(typeof minimum==="number"){json.minimum=minimum}if(exMax){if(legacy){json.maximum=exclusiveMaximum;json.exclusiveMaximum=true}else{json.exclusiveMaximum=exclusiveMaximum}}else if(typeof maximum==="number"){json.maximum=maximum}if(multipleOf){const divisors=new Set;for(const divisor of multipleOf){if(Number.isFinite(divisor)&&divisor!==0)divisors.add(Math.abs(divisor));else handleUnrepresentable(schema,ctx,json,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`)}const[first,...rest]=divisors;if(first!==undefined)json.multipleOf=first;if(rest.length)json.allOf=[...json.allOf??[],...rest.map((m)=>({multipleOf:m}))]}};var booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var bigintProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"BigInt cannot be represented in JSON Schema")};var symbolProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Symbols cannot be represented in JSON Schema")};var nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0"){json.type="string";json.nullable=true;json.enum=[null]}else{json.type="null"}};var undefinedProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Undefined cannot be represented in JSON Schema")};var voidProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Void cannot be represented in JSON Schema")};var neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}};var anyProcessor=(_schema,_ctx,_json,_params)=>{};var unknownProcessor=(_schema,_ctx,_json,_params)=>{};var dateProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Date cannot be represented in JSON Schema")};var enumProcessor=(schema,_ctx,json,_params)=>{const def=schema._zod.def;const values=getEnumValues(def.entries);if(values.length===0){json.not={};return}if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values};var literalProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;if(def.values.length===0){json.not={};return}const vals=[];for(const val of def.values){if(val===undefined){if(handleUnrepresentable(schema,ctx,json,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val==="bigint"){if(handleUnrepresentable(schema,ctx,json,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else{vals.push(val)}}if(vals.length===0){}else if(vals.length===1){const val=vals[0];json.type=val===null?"null":typeof val;if(ctx.target==="draft-04"||ctx.target==="openapi-3.0"){json.enum=[val]}else{json.const=val}}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}};var nanProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"NaN cannot be represented in JSON Schema")};var templateLiteralProcessor=(schema,_ctx,json,_params)=>{const _json=json;const pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string";_json.pattern=pattern.source};var fileProcessor=(schema,_ctx,json,_params)=>{const _json=json;_json.type="string";_json.format="binary";_json.contentEncoding="binary";const{minimum,maximum,mime}=aggregateChecks(schema);if(minimum!==undefined)_json.minLength=minimum;if(maximum!==undefined)_json.maxLength=maximum;if(!mime)return;if(mime.length===0)_json.not={};else if(mime.length===1)_json.contentMediaType=mime[0];else _json.anyOf=mime.map((m)=>({contentMediaType:m}))};var successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var customProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Custom types cannot be represented in JSON Schema")};var functionProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Function types cannot be represented in JSON Schema")};var transformProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Transforms cannot be represented in JSON Schema")};var mapProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Map cannot be represented in JSON Schema")};var setProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Set cannot be represented in JSON Schema")};var arrayProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;const{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array";json.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};function inputOptin(schema){const def=schema._zod.def;if(def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")){return inputOptin(def.out)}if(def.type==="catch"){return inputOptin(def.innerType)}return schema._zod.optin}var objectProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;const shape=def.shape;const symbolKeys=Object.getOwnPropertySymbols(shape);if(symbolKeys.length&&handleUnrepresentable(schema,ctx,json,params,"Symbol keys cannot be represented in JSON Schema")){return}json.type="object";json.properties={};for(const key in shape){assignProp(json.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}))}const requiredKeys=[];for(const key of Object.keys(shape)){const field=def.shape[key];if(ctx.io==="input"?inputOptin(field)===undefined:field._zod.optout===undefined){requiredKeys.push(key)}}if(requiredKeys.length>0){json.required=requiredKeys}if(def.catchall?._zod.def.type==="never"){json.additionalProperties=false}else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=false}else if(def.catchall){json.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})}};var unionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const isExclusive=def.inclusive===false;const options=def.options.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive){json.oneOf=options}else{json.anyOf=options}};var intersectionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]});const b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]});const isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1;const allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf;ctx.intersections.push(allOf)};var tupleProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="array";const prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items";const restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems";const prefixItems=def.items.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,prefixPath,i]}));const rest=def.rest?processSchema(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;let minItems=def.items.length;while(minItems>0){const item=def.items[minItems-1];const optional=ctx.io==="input"?inputOptin(item)!==undefined:item._zod.optout==="optional";if(!optional)break;minItems--}const maxItems=def.items.length;const isClosed=!def.rest;if(ctx.target==="draft-2020-12"){json.prefixItems=prefixItems;if(isClosed){json.items=false}else if(rest){json.items=rest}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else if(ctx.target==="openapi-3.0"){json.items={anyOf:prefixItems};if(rest){json.items.anyOf.push(rest)}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else{json.items=prefixItems;if(isClosed){json.additionalItems=false}else if(rest){json.additionalItems=rest}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}const{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum};function stringifyKeyNames(bySchema,json,visited){if(json.$ref){if(visited.has(json))return json;visited.add(json);const def=bySchema.get(json)?.def;if(!def)return json;const inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json:inlined}for(const keyword of["anyOf","oneOf"]){const branches=json[keyword];if(!Array.isArray(branches))continue;const mapped=branches.map((branch)=>stringifyKeyNames(bySchema,branch,visited));if(mapped.some((branch,i)=>branch!==branches[i]))json={...json,[keyword]:mapped}}const types=Array.isArray(json.type)?json.type:[json.type];const numericType=!types.includes("string")&&types.some((t)=>t==="number"||t==="integer");const values=json.enum??(json.const!==undefined?[json.const]:undefined);if(!numericType&&!values?.some((v)=>typeof v==="number"))return json;const{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json;if(rest.enum)rest.enum=rest.enum.map((v)=>typeof v==="number"?String(v):v);else if(typeof rest.const==="number")rest.const=String(rest.const);if(!numericType)return rest;rest.type="string";if(!values)rest.pattern=(types.includes("number")?number:integer).source;return rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){const bySchema=new Map;for(const entry of ctx.seen.values()){if(entry.def&&!bySchema.has(entry.schema))bySchema.set(entry.schema,entry)}const rewrites=new Map;for(const record of pendingRecords.get(ctx)??[]){const seen=ctx.seen.get(record);const names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===true||rewrites.has(names))continue;const rewritten=stringifyKeyNames(bySchema,names,new Set);if(rewritten!==names)rewrites.set(names,rewritten)}if(!rewrites.size)return;for(const entry of ctx.seen.values()){for(const carrier of[entry.schema,entry.def]){const rewritten=carrier&&rewrites.get(carrier.propertyNames);if(rewritten)carrier.propertyNames=rewritten}}}var recordProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="object";const keyType=def.keyType;const patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){const valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(const pattern of patterns){assignProp(json.patternProperties,exactPattern(pattern).source,valueSchema)}}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending=pendingRecords.get(ctx);if(!pending){pending=[];pendingRecords.set(ctx,pending);ctx.deferred.push(()=>rewriteKeyNames(ctx))}pending.push(schema)}json.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}const keyValues=keyType._zod.values;const omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==undefined;if(keyValues&&!def.partial&&!omittableOnInput){const validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0){json.required=validKeyValues.map(String)}}};var nullableProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const inner=processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0"){seen.ref=def.innerType;json.nullable=true}else{json.anyOf=[inner,{type:"null"}]}};var nonoptionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value,schema,ctx,json,params){let unrepresentable=false;const serialized=JSON.stringify(value,(_,val)=>{if(typeof val!=="bigint")return val;unrepresentable=true;return null});if(!unrepresentable)return JSON.parse(serialized);handleUnrepresentable(schema,ctx,json,params,"BigInt defaults cannot be represented in JSON Schema");return UNREPRESENTABLE_DEFAULT}var defaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;const value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json.default=value};var prefaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;if(ctx.io!=="input")return;const value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json._prefault=value};var catchProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(undefined)}catch{handleUnrepresentable(schema,ctx,json,params,"Dynamic catch values are not supported in JSON Schema");return}json.default=catchValue};var pipeProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;const inIsTransform=def.in._zod.traits.has("$ZodTransform");const innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};var readonlyProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json.readOnly=true};var promiseProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var optionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var lazyProcessor=(schema,ctx,_json,params)=>{const innerType=schema._zod.innerType;processSchema(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};var allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(input,params){if("_idmap"in input){const registry=input;const ctx=initializeContext({...params,processors:allProcessors});const defs={};for(const entry of registry._idmap.entries()){const[_,schema]=entry;processSchema(schema,ctx)}const schemas={};const external={registry,uri:params?.uri,defs};ctx.external=external;for(const entry of registry._idmap.entries()){const[key,schema]=entry;extractDefs(ctx,schema);assignProp(schemas,key,finalize(ctx,schema))}if(Object.keys(defs).length>0){const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}const ctx=initializeContext({...params,processors:allProcessors});processSchema(input,ctx);extractDefs(ctx,input);return finalize(ctx,input)}class JSONSchemaGenerator{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return processSchema(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}this.ctx.sharedDefsExtractedFor=undefined;this.ctx.sharedEmitDoneFor=undefined;extractDefs(this.ctx,schema);const result=finalize(this.ctx,schema);const{"~standard":_,...plainResult}=result;return plainResult}}var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:true,enumerable:false,get(){const value=make(this);Object.defineProperty(this,key,{value,configurable:true,writable:true});return value},set(value){Object.defineProperty(this,key,{value,configurable:true,writable:true})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues);inst.name="ZodError";const proto=Object.getPrototypeOf(inst);if(_installedErrorProtos.has(proto))return;_installedErrorProtos.add(proto);_lazyMethod(proto,"format",(self)=>(mapper)=>formatError(self,mapper));_lazyMethod(proto,"flatten",(self)=>(mapper)=>flattenError(self,mapper));_lazyMethod(proto,"addIssue",(self)=>(issue)=>{self.issues.push(issue);self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)});_lazyMethod(proto,"addIssues",(self)=>(issues)=>{self.issues.push(...issues);self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)});Object.defineProperty(proto,"isEmpty",{configurable:true,enumerable:false,get(){return this.issues.length===0}})};var ZodError=$constructor("ZodError",initializer2);var ZodRealError=$constructor("ZodError",initializer2,undefined,{Parent:Error});var parse3=_parse(ZodRealError);var parseAsync2=_parseAsync(ZodRealError);var safeParse2=_safeParse(ZodRealError);var safeParseAsync2=_safeParseAsync(ZodRealError);var encode2=_encode(ZodRealError);var decode2=_decode(ZodRealError);var encodeAsync2=_encodeAsync(ZodRealError);var decodeAsync2=_decodeAsync(ZodRealError);var safeEncode2=_safeEncode(ZodRealError);var safeDecode2=_safeDecode(ZodRealError);var safeEncodeAsync2=_safeEncodeAsync(ZodRealError);var safeDecodeAsync2=_safeDecodeAsync(ZodRealError);function _ensureDefaultLocale(){if(!globalConfig.localeError)config(en_default())}function _ensureDefaultMemoizer(){if(!globalConfig.memoizer)config({memoizer:memoizer()})}var ZodType=$constructor("ZodType",(inst,def)=>{_ensureDefaultLocale();$ZodType.init(inst,def);inst.def=def;inst.type=def.type;return inst},{check(...chks){const def=this.def;return this.clone(mergeDefs(def,{checks:[...def.checks??[],...chks.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:true})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta){reg.add(this,meta);return this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){const cl=this.clone();globalRegistry.add(cl,{description});return cl},meta(...args){if(args.length===0)return globalRegistry.get(this);const cl=this.clone();globalRegistry.add(cl,args[0]);return cl},isOptional(){return this.safeParse(undefined).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get "~standard"(){return hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set "~standard"(value){own(this,"~standard",value)},parse:function _parse(data,params){return parse3(this,data,params,{callee:_parse})},parseAsync:async function _parseAsync(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value){own(this,"spa",value)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode(data,params){return encode2(this,data,params,{callee:_encode})},decode:function _decode(data,params){return decode2(this,data,params,{callee:_decode})},encodeAsync:async function _encodeAsync(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}});var _ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params)},derived({format:(inst)=>aggregateChecks(inst).format??null,minLength:(inst)=>aggregateChecks(inst).minimum??null,maxLength:(inst)=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}}));var ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def);_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def);_ZodString.init(inst,def)});var ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def);ZodStringFormat.init(inst,def)});var ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def);ZodStringFormat.init(inst,def)});function email2(params){return _email(ZodEmail,params)}var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def);ZodStringFormat.init(inst,def)});function guid2(params){return _guid(ZodGUID,params)}var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def);ZodStringFormat.init(inst,def)});function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def);ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:httpProtocol,hostname:domain,...normalizeParams(params)})}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def);ZodStringFormat.init(inst,def)});function emoji2(params){return _emoji2(ZodEmoji,params)}var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def);ZodStringFormat.init(inst,def)});function nanoid2(params){return _nanoid(ZodNanoID,params)}var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def);ZodStringFormat.init(inst,def)});function cuid3(params){return _cuid(ZodCUID,params)}var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def);ZodStringFormat.init(inst,def)});function cuid22(params){return _cuid2(ZodCUID2,params)}var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def);ZodStringFormat.init(inst,def)});function ulid2(params){return _ulid(ZodULID,params)}var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def);ZodStringFormat.init(inst,def)});function xid2(params){return _xid(ZodXID,params)}var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def);ZodStringFormat.init(inst,def)});function ksuid2(params){return _ksuid(ZodKSUID,params)}var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def);ZodStringFormat.init(inst,def)});function ipv42(params){return _ipv4(ZodIPv4,params)}var ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def);ZodStringFormat.init(inst,def)});function mac2(params){return _mac(ZodMAC,params)}var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def);ZodStringFormat.init(inst,def)});function ipv62(params){return _ipv6(ZodIPv6,params)}var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def);ZodStringFormat.init(inst,def)});function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def);ZodStringFormat.init(inst,def)});function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def);ZodStringFormat.init(inst,def)});function base642(params){return _base64(ZodBase64,params)}var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def);ZodStringFormat.init(inst,def)});function base64url2(params){return _base64url(ZodBase64URL,params)}var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def);ZodStringFormat.init(inst,def)});function e1642(params){return _e164(ZodE164,params)}var ZodCreditCard=$constructor("ZodCreditCard",(inst,def)=>{$ZodCreditCard.init(inst,def);ZodStringFormat.init(inst,def)});function creditCard2(params){return _creditCard(ZodCreditCard,params)}var ZodIBAN=$constructor("ZodIBAN",(inst,def)=>{$ZodIBAN.init(inst,def);ZodStringFormat.init(inst,def)});function iban2(params){return _iban(ZodIBAN,params)}var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def);ZodStringFormat.init(inst,def)});function jwt(params){return _jwt(ZodJWT,params)}var ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def);ZodStringFormat.init(inst,def)});function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",hex,_params)}function currencyCode2(_params){return _stringFormat(ZodCustomStringFormat,"currency_code",currencyCode,_params)}function hash(alg,params){const enc=params?.enc??"hex";const format=`${alg}_${enc}`;const regex=exports_regexes[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params);inst.isFinite=true},derived({minValue:(inst)=>{const{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:(inst)=>{const{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:(inst)=>{const{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:(inst)=>aggregateChecks(inst).format??null},{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}}));function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def);ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params)},derived({minValue:(inst)=>aggregateChecks(inst).minimum??null,maxValue:(inst)=>aggregateChecks(inst).maximum??null,format:(inst)=>aggregateChecks(inst).format??null},{gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},gt(value,params){return this.check(_gt(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},positive(params){return this.check(_gt(BigInt(0),params))},negative(params){return this.check(_lt(BigInt(0),params))},nonpositive(params){return this.check(_lte(BigInt(0),params))},nonnegative(params){return this.check(_gte(BigInt(0),params))},multipleOf(value,params){return this.check(_multipleOf(value,params))}}));function bigint2(params){return _bigint(ZodBigInt,params)}var ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def);ZodBigInt.init(inst,def)});function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}var ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});function symbol(params){return _symbol(ZodSymbol,params)}var ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});function _undefined3(params){return _undefined2(ZodUndefined,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});function _null3(params){return _null2(ZodNull,params)}var ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});function any(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});function never(params){return _never(ZodNever,params)}var ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});function _void2(params){return _void(ZodVoid,params)}var ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params);inst.min=(value,params)=>inst.check(_gte(value,params));inst.max=(value,params)=>inst.check(_lte(value,params))},derived({minDate:(inst)=>{const{minimum}=aggregateChecks(inst);return minimum?new Date(minimum):null},maxDate:(inst)=>{const{maximum}=aggregateChecks(inst);return maximum?new Date(maximum):null}},{}));function date2(params){return _date(ZodDate,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer();$ZodArray.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params);inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){const shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer();$ZodObjectJIT.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params);installLazyProp(inst,"shape",(self)=>self._zod.def.shape,false)},{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(mergeDefs(this._zod.def,{catchall:undefined}))},extend(incoming){return extend(this,incoming)},safeExtend(incoming){return safeExtend(this,incoming)},merge(other){return merge(this,other)},pick(mask){return pick(this,mask)},omit(mask){return omit(this,mask)},partial(...args){return partial(ZodOptional,this,args[0])},exactPartial(...args){return partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return required(ZodNonOptional,this,args[0])}});function object(shape,params){const def={type:"object",shape:shape??{},...normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...normalizeParams(params)})}var ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def);$ZodXor.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});function xor(options,params){return new ZodXor({type:"union",options,inclusive:false,...normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def);$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodTuple=$constructor("ZodTuple",(inst,def)=>{_ensureDefaultMemoizer();$ZodTuple.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params)},{rest(rest){return this.clone({...this._zod.def,rest})},partial(){const def=this._zod.def;if(def.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...def,items:def.items.map((item)=>new ZodOptional({type:"optional",innerType:item}))})}});function tuple(items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...normalizeParams(params)})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer();$ZodRecord.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType});function record(keyType,valueType,params){if(!valueType||!valueType._zod){return new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...normalizeParams(valueType)})}return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params)})}function partialRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params),partial:true})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...normalizeParams(params)})}var ZodMap=$constructor("ZodMap",(inst,def)=>{_ensureDefaultMemoizer();$ZodMap.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType;inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=(params)=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...normalizeParams(params)})}var ZodSet=$constructor("ZodSet",(inst,def)=>{_ensureDefaultMemoizer();$ZodSet.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params);inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=(params)=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});function set(valueType,params){return new ZodSet({type:"set",valueType,...normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params);inst.enum=def.entries;inst.options=[...inst._zod.values];const keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{const newEntries={};for(const value of values){if(keys.has(value)){newEntries[value]=def.entries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})};inst.exclude=(values,params)=>{const newEntries={...def.entries};for(const value of values){if(keys.has(value)){delete newEntries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})}});function _enum2(values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params);inst.values=new Set(def.values);Object.defineProperty(inst,"value",{get(){if(def.values.length>1){throw new Error("This schema contains multiple valid literal values. Use `.values` instead.")}return def.values[0]}})});function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}var ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params);inst.min=(size,params)=>inst.check(_minSize(size,params));inst.max=(size,params)=>inst.check(_maxSize(size,params));inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});function file(params){return _file(ZodFile,params)}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer();$ZodTransform.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params);inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward"){throw new $ZodEncodeError(inst.constructor.name)}payload.addIssue=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");if(!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=inst);payload.issues.push(issue(_issue))}};const output=def.transform(payload.value,payload);if(output instanceof Promise){return output.then((output)=>{payload.value=output;return payload})}payload.value=output;return payload}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeDefault=inst.unwrap});function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...normalizeParams(params)})}var ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function success(innerType){return new ZodSuccess({type:"success",innerType})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeCatch=inst.unwrap});function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}var ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});function nan(params){return _nan(ZodNaN,params)}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params);inst.in=def.in;inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def);$ZodCodec.init(inst,def)});function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){const def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def);$ZodPreprocess.init(inst,def)});var ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...normalizeParams(params)})}var ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.getter()});function lazy(getter){return new ZodLazy({type:"lazy",getter})}var ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function promise(innerType){return new ZodPromise({type:"promise",innerType})}var ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});function check(fn){const ch=new $ZodCheck({check:"custom"});ch._zod.check=fn;return ch}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>true),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}var describe2=describe;var meta2=meta;var ZodInstanceOf=$constructor("ZodInstanceOf",(inst,def)=>{ZodCustom.init(inst,def)},{properties(shape,params){return this.check(_properties(shape,params))}});function _instanceof(cls,params={}){const inst=new ZodInstanceOf({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:true,...normalizeParams(params)});inst._zod.bag.Class=cls;inst._zod.check=(payload)=>{if(!(payload.value instanceof cls)){payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})}};return inst}var stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args);function json(params){const jsonSchema=lazy(()=>{return union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function setErrorMap(map){config({customError:map})}function getErrorMap(){return config().customError}var ZodFirstPartyTypeKind;(function(ZodFirstPartyTypeKind){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date3(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var z={...exports_schemas2,...exports_checks2,iso:exports_iso};var RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function detectVersion(schema,defaultTarget){const $schema=schema.$schema;if($schema==="https://json-schema.org/draft/2020-12/schema"){return"draft-2020-12"}if($schema==="http://json-schema.org/draft-07/schema#"){return"draft-7"}if($schema==="http://json-schema.org/draft-04/schema#"){return"draft-4"}return defaultTarget??"draft-2020-12"}function applyMinItems(items,minItems){return items.map((item,index)=>index<minItems?item:item.optional())}function decodeJSONPointerSegment(segment){return segment.replace(/~1/g,"/").replace(/~0/g,"~")}function resolveRef(ref,ctx){if(!ref.startsWith("#")){throw new Error("External $ref is not supported, only local refs (#/...) are allowed")}const path=ref.slice(1).split("/").filter(Boolean);if(path.length===0){return ctx.rootSchema}const defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path[0]===defsKey){const key=path[1]===undefined?undefined:decodeJSONPointerSegment(path[1]);if(!key||!ctx.defs[key]){throw new Error(`Reference not found: ${ref}`)}return ctx.defs[key]}throw new Error(`Reference not found: ${ref}`)}function checkObjectGuards(objectSchema,guards){const guard=z.transform((value)=>value).check((payload)=>{const value=payload.value;if(typeof value!=="object"||value===null||Array.isArray(value))return;const keys=Object.getOwnPropertyNames(value);if(guards.minProperties!==undefined&&keys.length<guards.minProperties){payload.issues.push({origin:"object",code:"too_small",minimum:guards.minProperties,inclusive:true,message:`Too small: expected object to have >=${guards.minProperties} properties`,input:value,inst:objectSchema,continue:true})}if(guards.maxProperties!==undefined&&keys.length>guards.maxProperties){payload.issues.push({origin:"object",code:"too_big",maximum:guards.maxProperties,inclusive:true,message:`Too big: expected object to have <=${guards.maxProperties} properties`,input:value,inst:objectSchema,continue:true})}if(guards.keySchema){for(const key of keys){const result=guards.keySchema.safeParse(key);if(result.success)continue;payload.issues.push({code:"invalid_key",origin:"record",issues:result.error.issues,input:key,path:[key],continue:true})}}});return guard.pipe(objectSchema)}function canonicalKey(value,seen){if(value===null)return"z";const type=typeof value;if(type!=="object"){if(type==="number"&&Number.isNaN(value))return null;const raw=String(value);return`${type[0]}${raw.length}:${raw}`}if(seen.has(value))return null;seen.add(value);try{if(Array.isArray(value)){const parts=[];for(const item of value){const key=canonicalKey(item,seen);if(key===null)return null;parts.push(key)}return`a${parts.length}:[${parts.join(",")}]`}const keys=Object.keys(value).sort();const parts=[];for(const k of keys){const key=canonicalKey(value[k],seen);if(key===null)return null;parts.push(`${k.length}:${k}=${key}`)}return`o${parts.length}:{${parts.join(",")}}`}finally{seen.delete(value)}}var SCHEMA_KEYWORDS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]);var SCHEMA_MAP_KEYWORDS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function containsRef(value){if(typeof value!=="object"||value===null)return false;if(Array.isArray(value))return value.some(containsRef);if(typeof value.$ref==="string")return true;return Object.entries(value).some(([key,sub])=>{if(SCHEMA_KEYWORDS.has(key))return containsRef(sub);if(!SCHEMA_MAP_KEYWORDS.has(key)||typeof sub!=="object"||sub===null)return false;return Object.values(sub).some(containsRef)})}function plural(n){return n===1?"element":"elements"}function checkArrayGuards(arraySchema,guards){const guard=z.transform((value)=>value).check((payload)=>{const items=payload.value;if(!Array.isArray(items))return;if(guards.uniqueItems===true){const firstSeen=new Map;for(let i=0;i<items.length;i++){const key=canonicalKey(items[i],new Set);if(key===null)continue;const first=firstSeen.get(key);if(first===undefined){firstSeen.set(key,i);continue}payload.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${first}`,input:items,path:[i],continue:true})}}if(guards.containsSchema){const minContains=guards.minContains??1;const ceiling=guards.maxContains!==undefined?guards.maxContains+1:Number.POSITIVE_INFINITY;let matches=0;for(const item of items){if(guards.containsSchema.safeParse(item).success&&++matches>=ceiling)break}if(matches<minContains){payload.issues.push({code:"custom",message:`Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,input:items,continue:true})}if(guards.maxContains!==undefined&&matches>guards.maxContains){payload.issues.push({code:"custom",message:`Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,input:items,continue:true})}}});return guard.pipe(arraySchema)}function getTupleRest(restSchema,ctx){if(restSchema===false){return}if(restSchema===undefined||restSchema===true){return z.any()}return convertSchema(restSchema,ctx)}var fullTime=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function convertBaseSchema(schema,ctx){if(schema.not!==undefined){if(typeof schema.not==="object"&&Object.keys(schema.not).length===0){return z.never()}throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==undefined){throw new Error("unevaluatedItems is not supported")}if(schema.unevaluatedProperties!==undefined){throw new Error("unevaluatedProperties is not supported")}if(schema.if!==undefined||schema.then!==undefined||schema.else!==undefined){throw new Error("Conditional schemas (if/then/else) are not supported")}if(schema.dependentSchemas!==undefined||schema.dependentRequired!==undefined){throw new Error("dependentSchemas and dependentRequired are not supported")}if(schema.$ref){const refPath=schema.$ref;if(ctx.refs.has(refPath)){return ctx.refs.get(refPath)}if(ctx.processing.has(refPath)){return z.lazy(()=>{if(!ctx.refs.has(refPath)){throw new Error(`Circular reference not resolved: ${refPath}`)}return ctx.refs.get(refPath)})}ctx.processing.add(refPath);const resolved=resolveRef(refPath,ctx);const zodSchema=convertSchema(resolved,ctx);ctx.refs.set(refPath,zodSchema);ctx.processing.delete(refPath);return zodSchema}if(schema.enum!==undefined){const enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===true&&enumValues.length===1&&enumValues[0]===null){return z.null()}if(enumValues.length===0){return z.never()}if(enumValues.length===1){return z.literal(enumValues[0])}if(enumValues.every((v)=>typeof v==="string")){return z.enum(enumValues)}const literalSchemas=enumValues.map((v)=>z.literal(v));if(literalSchemas.length<2){return literalSchemas[0]}return z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==undefined){return z.literal(schema.const)}const type=schema.type;if(Array.isArray(type)){const typeSchemas=type.map((t)=>{const typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});if(typeSchemas.length===0){return z.never()}if(typeSchemas.length===1){return typeSchemas[0]}return z.union(typeSchemas)}if(!type){return z.any()}let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){const format=schema.format;if(format==="email"){stringSchema=stringSchema.check(z.email())}else if(format==="uri"||format==="uri-reference"){stringSchema=stringSchema.check(z.url())}else if(format==="uuid"||format==="guid"){stringSchema=stringSchema.check(z.uuid())}else if(format==="date-time"){stringSchema=stringSchema.check(z.iso.datetime({offset:true}))}else if(format==="date"){stringSchema=stringSchema.check(z.iso.date())}else if(format==="time"){stringSchema=stringSchema.check(z.regex(fullTime))}else if(format==="duration"){stringSchema=stringSchema.check(z.iso.duration())}else if(format==="hostname"){stringSchema=stringSchema.check(z.hostname())}else if(format==="ipv4"){stringSchema=stringSchema.check(z.ipv4())}else if(format==="ipv6"){stringSchema=stringSchema.check(z.ipv6())}else if(format==="mac"){stringSchema=stringSchema.check(z.mac())}else if(format==="cidr"){stringSchema=stringSchema.check(z.cidrv4())}else if(format==="cidr-v6"){stringSchema=stringSchema.check(z.cidrv6())}else if(format==="base64"){stringSchema=stringSchema.check(z.base64())}else if(format==="base64url"){stringSchema=stringSchema.check(z.base64url())}else if(format==="e164"){stringSchema=stringSchema.check(z.e164())}else if(format==="credit_card"){stringSchema=stringSchema.check(z.creditCard())}else if(format==="iban"){stringSchema=stringSchema.check(z.iban())}else if(format==="jwt"){stringSchema=stringSchema.check(z.jwt())}else if(format==="emoji"){stringSchema=stringSchema.check(z.emoji())}else if(format==="nanoid"){stringSchema=stringSchema.check(z.nanoid())}else if(format==="cuid"){stringSchema=stringSchema.check(z.cuid())}else if(format==="cuid2"){stringSchema=stringSchema.check(z.cuid2())}else if(format==="ulid"){stringSchema=stringSchema.check(z.ulid())}else if(format==="xid"){stringSchema=stringSchema.check(z.xid())}else if(format==="ksuid"){stringSchema=stringSchema.check(z.ksuid())}}if(typeof schema.minLength==="number"){stringSchema=stringSchema.min(schema.minLength)}if(typeof schema.maxLength==="number"){stringSchema=stringSchema.max(schema.maxLength)}if(schema.pattern){stringSchema=stringSchema.regex(new RegExp(schema.pattern))}zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();if(typeof schema.minimum==="number"&&schema.exclusiveMinimum!==true){numberSchema=numberSchema.min(schema.minimum)}if(typeof schema.maximum==="number"&&schema.exclusiveMaximum!==true){numberSchema=numberSchema.max(schema.maximum)}if(typeof schema.exclusiveMinimum==="number"){numberSchema=numberSchema.gt(schema.exclusiveMinimum)}else if(schema.exclusiveMinimum===true&&typeof schema.minimum==="number"){numberSchema=numberSchema.gt(schema.minimum)}if(typeof schema.exclusiveMaximum==="number"){numberSchema=numberSchema.lt(schema.exclusiveMaximum)}else if(schema.exclusiveMaximum===true&&typeof schema.maximum==="number"){numberSchema=numberSchema.lt(schema.maximum)}if(typeof schema.multipleOf==="number"){numberSchema=numberSchema.multipleOf(schema.multipleOf)}zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{const shape={};const properties=schema.properties||{};const requiredSet=new Set(schema.required||[]);const additionalSchema=typeof schema.additionalProperties==="object"?convertSchema(schema.additionalProperties,ctx):undefined;for(const[key,propSchema]of Object.entries(properties)){const propZodSchema=convertSchema(propSchema,ctx);assignProp(shape,key,requiredSet.has(key)?propZodSchema:propZodSchema.optional())}if(schema.patternProperties){const patternProps=schema.patternProperties;const patternKeys=Object.keys(patternProps);const looseRecords=[];for(const pattern of patternKeys){const patternValue=convertSchema(patternProps[pattern],ctx);const keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}const schemasToIntersect=[];if(Object.keys(shape).length>0){schemasToIntersect.push(z.object(shape).passthrough())}schemasToIntersect.push(...looseRecords);if(schemasToIntersect.length===0){zodSchema=z.object({}).passthrough()}else if(schemasToIntersect.length===1){zodSchema=schemasToIntersect[0]}else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++){result=z.intersection(result,schemasToIntersect[i])}zodSchema=result}if(schema.additionalProperties===false){const propertyKeys=Object.keys(shape);const patterns=patternKeys.map((p)=>new RegExp(p));const basePatternSchema=zodSchema;zodSchema=zodSchema.check((payload)=>{if(!isPlainObject(payload.value))return;const unrecognized=[];for(const key of Object.keys(payload.value)){if(propertyKeys.includes(key))continue;if(patterns.some((regex)=>regex.test(key)))continue;unrecognized.push(key)}if(unrecognized.length){payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input:payload.value,inst:basePatternSchema})}})}}else{const objectSchema=z.object(shape);if(schema.additionalProperties===false){zodSchema=objectSchema.strict()}else if(additionalSchema){zodSchema=objectSchema.catchall(additionalSchema)}else{zodSchema=objectSchema.passthrough()}}const hasKeyGuard=schema.propertyNames!==undefined&&schema.propertyNames!==true;const minProperties=typeof schema.minProperties==="number"?schema.minProperties:undefined;const maxProperties=typeof schema.maxProperties==="number"?schema.maxProperties:undefined;if(hasKeyGuard||minProperties!==undefined||maxProperties!==undefined){let keySchema;if(hasKeyGuard){const keyJSONSchema=typeof schema.propertyNames==="object"&&schema.propertyNames.type===undefined?{type:"string",...schema.propertyNames}:schema.propertyNames;keySchema=convertSchema(keyJSONSchema,ctx)}zodSchema=checkObjectGuards(zodSchema,{keySchema,minProperties,maxProperties})}break}case"array":{const prefixItems=schema.prefixItems;const items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){const minItems=typeof schema.minItems==="number"?schema.minItems:0;const tupleItems=prefixItems.map((item)=>convertSchema(item,ctx));const positionalItems=applyMinItems(tupleItems,minItems);const rest=!Array.isArray(items)?getTupleRest(items,ctx):undefined;const tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema;if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(Array.isArray(items)){const minItems=typeof schema.minItems==="number"?schema.minItems:0;const tupleItems=items.map((item)=>convertSchema(item,ctx));const positionalItems=applyMinItems(tupleItems,minItems);const rest=getTupleRest(schema.additionalItems,ctx);const tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema;if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(items!==undefined){const element=convertSchema(items,ctx);let arraySchema=z.array(element);if(typeof schema.minItems==="number"){arraySchema=arraySchema.min(schema.minItems)}if(typeof schema.maxItems==="number"){arraySchema=arraySchema.max(schema.maxItems)}zodSchema=arraySchema}else{zodSchema=z.array(z.any())}if(schema.uniqueItems===true||schema.contains!==undefined){zodSchema=checkArrayGuards(zodSchema,{uniqueItems:schema.uniqueItems===true,containsSchema:schema.contains!==undefined?convertSchema(schema.contains,ctx):undefined,minContains:typeof schema.minContains==="number"?schema.minContains:undefined,maxContains:typeof schema.maxContains==="number"?schema.maxContains:undefined})}break}default:throw new Error(`Unsupported type: ${type}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema==="boolean"){return schema?z.any():z.never()}let baseSchema=convertBaseSchema(schema,ctx);const hasExplicitType=schema.type||schema.enum!==undefined||schema.const!==undefined;if(schema.anyOf&&Array.isArray(schema.anyOf)){const options=schema.anyOf.map((s)=>convertSchema(s,ctx));const anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){const options=schema.oneOf.map((s)=>convertSchema(s,ctx));const oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf)){if(schema.allOf.length===0){baseSchema=hasExplicitType?baseSchema:z.any()}else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx);const startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++){result=z.intersection(result,convertSchema(schema.allOf[i],ctx))}baseSchema=result}}if(schema.nullable===true&&ctx.version==="openapi-3.0"){baseSchema=z.nullable(baseSchema)}if(schema.readOnly===true){baseSchema=z.readonly(baseSchema)}if(schema.default!==undefined){baseSchema=baseSchema.default(schema.default)}const extraMeta={};const coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const key of coreMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}const contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(const key of contentMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}if(schema.type==="object"&&schema.$ref===undefined){if(schema.propertyNames!==undefined&&!containsRef(schema.propertyNames)){extraMeta.propertyNames=schema.propertyNames}for(const key of["minProperties","maxProperties"]){if(schema[key]!==undefined)extraMeta[key]=schema[key]}}if(schema.type==="array"&&schema.$ref===undefined){if(schema.contains!==undefined&&!containsRef(schema.contains)){extraMeta.contains=schema.contains}for(const key of["uniqueItems","minContains","maxContains"]){if(schema[key]!==undefined)extraMeta[key]=schema[key]}}for(const key of Object.keys(schema)){if(!RECOGNIZED_KEYS.has(key)){assignProp(extraMeta,key,schema[key])}}if(Object.keys(extraMeta).length>0){ctx.registry.add(baseSchema,extraMeta)}if(schema.description){baseSchema=baseSchema.describe(schema.description)}return baseSchema}function fromJSONSchema(schema,params){if(typeof schema==="boolean"){return schema?z.any():z.never()}let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}const version=detectVersion(normalized,params?.defaultTarget);const defs=normalized.$defs||normalized.definitions||{};const ctx={version,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var RESOLVING=Symbol("z.visit/resolving");function visit(schema,fnOrHandlers){const fn=typeof fnOrHandlers==="function"?fnOrHandlers:(node,rewritten)=>{const h=fnOrHandlers[node._zod.def.type];return h?h(node,rewritten):node};const cache=new Map;function run(s){const cached=cache.get(s);if(cached===RESOLVING){return new $ZodLazy({type:"lazy",getter:()=>cache.get(s)})}if(cached!==undefined)return cached;cache.set(s,RESOLVING);const inner=mapInner(s);const mapped=fn(inner,inner!==s);cache.set(s,mapped);return mapped}function mapInner(s){const def=s._zod.def;const kind=def.type;switch(kind){case"object":{const oldShape=def.shape;const keys=Object.keys(oldShape);let changed=false;const newShape={};for(const k of keys){const mapped=run(oldShape[k]);if(mapped!==oldShape[k])changed=true;newShape[k]=mapped}let newCatchall=def.catchall;if(def.catchall){newCatchall=run(def.catchall);if(newCatchall!==def.catchall)changed=true}return changed?clone(s,{...def,shape:newShape,catchall:newCatchall}):s}case"array":{const mapped=run(def.element);return mapped===def.element?s:clone(s,{...def,element:mapped})}case"tuple":{const oldItems=def.items;let changed=false;const newItems=[];for(const item of oldItems){const mapped=run(item);if(mapped!==item)changed=true;newItems.push(mapped)}let newRest=def.rest;if(def.rest){newRest=run(def.rest);if(newRest!==def.rest)changed=true}return changed?clone(s,{...def,items:newItems,rest:newRest}):s}case"record":case"map":{const newKey=run(def.keyType);const newVal=run(def.valueType);return newKey===def.keyType&&newVal===def.valueType?s:clone(s,{...def,keyType:newKey,valueType:newVal})}case"set":{const newVal=run(def.valueType);return newVal===def.valueType?s:clone(s,{...def,valueType:newVal})}case"union":{const oldOptions=def.options;let changed=false;const newOptions=[];for(const opt of oldOptions){const mapped=run(opt);if(mapped!==opt)changed=true;newOptions.push(mapped)}return changed?clone(s,{...def,options:newOptions}):s}case"intersection":{const newLeft=run(def.left);const newRight=run(def.right);return newLeft===def.left&&newRight===def.right?s:clone(s,{...def,left:newLeft,right:newRight})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{const newInner=run(def.innerType);return newInner===def.innerType?s:clone(s,{...def,innerType:newInner})}case"pipe":{const newIn=run(def.in);const newOut=run(def.out);return newIn===def.in&&newOut===def.out?s:clone(s,{...def,in:newIn,out:newOut})}case"function":{const newInput=run(def.input);const newOutput=run(def.output);return newInput===def.input&&newOutput===def.output?s:clone(s,{...def,input:newInput,output:newOutput})}case"lazy":{const original=def.getter;const{_cachedInner,...rest}=def;return clone(s,{...rest,getter:()=>run(original())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:{return s}}}return run(schema)}function deepPartial(schema){return visit(schema,{object:(s)=>s.partial(),union:(s)=>{const def=s._zod.def;return def.discriminator===undefined?s:union(def.options)}})}function withChecks(side,checks){if(!checks?.length)return side;const def=side._zod.def;return clone(side,mergeDefs(def,{checks:[...def.checks??[],...checks]}),{parent:true})}function outSide(def){return withChecks(def.out,def.checks)}function inSide(def){return def.in._zod.traits.has("$ZodTransform")?outSide(def):def.in}function input(schema){return visit(schema,{pipe:(s)=>inSide(s._zod.def),default:(s,rewritten)=>rewritten?optional(s._zod.def.innerType):s,catch:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function output(schema){return visit(schema,{pipe:(s)=>outSide(s._zod.def),prefault:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}import path from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{createReadStream}from"node:fs";import{tmpdir}from"node:os";import{readFileSync}from"node:fs";var pageBundle=readFileSync(new URL("./page-bundle.js",import.meta.url),"utf8");init_internal_capability();function normalizeDialogPolicy(policy){return policy??{accept:true}}function dialogFromOpening(params={}){return{type:params.type,message:params.message,defaultPrompt:params.defaultPrompt??"",url:params.url}}function decisionFromResult(result){if(typeof result==="boolean")return{accept:result};if(result&&typeof result==="object"){const decision={accept:result.accept!==false};if(result.promptText!==undefined)decision.promptText=result.promptText;return decision}return{accept:true}}async function resolveDialogAction(policy,params={}){try{const result=typeof policy==="function"?await policy(dialogFromOpening(params)):policy;return decisionFromResult(result)}catch{return{accept:true}}}var __defProp2=Object.defineProperty;var __exportAll=(definitions,namespace)=>{const exports={};for(const name in definitions)__defProp2(exports,name,{get:definitions[name],enumerable:true});if(!namespace)__defProp2(exports,Symbol.toStringTag,{value:"Module"});return exports};var __esmMin=(factory,value,error)=>()=>{if(error)throw error[0];try{return factory&&(value=factory(factory=0)),value}catch(caught){error=[caught];throw caught}};if(!Promise.withResolvers){Promise.withResolvers=()=>{let resolve,reject;const promise=new Promise((res,rej)=>{resolve=res;reject=rej});return{promise,resolve,reject}}}class Emittery{#listeners=new Map;on(name,listener){const listeners=this.#listeners.get(name)??new Set;listeners.add(listener);this.#listeners.set(name,listeners);return()=>{listeners.delete(listener)}}async emit(name,data){const event={data,eventName:name};await Promise.all([...this.#listeners.get(name)??[]].map((listener)=>listener(event)))}clearListeners(){this.#listeners.clear()}}var{object:object2,string:string$2,number:number$2,array:array2,union:union$1,unknown:unknown$1,null:_null4}=exports_zod;var SESSION_ARTIFACTS_DIR=path.join(tmpdir(),"omowright-artifacts");var noop=()=>{};var init_emittery=noop;var init_zod=noop;var init_context=noop;var init_utils$13=noop;var init_config=noop;var init_extension_bridge=noop;var init_commands$1=noop;var init_directory=noop;var init_process=noop;var init_event_bus=noop;var init_state_db=noop;var init_schema=noop;var init_store$1=noop;var init_drizzle_orm=noop;var init_types$8=noop;var init_nanoid=noop;function sleep$12(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted)return reject(signal.reason??Error("Aborted"));const onAbort=()=>{clearTimeout(timer);reject(signal.reason??Error("Aborted"))};const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);signal?.addEventListener("abort",onAbort,{once:true})})}function getCurrentReplAbortSignal(){return}function withCurrentReplAbort(fn){return fn()}function withoutReplContext(fn){return fn()}function replPrint(...values){console.warn(...values)}async function sendCommandToExtension(command){throw new UnsupportedOperationError(`Extension command is unavailable: ${command.method}`)}class UnsupportedOperationError extends Error{constructor(message){super(message);this.name="UnsupportedOperationError"}}var stateDb=()=>{throw new UnsupportedOperationError("Daemon persistence is unavailable")};var NotificationGrantTable={};function spawnCommand(){throw new UnsupportedOperationError("Video recording is unavailable")}async function waitForExitCode(){return 1}function isWebSocketUrl(xn){return xn.startsWith(`ws://`)||xn.startsWith(`wss://`)}function isAuthorizationError(xn){let jn=xn instanceof Error?xn.message:String(xn),Vn=xn;return jn.includes(`401`)||jn.includes(`403`)||jn.includes(`Missing or invalid Authorization header.`)||jn.includes(`Unauthorized`)||jn.includes(`Forbidden`)||typeof Vn.status==`number`&&(Vn.status===401||Vn.status===403)||typeof Vn.response?.status==`number`&&(Vn.response.status===401||Vn.response.status===403)||typeof Vn.error?.status==`number`&&(Vn.error.status===401||Vn.error.status===403)||typeof Vn.cause?.status==`number`&&(Vn.cause.status===401||Vn.cause.status===403)||String(Vn.error?.message??``).includes(`Missing or invalid Authorization header.`)||String(Vn.cause?.message??``).includes(`Missing or invalid Authorization header.`)}function normalizeBaseUrl(xn){return xn.replace(/\/$/,``)}function createAbortError$1(){let xn=Error(`Operation aborted`);return xn.name=`AbortError`,xn}var DEFAULT_COMMAND_TIMEOUT_MS;var DEFAULT_RECONNECT_DELAYS_MS;var jsonVersionSchema;var jsonTargetSchema;var cdpWireMessageSchema;var BrowserCdpCommandError;var CdpClient;var init_client$6=__esmMin(()=>{init_emittery(),init_zod(),init_context(),init_utils$13(),init_config(),init_extension_bridge(),init_commands$1(),DEFAULT_COMMAND_TIMEOUT_MS=30000,DEFAULT_RECONNECT_DELAYS_MS=[0,250,750,1500,3000],jsonVersionSchema=object2({Browser:string$2().optional(),"Protocol-Version":string$2().optional(),"User-Agent":string$2().optional(),"V8-Version":string$2().optional(),"WebKit-Version":string$2().optional(),webSocketDebuggerUrl:string$2()}).loose(),jsonTargetSchema=object2({description:string$2().optional(),devtoolsFrontendUrl:string$2().optional(),faviconUrl:string$2().optional(),id:string$2(),parentId:string$2().optional(),title:string$2().default(``),type:string$2(),url:string$2().default(``),webSocketDebuggerUrl:string$2().optional()}).loose(),cdpWireMessageSchema=union$1([object2({id:number$2(),sessionId:string$2().optional(),error:object2({code:number$2().optional(),data:unknown$1().optional(),message:string$2()}).loose().optional(),result:unknown$1().optional()}).loose(),object2({method:string$2(),params:unknown$1().optional(),sessionId:string$2().optional()}).loose(),_null4()]),BrowserCdpCommandError=class extends Error{method;code;data;constructor(xn,jn,Vn,qn){super(qn??`CDP command failed: ${xn}`),this.method=xn,this.code=jn,this.data=Vn}},CdpClient=class{cdpUrl;logId;#dialogPolicy;#e;#t;#n;#r=null;#i=null;#a=null;#o=false;#s=1;#c=new Map;#l=new Emittery;#u=false;transportEvents=new Emittery;constructor(xn={}){if(typeof xn.cdpUrl!=`string`||xn.cdpUrl===``)throw TypeError(`CdpClient requires a cdpUrl: there is no default endpoint, so a missing URL can never reach a browser on 127.0.0.1:9222`);this.cdpUrl=normalizeBaseUrl(xn.cdpUrl),this.logId=xn.logId??`cdp-${Date.now()}`,this.#e=xn.authorizer,this.#t=xn.commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS,this.#n=xn.reconnectDelaysMs??DEFAULT_RECONNECT_DELAYS_MS,this.#dialogPolicy=normalizeDialogPolicy(xn.dialogPolicy)}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(xn){this.#dialogPolicy=normalizeDialogPolicy(xn)}get isConnected(){return this.#r?.readyState===wrapper_default.OPEN}start(){this.#o||(this.#o=true,this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] Initial CDP connect failed`,xn),this.#b()}))}async discoverVersion(xn={}){return await this.#f(this.#d(`/json/version`),jsonVersionSchema,xn)}async discoverTargets(xn={}){return await this.#f(this.#d(`/json/list`),array2(jsonTargetSchema),xn)}async ensureConnected(){if(this.#o=true,this.isConnected)return;if(this.#i){await this.#i;return}let xn=this.#g();this.#i=xn;try{await xn}finally{this.#i===xn&&(this.#i=null)}}async send(xn,jn,Vn,qn={}){if(xn===`Target.createTarget`&&qn.capability!==targetCreationCapability)throw Error(`Target.createTarget is reserved for createAgentTabs`);let Jn=getCurrentReplAbortSignal();if(Jn?.aborted)throw createAbortError$1();if(xn.startsWith(`OmO.`)){let Vn=await sendCommandToExtension({method:xn,params:jn},{...qn.extensionBridge,signal:Jn});if(Jn?.aborted)throw createAbortError$1();return Vn}await this.ensureConnected();let Yn=this.#r;if(!Yn||Yn.readyState!==wrapper_default.OPEN)throw Error(`CDP websocket is not connected`);let Zn=this.#s++,Qn={id:Zn,method:xn};jn!==undefined&&(Qn.params=jn),Vn&&(Qn.sessionId=Vn);let{promise:ei,reject:ti,resolve:ni}=Promise.withResolvers(),ri=qn.timeoutMs??this.#t,ii=ri>0?setTimeout(()=>{this.#c.delete(Zn),ti(Error(`CDP command timeout: ${String(xn)}`))},ri):undefined,ai=Jn?()=>{ii&&clearTimeout(ii),this.#c.delete(Zn),ti(createAbortError$1())}:undefined;if(this.#c.set(Zn,{method:String(xn),reject:ti,resolve:ni,timeout:ii}),Jn?.addEventListener(`abort`,ai,{once:true}),Jn?.aborted)return ai?.(),await ei;try{Yn.send(JSON.stringify(Qn))}catch(xn){throw ii&&clearTimeout(ii),this.#c.delete(Zn),ai&&Jn?.removeEventListener(`abort`,ai),xn instanceof Error?xn:Error(String(xn))}try{return await ei}finally{ai&&Jn?.removeEventListener(`abort`,ai)}}on(xn,jn){return this.#l.on(xn,({data:xn})=>jn(xn.payload,xn.meta))}async close(){this.#o=false,this.#a&&=(clearTimeout(this.#a),null);let xn=this.#r;if(this.#r=null,this.#x(Error(`CDP client closed`)),xn&&xn.readyState<=wrapper_default.OPEN)try{xn.close(1000,`client closing`)}catch{}}#d(xn){let jn=new URL(this.cdpUrl);return isWebSocketUrl(this.cdpUrl)?(jn.protocol=jn.protocol===`wss:`?`https:`:`http:`,jn.pathname=xn,jn.search=``,jn.toString()):(jn.pathname=xn,jn.search=``,jn.toString())}async#f(xn,jn,Vn={}){let qn=await this.#p(Vn),Jn=await fetch(xn,{headers:qn});if((Jn.status===401||Jn.status===403)&&this.#e&&!Vn.forceRefresh)return await this.#f(xn,jn,{forceRefresh:true});if(!Jn.ok)throw Error(`CDP discovery request failed (${Jn.status} ${Jn.statusText})`);return jn.parse(await Jn.json())}async#p(xn={}){return this.#e?{Authorization:await this.#e.resolveAuthorization(xn)}:{}}async#m(xn={}){let jn=await this.#p(xn);return isWebSocketUrl(this.cdpUrl)?{headers:jn,wsUrl:this.cdpUrl}:{headers:jn,wsUrl:(await this.discoverVersion(xn)).webSocketDebuggerUrl}}async#g(){let xn=null,jn=false;for(let Vn of this.#n){Vn>0&&await sleep$12(Vn);try{await this.#_({forceRefresh:jn});return}catch(Vn){let qn=Vn??Error(`Unknown error`);xn=qn,isAuthorizationError(qn)&&(jn=true)}}throw xn instanceof Error?xn:Error(String(xn??`Failed to connect CDP websocket`))}async#_(xn={}){let{headers:jn,wsUrl:Vn}=await this.#m(xn);await new Promise((xn,qn)=>{let Jn=new wrapper_default(Vn,{headers:jn}),Yn=false,Zn=(xn)=>{Yn||(Yn=true,qn(xn))};Jn.addEventListener(`open`,()=>{Yn||(Yn=true,this.#v(Jn),xn())}),Jn.addEventListener(`message`,(xn)=>{this.#r===Jn&&this.#S(xn.data).catch(()=>{})}),Jn.addEventListener(`close`,(xn)=>{this.#r===Jn&&this.#y(Jn),Yn||Zn(Error(`CDP websocket closed during connect (${xn.code} ${xn.reason||`no reason`})`))}),Jn.addEventListener(`error`,()=>{Zn(Error(`Failed to connect CDP websocket: ${Vn}`))})})}#v(xn){this.#a&&=(clearTimeout(this.#a),null);let jn=this.#r;if(this.#r=xn,this.send(`Target.setDiscoverTargets`,{discover:true}).catch(()=>{}),this.transportEvents.emit(this.#u?`reconnected`:`connected`).catch((xn)=>{console.warn(`[${this.logId}] CDP transport listener failed`,xn)}),this.#u=true,jn&&jn!==xn&&jn.readyState<=wrapper_default.OPEN)try{jn.close(1000,`replaced`)}catch{}}#y(xn){this.#r===xn&&(this.#r=null,this.#x(Error(`CDP websocket disconnected`)),this.transportEvents.emit(`disconnected`).catch((xn)=>{console.warn(`[${this.logId}] CDP disconnect listener failed`,xn)}),this.#o&&this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] CDP reconnect failed`,xn),this.#b()}))}#b(){if(!this.#o||this.isConnected||this.#i||this.#a)return;let xn=this.#n[this.#n.length-1]??3000;this.#a=setTimeout(()=>{this.#a=null,this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] Scheduled CDP reconnect failed`,xn),this.#b()})},xn)}#x(xn){for(let jn of this.#c.values())jn.timeout&&clearTimeout(jn.timeout),jn.reject(xn);this.#c.clear()}async#S(xn){let jn=typeof xn==`string`?xn:xn instanceof Blob?await xn.text():new TextDecoder().decode(xn),{data:Vn}=cdpWireMessageSchema.safeParse(JSON.parse(jn));if(Vn){if(typeof Vn.id==`number`){let xn=this.#c.get(Vn.id);if(!xn)return;if(this.#c.delete(Vn.id),xn.timeout&&clearTimeout(xn.timeout),Vn.error){let jn=Vn.error;xn.reject(new BrowserCdpCommandError(xn.method,jn.code,jn.data,jn.message??`CDP command failed: ${xn.method}`));return}xn.resolve(Vn.result);return}if(typeof Vn.method==`string`){let xn=Vn.method;if(xn===`Page.javascriptDialogOpening`&&Vn.sessionId){let dialogSessionId=Vn.sessionId;resolveDialogAction(this.#dialogPolicy,Vn.params).then((dialogAction)=>{let xn=this.#r;xn?.readyState===wrapper_default.OPEN&&xn.send(JSON.stringify({id:this.#s++,method:`Page.handleJavaScriptDialog`,params:dialogAction,sessionId:dialogSessionId}))})}let jn={payload:Vn.params,meta:{sessionId:Vn.sessionId}};this.#l.emit(xn,jn).catch((jn)=>{console.warn(`[${this.logId}] CDP event listener failed for ${xn}`,jn)})}}}}});var SessionManager;var init_session_manager=__esmMin(()=>{init_client$6(),SessionManager=class{#e;#t=new Map;#n=new Map;#r=new Map;#i=new Set;#a;constructor(xn){this.#e=xn,this.#a=[this.#e.on(`Target.attachedToTarget`,(xn)=>{let jn=xn.targetInfo.targetId;jn&&this.#s(jn,xn.sessionId)}),this.#e.on(`Target.detachedFromTarget`,(xn)=>{let jn=xn.targetId??this.#n.get(xn.sessionId);this.#n.delete(xn.sessionId),jn&&this.#t.get(jn)===xn.sessionId&&this.#t.delete(jn)})]}clear(){this.#t.clear(),this.#n.clear(),this.#r.clear()}async dispose(){for(let xn of this.#a)xn();await Promise.allSettled([...this.#i].map((xn)=>this.#e.send(`Target.detachFromTarget`,{sessionId:xn}).catch(()=>{}))),this.#i.clear(),this.clear()}async discoverTargets(){return await this.#e.discoverTargets()}async getPageTarget(xn){return(await this.discoverTargets()).find((jn)=>jn.id===xn&&jn.type===`page`)??null}hasTargetSession(xn,jn){return this.#t.get(xn)===jn}getTargetSession(xn){return this.#t.get(xn)}async resolvePageSession(xn,jn){if(jn&&this.hasTargetSession(xn,jn))return jn;let Vn=this.#t.get(xn);if(Vn)return Vn;let qn=this.#r.get(xn);if(qn)return await qn;let Jn=this.#o(xn).finally(()=>{this.#r.delete(xn)});return this.#r.set(xn,Jn),await Jn}async#o(xn){if(!await this.getPageTarget(xn))throw Error(`Tab ${xn} is no longer available.`);let jn=await this.#e.send(`Target.attachToTarget`,{targetId:xn,flatten:true});return this.#i.add(jn.sessionId),this.#s(xn,jn.sessionId),jn.sessionId}#s(xn,jn){this.#t.set(xn,jn),this.#n.set(jn,xn)}}});var init_cdp=__esmMin(()=>{init_client$6(),init_session_manager()});var BUNDLE$1;var init_omowright_world_bundle=__esmMin(()=>{BUNDLE$1=pageBundle});var MAX_BUFFER_SIZE;var CONSOLE_INTERCEPTOR_SCRIPT;var PageConsole;var init_console_capture=__esmMin(()=>{MAX_BUFFER_SIZE=1000,CONSOLE_INTERCEPTOR_SCRIPT=`(function(){if(window.__omowrightConsole)return;var logs=[];var orig={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug};@@ -232,7 +232,6 @@ ${qn.join(`const isComboboxLike = !!this.matches?.('[role="combobox"], [aria-haspopup="listbox"], summary');const isLink = this.tagName?.toUpperCase() === 'A';const href = isLink ? (this.getAttribute?.('href') || '') : '';- const absoluteHref = isLink ? this.href : '';const role = String(this.getAttribute?.('role') || '').toLowerCase();const nativeCheckable = this instanceof HTMLInputElement? this@@ -263,7 +262,6 @@ ${qn.join(`isComboboxLike,isCheckable: isNativeCheckable || checked !== null,isRadio: nativeType === 'radio' || role === 'radio',- popupUrl: prefersDomActivation && this.target === '_blank' ? absoluteHref : null,prefersDomActivation,expanded: isComboboxLike ? this.getAttribute?.('aria-expanded') ?? null : null,};@@ -309,7 +307,7 @@ ${qn.join(`if (target && 'blur' in target && typeof target.blur === 'function') {target.blur();}- }`)}async function readComboboxState(xn,jn){let Vn=await readClickTargetState(xn,jn);return{hasComboboxTarget:Vn.isComboboxLike,expanded:Vn.expanded}}async function clickComboboxFallback(xn,jn){await domClickTarget(xn,jn)}async function clickElement(xn,jn,Vn={},qn=defaultModifierState){let Jn=await resolveClickTarget(xn,jn),Yn=Vn.modifiers??[],Zn=[],Qn=await xn.resolveSessionId(),ei=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:false,expanded:null})),ti=await readClickTargetState(xn,Jn).catch(()=>({expanded:null,checked:null,isComboboxLike:false,isCheckable:false,isRadio:false,popupUrl:null,prefersDomActivation:false}));try{let jn=async()=>{let jn=async()=>!ti.isCheckable||ti.checked===null||ti.isRadio&&ti.checked?true:(await readClickTargetState(xn,Jn).catch(()=>null))?.checked!==ti.checked,ni=async()=>{if(ti.popupUrl&&xn.openPopupUrl){await xn.openPopupUrl(ti.popupUrl);return}await domClickTarget(xn,Jn)};if(ti.prefersDomActivation){if(await ni(),!await jn())throw Error(`Checkbox click did not change checked state`);return}let ri;try{let jn=Vn.force?await getPointerDispatchTarget(xn,Jn):await ensurePointerActionable(xn,Jn);ri=jn.point,Qn=jn.sessionId}catch(qn){let Yn=qn instanceof Error?qn.message:String(qn);if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;if(!Vn.force&&Yn.includes(`obscured`)){await domClickTarget(xn,Jn);return}throw qn}let{x:ii,y:ai}=ri;try{for(let jn of Yn)await keyDown(xn,Qn,jn,qn),Zn.push(jn);Vn.moveBeforeClick!==false&&await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:ii,y:ai,button:`none`,modifiers:qn.toModifiersMask()},Qn);let jn=Vn.dblClick?2:1;await xn.prepareForPotentialFileChooser?.();for(let Vn=1;Vn<=jn;Vn+=1)await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:ii,y:ai,button:`left`,buttons:1,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn),await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:ii,y:ai,button:`left`,buttons:0,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn)}catch(xn){if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;throw xn}ei.hasComboboxTarget&&ei.expanded===`false`&&await sleep$12(80);let oi=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:false,expanded:null}));if(ei.hasComboboxTarget&&ei.expanded===`false`&&oi.expanded===`false`&&await clickComboboxFallback(xn,Jn),!await jn()&&(await ni(),!await jn()))throw Error(`Checkbox click did not change checked state`)};if(Vn.waitAfter===false)await jn();else try{await performActionAndWait(xn,jn,{frameSessionId:Jn.frameSessionId})}catch(xn){if(xn instanceof NavigationReadinessTimeoutError&&xn.mode===`interactive`){replPrint(`[warning] Waited ${xn.timeoutMs}ms for the page to become ready after the click.`);return}throw xn}}finally{for(let jn=Zn.length-1;jn>=0;--jn)await keyUp(xn,Qn,Zn[jn],qn).catch(()=>{})}}async function fillElement(xn,jn,Vn){let qn=await resolveActionSessionId(xn,jn),Jn=await callOnElementSync(xn,jn,`function(nextValue, setValueTypes, typeIntoTypes) {+ }`)}async function readComboboxState(xn,jn){let Vn=await readClickTargetState(xn,jn);return{hasComboboxTarget:Vn.isComboboxLike,expanded:Vn.expanded}}async function clickComboboxFallback(xn,jn){await domClickTarget(xn,jn)}async function clickElement(xn,jn,Vn={},qn=defaultModifierState){let Jn=await resolveClickTarget(xn,jn),Yn=Vn.modifiers??[],Zn=[],Qn=await xn.resolveSessionId(),ei=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:false,expanded:null})),ti=await readClickTargetState(xn,Jn).catch(()=>({expanded:null,checked:null,isComboboxLike:false,isCheckable:false,isRadio:false,prefersDomActivation:false}));try{let jn=async()=>{let jn=async()=>!ti.isCheckable||ti.checked===null||ti.isRadio&&ti.checked?true:(await readClickTargetState(xn,Jn).catch(()=>null))?.checked!==ti.checked,ni=async()=>{await domClickTarget(xn,Jn)};if(ti.prefersDomActivation){if(await ni(),!await jn())throw Error(`Checkbox click did not change checked state`);return}let ri;try{let jn=Vn.force?await getPointerDispatchTarget(xn,Jn):await ensurePointerActionable(xn,Jn);ri=jn.point,Qn=jn.sessionId}catch(qn){let Yn=qn instanceof Error?qn.message:String(qn);if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;if(!Vn.force&&Yn.includes(`obscured`)){await domClickTarget(xn,Jn);return}throw qn}let{x:ii,y:ai}=ri;try{for(let jn of Yn)await keyDown(xn,Qn,jn,qn),Zn.push(jn);Vn.moveBeforeClick!==false&&await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:ii,y:ai,button:`none`,modifiers:qn.toModifiersMask()},Qn);let jn=Vn.dblClick?2:1;await xn.prepareForPotentialFileChooser?.();for(let Vn=1;Vn<=jn;Vn+=1)await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:ii,y:ai,button:`left`,buttons:1,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn),await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:ii,y:ai,button:`left`,buttons:0,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn)}catch(xn){if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;throw xn}ei.hasComboboxTarget&&ei.expanded===`false`&&await sleep$12(80);let oi=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:false,expanded:null}));if(ei.hasComboboxTarget&&ei.expanded===`false`&&oi.expanded===`false`&&await clickComboboxFallback(xn,Jn),!await jn()&&(await ni(),!await jn()))throw Error(`Checkbox click did not change checked state`)};if(Vn.waitAfter===false)await jn();else try{await performActionAndWait(xn,jn,{frameSessionId:Jn.frameSessionId})}catch(xn){if(xn instanceof NavigationReadinessTimeoutError&&xn.mode===`interactive`){replPrint(`[warning] Waited ${xn.timeoutMs}ms for the page to become ready after the click.`);return}throw xn}}finally{for(let jn=Zn.length-1;jn>=0;--jn)await keyUp(xn,Qn,Zn[jn],qn).catch(()=>{})}}async function fillElement(xn,jn,Vn){let qn=await resolveActionSessionId(xn,jn),Jn=await callOnElementSync(xn,jn,`function(nextValue, setValueTypes, typeIntoTypes) {const target = globalThis.__omowright?.retarget(this, 'follow-label');if (!target) {return { mode: 'needsinput', kind: 'input', expectedValue: '', error: 'Unable to retarget element' };@@ -679,7 +677,7 @@ ${qn.join(`throw new Error('$$eval pageFunction must evaluate to a function');}return await pageFunction(elements, arg);- }`,arguments:Zn,executionContextId:Jn.contextId,returnByValue:true,awaitPromise:true,userGesture:false},await this.#e.resolveSessionId(Jn.frameSessionId));if(ei)throw Error(formatRuntimeException(ei,`$$eval failed`));return Qn.value}async boundingBox(){let xn=await this.#r();return await boundingBoxElement(this.#e,xn)}async screenshot(xn={}){let jn=xn.margin??DEFAULT_SCREENSHOT_MARGIN;if(!Number.isFinite(jn)||jn<0)throw Error(`locator.screenshot: margin must be a non-negative number`);let Vn=await this.#r(),qn=await evaluateOnElement(this.#e,Vn,`function(margin) {+ }`,arguments:Zn,executionContextId:Jn.contextId,returnByValue:true,awaitPromise:true,userGesture:false},await this.#e.resolveSessionId(Jn.frameSessionId));if(ei)throw Error(formatRuntimeException(ei,`$$eval failed`));return Qn.value}async boundingBox(){let xn=await this.#r();return await boundingBoxElement(this.#e,xn)}async screenshot(xn={}){let jn=xn.margin??DEFAULT_SCREENSHOT_MARGIN;if(!Number.isFinite(jn)||jn<0)throw Error(`locator.screenshot: margin must be a non-negative number`);let Vn=await this.#r(),qn=await evaluateOnElement(this.#e,Vn,`function(_, margin) {const rect = this.getBoundingClientRect();if (rect.width <= 0 || rect.height <= 0) {return null;@@ -1466,22 +1464,15 @@ ${qn.join(`return globalThis.__omowright.takeSnapshot(opts);}`,arguments:[{value:ai}],executionContextId:ii,returnByValue:true,awaitPromise:false,userGesture:false},jn.getFrame(qn)?.sessionId),Yn=Vn.value;if(Yn){if(Yn.error){Jn&&(ri=Yn.error);return}ni.set(qn,Yn);return}}catch(xn){Qn=xn,isContextDestroyedError(xn)&&jn.invalidateContext(qn)}Jn&&Zn-1}Jn&&(ri=Qn)}));let ii=ni.get(ei);if(!ii){let xn=ri;throw xn instanceof Error?xn:typeof xn==`string`&&xn.length>0?Error(xn):Error(ei===qn?`Main frame snapshot failed`:`Ref subtree snapshot failed`)}let ai=new Map,oi=new Map;await Promise.all(ti.map(async({frameId:Vn})=>{let qn=ni.get(Vn),Jn=jn.getFrame(Vn);if(!qn||!Jn?.isolatedContextId)return;let Yn=Object.entries(qn.refs).filter(([,xn])=>xn.tagName.toLowerCase()===`iframe`).map(([xn])=>xn);if(Yn.length===0)return;let Zn=await Promise.all(Yn.map(async(qn)=>{let{result:Yn}=await xn.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(ref) {return globalThis.__omowright.elementRegistry.get(ref);- }`,arguments:[{value:qn}],executionContextId:Jn.isolatedContextId,returnByValue:false},Jn.sessionId).catch((xn)=>(isContextDestroyedError(xn)&&jn.invalidateContext(Vn),{result:{}})),Zn=typeof Yn==`object`&&Yn&&`objectId`in Yn?Yn.objectId:undefined;if(!Zn)return null;try{let{node:Vn}=await xn.send(`DOM.describeNode`,{objectId:Zn},Jn.sessionId),Yn=Vn.frameId?jn.getFrame(Vn.frameId)?.url:null,Qn=getCdpNodeAttribute(Vn.attributes,`src`),ei=getKnownIframeOriginLabel(Yn??``)??getKnownIframeOriginLabel(Qn??``);return{childFrameId:Vn.frameId,iframeRef:qn,originLabel:ei}}catch{return null}finally{await xn.send(`Runtime.releaseObject`,{objectId:Zn},Jn.sessionId).catch(()=>{})}})),Qn=new Map,ei=new Map;for(let xn of Zn)xn&&(xn.childFrameId&&Qn.set(xn.childFrameId,xn.iframeRef),xn.originLabel&&ei.set(xn.iframeRef,xn.originLabel));ai.set(Vn,Qn),ei.size>0&&oi.set(Vn,ei)}));let si=[...ti].sort((xn,jn)=>jn.depth-xn.depth),ci={};for(let xn of ni.values())Object.assign(ci,xn.refs);for(let[xn,jn]of oi){let Vn=ni.get(xn);if(Vn)for(let[xn,qn]of jn)Vn.tree=tagIframeLine(Vn.tree,xn,qn)}for(let xn of si){if(xn.frameId===qn||!xn.parentFrameId)continue;let Vn=ni.get(xn.frameId),Jn=ni.get(xn.parentFrameId);if(!Vn||!Jn||!Vn.tree)continue;let Yn=ai.get(xn.parentFrameId)?.get(xn.frameId),Zn=getKnownIframeOriginLabel(jn.getFrame(xn.frameId)?.url??``);Jn.tree=Yn?inlineChildTree(Jn.tree,Yn,Vn.tree):appendOrphanChildTree(Jn.tree,Vn.tree,Zn)}return{tree:ii.tree,refs:ci}}var KNOWN_IFRAME_ORIGINS;var SNAPSHOT_RETRY_DELAY_MS;var SNAPSHOT_MAX_RETRIES;var init_snapshot=__esmMin(()=>{init_extension_ids(),init_utils$13(),init_client$6(),init_frame_manager(),KNOWN_IFRAME_ORIGINS=[{urlPrefix:`chrome-extension://aeblfdkhhhdcdjpifhhbdiojplfjncoa/`,label:`1Password`},{urlPrefix:`chrome-extension://nngceckbapebfimnlniiiahkandclblb/`,label:`Bitwarden`},{urlPrefix:`chrome-extension://fdjamakpfbbddfjaooikfcpapjohcfmg/`,label:`Dashlane`},{urlPrefix:`chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/`,label:`LastPass`},{urlPrefix:`${PASSWORD_MANAGER_EXTENSION_ORIGIN}/`,label:`OmO Password Manager`}],SNAPSHOT_RETRY_DELAY_MS=300,SNAPSHOT_MAX_RETRIES=3});function diffLines(xn,jn){let Vn=xn.length,qn=jn.length,Jn=Vn+qn;if(Jn===0)return[];if(Vn===qn&&xn.every((xn,Vn)=>xn===jn[Vn]))return xn.map((xn)=>({type:`equal`,line:xn}));let Yn=Jn,Zn=new Int32Array(2*Jn+1);Zn.fill(-1),Zn[Yn+1]=0;let Qn=[];for(let ei=0;ei<=Jn;ei+=1){Qn.push(new Int32Array(Zn));for(let Jn=-ei;Jn<=ei;Jn+=2){let ti=Jn+Yn,ni=Jn===-ei||Jn!==ei&&Zn[ti-1]<Zn[ti+1]?Zn[ti+1]:Zn[ti-1]+1,ri=ni-Jn;for(;ni<Vn&&ri<qn&&xn[ni]===jn[ri];)ni+=1,ri+=1;if(Zn[ti]=ni,ni>=Vn&&ri>=qn)return buildEditScript(Qn,xn,jn,Yn)}}return buildEditScript(Qn,xn,jn,Yn)}function buildEditScript(xn,jn,Vn,qn){let Jn=[],Yn=jn.length,Zn=Vn.length;for(let Qn=xn.length-1;Qn>0;--Qn){let ei=xn[Qn],ti=Yn-Zn,ni=ti+qn,ri=ti===-Qn||ti!==Qn&&ei[ni-1]<ei[ni+1]?ti+1:ti-1,ii=ei[ri+qn],ai=ii-ri;for(;Yn>ii&&Zn>ai;)--Yn,--Zn,Jn.push({type:`equal`,line:jn[Yn]});if(Yn===ii){--Zn,Jn.push({type:`insert`,line:Vn[Zn]});continue}--Yn,Jn.push({type:`delete`,line:jn[Yn]})}for(;Yn>0&&Zn>0;)--Yn,--Zn,Jn.push({type:`equal`,line:jn[Yn]});return Jn.reverse()}function toUnifiedDiffHunks(xn){let jn=[],Vn=null,qn=1,Jn=1,Yn=()=>{Vn&&=(jn.push(Vn),null)};for(let jn of xn){if(jn.type===`equal`){Yn(),qn+=1,Jn+=1;continue}if(Vn||={oldStart:qn,oldCount:0,newStart:Jn,newCount:0,lines:[]},jn.type===`delete`){Vn.oldCount+=1,Vn.lines.push(`-${jn.line}`),qn+=1;continue}Vn.newCount+=1,Vn.lines.push(`+${jn.line}`),Jn+=1}return Yn(),jn}function diff(xn,jn){let Vn=toUnifiedDiffHunks(diffLines(xn.trim().split(`-`),jn.trim().split(`-`)));return Vn.length===0?`No changes detected-`:`${Vn.map((xn)=>[`@@ -${formatRange(xn.oldStart,xn.oldCount)} +${formatRange(xn.newStart,xn.newCount)} @@`,...xn.lines].join(`-`)).join(`-`)}-`}var formatRange;var init_diff=__esmMin(()=>{formatRange=(xn,jn)=>jn===1?String(xn):`${xn},${jn}`});function toSessionTab(xn){return nullToUndefined(xn)}function emitSessionTabsUpdated(xn,jn){EventBus.emit(`session:tabs-updated`,{sessionId:jn});let Vn=SessionStore.get(xn,jn)?.parentId;Vn&&EventBus.emit(`session:tabs-updated`,{sessionId:Vn})}function getSessionTab(xn,jn){let Vn=stateDb(xn).select().from(SessionTabTable).where(eq(SessionTabTable.id,jn)).get();return Vn?toSessionTab(Vn):null}function listSessionTabs(xn,jn,Vn={}){let qn=stateDb(xn);if(!Vn.includeChildSessions)return qn.select().from(SessionTabTable).where(eq(SessionTabTable.sessionId,jn)).all().map(toSessionTab);let Jn=qn.select({id:SessionTable.id}).from(SessionTable).where(eq(SessionTable.parentId,jn)).all().map((xn)=>xn.id);return qn.select().from(SessionTabTable).where(inArray(SessionTabTable.sessionId,[jn,...Jn])).all().map(toSessionTab)}function insertSessionTab(xn,jn){let Vn=nanoid3(),qn=new Date;return stateDb(xn).insert(SessionTabTable).values({...jn,id:Vn,createdAt:qn,updatedAt:qn}).run(),SessionStore.touch(xn,jn.sessionId),emitSessionTabsUpdated(xn,jn.sessionId),getSessionTab(xn,Vn)}function updateSessionTab(xn,jn,Vn){let qn=getSessionTab(xn,jn);return qn?(stateDb(xn).update(SessionTabTable).set({...Vn,updatedAt:new Date}).where(eq(SessionTabTable.id,jn)).run(),SessionStore.touch(xn,qn.sessionId),emitSessionTabsUpdated(xn,qn.sessionId),getSessionTab(xn,jn)):null}function removeSessionTab(xn,jn){let Vn=getSessionTab(xn,jn);stateDb(xn).delete(SessionTabTable).where(eq(SessionTabTable.id,jn)).run(),Vn&&(SessionStore.get(xn,Vn.sessionId)?.activeTabTargetId===Vn.targetId&&SessionStore.update(xn,Vn.sessionId,{activeTabTargetId:null}),SessionStore.touch(xn,Vn.sessionId),emitSessionTabsUpdated(xn,Vn.sessionId))}function getSessionTabByTargetId(xn,jn,Vn){let qn=stateDb(xn).select().from(SessionTabTable).where(and(eq(SessionTabTable.sessionId,jn),eq(SessionTabTable.targetId,Vn))).get();return qn?toSessionTab(qn):null}var init_session_tab_queries=__esmMin(()=>{init_drizzle_orm(),init_event_bus(),init_extension_bridge(),init_schema(),init_state_db(),init_nanoid(),init_utils$13(),init_store$1()});async function injectAnnotationOverlay(xn,jn){return await xn(({refIds:xn,overlayId:jn})=>{let Vn=document.getElementById(jn);Vn&&Vn.remove();let qn=[];for(let jn of xn){let xn=jn.match(/^(?:.*?)e(\d+)$/);if(!xn)continue;let Vn=parseInt(xn[1],10),Jn=globalThis.__omowright?.deref(jn)??null;if(!Jn)continue;let Yn=Jn.getBoundingClientRect();Yn.width<=0||Yn.height<=0||qn.push({number:Vn,x:Math.round(Yn.x),y:Math.round(Yn.y),width:Math.round(Yn.width),height:Math.round(Yn.height)})}if(qn.length===0)return 0;qn.sort((xn,jn)=>xn.number-jn.number);let Jn=window.scrollX||0,Yn=window.scrollY||0,Zn=document.createElement(`div`);Zn.id=jn,Zn.style.cssText=`position:absolute;top:0;left:0;width:0;height:0;pointer-events:none;z-index:2147483647;`;for(let xn of qn){let jn=xn.x+Jn,Vn=xn.y+Yn,qn=document.createElement(`div`);qn.style.cssText=`position:absolute;left:${jn}px;top:${Vn}px;width:${xn.width}px;height:${xn.height}px;border:2px solid rgba(255,0,0,0.8);box-sizing:border-box;pointer-events:none;`;let Qn=document.createElement(`div`);Qn.textContent=String(xn.number);let ei=Vn<14?`2px`:`-14px`;Qn.style.cssText=`position:absolute;top:${ei};left:-2px;background:rgba(255,0,0,0.9);color:#fff;font:bold 11px/14px monospace;padding:0 4px;border-radius:2px;white-space:nowrap;`,qn.appendChild(Qn),Zn.appendChild(qn)}return document.documentElement.appendChild(Zn),qn.length},{refIds:jn,overlayId:ANNOTATION_OVERLAY_ID})}async function removeAnnotationOverlay(xn){await xn((xn)=>{let jn=document.getElementById(xn);jn&&jn.remove()},ANNOTATION_OVERLAY_ID)}var ANNOTATION_OVERLAY_ID;var init_annotate_screenshot=__esmMin(()=>{ANNOTATION_OVERLAY_ID=`__omowright_annotations__`});function isStableAiTabViewport(xn){return!!xn&&xn.width>=MIN_STABLE_AI_TAB_VIEWPORT.width&&xn.height>=MIN_STABLE_AI_TAB_VIEWPORT.height}function normalizeOpenUrl(xn){return/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(xn)?xn:`https://${xn}`}function urlsMatchPopupTarget(xn,jn){if(!xn||!jn||jn===`about:blank`)return false;try{return new URL(xn).href===new URL(jn).href}catch{return xn===jn}}function isPlaceholderPopupUrl(xn){return xn===`:`||xn===`about:blank`||xn.trim()===``}function isTransientPageScriptError(xn){let jn=(xn instanceof Error?xn.message:String(xn)).toLowerCase();return jn.includes(`execution context was destroyed`)||jn.includes(`cannot find context with specified id`)||jn.includes(`frame was detached`)||jn.includes(`frame has been detached`)||jn.includes(`navigating frame was detached`)||jn.includes(`most likely because of a navigation`)||jn.includes(`target page, context or browser has been closed`)||jn.includes(`target closed`)}var PAGE_SCRIPT_RETRY_COUNT;var PAGE_SCRIPT_RETRY_DELAY_MS;var OPEN_TAB_WARNING_THRESHOLD;var DEFAULT_BROWSER_FETCH_USER_AGENT;var AI_TAB_STABLE_VIEWPORT;var MIN_STABLE_AI_TAB_VIEWPORT;var OmOBrowser;var init_browser=__esmMin(()=>{init_context(),init_cdp(),init_directory(),init_event_bus(),init_extension_bridge(),init_diff(),init_utils$13(),init_session_tab_queries(),init_store$1(),init_types$8(),init_utils$4(),init_annotate_screenshot(),init_frame_manager(),init_page(),init_snapshot(),PAGE_SCRIPT_RETRY_COUNT=10,PAGE_SCRIPT_RETRY_DELAY_MS=200,OPEN_TAB_WARNING_THRESHOLD=5,DEFAULT_BROWSER_FETCH_USER_AGENT=`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36`,AI_TAB_STABLE_VIEWPORT={width:1440,height:900},MIN_STABLE_AI_TAB_VIEWPORT={width:960,height:540},OmOBrowser=class{#e;#t;#n;#r;#i;#a=new Map;#o=new WeakMap;#s=[];#c=[];#l=new Map;#u=[];#d=[];#f=null;#p=[];#m=null;#h=null;#g;#_=new Set;#v=false;constructor(xn,jn,Vn,qn){this.#e=xn,this.#t=new SessionManager(xn),this.#n=jn,this.#r=Vn,this.#i=qn,this.#s.push(this.#e.transportEvents.on(`reconnected`,()=>{this.#g=undefined,this.#E()}),this.#e.on(`Target.targetInfoChanged`,(xn)=>{this.#y(xn.targetInfo),withoutReplContext(()=>this.#b(xn.targetInfo,{notifyRepl:false})).catch(()=>{})}),this.#e.on(`Target.targetCreated`,(xn)=>{withoutReplContext(()=>this.#b(xn.targetInfo,{notifyRepl:false})).catch(()=>{})}),this.#e.on(`Target.targetDestroyed`,(xn)=>{this.#R(xn.targetId).catch(()=>{})}))}get state(){if(!this.#m){let xn=this.#r.id,jn=SessionStore.get(this.#n,xn),Vn=listSessionTabs(this.#n,xn).map((xn)=>({sessionTabId:xn.id,targetId:xn.targetId,url:xn.url,ownership:xn.ownership,source:xn.source,...xn.data}));this.#m={activePage:Vn.find((xn)=>xn.targetId===jn?.activeTabTargetId),tabs:Vn},jn?.activeTabTargetId&&!this.#m.activePage&&console.warn(`[OmOBrowser.state] Stale activeTabTargetId ${jn.activeTabTargetId} for session ${xn}`)}return this.#m}setActiveTab(xn){SessionStore.update(this.#n,this.#r.id,{activeTabTargetId:xn}),this.#m=null}addNewTabState(xn){let jn=this.#r.id;if(!SessionStore.get(this.#n,jn))throw Error(`Cannot create session tab: parent session ${jn} no longer exists`);if(xn.targetId){let Vn=getSessionTabByTargetId(this.#n,jn,xn.targetId);if(Vn)return this.#m=null,Vn}let Vn=insertSessionTab(this.#n,{sessionId:jn,targetId:xn.targetId,url:xn.url,ownership:xn.ownership,source:xn.source,data:{title:xn.title??``,viewport:xn.viewport??AI_TAB_STABLE_VIEWPORT,...xn.iconUrl===undefined?{}:{iconUrl:xn.iconUrl}}});return this.#m=null,Vn}#y(xn){if(xn.type!==`page`||!xn.targetId)return;let jn=getSessionTabByTargetId(this.#n,this.#r.id,xn.targetId);if(!jn)return;let Vn=xn.url?.trim()||jn.url,qn=Vn!==jn.url,Jn=xn.title?.trim()||(qn?``:jn.data.title),Yn=xn.faviconUrl?.trim(),Zn=xn.faviconUrl!==undefined||qn,Qn=Zn?{...jn.data}:jn.data;Zn&&(delete Qn.iconUrl,Yn&&(Qn.iconUrl=Yn)),!(jn.url===Vn&&jn.data.title===Jn&&jn.data.iconUrl===Qn.iconUrl)&&(qn&&delete Qn.snapshot,updateSessionTab(this.#n,jn.id,{url:Vn,data:{...Qn,title:Jn}}),qn&&this.setActiveTab(jn.targetId),this.#m=null)}async#b(xn,jn={}){let Vn=xn.targetId;if(xn.type!==`page`||!Vn||this.#B(Vn))return;let qn=xn.openerId,Jn=this.#S({openerFrameId:xn.openerFrameId,openerTargetId:qn});if(Jn){await this.#L(Vn,Jn,jn);return}let Yn=this.#z(xn.url??``);Yn&&await this.#L(Vn,Yn.openerTargetId,jn)}async#x(xn={}){let{targetInfos:jn}=await this.#e.send(`Target.getTargets`).catch(()=>({targetInfos:[]}));await Promise.all(jn.map((jn)=>this.#b(jn,xn)))}#S({openerFrameId:xn,openerTargetId:jn}){if(jn){if(this.#a.has(jn)||this.state.tabs.some((xn)=>xn.targetId===jn))return jn;for(let[xn,Vn]of this.#a)if(Vn.frameManager.getFrame(jn))return xn}if(!xn)return null;for(let[jn,Vn]of this.#a)if(Vn.frameManager.getFrame(xn))return jn;return null}async updateTabState(xn,jn={}){if(!this.#a.has(xn.targetId))return null;let[Vn,qn]=await Promise.all([xn.title().catch(()=>``),this.#O(xn)]);xn.setCachedViewportSize(qn);let Jn=this.#B(xn.targetId);if(!Jn)return null;let Yn=getSessionTab(this.#n,Jn);if(!Yn)return null;let Zn=updateSessionTab(this.#n,Jn,{targetId:xn.targetId,url:jn.url??xn.url(),data:{...Yn.data,title:jn.title??Vn,viewport:jn.viewport??qn,...jn.iconUrl===undefined?{}:{iconUrl:jn.iconUrl},...jn.latestScreenshotPath===undefined?{}:{latestScreenshotPath:jn.latestScreenshotPath},...jn.snapshot===undefined?{}:{snapshot:jn.snapshot}}});return this.#m=null,Zn}removeTab(xn,jn){let Vn=getSessionTab(this.#n,xn);if(!Vn)return;let qn=SessionStore.get(this.#n,Vn.sessionId);removeSessionTab(this.#n,xn),qn?.activeTabTargetId===Vn.targetId&&(this.setActiveTab(null),!jn?.agentInitiated&&qn.status===`running`&&Promise.resolve().then(()=>(init_agent_session_server(),agent_session_server_exports)).then(({GlobalAgentSessionServer:xn})=>xn.sendSystemMessage(this.#n,Vn.sessionId,`The active browser tab for this session just closed.-Closed tab: ${Vn.data.title??`Unknown`} (${Vn.url})`,{kind:`tab_lifecycle`,mode:`steer`})).catch((xn)=>{console.warn(`[OmOBrowser] Failed to send tab lifecycle system message`,xn)})),this.#m=null}get page(){return this.#f}set page(xn){if(xn!==null&&!(xn instanceof OmOPage))throw Error(`page must be set to null or an OmOPage instance`);this.#f=xn,this.setActiveTab(xn?.targetId??null)}get tabs(){return this.#p}get extensionBridgeRoute(){return this.#j()}refreshBrowserBinding(xn){this.#r.browserBinding=xn,this.#g=undefined}async resolvePageSession(xn,jn){return await this.#t.resolvePageSession(xn,jn)}async ensurePage(xn){let jn=this.#a.get(xn);if(jn)return jn.page;if(this.#v)throw Error(`Browser is disposed`);if(!await this.#t.getPageTarget(xn))throw Error(`Tab ${xn} is no longer available.`);await this.#F(xn);let Vn=await this.resolvePageSession(xn),qn=new FrameManager(this.#e,xn,Vn);await qn.initialize();let Jn=new OmOPage(this.#e,qn,xn,Vn,this),Yn={frameManager:qn,page:Jn,unsubscribers:this.#V(Jn,Vn)};return this.#a.set(xn,Yn),Jn}async syncVmContext(xn,jn={}){for(let xn of this.#d.splice(0))replPrint(xn);if(await this.#x({notifyRepl:jn.notifyRecoveredPopups}),jn.notifyRecoveredPopups)for(let xn of this.#u.splice(0))replPrint(xn);this.#m=null;let Vn=this.state.tabs.map((xn)=>xn.targetId).filter((xn)=>!!xn),qn=(await Promise.all(Vn.map((xn)=>this.ensurePage(xn).catch(()=>null)))).filter((xn)=>xn!==null);this.#p=qn,xn.tabs=qn;let Jn=this.#f&&qn.some((xn)=>xn.targetId===this.#f.targetId),Yn=qn.find((xn)=>xn.targetId===this.state.activePage?.targetId)??null,Zn=Jn?this.#f:Yn;xn.page=Zn,this.#f=Zn}#C(){let{tabs:xn,activePage:jn}=this.state;if(xn.length===0){this.#T(`[system] no current open tabs in this session.`);return}this.#T(`[system] current open tabs in this session (${xn.length}):-`+xn.map(({title:xn,url:Vn,targetId:qn},Jn)=>` - \`tabs[${Jn}]\`: ${qn===jn?.targetId?`(active) `:``}${xn} (${truncateUrlForLLM(Vn)})`).join(`-`))}async openTab(xn){if(this.#v)throw Error(`Browser is disposed`);let jn=this.state.activePage?.targetId??this.#f?.targetId??this.#r.browserBinding?.anchorTargetId,{targetId:Vn}=await sendCommandToExtension({method:`OmO.createAgentTab`,params:{url:normalizeOpenUrl(xn),...jn?{anchorTargetId:jn}:{}}},this.#j());try{let jn=await this.ensurePage(Vn),qn=await this.#O(jn),Jn=this.addNewTabState({targetId:jn.targetId,url:xn,viewport:qn,ownership:`owned`,source:`open_tab`});this.setActiveTab(Jn.targetId),this.#p=[...this.#p.filter((xn)=>xn.targetId!==Vn),jn],await jn.waitForLoadState(`stable`,5000).catch((jn)=>{console.warn(`[browser] openTab: waitForLoadState failed`,{targetId:Vn,url:xn,error:jn instanceof Error?jn.message:String(jn)})});let Yn=await this.updateTabState(jn);await this.#w(Vn,xn,`openTab`),this.page=jn;let Zn=this.#p.length-1;return this.#T(`✔︎ Opened a new tab and set it active: tabs[${Zn}], page → ${Yn?.data?.title??`(no title)`} (${jn.url({truncate:true})})`),this.#p.length>=OPEN_TAB_WARNING_THRESHOLD&&this.#T(`[warning] ${this.#p.length} tabs are open. Close tabs you do not need as you work.`),jn}catch(jn){throw await this.#A(Vn),sendCommandToExtension({method:`OmO.controlTab`,params:{action:`close`,targetId:Vn,url:xn}},this.#j()).catch(()=>{}),jn}}async openPopupTab(xn,jn){if(this.#v)throw Error(`Browser is disposed`);let Vn=normalizeOpenUrl(xn);await this.#F(jn);let{targetId:qn}=await sendCommandToExtension({method:`OmO.createAgentTab`,params:{url:Vn,anchorTargetId:jn}},this.#j());try{await this.#L(qn,jn)}catch(xn){throw await this.#A(qn),sendCommandToExtension({method:`OmO.controlTab`,params:{action:`close`,targetId:qn,url:Vn}},this.#j()).catch(()=>{}),xn}}async closeTab(xn,jn={}){let Vn=xn.targetId,qn=this.state.tabs.find((xn)=>xn.targetId===Vn);if(!qn)throw Error(`Tab ${Vn} is not tracked in this session.`);if(qn.ownership!==`owned`){let xn=this.#B(Vn);xn&&this.removeTab(xn,{agentInitiated:true}),await this.#R(Vn);return}let Jn=this.#B(Vn);Jn&&this.removeTab(Jn,{agentInitiated:true});let Yn=false,Zn=false,Qn=this.#e.on(`Target.targetDestroyed`,(xn)=>{xn.targetId===Vn&&(Yn=true)});try{let qn=sendCommandToExtension({method:`OmO.controlTab`,params:{action:`close`,targetId:Vn,url:xn.url()}},this.#j()).catch(async(xn)=>{if(!Yn&&await this.#t.getPageTarget(Vn).catch(()=>null))throw xn}).finally(()=>{Zn=true});if(jn.runBeforeUnload)await qn;else{for(;!Yn&&!Zn&&await this.#t.getPageTarget(Vn).catch(()=>null);)await sleep$12(50);await Promise.race([qn,sleep$12(Yn?250:0)]),Yn||await qn}}finally{Qn()}await this.#R(Vn)}async closeOwnedTabs(){let xn=this.state.tabs.filter((xn)=>xn.ownership===`owned`&&xn.targetId);await Promise.allSettled(xn.map(async(xn)=>{let jn=xn.targetId;await this.#A(jn),await sendCommandToExtension({method:`OmO.controlTab`,params:{action:`close`,targetId:jn,url:xn.url,skipIfActive:true}},this.#j()).catch(()=>{})})),this.#m=null}async dispose(xn={}){let{closeOwnedTabs:jn=true}=xn;if(!this.#v){this.#v=true,this.#h=null;for(let xn of this.#s)xn();this.#s.length=0,jn&&await this.closeOwnedTabs().catch(()=>{});for(let xn of this.#a.keys())await this.#A(xn);await this.#t.dispose(),this.#p=[],this.#f=null}}async installPageScript(xn,jn,Vn){let qn;for(let Jn=0;Jn<PAGE_SCRIPT_RETRY_COUNT;Jn+=1)try{let qn=this.#o.get(xn)??new Map,Jn=qn.get(jn);if(Jn){await Jn;return}let Yn=xn.evaluate(Vn).then(()=>{});qn.set(jn,Yn),this.#o.set(xn,qn),await Yn;return}catch(Vn){if(qn=Vn,this.#o.get(xn)?.delete(jn),Jn===PAGE_SCRIPT_RETRY_COUNT-1||!isTransientPageScriptError(Vn))throw Vn;await sleep$12(PAGE_SCRIPT_RETRY_DELAY_MS)}if(qn)throw qn}async snapshot(xn,jn={}){if(jn.selector&&!await xn.evaluate((xn)=>!!document.querySelector(xn),jn.selector))throw Error(`Selector "${jn.selector}" matched no elements on page.`);let Vn=xn.targetId,qn=xn.url();this.#r.runtimeConfig.takeScreenshotOnEverySnapshot&&withoutReplContext(async()=>{let jn=`./tmp/screenshot-${Date.now()}.webp`;await mkdir(path.dirname(this.resolvePath(jn)),{recursive:true});let Vn=await this.#O(xn);await xn.screenshot({type:`webp`,path:jn,clip:{x:0,y:0,width:Vn.width,height:Vn.height}}),await this.updateTabState(xn,{latestScreenshotPath:jn})}).catch((xn)=>{console.warn(`[OmOBrowser] Failed to capture automatic snapshot screenshot`,xn)});let[Jn,Yn]=await Promise.all([takeSnapshot(this.#e,xn.frameManager,jn),xn.title().catch(()=>``)]),Zn=this.state.tabs.find((xn)=>xn.targetId===Vn)?.snapshot?.tree??``;await this.updateTabState(xn,{snapshot:Jn}),this.emitBrowserEvent(`browser:snapshot`,{targetId:Vn,url:qn,options:jn,snapshot:Jn});let Qn=[jn.interactive&&`# note: interactive (clickable / focusable) elements only.`,jn.showHidden&&`# note: hidden elements are shown.`,`- title: "${Yn}" [url=${truncateUrlForLLM(qn)}]`,Jn.tree].filter((xn)=>!!xn).join(`-`),ei=diff(Zn,Jn.tree);return{tree:Qn,refs:Jn.refs,diff:ei.length>Qn.length?Qn:ei}}async annotatedScreenshot(xn){let jn=await xn.snapshot({interactive:true}),Vn=await xn.frameManager.ensureInjected(xn.frameManager.mainFrameId),qn=async(jn,qn)=>{let{result:Jn,exceptionDetails:Yn}=await xn._sendToTarget(`Runtime.callFunctionOn`,{functionDeclaration:`function(arg) { return (${jn.toString()})(arg); }`,arguments:[{value:qn}],executionContextId:Vn,returnByValue:true,awaitPromise:true});if(Yn)throw Error(Yn.text??`Annotation overlay failed`);return Jn.value},Jn=false;try{return Jn=await injectAnnotationOverlay(qn,Object.keys(jn.refs))>0,{base64Image:(await xn.screenshot({type:`png`})).toString(`base64`)}}finally{Jn&&await removeAnnotationOverlay(qn).catch(()=>{})}}async getUserAgent(){return(await this.#e.send(`Browser.getVersion`,undefined).catch(()=>null))?.userAgent}async fetch(xn,jn={}){let Vn=xn.toString(),[qn,Jn]=await Promise.all([this.getCookiesForUrl(Vn),this.getUserAgent()]),Yn=new Headers(jn.headers);return qn&&!Yn.has(`Cookie`)&&Yn.set(`Cookie`,qn),Yn.has(`User-Agent`)||Yn.set(`User-Agent`,Jn??DEFAULT_BROWSER_FETCH_USER_AGENT),fetch(Vn,{...jn,headers:Yn})}async getCookiesForUrl(xn){let jn=this.#f?.targetId??this.state.activePage?.targetId??this.#r.browserBinding?.anchorTargetId;if(!jn)return;let Vn=await(this.#a.get(jn)?.page??await this.ensurePage(jn))._sendToTarget(`Network.getCookies`,{urls:[xn]});if(Vn.cookies.length)return Vn.cookies.map((xn)=>`${xn.name}=${xn.value}`).join(`; `).trim()||undefined}getPageSnapshot(xn){let jn=`targetId`in xn?xn.targetId:xn.page?.targetId;if(jn)return this.state.tabs.find((xn)=>xn.targetId===jn)?.snapshot}resolvePath(xn){return resolveSessionPath(getSessionStorageDir(this.#r,this.#n),xn,getSharedSessionStorageDir(this.#r,this.#n))}registerReadableDownloadPath(xn){let jn=path.resolve(xn);return this.#_.add(jn),jn}isReadableDownloadPath(xn){return this.#_.has(path.resolve(xn))}async ensurePath(xn,jn,Vn){let qn=this.resolvePath(xn),Jn=getCurrentReplToolCallId();if(!this.#i||!Jn)return qn;let Yn={toolCallId:Jn,path:qn,mode:jn,source:Vn};return await this.#i.trigger(`file.access`,Yn,Yn),qn}get daemonSession(){return{accountId:this.#n,id:this.#r.id,projectId:this.#r.projectId}}async#w(xn,jn,Vn){try{await sendCommandToExtension({method:`OmO.ensureTabInAiTabsGroup`,params:{targetId:xn}},this.#j())}catch(qn){let Jn=qn instanceof Error?qn.message:String(qn);console.warn(`[browser] ${Vn}: failed to move tab into Agent Tabs group`,{targetId:xn,url:jn,error:Jn}),this.#T(`[warning] Failed to move tab into Agent Tabs group: ${Jn}`)}}#T(xn){hasActiveReplContext()?replPrint(xn):this.#d.push(xn)}emitBrowserEvent(xn,jn){EventBus.emit(xn,[jn,{session:this.#r}]).catch((jn)=>{console.warn(`[omowright-browser] Failed to emit ${xn}`,jn)})}#E(){this.#v||this.#h||(this.#h=this.#D().finally(()=>{this.#h=null}))}async#D(){if(!this.#v){this.#t.clear();for(let[xn,jn]of this.#a)try{if(!await this.#t.getPageTarget(xn)){await this.#I(xn);continue}let Vn=await this.resolvePageSession(xn);for(let xn of jn.unsubscribers)xn();jn.unsubscribers=this.#V(jn.page,Vn),await jn.frameManager.reconnect(Vn),jn.page.reconnect(Vn),await this.updateTabState(jn.page).catch(()=>{})}catch{await this.#I(xn)}this.#p=this.#p.filter((xn)=>this.#a.has(xn.targetId)),this.#f&&!this.#a.has(this.#f.targetId)&&(this.#f=null)}}async#O(xn){let jn=this.#k(xn),Vn=await xn.refreshViewportSize().catch(()=>jn);return isStableAiTabViewport(Vn)?Vn:(xn.setCachedViewportSize(jn),jn)}#k(xn){let jn=xn.viewportSize();if(isStableAiTabViewport(jn))return jn;let Vn=getSessionTabByTargetId(this.#n,this.#r.id,xn.targetId)?.data.viewport;return isStableAiTabViewport(Vn)?Vn:AI_TAB_STABLE_VIEWPORT}async#A(xn){let jn=this.#a.get(xn),Vn=this.#t.getTargetSession(xn);if(Vn&&await this.#e.send(`Target.detachFromTarget`,{sessionId:Vn}).catch(()=>{}),jn){this.#a.delete(xn);for(let xn of jn.unsubscribers)xn();await jn.page.dispose().catch(()=>{}),await jn.frameManager.dispose().catch(()=>{})}}#j(){let xn=this.#r.browserBinding;if(!xn)throw Error(BROWSER_BINDING_REQUIRED_MESSAGE);return{accountId:this.#n,profileId:xn.profileId,windowId:xn.windowId}}async#M(xn){return(await this.#e.send(`Target.getTargetInfo`,{targetId:xn}).catch(()=>null))?.targetInfo.browserContextId}async#N(xn){let{owned:jn}=await sendCommandToExtension({method:`OmO.ownsTarget`,params:{targetId:xn}},this.#j());return jn}async#P(){if(this.#g)return this.#g;let xn=this.#r.browserBinding,jn=new Set([this.#r.activeTabTargetId,xn?.anchorTargetId].filter((xn)=>!!xn));for(let xn of jn){if(!await this.#N(xn))continue;let jn=await this.#M(xn);if(jn)return this.#g=jn,jn}}async#F(xn){if(!await this.#N(xn))throw Error(`Tab ${xn} belongs to a different browser profile.`);let jn=await this.#M(xn);if(!jn)throw Error(`Unable to verify the browser profile for tab ${xn}.`);let Vn=await this.#P();if(Vn&&jn!==Vn)throw Error(`Tab ${xn} belongs to a different browser profile.`);this.#g??=jn}async#I(xn){await this.#A(xn),this.#p=this.#p.filter((jn)=>jn.targetId!==xn),this.#f?.targetId===xn&&(this.#f=null)}async#L(xn,jn,Vn={}){let qn=this.#l.get(xn);if(qn){await qn;return}if(this.#B(xn))return;let Jn=(async()=>{this.#m=null;let qn=await this.ensurePage(xn);await this.#w(xn,qn.url(),`trackPopupTarget`),await qn.waitForLoadState(`stable`,5000).catch(()=>{});let[Jn,Yn]=await Promise.all([qn.title().catch(()=>``),this.#O(qn)]),Zn=qn.url();if(isPlaceholderPopupUrl(Zn)){await this.#A(xn),sendCommandToExtension({method:`OmO.controlTab`,params:{action:`close`,targetId:xn,url:Zn}},this.#j()).catch(()=>{});return}qn.setCachedViewportSize(Yn),this.addNewTabState({targetId:xn,url:Zn,title:Jn,viewport:Yn,ownership:`owned`,source:`popup`}),this.#p=[...this.#p.filter((jn)=>jn.targetId!==xn),qn];let Qn=this.#p.length-1,ei=`[system] popup opened: ${Jn??`(no title)`} (${truncateUrlForLLM(Zn)})- to use, explicitly access it via \`tabs[${Qn}]\` or switch it with \`page = tabs[${Qn}];\``;Vn.notifyRepl??true?this.#T(ei):this.#u.push(ei),this.emitBrowserEvent(`browser:popup`,{targetId:xn,openerTargetId:jn,url:Zn})})().finally(()=>{this.#l.delete(xn)});this.#l.set(xn,Jn),await Jn}async#R(xn){if(!this.#p.find((jn)=>jn.targetId===xn)&&!this.#a.has(xn))return;let jn=this.#B(xn),Vn=this.#f?.targetId===xn;if(await this.#A(xn),jn&&(this.removeTab(jn),this.#m=null),this.#p=this.#p.filter((jn)=>jn.targetId!==xn),Vn){let xn=(this.#p.length>0?this.#p[this.#p.length-1]:null)??null;this.#f=xn,xn?(this.setActiveTab(xn.targetId),this.#T(`[system] tab closed. \`page\` is changed to the last tab: ${xn.url({truncate:true})}`)):this.#T("[system] last tab closed. `page` is now null. call openTab(url) to open a new one."),this.#C()}else{let xn=this.state.activePage?.targetId;this.#f=xn?this.#p.find((jn)=>jn.targetId===xn)??null:null}}#z(xn){let jn=Date.now();for(;this.#c.length>0&&jn-this.#c[0].timestamp>1e4;)this.#c.shift();if(this.#c.length===1&&(!xn||xn===`about:blank`))return this.#c.shift()??null;let Vn=this.#c.findIndex((jn)=>urlsMatchPopupTarget(jn.url,xn));if(Vn===-1)return null;let[qn]=this.#c.splice(Vn,1);return qn??null}#B(xn){return xn?getSessionTabByTargetId(this.#n,this.#r.id,xn)?.id??null:null}#V(xn,jn){return[xn.on(`framenavigated`,(jn)=>{(!xn.frameManager.mainFrameId||jn.frameId===xn.frameManager.mainFrameId)&&this.updateTabState(xn).then(async(jn)=>{if(!jn)return;let Vn=xn.url(),qn=this.#i?await this.#i.trigger(`browser.navigation`,{page:xn,url:Vn},{url:Vn}):{url:Vn},Jn=this.#p.findIndex((jn)=>jn.targetId===xn.targetId),Yn=this.#f?.targetId===xn.targetId?`page`:`tabs[${Jn}]`;this.#T(`[system] \`${Yn}\` navigated to: [${jn.data.title}](${truncateUrlForLLM(Vn)}) `),this.emitBrowserEvent(`browser:navigation`,{targetId:xn.targetId,url:qn.url})}).catch(()=>{})}),this.#e.on(`Page.javascriptDialogOpening`,(jn,Vn)=>{if(!Vn.sessionId||!xn.frameManager.hasSession(Vn.sessionId))return;let qn={targetId:xn.targetId,url:jn.url,type:jn.type,message:jn.message,defaultPrompt:jn.defaultPrompt??``};this.emitBrowserEvent(`browser:alert`,qn);let Jn=this.#p.findIndex((jn)=>jn.targetId===xn.targetId),Yn=this.#f?.targetId===xn.targetId?`page`:`tabs[${Jn}]`,Zn=qn.type===`prompt`?`[system] \`${Yn}\` showed a prompt dialog: "${qn.message}" (default: "${qn.defaultPrompt}"). options: [OK (text input)] [Cancel]. auto-accepted with default value.`:qn.type===`confirm`?`[system] \`${Yn}\` showed a confirm dialog: "${qn.message}". options: [OK] [Cancel]. auto-accepted (OK).`:`[system] \`${Yn}\` showed an alert: "${qn.message}". auto-accepted.`;this.#T(Zn),this.updateTabState(xn,{url:jn.url}).catch(()=>{})}),xn.on(`popup`,(jn)=>{this.#c.push({openerTargetId:xn.targetId,url:jn.url,timestamp:Date.now()})}),xn.on(`download`,async(jn)=>{let Vn=await withoutReplContext(()=>jn.path()).catch((xn)=>{let Vn=xn instanceof Error?xn.message:String(xn);try{this.#T(`[system] download started: ${jn.suggestedFilename()} (${Vn})`)}catch{}return null});if(!Vn)return;let qn=jn.url();this.#i&&await this.#i.trigger(`browser.download`,{page:xn,url:qn,path:Vn},{path:Vn}),this.#T(`[system] downloading file: ${jn.suggestedFilename()} to ${Vn}`),this.emitBrowserEvent(`browser:download`,{targetId:xn.targetId,url:qn,path:Vn,suggestedFilename:jn.suggestedFilename()})})]}}});function defaultVideoSize(xn){let jn=Math.min(1,DEFAULT_VIDEO_MAX_EDGE/xn.width,DEFAULT_VIDEO_MAX_EDGE/xn.height),Vn=Math.max(2,Math.round(xn.width*jn)),qn=Math.max(2,Math.round(xn.height*jn));return{height:qn%2==0?qn:qn+1,width:Vn%2==0?Vn:Vn+1}}function inferVideoFormat(xn){return xn.format?xn.format:xn.path?.toLowerCase().endsWith(`.mp4`)?`mp4`:DEFAULT_VIDEO_FORMAT}async function ensureDirForFile(xn){await fs$16.mkdir(path.dirname(xn),{recursive:true})}async function readProcessStderr(xn){return await readProcessStream(xn.stderr).catch(()=>``)}var DEFAULT_VIDEO_FORMAT;var DEFAULT_VIDEO_FRAMERATE;var DEFAULT_VIDEO_JPEG_QUALITY;var DEFAULT_VIDEO_MAX_EDGE;var FfmpegVideoRecorder;var OmOVideo;var init_video=__esmMin(()=>{init_context(),init_process(),init_browser(),DEFAULT_VIDEO_FORMAT=`webm`,DEFAULT_VIDEO_FRAMERATE=25,DEFAULT_VIDEO_JPEG_QUALITY=90,DEFAULT_VIDEO_MAX_EDGE=800,FfmpegVideoRecorder=class{#e;#t;#n=0;#r=false;#i=null;#a=Promise.resolve();#o=0;#s=[];constructor(xn,jn,Vn,qn){this.#e=Vn;let Jn=qn===`mp4`?[`-c:v`,`libx264`,`-movflags`,`+faststart`]:[`-c:v`,`libvpx`,`-qmin`,`0`,`-qmax`,`50`,`-crf`,`8`,`-deadline`,`realtime`,`-speed`,`8`,`-b:v`,`1M`];this.#t=spawnCommand([`ffmpeg`,`-loglevel`,`error`,`-f`,`image2pipe`,`-avioflags`,`direct`,`-fpsprobesize`,`0`,`-probesize`,`32`,`-analyzeduration`,`0`,`-c:v`,`mjpeg`,`-i`,`pipe:0`,`-y`,`-an`,`-r`,String(Vn),...Jn,`-threads`,`1`,`-vf`,`scale=${jn.width}:${jn.height}:force_original_aspect_ratio=decrease,pad=${jn.width}:${jn.height}:(ow-iw)/2:(oh-ih)/2:gray`,`-pix_fmt`,`yuv420p`,xn],{stdio:[`pipe`,`ignore`,`pipe`]})}writeFrame(xn,jn){if(this.#r)return;this.#n||=jn;let Vn=Math.floor((jn-this.#n)*this.#e);if(this.#i){let xn=Vn-this.#i.frameNumber;for(let jn=0;jn<xn;jn+=1)this.#s.push(this.#i.buffer);this.#a=this.#a.then(()=>this.#c())}this.#i={buffer:xn,frameNumber:Vn,timestamp:jn},this.#o=Date.now()}async stop(xn){if(this.#r)return;if(!this.#i){if(!xn)throw Error(`Video recorder did not capture any frames.`);this.writeFrame(xn,Date.now()/1000)}let jn=this.#i;if(!jn)throw Error(`Video recorder did not capture any frames.`);let Vn=Math.max((Date.now()-this.#o)/1000,1);if(this.writeFrame(Buffer.from([]),jn.timestamp+Vn),this.#r=true,await withCurrentReplAbort(async()=>await this.#a),!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let qn=this.#t.stdin;await withCurrentReplAbort(async()=>await endProcessInput(qn));let Jn=await withCurrentReplAbort(async()=>await waitForExitCode(this.#t));if(Jn!==0){let xn=await readProcessStderr(this.#t);throw Error(xn.trim()||`ffmpeg exited with code ${Jn}`)}}async#c(){if(!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let xn=this.#t.stdin;for(;this.#s.length>0;){let jn=this.#s.shift();if(!(!jn||jn.length===0))try{await withCurrentReplAbort(async()=>await writeProcessChunk(xn,jn))}catch(xn){let jn=(await readProcessStderr(this.#t)).trim();throw Error(jn.length>0?`ffmpeg rejected video frame input: ${jn}`:xn instanceof Error?xn.message:String(xn))}}}},OmOVideo=class{#e;#t=null;#n=null;constructor(xn){this.#e=xn}async start(xn={}){return await withCurrentReplAbort(async()=>{if(this.#t)throw Error(`Video recording is already active.`);let jn=await this.#e.resolveSessionId(),Vn=this.#e.viewportSize()??await this.#e.refreshViewportSize().catch(()=>null)??AI_TAB_STABLE_VIEWPORT,qn=inferVideoFormat(xn),Jn=xn.size??defaultVideoSize(Vn),Yn=await this.#e.browser.ensurePath(xn.path??`video-${Date.now()}.${qn}`,`write`,`page.video.start`),Zn=xn.quality??DEFAULT_VIDEO_JPEG_QUALITY,Qn=xn.framerate??DEFAULT_VIDEO_FRAMERATE;await ensureDirForFile(Yn);let ei=new FfmpegVideoRecorder(Yn,Jn,Qn,qn),{promise:ti,resolve:ni,reject:ri}=Promise.withResolvers(),ii=this.#e.cdp.on(`Page.screencastFrame`,(xn,Vn)=>{if(Vn.sessionId!==jn)return;let qn=Buffer.from(xn.data,`base64`),Jn=xn.metadata?.timestamp??Date.now()/1000;ei.writeFrame(qn,Jn),this.#e.cdp.send(`Page.screencastFrameAck`,{sessionId:xn.sessionId},jn).catch(()=>{})});this.#t={completion:ti,format:qn,outputPath:Yn,pendingCopies:new Set,recorder:ei,rejectCompletion:ri,resolveCompletion:ni,sessionId:jn,unsubscribe:ii},this.#n=Yn;try{await this.#e.cdp.send(`Page.startScreencast`,{everyNthFrame:1,format:`jpeg`,maxHeight:Jn.height,maxWidth:Jn.width,quality:Zn},jn)}catch(xn){throw ii(),this.#t=null,this.#n=null,ri(xn),xn}})}async stop(xn={}){return await withCurrentReplAbort(async()=>{let jn=this.#t;if(!jn)throw Error(`Video recording has not been started.`);this.#t=null,jn.unsubscribe(),await this.#e.cdp.send(`Page.stopScreencast`,undefined,jn.sessionId).catch(()=>{});try{let Vn=await this.#e.screenshot({type:`jpeg`}).catch(()=>{return}),qn=xn.path?await this.#e.browser.ensurePath(xn.path,`write`,`page.video.stop`):jn.outputPath;await jn.recorder.stop(Vn),qn!==jn.outputPath&&(await ensureDirForFile(qn),await fs$16.copyFile(jn.outputPath,qn)),this.#n=qn;for(let xn of jn.pendingCopies){let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);jn!==qn&&(await ensureDirForFile(jn),await fs$16.copyFile(qn,jn))}jn.resolveCompletion(qn)}catch(xn){throw jn.rejectCompletion(xn),xn}})}async path(){if(this.#t)return this.#t.outputPath;if(this.#n)return this.#n;throw Error(`Video recording has not been started.`)}async saveAs(xn){return await withCurrentReplAbort(async()=>{let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);if(this.#t){this.#t.pendingCopies.add(xn),await this.#t.completion;return}if(!this.#n)throw Error(`Video recording has not been started.`);await ensureDirForFile(jn),await fs$16.copyFile(this.#n,jn)})}async delete(){return await withCurrentReplAbort(async()=>{if(this.#t&&await this.stop(),!this.#n)throw Error(`Video recording has not been started.`);let xn=this.#n;this.#n=null,await fs$16.unlink(xn).catch(()=>{})})}}});function isOmOEvaluateOptions(xn){if(typeof xn!=`object`||!xn||Array.isArray(xn))return false;let jn=Object.keys(xn);return jn.length===1&&jn[0]===`userGesture`}function resolveEvaluateCall(xn,jn,Vn){if(Vn!==undefined&&!isOmOEvaluateOptions(Vn))throw Error(`page.evaluate() accepts a single optional argument. Pass multiple values as one object or array, e.g. page.evaluate(fn, [a, b]).`);return typeof xn==`string`&&isOmOEvaluateOptions(jn)?{actualArg:undefined,evaluateOptions:jn}:{actualArg:jn,evaluateOptions:Vn??{}}}function clampScreenshotClipToTextureLimit(xn,jn){let Vn=Math.max(1,Math.floor(MAX_SCREENSHOT_TEXTURE_SIZE/(Number.isFinite(jn)&&jn>0?jn:1)));return{...xn,width:Math.max(1,Math.min(xn.width,Vn)),height:Math.max(1,Math.min(xn.height,Vn))}}function normalizeScreenshotTimeout(xn){if(xn!==undefined){if(!Number.isFinite(xn)||xn<0)throw Error(`page.screenshot: timeout must be a non-negative number`);return xn}}function screenshotCaptureLabel(xn){return xn.clip?`clipped screenshot`:xn.fullPage?`full-page screenshot`:`viewport screenshot`}function formatScreenshotError(xn){return xn instanceof Error?xn.message:String(xn)}function rewriteCaptureScreenshotError(xn,jn,Vn){let qn=formatScreenshotError(xn);if(qn!==`CDP command timeout: Page.captureScreenshot`)return xn instanceof Error?xn:Error(qn);let Jn=jn===undefined?`the default screenshot timeout`:jn===0?`a disabled page.screenshot timeout`:`the requested ${jn}ms page.screenshot timeout`;return Error(`page.screenshot: browser CDP command timed out while capturing ${Vn} before ${Jn} completed`)}function isCaptureScreenshotTimeout(xn){let jn=formatScreenshotError(xn);return jn===`CDP command timeout: Page.captureScreenshot`||jn.startsWith(`page.screenshot: browser CDP command timed out while capturing `)}function formatPdfLength(xn){if(xn!==undefined)return typeof xn==`number`?`${xn}px`:xn}var DEFAULT_WAIT_TIMEOUT_MS;var NETWORK_IDLE_MS;var MAX_SCREENSHOT_TEXTURE_SIZE;var FILECHOOSER_OOPIF_FALLBACK_MS;var OmOPage;var init_page=__esmMin(()=>{init_emittery(),init_context(),init_extension_bridge(),init_notification_grants(),init_utils$13(),init_client$6(),init_errors$3(),init_utils$4(),init_console_capture(),init_download(),init_file_chooser(),init_frame(),init_frame_manager(),init_keyboard(),init_locator(),init_mouse(),init_snapshot(),init_video(),init_wait(),DEFAULT_WAIT_TIMEOUT_MS=30000,NETWORK_IDLE_MS=500,MAX_SCREENSHOT_TEXTURE_SIZE=16384,FILECHOOSER_OOPIF_FALLBACK_MS=2000,OmOPage=class{cdp;frameManager;targetId;modifierState;mouse;keyboard;events=new Emittery;browser;#e=new Map;#t=null;#n;#r=``;#i=null;#a=[];#o=null;#s=false;#c=0;constructor(xn,jn,Vn,qn,Jn){this.cdp=xn,this.frameManager=jn,this.targetId=Vn,this.modifierState=new ModifierState,this.mouse=new OmOMouse(this,this.modifierState),this.keyboard=new OmOKeyboard(this,this.modifierState),this.browser=Jn,this.#n=qn,this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??``,this.#l()}#l(){let xn=new Set,jn=(xn)=>{replPrint(`[error] page event listener threw: ${xn instanceof Error?xn.message:xn}`)};this.#u(`Page.frameNavigated`,(xn)=>{xn.frame.parentId||(this.#r=xn.frame.url)}),this.#u(`Page.loadEventFired`,()=>{this.events.emit(`load`).catch(jn)}),this.#u(`Page.domContentEventFired`,()=>{this.events.emit(`domcontentloaded`).catch(jn)}),this.#u(`Page.javascriptDialogOpening`,(xn)=>{this.events.emit(`dialog`,{type:xn.type,message:xn.message,defaultPrompt:xn.defaultPrompt??``,url:xn.url}).catch(jn)}),this.#a.push(this.cdp.on(`Page.fileChooserOpened`,(xn,Vn)=>{!Vn.sessionId||!xn.backendNodeId||this.events.emit(`filechooser`,new FileChooser(this,xn.frameId,xn.backendNodeId,xn.mode===`selectMultiple`)).catch(jn)})),this.#u(`Page.frameAttached`,(xn)=>{this.events.emit(`frameattached`,{frameId:xn.frameId,parentFrameId:xn.parentFrameId}).catch(jn)}),this.#u(`Page.frameDetached`,(xn)=>{this.events.emit(`framedetached`,{frameId:xn.frameId}).catch(jn)}),this.#u(`Page.frameNavigated`,(xn)=>{this.events.emit(`framenavigated`,{frameId:xn.frame.id,url:xn.frame.url,name:xn.frame.name??``}).catch(jn)});let Vn=(Vn)=>{xn.has(Vn.guid)||this.frameManager.getFrame(Vn.frameId)&&(xn.add(Vn.guid),this.events.emit(`download`,new OmODownload(this,{guid:Vn.guid,startedAfterMs:Date.now(),suggestedFilename:Vn.suggestedFilename,url:Vn.url})).catch(jn))};this.#a.push(this.cdp.on(`Browser.downloadWillBegin`,(xn)=>Vn(xn))),this.#u(`Page.downloadWillBegin`,(xn)=>{Vn(xn)}),this.#a.push(this.cdp.on(`Page.windowOpen`,(xn,Vn)=>{!Vn.sessionId||!this.frameManager.hasSession(Vn.sessionId)||this.events.emit(`popup`,{url:xn.url,windowName:xn.windowName}).catch(jn)})),this.#u(`Inspector.targetCrashed`,()=>{this.events.emit(`crash`).catch(jn)}),this.frameManager.onSessionInitialized=(xn)=>{this.#c>0&&this.#p(true,[xn])}}#u(xn,jn){this.#a.push(this.cdp.on(xn,(xn,Vn)=>{Vn.sessionId===this.#n&&jn(xn)}))}on(xn,jn){let Vn=this.#e.get(xn)??new WeakMap,qn=this.events.on(xn,({data:xn})=>jn(xn));return Vn.set(jn,qn),this.#e.set(xn,Vn),xn===`filechooser`&&this.#m(),()=>{qn(),Vn.delete(jn),xn===`filechooser`&&this.#h()}}off(xn,jn){let Vn=this.#e.get(xn),qn=Vn?.get(jn);qn?.(),Vn?.delete(jn),qn&&xn===`filechooser`&&this.#h()}async waitForEvent(xn,jn={}){let Vn=jn.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(xn===`download`){let qn=Date.now();return await new Promise((Jn,Yn)=>{let Zn=false,Qn=()=>{ri(),clearTimeout(ni)},ei=(xn)=>{Zn||(Zn=true,Qn(),xn())},ti=(xn)=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>Jn(xn))}catch(xn){ei(()=>Yn(xn instanceof Error?xn:Error(String(xn))))}})()},ni=setTimeout(()=>{ei(()=>Yn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn),ri=this.on(`download`,ti);this.cdp.send(`OmO.waitForDownload`,{startedAfterMs:qn,timeoutMs:Vn},undefined,{extensionBridge:this.browser.extensionBridgeRoute}).then((xn)=>{ti(new OmODownload(this,{guid:String(xn.downloadId),sourcePath:xn.absolutePath,startedAfterMs:qn,suggestedFilename:path.basename(xn.absolutePath),url:this.url()}))}).catch(()=>{})})}return await new Promise((qn,Jn)=>{let Yn=false,Zn=null,Qn=()=>{ni(),clearTimeout(ti),Zn&&clearTimeout(Zn)},ei=(xn)=>{Yn||(Yn=true,Qn(),xn())},ti=setTimeout(()=>{ei(()=>Jn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn);xn===`filechooser`&&Vn>FILECHOOSER_OOPIF_FALLBACK_MS&&(Zn=setTimeout(()=>{Yn||this.#g().then((xn)=>{xn&&!Yn&&ei(()=>qn(xn))})},FILECHOOSER_OOPIF_FALLBACK_MS));let ni=this.on(xn,(xn)=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>qn(xn))}catch(xn){ei(()=>Jn(xn instanceof Error?xn:Error(String(xn))))}})()})})}#d(){for(let xn of this.#a)xn();this.#a=[]}async dispose(){this.#s||(this.#s=true,await this.#o?.stop().catch(()=>{}),this.#d(),this.#c=0,await this.events.emit(`close`),this.events.clearListeners(),this.#e.clear())}reconnect(xn){this.#n=xn,this.#s=false,this.#d(),this.#l(),this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??this.#r,this.#c>0&&this.#p(true)}#f(){return[...new Set([this.#n,...[...this.frameManager.frames.values()].map((xn)=>xn.sessionId)])]}async prepareForPotentialFileChooser(){this.#c!==0&&await this.#p(true)}#p(xn,jn=this.#f()){return withoutReplContext(async()=>{await Promise.allSettled(jn.map((jn)=>this.cdp.send(`Page.setInterceptFileChooserDialog`,{enabled:xn},jn)))})}#m(){this.#c+=1,this.#c===1&&this.#p(true)}#h(){this.#c!==0&&(--this.#c,this.#c===0&&this.#p(false))}async#g(){for(let xn of this.frameManager.frames.values())if(xn.sessionId!==this.#n)try{let{root:jn}=await this.cdp.send(`DOM.getDocument`,{depth:0},xn.sessionId),{nodeIds:Vn}=await this.cdp.send(`DOM.querySelectorAll`,{nodeId:jn.nodeId,selector:`input[type=file]`},xn.sessionId);if(Vn.length===0)continue;let qn=Vn[Vn.length-1],{node:Jn}=await this.cdp.send(`DOM.describeNode`,{nodeId:qn},xn.sessionId),Yn=(Jn.attributes??[]).includes(`multiple`);return new FileChooser(this,xn.frameId,Jn.backendNodeId,Yn)}catch{}return null}async resolveSessionId(xn){if(xn&&this.frameManager.hasSession(xn))return xn;let jn=await this.browser.resolvePageSession(this.targetId,this.#n);return jn!==this.#n&&(this.#n=jn),jn}async goto(xn,jn={}){let Vn=jn.waitUntil??`interactive`,qn=await this.resolveSessionId(this.#n),Jn=()=>{},Yn=Vn===`commit`?null:Vn===`interactive`||Vn===`stable`?waitForNavigationReadiness(this,Vn,DEFAULT_WAIT_TIMEOUT_MS).then(()=>{}):Vn===`networkidle`?this.#S(DEFAULT_WAIT_TIMEOUT_MS):new Promise((xn,jn)=>{let Yn=false,Zn,Qn=()=>{},ei=(xn)=>{Yn||(Yn=true,clearTimeout(Zn),Qn(),xn())};Zn=setTimeout(()=>{ei(()=>jn(Error(`Timed out waiting for "${Vn}" after goto`)))},DEFAULT_WAIT_TIMEOUT_MS);let ti=Vn===`load`?`Page.loadEventFired`:`Page.domContentEventFired`;Qn=this.cdp.on(ti,(jn,Vn)=>{Vn.sessionId===qn&&ei(xn)}),Jn=()=>ei(xn)}),Zn=await this.cdp.send(`Page.navigate`,{url:xn},qn);if(Zn.errorText)throw Error(Zn.errorText);if(this.#r=xn,Vn===`domcontentloaded`&&Yn){if(!Zn.loaderId){Jn(),await this.#v(`Timed out waiting for "${Vn}" after goto`);return}try{await Yn}catch(xn){if(await this.#_())return;throw xn}return}Yn&&await Yn}async goBack(){let xn=await this._sendToTarget(`Page.getNavigationHistory`),jn=xn.currentIndex-1;if(jn<0)return;let Vn=xn.entries[jn];if(!Vn)return;let qn=this.#C();await this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:Vn.id}),await qn}async goForward(){let xn=await this._sendToTarget(`Page.getNavigationHistory`),jn=xn.currentIndex+1;if(jn>=xn.entries.length)return;let Vn=xn.entries[jn];if(!Vn)return;let qn=this.#C();await this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:Vn.id}),await qn}async reload(){let xn=this.#C();await this._sendToTarget(`Page.reload`),await xn}async waitForLoadState(xn=`interactive`,jn=DEFAULT_WAIT_TIMEOUT_MS){if(xn===`interactive`||xn===`stable`){await waitForNavigationReadiness(this,xn,jn);return}if(xn===`networkidle`||xn===`load`){replPrint(`[system] this is redundant wait; openTab() already waits for the page to become usable. Falling back to 'stable' with 5s timeout.`),await waitForNavigationReadiness(this,`stable`,5000).catch(()=>{});return}if(await this.#_())return;let Vn=`Page.domContentEventFired`,qn=await this.resolveSessionId(this.#n);await new Promise((jn,Vn)=>{let Jn=setTimeout(()=>{Yn(),Vn(Error(`Timed out waiting for load state "${xn}"`))},DEFAULT_WAIT_TIMEOUT_MS),Yn=this.cdp.on(`Page.domContentEventFired`,(xn,Vn)=>{Vn.sessionId===qn&&(clearTimeout(Jn),Yn(),jn())})})}async#_(){return await this.evaluate(`document.readyState`).catch(()=>`loading`)!==`loading`}async#v(xn,jn=DEFAULT_WAIT_TIMEOUT_MS){let Vn=Date.now();for(;Date.now()-Vn<jn;){if(await this.#_())return;await sleep$12(50)}throw Error(xn)}async waitForURL(xn,jn={}){let Vn=jn.timeout??DEFAULT_WAIT_TIMEOUT_MS,qn=Date.now();for(;Date.now()-qn<Vn;){let jn=this.url();if(typeof xn==`string`?jn===xn:xn.test(jn))return;await sleep$12(100)}throw Error(`Timed out waiting for URL match: ${String(xn)}`)}async waitForSelector(xn,jn={}){let Vn=jn.state??`visible`,qn=jn.timeout??3000,Jn=[0,20,50,100,100,500],Yn=Date.now(),Zn=0;for(;;){if(Date.now()-Yn>=qn)throw Error(`waitForSelector: timed out after ${qn}ms waiting for "${xn}" to be ${Vn}`);let jn=await this.evaluate((xn)=>{let jn=document.querySelector(xn);if(!jn)return{attached:false,visible:false};let Vn=jn.getBoundingClientRect(),qn=window.getComputedStyle(jn);return{attached:true,visible:qn.visibility!==`hidden`&&qn.display!==`none`&&parseFloat(qn.opacity)!==0&&Vn.width>0&&Vn.height>0}},xn);if(Vn===`attached`?jn.attached:Vn===`detached`?!jn.attached:Vn===`visible`?jn.visible:!jn.visible)return;let Qn=Jn[Math.min(Zn++,Jn.length-1)];await sleep$12(Qn)}}locator(xn,jn={}){return new Locator(this,xn).filter(jn)}async click(xn,jn){await this.locator(xn).click(jn)}async fill(xn,jn){await this.locator(xn).fill(jn)}async $(xn){return replPrint(`warn`,`page.$() is deprecated in OmOWright — use page.locator(selector).first() instead`),this.locator(xn).first()}async $$(xn){return replPrint(`warn`,`page.$$() is deprecated in OmOWright — use page.locator(selector).all() instead`),await this.locator(xn).all()}async $$eval(xn,jn,Vn){return await this.locator(xn).evaluateAll(jn,Vn)}getByRole(xn,jn={}){return new Locator(this,Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`internal:label=/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(xn){return new FrameLocator(this,this.mainFrame(),xn)}async evaluate(xn,jn,Vn){let{actualArg:qn,evaluateOptions:Jn}=resolveEvaluateCall(xn,jn,Vn);if(typeof xn==`string`&&qn===undefined){let{result:jn,exceptionDetails:Vn}=await this._sendToTarget(`Runtime.evaluate`,{expression:xn,returnByValue:true,awaitPromise:true,userGesture:Jn.userGesture});if(Vn)throw Error(formatRuntimeException(Vn,`Evaluation failed`));return jn.value}let Yn=typeof xn==`function`?xn.toString():xn,Zn=await this.#x();try{let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.callFunctionOn`,{objectId:Zn,functionDeclaration:`function(arg) { var __name = (t) => t; return (${Yn})(arg); }`,arguments:[{value:qn}],returnByValue:true,awaitPromise:true,userGesture:Jn.userGesture});if(jn)throw Error(formatRuntimeException(jn,`Evaluation failed`));return xn.value}finally{await this._sendToTarget(`Runtime.releaseObject`,{objectId:Zn}).catch(()=>{})}}async evaluateInFrame(xn,jn,Vn,qn){let Jn=this.frameManager.getFrame(xn);if(!Jn)throw Error(`Frame is not available: ${xn}`);let{actualArg:Yn,evaluateOptions:Zn}=resolveEvaluateCall(jn,Vn,qn),Qn=await this.resolveSessionId(Jn.sessionId);if(typeof jn==`string`&&Yn===undefined){let Vn=await this.frameManager.ensureInjected(xn);if(!Vn)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:qn,exceptionDetails:Jn}=await this.cdp.send(`Runtime.evaluate`,{expression:jn,contextId:Vn,returnByValue:true,awaitPromise:true,userGesture:Zn.userGesture},Qn);if(Jn)throw Error(formatRuntimeException(Jn,`Evaluation failed`));return qn.value}let ei=typeof jn==`function`?jn.toString():jn,ti=await this.frameManager.ensureInjected(xn);if(!ti)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:ni,exceptionDetails:ri}=await this.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(arg) { var __name = (t) => t; return (${ei})(arg); }`,arguments:[{value:Yn}],executionContextId:ti,returnByValue:true,awaitPromise:true,userGesture:Zn.userGesture},Qn);if(ri)throw Error(formatRuntimeException(ri,`Evaluation failed`));return ni.value}async grantNotificationPermission(){await sendCommandToExtension({method:`OmO.grantNotificationPermission`,params:{targetId:this.targetId}},this.browser.extensionBridgeRoute);let xn=new URL(this.#r).origin,jn=this.browser.daemonSession;upsertNotificationGrant({accountId:jn.accountId,origin:xn,grantedBySessionId:jn.id})}url({truncate:xn=false}={}){return xn?truncateUrlForLLM(this.#r):this.#r}async title(){return await this.evaluate(`document.title`).catch(()=>``)}async content(){return await this.evaluate(`document.documentElement.outerHTML`)}async screenshot(xn={}){let jn=normalizeScreenshotTimeout(xn.timeout),Vn=jn&&jn>0?Date.now()+jn:undefined,qn;if(xn.clip)qn={x:xn.clip.x,y:xn.clip.y,width:xn.clip.width,height:xn.clip.height,scale:1};else if(xn.fullPage){let xn=await this._sendToTarget(`Page.getLayoutMetrics`),jn=xn.cssContentSize??xn.contentSize;qn={x:0,y:0,width:jn.width,height:jn.height,scale:1}}qn&&=clampScreenshotClipToTextureLimit(qn,await this.#y());let Jn={format:xn.type??`png`,captureBeyondViewport:!!xn.fullPage,quality:xn.quality,...qn?{clip:qn}:{}},Yn;try{({data:Yn}=await this.#b(Jn,jn,screenshotCaptureLabel(xn)))}catch(jn){if(!xn.fullPage||xn.clip||!isCaptureScreenshotTimeout(jn))throw jn;let qn=Vn?Math.max(0,Vn-Date.now()):undefined;if(qn===0)throw jn;let Jn={format:xn.type??`png`,captureBeyondViewport:false,quality:xn.quality};try{({data:Yn}=await this.#b(Jn,qn,`viewport fallback screenshot`)),replPrint(`[system] full-page screenshot failed; returned viewport fallback. ${formatScreenshotError(jn)}`)}catch(xn){throw Error(`${formatScreenshotError(jn)}-Viewport fallback also failed: ${formatScreenshotError(xn)}`)}}let Zn=Buffer.from(Yn,`base64`);if(xn.path)if(xn.path.startsWith(`/tmp`)){let jn=this.browser.resolvePath(`tmp`),Vn=path.join(jn,path.basename(xn.path));await mkdir(path.dirname(Vn),{recursive:true}),await writeFile(Vn,Zn),replPrint(`[WARN] Use ${jn} instead of /tmp. Saved it to ${Vn}`)}else{let jn=this.browser.resolvePath(xn.path);await mkdir(path.dirname(jn),{recursive:true}),await writeFile(jn,Zn)}return Zn}async#y(){return await this.evaluate(`window.devicePixelRatio`).catch(()=>1)}async#b(xn,jn,Vn){try{return await this._sendToTarget(`Page.captureScreenshot`,xn,{timeoutMs:jn})}catch(xn){throw rewriteCaptureScreenshotError(xn,jn,Vn)}}async snapshot(xn={}){return await takeSnapshot(this.cdp,this.frameManager,xn)}frames(){return this.frameManager.collectDescendantFrames(this.frameManager.mainFrameId).map(({frameId:xn})=>new OmOFrame(this,xn))}mainFrame(){let xn=this.frameManager.getFrame(this.frameManager.mainFrameId);if(!xn)throw Error(`Main frame is not available`);return new OmOFrame(this,xn.frameId)}async bringToFront(){this.browser.page=this,replPrint(`page is now [${await this.title().catch(()=>``)}](${this.url()})`)}async openPopupUrl(xn){await this.browser.openPopupTab(xn,this.targetId)}get console(){return this.#t??=new PageConsole(this)}video(){return this.#w()}viewportSize(){return this.#i?{...this.#i}:null}async refreshViewportSize(){let xn=await this.evaluate(()=>({width:Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0),height:Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0)}));if(xn.width<=0||xn.height<=0)throw Error(`Measured viewport size is invalid: ${JSON.stringify(xn)}`);return this.#i=xn,xn}setCachedViewportSize(xn){this.#i=xn?{...xn}:null}async pdf(xn={}){let jn=xn.path?await this.browser.ensurePath(xn.path,`write`,`page.pdf`):undefined,Vn={...xn,height:formatPdfLength(xn.height),margin:xn.margin?{bottom:formatPdfLength(xn.margin.bottom),left:formatPdfLength(xn.margin.left),right:formatPdfLength(xn.margin.right),top:formatPdfLength(xn.margin.top)}:undefined,printBackground:xn.printBackground??true,transferMode:`ReturnAsBase64`,width:formatPdfLength(xn.width)},{data:qn}=await this._sendToTarget(`Page.printToPDF`,Vn),Jn=Buffer.from(qn,`base64`);return jn&&(await mkdir(path.dirname(jn),{recursive:true}).catch(()=>{}),await writeFile(jn,Jn)),Jn}async close(xn={}){if(await this.#w().stop().catch(()=>{}),xn.runBeforeUnload){let jn=await this.resolveSessionId(this.#n);await this.cdp.send(`Page.close`,undefined,jn).catch(async()=>{await this.browser.closeTab(this,xn)});return}await this.browser.closeTab(this,xn)}async#x(){let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.evaluate`,{expression:`globalThis`,serializationOptions:{serialization:`idOnly`}});if(jn)throw Error(formatRuntimeException(jn,`Failed to resolve main world`));if(!xn.objectId)throw Error(`Main world object is not available`);return xn.objectId}async#S(xn){await this._sendToTarget(`Network.enable`).catch(()=>{});let jn=await this.resolveSessionId(this.#n);await new Promise((Vn,qn)=>{let Jn=new Set,Yn=null,Zn=null,Qn=()=>{ti(),ri(),ii(),Yn&&=(clearTimeout(Yn),null),Zn&&=(clearTimeout(Zn),null)},ei=()=>{Yn&&clearTimeout(Yn),Jn.size===0&&(Yn=setTimeout(()=>{Qn(),Vn()},NETWORK_IDLE_MS))},ti=this.cdp.on(`Network.requestWillBeSent`,(xn,Vn)=>{Vn.sessionId===jn&&(xn.request.url.startsWith(`data:`)||Jn.add(xn.requestId))}),ni=(xn)=>{Jn.delete(xn),ei()},ri=this.cdp.on(`Network.loadingFinished`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)}),ii=this.cdp.on(`Network.loadingFailed`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)});Zn=setTimeout(()=>{Qn(),qn(Error(`Timed out waiting for load state "networkidle"`))},xn),ei()})}async#C(){let xn=await this.resolveSessionId(this.#n);await new Promise((jn,Vn)=>{let qn=setTimeout(()=>{Jn(),Vn(Error(`Timed out waiting for navigation`))},DEFAULT_WAIT_TIMEOUT_MS),Jn=this.cdp.on(`Page.frameNavigated`,(Vn,Yn)=>{Yn.sessionId===xn&&(Vn.frame.parentId||(clearTimeout(qn),Jn(),jn()))})})}async _sendToTarget(xn,jn,Vn={}){if(this.#s)throw Error(`Page ${this.targetId} is disposed`);let{preferredSessionId:qn,...Jn}=Vn;if(qn!==undefined){if(!this.frameManager.hasSession(qn))throw Error(`Frame is stale or detached: CDP session ${qn} is unavailable`);return await this.cdp.send(xn,jn,qn,Jn)}let Yn=await this.resolveSessionId(this.#n);return await this.cdp.send(xn,jn,Yn,Jn)}#w(){return this.#o??=new OmOVideo(this),this.#o}}});init_client$6();init_session_manager();init_frame_manager();init_page();class TabRepository{#client;constructor(client){this.#client=client}async listTargets(){return this.#client.discoverTargets()}}class BrowserConnection{#client;#sessions;#pages=new Map;#storageRoot;constructor(client,options={}){this.#client=client;this.#sessions=new SessionManager(client);this.tabs=new TabRepository(client);this.#storageRoot=path2.resolve(options.storageRoot??process.cwd())}async initialize(){await this.#client.ensureConnected();return this}get cdp(){return this.#client}setDialogPolicy(policy){if(typeof this.#client.setDialogPolicy!=="function"){throw new Error("dialog policy is not supported by this transport")}this.#client.setDialogPolicy(policy)}async listTargets(){return this.tabs.listTargets()}async attachPage(targetId){if(this.#pages.has(targetId))return this.#pages.get(targetId).page;const sessionId=await this.#sessions.resolvePageSession(targetId);const frames=new FrameManager(this.#client,targetId,sessionId);await frames.initialize();const entry={frames,page:null};const host=this.#createPageHost(targetId,entry);const page=new OmOPage(this.#client,frames,targetId,sessionId,host);entry.page=page;this.#pages.set(targetId,entry);return page}#createPageHost(targetId,entry){return{daemonSession:{accountId:0,id:"standalone"},extensionBridgeRoute:{},page:null,resolvePageSession:(id,preferred)=>this.#sessions.resolvePageSession(id,preferred),resolvePath:(value)=>path2.resolve(this.#storageRoot,value),ensurePath:async(value)=>{const resolved=path2.resolve(this.#storageRoot,value);await mkdir2(path2.dirname(resolved),{recursive:true});return resolved},registerReadableDownload:(value)=>value,isReadableDownload:()=>false,openPopupTab:async()=>{throw Error("Popup tab control requires the extension bridge")},closeTab:async(_page,options={})=>{if(options.runBeforeUnload){await this.#client.send("Page.close",undefined,await this.#sessions.resolvePageSession(targetId))}else{await this.#client.send("Target.closeTarget",{targetId})}await entry.page?.dispose();await entry.frames.dispose();this.#pages.delete(targetId)}}}async close(){for(const[targetId,entry]of[...this.#pages]){await entry.page.dispose().catch(()=>{});await entry.frames.dispose().catch(()=>{});this.#pages.delete(targetId)}await this.#sessions.dispose();await this.#client.close()}}async function connect(cdpHttpUrl,options={}){if(typeof cdpHttpUrl!=="string"||cdpHttpUrl.length===0){throw new TypeError("connect(cdpHttpUrl) requires a Chromium CDP HTTP URL")}const client=new CdpClient({cdpUrl:cdpHttpUrl,...options.client});return new BrowserConnection(client,options).initialize()}import{spawn}from"node:child_process";function normalizeDialogPolicy(policy){return policy??{accept:true}}function dialogFromOpening(params={}){return{type:params.type,message:params.message,defaultPrompt:params.defaultPrompt??"",url:params.url}}function decisionFromResult(result){if(typeof result==="boolean")return{accept:result};if(result&&typeof result==="object"){const decision={accept:result.accept!==false};if(result.promptText!==undefined)decision.promptText=result.promptText;return decision}return{accept:true}}async function resolveDialogAction(policy,params={}){try{const result=typeof policy==="function"?await policy(dialogFromOpening(params)):policy;return decisionFromResult(result)}catch{return{accept:true}}}init_internal_capability();class Emittery2{#listeners=new Map;on(event,fn){const list=this.#listeners.get(event)??[];list.push(fn);this.#listeners.set(event,list);return()=>{const cur=this.#listeners.get(event)??[];this.#listeners.set(event,cur.filter((f)=>f!==fn))}}async emit(event,data){for(const fn of this.#listeners.get(event)??[])await fn(data)}}var DEFAULT_COMMAND_TIMEOUT_MS2=30000;var DEFAULT_READINESS_TIMEOUT_MS=1e4;var GRACEFUL_CLOSE_TIMEOUT_MS=2000;var STDIO_TAIL_LIMIT=16384;class PipeCdpClient{#child;#writeStream;#readStream;#buffer=Buffer.alloc(0);#seq=1;#pending=new Map;#events=new Emittery2;#connected=false;#commandTimeoutMs;#readinessTimeoutMs;#browserPath;#browserArgs;#spawnOptions;#stdioTail="";#dialogPolicy;transportEvents=new Emittery2;logId;constructor({browserPath,browserArgs=[],spawnOptions={},commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy}){if(!browserPath)throw new TypeError("PipeCdpClient requires browserPath");this.#browserPath=browserPath;this.#browserArgs=browserArgs;this.#spawnOptions=spawnOptions;this.#commandTimeoutMs=commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS2;this.#readinessTimeoutMs=readinessTimeoutMs??DEFAULT_READINESS_TIMEOUT_MS;this.logId=logId??`cdp-pipe-${Date.now()}`;this.#dialogPolicy=normalizeDialogPolicy(dialogPolicy)}get isConnected(){return this.#connected}get isHeadless(){return this.#browserArgs.some((arg)=>/^--headless(?:=|$)/.test(arg))}get childProcess(){return this.#child}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(policy){this.#dialogPolicy=normalizeDialogPolicy(policy)}async ensureConnected(){if(this.#connected)return;const stdio=["ignore","pipe","pipe","pipe","pipe"];this.#child=spawn(this.#browserPath,[...this.#browserArgs,"--remote-debugging-pipe"],{...this.#spawnOptions,stdio});this.#stdioTail="";for(const stream of[this.#child.stdout,this.#child.stderr]){if(!stream)continue;stream.setEncoding("utf8");stream.on("data",(chunk)=>{this.#stdioTail=(this.#stdioTail+chunk).slice(-STDIO_TAIL_LIMIT)});stream.on("error",()=>{})}this.#writeStream=this.#child.stdio[3];this.#readStream=this.#child.stdio[4];this.#readStream.on("data",(chunk)=>this.#onData(chunk));for(const stream of[this.#writeStream,this.#readStream]){stream.on("error",(error)=>this.#failAll(Error(`CDP pipe error: ${error.code??error.message}`)))}this.#child.on("exit",()=>{this.#connected=false;this.#failAll(Error("CDP pipe browser exited"));this.transportEvents.emit("disconnected").catch(()=>{})});this.#connected=true;await this.#awaitReady();await this.send("Target.setDiscoverTargets",{discover:true}).catch(()=>{});await this.transportEvents.emit("connected")}async#awaitReady(){const deadline=Date.now()+this.#readinessTimeoutMs;let lastError;while(Date.now()<deadline){try{await this.send("Browser.getVersion",undefined,undefined,{timeoutMs:1000});return}catch(error){lastError=error;await new Promise((resolve)=>setTimeout(resolve,100))}}const reason=lastError?String(lastError.message??lastError):"no response";const tail=this.#stdioTail.trim();throw Error(`Browser did not become ready over the CDP pipe (${reason})`+(tail?`+ }`,arguments:[{value:qn}],executionContextId:Jn.isolatedContextId,returnByValue:false},Jn.sessionId).catch((xn)=>(isContextDestroyedError(xn)&&jn.invalidateContext(Vn),{result:{}})),Zn=typeof Yn==`object`&&Yn&&`objectId`in Yn?Yn.objectId:undefined;if(!Zn)return null;try{let{node:Vn}=await xn.send(`DOM.describeNode`,{objectId:Zn},Jn.sessionId),Yn=Vn.frameId?jn.getFrame(Vn.frameId)?.url:null,Qn=getCdpNodeAttribute(Vn.attributes,`src`),ei=getKnownIframeOriginLabel(Yn??``)??getKnownIframeOriginLabel(Qn??``);return{childFrameId:Vn.frameId,iframeRef:qn,originLabel:ei}}catch{return null}finally{await xn.send(`Runtime.releaseObject`,{objectId:Zn},Jn.sessionId).catch(()=>{})}})),Qn=new Map,ei=new Map;for(let xn of Zn)xn&&(xn.childFrameId&&Qn.set(xn.childFrameId,xn.iframeRef),xn.originLabel&&ei.set(xn.iframeRef,xn.originLabel));ai.set(Vn,Qn),ei.size>0&&oi.set(Vn,ei)}));let si=[...ti].sort((xn,jn)=>jn.depth-xn.depth),ci={};for(let xn of ni.values())Object.assign(ci,xn.refs);for(let[xn,jn]of oi){let Vn=ni.get(xn);if(Vn)for(let[xn,qn]of jn)Vn.tree=tagIframeLine(Vn.tree,xn,qn)}for(let xn of si){if(xn.frameId===qn||!xn.parentFrameId)continue;let Vn=ni.get(xn.frameId),Jn=ni.get(xn.parentFrameId);if(!Vn||!Jn||!Vn.tree)continue;let Yn=ai.get(xn.parentFrameId)?.get(xn.frameId),Zn=getKnownIframeOriginLabel(jn.getFrame(xn.frameId)?.url??``);Jn.tree=Yn?inlineChildTree(Jn.tree,Yn,Vn.tree):appendOrphanChildTree(Jn.tree,Vn.tree,Zn)}return{tree:ii.tree,refs:ci}}var KNOWN_IFRAME_ORIGINS;var SNAPSHOT_RETRY_DELAY_MS;var SNAPSHOT_MAX_RETRIES;var init_snapshot=__esmMin(()=>{init_extension_ids(),init_utils$13(),init_client$6(),init_frame_manager(),KNOWN_IFRAME_ORIGINS=[{urlPrefix:`chrome-extension://aeblfdkhhhdcdjpifhhbdiojplfjncoa/`,label:`1Password`},{urlPrefix:`chrome-extension://nngceckbapebfimnlniiiahkandclblb/`,label:`Bitwarden`},{urlPrefix:`chrome-extension://fdjamakpfbbddfjaooikfcpapjohcfmg/`,label:`Dashlane`},{urlPrefix:`chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/`,label:`LastPass`},{urlPrefix:`${PASSWORD_MANAGER_EXTENSION_ORIGIN}/`,label:`OmO Password Manager`}],SNAPSHOT_RETRY_DELAY_MS=300,SNAPSHOT_MAX_RETRIES=3});var formatRange;var init_diff=__esmMin(()=>{formatRange=(xn,jn)=>jn===1?String(xn):`${xn},${jn}`});var init_session_tab_queries=__esmMin(()=>{init_drizzle_orm(),init_event_bus(),init_extension_bridge(),init_schema(),init_state_db(),init_nanoid(),init_utils$13(),init_store$1()});var ANNOTATION_OVERLAY_ID;var init_annotate_screenshot=__esmMin(()=>{ANNOTATION_OVERLAY_ID=`__omowright_annotations__`});var AI_TAB_STABLE_VIEWPORT;var MIN_STABLE_AI_TAB_VIEWPORT;var init_browser=__esmMin(()=>{init_context(),init_cdp(),init_directory(),init_event_bus(),init_extension_bridge(),init_diff(),init_utils$13(),init_session_tab_queries(),init_store$1(),init_types$8(),init_utils$4(),init_annotate_screenshot(),init_frame_manager(),init_page(),init_snapshot(),AI_TAB_STABLE_VIEWPORT={width:1440,height:900},MIN_STABLE_AI_TAB_VIEWPORT={width:960,height:540}});function defaultVideoSize(xn){let jn=Math.min(1,DEFAULT_VIDEO_MAX_EDGE/xn.width,DEFAULT_VIDEO_MAX_EDGE/xn.height),Vn=Math.max(2,Math.round(xn.width*jn)),qn=Math.max(2,Math.round(xn.height*jn));return{height:qn%2==0?qn:qn+1,width:Vn%2==0?Vn:Vn+1}}function inferVideoFormat(xn){return xn.format?xn.format:xn.path?.toLowerCase().endsWith(`.mp4`)?`mp4`:DEFAULT_VIDEO_FORMAT}async function ensureDirForFile(xn){await fs$16.mkdir(path.dirname(xn),{recursive:true})}async function readProcessStderr(xn){return await readProcessStream(xn.stderr).catch(()=>``)}var DEFAULT_VIDEO_FORMAT;var DEFAULT_VIDEO_FRAMERATE;var DEFAULT_VIDEO_JPEG_QUALITY;var DEFAULT_VIDEO_MAX_EDGE;var FfmpegVideoRecorder;var OmOVideo;var init_video=__esmMin(()=>{init_context(),init_process(),init_browser(),DEFAULT_VIDEO_FORMAT=`webm`,DEFAULT_VIDEO_FRAMERATE=25,DEFAULT_VIDEO_JPEG_QUALITY=90,DEFAULT_VIDEO_MAX_EDGE=800,FfmpegVideoRecorder=class{#e;#t;#n=0;#r=false;#i=null;#a=Promise.resolve();#o=0;#s=[];constructor(xn,jn,Vn,qn){this.#e=Vn;let Jn=qn===`mp4`?[`-c:v`,`libx264`,`-movflags`,`+faststart`]:[`-c:v`,`libvpx`,`-qmin`,`0`,`-qmax`,`50`,`-crf`,`8`,`-deadline`,`realtime`,`-speed`,`8`,`-b:v`,`1M`];this.#t=spawnCommand([`ffmpeg`,`-loglevel`,`error`,`-f`,`image2pipe`,`-avioflags`,`direct`,`-fpsprobesize`,`0`,`-probesize`,`32`,`-analyzeduration`,`0`,`-c:v`,`mjpeg`,`-i`,`pipe:0`,`-y`,`-an`,`-r`,String(Vn),...Jn,`-threads`,`1`,`-vf`,`scale=${jn.width}:${jn.height}:force_original_aspect_ratio=decrease,pad=${jn.width}:${jn.height}:(ow-iw)/2:(oh-ih)/2:gray`,`-pix_fmt`,`yuv420p`,xn],{stdio:[`pipe`,`ignore`,`pipe`]})}writeFrame(xn,jn){if(this.#r)return;this.#n||=jn;let Vn=Math.floor((jn-this.#n)*this.#e);if(this.#i){let xn=Vn-this.#i.frameNumber;for(let jn=0;jn<xn;jn+=1)this.#s.push(this.#i.buffer);this.#a=this.#a.then(()=>this.#c())}this.#i={buffer:xn,frameNumber:Vn,timestamp:jn},this.#o=Date.now()}async stop(xn){if(this.#r)return;if(!this.#i){if(!xn)throw Error(`Video recorder did not capture any frames.`);this.writeFrame(xn,Date.now()/1000)}let jn=this.#i;if(!jn)throw Error(`Video recorder did not capture any frames.`);let Vn=Math.max((Date.now()-this.#o)/1000,1);if(this.writeFrame(Buffer.from([]),jn.timestamp+Vn),this.#r=true,await withCurrentReplAbort(async()=>await this.#a),!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let qn=this.#t.stdin;await withCurrentReplAbort(async()=>await endProcessInput(qn));let Jn=await withCurrentReplAbort(async()=>await waitForExitCode(this.#t));if(Jn!==0){let xn=await readProcessStderr(this.#t);throw Error(xn.trim()||`ffmpeg exited with code ${Jn}`)}}async#c(){if(!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let xn=this.#t.stdin;for(;this.#s.length>0;){let jn=this.#s.shift();if(!(!jn||jn.length===0))try{await withCurrentReplAbort(async()=>await writeProcessChunk(xn,jn))}catch(xn){let jn=(await readProcessStderr(this.#t)).trim();throw Error(jn.length>0?`ffmpeg rejected video frame input: ${jn}`:xn instanceof Error?xn.message:String(xn))}}}},OmOVideo=class{#e;#t=null;#n=null;constructor(xn){this.#e=xn}async start(xn={}){return await withCurrentReplAbort(async()=>{if(this.#t)throw Error(`Video recording is already active.`);let jn=await this.#e.resolveSessionId(),Vn=this.#e.viewportSize()??await this.#e.refreshViewportSize().catch(()=>null)??AI_TAB_STABLE_VIEWPORT,qn=inferVideoFormat(xn),Jn=xn.size??defaultVideoSize(Vn),Yn=await this.#e.browser.ensurePath(xn.path??`video-${Date.now()}.${qn}`,`write`,`page.video.start`),Zn=xn.quality??DEFAULT_VIDEO_JPEG_QUALITY,Qn=xn.framerate??DEFAULT_VIDEO_FRAMERATE;await ensureDirForFile(Yn);let ei=new FfmpegVideoRecorder(Yn,Jn,Qn,qn),{promise:ti,resolve:ni,reject:ri}=Promise.withResolvers(),ii=this.#e.cdp.on(`Page.screencastFrame`,(xn,Vn)=>{if(Vn.sessionId!==jn)return;let qn=Buffer.from(xn.data,`base64`),Jn=xn.metadata?.timestamp??Date.now()/1000;ei.writeFrame(qn,Jn),this.#e.cdp.send(`Page.screencastFrameAck`,{sessionId:xn.sessionId},jn).catch(()=>{})});this.#t={completion:ti,format:qn,outputPath:Yn,pendingCopies:new Set,recorder:ei,rejectCompletion:ri,resolveCompletion:ni,sessionId:jn,unsubscribe:ii},this.#n=Yn;try{await this.#e.cdp.send(`Page.startScreencast`,{everyNthFrame:1,format:`jpeg`,maxHeight:Jn.height,maxWidth:Jn.width,quality:Zn},jn)}catch(xn){throw ii(),this.#t=null,this.#n=null,ri(xn),xn}})}async stop(xn={}){return await withCurrentReplAbort(async()=>{let jn=this.#t;if(!jn)throw Error(`Video recording has not been started.`);this.#t=null,jn.unsubscribe(),await this.#e.cdp.send(`Page.stopScreencast`,undefined,jn.sessionId).catch(()=>{});try{let Vn=await this.#e.screenshot({type:`jpeg`}).catch(()=>{return}),qn=xn.path?await this.#e.browser.ensurePath(xn.path,`write`,`page.video.stop`):jn.outputPath;await jn.recorder.stop(Vn),qn!==jn.outputPath&&(await ensureDirForFile(qn),await fs$16.copyFile(jn.outputPath,qn)),this.#n=qn;for(let xn of jn.pendingCopies){let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);jn!==qn&&(await ensureDirForFile(jn),await fs$16.copyFile(qn,jn))}jn.resolveCompletion(qn)}catch(xn){throw jn.rejectCompletion(xn),xn}})}async path(){if(this.#t)return this.#t.outputPath;if(this.#n)return this.#n;throw Error(`Video recording has not been started.`)}async saveAs(xn){return await withCurrentReplAbort(async()=>{let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);if(this.#t){this.#t.pendingCopies.add(xn),await this.#t.completion;return}if(!this.#n)throw Error(`Video recording has not been started.`);await ensureDirForFile(jn),await fs$16.copyFile(this.#n,jn)})}async delete(){return await withCurrentReplAbort(async()=>{if(this.#t&&await this.stop(),!this.#n)throw Error(`Video recording has not been started.`);let xn=this.#n;this.#n=null,await fs$16.unlink(xn).catch(()=>{})})}}});function isOmOEvaluateOptions(xn){if(typeof xn!=`object`||!xn||Array.isArray(xn))return false;let jn=Object.keys(xn);return jn.length===1&&jn[0]===`userGesture`}function resolveEvaluateCall(xn,jn,Vn){if(Vn!==undefined&&!isOmOEvaluateOptions(Vn))throw Error(`page.evaluate() accepts a single optional argument. Pass multiple values as one object or array, e.g. page.evaluate(fn, [a, b]).`);return typeof xn==`string`&&isOmOEvaluateOptions(jn)?{actualArg:undefined,evaluateOptions:jn}:{actualArg:jn,evaluateOptions:Vn??{}}}function clampScreenshotClipToTextureLimit(xn,jn){let Vn=Math.max(1,Math.floor(MAX_SCREENSHOT_TEXTURE_SIZE/(Number.isFinite(jn)&&jn>0?jn:1)));return{...xn,width:Math.max(1,Math.min(xn.width,Vn)),height:Math.max(1,Math.min(xn.height,Vn))}}function normalizeScreenshotTimeout(xn){if(xn!==undefined){if(!Number.isFinite(xn)||xn<0)throw Error(`page.screenshot: timeout must be a non-negative number`);return xn}}function screenshotCaptureLabel(xn){return xn.clip?`clipped screenshot`:xn.fullPage?`full-page screenshot`:`viewport screenshot`}function formatScreenshotError(xn){return xn instanceof Error?xn.message:String(xn)}function rewriteCaptureScreenshotError(xn,jn,Vn){let qn=formatScreenshotError(xn);if(qn!==`CDP command timeout: Page.captureScreenshot`)return xn instanceof Error?xn:Error(qn);let Jn=jn===undefined?`the default screenshot timeout`:jn===0?`a disabled page.screenshot timeout`:`the requested ${jn}ms page.screenshot timeout`;return Error(`page.screenshot: browser CDP command timed out while capturing ${Vn} before ${Jn} completed`)}function isCaptureScreenshotTimeout(xn){let jn=formatScreenshotError(xn);return jn===`CDP command timeout: Page.captureScreenshot`||jn.startsWith(`page.screenshot: browser CDP command timed out while capturing `)}function formatPdfLength(xn){if(xn!==undefined)return typeof xn==`number`?`${xn}px`:xn}var DEFAULT_WAIT_TIMEOUT_MS;var NETWORK_IDLE_MS;var MAX_SCREENSHOT_TEXTURE_SIZE;var FILECHOOSER_OOPIF_FALLBACK_MS;var OmOPage;var init_page=__esmMin(()=>{init_emittery(),init_context(),init_extension_bridge(),init_notification_grants(),init_utils$13(),init_client$6(),init_errors$3(),init_utils$4(),init_console_capture(),init_download(),init_file_chooser(),init_frame(),init_frame_manager(),init_keyboard(),init_locator(),init_mouse(),init_snapshot(),init_video(),init_wait(),DEFAULT_WAIT_TIMEOUT_MS=30000,NETWORK_IDLE_MS=500,MAX_SCREENSHOT_TEXTURE_SIZE=16384,FILECHOOSER_OOPIF_FALLBACK_MS=2000,OmOPage=class{cdp;frameManager;targetId;modifierState;mouse;keyboard;events=new Emittery;browser;#e=new Map;#t=null;#n;#r=``;#i=null;#a=[];#o=null;#s=false;#c=0;constructor(xn,jn,Vn,qn,Jn){this.cdp=xn,this.frameManager=jn,this.targetId=Vn,this.modifierState=new ModifierState,this.mouse=new OmOMouse(this,this.modifierState),this.keyboard=new OmOKeyboard(this,this.modifierState),this.browser=Jn,this.#n=qn,this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??``,this.#l()}#l(){let xn=new Set,jn=(xn)=>{replPrint(`[error] page event listener threw: ${xn instanceof Error?xn.message:xn}`)};this.#u(`Page.frameNavigated`,(xn)=>{xn.frame.parentId||(this.#r=xn.frame.url)}),this.#u(`Page.loadEventFired`,()=>{this.events.emit(`load`).catch(jn)}),this.#u(`Page.domContentEventFired`,()=>{this.events.emit(`domcontentloaded`).catch(jn)}),this.#u(`Page.javascriptDialogOpening`,(xn)=>{this.events.emit(`dialog`,{type:xn.type,message:xn.message,defaultPrompt:xn.defaultPrompt??``,url:xn.url}).catch(jn)}),this.#a.push(this.cdp.on(`Page.fileChooserOpened`,(xn,Vn)=>{!Vn.sessionId||!xn.backendNodeId||this.events.emit(`filechooser`,new FileChooser(this,xn.frameId,xn.backendNodeId,xn.mode===`selectMultiple`)).catch(jn)})),this.#u(`Page.frameAttached`,(xn)=>{this.events.emit(`frameattached`,{frameId:xn.frameId,parentFrameId:xn.parentFrameId}).catch(jn)}),this.#u(`Page.frameDetached`,(xn)=>{this.events.emit(`framedetached`,{frameId:xn.frameId}).catch(jn)}),this.#u(`Page.frameNavigated`,(xn)=>{this.events.emit(`framenavigated`,{frameId:xn.frame.id,url:xn.frame.url,name:xn.frame.name??``}).catch(jn)});let Vn=(Vn)=>{xn.has(Vn.guid)||this.frameManager.getFrame(Vn.frameId)&&(xn.add(Vn.guid),this.events.emit(`download`,new OmODownload(this,{guid:Vn.guid,startedAfterMs:Date.now(),suggestedFilename:Vn.suggestedFilename,url:Vn.url})).catch(jn))};this.#a.push(this.cdp.on(`Browser.downloadWillBegin`,(xn)=>Vn(xn))),this.#u(`Page.downloadWillBegin`,(xn)=>{Vn(xn)}),this.#a.push(this.cdp.on(`Page.windowOpen`,(xn,Vn)=>{!Vn.sessionId||!this.frameManager.hasSession(Vn.sessionId)||this.events.emit(`popup`,{url:xn.url,windowName:xn.windowName}).catch(jn)})),this.#u(`Inspector.targetCrashed`,()=>{this.events.emit(`crash`).catch(jn)}),this.frameManager.onSessionInitialized=(xn)=>{this.#c>0&&this.#p(true,[xn])}}#u(xn,jn){this.#a.push(this.cdp.on(xn,(xn,Vn)=>{Vn.sessionId===this.#n&&jn(xn)}))}on(xn,jn){let Vn=this.#e.get(xn)??new WeakMap,qn=this.events.on(xn,({data:xn})=>jn(xn));return Vn.set(jn,qn),this.#e.set(xn,Vn),xn===`filechooser`&&this.#m(),()=>{qn(),Vn.delete(jn),xn===`filechooser`&&this.#h()}}off(xn,jn){let Vn=this.#e.get(xn),qn=Vn?.get(jn);qn?.(),Vn?.delete(jn),qn&&xn===`filechooser`&&this.#h()}async waitForEvent(xn,jn={}){let Vn=jn.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(xn===`download`){let qn=Date.now();return await new Promise((Jn,Yn)=>{let Zn=false,Qn=()=>{ri(),clearTimeout(ni)},ei=(xn)=>{Zn||(Zn=true,Qn(),xn())},ti=(xn)=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>Jn(xn))}catch(xn){ei(()=>Yn(xn instanceof Error?xn:Error(String(xn))))}})()},ni=setTimeout(()=>{ei(()=>Yn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn),ri=this.on(`download`,ti);this.cdp.send(`OmO.waitForDownload`,{startedAfterMs:qn,timeoutMs:Vn},undefined,{extensionBridge:this.browser.extensionBridgeRoute}).then((xn)=>{ti(new OmODownload(this,{guid:String(xn.downloadId),sourcePath:xn.absolutePath,startedAfterMs:qn,suggestedFilename:path.basename(xn.absolutePath),url:this.url()}))}).catch(()=>{})})}return await new Promise((qn,Jn)=>{let Yn=false,Zn=null,Qn=()=>{ni(),clearTimeout(ti),Zn&&clearTimeout(Zn)},ei=(xn)=>{Yn||(Yn=true,Qn(),xn())},ti=setTimeout(()=>{ei(()=>Jn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn);xn===`filechooser`&&Vn>FILECHOOSER_OOPIF_FALLBACK_MS&&(Zn=setTimeout(()=>{Yn||this.#g().then((xn)=>{xn&&!Yn&&ei(()=>qn(xn))})},FILECHOOSER_OOPIF_FALLBACK_MS));let ni=this.on(xn,(xn)=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>qn(xn))}catch(xn){ei(()=>Jn(xn instanceof Error?xn:Error(String(xn))))}})()})})}#d(){for(let xn of this.#a)xn();this.#a=[]}async dispose(){this.#s||(this.#s=true,await this.#o?.stop().catch(()=>{}),this.#d(),this.#c=0,await this.events.emit(`close`),this.events.clearListeners(),this.#e.clear())}reconnect(xn){this.#n=xn,this.#s=false,this.#d(),this.#l(),this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??this.#r,this.#c>0&&this.#p(true)}#f(){return[...new Set([this.#n,...[...this.frameManager.frames.values()].map((xn)=>xn.sessionId)])]}async prepareForPotentialFileChooser(){this.#c!==0&&await this.#p(true)}#p(xn,jn=this.#f()){return withoutReplContext(async()=>{await Promise.allSettled(jn.map((jn)=>this.cdp.send(`Page.setInterceptFileChooserDialog`,{enabled:xn},jn)))})}#m(){this.#c+=1,this.#c===1&&this.#p(true)}#h(){this.#c!==0&&(--this.#c,this.#c===0&&this.#p(false))}async#g(){for(let xn of this.frameManager.frames.values())if(xn.sessionId!==this.#n)try{let{root:jn}=await this.cdp.send(`DOM.getDocument`,{depth:0},xn.sessionId),{nodeIds:Vn}=await this.cdp.send(`DOM.querySelectorAll`,{nodeId:jn.nodeId,selector:`input[type=file]`},xn.sessionId);if(Vn.length===0)continue;let qn=Vn[Vn.length-1],{node:Jn}=await this.cdp.send(`DOM.describeNode`,{nodeId:qn},xn.sessionId),Yn=(Jn.attributes??[]).includes(`multiple`);return new FileChooser(this,xn.frameId,Jn.backendNodeId,Yn)}catch{}return null}async resolveSessionId(xn){if(xn&&this.frameManager.hasSession(xn))return xn;let jn=await this.browser.resolvePageSession(this.targetId,this.#n);return jn!==this.#n&&(this.#n=jn),jn}async goto(xn,jn={}){let Vn=jn.waitUntil??`interactive`,qn=await this.resolveSessionId(this.#n),Jn=()=>{},Yn=Vn===`commit`?null:Vn===`interactive`||Vn===`stable`?waitForNavigationReadiness(this,Vn,DEFAULT_WAIT_TIMEOUT_MS).then(()=>{}):Vn===`networkidle`?this.#S(DEFAULT_WAIT_TIMEOUT_MS):new Promise((xn,jn)=>{let Yn=false,Zn,Qn=()=>{},ei=(xn)=>{Yn||(Yn=true,clearTimeout(Zn),Qn(),xn())};Zn=setTimeout(()=>{ei(()=>jn(Error(`Timed out waiting for "${Vn}" after goto`)))},DEFAULT_WAIT_TIMEOUT_MS);let ti=Vn===`load`?`Page.loadEventFired`:`Page.domContentEventFired`;Qn=this.cdp.on(ti,(jn,Vn)=>{Vn.sessionId===qn&&ei(xn)}),Jn=()=>ei(xn)}),Zn=await this.cdp.send(`Page.navigate`,{url:xn},qn);if(Zn.errorText)throw Error(Zn.errorText);if(this.#r=xn,Vn===`domcontentloaded`&&Yn){if(!Zn.loaderId){Jn(),await this.#v(`Timed out waiting for "${Vn}" after goto`);return}try{await Yn}catch(xn){if(await this.#_())return;throw xn}return}Yn&&await Yn}async goBack(){let xn=await this._sendToTarget(`Page.getNavigationHistory`),jn=xn.currentIndex-1;if(jn<0)return;let Vn=xn.entries[jn];if(!Vn)return;let qn=this.#C();await this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:Vn.id}),await qn}async goForward(){let xn=await this._sendToTarget(`Page.getNavigationHistory`),jn=xn.currentIndex+1;if(jn>=xn.entries.length)return;let Vn=xn.entries[jn];if(!Vn)return;let qn=this.#C();await this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:Vn.id}),await qn}async reload(){let xn=this.#C();await this._sendToTarget(`Page.reload`),await xn}async waitForLoadState(xn=`interactive`,jn=DEFAULT_WAIT_TIMEOUT_MS){if(xn===`interactive`||xn===`stable`){await waitForNavigationReadiness(this,xn,jn);return}if(xn===`networkidle`||xn===`load`){replPrint(`[system] this is redundant wait; openTab() already waits for the page to become usable. Falling back to 'stable' with 5s timeout.`),await waitForNavigationReadiness(this,`stable`,5000).catch(()=>{});return}if(await this.#_())return;let Vn=`Page.domContentEventFired`,qn=await this.resolveSessionId(this.#n);await new Promise((jn,Vn)=>{let Jn=setTimeout(()=>{Yn(),Vn(Error(`Timed out waiting for load state "${xn}"`))},DEFAULT_WAIT_TIMEOUT_MS),Yn=this.cdp.on(`Page.domContentEventFired`,(xn,Vn)=>{Vn.sessionId===qn&&(clearTimeout(Jn),Yn(),jn())})})}async#_(){return await this.evaluate(`document.readyState`).catch(()=>`loading`)!==`loading`}async#v(xn,jn=DEFAULT_WAIT_TIMEOUT_MS){let Vn=Date.now();for(;Date.now()-Vn<jn;){if(await this.#_())return;await sleep$12(50)}throw Error(xn)}async waitForURL(xn,jn={}){let Vn=jn.timeout??DEFAULT_WAIT_TIMEOUT_MS,qn=Date.now();for(;Date.now()-qn<Vn;){let jn=this.url();if(typeof xn==`string`?jn===xn:xn.test(jn))return;await sleep$12(100)}throw Error(`Timed out waiting for URL match: ${String(xn)}`)}async waitForSelector(xn,jn={}){let Vn=jn.state??`visible`,qn=jn.timeout??3000,Jn=[0,20,50,100,100,500],Yn=Date.now(),Zn=0;for(;;){if(Date.now()-Yn>=qn)throw Error(`waitForSelector: timed out after ${qn}ms waiting for "${xn}" to be ${Vn}`);let jn=await this.evaluate((xn)=>{let jn=document.querySelector(xn);if(!jn)return{attached:false,visible:false};let Vn=jn.getBoundingClientRect(),qn=window.getComputedStyle(jn);return{attached:true,visible:qn.visibility!==`hidden`&&qn.display!==`none`&&parseFloat(qn.opacity)!==0&&Vn.width>0&&Vn.height>0}},xn);if(Vn===`attached`?jn.attached:Vn===`detached`?!jn.attached:Vn===`visible`?jn.visible:!jn.visible)return;let Qn=Jn[Math.min(Zn++,Jn.length-1)];await sleep$12(Qn)}}locator(xn,jn={}){return new Locator(this,xn).filter(jn)}async click(xn,jn){await this.locator(xn).click(jn)}async fill(xn,jn){await this.locator(xn).fill(jn)}async $(xn){return replPrint(`warn`,`page.$() is deprecated in OmOWright — use page.locator(selector).first() instead`),this.locator(xn).first()}async $$(xn){return replPrint(`warn`,`page.$$() is deprecated in OmOWright — use page.locator(selector).all() instead`),await this.locator(xn).all()}async $$eval(xn,jn,Vn){return await this.locator(xn).evaluateAll(jn,Vn)}getByRole(xn,jn={}){return new Locator(this,Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`internal:label=/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(xn){return new FrameLocator(this,this.mainFrame(),xn)}async evaluate(xn,jn,Vn){let{actualArg:qn,evaluateOptions:Jn}=resolveEvaluateCall(xn,jn,Vn);if(typeof xn==`string`&&qn===undefined){let{result:jn,exceptionDetails:Vn}=await this._sendToTarget(`Runtime.evaluate`,{expression:xn,returnByValue:true,awaitPromise:true,userGesture:Jn.userGesture});if(Vn)throw Error(formatRuntimeException(Vn,`Evaluation failed`));return jn.value}let Yn=typeof xn==`function`?xn.toString():xn,Zn=await this.#x();try{let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.callFunctionOn`,{objectId:Zn,functionDeclaration:`function(arg) { var __name = (t) => t; return (${Yn})(arg); }`,arguments:[{value:qn}],returnByValue:true,awaitPromise:true,userGesture:Jn.userGesture});if(jn)throw Error(formatRuntimeException(jn,`Evaluation failed`));return xn.value}finally{await this._sendToTarget(`Runtime.releaseObject`,{objectId:Zn}).catch(()=>{})}}async evaluateInFrame(xn,jn,Vn,qn){let Jn=this.frameManager.getFrame(xn);if(!Jn)throw Error(`Frame is not available: ${xn}`);let{actualArg:Yn,evaluateOptions:Zn}=resolveEvaluateCall(jn,Vn,qn),Qn=await this.resolveSessionId(Jn.sessionId);if(typeof jn==`string`&&Yn===undefined){let Vn=await this.frameManager.ensureInjected(xn);if(!Vn)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:qn,exceptionDetails:Jn}=await this.cdp.send(`Runtime.evaluate`,{expression:jn,contextId:Vn,returnByValue:true,awaitPromise:true,userGesture:Zn.userGesture},Qn);if(Jn)throw Error(formatRuntimeException(Jn,`Evaluation failed`));return qn.value}let ei=typeof jn==`function`?jn.toString():jn,ti=await this.frameManager.ensureInjected(xn);if(!ti)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:ni,exceptionDetails:ri}=await this.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(arg) { var __name = (t) => t; return (${ei})(arg); }`,arguments:[{value:Yn}],executionContextId:ti,returnByValue:true,awaitPromise:true,userGesture:Zn.userGesture},Qn);if(ri)throw Error(formatRuntimeException(ri,`Evaluation failed`));return ni.value}async grantNotificationPermission(){await sendCommandToExtension({method:`OmO.grantNotificationPermission`,params:{targetId:this.targetId}},this.browser.extensionBridgeRoute);let xn=new URL(this.#r).origin,jn=this.browser.daemonSession;upsertNotificationGrant({accountId:jn.accountId,origin:xn,grantedBySessionId:jn.id})}url({truncate:xn=false}={}){return xn?truncateUrlForLLM(this.#r):this.#r}async title(){return await this.evaluate(`document.title`).catch(()=>``)}async content(){return await this.evaluate(`document.documentElement.outerHTML`)}async screenshot(xn={}){let jn=normalizeScreenshotTimeout(xn.timeout),Vn=jn&&jn>0?Date.now()+jn:undefined,qn;if(xn.clip)qn={x:xn.clip.x,y:xn.clip.y,width:xn.clip.width,height:xn.clip.height,scale:1};else if(xn.fullPage){let xn=await this._sendToTarget(`Page.getLayoutMetrics`),jn=xn.cssContentSize??xn.contentSize;qn={x:0,y:0,width:jn.width,height:jn.height,scale:1}}qn&&=clampScreenshotClipToTextureLimit(qn,await this.#y());let Jn={format:xn.type??`png`,captureBeyondViewport:!!xn.fullPage,quality:xn.quality,...qn?{clip:qn}:{}},Yn;try{({data:Yn}=await this.#b(Jn,jn,screenshotCaptureLabel(xn)))}catch(jn){if(!xn.fullPage||xn.clip||!isCaptureScreenshotTimeout(jn))throw jn;let qn=Vn?Math.max(0,Vn-Date.now()):undefined;if(qn===0)throw jn;let Jn={format:xn.type??`png`,captureBeyondViewport:false,quality:xn.quality};try{({data:Yn}=await this.#b(Jn,qn,`viewport fallback screenshot`)),replPrint(`[system] full-page screenshot failed; returned viewport fallback. ${formatScreenshotError(jn)}`)}catch(xn){throw Error(`${formatScreenshotError(jn)}+Viewport fallback also failed: ${formatScreenshotError(xn)}`)}}let Zn=Buffer.from(Yn,`base64`);if(xn.path)if(xn.path.startsWith(`/tmp`)){let jn=this.browser.resolvePath(`tmp`),Vn=path.join(jn,path.basename(xn.path));await mkdir(path.dirname(Vn),{recursive:true}),await writeFile(Vn,Zn),replPrint(`[WARN] Use ${jn} instead of /tmp. Saved it to ${Vn}`)}else{let jn=this.browser.resolvePath(xn.path);await mkdir(path.dirname(jn),{recursive:true}),await writeFile(jn,Zn)}return Zn}async#y(){return await this.evaluate(`window.devicePixelRatio`).catch(()=>1)}async#b(xn,jn,Vn){try{return await this._sendToTarget(`Page.captureScreenshot`,xn,{timeoutMs:jn})}catch(xn){throw rewriteCaptureScreenshotError(xn,jn,Vn)}}async snapshot(xn={}){return await takeSnapshot(this.cdp,this.frameManager,xn)}frames(){return this.frameManager.collectDescendantFrames(this.frameManager.mainFrameId).map(({frameId:xn})=>new OmOFrame(this,xn))}mainFrame(){let xn=this.frameManager.getFrame(this.frameManager.mainFrameId);if(!xn)throw Error(`Main frame is not available`);return new OmOFrame(this,xn.frameId)}async bringToFront(){this.browser.page=this,replPrint(`page is now [${await this.title().catch(()=>``)}](${this.url()})`)}async openPopupUrl(xn){await this.browser.openPopupTab(xn,this.targetId)}get console(){return this.#t??=new PageConsole(this)}video(){return this.#w()}viewportSize(){return this.#i?{...this.#i}:null}async refreshViewportSize(){let xn=await this.evaluate(()=>({width:Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0),height:Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0)}));if(xn.width<=0||xn.height<=0)throw Error(`Measured viewport size is invalid: ${JSON.stringify(xn)}`);return this.#i=xn,xn}setCachedViewportSize(xn){this.#i=xn?{...xn}:null}async pdf(xn={}){let jn=xn.path?await this.browser.ensurePath(xn.path,`write`,`page.pdf`):undefined,Vn={...xn,height:formatPdfLength(xn.height),margin:xn.margin?{bottom:formatPdfLength(xn.margin.bottom),left:formatPdfLength(xn.margin.left),right:formatPdfLength(xn.margin.right),top:formatPdfLength(xn.margin.top)}:undefined,printBackground:xn.printBackground??true,transferMode:`ReturnAsBase64`,width:formatPdfLength(xn.width)},{data:qn}=await this._sendToTarget(`Page.printToPDF`,Vn),Jn=Buffer.from(qn,`base64`);return jn&&(await mkdir(path.dirname(jn),{recursive:true}).catch(()=>{}),await writeFile(jn,Jn)),Jn}async close(xn={}){if(await this.#w().stop().catch(()=>{}),xn.runBeforeUnload){let jn=await this.resolveSessionId(this.#n);await this.cdp.send(`Page.close`,undefined,jn).catch(async()=>{await this.browser.closeTab(this,xn)});return}await this.browser.closeTab(this,xn)}async#x(){let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.evaluate`,{expression:`globalThis`,serializationOptions:{serialization:`idOnly`}});if(jn)throw Error(formatRuntimeException(jn,`Failed to resolve main world`));if(!xn.objectId)throw Error(`Main world object is not available`);return xn.objectId}async#S(xn){await this._sendToTarget(`Network.enable`).catch(()=>{});let jn=await this.resolveSessionId(this.#n);await new Promise((Vn,qn)=>{let Jn=new Set,Yn=null,Zn=null,Qn=()=>{ti(),ri(),ii(),Yn&&=(clearTimeout(Yn),null),Zn&&=(clearTimeout(Zn),null)},ei=()=>{Yn&&clearTimeout(Yn),Jn.size===0&&(Yn=setTimeout(()=>{Qn(),Vn()},NETWORK_IDLE_MS))},ti=this.cdp.on(`Network.requestWillBeSent`,(xn,Vn)=>{Vn.sessionId===jn&&(xn.request.url.startsWith(`data:`)||Jn.add(xn.requestId))}),ni=(xn)=>{Jn.delete(xn),ei()},ri=this.cdp.on(`Network.loadingFinished`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)}),ii=this.cdp.on(`Network.loadingFailed`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)});Zn=setTimeout(()=>{Qn(),qn(Error(`Timed out waiting for load state "networkidle"`))},xn),ei()})}async#C(){let xn=await this.resolveSessionId(this.#n);await new Promise((jn,Vn)=>{let qn=setTimeout(()=>{Jn(),Vn(Error(`Timed out waiting for navigation`))},DEFAULT_WAIT_TIMEOUT_MS),Jn=this.cdp.on(`Page.frameNavigated`,(Vn,Yn)=>{Yn.sessionId===xn&&(Vn.frame.parentId||(clearTimeout(qn),Jn(),jn()))})})}async _sendToTarget(xn,jn,Vn={}){if(this.#s)throw Error(`Page ${this.targetId} is disposed`);let{preferredSessionId:qn,...Jn}=Vn;if(qn!==undefined){if(!this.frameManager.hasSession(qn))throw Error(`Frame is stale or detached: CDP session ${qn} is unavailable`);return await this.cdp.send(xn,jn,qn,Jn)}let Yn=await this.resolveSessionId(this.#n);return await this.cdp.send(xn,jn,Yn,Jn)}#w(){return this.#o??=new OmOVideo(this),this.#o}}});init_client$6();init_session_manager();init_frame_manager();init_page();import{isDeepStrictEqual}from"node:util";var shared=new Map;function withinTimeout(pending,timeoutMs,message){let timer;return Promise.race([pending,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message)),timeoutMs)})]).finally(()=>clearTimeout(timer))}function release(key,entry){entry.refs-=1;if(entry.refs>0)return Promise.resolve();if(shared.get(key)===entry)shared.delete(key);return entry.ready.then((connection)=>connection.close(),()=>{})}function bindTo(target,value){return typeof value==="function"?value.bind(target):value}class SharedConnectionError extends Error{constructor(){super("this browser connection is shared; pass dialogPolicy to connect()/connectNamed() so this holder gets its own connection");this.name="SharedConnectionError";this.code="shared_connection"}}var RESERVED=new Set(["cdp","close","setDialogPolicy"]);function refuse(what){return(_target,property)=>{throw new TypeError(`cannot change ${String(property)} on ${what} through a handle: every holder of this connection uses it`)}}function lease(key,entry,connection){let closed;const overlay=Object.create(null);const subscriptions=[];const ensureOpen=(property)=>{if(closed&&typeof property==="string"&&property!=="then"){throw new Error("this browser connection handle was closed")}};const close=()=>{if(!closed){for(const unsubscribe of subscriptions.splice(0))unsubscribe();closed=release(key,entry)}return closed};const setDialogPolicy=(policy)=>{ensureOpen("setDialogPolicy");if(entry.refs>1)throw new SharedConnectionError;if(shared.get(key)===entry)shared.delete(key);return connection.setDialogPolicy(policy)};const tracked=(subscribe)=>(...args)=>{const unsubscribe=subscribe(...args);subscriptions.push(unsubscribe);return unsubscribe};const readOnly=(what,get)=>({get,set:refuse(what),defineProperty:refuse(what),deleteProperty:refuse(what)});const client=connection.cdp;const transportSubscriptions=[];const transportEvents=new Proxy(client.transportEvents,readOnly("the shared transport events",(target,property)=>{ensureOpen(property);if(property==="on"){return(...args)=>{const unsubscribe=tracked(target.on.bind(target))(...args);transportSubscriptions.push(unsubscribe);return unsubscribe}}if(property==="clearListeners"){return()=>{for(const unsubscribe of transportSubscriptions.splice(0))unsubscribe()}}if(property==="emit"){return()=>{throw new TypeError("cannot emit transport events through a handle: every holder of this connection hears them")}}return bindTo(target,Reflect.get(target,property,target))}));const clientView=new Proxy(client,readOnly("the shared CDP client",(target,property)=>{ensureOpen(property);if(property==="setDialogPolicy")return setDialogPolicy;if(property==="close")return close;if(property==="on")return tracked(target.on.bind(target));if(property==="transportEvents")return transportEvents;return bindTo(target,Reflect.get(target,property,target))}));return new Proxy(connection,{get(target,property){if(property==="close")return close;ensureOpen(property);if(property==="setDialogPolicy")return setDialogPolicy;if(property==="cdp")return clientView;if(Object.hasOwn(overlay,property))return overlay[property];return bindTo(target,Reflect.get(target,property,target))},set(target,property,value){ensureOpen(property);if(RESERVED.has(property))return refuse("a handle")(target,property);return Reflect.set(overlay,property,value)},defineProperty(target,property,descriptor){ensureOpen(property);if(RESERVED.has(property))return refuse("a handle")(target,property);if(descriptor.configurable!==true)return false;return Reflect.defineProperty(overlay,property,descriptor)},deleteProperty(target,property){ensureOpen(property);if(Object.hasOwn(overlay,property))return Reflect.deleteProperty(overlay,property);return refuse("the shared connection")(target,property)},has(target,property){return Object.hasOwn(overlay,property)||Reflect.has(target,property)},ownKeys(target){return[...new Set([...Reflect.ownKeys(target),...Reflect.ownKeys(overlay)])]},getOwnPropertyDescriptor(target,property){return Object.hasOwn(overlay,property)?Reflect.getOwnPropertyDescriptor(overlay,property):Reflect.getOwnPropertyDescriptor(target,property)}})}function isPlainData(value,path=new Set){if(typeof value==="function"||value===null||typeof value!=="object")return true;if(path.has(value))return false;const prototype=Object.getPrototypeOf(value);const isArray=Array.isArray(value);if(isArray?prototype!==Array.prototype:prototype!==Object.prototype&&prototype!==null){return false}path.add(value);try{for(const key of Reflect.ownKeys(value)){if(isArray&&key==="length")continue;if(typeof key==="symbol")return false;const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor.enumerable||!("value"in descriptor))return false;if(!isPlainData(descriptor.value,path))return false}return true}finally{path.delete(value)}}function canShareConnection(options){return options?.client?.authorizer===undefined&&isPlainData(options)}async function acquireSharedConnection(webSocketDebuggerUrl,options,{open,timeoutMs}){if(!canShareConnection(options))return open(options);let entry=shared.get(webSocketDebuggerUrl);if(entry&&!isDeepStrictEqual(entry.options,options))return open(options);if(!entry){entry={options,refs:0,ready:open(options)};shared.set(webSocketDebuggerUrl,entry)}entry.refs+=1;try{const connection=await entry.ready;const reconnected=connection.cdp.ensureConnected();await(timeoutMs===undefined?reconnected:withinTimeout(reconnected,timeoutMs,`timed out after ${timeoutMs}ms reconnecting the CDP session on ${webSocketDebuggerUrl}`));return lease(webSocketDebuggerUrl,entry,connection)}catch(error){if(shared.get(webSocketDebuggerUrl)===entry)shared.delete(webSocketDebuggerUrl);await release(webSocketDebuggerUrl,entry);throw error}}class TabRepository{#client;constructor(client){this.#client=client}async listTargets(){return this.#client.discoverTargets()}}class BrowserConnection{#client;#sessions;#pages=new Map;#storageRoot;constructor(client,options={}){this.#client=client;this.#sessions=new SessionManager(client);this.tabs=new TabRepository(client);this.#storageRoot=path2.resolve(options.storageRoot??process.cwd())}async initialize(){await this.#client.ensureConnected();return this}get cdp(){return this.#client}setDialogPolicy(policy){if(typeof this.#client.setDialogPolicy!=="function"){throw new Error("dialog policy is not supported by this transport")}this.#client.setDialogPolicy(policy)}async listTargets(){return this.tabs.listTargets()}async newTab(url="about:blank"){await Promise.resolve().then(() => init_agent_tabs());return(await createAgentTabs(this).create(url)).page}async attachPage(targetId){if(this.#pages.has(targetId))return this.#pages.get(targetId).page;const sessionId=await this.#sessions.resolvePageSession(targetId);const frames=new FrameManager(this.#client,targetId,sessionId);await frames.initialize();const entry={frames,page:null};const host=this.#createPageHost(targetId,entry);const page=new OmOPage(this.#client,frames,targetId,sessionId,host);entry.page=page;this.#pages.set(targetId,entry);return page}#createPageHost(targetId,entry){return{daemonSession:{accountId:0,id:"standalone"},extensionBridgeRoute:{},page:null,resolvePageSession:(id,preferred)=>this.#sessions.resolvePageSession(id,preferred),resolvePath:(value)=>path2.resolve(this.#storageRoot,value),ensurePath:async(value)=>{const resolved=path2.resolve(this.#storageRoot,value);await mkdir2(path2.dirname(resolved),{recursive:true});return resolved},registerReadableDownload:(value)=>value,isReadableDownload:()=>false,openPopupTab:async()=>{throw Error("Popup tab control requires the extension bridge")},closeTab:async(_page,options={})=>{if(options.runBeforeUnload){await this.#client.send("Page.close",undefined,await this.#sessions.resolvePageSession(targetId))}else{await this.#client.send("Target.closeTarget",{targetId})}await entry.page?.dispose();await entry.frames.dispose();this.#pages.delete(targetId)}}}async close(){for(const[targetId,entry]of[...this.#pages]){await entry.page.dispose().catch(()=>{});await entry.frames.dispose().catch(()=>{});this.#pages.delete(targetId)}await this.#sessions.dispose();await this.#client.close()}}async function browserKey(client,cdpUrl){if(/^wss?:\/\//.test(cdpUrl))return cdpUrl;return(await client.discoverVersion()).webSocketDebuggerUrl}function createClient(cdpHttpUrl,options){if(typeof cdpHttpUrl!=="string"||cdpHttpUrl.length===0){throw new TypeError("connect(cdpHttpUrl) requires a Chromium CDP HTTP URL")}return new CdpClient({cdpUrl:cdpHttpUrl,...options.client,dialogPolicy:options.dialogPolicy??options.client?.dialogPolicy})}async function openConnection(cdpHttpUrl,options={}){return new BrowserConnection(createClient(cdpHttpUrl,options),options).initialize()}async function connect(cdpHttpUrl,options={}){const client=createClient(cdpHttpUrl,options);if(!canShareConnection(options))return new BrowserConnection(client,options).initialize();const key=await browserKey(client,cdpHttpUrl);return acquireSharedConnection(key,options,{open:()=>openConnection(key,options)})}var OMOWRIGHT_PAGE_CDP_METHODS=Object.freeze(["Browser.getVersion","DOM.describeNode","DOM.enable","DOM.getBoxModel","DOM.getContentQuads","DOM.getDocument","DOM.querySelectorAll","DOM.resolveNode","DOM.scrollIntoViewIfNeeded","DOM.setFileInputFiles","Emulation.setDeviceMetricsOverride","Emulation.setFocusEmulationEnabled","Input.dispatchKeyEvent","Input.dispatchMouseEvent","Input.insertText","Inspector.enable","Network.enable","Page.addScriptToEvaluateOnNewDocument","Page.captureScreenshot","Page.close","Page.createIsolatedWorld","Page.enable","Page.getFrameTree","Page.getLayoutMetrics","Page.getNavigationHistory","Page.handleJavaScriptDialog","Page.navigate","Page.navigateToHistoryEntry","Page.printToPDF","Page.reload","Page.removeScriptToEvaluateOnNewDocument","Page.screencastFrameAck","Page.setInterceptFileChooserDialog","Page.setWebLifecycleState","Page.startScreencast","Page.stopScreencast","Runtime.callFunctionOn","Runtime.evaluate","Runtime.releaseObject","Target.activateTarget","Target.attachToTarget","Target.closeTarget","Target.createTarget","Target.detachFromTarget","Target.getTargetInfo","Target.getTargets","Target.setAutoAttach","Target.setDiscoverTargets"]);import{spawn}from"node:child_process";init_internal_capability();class Emittery2{#listeners=new Map;on(event,fn){const list=this.#listeners.get(event)??[];list.push(fn);this.#listeners.set(event,list);return()=>{const cur=this.#listeners.get(event)??[];this.#listeners.set(event,cur.filter((f)=>f!==fn))}}async emit(event,data){for(const fn of this.#listeners.get(event)??[])await fn(data)}}var DEFAULT_COMMAND_TIMEOUT_MS2=30000;var DEFAULT_READINESS_TIMEOUT_MS=1e4;var GRACEFUL_CLOSE_TIMEOUT_MS=2000;var STDIO_TAIL_LIMIT=16384;class PipeCdpClient{#child;#writeStream;#readStream;#buffer=Buffer.alloc(0);#seq=1;#pending=new Map;#events=new Emittery2;#connected=false;#commandTimeoutMs;#readinessTimeoutMs;#browserPath;#browserArgs;#spawnOptions;#stdioTail="";#dialogPolicy;transportEvents=new Emittery2;logId;constructor({browserPath,browserArgs=[],spawnOptions={},commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy}){if(!browserPath)throw new TypeError("PipeCdpClient requires browserPath");this.#browserPath=browserPath;this.#browserArgs=browserArgs;this.#spawnOptions=spawnOptions;this.#commandTimeoutMs=commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS2;this.#readinessTimeoutMs=readinessTimeoutMs??DEFAULT_READINESS_TIMEOUT_MS;this.logId=logId??`cdp-pipe-${Date.now()}`;this.#dialogPolicy=normalizeDialogPolicy(dialogPolicy)}get isConnected(){return this.#connected}get isHeadless(){return this.#browserArgs.some((arg)=>/^--headless(?:=|$)/.test(arg))}get childProcess(){return this.#child}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(policy){this.#dialogPolicy=normalizeDialogPolicy(policy)}async ensureConnected(){if(this.#connected)return;const stdio=["ignore","pipe","pipe","pipe","pipe"];this.#child=spawn(this.#browserPath,[...this.#browserArgs,"--remote-debugging-pipe"],{...this.#spawnOptions,stdio});this.#stdioTail="";for(const stream of[this.#child.stdout,this.#child.stderr]){if(!stream)continue;stream.setEncoding("utf8");stream.on("data",(chunk)=>{this.#stdioTail=(this.#stdioTail+chunk).slice(-STDIO_TAIL_LIMIT)});stream.on("error",()=>{})}this.#writeStream=this.#child.stdio[3];this.#readStream=this.#child.stdio[4];this.#readStream.on("data",(chunk)=>this.#onData(chunk));for(const stream of[this.#writeStream,this.#readStream]){stream.on("error",(error)=>this.#failAll(Error(`CDP pipe error: ${error.code??error.message}`)))}this.#child.on("exit",()=>{this.#connected=false;this.#failAll(Error("CDP pipe browser exited"));this.transportEvents.emit("disconnected").catch(()=>{})});this.#connected=true;await this.#awaitReady();await this.send("Target.setDiscoverTargets",{discover:true}).catch(()=>{});await this.transportEvents.emit("connected")}async#awaitReady(){const deadline=Date.now()+this.#readinessTimeoutMs;let lastError;while(Date.now()<deadline){try{await this.send("Browser.getVersion",undefined,undefined,{timeoutMs:1000});return}catch(error){lastError=error;await new Promise((resolve)=>setTimeout(resolve,100))}}const reason=lastError?String(lastError.message??lastError):"no response";const tail=this.#stdioTail.trim();throw Error(`Browser did not become ready over the CDP pipe (${reason})`+(tail?`Browser stdio tail:-${tail}`:""))}async send(method,params,sessionId,opts={}){if(method==="Target.createTarget"&&opts.capability!==targetCreationCapability)throw Error("Target.createTarget is reserved for createAgentTabs");if(String(method).startsWith("OmO.")){throw Error(`Extension commands are unavailable over pipe transport: ${method}`)}await this.ensureConnected();const id=this.#seq++;const msg={id,method};if(params!==undefined)msg.params=params;if(sessionId)msg.sessionId=sessionId;const{promise,resolve,reject}=Promise.withResolvers();const timeoutMs=opts.timeoutMs??this.#commandTimeoutMs;const timeout=timeoutMs>0?setTimeout(()=>{this.#pending.delete(id);reject(Error(`CDP command timeout: ${method}`))},timeoutMs):undefined;this.#pending.set(id,{method,resolve,reject,timeout});this.#writeStream.write(JSON.stringify(msg)+"\x00");return promise}on(method,fn){return this.#events.on(method,({data})=>fn(data.payload,data.meta))}async discoverTargets(){const{targetInfos}=await this.send("Target.getTargets");return targetInfos.map((t)=>({id:t.targetId,type:t.type,url:t.url??"",title:t.title??"",description:t.description,faviconUrl:t.faviconUrl,parentId:t.openerId}))}async close(){const child=this.#child;this.#child=undefined;if(child&&child.exitCode===null){const exited=new Promise((resolve)=>child.once("exit",resolve));if(this.#connected){await Promise.race([this.send("Browser.close",undefined,undefined,{timeoutMs:GRACEFUL_CLOSE_TIMEOUT_MS}).catch(()=>{}),exited])}this.#connected=false;this.#failAll(Error("CDP pipe client closed"));if(child.exitCode===null){await Promise.race([exited,new Promise((resolve)=>setTimeout(resolve,GRACEFUL_CLOSE_TIMEOUT_MS))])}if(child.exitCode===null){try{child.kill("SIGKILL")}catch{}await exited}return}this.#connected=false;this.#failAll(Error("CDP pipe client closed"))}#onData(chunk){this.#buffer=Buffer.concat([this.#buffer,chunk]);let idx;while((idx=this.#buffer.indexOf(0))!==-1){const raw=this.#buffer.subarray(0,idx).toString("utf8");this.#buffer=this.#buffer.subarray(idx+1);if(raw.length===0)continue;let msg;try{msg=JSON.parse(raw)}catch{continue}this._handleTransportMessage(msg)}}_handleTransportMessage(msg){if(typeof msg.id==="number"){const entry=this.#pending.get(msg.id);if(!entry)return;this.#pending.delete(msg.id);if(entry.timeout)clearTimeout(entry.timeout);if(msg.error){const err=Error(msg.error.message??`CDP command failed: ${entry.method}`);err.code=msg.error.code;err.data=msg.error.data;entry.reject(err)}else{entry.resolve(msg.result)}return}if(typeof msg.method==="string"){const handled=msg.method==="Page.javascriptDialogOpening"&&msg.sessionId?this.#handleJavaScriptDialog(msg).catch(()=>{}):undefined;this.#events.emit(msg.method,{data:{payload:msg.params,meta:{sessionId:msg.sessionId}}}).catch(()=>{});return handled}}async#handleJavaScriptDialog(msg){const params=await resolveDialogAction(this.#dialogPolicy,msg.params);await this.send("Page.handleJavaScriptDialog",params,msg.sessionId)}#failAll(err){for(const entry of this.#pending.values()){if(entry.timeout)clearTimeout(entry.timeout);entry.reject(err)}this.#pending.clear()}}async function connectPipe({browserPath,browserArgs=[],spawnOptions,storageRoot,commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy}={}){const client=new PipeCdpClient({browserPath,browserArgs,spawnOptions,commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy});await client.ensureConnected();const connection=new BrowserConnection(client,{storageRoot});await connection.initialize();connection.browserProcess=client.childProcess;connection.newTab=async(url="about:blank")=>{await Promise.resolve().then(() => init_agent_tabs());return(await createAgentTabs(connection).create(url)).page};return connection}import{randomInt}from"node:crypto";import{chmod,mkdir as mkdir3,open as open2,readFile}from"node:fs/promises";import{globSync}from"node:fs";import os from"node:os";import path3 from"node:path";var MIN_FINGERPRINT_SEED=1e4;var MAX_FINGERPRINT_SEED=99999;var METADATA_FILE=".omowright-cloak.json";var DEFAULT_PROFILE_DIR=path3.join(os.homedir(),".local","share","omowright-cloak");function normalizeFingerprintSeed(value){const seed=typeof value==="string"&&value.trim()!==""?Number(value):value;if(!Number.isInteger(seed)||seed<MIN_FINGERPRINT_SEED||seed>MAX_FINGERPRINT_SEED){throw new RangeError(`fingerprint seed must be an integer from ${MIN_FINGERPRINT_SEED} to ${MAX_FINGERPRINT_SEED}`)}return seed}function platformFingerprint(){return process.platform==="darwin"?"macos":"windows"}function identityFlag(value){return/^(--user-data-dir|--fingerprint|--fingerprint-platform)(?:=|$)/.test(value)}function buildCloakBrowserArgs({profileDir,fingerprintSeed,extraArgs=[]}={}){const profile=path3.resolve(profileDir??DEFAULT_PROFILE_DIR);const seed=normalizeFingerprintSeed(fingerprintSeed);const conflicting=extraArgs.filter(identityFlag);if(conflicting.length>0){throw new Error(`extraArgs cannot override fixed profile identity: ${conflicting.join(", ")}`)}return["--no-first-run","--no-default-browser-check","--disable-session-crashed-bubble",`--user-data-dir=${profile}`,`--fingerprint=${seed}`,`--fingerprint-platform=${platformFingerprint()}`,...extraArgs]}async function readMetadata(metadataPath){try{const parsed=JSON.parse(await readFile(metadataPath,"utf8"));return normalizeFingerprintSeed(parsed.fingerprintSeed)}catch(error){if(error?.code==="ENOENT")return null;if(error instanceof SyntaxError){throw new Error(`invalid CloakBrowser profile metadata: ${metadataPath}`)}throw error}}async function writeMetadata(metadataPath,fingerprintSeed){const handle=await open2(metadataPath,"wx",384);try{await handle.writeFile(`${JSON.stringify({fingerprintSeed},null,2)}-`,"utf8")}finally{await handle.close()}await chmod(metadataPath,384)}async function resolveCloakProfile({profileDir=DEFAULT_PROFILE_DIR,fingerprintSeed,randomSeed=()=>randomInt(MIN_FINGERPRINT_SEED,MAX_FINGERPRINT_SEED+1)}={}){const resolvedProfile=path3.resolve(profileDir);const metadataPath=path3.join(resolvedProfile,METADATA_FILE);await mkdir3(resolvedProfile,{recursive:true,mode:448});await chmod(resolvedProfile,448);const requested=fingerprintSeed===undefined?null:normalizeFingerprintSeed(fingerprintSeed);let stored=await readMetadata(metadataPath);if(stored===null){const candidate=requested??normalizeFingerprintSeed(randomSeed());try{await writeMetadata(metadataPath,candidate);stored=candidate}catch(error){if(error?.code!=="EEXIST")throw error;stored=await readMetadata(metadataPath);if(stored===null){throw new Error(`CloakBrowser profile seed metadata disappeared: ${metadataPath}`)}}}if(requested!==null&&requested!==stored){throw new Error(`fingerprint seed mismatch: profile is fixed at ${stored}, requested ${requested}`)}await chmod(metadataPath,384);return{profileDir:resolvedProfile,metadataPath,fingerprintSeed:stored,browserArgs:buildCloakBrowserArgs({profileDir:resolvedProfile,fingerprintSeed:stored})}}function findCloakBrowserPath({browserRoot=path3.join(os.homedir(),".cloakbrowser")}={}){const candidates=globSync(path3.join(path3.resolve(browserRoot),"chromium-*","Chromium.app","Contents","MacOS","Chromium")).sort();const browserPath=candidates.at(-1);if(!browserPath){throw new Error(`CloakBrowser binary not found under ${path3.resolve(browserRoot)}; set CLOAKBROWSER_BIN`)}return browserPath}async function connectCloakProfile({browserPath=process.env.CLOAKBROWSER_BIN??findCloakBrowserPath(),profileDir=process.env.CLOAK_PROFILE_DIR??DEFAULT_PROFILE_DIR,fingerprintSeed=process.env.CLOAK_FINGERPRINT_SEED,browserArgs=[],storageRoot,...options}={}){const profile=await resolveCloakProfile({profileDir,fingerprintSeed});return connectPipe({browserPath,browserArgs:buildCloakBrowserArgs({profileDir:profile.profileDir,fingerprintSeed:profile.fingerprintSeed,extraArgs:browserArgs}),storageRoot:storageRoot??profile.profileDir,...options})}var SNAPSHOT_PARSE_ERROR="compactSnapshot expected a snapshot() result (JSON string or {tree, refs} object)";function compactSnapshot(snapshot){const obj=typeof snapshot==="string"?JSON.parse(snapshot):snapshot;if(!obj||typeof obj.tree!=="string")throw new TypeError(SNAPSHOT_PARSE_ERROR);return obj.tree}function snapshotTokens(snapshot){const text=typeof snapshot==="string"?snapshot:JSON.stringify(snapshot);return{bytes:Buffer.byteLength(text,"utf8"),estTokens:Math.ceil(Buffer.byteLength(text,"utf8")/4)}}var toolSchemas=[{name:"newTab",description:"Open a tab and return its page. Waits for interactivity.",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"]}},{name:"attachPage",description:"Attach to an existing tab by targetId from listTargets().",parameters:{type:"object",properties:{targetId:{type:"string"}},required:["targetId"]}},{name:"page.goto",description:"Navigate the page; resolves when the page looks interactive.",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"]}},{name:"page.snapshot",description:"PRIMARY page read. Returns a compact a11y tree; interactive elements carry [ref=eN] ids for page.locator. Options: maxDepth, maxChars, interactive, showHidden, selector, ref.",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"page.locator",description:"Resolve a ref id (e.g. 'e1') or CSS selector to a Locator: click, fill, press, hover, check, selectOption, dragTo, setInputFiles, textContent, isVisible, waitFor.",parameters:{type:"object",properties:{selectorOrRef:{type:"string"}},required:["selectorOrRef"]}},{name:"page.evaluate",description:"Run JS in the page and return the result.",parameters:{type:"object",properties:{expression:{type:"string"}},required:["expression"]}},{name:"page.screenshot",description:"Capture page image bytes (path, fullPage, clip, type, quality).",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"page.pdf",description:"Print the page to PDF bytes (path, format, margin, printBackground).",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"compactSnapshot",description:"Pass page.snapshot() output through this before reading: returns the raw tree without the refs map (refs resolve in-page; the map is ~54% of bytes on real pages).",parameters:{type:"object",properties:{snapshot:{}},required:["snapshot"]}},{name:"createCua",description:"Coordinate fallback for UI that refs cannot target: click/doubleClick/drag/move/scroll/type/keypress at viewport points, getVisibleScreenshot() as base64 PNG.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"createCaptcha",description:"Captcha helpers: click(bounds) and drag(from,to) return a post-action snapshot tree; readText(bounds?) OCRs a screenshot region (macOS Vision default, custom ocr injectable).",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"createChromeApi",description:"Chrome MV3-shaped APIs: tabs.query/get, windows.*, bookmarks/history/topSites (read-only from profile files), downloads.search/download. Writes throw UnsupportedOperationError.",parameters:{type:"object",properties:{connection:{},options:{type:"object"}},required:["connection"]}},{name:"injectCookies",description:"Inject raw cookie exports into a page with CDP sanitization handled (negative expires dropped, __Host- forced secure+root path+url-scoped, SameSite=None dropped when not secure, name+domain deduped).",parameters:{type:"object",properties:{page:{},cookies:{type:"array"}},required:["page","cookies"]}},{name:"createNetworkSnoop",description:"Buffer a page's CDP network traffic and return {pop,peek,popJson,waitFor,summary,dispose}; match is a predicate or {url,method,mimeType,resourceType}.",parameters:{type:"object",properties:{page:{},match:{},bodies:{type:"boolean"},maxEntries:{type:"number"},maxBodyBytes:{type:"number"}},required:["page"]}},{name:"snoop.waitFor",description:"Wait until a finished entry matches a predicate or {url,method,mimeType,resourceType}; timeoutMs defaults to 30000.",parameters:{type:"object",properties:{match:{},timeoutMs:{type:"number"}}}},{name:"snoop.popJson",description:"Drain the buffer and parse JSON bodies; skips non-JSON mime types and payloads that fail to parse.",parameters:{type:"object",properties:{}}},{name:"snoop.summary",description:"Return a compact text view of buffered entries (method, status, mimeType, size, url) capped by {max}.",parameters:{type:"object",properties:{max:{type:"number"}}}},{name:"collectWhileScrolling",description:"Async generator that scrolls the page, drains snoop.popJson(), and yields extracted items until minItems, maxScrolls, or noGrowth.",parameters:{type:"object",properties:{page:{},snoop:{},minItems:{type:"number"},maxScrolls:{type:"number"},extract:{},scroll:{type:"string",enum:["wheel","end"]},settleMs:{type:"number"}},required:["page","snoop"]}},{name:"createTrace",description:"Start a page flight recorder that writes dir/trace.jsonl, dir/trace.har, dir/summary.json and screenshots; never sends Runtime.enable.",parameters:{type:"object",properties:{page:{},dir:{type:"string"},screenshots:{type:"boolean"},network:{type:"boolean"},console:{type:"boolean"},maxBodyBytes:{type:"number"},events:{}},required:["page","dir"]}},{name:"trace.step",description:"Run named fn as a traced step with optional before/after screenshots; records the error and rethrows on failure.",parameters:{type:"object",properties:{name:{type:"string"},fn:{}},required:["name","fn"]}},{name:"trace.stop",description:"Flush listeners, write summary.json and trace.har, dispose the snoop, and return the summary for dir.",parameters:{type:"object",properties:{}}},{name:"reconcileFrames",description:"Adopt OOPIF iframe targets missing from FrameManager so later snapshots include them; returns the frames that were added.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"snapshotWithFrames",description:"Reconcile missing OOPIF frames then snapshot; refs stay page-level: page.locator(ref), never frame.locator.",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"connectPipe.dialogPolicy",description:"Wire connectPipe({dialogPolicy}) and client.setDialogPolicy to {accept,promptText} or (dialog)=>boolean|{accept,promptText}; throwing policy accepts. WebSocket connect() keeps auto-accept.",parameters:{type:"object",properties:{accept:{type:"boolean"},promptText:{type:"string"}}}},{name:"requestHuman",description:"Pause for a human: inject a shadow-DOM Done banner, bringToFront first, and remove the banner on every path; until is {url}|{selector}|async predicate.",parameters:{type:"object",properties:{page:{},prompt:{type:"string"},until:{},timeoutMs:{type:"number"},pollMs:{type:"number"},signal:{}},required:["page"]}},{name:"describeLayers",description:"Sample a viewport grid and return {blocking,candidates,viewport} so overlay coverage and selectorHint are visible.",parameters:{type:"object",properties:{page:{},grid:{type:"number"}},required:["page"]}},{name:"snapshotWithLayers",description:"Prepend a @layers header to the snapshot tree and attach a layers field so overlays are visible before the a11y tree.",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"emulate",description:"Apply a DEVICE_PRESETS name, a custom metrics object, or null to restore the original UA captured on first call.",parameters:{type:"object",properties:{page:{},preset:{}},required:["page","preset"]}},{name:"createRoutes",description:"Install page request interception; Fetch.enable is sent only on the first route(); interception is fingerprintable, keep it off by default.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"route.continue",description:"Continue an intercepted request, optionally overriding url, method, headers, or postData.",parameters:{type:"object",properties:{url:{type:"string"},method:{type:"string"},headers:{type:"object"},postData:{}}}},{name:"route.fulfill",description:"Fulfill an intercepted request with {status,headers,contentType,body} instead of hitting the network.",parameters:{type:"object",properties:{status:{type:"number"},headers:{type:"object"},contentType:{type:"string"},body:{}}}},{name:"route.abort",description:"Abort an intercepted request with a CDP errorReason (defaults to Failed).",parameters:{type:"object",properties:{reason:{type:"string"}}}}];var MODIFIER_KEYS2=new Set(["Alt","Control","Meta","Shift"]);function splitModifiers(keys=[]){const modifiers=keys.filter((key)=>MODIFIER_KEYS2.has(key)||/^(cmd|command|ctrl|option|controlormeta)$/i.test(key));const rest=keys.filter((key)=>!modifiers.includes(key));return{modifiers,rest}}function createCua(page){async function holdModifiers(keys,fn){const{modifiers}=splitModifiers(keys);for(const key of modifiers)await page.keyboard.down(key);try{return await fn()}finally{for(const key of[...modifiers].reverse())await page.keyboard.up(key)}}return{page,async click({x,y,button="left",keypress}){await holdModifiers(keypress,()=>page.mouse.click(x,y,{button}))},async doubleClick({x,y,keypress}){await holdModifiers(keypress,()=>page.mouse.click(x,y,{clickCount:2}))},async drag({path,keys}){if(!Array.isArray(path)||path.length<2){throw new TypeError("cua.drag requires path with at least two points")}await holdModifiers(keys,async()=>{const[first,...rest]=path;await page.mouse.move(first.x,first.y);await page.mouse.down();try{for(const point of rest)await page.mouse.move(point.x,point.y)}finally{await page.mouse.up()}})},async getVisibleScreenshot(){const buffer=await page.screenshot({type:"png"});return buffer.toString("base64")},async keypress({keys}){if(!Array.isArray(keys)||keys.length===0){throw new TypeError("cua.keypress requires a non-empty keys array")}await page.keyboard.press(keys.join("+"))},async move({x,y,keys}){await holdModifiers(keys,()=>page.mouse.move(x,y))},async scroll({x,y,scrollX,scrollY,keypress}){await holdModifiers(keypress,async()=>{await page.mouse.move(x,y);await page.mouse.wheel(scrollX,scrollY)})},async type({text}){await page.keyboard.type(text)}}}import{spawn as spawn2}from"node:child_process";import{mkdtempSync,writeFileSync,rmSync}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import path4 from"node:path";var MAX_TIMER_MS=2147483647;var STOP=Symbol("wait stopped");async function waitForCaptcha(page,{until,timeoutMs=1e4,pollMs=100,signal}={}){if(typeof until!=="function")throw new TypeError("until must be a function");if(!Number.isFinite(timeoutMs)||timeoutMs<0||timeoutMs>MAX_TIMER_MS){throw new RangeError("timeoutMs must be between 0 and 2147483647")}if(!Number.isFinite(pollMs)||pollMs<=0||pollMs>MAX_TIMER_MS){throw new RangeError("pollMs must be greater than 0 and at most 2147483647")}if(signal!==undefined&&(typeof signal?.aborted!=="boolean"||typeof signal.addEventListener!=="function"||typeof signal.removeEventListener!=="function")){throw new TypeError("signal must be AbortSignal-compatible")}const started=performance.now();const deadline=started+timeoutMs;const operation=new AbortController;let deadlineTimer;let pollTimer;let stop;const stopped=new Promise((resolve)=>{stop=()=>resolve(STOP)});const terminal=()=>signal?.aborted?"cancelled":performance.now()>=deadline?"timed_out":null;const result=(outcome)=>({outcome,elapsedMs:performance.now()-started});const scheduleDeadline=()=>{const remaining=deadline-performance.now();if(remaining<=0)stop();else deadlineTimer=setTimeout(scheduleDeadline,Math.ceil(remaining))};try{const initial=terminal();if(initial)return result(initial);signal?.addEventListener("abort",stop,{once:true});scheduleDeadline();for(;;){let accepted;try{accepted=await Promise.race([Promise.resolve().then(()=>terminal()?STOP:until(page,{signal:operation.signal})),stopped])}catch(error){const outcome=terminal();if(outcome)return result(outcome);throw error}const outcome=terminal();if(outcome)return result(outcome);if(accepted===true)return result("matched");await Promise.race([new Promise((resolve)=>{pollTimer=setTimeout(resolve,Math.ceil(Math.min(pollMs,deadline-performance.now())))}),stopped]);clearTimeout(pollTimer);const afterDelay=terminal();if(afterDelay)return result(afterDelay)}}finally{clearTimeout(deadlineTimer);clearTimeout(pollTimer);signal?.removeEventListener("abort",stop);operation.abort();stop()}}var DEFAULT_DRAG_STEPS=20;var POST_ACTION_SETTLE_MS=3000;function validatePoint(point){if(!Number.isFinite(point?.x)||!Number.isFinite(point?.y)){throw new TypeError("point coordinates must be finite numbers")}}function validateSteps(steps){if(!Number.isSafeInteger(steps)||steps<=0){throw new RangeError("steps must be a positive safe integer")}}function validateSettleMs(value){if(!Number.isFinite(value)||value<0||value>2147483647){throw new RangeError("settleMs must be between 0 and 2147483647")}}var MACOS_VISION_OCR_SWIFT=`+${tail}`:""))}async send(method,params,sessionId,opts={}){if(method==="Target.createTarget"&&opts.capability!==targetCreationCapability)throw Error("Target.createTarget is reserved for createAgentTabs");if(String(method).startsWith("OmO.")){throw Error(`Extension commands are unavailable over pipe transport: ${method}`)}await this.ensureConnected();const id=this.#seq++;const msg={id,method};if(params!==undefined)msg.params=params;if(sessionId)msg.sessionId=sessionId;const{promise,resolve,reject}=Promise.withResolvers();const timeoutMs=opts.timeoutMs??this.#commandTimeoutMs;const timeout=timeoutMs>0?setTimeout(()=>{this.#pending.delete(id);reject(Error(`CDP command timeout: ${method}`))},timeoutMs):undefined;this.#pending.set(id,{method,resolve,reject,timeout});this.#writeStream.write(JSON.stringify(msg)+"\x00");return promise}on(method,fn){return this.#events.on(method,({data})=>fn(data.payload,data.meta))}async discoverTargets(){const{targetInfos}=await this.send("Target.getTargets");return targetInfos.map((t)=>({id:t.targetId,type:t.type,url:t.url??"",title:t.title??"",description:t.description,faviconUrl:t.faviconUrl,parentId:t.openerId}))}async close(){const child=this.#child;this.#child=undefined;if(child&&child.exitCode===null){const exited=new Promise((resolve)=>child.once("exit",resolve));if(this.#connected){await Promise.race([this.send("Browser.close",undefined,undefined,{timeoutMs:GRACEFUL_CLOSE_TIMEOUT_MS}).catch(()=>{}),exited])}this.#connected=false;this.#failAll(Error("CDP pipe client closed"));if(child.exitCode===null){await Promise.race([exited,new Promise((resolve)=>setTimeout(resolve,GRACEFUL_CLOSE_TIMEOUT_MS))])}if(child.exitCode===null){try{child.kill("SIGKILL")}catch{}await exited}return}this.#connected=false;this.#failAll(Error("CDP pipe client closed"))}#onData(chunk){this.#buffer=Buffer.concat([this.#buffer,chunk]);let idx;while((idx=this.#buffer.indexOf(0))!==-1){const raw=this.#buffer.subarray(0,idx).toString("utf8");this.#buffer=this.#buffer.subarray(idx+1);if(raw.length===0)continue;let msg;try{msg=JSON.parse(raw)}catch{continue}this._handleTransportMessage(msg)}}_handleTransportMessage(msg){if(typeof msg.id==="number"){const entry=this.#pending.get(msg.id);if(!entry)return;this.#pending.delete(msg.id);if(entry.timeout)clearTimeout(entry.timeout);if(msg.error){const err=Error(msg.error.message??`CDP command failed: ${entry.method}`);err.code=msg.error.code;err.data=msg.error.data;entry.reject(err)}else{entry.resolve(msg.result)}return}if(typeof msg.method==="string"){const handled=msg.method==="Page.javascriptDialogOpening"&&msg.sessionId?this.#handleJavaScriptDialog(msg).catch(()=>{}):undefined;this.#events.emit(msg.method,{data:{payload:msg.params,meta:{sessionId:msg.sessionId}}}).catch(()=>{});return handled}}async#handleJavaScriptDialog(msg){const params=await resolveDialogAction(this.#dialogPolicy,msg.params);await this.send("Page.handleJavaScriptDialog",params,msg.sessionId)}#failAll(err){for(const entry of this.#pending.values()){if(entry.timeout)clearTimeout(entry.timeout);entry.reject(err)}this.#pending.clear()}}async function connectPipe({browserPath,browserArgs=[],spawnOptions,storageRoot,commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy}={}){const client=new PipeCdpClient({browserPath,browserArgs,spawnOptions,commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy});await client.ensureConnected();const connection=new BrowserConnection(client,{storageRoot});await connection.initialize();connection.browserProcess=client.childProcess;return connection}import{spawn as spawn2}from"node:child_process";import{createHash,randomUUID as randomUUID3}from"node:crypto";import{chmod as chmod2,mkdir as mkdir3,open as open3,readFile as readFile3,readdir as readdir2,rename as rename2,unlink as unlink3}from"node:fs/promises";import os from"node:os";import path5 from"node:path";import{randomUUID as randomUUID2}from"node:crypto";import{watch}from"node:fs";import{link as link2,readdir,rename,stat,unlink as unlink2}from"node:fs/promises";import path3 from"node:path";import{setTimeout as sleep}from"node:timers/promises";import{execFile}from"node:child_process";import{randomUUID}from"node:crypto";import{chmod,link,open as open2,readFile,unlink}from"node:fs/promises";import{promisify}from"node:util";var execFileAsync=promisify(execFile);var ownStartTime;async function processStartTime(pid){if(process.platform==="win32")return null;if(process.platform==="linux"){try{const text=await readFile(`/proc/${pid}/stat`,"utf8");return text.slice(text.lastIndexOf(")")+2).split(" ")[19]??null}catch{return null}}try{const{stdout}=await execFileAsync("ps",["-o","lstart=","-p",String(pid)],{env:{...process.env,LC_ALL:"C",TZ:"UTC"}});return stdout.trim()||null}catch{return null}}async function createLock(lockPath){ownStartTime??=processStartTime(process.pid);const token=randomUUID();const tempPath=`${lockPath}.${process.pid}.${randomUUID()}.tmp`;let handle;try{handle=await open2(tempPath,"wx",384);await handle.writeFile(`${JSON.stringify({pid:process.pid,start:await ownStartTime,token,acquiredAt:new Date().toISOString()})}+`,"utf8");const{ino}=await handle.stat();await handle.close();handle=null;await chmod(tempPath,384);try{await link(tempPath,lockPath)}catch(error){if(error?.code==="EEXIST")return null;throw error}return{ino,token}}finally{await handle?.close().catch(()=>{});await unlink(tempPath).catch(()=>{})}}async function readLockState(lockPath){let handle;try{handle=await open2(lockPath,"r")}catch(error){if(error?.code==="ENOENT")return null;throw error}try{const stats=await handle.stat();const text=await handle.readFile("utf8");const state={ino:stats.ino,mtimeMs:stats.mtimeMs,pid:null,start:null,token:null};try{const value=JSON.parse(text);if(Number.isInteger(value?.pid)&&value.pid>0)state.pid=value.pid;if(typeof value?.start==="string")state.start=value.start;if(typeof value?.token==="string")state.token=value.token}catch{}return state}finally{await handle.close().catch(()=>{})}}function isSameLock(state,ino,token){return state!==null&&state.ino===ino&&state.token===token}var LOCK_POLL_INTERVAL_MS=250;var LOCK_RETRY_JITTER_MS=25;var LOCK_PUT_BACK_TIMEOUT_MS=30000;var localLocks=new Map;function isPidAlive(pid){try{process.kill(pid,0);return true}catch(error){if(error?.code==="EPERM")return true;if(error?.code==="ESRCH")return false;throw error}}async function unlinkIfPresent(target){await unlink2(target).catch((error)=>{if(error?.code!=="ENOENT")throw error})}async function isAbandoned(state,staleGraceMs){if(state.pid===null)return Date.now()-state.mtimeMs>=staleGraceMs;if(!isPidAlive(state.pid))return true;if(state.start===null)return false;const start=await processStartTime(state.pid);return start!==null&&start!==state.start}async function reclaimLock(lockPath,ino,token,{deadline=Date.now()+LOCK_PUT_BACK_TIMEOUT_MS,hooks={}}={}){if(!isSameLock(await readLockState(lockPath),ino,token)){return await stat(lockPath).catch(()=>null)===null}const movedPath=`${lockPath}.${process.pid}.${randomUUID2()}.stale`;await hooks.beforeMove?.();try{await rename(lockPath,movedPath)}catch(error){if(error?.code==="ENOENT")return true;throw error}await hooks.afterMove?.();if(isSameLock(await readLockState(movedPath).catch(()=>null),ino,token)){await unlinkIfPresent(movedPath);return true}await putBack(movedPath,lockPath,deadline,hooks);return false}async function putBack(movedPath,lockPath,deadline,hooks){for(;;){try{await link2(movedPath,lockPath);await unlinkIfPresent(movedPath);return}catch(error){if(error?.code==="ENOENT")return;if(error?.code!=="EEXIST")throw error}await hooks.onPutBackBlocked?.();if(await stat(movedPath).catch(()=>null)===null)return;const remainingMs=deadline-Date.now();if(remainingMs<=0)return;await waitForLockRelease(lockPath,Math.min(remainingMs,LOCK_POLL_INTERVAL_MS))}}async function releaseLock(lockPath,ino,token){const prefix=`${path3.basename(lockPath)}.`;const entries=await readdir(path3.dirname(lockPath)).catch(()=>[]);for(const entry of entries){if(!entry.startsWith(prefix)||!entry.endsWith(".stale"))continue;const moved=path3.join(path3.dirname(lockPath),entry);if(isSameLock(await readLockState(moved).catch(()=>null),ino,token)){await unlinkIfPresent(moved)}}if(!isSameLock(await readLockState(lockPath),ino,token))return;await unlinkIfPresent(lockPath)}function waitForLockRelease(lockPath,timeoutMs){return new Promise((resolve,reject)=>{let settled=false;let watcher;let timer;const finish=(error,released)=>{if(settled)return;settled=true;clearTimeout(timer);watcher?.close();if(error)reject(error);else resolve(released)};const check=()=>{stat(lockPath).then(()=>{},(error)=>{if(error?.code==="ENOENT")finish(null,true);else finish(error)})};try{watcher=watch(path3.dirname(lockPath),(event,filename)=>{if((event==="rename"||event==="change")&&(!filename||filename.toString()===path3.basename(lockPath))){check()}})}catch(error){if(error?.code!=="ENOENT"){finish(error);return}}timer=setTimeout(()=>finish(null,false),timeoutMs);check()})}async function acquireLock(lockPath,timeoutMs,staleGraceMs){const deadline=Date.now()+timeoutMs;let holderPid=null;for(;;){const ours=await createLock(lockPath);if(ours!==null)return()=>releaseLock(lockPath,ours.ino,ours.token);if(Date.now()>=deadline){throw new Error(`timed out waiting for instance lock held by pid ${holderPid??"unknown"}`)}const state=await readLockState(lockPath);if(state===null)continue;holderPid=state.pid??holderPid;if(await isAbandoned(state,staleGraceMs)){await reclaimLock(lockPath,state.ino,state.token,{deadline});await sleep(Math.random()*LOCK_RETRY_JITTER_MS);continue}const remainingMs=deadline-Date.now();if(remainingMs>0){await waitForLockRelease(lockPath,Math.min(remainingMs,LOCK_POLL_INTERVAL_MS))}}}async function acquireLocalLock(key){const previous=localLocks.get(key)??Promise.resolve();let releaseCurrent;const current=new Promise((resolve)=>{releaseCurrent=resolve});const tail=previous.then(()=>current);localLocks.set(key,tail);await previous;return()=>{releaseCurrent();if(localLocks.get(key)===tail)localLocks.delete(key)}}async function withLock(lockPath,{timeoutMs,staleGraceMs},run){const releaseLocal=await acquireLocalLock(lockPath);try{const release=await acquireLock(lockPath,timeoutMs,staleGraceMs);try{return await run()}finally{await release()}}finally{releaseLocal()}}import{watch as watch2}from"node:fs";import{readFile as readFile2,stat as stat2}from"node:fs/promises";import path4 from"node:path";var ACTIVE_PORT_POLL_MS=100;function httpEndpointFromWebSocket(webSocketUrl){const endpoint=new URL(webSocketUrl);endpoint.protocol=endpoint.protocol==="wss:"?"https:":"http:";endpoint.pathname="/";endpoint.search="";endpoint.hash="";return endpoint.toString().replace(/\/$/,"")}function parseActivePort(text){const[portLine,browserPath]=text.trim().split(/\r?\n/);const port=Number(portLine);if(!Number.isInteger(port)||port<1||port>65535)return null;return{endpoint:`http://127.0.0.1:${port}`,browserPath:browserPath?.trim()||null}}function activePortIdentity(info){return{ino:info.ino,mtimeMs:info.mtimeMs,size:info.size}}async function snapshotActivePort(profileDir){if(!profileDir)return null;try{return activePortIdentity(await stat2(path4.join(profileDir,"DevToolsActivePort")))}catch(error){if(error?.code==="ENOENT")return null;throw error}}function isSameFile(info,previous){return previous!==null&&info.ino===previous.ino&&info.mtimeMs===previous.mtimeMs&&info.size===previous.size}function assertLaunchedBrowser(child,report,webSocketDebuggerUrl){if(child.exitCode!==null||child.signalCode!==null){throw new Error(`browser exited before its DevTools endpoint ${report.endpoint} could be verified`)}const answered=new URL(webSocketDebuggerUrl).pathname;if(report.browserPath===null||answered!==report.browserPath){throw new Error(`DevTools endpoint ${report.endpoint} answers as ${answered}, not as the launched browser (${report.browserPath??"no browser id reported"})`)}}async function discoverLaunchedEndpoint(child,{profileDir,timeoutMs,previousActivePort=null}={}){const activePortPath=profileDir?path4.join(profileDir,"DevToolsActivePort"):null;return new Promise((resolve,reject)=>{let settled=false;let stderr="";let activePortWatcher;let activePortReading=false;let activePortChangedWhileReading=false;const cleanups=[];const finish=(error,endpoint)=>{if(settled)return;settled=true;for(const cleanup of cleanups.splice(0))cleanup();activePortWatcher?.close();if(error)reject(error);else resolve(endpoint)};const readActivePort=async()=>{const info=await stat2(activePortPath);if(isSameFile(activePortIdentity(info),previousActivePort))return;const report=parseActivePort(await readFile2(activePortPath,"utf8"));if(report)finish(null,report)};const tryActivePort=async()=>{if(!activePortPath||settled)return;if(activePortReading){activePortChangedWhileReading=true;return}activePortReading=true;try{do{activePortChangedWhileReading=false;await readActivePort()}while(activePortChangedWhileReading&&!settled)}catch(error){if(error?.code!=="ENOENT")finish(error)}finally{activePortReading=false}};const onStderr=(chunk)=>{stderr=`${stderr}${chunk}`.slice(-16384);const match=/DevTools listening on (ws:\/\/\S+)/.exec(stderr);if(match){finish(null,{endpoint:httpEndpointFromWebSocket(match[1]),browserPath:new URL(match[1]).pathname})}else tryActivePort()};const onError=(error)=>finish(error);const onExit=(code,signal)=>{finish(new Error(`browser exited before exposing DevTools (code ${code}, signal ${signal??"none"})${stderr?`+${stderr}`:""}`))};child.stderr.setEncoding("utf8");child.stderr.on("data",onStderr);child.once("error",onError);child.once("exit",onExit);cleanups.push(()=>child.stderr.off("data",onStderr));cleanups.push(()=>child.off("error",onError));cleanups.push(()=>child.off("exit",onExit));if(activePortPath){try{activePortWatcher=watch2(profileDir,(event,filename)=>{if((event==="rename"||event==="change")&&(!filename||filename.toString()===path4.basename(activePortPath))){tryActivePort()}})}catch(error){if(error?.code!=="ENOENT")finish(error)}tryActivePort();const poll=setInterval(()=>void tryActivePort(),ACTIVE_PORT_POLL_MS);cleanups.push(()=>clearInterval(poll))}const timeout=setTimeout(()=>{finish(new Error(`browser did not expose a DevTools endpoint within ${timeoutMs}ms${stderr?`+${stderr}`:""}`))},timeoutMs);cleanups.push(()=>clearTimeout(timeout))})}var RECORD_VERSION=2;var DEFAULT_REGISTRY_ROOT=path5.join(os.homedir(),".local","share","omowright","instances");var DEFAULT_PROBE_TIMEOUT_MS=1000;var DEFAULT_LAUNCH_TIMEOUT_MS=1e4;var DEFAULT_CONNECT_TIMEOUT_MS=1e4;var LOCK_TIMEOUT_MARGIN_MS=5000;var DEFAULT_LOCK_TIMEOUT_MS=resolveLockTimeoutMs({});var STALE_LOCK_GRACE_MS=DEFAULT_LOCK_TIMEOUT_MS;function normalizeName(name){if(typeof name!=="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)){throw new TypeError("instance name must start with a letter or number and contain only letters, numbers, dots, dashes, or underscores")}return name}function registryPaths(registryRoot,name){const root=path5.resolve(registryRoot??DEFAULT_REGISTRY_ROOT);return{root,recordPath:path5.join(root,`${name}.json`),lockPath:path5.join(root,`${name}.lock`)}}async function ensureRegistryRoot(root){await mkdir3(root,{recursive:true,mode:448});await chmod2(root,448)}function isRecord(value,expectedName){return value!==null&&typeof value==="object"&&value.version===RECORD_VERSION&&value.name===expectedName&&Number.isInteger(value.pid)&&value.pid>0&&typeof value.endpoint==="string"&&value.endpoint.length>0&&typeof value.webSocketDebuggerUrl==="string"&&value.webSocketDebuggerUrl.length>0&&(typeof value.profileDir==="string"||value.profileDir===null)&&typeof value.browserPath==="string"&&value.browserPath.length>0&&typeof value.startedAt==="string"&&!Number.isNaN(Date.parse(value.startedAt))}async function readRecord(recordPath,expectedName){let text;try{text=await readFile3(recordPath,"utf8")}catch(error){if(error?.code==="ENOENT")return{exists:false,record:null};throw error}try{const record=JSON.parse(text);return{exists:true,record:isRecord(record,expectedName)?record:null}}catch{return{exists:true,record:null}}}async function writeRecordAtomic(root,recordPath,record){const tempPath=path5.join(root,`.${record.name}.${process.pid}.${randomUUID3()}.tmp`);let handle;try{handle=await open3(tempPath,"wx",384);await handle.writeFile(`${JSON.stringify(record,null,2)}+`,"utf8");await handle.close();handle=null;await chmod2(tempPath,384);await rename2(tempPath,recordPath);await chmod2(recordPath,384)}catch(error){await handle?.close().catch(()=>{});await unlink3(tempPath).catch(()=>{});throw error}}function isConnectionRefused(error){for(let cause=error;cause;cause=cause?.cause){if(cause.code==="ECONNREFUSED"||cause.code==="ENOTFOUND"||cause.code==="ConnectionRefused"){return true}}return false}async function probeEndpoint(endpoint,timeoutMs){const versionUrl=new URL("/json/version",endpoint);const response=await fetch(versionUrl,{signal:AbortSignal.timeout(timeoutMs)});if(!response.ok){throw new Error(`CDP discovery request failed (${response.status} ${response.statusText})`)}const version=await response.json();if(typeof version?.webSocketDebuggerUrl!=="string"||version.webSocketDebuggerUrl.length===0){throw new Error("CDP discovery response lacks webSocketDebuggerUrl")}return version}function resolveConnectTimeoutMs(options){return options.connectTimeoutMs??DEFAULT_CONNECT_TIMEOUT_MS}function resolveLockTimeoutMs(options){if(options.lockTimeoutMs!==undefined)return options.lockTimeoutMs;return(options.launchTimeoutMs??DEFAULT_LAUNCH_TIMEOUT_MS)+(options.probeTimeoutMs??DEFAULT_PROBE_TIMEOUT_MS)+resolveConnectTimeoutMs(options)+LOCK_TIMEOUT_MARGIN_MS}function nameLockOptions(options){return{timeoutMs:resolveLockTimeoutMs(options),staleGraceMs:STALE_LOCK_GRACE_MS}}async function connectWithin(endpoint,options,timeoutMs){const pending=openConnection(endpoint,options);let timer;try{return await Promise.race([pending,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`timed out after ${timeoutMs}ms opening a CDP session on ${endpoint}`)),timeoutMs)})])}catch(error){pending.then((connection)=>connection.close().catch(()=>{}),()=>{});throw error}finally{clearTimeout(timer)}}async function removeOwnedRecord(recordPath,name,pid){const loaded=await readRecord(recordPath,name);if(loaded.record?.pid!==pid)return;await unlinkIfPresent(recordPath)}function profileDirFromArgs(browserArgs){for(let index=0;index<browserArgs.length;index+=1){const argument=browserArgs[index];if(argument==="--user-data-dir"&&browserArgs[index+1]){return path5.resolve(browserArgs[index+1])}if(argument.startsWith("--user-data-dir=")){return path5.resolve(argument.slice("--user-data-dir=".length))}}return null}async function terminateBrowser(child){if(!child||child.exitCode!==null||child.signalCode!==null)return;const exited=new Promise((resolve)=>child.once("exit",resolve));child.kill("SIGTERM");let forceTimer;const force=new Promise((resolve)=>{forceTimer=setTimeout(()=>{if(child.exitCode===null&&child.signalCode===null){child.kill("SIGKILL")}resolve()},5000)});await Promise.race([exited,force]);clearTimeout(forceTimer);if(child.exitCode===null&&child.signalCode===null)await exited}function connectionOptions(options,profileDir){const result={...options.connectionOptions??{}};if(options.storageRoot!==undefined)result.storageRoot=options.storageRoot;else if(result.storageRoot===undefined&&profileDir){result.storageRoot=profileDir}if(options.client!==undefined){result.client={...result.client??{},...options.client}}if(options.dialogPolicy!==undefined)result.dialogPolicy=options.dialogPolicy;return result}async function launchNamed(name,{root,recordPath,lockPath},options){if(typeof options.browserPath!=="string"||options.browserPath.length===0){throw new TypeError(`connectNamed("${name}") requires browserPath when no healthy instance is registered`)}const browserArgs=[...options.browserArgs??[]];const profileDir=options.profileDir?path5.resolve(options.profileDir):profileDirFromArgs(browserArgs);const previousActivePort=await snapshotActivePort(profileDir);const child=spawn2(options.browserPath,[...browserArgs,"--remote-debugging-address=127.0.0.1","--remote-debugging-port=0"],{...options.spawnOptions??{},stdio:["ignore","ignore","pipe"]});let connection;try{const launchTimeoutMs=options.launchTimeoutMs??DEFAULT_LAUNCH_TIMEOUT_MS;const report=await discoverLaunchedEndpoint(child,{profileDir,timeoutMs:launchTimeoutMs,previousActivePort});const{endpoint}=report;const{webSocketDebuggerUrl}=await probeEndpoint(endpoint,launchTimeoutMs);assertLaunchedBrowser(child,report,webSocketDebuggerUrl);connection=await connectWithin(endpoint,connectionOptions(options,profileDir),resolveConnectTimeoutMs(options));const record={version:RECORD_VERSION,name,pid:child.pid,endpoint,webSocketDebuggerUrl,profileDir,browserPath:path5.resolve(options.browserPath),startedAt:new Date().toISOString()};await writeRecordAtomic(root,recordPath,record);connection.browserProcess=child;const disconnect=connection.close.bind(connection);connection.close=async()=>{let failure;try{await disconnect()}catch(error){failure=error}await terminateBrowser(child);try{await withLock(lockPath,nameLockOptions(options),()=>removeOwnedRecord(recordPath,name,child.pid))}catch(error){failure??=error}if(failure)throw failure};return connection}catch(error){await connection?.close().catch(()=>{});await terminateBrowser(child);throw error}}async function withEngineLock(registryRoot,engineKey,run){const root=path5.resolve(registryRoot??DEFAULT_REGISTRY_ROOT);await ensureRegistryRoot(root);const digest=createHash("sha256").update(path5.resolve(engineKey)).digest("hex").slice(0,16);const lockPath=path5.join(root,`_engine-${digest}.lock`);return withLock(lockPath,{timeoutMs:DEFAULT_LOCK_TIMEOUT_MS,staleGraceMs:STALE_LOCK_GRACE_MS},run)}async function connectNamed(name,options={}){const normalizedName=normalizeName(name);const paths=registryPaths(options.registryRoot,normalizedName);await ensureRegistryRoot(paths.root);return withLock(paths.lockPath,nameLockOptions(options),()=>attachOrLaunch(normalizedName,paths,options))}async function attachOrLaunch(normalizedName,paths,options){const loaded=await readRecord(paths.recordPath,normalizedName);if(loaded.record){await chmod2(paths.recordPath,384);if(isPidAlive(loaded.record.pid)){let version=null;try{version=await probeEndpoint(loaded.record.endpoint,options.probeTimeoutMs??DEFAULT_PROBE_TIMEOUT_MS)}catch(error){if(!isConnectionRefused(error)){throw new Error(`unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${error.message}`,{cause:error})}}if(version?.webSocketDebuggerUrl===loaded.record.webSocketDebuggerUrl){const{webSocketDebuggerUrl}=loaded.record;const timeoutMs=resolveConnectTimeoutMs(options);try{return await acquireSharedConnection(webSocketDebuggerUrl,connectionOptions(options,loaded.record.profileDir),{open:(shared)=>connectWithin(webSocketDebuggerUrl,shared,timeoutMs),timeoutMs})}catch(error){throw new Error(`unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${error.message}`,{cause:error})}}}}if(loaded.exists){await unlink3(paths.recordPath).catch((error)=>{if(error?.code!=="ENOENT")throw error})}return await launchNamed(normalizedName,paths,options)}async function listInstances(options={}){const root=path5.resolve(options.registryRoot??DEFAULT_REGISTRY_ROOT);await ensureRegistryRoot(root);const entries=await readdir2(root,{withFileTypes:true});const records=await Promise.all(entries.filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).map(async(entry)=>{const expectedName=entry.name.slice(0,-".json".length);const recordPath=path5.join(root,entry.name);const loaded=await readRecord(recordPath,expectedName);if(!loaded.record)return null;await chmod2(recordPath,384);const alive=isPidAlive(loaded.record.pid);let responsive=false;if(alive){responsive=await probeEndpoint(loaded.record.endpoint,options.probeTimeoutMs??DEFAULT_PROBE_TIMEOUT_MS).then((version)=>version.webSocketDebuggerUrl===loaded.record.webSocketDebuggerUrl,()=>false)}return{...loaded.record,alive,responsive}}));return records.filter((record)=>record!==null).sort((left,right)=>left.name.localeCompare(right.name))}import{randomInt}from"node:crypto";import{chmod as chmod3,mkdir as mkdir4,open as open4,readFile as readFile4}from"node:fs/promises";import{globSync}from"node:fs";import os2 from"node:os";import path6 from"node:path";var LEGACY_CLOAK_PROBE_URL="http://127.0.0.1:9242";var LEGACY_PROBE_TIMEOUT_MS=1500;var MIN_FINGERPRINT_SEED=1e4;var MAX_FINGERPRINT_SEED=99999;var METADATA_FILE=".omowright-cloak.json";var DEFAULT_PROFILE_DIR=path6.join(os2.homedir(),".local","share","omowright-cloak");function normalizeFingerprintSeed(value){const seed=typeof value==="string"&&value.trim()!==""?Number(value):value;if(!Number.isInteger(seed)||seed<MIN_FINGERPRINT_SEED||seed>MAX_FINGERPRINT_SEED){throw new RangeError(`fingerprint seed must be an integer from ${MIN_FINGERPRINT_SEED} to ${MAX_FINGERPRINT_SEED}`)}return seed}function platformFingerprint(){return process.platform==="darwin"?"macos":"windows"}function identityFlag(value){return/^(--user-data-dir|--fingerprint|--fingerprint-platform)(?:=|$)/.test(value)}function buildCloakBrowserArgs({profileDir,fingerprintSeed,extraArgs=[]}={}){const profile=path6.resolve(profileDir??DEFAULT_PROFILE_DIR);const seed=normalizeFingerprintSeed(fingerprintSeed);const conflicting=extraArgs.filter(identityFlag);if(conflicting.length>0){throw new Error(`extraArgs cannot override fixed profile identity: ${conflicting.join(", ")}`)}return["--no-first-run","--no-default-browser-check","--disable-session-crashed-bubble",`--user-data-dir=${profile}`,`--fingerprint=${seed}`,`--fingerprint-platform=${platformFingerprint()}`,...extraArgs]}async function readMetadata(metadataPath){try{const parsed=JSON.parse(await readFile4(metadataPath,"utf8"));return normalizeFingerprintSeed(parsed.fingerprintSeed)}catch(error){if(error?.code==="ENOENT")return null;if(error instanceof SyntaxError){throw new Error(`invalid CloakBrowser profile metadata: ${metadataPath}`)}throw error}}async function writeMetadata(metadataPath,fingerprintSeed){const handle=await open4(metadataPath,"wx",384);try{await handle.writeFile(`${JSON.stringify({fingerprintSeed},null,2)}+`,"utf8")}finally{await handle.close()}await chmod3(metadataPath,384)}async function resolveCloakProfile({profileDir=DEFAULT_PROFILE_DIR,fingerprintSeed,randomSeed=()=>randomInt(MIN_FINGERPRINT_SEED,MAX_FINGERPRINT_SEED+1)}={}){const resolvedProfile=path6.resolve(profileDir);const metadataPath=path6.join(resolvedProfile,METADATA_FILE);await mkdir4(resolvedProfile,{recursive:true,mode:448});await chmod3(resolvedProfile,448);const requested=fingerprintSeed===undefined?null:normalizeFingerprintSeed(fingerprintSeed);let stored=await readMetadata(metadataPath);if(stored===null){const candidate=requested??normalizeFingerprintSeed(randomSeed());try{await writeMetadata(metadataPath,candidate);stored=candidate}catch(error){if(error?.code!=="EEXIST")throw error;stored=await readMetadata(metadataPath);if(stored===null){throw new Error(`CloakBrowser profile seed metadata disappeared: ${metadataPath}`)}}}if(requested!==null&&requested!==stored){throw new Error(`fingerprint seed mismatch: profile is fixed at ${stored}, requested ${requested}`)}await chmod3(metadataPath,384);return{profileDir:resolvedProfile,metadataPath,fingerprintSeed:stored,browserArgs:buildCloakBrowserArgs({profileDir:resolvedProfile,fingerprintSeed:stored})}}function findCloakBrowserPath({browserRoot=path6.join(os2.homedir(),".cloakbrowser")}={}){const candidates=globSync(path6.join(path6.resolve(browserRoot),"chromium-*","Chromium.app","Contents","MacOS","Chromium")).sort();const browserPath=candidates.at(-1);if(!browserPath){throw new Error(`CloakBrowser binary not found under ${path6.resolve(browserRoot)}; set CLOAKBROWSER_BIN`)}return browserPath}async function assertCloakLaunchClear({browserPath,profileDir,registryRoot,legacyProbeUrl=LEGACY_CLOAK_PROBE_URL,probeTimeoutMs}){const records=await listInstances({registryRoot,probeTimeoutMs});for(const record of records){if(!record.alive||!record.responsive)continue;if(!record.profileDir)continue;if(path6.resolve(record.profileDir)===path6.resolve(profileDir))continue;if(path6.resolve(record.browserPath)!==path6.resolve(browserPath))continue;throw new Error(`CloakBrowser allows one instance: "${record.name}" (pid ${record.pid}, profile ${record.profileDir}) is live — connectNamed("${record.name}") to reuse it or close it first`)}const legacyHost=new URL(legacyProbeUrl).host;const explainedByRecord=records.some((record)=>record.alive&&record.responsive&&new URL(record.endpoint).host===legacyHost);if(explainedByRecord)return;try{const response=await fetch(new URL("/json/version",legacyProbeUrl),{signal:AbortSignal.timeout(probeTimeoutMs??LEGACY_PROBE_TIMEOUT_MS)});if(response.ok){throw new Error(`an unregistered CloakBrowser is answering on ${legacyProbeUrl} — attach with connect("${legacyProbeUrl}") or close it before launching`)}}catch(error){const unreachable=error instanceof TypeError||error?.name==="TimeoutError"||error?.name==="AbortError";if(!unreachable)throw error}}async function connectCloakProfile({browserPath=process.env.CLOAKBROWSER_BIN??findCloakBrowserPath(),profileDir=process.env.CLOAK_PROFILE_DIR??DEFAULT_PROFILE_DIR,fingerprintSeed=process.env.CLOAK_FINGERPRINT_SEED,browserArgs=[],storageRoot,name,...options}={}){const profile=await resolveCloakProfile({profileDir,fingerprintSeed});const resolvedBrowserArgs=buildCloakBrowserArgs({profileDir:profile.profileDir,fingerprintSeed:profile.fingerprintSeed,extraArgs:browserArgs});if(name===undefined){return connectPipe({browserPath,browserArgs:resolvedBrowserArgs,storageRoot:storageRoot??profile.profileDir,...options})}const{legacyProbeUrl,...connectOptions}=options;return withEngineLock(connectOptions.registryRoot,browserPath,async()=>{await assertCloakLaunchClear({browserPath,profileDir:profile.profileDir,registryRoot:connectOptions.registryRoot,legacyProbeUrl,probeTimeoutMs:connectOptions.probeTimeoutMs});return connectNamed(name,{browserPath,browserArgs:resolvedBrowserArgs,profileDir:profile.profileDir,storageRoot:storageRoot??profile.profileDir,...connectOptions})})}var SNAPSHOT_PARSE_ERROR="compactSnapshot expected a snapshot() result (JSON string or {tree, refs} object)";function compactSnapshot(snapshot){const obj=typeof snapshot==="string"?JSON.parse(snapshot):snapshot;if(!obj||typeof obj.tree!=="string")throw new TypeError(SNAPSHOT_PARSE_ERROR);return obj.tree}function snapshotTokens(snapshot){const text=typeof snapshot==="string"?snapshot:JSON.stringify(snapshot);return{bytes:Buffer.byteLength(text,"utf8"),estTokens:Math.ceil(Buffer.byteLength(text,"utf8")/4)}}var toolSchemas=[{name:"newTab",description:"Open a tab and return its page. Waits for interactivity.",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"]}},{name:"attachPage",description:"Attach to an existing tab by targetId from listTargets().",parameters:{type:"object",properties:{targetId:{type:"string"}},required:["targetId"]}},{name:"page.goto",description:"Navigate the page; resolves when the page looks interactive.",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"]}},{name:"page.snapshot",description:"PRIMARY page read. Returns a compact a11y tree; interactive elements carry [ref=eN] ids for page.locator. Options: maxDepth, maxChars, interactive, showHidden, selector, ref.",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"page.locator",description:"Resolve a ref id (e.g. 'e1') or CSS selector to a Locator: click, fill, press, hover, check, selectOption, dragTo, setInputFiles, textContent, isVisible, waitFor.",parameters:{type:"object",properties:{selectorOrRef:{type:"string"}},required:["selectorOrRef"]}},{name:"page.evaluate",description:"Run JS in the page and return the result.",parameters:{type:"object",properties:{expression:{type:"string"}},required:["expression"]}},{name:"page.screenshot",description:"Capture page image bytes (path, fullPage, clip, type, quality).",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"page.pdf",description:"Print the page to PDF bytes (path, format, margin, printBackground).",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"compactSnapshot",description:"Pass page.snapshot() output through this before reading: returns the raw tree without the refs map (refs resolve in-page; the map is ~54% of bytes on real pages).",parameters:{type:"object",properties:{snapshot:{}},required:["snapshot"]}},{name:"createCua",description:"Coordinate fallback for UI that refs cannot target: click/doubleClick/drag/move/scroll/type/keypress at viewport points, getVisibleScreenshot() as base64 PNG.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"createCaptcha",description:"Captcha helpers: click(bounds) and drag(from,to) return a post-action snapshot tree; readText(bounds?) OCRs a screenshot region (macOS Vision default, custom ocr injectable).",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"createChromeApi",description:"Chrome MV3-shaped APIs: tabs.query/get, windows.*, bookmarks/history/topSites (read-only from profile files), downloads.search/download. Writes throw UnsupportedOperationError.",parameters:{type:"object",properties:{connection:{},options:{type:"object"}},required:["connection"]}},{name:"injectCookies",description:"Inject raw cookie exports into a page with CDP sanitization handled (negative expires dropped, __Host- forced secure+root path+url-scoped, SameSite=None dropped when not secure, name+domain deduped).",parameters:{type:"object",properties:{page:{},cookies:{type:"array"}},required:["page","cookies"]}},{name:"createNetworkSnoop",description:"Buffer a page's CDP network traffic and return {pop,peek,popJson,waitFor,summary,dispose}; match is a predicate or {url,method,mimeType,resourceType}.",parameters:{type:"object",properties:{page:{},match:{},bodies:{type:"boolean"},maxEntries:{type:"number"},maxBodyBytes:{type:"number"}},required:["page"]}},{name:"snoop.waitFor",description:"Wait until a finished entry matches a predicate or {url,method,mimeType,resourceType}; timeoutMs defaults to 30000.",parameters:{type:"object",properties:{match:{},timeoutMs:{type:"number"}}}},{name:"snoop.popJson",description:"Drain the buffer and parse JSON bodies; skips non-JSON mime types and payloads that fail to parse.",parameters:{type:"object",properties:{}}},{name:"snoop.summary",description:"Return a compact text view of buffered entries (method, status, mimeType, size, url) capped by {max}.",parameters:{type:"object",properties:{max:{type:"number"}}}},{name:"collectWhileScrolling",description:"Async generator that scrolls the page, drains snoop.popJson(), and yields extracted items until minItems, maxScrolls, or noGrowth.",parameters:{type:"object",properties:{page:{},snoop:{},minItems:{type:"number"},maxScrolls:{type:"number"},extract:{},scroll:{type:"string",enum:["wheel","end"]},settleMs:{type:"number"}},required:["page","snoop"]}},{name:"createTrace",description:"Start a page flight recorder that writes dir/trace.jsonl, dir/trace.har, dir/summary.json and screenshots; never sends Runtime.enable.",parameters:{type:"object",properties:{page:{},dir:{type:"string"},screenshots:{type:"boolean"},network:{type:"boolean"},console:{type:"boolean"},maxBodyBytes:{type:"number"},events:{}},required:["page","dir"]}},{name:"trace.step",description:"Run named fn as a traced step with optional before/after screenshots; records the error and rethrows on failure.",parameters:{type:"object",properties:{name:{type:"string"},fn:{}},required:["name","fn"]}},{name:"trace.stop",description:"Flush listeners, write summary.json and trace.har, dispose the snoop, and return the summary for dir.",parameters:{type:"object",properties:{}}},{name:"reconcileFrames",description:"Adopt OOPIF iframe targets missing from FrameManager so later snapshots include them; returns the frames that were added.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"snapshotWithFrames",description:"Reconcile missing OOPIF frames then snapshot; refs stay page-level: page.locator(ref), never frame.locator.",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"connectPipe.dialogPolicy",description:"Wire connectPipe({dialogPolicy}), connect(url, {dialogPolicy}) and setDialogPolicy to {accept,promptText} or (dialog)=>boolean|{accept,promptText}; a throwing policy accepts.",parameters:{type:"object",properties:{accept:{type:"boolean"},promptText:{type:"string"}}}},{name:"requestHuman",description:"Pause for a human: inject a shadow-DOM Done banner, bringToFront first, and remove the banner on every path; until is {url}|{selector}|async predicate.",parameters:{type:"object",properties:{page:{},prompt:{type:"string"},until:{},timeoutMs:{type:"number"},pollMs:{type:"number"},signal:{}},required:["page"]}},{name:"describeLayers",description:"Sample a viewport grid and return {blocking,candidates,viewport} so overlay coverage and selectorHint are visible.",parameters:{type:"object",properties:{page:{},grid:{type:"number"}},required:["page"]}},{name:"snapshotWithLayers",description:"Prepend a @layers header to the snapshot tree and attach a layers field so overlays are visible before the a11y tree.",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"emulate",description:"Apply a DEVICE_PRESETS name, a custom metrics object, or null to restore the original UA captured on first call.",parameters:{type:"object",properties:{page:{},preset:{}},required:["page","preset"]}},{name:"createRoutes",description:"Install page request interception; Fetch.enable is sent only on the first route(); interception is fingerprintable, keep it off by default.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"route.continue",description:"Continue an intercepted request, optionally overriding url, method, headers, or postData.",parameters:{type:"object",properties:{url:{type:"string"},method:{type:"string"},headers:{type:"object"},postData:{}}}},{name:"route.fulfill",description:"Fulfill an intercepted request with {status,headers,contentType,body} instead of hitting the network.",parameters:{type:"object",properties:{status:{type:"number"},headers:{type:"object"},contentType:{type:"string"},body:{}}}},{name:"route.abort",description:"Abort an intercepted request with a CDP errorReason (defaults to Failed).",parameters:{type:"object",properties:{reason:{type:"string"}}}}];var MODIFIER_KEYS2=new Set(["Alt","Control","Meta","Shift"]);function splitModifiers(keys=[]){const modifiers=keys.filter((key)=>MODIFIER_KEYS2.has(key)||/^(cmd|command|ctrl|option|controlormeta)$/i.test(key));const rest=keys.filter((key)=>!modifiers.includes(key));return{modifiers,rest}}function createCua(page){async function holdModifiers(keys,fn){const{modifiers}=splitModifiers(keys);for(const key of modifiers)await page.keyboard.down(key);try{return await fn()}finally{for(const key of[...modifiers].reverse())await page.keyboard.up(key)}}return{page,async click({x,y,button="left",keypress}){await holdModifiers(keypress,()=>page.mouse.click(x,y,{button}))},async doubleClick({x,y,keypress}){await holdModifiers(keypress,()=>page.mouse.click(x,y,{clickCount:2}))},async drag({path,keys}){if(!Array.isArray(path)||path.length<2){throw new TypeError("cua.drag requires path with at least two points")}await holdModifiers(keys,async()=>{const[first,...rest]=path;await page.mouse.move(first.x,first.y);await page.mouse.down();try{for(const point of rest)await page.mouse.move(point.x,point.y)}finally{await page.mouse.up()}})},async getVisibleScreenshot(){const buffer=await page.screenshot({type:"png"});return buffer.toString("base64")},async keypress({keys}){if(!Array.isArray(keys)||keys.length===0){throw new TypeError("cua.keypress requires a non-empty keys array")}await page.keyboard.press(keys.join("+"))},async move({x,y,keys}){await holdModifiers(keys,()=>page.mouse.move(x,y))},async scroll({x,y,scrollX,scrollY,keypress}){await holdModifiers(keypress,async()=>{await page.mouse.move(x,y);await page.mouse.wheel(scrollX,scrollY)})},async type({text}){await page.keyboard.type(text)}}}import{spawn as spawn3}from"node:child_process";import{mkdtempSync,writeFileSync,rmSync}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import path7 from"node:path";var MAX_TIMER_MS=2147483647;var STOP=Symbol("wait stopped");async function waitForCaptcha(page,{until,timeoutMs=1e4,pollMs=100,signal}={}){if(typeof until!=="function")throw new TypeError("until must be a function");if(!Number.isFinite(timeoutMs)||timeoutMs<0||timeoutMs>MAX_TIMER_MS){throw new RangeError("timeoutMs must be between 0 and 2147483647")}if(!Number.isFinite(pollMs)||pollMs<=0||pollMs>MAX_TIMER_MS){throw new RangeError("pollMs must be greater than 0 and at most 2147483647")}if(signal!==undefined&&(typeof signal?.aborted!=="boolean"||typeof signal.addEventListener!=="function"||typeof signal.removeEventListener!=="function")){throw new TypeError("signal must be AbortSignal-compatible")}const started=performance.now();const deadline=started+timeoutMs;const operation=new AbortController;let deadlineTimer;let pollTimer;let stop;const stopped=new Promise((resolve)=>{stop=()=>resolve(STOP)});const terminal=()=>signal?.aborted?"cancelled":performance.now()>=deadline?"timed_out":null;const result=(outcome)=>({outcome,elapsedMs:performance.now()-started});const scheduleDeadline=()=>{const remaining=deadline-performance.now();if(remaining<=0)stop();else deadlineTimer=setTimeout(scheduleDeadline,Math.ceil(remaining))};try{const initial=terminal();if(initial)return result(initial);signal?.addEventListener("abort",stop,{once:true});scheduleDeadline();for(;;){let accepted;try{accepted=await Promise.race([Promise.resolve().then(()=>terminal()?STOP:until(page,{signal:operation.signal})),stopped])}catch(error){const outcome=terminal();if(outcome)return result(outcome);throw error}const outcome=terminal();if(outcome)return result(outcome);if(accepted===true)return result("matched");await Promise.race([new Promise((resolve)=>{pollTimer=setTimeout(resolve,Math.ceil(Math.min(pollMs,deadline-performance.now())))}),stopped]);clearTimeout(pollTimer);const afterDelay=terminal();if(afterDelay)return result(afterDelay)}}finally{clearTimeout(deadlineTimer);clearTimeout(pollTimer);signal?.removeEventListener("abort",stop);operation.abort();stop()}}var DEFAULT_DRAG_STEPS=20;var POST_ACTION_SETTLE_MS=3000;function validatePoint(point){if(!Number.isFinite(point?.x)||!Number.isFinite(point?.y)){throw new TypeError("point coordinates must be finite numbers")}}function validateSteps(steps){if(!Number.isSafeInteger(steps)||steps<=0){throw new RangeError("steps must be a positive safe integer")}}function validateSettleMs(value){if(!Number.isFinite(value)||value<0||value>2147483647){throw new RangeError("settleMs must be between 0 and 2147483647")}}var MACOS_VISION_OCR_SWIFT=`import Visionimport AppKitlet path = CommandLine.arguments[1]@@ -1496,31 +1487,31 @@ let text = (request.results ?? []).compactMap { $0.topCandidates(1).first?.string }.joined(separator: " ")print(text)-`;async function macOSVisionOcr(pngBuffer){if(process.platform!=="darwin"){throw new Error("macOSVisionOcr is only available on macOS; pass a custom ocr(buffer) instead")}const dir=mkdtempSync(path4.join(tmpdir2(),"omowright-ocr-"));try{const imagePath=path4.join(dir,"region.png");const scriptPath=path4.join(dir,"ocr.swift");writeFileSync(imagePath,pngBuffer);writeFileSync(scriptPath,MACOS_VISION_OCR_SWIFT);return await new Promise((resolve,reject)=>{const child=spawn2("swift",[scriptPath,imagePath],{stdio:["ignore","pipe","pipe"]});let stdout="";let stderr="";child.stdout.on("data",(chunk)=>{stdout+=chunk});child.stderr.on("data",(chunk)=>{stderr+=chunk});child.on("error",reject);child.on("close",(code)=>{if(code===0){const text=stdout.trim();resolve(text.length>0?text:null)}else{reject(new Error(`Vision OCR failed (exit ${code}): ${stderr.trim()}`))}})})}finally{rmSync(dir,{recursive:true,force:true})}}function createCaptcha(page,options={}){const ocr=options.ocr??macOSVisionOcr;function centerOf(bounds){validatePoint(bounds);if(!Number.isFinite(bounds.width)||bounds.width<=0||!Number.isFinite(bounds.height)||bounds.height<=0||!Number.isFinite(bounds.x+bounds.width)||!Number.isFinite(bounds.y+bounds.height)){throw new RangeError("bounds must have positive finite dimensions and finite edges")}return{x:bounds.x+bounds.width/2,y:bounds.y+bounds.height/2}}async function settleAndSnapshot(settleMs){await new Promise((resolve)=>setTimeout(resolve,settleMs));return compactSnapshot(await page.snapshot())}return{page,waitFor(opts){return waitForCaptcha(page,opts)},async click(bounds,opts={}){const center=centerOf(bounds);const point=opts.point===undefined?center:opts.point;validatePoint(point);if(point.x<bounds.x||point.x>=bounds.x+bounds.width||point.y<bounds.y||point.y>=bounds.y+bounds.height){throw new RangeError("point must be inside bounds")}const settleMs=opts.settleMs===undefined?POST_ACTION_SETTLE_MS:opts.settleMs;validateSettleMs(settleMs);if(opts.approachSteps!==undefined){validateSteps(opts.approachSteps);await page.mouse.move(point.x,point.y,{steps:opts.approachSteps})}await page.mouse.click(point.x,point.y);return settleAndSnapshot(settleMs)},async drag(from,to,opts={}){validatePoint(from);validatePoint(to);const steps=opts.steps===undefined?DEFAULT_DRAG_STEPS:opts.steps;validateSteps(steps);const settleMs=opts.settleMs===undefined?POST_ACTION_SETTLE_MS:opts.settleMs;validateSettleMs(settleMs);await page.mouse.move(from.x,from.y);await page.mouse.down();try{await page.mouse.move(to.x,to.y,{steps})}finally{await page.mouse.up()}return settleAndSnapshot(settleMs)},async readText(bounds){const buffer=await page.screenshot(bounds?{type:"png",clip:bounds}:{type:"png"});return ocr(buffer)}}}var EVENT_NAMES=["tabOpened","tabClosed","popupOpened","downloadStarted","downloadProgress","downloadFinished"];var BROWSER_EVENT_NAMES=Object.freeze([...EVENT_NAMES]);var DEFAULT_TIMEOUT=30000;var TERMINAL_LIMIT=4096;function pageTarget(info){return info?.type==="page"&&info?.targetId?info:null}function normalizeTarget(info){return{targetId:String(info.targetId),type:"page",url:info.url??"about:blank",title:info.title??"",openerId:info.openerId??null,openerFrameId:info.openerFrameId??null,browserContextId:info.browserContextId??null,attached:Boolean(info.attached),subtype:info.subtype??null}}function errorValue(value){return value instanceof Error?value:Error(String(value))}class BrowserEventBridge{#cdp;#options;#listeners=new Map;#unsubscribers=[];#targetInfos=new Map;#crashes=new Map;#downloads=new Map;#terminalDownloads=new Map;#terminal=new Set;#frameToTarget=new Map;#sessionToTarget=new Map;#waits=new Set;#disposed=false;#explicitDispose=false;ready;constructor(connection,options){if(!connection?.cdp)throw new TypeError("createEvents requires a browser connection");this.#cdp=connection.cdp;this.#options=this.#validate(options);this.#register();this.ready=this.#initialize()}#validate(options){const behavior=options.downloadBehavior??"default";if(!["default","allow","deny","allowAndName"].includes(behavior))throw new TypeError("Invalid downloadBehavior");if(behavior==="allow"&&!pathIsAbsolute(options.downloadPath))throw new TypeError("downloadPath must be an absolute path for allow");return{...options,downloadBehavior:behavior}}#register(){const on=(method,fn)=>this.#unsubscribers.push(this.#cdp.on(method,fn));on("Target.targetCreated",(info)=>this.#created(info,false));on("Target.targetDestroyed",(info)=>this.#destroyed(info));on("Target.targetInfoChanged",(info)=>{const target=pageTarget(info?.targetInfo);if(target&&this.#targetInfos.has(target.targetId))this.#targetInfos.set(target.targetId,normalizeTarget(target))});on("Target.targetCrashed",(info)=>{if(info?.targetId)this.#crashes.set(info.targetId,{status:info.status??"",errorCode:info.errorCode??0})});on("Target.attachedToTarget",(info,meta)=>{const targetId=info?.targetInfo?.targetId;const sessionId=info?.sessionId??meta?.sessionId;if(targetId&&sessionId){this.#sessionToTarget.set(sessionId,targetId)}});on("Target.detachedFromTarget",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId)this.#sessionToTarget.delete(sessionId)});on("Browser.downloadWillBegin",(info)=>this.#downloadBegin(info));on("Browser.downloadProgress",(info)=>this.#downloadProgress(info));on("Page.frameAttached",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId&&info?.frameId)this.#mapFrame(info.frameId,sessionId)});on("Page.frameNavigated",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId&&info?.frame?.id)this.#mapFrame(info.frame.id,sessionId)});if(this.#cdp.transportEvents?.on){this.#unsubscribers.push(this.#cdp.transportEvents.on("disconnected",()=>{this.#disconnectDownloads();this.#cancelWaits(Error("Browser transport disconnected"))}));this.#unsubscribers.push(this.#cdp.transportEvents.on("reconnected",()=>{this.#reconcile().catch((error)=>console.warn("[events] target reconciliation failed",error));this.#configureDownloads().catch((error)=>console.warn("[events] download reconfiguration failed",error))}))}}async#initialize(){await this.#cdp.ensureConnected();await this.#cdp.send("Target.setDiscoverTargets",{discover:true});const result=await this.#cdp.send("Target.getTargets");await this.#configureDownloads();const targets=(result?.targetInfos??[]).filter((info)=>pageTarget(info));targets.sort((a,b)=>Boolean(a.openerId)-Boolean(b.openerId));for(const info of targets)this.#created(info,true)}async#reconcile(){const result=await this.#cdp.send("Target.getTargets");const current=new Set((result?.targetInfos??[]).filter((info)=>pageTarget(info)).map((info)=>String(info.targetId)));for(const id of[...this.#targetInfos.keys()])if(!current.has(id))this.#destroyed({targetId:id});const targets=(result?.targetInfos??[]).filter((info)=>pageTarget(info));targets.sort((a,b)=>Boolean(a.openerId)-Boolean(b.openerId));for(const info of targets)this.#created(info,true)}async#configureDownloads(){const params={behavior:this.#options.downloadBehavior,eventsEnabled:true};if(this.#options.downloadBehavior==="allow"||this.#options.downloadBehavior==="allowAndName")params.downloadPath=this.#options.downloadPath;await this.#cdp.send("Browser.setDownloadBehavior",params)}#mapFrame(frameId,sessionId){const targetId=this.#sessionToTarget.get(sessionId)??[...this.#targetInfos.values()].find((info)=>info.attached&&info.targetId===sessionId)?.targetId;if(targetId)this.#frameToTarget.set(frameId,targetId)}#created(info,initial){const target=pageTarget(info?.targetInfo??info);if(!target)return;const normalized=normalizeTarget(target);const id=normalized.targetId;if(this.#targetInfos.has(id))return;this.#targetInfos.set(id,normalized);const popup=Boolean(normalized.openerId&&this.#targetInfos.has(normalized.openerId));this.#dispatch("tabOpened",{...normalized,popup,initial:Boolean(initial)});if(popup)this.#dispatch("popupOpened",{targetId:id,openerTargetId:normalized.openerId,openerFrameId:normalized.openerFrameId,url:normalized.url,title:normalized.title,initial:Boolean(initial)})}#destroyed(info){const id=info?.targetId;const last=this.#targetInfos.get(id);if(!last)return;this.#targetInfos.delete(id);const crash=this.#crashes.get(id)??null;this.#crashes.delete(id);for(const[frame,targetId]of this.#frameToTarget)if(targetId===id)this.#frameToTarget.delete(frame);this.#dispatch("tabClosed",{targetId:id,reason:crash?"crashed":"destroyed",lastKnown:last,crash})}#rememberTerminal(guid){this.#terminal.delete(guid);this.#terminal.add(guid);if(this.#terminal.size>TERMINAL_LIMIT){const oldest=this.#terminal.values().next().value;this.#terminal.delete(oldest);this.#terminalDownloads.delete(oldest)}}#downloadBegin(info={}){if(!info.guid||this.#terminal.has(info.guid))return;const record={guid:info.guid,url:info.url??null,suggestedFilename:info.suggestedFilename??"",frameId:info.frameId??null,targetId:this.#frameToTarget.get(info.frameId)??null,totalBytes:0,receivedBytes:0,filePath:null};this.#downloads.set(info.guid,record);this.#dispatch("downloadStarted",{guid:record.guid,url:record.url,suggestedFilename:record.suggestedFilename,frameId:record.frameId,targetId:record.targetId})}#downloadProgress(info={}){if(!info.guid)return;const alreadyTerminal=this.#terminal.has(info.guid);const record=this.#downloads.get(info.guid)??this.#terminalDownloads.get(info.guid);if(!record)return;Object.assign(record,{totalBytes:Number(info.totalBytes??0),receivedBytes:Number(info.receivedBytes??0),filePath:info.filePath??null});this.#dispatch("downloadProgress",{guid:info.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:info.state,filePath:record.filePath,targetId:record.targetId});if((info.state==="completed"||info.state==="canceled")&&!alreadyTerminal){this.#rememberTerminal(info.guid);this.#downloads.delete(info.guid);this.#terminalDownloads.set(info.guid,record);this.#dispatch("downloadFinished",{guid:info.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:info.state,cdpState:info.state,filePath:record.filePath,targetId:record.targetId,error:null})}}#disconnectDownloads(){if(this.#explicitDispose)return;for(const record of this.#downloads.values()){this.#rememberTerminal(record.guid);this.#dispatch("downloadFinished",{guid:record.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:"failed",cdpState:null,filePath:record.filePath,targetId:record.targetId,error:{code:"browserDisconnected",message:"Browser transport disconnected"}})}this.#downloads.clear()}#dispatch(name,payload){const listeners=[...this.#listeners.get(name)??[]];Promise.allSettled(listeners.map((listener)=>Promise.resolve().then(()=>listener(payload)))).then((results)=>results.filter((r)=>r.status==="rejected").forEach((r)=>console.warn(`[events] ${name} listener failed`,r.reason)))}on(name,listener){this.#assertName(name);if(typeof listener!=="function")throw new TypeError("listener must be a function");const set=this.#listeners.get(name)??new Set;set.add(listener);this.#listeners.set(name,set);return()=>this.off(name,listener)}off(name,listener){this.#assertName(name);this.#listeners.get(name)?.delete(listener)}#cancelWaits(error){for(const cancel of this.#waits)cancel(error);this.#waits.clear()}waitForEvent(name,options={}){this.#assertName(name);if(this.#disposed)return Promise.reject(Error("Events bridge is disposed"));const timeout=options.timeout??DEFAULT_TIMEOUT;return new Promise((resolve,reject)=>{let done=false;let timer;const off=this.on(name,async(value)=>{try{if(options.predicate&&!await options.predicate(value))return;if(done)return;done=true;clearTimeout(timer);this.#waits.delete(cancel);off();resolve(value)}catch(error){if(!done){done=true;clearTimeout(timer);this.#waits.delete(cancel);off();reject(errorValue(error))}}});const cancel=(error)=>{if(!done){done=true;clearTimeout(timer);this.#waits.delete(cancel);off();reject(error??Error("Events bridge disposed"))}};this.#waits.add(cancel);timer=setTimeout(()=>cancel(Error(`Timed out waiting for browser event "${name}"`)),timeout)})}#assertName(name){if(!EVENT_NAMES.includes(name))throw new TypeError(`Unknown browser event: ${String(name)}`)}async dispose(){if(this.#disposed)return;this.#disposed=true;this.#explicitDispose=true;this.#cancelWaits();for(const off of this.#unsubscribers)off();this.#unsubscribers=[];this.#listeners.clear();await this.ready.catch(()=>{})}}function pathIsAbsolute(value){return typeof value==="string"&&(value.startsWith("/")||/^[A-Za-z]:[\\/]/.test(value))}function createEvents(connection,options={}){return new BrowserEventBridge(connection,options)}init_agent_tabs();init_viewport();import{randomUUID}from"node:crypto";import path7 from"node:path";import{mkdir as mkdir4,open as open3,readFile as readFile2,rename,lstat,chmod as chmod2}from"node:fs/promises";import{homedir}from"node:os";import{TextDecoder as TextDecoder2}from"node:util";import{mkdirSync}from"node:fs";import path6 from"node:path";import{tmpdir as tmpdir3}from"node:os";import{existsSync,readFileSync as readFileSync2}from"node:fs";import path5 from"node:path";var DatabaseCtor;async function loadSqlite(){if(DatabaseCtor)return DatabaseCtor;try{const mod=await import("node:sqlite");DatabaseCtor=(file)=>new mod.DatabaseSync(file,{readOnly:true,readBigInts:true})}catch{const mod=await import("bun:sqlite");DatabaseCtor=(file)=>new mod.Database(file,{readonly:true})}return DatabaseCtor}var CHROME_EPOCH_OFFSET_MS=11644473600000;var chromeTimeToMs=(time)=>Number(BigInt(time)/1000n)-CHROME_EPOCH_OFFSET_MS;var msToChromeTime=(ms)=>BigInt(Math.floor((ms+CHROME_EPOCH_OFFSET_MS)*1000));var EXTENSION_BRIDGE_REQUIRED="requires the extension bridge in standalone OmOWright";function createProfileApis(profilePath){function profileDir(){if(!profilePath){throw new UnsupportedOperationError("chrome.bookmarks/history/topSites need a profilePath (the browser's user-data-dir); pass it to createChromeApi(connection, { profilePath })")}return path5.join(profilePath,"Default")}async function openDb(fileName){const file=path5.join(profileDir(),fileName);if(!existsSync(file))return null;const ctor=await loadSqlite();return ctor(file)}async function withDb(fileName,fn){const db=await openDb(fileName);if(!db)return[];try{return fn(db)}finally{db.close()}}function bookmarkRoots(){const file=path5.join(profileDir(),"Bookmarks");if(!existsSync(file))return[];const parsed=JSON.parse(readFileSync2(file,"utf8"));return Object.values(parsed.roots??{}).filter((node)=>node&&typeof node==="object"&&node.id)}function walkBookmarks(nodes,visit,acc=[]){for(const node of nodes){visit(node,acc);if(Array.isArray(node.children))walkBookmarks(node.children,visit,acc)}return acc}function findBookmark(id){for(const root of bookmarkRoots()){const found=walkBookmarks([root],(node,acc)=>{if(node.id===String(id))acc.push(node)});if(found.length>0)return found[0]}return null}function toBookmark(node){const out={id:node.id,title:node.name??"",type:node.type};if(node.url)out.url=node.url;if(node.date_added)out.dateAdded=chromeTimeToMs(node.date_added);if(node.children)out.children=node.children.map(toBookmark);return out}const bookmarks={async get(idOrIdList){const ids=Array.isArray(idOrIdList)?idOrIdList:[idOrIdList];return ids.map(findBookmark).filter(Boolean).map(toBookmark)},async getChildren(id){const node=findBookmark(id);return(node?.children??[]).map(toBookmark)},async getRecent(numberOfItems){const urls=walkBookmarks(bookmarkRoots(),(node,acc)=>{if(node.type==="url")acc.push(node)});return urls.sort((a,b)=>Number(b.date_added??0)-Number(a.date_added??0)).slice(0,numberOfItems).map(toBookmark)},async getSubTree(id){const node=findBookmark(id);return node?[toBookmark(node)]:[]},async getTree(){return bookmarkRoots().map(toBookmark)},async search(query){const needle=typeof query==="string"?query.toLowerCase():(query.query??"").toLowerCase();const url=typeof query==="object"?query.url?.toLowerCase():undefined;const title=typeof query==="object"?query.title?.toLowerCase():undefined;return walkBookmarks(bookmarkRoots(),(node,acc)=>{if(node.type!=="url")return;const name=(node.name??"").toLowerCase();const href=(node.url??"").toLowerCase();const ok=needle&&(name.includes(needle)||href.includes(needle))||url&&href.includes(url)||title&&name.includes(title);if(ok)acc.push(node)}).map(toBookmark)},async create(){throw new UnsupportedOperationError(`chrome.bookmarks.create ${EXTENSION_BRIDGE_REQUIRED}`)},async update(){throw new UnsupportedOperationError(`chrome.bookmarks.update ${EXTENSION_BRIDGE_REQUIRED}`)},async move(){throw new UnsupportedOperationError(`chrome.bookmarks.move ${EXTENSION_BRIDGE_REQUIRED}`)},async remove(){throw new UnsupportedOperationError(`chrome.bookmarks.remove ${EXTENSION_BRIDGE_REQUIRED}`)},async removeTree(){throw new UnsupportedOperationError(`chrome.bookmarks.removeTree ${EXTENSION_BRIDGE_REQUIRED}`)}};const history={async search(query){const text=`%${query.text??""}%`;const start=query.startTime!=null?msToChromeTime(query.startTime):0n;const end=query.endTime!=null?msToChromeTime(query.endTime):99999999999999999n;const max=query.maxResults??100;return await withDb("History",(db)=>db.prepare(`SELECT id, url, title, visit_count, last_visit_time FROM urls+`;async function macOSVisionOcr(pngBuffer){if(process.platform!=="darwin"){throw new Error("macOSVisionOcr is only available on macOS; pass a custom ocr(buffer) instead")}const dir=mkdtempSync(path7.join(tmpdir2(),"omowright-ocr-"));try{const imagePath=path7.join(dir,"region.png");const scriptPath=path7.join(dir,"ocr.swift");writeFileSync(imagePath,pngBuffer);writeFileSync(scriptPath,MACOS_VISION_OCR_SWIFT);return await new Promise((resolve,reject)=>{const child=spawn3("swift",[scriptPath,imagePath],{stdio:["ignore","pipe","pipe"]});let stdout="";let stderr="";child.stdout.on("data",(chunk)=>{stdout+=chunk});child.stderr.on("data",(chunk)=>{stderr+=chunk});child.on("error",reject);child.on("close",(code)=>{if(code===0){const text=stdout.trim();resolve(text.length>0?text:null)}else{reject(new Error(`Vision OCR failed (exit ${code}): ${stderr.trim()}`))}})})}finally{rmSync(dir,{recursive:true,force:true})}}function createCaptcha(page,options={}){const ocr=options.ocr??macOSVisionOcr;function centerOf(bounds){validatePoint(bounds);if(!Number.isFinite(bounds.width)||bounds.width<=0||!Number.isFinite(bounds.height)||bounds.height<=0||!Number.isFinite(bounds.x+bounds.width)||!Number.isFinite(bounds.y+bounds.height)){throw new RangeError("bounds must have positive finite dimensions and finite edges")}return{x:bounds.x+bounds.width/2,y:bounds.y+bounds.height/2}}async function settleAndSnapshot(settleMs){await new Promise((resolve)=>setTimeout(resolve,settleMs));return compactSnapshot(await page.snapshot())}return{page,waitFor(opts){return waitForCaptcha(page,opts)},async click(bounds,opts={}){const center=centerOf(bounds);const point=opts.point===undefined?center:opts.point;validatePoint(point);if(point.x<bounds.x||point.x>=bounds.x+bounds.width||point.y<bounds.y||point.y>=bounds.y+bounds.height){throw new RangeError("point must be inside bounds")}const settleMs=opts.settleMs===undefined?POST_ACTION_SETTLE_MS:opts.settleMs;validateSettleMs(settleMs);if(opts.approachSteps!==undefined){validateSteps(opts.approachSteps);await page.mouse.move(point.x,point.y,{steps:opts.approachSteps})}await page.mouse.click(point.x,point.y);return settleAndSnapshot(settleMs)},async drag(from,to,opts={}){validatePoint(from);validatePoint(to);const steps=opts.steps===undefined?DEFAULT_DRAG_STEPS:opts.steps;validateSteps(steps);const settleMs=opts.settleMs===undefined?POST_ACTION_SETTLE_MS:opts.settleMs;validateSettleMs(settleMs);await page.mouse.move(from.x,from.y);await page.mouse.down();try{await page.mouse.move(to.x,to.y,{steps})}finally{await page.mouse.up()}return settleAndSnapshot(settleMs)},async readText(bounds){const buffer=await page.screenshot(bounds?{type:"png",clip:bounds}:{type:"png"});return ocr(buffer)}}}var EVENT_NAMES=["tabOpened","tabClosed","popupOpened","downloadStarted","downloadProgress","downloadFinished"];var BROWSER_EVENT_NAMES=Object.freeze([...EVENT_NAMES]);var DEFAULT_TIMEOUT=30000;var TERMINAL_LIMIT=4096;function pageTarget(info){return info?.type==="page"&&info?.targetId?info:null}function normalizeTarget(info){return{targetId:String(info.targetId),type:"page",url:info.url??"about:blank",title:info.title??"",openerId:info.openerId??null,openerFrameId:info.openerFrameId??null,browserContextId:info.browserContextId??null,attached:Boolean(info.attached),subtype:info.subtype??null}}function errorValue(value){return value instanceof Error?value:Error(String(value))}class BrowserEventBridge{#cdp;#options;#listeners=new Map;#unsubscribers=[];#targetInfos=new Map;#crashes=new Map;#downloads=new Map;#terminalDownloads=new Map;#terminal=new Set;#frameToTarget=new Map;#sessionToTarget=new Map;#waits=new Set;#disposed=false;#explicitDispose=false;ready;constructor(connection,options){if(!connection?.cdp)throw new TypeError("createEvents requires a browser connection");this.#cdp=connection.cdp;this.#options=this.#validate(options);this.#register();this.ready=this.#initialize()}#validate(options){const behavior=options.downloadBehavior??"default";if(!["default","allow","deny","allowAndName"].includes(behavior))throw new TypeError("Invalid downloadBehavior");if(behavior==="allow"&&!pathIsAbsolute(options.downloadPath))throw new TypeError("downloadPath must be an absolute path for allow");return{...options,downloadBehavior:behavior}}#register(){const on=(method,fn)=>this.#unsubscribers.push(this.#cdp.on(method,fn));on("Target.targetCreated",(info)=>this.#created(info,false));on("Target.targetDestroyed",(info)=>this.#destroyed(info));on("Target.targetInfoChanged",(info)=>{const target=pageTarget(info?.targetInfo);if(target&&this.#targetInfos.has(target.targetId))this.#targetInfos.set(target.targetId,normalizeTarget(target))});on("Target.targetCrashed",(info)=>{if(info?.targetId)this.#crashes.set(info.targetId,{status:info.status??"",errorCode:info.errorCode??0})});on("Target.attachedToTarget",(info,meta)=>{const targetId=info?.targetInfo?.targetId;const sessionId=info?.sessionId??meta?.sessionId;if(targetId&&sessionId){this.#sessionToTarget.set(sessionId,targetId)}});on("Target.detachedFromTarget",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId)this.#sessionToTarget.delete(sessionId)});on("Browser.downloadWillBegin",(info)=>this.#downloadBegin(info));on("Browser.downloadProgress",(info)=>this.#downloadProgress(info));on("Page.frameAttached",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId&&info?.frameId)this.#mapFrame(info.frameId,sessionId)});on("Page.frameNavigated",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId&&info?.frame?.id)this.#mapFrame(info.frame.id,sessionId)});if(this.#cdp.transportEvents?.on){this.#unsubscribers.push(this.#cdp.transportEvents.on("disconnected",()=>{this.#disconnectDownloads();this.#cancelWaits(Error("Browser transport disconnected"))}));this.#unsubscribers.push(this.#cdp.transportEvents.on("reconnected",()=>{this.#reconcile().catch((error)=>console.warn("[events] target reconciliation failed",error));this.#configureDownloads().catch((error)=>console.warn("[events] download reconfiguration failed",error))}))}}async#initialize(){await this.#cdp.ensureConnected();await this.#cdp.send("Target.setDiscoverTargets",{discover:true});const result=await this.#cdp.send("Target.getTargets");await this.#configureDownloads();const targets=(result?.targetInfos??[]).filter((info)=>pageTarget(info));targets.sort((a,b)=>Boolean(a.openerId)-Boolean(b.openerId));for(const info of targets)this.#created(info,true)}async#reconcile(){const result=await this.#cdp.send("Target.getTargets");const current=new Set((result?.targetInfos??[]).filter((info)=>pageTarget(info)).map((info)=>String(info.targetId)));for(const id of[...this.#targetInfos.keys()])if(!current.has(id))this.#destroyed({targetId:id});const targets=(result?.targetInfos??[]).filter((info)=>pageTarget(info));targets.sort((a,b)=>Boolean(a.openerId)-Boolean(b.openerId));for(const info of targets)this.#created(info,true)}async#configureDownloads(){const params={behavior:this.#options.downloadBehavior,eventsEnabled:true};if(this.#options.downloadBehavior==="allow"||this.#options.downloadBehavior==="allowAndName")params.downloadPath=this.#options.downloadPath;await this.#cdp.send("Browser.setDownloadBehavior",params)}#mapFrame(frameId,sessionId){const targetId=this.#sessionToTarget.get(sessionId)??[...this.#targetInfos.values()].find((info)=>info.attached&&info.targetId===sessionId)?.targetId;if(targetId)this.#frameToTarget.set(frameId,targetId)}#created(info,initial){const target=pageTarget(info?.targetInfo??info);if(!target)return;const normalized=normalizeTarget(target);const id=normalized.targetId;if(this.#targetInfos.has(id))return;this.#targetInfos.set(id,normalized);const popup=Boolean(normalized.openerId&&this.#targetInfos.has(normalized.openerId));this.#dispatch("tabOpened",{...normalized,popup,initial:Boolean(initial)});if(popup)this.#dispatch("popupOpened",{targetId:id,openerTargetId:normalized.openerId,openerFrameId:normalized.openerFrameId,url:normalized.url,title:normalized.title,initial:Boolean(initial)})}#destroyed(info){const id=info?.targetId;const last=this.#targetInfos.get(id);if(!last)return;this.#targetInfos.delete(id);const crash=this.#crashes.get(id)??null;this.#crashes.delete(id);for(const[frame,targetId]of this.#frameToTarget)if(targetId===id)this.#frameToTarget.delete(frame);this.#dispatch("tabClosed",{targetId:id,reason:crash?"crashed":"destroyed",lastKnown:last,crash})}#rememberTerminal(guid){this.#terminal.delete(guid);this.#terminal.add(guid);if(this.#terminal.size>TERMINAL_LIMIT){const oldest=this.#terminal.values().next().value;this.#terminal.delete(oldest);this.#terminalDownloads.delete(oldest)}}#downloadBegin(info={}){if(!info.guid||this.#terminal.has(info.guid))return;const record={guid:info.guid,url:info.url??null,suggestedFilename:info.suggestedFilename??"",frameId:info.frameId??null,targetId:this.#frameToTarget.get(info.frameId)??null,totalBytes:0,receivedBytes:0,filePath:null};this.#downloads.set(info.guid,record);this.#dispatch("downloadStarted",{guid:record.guid,url:record.url,suggestedFilename:record.suggestedFilename,frameId:record.frameId,targetId:record.targetId})}#downloadProgress(info={}){if(!info.guid)return;const alreadyTerminal=this.#terminal.has(info.guid);const record=this.#downloads.get(info.guid)??this.#terminalDownloads.get(info.guid);if(!record)return;Object.assign(record,{totalBytes:Number(info.totalBytes??0),receivedBytes:Number(info.receivedBytes??0),filePath:info.filePath??null});this.#dispatch("downloadProgress",{guid:info.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:info.state,filePath:record.filePath,targetId:record.targetId});if((info.state==="completed"||info.state==="canceled")&&!alreadyTerminal){this.#rememberTerminal(info.guid);this.#downloads.delete(info.guid);this.#terminalDownloads.set(info.guid,record);this.#dispatch("downloadFinished",{guid:info.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:info.state,cdpState:info.state,filePath:record.filePath,targetId:record.targetId,error:null})}}#disconnectDownloads(){if(this.#explicitDispose)return;for(const record of this.#downloads.values()){this.#rememberTerminal(record.guid);this.#dispatch("downloadFinished",{guid:record.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:"failed",cdpState:null,filePath:record.filePath,targetId:record.targetId,error:{code:"browserDisconnected",message:"Browser transport disconnected"}})}this.#downloads.clear()}#dispatch(name,payload){const listeners=[...this.#listeners.get(name)??[]];Promise.allSettled(listeners.map((listener)=>Promise.resolve().then(()=>listener(payload)))).then((results)=>results.filter((r)=>r.status==="rejected").forEach((r)=>console.warn(`[events] ${name} listener failed`,r.reason)))}on(name,listener){this.#assertName(name);if(typeof listener!=="function")throw new TypeError("listener must be a function");const set=this.#listeners.get(name)??new Set;set.add(listener);this.#listeners.set(name,set);return()=>this.off(name,listener)}off(name,listener){this.#assertName(name);this.#listeners.get(name)?.delete(listener)}#cancelWaits(error){for(const cancel of this.#waits)cancel(error);this.#waits.clear()}waitForEvent(name,options={}){this.#assertName(name);if(this.#disposed)return Promise.reject(Error("Events bridge is disposed"));const timeout=options.timeout??DEFAULT_TIMEOUT;return new Promise((resolve,reject)=>{let done=false;let timer;const off=this.on(name,async(value)=>{try{if(options.predicate&&!await options.predicate(value))return;if(done)return;done=true;clearTimeout(timer);this.#waits.delete(cancel);off();resolve(value)}catch(error){if(!done){done=true;clearTimeout(timer);this.#waits.delete(cancel);off();reject(errorValue(error))}}});const cancel=(error)=>{if(!done){done=true;clearTimeout(timer);this.#waits.delete(cancel);off();reject(error??Error("Events bridge disposed"))}};this.#waits.add(cancel);timer=setTimeout(()=>cancel(Error(`Timed out waiting for browser event "${name}"`)),timeout)})}#assertName(name){if(!EVENT_NAMES.includes(name))throw new TypeError(`Unknown browser event: ${String(name)}`)}async dispose(){if(this.#disposed)return;this.#disposed=true;this.#explicitDispose=true;this.#cancelWaits();for(const off of this.#unsubscribers)off();this.#unsubscribers=[];this.#listeners.clear();await this.ready.catch(()=>{})}}function pathIsAbsolute(value){return typeof value==="string"&&(value.startsWith("/")||/^[A-Za-z]:[\\/]/.test(value))}function createEvents(connection,options={}){return new BrowserEventBridge(connection,options)}init_agent_tabs();init_viewport();import{randomUUID as randomUUID4}from"node:crypto";import path10 from"node:path";import{mkdir as mkdir5,open as open5,readFile as readFile5,rename as rename3,lstat,chmod as chmod4}from"node:fs/promises";import{homedir}from"node:os";import{TextDecoder as TextDecoder2}from"node:util";import{mkdirSync}from"node:fs";import path9 from"node:path";import{tmpdir as tmpdir3}from"node:os";import{existsSync,readFileSync as readFileSync2}from"node:fs";import path8 from"node:path";var DatabaseCtor;async function loadSqlite(){if(DatabaseCtor)return DatabaseCtor;try{const mod=await import("node:sqlite");DatabaseCtor=(file)=>new mod.DatabaseSync(file,{readOnly:true,readBigInts:true})}catch{const mod=await import("bun:sqlite");DatabaseCtor=(file)=>new mod.Database(file,{readonly:true})}return DatabaseCtor}var CHROME_EPOCH_OFFSET_MS=11644473600000;var chromeTimeToMs=(time)=>Number(BigInt(time)/1000n)-CHROME_EPOCH_OFFSET_MS;var msToChromeTime=(ms)=>BigInt(Math.floor((ms+CHROME_EPOCH_OFFSET_MS)*1000));var EXTENSION_BRIDGE_REQUIRED="requires the extension bridge in standalone OmOWright";function createProfileApis(profilePath){function profileDir(){if(!profilePath){throw new UnsupportedOperationError("chrome.bookmarks/history/topSites need a profilePath (the browser's user-data-dir); pass it to createChromeApi(connection, { profilePath })")}return path8.join(profilePath,"Default")}async function openDb(fileName){const file=path8.join(profileDir(),fileName);if(!existsSync(file))return null;const ctor=await loadSqlite();return ctor(file)}async function withDb(fileName,fn){const db=await openDb(fileName);if(!db)return[];try{return fn(db)}finally{db.close()}}function bookmarkRoots(){const file=path8.join(profileDir(),"Bookmarks");if(!existsSync(file))return[];const parsed=JSON.parse(readFileSync2(file,"utf8"));return Object.values(parsed.roots??{}).filter((node)=>node&&typeof node==="object"&&node.id)}function walkBookmarks(nodes,visit,acc=[]){for(const node of nodes){visit(node,acc);if(Array.isArray(node.children))walkBookmarks(node.children,visit,acc)}return acc}function findBookmark(id){for(const root of bookmarkRoots()){const found=walkBookmarks([root],(node,acc)=>{if(node.id===String(id))acc.push(node)});if(found.length>0)return found[0]}return null}function toBookmark(node){const out={id:node.id,title:node.name??"",type:node.type};if(node.url)out.url=node.url;if(node.date_added)out.dateAdded=chromeTimeToMs(node.date_added);if(node.children)out.children=node.children.map(toBookmark);return out}const bookmarks={async get(idOrIdList){const ids=Array.isArray(idOrIdList)?idOrIdList:[idOrIdList];return ids.map(findBookmark).filter(Boolean).map(toBookmark)},async getChildren(id){const node=findBookmark(id);return(node?.children??[]).map(toBookmark)},async getRecent(numberOfItems){const urls=walkBookmarks(bookmarkRoots(),(node,acc)=>{if(node.type==="url")acc.push(node)});return urls.sort((a,b)=>Number(b.date_added??0)-Number(a.date_added??0)).slice(0,numberOfItems).map(toBookmark)},async getSubTree(id){const node=findBookmark(id);return node?[toBookmark(node)]:[]},async getTree(){return bookmarkRoots().map(toBookmark)},async search(query){const needle=typeof query==="string"?query.toLowerCase():(query.query??"").toLowerCase();const url=typeof query==="object"?query.url?.toLowerCase():undefined;const title=typeof query==="object"?query.title?.toLowerCase():undefined;return walkBookmarks(bookmarkRoots(),(node,acc)=>{if(node.type!=="url")return;const name=(node.name??"").toLowerCase();const href=(node.url??"").toLowerCase();const ok=needle&&(name.includes(needle)||href.includes(needle))||url&&href.includes(url)||title&&name.includes(title);if(ok)acc.push(node)}).map(toBookmark)},async create(){throw new UnsupportedOperationError(`chrome.bookmarks.create ${EXTENSION_BRIDGE_REQUIRED}`)},async update(){throw new UnsupportedOperationError(`chrome.bookmarks.update ${EXTENSION_BRIDGE_REQUIRED}`)},async move(){throw new UnsupportedOperationError(`chrome.bookmarks.move ${EXTENSION_BRIDGE_REQUIRED}`)},async remove(){throw new UnsupportedOperationError(`chrome.bookmarks.remove ${EXTENSION_BRIDGE_REQUIRED}`)},async removeTree(){throw new UnsupportedOperationError(`chrome.bookmarks.removeTree ${EXTENSION_BRIDGE_REQUIRED}`)}};const history={async search(query){const text=`%${query.text??""}%`;const start=query.startTime!=null?msToChromeTime(query.startTime):0n;const end=query.endTime!=null?msToChromeTime(query.endTime):99999999999999999n;const max=query.maxResults??100;return await withDb("History",(db)=>db.prepare(`SELECT id, url, title, visit_count, last_visit_time FROM urlsWHERE (url LIKE ? OR title LIKE ?) AND last_visit_time BETWEEN ? AND ?ORDER BY last_visit_time DESC LIMIT ?`).all(text,text,start,end,max).map((row)=>({id:String(row.id),url:row.url,title:row.title??"",visitCount:Number(row.visit_count),lastVisitTime:chromeTimeToMs(row.last_visit_time)})))},async getVisits(details){return await withDb("History",(db)=>db.prepare(`SELECT v.id, v.visit_time, v.transition FROM visits vJOIN urls u ON u.id = v.url WHERE u.url = ?ORDER BY v.visit_time DESC`).all(details.url).map((row)=>({id:String(row.id),url:details.url,visitTime:chromeTimeToMs(row.visit_time),transition:Number(row.transition)})))},async addUrl(){throw new UnsupportedOperationError(`chrome.history.addUrl ${EXTENSION_BRIDGE_REQUIRED}`)},async deleteUrl(){throw new UnsupportedOperationError(`chrome.history.deleteUrl ${EXTENSION_BRIDGE_REQUIRED}`)},async deleteRange(){throw new UnsupportedOperationError(`chrome.history.deleteRange ${EXTENSION_BRIDGE_REQUIRED}`)}};const topSites={async get(){return(await withDb("Top Sites",(db)=>db.prepare(`SELECT url, title, url_rank FROM top_sites ORDER BY url_rank ASC LIMIT 50`).all())).map((row)=>({url:row.url,title:row.title??""}))}};return{bookmarks,history,topSites,withDb}}var EXTENSION_BRIDGE_REQUIRED2="requires the extension bridge in standalone OmOWright";var DOWNLOAD_TIMEOUT_MS=30000;function matchUrlPattern(url,pattern){const patterns=Array.isArray(pattern)?pattern:[pattern];return patterns.some((item)=>{if(!item.includes("*"))return url.startsWith(item);const regex=new RegExp(`^${item.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`);return regex.test(url)})}function createChromeApi(connection,options={}){const profile=createProfileApis(options.profilePath);const cdp=connection.cdp;async function pageTargets(){return(await connection.listTargets()).filter((target)=>target.type==="page")}async function toTab(target){let windowId=0;try{const win=await cdp.send("Browser.getWindowForTarget",{targetId:target.targetId??target.id});windowId=win.windowId}catch{}return{id:target.targetId??target.id,url:target.url??"",title:target.title??"",windowId,active:false,pinned:false,audible:false,discarded:false,groupId:-1,index:-1}}const tabs={async query(queryInfo={}){let targets=await pageTargets();if(queryInfo.url)targets=targets.filter((t)=>matchUrlPattern(t.url??"",queryInfo.url));if(queryInfo.title)targets=targets.filter((t)=>(t.title??"").includes(queryInfo.title));const out=[];for(const target of targets){const tab=await toTab(target);if(queryInfo.windowId!=null&&tab.windowId!==queryInfo.windowId)continue;out.push(tab)}return out},async get(tabId){const targets=await pageTargets();const target=targets.find((t)=>(t.targetId??t.id)===tabId);if(!target)throw new Error(`No tab with id: ${tabId}`);return toTab(target)}};async function collectWindows(queryOptions={}){const byWindow=new Map;for(const target of await pageTargets()){const tab=await toTab(target);const list=byWindow.get(tab.windowId)??[];list.push(tab);byWindow.set(tab.windowId,list)}return[...byWindow.entries()].map(([windowId,windowTabs],index)=>{const win={id:windowId,focused:index===0,type:"normal",state:"normal",alwaysOnTop:false,incognito:false};if(queryOptions.populate)win.tabs=windowTabs;return win})}const windows={async get(windowId,queryOptions={}){const all=await collectWindows(queryOptions);const win=all.find((item)=>item.id===windowId);if(!win)throw new Error(`No window with id: ${windowId}`);return win},async getCurrent(queryOptions={}){const all=await collectWindows(queryOptions);if(all.length===0)throw new Error("No browser window found");return all[0]},async getLastFocused(queryOptions={}){const all=await collectWindows(queryOptions);if(all.length===0)throw new Error("No browser window found");return all[0]},async getAll(queryOptions={}){return collectWindows(queryOptions)}};const downloads={async search(query={}){return profile.withDb("History",(db)=>{const rows=db.prepare(`SELECT d.id, d.target_path, d.start_time, d.received_bytes, d.total_bytes, d.state,(SELECT url FROM downloads_url_chains c WHERE c.id = d.id AND c.chain_index = 0) AS url- FROM downloads d ORDER BY d.start_time DESC LIMIT ?`).all(query.limit??100);return rows.map((row)=>({id:Number(row.id),url:row.url??"",filename:row.target_path,startTime:row.start_time?new Date(chromeTimeToMs(row.start_time)).toISOString():null,bytesReceived:Number(row.received_bytes),totalBytes:Number(row.total_bytes),state:Number(row.state)===1?"complete":Number(row.state)===2?"canceled":Number(row.state)===3?"interrupted":"in_progress"})).filter((item)=>!query.url||item.url.includes(query.url)).filter((item)=>!query.filename||item.filename.includes(query.filename))})},async download(downloadOptions){const downloadDir=options.downloadDir??path6.join(tmpdir3(),"omowright-downloads");mkdirSync(downloadDir,{recursive:true});let resolveBegin;let resolveDone;let rejectDone;const began=new Promise((resolve)=>{resolveBegin=resolve});const done=new Promise((resolve,reject)=>{resolveDone=resolve;rejectDone=reject});const offBegin=cdp.on("Browser.downloadWillBegin",(params)=>resolveBegin(params));const offProgress=cdp.on("Browser.downloadProgress",(params)=>{if(params.state==="completed")resolveDone(params);else if(params.state==="canceled")rejectDone(new Error("Download was canceled"))});const timer=setTimeout(()=>rejectDone(new Error(`chrome.downloads.download timed out after ${DOWNLOAD_TIMEOUT_MS}ms`)),DOWNLOAD_TIMEOUT_MS);const page=await connection.newTab("about:blank");try{await cdp.send("Browser.setDownloadBehavior",{behavior:"allow",downloadPath:downloadDir,eventsEnabled:true});await page.evaluate(`(() => {+ FROM downloads d ORDER BY d.start_time DESC LIMIT ?`).all(query.limit??100);return rows.map((row)=>({id:Number(row.id),url:row.url??"",filename:row.target_path,startTime:row.start_time?new Date(chromeTimeToMs(row.start_time)).toISOString():null,bytesReceived:Number(row.received_bytes),totalBytes:Number(row.total_bytes),state:Number(row.state)===1?"complete":Number(row.state)===2?"canceled":Number(row.state)===3?"interrupted":"in_progress"})).filter((item)=>!query.url||item.url.includes(query.url)).filter((item)=>!query.filename||item.filename.includes(query.filename))})},async download(downloadOptions){const downloadDir=options.downloadDir??path9.join(tmpdir3(),"omowright-downloads");mkdirSync(downloadDir,{recursive:true});let resolveBegin;let resolveDone;let rejectDone;const began=new Promise((resolve)=>{resolveBegin=resolve});const done=new Promise((resolve,reject)=>{resolveDone=resolve;rejectDone=reject});const offBegin=cdp.on("Browser.downloadWillBegin",(params)=>resolveBegin(params));const offProgress=cdp.on("Browser.downloadProgress",(params)=>{if(params.state==="completed")resolveDone(params);else if(params.state==="canceled")rejectDone(new Error("Download was canceled"))});const timer=setTimeout(()=>rejectDone(new Error(`chrome.downloads.download timed out after ${DOWNLOAD_TIMEOUT_MS}ms`)),DOWNLOAD_TIMEOUT_MS);const page=await connection.newTab("about:blank");try{await cdp.send("Browser.setDownloadBehavior",{behavior:"allow",downloadPath:downloadDir,eventsEnabled:true});await page.evaluate(`(() => {const a = document.createElement("a");a.href = ${JSON.stringify(downloadOptions.url)};document.body.appendChild(a);a.click();- })()`);const begin=await Promise.race([began,done.then(()=>null)]);if(!begin)throw new Error("No download started for the given URL");await done;const filename=downloadOptions.filename??begin.suggestedFilename;return{id:begin.guid,url:begin.url??downloadOptions.url,filename:path6.join(downloadDir,filename??"download"),state:"complete"}}finally{clearTimeout(timer);offBegin();offProgress();await page.close().catch(()=>{})}},async pause(){throw new UnsupportedOperationError(`chrome.downloads.pause ${EXTENSION_BRIDGE_REQUIRED2}`)},async resume(){throw new UnsupportedOperationError(`chrome.downloads.resume ${EXTENSION_BRIDGE_REQUIRED2}`)},async cancel(){throw new UnsupportedOperationError(`chrome.downloads.cancel ${EXTENSION_BRIDGE_REQUIRED2}`)},async erase(){throw new UnsupportedOperationError(`chrome.downloads.erase ${EXTENSION_BRIDGE_REQUIRED2}`)}};return{tabs,windows,downloads,bookmarks:profile.bookmarks,history:profile.history,topSites:profile.topSites}}var HOST_NAME="com.omowright.cloakbridge";var PROTOCOL=1;var MAX_MESSAGE_BYTES=1024*1024;var EVENT_NAMES2=Object.freeze(["notifications.shown","notifications.clicked","notifications.closed","tabGroups.created","tabGroups.updated","tabGroups.moved","tabs.activated","windows.focusChanged"]);var COMMAND_NAMES=Object.freeze(["bookmarks.create","bookmarks.move","bookmarks.remove","history.deleteUrl","history.deleteRange","tabGroups.update","debugger.attach","debugger.detach"]);var MUTATING_COMMANDS=new Set(COMMAND_NAMES);var id=string2().min(1).max(128);var uuid3=string2().regex(/^[0-9a-fA-F-]{16,128}$/);var finite=number2().finite();var color=_enum2(["grey","blue","red","yellow","green","pink","purple","cyan","orange"]);var group=object({id:number2().int().min(0),collapsed:boolean2(),color,title:string2().max(1024).nullable().optional(),windowId:number2().int().min(-1)}).strict();var bookmarkNode=lazy(()=>object({id:string2().min(1),parentId:string2().min(1).optional(),index:number2().int().min(0).optional(),title:string2(),url:string2().optional(),dateAdded:finite.min(0).optional(),dateGroupModified:finite.min(0).optional(),dateLastUsed:finite.min(0).optional(),folderType:string2().optional(),syncing:boolean2().optional(),unmodifiable:string2().optional(),type:_enum2(["bookmark","folder","url"]).optional(),children:array(bookmarkNode).optional()}).strict());var empty=object({}).strict();var payloadSchemas={"notifications.shown":object({notificationId:string2().min(1).max(1024)}).strict(),"notifications.clicked":object({notificationId:string2().min(1).max(1024)}).strict(),"notifications.closed":object({notificationId:string2().min(1).max(1024),byUser:boolean2()}).strict(),"tabGroups.created":object({group}).strict(),"tabGroups.updated":object({group}).strict(),"tabGroups.moved":object({group}).strict(),"tabs.activated":object({tabId:number2().int().min(0),windowId:number2().int().min(-1),previousTabId:number2().int().min(0).optional()}).strict(),"windows.focusChanged":object({windowId:number2().int().min(-1)}).strict()};var commandParams={"bookmarks.create":object({details:object({parentId:string2().min(1).optional(),index:number2().int().min(0).optional(),title:string2().max(8192),url:string2().url().max(8192).optional()}).strict()}).strict(),"bookmarks.move":object({details:object({id:string2().min(1),parentId:string2().min(1).optional(),index:number2().int().min(0).optional()}).strict()}).strict(),"bookmarks.remove":object({details:object({id:string2().min(1)}).strict()}).strict(),"history.deleteUrl":object({details:object({url:string2().url().max(8192)}).strict()}).strict(),"history.deleteRange":object({details:object({startTime:finite.min(0),endTime:finite.min(0)}).strict()}).strict().refine((v)=>v.details.startTime<=v.details.endTime,"startTime must not exceed endTime"),"tabGroups.update":object({details:object({groupId:number2().int().min(0),updateProperties:object({collapsed:boolean2().optional(),color:color.optional(),title:string2().max(1024).nullable().optional()}).strict().refine((v)=>Object.keys(v).length>0,"updateProperties must not be empty")}).strict()}).strict(),"debugger.attach":object({details:object({tabId:number2().int().min(0),requiredVersion:string2().regex(/^\d+\.\d+$/)}).strict()}).strict(),"debugger.detach":object({details:object({tabId:number2().int().min(0)}).strict()}).strict()};var resultSchemas={"bookmarks.create":bookmarkNode,"bookmarks.move":bookmarkNode,"bookmarks.remove":empty,"history.deleteUrl":empty,"history.deleteRange":empty,"tabGroups.update":group,"debugger.attach":object({tabId:number2().int().min(0),attached:literal(true),requiredVersion:string2()}).strict(),"debugger.detach":object({tabId:number2().int().min(0),detached:literal(true)}).strict()};var base={protocol:literal(PROTOCOL)};function unique(values,ctx){if(new Set(values).size!==values.length)ctx.addIssue({code:ZodIssueCode.custom,message:"array entries must be unique"})}var names=(allowed)=>array(_enum2([...allowed])).superRefine(unique);var ExtensionHelloSchema=object({...base,type:literal("hello"),role:literal("extension"),connectionId:id,extensionId:string2().regex(/^[a-p]{32}$/),extensionVersion:string2().min(1).max(64),events:names(EVENT_NAMES2),commands:names(COMMAND_NAMES),maxMessageBytes:number2().int().min(1).max(MAX_MESSAGE_BYTES)}).strict();var HostHelloSchema=object({...base,type:literal("hello"),role:literal("host"),connectionId:id,hostName:literal(HOST_NAME),hostVersion:string2().min(1).max(64),events:names(EVENT_NAMES2),commands:names(COMMAND_NAMES),maxMessageBytes:number2().int().min(1).max(MAX_MESSAGE_BYTES)}).strict();var EventSchema=object({...base,type:literal("event"),connectionId:id,seq:number2().int().min(1),occurredAt:number2().int().min(0),name:_enum2(EVENT_NAMES2),payload:record(string2(),unknown())}).strict().superRefine((v,ctx)=>{if(!payloadSchemas[v.name].safeParse(v.payload).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid event payload"})});var CommandSchema=object({...base,type:literal("command"),requestId:uuid3,name:_enum2(COMMAND_NAMES),params:record(string2(),unknown()),deadlineAt:number2().int().min(0).optional()}).strict().superRefine((v,ctx)=>{if(!commandParams[v.name].safeParse(v.params).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid command parameters"})});var errorSchema=object({code:_enum2(["INVALID_MESSAGE","UNKNOWN_COMMAND","UNSUPPORTED_COMMAND","CHROME_ERROR","DEBUGGER_ERROR","NATIVE_HOST_DISCONNECTED","TIMEOUT","PAYLOAD_TOO_LARGE","INTERNAL_ERROR"]),message:string2().min(1).max(512),details:record(string2(),unknown()).optional()}).strict();var responseNames=[...COMMAND_NAMES,"protocolError"];var ResponseSchema=object({...base,type:literal("response"),requestId:uuid3,name:_enum2(responseNames),ok:boolean2(),result:unknown().optional(),error:errorSchema.optional()}).strict().superRefine((v,ctx)=>{const valid=v.ok?v.result!==undefined&&v.error===undefined&&v.name!=="protocolError":v.error!==undefined&&v.result===undefined;if(!valid)ctx.addIssue({code:ZodIssueCode.custom,message:"response must contain exactly one result or error"});if(v.ok&&resultSchemas[v.name]&&!resultSchemas[v.name].safeParse(v.result).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid command result"})});class BridgeUnavailableError extends Error{constructor(message="Cloak bridge is unavailable"){super(message);this.name="BridgeUnavailableError"}}class BridgeProtocolError extends Error{constructor(message){super(message);this.name="BridgeProtocolError"}}var decoder=new TextDecoder2("utf-8",{fatal:true});var checked=(schema,value,message)=>{const result=schema.safeParse(value);if(!result.success)throw new BridgeProtocolError(message);return result.data};function schemaFor(value){if(value.type==="hello")return value.role==="host"?HostHelloSchema:ExtensionHelloSchema;if(value.type==="event")return EventSchema;if(value.type==="command")return CommandSchema;if(value.type==="response")return ResponseSchema;return null}function encodeFrame(value,maxMessageBytes=MAX_MESSAGE_BYTES){const schema=schemaFor(value);if(schema)checked(schema,value,"invalid outbound message");let json;try{json=JSON.stringify(value)}catch{throw new BridgeProtocolError("invalid JSON")}const body=Buffer.from(json,"utf8");if(body.length===0||body.length>maxMessageBytes)throw new BridgeProtocolError("PAYLOAD_TOO_LARGE");const frame=Buffer.allocUnsafe(4+body.length);frame.writeUInt32LE(body.length,0);body.copy(frame,4);return frame}function decodeFrames(buffer,maxMessageBytes=MAX_MESSAGE_BYTES){const frames=[];let offset=0;while(buffer.length-offset>=4){const length=buffer.readUInt32LE(offset);if(!length||length>maxMessageBytes)throw new BridgeProtocolError("PAYLOAD_TOO_LARGE");if(buffer.length-offset<length+4)break;const body=buffer.subarray(offset+4,offset+4+length);let text;try{text=decoder.decode(body)}catch{throw new BridgeProtocolError("invalid UTF-8")}try{frames.push(JSON.parse(text))}catch{throw new BridgeProtocolError("invalid JSON")}offset+=length+4}return{frames,remainder:buffer.subarray(offset)}}function createNativeMessagingHost({stdin=process.stdin,stdout=process.stdout,stderr=process.stderr,extensionId,hostName=HOST_NAME,maxMessageBytes=MAX_MESSAGE_BYTES,commandTimeoutMs=30000,maxPendingWrites=256,onEvent,onDisconnect}={}){if(!/^[a-p]{32}$/.test(extensionId??""))throw new BridgeProtocolError("a valid extensionId is required");if(!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName)||hostName!==HOST_NAME)throw new BridgeProtocolError("invalid hostName");let buffer=Buffer.alloc(0),closed=false,hello=null,hostConnectionId=null,effectiveMax=maxMessageBytes,lastEventSeq=0,sequence=0,mutationBusy=false;const pending=new Map,listeners=new Map,commandQueue=[],writeQueue=[];let writing=false;const disconnect=(reason)=>{if(closed)return;closed=true;const error=reason instanceof Error?reason:new BridgeUnavailableError(reason??"native host disconnected");for(const item of pending.values()){item.cleanup?.();item.reject(error)}pending.clear();for(const item of commandQueue.splice(0)){item.cleanup?.();item.reject(error)}for(const item of writeQueue.splice(0))item.reject(error);onDisconnect?.(error)};const write=(value)=>{if(closed)return Promise.reject(new BridgeUnavailableError);let frame;try{const schema=schemaFor(value);if(!schema)throw new BridgeProtocolError("invalid outbound message type");checked(schema,value,"invalid outbound message");frame=encodeFrame(value,effectiveMax)}catch(error){return Promise.reject(error)}if(writeQueue.length+(writing?1:0)>=maxPendingWrites)return Promise.reject(new BridgeProtocolError("BOUNDED_TRANSPORT"));return new Promise((resolve,reject)=>{writeQueue.push({frame,resolve,reject});pumpWrites()})};const pumpWrites=()=>{if(writing||closed||!writeQueue.length)return;writing=true;const item=writeQueue.shift();let finished=false;const done=(error)=>{if(finished)return;finished=true;writing=false;if(error){item.reject(error);disconnect(error)}else item.resolve();pumpWrites()};try{const result=stdout.write(item.frame,(error)=>done(error));if(result===false&&stdout.once)stdout.once("error",done)}catch(error){done(error)}};const pumpCommands=()=>{if(closed||mutationBusy||!commandQueue.length)return;const item=commandQueue.shift();item.started=true;mutationBusy=true;pending.set(item.requestId,item);write(item.command).catch((error)=>{if(pending.delete(item.requestId)){item.settled=true;item.cleanup();item.reject(error)}disconnect(error)})};const dispatchEvent=(event)=>{if(!hello||event.connectionId!==hello.connectionId||event.seq<=lastEventSeq||!hello.events.includes(event.name))throw new BridgeProtocolError("invalid event ordering or capability");lastEventSeq=event.seq;try{Promise.resolve(onEvent?.(event)).catch((error)=>stderr.write?.(`bridge listener: ${error.message}+ })()`);const begin=await Promise.race([began,done.then(()=>null)]);if(!begin)throw new Error("No download started for the given URL");await done;const filename=downloadOptions.filename??begin.suggestedFilename;return{id:begin.guid,url:begin.url??downloadOptions.url,filename:path9.join(downloadDir,filename??"download"),state:"complete"}}finally{clearTimeout(timer);offBegin();offProgress();await page.close().catch(()=>{})}},async pause(){throw new UnsupportedOperationError(`chrome.downloads.pause ${EXTENSION_BRIDGE_REQUIRED2}`)},async resume(){throw new UnsupportedOperationError(`chrome.downloads.resume ${EXTENSION_BRIDGE_REQUIRED2}`)},async cancel(){throw new UnsupportedOperationError(`chrome.downloads.cancel ${EXTENSION_BRIDGE_REQUIRED2}`)},async erase(){throw new UnsupportedOperationError(`chrome.downloads.erase ${EXTENSION_BRIDGE_REQUIRED2}`)}};return{tabs,windows,downloads,bookmarks:profile.bookmarks,history:profile.history,topSites:profile.topSites}}var HOST_NAME="com.omowright.cloakbridge";var PROTOCOL=1;var MAX_MESSAGE_BYTES=1024*1024;var EVENT_NAMES2=Object.freeze(["notifications.shown","notifications.clicked","notifications.closed","tabGroups.created","tabGroups.updated","tabGroups.moved","tabs.activated","windows.focusChanged"]);var COMMAND_NAMES=Object.freeze(["bookmarks.create","bookmarks.move","bookmarks.remove","history.deleteUrl","history.deleteRange","tabGroups.update","debugger.attach","debugger.detach"]);var MUTATING_COMMANDS=new Set(COMMAND_NAMES);var id=string2().min(1).max(128);var uuid3=string2().regex(/^[0-9a-fA-F-]{16,128}$/);var finite=number2().finite();var color=_enum2(["grey","blue","red","yellow","green","pink","purple","cyan","orange"]);var group=object({id:number2().int().min(0),collapsed:boolean2(),color,title:string2().max(1024).nullable().optional(),windowId:number2().int().min(-1)}).strict();var bookmarkNode=lazy(()=>object({id:string2().min(1),parentId:string2().min(1).optional(),index:number2().int().min(0).optional(),title:string2(),url:string2().optional(),dateAdded:finite.min(0).optional(),dateGroupModified:finite.min(0).optional(),dateLastUsed:finite.min(0).optional(),folderType:string2().optional(),syncing:boolean2().optional(),unmodifiable:string2().optional(),type:_enum2(["bookmark","folder","url"]).optional(),children:array(bookmarkNode).optional()}).strict());var empty=object({}).strict();var payloadSchemas={"notifications.shown":object({notificationId:string2().min(1).max(1024)}).strict(),"notifications.clicked":object({notificationId:string2().min(1).max(1024)}).strict(),"notifications.closed":object({notificationId:string2().min(1).max(1024),byUser:boolean2()}).strict(),"tabGroups.created":object({group}).strict(),"tabGroups.updated":object({group}).strict(),"tabGroups.moved":object({group}).strict(),"tabs.activated":object({tabId:number2().int().min(0),windowId:number2().int().min(-1),previousTabId:number2().int().min(0).optional()}).strict(),"windows.focusChanged":object({windowId:number2().int().min(-1)}).strict()};var commandParams={"bookmarks.create":object({details:object({parentId:string2().min(1).optional(),index:number2().int().min(0).optional(),title:string2().max(8192),url:string2().url().max(8192).optional()}).strict()}).strict(),"bookmarks.move":object({details:object({id:string2().min(1),parentId:string2().min(1).optional(),index:number2().int().min(0).optional()}).strict()}).strict(),"bookmarks.remove":object({details:object({id:string2().min(1)}).strict()}).strict(),"history.deleteUrl":object({details:object({url:string2().url().max(8192)}).strict()}).strict(),"history.deleteRange":object({details:object({startTime:finite.min(0),endTime:finite.min(0)}).strict()}).strict().refine((v)=>v.details.startTime<=v.details.endTime,"startTime must not exceed endTime"),"tabGroups.update":object({details:object({groupId:number2().int().min(0),updateProperties:object({collapsed:boolean2().optional(),color:color.optional(),title:string2().max(1024).nullable().optional()}).strict().refine((v)=>Object.keys(v).length>0,"updateProperties must not be empty")}).strict()}).strict(),"debugger.attach":object({details:object({tabId:number2().int().min(0),requiredVersion:string2().regex(/^\d+\.\d+$/)}).strict()}).strict(),"debugger.detach":object({details:object({tabId:number2().int().min(0)}).strict()}).strict()};var resultSchemas={"bookmarks.create":bookmarkNode,"bookmarks.move":bookmarkNode,"bookmarks.remove":empty,"history.deleteUrl":empty,"history.deleteRange":empty,"tabGroups.update":group,"debugger.attach":object({tabId:number2().int().min(0),attached:literal(true),requiredVersion:string2()}).strict(),"debugger.detach":object({tabId:number2().int().min(0),detached:literal(true)}).strict()};var base={protocol:literal(PROTOCOL)};function unique(values,ctx){if(new Set(values).size!==values.length)ctx.addIssue({code:ZodIssueCode.custom,message:"array entries must be unique"})}var names=(allowed)=>array(_enum2([...allowed])).superRefine(unique);var ExtensionHelloSchema=object({...base,type:literal("hello"),role:literal("extension"),connectionId:id,extensionId:string2().regex(/^[a-p]{32}$/),extensionVersion:string2().min(1).max(64),events:names(EVENT_NAMES2),commands:names(COMMAND_NAMES),maxMessageBytes:number2().int().min(1).max(MAX_MESSAGE_BYTES)}).strict();var HostHelloSchema=object({...base,type:literal("hello"),role:literal("host"),connectionId:id,hostName:literal(HOST_NAME),hostVersion:string2().min(1).max(64),events:names(EVENT_NAMES2),commands:names(COMMAND_NAMES),maxMessageBytes:number2().int().min(1).max(MAX_MESSAGE_BYTES)}).strict();var EventSchema=object({...base,type:literal("event"),connectionId:id,seq:number2().int().min(1),occurredAt:number2().int().min(0),name:_enum2(EVENT_NAMES2),payload:record(string2(),unknown())}).strict().superRefine((v,ctx)=>{if(!payloadSchemas[v.name].safeParse(v.payload).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid event payload"})});var CommandSchema=object({...base,type:literal("command"),requestId:uuid3,name:_enum2(COMMAND_NAMES),params:record(string2(),unknown()),deadlineAt:number2().int().min(0).optional()}).strict().superRefine((v,ctx)=>{if(!commandParams[v.name].safeParse(v.params).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid command parameters"})});var errorSchema=object({code:_enum2(["INVALID_MESSAGE","UNKNOWN_COMMAND","UNSUPPORTED_COMMAND","CHROME_ERROR","DEBUGGER_ERROR","NATIVE_HOST_DISCONNECTED","TIMEOUT","PAYLOAD_TOO_LARGE","INTERNAL_ERROR"]),message:string2().min(1).max(512),details:record(string2(),unknown()).optional()}).strict();var responseNames=[...COMMAND_NAMES,"protocolError"];var ResponseSchema=object({...base,type:literal("response"),requestId:uuid3,name:_enum2(responseNames),ok:boolean2(),result:unknown().optional(),error:errorSchema.optional()}).strict().superRefine((v,ctx)=>{const valid=v.ok?v.result!==undefined&&v.error===undefined&&v.name!=="protocolError":v.error!==undefined&&v.result===undefined;if(!valid)ctx.addIssue({code:ZodIssueCode.custom,message:"response must contain exactly one result or error"});if(v.ok&&resultSchemas[v.name]&&!resultSchemas[v.name].safeParse(v.result).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid command result"})});class BridgeUnavailableError extends Error{constructor(message="Cloak bridge is unavailable"){super(message);this.name="BridgeUnavailableError"}}class BridgeProtocolError extends Error{constructor(message){super(message);this.name="BridgeProtocolError"}}var decoder=new TextDecoder2("utf-8",{fatal:true});var checked=(schema,value,message)=>{const result=schema.safeParse(value);if(!result.success)throw new BridgeProtocolError(message);return result.data};function schemaFor(value){if(value.type==="hello")return value.role==="host"?HostHelloSchema:ExtensionHelloSchema;if(value.type==="event")return EventSchema;if(value.type==="command")return CommandSchema;if(value.type==="response")return ResponseSchema;return null}function encodeFrame(value,maxMessageBytes=MAX_MESSAGE_BYTES){const schema=schemaFor(value);if(schema)checked(schema,value,"invalid outbound message");let json;try{json=JSON.stringify(value)}catch{throw new BridgeProtocolError("invalid JSON")}const body=Buffer.from(json,"utf8");if(body.length===0||body.length>maxMessageBytes)throw new BridgeProtocolError("PAYLOAD_TOO_LARGE");const frame=Buffer.allocUnsafe(4+body.length);frame.writeUInt32LE(body.length,0);body.copy(frame,4);return frame}function decodeFrames(buffer,maxMessageBytes=MAX_MESSAGE_BYTES){const frames=[];let offset=0;while(buffer.length-offset>=4){const length=buffer.readUInt32LE(offset);if(!length||length>maxMessageBytes)throw new BridgeProtocolError("PAYLOAD_TOO_LARGE");if(buffer.length-offset<length+4)break;const body=buffer.subarray(offset+4,offset+4+length);let text;try{text=decoder.decode(body)}catch{throw new BridgeProtocolError("invalid UTF-8")}try{frames.push(JSON.parse(text))}catch{throw new BridgeProtocolError("invalid JSON")}offset+=length+4}return{frames,remainder:buffer.subarray(offset)}}function createNativeMessagingHost({stdin=process.stdin,stdout=process.stdout,stderr=process.stderr,extensionId,hostName=HOST_NAME,maxMessageBytes=MAX_MESSAGE_BYTES,commandTimeoutMs=30000,maxPendingWrites=256,onEvent,onDisconnect}={}){if(!/^[a-p]{32}$/.test(extensionId??""))throw new BridgeProtocolError("a valid extensionId is required");if(!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName)||hostName!==HOST_NAME)throw new BridgeProtocolError("invalid hostName");let buffer=Buffer.alloc(0),closed=false,hello=null,hostConnectionId=null,effectiveMax=maxMessageBytes,lastEventSeq=0,sequence=0,mutationBusy=false;const pending=new Map,listeners=new Map,commandQueue=[],writeQueue=[];let writing=false;const disconnect=(reason)=>{if(closed)return;closed=true;const error=reason instanceof Error?reason:new BridgeUnavailableError(reason??"native host disconnected");for(const item of pending.values()){item.cleanup?.();item.reject(error)}pending.clear();for(const item of commandQueue.splice(0)){item.cleanup?.();item.reject(error)}for(const item of writeQueue.splice(0))item.reject(error);onDisconnect?.(error)};const write=(value)=>{if(closed)return Promise.reject(new BridgeUnavailableError);let frame;try{const schema=schemaFor(value);if(!schema)throw new BridgeProtocolError("invalid outbound message type");checked(schema,value,"invalid outbound message");frame=encodeFrame(value,effectiveMax)}catch(error){return Promise.reject(error)}if(writeQueue.length+(writing?1:0)>=maxPendingWrites)return Promise.reject(new BridgeProtocolError("BOUNDED_TRANSPORT"));return new Promise((resolve,reject)=>{writeQueue.push({frame,resolve,reject});pumpWrites()})};const pumpWrites=()=>{if(writing||closed||!writeQueue.length)return;writing=true;const item=writeQueue.shift();let finished=false;const done=(error)=>{if(finished)return;finished=true;writing=false;if(error){item.reject(error);disconnect(error)}else item.resolve();pumpWrites()};try{const result=stdout.write(item.frame,(error)=>done(error));if(result===false&&stdout.once)stdout.once("error",done)}catch(error){done(error)}};const pumpCommands=()=>{if(closed||mutationBusy||!commandQueue.length)return;const item=commandQueue.shift();item.started=true;mutationBusy=true;pending.set(item.requestId,item);write(item.command).catch((error)=>{if(pending.delete(item.requestId)){item.settled=true;item.cleanup();item.reject(error)}disconnect(error)})};const dispatchEvent=(event)=>{if(!hello||event.connectionId!==hello.connectionId||event.seq<=lastEventSeq||!hello.events.includes(event.name))throw new BridgeProtocolError("invalid event ordering or capability");lastEventSeq=event.seq;try{Promise.resolve(onEvent?.(event)).catch((error)=>stderr.write?.(`bridge listener: ${error.message}`))}catch(error){stderr.write?.(`bridge listener: ${error.message}`)}for(const fn of listeners.get(event.name)??[]){try{Promise.resolve(fn(event.payload)).catch((error)=>stderr.write?.(`bridge listener: ${error.message}`))}catch(error){stderr.write?.(`bridge listener: ${error.message}-`)}}};const handle=(raw)=>{if(!hello){const parsed=checked(ExtensionHelloSchema,raw,"extension hello rejected");if(parsed.extensionId!==extensionId)throw new BridgeProtocolError("extension hello rejected");hello=parsed;hostConnectionId=randomUUID();effectiveMax=Math.min(maxMessageBytes,parsed.maxMessageBytes);lastEventSeq=0;return write({protocol:PROTOCOL,type:"hello",role:"host",connectionId:hostConnectionId,hostName,hostVersion:"0.1.0",events:EVENT_NAMES2.filter((x)=>parsed.events.includes(x)),commands:COMMAND_NAMES.filter((x)=>parsed.commands.includes(x)),maxMessageBytes:effectiveMax})}if(raw.type==="event")return dispatchEvent(checked(EventSchema,raw,"invalid event"));if(raw.type==="response"){const parsed=checked(ResponseSchema,raw,"invalid response");if(parsed.name==="protocolError")throw Object.assign(new BridgeProtocolError(parsed.error.message),{code:parsed.error.code,details:parsed.error.details});const item=pending.get(parsed.requestId);if(!item||item.name!==parsed.name)throw new BridgeProtocolError("invalid or unknown response");item.settled=true;pending.delete(parsed.requestId);item.cleanup();mutationBusy=false;if(parsed.ok)item.resolve(parsed.result);else item.reject(Object.assign(new Error(parsed.error.message),{code:parsed.error.code,details:parsed.error.details}));pumpCommands();return}throw new BridgeProtocolError("unexpected message")};const onData=(chunk)=>{try{buffer=Buffer.concat([buffer,Buffer.from(chunk)]);const out=decodeFrames(buffer,effectiveMax);buffer=out.remainder;for(const raw of out.frames)Promise.resolve(handle(raw)).catch((error)=>{stderr.write?.(`bridge: ${error.message}+`)}}};const handle=(raw)=>{if(!hello){const parsed=checked(ExtensionHelloSchema,raw,"extension hello rejected");if(parsed.extensionId!==extensionId)throw new BridgeProtocolError("extension hello rejected");hello=parsed;hostConnectionId=randomUUID4();effectiveMax=Math.min(maxMessageBytes,parsed.maxMessageBytes);lastEventSeq=0;return write({protocol:PROTOCOL,type:"hello",role:"host",connectionId:hostConnectionId,hostName,hostVersion:"0.1.0",events:EVENT_NAMES2.filter((x)=>parsed.events.includes(x)),commands:COMMAND_NAMES.filter((x)=>parsed.commands.includes(x)),maxMessageBytes:effectiveMax})}if(raw.type==="event")return dispatchEvent(checked(EventSchema,raw,"invalid event"));if(raw.type==="response"){const parsed=checked(ResponseSchema,raw,"invalid response");if(parsed.name==="protocolError")throw Object.assign(new BridgeProtocolError(parsed.error.message),{code:parsed.error.code,details:parsed.error.details});const item=pending.get(parsed.requestId);if(!item||item.name!==parsed.name)throw new BridgeProtocolError("invalid or unknown response");item.settled=true;pending.delete(parsed.requestId);item.cleanup();mutationBusy=false;if(parsed.ok)item.resolve(parsed.result);else item.reject(Object.assign(new Error(parsed.error.message),{code:parsed.error.code,details:parsed.error.details}));pumpCommands();return}throw new BridgeProtocolError("unexpected message")};const onData=(chunk)=>{try{buffer=Buffer.concat([buffer,Buffer.from(chunk)]);const out=decodeFrames(buffer,effectiveMax);buffer=out.remainder;for(const raw of out.frames)Promise.resolve(handle(raw)).catch((error)=>{stderr.write?.(`bridge: ${error.message}`);disconnect(error)})}catch(error){stderr.write?.(`bridge: ${error.message}-`);disconnect(error)}};stdin.on("data",onData);stdin.once?.("end",()=>disconnect());stdin.once?.("error",disconnect);return{get isConnected(){return!closed&&!!hello},get capabilities(){return{commands:new Set(hello?.commands??[]),events:new Set(hello?.events??[])}},send:write,request(name,params,{signal,timeoutMs=commandTimeoutMs}={}){if(!hello||!hello.commands.includes(name))return Promise.reject(new BridgeUnavailableError(`unsupported bridge command: ${name}`));let command;try{command=checked(CommandSchema,{protocol:PROTOCOL,type:"command",requestId:randomUUID(),name,params},"invalid command parameters")}catch(error){return Promise.reject(error)}return new Promise((resolve,reject)=>{if(commandQueue.length+pending.size>=maxPendingWrites){reject(new BridgeProtocolError("BOUNDED_TRANSPORT"));return}const item={requestId:command.requestId,name,command,resolve,reject,timer:null,abortHandler:null,cleanup:null,settled:false};const cleanup=()=>{clearTimeout(item.timer);if(item.abortHandler){signal?.removeEventListener("abort",item.abortHandler);item.abortHandler=null}};item.cleanup=cleanup;const failIndeterminate=(code,reason=null)=>{if(item.settled)return;item.settled=true;cleanup();if(pending.delete(item.requestId)||commandQueue.includes(item)){const i=commandQueue.indexOf(item);if(i>=0)commandQueue.splice(i,1);item.reject(reason??Object.assign(new Error(`bridge command timed out: ${name}`),{code}))}if(item.started)disconnect(Object.assign(new Error("mutation completion is indeterminate"),{code}))};item.timer=setTimeout(()=>failIndeterminate("TIMEOUT"),timeoutMs);if(signal?.aborted){item.settled=true;cleanup();reject(signal.reason??Object.assign(new Error(`bridge command aborted: ${name}`),{code:"ABORT_ERR"}));return}item.abortHandler=()=>failIndeterminate("ABORT_ERR",signal.reason);signal?.addEventListener("abort",item.abortHandler,{once:true});commandQueue.push(item);pumpCommands()})},on(name,listener){if(!EVENT_NAMES2.includes(name))throw new BridgeProtocolError("invalid event name");const set=listeners.get(name)??new Set;set.add(listener);listeners.set(name,set);return()=>{set.delete(listener);if(!set.size)listeners.delete(name)}},emitEvent(name,payload){if(!hello?.events.includes(name))return Promise.reject(new BridgeUnavailableError("unsupported bridge event"));const checkedPayload=payloadSchemas[name].safeParse(payload);if(!checkedPayload.success)return Promise.reject(new BridgeProtocolError("invalid event payload"));sequence+=1;return write({protocol:PROTOCOL,type:"event",connectionId:hostConnectionId,seq:sequence,occurredAt:Date.now(),name,payload:checkedPayload.data})},close(){disconnect("closed");stdin.removeListener?.("data",onData)}}}var NATIVE_HOST_DIRS={darwin:{chrome:["Library","Application Support","Google","Chrome"],chromium:["Library","Application Support","Chromium"]},linux:{chrome:[".config","google-chrome"],chromium:[".config","chromium"]}};function defaultNativeMessagingHostDir(browser="chrome",platform=process.platform){const byBrowser=NATIVE_HOST_DIRS[platform];if(!byBrowser)throw new BridgeProtocolError(`no default nativeMessagingHostDir on ${platform}; pass nativeMessagingHostDir`);const segments=byBrowser[browser];if(!segments)throw new BridgeProtocolError("custom browser requires nativeMessagingHostDir");return path7.join(homedir(),...segments,"NativeMessagingHosts")}async function secureDirectory(dir){const absolute=path7.resolve(dir);const parts=absolute.split(path7.sep).filter(Boolean);let current=path7.parse(absolute).root;let final;for(const[index,part]of parts.entries()){current=path7.join(current,part);let info=await lstat(current).catch(()=>null);if(!info){await mkdir4(current,{mode:448});info=await lstat(current)}if(current!=="/var"&&(info.isSymbolicLink()||!info.isDirectory()))throw new BridgeProtocolError("nativeMessagingHostDir security rejected");if(current!=="/var"&&info.uid!==process.getuid?.()&&info.uid!==0)throw new BridgeProtocolError("nativeMessagingHostDir ownership rejected");const stickyRootAncestor=index<parts.length-1&&info.uid===0&&(info.mode&512)!==0;if(current!=="/var"&&!stickyRootAncestor&&(info.mode&18)!==0)throw new BridgeProtocolError("nativeMessagingHostDir security rejected");final=info}if(!final||final.uid!==process.getuid?.()&&final.uid!==0)throw new BridgeProtocolError("nativeMessagingHostDir ownership rejected");if((final.mode&63)!==0)await chmod2(absolute,448)}async function secureExecutable(hostPath){const info=await lstat(hostPath).catch(()=>null);if(!info?.isFile()||info.isSymbolicLink()||info.uid!==process.getuid?.()||(info.mode&73)===0||(info.mode&18)!==0)throw new BridgeProtocolError("hostPath must be a securely owned executable file")}async function installNativeMessagingHost({hostName=HOST_NAME,hostPath,extensionId,browser="chrome",nativeMessagingHostDir,force=false,endpointPath}={}){if(endpointPath!==undefined)throw new BridgeProtocolError("endpointPath is not supported");if(hostName!==HOST_NAME||!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName))throw new BridgeProtocolError("invalid hostName");if(!path7.isAbsolute(hostPath??""))throw new BridgeProtocolError("hostPath must be absolute");await secureExecutable(hostPath);if(!/^[a-p]{32}$/.test(extensionId??""))throw new BridgeProtocolError("invalid extensionId");if(!nativeMessagingHostDir&&browser==="cloakbrowser")throw new BridgeProtocolError("CloakBrowser nativeMessagingHostDir must be explicit and verified");const dir=nativeMessagingHostDir??defaultNativeMessagingHostDir(browser);await secureDirectory(dir);const manifest={name:hostName,description:"OmOWright internal CloakBrowser native messaging bridge.",path:hostPath,type:"stdio",allowed_origins:[`chrome-extension://${extensionId}/`]};const file=path7.join(dir,`${hostName}.json`);if(!force&&await lstat(file).catch(()=>null))throw new BridgeProtocolError("registration manifest already exists; use force");const temp=`${file}.${process.pid}.${randomUUID()}.tmp`;const handle=await open3(temp,"wx",384);try{await handle.writeFile(JSON.stringify(manifest,null,2)+`-`);await handle.sync()}finally{await handle.close()}await rename(temp,file);const parsed=JSON.parse(await readFile2(file,"utf8"));await chmod2(file,384);return{path:file,manifest:parsed}}function createBridgeClient(options={}){return createNativeMessagingHost(options)}function createChromeApi2(connection,options={}){const chrome=createChromeApi(connection,options);const bridge=options.bridge;const request=(wire,params)=>bridge?.isConnected&&bridge.capabilities?.commands?.has(wire)?bridge.request(wire,params):Promise.reject(new UnsupportedOperationError(`chrome.${wire} requires the extension bridge in standalone OmOWright`));chrome.bookmarks.create=(details)=>request("bookmarks.create",{details});chrome.bookmarks.move=(id,details={})=>request("bookmarks.move",{details:{...details,id:String(id)}});chrome.bookmarks.remove=(id)=>request("bookmarks.remove",{details:{id:String(id)}});chrome.history.deleteUrl=(details)=>request("history.deleteUrl",{details});chrome.history.deleteRange=(details)=>request("history.deleteRange",{details});chrome.tabGroups={update:(groupId,updateProperties)=>request("tabGroups.update",{details:{groupId,updateProperties}})};chrome.debugger={attach:(target,requiredVersion)=>request("debugger.attach",{details:{tabId:target.tabId??target,requiredVersion}}),detach:(target)=>request("debugger.detach",{details:{tabId:target.tabId??target}})};const eventMap={notifications:["onShown","onClicked","onClosed"],tabGroups:["onCreated","onUpdated","onMoved"],tabs:["onActivated"],windows:["onFocusChanged"]};for(const[namespace,events]of Object.entries(eventMap)){chrome[namespace]??={};for(const event of events){const wire=`${namespace}.${event.slice(2,3).toLowerCase()+event.slice(3)}`;const subscriptions=new Map;chrome[namespace][event]={addListener(listener){if(!bridge?.on)return;const unsubscribe=bridge.on(wire,(payload)=>listener(...namespace==="notifications"&&event==="onClosed"?[payload.notificationId,payload.byUser]:namespace==="notifications"?[payload.notificationId]:namespace==="tabGroups"?[payload.group]:namespace==="windows"?[payload.windowId]:[payload]));subscriptions.set(listener,unsubscribe);return unsubscribe},removeListener(listener){const unsubscribe=subscriptions.get(listener);if(unsubscribe){unsubscribe();subscriptions.delete(listener)}}}}}return chrome}function sanitizeCookies(cookies){const byKey=new Map;for(const cookie of cookies){const out={name:cookie.name,value:cookie.value,path:cookie.path||"/",secure:Boolean(cookie.secure),httpOnly:Boolean(cookie.httpOnly)};if(cookie.name.startsWith("__Host-")){out.secure=true;out.path="/";out.url=`https://${cookie.domain.replace(/^\./,"")}`}else{out.domain=cookie.domain}if(cookie.expires&&cookie.expires>0)out.expires=cookie.expires;if(cookie.sameSite&&(cookie.sameSite!=="None"||out.secure))out.sameSite=cookie.sameSite;const key=`${out.name}|${out.domain??out.url}`;const prev=byKey.get(key);if(!prev||(out.expires??0)>(prev.expires??0))byKey.set(key,out)}return[...byKey.values()]}async function injectCookies(page,cookies){await page._sendToTarget("Network.setCookies",{cookies:sanitizeCookies(cookies)})}var DEVICE_PRESETS=Object.freeze({"iphone-14":{width:390,height:844,deviceScaleFactor:3,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"iPhone"},"pixel-7":{width:412,height:915,deviceScaleFactor:2.625,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",platform:"Linux armv8l"},"ipad-air":{width:820,height:1180,deviceScaleFactor:2,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"MacIntel"},"desktop-1440":{width:1440,height:900,deviceScaleFactor:1,mobile:false,hasTouch:false,userAgent:undefined,platform:undefined}});var originalUAs=new WeakMap;async function emulate(page,presetNameOrObject){let preset;if(presetNameOrObject===null){preset=null}else if(typeof presetNameOrObject==="string"){if(!DEVICE_PRESETS[presetNameOrObject]){throw new Error(`unknown device preset: ${presetNameOrObject}`)}preset=DEVICE_PRESETS[presetNameOrObject]}else{preset=presetNameOrObject}const sessionId=await page.resolveSessionId();if(preset===null){await page.cdp.send("Emulation.clearDeviceMetricsOverride",{},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:false},sessionId);const originalUA=originalUAs.get(page);if(originalUA){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:originalUA},sessionId)}}else{if(!originalUAs.has(page)){const ua=await page.evaluate(()=>navigator.userAgent);originalUAs.set(page,ua)}await page.cdp.send("Emulation.setDeviceMetricsOverride",{width:preset.width,height:preset.height,deviceScaleFactor:preset.deviceScaleFactor,mobile:preset.mobile,screenWidth:preset.width,screenHeight:preset.height},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:preset.hasTouch,maxTouchPoints:preset.hasTouch?5:1},sessionId);if(preset.userAgent!==undefined){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:preset.userAgent,platform:preset.platform},sessionId)}}if(page.refreshViewportSize){await page.refreshViewportSize()}return preset}var AUTO_ATTACH={autoAttach:true,waitForDebuggerOnStart:false,flatten:true};var REF_PATTERN2=/^(f\d+)?e\d+$/;function detach(page,sessionId){return page.cdp.send("Target.detachFromTarget",{sessionId}).catch(()=>{})}async function iframeTargets(page){const{targetInfo}=await page.cdp.send("Target.getTargetInfo",{targetId:page.targetId});const browserContextId=targetInfo?.browserContextId;const{targetInfos}=await page.cdp.send("Target.getTargets",{filter:[{type:"iframe"}]});return targetInfos.filter((info)=>info.type==="iframe"&&(!browserContextId||!info.browserContextId||info.browserContextId===browserContextId))}function isAttributed(fm,frameId){const seen=new Set;let frame=fm.frames.get(frameId);while(frame&&!seen.has(frame.frameId)){if(frame.frameId===fm.mainFrameId)return true;seen.add(frame.frameId);frame=frame.parentFrameId?fm.frames.get(frame.parentFrameId):null}return false}async function describeTarget(page,targetId){const{sessionId}=await page.cdp.send("Target.attachToTarget",{targetId,flatten:true});try{await page.cdp.send("Page.enable",undefined,sessionId);const{frameTree}=await page.cdp.send("Page.getFrameTree",undefined,sessionId);return{sessionId,frame:frameTree.frame}}catch(error){await detach(page,sessionId);throw error}}async function adopt(page,sessionId,frame,parentFrameId){await page.cdp.send("DOM.enable",undefined,sessionId);await page.cdp.send("Target.setAutoAttach",AUTO_ATTACH,sessionId).catch(()=>{});page.frameManager.frames.set(frame.id,{frameId:frame.id,parentFrameId,url:frame.url??"",name:frame.name??"",sessionId});const isolatedContextId=await page.frameManager.ensureInjected(frame.id);return{frameId:frame.id,parentFrameId,url:frame.url??"",sessionId,isolatedContextId}}async function reconcileFrames(page){const fm=page.frameManager;const added=[];let pending=(await iframeTargets(page)).filter((info)=>!isAttributed(fm,info.targetId));let progress=true;while(progress&&pending.length>0){progress=false;const retry=[];for(const target of pending){if(isAttributed(fm,target.targetId))continue;const{sessionId,frame}=await describeTarget(page,target.targetId);const parentFrameId=frame.parentId??null;if(!parentFrameId||!isAttributed(fm,parentFrameId)){await detach(page,sessionId);if(parentFrameId)retry.push(target);continue}added.push(await adopt(page,sessionId,frame,parentFrameId));progress=true}pending=retry}return added}function framePrefixes(fm){let counter=1;return fm.collectDescendantFrames(fm.mainFrameId).map(({frameId})=>({frameId,prefix:frameId===fm.mainFrameId?"":`f${counter++}`}))}function collectMissingFrames(page,refs){const seen=new Set(Object.keys(refs??{}).map((ref)=>ref.match(REF_PATTERN2)?.[1]??""));const missing=[];for(const{frameId,prefix}of framePrefixes(page.frameManager)){if(prefix===""||seen.has(prefix))continue;const frame=page.frameManager.getFrame(frameId);if(frame?.isolatedContextId)continue;missing.push({frameId,url:frame?.url??"",injected:false})}return missing}async function snapshotWithFrames(page,opts={}){await reconcileFrames(page);const result=await page.snapshot(opts);const missingFrames=collectMissingFrames(page,result.refs);return missingFrames.length>0?{...result,missingFrames}:result}var HTTP_VERSION="HTTP/1.1";var CREATOR=Object.freeze({name:"omowright",version:"0.0.1"});function headerList(headers){return Object.entries(headers??{}).map(([name,value])=>({name,value:String(value)}))}function headerValue(headers,name){for(const[key,value]of Object.entries(headers??{})){if(key.toLowerCase()===name)return String(value)}return null}function queryString(url){try{return[...new URL(String(url)).searchParams].map(([name,value])=>({name,value}))}catch{return[]}}function elapsed(entry){const started=Number(entry.startedAt);const finished=Number(entry.finishedAt);if(!Number.isFinite(started)||!Number.isFinite(finished))return 0;return Math.max(0,finished-started)}function requestOf(entry){const postData=entry.postData??null;const request={method:entry.method??"GET",url:entry.url??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.requestHeaders),queryString:queryString(entry.url),headersSize:-1,bodySize:postData===null?0:Buffer.byteLength(postData)};if(postData!==null){request.postData={mimeType:headerValue(entry.requestHeaders,"content-type")??"",text:postData}}return request}function contentOf(entry){const content={size:Number(entry.encodedDataLength??0),mimeType:entry.mimeType??""};if(typeof entry.body==="string")content.text=entry.body;if(entry.base64Encoded)content.encoding="base64";return content}function responseOf(entry){return{status:entry.failed?0:Number(entry.status??0),statusText:entry.statusText??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.responseHeaders),content:contentOf(entry),redirectURL:headerValue(entry.responseHeaders,"location")??"",headersSize:-1,bodySize:Number(entry.encodedDataLength??0)}}function toHar(entries,{creator=CREATOR,pages=[]}={}){const log={version:"1.2",creator,pages,entries:[...entries??[]].map((entry)=>{const time=elapsed(entry);const har={startedDateTime:new Date(Number(entry.startedAt)||0).toISOString(),time,request:requestOf(entry),response:responseOf(entry),cache:{},timings:{send:0,wait:time,receive:0}};if(entry.failed)har._errorText=entry.errorText??"";return har})};return{log}}function injectHumanBanner(prompt){if(document.querySelector('[data-omowright-human="1"]'))return true;const host=document.createElement("div");host.setAttribute("data-omowright-human","1");host.style.cssText="position:fixed;top:0;left:0;right:0;z-index:2147483647;display:block;visibility:visible;opacity:1;pointer-events:auto;";const root=host.attachShadow({mode:"open"});const bar=document.createElement("div");bar.setAttribute("style","display:flex;align-items:center;gap:12px;padding:10px 16px;background:#111;color:#fff;font:14px/1.4 system-ui,sans-serif;");const message=document.createElement("span");message.textContent=prompt==null?"":String(prompt);const button=document.createElement("button");button.textContent="Done";button.addEventListener("click",()=>{window.__omowrightHumanDone=true});bar.append(message,button);root.append(bar);(document.documentElement??document.body).appendChild(host);return true}function humanBannerPresent(){return document.querySelector('[data-omowright-human="1"]')!==null}function humanDoneFlag(){return window.__omowrightHumanDone===true}function querySelectorExists(selector){return document.querySelector(selector)!==null}function removeHumanBanner(){document.querySelectorAll('[data-omowright-human="1"]').forEach((node)=>node.remove());try{delete window.__omowrightHumanDone}catch{window.__omowrightHumanDone=undefined}}function sleep(ms,signal){return new Promise((resolve)=>{if(signal?.aborted){resolve();return}const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);function onAbort(){clearTimeout(timer);resolve()}signal?.addEventListener("abort",onAbort,{once:true})})}async function ensureBanner(page,prompt){try{if(await page.evaluate(humanBannerPresent))return;await page.evaluate(injectHumanBanner,prompt??"")}catch{}}async function matchesUntil(page,until){if(until==null)return false;if(typeof until==="function")return Boolean(await until(page));if(typeof until==="object"){if(Object.prototype.hasOwnProperty.call(until,"url")){const current=page.url();const expected=until.url;if(expected instanceof RegExp)return expected.test(current);return String(current).includes(String(expected))}if(typeof until.selector==="string"){try{return Boolean(await page.evaluate(querySelectorExists,until.selector))}catch{return false}}}return false}async function isDone(page){try{return await page.evaluate(humanDoneFlag)===true}catch{return false}}async function requestHuman(page,{prompt,until,timeoutMs=300000,pollMs=500,signal}={}){const started=Date.now();const finish=(outcome,reason)=>({outcome,elapsedMs:Date.now()-started,reason});try{await page.bringToFront().catch(()=>{});await ensureBanner(page,prompt);for(;;){if(signal?.aborted)return finish("cancelled","signal");if(Date.now()-started>=timeoutMs)return finish("timed_out","timed_out");if(await matchesUntil(page,until))return finish("continued","until");if(await isDone(page))return finish("continued","done-button");await ensureBanner(page,prompt);const remaining=timeoutMs-(Date.now()-started);if(remaining<=0)return finish("timed_out","timed_out");await sleep(Math.min(pollMs,remaining),signal)}}finally{await page.evaluate(removeHumanBanner).catch(()=>{})}}async function describeLayers(page,{grid=5}={}){return page.evaluate((gridSize)=>{const width=Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0);const height=Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0);const viewport={width,height};const total=gridSize*gridSize;const hits=new Map;function pierceTopmost(x,y){const stack=document.elementsFromPoint(x,y);let el=stack[0]??null;const seen=new Set;while(el?.shadowRoot&&typeof el.shadowRoot.elementsFromPoint==="function"){if(seen.has(el))break;seen.add(el);const inner=el.shadowRoot.elementsFromPoint(x,y)??[];const next=inner.find((node)=>node&&node!==el);if(!next)break;el=next}return el}function parentOf(node){if(!node)return null;if(node.parentElement)return node.parentElement;const root=node.getRootNode?.();return root?.host??null}function promote(el){const minArea=0.5*width*height;let node=el;while(node&&node.nodeType===1){const position=getComputedStyle(node).position;if(position==="fixed"||position==="sticky"||position==="absolute"){const rect=node.getBoundingClientRect();if(rect.width*rect.height>=minArea)return node}node=parentOf(node)}return el}function labelledByText(el){const ids=(el.getAttribute("aria-labelledby")||"").trim();if(!ids)return"";return ids.split(/\s+/).map((id)=>document.getElementById(id)?.textContent?.trim()??"").filter(Boolean).join(" ")}function elementName(el){const ariaLabel=el.getAttribute("aria-label");if(ariaLabel)return ariaLabel;const labelled=labelledByText(el);if(labelled)return labelled;const heading=el.querySelector("h1,h2,h3,h4,h5,h6")?.textContent?.trim();if(heading)return heading;return(el.innerText||el.textContent||"").trim().replace(/\s+/g," ").slice(0,80)}function selectorHint(el){if(el.id)return`#${el.id}`;const classes=[...el.classList].join(".");return classes?`${el.tagName.toLowerCase()}.${classes}`:el.tagName.toLowerCase()}function describe(el,coverage){return{tagName:el.tagName,role:el.getAttribute("role")||"",name:elementName(el),coverage,position:getComputedStyle(el).position,selectorHint:selectorHint(el),ariaModal:el.getAttribute("aria-modal")==="true"}}function isMainContent(el){if(el===document.documentElement||el===document.body)return true;if(el.tagName==="MAIN")return true;return(el.getAttribute("role")||"").toLowerCase()==="main"}function isBlocking(el,info){if(info.coverage<0.6)return false;if(getComputedStyle(el).pointerEvents==="none")return false;const role=(info.role||"").toLowerCase();if(role==="dialog"||role==="alertdialog")return true;if(info.ariaModal)return true;if(isMainContent(el))return false;return info.position==="fixed"||info.position==="absolute"}const insetX=width*0.05;const insetY=height*0.05;const spanX=width*0.9;const spanY=height*0.9;for(let row=0;row<gridSize;row++){for(let col=0;col<gridSize;col++){const x=insetX+(col+0.5)*spanX/gridSize;const y=insetY+(row+0.5)*spanY/gridSize;const top=pierceTopmost(x,y);if(!top)continue;const candidate=promote(top);hits.set(candidate,(hits.get(candidate)??0)+1)}}const candidates=[...hits.entries()].map(([el,count])=>{const info=describe(el,total>0?count/total:0);return{el,info}}).sort((a,b)=>b.info.coverage-a.info.coverage);const blockingEntry=candidates.find((entry)=>isBlocking(entry.el,entry.info));return{blocking:blockingEntry?blockingEntry.info:null,candidates:candidates.map((entry)=>entry.info),viewport}},grid)}function layersHeader(result){const blocking=result?.blocking;if(!blocking)return"@layers none";const who=blocking.role||blocking.tagName;const pct=Math.round(blocking.coverage*100);return`@layers blocking=${who} "${blocking.name}" coverage=${pct}% hint=${blocking.selectorHint}`}async function snapshotWithLayers(page,snapshotOptions){const snapshot=await page.snapshot(snapshotOptions);const layers=await describeLayers(page);return{...snapshot,layers,tree:`${layersHeader(layers)}+`);disconnect(error)}};stdin.on("data",onData);stdin.once?.("end",()=>disconnect());stdin.once?.("error",disconnect);return{get isConnected(){return!closed&&!!hello},get capabilities(){return{commands:new Set(hello?.commands??[]),events:new Set(hello?.events??[])}},send:write,request(name,params,{signal,timeoutMs=commandTimeoutMs}={}){if(!hello||!hello.commands.includes(name))return Promise.reject(new BridgeUnavailableError(`unsupported bridge command: ${name}`));let command;try{command=checked(CommandSchema,{protocol:PROTOCOL,type:"command",requestId:randomUUID4(),name,params},"invalid command parameters")}catch(error){return Promise.reject(error)}return new Promise((resolve,reject)=>{if(commandQueue.length+pending.size>=maxPendingWrites){reject(new BridgeProtocolError("BOUNDED_TRANSPORT"));return}const item={requestId:command.requestId,name,command,resolve,reject,timer:null,abortHandler:null,cleanup:null,settled:false};const cleanup=()=>{clearTimeout(item.timer);if(item.abortHandler){signal?.removeEventListener("abort",item.abortHandler);item.abortHandler=null}};item.cleanup=cleanup;const failIndeterminate=(code,reason=null)=>{if(item.settled)return;item.settled=true;cleanup();if(pending.delete(item.requestId)||commandQueue.includes(item)){const i=commandQueue.indexOf(item);if(i>=0)commandQueue.splice(i,1);item.reject(reason??Object.assign(new Error(`bridge command timed out: ${name}`),{code}))}if(item.started)disconnect(Object.assign(new Error("mutation completion is indeterminate"),{code}))};item.timer=setTimeout(()=>failIndeterminate("TIMEOUT"),timeoutMs);if(signal?.aborted){item.settled=true;cleanup();reject(signal.reason??Object.assign(new Error(`bridge command aborted: ${name}`),{code:"ABORT_ERR"}));return}item.abortHandler=()=>failIndeterminate("ABORT_ERR",signal.reason);signal?.addEventListener("abort",item.abortHandler,{once:true});commandQueue.push(item);pumpCommands()})},on(name,listener){if(!EVENT_NAMES2.includes(name))throw new BridgeProtocolError("invalid event name");const set=listeners.get(name)??new Set;set.add(listener);listeners.set(name,set);return()=>{set.delete(listener);if(!set.size)listeners.delete(name)}},emitEvent(name,payload){if(!hello?.events.includes(name))return Promise.reject(new BridgeUnavailableError("unsupported bridge event"));const checkedPayload=payloadSchemas[name].safeParse(payload);if(!checkedPayload.success)return Promise.reject(new BridgeProtocolError("invalid event payload"));sequence+=1;return write({protocol:PROTOCOL,type:"event",connectionId:hostConnectionId,seq:sequence,occurredAt:Date.now(),name,payload:checkedPayload.data})},close(){disconnect("closed");stdin.removeListener?.("data",onData)}}}var NATIVE_HOST_DIRS={darwin:{chrome:["Library","Application Support","Google","Chrome"],chromium:["Library","Application Support","Chromium"]},linux:{chrome:[".config","google-chrome"],chromium:[".config","chromium"]}};function defaultNativeMessagingHostDir(browser="chrome",platform=process.platform){const byBrowser=NATIVE_HOST_DIRS[platform];if(!byBrowser)throw new BridgeProtocolError(`no default nativeMessagingHostDir on ${platform}; pass nativeMessagingHostDir`);const segments=byBrowser[browser];if(!segments)throw new BridgeProtocolError("custom browser requires nativeMessagingHostDir");return path10.join(homedir(),...segments,"NativeMessagingHosts")}async function secureDirectory(dir){const absolute=path10.resolve(dir);const parts=absolute.split(path10.sep).filter(Boolean);let current=path10.parse(absolute).root;let final;for(const[index,part]of parts.entries()){current=path10.join(current,part);let info=await lstat(current).catch(()=>null);if(!info){await mkdir5(current,{mode:448});info=await lstat(current)}if(current!=="/var"&&(info.isSymbolicLink()||!info.isDirectory()))throw new BridgeProtocolError("nativeMessagingHostDir security rejected");if(current!=="/var"&&info.uid!==process.getuid?.()&&info.uid!==0)throw new BridgeProtocolError("nativeMessagingHostDir ownership rejected");const stickyRootAncestor=index<parts.length-1&&info.uid===0&&(info.mode&512)!==0;if(current!=="/var"&&!stickyRootAncestor&&(info.mode&18)!==0)throw new BridgeProtocolError("nativeMessagingHostDir security rejected");final=info}if(!final||final.uid!==process.getuid?.()&&final.uid!==0)throw new BridgeProtocolError("nativeMessagingHostDir ownership rejected");if((final.mode&63)!==0)await chmod4(absolute,448)}async function secureExecutable(hostPath){const info=await lstat(hostPath).catch(()=>null);if(!info?.isFile()||info.isSymbolicLink()||info.uid!==process.getuid?.()||(info.mode&73)===0||(info.mode&18)!==0)throw new BridgeProtocolError("hostPath must be a securely owned executable file")}async function installNativeMessagingHost({hostName=HOST_NAME,hostPath,extensionId,browser="chrome",nativeMessagingHostDir,force=false,endpointPath}={}){if(endpointPath!==undefined)throw new BridgeProtocolError("endpointPath is not supported");if(hostName!==HOST_NAME||!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName))throw new BridgeProtocolError("invalid hostName");if(!path10.isAbsolute(hostPath??""))throw new BridgeProtocolError("hostPath must be absolute");await secureExecutable(hostPath);if(!/^[a-p]{32}$/.test(extensionId??""))throw new BridgeProtocolError("invalid extensionId");if(!nativeMessagingHostDir&&browser==="cloakbrowser")throw new BridgeProtocolError("CloakBrowser nativeMessagingHostDir must be explicit and verified");const dir=nativeMessagingHostDir??defaultNativeMessagingHostDir(browser);await secureDirectory(dir);const manifest={name:hostName,description:"OmOWright internal CloakBrowser native messaging bridge.",path:hostPath,type:"stdio",allowed_origins:[`chrome-extension://${extensionId}/`]};const file=path10.join(dir,`${hostName}.json`);if(!force&&await lstat(file).catch(()=>null))throw new BridgeProtocolError("registration manifest already exists; use force");const temp=`${file}.${process.pid}.${randomUUID4()}.tmp`;const handle=await open5(temp,"wx",384);try{await handle.writeFile(JSON.stringify(manifest,null,2)+`+`);await handle.sync()}finally{await handle.close()}await rename3(temp,file);const parsed=JSON.parse(await readFile5(file,"utf8"));await chmod4(file,384);return{path:file,manifest:parsed}}function createBridgeClient(options={}){return createNativeMessagingHost(options)}function createChromeApi2(connection,options={}){const chrome=createChromeApi(connection,options);const bridge=options.bridge;const request=(wire,params)=>bridge?.isConnected&&bridge.capabilities?.commands?.has(wire)?bridge.request(wire,params):Promise.reject(new UnsupportedOperationError(`chrome.${wire} requires the extension bridge in standalone OmOWright`));chrome.bookmarks.create=(details)=>request("bookmarks.create",{details});chrome.bookmarks.move=(id,details={})=>request("bookmarks.move",{details:{...details,id:String(id)}});chrome.bookmarks.remove=(id)=>request("bookmarks.remove",{details:{id:String(id)}});chrome.history.deleteUrl=(details)=>request("history.deleteUrl",{details});chrome.history.deleteRange=(details)=>request("history.deleteRange",{details});chrome.tabGroups={update:(groupId,updateProperties)=>request("tabGroups.update",{details:{groupId,updateProperties}})};chrome.debugger={attach:(target,requiredVersion)=>request("debugger.attach",{details:{tabId:target.tabId??target,requiredVersion}}),detach:(target)=>request("debugger.detach",{details:{tabId:target.tabId??target}})};const eventMap={notifications:["onShown","onClicked","onClosed"],tabGroups:["onCreated","onUpdated","onMoved"],tabs:["onActivated"],windows:["onFocusChanged"]};for(const[namespace,events]of Object.entries(eventMap)){chrome[namespace]??={};for(const event of events){const wire=`${namespace}.${event.slice(2,3).toLowerCase()+event.slice(3)}`;const subscriptions=new Map;chrome[namespace][event]={addListener(listener){if(!bridge?.on)return;const unsubscribe=bridge.on(wire,(payload)=>listener(...namespace==="notifications"&&event==="onClosed"?[payload.notificationId,payload.byUser]:namespace==="notifications"?[payload.notificationId]:namespace==="tabGroups"?[payload.group]:namespace==="windows"?[payload.windowId]:[payload]));subscriptions.set(listener,unsubscribe);return unsubscribe},removeListener(listener){const unsubscribe=subscriptions.get(listener);if(unsubscribe){unsubscribe();subscriptions.delete(listener)}}}}}return chrome}function sanitizeCookies(cookies){const byKey=new Map;for(const cookie of cookies){const out={name:cookie.name,value:cookie.value,path:cookie.path||"/",secure:Boolean(cookie.secure),httpOnly:Boolean(cookie.httpOnly)};if(cookie.name.startsWith("__Host-")){out.secure=true;out.path="/";out.url=`https://${cookie.domain.replace(/^\./,"")}`}else{out.domain=cookie.domain}if(cookie.expires&&cookie.expires>0)out.expires=cookie.expires;if(cookie.sameSite&&(cookie.sameSite!=="None"||out.secure))out.sameSite=cookie.sameSite;const key=`${out.name}|${out.domain??out.url}`;const prev=byKey.get(key);if(!prev||(out.expires??0)>(prev.expires??0))byKey.set(key,out)}return[...byKey.values()]}async function injectCookies(page,cookies){await page._sendToTarget("Network.setCookies",{cookies:sanitizeCookies(cookies)})}var DEVICE_PRESETS=Object.freeze({"iphone-14":{width:390,height:844,deviceScaleFactor:3,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"iPhone"},"pixel-7":{width:412,height:915,deviceScaleFactor:2.625,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",platform:"Linux armv8l"},"ipad-air":{width:820,height:1180,deviceScaleFactor:2,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"MacIntel"},"desktop-1440":{width:1440,height:900,deviceScaleFactor:1,mobile:false,hasTouch:false,userAgent:undefined,platform:undefined}});var originalUAs=new WeakMap;async function emulate(page,presetNameOrObject){let preset;if(presetNameOrObject===null){preset=null}else if(typeof presetNameOrObject==="string"){if(!DEVICE_PRESETS[presetNameOrObject]){throw new Error(`unknown device preset: ${presetNameOrObject}`)}preset=DEVICE_PRESETS[presetNameOrObject]}else{preset=presetNameOrObject}const sessionId=await page.resolveSessionId();if(preset===null){await page.cdp.send("Emulation.clearDeviceMetricsOverride",{},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:false},sessionId);const originalUA=originalUAs.get(page);if(originalUA){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:originalUA},sessionId)}}else{if(!originalUAs.has(page)){const ua=await page.evaluate(()=>navigator.userAgent);originalUAs.set(page,ua)}await page.cdp.send("Emulation.setDeviceMetricsOverride",{width:preset.width,height:preset.height,deviceScaleFactor:preset.deviceScaleFactor,mobile:preset.mobile,screenWidth:preset.width,screenHeight:preset.height},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:preset.hasTouch,maxTouchPoints:preset.hasTouch?5:1},sessionId);if(preset.userAgent!==undefined){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:preset.userAgent,platform:preset.platform},sessionId)}}if(page.refreshViewportSize){await page.refreshViewportSize()}return preset}var AUTO_ATTACH={autoAttach:true,waitForDebuggerOnStart:false,flatten:true};var REF_PATTERN2=/^(f\d+)?e\d+$/;function detach(page,sessionId){return page.cdp.send("Target.detachFromTarget",{sessionId}).catch(()=>{})}async function iframeTargets(page){const{targetInfo}=await page.cdp.send("Target.getTargetInfo",{targetId:page.targetId});const browserContextId=targetInfo?.browserContextId;const{targetInfos}=await page.cdp.send("Target.getTargets",{filter:[{type:"iframe"}]});return targetInfos.filter((info)=>info.type==="iframe"&&(!browserContextId||!info.browserContextId||info.browserContextId===browserContextId))}function isAttributed(fm,frameId){const seen=new Set;let frame=fm.frames.get(frameId);while(frame&&!seen.has(frame.frameId)){if(frame.frameId===fm.mainFrameId)return true;seen.add(frame.frameId);frame=frame.parentFrameId?fm.frames.get(frame.parentFrameId):null}return false}async function describeTarget(page,targetId){const{sessionId}=await page.cdp.send("Target.attachToTarget",{targetId,flatten:true});try{await page.cdp.send("Page.enable",undefined,sessionId);const{frameTree}=await page.cdp.send("Page.getFrameTree",undefined,sessionId);return{sessionId,frame:frameTree.frame}}catch(error){await detach(page,sessionId);throw error}}async function adopt(page,sessionId,frame,parentFrameId){await page.cdp.send("DOM.enable",undefined,sessionId);await page.cdp.send("Target.setAutoAttach",AUTO_ATTACH,sessionId).catch(()=>{});page.frameManager.frames.set(frame.id,{frameId:frame.id,parentFrameId,url:frame.url??"",name:frame.name??"",sessionId});const isolatedContextId=await page.frameManager.ensureInjected(frame.id);return{frameId:frame.id,parentFrameId,url:frame.url??"",sessionId,isolatedContextId}}async function reconcileFrames(page){const fm=page.frameManager;const added=[];let pending=(await iframeTargets(page)).filter((info)=>!isAttributed(fm,info.targetId));let progress=true;while(progress&&pending.length>0){progress=false;const retry=[];for(const target of pending){if(isAttributed(fm,target.targetId))continue;const{sessionId,frame}=await describeTarget(page,target.targetId);const parentFrameId=frame.parentId??null;if(!parentFrameId||!isAttributed(fm,parentFrameId)){await detach(page,sessionId);if(parentFrameId)retry.push(target);continue}added.push(await adopt(page,sessionId,frame,parentFrameId));progress=true}pending=retry}return added}function framePrefixes(fm){let counter=1;return fm.collectDescendantFrames(fm.mainFrameId).map(({frameId})=>({frameId,prefix:frameId===fm.mainFrameId?"":`f${counter++}`}))}function collectMissingFrames(page,refs){const seen=new Set(Object.keys(refs??{}).map((ref)=>ref.match(REF_PATTERN2)?.[1]??""));const missing=[];for(const{frameId,prefix}of framePrefixes(page.frameManager)){if(prefix===""||seen.has(prefix))continue;const frame=page.frameManager.getFrame(frameId);if(frame?.isolatedContextId)continue;missing.push({frameId,url:frame?.url??"",injected:false})}return missing}async function snapshotWithFrames(page,opts={}){await reconcileFrames(page);const result=await page.snapshot(opts);const missingFrames=collectMissingFrames(page,result.refs);return missingFrames.length>0?{...result,missingFrames}:result}var HTTP_VERSION="HTTP/1.1";var CREATOR=Object.freeze({name:"omowright",version:"0.0.1"});function headerList(headers){return Object.entries(headers??{}).map(([name,value])=>({name,value:String(value)}))}function headerValue(headers,name){for(const[key,value]of Object.entries(headers??{})){if(key.toLowerCase()===name)return String(value)}return null}function queryString(url){try{return[...new URL(String(url)).searchParams].map(([name,value])=>({name,value}))}catch{return[]}}function elapsed(entry){const started=Number(entry.startedAt);const finished=Number(entry.finishedAt);if(!Number.isFinite(started)||!Number.isFinite(finished))return 0;return Math.max(0,finished-started)}function requestOf(entry){const postData=entry.postData??null;const request={method:entry.method??"GET",url:entry.url??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.requestHeaders),queryString:queryString(entry.url),headersSize:-1,bodySize:postData===null?0:Buffer.byteLength(postData)};if(postData!==null){request.postData={mimeType:headerValue(entry.requestHeaders,"content-type")??"",text:postData}}return request}function contentOf(entry){const content={size:Number(entry.encodedDataLength??0),mimeType:entry.mimeType??""};if(typeof entry.body==="string")content.text=entry.body;if(entry.base64Encoded)content.encoding="base64";return content}function responseOf(entry){return{status:entry.failed?0:Number(entry.status??0),statusText:entry.statusText??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.responseHeaders),content:contentOf(entry),redirectURL:headerValue(entry.responseHeaders,"location")??"",headersSize:-1,bodySize:Number(entry.encodedDataLength??0)}}function toHar(entries,{creator=CREATOR,pages=[]}={}){const log={version:"1.2",creator,pages,entries:[...entries??[]].map((entry)=>{const time=elapsed(entry);const har={startedDateTime:new Date(Number(entry.startedAt)||0).toISOString(),time,request:requestOf(entry),response:responseOf(entry),cache:{},timings:{send:0,wait:time,receive:0}};if(entry.failed)har._errorText=entry.errorText??"";return har})};return{log}}function injectHumanBanner(prompt){if(document.querySelector('[data-omowright-human="1"]'))return true;const host=document.createElement("div");host.setAttribute("data-omowright-human","1");host.style.cssText="position:fixed;top:0;left:0;right:0;z-index:2147483647;display:block;visibility:visible;opacity:1;pointer-events:auto;";const root=host.attachShadow({mode:"open"});const bar=document.createElement("div");bar.setAttribute("style","display:flex;align-items:center;gap:12px;padding:10px 16px;background:#111;color:#fff;font:14px/1.4 system-ui,sans-serif;");const message=document.createElement("span");message.textContent=prompt==null?"":String(prompt);const button=document.createElement("button");button.textContent="Done";button.addEventListener("click",()=>{window.__omowrightHumanDone=true});bar.append(message,button);root.append(bar);(document.documentElement??document.body).appendChild(host);return true}function humanBannerPresent(){return document.querySelector('[data-omowright-human="1"]')!==null}function humanDoneFlag(){return window.__omowrightHumanDone===true}function querySelectorExists(selector){return document.querySelector(selector)!==null}function removeHumanBanner(){document.querySelectorAll('[data-omowright-human="1"]').forEach((node)=>node.remove());try{delete window.__omowrightHumanDone}catch{window.__omowrightHumanDone=undefined}}function sleep2(ms,signal){return new Promise((resolve)=>{if(signal?.aborted){resolve();return}const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);function onAbort(){clearTimeout(timer);resolve()}signal?.addEventListener("abort",onAbort,{once:true})})}async function ensureBanner(page,prompt){try{if(await page.evaluate(humanBannerPresent))return;await page.evaluate(injectHumanBanner,prompt??"")}catch{}}async function matchesUntil(page,until){if(until==null)return false;if(typeof until==="function")return Boolean(await until(page));if(typeof until==="object"){if(Object.prototype.hasOwnProperty.call(until,"url")){const current=page.url();const expected=until.url;if(expected instanceof RegExp)return expected.test(current);return String(current).includes(String(expected))}if(typeof until.selector==="string"){try{return Boolean(await page.evaluate(querySelectorExists,until.selector))}catch{return false}}}return false}async function isDone(page){try{return await page.evaluate(humanDoneFlag)===true}catch{return false}}async function requestHuman(page,{prompt,until,timeoutMs=300000,pollMs=500,signal}={}){const started=Date.now();const finish=(outcome,reason)=>({outcome,elapsedMs:Date.now()-started,reason});try{await page.bringToFront().catch(()=>{});await ensureBanner(page,prompt);for(;;){if(signal?.aborted)return finish("cancelled","signal");if(Date.now()-started>=timeoutMs)return finish("timed_out","timed_out");if(await matchesUntil(page,until))return finish("continued","until");if(await isDone(page))return finish("continued","done-button");await ensureBanner(page,prompt);const remaining=timeoutMs-(Date.now()-started);if(remaining<=0)return finish("timed_out","timed_out");await sleep2(Math.min(pollMs,remaining),signal)}}finally{await page.evaluate(removeHumanBanner).catch(()=>{})}}async function describeLayers(page,{grid=5}={}){return page.evaluate((gridSize)=>{const width=Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0);const height=Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0);const viewport={width,height};const total=gridSize*gridSize;const hits=new Map;function pierceTopmost(x,y){const stack=document.elementsFromPoint(x,y);let el=stack[0]??null;const seen=new Set;while(el?.shadowRoot&&typeof el.shadowRoot.elementsFromPoint==="function"){if(seen.has(el))break;seen.add(el);const inner=el.shadowRoot.elementsFromPoint(x,y)??[];const next=inner.find((node)=>node&&node!==el);if(!next)break;el=next}return el}function parentOf(node){if(!node)return null;if(node.parentElement)return node.parentElement;const root=node.getRootNode?.();return root?.host??null}function promote(el){const minArea=0.5*width*height;let node=el;while(node&&node.nodeType===1){const position=getComputedStyle(node).position;if(position==="fixed"||position==="sticky"||position==="absolute"){const rect=node.getBoundingClientRect();if(rect.width*rect.height>=minArea)return node}node=parentOf(node)}return el}function labelledByText(el){const ids=(el.getAttribute("aria-labelledby")||"").trim();if(!ids)return"";return ids.split(/\s+/).map((id)=>document.getElementById(id)?.textContent?.trim()??"").filter(Boolean).join(" ")}function elementName(el){const ariaLabel=el.getAttribute("aria-label");if(ariaLabel)return ariaLabel;const labelled=labelledByText(el);if(labelled)return labelled;const heading=el.querySelector("h1,h2,h3,h4,h5,h6")?.textContent?.trim();if(heading)return heading;return(el.innerText||el.textContent||"").trim().replace(/\s+/g," ").slice(0,80)}function selectorHint(el){if(el.id)return`#${el.id}`;const classes=[...el.classList].join(".");return classes?`${el.tagName.toLowerCase()}.${classes}`:el.tagName.toLowerCase()}function describe(el,coverage){return{tagName:el.tagName,role:el.getAttribute("role")||"",name:elementName(el),coverage,position:getComputedStyle(el).position,selectorHint:selectorHint(el),ariaModal:el.getAttribute("aria-modal")==="true"}}function isMainContent(el){if(el===document.documentElement||el===document.body)return true;if(el.tagName==="MAIN")return true;return(el.getAttribute("role")||"").toLowerCase()==="main"}function isBlocking(el,info){if(info.coverage<0.6)return false;if(getComputedStyle(el).pointerEvents==="none")return false;const role=(info.role||"").toLowerCase();if(role==="dialog"||role==="alertdialog")return true;if(info.ariaModal)return true;if(isMainContent(el))return false;return info.position==="fixed"||info.position==="absolute"}const insetX=width*0.05;const insetY=height*0.05;const spanX=width*0.9;const spanY=height*0.9;for(let row=0;row<gridSize;row++){for(let col=0;col<gridSize;col++){const x=insetX+(col+0.5)*spanX/gridSize;const y=insetY+(row+0.5)*spanY/gridSize;const top=pierceTopmost(x,y);if(!top)continue;const candidate=promote(top);hits.set(candidate,(hits.get(candidate)??0)+1)}}const candidates=[...hits.entries()].map(([el,count])=>{const info=describe(el,total>0?count/total:0);return{el,info}}).sort((a,b)=>b.info.coverage-a.info.coverage);const blockingEntry=candidates.find((entry)=>isBlocking(entry.el,entry.info));return{blocking:blockingEntry?blockingEntry.info:null,candidates:candidates.map((entry)=>entry.info),viewport}},grid)}function layersHeader(result){const blocking=result?.blocking;if(!blocking)return"@layers none";const who=blocking.role||blocking.tagName;const pct=Math.round(blocking.coverage*100);return`@layers blocking=${who} "${blocking.name}" coverage=${pct}% hint=${blocking.selectorHint}`}async function snapshotWithLayers(page,snapshotOptions){const snapshot=await page.snapshot(snapshotOptions);const layers=await describeLayers(page);return{...snapshot,layers,tree:`${layersHeader(layers)}${snapshot.tree}`}}var DEFAULT_TIMEOUT_MS=30000;var JSON_MIME=/^application\/json\s*(;|$)|\+json\s*(;|$)/i;function matchesText(value,pattern){if(pattern===undefined)return true;if(value===null||value===undefined)return false;if(pattern instanceof RegExp)return pattern.test(String(value));return String(value).includes(String(pattern))}function matchesToken(value,expected){if(expected===undefined)return true;if(value===null||value===undefined)return false;return String(value).toLowerCase()===String(expected).toLowerCase()}function toPredicate(match){if(match===undefined||match===null)return()=>true;if(typeof match==="function")return match;if(typeof match!=="object")throw new TypeError("match must be a predicate function or a descriptor object");return(entry)=>matchesText(entry.url,match.url)&&matchesToken(entry.method,match.method)&&matchesText(entry.mimeType,match.mimeType)&&matchesToken(entry.resourceType,match.resourceType)}function startedAtOf(params){const wallTime=Number(params?.wallTime);return Number.isFinite(wallTime)&&wallTime>0?Math.round(wallTime*1000):Date.now()}function decodeBody(entry){if(typeof entry.body!=="string")return null;return entry.base64Encoded?Buffer.from(entry.body,"base64").toString("utf8"):entry.body}function createNetworkSnoop(page,options={}){if(!page?.cdp||typeof page.resolveSessionId!=="function"){throw new TypeError("createNetworkSnoop requires a page with cdp and resolveSessionId")}const{match,bodies=true,maxEntries=500,maxBodyBytes=5000000}=options;const wanted=toPredicate(match);const inflight=new Map;const buffer=[];const waiters=new Set;const unsubscribers=[];let sessionId=null;let disposed=false;let queue=Promise.resolve();const ready=Promise.resolve(page.resolveSessionId()).then((id)=>{sessionId=id});ready.catch((error)=>console.warn("[network-snoop] failed to resolve the page session",error));function subscribe(method,handler){unsubscribers.push(page.cdp.on(method,(params,meta)=>{if(disposed)return;if(sessionId===null){ready.then(()=>{if(!disposed&&meta?.sessionId===sessionId)handler(params)}).catch(()=>{});return}if(meta?.sessionId!==sessionId)return;handler(params)}))}function enqueue(task){queue=queue.then(task).catch((error)=>console.warn("[network-snoop] entry processing failed",error))}async function loadBody(entry){if(entry.encodedDataLength>maxBodyBytes){entry.bodySkipped=true;return}try{const result=await page.cdp.send("Network.getResponseBody",{requestId:entry.requestId},sessionId);entry.body=result?.body??null;entry.base64Encoded=Boolean(result?.base64Encoded)}catch{entry.body=null}}function commit(entry){buffer.push(entry);while(buffer.length>maxEntries)buffer.shift();for(const waiter of[...waiters])if(waiter.test(entry))waiter.resolve(entry)}subscribe("Network.requestWillBeSent",(params)=>{const requestId=params?.requestId;if(!requestId)return;inflight.set(requestId,{requestId,url:params.request?.url??params.documentURL??"",method:params.request?.method??"GET",resourceType:params.type??null,status:null,statusText:null,mimeType:null,requestHeaders:params.request?.headers??{},responseHeaders:null,remoteIPAddress:null,postData:params.request?.postData??null,encodedDataLength:0,body:null,base64Encoded:false,bodySkipped:false,failed:false,errorText:null,startedAt:startedAtOf(params),finishedAt:null})});subscribe("Network.responseReceived",(params)=>{const entry=inflight.get(params?.requestId);if(!entry)return;const response=params.response??{};entry.status=response.status??null;entry.statusText=response.statusText??"";entry.mimeType=response.mimeType??null;entry.responseHeaders=response.headers??{};entry.remoteIPAddress=response.remoteIPAddress??null;if(params.type)entry.resourceType=params.type});subscribe("Network.loadingFinished",(params)=>{const entry=inflight.get(params?.requestId);if(!entry)return;inflight.delete(entry.requestId);entry.encodedDataLength=Number(params.encodedDataLength??0);entry.finishedAt=Date.now();enqueue(async()=>{if(!wanted(entry))return;if(bodies)await loadBody(entry);commit(entry)})});subscribe("Network.loadingFailed",(params)=>{const entry=inflight.get(params?.requestId);if(!entry)return;inflight.delete(entry.requestId);entry.failed=true;entry.errorText=params.errorText??"";entry.encodedDataLength=Number(params.encodedDataLength??entry.encodedDataLength);entry.finishedAt=Date.now();enqueue(async()=>{if(wanted(entry))commit(entry)})});function pop(){return buffer.splice(0,buffer.length)}function peek(){return[...buffer]}function popJson(){const values=[];for(const entry of pop()){if(!JSON_MIME.test(String(entry.mimeType??"")))continue;const text=decodeBody(entry);if(text===null)continue;try{values.push(JSON.parse(text))}catch{}}return values}function waitFor(match,{timeoutMs=DEFAULT_TIMEOUT_MS}={}){if(disposed)return Promise.reject(Error("Network snoop is disposed"));const predicate=toPredicate(match);return new Promise((resolve,reject)=>{let settled=false;const waiter={};const finish=(callback)=>(value)=>{if(settled)return;settled=true;clearTimeout(timer);waiters.delete(waiter);callback(value)};waiter.resolve=finish(resolve);waiter.reject=finish(reject);waiter.test=(entry)=>{try{return Boolean(predicate(entry))}catch(error){waiter.reject(error instanceof Error?error:Error(String(error)));return false}};const timer=setTimeout(()=>waiter.reject(Error(`Timed out waiting for network response after ${timeoutMs}ms`)),timeoutMs);waiters.add(waiter)})}function summary({max=50}={}){const shown=buffer.slice(0,max);const lines=shown.map((entry)=>[entry.method,entry.status??(entry.failed?"FAILED":"-"),entry.mimeType??"-",`${entry.encodedDataLength}B`,entry.url].join(" "));const hidden=buffer.length-shown.length;if(hidden>0)lines.push(`... +${hidden} more`);return lines.join(`-`)}function dispose(){if(disposed)return;disposed=true;for(const off of unsubscribers.splice(0,unsubscribers.length))off();for(const waiter of[...waiters])waiter.reject(Error("Network snoop disposed"));waiters.clear();inflight.clear()}return{pop,peek,popJson,waitFor,summary,dispose}}function globToRegExp(glob){let source="";for(const char of glob){if(char==="*")source+=".*";else if(char==="?")source+=".";else if("\\^$+{}[]()|.".includes(char))source+=`\\${char}`;else source+=char}return new RegExp(`^${source}$`)}function hasGlobChars(value){return value.includes("*")||value.includes("?")}function matches(match,request){if(typeof match==="function"){return Boolean(match({url:request.url,method:request.method,resourceType:request.resourceType,headers:request.headers}))}if(match instanceof RegExp)return match.test(request.url);if(typeof match==="string"){if(hasGlobChars(match))return globToRegExp(match).test(request.url);return request.url.includes(match)}return false}function sameMatch(left,right){if(left===right)return true;if(left instanceof RegExp&&right instanceof RegExp)return left.source===right.source&&left.flags===right.flags;return false}function toHeaderEntries(headers){if(!headers)return[];if(Array.isArray(headers)){return headers.map((header)=>({name:String(header.name),value:String(header.value??"")}))}return Object.entries(headers).map(([name,value])=>({name,value:String(value??"")}))}function encodeBody(body){if(body==null)return"";if(Buffer.isBuffer(body))return body.toString("base64");if(body instanceof Uint8Array)return Buffer.from(body).toString("base64");return Buffer.from(String(body)).toString("base64")}function buildContinue(requestId,{url,method,headers,postData}={}){const params={requestId};if(url!==undefined)params.url=url;if(method!==undefined)params.method=method;if(headers!==undefined)params.headers=toHeaderEntries(headers);if(postData!==undefined)params.postData=encodeBody(postData);return params}function buildFulfill(requestId,{status=200,headers={},contentType,body=""}={}){const responseHeaders=toHeaderEntries(headers);if(contentType!=null&&String(contentType).length>0){const hasType=responseHeaders.some((header)=>header.name.toLowerCase()==="content-type");if(!hasType)responseHeaders.push({name:"content-type",value:String(contentType)})}return{requestId,responseCode:status,responseHeaders,body:encodeBody(body)}}function createRoutes(page){if(!page?.cdp)throw new TypeError("createRoutes requires a page with cdp");const entries=[];const warned=new WeakSet;const settledIds=new Set;let enabled=false;let sessionId;let unsubscribe=null;let enablePromise=null;function warnOnce(handler,error){if(typeof handler==="function"){if(warned.has(handler))return;warned.add(handler)}if(error)console.warn("[routes] route handler failed; continuing request",error);else console.warn("[routes] route handler did not settle the request; continuing")}function findHandler(request){for(const entry of entries){if(matches(entry.match,request))return entry.handler}return}async function handlePaused(params,meta){if(!sessionId||meta?.sessionId!==sessionId)return;const requestId=params?.requestId;if(!requestId||settledIds.has(requestId))return;const request={url:params.request?.url??"",method:params.request?.method??"GET",headers:params.request?.headers??{},postData:params.request?.postData,resourceType:params.resourceType};let settled=false;const settle=(method,cdpParams)=>{if(settled)return Promise.resolve();settled=true;settledIds.add(requestId);return page.cdp.send(method,cdpParams,sessionId)};const route={request,continue(overrides={}){return settle("Fetch.continueRequest",buildContinue(requestId,overrides))},fulfill(options={}){return settle("Fetch.fulfillRequest",buildFulfill(requestId,options))},abort(errorReason="Failed"){return settle("Fetch.failRequest",{requestId,errorReason})}};const handler=findHandler(request);if(!handler){await settle("Fetch.continueRequest",{requestId});return}try{await handler(route)}catch(error){warnOnce(handler,error)}if(!settled){warnOnce(handler);await settle("Fetch.continueRequest",{requestId})}}function onPaused(params,meta){handlePaused(params,meta).catch((error)=>{console.warn("[routes] requestPaused handling failed",error)})}async function ensureEnabled(){if(enabled)return;if(!enablePromise){enablePromise=(async()=>{sessionId=await page.resolveSessionId();if(!unsubscribe)unsubscribe=page.cdp.on("Fetch.requestPaused",onPaused);await page.cdp.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]},sessionId);enabled=true})()}try{await enablePromise}catch(error){enablePromise=null;throw error}}async function disableFetch(){const pending=enablePromise;enablePromise=null;if(pending)await pending.catch(()=>{});if(unsubscribe){unsubscribe();unsubscribe=null}if(!enabled)return;enabled=false;await page.cdp.send("Fetch.disable",{},sessionId)}async function route(match,handler){if(typeof handler!=="function")throw new TypeError("handler must be a function");entries.push({match,handler});await ensureEnabled()}async function unroute(match){if(match===undefined)entries.length=0;else{for(let index=entries.length-1;index>=0;index-=1){if(sameMatch(entries[index].match,match))entries.splice(index,1)}}if(entries.length===0)await disableFetch()}async function dispose(){entries.length=0;await disableFetch()}return{route,unroute,dispose,get enabled(){return enabled}}}async function viewportOf(page){return page.viewportSize()??await page.evaluate(()=>({width:innerWidth,height:innerHeight}))}async function scrollOnce(page,mode){if(mode==="end"){await page.evaluate(()=>scrollTo(0,document.scrollingElement.scrollHeight));return}const viewport=await viewportOf(page);await page.mouse.move(Math.floor(viewport.width/2),Math.floor(viewport.height/2));await page.mouse.wheel(0,Math.floor(viewport.height*0.9))}async function*collectWhileScrolling(page,snoop,options={}){const{minItems=Infinity,maxScrolls=10,extract=(json)=>Array.isArray(json)?json:[],scroll="wheel",settleMs=800}=options;if(scroll!=="wheel"&&scroll!=="end")throw new TypeError(`Unknown scroll mode: ${String(scroll)}`);let rounds=0;let total=0;let lastHeight=null;let unchanged=0;let stoppedBecause="maxScrolls";for(;;){for(const json of snoop.popJson()){for(const item of extract(json)){total+=1;yield item}}if(total>=minItems){stoppedBecause="minItems";break}if(rounds>=maxScrolls){stoppedBecause="maxScrolls";break}const height=await page.evaluate(()=>document.scrollingElement.scrollHeight);if(lastHeight!==null&&height===lastHeight){unchanged+=1;if(unchanged>=2){stoppedBecause="noGrowth";break}}else{unchanged=0}lastHeight=height;await scrollOnce(page,scroll);rounds+=1;await new Promise((resolve)=>setTimeout(resolve,settleMs))}return{rounds,total,stoppedBecause}}import{mkdir as mkdir5,writeFile as writeFile2}from"node:fs/promises";import path8 from"node:path";var SLUG_MAX=48;var SNOOP_MAX_ENTRIES=5000;function slug(name){const value=String(name??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return(value||"step").slice(0,SLUG_MAX)}function messageOf(error){return error instanceof Error?error.message:String(error)}async function readConsole(page){const api=page.console;const entries=typeof api==="function"?await api.call(page):await api?.logs?.();return Array.isArray(entries)?entries:[]}function createTrace(page,options={}){if(!page?.cdp||typeof page.resolveSessionId!=="function"){throw new TypeError("createTrace requires a page with cdp and resolveSessionId")}const{dir,screenshots=true,network=true,console:consoleLogs=true,maxBodyBytes=1e6,events}=options;if(typeof dir!=="string"||dir.length===0)throw new TypeError("createTrace requires a dir");const shotDir=path8.join(dir,"screenshots");const ready=mkdir5(shotDir,{recursive:true});const startedAt=Date.now();const records=[];const netEntries=[];const unsubscribers=[];const snoop=network?createNetworkSnoop(page,{bodies:true,maxBodyBytes,maxEntries:SNOOP_MAX_ENTRIES}):null;let seq=0;let consoleSeen=0;let sessionId=null;let stopped=false;let stopping=null;function record(event){const entry={...event,ts:Date.now(),seq:seq++};records.push(entry);return entry}const sessionReady=Promise.resolve(page.resolveSessionId()).then((id)=>{sessionId=id});sessionReady.catch((error)=>record({kind:"warning",scope:"session",message:messageOf(error)}));unsubscribers.push(page.cdp.on("Page.frameNavigated",(params,meta)=>{if(stopped||params?.frame?.parentId)return;const add=()=>record({kind:"navigation",url:params?.frame?.url??"",frameId:params?.frame?.id??null});if(sessionId===null){sessionReady.then(()=>{if(!stopped&&meta?.sessionId===sessionId)add()}).catch(()=>{});return}if(meta?.sessionId===sessionId)add()}));unsubscribers.push(page.on("dialog",(dialog)=>record({kind:"dialog",type:dialog?.type??null,message:dialog?.message??"",defaultPrompt:dialog?.defaultPrompt??"",url:dialog?.url??null})));if(events){unsubscribers.push(events.on("downloadStarted",(payload)=>record({kind:"download",phase:"started",...payload})));unsubscribers.push(events.on("downloadFinished",(payload)=>record({kind:"download",phase:"finished",...payload})))}async function capture(step,phase){const file=path8.join(shotDir,`${step.seq}-${slug(step.name)}-${phase}.png`);try{await writeFile2(file,await page.screenshot({type:"png"}));step.screenshots[phase]=file}catch(error){record({kind:"warning",scope:`screenshot:${phase}`,step:step.seq,message:messageOf(error)})}}function drainNetwork(){for(const entry of snoop?.pop()??[]){if(typeof entry.body==="string"&&Buffer.byteLength(entry.body)>maxBodyBytes){entry.body=null;entry.bodySkipped=true}netEntries.push(entry);record({kind:"network",...entry})}}async function drainConsole(){if(!consoleLogs)return;let entries;try{entries=await readConsole(page)}catch{return}if(entries.length<consoleSeen)consoleSeen=0;for(const entry of entries.slice(consoleSeen))record({kind:"console",...entry});consoleSeen=entries.length}async function drain(){drainNetwork();await drainConsole()}async function step(name,fn){if(typeof fn!=="function")throw new TypeError("trace.step requires a function");await ready;const entry=record({kind:"step",name:String(name),startedAt:Date.now(),screenshots:{}});if(screenshots)await capture(entry,"before");try{return await fn()}catch(error){entry.error=messageOf(error);throw error}finally{entry.endedAt=Date.now();entry.durationMs=entry.endedAt-entry.startedAt;if(screenshots)await capture(entry,"after");await drain()}}function mark(name,data){return record({kind:"mark",name:String(name),data:data??null})}async function finish(){await ready;await drain();stopped=true;for(const off of unsubscribers.splice(0,unsubscribers.length))off();snoop?.dispose();const ordered=[...records].sort((a,b)=>a.seq-b.seq);const summary={steps:ordered.filter((entry)=>entry.kind==="step").length,events:ordered.length,network:netEntries.length,startedAt,endedAt:Date.now(),url:page.url()};await writeFile2(path8.join(dir,"trace.jsonl"),ordered.map((entry)=>`${JSON.stringify(entry)}-`).join(""));await writeFile2(path8.join(dir,"trace.har"),`${JSON.stringify(toHar(netEntries),null,2)}-`);await writeFile2(path8.join(dir,"summary.json"),`${JSON.stringify(summary,null,2)}-`);return summary}function stop(){return stopping??=finish()}return{step,mark,stop,get dir(){return dir}}}import{connect as connect2}from"node:net";import{existsSync as existsSync3}from"node:fs";import path10 from"node:path";import{randomBytes}from"node:crypto";import{existsSync as existsSync2,readFileSync as readFileSync3}from"node:fs";import{homedir as homedir2}from"node:os";import path9 from"node:path";import{spawn as spawn3}from"node:child_process";import{createHash}from"node:crypto";function resolveBskHome(env=process.env){const override=env.BSK_HOME;if(typeof override==="string"&&override.length>0)return override;const home=env.HOME&&env.HOME.length>0?env.HOME:homedir2();return path9.join(home,".bsk")}function daemonInfoPath(home){return path9.join(home,"daemon.json")}function readDaemonInfo(home){let raw;try{raw=readFileSync3(daemonInfoPath(home),"utf8")}catch{return null}let info;try{info=JSON.parse(raw)}catch{return null}if(!info||typeof info.sock_path!=="string"||info.sock_path.length===0)return null;return info}function findBskBinary(env=process.env){const home=env.HOME&&env.HOME.length>0?env.HOME:homedir2();const candidates=[env.BSK_BIN,path9.join(home,".local","bin",process.platform==="win32"?"bsk.exe":"bsk")].filter(Boolean);for(const candidate of candidates)if(existsSync2(candidate))return candidate;return"bsk"}var NO_BREAKAWAY=/Job Object/;function windowsDaemonTaskName(home){return`bsk-daemon-${createHash("sha256").update(path9.resolve(home).toLowerCase()).digest("hex").slice(0,12)}`}function windowsDaemonLaunch(home,bskBin){const literal=(value)=>`'${value.replace(/['\u2018\u2019\u201A\u201B]/g,(quote)=>quote+quote)}'`;const script=`$env:BSK_HOME = ${literal(home)}; & ${literal(bskBin)} daemon start --foreground; exit $LASTEXITCODE`;return`--headless powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function startDaemonInWindowsTask({home,bskBin,timeoutMs}){const script=["$action = New-ScheduledTaskAction -Execute (Join-Path $env:SystemRoot 'System32\\conhost.exe') -Argument $env:BSK_TASK_ARGUMENT","$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew","Register-ScheduledTask -TaskName $env:BSK_TASK_NAME -Action $action -Settings $settings -Force | Out-Null","Start-ScheduledTask -TaskName $env:BSK_TASK_NAME"].join("; ");return runToExit("powershell.exe",["-NoProfile","-NonInteractive","-Command",script],{env:{...process.env,BSK_TASK_NAME:windowsDaemonTaskName(home),BSK_TASK_ARGUMENT:windowsDaemonLaunch(home,bskBin)},timeoutMs,label:"registering the bsk daemon task"})}function runToExit(command,args,{env,timeoutMs,label}){return new Promise((resolve,reject)=>{const child=spawn3(command,args,{env,stdio:["ignore","pipe","pipe"],windowsHide:true});let output="";const keep=(chunk)=>{output=(output+chunk).slice(-4096)};child.stdout.on("data",keep);child.stderr.on("data",keep);const timer=setTimeout(()=>{child.kill("SIGKILL");reject(new Error(`${label} did not return within ${timeoutMs}ms`))},timeoutMs);child.on("error",(error)=>{clearTimeout(timer);reject(new Error(`could not run ${command}: ${error.message}`))});child.on("exit",(code)=>{clearTimeout(timer);resolve({code,output:output.trim()})})})}async function startDaemonWithCli({home,env=process.env,bskBin=findBskBinary(env),timeoutMs=20000}={}){const status=await runToExit(bskBin,["status","--json"],{env:{...env,BSK_HOME:home},timeoutMs,label:"bsk status"});if(status.code===0)return;if(process.platform==="win32"&&NO_BREAKAWAY.test(status.output)){const task=await startDaemonInWindowsTask({home,bskBin,timeoutMs});if(task.code===0)return;throw new Error(`registering the bsk daemon task exited with ${task.code}${task.output?`: ${task.output}`:""}`)}throw new Error(`bsk status exited with ${status.code}${status.output?`: ${status.output}`:""}`)}var DEFAULT_TIMEOUT_MS2=35000;var DISCOVERY_RETRY_MS=250;var DISCOVERY_BUDGET_MS=15000;var TOOL_TIMEOUT_GRACE_MS=5000;var HUMAN_WAIT_METHODS=new Set(["tool.request_help","tool.tab_borrow"]);var HUMAN_WAIT_BACKSTOP_MS=3600000;function ownBudgetMs(params){const budgets=[params?.timeout_ms,params?.confirmation_timeout_ms].filter((value)=>typeof value==="number");return budgets.length>0?Math.max(...budgets)+TOOL_TIMEOUT_GRACE_MS:undefined}var PROBE_TIMEOUT_MS=2000;function defaultSocketPath(home){return path10.join(home,"run","daemon.sock")}function probeSocket(sockPath){if(process.platform==="win32"||!existsSync3(sockPath))return Promise.resolve(false);return new Promise((resolve)=>{const socket=connect2(sockPath);const done=(alive)=>{clearTimeout(timer);socket.destroy();resolve(alive)};const timer=setTimeout(()=>done(false),PROBE_TIMEOUT_MS);socket.on("error",()=>done(false));socket.on("connect",()=>socket.write(JSON.stringify({id:"probe-orphan",method:"system.ping"})+`-`));socket.on("data",()=>done(true))})}class BskRpcError extends Error{constructor(code,message,data){super(message);this.name="BskRpcError";this.code=code;this.data=data}}function shortId(){return randomBytes(6).toString("hex")}function sleep2(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}class BskIpcClient{#home;#sockPath;#autoStart;#startDaemon;#timeoutMs;#starting=null;constructor({home,env=process.env,sockPath,autoStart,startDaemon,timeoutMs=DEFAULT_TIMEOUT_MS2,bskBin}={}){this.#home=home??resolveBskHome(env);this.#sockPath=sockPath??null;this.#autoStart=autoStart??env.BSK_AUTO_START!=="0";this.#startDaemon=startDaemon??(()=>startDaemonWithCli({home:this.#home,env,bskBin}));this.#timeoutMs=timeoutMs}get home(){return this.#home}async resolveSocket({isAborted=()=>false}={}){if(this.#sockPath)return this.#sockPath;const found=readDaemonInfo(this.#home);if(found)return found.sock_path;const orphan=defaultSocketPath(this.#home);if(existsSync3(orphan)){if(await probeSocket(orphan))return orphan;if(isAborted())throw new BskRpcError("cancelled","cancelled before the daemon was located")}if(!this.#autoStart){throw new BskRpcError("no_daemon",`no BrowserSkill daemon published at ${this.#home}/daemon.json and automatic start is disabled (BSK_AUTO_START=0); run \`bsk daemon start\` in the environment that owns it`)}if(!this.#starting)this.#starting=this.#startDaemon().finally(()=>{this.#starting=null});await this.#starting;const deadline=Date.now()+DISCOVERY_BUDGET_MS;while(Date.now()<deadline&&!isAborted()){const info=readDaemonInfo(this.#home);if(info)return info.sock_path;await sleep2(DISCOVERY_RETRY_MS)}if(isAborted())throw new BskRpcError("cancelled","cancelled while waiting for the daemon to publish daemon.json");throw new BskRpcError("no_daemon",`daemon start was requested but ${this.#home}/daemon.json never appeared`)}call(method,params,options={}){return this.callWithHandle(method,params,options).promise}callWithHandle(method,params,{idPrefix=method.replace(/[^a-z0-9]+/gi,"-"),timeoutMs}={}){const ownBudget=ownBudgetMs(params);const humanWait=HUMAN_WAIT_METHODS.has(method);const waitMs=humanWait&&ownBudget===undefined&&timeoutMs===undefined?HUMAN_WAIT_BACKSTOP_MS:Math.max(timeoutMs??this.#timeoutMs,ownBudget??0);const rpcId=`${idPrefix}-${shortId()}`;const frame={id:rpcId,method};if(params!==undefined)frame.params=params;let aborted=false;let abortSocket=()=>{};const promise=(async()=>{const sockPath=await this.resolveSocket({isAborted:()=>aborted});if(aborted)throw new BskRpcError("cancelled",`${method} cancelled by caller`);return new Promise((resolve,reject)=>{const socket=connect2(sockPath);let buffer="";let settled=false;const finish=(fn,value)=>{if(settled)return;settled=true;clearTimeout(timer);socket.destroy();fn(value)};const timer=setTimeout(()=>{const cancels=method!=="cancel"&&!humanWait;finish(reject,new BskRpcError("timeout",`${method} did not answer within ${waitMs}ms${cancels?"; a cancel was requested at the daemon":""}`));if(cancels)this.cancel(rpcId).catch(()=>{})},waitMs);abortSocket=()=>finish(reject,new BskRpcError("cancelled",`${method} cancelled by caller`));socket.on("error",(error)=>finish(reject,new BskRpcError("no_daemon",`IPC socket ${sockPath}: ${error.code??error.message}`)));socket.on("connect",()=>socket.write(JSON.stringify(frame)+`+`)}function dispose(){if(disposed)return;disposed=true;for(const off of unsubscribers.splice(0,unsubscribers.length))off();for(const waiter of[...waiters])waiter.reject(Error("Network snoop disposed"));waiters.clear();inflight.clear()}return{pop,peek,popJson,waitFor,summary,dispose}}function globToRegExp(glob){let source="";for(const char of glob){if(char==="*")source+=".*";else if(char==="?")source+=".";else if("\\^$+{}[]()|.".includes(char))source+=`\\${char}`;else source+=char}return new RegExp(`^${source}$`)}function hasGlobChars(value){return value.includes("*")||value.includes("?")}function matches(match,request){if(typeof match==="function"){return Boolean(match({url:request.url,method:request.method,resourceType:request.resourceType,headers:request.headers}))}if(match instanceof RegExp)return match.test(request.url);if(typeof match==="string"){if(hasGlobChars(match))return globToRegExp(match).test(request.url);return request.url.includes(match)}return false}function sameMatch(left,right){if(left===right)return true;if(left instanceof RegExp&&right instanceof RegExp)return left.source===right.source&&left.flags===right.flags;return false}function toHeaderEntries(headers){if(!headers)return[];if(Array.isArray(headers)){return headers.map((header)=>({name:String(header.name),value:String(header.value??"")}))}return Object.entries(headers).map(([name,value])=>({name,value:String(value??"")}))}function encodeBody(body){if(body==null)return"";if(Buffer.isBuffer(body))return body.toString("base64");if(body instanceof Uint8Array)return Buffer.from(body).toString("base64");return Buffer.from(String(body)).toString("base64")}function buildContinue(requestId,{url,method,headers,postData}={}){const params={requestId};if(url!==undefined)params.url=url;if(method!==undefined)params.method=method;if(headers!==undefined)params.headers=toHeaderEntries(headers);if(postData!==undefined)params.postData=encodeBody(postData);return params}function buildFulfill(requestId,{status=200,headers={},contentType,body=""}={}){const responseHeaders=toHeaderEntries(headers);if(contentType!=null&&String(contentType).length>0){const hasType=responseHeaders.some((header)=>header.name.toLowerCase()==="content-type");if(!hasType)responseHeaders.push({name:"content-type",value:String(contentType)})}return{requestId,responseCode:status,responseHeaders,body:encodeBody(body)}}function createRoutes(page){if(!page?.cdp)throw new TypeError("createRoutes requires a page with cdp");const entries=[];const warned=new WeakSet;const settledIds=new Set;let enabled=false;let sessionId;let unsubscribe=null;let enablePromise=null;function warnOnce(handler,error){if(typeof handler==="function"){if(warned.has(handler))return;warned.add(handler)}if(error)console.warn("[routes] route handler failed; continuing request",error);else console.warn("[routes] route handler did not settle the request; continuing")}function findHandler(request){for(const entry of entries){if(matches(entry.match,request))return entry.handler}return}async function handlePaused(params,meta){if(!sessionId||meta?.sessionId!==sessionId)return;const requestId=params?.requestId;if(!requestId||settledIds.has(requestId))return;const request={url:params.request?.url??"",method:params.request?.method??"GET",headers:params.request?.headers??{},postData:params.request?.postData,resourceType:params.resourceType};let settled=false;const settle=(method,cdpParams)=>{if(settled)return Promise.resolve();settled=true;settledIds.add(requestId);return page.cdp.send(method,cdpParams,sessionId)};const route={request,continue(overrides={}){return settle("Fetch.continueRequest",buildContinue(requestId,overrides))},fulfill(options={}){return settle("Fetch.fulfillRequest",buildFulfill(requestId,options))},abort(errorReason="Failed"){return settle("Fetch.failRequest",{requestId,errorReason})}};const handler=findHandler(request);if(!handler){await settle("Fetch.continueRequest",{requestId});return}try{await handler(route)}catch(error){warnOnce(handler,error)}if(!settled){warnOnce(handler);await settle("Fetch.continueRequest",{requestId})}}function onPaused(params,meta){handlePaused(params,meta).catch((error)=>{console.warn("[routes] requestPaused handling failed",error)})}async function ensureEnabled(){if(enabled)return;if(!enablePromise){enablePromise=(async()=>{sessionId=await page.resolveSessionId();if(!unsubscribe)unsubscribe=page.cdp.on("Fetch.requestPaused",onPaused);await page.cdp.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]},sessionId);enabled=true})()}try{await enablePromise}catch(error){enablePromise=null;throw error}}async function disableFetch(){const pending=enablePromise;enablePromise=null;if(pending)await pending.catch(()=>{});if(unsubscribe){unsubscribe();unsubscribe=null}if(!enabled)return;enabled=false;await page.cdp.send("Fetch.disable",{},sessionId)}async function route(match,handler){if(typeof handler!=="function")throw new TypeError("handler must be a function");entries.push({match,handler});await ensureEnabled()}async function unroute(match){if(match===undefined)entries.length=0;else{for(let index=entries.length-1;index>=0;index-=1){if(sameMatch(entries[index].match,match))entries.splice(index,1)}}if(entries.length===0)await disableFetch()}async function dispose(){entries.length=0;await disableFetch()}return{route,unroute,dispose,get enabled(){return enabled}}}async function viewportOf(page){return page.viewportSize()??await page.evaluate(()=>({width:innerWidth,height:innerHeight}))}async function scrollOnce(page,mode){if(mode==="end"){await page.evaluate(()=>scrollTo(0,document.scrollingElement.scrollHeight));return}const viewport=await viewportOf(page);await page.mouse.move(Math.floor(viewport.width/2),Math.floor(viewport.height/2));await page.mouse.wheel(0,Math.floor(viewport.height*0.9))}async function*collectWhileScrolling(page,snoop,options={}){const{minItems=Infinity,maxScrolls=10,extract=(json)=>Array.isArray(json)?json:[],scroll="wheel",settleMs=800}=options;if(scroll!=="wheel"&&scroll!=="end")throw new TypeError(`Unknown scroll mode: ${String(scroll)}`);let rounds=0;let total=0;let lastHeight=null;let unchanged=0;let stoppedBecause="maxScrolls";for(;;){for(const json of snoop.popJson()){for(const item of extract(json)){total+=1;yield item}}if(total>=minItems){stoppedBecause="minItems";break}if(rounds>=maxScrolls){stoppedBecause="maxScrolls";break}const height=await page.evaluate(()=>document.scrollingElement.scrollHeight);if(lastHeight!==null&&height===lastHeight){unchanged+=1;if(unchanged>=2){stoppedBecause="noGrowth";break}}else{unchanged=0}lastHeight=height;await scrollOnce(page,scroll);rounds+=1;await new Promise((resolve)=>setTimeout(resolve,settleMs))}return{rounds,total,stoppedBecause}}import{mkdir as mkdir6,writeFile as writeFile2}from"node:fs/promises";import path11 from"node:path";var SLUG_MAX=48;var SNOOP_MAX_ENTRIES=5000;function slug(name){const value=String(name??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return(value||"step").slice(0,SLUG_MAX)}function messageOf(error){return error instanceof Error?error.message:String(error)}async function readConsole(page){const api=page.console;const entries=typeof api==="function"?await api.call(page):await api?.logs?.();return Array.isArray(entries)?entries:[]}function createTrace(page,options={}){if(!page?.cdp||typeof page.resolveSessionId!=="function"){throw new TypeError("createTrace requires a page with cdp and resolveSessionId")}const{dir,screenshots=true,network=true,console:consoleLogs=true,maxBodyBytes=1e6,events}=options;if(typeof dir!=="string"||dir.length===0)throw new TypeError("createTrace requires a dir");const shotDir=path11.join(dir,"screenshots");const ready=mkdir6(shotDir,{recursive:true});const startedAt=Date.now();const records=[];const netEntries=[];const unsubscribers=[];const snoop=network?createNetworkSnoop(page,{bodies:true,maxBodyBytes,maxEntries:SNOOP_MAX_ENTRIES}):null;let seq=0;let consoleSeen=0;let sessionId=null;let stopped=false;let stopping=null;function record(event){const entry={...event,ts:Date.now(),seq:seq++};records.push(entry);return entry}const sessionReady=Promise.resolve(page.resolveSessionId()).then((id)=>{sessionId=id});sessionReady.catch((error)=>record({kind:"warning",scope:"session",message:messageOf(error)}));unsubscribers.push(page.cdp.on("Page.frameNavigated",(params,meta)=>{if(stopped||params?.frame?.parentId)return;const add=()=>record({kind:"navigation",url:params?.frame?.url??"",frameId:params?.frame?.id??null});if(sessionId===null){sessionReady.then(()=>{if(!stopped&&meta?.sessionId===sessionId)add()}).catch(()=>{});return}if(meta?.sessionId===sessionId)add()}));unsubscribers.push(page.on("dialog",(dialog)=>record({kind:"dialog",type:dialog?.type??null,message:dialog?.message??"",defaultPrompt:dialog?.defaultPrompt??"",url:dialog?.url??null})));if(events){unsubscribers.push(events.on("downloadStarted",(payload)=>record({kind:"download",phase:"started",...payload})));unsubscribers.push(events.on("downloadFinished",(payload)=>record({kind:"download",phase:"finished",...payload})))}async function capture(step,phase){const file=path11.join(shotDir,`${step.seq}-${slug(step.name)}-${phase}.png`);try{await writeFile2(file,await page.screenshot({type:"png"}));step.screenshots[phase]=file}catch(error){record({kind:"warning",scope:`screenshot:${phase}`,step:step.seq,message:messageOf(error)})}}function drainNetwork(){for(const entry of snoop?.pop()??[]){if(typeof entry.body==="string"&&Buffer.byteLength(entry.body)>maxBodyBytes){entry.body=null;entry.bodySkipped=true}netEntries.push(entry);record({kind:"network",...entry})}}async function drainConsole(){if(!consoleLogs)return;let entries;try{entries=await readConsole(page)}catch{return}if(entries.length<consoleSeen)consoleSeen=0;for(const entry of entries.slice(consoleSeen))record({kind:"console",...entry});consoleSeen=entries.length}async function drain(){drainNetwork();await drainConsole()}async function step(name,fn){if(typeof fn!=="function")throw new TypeError("trace.step requires a function");await ready;const entry=record({kind:"step",name:String(name),startedAt:Date.now(),screenshots:{}});if(screenshots)await capture(entry,"before");try{return await fn()}catch(error){entry.error=messageOf(error);throw error}finally{entry.endedAt=Date.now();entry.durationMs=entry.endedAt-entry.startedAt;if(screenshots)await capture(entry,"after");await drain()}}function mark(name,data){return record({kind:"mark",name:String(name),data:data??null})}async function finish(){await ready;await drain();stopped=true;for(const off of unsubscribers.splice(0,unsubscribers.length))off();snoop?.dispose();const ordered=[...records].sort((a,b)=>a.seq-b.seq);const summary={steps:ordered.filter((entry)=>entry.kind==="step").length,events:ordered.length,network:netEntries.length,startedAt,endedAt:Date.now(),url:page.url()};await writeFile2(path11.join(dir,"trace.jsonl"),ordered.map((entry)=>`${JSON.stringify(entry)}+`).join(""));await writeFile2(path11.join(dir,"trace.har"),`${JSON.stringify(toHar(netEntries),null,2)}+`);await writeFile2(path11.join(dir,"summary.json"),`${JSON.stringify(summary,null,2)}+`);return summary}function stop(){return stopping??=finish()}return{step,mark,stop,get dir(){return dir}}}import{connect as connect2}from"node:net";import{existsSync as existsSync3}from"node:fs";import path13 from"node:path";import{randomBytes}from"node:crypto";import{existsSync as existsSync2,readFileSync as readFileSync3}from"node:fs";import{homedir as homedir2}from"node:os";import path12 from"node:path";import{spawn as spawn4}from"node:child_process";import{createHash as createHash2}from"node:crypto";function resolveBskHome(env=process.env){const override=env.BSK_HOME;if(typeof override==="string"&&override.length>0)return override;const home=env.HOME&&env.HOME.length>0?env.HOME:homedir2();return path12.join(home,".bsk")}function daemonInfoPath(home){return path12.join(home,"daemon.json")}function readDaemonInfo(home){let raw;try{raw=readFileSync3(daemonInfoPath(home),"utf8")}catch{return null}let info;try{info=JSON.parse(raw)}catch{return null}if(!info||typeof info.sock_path!=="string"||info.sock_path.length===0)return null;return info}function findBskBinary(env=process.env){const home=env.HOME&&env.HOME.length>0?env.HOME:homedir2();const candidates=[env.BSK_BIN,path12.join(home,".local","bin",process.platform==="win32"?"bsk.exe":"bsk")].filter(Boolean);for(const candidate of candidates)if(existsSync2(candidate))return candidate;return"bsk"}var NO_BREAKAWAY=/Job Object/;function windowsDaemonTaskName(home){return`bsk-daemon-${createHash2("sha256").update(path12.resolve(home).toLowerCase()).digest("hex").slice(0,12)}`}function windowsDaemonLaunch(home,bskBin){const literal=(value)=>`'${value.replace(/['\u2018\u2019\u201A\u201B]/g,(quote)=>quote+quote)}'`;const script=`$env:BSK_HOME = ${literal(home)}; & ${literal(bskBin)} daemon start --foreground; exit $LASTEXITCODE`;return`--headless powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function startDaemonInWindowsTask({home,bskBin,timeoutMs}){const script=["$action = New-ScheduledTaskAction -Execute (Join-Path $env:SystemRoot 'System32\\conhost.exe') -Argument $env:BSK_TASK_ARGUMENT","$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew","Register-ScheduledTask -TaskName $env:BSK_TASK_NAME -Action $action -Settings $settings -Force | Out-Null","Start-ScheduledTask -TaskName $env:BSK_TASK_NAME"].join("; ");return runToExit("powershell.exe",["-NoProfile","-NonInteractive","-Command",script],{env:{...process.env,BSK_TASK_NAME:windowsDaemonTaskName(home),BSK_TASK_ARGUMENT:windowsDaemonLaunch(home,bskBin)},timeoutMs,label:"registering the bsk daemon task"})}function runToExit(command,args,{env,timeoutMs,label}){return new Promise((resolve,reject)=>{const child=spawn4(command,args,{env,stdio:["ignore","pipe","pipe"],windowsHide:true});let output="";const keep=(chunk)=>{output=(output+chunk).slice(-4096)};child.stdout.on("data",keep);child.stderr.on("data",keep);const timer=setTimeout(()=>{child.kill("SIGKILL");reject(new Error(`${label} did not return within ${timeoutMs}ms`))},timeoutMs);child.on("error",(error)=>{clearTimeout(timer);reject(new Error(`could not run ${command}: ${error.message}`))});child.on("exit",(code)=>{clearTimeout(timer);resolve({code,output:output.trim()})})})}async function startDaemonWithCli({home,env=process.env,bskBin=findBskBinary(env),timeoutMs=20000}={}){const status=await runToExit(bskBin,["status","--json"],{env:{...env,BSK_HOME:home},timeoutMs,label:"bsk status"});if(status.code===0)return;if(process.platform==="win32"&&NO_BREAKAWAY.test(status.output)){const task=await startDaemonInWindowsTask({home,bskBin,timeoutMs});if(task.code===0)return;throw new Error(`registering the bsk daemon task exited with ${task.code}${task.output?`: ${task.output}`:""}`)}throw new Error(`bsk status exited with ${status.code}${status.output?`: ${status.output}`:""}`)}var DEFAULT_TIMEOUT_MS2=35000;var DISCOVERY_RETRY_MS=250;var DISCOVERY_BUDGET_MS=15000;var TOOL_TIMEOUT_GRACE_MS=5000;var HUMAN_WAIT_METHODS=new Set(["tool.request_help","tool.tab_borrow"]);var HUMAN_WAIT_BACKSTOP_MS=3600000;function ownBudgetMs(params){const budgets=[params?.timeout_ms,params?.confirmation_timeout_ms].filter((value)=>typeof value==="number");return budgets.length>0?Math.max(...budgets)+TOOL_TIMEOUT_GRACE_MS:undefined}var PROBE_TIMEOUT_MS=2000;function defaultSocketPath(home){return path13.join(home,"run","daemon.sock")}function probeSocket(sockPath){if(process.platform==="win32"||!existsSync3(sockPath))return Promise.resolve(false);return new Promise((resolve)=>{const socket=connect2(sockPath);const done=(alive)=>{clearTimeout(timer);socket.destroy();resolve(alive)};const timer=setTimeout(()=>done(false),PROBE_TIMEOUT_MS);socket.on("error",()=>done(false));socket.on("connect",()=>socket.write(JSON.stringify({id:"probe-orphan",method:"system.ping"})+`+`));socket.on("data",()=>done(true))})}class BskRpcError extends Error{constructor(code,message,data){super(message);this.name="BskRpcError";this.code=code;this.data=data}}function shortId(){return randomBytes(6).toString("hex")}function sleep3(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}class BskIpcClient{#home;#sockPath;#autoStart;#startDaemon;#timeoutMs;#starting=null;constructor({home,env=process.env,sockPath,autoStart,startDaemon,timeoutMs=DEFAULT_TIMEOUT_MS2,bskBin}={}){this.#home=home??resolveBskHome(env);this.#sockPath=sockPath??null;this.#autoStart=autoStart??env.BSK_AUTO_START!=="0";this.#startDaemon=startDaemon??(()=>startDaemonWithCli({home:this.#home,env,bskBin}));this.#timeoutMs=timeoutMs}get home(){return this.#home}async resolveSocket({isAborted=()=>false}={}){if(this.#sockPath)return this.#sockPath;const found=readDaemonInfo(this.#home);if(found)return found.sock_path;const orphan=defaultSocketPath(this.#home);if(existsSync3(orphan)){if(await probeSocket(orphan))return orphan;if(isAborted())throw new BskRpcError("cancelled","cancelled before the daemon was located")}if(!this.#autoStart){throw new BskRpcError("no_daemon",`no BrowserSkill daemon published at ${this.#home}/daemon.json and automatic start is disabled (BSK_AUTO_START=0); run \`bsk daemon start\` in the environment that owns it`)}if(!this.#starting)this.#starting=this.#startDaemon().finally(()=>{this.#starting=null});await this.#starting;const deadline=Date.now()+DISCOVERY_BUDGET_MS;while(Date.now()<deadline&&!isAborted()){const info=readDaemonInfo(this.#home);if(info)return info.sock_path;await sleep3(DISCOVERY_RETRY_MS)}if(isAborted())throw new BskRpcError("cancelled","cancelled while waiting for the daemon to publish daemon.json");throw new BskRpcError("no_daemon",`daemon start was requested but ${this.#home}/daemon.json never appeared`)}call(method,params,options={}){return this.callWithHandle(method,params,options).promise}callWithHandle(method,params,{idPrefix=method.replace(/[^a-z0-9]+/gi,"-"),timeoutMs}={}){const ownBudget=ownBudgetMs(params);const humanWait=HUMAN_WAIT_METHODS.has(method);const waitMs=humanWait&&ownBudget===undefined&&timeoutMs===undefined?HUMAN_WAIT_BACKSTOP_MS:Math.max(timeoutMs??this.#timeoutMs,ownBudget??0);const rpcId=`${idPrefix}-${shortId()}`;const frame={id:rpcId,method};if(params!==undefined)frame.params=params;let aborted=false;let abortSocket=()=>{};const promise=(async()=>{const sockPath=await this.resolveSocket({isAborted:()=>aborted});if(aborted)throw new BskRpcError("cancelled",`${method} cancelled by caller`);return new Promise((resolve,reject)=>{const socket=connect2(sockPath);let buffer="";let settled=false;const finish=(fn,value)=>{if(settled)return;settled=true;clearTimeout(timer);socket.destroy();fn(value)};const timer=setTimeout(()=>{const cancels=method!=="cancel"&&!humanWait;finish(reject,new BskRpcError("timeout",`${method} did not answer within ${waitMs}ms${cancels?"; a cancel was requested at the daemon":""}`));if(cancels)this.cancel(rpcId).catch(()=>{})},waitMs);abortSocket=()=>finish(reject,new BskRpcError("cancelled",`${method} cancelled by caller`));socket.on("error",(error)=>finish(reject,new BskRpcError("no_daemon",`IPC socket ${sockPath}: ${error.code??error.message}`)));socket.on("connect",()=>socket.write(JSON.stringify(frame)+``));socket.on("data",(chunk)=>{buffer+=chunk.toString("utf8");const idx=buffer.indexOf(``);if(idx===-1)return;try{finish(resolve,decodeResponse(buffer.slice(0,idx),rpcId,method))}catch(error){finish(reject,error)}});socket.on("close",()=>finish(reject,new BskRpcError("protocol_error",`${method}: daemon closed the connection without a reply`)))})})();return{rpcId,promise,abort:()=>{aborted=true;abortSocket()}}}async cancel(rpcId){return this.call("cancel",{rpc_id:rpcId},{idPrefix:"cancel",timeoutMs:2000})}}function decodeResponse(line,rpcId,method){let reply;try{reply=JSON.parse(line)}catch{throw new BskRpcError("protocol_error",`${method}: daemon reply is not JSON: ${line.slice(0,120)}`)}const undecodableFrame=reply.id==="0"&&reply.error;if(reply.id!==rpcId&&!undecodableFrame){throw new BskRpcError("protocol_error",`${method}: reply id ${reply.id} does not match request ${rpcId}`)}if(reply.error){const{code="protocol_error",message="daemon error",data}=reply.error;throw new BskRpcError(code,message,data)}return reply.result}var REF_SHAPE=/^@?e\d+$/;function resolveTarget(target){if(typeof target==="string"){return REF_SHAPE.test(target)?{ref:target}:{selector:target}}if(target&&typeof target==="object"){if(typeof target.ref==="string")return{ref:target.ref};if(typeof target.selector==="string")return{selector:target.selector};if(typeof target.captureId==="string"){return{capture_id:target.captureId,image_x:target.x,image_y:target.y}}}throw new TypeError("target must be a ref ('e3' / '@e3'), a CSS selector, or {captureId, x, y}")}function optionalTarget(target){return target===undefined?{}:resolveTarget(target)}function compact(params){const out={};for(const[key,value]of Object.entries(params))if(value!==undefined)out[key]=value;return out}async function captureScreenshot(session,{ref,tabId,fullPage=false,scope,timeoutMs}={}){if(!fullPage){const result=await session.tool("screenshot",{ref,tab_id:tabId});return{buffer:Buffer.from(result.image_base64,"base64"),width:result.width,height:result.height,format:result.format,captureId:result.capture_id??null,captureUnavailable:result.capture_unavailable??null,tabId:result.tab_id,dialogs:result.dialogs??[]}}const started=await session.tool("screenshot_full_page",{scope,tab_id:tabId,timeout_ms:timeoutMs});const buffer=await readCapture(session,started.capture_id,started.byte_size);return{buffer,width:started.width,height:started.height,format:started.format,captureId:started.capture_id,scope:started.scope??scope??null,tabId:started.tab_id,dialogs:started.dialogs??[]}}async function readCapture(session,captureId,byteSize){const chunks=[];let offset=0;try{for(;;){const chunk=await session.tool("screenshot_read",{capture_id:captureId,offset});const bytes=Buffer.from(chunk.data_base64??"","base64");chunks.push(bytes);if(chunk.eof||bytes.length===0)break;if(chunk.next_offset<=offset)throw new Error(`screenshot_read did not advance past offset ${offset}`);offset=chunk.next_offset}}finally{await session.tool("screenshot_release",{capture_id:captureId}).catch(()=>{})}const buffer=Buffer.concat(chunks);if(typeof byteSize==="number"&&buffer.length!==byteSize){throw new Error(`screenshot capture ${captureId}: expected ${byteSize} bytes, assembled ${buffer.length}`)}return buffer}var SESSION_STOP_TIMEOUT_MS=3600000;class BskSession{#client;#stopped=false;constructor(client,{sessionId,browserInstanceId=null,agentWindowId=null,interaction=null}={}){if(typeof sessionId!=="string"||sessionId.length===0)throw new TypeError("BskSession requires a sessionId");this.#client=client;this.sessionId=sessionId;this.browserInstanceId=browserInstanceId;this.agentWindowId=agentWindowId;this.interaction=interaction}get client(){return this.#client}get stopped(){return this.#stopped}tool(name,params={}){if(this.#stopped)return Promise.reject(new Error(`BrowserSkill session ${this.sessionId} is stopped`));return this.#client.call(`tool.${name}`,compact({session_id:this.sessionId,...params}),{idPrefix:name.replace(/_/g,"-")})}navigate(url,{tabId,waitUntil,timeoutMs}={}){return this.tool("navigate",{url,tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs})}back({tabId,waitUntil,timeoutMs}={}){return this.tool("navigate_back",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs})}forward({tabId,waitUntil,timeoutMs}={}){return this.tool("navigate_forward",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs})}reload({tabId,waitUntil,timeoutMs,hard}={}){return this.tool("reload",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,hard})}observe({cursor,tabId,maxDepth,maxTokens,debugSurfaces,probeHover}={}){return this.tool("observe",{cursor,tab_id:tabId,max_depth:maxDepth,max_tokens:maxTokens,debug_surfaces:debugSurfaces,probe_hover:probeHover})}snapshot({tabId,maxDepth,maxTokens}={}){return this.tool("snapshot",{tab_id:tabId,max_depth:maxDepth,max_tokens:maxTokens})}getHtml({ref,tabId,maxBytes}={}){return this.tool("get_html",{ref,tab_id:tabId,max_bytes:maxBytes})}screenshot(options){return captureScreenshot(this,options)}click(target,{button,clickCount,modifiers,tabId,timeoutMs}={}){return this.tool("click",{...resolveTarget(target),button,click_count:clickCount,modifiers,tab_id:tabId,timeout_ms:timeoutMs})}hover(target,{modifiers,settleMs,tabId,timeoutMs}={}){return this.tool("hover",{...resolveTarget(target),modifiers,settle_ms:settleMs,tab_id:tabId,timeout_ms:timeoutMs})}focus(target,{tabId,timeoutMs}={}){return this.tool("focus",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs})}blur(target,{tabId,timeoutMs}={}){return this.tool("blur",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs})}fill(target,value,{clearBefore,tabId,timeoutMs}={}){return this.tool("fill",{...resolveTarget(target),value,clear_before:clearBefore,tab_id:tabId,timeout_ms:timeoutMs})}press(key,{target,modifiers,holdMs,tabId,timeoutMs}={}){return this.tool("press",{key,...optionalTarget(target),modifiers,hold_ms:holdMs,tab_id:tabId,timeout_ms:timeoutMs})}select(target,values,{tabId,timeoutMs}={}){return this.tool("select",{...resolveTarget(target),values:Array.isArray(values)?values:[values],tab_id:tabId,timeout_ms:timeoutMs})}scrollTo(target,{tabId,timeoutMs}={}){return this.tool("scroll_to",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs})}wheel({deltaX=0,deltaY=0,target,modifiers,tabId,timeoutMs}={}){return this.tool("wheel",{...optionalTarget(target),delta_x:deltaX,delta_y:deltaY,modifiers,tab_id:tabId,timeout_ms:timeoutMs})}evaluate(expression,{tabId,awaitPromise,returnByValue,timeoutMs}={}){return this.tool("evaluate",{expression,tab_id:tabId,await_promise:awaitPromise,return_by_value:returnByValue,timeout_ms:timeoutMs})}tabList({scope}={}){return this.tool("tab_list",{scope})}tabCreate({url,active,index}={}){return this.tool("tab_create",{url,active,index})}tabClose(tabId){return this.tool("tab_close",{tab_id:tabId})}tabSelect(tabId){return this.tool("tab_select",{tab_id:tabId})}tabBorrow(tabId,{confirmationTimeoutMs}={}){return this.tool("tab_borrow",{tab_id:tabId,confirmation_timeout_ms:confirmationTimeoutMs})}tabReturn(tabId){return this.tool("tab_return",{tab_id:tabId})}waitForNavigation({tabId,waitUntil,timeoutMs}={}){return this.tool("wait_for_navigation",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs})}requestHelp({prompt,title,targets,completionCriteria,tabId,timeoutMs}={}){return this.tool("request_help",{prompt,title,tab_id:tabId,timeout_ms:timeoutMs,targets:targets?.map((t)=>resolveTarget(t)),completion_criteria:completionCriteria})}console({tabId,since,limit,maxTextChars,includeStack}={}){return this.tool("console",{tab_id:tabId,since,limit,max_text_chars:maxTextChars,include_stack:includeStack})}network({tabId,since,limit,maxTextChars}={}){return this.tool("network",{tab_id:tabId,since,limit,max_text_chars:maxTextChars})}resize(width,height){return this.tool("window_resize",{width,height})}emulate({tabId,off,overrides}={}){return this.tool("emulate",{tab_id:tabId,off,overrides})}async stop(){if(this.#stopped)return null;this.#stopped=true;return this.#client.call("session.stop",{session_id:this.sessionId},{idPrefix:"session-stop",timeoutMs:SESSION_STOP_TIMEOUT_MS})}}var DEFAULT_WAIT_FOR_BROWSER_MS=15000;async function listBrowsers(client,{waitForBrowserMs}={}){const status=await client.call("system.status",compact({wait_for_browser_ms:waitForBrowserMs}),{idPrefix:"status"});return status.browsers??[]}async function connectBrowserSkill({client,home,env,sockPath,autoStart,timeoutMs,bskBin,name,browser,width,height,focused=false,waitForBrowserMs=DEFAULT_WAIT_FOR_BROWSER_MS}={}){const ipc=client??new BskIpcClient({home,env,sockPath,autoStart,timeoutMs,bskBin});const browsers=await listBrowsers(ipc,{waitForBrowserMs});if(browsers.length===0){throw new BskRpcError("no_browser_connected","the BrowserSkill daemon is up but no browser extension is connected; open the browser that has the BrowserSkill extension enabled (bskDoctor() explains the remaining step) instead of falling back to a headless browser")}const started=await ipc.call("session.start",compact({task_name:name,browser_instance_id:browser,width,height,focused}),{idPrefix:"session-start"});return new BskSession(ipc,{sessionId:started.session_id,browserInstanceId:started.browser_instance_id??null,agentWindowId:started.agent_window_id??null,interaction:started.interaction??null})}var CSS_PATH_FN=String(function cssPath(el){if(!(el instanceof Element))return null;if(el.getRootNode()!==document)return null;const parts=[];let node=el;while(node&&node.nodeType===1&&node!==document.documentElement){let part=node.localName;if(node.id&&/^[A-Za-z_][\w-]*$/.test(node.id)&&document.querySelectorAll("#"+node.id).length===1){parts.unshift("#"+node.id);return parts.join(" > ")}const parent=node.parentElement;if(parent){const same=Array.from(parent.children).filter((c)=>c.localName===node.localName);if(same.length>1)part+=`:nth-of-type(${same.indexOf(node)+1})`}parts.unshift(part);node=parent}parts.unshift("html");return parts.join(" > ")});function buildSnapshotExpression(options={}){return`(function () {const globalThis = {};@@ -1531,5 +1522,5 @@ ${snapshot.tree}`}}var DEFAULT_TIMEOUT_MS=30000;var JSON_MIME=/^application\/jsoconst css = {};for (const ref of Object.keys(result.refs || {})) css[ref] = cssPath(api.elementRegistry.get(ref));return { tree: result.tree, refs: result.refs || {}, css, error: result.error };-})()`}async function bskSnapshot(session,{tabId,timeoutMs,...snapshotOptions}={}){const reply=await session.evaluate(buildSnapshotExpression(snapshotOptions),{tabId,timeoutMs,awaitPromise:false,returnByValue:true});if(!reply||reply.ok===false){const text=reply?.error?.text??"unknown error";throw new Error(`bskSnapshot failed inside the page: ${text}`)}const value=reply.value;if(!value||typeof value.tree!=="string")throw new Error("bskSnapshot: page returned no tree");if(value.error)throw new Error(`bskSnapshot: ${value.error}`);return{tree:value.tree,refs:value.refs,css:value.css}}import{existsSync as existsSync5,mkdirSync as mkdirSync2,readFileSync as readFileSync4,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{spawn as spawn4}from"node:child_process";import path12 from"node:path";import{existsSync as existsSync4}from"node:fs";import{homedir as homedir3}from"node:os";import path11 from"node:path";var BROWSERSKILL_EXTENSION_IDS=Object.freeze({chrome:"hhcmgoofomhgciiibhipgmgkgnoenaoi",edge:"emacgiaaaiojkkpkddmmdfhmokgmnikg"});var STORE_UPDATE_URLS=Object.freeze({chrome:"https://clients2.google.com/service/update2/crx",edge:"https://edge.microsoft.com/extensionwebstorebase/v1/crx"});var STORE_PAGE_URLS=Object.freeze({chrome:`https://chromewebstore.google.com/detail/${BROWSERSKILL_EXTENSION_IDS.chrome}`,edge:`https://microsoftedge.microsoft.com/addons/detail/browserskill/${BROWSERSKILL_EXTENSION_IDS.edge}`});var NON_CHROMIUM_DEFAULTS=Object.freeze([{id:"safari",label:"Safari",match:["com.apple.safari","safarihtml"]},{id:"firefox",label:"Firefox",match:["org.mozilla.firefox","firefox.desktop","firefoxurl","firefoxhtml"]},{id:"zen",label:"Zen",match:["app.zen-browser.zen","zen.desktop","zenhtml"]},{id:"orion",label:"Orion",match:["com.kagi.kagimacos"]}]);var MAC=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Library/Application Support/Google/Chrome",app:"Google Chrome",bundleId:"com.google.Chrome"},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Library/Application Support/Microsoft Edge",app:"Microsoft Edge",bundleId:"com.microsoft.edgemac"},{id:"brave",label:"Brave",store:"chrome",userData:"Library/Application Support/BraveSoftware/Brave-Browser",app:"Brave Browser",bundleId:"com.brave.Browser"},{id:"chromium",label:"Chromium",store:"chrome",userData:"Library/Application Support/Chromium",app:"Chromium",bundleId:"org.chromium.Chromium"},{id:"arc",label:"Arc",store:"chrome",userData:"Library/Application Support/Arc/User Data",app:"Arc",bundleId:"company.thebrowser.Browser"},{id:"dia",label:"Dia",store:"chrome",userData:"Library/Application Support/Dia/User Data",app:"Dia",bundleId:"company.thebrowser.dia"},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Library/Application Support/Vivaldi",app:"Vivaldi",bundleId:"com.vivaldi.Vivaldi"},{id:"opera",label:"Opera",store:"chrome",userData:"Library/Application Support/com.operasoftware.Opera",app:"Opera",bundleId:"com.operasoftware.Opera",externalExtensions:false},{id:"comet",label:"Comet",store:"chrome",userData:"Library/Application Support/Comet",app:"Comet",bundleId:"ai.perplexity.comet"},{id:"aside",label:"Aside",store:"chrome",userData:"Library/Application Support/Aside",app:"Aside",bundleId:"at.studio.AsideBrowser"},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Library/Application Support/Naver/Whale",app:"Naver Whale",bundleId:"com.naver.Whale"}];var LINUX=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:".config/google-chrome",binaries:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/opt/google/chrome/chrome"],externalDir:"/opt/google/chrome/extensions",userExternalDir:false,desktopIds:["google-chrome.desktop","google-chrome-stable.desktop","com.google.Chrome.desktop"],processNames:["chrome","google-chrome"]},{id:"chromium",label:"Chromium",store:"chrome",userData:".config/chromium",binaries:["/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],externalDir:"/usr/share/chromium/extensions",userExternalDir:true,desktopIds:["chromium.desktop","chromium-browser.desktop","chromium_chromium.desktop","org.chromium.Chromium.desktop"],processNames:["chromium","chromium-browse"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:".config/microsoft-edge",binaries:["/usr/bin/microsoft-edge","/opt/microsoft/msedge/msedge"],externalDir:"/usr/share/microsoft-edge/extensions",userExternalDir:false,desktopIds:["microsoft-edge.desktop","microsoft-edge-stable.desktop","com.microsoft.Edge.desktop"],processNames:["msedge"]},{id:"brave",label:"Brave",store:"chrome",userData:".config/BraveSoftware/Brave-Browser",binaries:["/usr/bin/brave-browser","/opt/brave.com/brave/brave"],externalDir:"/usr/share/brave/extensions",userExternalDir:false,desktopIds:["brave-browser.desktop","com.brave.Browser.desktop"],processNames:["brave"]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:".config/vivaldi",binaries:["/usr/bin/vivaldi","/opt/vivaldi/vivaldi"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["vivaldi-stable.desktop","vivaldi.desktop"],processNames:["vivaldi-bin"]},{id:"opera",label:"Opera",store:"chrome",userData:".config/opera",binaries:["/usr/bin/opera"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["opera.desktop"],processNames:["opera"]}];var WINDOWS=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Google/Chrome/User Data",registryKey:"HKCU\\Software\\Google\\Chrome\\Extensions",binaryRel:"Google/Chrome/Application/chrome.exe",progIds:["chromehtml"],processNames:["chrome.exe"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Microsoft/Edge/User Data",registryKey:"HKCU\\Software\\Microsoft\\Edge\\Extensions",binaryRel:"Microsoft/Edge/Application/msedge.exe",progIds:["msedgehtm"],processNames:["msedge.exe"]},{id:"brave",label:"Brave",store:"chrome",userData:"BraveSoftware/Brave-Browser/User Data",registryKey:"HKCU\\Software\\BraveSoftware\\Brave-Browser\\Extensions",binaryRel:"BraveSoftware/Brave-Browser/Application/brave.exe",progIds:["bravehtml"],processNames:["brave.exe"]},{id:"chromium",label:"Chromium",store:"chrome",userData:"Chromium/User Data",registryKey:"HKCU\\Software\\Chromium\\Extensions",binaryRel:"Chromium/Application/chrome.exe",progIds:["chromiumhtm"],processNames:[]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Vivaldi/User Data",registryKey:null,externalExtensions:false,binaryRel:"Vivaldi/Application/vivaldi.exe",progIds:["vivaldihtm"],processNames:["vivaldi.exe"]},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Naver/Naver Whale/User Data",registryKey:null,externalExtensions:false,binaryRel:"Naver/Naver Whale/Application/whale.exe",progIds:["whalehtml"],processNames:["whale.exe"]}];var BROWSER_IDS=Object.freeze([...new Set([...MAC,...LINUX,...WINDOWS].map((b)=>b.id))]);function macRow(b,home,exists){const apps=[path11.join("/Applications",`${b.app}.app`),path11.join(home,"Applications",`${b.app}.app`)];const appPath=apps.find((p)=>exists(p))??null;const userDataDir=path11.join(home,b.userData);return{id:b.id,label:b.label,store:b.store,userDataDir,binary:path11.join(appPath??apps[0],"Contents","MacOS",b.app),bundleId:b.bundleId,processNames:apps.map((a)=>path11.join(a,"Contents","MacOS",b.app)),defaultIds:[b.bundleId.toLowerCase()],externalExtensions:b.externalExtensions!==false,installed:appPath!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function linuxRow(b,home,exists){const userDataDir=path11.join(home,b.userData);const binary=b.binaries.find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,binary,externalDir:b.externalDir,userExternalDir:b.userExternalDir,processNames:b.processNames,defaultIds:b.desktopIds.map((d)=>d.toLowerCase()),externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function windowsRow(b,env,home,exists){const localAppData=env.LOCALAPPDATA??path11.join(home,"AppData","Local");const programFiles=[localAppData,env.PROGRAMFILES,env["PROGRAMFILES(X86)"],"C:\\Program Files","C:\\Program Files (x86)"].filter(Boolean);const userDataDir=path11.join(localAppData,b.userData);const binary=programFiles.map((root)=>path11.join(root,b.binaryRel)).find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,registryKey:b.registryKey,binary,processNames:b.processNames,defaultIds:b.progIds,externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function catalogBrowsers({platform=process.platform,home=homedir3(),env=process.env,exists=existsSync4}={}){if(platform==="darwin")return MAC.map((b)=>macRow(b,home,exists));if(platform==="linux")return LINUX.map((b)=>linuxRow(b,home,exists));if(platform==="win32")return WINDOWS.map((b)=>windowsRow(b,env,home,exists));return[]}function detectBrowsers(options={}){return catalogBrowsers(options).filter((b)=>b.installed)}var ENABLE_STEP=(browser)=>`Quit ${browser} completely and open it again; a dialog offers to enable "BrowserSkill" — click Enable.`;var BADGE_STEP=(browser)=>`In ${browser}, open the menu (the badge on the toolbar) and enable "BrowserSkill" when prompted; no restart is needed.`;var storeStep=(browser,label)=>`Open ${STORE_PAGE_URLS[browser.store]} in ${label} and click the "Add" button.`;function externalExtensionEntry({platform=process.platform,browser}){const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const updateUrl=STORE_UPDATE_URLS[browser.store];const label=browser.label??browser.id.charAt(0).toUpperCase()+browser.id.slice(1);if(browser.externalExtensions===false){return{kind:"store",needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:storeStep(browser,label)}}if(platform==="win32"){const key=`${browser.registryKey}\\${id}`;return{kind:"registry",key,needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],regAddArgs:["add",key,"/v","update_url","/t","REG_SZ","/d",updateUrl,"/f"],regDeleteArgs:["delete",key,"/f"],humanStep:BADGE_STEP(label)}}const content=JSON.stringify({external_update_url:updateUrl},null,2)+`-`;if(platform==="linux"&&!browser.userExternalDir){return{kind:"file",path:path12.join(browser.externalDir,`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:`Quit ${label} completely and open it again; the extension installs without a prompt.`}}return{kind:"file",path:path12.join(browser.userDataDir,"External Extensions",`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:platform==="linux"?`Quit ${label} completely and open it again; the extension installs without a prompt.`:ENABLE_STEP(label)}}function isBlocklisted(browser,id,{readFile=readFileSync4}={}){if(!browser.userDataDir)return false;for(const profile of["Default","Profile 1","Profile 2","Profile 3"]){const file=path12.join(browser.userDataDir,profile,"Preferences");let prefs;try{prefs=JSON.parse(readFile(file,"utf8"))}catch{continue}if(Array.isArray(prefs?.extensions?.external_uninstalls)&&prefs.extensions.external_uninstalls.includes(id))return true}return false}function runRegDefault(args){return new Promise((resolve)=>{const child=spawn4("reg",args,{stdio:["ignore","ignore","pipe"],windowsHide:true});let stderr="";child.stderr.on("data",(c)=>{stderr+=c});child.on("error",(error)=>resolve({code:-1,stderr:error.message}));child.on("exit",(code)=>resolve({code,stderr}))})}async function registerExternalExtension({platform=process.platform,browser,writeFile=writeFileSync2,readFile=readFileSync4,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const label=browser.label??browser.id;const storeStep=`Open ${entry.storeUrl} in ${label} and click the "Add" button.`;if(entry.kind==="store")return{...entry,registered:false,alreadyPresent:false,reason:"store_only"};if(isBlocklisted(browser,id,{readFile})){return{...entry,registered:false,alreadyPresent:false,reason:"blocklisted",humanStep:`The extension was removed from ${label} before, so external registration is ignored. ${storeStep}`}}if(entry.kind==="registry"){const result=await runReg(entry.regAddArgs);if(result.code!==0)return{...entry,registered:false,alreadyPresent:false,reason:"reg_failed",detail:result.stderr,humanStep:storeStep};return{...entry,registered:true,alreadyPresent:false}}let alreadyPresent=false;try{alreadyPresent=readFile(entry.path,"utf8")===entry.content}catch{}if(alreadyPresent)return{...entry,registered:true,alreadyPresent:true};try{mkdirSync2(path12.dirname(entry.path),{recursive:true});writeFile(entry.path,entry.content)}catch(error){if(error.code==="EACCES"||error.code==="EPERM"||error.code==="EROFS"){return{...entry,registered:false,alreadyPresent:false,reason:"not_writable",humanStep:`${entry.path} is not writable without administrator rights. ${storeStep}`}}throw error}return{...entry,registered:true,alreadyPresent:false}}async function unregisterExternalExtension({platform=process.platform,browser,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});if(entry.kind==="store")return{...entry,removed:false};if(entry.kind==="registry"){const result=await runReg(entry.regDeleteArgs);return{...entry,removed:result.code===0,detail:result.stderr}}const present=existsSync5(entry.path);if(present)rmSync2(entry.path,{force:true});return{...entry,removed:present}}import{execFile}from"node:child_process";import{statSync}from"node:fs";import{homedir as homedir4}from"node:os";import path13 from"node:path";var PROBE_TIMEOUT_MS2=3000;function runDefault(command,args){return new Promise((resolve)=>{execFile(command,args,{timeout:PROBE_TIMEOUT_MS2,windowsHide:true,maxBuffer:8*1024*1024},(error,stdout)=>{resolve(error?null:String(stdout))})})}function parseMacDefaultBrowser(plistJson){let handlers;try{handlers=JSON.parse(plistJson)?.LSHandlers}catch{return null}if(!Array.isArray(handlers))return null;const pick=(scheme)=>handlers.find((h)=>h?.LSHandlerURLScheme===scheme&&typeof h.LSHandlerRoleAll==="string");const handler=pick("https")??pick("http");return handler?handler.LSHandlerRoleAll.toLowerCase():"com.apple.safari"}function parseWindowsProgId(regOutput){const match=/ProgId\s+REG_SZ\s+(\S+)/i.exec(regOutput??"");return match?match[1].toLowerCase():null}function parseProcessNames(platform,output){const names=new Set;for(const raw of String(output??"").split(/\r?\n/)){const line=raw.trim();if(!line)continue;if(platform==="win32"){const image=/^"([^"]+)"/.exec(line)?.[1];if(image)names.add(image.toLowerCase())}else if(platform==="darwin"){if(/\.app\/Contents\/MacOS\/[^/]+$/.test(line))names.add(line)}else{names.add(path13.basename(line))}}return[...names]}async function probeDefault({platform,home,run}){if(platform==="darwin"){const plist=path13.join(home,"Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist");const json=await run("plutil",["-convert","json","-o","-",plist]);return json===null?null:parseMacDefaultBrowser(json)}if(platform==="linux"){const out=await run("xdg-settings",["get","default-web-browser"]);return out?.trim()?out.trim().toLowerCase():null}if(platform==="win32"){const key="HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice";return parseWindowsProgId(await run("reg",["query",key,"/v","ProgId"]))}return null}async function probeRunning({platform,run}){const out=platform==="win32"?await run("tasklist",["/fo","csv","/nh"]):await run("ps",platform==="darwin"?["-axo","comm="]:["-eo","comm="]);return out===null?null:parseProcessNames(platform,out)}function lastUsedAt(browser,stat){let latest=null;for(const rel of["Local State",path13.join("Default","History"),path13.join("Default","Preferences")]){try{const mtime=stat(path13.join(browser.userDataDir,rel)).mtimeMs;if(latest===null||mtime>latest)latest=mtime}catch{}}return latest}async function probeBrowserSignals({platform=process.platform,home=homedir4(),browsers=[],run=runDefault,stat=statSync}={}){const[defaultBrowser,running]=await Promise.all([probeDefault({platform,home,run}),probeRunning({platform,run})]);const lastUsed=Object.fromEntries(browsers.map((b)=>[b.id,lastUsedAt(b,stat)]));return{defaultBrowser,running,lastUsed}}var RECENT_USE_MS=7*24*60*60*1000;function matchesDefault(browser,defaultId){if(!defaultId)return false;return browser.defaultIds.some((id)=>defaultId===id||defaultId.startsWith(id))}function describeDefault(defaultId,catalog){if(defaultId===null||defaultId===undefined)return{raw:null,id:null,label:null,supported:null};const hit=catalog.find((b)=>matchesDefault(b,defaultId));if(hit)return{raw:defaultId,id:hit.id,label:hit.label,supported:true};const other=NON_CHROMIUM_DEFAULTS.find((b)=>b.match.some((m)=>defaultId===m||defaultId.startsWith(m)));return other?{raw:defaultId,id:other.id,label:other.label,supported:false}:{raw:defaultId,id:null,label:defaultId,supported:false}}function candidateRow(browser,{defaultBrowser,running,lastUsed},now){const isDefault=defaultBrowser.id===browser.id;const isRunning=Array.isArray(running)?browser.processNames.some((n)=>running.includes(n)||running.includes(n.toLowerCase())):null;const last=lastUsed?.[browser.id]??null;const recentlyUsed=last!==null&&now-last<=RECENT_USE_MS;const signals=[isDefault&&"default browser",isRunning&&"running now",recentlyUsed&&"used in the last 7 days"].filter(Boolean);return{id:browser.id,label:browser.label,installed:browser.installed,isDefault,running:isRunning,lastUsedAt:last===null?null:new Date(last).toISOString(),recentlyUsed,signals,browser}}function choose(candidates,primary,confidence,reason,defaultBrowser){return{primary:primary.browser,primaryId:primary.id,confidence,needsChoice:false,reason,defaultBrowser,candidates:candidates.map(({browser,...row})=>row)}}function ask(candidates,reason,defaultBrowser,suggested=null){return{primary:null,primaryId:null,confidence:null,needsChoice:true,reason,suggested,defaultBrowser,candidates:candidates.map(({browser,...row})=>row)}}function identifyBrowser({catalog,signals={},explicit=null,now=Date.now()}){const defaultBrowser=describeDefault(signals.defaultBrowser??null,catalog);const installed=catalog.filter((b)=>b.installed||b.id===explicit);const candidates=installed.map((b)=>candidateRow(b,{defaultBrowser,running:signals.running??null,lastUsed:signals.lastUsed},now));if(explicit){const hit=candidates.find((c)=>c.id===explicit);if(hit)return choose(candidates,hit,"explicit",`${hit.label} was chosen explicitly`,defaultBrowser);return ask(candidates,`"${explicit}" is not a Chromium-family browser this library knows; pick one of the candidates`,defaultBrowser)}if(candidates.length===0)return ask(candidates,"no Chromium-family browser is installed",defaultBrowser);const inUse=candidates.filter((c)=>c.running||c.recentlyUsed);const def=candidates.find((c)=>c.isDefault);if(def&&(def.running||def.recentlyUsed))return choose(candidates,def,"default-and-in-use",`${def.label} is the default browser and ${def.signals.slice(1).join(", ")}`,defaultBrowser);if(def&&inUse.length===0)return choose(candidates,def,"default",`${def.label} is the default browser`,defaultBrowser);if(def)return ask(candidates,`${def.label} is the default browser, but ${inUse.map((c)=>c.label).join(" and ")} ${inUse.length===1?"is":"are"} the one in use`,defaultBrowser);if(defaultBrowser.supported===false){const suggested=inUse.length===1?inUse[0].id:null;return ask(candidates,`the default browser is ${defaultBrowser.label}, which BrowserSkill cannot drive; the user has to name the Chromium browser to use`,defaultBrowser,suggested)}const runningNow=inUse.filter((c)=>c.running);if(inUse.length===1)return choose(candidates,inUse[0],"only-in-use",`${inUse[0].label} is the only browser ${inUse[0].signals.join(", ")}`,defaultBrowser);if(runningNow.length===1)return choose(candidates,runningNow[0],"only-running",`${runningNow[0].label} is the only browser running now`,defaultBrowser);if(inUse.length===0&&candidates.length===1)return choose(candidates,candidates[0],"only-installed",`${candidates[0].label} is the only Chromium-family browser installed`,defaultBrowser);return ask(candidates,inUse.length>1?`several browsers are in use (${inUse.map((c)=>c.label).join(", ")})`:"no browser shows recent use",defaultBrowser)}import{existsSync as existsSync6,readFileSync as readFileSync5,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{homedir as homedir5}from"node:os";import path14 from"node:path";import{spawn as spawn5}from"node:child_process";var INSTALL_SH="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.sh";var INSTALL_PS1="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.ps1";var RC_FILES=[".zshrc",".bashrc",".profile"];function cliInstallCommand({platform=process.platform,installDir,version}={}){const env={BSK_INSTALL_DIR:installDir};if(version)env.BSK_VERSION=version;if(platform==="win32"){return{command:"powershell",args:["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${INSTALL_PS1} | iex`],env}}return{command:"sh",args:["-c",`curl -fsSL ${INSTALL_SH} | sh`],env}}function runDefault2(command,args,env){return new Promise((resolve)=>{const child=spawn5(command,args,{env:{...process.env,...env},stdio:["ignore","pipe","pipe"],windowsHide:true});let stdout="",stderr="";child.stdout.on("data",(c)=>{stdout=(stdout+c).slice(-8192)});child.stderr.on("data",(c)=>{stderr=(stderr+c).slice(-8192)});child.on("error",(error)=>resolve({code:-1,stdout,stderr:error.message}));child.on("exit",(code)=>resolve({code,stdout,stderr}))})}function snapshotRcFiles(home){const snapshot=new Map;for(const name of RC_FILES){const file=path14.join(home,name);snapshot.set(file,existsSync6(file)?readFileSync5(file):null)}return snapshot}function restoreRcFiles(snapshot){const restored=[];for(const[file,before]of snapshot){const after=existsSync6(file)?readFileSync5(file):null;if(before===null&&after===null)continue;if(before!==null&&after!==null&&before.equals(after))continue;if(before===null)rmSync3(file,{force:true});else writeFileSync3(file,before);restored.push(file)}return restored}async function installBskCli({platform=process.platform,home=homedir5(),installDir=path14.join(home,".local","bin"),version,run=runDefault2}={}){const spec=cliInstallCommand({platform,installDir,version});const rcBefore=platform==="win32"?new Map:snapshotRcFiles(home);const result=await run(spec.command,spec.args,spec.env);const restoredRcFiles=restoreRcFiles(rcBefore);const bskBin=path14.join(installDir,platform==="win32"?"bsk.exe":"bsk");const installed=result.code===0&&existsSync6(bskBin);return{installed,bskBin:installed?bskBin:null,code:result.code,stdout:result.stdout,stderr:result.stderr,restoredRcFiles}}function cliVersionDefault(bskBin){return new Promise((resolve)=>{const child=spawn5(bskBin,["--version"],{stdio:["ignore","pipe","ignore"],windowsHide:true});let out="";child.stdout.on("data",(c)=>{out+=c});child.on("error",()=>resolve(null));child.on("exit",(code)=>resolve(code===0?out.trim():null))})}import{homedir as homedir6}from"node:os";import{existsSync as existsSync7,readFileSync as readFileSync6}from"node:fs";var DEFAULT_WAIT_TOTAL_MS=180000;function resolveBskBin(bskBin,env){if(bskBin===null)return null;return bskBin??findBskBinary(env)}async function cliReport({bskBin,env,cliVersion}){const bin=resolveBskBin(bskBin,env);if(!bin)return{installed:false,bskBin:null,version:null};const raw=await cliVersion(bin);return raw?{installed:true,bskBin:bin,version:raw.replace(/^bsk\s+/,"")}:{installed:false,bskBin:bin,version:null}}async function daemonReport(client,waitForBrowserMs){try{const status=await client.call("system.status",waitForBrowserMs>0?{wait_for_browser_ms:waitForBrowserMs}:{},{idPrefix:"status"});return{running:true,version:status.daemon_version,protocolVersion:status.protocol_version,browsers:status.browsers??[],sessions:status.sessions??[]}}catch(error){return{running:false,error:error.message,code:error.code,browsers:[],sessions:[]}}}var NO_BROWSER_STEP=`No Chromium-family browser was found. Install one (Chrome, Edge, Brave, Arc, ...), then add the extension from ${STORE_PAGE_URLS.chrome}.`;function withRegistration(platform,browser){const entry=externalExtensionEntry({platform,browser});const extensionRegistered=entry.kind==="file"&&existsSync7(entry.path)&&readFileSync6(entry.path,"utf8")===entry.content;return{...browser,registration:entry,extensionRegistered}}async function identify({platform,home,env,exists,browser,signals,probeSignals,now}){const catalog=catalogBrowsers({platform,home,env,exists}).map((b)=>withRegistration(platform,b));const observed=signals??await probeSignals({platform,home,browsers:catalog.filter((b)=>b.hasProfile)});const explicit=browser??env.OMOWRIGHT_BROWSER??null;const{primary,...identification}=identifyBrowser({catalog,signals:observed,explicit:explicit||null,now});const browsers=catalog.filter((b)=>b.installed);const registeredElsewhere=browsers.filter((b)=>b.extensionRegistered&&b.id!==identification.primaryId).map((b)=>b.id);return{browsers,identification:{...identification,registeredElsewhere},primary}}function choiceStep(identification){const listed=identification.candidates.map((c)=>`${c.label} [${c.id}]${c.signals.length?` — ${c.signals.join(", ")}`:""}`).join("; ");const hint=identification.suggested?` Likely ${identification.suggested}, but confirm first.`:"";return`Ask the user which browser they actually use (${identification.reason}). Candidates: ${listed}.${hint} Then re-run with browser: "<id>"; register nothing until they answer.`}function nextStepFor({cli,daemon,browsers,browsersConnected,identification,primary}){if(browsersConnected.length>0)return null;if(!cli.installed)return"Install the bsk CLI (bskOnboard() runs the official installer).";if(!daemon.running)return"Start the BrowserSkill daemon: run `bsk status` once, or `bsk daemon start` in the environment that owns it.";if(browsers.length===0&&!primary)return NO_BROWSER_STEP;if(identification.needsChoice)return choiceStep(identification);if(!primary.extensionRegistered&&primary.registration.kind!=="store")return`Register the BrowserSkill extension for ${primary.label} (bskOnboard() does this), then let the user enable it.`;return primary.registration.humanStep}async function bskDoctor({platform=process.platform,home=homedir6(),env=process.env,client,bskBin,cliVersion=cliVersionDefault,waitForBrowserMs=0,exists=existsSync7,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){const cli=await cliReport({bskBin,env,cliVersion});const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:false});const daemon=await daemonReport(ipc,waitForBrowserMs);const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,signals,probeSignals,now});const browsersConnected=daemon.browsers;const report={cli,daemon,browsers,primary:primary??null,identification,browsersConnected,ready:browsersConnected.length>0};report.nextStep=nextStepFor(report);return report}async function bskOnboard({platform=process.platform,home=homedir6(),env=process.env,client,bskBin,installDir,installCli=installBskCli,cliVersion=cliVersionDefault,onHumanStep=()=>{},waitForBrowserMs=15000,waitTotalMs=DEFAULT_WAIT_TOTAL_MS,exists=existsSync7,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){let cli=await cliReport({bskBin,env,cliVersion});let install=null;if(!cli.installed){install=await installCli({platform,home,installDir});cli=install.installed?await cliReport({bskBin:install.bskBin,env,cliVersion}):cli}const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:true});let daemon=await daemonReport(ipc,0);const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,signals,probeSignals,now});const registrations=[];let humanStep=null;let needsChoice=false;if(daemon.browsers.length===0){if(browsers.length===0&&!primary){humanStep=NO_BROWSER_STEP}else if(identification.needsChoice){needsChoice=true;humanStep=choiceStep(identification)}else{const registration=await registerExternalExtension({platform,browser:primary});registrations.push({browser:primary.id,...registration});humanStep=registration.humanStep;onHumanStep({browser:primary.id,step:registration.humanStep,registered:registration.registered,needsRestart:registration.needsRestart})}}const deadline=Date.now()+waitTotalMs;let browsersConnected=daemon.browsers;while(!needsChoice&&browsersConnected.length===0&&daemon.running&&Date.now()<deadline){browsersConnected=await listBrowsers(ipc,{waitForBrowserMs});if(waitForBrowserMs===0)break}daemon={...daemon,browsers:browsersConnected};const ready=browsersConnected.length>0;return{cli,install,daemon,browsers,primary:primary??null,identification,needsChoice,registrations,humanStep:ready?null:humanStep,browsersConnected,ready}}export{AgentTabManager,BROWSERSKILL_EXTENSION_IDS,BROWSER_EVENT_NAMES,BridgeProtocolError,BridgeUnavailableError,BrowserCdpCommandError,BrowserConnection,BskIpcClient,BskRpcError,BskSession,CdpClient,CommandSchema,DEFAULT_AGENT_VIEWPORT,DEVICE_PRESETS,ElementHandle,EventSchema,ExtensionHelloSchema,FrameLocator,FrameManager,HostHelloSchema,Locator,ModifierState,OmOKeyboard,OmOMouse,OmOPage,PipeCdpClient,ResponseSchema,STORE_PAGE_URLS,SessionManager,TabRepository,UnsupportedOperationError,bskDoctor,bskOnboard,bskSnapshot,buildCloakBrowserArgs,buildSnapshotExpression,catalogBrowsers,collectWhileScrolling,compactSnapshot,connect,connectBrowserSkill,connectCloakProfile,connectPipe,createAgentTabs,createBridgeClient,createCaptcha,createChromeApi2 as createChromeApi,createCua,createEvents,createNativeMessagingHost,createNetworkSnoop,createRoutes,createTrace,decodeFrames,describeLayers,detectBrowsers,emulate,encodeFrame,externalExtensionEntry,findCloakBrowserPath,identifyBrowser,injectCookies,installBskCli,installNativeMessagingHost,layersHeader,listBrowsers,macOSVisionOcr,normalizeDialogPolicy,pageBundle,probeBrowserSignals,readDaemonInfo,reconcileFrames,registerExternalExtension,repinViewport,requestHuman,resolveBskHome,resolveCloakProfile,resolveDialogAction,sanitizeCookies,snapshotTokens,snapshotWithFrames,snapshotWithLayers,takeSnapshot,toHar,toolSchemas,unregisterExternalExtension};+})()`}async function bskSnapshot(session,{tabId,timeoutMs,...snapshotOptions}={}){const reply=await session.evaluate(buildSnapshotExpression(snapshotOptions),{tabId,timeoutMs,awaitPromise:false,returnByValue:true});if(!reply||reply.ok===false){const text=reply?.error?.text??"unknown error";throw new Error(`bskSnapshot failed inside the page: ${text}`)}const value=reply.value;if(!value||typeof value.tree!=="string")throw new Error("bskSnapshot: page returned no tree");if(value.error)throw new Error(`bskSnapshot: ${value.error}`);return{tree:value.tree,refs:value.refs,css:value.css}}import{existsSync as existsSync5,mkdirSync as mkdirSync2,readFileSync as readFileSync4,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{spawn as spawn5}from"node:child_process";import path15 from"node:path";import{existsSync as existsSync4}from"node:fs";import{homedir as homedir3}from"node:os";import path14 from"node:path";var BROWSERSKILL_EXTENSION_IDS=Object.freeze({chrome:"hhcmgoofomhgciiibhipgmgkgnoenaoi",edge:"emacgiaaaiojkkpkddmmdfhmokgmnikg"});var STORE_UPDATE_URLS=Object.freeze({chrome:"https://clients2.google.com/service/update2/crx",edge:"https://edge.microsoft.com/extensionwebstorebase/v1/crx"});var STORE_PAGE_URLS=Object.freeze({chrome:`https://chromewebstore.google.com/detail/${BROWSERSKILL_EXTENSION_IDS.chrome}`,edge:`https://microsoftedge.microsoft.com/addons/detail/browserskill/${BROWSERSKILL_EXTENSION_IDS.edge}`});var NON_CHROMIUM_DEFAULTS=Object.freeze([{id:"safari",label:"Safari",match:["com.apple.safari","safarihtml"]},{id:"firefox",label:"Firefox",match:["org.mozilla.firefox","firefox.desktop","firefoxurl","firefoxhtml"]},{id:"zen",label:"Zen",match:["app.zen-browser.zen","zen.desktop","zenhtml"]},{id:"orion",label:"Orion",match:["com.kagi.kagimacos"]}]);var MAC=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Library/Application Support/Google/Chrome",app:"Google Chrome",bundleId:"com.google.Chrome"},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Library/Application Support/Microsoft Edge",app:"Microsoft Edge",bundleId:"com.microsoft.edgemac"},{id:"brave",label:"Brave",store:"chrome",userData:"Library/Application Support/BraveSoftware/Brave-Browser",app:"Brave Browser",bundleId:"com.brave.Browser"},{id:"chromium",label:"Chromium",store:"chrome",userData:"Library/Application Support/Chromium",app:"Chromium",bundleId:"org.chromium.Chromium"},{id:"arc",label:"Arc",store:"chrome",userData:"Library/Application Support/Arc/User Data",app:"Arc",bundleId:"company.thebrowser.Browser"},{id:"dia",label:"Dia",store:"chrome",userData:"Library/Application Support/Dia/User Data",app:"Dia",bundleId:"company.thebrowser.dia"},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Library/Application Support/Vivaldi",app:"Vivaldi",bundleId:"com.vivaldi.Vivaldi"},{id:"opera",label:"Opera",store:"chrome",userData:"Library/Application Support/com.operasoftware.Opera",app:"Opera",bundleId:"com.operasoftware.Opera",externalExtensions:false},{id:"comet",label:"Comet",store:"chrome",userData:"Library/Application Support/Comet",app:"Comet",bundleId:"ai.perplexity.comet"},{id:"aside",label:"Aside",store:"chrome",userData:"Library/Application Support/Aside",app:"Aside",bundleId:"at.studio.AsideBrowser"},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Library/Application Support/Naver/Whale",app:"Naver Whale",bundleId:"com.naver.Whale"}];var LINUX=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:".config/google-chrome",binaries:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/opt/google/chrome/chrome"],externalDir:"/opt/google/chrome/extensions",userExternalDir:false,desktopIds:["google-chrome.desktop","google-chrome-stable.desktop","com.google.Chrome.desktop"],processNames:["chrome","google-chrome"]},{id:"chromium",label:"Chromium",store:"chrome",userData:".config/chromium",binaries:["/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],externalDir:"/usr/share/chromium/extensions",userExternalDir:true,desktopIds:["chromium.desktop","chromium-browser.desktop","chromium_chromium.desktop","org.chromium.Chromium.desktop"],processNames:["chromium","chromium-browse"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:".config/microsoft-edge",binaries:["/usr/bin/microsoft-edge","/opt/microsoft/msedge/msedge"],externalDir:"/usr/share/microsoft-edge/extensions",userExternalDir:false,desktopIds:["microsoft-edge.desktop","microsoft-edge-stable.desktop","com.microsoft.Edge.desktop"],processNames:["msedge"]},{id:"brave",label:"Brave",store:"chrome",userData:".config/BraveSoftware/Brave-Browser",binaries:["/usr/bin/brave-browser","/opt/brave.com/brave/brave"],externalDir:"/usr/share/brave/extensions",userExternalDir:false,desktopIds:["brave-browser.desktop","com.brave.Browser.desktop"],processNames:["brave"]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:".config/vivaldi",binaries:["/usr/bin/vivaldi","/opt/vivaldi/vivaldi"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["vivaldi-stable.desktop","vivaldi.desktop"],processNames:["vivaldi-bin"]},{id:"opera",label:"Opera",store:"chrome",userData:".config/opera",binaries:["/usr/bin/opera"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["opera.desktop"],processNames:["opera"]}];var WINDOWS=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Google/Chrome/User Data",registryKey:"HKCU\\Software\\Google\\Chrome\\Extensions",binaryRel:"Google/Chrome/Application/chrome.exe",progIds:["chromehtml"],processNames:["chrome.exe"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Microsoft/Edge/User Data",registryKey:"HKCU\\Software\\Microsoft\\Edge\\Extensions",binaryRel:"Microsoft/Edge/Application/msedge.exe",progIds:["msedgehtm"],processNames:["msedge.exe"]},{id:"brave",label:"Brave",store:"chrome",userData:"BraveSoftware/Brave-Browser/User Data",registryKey:"HKCU\\Software\\BraveSoftware\\Brave-Browser\\Extensions",binaryRel:"BraveSoftware/Brave-Browser/Application/brave.exe",progIds:["bravehtml"],processNames:["brave.exe"]},{id:"chromium",label:"Chromium",store:"chrome",userData:"Chromium/User Data",registryKey:"HKCU\\Software\\Chromium\\Extensions",binaryRel:"Chromium/Application/chrome.exe",progIds:["chromiumhtm"],processNames:[]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Vivaldi/User Data",registryKey:null,externalExtensions:false,binaryRel:"Vivaldi/Application/vivaldi.exe",progIds:["vivaldihtm"],processNames:["vivaldi.exe"]},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Naver/Naver Whale/User Data",registryKey:null,externalExtensions:false,binaryRel:"Naver/Naver Whale/Application/whale.exe",progIds:["whalehtml"],processNames:["whale.exe"]}];var BROWSER_IDS=Object.freeze([...new Set([...MAC,...LINUX,...WINDOWS].map((b)=>b.id))]);function macRow(b,home,exists){const apps=[path14.join("/Applications",`${b.app}.app`),path14.join(home,"Applications",`${b.app}.app`)];const appPath=apps.find((p)=>exists(p))??null;const userDataDir=path14.join(home,b.userData);return{id:b.id,label:b.label,store:b.store,userDataDir,binary:path14.join(appPath??apps[0],"Contents","MacOS",b.app),bundleId:b.bundleId,processNames:apps.map((a)=>path14.join(a,"Contents","MacOS",b.app)),defaultIds:[b.bundleId.toLowerCase()],externalExtensions:b.externalExtensions!==false,installed:appPath!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function linuxRow(b,home,exists){const userDataDir=path14.join(home,b.userData);const binary=b.binaries.find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,binary,externalDir:b.externalDir,userExternalDir:b.userExternalDir,processNames:b.processNames,defaultIds:b.desktopIds.map((d)=>d.toLowerCase()),externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function windowsRow(b,env,home,exists){const localAppData=env.LOCALAPPDATA??path14.join(home,"AppData","Local");const programFiles=[localAppData,env.PROGRAMFILES,env["PROGRAMFILES(X86)"],"C:\\Program Files","C:\\Program Files (x86)"].filter(Boolean);const userDataDir=path14.join(localAppData,b.userData);const binary=programFiles.map((root)=>path14.join(root,b.binaryRel)).find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,registryKey:b.registryKey,binary,processNames:b.processNames,defaultIds:b.progIds,externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function catalogBrowsers({platform=process.platform,home=homedir3(),env=process.env,exists=existsSync4}={}){if(platform==="darwin")return MAC.map((b)=>macRow(b,home,exists));if(platform==="linux")return LINUX.map((b)=>linuxRow(b,home,exists));if(platform==="win32")return WINDOWS.map((b)=>windowsRow(b,env,home,exists));return[]}function detectBrowsers(options={}){return catalogBrowsers(options).filter((b)=>b.installed)}var ENABLE_STEP=(browser)=>`Quit ${browser} completely and open it again; a dialog offers to enable "BrowserSkill" — click Enable.`;var BADGE_STEP=(browser)=>`In ${browser}, open the menu (the badge on the toolbar) and enable "BrowserSkill" when prompted; no restart is needed.`;var storeStep=(browser,label)=>`Open ${STORE_PAGE_URLS[browser.store]} in ${label} and click the "Add" button.`;function externalExtensionEntry({platform=process.platform,browser}){const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const updateUrl=STORE_UPDATE_URLS[browser.store];const label=browser.label??browser.id.charAt(0).toUpperCase()+browser.id.slice(1);if(browser.externalExtensions===false){return{kind:"store",needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:storeStep(browser,label)}}if(platform==="win32"){const key=`${browser.registryKey}\\${id}`;return{kind:"registry",key,needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],regAddArgs:["add",key,"/v","update_url","/t","REG_SZ","/d",updateUrl,"/f"],regDeleteArgs:["delete",key,"/f"],humanStep:BADGE_STEP(label)}}const content=JSON.stringify({external_update_url:updateUrl},null,2)+`+`;if(platform==="linux"&&!browser.userExternalDir){return{kind:"file",path:path15.join(browser.externalDir,`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:`Quit ${label} completely and open it again; the extension installs without a prompt.`}}return{kind:"file",path:path15.join(browser.userDataDir,"External Extensions",`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:platform==="linux"?`Quit ${label} completely and open it again; the extension installs without a prompt.`:ENABLE_STEP(label)}}function isBlocklisted(browser,id,{readFile=readFileSync4}={}){if(!browser.userDataDir)return false;for(const profile of["Default","Profile 1","Profile 2","Profile 3"]){const file=path15.join(browser.userDataDir,profile,"Preferences");let prefs;try{prefs=JSON.parse(readFile(file,"utf8"))}catch{continue}if(Array.isArray(prefs?.extensions?.external_uninstalls)&&prefs.extensions.external_uninstalls.includes(id))return true}return false}function runRegDefault(args){return new Promise((resolve)=>{const child=spawn5("reg",args,{stdio:["ignore","ignore","pipe"],windowsHide:true});let stderr="";child.stderr.on("data",(c)=>{stderr+=c});child.on("error",(error)=>resolve({code:-1,stderr:error.message}));child.on("exit",(code)=>resolve({code,stderr}))})}async function registerExternalExtension({platform=process.platform,browser,writeFile=writeFileSync2,readFile=readFileSync4,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const label=browser.label??browser.id;const storeStep=`Open ${entry.storeUrl} in ${label} and click the "Add" button.`;if(entry.kind==="store")return{...entry,registered:false,alreadyPresent:false,reason:"store_only"};if(isBlocklisted(browser,id,{readFile})){return{...entry,registered:false,alreadyPresent:false,reason:"blocklisted",humanStep:`The extension was removed from ${label} before, so external registration is ignored. ${storeStep}`}}if(entry.kind==="registry"){const result=await runReg(entry.regAddArgs);if(result.code!==0)return{...entry,registered:false,alreadyPresent:false,reason:"reg_failed",detail:result.stderr,humanStep:storeStep};return{...entry,registered:true,alreadyPresent:false}}let alreadyPresent=false;try{alreadyPresent=readFile(entry.path,"utf8")===entry.content}catch{}if(alreadyPresent)return{...entry,registered:true,alreadyPresent:true};try{mkdirSync2(path15.dirname(entry.path),{recursive:true});writeFile(entry.path,entry.content)}catch(error){if(error.code==="EACCES"||error.code==="EPERM"||error.code==="EROFS"){return{...entry,registered:false,alreadyPresent:false,reason:"not_writable",humanStep:`${entry.path} is not writable without administrator rights. ${storeStep}`}}throw error}return{...entry,registered:true,alreadyPresent:false}}async function unregisterExternalExtension({platform=process.platform,browser,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});if(entry.kind==="store")return{...entry,removed:false};if(entry.kind==="registry"){const result=await runReg(entry.regDeleteArgs);return{...entry,removed:result.code===0,detail:result.stderr}}const present=existsSync5(entry.path);if(present)rmSync2(entry.path,{force:true});return{...entry,removed:present}}import{execFile as execFile2}from"node:child_process";import{statSync}from"node:fs";import{homedir as homedir4}from"node:os";import path16 from"node:path";var PROBE_TIMEOUT_MS2=3000;function runDefault(command,args){return new Promise((resolve)=>{execFile2(command,args,{timeout:PROBE_TIMEOUT_MS2,windowsHide:true,maxBuffer:8*1024*1024},(error,stdout)=>{resolve(error?null:String(stdout))})})}function parseMacDefaultBrowser(plistJson){let handlers;try{handlers=JSON.parse(plistJson)?.LSHandlers}catch{return null}if(!Array.isArray(handlers))return null;const pick=(scheme)=>handlers.find((h)=>h?.LSHandlerURLScheme===scheme&&typeof h.LSHandlerRoleAll==="string");const handler=pick("https")??pick("http");return handler?handler.LSHandlerRoleAll.toLowerCase():"com.apple.safari"}function parseWindowsProgId(regOutput){const match=/ProgId\s+REG_SZ\s+(\S+)/i.exec(regOutput??"");return match?match[1].toLowerCase():null}function parseProcessNames(platform,output){const names=new Set;for(const raw of String(output??"").split(/\r?\n/)){const line=raw.trim();if(!line)continue;if(platform==="win32"){const image=/^"([^"]+)"/.exec(line)?.[1];if(image)names.add(image.toLowerCase())}else if(platform==="darwin"){if(/\.app\/Contents\/MacOS\/[^/]+$/.test(line))names.add(line)}else{names.add(path16.basename(line))}}return[...names]}async function probeDefault({platform,home,run}){if(platform==="darwin"){const plist=path16.join(home,"Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist");const json=await run("plutil",["-convert","json","-o","-",plist]);return json===null?null:parseMacDefaultBrowser(json)}if(platform==="linux"){const out=await run("xdg-settings",["get","default-web-browser"]);return out?.trim()?out.trim().toLowerCase():null}if(platform==="win32"){const key="HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice";return parseWindowsProgId(await run("reg",["query",key,"/v","ProgId"]))}return null}async function probeRunning({platform,run}){const out=platform==="win32"?await run("tasklist",["/fo","csv","/nh"]):await run("ps",platform==="darwin"?["-axo","comm="]:["-eo","comm="]);return out===null?null:parseProcessNames(platform,out)}function lastUsedAt(browser,stat){let latest=null;for(const rel of["Local State",path16.join("Default","History"),path16.join("Default","Preferences")]){try{const mtime=stat(path16.join(browser.userDataDir,rel)).mtimeMs;if(latest===null||mtime>latest)latest=mtime}catch{}}return latest}async function probeBrowserSignals({platform=process.platform,home=homedir4(),browsers=[],run=runDefault,stat=statSync}={}){const[defaultBrowser,running]=await Promise.all([probeDefault({platform,home,run}),probeRunning({platform,run})]);const lastUsed=Object.fromEntries(browsers.map((b)=>[b.id,lastUsedAt(b,stat)]));return{defaultBrowser,running,lastUsed}}var RECENT_USE_MS=7*24*60*60*1000;function matchesDefault(browser,defaultId){if(!defaultId)return false;return browser.defaultIds.some((id)=>defaultId===id||defaultId.startsWith(id))}function describeDefault(defaultId,catalog){if(defaultId===null||defaultId===undefined)return{raw:null,id:null,label:null,supported:null};const hit=catalog.find((b)=>matchesDefault(b,defaultId));if(hit)return{raw:defaultId,id:hit.id,label:hit.label,supported:true};const other=NON_CHROMIUM_DEFAULTS.find((b)=>b.match.some((m)=>defaultId===m||defaultId.startsWith(m)));return other?{raw:defaultId,id:other.id,label:other.label,supported:false}:{raw:defaultId,id:null,label:defaultId,supported:false}}function candidateRow(browser,{defaultBrowser,running,lastUsed},now){const isDefault=defaultBrowser.id===browser.id;const isRunning=Array.isArray(running)?browser.processNames.some((n)=>running.includes(n)||running.includes(n.toLowerCase())):null;const last=lastUsed?.[browser.id]??null;const recentlyUsed=last!==null&&now-last<=RECENT_USE_MS;const signals=[isDefault&&"default browser",isRunning&&"running now",recentlyUsed&&"used in the last 7 days"].filter(Boolean);return{id:browser.id,label:browser.label,installed:browser.installed,isDefault,running:isRunning,lastUsedAt:last===null?null:new Date(last).toISOString(),recentlyUsed,signals,browser}}function choose(candidates,primary,confidence,reason,defaultBrowser){return{primary:primary.browser,primaryId:primary.id,confidence,needsChoice:false,reason,defaultBrowser,candidates:candidates.map(({browser,...row})=>row)}}function ask(candidates,reason,defaultBrowser,suggested=null){return{primary:null,primaryId:null,confidence:null,needsChoice:true,reason,suggested,defaultBrowser,candidates:candidates.map(({browser,...row})=>row)}}function identifyBrowser({catalog,signals={},explicit=null,now=Date.now()}){const defaultBrowser=describeDefault(signals.defaultBrowser??null,catalog);const installed=catalog.filter((b)=>b.installed||b.id===explicit);const candidates=installed.map((b)=>candidateRow(b,{defaultBrowser,running:signals.running??null,lastUsed:signals.lastUsed},now));if(explicit){const hit=candidates.find((c)=>c.id===explicit);if(hit)return choose(candidates,hit,"explicit",`${hit.label} was chosen explicitly`,defaultBrowser);return ask(candidates,`"${explicit}" is not a Chromium-family browser this library knows; pick one of the candidates`,defaultBrowser)}if(candidates.length===0)return ask(candidates,"no Chromium-family browser is installed",defaultBrowser);const inUse=candidates.filter((c)=>c.running||c.recentlyUsed);const def=candidates.find((c)=>c.isDefault);if(def&&(def.running||def.recentlyUsed))return choose(candidates,def,"default-and-in-use",`${def.label} is the default browser and ${def.signals.slice(1).join(", ")}`,defaultBrowser);if(def&&inUse.length===0)return choose(candidates,def,"default",`${def.label} is the default browser`,defaultBrowser);if(def)return ask(candidates,`${def.label} is the default browser, but ${inUse.map((c)=>c.label).join(" and ")} ${inUse.length===1?"is":"are"} the one in use`,defaultBrowser);if(defaultBrowser.supported===false){const suggested=inUse.length===1?inUse[0].id:null;return ask(candidates,`the default browser is ${defaultBrowser.label}, which BrowserSkill cannot drive; the user has to name the Chromium browser to use`,defaultBrowser,suggested)}const runningNow=inUse.filter((c)=>c.running);if(inUse.length===1)return choose(candidates,inUse[0],"only-in-use",`${inUse[0].label} is the only browser ${inUse[0].signals.join(", ")}`,defaultBrowser);if(runningNow.length===1)return choose(candidates,runningNow[0],"only-running",`${runningNow[0].label} is the only browser running now`,defaultBrowser);if(inUse.length===0&&candidates.length===1)return choose(candidates,candidates[0],"only-installed",`${candidates[0].label} is the only Chromium-family browser installed`,defaultBrowser);return ask(candidates,inUse.length>1?`several browsers are in use (${inUse.map((c)=>c.label).join(", ")})`:"no browser shows recent use",defaultBrowser)}import{existsSync as existsSync6,readFileSync as readFileSync5,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{homedir as homedir5}from"node:os";import path17 from"node:path";import{spawn as spawn6}from"node:child_process";var INSTALL_SH="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.sh";var INSTALL_PS1="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.ps1";var RC_FILES=[".zshrc",".bashrc",".profile"];function cliInstallCommand({platform=process.platform,installDir,version}={}){const env={BSK_INSTALL_DIR:installDir};if(version)env.BSK_VERSION=version;if(platform==="win32"){return{command:"powershell",args:["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${INSTALL_PS1} | iex`],env}}return{command:"sh",args:["-c",`curl -fsSL ${INSTALL_SH} | sh`],env}}function runDefault2(command,args,env){return new Promise((resolve)=>{const child=spawn6(command,args,{env:{...process.env,...env},stdio:["ignore","pipe","pipe"],windowsHide:true});let stdout="",stderr="";child.stdout.on("data",(c)=>{stdout=(stdout+c).slice(-8192)});child.stderr.on("data",(c)=>{stderr=(stderr+c).slice(-8192)});child.on("error",(error)=>resolve({code:-1,stdout,stderr:error.message}));child.on("exit",(code)=>resolve({code,stdout,stderr}))})}function snapshotRcFiles(home){const snapshot=new Map;for(const name of RC_FILES){const file=path17.join(home,name);snapshot.set(file,existsSync6(file)?readFileSync5(file):null)}return snapshot}function restoreRcFiles(snapshot){const restored=[];for(const[file,before]of snapshot){const after=existsSync6(file)?readFileSync5(file):null;if(before===null&&after===null)continue;if(before!==null&&after!==null&&before.equals(after))continue;if(before===null)rmSync3(file,{force:true});else writeFileSync3(file,before);restored.push(file)}return restored}async function installBskCli({platform=process.platform,home=homedir5(),installDir=path17.join(home,".local","bin"),version,run=runDefault2}={}){const spec=cliInstallCommand({platform,installDir,version});const rcBefore=platform==="win32"?new Map:snapshotRcFiles(home);const result=await run(spec.command,spec.args,spec.env);const restoredRcFiles=restoreRcFiles(rcBefore);const bskBin=path17.join(installDir,platform==="win32"?"bsk.exe":"bsk");const installed=result.code===0&&existsSync6(bskBin);return{installed,bskBin:installed?bskBin:null,code:result.code,stdout:result.stdout,stderr:result.stderr,restoredRcFiles}}function cliVersionDefault(bskBin){return new Promise((resolve)=>{const child=spawn6(bskBin,["--version"],{stdio:["ignore","pipe","ignore"],windowsHide:true});let out="";child.stdout.on("data",(c)=>{out+=c});child.on("error",()=>resolve(null));child.on("exit",(code)=>resolve(code===0?out.trim():null))})}import{homedir as homedir6}from"node:os";import{existsSync as existsSync7,readFileSync as readFileSync6}from"node:fs";var DEFAULT_WAIT_TOTAL_MS=180000;function resolveBskBin(bskBin,env){if(bskBin===null)return null;return bskBin??findBskBinary(env)}async function cliReport({bskBin,env,cliVersion}){const bin=resolveBskBin(bskBin,env);if(!bin)return{installed:false,bskBin:null,version:null};const raw=await cliVersion(bin);return raw?{installed:true,bskBin:bin,version:raw.replace(/^bsk\s+/,"")}:{installed:false,bskBin:bin,version:null}}async function daemonReport(client,waitForBrowserMs){try{const status=await client.call("system.status",waitForBrowserMs>0?{wait_for_browser_ms:waitForBrowserMs}:{},{idPrefix:"status"});return{running:true,version:status.daemon_version,protocolVersion:status.protocol_version,browsers:status.browsers??[],sessions:status.sessions??[]}}catch(error){return{running:false,error:error.message,code:error.code,browsers:[],sessions:[]}}}var NO_BROWSER_STEP=`No Chromium-family browser was found. Install one (Chrome, Edge, Brave, Arc, ...), then add the extension from ${STORE_PAGE_URLS.chrome}.`;function withRegistration(platform,browser){const entry=externalExtensionEntry({platform,browser});const extensionRegistered=entry.kind==="file"&&existsSync7(entry.path)&&readFileSync6(entry.path,"utf8")===entry.content;return{...browser,registration:entry,extensionRegistered}}async function identify({platform,home,env,exists,browser,signals,probeSignals,now}){const catalog=catalogBrowsers({platform,home,env,exists}).map((b)=>withRegistration(platform,b));const observed=signals??await probeSignals({platform,home,browsers:catalog.filter((b)=>b.hasProfile)});const explicit=browser??env.OMOWRIGHT_BROWSER??null;const{primary,...identification}=identifyBrowser({catalog,signals:observed,explicit:explicit||null,now});const browsers=catalog.filter((b)=>b.installed);const registeredElsewhere=browsers.filter((b)=>b.extensionRegistered&&b.id!==identification.primaryId).map((b)=>b.id);return{browsers,identification:{...identification,registeredElsewhere},primary}}function choiceStep(identification){const listed=identification.candidates.map((c)=>`${c.label} [${c.id}]${c.signals.length?` — ${c.signals.join(", ")}`:""}`).join("; ");const hint=identification.suggested?` Likely ${identification.suggested}, but confirm first.`:"";return`Ask the user which browser they actually use (${identification.reason}). Candidates: ${listed}.${hint} Then re-run with browser: "<id>"; register nothing until they answer.`}function nextStepFor({cli,daemon,browsers,browsersConnected,identification,primary}){if(browsersConnected.length>0)return null;if(!cli.installed)return"Install the bsk CLI (bskOnboard() runs the official installer).";if(!daemon.running)return"Start the BrowserSkill daemon: run `bsk status` once, or `bsk daemon start` in the environment that owns it.";if(browsers.length===0&&!primary)return NO_BROWSER_STEP;if(identification.needsChoice)return choiceStep(identification);if(!primary.extensionRegistered&&primary.registration.kind!=="store")return`Register the BrowserSkill extension for ${primary.label} (bskOnboard() does this), then let the user enable it.`;return primary.registration.humanStep}async function bskDoctor({platform=process.platform,home=homedir6(),env=process.env,client,bskBin,cliVersion=cliVersionDefault,waitForBrowserMs=0,exists=existsSync7,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){const cli=await cliReport({bskBin,env,cliVersion});const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:false});const daemon=await daemonReport(ipc,waitForBrowserMs);const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,signals,probeSignals,now});const browsersConnected=daemon.browsers;const report={cli,daemon,browsers,primary:primary??null,identification,browsersConnected,ready:browsersConnected.length>0};report.nextStep=nextStepFor(report);return report}async function bskOnboard({platform=process.platform,home=homedir6(),env=process.env,client,bskBin,installDir,installCli=installBskCli,cliVersion=cliVersionDefault,onHumanStep=()=>{},waitForBrowserMs=15000,waitTotalMs=DEFAULT_WAIT_TOTAL_MS,exists=existsSync7,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){let cli=await cliReport({bskBin,env,cliVersion});let install=null;if(!cli.installed){install=await installCli({platform,home,installDir});cli=install.installed?await cliReport({bskBin:install.bskBin,env,cliVersion}):cli}const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:true});let daemon=await daemonReport(ipc,0);const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,signals,probeSignals,now});const registrations=[];let humanStep=null;let needsChoice=false;if(daemon.browsers.length===0){if(browsers.length===0&&!primary){humanStep=NO_BROWSER_STEP}else if(identification.needsChoice){needsChoice=true;humanStep=choiceStep(identification)}else{const registration=await registerExternalExtension({platform,browser:primary});registrations.push({browser:primary.id,...registration});humanStep=registration.humanStep;onHumanStep({browser:primary.id,step:registration.humanStep,registered:registration.registered,needsRestart:registration.needsRestart})}}const deadline=Date.now()+waitTotalMs;let browsersConnected=daemon.browsers;while(!needsChoice&&browsersConnected.length===0&&daemon.running&&Date.now()<deadline){browsersConnected=await listBrowsers(ipc,{waitForBrowserMs});if(waitForBrowserMs===0)break}daemon={...daemon,browsers:browsersConnected};const ready=browsersConnected.length>0;return{cli,install,daemon,browsers,primary:primary??null,identification,needsChoice,registrations,humanStep:ready?null:humanStep,browsersConnected,ready}}export{AgentTabManager,BROWSERSKILL_EXTENSION_IDS,BROWSER_EVENT_NAMES,BridgeProtocolError,BridgeUnavailableError,BrowserCdpCommandError,BrowserConnection,BskIpcClient,BskRpcError,BskSession,CdpClient,CommandSchema,DEFAULT_AGENT_VIEWPORT,DEVICE_PRESETS,ElementHandle,EventSchema,ExtensionHelloSchema,FrameLocator,FrameManager,HostHelloSchema,Locator,ModifierState,OMOWRIGHT_PAGE_CDP_METHODS,OmOKeyboard,OmOMouse,OmOPage,PipeCdpClient,ResponseSchema,STORE_PAGE_URLS,SessionManager,SharedConnectionError,TabRepository,UnsupportedOperationError,bskDoctor,bskOnboard,bskSnapshot,buildCloakBrowserArgs,buildSnapshotExpression,catalogBrowsers,collectWhileScrolling,compactSnapshot,connect,connectBrowserSkill,connectCloakProfile,connectNamed,connectPipe,createAgentTabs,createBridgeClient,createCaptcha,createChromeApi2 as createChromeApi,createCua,createEvents,createNativeMessagingHost,createNetworkSnoop,createRoutes,createTrace,decodeFrames,describeLayers,detectBrowsers,emulate,encodeFrame,externalExtensionEntry,findCloakBrowserPath,identifyBrowser,injectCookies,installBskCli,installNativeMessagingHost,layersHeader,listBrowsers,listInstances,macOSVisionOcr,normalizeDialogPolicy,pageBundle,probeBrowserSignals,readDaemonInfo,reconcileFrames,registerExternalExtension,repinViewport,requestHuman,resolveBskHome,resolveCloakProfile,resolveDialogAction,sanitizeCookies,snapshotTokens,snapshotWithFrames,snapshotWithLayers,takeSnapshot,toHar,toolSchemas,unregisterExternalExtension};diff --git a/plugins/omo/skills/browser/runtime/omowright/manifest.json b/plugins/omo/skills/browser/runtime/omowright/manifest.jsonindex 81a8b5b0..91974289 100644--- a/plugins/omo/skills/browser/runtime/omowright/manifest.json+++ b/plugins/omo/skills/browser/runtime/omowright/manifest.json@@ -1,9 +1,9 @@{"version": "0.0.1",- "sourceDigest": "646863e33d2a1af1fdd3651ee157ada9ba24337e82430edef94342774c80f0f6",+ "sourceDigest": "c9eaae75e948cc52d5b60bb654a5565869d68627046453d87d6f695a5b618045","files": {- "index.js": "d67d3a847fe0bbc43e824feded48b280890d31879538309e671cd5f671133995",+ "index.js": "8b14c1775f397e36967a0d094c67e2a31f8ae1e92add172925548723ca339046","page-bundle.js": "bfd51e8383cf47200d57387bbbed258bce5a3a3d00c38fc108034d2888e23f0c"},- "stagedAtUtc": "2026-10-28T22:42:23.745Z"+ "stagedAtUtc": "2026-10-31T16:02:49.033Z"}diff --git a/plugins/omo/skills/frontend/ATTRIBUTION.md b/plugins/omo/skills/frontend/ATTRIBUTION.mdindex b8833a84..80cfa4b8 100644--- a/plugins/omo/skills/frontend/ATTRIBUTION.md+++ b/plugins/omo/skills/frontend/ATTRIBUTION.md@@ -190,7 +190,8 @@ SOFTWARE.## 5. Project-original files-`frontend/SKILL.md`, `frontend/references/design/README.md`, `_INDEX.md`, `aside.md`,+`frontend/SKILL.md` (apart from the browser-surface, type-and-spacing-floor, and generated-scaffold+rules adapted from Impeccable, section 6), `frontend/references/design/README.md`, `_INDEX.md`, `aside.md`,`design-system-architecture.md`, `grounding.md`, `react-dev-tooling-skill.md`,`frontend/references/perfection/README.md`, `react-perf-tooling.md`, and`frontend/scripts/perfection/lighthouse-audit.py` are original to this project and require@@ -245,3 +246,105 @@ MIT-licensed `JCodesMore/ai-website-cloner-template` clone-website workflow thatcites; no source from that template is copied. It carries no third-party attribution beyondthat lineage note, and it grants no license to copy any target site's trademarks, brandassets, or proprietary copy.++---++## 6. Impeccable (Paul Bakaus): craft-floor rules++`frontend/references/perfection/craft-floor.md`, the "Browser surfaces", "Type and spacing+floor" and "No generated scaffold" rules in `frontend/SKILL.md`, and the matching+`visual-qa/SKILL.md` checklist items (A3 measure, A13, B8, E7, F8, F9) are adapted from+`skill/reference/craft-floor.md` of the Impeccable project. Unlike sections 1-4 these files+are committed: they are rewritten in this project's words, with a few short phrases kept+close to the source.++- Source: https://github.com/pbakaus/impeccable+- Adapted from upstream commit: 5e745ace7e151feb2a93d360d0281fe39448b857+- Copyright 2025 Paul Bakaus+- Licensed under the Apache License, Version 2.0 (the "License"); you may not use these+ files except in compliance with the License. You may obtain a copy of the License at:++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software distributed under+ the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ KIND, either express or implied. See the License for the specific language governing+ permissions and limitations under the License. A full copy of the Apache-2.0 license+ text is provided in `LICENSE-Apache-2.0.txt` alongside this notice.++- **Changes (Apache-2.0 §4(b)):** the rules were selected and rewritten. Kept: the+ browser-surface list, more space above a heading than below it, the 65-75ch body+ measure, the 6rem display cap, the -0.04em tracking floor, and the scaffold and shadow+ patterns listed above. Added: a property per browser surface, the 1.25x type-scale step,+ the 1.5x above-versus-below heading ratio, the 2x between-versus-within group gap, the+ phone measure floor, the split into floors and route-overridable defaults (the kicker is a+ default here, not upstream's absolute ban), and the `/visual-qa` item mapping. Dropped+ because they conflict with this skill: blur and `backdrop-filter` as general motion+ materials (here they animate only in an ambience reveal the brief asked for), choosing+ one theme per product category, decorative custom scrollbars, a blanket bounce-easing+ ban, and the common-typeface ban.+ The upstream `NOTICE.md` names only the MIT-licensed `platform-design-skills` origin of+ its iOS and Android references, none of which is used here.++---++## 7. frontend-detect SDK: Impeccable detector logic and a StyleGallery reflow check++`frontend/scripts/detect/` (the SDK, its rules under `rules/`, the CLI, and their tests),+`frontend/references/perfection/detect.md`, and the development parity scripts+`packages/shared-skills/scripts/detect-parity.ts`, `detect-source-parity.ts` and `detect-parity-oracle.ts` reimplement in TypeScript the rule logic of+the Impeccable detector (`crates/core`, `crates/detect`, `crates/foundation/src/registry.rs`)+at the upstream commit named in section 6. No Rust or JavaScript source is copied; the rule+ids, thresholds, exemptions and the `data-impeccable-ignore` waiver attribute follow+upstream so findings stay comparable, and the unit tests model upstream's fixture cases.+The license, copyright line and license text pointer in section 6 apply to this derived+work as well. `detect-parity-oracle.ts` is not shipped in the skill: at development time it+loads the prebuilt in-page detector from a local Impeccable checkout to record reference+findings, and copies none of it.++- **Changes (Apache-2.0 §4(b)):** a new TypeScript implementation over a browser-captured+ page snapshot instead of upstream's Rust engine and WASM bundle; every rule description+ and fix hint is rewritten; `low-contrast` is an error rather than a warning; project+ allowlists (`allowFonts`, `allowEasings`) and design tokens are configuration rather than+ files; our own `data-detect-ignore` waiver is added beside upstream's; telemetry, the+ hosted design-direction service, the edit hook, the live mode and the browser extension+ are not ported.++The `viewport-reflow` rule and the reflow pass in `detect.ts` (render at 320, 375, 768,+1024 and 1440 px, append an unbroken stress string at 320 px, report horizontal overflow)+follow the layout verification matrix and `tests/pattern-runtime.spec.mjs` of StyleGallery.++- Source: https://github.com/changeroa/StyleGallery+- Adapted from upstream commit: 0bf928f6269b1cb6cf24f04e0bf28a8ce2bbc0ff+- Code licensed under the MIT License; documentation under CC BY 4.0:++```+MIT License++Copyright (c) 2026 IYEN++This license applies to the source code in this repository: scripts, CLI and+MCP server implementations, the website and server code under `site/`,+validators, and test code. The Markdown documentation, pattern and recipe+prose, and domain documents are licensed separately under CC BY 4.0; see+LICENSE-DOCS. Third-party material adapted into this repository keeps its+original rights; see NOTICE.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+```diff --git a/plugins/omo/skills/frontend/SKILL.md b/plugins/omo/skills/frontend/SKILL.mdindex 7ee8b558..4284ece5 100644--- a/plugins/omo/skills/frontend/SKILL.md+++ b/plugins/omo/skills/frontend/SKILL.md@@ -23,7 +23,7 @@ Before the first edit, name the references the request routes to and one reason| Interaction or motion: micro-interactions, transitions, gestures, hover/press/state feedback | `references/design/interaction-skill.md`. The beui.dev catalog is the reference: read the nearest pattern's real source through its curl recipe, adapt the mechanism to `DESIGN.md` motion tokens. || Ambience, only when the brief asks: an animated, shader, particle, or grid background; a typographic reveal; scroll storytelling; spotlight, tilt, or glowing-border cards | `references/design/ambience-skill.md`. The react-bits catalog is the reference: nearest pattern, real source, its retrofit checklist (reduced motion, off-screen pause, compositor-only, tokens, budget); never vendor its code. || Tone outside both anchors: AI-agent UI, charts, landing sections, a brutalist or Tailwind-only build, or no nearest pattern | `references/design/component-catalogs.md`: which catalog per tone, the exploration procedure, the licence gate. |-| Writing or modifying frontend code; auditing performance, SEO, accessibility, quality | `references/perfection/README.md` (+ `react-perf-tooling.md` before any React audit). Lighthouse 100 in every category on real Playwright Chromium, won in the architecture. Design and perfection load together for implementation work. |+| Writing or modifying frontend code; auditing performance, SEO, accessibility, quality | `references/perfection/README.md`, `references/perfection/craft-floor.md`, and `references/perfection/detect.md` (+ `react-perf-tooling.md` before any React audit). Lighthouse 100 in every category on real Playwright Chromium, won in the architecture. Design and perfection load together for implementation work. || On request, or a greenfield palette, type, chart, or landing-structure question | `references/ui-ux-db/README.md` and its search CLI (library, below). A lookup tool, never the posture. || Creating or updating `DESIGN.md`; personas, critique, debt, handoff, synthetic user testing | `references/designpowers/README.md` + `lane-c-review.md` (lane-c is the Phase Final critique reviewer and fills the accessibility-constraint and accepted-debt sections). || Any code change in a React project | `references/design/README.md` Phase 0.5: the react-grab / react-scan / react-doctor check (a grep), the install when one is missing, and the dev-only gate; `react-dev-tooling-skill.md` for per-framework snippets. |@@ -56,6 +56,8 @@ Take the branch in `references/design/README.md` Phase 0 first (a small change o- **Keyboard.** Every action reachable in reading order with a visible focus ring that no sticky bar or overlay covers; Escape closes the topmost overlay; Enter triggers the non-destructive default; standard shortcuts keep their meaning; icon-only controls carry an accessible name and a tooltip.- **Motion.** Only for a cause (an interaction, a state change, an arrival), on `transform`, `opacity`, `filter`; interruptible, never gating input; movement becomes a cross-fade under `prefers-reduced-motion`. A hover that changes nothing or motion on a non-interactive element is slop: leave it out.- **Icons.** One SVG set (Lucide, Heroicons, Radix, Phosphor); never an emoji.+- **Browser surfaces.** Text selection, the caret, visible scrollbars, the focus ring, link underline offset, and tabular numerals are themed from the palette in both themes; none ships as the browser default. `references/perfection/craft-floor.md` has the property for each.+- **Type and spacing floor.** Each heading step (display to h3, and the smallest heading to body) differs by at least 1.25x, and body-family roles that sit closer also differ by weight, colour or case; the space above a section heading is at least 1.5x the space below it; the gap between groups is at least 2x the gap inside one; body text runs 65-75 characters per line on desktop; display type stays at or under 6rem and tracking at or above -0.04em unless the chosen style route sets its own. Check computed values, not the source.- **Concrete reference = contract.** Match its pixels, copy, component structure, and responsive intent unless the user accepts a deviation.- **Never weaken UX to buy points.** No dropping animations, hiding content, or simplifying interactions for a Lighthouse score or a deadline.@@ -63,16 +65,18 @@ Take the branch in `references/design/README.md` Phase 0 first (a small change oSome tells regenerate by default, so they are kept out of the first draft rather than left for QA to find.-- **No coloured bar on one side of a box, rounded or square, and no accent outline on a rounded card, decorative or state.** A card, callout, warning, cover block, stat tile, testimonial, alert, or list row never carries a coloured stripe on one side: `border-left: 4px solid <accent>` or `border-l-4 border-indigo-500`, a coloured `::before`/`::after` bar inside it, an inset `box-shadow` stripe, or a hard-stop gradient band or gradient `border-image` along one edge. A rounded card never wears a 2px-or-wider accent outline either (`border: 2px solid var(--primary)`, `ring-2 ring-indigo-500`, an inset ring). Both read as generated whether they decorate the box or mark it selected, focused, or active, and an accent underline under a heading, tab, or link counts too: use a neutral 1px rule, or set the text itself in the accent ink. Give the card its identity another way: a tonal surface (one ink at a low alpha, or the next step of the surface ramp), an eyebrow or heading set in the accent ink, a leading glyph, or more space between groups. Encode state with one ink at many alphas (hover/selected/active washes), a check glyph for selection, and tonal layering for focus. The coloured edges that stay allowed: keyboard `focus-visible` rings, validation states on form inputs, neutral 1px hairlines and dividers between rows or sections, table rules, and a blockquote's neutral rule. This covers pre-existing instances on any surface you touch.+- **No coloured bar on one side of a box, rounded or square, and no accent outline on a rounded card, decorative or state.** A card, callout, warning, cover block, stat tile, testimonial, alert, or list row never carries a coloured stripe on one side: `border-left: 4px solid <accent>` or `border-l-4 border-indigo-500`, a coloured `::before`/`::after` bar inside it, an inset `box-shadow` stripe, or a hard-stop gradient band or gradient `border-image` along one edge. A rounded card never wears a 2px-or-wider accent outline either (`border: 2px solid var(--primary)`, `ring-2 ring-indigo-500`, an inset ring). Both read as generated whether they decorate the box or mark it selected, focused, or active, and an accent underline under a heading, tab, or link counts too: use a neutral 1px rule, or set the text itself in the accent ink. Give the card its identity another way: a tonal surface (one ink at a low alpha, or the next step of the surface ramp), a heading set in the accent ink, a leading glyph, or more space between groups. Encode state with one ink at many alphas (hover/selected/active washes), a check glyph for selection, and tonal layering for focus. The coloured edges that stay allowed: keyboard `focus-visible` rings, validation states on form inputs, neutral 1px hairlines and dividers between rows or sections, table rules, and a blockquote's neutral rule. This covers pre-existing instances on any surface you touch.- **Lint before visual QA.** Run `bun $SKILL_DIR/scripts/perfection/check-draft-guard.ts <changed files or dirs>` on every stylesheet, component, and HTML file you wrote, including a report or figure you will print, screenshot, or render to an image. It reads CSS/SCSS/Less, HTML, JSX/TSX, Vue, Svelte, Astro, Tailwind classes (including `@apply` and `cva`/`cn` strings), inline styles, and styled-components, and flags the stripes above plus promotional filler copy, emoji used as icons, hype badges, and hard-coded vanity numbers in stat tiles. Exit 1 means a tell is in the draft: remove it, do not argue with the finding.+- **Detect after the build renders.** Once the page renders, run the detect SDK on it at 1440 and 390 with reflow on (`references/perfection/detect.md`): `detectPage({ kind: "url", url }, { reflow: true })` from code, or `bun $SKILL_DIR/scripts/detect/cli.ts --reflow <url-or-html-files>`. It reads the rendered page (contrast on the painted background, type scale, heading order, overflow, decoration and copy tells). Fix every error and warning before `/visual-qa`; record a decision for each advisory.- **No decorative badge without a state behind it.** A pill, chip, or tag appears only when it carries a value that can change: a status, a count, a category the user filters by. "New", "Pro", or "AI-powered" on a static heading is decoration.- **No stat tile without a decision behind it.** A number earns a tile when someone acts on it; four tiles above a table that already holds the numbers are filler.- **No invented proof.** Testimonials, quotes, customer logos, ratings, user counts, and prices come from the project or stay out. A section that needs proof the project does not have is cut, or ships as an empty slot labelled for the owner to fill; a "sample" testimonial is still a fabricated one.- **No prop decoration.** A device tilted for effect, a floating reassurance card, decorative coordinates, sparkles, and ornaments that say nothing about the product are the generated version of "premium". A product preview shows a real state of the product, with its text readable at the rendered size.-- **No repeated formula.** A treatment that carries one heading (a serif line with an italic accent phrase, a gradient word, an eyebrow-headline-subtitle stack) becomes a template when every section repeats it; so does one image reused across sections. Use each once, where it means something.+- **No repeated formula.** A treatment that carries one heading (a serif line with an italic accent phrase, a gradient word, a headline-subtitle pair) becomes a template when every section repeats it; so does one image reused across sections. Use each once, where it means something.- **No subtitle under every heading.** A heading explains itself; a one-line description under each one is the generated rhythm. Keep a subtitle only where the heading alone would be misread.- **One fact, one place.** A conclusion banner and a callout that restates it, a summary card and a table row with the same figure, a label repeated as its placeholder: keep one.- **No dated or borrowed surface.** Glass and blur panels (they read as a clone of a popular open-source chat app), neumorphism, mesh-gradient heroes, heavy drop shadows, and 2019-era SaaS illustration date a draft on sight. Surfaces come from `DESIGN.md` section 7; a material ships only when the brief or a concrete reference supplies it.+- **No generated scaffold.** No kicker label above a heading, no icon tile stacked over a heading in a grid of same-size cards, no hero metric (a giant number with a small label and supporting stats), no card inside a card, no neutral gray text on a coloured surface, no monospace as a "technical" costume, and no zero-offset coloured glow standing in for a shadow. `references/perfection/craft-floor.md` gives the replacement for each, and says when the brief or its chosen route brings one back.- **No promotional copy.** Interface copy states what a thing is or does. "Seamlessly", "effortlessly", "smart", "powerful", "at a glance", "supercharge", and their Korean counterparts ("한눈에", "손쉽게", "스마트한", "효율적으로", "간편하게") are marketing, not interface: rewrite as the plain fact or delete.## 3. Subtractdiff --git a/plugins/omo/skills/frontend/references/design/design-system-architecture.md b/plugins/omo/skills/frontend/references/design/design-system-architecture.mdindex 9835b741..577f5573 100644--- a/plugins/omo/skills/frontend/references/design/design-system-architecture.md+++ b/plugins/omo/skills/frontend/references/design/design-system-architecture.md@@ -73,11 +73,11 @@ rather than borders, creating layers you feel more than see."| H1 | 36px / 2.25rem | 700 | 1.2 | -0.015em | Section headers || H2 | 28px / 1.75rem | 600 | 1.3 | -0.01em | Subsection headers || H3 | 22px / 1.375rem | 600 | 1.4 | 0 | Card titles |-| Body/lg | 18px / 1.125rem | 400 | 1.6 | 0 | Lead paragraphs |+| Body/lg | 18px / 1.125rem | 400 | 1.6 | 0 | Lead paragraphs, in the secondary ink || Body | 16px / 1rem | 400 | 1.6 | 0 | Default text |-| Body/sm | 14px / 0.875rem | 400 | 1.5 | 0 | Secondary info |+| Body/sm | 14px / 0.875rem | 400 | 1.5 | 0 | Secondary info, in the secondary ink || Caption | 12px / 0.75rem | 500 | 1.4 | 0.02em | Labels, metadata |-| Overline | 11px / 0.6875rem | 600 | 1.3 | 0.08em | Section labels, uppercase |+| Overline | 11px / 0.6875rem | 600 | 1.3 | 0.08em | Field, table and metadata labels, uppercase; by default not a label above a heading, unless the chosen route asks for one (`references/perfection/craft-floor.md`) |### Font Stack- Primary: [specify — e.g. "Inter, system-ui, -apple-system, sans-serif"]diff --git a/plugins/omo/skills/frontend/references/perfection/craft-floor.md b/plugins/omo/skills/frontend/references/perfection/craft-floor.mdnew file mode 100644index 00000000..3206e9bb--- /dev/null+++ b/plugins/omo/skills/frontend/references/perfection/craft-floor.md@@ -0,0 +1,59 @@+# Craft floor: the numbers a build must clear++Adapted from the `craft-floor` reference of [pbakaus/impeccable](https://github.com/pbakaus/impeccable) (Apache-2.0, Copyright 2025 Paul Bakaus), rewritten for this skill; see `ATTRIBUTION.md` section 6 for the license and the list of changes.++Read this with `README.md` for any code change. It sets no direction, and it has two kinds of line. Each line is checked on the rendered page by reading computed values, not by looking at the source. `/visual-qa` checks them again (A3, A13, B8, E7, F8, F9).++- **Floors** (marked *floor* below) hold under every style skill and brand. A project's `DESIGN.md` may raise them, never lower them.+- **Defaults** (every other line) hold until the brief asks otherwise. That means the brief's own words, a concrete reference, or a route the brief chose that names the value or pattern: a Layer A style skill or Layer B brand under `references/design/`, or the ambience route. Brutalist display scale and tracking, a brand's labels above headings, and the ambience route's blur reveals and glowing-border cards are examples. The route wins for that one item only. Record the deviation in the brief or `DESIGN.md` so `/visual-qa` reads it as chosen, not generated.++## Browser surfaces++*Floor.* The parts of a page the browser draws by default ship with no design unless you give them one. Theme every one that the surface has, from the palette tokens, in both themes:++| Surface | What to set |+|---|---|+| Text selection | `::selection { background: <accent at low alpha>; color: <ink> }`; the default system blue never shows. |+| Caret | `caret-color: <accent or ink>` on inputs, textareas and contenteditable. |+| Scrollbars | `scrollbar-color: <thumb> <track>` and `scrollbar-width: thin` on scroll containers that keep a visible bar. Overlay scrollbars stay overlay (`/visual-qa` A5); this styles the bar, it never adds a gutter. |+| Focus ring | `:focus-visible { outline: 2px solid <focus token>; outline-offset: 2px }`, visible on every surface colour. |+| Underlines | `text-underline-offset: 0.15em` to `0.25em` and `text-decoration-thickness` from the type scale on links, so the line clears descenders. |+| Numerals | `font-variant-numeric: tabular-nums` on every column, counter, timer, price and table cell that changes or aligns. |++Exempt: a surface with no instance of the element (no inputs means no caret), and a native control the brief keeps unstyled on purpose.++## Type and spacing floor++| Rule | Floor | Read from |+|---|---|---|+| Type scale steps (*floor*) | Each step of the heading ladder (display, h1, h2, h3) and the step from the smallest heading to body differ by at least 1.25x in size. The body-family roles (lead, body, small, caption, overline or label) may sit closer, but each also differs from its neighbour by weight, colour or case, never by size alone. | computed `font-size` of each role in use |+| Space around a heading | The space above a section heading is at least 1.5x the space below it, so the heading belongs to the content it introduces. | computed margin/padding plus the parent gap |+| Group separation | The gap between groups is at least 2x the gap inside a group. | computed `gap` / margins of siblings |+| Body measure (*floor*) | Body text runs 65-75 characters per line on desktop; 45 is the lower bound on a phone. | rendered line length at 1440 and 390 |+| Display size | A display heading stays at or under 6rem unless the chosen route sets a larger display scale. | computed `font-size` |+| Tracking | Letter spacing stays at or above -0.04em unless the chosen route sets tighter display tracking; -0.02em to -0.03em usually reads better on large type. Body text keeps 0. | computed `letter-spacing` / `font-size` |++Run the real copy at every captured width and fix what overflows or wraps a heading to four lines.++## Patterns kept out of the first draft++These extend the Draft guard in `SKILL.md`. Each one is what a generator reaches for when nothing decided otherwise, so the first draft leaves it out. The brief or its chosen route can still ask for one (see the defaults rule above). The hard offset shadow below is narrower than that.++- **Kicker above a heading.** A small uppercase or accent label sitting on top of a heading ("FEATURES", "01 - OVERVIEW"). Delete it; the heading carries its own weight.+- **Icon in a tile over a heading.** A rounded square holding an icon, stacked above a heading and a line of text, repeated across a grid of same-size cards. Use the content's own structure (a list, a table, a real image) instead of the card formula.+- **Hero metric.** One giant number with a small label, flanked by supporting stats and an accent. A number earns that size only when it is the decision the screen exists for.+- **Cards inside cards.** A bordered or shadowed box inside another. Separate inner groups with space or a neutral 1px rule.+- **Gray text on a coloured surface.** Secondary text on a tinted or coloured background takes a shade of that hue (or the foreground at reduced alpha), never neutral gray, which looks dirty and fails contrast first.+- **Monospace as a costume.** A monospace face only for code, data, ids and measurements, never to make a heading or a UI read as "technical".+- **Glow and halo shadows.** A shadow carries a y-offset and a soft blur. A zero-offset coloured glow around a card or button is decoration, unless the brief asked for glowing-border cards through the ambience route. Hard offset shadows with no blur (`4px 4px 0`) only when the brief chose a neobrutalist direction.++## What this skill does not take from the source++The upstream reference disagrees with rules this skill already holds; ours win:++- Blur, `backdrop-filter` and `filter: blur()` are not general motion materials. They animate only in an ambience reveal the brief asked for (`references/design/ambience-skill.md`), and never under `prefers-reduced-motion` (`/visual-qa` G4).+- A label above a heading is a default to leave out, not an absolute ban: a style route that allows a limited number of them (`taste-skill.md`) is followed.+- Both light and dark themes ship (`/visual-qa` E1); the theme is not picked per product category.+- An intentional spring is allowed where `DESIGN.md` names it; bounce easing is a finding only when no token asked for it.+- A typeface the project chose (for example Inter in a product that matches its platform) is never a finding because it is common.+- Scrollbars follow the overlay rule above; this skill never asks for a decorative custom scrollbar.diff --git a/plugins/omo/skills/frontend/references/perfection/detect.md b/plugins/omo/skills/frontend/references/perfection/detect.mdnew file mode 100644index 00000000..577b468a--- /dev/null+++ b/plugins/omo/skills/frontend/references/perfection/detect.md@@ -0,0 +1,52 @@+# frontend-detect: the after-build lint++`scripts/detect/` is a typed TypeScript SDK that renders a page and lints what the browser actually drew: contrast against the painted background, the type scale in use, spacing, overflow, decoration tells, and copy tells. The rule logic is ported from the detector of [pbakaus/impeccable](https://github.com/pbakaus/impeccable) (Apache-2.0, Copyright 2025 Paul Bakaus) plus one reflow check from [changeroa/StyleGallery](https://github.com/changeroa/StyleGallery) (MIT); see `ATTRIBUTION.md` section 7.++It runs after the draft builds and before `/visual-qa`. `check-draft-guard.ts` stays the first lint on source; this one needs a rendered page and catches what source cannot show: a 4.2:1 table header in dark mode, an h1 followed by an h3, a heading that wraps one word onto its last line, a card that overflows at 390.++## Run it++From code (the primary interface). Import `index.ts`; importing does nothing until you call a function:++```ts+const detect = await import(`${SKILL_DIR}/scripts/detect/index.ts`)+const findings = await detect.detectPage({ kind: "url", url: "http://localhost:5173/settings" }, {+ viewports: [{ width: 1440, height: 900 }, { width: 390, height: 844 }],+ reflow: true,+ config: { allowFonts: ["Inter"], designTokens: { radii: [8, 12] } },+})+if (detect.hasFailures(findings)) console.log(detect.formatFindingsText(findings))+```++- `detectPage(target, options)`: `target` is `{ kind: "url", url }` or `{ kind: "html", html }`. Renders at each viewport (default 1440 and 390) and returns sorted, de-duplicated findings.+- `detectFiles(paths, options)`: HTML files are rendered; CSS/SCSS/Less, JSX/TSX, Vue, Svelte and Astro files run the source-text rules.+- `lintSnapshot(snapshot, options)` / `lintSources(files, options)`: the pure rule engines, for a snapshot you captured yourself with `collectPageSnapshot` in your own Playwright or omowright page.+- `renderer`: pass your own `Renderer` to reuse a browser you already drive; the default is `Bun.WebView` (system WebKit on macOS, installed Chrome elsewhere; `createWebViewRenderer({ backend: "chrome" })` matches the upstream engine most closely).+- Every finding carries `ruleId`, `severity` (`error`, `warning`, `advisory`), `category`, `message`, `fixHint`, and a `location`: an element (`selector`, `rect`, `viewport`), a source position (`file`, `line`, `column`), or the page.++From a shell, the CLI is a thin wrapper over the same calls:++```bash+bun $SKILL_DIR/scripts/detect/cli.ts [--json] [--reflow] [--config detect.json] <file-or-dir-or-url>...+```++Exit 0: no error or warning findings. Exit 1: at least one. Exit 2: usage error or a page that failed to render.++## Config++`--config` (or `options.config`) takes JSON:++| Key | Meaning |+|---|---|+| `rules` | `{ "<rule-id>": "error" \| "warning" \| "advisory" \| "off" }` per rule |+| `allowFonts` | Families the project chose on purpose (Inter on a product that matches its platform); never reported as overused |+| `allowEasings` | Timing functions `DESIGN.md` names on purpose, such as an intentional spring |+| `designTokens` | `{ fonts, colors, radii, fontSizes }`; the `design-system-*` rules report values outside them and stay silent without them |++Waive one element with `data-detect-ignore="<rule-id> <rule-id>"` on it or an ancestor (upstream's `data-impeccable-ignore` is honoured too). A waiver needs the reason in `DESIGN.md`.++## Reading the result++- `error` and `warning` fail the gate: fix them before `/visual-qa`. `low-contrast` is an error here, stricter than upstream, because a contrast failure is never a taste call.+- `advisory` findings are review prompts (`hard-offset-shadow` on a page that chose neobrutalism, `bounce-easing` on a named spring). Record the decision; do not delete a deliberate choice to silence one.+- A finding you believe is wrong: rerun at the viewport it names and read the computed values it quotes. Waive it with the attribute only when `DESIGN.md` explains why.diff --git a/plugins/omo/skills/frontend/scripts/detect/cli.ts b/plugins/omo/skills/frontend/scripts/detect/cli.tsnew file mode 100644index 00000000..40fbe44c--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/cli.ts@@ -0,0 +1,70 @@+#!/usr/bin/env bun+// Thin CLI over the detect SDK (index.ts). Usage:+// bun cli.ts [--json] [--reflow] [--config <file.json>] <file-or-dir-or-url>...+// Exit 0 no error or warning findings, 1 findings that fail the gate, 2 usage or render failure.+import { readFileSync } from "node:fs"+import { collectFiles } from "../perfection/collect-files"+import { type DetectConfig, detectFiles, detectPage, type Finding, formatFindingsText, hasFailures, parseConfig, RenderError, sortFindings } from "./index"++type Args = { readonly json: boolean; readonly reflow: boolean; readonly config: DetectConfig; readonly targets: readonly string[] }++function readConfig(path: string): DetectConfig | string {+ let raw: unknown+ try {+ raw = JSON.parse(readFileSync(path, "utf8"))+ } catch (error) {+ // no-excuse-ok: catch (CLI boundary: an unreadable or malformed config file is a usage error reported as exit 2)+ if (error instanceof Error) return error.message+ throw error+ }+ return parseConfig(raw)+}++function parseArgs(argv: readonly string[]): Args | string {+ let json = false+ let reflow = false+ let config: DetectConfig = {}+ const targets: string[] = []+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i] ?? ""+ if (a === "--json") json = true+ else if (a === "--reflow") reflow = true+ else if (a === "--config") {+ const path = argv[++i]+ if (!path) return "--config needs a file"+ const parsed = readConfig(path)+ if (typeof parsed === "string") return `${path}: ${parsed}`+ config = parsed+ } else targets.push(a)+ }+ return targets.length === 0 ? "no targets" : { json, reflow, config, targets }+}++async function main(argv: readonly string[]): Promise<number> {+ const args = parseArgs(argv)+ if (typeof args === "string") {+ process.stderr.write(`frontend-detect: ${args}\nusage: cli.ts [--json] [--reflow] [--config <file.json>] <file-or-dir-or-url>...\n`)+ return 2+ }+ const urls = args.targets.filter((t) => /^https?:\/\//.test(t))+ const { paths, missing } = collectFiles(args.targets.filter((t) => !urls.includes(t)))+ if (missing.length > 0) {+ process.stderr.write(`frontend-detect: cannot read ${missing.join(", ")}\n`)+ return 2+ }+ const options = { config: args.config, reflow: args.reflow }+ const findings: Finding[] = [...(await detectFiles(paths, options))]+ for (const url of urls) findings.push(...(await detectPage({ kind: "url", url }, { ...options, file: url })))+ const sorted = sortFindings(findings)+ process.stdout.write(args.json ? `${JSON.stringify(sorted, null, 2)}\n` : formatFindingsText(sorted))+ return hasFailures(sorted) ? 1 : 0+}++try {+ process.exitCode = await main(process.argv.slice(2))+} catch (error) {+ // no-excuse-ok: catch (CLI boundary: a render failure is reported as exit 2, anything else propagates)+ if (!(error instanceof RenderError)) throw error+ process.stderr.write(`frontend-detect: ${error.message}\n`)+ process.exitCode = 2+}diff --git a/plugins/omo/skills/frontend/scripts/detect/config.ts b/plugins/omo/skills/frontend/scripts/detect/config.tsnew file mode 100644index 00000000..2801234b--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/config.ts@@ -0,0 +1,53 @@+import type { DesignTokens, DetectConfig, RuleSetting } from "./types"++const SETTINGS: readonly RuleSetting[] = ["error", "warning", "advisory", "off"]++const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v)+const isStringArray = (v: unknown): v is readonly string[] => Array.isArray(v) && v.every((x) => typeof x === "string")+const isNumberArray = (v: unknown): v is readonly number[] => Array.isArray(v) && v.every((x) => typeof x === "number" && Number.isFinite(x))++function parseTokens(v: unknown): DesignTokens | string {+ if (!isRecord(v)) return "designTokens must be an object"+ const { fonts, colors, radii, fontSizes, ...rest } = v+ const extra = Object.keys(rest)[0]+ if (extra) return `unknown designTokens key '${extra}'`+ if (fonts !== undefined && !isStringArray(fonts)) return "designTokens.fonts must be an array of family names"+ if (colors !== undefined && !isStringArray(colors)) return "designTokens.colors must be an array of CSS colors"+ if (radii !== undefined && !isNumberArray(radii)) return "designTokens.radii must be an array of px numbers"+ if (fontSizes !== undefined && !isNumberArray(fontSizes)) return "designTokens.fontSizes must be an array of px numbers"+ return {+ ...(fonts !== undefined ? { fonts } : {}),+ ...(colors !== undefined ? { colors } : {}),+ ...(radii !== undefined ? { radii } : {}),+ ...(fontSizes !== undefined ? { fontSizes } : {}),+ }+}++const isSetting = (v: unknown): v is RuleSetting => SETTINGS.some((s) => s === v)++/** Parses a detect config from untrusted JSON; returns the config or a message naming the first bad field. */+export function parseConfig(input: unknown): DetectConfig | string {+ if (!isRecord(input)) return "config must be a JSON object"+ const known = new Set(["rules", "allowFonts", "allowEasings", "designTokens"])+ const unknownKey = Object.keys(input).find((k) => !known.has(k))+ if (unknownKey) return `unknown config key '${unknownKey}'`+ const { rules, allowFonts, allowEasings, designTokens } = input+ const tokens = designTokens === undefined ? undefined : parseTokens(designTokens)+ if (typeof tokens === "string") return tokens+ const parsedRules: Record<string, RuleSetting> = {}+ if (rules !== undefined) {+ if (!isRecord(rules)) return "rules must be an object of rule id -> error|warning|advisory|off"+ for (const [id, setting] of Object.entries(rules)) {+ if (!isSetting(setting)) return `rules.${id} must be one of ${SETTINGS.join(", ")}`+ parsedRules[id] = setting+ }+ }+ if (allowFonts !== undefined && !isStringArray(allowFonts)) return "allowFonts must be an array of family names"+ if (allowEasings !== undefined && !isStringArray(allowEasings)) return "allowEasings must be an array of timing functions"+ return {+ ...(rules !== undefined ? { rules: parsedRules } : {}),+ ...(allowFonts !== undefined ? { allowFonts } : {}),+ ...(allowEasings !== undefined ? { allowEasings } : {}),+ ...(tokens !== undefined ? { designTokens: tokens } : {}),+ }+}diff --git a/plugins/omo/skills/frontend/scripts/detect/core/characters.ts b/plugins/omo/skills/frontend/scripts/detect/core/characters.tsnew file mode 100644index 00000000..2fff80ec--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/core/characters.ts@@ -0,0 +1,2 @@+/** The em dash, built from its code point so the character never appears as a copy literal in source. */+export const EM_DASH = String.fromCharCode(0x2014)diff --git a/plugins/omo/skills/frontend/scripts/detect/core/color.ts b/plugins/omo/skills/frontend/scripts/detect/core/color.tsnew file mode 100644index 00000000..f0dda4e7--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/core/color.ts@@ -0,0 +1,150 @@+export type Rgba = { readonly r: number; readonly g: number; readonly b: number; readonly a: number }++export const TRANSPARENT: Rgba = { r: 0, g: 0, b: 0, a: 0 }+export const WHITE: Rgba = { r: 255, g: 255, b: 255, a: 1 }++const clamp255 = (n: number): number => Math.max(0, Math.min(255, n))++function parseHex(hex: string): Rgba | null {+ const h = hex.slice(1)+ const full = h.length === 3 || h.length === 4 ? [...h].map((c) => c + c).join("") : h+ if (!/^[0-9a-f]{6}([0-9a-f]{2})?$/i.test(full)) return null+ const n = (i: number): number => Number.parseInt(full.slice(i, i + 2), 16)+ return { r: n(0), g: n(2), b: n(4), a: full.length === 8 ? n(6) / 255 : 1 }+}++function channel(token: string, scale: number): number {+ return token.endsWith("%") ? (Number.parseFloat(token) / 100) * scale : Number.parseFloat(token)+}++function oklabToRgb(l: number, a: number, b: number): readonly [number, number, number] {+ const l_ = (l + 0.3963377774 * a + 0.2158037573 * b) ** 3+ const m_ = (l - 0.1055613458 * a - 0.0638541728 * b) ** 3+ const s_ = (l - 0.0894841775 * a - 1.291485548 * b) ** 3+ const lin = [+ 4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_,+ -1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_,+ -0.0041960863 * l_ - 0.7034186147 * m_ + 1.707614701 * s_,+ ] as const+ const gamma = (c: number): number => clamp255(255 * (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055))+ return [gamma(lin[0]), gamma(lin[1]), gamma(lin[2])]+}++type Vec3 = readonly [number, number, number]+const mul = (m: readonly Vec3[], v: Vec3): Vec3 => {+ const row = (i: number): Vec3 => m[i] ?? [0, 0, 0]+ const dot = (r: Vec3): number => r[0] * v[0] + r[1] * v[1] + r[2] * v[2]+ return [dot(row(0)), dot(row(1)), dot(row(2))]+}+const XYZ_D65_TO_LINEAR_SRGB: readonly Vec3[] = [+ [3.2409699419, -1.5373831776, -0.4986107603],+ [-0.9692436363, 1.8759675015, 0.0415550574],+ [0.0556300797, -0.2039769589, 1.0569715142],+]+const LINEAR_P3_TO_XYZ_D65: readonly Vec3[] = [+ [0.4865709486, 0.2656676932, 0.1982172852],+ [0.2289745641, 0.6917385218, 0.0792869141],+ [0, 0.0451133819, 1.0439443689],+]+const XYZ_D50_TO_D65: readonly Vec3[] = [+ [0.9554734528, -0.0230985368, 0.0632593086],+ [-0.0283697094, 1.0099954580, 0.0210413990],+ [0.0123140016, -0.0205076964, 1.3303659366],+]+const toLinear = (c: number): number => (Math.abs(c) <= 0.04045 ? c / 12.92 : Math.sign(c) * ((Math.abs(c) + 0.055) / 1.055) ** 2.4)+const encode = (lin: Vec3): Vec3 => {+ const gamma = (c: number): number => clamp255(255 * (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055))+ return [gamma(lin[0]), gamma(lin[1]), gamma(lin[2])]+}++function labToRgb(l: number, a: number, b: number): Vec3 {+ const fy = (l + 16) / 116+ const [fx, fz] = [fy + a / 500, fy - b / 200]+ const inv = (t: number): number => (t ** 3 > 216 / 24389 ? t ** 3 : (116 * t - 16) / (24389 / 27))+ const xyzD50: Vec3 = [0.3457 / 0.3585 * inv(fx), l > 8 ? fy ** 3 : l / (24389 / 27), (1 - 0.3457 - 0.3585) / 0.3585 * inv(fz)]+ return encode(mul(XYZ_D65_TO_LINEAR_SRGB, mul(XYZ_D50_TO_D65, xyzD50)))+}++function predefinedToRgb(space: string, c: Vec3): Vec3 | null {+ if (space === "srgb") return [clamp255(c[0] * 255), clamp255(c[1] * 255), clamp255(c[2] * 255)]+ if (space === "srgb-linear") return encode(c)+ if (space === "display-p3") return encode(mul(XYZ_D65_TO_LINEAR_SRGB, mul(LINEAR_P3_TO_XYZ_D65, [toLinear(c[0]), toLinear(c[1]), toLinear(c[2])])))+ return null+}++/** Parses the color forms getComputedStyle returns (rgb/rgba, color(srgb | srgb-linear | display-p3), lab/lch, oklab/oklch) plus hex and `transparent`; other spaces return null. Out-of-gamut values are clamped to sRGB. */+export function parseColor(input: string): Rgba | null {+ const s = input.trim().toLowerCase()+ if (s === "transparent") return TRANSPARENT+ if (s.startsWith("#")) return parseHex(s)+ const m = /^(rgba?|color|oklab|oklch|lab|lch)\((.*)\)$/.exec(s)+ if (!m) return null+ const [, fn, body = ""] = m+ const [main = "", alphaPart] = body.split("/")+ const parts = main.replace(/,/g, " ").split(/\s+/).filter(Boolean)+ const commaAlpha = fn?.startsWith("rgb") && parts.length === 4 ? parts[3] : undefined+ const alphaToken = alphaPart?.trim() ?? commaAlpha+ const a = alphaToken === undefined ? 1 : channel(alphaToken, 1)+ if (fn === "rgb" || fn === "rgba") return { r: channel(parts[0] ?? "0", 255), g: channel(parts[1] ?? "0", 255), b: channel(parts[2] ?? "0", 255), a }+ if (fn === "color") {+ const rgb = predefinedToRgb(parts[0] ?? "", [channel(parts[1] ?? "0", 1), channel(parts[2] ?? "0", 1), channel(parts[3] ?? "0", 1)])+ return rgb ? { r: rgb[0], g: rgb[1], b: rgb[2], a } : null+ }+ if (fn === "lab" || fn === "lch") {+ const l = channel(parts[0] ?? "0", 100)+ const [q1, q2] = [Number.parseFloat(parts[1] ?? "0"), Number.parseFloat(parts[2] ?? "0")]+ const [la, lb] = fn === "lch" ? [q1 * Math.cos((q2 * Math.PI) / 180), q1 * Math.sin((q2 * Math.PI) / 180)] : [q1, q2]+ const [r, g, b] = labToRgb(l, la, lb)+ return { r, g, b, a }+ }+ const l = channel(parts[0] ?? "0", 1)+ const [p1, p2] = [Number.parseFloat(parts[1] ?? "0"), Number.parseFloat(parts[2] ?? "0")]+ const [oa, ob] = fn === "oklch" ? [p1 * Math.cos((p2 * Math.PI) / 180), p1 * Math.sin((p2 * Math.PI) / 180)] : [p1, p2]+ const [r, g, b] = oklabToRgb(l, oa, ob)+ return { r, g, b, a }+}++/** Source-over compositing of `top` onto an opaque `bottom`. */+export function blend(top: Rgba, bottom: Rgba): Rgba {+ const a = top.a + bottom.a * (1 - top.a)+ if (a === 0) return TRANSPARENT+ const mix = (t: number, b: number): number => (t * top.a + b * bottom.a * (1 - top.a)) / a+ return { r: mix(top.r, bottom.r), g: mix(top.g, bottom.g), b: mix(top.b, bottom.b), a }+}++/** WCAG 2.x relative luminance. */+export function luminance(c: Rgba): number {+ const lin = (v: number): number => {+ const s = v / 255+ return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4+ }+ return 0.2126 * lin(c.r) + 0.7152 * lin(c.g) + 0.0722 * lin(c.b)+}++/** WCAG 2.x contrast ratio between two opaque colors, 1..21. */+export function contrastRatio(a: Rgba, b: Rgba): number {+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x)+ return ((hi ?? 0) + 0.05) / ((lo ?? 0) + 0.05)+}++export function toHsl(c: Rgba): { readonly h: number; readonly s: number; readonly l: number } {+ const [r, g, b] = [c.r / 255, c.g / 255, c.b / 255]+ const max = Math.max(r, g, b)+ const min = Math.min(r, g, b)+ const l = (max + min) / 2+ if (max === min) return { h: 0, s: 0, l }+ const d = max - min+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min)+ const h = max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4+ return { h: h * 60, s, l }+}++/** Every color literal inside a computed value such as `box-shadow` or `background-image`. */+export function colorsIn(value: string): readonly Rgba[] {+ const out: Rgba[] = []+ for (const m of value.matchAll(/(rgba?|color|oklab|oklch|lab|lch)\([^()]*\)|#[0-9a-f]{3,8}\b/gi)) {+ const c = parseColor(m[0])+ if (c) out.push(c)+ }+ return out+}diff --git a/plugins/omo/skills/frontend/scripts/detect/core/page.ts b/plugins/omo/skills/frontend/scripts/detect/core/page.tsnew file mode 100644index 00000000..76385bdd--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/core/page.ts@@ -0,0 +1,84 @@+import type { ElementSnapshot, PageSnapshot } from "../types"+import { blend, parseColor, type Rgba, WHITE } from "./color"++export const IGNORE_ATTRIBUTES = ["data-detect-ignore", "data-impeccable-ignore"] as const++/** Numeric value of a computed length in px ("12px" -> 12, "normal"/"auto" -> null). */+export function px(value: string | undefined): number | null {+ if (value === undefined) return null+ const m = /^(-?\d*\.?\d+)px$/.exec(value.trim())+ return m?.[1] === undefined ? null : Number.parseFloat(m[1])+}++export const styleOf = (el: ElementSnapshot, prop: string): string => el.style[prop] ?? ""++export function parentOf(snap: PageSnapshot, el: ElementSnapshot): ElementSnapshot | null {+ return el.parent === null ? null : (snap.elements[el.parent] ?? null)+}++export function* ancestors(snap: PageSnapshot, el: ElementSnapshot): Generator<ElementSnapshot> {+ let cur = parentOf(snap, el)+ while (cur) {+ yield cur+ cur = parentOf(snap, cur)+ }+}++export function* descendants(snap: PageSnapshot, el: ElementSnapshot): Generator<ElementSnapshot> {+ for (const i of el.children) {+ const child = snap.elements[i]+ if (!child) continue+ yield child+ yield* descendants(snap, child)+ }+}++export const childrenOf = (snap: PageSnapshot, el: ElementSnapshot): readonly ElementSnapshot[] =>+ el.children.map((i) => snap.elements[i]).filter((c): c is ElementSnapshot => c !== undefined)++/** Rendered and not visually suppressed: has a box, is not display:none/visibility:hidden, and no ancestor has opacity 0. */+export function isRendered(snap: PageSnapshot, el: ElementSnapshot): boolean {+ if (el.rect.width <= 0 || el.rect.height <= 0) return false+ if (styleOf(el, "display") === "none" || styleOf(el, "visibility") === "hidden") return false+ if (Number.parseFloat(styleOf(el, "opacity")) === 0) return false+ for (const a of ancestors(snap, el)) if (Number.parseFloat(styleOf(a, "opacity")) === 0) return false+ return true+}++/** True when the element or an ancestor waives `ruleId` with data-detect-ignore (or upstream's data-impeccable-ignore). */+export function isIgnored(snap: PageSnapshot, el: ElementSnapshot, ruleId: string): boolean {+ const waives = (e: ElementSnapshot): boolean =>+ IGNORE_ATTRIBUTES.some((name) => {+ const v = e.attributes[name]+ if (v === undefined) return false+ const ids = v.split(/[\s,]+/).filter(Boolean)+ return ids.length === 0 || ids.includes(ruleId) || ids.includes("all")+ })+ if (waives(el)) return true+ for (const a of ancestors(snap, el)) if (waives(a)) return true+ return false+}++/** The opaque color painted behind `el`: its own and its ancestors' background-colors composited bottom-up over white. */+export function effectiveBackground(snap: PageSnapshot, el: ElementSnapshot): Rgba {+ const layers: Rgba[] = []+ for (const e of [el, ...ancestors(snap, el)]) {+ const c = parseColor(styleOf(e, "background-color"))+ if (c && c.a > 0) {+ layers.push(c)+ if (c.a >= 1) break+ }+ }+ return layers.reduceRight<Rgba>((under, top) => blend(top, under), WHITE)+}++const HEADING_TAGS = ["h1", "h2", "h3", "h4", "h5", "h6"] as const+export const isHeading = (el: ElementSnapshot): boolean => HEADING_TAGS.some((tag) => tag === el.tag)+export const headingLevel = (el: ElementSnapshot): number | null => (isHeading(el) ? Number(el.tag.slice(1)) : null)++export const textElements = (snap: PageSnapshot): readonly ElementSnapshot[] =>+ snap.elements.filter((el) => el.ownText !== "" && isRendered(snap, el))++export const fontSizePx = (el: ElementSnapshot): number => px(styleOf(el, "font-size")) ?? 16++export const shortSnippet = (el: ElementSnapshot): string => (el.text === "" ? `<${el.tag}>` : `<${el.tag}> ${el.text.slice(0, 80)}`)diff --git a/plugins/omo/skills/frontend/scripts/detect/core/shadow.ts b/plugins/omo/skills/frontend/scripts/detect/core/shadow.tsnew file mode 100644index 00000000..51ddcb75--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/core/shadow.ts@@ -0,0 +1,40 @@+import { parseColor, type Rgba } from "./color"++export type ShadowLayer = {+ readonly inset: boolean+ readonly color: Rgba+ readonly x: number+ readonly y: number+ readonly blur: number+ readonly spread: number+}++function splitLayers(value: string): readonly string[] {+ const layers: string[] = []+ let depth = 0+ let start = 0+ for (let i = 0; i < value.length; i++) {+ const ch = value[i]+ if (ch === "(") depth+++ else if (ch === ")") depth--+ else if (ch === "," && depth === 0) {+ layers.push(value.slice(start, i).trim())+ start = i + 1+ }+ }+ layers.push(value.slice(start).trim())+ return layers.filter(Boolean)+}++/** Parses a computed box-shadow or text-shadow value into layers; `none` yields no layers. */+export function parseShadow(value: string): readonly ShadowLayer[] {+ if (value.trim() === "" || value.trim() === "none") return []+ return splitLayers(value).flatMap((layer) => {+ const colorMatch = /(rgba?|color|oklab|oklch)\([^()]*\)|#[0-9a-f]{3,8}\b|\btransparent\b/i.exec(layer)+ const color = (colorMatch ? parseColor(colorMatch[0]) : null) ?? { r: 0, g: 0, b: 0, a: 1 }+ const rest = colorMatch ? layer.replace(colorMatch[0], " ") : layer+ const lengths = [...rest.matchAll(/(-?\d*\.?\d+)(px)?(?=\s|$)/g)].map((m) => Number.parseFloat(m[1] ?? "0"))+ if (lengths.length < 2) return []+ return [{ inset: /\binset\b/.test(rest), color, x: lengths[0] ?? 0, y: lengths[1] ?? 0, blur: lengths[2] ?? 0, spread: lengths[3] ?? 0 }]+ })+}diff --git a/plugins/omo/skills/frontend/scripts/detect/core/source.ts b/plugins/omo/skills/frontend/scripts/detect/core/source.tsnew file mode 100644index 00000000..d28acc77--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/core/source.ts@@ -0,0 +1,33 @@+import type { SourceHit } from "../rule"++export const extensionOf = (path: string): string => (/\.([a-z0-9]+)$/i.exec(path)?.[1] ?? "").toLowerCase()++/** 1-based line and column of a string offset. */+export function positionAt(text: string, offset: number): { readonly line: number; readonly column: number } {+ let line = 1+ let lineStart = 0+ for (let i = 0; i < offset && i < text.length; i++) {+ if (text.charCodeAt(i) === 10) {+ line+++ lineStart = i + 1+ }+ }+ return { line, column: offset - lineStart + 1 }+}++export function lineAt(text: string, offset: number): string {+ const start = text.lastIndexOf("\n", offset - 1) + 1+ const end = text.indexOf("\n", offset)+ return text.slice(start, end === -1 ? text.length : end).trim().slice(0, 160)+}++/** CSS declaration blocks of a stylesheet-like text: selector plus raw body, with the body's start offset. */+export function cssBlocks(text: string): readonly { readonly selector: string; readonly body: string; readonly offset: number }[] {+ const stripped = text.replace(/\/\*[\s\S]*?\*\//g, (c) => " ".repeat(c.length))+ const out: { selector: string; body: string; offset: number }[] = []+ for (const m of stripped.matchAll(/([^{};]+)\{([^{}]*)\}/g)) {+ if (m.index === undefined) continue+ out.push({ selector: (m[1] ?? "").trim(), body: m[2] ?? "", offset: m.index + (m[1] ?? "").length + 1 })+ }+ return out+}diff --git a/plugins/omo/skills/frontend/scripts/detect/detect.ts b/plugins/omo/skills/frontend/scripts/detect/detect.tsnew file mode 100644index 00000000..f538c754--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/detect.ts@@ -0,0 +1,77 @@+import { readFileSync } from "node:fs"+import { resolve } from "node:path"+import { pathToFileURL } from "node:url"+import { extensionOf } from "./core/source"+import { lintSnapshot, lintSources, sortFindings, type LintOptions } from "./lint"+import type { RenderTarget, Renderer } from "./render/renderer"+import { createWebViewRenderer } from "./render/webview"+import type { DetectConfig, Finding, Viewport } from "./types"++/** @public */+export const DEFAULT_VIEWPORTS: readonly Viewport[] = [+ { width: 1440, height: 900 },+ { width: 390, height: 844 },+]++/** StyleGallery's reflow matrix: every width, with an unbroken stress token added at the narrowest one. @public */+export const REFLOW_VIEWPORTS: readonly Viewport[] = [320, 375, 768, 1024, 1440].map((width) => ({ width, height: 800 }))++export type DetectPageOptions = LintOptions & {+ readonly viewports?: readonly Viewport[]+ /** Bring your own renderer (Playwright, omowright); defaults to a Bun.WebView renderer created and closed here. */+ readonly renderer?: Renderer+ /** Also render at REFLOW_VIEWPORTS with content stress at 320 px, feeding the viewport-reflow rule. */+ readonly reflow?: boolean+}++const PAGE_EXTENSIONS = new Set(["html", "htm"])++/** Renders a page at each viewport and lints every snapshot. */+export async function detectPage(target: RenderTarget, options: DetectPageOptions = {}): Promise<readonly Finding[]> {+ const renderer = options.renderer ?? createWebViewRenderer()+ try {+ const findings: Finding[] = []+ const passes = [+ ...(options.viewports ?? DEFAULT_VIEWPORTS).map((viewport) => ({ viewport, contentStress: false })),+ ...(options.reflow ? REFLOW_VIEWPORTS.map((viewport) => ({ viewport, contentStress: viewport.width === 320 })) : []),+ ]+ for (const pass of passes) {+ const snapshot = await renderer.render({ target, ...pass })+ findings.push(...lintSnapshot(snapshot, options))+ }+ return sortFindings(dedupe(findings))+ } finally {+ if (!options.renderer) await renderer.close()+ }+}++/** Lints files: HTML is rendered and checked as a page, everything else is checked as source text. */+export async function detectFiles(paths: readonly string[], options: DetectPageOptions = {}): Promise<readonly Finding[]> {+ const pages = paths.filter((p) => PAGE_EXTENSIONS.has(extensionOf(p)))+ const sources = paths.filter((p) => !PAGE_EXTENSIONS.has(extensionOf(p)))+ const findings: Finding[] = [...lintSources(sources.map((path) => ({ path, text: readFileSync(path, "utf8") })), options)]+ const renderer = options.renderer ?? createWebViewRenderer()+ try {+ for (const page of pages) {+ const url = pathToFileURL(resolve(page)).href+ findings.push(...(await detectPage({ kind: "url", url }, { ...options, renderer, file: page })))+ }+ } finally {+ if (!options.renderer) await renderer.close()+ }+ return sortFindings(findings)+}++/** The same rule on the same element at two viewports is one finding; the first viewport's location is kept. */+function dedupe(findings: readonly Finding[]): readonly Finding[] {+ const seen = new Set<string>()+ return findings.filter((f) => {+ const where = f.location.kind === "element" ? f.location.selector : f.location.kind === "source" ? `${f.location.line}:${f.location.column}` : "page"+ const key = `${f.ruleId}|${where}|${f.message}`+ if (seen.has(key)) return false+ seen.add(key)+ return true+ })+}++export type { DetectConfig }diff --git a/plugins/omo/skills/frontend/scripts/detect/index.ts b/plugins/omo/skills/frontend/scripts/detect/index.tsnew file mode 100644index 00000000..cf06a569--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/index.ts@@ -0,0 +1,23 @@+/** The frontend detect SDK's public API: everything below is for callers outside this repository (a skill script, a project's own lint step). */+/** @public */+export { blend, colorsIn, contrastRatio, luminance, parseColor, type Rgba } from "./core/color"+/** @public */+export { parseConfig } from "./config"+/** @public */+export { DEFAULT_VIEWPORTS, detectFiles, detectPage, type DetectPageOptions, REFLOW_VIEWPORTS } from "./detect"+/** @public */+export { effectiveSeverity, hasFailures, type LintOptions, lintSnapshot, lintSources, sortFindings } from "./lint"+/** @public */+export { formatFindingsText, summarize } from "./report"+/** @public */+export { RenderError, type RenderRequest, type RenderTarget, type Renderer } from "./render/renderer"+/** @public */+export { createWebViewRenderer } from "./render/webview"+export type { PageContext, PageHit, PageRule, Rule, SourceContext, SourceHit, SourceRule } from "./rule"+/** @public */+export { ALL_RULES } from "./rules"+/** @public */+export { collectPageSnapshot } from "./snapshot/collect"+/** @public */+export { STYLE_PROPS } from "./snapshot/style-props"+export type * from "./types"diff --git a/plugins/omo/skills/frontend/scripts/detect/lint.ts b/plugins/omo/skills/frontend/scripts/detect/lint.tsnew file mode 100644index 00000000..b2606921--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/lint.ts@@ -0,0 +1,98 @@+import { isIgnored } from "./core/page"+import { extensionOf } from "./core/source"+import type { PageRule, Rule, SourceRule } from "./rule"+import { ALL_RULES } from "./rules"+import type { DetectConfig, Finding, PageSnapshot, RuleMeta, Severity, SourceFile } from "./types"++export type LintOptions = {+ readonly config?: DetectConfig+ /** Rules to run; defaults to every built-in rule. */+ readonly rules?: readonly Rule[]+ /** File the snapshot was rendered from, carried into element locations. */+ readonly file?: string+}++/** Severity after the project's override, or null when the rule is switched off. @public */+export function effectiveSeverity(meta: RuleMeta, config: DetectConfig | undefined): Severity | null {+ const setting = config?.rules?.[meta.id]+ if (setting === "off") return null+ return setting ?? meta.severity+}++const isPageRule = (r: Rule): r is PageRule => r.meta.engine === "page"+const isSourceRule = (r: Rule): r is SourceRule => r.meta.engine === "source"++export function lintSnapshot(snapshot: PageSnapshot, options: LintOptions = {}): readonly Finding[] {+ const config = options.config ?? {}+ const findings: Finding[] = []+ for (const rule of (options.rules ?? ALL_RULES).filter(isPageRule)) {+ const severity = effectiveSeverity(rule.meta, config)+ if (severity === null) continue+ const overridden = config.rules?.[rule.meta.id] !== undefined+ for (const hit of rule.check({ snapshot, config })) {+ if (hit.element && isIgnored(snapshot, hit.element, rule.meta.id)) continue+ findings.push({+ ruleId: rule.meta.id,+ name: rule.meta.name,+ category: rule.meta.category,+ severity: hit.severityFixed && hit.severity ? hit.severity : overridden ? severity : (hit.severity ?? severity),+ message: hit.message,+ fixHint: rule.meta.fixHint,+ snippet: hit.snippet,+ location: hit.element+ ? { kind: "element", selector: hit.element.selector, rect: hit.element.rect, viewport: snapshot.viewport, ...(options.file ? { file: options.file } : {}) }+ : { kind: "page", viewport: snapshot.viewport, ...(options.file ? { file: options.file } : {}) },+ })+ }+ }+ return findings+}++export function lintSources(files: readonly SourceFile[], options: LintOptions = {}): readonly Finding[] {+ const config = options.config ?? {}+ const findings: Finding[] = []+ const rules = (options.rules ?? ALL_RULES).filter(isSourceRule)+ for (const file of files) {+ const ext = extensionOf(file.path)+ for (const rule of rules) {+ if (!rule.extensions.includes(ext)) continue+ const severity = effectiveSeverity(rule.meta, config)+ if (severity === null) continue+ for (const hit of rule.check({ file, config })) {+ findings.push({+ ruleId: rule.meta.id,+ name: rule.meta.name,+ category: rule.meta.category,+ severity,+ message: hit.message,+ fixHint: rule.meta.fixHint,+ snippet: hit.snippet,+ location: { kind: "source", file: file.path, line: hit.line, column: hit.column },+ })+ }+ }+ }+ return findings+}++const SEVERITY_ORDER: Readonly<Record<Severity, number>> = { error: 0, warning: 1, advisory: 2 }++export function sortFindings(findings: readonly Finding[]): readonly Finding[] {+ const key = (f: Finding): string => {+ const l = f.location+ switch (l.kind) {+ case "source":+ return `${l.file}:${String(l.line).padStart(8, "0")}:${String(l.column).padStart(6, "0")}`+ case "element":+ return `${l.file ?? ""}@${l.viewport.width}:${String(Math.round(l.rect.y)).padStart(8, "0")}:${l.selector}`+ case "page":+ return `${l.file ?? ""}@${l.viewport.width}`+ }+ }+ return [...findings].sort(+ (a, b) => key(a).localeCompare(key(b)) || SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity] || a.ruleId.localeCompare(b.ruleId),+ )+}++/** True when any finding is an error or a warning; advisories never fail a gate. */+export const hasFailures = (findings: readonly Finding[]): boolean => findings.some((f) => f.severity !== "advisory")diff --git a/plugins/omo/skills/frontend/scripts/detect/render/probe-placement.ts b/plugins/omo/skills/frontend/scripts/detect/render/probe-placement.tsnew file mode 100644index 00000000..a234f02b--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/render/probe-placement.ts@@ -0,0 +1,50 @@+const PROLOG_TAGS = ["!doctype", "html", "head"] as const++function skipBlankAndComments(html: string, from: number): number {+ let i = from+ for (;;) {+ while (i < html.length && /\s/.test(html.charAt(i))) i+++ const [open, close] = html.startsWith("<!--", i) ? ["<!--", "-->"] : html.startsWith("<?", i) ? ["<?", "?>"] : ["", ""]+ if (open === "") return i+ const end = html.indexOf(close, i + open.length)+ if (end === -1) return html.length+ i = end + close.length+ }+}++function tagEnd(html: string, from: number): number {+ let quote = ""+ for (let i = from; i < html.length; i++) {+ const c = html.charAt(i)+ if (quote !== "") {+ if (c === quote) quote = ""+ } else if (c === '"' || c === "'") quote = c+ else if (c === ">") return i + 1+ }+ return -1+}++function openingAt(html: string, at: number, name: string): boolean {+ if (html.charAt(at) !== "<" || html.slice(at + 1, at + 1 + name.length).toLowerCase() !== name) return false+ const next = html.charAt(at + 1 + name.length)+ return next === ">" || next === "/" || /\s/.test(next)+}++/**+ * Inserts `snippet` right after the document prolog (doctype, then the `<html>` and `<head>` openings, in that order,+ * with whitespace, comments and processing instructions such as `<?xml ...?>` between them), so it runs before any page script and never lands before the doctype,+ * inside a comment, inside an attribute value, or inside a later script. With no prolog it goes first.+ */+export function insertAfterProlog(html: string, snippet: string): string {+ let at = 0+ let next = 0+ for (const name of PROLOG_TAGS) {+ const start = skipBlankAndComments(html, next)+ if (!openingAt(html, start, name)) continue+ const end = tagEnd(html, start + 1 + name.length)+ if (end === -1) break+ at = end+ next = end+ }+ return `${html.slice(0, at)}${snippet}${html.slice(at)}`+}diff --git a/plugins/omo/skills/frontend/scripts/detect/render/renderer.ts b/plugins/omo/skills/frontend/scripts/detect/render/renderer.tsnew file mode 100644index 00000000..aa5951b3--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/render/renderer.ts@@ -0,0 +1,37 @@+import type { PageSnapshot, Viewport } from "../types"++export type RenderTarget = { readonly kind: "html"; readonly html: string } | { readonly kind: "url"; readonly url: string }++export type RenderRequest = {+ readonly target: RenderTarget+ readonly viewport: Viewport+ /** Appends an unbroken 300-character token to every element whose last child is text, to expose reflow breaks. */+ readonly contentStress?: boolean+}++/** Anything that can turn a page into a PageSnapshot: Bun.WebView by default, or a Playwright/omowright page you already drive. */+export type Renderer = {+ readonly render: (request: RenderRequest) => Promise<PageSnapshot>+ readonly close: () => Promise<void>+}++export class RenderError extends Error {+ readonly target: string+ constructor(target: string, cause: unknown) {+ super(`render failed for ${target}: ${cause instanceof Error ? cause.message : String(cause)}`, { cause })+ this.name = "RenderError"+ this.target = target+ }+}++const STRESS_TOKEN = "Unbrokencontentstresstoken".repeat(12)++export const CONTENT_STRESS_SCRIPT = `(() => {+ const token = ${JSON.stringify(STRESS_TOKEN)};+ for (const el of document.querySelectorAll("body *")) {+ const last = el.lastChild;+ if (!last || last.nodeType !== 3 || last.textContent.trim() === "") continue;+ if (["SCRIPT", "STYLE", "TEXTAREA", "OPTION", "TITLE"].includes(el.tagName)) continue;+ last.textContent = last.textContent + " " + token;+ }+})();`diff --git a/plugins/omo/skills/frontend/scripts/detect/render/webview.ts b/plugins/omo/skills/frontend/scripts/detect/render/webview.tsnew file mode 100644index 00000000..4f620231--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/render/webview.ts@@ -0,0 +1,71 @@+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"+import { tmpdir } from "node:os"+import { dirname, join } from "node:path"+import { fileURLToPath, pathToFileURL } from "node:url"+import { collectPageSnapshot, SCRIPT_ERROR_PROBE } from "../snapshot/collect"+import { STYLE_PROPS } from "../snapshot/style-props"+import type { PageSnapshot } from "../types"+import { insertAfterProlog } from "./probe-placement"+import { CONTENT_STRESS_SCRIPT, RenderError, type RenderRequest, type RenderTarget, type Renderer } from "./renderer"++const MAX_ELEMENTS = 20_000+const SETTLE_FRAMES = "new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)))))"++function withProbe(html: string, baseHref?: string): string {+ return insertAfterProlog(html, `${baseHref ? `<base href="${baseHref}">` : ""}<script>${SCRIPT_ERROR_PROBE}</script>`)+}++function isSnapshot(value: unknown): value is PageSnapshot {+ return typeof value === "object" && value !== null && Array.isArray(Reflect.get(value, "elements"))+}++/** A renderer backed by Bun.WebView (system WebKit on macOS, installed Chrome/Chromium elsewhere). One view per request. */+export function createWebViewRenderer(options: { readonly backend?: "webkit" | "chrome" } = {}): Renderer {+ const scratch = mkdtempSync(join(tmpdir(), "frontend-detect-"))+ let counter = 0+ const chrome = options.backend === "chrome" || (options.backend === undefined && process.platform !== "darwin")+ const writePage = (html: string, baseHref?: string): string => {+ const file = join(scratch, `page-${counter++}.html`)+ writeFileSync(file, withProbe(html, baseHref))+ return pathToFileURL(file).href+ }+ const open = async (view: Bun.WebView, target: RenderTarget): Promise<void> => {+ if (target.kind === "html") return view.navigate(writePage(target.html))+ if (chrome) {+ await view.navigate("about:blank")+ await view.cdp("Page.addScriptToEvaluateOnNewDocument", { source: SCRIPT_ERROR_PROBE })+ return view.navigate(target.url)+ }+ if (target.url.startsWith("file:")) {+ const path = fileURLToPath(target.url)+ return view.navigate(writePage(readFileSync(path, "utf8"), pathToFileURL(`${dirname(path)}/`).href))+ }+ return view.navigate(target.url)+ }+ return {+ async render(request: RenderRequest): Promise<PageSnapshot> {+ const label = request.target.kind === "url" ? request.target.url : "inline html"+ const view = new Bun.WebView({+ width: request.viewport.width,+ height: request.viewport.height,+ ...(options.backend ? { backend: options.backend } : {}),+ })+ try {+ await open(view, request.target)+ await view.evaluate("document.fonts ? document.fonts.ready.then(() => true) : true")+ await view.evaluate(SETTLE_FRAMES)+ if (request.contentStress) await view.evaluate(CONTENT_STRESS_SCRIPT)+ const snapshot: unknown = await view.evaluate(`(${collectPageSnapshot.toString()})(${JSON.stringify(STYLE_PROPS)}, ${MAX_ELEMENTS})`)+ if (!isSnapshot(snapshot)) throw new Error("the page did not return a snapshot")+ return snapshot+ } catch (error) {+ throw new RenderError(label, error)+ } finally {+ await view.close()+ }+ },+ async close(): Promise<void> {+ rmSync(scratch, { recursive: true, force: true })+ },+ }+}diff --git a/plugins/omo/skills/frontend/scripts/detect/report.ts b/plugins/omo/skills/frontend/scripts/detect/report.tsnew file mode 100644index 00000000..57cade89--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/report.ts@@ -0,0 +1,29 @@+import type { Finding, Severity } from "./types"++/** @public */+export function summarize(findings: readonly Finding[]): Readonly<Record<Severity, number>> {+ const counts: Record<Severity, number> = { error: 0, warning: 0, advisory: 0 }+ for (const f of findings) counts[f.severity]+++ return counts+}++function where(f: Finding): string {+ const l = f.location+ switch (l.kind) {+ case "source":+ return `${l.file}:${l.line}:${l.column}`+ case "element":+ return `${l.file ?? "page"} @${l.viewport.width}px ${l.selector}`+ case "page":+ return `${l.file ?? "page"} @${l.viewport.width}px`+ }+}++export function formatFindingsText(findings: readonly Finding[]): string {+ const lines = findings.map(+ (f) => `${where(f)} ${f.severity} ${f.ruleId} ${f.message}\n > ${f.snippet}\n fix: ${f.fixHint}`,+ )+ const c = summarize(findings)+ lines.push(`frontend-detect: ${findings.length} finding(s): ${c.error} error, ${c.warning} warning, ${c.advisory} advisory`)+ return `${lines.join("\n")}\n`+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rule.ts b/plugins/omo/skills/frontend/scripts/detect/rule.tsnew file mode 100644index 00000000..669d61b7--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rule.ts@@ -0,0 +1,42 @@+import type { DetectConfig, ElementSnapshot, PageSnapshot, RuleMeta, Severity, SourceFile } from "./types"++export type PageHit = {+ readonly element: ElementSnapshot | null+ readonly message: string+ readonly snippet: string+ /** Overrides the rule's default severity for this hit; a project override in config.rules still wins. */+ readonly severity?: Severity+ /** Keeps `severity` even when the project overrides the rule's severity in config.rules (a rule set to "off" still drops the hit). For notices about missing evidence, which an override must not turn into a failure. */+ readonly severityFixed?: boolean+}++export type PageContext = {+ readonly snapshot: PageSnapshot+ readonly config: DetectConfig+}++export type PageRule = {+ readonly meta: RuleMeta & { readonly engine: "page" }+ readonly check: (ctx: PageContext) => readonly PageHit[]+}++export type SourceHit = {+ readonly line: number+ readonly column: number+ readonly message: string+ readonly snippet: string+}++export type SourceContext = {+ readonly file: SourceFile+ readonly config: DetectConfig+}++export type SourceRule = {+ readonly meta: RuleMeta & { readonly engine: "source" }+ /** File extensions (without the dot) this rule reads, e.g. ["css", "scss", "tsx"]. */+ readonly extensions: readonly string[]+ readonly check: (ctx: SourceContext) => readonly SourceHit[]+}++export type Rule = PageRule | SourceRulediff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/ai-color-palette.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/ai-color-palette.tsnew file mode 100644index 00000000..d6e9fff0--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/ai-color-palette.ts@@ -0,0 +1,83 @@+import { luminance, parseColor, toHsl, type Rgba } from "../../core/color"+import { ancestors, childrenOf, fontSizePx, isIgnored, shortSnippet, styleOf } from "../../core/page"+import type { PageHit, PageRule } from "../../rule"+import type { ElementSnapshot, PageSnapshot } from "../../types"+import { backdrop, colorDistance, gradientStops, opacity, sameColor, spread } from "./support/gradients"+import { brandColor, categoryColor, paletteVisible, tellHue } from "./support/palette-roles"+import { clipsText } from "./support/text-colors"+import { gradientSamples } from "./support/gradient-samples"+import { stockAccent } from "./support/stock-accent"+import { textPainted } from "./support/painted-text"+import { bareText } from "./support/color-path"++function highlighted(snapshot: PageSnapshot, el: ElementSnapshot): boolean {+ if (!/mono|consolas|courier/i.test(styleOf(el, "font-family")) || !["pre", "pre-wrap", "break-spaces"].includes(styleOf(el, "white-space")) || !styleOf(el, "display").startsWith("inline")) return false+ const parent = el.parent === null ? undefined : snapshot.elements[el.parent]+ const ink = parseColor(styleOf(el, "color"))+ if (!parent || !ink) return false+ return [parent, ...childrenOf(snapshot, parent)].some((node) => {+ if (node === el || node.ownText.trim() === "" || (node !== parent && !styleOf(node, "display").startsWith("inline")) || !paletteVisible(snapshot, node) || opacity(node) === 0) return false+ const c = parseColor(styleOf(node, "color"))+ return c !== null && c.a > 0 && (Math.abs(c.r - ink.r) + Math.abs(c.g - ink.g) + Math.abs(c.b - ink.b) > 24 || Math.abs(c.a - ink.a) > 0.1)+ })+}++function covered(snapshot: PageSnapshot, el: ElementSnapshot): boolean {+ return childrenOf(snapshot, el).some((child) => {+ if (!["img", "video"].includes(child.tag) || !paletteVisible(snapshot, child) || styleOf(child, "object-fit") === "contain") return false+ const a = el.rect+ const b = child.rect+ return opacity(child) >= 0.95 && b.x <= a.x + 1 && b.y <= a.y + 1 && b.x + b.width >= a.x + a.width - 1 && b.y + b.height >= a.y + a.height - 1+ })+}++export const aiColorPalette: PageRule = {+ meta: {+ id: "ai-color-palette", name: "AI color palette", category: "slop", severity: "warning", engine: "page",+ description: "Stock violet and cyan ramps or paired neon inks replace an intentional palette.",+ fixHint: "Choose a distinctive palette and declare its colors as design tokens.",+ },+ check: ({ snapshot, config }) => {+ const allowed = config.designTokens?.colors?.map(parseColor).filter((c) => c !== null) ?? []+ const declared = (c: Rgba): boolean => allowed.some((token) => colorDistance(c, token) <= 6)+ const purpleDeclared = allowed.some((c) => tellHue(c) === "purple")+ const hits: PageHit[] = []+ const neon: { readonly el: ElementSnapshot; readonly hue: string }[] = []+ const tells = new Set<string>()+ for (const el of snapshot.elements) {+ if (!paletteVisible(snapshot, el) || !textPainted(snapshot, el) || isIgnored(snapshot, el, "ai-color-palette")) continue+ const image = styleOf(el, "background-image")+ const stops = gradientStops(image).map((s) => s.color)+ const first = stops[0]+ const blurred = [el, ...ancestors(snapshot, el)].some((node) => [...styleOf(node, "filter").matchAll(/blur\(([\d.]+)px\)/g)].some((m) => Number(m[1]) >= 24))+ const samples = gradientSamples(el, el.rect)+ const flat = first !== undefined && (stops.every((c) => colorDistance(c, first) === 0 && c.a === first.a) || (stops.every((c) => colorDistance(c, first) === 0) && stops.every((c) => c.a >= 0.75)) || (samples !== null && samples.length > 0 && samples.every((c) => samples[0] !== undefined && sameColor(c, samples[0]))))+ if (first && stops.length >= 2 && !flat && !blurred && !clipsText(el) && Math.min(el.rect.width, el.rect.height) >= 8 && el.rect.width * el.rect.height >= 256 && !covered(snapshot, el)) {+ const painted = stops.filter((c) => !declared(c) && c.a * opacity(el) >= 0.15 && spread(c) > 50)+ const bands = painted.map(tellHue).filter((h) => h !== null && !(h === "purple" && purpleDeclared))+ const bridge = painted.filter((c) => toHsl(c).h > 197 && toHsl(c).h < 260).length+ if (bands.length > 0 && bands.length * 2 >= painted.length && (bands.includes("purple") || bands.length * 2 > painted.length || bridge >= painted.length - bands.length)) {+ if (!categoryColor(snapshot, el, true)) {+ for (const band of bands) if (band) tells.add(band)+ hits.push({ element: el, message: "Stock violet or cyan gradient background", snippet: shortSnippet(el) })+ }+ }+ }+ const ink = parseColor(styleOf(el, "color"))+ if (!ink || declared(ink) || el.ownText.trim().length < 2 || highlighted(snapshot, el)) continue+ const band = tellHue(ink)+ if (!bareText(el) && band === "purple" && !purpleDeclared && spread(ink) > 50 && (["h1", "h2", "h3"].includes(el.tag) || (fontSizePx(el) >= 20 && toHsl(ink).s >= 0.3)) && !brandColor(snapshot, ink) && !categoryColor(snapshot, el, false)) {+ hits.push({ element: el, message: "Violet text on a heading", snippet: shortSnippet(el) })+ }+ const parent = el.parent === null ? undefined : snapshot.elements[el.parent]+ const ground = parent ? backdrop(snapshot, parent) : null+ if (band && !(band === "purple" && purpleDeclared) && ink.a * opacity(el) >= 0.15 && spread(ink) > 80 && ground && luminance(ground) < 0.1 && !categoryColor(snapshot, el, false)) {+ tells.add(band)+ neon.push({ el, hue: band })+ }+ }+ if (tells.size >= 2) for (const { el } of neon) if (!categoryColor(snapshot, el, false)) hits.push({ element: el, message: "Neon text paired with another stock palette hue on dark", snippet: shortSnippet(el) })+ if (!purpleDeclared && stockAccent(snapshot)) hits.push({ element: null, message: "Stock violet accent colors appear on the page", snippet: "Stock violet accent" })+ return hits+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/cream-palette.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/cream-palette.tsnew file mode 100644index 00000000..083214a4--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/cream-palette.ts@@ -0,0 +1,35 @@+import { parseColor, type Rgba } from "../../core/color"+import { isRendered, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"++const cream = (c: Rgba | null): boolean => c !== null && Math.min(c.r, c.g, c.b) >= 209 && c.r >= c.g && c.g >= c.b && c.r - c.b >= 6 && c.r - c.b <= 48+const CREAM_CLASSES = ["bg-amber-50", "bg-orange-50", "bg-yellow-50", "bg-orange-100"] as const++export const creamPalette: PageRule = {+ meta: {+ id: "cream-palette", name: "Cream / beige palette", category: "slop", severity: "warning", engine: "page",+ description: "The page defaults to a warm cream or beige ground.",+ fixHint: "Choose a page surface that follows the project's palette.",+ },+ check: ({ snapshot }) => {+ const body = snapshot.elements.find((el) => el.tag === "body")+ const html = snapshot.elements.find((el) => el.tag === "html")+ if (!body) return []+ let fill = parseColor(styleOf(body, "background-color"))+ if (!fill || fill.a === 0) fill = html ? parseColor(styleOf(html, "background-color")) : null+ const classes = [body, html].flatMap((el) => (el?.attributes["class"] ?? "").split(/\s+/))+ const classCream = classes.some((c) => CREAM_CLASSES.some((known) => known === c) || (c.startsWith("bg-[") && cream(parseColor(c.slice(4, -1).replaceAll("_", " ")))))+ if (!cream(fill) && !classCream) return []+ const bands = snapshot.elements.filter((el) => el !== body && el !== html && isRendered(snapshot, el) && el.rect.width >= snapshot.viewport.width * 0.9)+ const covering = bands.filter((el) => {+ const c = parseColor(styleOf(el, "background-color"))+ return c !== null && c.a >= 0.95 && el.rect.height >= snapshot.viewport.height * 0.9+ }).sort((a, b) => b.rect.width * b.rect.height - a.rect.width * a.rect.height)[0]+ if (covering) {+ const c = parseColor(styleOf(covering, "background-color"))+ const near = c !== null && Math.min(c.r, c.g, c.b) >= 209 && c.r >= c.g && c.g >= c.b && c.r - c.b >= 2 && c.r - c.b <= 48+ if (!cream(c) && !near && !bands.some((el) => cream(parseColor(styleOf(el, "background-color"))))) return []+ }+ return [{ element: body, message: "The page uses a cream or beige background", snippet: "<body>" }]+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/dark-glow.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/dark-glow.tsnew file mode 100644index 00000000..6daee53f--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/dark-glow.ts@@ -0,0 +1,44 @@+import { luminance, toHsl } from "../../core/color"+import { isRendered, shortSnippet, styleOf } from "../../core/page"+import { parseShadow } from "../../core/shadow"+import type { PageRule } from "../../rule"+import { backdrop, colorDistance, opacity, spread } from "./support/gradients"+import { glowForm } from "./support/glow-forms"+import { textBackgrounds } from "./support/text-colors"++export const darkGlow: PageRule = {+ meta: {+ id: "dark-glow", name: "Glowing shadow accents", category: "slop", severity: "warning", engine: "page",+ description: "A colored blurred shadow reads as a decorative glow.",+ fixHint: "Use a neutral elevation shadow or remove the halo.",+ },+ check: ({ snapshot }) => {+ const hits = snapshot.elements.flatMap((el) => {+ if (!isRendered(snapshot, el)) return []+ const parent = el.parent === null ? el : snapshot.elements[el.parent] ?? el+ const grounds = textBackgrounds(snapshot, { ...el, lineRects: [el.rect], style: { ...el.style, "background-color": "transparent", "background-image": "none" } })+ const surface = grounds[0] ?? backdrop(snapshot, parent)+ const dark = surface !== null && luminance(surface) < 0.1+ return ["box-shadow", "text-shadow"].flatMap((property) => {+ const value = styleOf(el, property)+ if (property === "text-shadow" && parent !== el && value === styleOf(parent, property)) return []+ const layers = parseShadow(value)+ const lift = surface === null ? null : layers.reduce((sum, layer) => {+ if (spread(layer.color) <= 30 || layer.blur * layer.color.a * opacity(el) < 1.5) return sum+ const hueDelta = Math.abs(toHsl(layer.color).h - toHsl(surface).h)+ const shade = (layer.x !== 0 || layer.y !== 0) && toHsl(layer.color).l < 0.25 && luminance(layer.color) < luminance(surface) && spread(surface) > 30 && Math.min(hueDelta, 360 - hueDelta) <= 50+ return sum + (shade ? 0 : 0.5 * layer.color.a * opacity(el) * colorDistance(layer.color, surface))+ }, 0)+ const hit = layers.find((layer) => {+ const extent = layer.blur / 2 + layer.spread+ const area = el.rect.width * el.rect.height+ const lit = (el.rect.width + 2 * extent) * (el.rect.height + 2 * extent) - area+ return !layer.inset && spread(layer.color) > 30 && layer.blur > 4 && extent > 0 && layer.blur * layer.color.a * opacity(el) >= 3 && lit <= area * 2 && (lift === null || lift >= 20) && ((layer.x === 0 && layer.y === 0) || dark)+ })+ return hit ? [{ element: el, message: `${property} creates a colored glow`, snippet: shortSnippet(el) }] : []+ })+ })+ const page = glowForm(snapshot, hits)+ return page ? [...hits, page] : hits+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/design-system-color.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/design-system-color.tsnew file mode 100644index 00000000..4bad9d76--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/design-system-color.ts@@ -0,0 +1,35 @@+import { parseColor } from "../../core/color"+import { isRendered, px, shortSnippet, styleOf } from "../../core/page"+import type { PageHit, PageRule } from "../../rule"+import { colorDistance } from "./support/gradients"++export const designSystemColor: PageRule = {+ meta: {+ id: "design-system-color", name: "Color outside DESIGN.md", category: "quality", severity: "advisory", engine: "page",+ description: "A painted color is outside the project's declared palette.",+ fixHint: "Use a declared color token or add the intentional color to the palette.",+ },+ check: ({ snapshot, config }) => {+ const tokens = config.designTokens?.colors?.map(parseColor).filter((c) => c !== null) ?? []+ if (tokens.length === 0) return []+ const seen = new Set<string>()+ const hits: PageHit[] = []+ for (const el of snapshot.elements) {+ if (!isRendered(snapshot, el) || ["head", "title", "meta", "link", "style", "script", "noscript", "template", "source"].includes(el.tag)) continue+ const props = ["background-color"]+ if (el.ownText.trim() !== "") props.push("color")+ for (const side of ["top", "right", "bottom", "left"]) if ((px(styleOf(el, `border-${side}-width`)) ?? 0) > 0) props.push(`border-${side}-color`)+ if ((px(styleOf(el, "outline-width")) ?? 0) > 0) props.push("outline-color")+ for (const prop of props) {+ const raw = styleOf(el, prop)+ const c = parseColor(raw)+ if (!c || c.a <= 0.05 || tokens.some((token) => colorDistance(c, token) <= 6)) continue+ const key = `${prop}:${raw}`+ if (seen.has(key)) continue+ seen.add(key)+ hits.push({ element: el, message: `${prop} ${raw} is outside the declared palette`, snippet: shortSnippet(el) })+ }+ }+ return hits+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/gradient-text.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/gradient-text.tsnew file mode 100644index 00000000..20ddaa5f--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/gradient-text.ts@@ -0,0 +1,59 @@+import { parseColor } from "../../core/color"+import { isRendered, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import type { ElementSnapshot, PageSnapshot } from "../../types"+import { effectiveOpacity, gradientStops, sameColor } from "./support/gradients"+import { clipsText } from "./support/text-colors"+import { textPainted } from "./support/painted-text"+import { bareText } from "./support/color-path"++function shimmer(snapshot: PageSnapshot, el: ElementSnapshot): boolean {+ const stops = gradientStops(styleOf(el, "background-image"))+ const first = stops[0]+ const last = stops.at(-1)+ const ink = parseColor(styleOf(el, "color"))+ if (!first || !last || !ink || stops.length < 3 || !sameColor(first.color, ink) || !sameColor(last.color, ink)) return false+ let plateau = 0+ for (let i = 1; i < stops.length; i++) {+ const a = stops[i - 1]+ const b = stops[i]+ if (a && b && a.position !== null && b.position !== null && sameColor(a.color, ink) && sameColor(b.color, ink)) plateau += b.position - a.position+ }+ if (plateau < 0.5 || Number.parseFloat(styleOf(el, "background-size")) <= 100 || !styleOf(el, "background-size").split(/\s+/)[0]?.endsWith("%")) return false+ if (styleOf(el, "animation-play-state") === "paused") return false+ return styleOf(el, "animation-iteration-count").includes("infinite") && styleOf(el, "animation-name").split(",").some((name) =>+ name.trim() !== "none" && snapshot.cssText.some((css) => {+ const start = css.indexOf(`@keyframes ${name.trim()}`)+ if (start < 0) return false+ const open = css.indexOf("{", start)+ let depth = 0+ for (let i = open; i < css.length; i++) {+ if (css[i] === "{") depth+++ if (css[i] === "}") depth--+ if (depth === 0) return /background-position/.test(css.slice(open, i))+ }+ return false+ }))+}++export const gradientText: PageRule = {+ meta: {+ id: "gradient-text", name: "Gradient text", category: "slop", severity: "warning", engine: "page",+ description: "A color ramp clipped to text adds decoration to the glyphs.",+ fixHint: "Use a solid text color to keep the emphasis readable.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap((el) => {+ if (!isRendered(snapshot, el) || !textPainted(snapshot, el) || el.text.trim() === "") return []+ if (bareText(el)) return []+ const tokens = (el.attributes["class"] ?? "").split(/\s+/)+ if (!clipsText(el)) return tokens.includes("bg-clip-text") && tokens.some((token) => /^bg-gradient-to-/.test(token))+ ? [{ element: el, message: "Utility classes declare a gradient text treatment", snippet: shortSnippet(el) }] : []+ if ([styleOf(el, "background-clip"), styleOf(el, "-webkit-background-clip")].every((v) => v !== "text")) return []+ const image = styleOf(el, "background-image")+ const stops = gradientStops(image)+ const first = stops[0]+ if (!first || !image.includes("gradient") || stops.every((s) => sameColor(s.color, first.color))) return []+ if (Math.max(...stops.map((s) => s.color.a)) * effectiveOpacity(snapshot, el) < 0.15 || shimmer(snapshot, el)) return []+ return [{ element: el, message: "A gradient paints the text", snippet: shortSnippet(el) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/gray-on-color.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/gray-on-color.tsnew file mode 100644index 00000000..58048f84--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/gray-on-color.ts@@ -0,0 +1,38 @@+import { luminance, parseColor, toHsl, type Rgba } from "../../core/color"+import { shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { oklch, spread } from "./support/gradients"+import { clipsText, textBackgrounds, textInk } from "./support/text-colors"+import { bareText } from "./support/color-path"+import { textPainted } from "./support/painted-text"++function colored(bg: Rgba): boolean {+ const lum = luminance(bg)+ const scale = lum >= 0.01 ? 1 : Math.sqrt(0.01 / Math.max(lum, 0.0001))+ const perceptual = oklch(bg)+ return spread(bg) > 40 * scale && (perceptual.l < 0.9 || perceptual.c >= 0.09)+}++export const grayOnColor: PageRule = {+ meta: {+ id: "gray-on-color", name: "Gray text on colored background", category: "quality", severity: "warning", engine: "page",+ description: "Mid-gray ink loses clarity on a chromatic surface.",+ fixHint: "Use a dark shade of the surface hue or a contrasting near-white ink.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap((el) => {+ if (!textPainted(snapshot, el) || bareText(el) || clipsText(el)) return []+ const color = parseColor(styleOf(el, "color"))+ if (!color) return []+ const hsl = toHsl(color)+ const gray = hsl.s < 0.2 && hsl.l > 0.3 && hsl.l < 0.85+ const tokens = (el.attributes["class"] ?? "").split(/\s+/)+ const grayClass = tokens.some((t) => /^text-(gray|slate|zinc|neutral|stone)-[1-6]00(?:\/\d+)?$/.test(t))+ const bgClass = tokens.some((t) => /^bg-(red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-([2-9]00|950)(?:\/\d+)?$/.test(t))+ const classHit = grayClass && bgClass && hsl.l < 0.85 && spread(color) <= 50+ const backgrounds = textBackgrounds(snapshot, el)+ const computedHit = textInk(snapshot, el) !== null && gray && backgrounds.length > 0 && backgrounds.every(colored)+ if (!classHit && !computedHit) return []+ const hit = { element: el, message: "Gray ink on a colored surface", snippet: shortSnippet(el) }+ return classHit && computedHit ? [hit, hit] : [hit]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/index.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/index.tsnew file mode 100644index 00000000..141fd3de--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/index.ts@@ -0,0 +1,15 @@+import type { PageRule } from "../../rule"+import { aiColorPalette } from "./ai-color-palette"+import { creamPalette } from "./cream-palette"+import { darkGlow } from "./dark-glow"+import { designSystemColor } from "./design-system-color"+import { gradientText } from "./gradient-text"+import { grayOnColor } from "./gray-on-color"+import { lowContrast } from "./low-contrast"+import { radialHalo } from "./radial-halo"+import { radialSpotlightGlow } from "./radial-spotlight-glow"++export const COLOR_RULES: readonly PageRule[] = [+ lowContrast, grayOnColor, aiColorPalette, creamPalette, gradientText,+ darkGlow, radialHalo, radialSpotlightGlow, designSystemColor,+]diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/low-contrast.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/low-contrast.tsnew file mode 100644index 00000000..d0fa2362--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/low-contrast.ts@@ -0,0 +1,57 @@+import { blend, contrastRatio } from "../../core/color"+import { ancestors, fontSizePx, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { distinctPairs, type ContrastHit } from "./support/contrast-pairs"+import { gradientStops } from "./support/gradients"+import { textPainted } from "./support/painted-text"+import { bareText } from "./support/color-path"+import { contrastRole } from "./support/contrast-role"+import { mockupRoots } from "./support/mockup-roots"+import { placeholderContrast } from "./support/placeholder-contrast"+import { clipsText, solidGround, textBackgrounds, textInk } from "./support/text-colors"++export const lowContrast: PageRule = {+ meta: {+ id: "low-contrast", name: "Low contrast text", category: "quality", severity: "error", engine: "page",+ description: "Text falls below the WCAG AA contrast ratio for its size.",+ fixHint: "Increase text and surface contrast to 4.5:1, or 3:1 for large text.",+ },+ check: ({ snapshot }) => {+ const mockups = mockupRoots(snapshot)+ const text = distinctPairs(snapshot, snapshot.elements.flatMap((el): readonly ContrastHit[] => {+ if ([el, ...ancestors(snapshot, el)].some((node) => mockups.get(node.index) === "declared")) return []+ if (!textPainted(snapshot, el)) return []+ if ([el, ...ancestors(snapshot, el)].some((node) => node.attributes["disabled"] !== undefined || node.attributes["aria-disabled"] === "true")) return []+ const size = fontSizePx(el)+ if (bareText(el) && size < 9) return []+ const familyWords = (styleOf(el, "font-family").split(",")[0] ?? "").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/)+ const namedBold = familyWords.some((w) => ["bold", "semibold", "demibold", "extrabold", "ultrabold", "heavy", "black"].includes(w))+ const weight = namedBold ? Math.max(700, Number.parseFloat(styleOf(el, "font-weight")) || 400) : Number.parseFloat(styleOf(el, "font-weight"))+ const threshold = size >= 24 || (size >= 18.66 && weight >= 700) ? 3 : 4.5+ if (clipsText(el) && el.ownText.trim() !== "") {+ const stops = gradientStops(styleOf(el, "background-image"))+ if (stops.length === 0 || stops.some((s) => s.color.a < 0.999)) return []+ const ground = solidGround(snapshot, el)+ const best = Math.max(...stops.map((s) => contrastRatio(s.color, ground)))+ return best < threshold ? [{ element: el, pair: JSON.stringify([stops, ground, threshold]), message: `Gradient text contrast ${best.toFixed(2)}:1; needs ${threshold}:1`, snippet: shortSnippet(el) }] : []+ }+ const ink = textInk(snapshot, el)+ if (!ink) return []+ const backgrounds = textBackgrounds(snapshot, el)+ if (backgrounds.length === 0) return []+ const ratios = backgrounds.map((bg) => contrastRatio(blend(ink, bg), bg))+ const ratio = Math.min(...ratios)+ if (ratio === 1 && ![el, ...ancestors(snapshot, el)].some((node) =>+ ["a", "button", "input", "select", "textarea"].includes(node.tag) || ["button", "link"].includes(node.attributes["role"] ?? ""))) return []+ const control = [el, ...ancestors(snapshot, el)].find((node) => node.tag === "button" || node.attributes["role"] === "button")+ if (ratio === 1 && control && control.children.length > 1 && control.text.trim() === el.text.trim()) return []+ const shape = size >= 96 && ink.a < 0.25 ? el.text : [el, ...ancestors(snapshot, el)].some((node) => mockups.get(node.index) === "labelled") ? "decorative" : contrastRole(snapshot, el)+ const gradient = bareText(el) ? ancestors(snapshot, el).find((node) => !clipsText(node) && styleOf(node, "background-image").includes("gradient")) : undefined+ const ground = backgrounds[ratios.indexOf(ratio)]+ const pair = gradient ? JSON.stringify([ink, gradient.index, shape]) : JSON.stringify([ink, ground, threshold, shape])+ return ratio < threshold ? [{ element: el, pair, message: `Text contrast ${ratio.toFixed(2)}:1; needs ${threshold}:1`, snippet: shortSnippet(el) }] : []+ }))+ return [...text, ...snapshot.elements.flatMap((el) =>+ [el, ...ancestors(snapshot, el)].some((node) => mockups.get(node.index) === "declared") ? [] : placeholderContrast(snapshot, el))]+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/radial-halo.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/radial-halo.tsnew file mode 100644index 00000000..5c273c4a--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/radial-halo.ts@@ -0,0 +1,31 @@+import { luminance, parseColor } from "../../core/color"+import { isRendered, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { backdrop, gradientStops, splitLayers, spread } from "./support/gradients"+import { darkBackground } from "../source/support/css-effects"++export const radialHalo: PageRule = {+ meta: {+ id: "radial-halo", name: "Radial-gradient background halo", category: "slop", severity: "warning", engine: "page",+ description: "A saturated radial fade decorates a dark surface with a halo.",+ fixHint: "Ground the section with a solid or subtly shifted background.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap((el) => {+ if (!isRendered(snapshot, el)) return []+ const body = snapshot.elements.find((node) => node.tag === "body")+ const root = body ? parseColor(styleOf(body, "background-color")) : null+ if (root && root.a > 0.5 && luminance(root) >= 0.1 && !snapshot.cssText.some(darkBackground)) return []+ const surface = backdrop(snapshot, el, "none")+ if (!surface || luminance(surface) >= 0.1) return []+ const styles = [el.style, el.before?.style, el.after?.style].filter((s) => s !== undefined)+ const halo = styles.some((style) => splitLayers(style["background-image"] ?? "").some((layer) => {+ if (!layer.startsWith("radial-gradient(")) return false+ const stops = gradientStops(layer)+ const first = stops[0]+ const last = stops.at(-1)+ if (!first || !last || stops.some((s) => /(?:^|\s)(-?\d*\.?\d+)px/.test(s.raw) && Math.abs(Number.parseFloat(s.raw.slice(s.raw.lastIndexOf(" ") + 1))) <= 24)) return false+ return first.color.a >= 0.7 && spread(first.color) >= 24 && last.color.a <= 0.05 && luminance(first.color) > luminance(surface)+ }))+ return halo ? [{ element: el, message: "Chromatic radial halo on a dark surface", snippet: shortSnippet(el) }] : []+ }).slice(0, 1),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/radial-spotlight-glow.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/radial-spotlight-glow.tsnew file mode 100644index 00000000..404b87eb--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/radial-spotlight-glow.ts@@ -0,0 +1,33 @@+import { blend, contrastRatio } from "../../core/color"+import { isRendered, shortSnippet, styleOf, textElements } from "../../core/page"+import type { PageRule } from "../../rule"+import { backdrop, effectiveOpacity, gradientStops, splitLayers, spread } from "./support/gradients"++export const radialSpotlightGlow: PageRule = {+ meta: {+ id: "radial-spotlight-glow", name: "Decorative radial spotlight glow", category: "slop", severity: "warning", engine: "page",+ description: "A translucent radial accent floats behind a section's copy.",+ fixHint: "Remove the floating wash or use a deliberate material surface.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap((el) => {+ if (!isRendered(snapshot, el) || el.rect.width < 240 || el.rect.height < 160) return []+ const layers = splitLayers(styleOf(el, "background-image"))+ const index = layers.findIndex((layer) => layer.startsWith("radial-gradient("))+ if (index < 0) return []+ const stops = gradientStops(layers[index] ?? "")+ const last = stops.at(-1)+ const colors = stops.filter((s) => s.color.a > 0.05)+ if (!last || last.color.a > 0.05 || colors.length === 0 || colors.length > 2 || colors.some((s) => s.color.a >= 0.45)) return []+ const surface = backdrop(snapshot, el, layers.slice(index + 1).join(", "))+ const prominent = colors.some((s) => {+ const a = s.color.a * effectiveOpacity(snapshot, el)+ return spread(s.color) > 24 && a >= 0.14 && (surface === null || contrastRatio(blend({ ...s.color, a }, surface), surface) >= 1.3)+ })+ if (!prominent) return []+ const behindText = textElements(snapshot).some((text) => {+ const r = text.rect+ return r.x < el.rect.x + el.rect.width && r.x + r.width > el.rect.x && r.y < el.rect.y + el.rect.height && r.y + r.height > el.rect.y+ })+ return behindText ? [{ element: el, message: "A radial spotlight glows behind text", snippet: shortSnippet(el) }] : []+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/animation-opacity.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/animation-opacity.tsnew file mode 100644index 00000000..79d439bc--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/animation-opacity.ts@@ -0,0 +1,78 @@+import { ancestors, styleOf } from "../../../core/page"+import { cssBlocks } from "../../../core/source"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { opacity } from "./gradients"++function opacityFrames(snapshot: PageSnapshot, name: string): readonly { readonly at: number; readonly opacity: number }[] {+ const frames: { at: number; opacity: number }[] = []+ for (const css of snapshot.cssText) {+ const marker = new RegExp(`@(?:-webkit-)?keyframes\\s+${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*\\{`).exec(css)+ if (!marker || marker.index === undefined) continue+ const open = marker.index + marker[0].length - 1+ let depth = 1+ let end = open + 1+ for (; end < css.length && depth > 0; end++) {+ if (css[end] === "{") depth+++ if (css[end] === "}") depth--+ }+ for (const block of cssBlocks(css.slice(open + 1, end - 1))) {+ const value = /(?:^|;)\s*opacity\s*:\s*([\d.]+)/.exec(block.body)+ if (!value) continue+ for (const selector of block.selector.split(",")) {+ const at = selector.trim() === "to" ? 100 : selector.trim() === "from" ? 0 : Number.parseFloat(selector)+ if (Number.isFinite(at)) frames.push({ at, opacity: Number(value[1]) })+ }+ }+ }+ return frames.sort((a, b) => a.at - b.at)+}++function settled(snapshot: PageSnapshot, node: ElementSnapshot): number {+ let value = opacity(node)+ const names = styleOf(node, "animation-name").split(",").map((n) => n.trim())+ const entries = names.flatMap((name, index) => {+ const frames = !name || name === "none" ? [] : opacityFrames(snapshot, name)+ return frames.length ? [{ name, index, frames }] : []+ })+ const at = (property: string, index: number, missing: string): string => {+ const list = styleOf(node, property).split(",").map((n) => n.trim())+ return list[index % list.length] || missing+ }+ for (const entry of entries) {+ const count = at("animation-iteration-count", entry.index, "1")+ const paused = at("animation-play-state", entry.index, "running") === "paused"+ const composition = at("animation-composition", entry.index, "replace")+ const vanishes = entry.frames.some((frame) => frame.opacity <= 0.1)+ if (count === "infinite" && paused && value < 0.999 && composition === "replace" && vanishes) return 0+ }+ if (node.motion.includes("opacity")) {+ const entry = entries.length === 1 ? entries[0] : undefined+ if (!entry) return 0+ const count = Number(at("animation-iteration-count", entry.index, "1"))+ const fill = at("animation-fill-mode", entry.index, "none")+ const composition = at("animation-composition", entry.index, "replace")+ const duration = at("animation-duration", entry.index, "0s")+ const delay = at("animation-delay", entry.index, "0s")+ const seconds = (time: string): number => /^-?[\d.]+m?s$/.test(time) ? Number.parseFloat(time) / (time.endsWith("ms") ? 1000 : 1) : Number.NaN+ if (!["forwards", "both"].includes(fill) || composition !== "replace" || !Number.isInteger(count) || count < 1+ || at("animation-play-state", entry.index, "running") !== "running"+ || !(seconds(duration) > 0 && Math.max(0, seconds(delay)) + seconds(duration) * count <= 60)) return 0+ const direction = at("animation-direction", entry.index, "normal")+ if (!["normal", "reverse", "alternate", "alternate-reverse"].includes(direction)) return 0+ const last = direction === "normal" || (direction === "alternate" && count % 2 === 1) || (direction === "alternate-reverse" && count % 2 === 0)+ const frame = entry.frames.find((candidate) => candidate.at === (last ? 100 : 0))+ return frame?.opacity ?? 0+ }+ for (const entry of entries) {+ const final = entry.frames.at(-1)+ const count = at("animation-iteration-count", entry.index, "1")+ if (count === "infinite" && final?.at === 100 && final.opacity <= 0.02) return 0+ if (styleOf(node, "animation-fill-mode") === "" && count !== "infinite" && final?.at === 100+ && at("animation-play-state", entry.index, "running") !== "paused") value = final.opacity+ }+ return value+}++export function textOpacity(snapshot: PageSnapshot, el: ElementSnapshot): number {+ return [el, ...ancestors(snapshot, el)].reduce((value, node) => value * settled(snapshot, node), 1)+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/color-path.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/color-path.tsnew file mode 100644index 00000000..9b7cfd8f--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/color-path.ts@@ -0,0 +1,15 @@+import { parseColor } from "../../../core/color"+import { fontSizePx, styleOf } from "../../../core/page"+import type { ElementSnapshot } from "../../../types"++const safeTags = new Set([+ "blockquote", "nav", "a", "input", "textarea", "select", "pre", "code", "span", "th", "td", "tr", "li", "label", "button",+ "hr", "html", "head", "body", "script", "style", "link", "meta", "title", "br", "img", "svg", "path", "circle", "rect",+ "line", "polyline", "polygon", "g", "defs", "use",+])++export function bareText(el: ElementSnapshot): boolean {+ if (!safeTags.has(el.tag)) return false+ const fill = parseColor(styleOf(el, "background-color"))+ return !(el.ownText.trim() && fontSizePx(el) >= 9 && ((fill?.a ?? 0) > 0.5 || styleOf(el, "background-image").includes("gradient")))+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/contrast-pairs.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/contrast-pairs.tsnew file mode 100644index 00000000..c7f4fb5f--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/contrast-pairs.ts@@ -0,0 +1,54 @@+import { ancestors, isIgnored } from "../../../core/page"+import type { PageHit } from "../../../rule"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { bareText } from "./color-path"+import { textWhole } from "./painted-text"++export type ContrastHit = PageHit & { readonly element: ElementSnapshot; readonly pair: string }++const vendors = [+ { name: "Taboola", subtree: true, ids: ["taboola-", "internal_trc_"], prefixes: ["trc_rbox"], classes: ["trc_related_container"] },+ { name: "Swiper", subtree: false, ids: ["swiper-wrapper-"], prefixes: [], classes: ["swiper", "swiper-container", "swiper-wrapper", "swiper-slide"] },+ { name: "Slick", subtree: false, ids: [], prefixes: [], classes: ["slick-slider", "slick-list", "slick-track", "slick-slide", "slick-arrow"] },+ { name: "Slick", subtree: true, ids: [], prefixes: [], classes: ["slick-dots"] },+ { name: "SuperSlide", subtree: false, ids: [], prefixes: [], classes: ["tempWrap"] },+ { name: "react-fast-marquee", subtree: true, ids: [], prefixes: ["rfm-"], classes: [] },+ { name: "Kaltura", subtree: true, ids: [], prefixes: ["playkit-"], classes: ["kaltura-player", "kaltura-player-container"] },+] as const++function vendorOf(snapshot: PageSnapshot, el: ElementSnapshot): string | null {+ for (const vendor of vendors) for (const node of vendor.subtree ? [el, ...ancestors(snapshot, el)] : [el]) {+ const classes = (node.attributes["class"] ?? "").split(/\s+/)+ if (vendor.ids.some((prefix) => (node.attributes["id"] ?? "").startsWith(prefix))+ || classes.some((token) => vendor.classes.some((name) => name === token) || vendor.prefixes.some((prefix) => token.startsWith(prefix)))) return vendor.name+ }+ return null+}++export function distinctPairs(snapshot: PageSnapshot, hits: readonly ContrastHit[]): readonly PageHit[] {+ const groups = new Map<string, ContrastHit[]>()+ const safeOwners = new Map<string, string | null>()+ for (const hit of hits) {+ if (isIgnored(snapshot, hit.element, "low-contrast")) continue+ const vendor = vendorOf(snapshot, hit.element)+ if (bareText(hit.element)) {+ if (safeOwners.has(hit.pair) && safeOwners.get(hit.pair) !== vendor) continue+ safeOwners.set(hit.pair, vendor)+ }+ const key = `${hit.pair}|${vendor ?? "page"}`+ const group = groups.get(key) ?? []+ group.push(hit)+ groups.set(key, group)+ }+ return [...groups.values()].flatMap((group) => {+ const whole = group.find((hit) => textWhole(snapshot, hit.element)) ?? group[0]+ const owner = (whole?.element.ownText.match(/\p{L}/gu)?.length ?? 0) >= 2 ? whole+ : group.find((hit) => textWhole(snapshot, hit.element) && (hit.element.ownText.match(/\p{L}/gu)?.length ?? 0) >= 2) ?? whole+ if (!owner) return []+ return [{+ element: owner.element,+ message: `${owner.message}${group.length > 1 ? ` (and ${group.length - 1} more)` : ""}`,+ snippet: owner.snippet,+ }]+ })+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/contrast-role.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/contrast-role.tsnew file mode 100644index 00000000..c9a8fa50--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/contrast-role.ts@@ -0,0 +1,76 @@+import { parseColor } from "../../../core/color"+import { ancestors, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { textRect } from "./painted-text"++const handwriting = new Set([+ "allura", "alex brush", "arizonia", "birthstone", "caveat", "cedarville cursive", "cookie", "dawning of a new day",+ "great vibes", "herr von muellerhoff", "homemade apple", "italianno", "la belle aurore", "meddon", "monsieur la doulaise",+ "mr dafoe", "mrs saint delafield", "ms madi", "nothing you could do", "pacifico", "parisienne", "qwigley", "reenie beanie",+ "sacramento", "satisfy", "tangerine", "whisper", "yellowtail", "zeyada",+])++function version(text: string): boolean {+ if (text.length > 64) return false+ let found = false+ const tokens = /\b(?:version|ver\.?|build|release|rev(?:ision)?|commit)\s*[:#]?\s*([0-9a-z][0-9a-z.+_-]*\d[0-9a-z.+_-]*)|(?:^|[\s([])v\d+(?:\.\d+)+(?:[-+][0-9a-z.]+)?|(?:^|[\s([])[a-z]{1,3}\d+\.\d+\.\d+(?:\.\d+)?(?:[-+][0-9a-z.]+)?/gi+ let rest = text.replace(tokens, (whole: string, id: string | undefined) => {+ if (id && (!/^(?:[a-z]?\d+(?:\.\d+)+(?:[-+_][0-9a-z.]+)?|\d+(?:[-+_][0-9a-z.]+)?|[0-9a-f]{7,40})$/i.test(id) || /^(?:19|20)\d\d(?:[-+_]|$)/.test(id))) return whole+ found = true+ return " "+ })+ rest = rest.replace(/(?:^|[\s([])(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:[-+][0-9a-z.]+)?\b/gi, (whole: string, _major: string, minor: string, patch: string) => {+ if ([minor, patch].some((part) => part.length > 1 && part.startsWith("0"))) return whole+ found = true+ return " "+ })+ return found && rest.replace(/\b\d{4}[-./]\d{1,2}[-./]\d{1,2}(?:[\sT]+\d{1,2}(?::\d{2}){0,2})?\b|\b\d{1,2}[-./]\d{1,2}[-./]\d{2,4}\b|\b\d{1,2}:\d{2}(?::\d{2})?\b|\b[0-9a-f]{7,12}\b|[\s\u00b7\u2022|/,()[\]\u2013\u2014-]+/gi, "") === ""+}++function mockup(el: ElementSnapshot): boolean {+ if (["html", "body", "main", "section", "article", "header", "footer", "nav", "aside", "figcaption"].includes(el.tag)) return false+ return [el.attributes["class"], el.attributes["id"]].join(" ").split(/\s+/).some((token) => {+ const parts = token.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/)+ if (parts.some((part) => ["credit", "credits", "caption", "captions", "title", "heading", "description", "copy"].includes(part))) return false+ return parts.some((part) => ["mockup", "mockups", "illustration", "illustrations"].includes(part))+ || (parts.includes("mock") && parts.some((part) => ["ui", "window", "browser", "screen", "device", "phone", "app"].includes(part)))+ })+}++/** Keeps upstream advisory pairs apart from reading text without changing the project's error severity. */+export function contrastRole(snapshot: PageSnapshot, el: ElementSnapshot): string {+ const chain = [el, ...ancestors(snapshot, el)]+ const text = el.ownText.trim()+ const words = text.split(/\s+/)+ const sentence = words.length >= 8 || (words.length >= 5 && /[.!?\u3002\uff01\uff1f]$/.test(text))+ for (const node of chain) {+ if (node.tag === "figcaption") break+ if (node.attributes["role"] === "img" && !chain.some((n) => n.tag === "svg")) return "decorative"+ if (!sentence && mockup(node)) return "decorative"+ }+ const control = chain.find((node) => ["a", "button", "label", "summary", "select", "option"].includes(node.tag)+ || ["button", "link", "tab", "menuitem", "option", "checkbox", "radio", "switch"].includes(node.attributes["role"] ?? ""))+ if (control?.text.trim() === text) return "copy"+ if (/^\p{L}{1,2}$/u.test(text) && !["i", "x", "v"].includes(text) && !chain.some((node) => node.tag === "kbd")) {+ const glyph = textRect(el)+ for (const node of chain.slice(0, 3)) {+ if (node.text.trim() !== text) break+ const box = node.rect+ const fill = parseColor(styleOf(node, "background-color"))+ const paints = (fill?.a ?? 0) > 0.1 || styleOf(node, "background-image") !== "none" || node.tag === "svg"+ const centered = Math.abs(glyph.x + glyph.width / 2 - box.x - box.width / 2) <= box.width * 0.15+ && Math.abs(glyph.y + glyph.height / 2 - box.y - box.height / 2) <= box.height * 0.15+ if (paints && centered && box.width >= 12 && box.width <= 72 && box.height >= 12 && box.height <= 72+ && box.width / box.height >= 0.8 && box.width / box.height <= 1.25) return "decorative"+ }+ }+ if (chain.some((node) => /^h[1-6]$/.test(node.tag) || node.attributes["role"] === "heading")) return "copy"+ if (version(text)) return "decorative"+ const marked = chain.slice(0, 2).some((node) => [node.attributes["class"], node.attributes["id"]].join(" ").split(/\s+/)+ .some((token) => /^(?:[a-z0-9]+(?:-{1,2}|_{1,2}))?(?:signature|autograph|sign-?off)(?:(?:-{1,2}|_{1,2})(?:name|text|line|block|wrap|wrapper|img|image))?$/i.test(token)))+ const family = (styleOf(el, "font-family").split(",")[0] ?? "").replace(/["']/g, "").trim().toLowerCase()+ const script = family === "cursive" || /script|handwriting/.test(family) || handwriting.has(family)+ if (text.length <= 40 && words.length <= (marked ? 4 : 3) && words.every((word) => /^[\p{L}.'-]+$/u.test(word))+ && (marked || (script && words.every((word) => /^\p{Lu}/u.test(word))))) return "decorative"+ return "copy"+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/glow-forms.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/glow-forms.tsnew file mode 100644index 00000000..846fac37--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/glow-forms.ts@@ -0,0 +1,56 @@+import { luminance } from "../../../core/color"+import { isIgnored, isRendered, styleOf } from "../../../core/page"+import { parseShadow, type ShadowLayer } from "../../../core/shadow"+import type { PageHit } from "../../../rule"+import type { PageSnapshot } from "../../../types"+import { backdrop, colorDistance, effectiveOpacity, spread } from "./gradients"++function glow(layer: ShadowLayer, dark: boolean): boolean {+ return spread(layer.color) >= 30 && layer.blur > 4 && layer.blur * layer.color.a >= 3+ && layer.blur / 2 + layer.spread > 0 && (dark || (layer.x === 0 && layer.y === 0))+}++export function glowForm(snapshot: PageSnapshot, hits: readonly PageHit[]): PageHit | null {+ const reported = hits.flatMap((hit) => {+ const element = hit.element+ return element ? ["box-shadow", "text-shadow"].flatMap((p) => parseShadow(styleOf(element, p)).map((layer) => ({ property: p, layer }))) : []+ })+ const unreported = (property: string, layer: ShadowLayer): boolean =>+ !reported.some((r) => r.property === property && colorDistance(r.layer.color, layer.color) < 1)+ for (const host of snapshot.elements) {+ if (!isRendered(snapshot, host) || effectiveOpacity(snapshot, host) <= 0.02 || isIgnored(snapshot, host, "dark-glow")) continue+ const surface = backdrop(snapshot, host)+ const dark = surface !== null && luminance(surface) < 0.1+ for (const pseudo of [host.before, host.after]) {+ if (!pseudo || ["none", "normal"].includes(pseudo.style["content"] ?? "none") || pseudo.style["display"] === "none" || Number(pseudo.style["opacity"] ?? 1) <= 0.02) continue+ for (const property of ["box-shadow", "text-shadow"]) {+ if (parseShadow(pseudo.style[property] ?? "").some((layer) => glow(layer, dark) && unreported(property, layer))) {+ return { element: null, message: "A pseudo-element paints a colored shadow glow", snippet: "Pseudo-element glow" }+ }+ }+ }+ }+ for (const css of snapshot.cssText) for (const match of css.matchAll(/@(?:-webkit-)?keyframes\s+([\w-]+)\s*\{/g)) {+ let depth = 1+ const start = (match.index ?? 0) + match[0].length+ let end = start+ for (; end < css.length && depth > 0; end++) {+ if (css[end] === "{") depth+++ if (css[end] === "}") depth--+ }+ const carriers = snapshot.elements.filter((el) => styleOf(el, "animation-name").split(",").map((n) => n.trim()).includes(match[1] ?? "")+ && isRendered(snapshot, el) && effectiveOpacity(snapshot, el) > 0.02 && !isIgnored(snapshot, el, "dark-glow"))+ if (carriers.length === 0) continue+ for (const declaration of css.slice(start, end).matchAll(/(?<![-\w])(box-shadow|text-shadow)\s*:\s*([^;{}]+)/g)) {+ const property = declaration[1] ?? ""+ const body = snapshot.elements.find((el) => el.tag === "body")+ const root = body ? backdrop(snapshot, body) : null+ const dark = root !== null && luminance(root) < 0.1+ if (parseShadow(declaration[2] ?? "").some((layer) => glow(layer, dark) && unreported(property, layer)+ && !snapshot.elements.some((el) => parseShadow(styleOf(el, property)).some((own) => own.blur > 4 && colorDistance(own.color, layer.color) < 1)))) {+ return { element: null, message: "A running animation declares a colored shadow glow", snippet: "Keyframe glow" }+ }+ }+ }+ return null+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/gradient-samples.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/gradient-samples.tsnew file mode 100644index 00000000..99d18194--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/gradient-samples.ts@@ -0,0 +1,134 @@+import { blend, TRANSPARENT, type Rgba } from "../../../core/color"+import { px, styleOf } from "../../../core/page"+import type { ElementSnapshot, Rect } from "../../../types"+import { gradientStops, splitLayers } from "./gradients"++function length(value: string, size: number): number | null {+ if (value.endsWith("%")) return Number.parseFloat(value) * size / 100+ return px(value)+}++function position(value: string, space: number): number | null {+ if (value === "left" || value === "top") return 0+ if (value === "center") return space / 2+ if (value === "right" || value === "bottom") return space+ return length(value, space)+}++function fraction(image: string, x: number, y: number, w: number, h: number): readonly [number, number] | null {+ const head = splitLayers(image.slice(image.indexOf("(") + 1, -1))[0] ?? ""+ if (image.startsWith("linear-gradient(")) {+ let angle = Math.PI+ const degrees = /^(-?[\d.]+)deg$/.exec(head)+ if (degrees) angle = Number(degrees[1]) * Math.PI / 180+ else if (head.startsWith("to ")) {+ const dx = head.includes("right") ? 1 : head.includes("left") ? -1 : 0+ const dy = head.includes("bottom") ? 1 : head.includes("top") ? -1 : 0+ if (dx === 0 && dy === 0) return null+ angle = Math.atan2(dx * (dy === 0 ? 1 : h), -dy * (dx === 0 ? 1 : w))+ } else if (!gradientStops(`linear-gradient(${head})`).length) return null+ const span = Math.abs(w * Math.sin(angle)) + Math.abs(h * Math.cos(angle))+ return [((x - w / 2) * Math.sin(angle) - (y - h / 2) * Math.cos(angle)) / span + 0.5, span]+ }+ if (!image.startsWith("radial-gradient(")) return null+ const hasHead = gradientStops(`linear-gradient(${head})`).length === 0+ const [size = "", at = "50% 50%"] = hasHead ? head.split(/\s+at\s+/) : []+ const center = at.split(/\s+/)+ const cx = position(center[0] ?? "50%", w)+ const cy = position(center[1] ?? "50%", h)+ if (cx === null || cy === null) return null+ const explicit = size.split(/\s+/).filter((s) => /^[-\d.]+(?:px|%)$/.test(s))+ let rx = length(explicit[0] ?? "", w)+ let ry = length(explicit[1] ?? explicit[0] ?? "", h)+ if (rx === null || ry === null) {+ const close = size.includes("closest")+ const dx = close ? Math.min(Math.abs(cx), Math.abs(w - cx)) : Math.max(Math.abs(cx), Math.abs(w - cx))+ const dy = close ? Math.min(Math.abs(cy), Math.abs(h - cy)) : Math.max(Math.abs(cy), Math.abs(h - cy))+ const side = size.includes("side")+ if (size.includes("circle")) rx = ry = side ? close ? Math.min(dx, dy) : Math.max(dx, dy) : Math.hypot(dx, dy)+ else {+ rx = dx * (side ? 1 : Math.SQRT2)+ ry = dy * (side ? 1 : Math.SQRT2)+ }+ }+ return rx > 0 && ry > 0 ? [Math.hypot((x - cx) / rx, (y - cy) / ry), rx] : null+}++function colorAt(image: string, x: number, y: number, w: number, h: number): Rgba | null {+ const sample = fraction(image, x, y, w, h)+ const stops = gradientStops(image)+ if (!sample || stops.length < 2) return null+ const [t, span] = sample+ const positions = stops.map((stop) => {+ const token = /(-?[\d.]+)(%|px)\s*$/.exec(stop.raw)+ return token ? Number(token[1]) / (token[2] === "%" ? 100 : span) : null+ })+ positions[0] ??= 0+ positions[positions.length - 1] ??= 1+ let last = 0+ for (let i = 1; i < positions.length; i++) {+ const end = positions[i]+ if (end === null || end === undefined) continue+ const start = positions[last] ?? 0+ const edge = Math.max(start, end)+ for (let j = last + 1; j <= i; j++) positions[j] = start + (edge - start) * (j - last) / (i - last)+ last = i+ }+ let upper = positions.findIndex((p) => p !== null && t <= p)+ if (upper < 0) upper = stops.length - 1+ if (upper === 0) return stops[0]?.color ?? null+ const a = stops[upper - 1]?.color+ const b = stops[upper]?.color+ if (!a || !b) return null+ const start = positions[upper - 1] ?? 0+ const end = positions[upper] ?? 1+ const f = end === start ? 1 : Math.max(0, Math.min(1, (t - start) / (end - start)))+ const alpha = a.a * (1 - f) + b.a * f+ if (alpha === 0) return TRANSPARENT+ const mix = (v: number, u: number): number => (v * a.a * (1 - f) + u * b.a * f) / alpha+ return { r: mix(a.r, b.r), g: mix(a.g, b.g), b: mix(a.b, b.b), a: alpha }+}++/** Samples supported gradient tiles at the upstream text-box grid; null leaves the stop fallback in charge. */+export function gradientSamples(el: ElementSnapshot, text: Rect): readonly Rgba[] | null {+ const images = splitLayers(styleOf(el, "background-image"))+ if (images.some((image) => !/^(?:linear|radial)-gradient\(/.test(image))) return null+ const border = ["top", "right", "bottom", "left"].map((side) => px(styleOf(el, `border-${side}-width`)) ?? 0)+ const w = el.rect.width - (border[1] ?? 0) - (border[3] ?? 0)+ const h = el.rect.height - (border[0] ?? 0) - (border[2] ?? 0)+ if (w <= 0 || h <= 0) return null+ const sizes = splitLayers(styleOf(el, "background-size"))+ const positions = splitLayers(styleOf(el, "background-position"))+ const repeats = splitLayers(styleOf(el, "background-repeat"))+ const inset = Math.min(1, text.width / 4)+ const xs = [inset, text.width / 6, text.width / 2, text.width * 5 / 6, text.width - inset]+ const colors: Rgba[] = []+ for (const fy of [1 / 6, 0.5, 5 / 6]) for (const fx of xs) {+ let paint = TRANSPARENT+ for (let i = images.length - 1; i >= 0; i--) {+ const image = images[i]+ if (!image) continue+ const size = (sizes[i % sizes.length] ?? "auto").split(/\s+/)+ const tw = size[0] === "auto" ? w : length(size[0] ?? "100%", w)+ const th = !size[1] || size[1] === "auto" ? h : length(size[1], h)+ if (tw === null || th === null) return null+ if (tw <= 0 || th <= 0) continue+ const pos = (positions[i % positions.length] ?? "0% 0%").split(/\s+/)+ const tx = position(pos[0] ?? "0%", w - tw)+ const ty = position(pos[1] ?? "50%", h - th)+ if (tx === null || ty === null) return null+ let x = text.x + fx - el.rect.x - (border[3] ?? 0) - tx+ let y = text.y + text.height * fy - el.rect.y - (border[0] ?? 0) - ty+ const repeat = repeats[i % repeats.length] ?? "repeat"+ if (repeat === "repeat" || repeat === "repeat-x") x = ((x % tw) + tw) % tw+ else if (x < 0 || x > tw) continue+ if (repeat === "repeat" || repeat === "repeat-y") y = ((y % th) + th) % th+ else if (y < 0 || y > th) continue+ const color = colorAt(image, x, y, tw, th)+ if (!color) return null+ paint = blend(color, paint)+ }+ colors.push(paint)+ }+ return colors+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/gradients.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/gradients.tsnew file mode 100644index 00000000..927ad5c1--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/gradients.ts@@ -0,0 +1,91 @@+import { blend, parseColor, TRANSPARENT, WHITE, type Rgba } from "../../../core/color"+import { ancestors, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"++export function splitLayers(value: string): readonly string[] {+ const parts: string[] = []+ let depth = 0+ let start = 0+ for (let i = 0; i < value.length; i++) {+ if (value[i] === "(") depth+++ if (value[i] === ")") depth--+ if (value[i] === "," && depth === 0) {+ parts.push(value.slice(start, i).trim())+ start = i + 1+ }+ }+ parts.push(value.slice(start).trim())+ return parts.filter(Boolean)+}++export type Stop = { readonly color: Rgba; readonly position: number | null; readonly raw: string }++export function gradientStops(value: string): readonly Stop[] {+ const out: Stop[] = []+ for (const layer of splitLayers(value)) {+ if (!/gradient\(/i.test(layer)) continue+ for (const raw of splitLayers(layer.slice(layer.indexOf("(") + 1, -1))) {+ const match = /^(rgba?|color|oklab|oklch)\([^()]*\)|^#[0-9a-f]{3,8}\b|^transparent\b|^(white|black)\b/i.exec(raw)+ if (!match) continue+ const literal = match[0].toLowerCase()+ const color = literal === "white" ? WHITE : literal === "black" ? { r: 0, g: 0, b: 0, a: 1 } : parseColor(literal)+ if (!color) continue+ const position = /(-?\d*\.?\d+)%/.exec(raw.slice(match[0].length))+ out.push({ color, raw, position: position ? Number(position[1]) / 100 : null })+ }+ }+ return out+}++export const spread = (c: Rgba): number => Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)+export const colorDistance = (a: Rgba, b: Rgba): number => Math.max(Math.abs(a.r - b.r), Math.abs(a.g - b.g), Math.abs(a.b - b.b))+export const sameColor = (a: Rgba, b: Rgba): boolean => colorDistance(a, b) < 12 && Math.abs(a.a - b.a) * 255 < 12+export const opacity = (el: ElementSnapshot): number => {+ const n = Number.parseFloat(styleOf(el, "opacity"))+ return Number.isFinite(n) ? Math.max(0, Math.min(1, n)) : 1+}+export const effectiveOpacity = (snapshot: PageSnapshot, el: ElementSnapshot): number =>+ [el, ...ancestors(snapshot, el)].reduce((v, node) => v * opacity(node), 1)++function meanGradient(value: string): Rgba | null {+ const stops = gradientStops(value)+ const total = stops.reduce((n, s) => n + s.color.a, 0)+ if (stops.length === 0) return null+ if (total === 0) return TRANSPARENT+ return {+ r: stops.reduce((n, s) => n + s.color.r * s.color.a, 0) / total,+ g: stops.reduce((n, s) => n + s.color.g * s.color.a, 0) / total,+ b: stops.reduce((n, s) => n + s.color.b * s.color.a, 0) / total,+ a: total / stops.length,+ }+}++export function backdrop(snapshot: PageSnapshot, el: ElementSnapshot, ownImage = styleOf(el, "background-image")): Rgba | null {+ const paints: Rgba[] = []+ for (const node of [el, ...ancestors(snapshot, el)]) {+ const image = node === el ? ownImage : styleOf(node, "background-image")+ for (const layer of splitLayers(image)) {+ if (layer.includes("url(")) return null+ const mean = meanGradient(layer)+ if (mean) {+ paints.push(mean)+ if (mean.a >= 0.99) return paints.reduceRight((under, top) => blend(top, under), WHITE)+ }+ }+ const fill = parseColor(styleOf(node, "background-color"))+ if (fill) {+ paints.push(fill)+ if (fill.a >= 0.99) break+ }+ }+ return paints.reduceRight((under, top) => blend(top, under), WHITE)+}++export function oklch(c: Rgba): { readonly l: number; readonly c: number } {+ const linear = (v: number): number => v / 255 <= 0.04045 ? v / 255 / 12.92 : ((v / 255 + 0.055) / 1.055) ** 2.4+ const [r, g, b] = [linear(c.r), linear(c.g), linear(c.b)]+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)+ return { l: 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, c: Math.hypot(1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s) }+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/mockup-roots.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/mockup-roots.tsnew file mode 100644index 00000000..b2d524ad--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/mockup-roots.ts@@ -0,0 +1,63 @@+import { ancestors, childrenOf, descendants, isRendered, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"++const skippedTags = new Set(["html", "body", "main", "header", "footer", "nav", "aside", "section", "article", "form", "dialog", "li", "tr", "td", "th", "tbody", "thead", "table", "details", "summary"])+const textTags = new Set(["h1", "h2", "h3", "h4", "h5", "h6", "p", "a", "button", "label", "summary", "legend", "caption", "figcaption", "blockquote", "q"])+const skippedParts = new Set([+ "clone", "clones", "cloned", "copy", "duplicate", "dup", "carousel", "embla", "flicking", "glide", "keen", "slick", "slide", "slider", "slides", "splide", "swiper", "marquee", "ticker",+ "menu", "submenu", "dropdown", "popup", "popover", "modal", "drawer", "dialog", "tooltip", "toast", "offcanvas", "overlay", "nav", "navbar", "navigation", "panel", "tab", "tabpanel",+ "accordion", "collapse", "collapsible", "intro", "splash", "loader", "preloader", "loading", "banner", "cookie", "cookies", "consent", "sidebar", "sidenav", "toc",+])+const hidden = (el: ElementSnapshot): boolean => el.attributes["inert"] !== undefined || el.attributes["aria-hidden"]?.trim().toLowerCase() === "true"+const squash = (text: string): string => text.replace(/\s/g, "")+const dialog = (el: ElementSnapshot): boolean => el.attributes["aria-modal"] === "true" || /^(?:alert)?dialog$/.test(el.attributes["role"] ?? "")+ || (el.tag === "dialog" && el.attributes["open"] !== undefined)++function structural(el: ElementSnapshot): boolean {+ if (skippedTags.has(el.tag) || el.attributes["aria-modal"] !== undefined || el.attributes["data-aria-hidden"] !== undefined+ || ["fixed", "sticky"].includes(styleOf(el, "position"))) return false+ const roles = (el.attributes["role"] ?? "").trim().toLowerCase().split(/\s+/).filter(Boolean)+ if (!roles.every((role) => ["presentation", "none", "img", "figure", "group"].includes(role))) return false+ const parts = [el.attributes["class"], el.attributes["id"]].join(" ").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/)+ return !parts.some((part) => skippedParts.has(part))+}++function hasPeer(snapshot: PageSnapshot, el: ElementSnapshot): boolean {+ const text = squash(el.text)+ if (text && ancestors(snapshot, el).some((node) => squash(node.attributes["aria-label"] ?? "").includes(text))) return true+ const parent = el.parent === null ? undefined : snapshot.elements[el.parent]+ if (!parent) return false+ const classes = (el.attributes["class"] ?? "").split(/\s+/).filter(Boolean)+ return childrenOf(snapshot, parent).some((peer) => {+ if (peer === el) return false+ const same = peer.tag === el.tag && classes.every((c) => (peer.attributes["class"] ?? "").split(/\s+/).includes(c))+ && (classes.length === 0) === ((peer.attributes["class"] ?? "").trim() === "")+ if (same && isRendered(snapshot, peer) && !hidden(peer)) return true+ if (text && squash(peer.text) === text) return true+ const picture = /\b(?:demo|demonstration|illustrat\w*|interface|screen ?shots?|mock-?ups?|graphic|animation|animated|preview|image|video|visual|diagram|depict\w*|shows|showing|displayed)\b/i.test(peer.text)+ return !hidden(peer) && isRendered(snapshot, peer) && peer.text.trim() !== "" && !picture && (peer.rect.width <= 1 || peer.rect.height <= 1)+ })+}++export function mockupRoots(snapshot: PageSnapshot): ReadonlyMap<number, "declared" | "labelled"> {+ const roots = new Map<number, "declared" | "labelled">()+ const pageChars = snapshot.elements.filter((el) => isRendered(snapshot, el)).reduce((sum, el) => sum + squash(el.ownText).length, 0)+ const modals = snapshot.elements.filter((el) => dialog(el) && !hidden(el) && isRendered(snapshot, el))+ for (const el of snapshot.elements) {+ if (el.rect.width < 120 || el.rect.height < 80 || !structural(el)) continue+ if (/\b(?:screen ?shots?|screen ?captures?|screencaps?|illustrations?|mock-?ups?)\b|\bpreview of\b/i.test(el.attributes["aria-label"] ?? "")) {+ roots.set(el.index, "labelled")+ }+ if (!hidden(el) || ancestors(snapshot, el).some((node) => textTags.has(node.tag))) continue+ const nodes = [el, ...descendants(snapshot, el)]+ if (nodes.length > 3000 || nodes.some((node) => node.tag === "h1")) continue+ const fields = nodes.filter((node) => ["input", "select", "textarea"].includes(node.tag) && node.attributes["type"] !== "hidden").length+ const runs = nodes.filter((node) => isRendered(snapshot, node) && node.ownText.trim() !== "")+ const links = runs.filter((node) => [node, ...ancestors(snapshot, node)].some((host) => nodes.includes(host) && host.tag === "a" && (host.attributes["href"] ?? "").trim() !== "")).length+ if (runs.length < 3 || fields >= 2 || (fields >= 1 && nodes.some((node) => node.tag === "label")) || links * 2 >= runs.length || hasPeer(snapshot, el)) continue+ if (modals.some((modal) => !nodes.includes(modal) && ![...ancestors(snapshot, el)].includes(modal))) continue+ const chars = runs.reduce((sum, node) => sum + squash(node.ownText).length, 0)+ if (pageChars > 0 && chars * 2 < pageChars) roots.set(el.index, "declared")+ }+ return roots+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/page-ignore.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/page-ignore.tsnew file mode 100644index 00000000..d7bb9bcc--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/page-ignore.ts@@ -0,0 +1,7 @@+import { ancestors, IGNORE_ATTRIBUTES, isIgnored } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"++export function pageIgnored(snapshot: PageSnapshot, el: ElementSnapshot, rule: string): boolean {+ return isIgnored(snapshot, el, rule) || [el, ...ancestors(snapshot, el)].some((node) =>+ IGNORE_ATTRIBUTES.some((name) => (node.attributes[name] ?? "").split(/[\s,]+/).includes("*")))+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/painted-text.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/painted-text.tsnew file mode 100644index 00000000..f674c71d--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/painted-text.ts@@ -0,0 +1,141 @@+import { ancestors, childrenOf, isRendered, px, styleOf } from "../../../core/page"+import type { ComputedStyle, ElementSnapshot, PageSnapshot, Rect } from "../../../types"+import { effectiveOpacity, gradientStops, opacity } from "./gradients"+import { textOpacity } from "./animation-opacity"++export function contains(outer: Rect, inner: Rect): boolean {+ return inner.x >= outer.x - 1 && inner.y >= outer.y - 1 && inner.x + inner.width <= outer.x + outer.width + 1 && inner.y + inner.height <= outer.y + outer.height + 1+}++export function textRect(el: ElementSnapshot): Rect {+ if (el.lineRects.length === 0) return el.rect+ const x = Math.min(...el.lineRects.map((r) => r.x))+ const y = Math.min(...el.lineRects.map((r) => r.y))+ return {+ x, y,+ width: Math.max(...el.lineRects.map((r) => r.x + r.width)) - x,+ height: Math.max(...el.lineRects.map((r) => r.y + r.height)) - y,+ }+}++const zIndex = (el: ElementSnapshot): number => Number.parseFloat(styleOf(el, "z-index")) || 0++function coveredBySibling(snapshot: PageSnapshot, el: ElementSnapshot): boolean {+ const rect = textRect(el)+ for (const node of [el, ...ancestors(snapshot, el)]) {+ const parent = node.parent === null ? undefined : snapshot.elements[node.parent]+ if (!parent) continue+ for (const sibling of childrenOf(snapshot, parent)) {+ if (sibling === node || !isRendered(snapshot, sibling) || effectiveOpacity(snapshot, sibling) < 0.99 || !contains(sibling.rect, rect)) continue+ if (!["absolute", "fixed"].includes(styleOf(sibling, "position")) && styleOf(sibling, "z-index") === "auto") continue+ if (zIndex(sibling) < zIndex(node) || (zIndex(sibling) === zIndex(node) && sibling.index < node.index)) continue+ const bg = sibling.style["background-color"] ?? ""+ const alpha = /rgba\([^)]*,\s*([\d.]+)\s*\)/.exec(bg)+ const solid = bg.startsWith("rgb(") || bg.startsWith("#") || (alpha !== null && Number(alpha[1]) >= 0.99)+ if (solid || ["img", "video", "canvas"].includes(sibling.tag)) return true+ }+ }+ return false+}++function maskHides(node: ElementSnapshot, rect: Rect): boolean {+ const mask = styleOf(node, "mask-image") || styleOf(node, "-webkit-mask-image")+ if (!mask.includes("linear-gradient")) return false+ const stops = gradientStops(mask)+ const last = stops.at(-1)+ if (!last || last.color.a > 0.02) return false+ const terminal = /([\d.]+)(px|%)(?:\s*\))?$/.exec(last.raw)+ if (!terminal) return false+ const edge = Number(terminal[1]) * (terminal[2] === "%" ? node.rect.height / 100 : 1)+ return rect.y >= node.rect.y + edge+}++function scrollFrame(snapshot: PageSnapshot, node: ElementSnapshot): boolean {+ const r = node.rect+ if (styleOf(node, "position") === "fixed" && r.x <= 1 && r.y <= 1+ && r.x + r.width >= snapshot.viewport.width - 1 && r.y + r.height >= snapshot.viewport.height - 1) return true+ if (r.height < snapshot.viewport.height - 1 || node.scroll.scrollHeight <= node.scroll.clientHeight + 1) return false+ const max = px(styleOf(node, "max-height"))+ if (max !== null && max > snapshot.viewport.height + 1 && Math.abs(r.height - max) <= 1) return false+ const stack = [...childrenOf(snapshot, node)]+ let read = 0+ while (stack.length > 0) {+ const child = stack.pop()+ if (!child) break+ if (++read > 2000) return true+ const position = styleOf(child, "position")+ if (position === "fixed") continue+ if (position === "absolute" && child.rect.height < r.height / 2) continue+ if (child.rect.y + child.rect.height > r.y + r.height + 1) return true+ stack.push(...childrenOf(snapshot, child))+ }+ return node.ownText.trim() !== ""+}++export function textWhole(snapshot: PageSnapshot, el: ElementSnapshot): boolean {+ const rect = textRect(el)+ if (el.rect.x < -1 || el.rect.x + el.rect.width > snapshot.viewport.width + 1) return false+ return ancestors(snapshot, el).every((node) => !["hidden", "clip", "auto", "scroll"].includes(styleOf(node, "overflow-x"))+ || (rect.x >= node.rect.x - 1 && rect.x + rect.width <= node.rect.x + node.rect.width + 1))+}++export function textPainted(snapshot: PageSnapshot, el: ElementSnapshot): boolean {+ if (el.rect.width <= 0 || el.rect.height <= 0 || textOpacity(snapshot, el) <= 0.02) return false+ const rect = textRect(el)+ if ([el, ...ancestors(snapshot, el)].some((node) => styleOf(node, "position") === "fixed")+ && (rect.x >= snapshot.viewport.width || rect.x + rect.width <= 0)) return false+ let left = rect.x+ let right = rect.x + rect.width+ const viewportFrame = [el, ...ancestors(snapshot, el)].some((node) => styleOf(node, "position") === "fixed"+ && node.rect.x <= 1 && node.rect.y <= 1 && node.rect.width >= snapshot.viewport.width - 1 && node.rect.height >= snapshot.viewport.height - 1)+ for (const node of [el, ...ancestors(snapshot, el)]) {+ if (["hidden", "collapse"].includes(styleOf(node, "visibility")) || styleOf(node, "display") === "none") return false+ if (node.attributes["hidden"] === "until-found" || (node.tag === "details" && node.attributes["open"] === undefined+ && node !== el && ![el, ...ancestors(snapshot, el)].some((child) => child.tag === "summary" && child.parent === node.index))) return false+ if (node.rect.width <= 1 && node.rect.height <= 1 && styleOf(node, "overflow-x") === "hidden") return false+ const r = node.rect+ if (["hidden", "clip", "auto", "scroll"].includes(styleOf(node, "overflow-x"))) {+ left = Math.max(left, r.x)+ right = Math.min(right, r.x + r.width)+ const inside = [el, ...ancestors(snapshot, el)].slice(0, [el, ...ancestors(snapshot, el)].indexOf(node))+ const parks = r.width < snapshot.viewport.width - 1 || ["auto", "scroll"].includes(styleOf(node, "overflow-x"))+ || inside.some((child) => !["", "none"].includes(styleOf(child, "transform")))+ if (right <= left || (parks && styleOf(node, "text-overflow") !== "ellipsis" && (right - left) / rect.width < 0.25)) return false+ }+ if (["hidden", "clip"].includes(styleOf(node, "overflow-y")) && !(node.tag === "body" && viewportFrame) && !scrollFrame(snapshot, node)+ && (rect.y >= r.y + r.height || rect.y + rect.height <= r.y)) return false+ if (maskHides(node, rect)) return false+ }+ return !coveredBySibling(snapshot, el)+}++export function pseudoCovers(style: ComputedStyle, host: ElementSnapshot, rect: Rect): boolean {+ if (style["display"] === "none" || ["hidden", "collapse"].includes(style["visibility"] ?? "") || Number.parseFloat(style["opacity"] ?? "1") < 0.9) return false+ if (style["content"] === "none" || style["content"] === "normal") return false+ const length = (value: string | undefined, size: number, fallback: number): number => value?.endsWith("%") ? Number.parseFloat(value) * size / 100 : px(value) ?? fallback+ const width = length(style["width"], host.rect.width, host.rect.width)+ const height = length(style["height"], host.rect.height, host.rect.height)+ let x = host.rect.x + length(style["left"], host.rect.width, 0)+ let y = host.rect.y + length(style["top"], host.rect.height, 0)+ const matrix = /^matrix\(([^)]+)\)/.exec(style["transform"] ?? "")+ if (matrix) {+ const [a = 1, b = 0, c = 0, d = 1, tx = 0, ty = 0] = (matrix[1] ?? "").split(",").map(Number)+ if (Math.abs(a) < 0.01 || Math.abs(d) < 0.01) return false+ x += tx+ y += ty+ if (b !== 0 && c === 0) {+ const conservativeEdge = y + height + Math.min(0, b * width)+ if (rect.y + rect.height > conservativeEdge) return false+ }+ }+ if (style["scale"]?.startsWith("0")) return false+ return contains({ x, y, width, height }, rect)+}++export function siblingGrounds(snapshot: PageSnapshot, node: ElementSnapshot, rect: Rect): readonly ElementSnapshot[] {+ const parent = node.parent === null ? undefined : snapshot.elements[node.parent]+ if (!parent) return []+ return childrenOf(snapshot, parent).filter((sib) =>+ sib !== node && sib.index < node.index && zIndex(sib) <= zIndex(node) && isRendered(snapshot, sib) && opacity(sib) > 0 && contains(sib.rect, rect),+ ).sort((a, b) => zIndex(b) - zIndex(a) || b.index - a.index)+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/palette-roles.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/palette-roles.tsnew file mode 100644index 00000000..ce28dafa--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/palette-roles.ts@@ -0,0 +1,58 @@+import { parseColor, toHsl, type Rgba } from "../../../core/color"+import { ancestors, fontSizePx, isHeading, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { gradientStops, spread } from "./gradients"++export const tellHue = (c: Rgba): "cyan" | "purple" | null => {+ const { h, s } = toHsl(c)+ return h >= 260 && h <= 310 ? "purple" : h >= 170 && h <= 197 && s >= 0.4 ? "cyan" : null+}++export function paletteVisible(snapshot: PageSnapshot, el: ElementSnapshot): boolean {+ return el.rect.width > 0 && el.rect.height > 0 && [el, ...ancestors(snapshot, el)].every((node) =>+ styleOf(node, "display") !== "none" && !["hidden", "collapse"].includes(styleOf(node, "visibility")))+}++function roleKey(el: ElementSnapshot, fill: boolean): string {+ return fill ? `${el.tag}|${Math.round(el.rect.width)}x${Math.round(el.rect.height)}` : `${el.tag}|${fontSizePx(el)}|${styleOf(el, "font-weight")}`+}++export function categoryColor(snapshot: PageSnapshot, el: ElementSnapshot, fill: boolean): boolean {+ const hues: number[] = []+ for (const other of snapshot.elements) {+ if (!paletteVisible(snapshot, other) || roleKey(other, fill) !== roleKey(el, fill)) continue+ const color = fill+ ? gradientStops(styleOf(other, "background-image")).find((s) => s.color.a > 0.1 && spread(s.color) > 50)?.color+ : parseColor(styleOf(other, "color"))+ if (color && spread(color) > 50 && (fill || color.a >= 0.5)) hues.push(toHsl(color).h)+ }+ const distinct: number[] = []+ for (const h of hues.sort((a, b) => a - b)) if (h - (distinct.at(-1) ?? -360) >= 5) distinct.push(h)+ if (distinct.length > 1 && (distinct[0] ?? 0) + 360 - (distinct.at(-1) ?? 0) < 5) distinct.pop()+ const outside = distinct.filter((h) => !(h >= 260 && h <= 310) && !(h >= 170 && h <= 197)).length+ return distinct.length >= 6 && outside * 2 >= distinct.length+}++export function brandColor(snapshot: PageSnapshot, ink: Rgba): boolean {+ return snapshot.elements.some((el) => {+ if (!paletteVisible(snapshot, el)) return false+ const local = [...ancestors(snapshot, el)].some((a) => a.tag === "main" || a.tag === "article")+ const name = [el.attributes["id"], el.attributes["class"], el.attributes["aria-label"], el.attributes["alt"]].join(" ").toLowerCase()+ const namedLogo = /(?:^|[\s_-])(logo|wordmark|logotype)(?:$|[\s_-])/.test(name) && !/(logos|gallery|grid|wall|list|strip|row|carousel|cloud|title|heading|section)/.test(name)+ if (isHeading(el) && !namedLogo) return false+ const logo = !local && namedLogo+ const bar = !local && (["nav", "header"].includes(el.tag) || ["navigation", "banner"].includes(el.attributes["role"] ?? "")) && el.rect.width >= snapshot.viewport.width * 0.5+ const band = el.rect.width >= snapshot.viewport.width * 0.9 && el.rect.width * el.rect.height >= snapshot.viewport.width * snapshot.viewport.height * 0.2+ if (!logo && !bar && !band) return false+ const colors = gradientStops(styleOf(el, "background-image")).length === 0 ? [parseColor(styleOf(el, "background-color"))] : []+ if (logo) {+ const text = el.ownText ? el : snapshot.elements.find((node) => node.ownText && [...ancestors(snapshot, node)].some((a) => a.index === el.index))+ if (text) colors.push(parseColor(styleOf(text, "color")))+ }+ return colors.some((c) => {+ if (!c || c.a < 0.9 || spread(c) <= 50) return false+ const delta = Math.abs(toHsl(c).h - toHsl(ink).h)+ return Math.min(delta, 360 - delta) <= 12+ })+ })+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/placeholder-contrast.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/placeholder-contrast.tsnew file mode 100644index 00000000..a446e29c--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/placeholder-contrast.ts@@ -0,0 +1,25 @@+import { blend, contrastRatio, parseColor } from "../../../core/color"+import { ancestors, fontSizePx, styleOf } from "../../../core/page"+import type { PageHit } from "../../../rule"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { textPainted } from "./painted-text"+import { textBackgrounds } from "./text-colors"++export function placeholderContrast(snapshot: PageSnapshot, el: ElementSnapshot): readonly PageHit[] {+ const text = (el.attributes["placeholder"] ?? "").trim()+ if (!["input", "textarea"].includes(el.tag) || !el.placeholder || !text || !textPainted(snapshot, el)) return []+ if ([el, ...ancestors(snapshot, el)].some((node) => node.attributes["disabled"] !== undefined || node.attributes["aria-disabled"] === "true")) return []+ if (el.tag === "input" && ["hidden", "checkbox", "radio", "file", "submit", "button", "image", "reset", "range", "color"].includes((el.attributes["type"] ?? "text").toLowerCase())) return []+ const ink = parseColor(el.placeholder.style["color"] ?? "")+ if (!ink || ink.a <= 0.02) return []+ const backgrounds = textBackgrounds(snapshot, el)+ if (backgrounds.length === 0) return []+ const size = fontSizePx(el)+ if (size <= 0) return []+ const words = (styleOf(el, "font-family").split(",")[0] ?? "").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/)+ const namedBold = words.some((word) => ["bold", "semibold", "demibold", "extrabold", "ultrabold", "heavy", "black"].includes(word))+ const weight = namedBold ? Math.max(700, Number.parseFloat(styleOf(el, "font-weight")) || 400) : Number.parseFloat(styleOf(el, "font-weight"))+ const threshold = size >= 24 || (size >= 18.66 && weight >= 700) ? 3 : 4.5+ const ratio = Math.min(...backgrounds.map((background) => contrastRatio(blend(ink, background), background)))+ return ratio < threshold ? [{ element: el, message: `Placeholder contrast ${ratio.toFixed(2)}:1; needs ${threshold}:1`, snippet: text }] : []+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/stock-accent.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/stock-accent.tsnew file mode 100644index 00000000..8d443ff3--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/stock-accent.ts@@ -0,0 +1,31 @@+import { parseColor, type Rgba } from "../../../core/color"+import { px, styleOf } from "../../../core/page"+import { parseShadow } from "../../../core/shadow"+import { cssBlocks } from "../../../core/source"+import type { PageSnapshot } from "../../../types"+import { matchesSelector } from "../../decoration/support/css-candidates"+import { colorDistance, gradientStops } from "./gradients"+import { paletteVisible } from "./palette-roles"++const colors = ["#7c3aed", "#8b5cf6", "#a855f7", "#9333ea", "#7e22ce", "#6d28d9", "#6366f1", "#764ba2", "#667eea"]+ .map(parseColor).filter((color) => color !== null)+const stock = (color: Rgba | null): boolean => color !== null && color.a > 0.1 && colors.some((c) => colorDistance(c, color) <= 8)++export function stockAccent(snapshot: PageSnapshot): boolean {+ const trigger = /(?:^|;)\s*color\s*:[^;]*#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9)\b|gradient[^;]*#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea)\b/i+ const declared = snapshot.elements.some((el) => trigger.test(el.attributes["style"] ?? "") && paletteVisible(snapshot, el))+ || snapshot.cssText.some((css) => cssBlocks(css).some((block) =>+ trigger.test(block.body) && block.selector.split(",").some((selector) =>+ snapshot.elements.some((el) => matchesSelector(snapshot, el, selector.trim()) && paletteVisible(snapshot, el)))))+ if (!declared) return false+ return snapshot.elements.some((el) => {+ if (!paletteVisible(snapshot, el)) return false+ if (el.ownText.trim() && stock(parseColor(styleOf(el, "color")))) return true+ if (stock(parseColor(styleOf(el, "background-color"))) || gradientStops(styleOf(el, "background-image")).some((s) => stock(s.color))) return true+ for (const side of ["top", "right", "bottom", "left"]) {+ if ((px(styleOf(el, `border-${side}-width`)) ?? 0) > 0 && !["none", "hidden"].includes(styleOf(el, `border-${side}-style`)) && stock(parseColor(styleOf(el, `border-${side}-color`)))) return true+ }+ if ((px(styleOf(el, "outline-width")) ?? 0) > 0 && !["", "none"].includes(styleOf(el, "outline-style")) && stock(parseColor(styleOf(el, "outline-color")))) return true+ return parseShadow(styleOf(el, "box-shadow")).some((s) => stock(s.color) && [s.x, s.y, s.blur, s.spread].some((n) => n !== 0))+ })+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/color/support/text-colors.ts b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/text-colors.tsnew file mode 100644index 00000000..1ccc5532--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/color/support/text-colors.ts@@ -0,0 +1,80 @@+import { blend, parseColor, WHITE, type Rgba } from "../../../core/color"+import { ancestors, fontSizePx, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { effectiveOpacity, gradientStops } from "./gradients"+import { gradientSamples } from "./gradient-samples"+import { contains, pseudoCovers, siblingGrounds, textPainted, textRect } from "./painted-text"+import { textOpacity } from "./animation-opacity"++export const clipsText = (el: ElementSnapshot): boolean =>+ [styleOf(el, "background-clip"), styleOf(el, "-webkit-background-clip")].some((v) => v.split(",").some((s) => s.trim() === "text"))++export function textInk(snapshot: PageSnapshot, el: ElementSnapshot): Rgba | null {+ if (!textPainted(snapshot, el) || !/[\p{L}\p{N}]/u.test(el.ownText)) return null+ if (fontSizePx(el) <= 0 || [el, ...ancestors(snapshot, el)].some((node) => ["video", "audio", "canvas", "iframe"].includes(node.tag))) return null+ if (["script", "style", "title", "option", "noscript", "template"].includes(el.tag)) return null+ const fill = styleOf(el, "-webkit-text-fill-color")+ const color = parseColor(fill || styleOf(el, "color"))+ if (!color || color.a <= 0.02) return null+ return { ...color, a: color.a * textOpacity(snapshot, el) }+}++export function textBackgrounds(snapshot: PageSnapshot, el: ElementSnapshot): readonly Rgba[] {+ const layers: Rgba[] = []+ const rect = textRect(el)+ const nodes = [el, ...ancestors(snapshot, el)].flatMap((node) => [node, ...siblingGrounds(snapshot, node, rect)])+ for (const node of nodes) {+ if (["img", "video", "canvas"].includes(node.tag)) return []+ const paired = node.before && node.after && contains(node.rect, rect)+ && node.before.style["background-color"] === node.after.style["background-color"]+ && node.before.style["background-image"] === node.after.style["background-image"]+ && [node.before, node.after].every((p) => Number.parseFloat(p.style["opacity"] ?? "1") >= 0.9)+ for (const pseudo of [node.after, node.before]) {+ if (!pseudo || (!paired && !pseudoCovers(pseudo.style, node, rect))) continue+ const hostFill = parseColor(styleOf(node, "background-color"))+ if (Number.parseFloat(pseudo.style["z-index"] ?? "") < 0 && styleOf(node, "z-index") === "auto" && (hostFill?.a ?? 0) >= 1) continue+ const fill = parseColor(pseudo.style["background-color"] ?? "")+ const stops = gradientStops(pseudo.style["background-image"] ?? "")+ if (stops.length > 0 && fill && fill.a >= 0.9) {+ return stops.map((s) => layers.reduceRight((under, top) => blend(top, under), blend(s.color, fill)))+ }+ if (fill && fill.a >= 0.9) return [layers.reduceRight((under, top) => blend(top, under), fill)]+ }+ const image = styleOf(node, "background-image")+ if (image.includes("url(")) return []+ const tile = styleOf(node, "background-size").split(/\s+/)+ const tileWidth = Number.parseFloat(tile[0] ?? "")+ const tileHeight = Number.parseFloat(tile[1] ?? tile[0] ?? "")+ const stops = gradientStops(image)+ const radius = /([\d.]+)px/.exec(stops[0]?.raw ?? "")+ const sparseDots = image.startsWith("radial-gradient(") && radius !== null && tileWidth > 0 && tileHeight > 0 && Math.PI * Number(radius[1]) ** 2 / (tileWidth * tileHeight) < 0.5 && (stops[0]?.color.a ?? 0) > 0+ const parkedImage = tile.some((v) => /^0(?:px|%)?$/.test(v))+ if (image.includes("gradient") && !clipsText(node) && !sparseDots && !parkedImage) {+ const ground = solidGround(snapshot, node)+ const samples = gradientSamples(node, rect)+ if (samples?.every((color) => color.a < 0.005)) continue+ return (samples ?? stops.map((s) => s.color)).map((color) => layers.reduceRight((under, top) => blend(top, under), blend(color, ground)))+ }+ const rawFill = styleOf(node, "background-color")+ const fill = parseColor(rawFill)+ if (rawFill !== "" && !fill) return []+ if (fill && fill.a > 0) {+ const a = fill.a * (nodes.includes(node) && ![el, ...ancestors(snapshot, el)].includes(node) ? effectiveOpacity(snapshot, node) : 1)+ layers.push({ ...fill, a })+ if (a >= 1) break+ }+ }+ return [layers.reduceRight((under, top) => blend(top, under), WHITE)]+}++export function solidGround(snapshot: PageSnapshot, el: ElementSnapshot): Rgba {+ const layers: Rgba[] = []+ for (const node of [el, ...ancestors(snapshot, el)]) {+ const c = parseColor(styleOf(node, "background-color"))+ if (c) {+ layers.push(c)+ if (c.a >= 1) break+ }+ }+ return layers.reduceRight((under, top) => blend(top, under), WHITE)+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/copy/aphoristic-cadence.ts b/plugins/omo/skills/frontend/scripts/detect/rules/copy/aphoristic-cadence.tsnew file mode 100644index 00000000..eadc6a5f--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/copy/aphoristic-cadence.ts@@ -0,0 +1,20 @@+import type { PageRule } from "../../rule"+import { pageText } from "./support/page-text"++export const aphoristicCadence: PageRule = {+ meta: {+ id: "aphoristic-cadence", name: "Aphoristic-cadence copy", category: "slop", severity: "warning", engine: "page",+ description: "Three or more short rebuttals give unrelated sections the same cadence.",+ fixHint: "Replace repeated rebuttals with specific information and vary sentence structure.",+ },+ check: ({ snapshot }) => {+ const text = pageText(snapshot)+ const matches = [+ ...text.matchAll(/\bNot an? [a-z][^.!?]{1,40}[.!]\s+[A-Z][^.!?]{1,60}[.!]/g),+ ...text.matchAll(/\b[A-Z][^.!?]{4,80}[.!]\s+(No|Just)\s+[a-z][^.!?]{2,60}[.!]/g),+ ]+ return matches.length < 3 ? [] : [{+ element: null, message: `${matches.length} aphoristic constructions`, snippet: (matches[0]?.[0] ?? "").trim().slice(0, 80),+ }]+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/copy/broken-image.ts b/plugins/omo/skills/frontend/scripts/detect/rules/copy/broken-image.tsnew file mode 100644index 00000000..88823ea4--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/copy/broken-image.ts@@ -0,0 +1,17 @@+import { shortSnippet } from "../../core/page"+import type { PageRule } from "../../rule"++export const brokenImage: PageRule = {+ meta: {+ id: "broken-image", name: "Broken or placeholder image", category: "quality", severity: "warning", engine: "page",+ description: "An image has no usable source attribute.",+ fixHint: "Provide a real src or srcset, or remove the unused image element.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap((el) => {+ if (el.tag !== "img") return []+ const hasSource = Object.entries(el.attributes).some(([name, value]) =>+ /(?:^|[:-])(?:src|srcset)$/i.test(name.split(".")[0] ?? "")+ && value.trim() !== "" && value.trim() !== "#")+ return hasSource ? [] : [{ element: el, message: "Image source is missing, empty or a placeholder", snippet: shortSnippet(el) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/copy/em-dash-overuse.ts b/plugins/omo/skills/frontend/scripts/detect/rules/copy/em-dash-overuse.tsnew file mode 100644index 00000000..5e1324e7--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/copy/em-dash-overuse.ts@@ -0,0 +1,46 @@+import { EM_DASH } from "../../core/characters"+import { ancestors, descendants, parentOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { lineage, visibleText } from "./support/page-text"++export const emDashOveruse: PageRule = {+ meta: {+ id: "em-dash-overuse", name: "Em-dash overuse", category: "slop", severity: "advisory", engine: "page",+ description: "At least eight prose dashes appear at a density of one per 500 characters or more.",+ fixHint: "Use sentence breaks or commas where the copy repeatedly interrupts itself.",+ },+ check: ({ snapshot }) => {+ const runs = snapshot.elements.filter((el) => visibleText(snapshot, el)+ && !lineage(snapshot, el).some((a) => ["select", "option", "datalist"].includes(a.tag)))+ .map((el) => el.ownText).filter((text) => text !== "" && !/^[\u2014–\s-]+$/.test(text))+ const text = runs.join(" ").replace(/\s+/g, " ")+ let count = 0+ for (const match of text.matchAll(/\u2014+|-+/g)) {+ const run = match[0]+ if (run.startsWith(EM_DASH)) count += run.length === 2 ? 1 : run.length+ else {+ const next = text[match.index + run.length] ?? ""+ const previous = text[match.index - 1] ?? ""+ if (run.length === 2 && next !== "" && !/\s/.test(next)) count+++ else if (run.length === 3 && /[\p{L}\p{N}]/u.test(previous) && /[\p{L}\p{N}]/u.test(next)) count+++ }+ }+ const groups = new Map<number | null, number>()+ for (const li of snapshot.elements.filter((el) => el.tag === "li").slice(0, 2000)) {+ if (!visibleText(snapshot, li) || [...descendants(snapshot, li)].some((d) => d.tag === "li")) continue+ const parts = li.text.replace(/^[^\p{L}\p{N}]+/u, "").split(EM_DASH)+ const term = (parts[0] ?? "").trim()+ const rest = (parts[1] ?? "").trim()+ if (term === "" || [...term].length > 60 || term.split(/\s+/).length > 6 || /[.!?。!?]/.test(term) || rest === "") continue+ const first = [...rest][0] ?? ""+ const label = [...descendants(snapshot, li)].some((d) => [...ancestors(snapshot, d)].findIndex((a) => a.index === li.index) < 3 && d.text === term)+ if (!(first.toUpperCase() === first && /\p{L}/u.test(first)) && !label) continue+ const key = parentOf(snapshot, parentOf(snapshot, li) ?? li)?.index ?? null+ groups.set(key, (groups.get(key) ?? 0) + 1)+ }+ count = Math.max(0, count - [...groups.values()].filter((n) => n >= 3).reduce((sum, n) => sum + n, 0))+ return count < 8 || text.length > count * 500 ? [] : [{+ element: null, message: `${count} em-dashes in body text`, snippet: `${count} em-dashes in body text`,+ }]+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/copy/index.ts b/plugins/omo/skills/frontend/scripts/detect/rules/copy/index.tsnew file mode 100644index 00000000..3bac9d9c--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/copy/index.ts@@ -0,0 +1,15 @@+import type { PageRule } from "../../rule"+import { aphoristicCadence } from "./aphoristic-cadence"+import { brokenImage } from "./broken-image"+import { emDashOveruse } from "./em-dash-overuse"+import { marketingBuzzword } from "./marketing-buzzword"+import { numberedSectionLabels } from "./numbered-section-labels"+import { repeatedContainerText } from "./repeated-container-text"+import { scriptError } from "./script-error"+import { skippedHeading } from "./skipped-heading"+import { theaterSlopPhrase } from "./theater-slop-phrase"++export const COPY_RULES: readonly PageRule[] = [+ emDashOveruse, marketingBuzzword, aphoristicCadence, theaterSlopPhrase, numberedSectionLabels,+ repeatedContainerText, skippedHeading, brokenImage, scriptError,+]diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/copy/marketing-buzzword.ts b/plugins/omo/skills/frontend/scripts/detect/rules/copy/marketing-buzzword.tsnew file mode 100644index 00000000..31807971--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/copy/marketing-buzzword.ts@@ -0,0 +1,33 @@+import type { PageRule } from "../../rule"+import { pageText } from "./support/page-text"++const PHRASES = [+ "streamline your", "empower your", "supercharge your", "unleash your", "unleash the power", "leverage the power",+ "built for the modern", "trusted by leading", "trusted by the world", "best-in-class", "industry-leading",+ "world-class", "enterprise-grade", "next-generation", "cutting-edge", "transform your business", "revolutionize",+ "game-changer", "game changing", "mission-critical", "best of breed", "future-proof", "future proof",+ "seamless experience", "seamlessly integrate", "drive engagement", "drive growth", "drive results", "harness the power",+] as const++export const marketingBuzzword: PageRule = {+ meta: {+ id: "marketing-buzzword", name: "Marketing buzzword", category: "slop", severity: "warning", engine: "page",+ description: "Generic promotion replaces a concrete description of the product.",+ fixHint: "Name the action, benefit or measured result instead of a stock marketing phrase.",+ },+ check: ({ snapshot }) => {+ const text = pageText(snapshot)+ const lower = text.toLowerCase()+ let count = 0+ let sample = ""+ for (const phrase of PHRASES) {+ let from = 0+ for (let at = lower.indexOf(phrase, from); at >= 0; at = lower.indexOf(phrase, from)) {+ count+++ if (sample === "") sample = text.slice(Math.max(0, at - 12), at + phrase.length + 12).trim()+ from = at + phrase.length+ }+ }+ return count === 0 ? [] : [{ element: null, message: `${count} buzzword phrases`, snippet: sample }]+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/copy/numbered-section-labels.ts b/plugins/omo/skills/frontend/scripts/detect/rules/copy/numbered-section-labels.tsnew file mode 100644index 00000000..7878b2df--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/copy/numbered-section-labels.ts@@ -0,0 +1,34 @@+import { descendants } from "../../core/page"+import type { PageRule } from "../../rule"+import { labelBefore, labelContext, labelType, parsedIndex, styledLabel } from "./support/numbered-label"++export const numberedSectionLabels: PageRule = {+ meta: {+ id: "numbered-section-labels", name: "Tiny numbered section labels", category: "slop", severity: "advisory", engine: "page",+ description: "Multiple headings carry tiny styled numeric indices that add scaffolding rather than information.",+ fixHint: "Remove decorative section numbers or make necessary numbering part of the heading.",+ },+ check: ({ snapshot }) => {+ const seen = new Set<number>()+ const candidates = snapshot.elements.flatMap((heading) => {+ if (!["h2", "h3", "h4"].includes(heading.tag) || heading.text.length < 3) return []+ const label = labelBefore(snapshot, heading)+ if (!label || seen.has(label.index) || !labelContext(snapshot, heading, label) || !labelContext(snapshot, label, heading)+ || !["span", "p", "div", "small", "em", "strong", "b"].includes(label.tag)) return []+ const text = (label.ownText || label.text).replace(/\s+/g, " ").trim()+ const index = parsedIndex(text)+ if (index === null || !styledLabel(labelType(snapshot, label), heading)) return []+ if ([...descendants(snapshot, label)].some((el) => ["img", "picture", "video", "canvas"].includes(el.tag)+ || el.tag === "svg" && snapshot.elements[el.parent ?? -1]?.ownText.match(/^\d{2}$/))) return []+ seen.add(label.index)+ return [{ label, heading, text, index }]+ })+ const hashWords = candidates.filter((c) => c.text.startsWith("#")).map((c) => /^#\d+\s+(\S+)/.exec(c.text)?.[1]?.toLowerCase())+ const matchingHashes = hashWords.length >= 2 && hashWords[0] !== undefined && hashWords.every((w) => w === hashWords[0])+ const filtered = matchingHashes ? candidates.filter((c) => !c.text.startsWith("#")) : candidates+ if (filtered.length < 2 || new Set(filtered.map((c) => c.index)).size < 2) return []+ return filtered.map(({ label, heading, text }) => ({+ element: label, message: `${filtered.length} tiny numeric labels beside section headings`, snippet: `${text.slice(0, 24)} / ${heading.text.slice(0, 60)}`,+ }))+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/copy/repeated-container-text.ts b/plugins/omo/skills/frontend/scripts/detect/rules/copy/repeated-container-text.tsnew file mode 100644index 00000000..1e27a4c6--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/copy/repeated-container-text.ts@@ -0,0 +1,56 @@+import { ancestors, descendants, px, styleOf } from "../../core/page"+import { parseColor } from "../../core/color"+import type { PageHit, PageRule } from "../../rule"+import type { ElementSnapshot, PageSnapshot } from "../../types"+import { lineage, paintedText } from "./support/page-text"++const skip = (snapshot: PageSnapshot, el: ElementSnapshot): boolean => lineage(snapshot, el).some((a) =>+ ["table", "select", "datalist", "nav", "menu"].includes(a.tag)+ || ["navigation", "menu", "menubar", "listbox", "grid", "tablist", "radiogroup"].includes(a.attributes["role"] ?? "")+ || a.attributes["aria-hidden"] === "true")++export const repeatedContainerText: PageRule = {+ meta: {+ id: "repeated-container-text", name: "Same text repeated inside one container", category: "quality", severity: "warning", engine: "page",+ description: "One card repeats a short string in at least three different structural slots.",+ fixHint: "State the status once; remove redundant labels from the other slots.",+ },+ check: ({ snapshot }) => {+ const containers = snapshot.elements.filter((el) => {+ if (!["div", "section", "article", "aside", "main", "figure", "form", "fieldset", "details", "li"].includes(el.tag) || skip(snapshot, el)) return false+ const shadow = styleOf(el, "box-shadow")+ const border = ["top", "right", "bottom", "left"].filter((side) => (px(styleOf(el, `border-${side}-width`)) ?? 0) >= 1).length >= 3+ const radius = (px(styleOf(el, "border-top-left-radius")) ?? 0) > 0+ const background = (parseColor(styleOf(el, "background-color"))?.a ?? 0) > 0.1+ return (shadow !== "" && shadow !== "none" || border) && (radius || background)+ })+ const containerIds = new Set(containers.map((el) => el.index))+ const hits: PageHit[] = []+ for (const container of containers) {+ if (!paintedText(snapshot, container)) continue+ const nodes = [...descendants(snapshot, container)]+ if (nodes.length > 250) continue+ const groups = new Map<string, string[]>()+ for (const el of nodes) {+ const path = [...ancestors(snapshot, el)]+ const owned = path.slice(0, path.findIndex((a) => a.index === container.index))+ if (owned.some((a) => containerIds.has(a.index)) || skip(snapshot, el) || !paintedText(snapshot, el)) continue+ if (/icon|material-symbols|(?:^|\s)fa[srlbd]?(?:\s|-|$)/i.test(el.attributes["class"] ?? "")) continue+ const text = el.ownText.trim()+ if (text.length < 4 || text.length > 48 || !/[a-zA-Z]/.test(text)) continue+ const signature = [el, ...owned].map((a) => {+ const classes = (a.attributes["class"] ?? "").split(/\s+/).filter((c) => c !== ""+ && !c.split(/[-_]/).some((part) => part.length >= 4 && /^[a-f\d]+$/i.test(part) && /\d/.test(part))).sort().join(".")+ return `${a.tag}${classes === "" ? "" : `.${classes}`}`+ }).join(">")+ const signatures = groups.get(text) ?? []+ signatures.push(signature)+ groups.set(text, signatures)+ }+ for (const [text, signatures] of groups) if (signatures.length >= 3 && new Set(signatures).size >= 3) hits.push({+ element: container, message: `Same text rendered ${signatures.length} times in distinct slots`, snippet: text.slice(0, 40),+ })+ }+ return hits+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/copy/script-error.ts b/plugins/omo/skills/frontend/scripts/detect/rules/copy/script-error.tsnew file mode 100644index 00000000..54e5aba1--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/copy/script-error.ts@@ -0,0 +1,38 @@+import type { PageHit, PageRule } from "../../rule"++export const scriptError: PageRule = {+ meta: {+ id: "script-error", name: "Uncaught script error on load", category: "quality", severity: "error", engine: "page",+ description: "An uncaught exception or rejected promise occurred while the page loaded.",+ fixHint: "Fix the failing script or handle its rejected promise, then verify the page loads without uncaught errors.",+ },+ check: ({ snapshot }) => {+ if (!snapshot.scriptErrorsCaptured) {+ return [{+ element: null,+ message: "Script errors were not captured: this renderer could not install its error probe before the page's scripts",+ snippet: snapshot.url,+ severity: "advisory",+ severityFixed: true,+ }]+ }+ const counts = new Map<string, number>()+ const hits: PageHit[] = []+ for (const error of new Set(snapshot.scriptErrors)) {+ const hydration = /Minified React error #(418|419|422|423|425)(?!\d)/.test(error)+ const media = error.includes("AbortError") && error.includes("The play() request was interrupted")+ const adTech = /browsingTopics|joinAdInterestGroup|runAdAuction|adsbygoogle|_prebidjs/.test(error)+ const kind = adTech ? "ad-tech" : hydration || media ? "recoverable" : "uncaught"+ const count = counts.get(kind) ?? 0+ if (error.trim() === "" || count >= 3) continue+ counts.set(kind, count + 1)+ hits.push({+ element: null,+ message: kind === "uncaught" ? "Uncaught page script error" : `Page script error (${kind})`,+ snippet: error,+ severity: kind === "uncaught" ? "error" : "advisory",+ })+ }+ return hits+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/copy/skipped-heading.ts b/plugins/omo/skills/frontend/scripts/detect/rules/copy/skipped-heading.tsnew file mode 100644index 00000000..b2c0acf7--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/copy/skipped-heading.ts@@ -0,0 +1,81 @@+import { childrenOf, descendants, headingLevel, parentOf } from "../../core/page"+import type { PageHit, PageRule } from "../../rule"+import { displayed, lineage } from "./support/page-text"++export const skippedHeading: PageRule = {+ meta: {+ id: "skipped-heading", name: "Skipped heading level", category: "quality", severity: "warning", engine: "page",+ description: "A heading jumps over a level in the visible content outline.",+ fixHint: "Use the next heading level and style it independently of its semantic rank.",+ },+ check: ({ snapshot }) => {+ const hits: PageHit[] = []+ let previous = 0+ let previousText = ""+ let previousFooter: number | undefined+ let previousOpensFooter = false+ const squash = (text: string): string => text.replace(/\s/g, "")+ const sourceTags = ["script", "style", "noscript", "template"]+ const textChars = snapshot.elements.filter((el) => displayed(snapshot, el) && el.style["visibility"] !== "hidden" && !sourceTags.includes(el.tag))+ .reduce((total, el) => total + [...squash(el.ownText)].length, 0)+ const hidden = (el: typeof snapshot.elements[number]): boolean =>+ el.attributes["inert"] !== undefined || el.attributes["aria-hidden"]?.trim().toLowerCase() === "true"+ const modals = snapshot.elements.filter((el) =>+ (el.attributes["aria-modal"] === "true" || ["dialog", "alertdialog"].includes(el.attributes["role"] ?? "")+ || el.tag === "dialog" && el.attributes["open"] !== undefined)+ && !hidden(el) && displayed(snapshot, el) && el.rect.width > 0 && el.rect.height > 0 && el.style["visibility"] !== "hidden")+ const mockups = new Set(snapshot.elements.filter((root) => {+ if (!hidden(root) || root.rect.width < 120 || root.rect.height < 80) return false+ if (["html", "body", "main", "header", "footer", "nav", "aside", "section", "article", "form", "dialog", "li", "tr", "td", "th", "tbody", "thead", "table", "details", "summary"].includes(root.tag)) return false+ if ((root.attributes["role"] ?? "").trim().split(/\s+/).some((r) => r !== "" && !["presentation", "none", "img", "figure", "group"].includes(r))) return false+ if (root.attributes["aria-modal"] !== undefined || root.attributes["data-aria-hidden"] !== undefined || ["fixed", "sticky"].includes(root.style["position"] ?? "")) return false+ const names = `${root.attributes["class"] ?? ""} ${root.attributes["id"] ?? ""}`+ if (/(?:^|[\s_-])(clones?|cloned|copy|duplicate|dup|carousel|embla|flicking|glide|keen|slick|slides?|slider|splide|swiper|marquee|ticker|menu|submenu|dropdown|popup|popover|modal|drawer|dialog|tooltip|toast|offcanvas|overlay|nav|navbar|navigation|panel|tab|tabpanel|accordion|collapse|collapsible|intro|splash|loader|preloader|loading|banner|cookies?|consent|sidebar|sidenav|toc)(?:$|[\s_-])/i.test(names)) return false+ const ancestors = lineage(snapshot, root).slice(1)+ if (ancestors.some((a) => ["h1", "h2", "h3", "h4", "h5", "h6", "p", "a", "button", "label", "summary", "legend", "caption", "figcaption", "blockquote", "q"].includes(a.tag))) return false+ const nodes = [root, ...descendants(snapshot, root)]+ if (nodes.length > 3000 || nodes.some((el) => el.tag === "h1")) return false+ const runs = nodes.filter((el) => displayed(snapshot, el) && el.style["visibility"] !== "hidden"+ && !sourceTags.includes(el.tag) && squash(el.ownText) !== "")+ const chars = runs.reduce((total, el) => total + [...squash(el.ownText)].length, 0)+ if (runs.length < 3 || textChars === 0 || chars * 2 >= textChars) return false+ const fields = nodes.filter((el) => ["input", "select", "textarea"].includes(el.tag) && !(el.tag === "input" && el.attributes["type"]?.toLowerCase() === "hidden"))+ const linkedRuns = runs.filter((el) => lineage(snapshot, el).some((a) => a.tag === "a" && (a.attributes["href"] ?? "").trim() !== ""))+ if (fields.length >= 2 || fields.length > 0 && nodes.some((el) => el.tag === "label") || linkedRuns.length * 2 >= runs.length) return false+ if (modals.some((modal) => !nodes.includes(modal) && !lineage(snapshot, root).includes(modal))) return false+ const text = squash(root.text)+ if (text !== "" && ancestors.some((a) => squash(a.attributes["aria-label"] ?? "").includes(text))) return false+ const parent = parentOf(snapshot, root)+ const peers = parent ? childrenOf(snapshot, parent).filter((el) => el.index !== root.index) : []+ const classes = (root.attributes["class"] ?? "").split(/\s+/).filter(Boolean)+ return !peers.some((peer) => {+ const peerClasses = (peer.attributes["class"] ?? "").split(/\s+/).filter(Boolean)+ const sameShape = peer.tag === root.tag && (classes.length === 0) === (peerClasses.length === 0) && classes.every((c) => peerClasses.includes(c))+ const shown = displayed(snapshot, peer) && peer.style["visibility"] !== "hidden" && !hidden(peer)+ if (shown && (sameShape && peer.rect.width > 0 && peer.rect.height > 0 || text !== "" && squash(peer.text) === text)) return true+ const alternative = peer.rect.width <= 1 || peer.rect.height <= 1 || /sr-only|visually-?hidden|screen-?reader|a11y-hidden|hidden-visually/i.test(peer.attributes["class"] ?? "")+ return shown && alternative && peer.text.trim() !== "" && !/\b(demo|demonstration|illustrat\w*|interface|screen ?shots?|mock-?ups?|graphic|animation|animated|preview|image|video|visual|diagram|depict\w*|shows|showing|displayed)\b/i.test(peer.text)+ })+ }).map((el) => el.index))+ for (const el of snapshot.elements) {+ const level = headingLevel(el)+ if (level === null || !displayed(snapshot, el) || el.rect.width <= 0 || el.rect.height <= 0) continue+ const path = lineage(snapshot, el)+ if (path.some((a) => mockups.has(a.index))) continue+ if (path.some((a) => a.style["visibility"] === "hidden" || (a.tag === "dialog" && a.attributes["open"] === undefined))) continue+ const footer = path.find((a) => a.tag === "footer" || a.attributes["role"] === "contentinfo" || a.attributes["id"] === "footer")?.index+ const opensFooter = footer !== undefined && footer !== previousFooter+ const intoFooter = footer !== undefined && (opensFooter || previousOpensFooter)+ const skips = previous > 0 && level > previous + 1+ if (skips && !intoFooter) hits.push({+ element: el, message: `h${previous} followed by h${level}; missing h${previous + 1}`,+ snippet: `${previousText.slice(0, 60)} / ${el.text.slice(0, 60)}`,+ })+ previousOpensFooter = opensFooter && previous > 0 && !skips+ previousFooter = footer+ previous = level+ previousText = el.text+ }+ return hits+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/copy/support/numbered-label.ts b/plugins/omo/skills/frontend/scripts/detect/rules/copy/support/numbered-label.tsnew file mode 100644index 00000000..2a6f2a85--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/copy/support/numbered-label.ts@@ -0,0 +1,94 @@+import { childrenOf, descendants, effectiveBackground, fontSizePx, parentOf, px, styleOf } from "../../../core/page"+import { parseColor } from "../../../core/color"+import { parseShadow } from "../../../core/shadow"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { displayed, lineage } from "./page-text"++export const parsedIndex = (text: string): number | null => {+ if (text.length > 40) return null+ const hash = /^#([0-9]{1,2})(?: [^ ].*)?$/.exec(text)+ if (hash && /^#\d+ (rated|ranked|rank|best|top|in|pick|choice|overall|seller|bestseller|selling|voted|place|trending)\b/i.test(text)) return null+ const match = hash ?? /^([0-9]{2})$/.exec(text) ?? /^([0-9]{1,2})\s*[^0-9A-Za-z_\s]\s*\S/.exec(text)+ return match?.[1] !== undefined && Number(match[1]) <= 40 ? Number(match[1]) : null+}++export const labelBefore = (snapshot: PageSnapshot, heading: ElementSnapshot): ElementSnapshot | null => {+ let current = heading+ for (let level = 0; level <= 4; level++) {+ const parent = parentOf(snapshot, current)+ if (!parent) return null+ const siblings = childrenOf(snapshot, parent)+ const label = siblings[siblings.findIndex((s) => s.index === current.index) - 1]+ if (label) {+ const l = label.rect+ const h = heading.rect+ if (level > 1 && (l.width <= 0 || l.height <= 0 || h.width <= 0 || h.height <= 0 || l.y >= h.y + h.height+ || Math.max(h.y - l.y - l.height, h.x - l.x - l.width, 0) > 96)) return null+ return label+ }+ if (["body", "html"].includes(parent.tag)) return null+ current = parent+ }+ return null+}++export const labelType = (snapshot: PageSnapshot, label: ElementSnapshot): ElementSnapshot => {+ let el = label+ for (let level = 0; level < 3; level++) {+ if (el.ownText !== "") return el+ const children = childrenOf(snapshot, el).filter((c) => c.text.trim() !== "")+ const only = children[0]+ if (children.length !== 1 || !only) return el+ el = only+ }+ return el+}++const drawsBox = (snapshot: PageSnapshot, el: ElementSnapshot): boolean => {+ const parent = parentOf(snapshot, el)+ const under = parent ? effectiveBackground(snapshot, parent) : { r: 255, g: 255, b: 255 }+ const fill = effectiveBackground(snapshot, el)+ const image = styleOf(el, "background-image")+ const border = ["top", "right", "bottom", "left"].filter((side) =>+ (px(styleOf(el, `border-${side}-width`)) ?? 0) >= 0.5+ && !["none", "hidden", ""].includes(styleOf(el, `border-${side}-style`))+ && (parseColor(styleOf(el, `border-${side}-color`))?.a ?? 0) > 0).length >= 3+ return Math.max(Math.abs(fill.r - under.r), Math.abs(fill.g - under.g), Math.abs(fill.b - under.b)) > 3+ || image !== "" && image !== "none" || border+ || parseShadow(styleOf(el, "box-shadow")).some((layer) => layer.color.a >= 0.03+ && (layer.x !== 0 || layer.y !== 0 || layer.blur > 0 || layer.spread !== 0))+}++export const labelContext = (snapshot: PageSnapshot, el: ElementSnapshot, partner: ElementSnapshot = el): boolean => {+ const path = lineage(snapshot, el)+ if (!displayed(snapshot, el) || path.some((a) => ["nav", "form", "table", "thead", "tbody", "tfoot", "figure", "figcaption", "ol", "ul", "li"].includes(a.tag)+ || a.attributes["role"] === "navigation" || a.attributes["aria-hidden"] === "true"+ || a.attributes["data-impeccable-allow-kickers"] !== undefined+ || /breadcrumb/i.test(`${a.attributes["class"] ?? ""} ${a.attributes["aria-label"] ?? ""}`))) return false+ const context = path.find((a) => ["article", "button", "a", "li"].includes(a.tag) || ["listitem", "option"].includes(a.attributes["role"] ?? ""))+ if (!context || context.rect.height > snapshot.viewport.height * 2 || !lineage(snapshot, partner).includes(context)) return true+ if (context.tag !== "article") return false+ const above = lineage(snapshot, context).slice(1)+ if (above.some((a) => ["a", "button", "li"].includes(a.tag) || ["listitem", "option"].includes(a.attributes["role"] ?? ""))) return false+ if (path.slice(1, path.findIndex((a) => a.index === context.index) + 1).some((a) =>+ lineage(snapshot, partner).includes(a) && drawsBox(snapshot, a))) return false+ let below = context+ for (const up of above.slice(0, 3)) {+ if (up.tag === "body") break+ const otherArticle = [...descendants(snapshot, up)].some((a) => a.tag === "article" && a.index !== context.index)+ if (!otherArticle && drawsBox(snapshot, up)) return false+ if (up.children.length !== 1 || up.children[0] !== below.index) break+ below = up+ }+ return true+}++export const styledLabel = (label: ElementSnapshot, heading: ElementSnapshot): boolean => {+ const size = fontSizePx(label)+ const headingSize = fontSizePx(heading)+ if (size <= 0 || size > Math.max(13, Math.min(16, headingSize * 0.45)) || headingSize > 0 && headingSize < size * 1.3) return false+ const color = parseColor(styleOf(label, "color"))+ return /mono/i.test(styleOf(label, "font-family")) || Number(styleOf(label, "font-weight")) >= 600+ || (px(styleOf(label, "letter-spacing")) ?? 0) >= 0.5 || styleOf(label, "text-transform") === "uppercase"+ || (color !== null && Math.max(color.r, color.g, color.b) - Math.min(color.r, color.g, color.b) >= 40)+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/copy/support/page-text.ts b/plugins/omo/skills/frontend/scripts/detect/rules/copy/support/page-text.tsnew file mode 100644index 00000000..c72a9f06--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/copy/support/page-text.ts@@ -0,0 +1,37 @@+import { ancestors, isRendered, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"++export const lineage = (snapshot: PageSnapshot, el: ElementSnapshot): readonly ElementSnapshot[] =>+ [el, ...ancestors(snapshot, el)]++export const displayed = (snapshot: PageSnapshot, el: ElementSnapshot): boolean =>+ lineage(snapshot, el).every((a) => styleOf(a, "display") !== "none" && styleOf(a, "content-visibility") !== "hidden")++export const visibleText = (snapshot: PageSnapshot, el: ElementSnapshot): boolean => {+ if (!isRendered(snapshot, el) || !displayed(snapshot, el)) return false+ return lineage(snapshot, el).every((a) => styleOf(a, "visibility") !== "hidden"+ && !(a.tag === "dialog" && a.attributes["open"] === undefined))+}++export const pageText = (snapshot: PageSnapshot): string =>+ snapshot.elements.filter((el) => visibleText(snapshot, el) && !["script", "style", "template", "noscript"].includes(el.tag))+ .map((el) => el.ownText).filter(Boolean).join(" ").replace(/\s+/g, " ").trim()++export const paintedText = (snapshot: PageSnapshot, el: ElementSnapshot): boolean => {+ if (!visibleText(snapshot, el)) return false+ let left = el.rect.x+ let top = el.rect.y+ let right = left + el.rect.width+ let bottom = top + el.rect.height+ for (const a of ancestors(snapshot, el)) {+ if (["hidden", "clip", "auto", "scroll"].includes(styleOf(a, "overflow-x"))) {+ left = Math.max(left, a.rect.x)+ right = Math.min(right, a.rect.x + a.rect.width)+ }+ if (["hidden", "clip", "auto", "scroll"].includes(styleOf(a, "overflow-y"))) {+ top = Math.max(top, a.rect.y)+ bottom = Math.min(bottom, a.rect.y + a.rect.height)+ }+ }+ return right > left && bottom > top+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/copy/theater-slop-phrase.ts b/plugins/omo/skills/frontend/scripts/detect/rules/copy/theater-slop-phrase.tsnew file mode 100644index 00000000..c58bab88--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/copy/theater-slop-phrase.ts@@ -0,0 +1,21 @@+import type { PageRule } from "../../rule"+import { pageText } from "./support/page-text"++const HEADS = [+ "accessibility", "accountability", "agile", "alignment", "compliance", "diversity", "engagement", "governance", "growth",+ "hiring", "hygiene", "innovation", "inclusion", "kindness", "leadership", "metrics", "privacy", "process", "productivity",+ "quality", "safety", "security", "strategy", "sustainability", "transparency", "trust", "wellness",+] as const++export const theaterSlopPhrase: PageRule = {+ meta: {+ id: "theater-slop-phrase", name: "Theater framing copy", category: "slop", severity: "advisory", engine: "page",+ description: "Calling a practice theater dismisses it without explaining the defect.",+ fixHint: "Describe the missing behavior or evidence instead of dismissing it as theater.",+ },+ check: ({ snapshot }) => {+ const match = [...pageText(snapshot).matchAll(/\b(\w+)\s+theater\b/gi)]+ .find((m) => HEADS.some((head) => head === m[1]?.toLowerCase()))+ return match ? [{ element: null, message: "Dismissive theater framing", snippet: match[0] }] : []+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/blinking-cursor.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/blinking-cursor.tsnew file mode 100644index 00000000..4181c7bf--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/blinking-cursor.ts@@ -0,0 +1,48 @@+import type { PageRule } from "../../rule"+import { parseColor } from "../../core/color"+import { ancestors, shortSnippet, styleOf } from "../../core/page"+import { context, radii, visible } from "./support/appearance"+import { infiniteNames, keyframes, toggles } from "./support/keyframes"+export const blinkingCursor: PageRule = {+ meta: {+ id: "blinking-cursor",+ name: "Decorative blinking cursor",+ category: "slop",+ severity: "advisory",+ engine: "page",+ description: "A fake caret blinks in non-editable landing content.",+ fixHint: "Remove the decorative cursor and let actual editable fields draw their caret.",+ },+ check: ({ snapshot }) =>+ snapshot.elements.flatMap((e) => {+ if (+ e.rect.width <= 0 || e.rect.height <= 0 ||+ styleOf(e, "display") === "none" || e.attributes["hidden"] !== undefined ||+ [...ancestors(snapshot, e)].some(a => !visible(snapshot, a)) ||+ ["input", "textarea", "select", "img", "svg", "script", "style"].includes(e.tag) ||+ e.rect.y > 1200 ||+ context(+ snapshot,+ e,+ (a) => a.attributes["role"] === "textbox" || ["", "true", "plaintext-only"].includes(a.attributes["contenteditable"] ?? "false"),+ )+ )+ return []+ const animated = infiniteNames(e.style).some((n) => /blink|caret|cursor/i.test(n) || toggles(keyframes(snapshot, n) ?? []))+ if (!animated) return []+ const text = e.text.trim(),+ { width: w, height: h } = e.rect+ const glyph = /^[_|\u2580-\u259f\u25a0\u25ae\u2759\u275a\uff5c]$/.test(text)+ const bg = parseColor(styleOf(e, "background-color"))+ const filled =+ (bg !== null && bg.a > 0.2) ||+ ["left", "right", "bottom"].some((side) => Number.parseFloat(styleOf(e, "border-" + side + "-width")) >= 1)+ const block =+ text === "" &&+ e.children.length === 0 &&+ filled &&+ ((w >= 1 && w <= 24 && h >= 6 && h <= 48 && h >= w) || (h >= 1 && h <= 6 && w >= 4 && w <= 24)) &&+ Math.max(...radii(e)) < 0.4 * Math.min(w, h)+ return glyph || block ? [{ element: e, message: "Blinking decorative cursor in the landing region", snippet: shortSnippet(e) }] : []+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/border-accent-on-rounded.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/border-accent-on-rounded.tsnew file mode 100644index 00000000..ed904b48--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/border-accent-on-rounded.ts@@ -0,0 +1,14 @@+import type { PageRule } from "../../rule"+import { borderHits } from "./support/borders"+export const borderAccentOnRounded: PageRule = {+ meta: {+ id: "border-accent-on-rounded",+ name: "Border accent on rounded element",+ category: "slop",+ severity: "warning",+ engine: "page",+ description: "A heavy accent band competes with rounded corners.",+ fixHint: "Remove the accent border or square the container.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap((e) => borderHits(snapshot, e, "border-accent-on-rounded")),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/bounce-easing.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/bounce-easing.tsnew file mode 100644index 00000000..2e26298b--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/bounce-easing.ts@@ -0,0 +1,83 @@+import type { PageHit, PageRule } from "../../rule"+import { shortSnippet, styleOf } from "../../core/page"+import { borderSafe, splitTop, visible } from "./support/appearance"+import { keyframes, onlyUnitPulse, overshoot } from "./support/keyframes"+import { pageIgnored } from "../color/support/page-ignore"+import { textPainted } from "../color/support/painted-text"+import { bounceEasing as sourceBounce } from "../source/bounce-easing"+import { cssBlocks } from "../../core/source"+import { matchesSelector } from "./support/css-candidates"+import type { ElementSnapshot } from "../../types"++function easingKey(value: string): string {+ const curve = /cubic-bezier\(([^)]+)\)/i.exec(value)+ if (curve) return `cubic-bezier(${(curve[1] ?? "").split(",").map(Number).join(",")})`+ return value.replace(/\s/g, "").toLowerCase()+}+export const bounceEasing: PageRule = {+ meta: {+ id: "bounce-easing",+ name: "Bounce or elastic easing",+ category: "slop",+ severity: "advisory",+ engine: "page",+ description: "Animation names or timing curves imply overshooting motion.",+ fixHint: "Use a smooth deceleration or document an intentional easing in allowEasings.",+ },+ check: ({ snapshot, config }) => {+ const covered = new Set<string>()+ const hits: PageHit[] = []+ const allowed = (value: string): boolean =>+ (config.allowEasings ?? []).some((easing) => easingKey(easing) === easingKey(value))+ const painted = (el: ElementSnapshot): boolean => visible(snapshot, el) && textPainted(snapshot, el)+ && el.rect.x + el.rect.width > 0 && el.rect.x < snapshot.document.scrollWidth+ && el.rect.y + el.rect.height > 0 && el.rect.y < snapshot.document.scrollHeight+ for (const e of snapshot.elements) {+ if (!painted(e) || borderSafe.has(e.tag) || e.tag === "label" || pageIgnored(snapshot, e, "bounce-easing")) continue+ const names = splitTop(styleOf(e, "animation-name")).filter((n) => /bounce|elastic|wobble|jiggle|spring/i.test(n))+ const named = names.filter((n) => {+ const f = keyframes(snapshot, n)+ return !allowed(n) && (f === null || !onlyUnitPulse(f))+ })+ const curves = [styleOf(e, "animation-timing-function"), styleOf(e, "transition-timing-function")]+ .flatMap((v) => splitTop(v))+ .filter((v) => !allowed(v) && overshoot(v))+ const tailwind = /(?:^|\s)animate-bounce(?:$|\s)/.test(e.attributes["class"] ?? "") && !allowed("animate-bounce")+ if (named.length === 0 && !tailwind && curves.length === 0) continue+ hits.push({ element: e, message: "Overshooting motion: " + (curves[0] ?? (named.join(",") || "animate-bounce")), snippet: shortSnippet(e) })+ for (const name of named) covered.add(easingKey(`animation: ${name}`))+ for (const curve of curves) covered.add(easingKey(curve))+ if (tailwind) {+ covered.add(easingKey("animate-bounce"))+ covered.add(easingKey("animation: bounce"))+ }+ }+ const original = snapshot.cssText.join("\n")+ const css = original.replace(/(^|[;{}])\s*(--[\w-]+)\s*:\s*([^;{}]+)/g, (whole: string, _prefix: string, name: string) =>+ new RegExp(`var\\(\\s*${name}\\s*[,)]`).test(original) ? whole : whole.replace(/[^{}\n;]/g, " "))+ const blocks = cssBlocks(css)+ const lines = css.split("\n")+ const forms = sourceBounce.check({ file: { path: "captured.css", text: css }, config })+ for (const form of forms) {+ const name = form.message.startsWith("animation: ") ? form.message.slice("animation: ".length) : null+ if (allowed(name ?? form.message)) continue+ if (name) {+ const frames = keyframes(snapshot, name)+ if (frames !== null && onlyUnitPulse(frames)) continue+ }+ const key = easingKey(form.message)+ if (covered.has(key)) continue+ const offset = lines.slice(0, form.line - 1).reduce((sum, line) => sum + line.length + 1, 0) + form.column - 1+ const block = blocks.find((candidate) => offset >= candidate.offset && offset < candidate.offset + candidate.body.length)+ if (block && !block.selector.split(",").every((part) => /^(?:from|to|[\d.]+%)$/i.test(part.trim()))) {+ const matches = snapshot.elements.filter((el) => block.selector.split(",").some((selector) => matchesSelector(snapshot, el, selector.trim())))+ const applies = (el: ElementSnapshot): boolean => name+ ? splitTop(styleOf(el, "animation-name")).some((value) => easingKey(`animation: ${value}`) === key)+ : [styleOf(el, "animation-timing-function"), styleOf(el, "transition-timing-function")].flatMap((value) => splitTop(value)).some((value) => easingKey(value) === key)+ if (!matches.some((el) => painted(el) && !pageIgnored(snapshot, el, "bounce-easing") && applies(el))) continue+ }+ hits.push({ element: null, message: form.message, snippet: form.snippet })+ }+ return hits+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/buried-raster.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/buried-raster.tsnew file mode 100644index 00000000..8e62b54a--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/buried-raster.ts@@ -0,0 +1,72 @@+import type { PageRule } from "../../rule"+import type { ElementSnapshot } from "../../types"+import { ancestors, childrenOf, parentOf, shortSnippet, styleOf } from "../../core/page"+import { colorsIn } from "../../core/color"+import { splitTop } from "./support/appearance"+import { pendingRaster } from "./support/raster-state"+export const buriedRaster: PageRule = {+ meta: {+ id: "buried-raster",+ name: "Raster buried under a wash or opacity",+ category: "quality",+ severity: "warning",+ engine: "page",+ description: "A raster image is almost invisible under a wash or low opacity.",+ fixHint: "Let the photo or material show through, or remove the unused raster.",+ },+ check: ({ snapshot }) => {+ const raster = (e: ElementSnapshot): boolean =>+ ["img", "picture", "video", "canvas"].includes(e.tag) || /url\(/i.test(styleOf(e, "background-image"))+ return snapshot.elements.flatMap((e) => {+ const bg = styleOf(e, "background-image"),+ src = e.attributes["src"] ?? ""+ if (e.rect.width <= 0 || e.rect.height <= 0 || styleOf(e, "display") === "none" || !raster(e) || pendingRaster(snapshot, e)) return []+ const urls = [...bg.matchAll(/url\(["']?([^)]*?)["']?\)/gi)].map((m) => m[1] ?? "")+ const svg = (s: string): boolean => /^data:image\/svg\+xml/i.test(s) || /\.svg(?:[?#]|$)/i.test(s)+ if (e.tag === "img" ? svg(src) : urls.length > 0 && urls.every(svg)) return []+ const opacity = Number(styleOf(e, "opacity"))+ const faint = Number.isFinite(opacity) && opacity >= 0 && opacity < 0.15+ const layers = splitTop(bg),+ imageAt = layers.findIndex((l) => /url\(/i.test(l))+ const washed =+ imageAt >= 0 &&+ layers.slice(0, imageAt).some((l) => {+ const stops = colorsIn(l)+ return /gradient\(/i.test(l) && stops.length > 0 && stops.every((c) => c.a >= 0.9)+ })+ if (!faint && !washed) return []+ if (faint) {+ if (+ (e.rect.width <= 48 && e.rect.height <= 48) ||+ [...styleOf(e, "filter").matchAll(/blur\(([\d.]+)px\)/g)].some((m) => Number(m[1]) >= 4)+ )+ return []+ const area = e.rect.width * e.rect.height,+ p = parentOf(snapshot, e)+ const cover = (n: ElementSnapshot): boolean => {+ if (n.index === e.index || !raster(n) || Number(styleOf(n, "opacity")) < 0.15 || styleOf(n, "display") === "none") return false+ const w = Math.max(0, Math.min(e.rect.x + e.rect.width, n.rect.x + n.rect.width) - Math.max(e.rect.x, n.rect.x))+ const h = Math.max(0, Math.min(e.rect.y + e.rect.height, n.rect.y + n.rect.height) - Math.max(e.rect.y, n.rect.y))+ return w * h >= area * 0.5+ }+ if (+ (p && childrenOf(snapshot, p).some(cover)) ||+ [...ancestors(snapshot, e)]+ .slice(0, 2)+ .filter((a) => a.tag !== "body")+ .some(cover)+ )+ return []+ }+ const blend = [styleOf(e, "background-blend-mode"), styleOf(e, "mix-blend-mode")].flatMap(v => v.split(","))+ if (blend.some(v => v.trim() !== "" && v.trim() !== "normal")) return []+ return [+ {+ element: e,+ message: faint ? "Raster at opacity " + opacity : "Raster covered by a near-opaque gradient",+ snippet: shortSnippet(e),+ },+ ]+ })+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/codex-grid-background.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/codex-grid-background.tsnew file mode 100644index 00000000..8630e5ff--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/codex-grid-background.ts@@ -0,0 +1,34 @@+import type { PageRule } from "../../rule"+import { shortSnippet } from "../../core/page"+import { splitTop, visible } from "./support/appearance"+export const codexGridBackground: PageRule = {+ meta: {+ id: "codex-grid-background",+ name: "Decorative grid-line background",+ category: "slop",+ severity: "advisory",+ engine: "page",+ description: "Tiled hairline gradients draw a decorative grid behind content.",+ fixHint: "Reserve grids for measurement or canvas surfaces; use a plain content background.",+ },+ check: ({ snapshot }) => {+ const e = snapshot.elements.find(+ (e) =>+ visible(snapshot, e) &&+ [e.style, e.before?.style, e.after?.style].some((s) => {+ const image = s?.["background-image"] ?? "",+ size = s?.["background-size"] ?? ""+ return (+ splitTop(image).filter(+ (layer) =>+ layer.includes("linear-gradient(") &&+ /(?:\b[0-9]{1,3}px\s*,\s*(?:transparent|rgba?\([^)]*[, /]\s*0\s*\)))|(?:transparent\s+calc\(100%\s*-\s*[0-9]{1,3}px\))/i.test(+ layer,+ ),+ ).length >= 2 && /\b[0-9]{1,3}px\b/.test(size)+ )+ }),+ )+ return e ? [{ element: e, message: "Tiled two-axis gradient grid", snippet: shortSnippet(e) }] : []+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/design-system-radius.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/design-system-radius.tsnew file mode 100644index 00000000..d1f3a9e8--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/design-system-radius.ts@@ -0,0 +1,31 @@+import type { PageRule } from "../../rule"+import { shortSnippet, styleOf } from "../../core/page"+import { corners, length, splitTop, visible } from "./support/appearance"+export const designSystemRadius: PageRule = {+ meta: {+ id: "design-system-radius",+ name: "Radius outside DESIGN.md",+ category: "quality",+ severity: "advisory",+ engine: "page",+ description: "A corner radius is outside the project radius scale.",+ fixHint: "Use a documented radius token or deliberately update the scale.",+ },+ check: ({ snapshot, config }) => {+ const tokens = config.designTokens?.radii+ if (!tokens?.length) return []+ return snapshot.elements.flatMap((e) => {+ if (!visible(snapshot, e)) return []+ const values = [+ ...new Set(+ corners+ .flatMap((c) => splitTop(styleOf(e, "border-" + c + "-radius"), /\s/))+ .filter((v) => !v.includes("%"))+ .map(length)+ .filter((v) => Number.isFinite(v) && v > 0.5 && !tokens.some((t) => Math.abs(t - v) <= 0.5 || (t >= 99 && v >= 99))),+ ),+ ]+ return values.map((v) => ({ element: e, message: v + "px radius is outside the project scale", snippet: shortSnippet(e) }))+ })+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/gpt-thin-border-wide-shadow.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/gpt-thin-border-wide-shadow.tsnew file mode 100644index 00000000..b85a8b49--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/gpt-thin-border-wide-shadow.ts@@ -0,0 +1,66 @@+import type { PageRule } from "../../rule"+import type { ElementSnapshot } from "../../types"+import { childrenOf, effectiveBackground, parentOf, shortSnippet, styleOf } from "../../core/page"+import { parseColor, WHITE } from "../../core/color"+import { parseShadow } from "../../core/shadow"+import { length, showsOver, sides, visible } from "./support/appearance"+export const gptThinBorderWideShadow: PageRule = {+ meta: {+ id: "gpt-thin-border-wide-shadow",+ name: "Hairline border with wide shadow",+ category: "slop",+ severity: "advisory",+ engine: "page",+ description: "Comparable cards repeat a hairline edge and broad halo.",+ fixHint: "Choose one edge treatment across the row: border or elevation.",+ },+ check: ({ snapshot }) => {+ const pair = (e: ElementSnapshot): boolean => {+ if (!visible(snapshot, e)) return false+ const p = parentOf(snapshot, e),+ surface = p ? effectiveBackground(snapshot, p) : WHITE+ const halo = parseShadow(styleOf(e, "box-shadow")).some(+ (l) => !l.inset && l.color.a >= 0.12 && l.blur + Math.min(0, l.spread) >= 32 && showsOver(l.color, surface),+ )+ if (!halo) return false+ const fill = effectiveBackground(snapshot, e)+ return (+ sides.filter((side) => {+ const w = length(styleOf(e, "border-" + side + "-width")),+ c = parseColor(styleOf(e, "border-" + side + "-color"))+ return w > 0 && w <= 1.5 && c !== null && c.a >= 0.28 && showsOver(c, fill)+ }).length >= 2+ )+ }+ const matches = (a: ElementSnapshot, b: ElementSnapshot): boolean =>+ ["width", "height"].every((k) => {+ const x = k === "width" ? a.rect.width : a.rect.height,+ y = k === "width" ? b.rect.width : b.rect.height+ return Math.max(x, y) > 0 && Math.abs(x - y) / Math.max(x, y) <= 0.25+ })+ return snapshot.elements.flatMap((e) => {+ if (!pair(e)) return []+ let cell = e+ for (let depth = 0; depth <= 2; depth++) {+ const p = parentOf(snapshot, cell)+ if (!p) break+ const siblings = childrenOf(snapshot, p),+ at = siblings.findIndex((s) => s.index === cell.index)+ let count = 1+ for (const sibling of siblings.slice(Math.max(0, at - 24), at + 25)) {+ if (sibling.index === cell.index || (depth > 0 && sibling.tag !== cell.tag)) continue+ let level: readonly ElementSnapshot[] = [sibling],+ budget = 32+ for (let i = 0; i < depth; i++) {+ level = level.flatMap((n) => childrenOf(snapshot, n)).slice(0, budget)+ budget -= level.length+ }+ count += level.filter((n) => matches(e, n) && pair(n)).length+ }+ if (count >= 3) return [{ element: e, message: "Hairline border and broad shadow repeated across a row", snippet: shortSnippet(e) }]+ cell = p+ }+ return []+ })+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/hard-offset-shadow.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/hard-offset-shadow.tsnew file mode 100644index 00000000..ccde508d--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/hard-offset-shadow.ts@@ -0,0 +1,31 @@+import { isRendered, shortSnippet, styleOf } from "../../core/page"+import { parseShadow } from "../../core/shadow"+import type { PageRule } from "../../rule"++const MIN_OFFSET_PX = 4++export const hardOffsetShadow: PageRule = {+ meta: {+ id: "hard-offset-shadow",+ name: "Hard offset shadow",+ category: "quality",+ severity: "advisory",+ engine: "page",+ description: "A visible shadow displaced by 4px or more with no blur: a neobrutalist costume unless the brief chose that direction.",+ fixHint: "Use an elevation shadow with a y-offset and a soft blur, or waive it with data-detect-ignore=\"hard-offset-shadow\" when neobrutalism is the brief.",+ },+ check: ({ snapshot }) =>+ snapshot.elements.flatMap((el) => {+ if (!isRendered(snapshot, el)) return []+ const hard = parseShadow(styleOf(el, "box-shadow")).find(+ (l) =>+ !l.inset &&+ l.color.a > 0 &&+ l.blur === 0 &&+ Math.max(Math.abs(l.x), Math.abs(l.y)) >= MIN_OFFSET_PX &&+ l.spread > -Math.max(Math.abs(l.x), Math.abs(l.y)),+ )+ if (!hard) return []+ return [{ element: el, message: `box-shadow ${hard.x}px ${hard.y}px with no blur`, snippet: shortSnippet(el) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/hero-eyebrow-chip.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/hero-eyebrow-chip.tsnew file mode 100644index 00000000..892fb64c--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/hero-eyebrow-chip.ts@@ -0,0 +1,19 @@+import type { PageRule } from "../../rule"+import { shortSnippet } from "../../core/page"+import { heroLabel } from "./support/labels"+export const heroEyebrowChip: PageRule = {+ meta: {+ id: "hero-eyebrow-chip",+ name: "Hero eyebrow / pill chip",+ category: "slop",+ severity: "warning",+ engine: "page",+ description: "A tiny tracked or accented label decorates a display hero heading.",+ fixHint: "Remove the eyebrow or integrate its words into the heading.",+ },+ check: ({ snapshot }) =>+ snapshot.elements.flatMap((h) => {+ const label = heroLabel(snapshot, h)+ return label ? [{ element: h, message: "Small decorative eyebrow above the hero heading", snippet: shortSnippet(h) }] : []+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/icon-tile-stack.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/icon-tile-stack.tsnew file mode 100644index 00000000..aca50210--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/icon-tile-stack.ts@@ -0,0 +1,92 @@+import type { PageRule } from "../../rule"+import { childrenOf, descendants, fontSizePx, isHeading, shortSnippet, styleOf } from "../../core/page"+import { parseColor } from "../../core/color"+import { parseShadow } from "../../core/shadow"+import { length, radii, visible } from "./support/appearance"+import { labelBefore, nearAbove } from "./support/labels"+export const iconTileStack: PageRule = {+ meta: {+ id: "icon-tile-stack",+ name: "Icon tile stacked above heading",+ category: "slop",+ severity: "warning",+ engine: "page",+ description: "A small framed icon tile sits above a heading.",+ fixHint: "Put the icon beside the title or remove its separate tile.",+ },+ check: ({ snapshot }) =>+ snapshot.elements.flatMap((h) => {+ const title =+ ["div", "span"].includes(h.tag) &&+ ["block", "flow-root"].includes(styleOf(h, "display")) &&+ h.children.length === 0 &&+ h.ownText.length >= 2 &&+ h.ownText.length <= 80 &&+ Number(styleOf(h, "font-weight")) >= 600 &&+ fontSizePx(h) >= 16+ if ((!isHeading(h) && !title) || !visible(snapshot, h)) return []+ const found = labelBefore(snapshot, h)+ if (!found) return []+ let box = found.label+ for (let i = 0; i < 3; i++) {+ const children = childrenOf(snapshot, box),+ only = children[0]+ if (styleOf(box, "display") === "contents") {+ box = children.at(-1) ?? box+ continue+ }+ const bg = parseColor(styleOf(box, "background-color"))+ const bare =+ (bg === null || bg.a === 0) &&+ ["none", ""].includes(styleOf(box, "background-image")) &&+ parseShadow(styleOf(box, "box-shadow")).length === 0 &&+ length(styleOf(box, "border-top-width")) === 0+ if (+ children.length !== 1 ||+ !only ||+ !bare ||+ Math.abs(box.rect.width - only.rect.width) > 2 ||+ Math.abs(box.rect.height - only.rect.height) > 2+ )+ break+ box = only+ }+ const candidates = [box]+ const tile = candidates.find((t) => {+ const { width: w, height: hgt } = t.rect,+ bg = parseColor(styleOf(t, "background-color"))+ if (+ w < 32 ||+ w > 128 ||+ hgt < 32 ||+ hgt > 128 ||+ w / hgt < 0.7 ||+ w / hgt > 1.4 ||+ Math.max(...radii(t)) >= w / 2 ||+ !visible(snapshot, t) ||+ !nearAbove(t, h)+ )+ return false+ const framed =+ (bg !== null && bg.a >= 0.05) ||+ !["none", ""].includes(styleOf(t, "background-image")) ||+ length(styleOf(t, "border-top-width")) > 0 ||+ parseShadow(styleOf(t, "box-shadow")).some((l) => l.color.a > 0 && !l.inset)+ if (!framed) return false+ const emoji = (text: string): boolean => /^[\p{Extended_Pictographic}\uFE0F\u200D\s]+$/u.test(text) && text.trim() !== ""+ return (+ emoji(t.ownText) ||+ [...descendants(snapshot, t)].some(+ (c) =>+ visible(snapshot, c) &&+ (["svg", "i", "img"].includes(c.tag) ||+ !["none", ""].includes(styleOf(c, "mask-image")) ||+ !["none", ""].includes(styleOf(c, "-webkit-mask-image")) ||+ emoji(c.text)) &&+ c.rect.width < w * 0.95,+ )+ )+ })+ return tile ? [{ element: h, message: "Framed icon tile stacked above heading", snippet: shortSnippet(h) }] : []+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/index.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/index.tsnew file mode 100644index 00000000..58bf4e1d--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/index.ts@@ -0,0 +1,38 @@+import type { Rule } from "../../rule"+import { hardOffsetShadow } from "./hard-offset-shadow"+import { sideTab } from "./side-tab"+import { borderAccentOnRounded } from "./border-accent-on-rounded"+import { gptThinBorderWideShadow } from "./gpt-thin-border-wide-shadow"+import { repeatingStripesGradient } from "./repeating-stripes-gradient"+import { codexGridBackground } from "./codex-grid-background"+import { organicClipPath } from "./organic-clip-path"+import { buriedRaster } from "./buried-raster"+import { shapeAssembledIllustration } from "./shape-assembled-illustration"+import { iconTileStack } from "./icon-tile-stack"+import { heroEyebrowChip } from "./hero-eyebrow-chip"+import { kickerAboveHeading } from "./kicker-above-heading"+import { designSystemRadius } from "./design-system-radius"+import { marquee } from "./marquee"+import { pulsingDot } from "./pulsing-dot"+import { blinkingCursor } from "./blinking-cursor"+import { bounceEasing } from "./bounce-easing"++export const DECORATION_RULES: readonly Rule[] = [+ hardOffsetShadow,+ sideTab,+ borderAccentOnRounded,+ gptThinBorderWideShadow,+ repeatingStripesGradient,+ codexGridBackground,+ organicClipPath,+ buriedRaster,+ shapeAssembledIllustration,+ iconTileStack,+ heroEyebrowChip,+ kickerAboveHeading,+ designSystemRadius,+ marquee,+ pulsingDot,+ blinkingCursor,+ bounceEasing,+]diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/kicker-above-heading.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/kicker-above-heading.tsnew file mode 100644index 00000000..d25b7918--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/kicker-above-heading.ts@@ -0,0 +1,69 @@+import type { PageRule } from "../../rule"+import { fontSizePx, shortSnippet, styleOf } from "../../core/page"+import { context, length, visible } from "./support/appearance"+import { application, caps, cardContext, headingLevel, heroLabel, labelBefore, labelType, nearAbove } from "./support/labels"+export const kickerAboveHeading: PageRule = {+ meta: {+ id: "kicker-above-heading",+ name: "Kicker / eyebrow label above heading",+ category: "slop",+ severity: "warning",+ engine: "page",+ description: "A separate tracked uppercase label repeats the heading hierarchy.",+ fixHint: "Delete the kicker or work meaningful words into the heading or body.",+ },+ check: ({ snapshot }) =>+ snapshot.elements.flatMap((h) => {+ const level = headingLevel(h),+ size = fontSizePx(h)+ if (+ level < 1 ||+ level > 4 ||+ size < 20 ||+ h.text.length < 3 ||+ /^\s*["']?\//.test(h.text) ||+ application(snapshot, h) ||+ !visible(snapshot, h)+ )+ return []+ const found = labelBefore(snapshot, h)+ if (!found) return []+ const label = found.label,+ ty = labelType(snapshot, label),+ text = label.text.trim(),+ fs = fontSizePx(ty)+ const variant = styleOf(ty, "font-variant") + styleOf(ty, "font-variant-caps")+ const smallCaps = /small-caps/.test(variant)+ if (+ !visible(snapshot, label) ||+ !["p", "span", "div", "small"].includes(label.tag) ||+ text.length < 2 ||+ text.length > 34 ||+ !(caps(ty) || smallCaps) ||+ fs <= 0 ||+ fs > Math.max(14, Math.min(16, size * 0.45)) ||+ !(length(styleOf(ty, "letter-spacing")) >= fs * 0.06)+ )+ return []+ if (+ !nearAbove(ty, h) ||+ /[·•|]|\b(?:19|20)\d{2}\b|\s[\/›»>]\s|^(?:step\s*\d|\d{1,2}$|§|\d+(?:\.\d+)+\b|(?:section|article|clause|appendix|exhibit|schedule|chapter|part|rule|title)\s+(?:[0-9ivxlc]+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)\b)/i.test(text) ||+ cardContext(snapshot, h, label)+ )+ return []+ if (h.tag === "h1" && size >= 48 &&+ (length(styleOf(ty, "letter-spacing")) >= 1.6 || (found.levels === 0 && fs <= 14 && heroLabel(snapshot, h)))) return []+ if (+ context(+ snapshot,+ h,+ (a) =>+ ["nav", "form", "figure", "footer", "header", "pre", "code"].includes(a.tag) ||+ a.attributes["data-impeccable-allow-kickers"] !== undefined ||+ a.attributes["aria-hidden"] === "true",+ )+ )+ return []+ return [{ element: label, message: "Tracked kicker above " + h.tag, snippet: shortSnippet(label) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/marquee.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/marquee.tsnew file mode 100644index 00000000..47aee1ce--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/marquee.ts@@ -0,0 +1,51 @@+import type { PageRule } from "../../rule"+import { ancestors, descendants, shortSnippet, styleOf } from "../../core/page"+import { visible } from "./support/appearance"+import { infiniteNames, keyframes } from "./support/keyframes"+import { pageIgnored } from "../color/support/page-ignore"+import type { PageSnapshot } from "../../types"++function marqueeKeyframes(snapshot: PageSnapshot, name: string): boolean {+ const frames = keyframes(snapshot, name)+ if (frames === null) return /marquee|ticker|crawl|scroll/i.test(name)+ const percentages = frames.flatMap((frame) => [...(frame["transform"] ?? "").matchAll(/\btranslate(?:x|3d)?\(\s*(?:calc\(\s*)?(-?[\d.]+)%/gi)]+ .map((match) => Number(match[1])))+ if (percentages.length === 0 || (percentages.length === 1 && frames.some((frame) =>+ frame["opacity"] !== undefined || /\bscale\(/i.test(frame["transform"] ?? "")))) return false+ const travel = percentages.length === 1 ? Math.abs(percentages[0] ?? 0) : Math.max(...percentages) - Math.min(...percentages)+ return travel >= 20+}+export const marquee: PageRule = {+ meta: {+ id: "marquee",+ name: "Auto-scrolling marquee",+ category: "slop",+ severity: "warning",+ engine: "page",+ description: "Content crawls automatically through a repeating horizontal loop.",+ fixHint: "Keep the content still and let readers scroll it themselves.",+ },+ check: ({ snapshot }) => {+ const seen = new Set<number>()+ const strips = new Set<number>()+ return snapshot.elements.flatMap((e) => {+ if (!visible(snapshot, e) || pageIgnored(snapshot, e, "marquee") || [...ancestors(snapshot, e)].some((a) => seen.has(a.index))) return []+ const carries =+ e.text.trim() !== "" ||+ [...descendants(snapshot, e)].some(+ (c) =>+ ["img", "picture", "video", "canvas", "iframe", "object", "embed", "marquee"].includes(c.tag) ||+ (c.tag === "svg" && c.attributes["aria-hidden"] !== "true"),+ )+ const loop = (style: Readonly<Record<string, string>>): boolean =>+ infiniteNames(style).some((name) => marqueeKeyframes(snapshot, name))+ const pseudo = [e.before, e.after].some((p) => p && loop(p.style) && !["", '""', "none", "normal"].includes(p.style["content"] ?? ""))+ if (e.tag !== "marquee" && !(carries && loop(e.style)) && !pseudo) return []+ const strip = [...ancestors(snapshot, e)].find((a) => ["hidden", "clip", "scroll", "auto"].includes(styleOf(a, "overflow-x")))+ if (strip && strips.has(strip.index)) return []+ if (strip) strips.add(strip.index)+ seen.add(e.index)+ return [{ element: e, message: "Continuously scrolling content track", snippet: shortSnippet(e) }]+ })+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/organic-clip-path.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/organic-clip-path.tsnew file mode 100644index 00000000..9b8171a7--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/organic-clip-path.ts@@ -0,0 +1,41 @@+import type { PageRule } from "../../rule"+import { shortSnippet, styleOf } from "../../core/page"+import { visible, splitTop } from "./support/appearance"+import { geometricPolygon, roundedPath } from "./support/clip-geometry"+import { cssCandidates, matchesSelector } from "./support/css-candidates"+export const organicClipPath: PageRule = {+ meta: {+ id: "organic-clip-path",+ name: "Organic contour drawn as clip-path",+ category: "quality",+ severity: "warning",+ engine: "page",+ description: "A complex CSS contour substitutes for produced organic material.",+ fixHint: "Use an image-derived alpha matte; keep CSS clipping for simple geometry.",+ },+ check: ({ snapshot }) => {+ const seen = new Set<string>()+ const declarations = [...cssCandidates(snapshot)].filter(([, style]) => style["clip-path"] !== undefined)+ return snapshot.elements.flatMap((e) => {+ if (!visible(snapshot, e)) return []+ const clip = styleOf(e, "clip-path"),+ kind = /^(polygon|path)\(([\s\S]*)\)$/.exec(clip),+ body = kind?.[2]+ if (!kind || body === undefined) return []+ const points = splitTop(body)+ const offGrid = [...body.matchAll(/[-+]?(?:\d*\.)?\d+/g)].filter(+ (m) => Math.abs(Number(m[0]) - Math.round(Number(m[0]) / 25) * 25) > 0.5,+ ).length+ const organic =+ kind[1] === "path"+ ? (body.match(/[CSQTA]/gi)?.length ?? 0) >= 3 && !roundedPath(body)+ : points.length >= 10 && offGrid >= points.length && !geometricPolygon(body)+ const inline = /(?:^|;)\s*clip-path\s*:/i.test(e.attributes["style"] ?? "")+ const selector = declarations.find(([selector]) => matchesSelector(snapshot, e, selector))?.[0]+ const key = inline ? clip : (selector ?? e.selector) + clip+ if (!organic || seen.has(key)) return []+ seen.add(key)+ return [{ element: e, message: "Organic contour approximated with CSS " + kind[1], snippet: shortSnippet(e) }]+ })+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/pulsing-dot.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/pulsing-dot.tsnew file mode 100644index 00000000..121c74b4--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/pulsing-dot.ts@@ -0,0 +1,72 @@+import type { PageHit, PageRule } from "../../rule"+import type { ComputedStyle, ElementSnapshot, PageSnapshot } from "../../types"+import { ancestors, shortSnippet, styleOf } from "../../core/page"+import { radii, splitTop } from "./support/appearance"+import { cssCandidates, matchesSelector } from "./support/css-candidates"+import { dotPulse, infiniteNames, keyframes } from "./support/keyframes"++function pulses(s: PageSnapshot, style: ComputedStyle): boolean {+ const shorthand = splitTop(style["animation"] ?? "").filter(v => /\binfinite\b/.test(v))+ const names = [...infiniteNames(style), ...shorthand.flatMap(v => v.split(/\s+/).filter(n => keyframes(s, n) !== null || /pulse|ping|ripple|beacon/i.test(n)))]+ return names.some(n => {+ const frames = keyframes(s, n)+ return frames === null ? /pulse|ping|ripple|beacon/i.test(n) : dotPulse(frames)+ })+}+const shown = (s: PageSnapshot, e: ElementSnapshot): boolean =>+ [e, ...ancestors(s, e)].every(n => styleOf(n, "display") !== "none" && styleOf(n, "visibility") !== "hidden" &&+ Number.parseFloat(styleOf(n, "opacity")) !== 0 && n.attributes["hidden"] === undefined)+const dotSize = (w: number, h: number): boolean =>+ w >= 2 && h >= 2 && w <= 16 && h <= 16 && Math.max(w, h) <= 1.5 * Math.min(w, h)++export const pulsingDot: PageRule = {+ meta: {+ id: "pulsing-dot", name: "Pulsing status dot", category: "slop", severity: "warning", engine: "page",+ description: "A tiny circular indicator pulses continuously.",+ fixHint: "Keep the indicator static unless it represents live changing data.",+ },+ check: ({ snapshot }) => {+ const hits: PageHit[] = []+ const covered = new Set<number>()+ const candidates = cssCandidates(snapshot)+ const vars = new Map([...candidates.values()].flatMap(d => Object.entries(d).filter(([p]) => p.startsWith("--"))))+ const length = (value: string): number => {+ const resolved = value.replace(/var\((--[\w-]+)\)/g, (_, name: string) => vars.get(name) ?? "")+ const m = /^([\d.]+)(px|rem|em)?$/.exec(resolved)+ return m ? Number(m[1]) * (m[2] === "rem" || m[2] === "em" ? 16 : 1) : Number.NaN+ }+ for (const [selector, style] of candidates) {+ const w = length(style["width"] ?? style["inline-size"] ?? ""), h = length(style["height"] ?? style["block-size"] ?? "")+ const radius = style["border-radius"] ?? ""+ if (!dotSize(w, h) || !pulses(snapshot, style) ||+ !radius.split(/[\s/]+/).every(r => r.endsWith("%") ? Number.parseFloat(r) >= 40 : length(r) >= Math.min(w, h) * 0.4)) continue+ const matches = snapshot.elements.filter(e => matchesSelector(snapshot, e, selector) && shown(snapshot, e))+ const first = matches[0]+ if (!first) continue+ matches.forEach(e => covered.add(e.index))+ hits.push({ element: first, message: "Infinitely pulsing " + w + "x" + h + "px status dot", snippet: shortSnippet(first) })+ }+ const tailwind = new Set<string>()+ for (const e of snapshot.elements) {+ const classes = e.attributes["class"] ?? ""+ if (/(?:^|\s)animate-(?:ping|pulse)(?:$|\s)/.test(classes) && /(?:^|\s)rounded-full(?:$|\s)/.test(classes) &&+ /(?:^|\s)[wh]-(?:0\.5|1|1\.5|2|2\.5|3|3\.5|4)(?:$|\s)/.test(classes)) {+ const side = (name: string): number | undefined => {+ const value = new RegExp("(?:^|\\s)" + name + "-([\\d.]+)(?:$|\\s)").exec(classes)?.[1]+ return value === undefined ? undefined : Number(value) * 4+ }+ const w = side("w"), h = side("h")+ if ((w === undefined || h === undefined || dotSize(w, h)) && !tailwind.has(classes)) {+ tailwind.add(classes)+ covered.add(e.index)+ hits.push({ element: e, message: "Infinitely pulsing utility status dot", snippet: shortSnippet(e) })+ }+ }+ if (covered.has(e.index) || !shown(snapshot, e) || !pulses(snapshot, e.style)) continue+ const w = e.rect.width, h = e.rect.height+ if (dotSize(w, h) && radii(e).every(r => r >= Math.min(w, h) * 0.4))+ hits.push({ element: e, message: "Infinitely pulsing " + w + "x" + h + "px status dot", snippet: shortSnippet(e) })+ }+ return hits+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/repeating-stripes-gradient.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/repeating-stripes-gradient.tsnew file mode 100644index 00000000..777f5bb6--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/repeating-stripes-gradient.ts@@ -0,0 +1,25 @@+import type { PageRule } from "../../rule"+import { shortSnippet } from "../../core/page"+import { visible } from "./support/appearance"+import { repeats } from "./support/gradient-pattern"+export const repeatingStripesGradient: PageRule = {+ meta: {+ id: "repeating-stripes-gradient",+ name: "Repeating-gradient stripes",+ category: "slop",+ severity: "advisory",+ engine: "page",+ description: "Repeating gradient bands decorate a surface without adding structure.",+ fixHint: "Use a deliberate texture or keep the surface plain.",+ },+ check: ({ snapshot }) => {+ const e = snapshot.elements.find(+ (e) =>+ visible(snapshot, e) &&+ [e.style, e.before?.style, e.after?.style].some((s) =>+ ["background-image", "mask-image", "-webkit-mask-image"].some((p) => repeats(s?.[p] ?? "")),+ ),+ )+ return e ? [{ element: e, message: "Repeating gradient surface stripes", snippet: shortSnippet(e) }] : []+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/shape-assembled-illustration.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/shape-assembled-illustration.tsnew file mode 100644index 00000000..a63c95e0--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/shape-assembled-illustration.ts@@ -0,0 +1,58 @@+import type { PageRule } from "../../rule"+import { ancestors, descendants, shortSnippet } from "../../core/page"+import { visible } from "./support/appearance"+export const shapeAssembledIllustration: PageRule = {+ meta: {+ id: "shape-assembled-illustration",+ name: "Shape-assembled illustration",+ category: "slop",+ severity: "advisory",+ engine: "page",+ description: "A hero-sized SVG scene is assembled mainly from primitive shapes.",+ fixHint: "Use produced artwork, a photograph, or a deliberately drawn illustration.",+ },+ check: ({ snapshot }) =>+ snapshot.elements.flatMap((e) => {+ if (e.tag !== "svg" || !visible(snapshot, e) || e.rect.width < 200 || e.rect.height < 200) return []+ const all = [...descendants(snapshot, e)]+ if (all.filter((n) => n.tag === "text").length > 2 || all.some((n) => n.tag === "pattern")) return []+ const primitive = (tag: string): boolean => ["rect", "circle", "ellipse", "polygon"].includes(tag)+ const drawn = (tag: string): boolean => primitive(tag) || ["path", "line", "polyline"].includes(tag)+ const painted = all.filter((n) => ![...ancestors(snapshot, n)].some((a) => a.tag === "defs"))+ const used = painted+ .filter((n) => n.tag === "use")+ .flatMap((n) => {+ const id = (n.attributes["href"] ?? n.attributes["xlink:href"] ?? "").replace(/^#/, "")+ const target = all.find((a) => a.attributes["id"] === id && drawn(a.tag))+ return target ? [target] : []+ })+ const shapes = [...painted, ...used],+ primitives = shapes.filter((n) => primitive(n.tag))+ if (primitives.length < 8 || primitives.length < shapes.filter((n) => drawn(n.tag)).length * 0.5) return []+ const fills = new Set(+ [e, ...all]+ .map((n) => n.attributes["fill"]?.toLowerCase())+ .filter((v) => v !== undefined && !["none", "transparent", "currentcolor", "inherit", ""].includes(v)),+ )+ if (fills.size < 3) return []+ const rects = primitives+ .filter((n) => n.tag === "rect")+ .map((n) => ({ w: Number(n.attributes["width"]), h: Number(n.attributes["height"]) }))+ .filter((r) => Number.isFinite(r.w) && Number.isFinite(r.h))+ if (+ primitives.length <= 400 &&+ primitives.filter((n) => ["circle", "ellipse", "polygon"].includes(n.tag)).length < primitives.length * 0.25+ ) {+ const series = rects.some((a) => {+ const sameWidth = rects.filter((b) => Math.abs(a.w - b.w) <= 1),+ sameHeight = rects.filter((b) => Math.abs(a.h - b.h) <= 1)+ return (+ (sameWidth.length >= primitives.length / 2 && sameWidth.some((b) => Math.abs(b.h - a.h) > 1)) ||+ (sameHeight.length >= primitives.length / 2 && sameHeight.some((b) => Math.abs(b.w - a.w) > 1))+ )+ })+ if (series) return []+ }+ return [{ element: e, message: "Large SVG scene assembled from " + primitives.length + " primitives", snippet: shortSnippet(e) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/side-tab.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/side-tab.tsnew file mode 100644index 00000000..8093a07e--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/side-tab.ts@@ -0,0 +1,17 @@+import type { PageRule } from "../../rule"+import { borderHits, childStripeHit, stripeHit } from "./support/borders"+import { pageIgnored } from "../color/support/page-ignore"+export const sideTab: PageRule = {+ meta: {+ id: "side-tab",+ name: "Side-tab accent border",+ category: "slop",+ severity: "warning",+ engine: "page",+ description: "A colored edge turns a card into a decorative side tab.",+ fixHint: "Remove the stripe and use spacing or a restrained surface change.",+ },+ check: ({ snapshot }) =>+ snapshot.elements.flatMap((e) => pageIgnored(snapshot, e, "side-tab") ? []+ : [...borderHits(snapshot, e, "side-tab"), ...stripeHit(snapshot, e), ...childStripeHit(snapshot, e)]),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/appearance.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/appearance.tsnew file mode 100644index 00000000..e1a8cc81--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/appearance.ts@@ -0,0 +1,110 @@+import { ancestors, isRendered, px, styleOf } from "../../../core/page"+import { blend, parseColor, type Rgba } from "../../../core/color"+import type { ElementSnapshot, PageSnapshot } from "../../../types"++export const sides = ["top", "right", "bottom", "left"] as const+export const corners = ["top-left", "top-right", "bottom-right", "bottom-left"] as const+export const borderSafe = new Set([+ "blockquote",+ "nav",+ "a",+ "input",+ "textarea",+ "select",+ "pre",+ "code",+ "span",+ "th",+ "td",+ "tr",+ "li",+ "button",+ "hr",+ "html",+ "head",+ "body",+ "script",+ "style",+ "link",+ "meta",+ "title",+ "br",+ "img",+ "svg",+ "path",+ "circle",+ "rect",+ "line",+ "polyline",+ "polygon",+ "g",+ "defs",+ "use",+])+export const length = (value: string): number => px(value) ?? (value.trim() === "0" ? 0 : Number.NaN)+export const chroma = (value: string, floor = 30): boolean => {+ const c = parseColor(value)+ return c !== null && c.a >= 0.1 && Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b) >= floor+}+export function borderAccent(value: string): boolean {+ const fn = /^(oklch|oklab|lch|lab|hsl|hsla|hwb)\(([^)]*)\)$/i.exec(value)+ if (!fn) return chroma(value)+ const parts = (fn[2] ?? "").split("/")[0]?.replace(/,/g, " ").trim().split(/\s+/) ?? []+ const n = (i: number, full: number): number => Number.parseFloat(parts[i] ?? "0") * ((parts[i] ?? "").endsWith("%") ? full / 100 : 1)+ const name = fn[1]?.toLowerCase()+ if (name === "oklch") return n(1, 0.4) >= 0.02+ if (name === "lch") return n(1, 150) >= 3+ if (name === "oklab") return Math.hypot(n(1, 0.4), n(2, 0.4)) >= 0.02+ if (name === "lab") return Math.hypot(n(1, 125), n(2, 125)) >= 3+ if (name === "hwb") return 1 - Math.min(100, n(1, 100) + n(2, 100)) / 100 >= 0.1+ return n(1, 100) >= 10+}+const radius = (el: ElementSnapshot, corner: string): number => {+ const parts = styleOf(el, "border-" + corner + "-radius").split(/\s+/)+ const values = parts.map((v) => (v.endsWith("%") ? (Number.parseFloat(v) * Math.min(el.rect.width, el.rect.height)) / 100 : length(v)))+ return Math.min(...values)+}+export const radii = (el: ElementSnapshot): readonly number[] => corners.map((c) => radius(el, c))+export const roundedAway = (el: ElementSnapshot, side: number): boolean => {+ const far =+ [+ [2, 3],+ [0, 3],+ [0, 1],+ [1, 2],+ ][side] ?? []+ const values = radii(el)+ return far.every((i) => (values[i] ?? 0) >= 4)+}+export const visible = (s: PageSnapshot, e: ElementSnapshot): boolean =>+ isRendered(s, e) &&+ [e, ...ancestors(s, e)].every(+ (a) => styleOf(a, "display") !== "none" && styleOf(a, "visibility") !== "hidden" && a.attributes["hidden"] === undefined,+ )+export const context = (s: PageSnapshot, e: ElementSnapshot, predicate: (e: ElementSnapshot) => boolean): boolean =>+ [e, ...ancestors(s, e)].some(predicate)+export const selected = (e: ElementSnapshot): boolean =>+ e.attributes["aria-selected"] === "true" ||+ (e.attributes["aria-current"] !== undefined && e.attributes["aria-current"] !== "false") ||+ /^(selected|active|checked|current)$/i.test(e.attributes["data-state"] ?? e.attributes["data-status"] ?? "") ||+ /(?:^|[\s_-])(?:selected|current|checked|active)(?:$|[\s_-])/.test(e.attributes["class"] ?? "")+export const showsOver = (paint: Rgba, surface: Rgba): boolean => {+ const over = blend(paint, surface)+ return Math.max(Math.abs(over.r - surface.r), Math.abs(over.g - surface.g), Math.abs(over.b - surface.b)) >= 8+}+export function splitTop(value: string, separator: RegExp = /,/): string[] {+ let depth = 0,+ start = 0+ const parts: string[] = []+ for (let i = 0; i < value.length; i++) {+ const c = value[i] ?? ""+ if (c === "(") depth+++ else if (c === ")") depth--+ else if (depth === 0 && separator.test(c)) {+ parts.push(value.slice(start, i).trim())+ start = i + 1+ }+ }+ parts.push(value.slice(start).trim())+ return parts.filter(Boolean)+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/assert-cases.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/assert-cases.tsnew file mode 100644index 00000000..07199148--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/assert-cases.ts@@ -0,0 +1,25 @@+import { expect } from "bun:test"+import type { PageRule } from "../../../rule"+import type { DetectConfig } from "../../../types"+import { buildSnapshot, type NodeSpec } from "../../../testing/build-snapshot"+import { lintSnapshot } from "../../../lint"+export function assertCases(+ rule: PageRule,+ nodes: readonly NodeSpec[],+ expected: readonly string[],+ options: { readonly cssText?: readonly string[]; readonly config?: DetectConfig } = {},+): void {+ const snapshot = buildSnapshot(nodes, { cssText: options.cssText ?? [] })+ const findings = lintSnapshot(snapshot, { rules: [rule], config: options.config ?? {} })+ expect(findings.map((f) => (f.location.kind === "element" ? f.location.selector : "page"))).toEqual([...expected])+}+export const round = (radius: string): Readonly<Record<string, string>> =>+ Object.fromEntries(["top-left", "top-right", "bottom-right", "bottom-left"].map((c) => ["border-" + c + "-radius", radius]))+export const border = (width: string, color = "rgb(230, 231, 233)"): Readonly<Record<string, string>> =>+ Object.fromEntries(+ ["top", "right", "bottom", "left"].flatMap((s) => [+ ["border-" + s + "-width", width],+ ["border-" + s + "-style", "solid"],+ ["border-" + s + "-color", color],+ ]),+ )diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/borders.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/borders.tsnew file mode 100644index 00000000..3cd8c452--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/borders.ts@@ -0,0 +1,150 @@+import { ancestors, parentOf, shortSnippet, styleOf } from "../../../core/page"+import { parseColor } from "../../../core/color"+import { parseShadow } from "../../../core/shadow"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import type { PageHit } from "../../../rule"+import { borderAccent, borderSafe, chroma, context, length, radii, roundedAway, selected, sides, visible } from "./appearance"++export function borderHits(s: PageSnapshot, e: ElementSnapshot, rule: string): PageHit[] {+ if (+ !visible(s, e) ||+ borderSafe.has(e.tag) ||+ e.rect.width < 20 ||+ e.rect.height < 20 ||+ context(+ s,+ e,+ (a) =>+ ["status", "alert", "alertdialog", "log"].includes(a.attributes["role"] ?? "") ||+ ["polite", "assertive"].includes(a.attributes["aria-live"] ?? ""),+ )+ )+ return []+ const rs = radii(e),+ min = Math.min(e.rect.width, e.rect.height)+ if (Math.max(e.rect.width, e.rect.height) <= min * 1.1 && rs.every((r) => r >= min / 2 - 0.5)) return []+ const widths = sides.map((side) => length(styleOf(e, "border-" + side + "-width")))+ return sides.flatMap((side, i) => {+ const w = widths[i] ?? 0,+ other = Math.max(...widths.filter((_, j) => i !== j))+ if (w < 2 || !(other <= 1 || w >= other * 2) || !borderAccent(styleOf(e, "border-" + side + "-color"))) return []+ const lateral = i === 1 || i === 3+ const id = lateral ? "side-tab" : (rs[0] ?? 0) > 0 ? "border-accent-on-rounded" : "side-tab"+ if (+ id !== rule ||+ (lateral && !roundedAway(e, i)) ||+ (!lateral && (rs[0] ?? 0) === 0 && (w < 3 || w > 12 || !roundedAway(e, i) || context(s, e, selected)))+ )+ return []+ return [{ element: e, message: "Accent border on the " + side + " edge (" + w + "px)", snippet: shortSnippet(e) }]+ })+}++export function stripeHit(s: PageSnapshot, e: ElementSnapshot): PageHit[] {+ if (!visible(s, e) || e.rect.width <= 40 || e.rect.height < 16) return []+ const hosts = [e, ...ancestors(s, e)]+ if (hosts.some((a) => ["nav", "blockquote", "pre"].includes(a.tag))) return []+ const rowNode = (a: ElementSnapshot): boolean =>+ ["tr", "td", "th"].includes(a.tag) ||+ ["row", "cell", "gridcell", "rowheader"].includes(a.attributes["role"] ?? "") ||+ /(?:^|[\s_-])(?:row|cell)(?:$|[\s_-])/.test(a.attributes["class"] ?? "")+ const row = rowNode(e) && !(!["tr", "td", "th"].includes(e.tag) && !e.attributes["role"] && radii(e).some((r) => r > 0))+ const rowHosts = row ? hosts.filter(rowNode) : [e]+ if (rowHosts.some(selected) || (!row && (borderSafe.has(e.tag) || context(s, e, selected)))) return []+ const status = rowHosts.some(+ (a) =>+ a.attributes["data-state"] !== undefined ||+ a.attributes["data-status"] !== undefined ||+ a.attributes["aria-invalid"] === "true" ||+ /(?:is-|has-|--)[a-z]/.test(a.attributes["class"] ?? ""),+ )+ const bg = parseColor(styleOf(e, "background-color"))+ const bare = (bg === null || bg.a < 0.1) && ["none", ""].includes(styleOf(e, "background-image"))+ const shadows = parseShadow(styleOf(e, "box-shadow"))+ const inset = shadows.length === 1 ? shadows[0] : undefined+ if (+ inset?.inset &&+ inset.blur === 0 &&+ inset.spread === 0 &&+ chroma("rgb(" + inset.color.r + " " + inset.color.g + " " + inset.color.b + " / " + inset.color.a + ")")+ ) {+ const axis = inset.x !== 0 && inset.y === 0 ? (inset.x > 0 ? 3 : 1) : inset.y !== 0 && inset.x === 0 ? (inset.y > 0 ? 0 : 2) : -1+ const w = Math.max(Math.abs(inset.x), Math.abs(inset.y))+ if (axis >= 0 && (row ? (axis === 1 || axis === 3) && w >= 2 && w <= 6 && (status || bare) : w >= 3 && w <= 12 && roundedAway(e, axis)))+ return [{ element: e, message: "Inset accent stripe (" + w + "px)", snippet: shortSnippet(e) }]+ }+ if (row && (status || bare)) {+ const drawn = sides.map(+ (side) =>+ length(styleOf(e, "border-" + side + "-width")) > 0 && !["none", "hidden", ""].includes(styleOf(e, "border-" + side + "-style")),+ )+ for (const i of [3, 1]) {+ const side = sides[i] ?? "left",+ w = length(styleOf(e, "border-" + side + "-width"))+ if (drawn[0] && drawn[2]) continue+ if (drawn[i] && w >= 2 && w <= 6 && chroma(styleOf(e, "border-" + side + "-color")) && (status || drawn.filter(Boolean).length === 1))+ return [{ element: e, message: "Row accent border (" + w + "px)", snippet: shortSnippet(e) }]+ }+ }+ if (!row && !borderSafe.has(e.tag)) {+ const stripes = [e.before, e.after].flatMap((p) =>+ p ? [{ style: p.style, width: length(p.style["width"] ?? ""), height: length(p.style["height"] ?? "") }] : [],+ )+ for (const p of stripes) {+ if (+ !["absolute", "fixed"].includes(p.style["position"] ?? "") ||+ !chroma(p.style["background-color"] ?? "") ||+ p.style["display"] === "none" ||+ Number(p.style["opacity"] ?? 1) <= 0.01+ )+ continue+ const hugs = (side: string): boolean => Math.abs(length(p.style[side] ?? "")) <= 2+ const axis =+ p.width >= 2 && p.width <= 12 && p.height >= Math.max(e.rect.height - 44, e.rect.height / 2)+ ? hugs("left")+ ? 3+ : hugs("right")+ ? 1+ : -1+ : p.height >= 3 && p.height <= 12 && p.width >= Math.max(e.rect.width - 44, e.rect.width / 2)+ ? hugs("top")+ ? 0+ : hugs("bottom")+ ? 2+ : -1+ : -1+ if (axis >= 0 && roundedAway(e, axis)) return [{ element: e, message: "Positioned accent stripe", snippet: shortSnippet(e) }]+ }+ }+ return []+}++export function childStripeHit(s: PageSnapshot, e: ElementSnapshot): PageHit[] {+ if (!["div", "span"].includes(e.tag) || e.children.length > 0 || e.text.trim() !== "" || !visible(s, e)) return []+ const p = parentOf(s, e)+ if (!p || ["body", "html", "h1", "h2", "h3", "h4", "h5", "h6"].includes(p.tag) || p.rect.width < 40 || p.rect.height < 20) return []+ if (+ context(+ s,+ e,+ (a) =>+ ["nav", "blockquote", "pre", "table", "button", "a", "select", "progress", "meter"].includes(a.tag) ||+ ["progressbar", "slider", "scrollbar", "separator", "tablist", "status", "alert"].includes(a.attributes["role"] ?? "") ||+ selected(a),+ )+ )+ return []+ const { width: w, height: h, x } = e.rect,+ host = p.rect+ const side = Math.abs(x - host.x) <= 3 ? 3 : Math.abs(host.x + host.width - x - w) <= 3 ? 1 : -1+ if (+ side < 0 ||+ w < 2 ||+ w > 12 ||+ h < Math.max(host.height - 44, host.height * 0.5) ||+ !roundedAway(p, side) ||+ !chroma(styleOf(e, "background-color"))+ )+ return []+ return [{ element: e, message: w + "px accent stripe child", snippet: shortSnippet(e) }]+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/clip-geometry.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/clip-geometry.tsnew file mode 100644index 00000000..cfcb7fce--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/clip-geometry.ts@@ -0,0 +1,151 @@+import { splitTop } from "./appearance"+import { arc, cubic, lerp, type Point } from "./curve-samples"+export function geometricPolygon(body: string): boolean {+ const points = splitTop(body)+ .filter((p) => !/^nonzero$|^evenodd$/.test(p))+ .map((p) => splitTop(p, /\s/))+ const key = (v: string): string => (/^[-+]?0(?:\.0+)?(?:%|px)?$/.test(v) ? "0" : v.replace(/\s/g, ""))+ if (+ points.every((p, i) => {+ const next = points[(i + 1) % points.length]+ return p.length === 2 && next !== undefined && (key(p[0] ?? "") === key(next[0] ?? "") || key(p[1] ?? "") === key(next[1] ?? ""))+ })+ )+ return true+ const numeric = points.map((p) => p.map((v) => (/^[-+]?[\d.]+(?:px|%)?$/.test(v) ? Number.parseFloat(v) : Number.NaN)))+ if (numeric.some((p) => p.length !== 2 || p.some((n) => !Number.isFinite(n)))) return false+ const xs = numeric.map((p) => p[0] ?? 0),+ ys = numeric.map((p) => p[1] ?? 0)+ const distinct = (vs: readonly number[]): number[] => [...new Set(vs)].sort((a, b) => a - b)+ const teeth = (along: readonly number[], across: readonly number[]): boolean => {+ const d = distinct(along),+ step = (d[1] ?? 0) - (d[0] ?? 0)+ if (d.length < 3 || step <= 0 || d.slice(1).some((v, i) => Math.abs(v - (d[i] ?? 0) - step) > 0.5)) return false+ let last: number | null = null,+ swings = 0+ for (let i = 0; i < along.length; i++) {+ const j = (i + 1) % along.length+ if (Math.abs(Math.abs((along[j] ?? 0) - (along[i] ?? 0)) - step) > 0.5) {+ last = null+ continue+ }+ const swing = (across[j] ?? 0) - (across[i] ?? 0)+ if (Math.abs(swing) < 0.01) continue+ if (last !== null && (Math.sign(last) === Math.sign(swing) || Math.abs(Math.abs(last) - Math.abs(swing)) > 0.5)) return false+ last = swing+ swings+++ }+ return swings >= 3+ }+ return (+ (distinct(xs).length >= 2 && distinct(xs).length <= 4 && teeth(ys, xs)) ||+ (distinct(ys).length >= 2 && distinct(ys).length <= 4 && teeth(xs, ys))+ )+}+export function roundedPath(body: string): boolean {+ const tokens = body.replace(/^["']|["']$/g, "").match(/[A-Za-z]|[-+]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][-+]?[0-9]+)?/g) ?? []+ const segments: { a: Point; b: Point; line: boolean }[] = [],+ points: Point[] = []+ let at: Point = [0, 0],+ start: Point = [0, 0],+ cmd = "",+ i = 0+ let lastCubic: Point | null = null,+ lastQuad: Point | null = null+ while (i < tokens.length) {+ const token = tokens[i] ?? ""+ if (/^[a-z]$/i.test(token)) {+ cmd = token+ i+++ if (cmd.toLowerCase() === "z") {+ if (at[0] !== start[0] || at[1] !== start[1]) segments.push({ a: at, b: start, line: true })+ at = start+ cmd = ""+ }+ continue+ }+ const upper = cmd.toUpperCase(),+ arity =+ upper === "H" || upper === "V"+ ? 1+ : upper === "C"+ ? 6+ : upper === "A"+ ? 7+ : upper === "S" || upper === "Q"+ ? 4+ : ["M", "L", "T"].includes(upper)+ ? 2+ : 0+ if (arity === 0 || i + arity > tokens.length) return false+ const args = tokens.slice(i, i + arity).map(Number)+ if (args.some((n) => !Number.isFinite(n))) return false+ i += arity+ const rel = cmd !== upper,+ base: Point = rel ? at : [0, 0]+ const end: Point =+ upper === "H"+ ? [base[0] + (args[0] ?? 0), at[1]]+ : upper === "V"+ ? [at[0], base[1] + (args[0] ?? 0)]+ : [base[0] + (args[arity - 2] ?? 0), base[1] + (args[arity - 1] ?? 0)]+ const point = (k: number): Point => [base[0] + (args[k] ?? 0), base[1] + (args[k + 1] ?? 0)]+ const reflect = (p: Point | null): Point => (p ? [2 * at[0] - p[0], 2 * at[1] - p[1]] : at)+ let nextCubic: Point | null = null,+ nextQuad: Point | null = null+ if (upper === "C" || upper === "S") {+ const c1 = upper === "C" ? point(0) : reflect(lastCubic),+ c2 = point(upper === "C" ? 2 : 0)+ points.push(...cubic(at, c1, c2, end))+ nextCubic = c2+ } else if (upper === "Q" || upper === "T") {+ const c: Point = upper === "Q" ? point(0) : reflect(lastQuad)+ points.push(...cubic(at, lerp(at, c, 2 / 3), lerp(end, c, 2 / 3), end))+ nextQuad = c+ } else if (upper === "A")+ points.push(...arc(at, args[0] ?? 0, args[1] ?? 0, args[2] ?? 0, (args[3] ?? 0) !== 0, (args[4] ?? 0) !== 0, end))+ lastCubic = nextCubic+ lastQuad = nextQuad+ if (upper === "M") {+ start = end+ cmd = rel ? "l" : "L"+ } else segments.push({ a: at, b: end, line: ["L", "H", "V"].includes(upper) })+ points.push(end)+ at = end+ }+ const lines = segments.filter((s) => s.line)+ if (lines.length < 4) return false+ const xs = points.map((p) => p[0]),+ ys = points.map((p) => p[1]),+ minX = Math.min(...xs),+ maxX = Math.max(...xs),+ minY = Math.min(...ys),+ maxY = Math.max(...ys)+ const tol = Math.max(1, maxX - minX, maxY - minY) * 0.01,+ near = (a: number, b: number): boolean => Math.abs(a - b) <= tol+ const edges = (p: Point): number[] =>+ [near(p[1], minY) ? 0 : -1, near(p[0], maxX) ? 1 : -1, near(p[1], maxY) ? 2 : -1, near(p[0], minX) ? 3 : -1].filter((i) => i >= 0)+ const reached = new Set<number>()+ for (const l of lines) {+ const edge = edges(l.a).find((i) => edges(l.b).includes(i))+ if (edge === undefined) return false+ reached.add(edge)+ }+ if (reached.size !== 4) return false+ const first = segments.findIndex((s) => s.line)+ const run: Point[] = []+ for (let k = 1; k <= segments.length; k++) {+ const segment = segments[(first + k) % segments.length]+ if (!segment) continue+ const a = run[0],+ b = run[1]+ if (segment.line) {+ if (a && b && !edges(a).some((x) => edges(b).some((y) => x % 2 !== y % 2))) return false+ run.length = 0+ } else {+ run[0] = a ?? segment.a+ run[1] = segment.b+ }+ }+ return true+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/css-candidates.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/css-candidates.tsnew file mode 100644index 00000000..c88b7cec--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/css-candidates.ts@@ -0,0 +1,66 @@+import { ancestors, parentOf } from "../../../core/page"+import { cssBlocks } from "../../../core/source"+import type { ElementSnapshot, PageSnapshot } from "../../../types"++function compound(e: ElementSnapshot, selector: string): boolean {+ const tag = /^[a-z][\w-]*|^\*/i.exec(selector)?.[0]+ if (tag && tag !== "*" && e.tag !== tag.toLowerCase()) return false+ let rest = selector.slice(tag?.length ?? 0)+ for (const m of rest.matchAll(/([.#])([\w-]+)|\[([\w-]+)(?:=["']?([^"'\]]*)["']?)?\]/g)) {+ if (m[1] === "#" && e.attributes["id"] !== m[2]) return false+ if (m[1] === "." && !(e.attributes["class"] ?? "").split(/\s+/).includes(m[2] ?? "")) return false+ if (m[3] && (e.attributes[m[3]] === undefined || (m[4] !== undefined && e.attributes[m[3]] !== m[4]))) return false+ }+ rest = rest.replace(/([.#])[\w-]+|\[[^\]]+\]/g, "")+ return rest === ""+}++export function matchesSelector(s: PageSnapshot, e: ElementSnapshot, selector: string): boolean {+ const pieces = selector.trim().replace(/\s*>\s*/g, " > ").split(/\s+/)+ const last = pieces.pop()+ if (!last || !compound(e, last)) return false+ let current = e+ while (pieces.length > 0) {+ const part = pieces.pop()+ if (part === ">") {+ const parent = parentOf(s, current)+ const wanted = pieces.pop()+ if (!parent || !wanted || !compound(parent, wanted)) return false+ current = parent+ } else {+ const match = [...ancestors(s, current)].find(a => compound(a, part ?? ""))+ if (!match) return false+ current = match+ }+ }+ return true+}++export function cssCandidates(s: PageSnapshot): ReadonlyMap<string, Readonly<Record<string, string>>> {+ const merged = new Map<string, Record<string, string>>()+ for (const css of s.cssText) {+ let text = css+ for (const match of css.matchAll(/@media[^{]*prefers-reduced-motion\s*:\s*reduce\s*\)[^{]*\{/g)) {+ let end = (match.index ?? 0) + match[0].length+ let depth = 1+ const start = match.index ?? 0+ while (end < css.length && depth > 0) {+ if (css[end] === "{") depth+++ if (css[end] === "}") depth--+ end+++ }+ text = text.replace(css.slice(start, end), "")+ }+ for (const block of cssBlocks(text)) {+ for (const selector of block.selector.split(",").map(v => v.trim()).filter(v => v !== "" && !v.startsWith("@"))) {+ const declarations = merged.get(selector) ?? {}+ for (const entry of block.body.split(";")) {+ const colon = entry.indexOf(":")+ if (colon >= 0) declarations[entry.slice(0, colon).trim().toLowerCase()] = entry.slice(colon + 1).trim()+ }+ merged.set(selector, declarations)+ }+ }+ }+ return merged+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/curve-samples.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/curve-samples.tsnew file mode 100644index 00000000..b700cfcf--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/curve-samples.ts@@ -0,0 +1,55 @@+export type Point = readonly [number, number]+export const lerp = (a: Point, b: Point, t: number): Point => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]+export function cubic(p0: Point, p1: Point, p2: Point, p3: Point): readonly Point[] {+ return Array.from({ length: 15 }, (_, i) => {+ const t = (i + 1) / 16,+ u = 1 - t,+ a = u * u * u,+ b = 3 * u * u * t,+ c = 3 * u * t * t,+ d = t * t * t+ return [a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0], a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]] satisfies Point+ })+}+export function arc(+ from: Point,+ rxInput: number,+ ryInput: number,+ rotation: number,+ large: boolean,+ sweep: boolean,+ to: Point,+): readonly Point[] {+ let rx = Math.abs(rxInput),+ ry = Math.abs(ryInput)+ if ((from[0] === to[0] && from[1] === to[1]) || rx === 0 || ry === 0) return []+ const phi = (rotation * Math.PI) / 180,+ sin = Math.sin(phi),+ cos = Math.cos(phi),+ dx = (from[0] - to[0]) / 2,+ dy = (from[1] - to[1]) / 2+ const x1 = cos * dx + sin * dy,+ y1 = -sin * dx + cos * dy,+ lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry)+ if (lambda > 1) {+ rx *= Math.sqrt(lambda)+ ry *= Math.sqrt(lambda)+ }+ const num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1,+ den = rx * rx * y1 * y1 + ry * ry * x1 * x1+ const coef = (den === 0 ? 0 : Math.sqrt(Math.max(0, num / den))) * (large === sweep ? -1 : 1)+ const cx1 = (coef * rx * y1) / ry,+ cy1 = (-coef * ry * x1) / rx,+ cx = cos * cx1 - sin * cy1 + (from[0] + to[0]) / 2,+ cy = sin * cx1 + cos * cy1 + (from[1] + to[1]) / 2+ const theta = Math.atan2((y1 - cy1) / ry, (x1 - cx1) / rx)+ let delta = Math.atan2((-y1 - cy1) / ry, (-x1 - cx1) / rx) - theta+ if (sweep && delta < 0) delta += Math.PI * 2+ else if (!sweep && delta > 0) delta -= Math.PI * 2+ return Array.from({ length: 15 }, (_, i) => {+ const t = theta + (delta * (i + 1)) / 16,+ ex = rx * Math.cos(t),+ ey = ry * Math.sin(t)+ return [cos * ex - sin * ey + cx, sin * ex + cos * ey + cy] satisfies Point+ })+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/gradient-pattern.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/gradient-pattern.tsnew file mode 100644index 00000000..ee21f254--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/gradient-pattern.ts@@ -0,0 +1,40 @@+import { parseColor } from "../../../core/color"+import { splitTop } from "./appearance"+const position = (value: string): number | null => {+ const token = value+ .replace(/\s/g, "")+ .replace(/^(?:calc\()+/, "")+ .replace(/\)+$/, "")+ const match = /^([-+]?[\d.]+)(%|deg|grad|turn|px)?$/.exec(token)+ if (!match) return null+ const n = Number(match[1])+ if (n === 0) return 0+ return match[2] === "%" ? n / 100 : match[2] === "deg" ? n / 360 : match[2] === "grad" ? n / 400 : match[2] === "turn" ? n : null+}+export function repeats(value: string): boolean {+ for (const layer of splitTop(value)) {+ const m = /^repeating-(linear|radial)-gradient\(([\s\S]*)\)$/i.exec(layer)+ if (!m) continue+ const stops = splitTop(m[2] ?? ""),+ first = splitTop(stops[0] ?? "", /\s/),+ token = first[0] ?? ""+ if (token.includes("var(")) return true+ const start =+ parseColor(token) !== null ||+ (/^(?:transparent|currentcolor|[a-z]+)$/i.test(token) && !/^(?:circle|ellipse|to|at|in|closest|farthest)/i.test(token))+ ? 0+ : 1+ if (stops.length < start + 2) return true+ if (m[1]?.toLowerCase() === "radial" && start === 1) {+ const prelude = (stops[0] ?? "").split(/\bat\b|\bin\b/)[0] ?? ""+ if (/closest-|farthest-side|[0-9]/.test(prelude)) return true+ }+ const a = splitTop(stops[start] ?? "", /\s/),+ b = splitTop(stops.at(-1) ?? "", /\s/)+ if (b.length === 1 && b[0]?.includes("var(")) return true+ const zero = a[1] === undefined || position(a[1]) === 0,+ full = b.length === 1 || position(b.at(-1) ?? "") === 1+ if (!(zero && full)) return true+ }+ return false+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/keyframes.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/keyframes.tsnew file mode 100644index 00000000..115103c5--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/keyframes.ts@@ -0,0 +1,134 @@+import type { ComputedStyle, PageSnapshot } from "../../../types"+import { splitTop } from "./appearance"+export type Frame = Readonly<Record<string, string>>+export type KeyframeStep = { readonly key: string; readonly declarations: Frame }+export function keyframeSteps(s: PageSnapshot, name: string): readonly KeyframeStep[] | null {+ const frames: KeyframeStep[] = []+ let found = false+ for (const css of s.cssText) {+ const text = css.replace(/\/\*[\s\S]*?\*\//g, "")+ for (const m of text.matchAll(/@(?:-webkit-)?keyframes\s+([\w-]+)\s*\{/g)) {+ if (m[1] !== name) continue+ found = true+ let end = (m.index ?? 0) + m[0].length,+ depth = 1+ const start = end+ while (end < text.length && depth > 0) {+ if (text[end] === "{") depth+++ if (text[end] === "}") depth--+ end+++ }+ for (const step of text.slice(start, end - 1).matchAll(/([^{}]+)\{([^{}]*)\}/g)) {+ const entries = (step[2] ?? "").split(";").flatMap((d) => {+ const i = d.indexOf(":")+ return i < 0 ? [] : [[d.slice(0, i).trim().toLowerCase(), d.slice(i + 1).trim()]]+ })+ frames.push({ key: (step[1] ?? "").trim(), declarations: Object.fromEntries(entries) })+ }+ }+ }+ return found ? frames : null+}+export function keyframes(s: PageSnapshot, name: string): readonly Frame[] | null {+ return keyframeSteps(s, name)?.map(step => step.declarations) ?? null+}+export function infiniteNames(style: ComputedStyle): readonly string[] {+ const iterations = splitTop(style["animation-iteration-count"] ?? "")+ return splitTop(style["animation-name"] ?? "").filter((n, i) => n !== "none" && iterations[i % iterations.length] === "infinite")+}+export function onlyUnitPulse(frames: readonly Frame[]): boolean {+ return (+ frames.length > 0 &&+ frames.every((f) =>+ Object.entries(f).every(([p, v]) => {+ if (p === "opacity") return true+ if (p === "animation-timing-function") return !/linear\(|var\(/.test(v) && !overshoot(v)+ if (p !== "scale" && p !== "transform") return false+ if (v === "none") return true+ const rest = p === "scale" ? v : v.replace(/scale(?:[XYZ]|3d)?\(([^)]*)\)/gi, "$1")+ return (+ /^[\s,0-9.+-]+$/.test(rest) &&+ rest+ .split(/[\s,]+/)+ .filter(Boolean)+ .every((n) => Number(n) >= 0 && Number(n) <= 1)+ )+ }),+ )+ )+}+export const overshoot = (v: string): boolean =>+ [...v.matchAll(/cubic-bezier\(\s*([\d.+-]+)\s*,\s*([\d.+-]+)\s*,\s*([\d.+-]+)\s*,\s*([\d.+-]+)\s*\)/g)].some((m) =>+ [Number(m[2]), Number(m[4])].some((y) => y < -0.1 || y > 1.1),+ )+const scalar = (v: string): number | null => (/^[-+]?(?:\d*\.)?\d+(?:px)?$/.test(v) ? Number.parseFloat(v) : null)+const differs = (a: string | undefined, b: string | undefined): boolean => {+ if (a === undefined || b === undefined) return false+ const x = scalar(a),+ y = scalar(b)+ return x !== null && y !== null ? Math.abs(x - y) >= 4 : a.replace(/\s/g, "") !== b.replace(/\s/g, "")+}+function translation(f: Frame): readonly string[] | null {+ const t = f["transform"]+ if (t === undefined && f["translate"] === undefined) return null+ if (t?.includes("matrix")) return []+ const axes = ["0", "0", "0"]+ for (const m of (t ?? "").matchAll(/translate([XYZ]|3d)?\(([^)]*)\)/gi)) {+ const suffix = m[1]?.toLowerCase(),+ args = (m[2] ?? "").split(/,\s*/).map((x) => x.trim())+ if (suffix === "x" || suffix === "y" || suffix === "z") axes[suffix === "x" ? 0 : suffix === "y" ? 1 : 2] = args[0] ?? "0"+ else+ args.forEach((v, i) => {+ axes[i] = v+ })+ }+ if (f["translate"])+ f["translate"].split(/\s+/).forEach((v, i) => {+ axes[i] = v+ })+ return axes+}+export function dotPulse(frames: readonly Frame[]): boolean {+ const declarations = frames.flatMap((f) => Object.entries(f))+ const scales = declarations+ .filter(([p]) => p === "transform")+ .flatMap(([, v]) => [...v.matchAll(/scale([XY]|3d)?\(/gi)].map((m) => m[1] ?? "both"))+ const oneAxis =+ scales.length > 0 &&+ new Set(scales).size === 1 &&+ ["X", "Y", "x", "y"].includes(scales[0] ?? "") &&+ !declarations.some(([p]) => p === "scale")+ const signal = declarations.some(+ ([p, v]) => p === "opacity" || p === "box-shadow" || p === "scale" || (p === "transform" && /scale/i.test(v) && !oneAxis),+ )+ if (!signal) return false+ const translations = frames.map(translation).filter((t): t is readonly string[] => t !== null)+ for (const a of translations)+ for (const b of translations)+ for (let i = 0; i < 3; i++) {+ const x = a[i] ?? "0",+ y = b[i] ?? "0"+ if (!x.includes("%") && !y.includes("%") && differs(x, y)) return false+ }+ const sizes = frames.filter((f) => f["height"] !== undefined)+ if (sizes.some((f) => f["height"] !== sizes[0]?.["height"]) && sizes.every((f) => f["width"] === sizes[0]?.["width"])) return false+ const pairs = [+ ["left", "right"],+ ["top", "bottom"],+ ["inset-inline-start", "inset-inline-end"],+ ["inset-block-start", "inset-block-end"],+ ["margin-left", "margin-right"],+ ["margin-top", "margin-bottom"],+ ["margin-inline-start", "margin-inline-end"],+ ["margin-block-start", "margin-block-end"],+ ]+ for (const a of frames)+ for (const b of frames) {+ if (differs(a["width"], b["width"]) || differs(a["height"], b["height"])) continue+ for (const [x = "", y = ""] of pairs) if (differs(a[x], b[x]) !== differs(a[y], b[y])) return false+ }+ return true+}+export const toggles = (frames: readonly Frame[]): boolean =>+ frames.some((f) => Number(f["opacity"] ?? 1) <= 0.15 || f["visibility"] === "hidden") &&+ frames.every((f) => Object.keys(f).every((p) => ["opacity", "visibility", "animation-timing-function"].includes(p)))diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/labels.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/labels.tsnew file mode 100644index 00000000..57abf410--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/labels.ts@@ -0,0 +1,85 @@+import { ancestors, childrenOf, descendants, fontSizePx, isHeading, parentOf, styleOf } from "../../../core/page"+import { parseColor } from "../../../core/color"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { chroma, context, length, radii, visible } from "./appearance"+function previous(s: PageSnapshot, e: ElementSnapshot): ElementSnapshot | null {+ const p = parentOf(s, e)+ if (!p) return null+ const siblings = childrenOf(s, p),+ at = siblings.findIndex((n) => n.index === e.index)+ return siblings[at - 1] ?? null+}+export function labelBefore(s: PageSnapshot, h: ElementSnapshot): { label: ElementSnapshot; levels: number } | null {+ let at = h+ for (let levels = 0; levels <= 4; levels++) {+ const label = previous(s, at)+ if (label) return { label, levels }+ const p = parentOf(s, at)+ if (!p || ["body", "html"].includes(p.tag)) return null+ at = p+ }+ return null+}+export function labelType(s: PageSnapshot, e: ElementSnapshot): ElementSnapshot {+ let at = e+ for (let i = 0; i < 3; i++) {+ if (at.ownText.trim() !== "") return at+ const children = childrenOf(s, at).filter((c) => c.text.trim() !== "")+ const only = children[0]+ if (children.length !== 1 || !only) return at+ at = only+ }+ return at+}+export const application = (s: PageSnapshot, e: ElementSnapshot): boolean =>+ context(s, e, (a) => a.tag === "dialog" || ["tabpanel", "dialog", "application"].includes(a.attributes["role"] ?? ""))+export const caps = (e: ElementSnapshot): boolean =>+ styleOf(e, "text-transform") === "uppercase" || (/[A-Z]/.test(e.text) && !/[a-z]/.test(e.text))+export function heroLabel(s: PageSnapshot, h: ElementSnapshot): ElementSnapshot | null {+ if (h.tag !== "h1" || fontSizePx(h) < 48 || application(s, h) || !visible(s, h)) return null+ const e = previous(s, h)+ if (!e || isHeading(e) || e.text.trim().length < 2 || e.text.trim().length > 60 || !visible(s, e)) return null+ const ty = labelType(s, e),+ size = fontSizePx(ty),+ spacing = length(styleOf(ty, "letter-spacing"))+ if (size <= 0 || size > 14) return null+ const dated =+ (e.tag === "time" || [...descendants(s, e)].some((c) => c.tag === "time") || /\b(?:19|20)\d{2}\b/.test(e.text)) && spacing < 1.6+ const tracked = caps(ty) && !dated && (spacing >= 1.6 || spacing >= size * 0.08)+ const bold = Number(styleOf(ty, "font-weight")) >= 700 && chroma(styleOf(ty, "color"), 40)+ const dash = [e.before, e.after].some(+ (p) =>+ p &&+ length(p.style["width"] ?? "") >= 8 &&+ length(p.style["width"] ?? "") <= 80 &&+ length(p.style["height"] ?? "") >= 1 &&+ length(p.style["height"] ?? "") <= 6 &&+ chroma(p.style["background-color"] ?? ""),+ )+ return tracked || bold || dash ? e : null+}+export const headingLevel = (e: ElementSnapshot): number =>+ isHeading(e) ? Number(e.tag.slice(1)) : e.attributes["role"] === "heading" ? Number(e.attributes["aria-level"] ?? 2) : 0+export function cardContext(s: PageSnapshot, h: ElementSnapshot, label: ElementSnapshot): boolean {+ for (const a of ancestors(s, h)) {+ if (a.tag === "body") break+ if (![...descendants(s, a)].some((n) => n.index === label.index)) continue+ if (["article", "li", "a", "button"].includes(a.tag) && a.rect.height <= s.viewport.height * 2) return true+ if (headingLevel(h) < 3 || a.rect.height >= s.viewport.height) continue+ const bg = parseColor(styleOf(a, "background-color")),+ framed = radii(a).some((r) => r > 0) && bg !== null && bg.a >= 0.9+ if (!framed) continue+ const own = parseColor(styleOf(label, "background-color"))+ const badge =+ styleOf(label, "position") === "absolute" &&+ (label.rect.y <= a.rect.y + 2 ||+ (own !== null && own.a >= 0.9 && Math.max(Math.abs(own.r - bg.r), Math.abs(own.g - bg.g), Math.abs(own.b - bg.b)) > 3))+ return fontSizePx(h) < 24 || badge+ }+ return false+}+export const nearAbove = (label: ElementSnapshot, h: ElementSnapshot): boolean =>+ label.rect.y + label.rect.height <= h.rect.y + 4 &&+ h.rect.y - label.rect.y - label.rect.height <= Math.max(64, fontSizePx(h) * 2) &&+ label.rect.x < h.rect.x + h.rect.width &&+ label.rect.x + label.rect.width > h.rect.xdiff --git a/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/raster-state.ts b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/raster-state.tsnew file mode 100644index 00000000..dc1946b6--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/decoration/support/raster-state.ts@@ -0,0 +1,51 @@+import { ancestors, childrenOf, parentOf, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"++const tokens = (e: ElementSnapshot): readonly string[] => [...new Set((e.attributes["class"] ?? "").toLowerCase().split(/\s+/).filter(Boolean))]+const opacity = (s: PageSnapshot, e: ElementSnapshot): number =>+ [e, ...ancestors(s, e)].reduce((value, n) => {+ const own = Number.parseFloat(styleOf(n, "opacity"))+ return value * (Number.isFinite(own) ? own : 1)+ }, 1)+const transitionsOpacity = (e: ElementSnapshot): boolean => {+ const times = styleOf(e, "transition-duration").split(",")+ return styleOf(e, "transition-property").split(",").some((p, i) =>+ ["opacity", "all"].includes(p.trim()) && Number.parseFloat(times[i % times.length] ?? "0") > 0)+}++export function pendingRaster(s: PageSnapshot, e: ElementSnapshot): boolean {+ if (e.motion.includes("opacity")) return true+ const chain = [e, ...ancestors(s, e)]+ if (chain.slice(1).some(n => Number.parseFloat(styleOf(n, "opacity")) <= 0.02) ||+ chain.some(n => styleOf(n, "display") === "none" || styleOf(n, "visibility") === "hidden")) return true+ const attrs = e.attributes+ if (attrs["data-loaded"]?.trim().toLowerCase() === "false" ||+ (attrs["data-ll-status"] !== undefined && attrs["data-ll-status"].trim().toLowerCase() !== "loaded")) return true+ if (["data-src", "data-srcset", "data-lazy", "data-lazy-src", "data-lazy-srcset", "data-original", "data-original-src"]+ .some(name => attrs[name] !== undefined) && (attrs["src"] ?? "").trim() === "") return true+ const parent = parentOf(s, e)+ const classes = [e, ...(parent ? [parent] : [])].flatMap(tokens)+ if (classes.some(t => t.includes("lazy")) && !classes.some(t => t.includes("loaded")) &&+ (opacity(s, e) <= 0.02 || /(?:^|;)\s*opacity\s*:/i.test(attrs["style"] ?? ""))) return true+ if (parent && opacity(s, e) <= 0.02) {+ const videoOver = (n: ElementSnapshot, depth: number): boolean => {+ const w = Math.min(e.rect.x + e.rect.width, n.rect.x + n.rect.width) - Math.max(e.rect.x, n.rect.x)+ const h = Math.min(e.rect.y + e.rect.height, n.rect.y + n.rect.height) - Math.max(e.rect.y, n.rect.y)+ if (n.tag === "video" && opacity(s, n) > 0.02 && [n, ...ancestors(s, n)].every(a =>+ styleOf(a, "display") !== "none" && styleOf(a, "visibility") !== "hidden") &&+ w > 0 && h > 0 && w * h >= e.rect.width * e.rect.height * 0.5) return true+ return depth > 0 && childrenOf(s, n).some(child => videoOver(child, depth - 1))+ }+ if (parent.tag === "video" || childrenOf(s, parent).some(n => n.index !== e.index && videoOver(n, 3))) return true+ }+ if (e.tag !== "img" || opacity(s, e) > 0.02) return false+ const own = tokens(e)+ const peers = s.elements.filter(other => {+ if (other.index === e.index || other.tag !== "img" || Number.parseFloat(styleOf(other, "opacity")) < 0.5 ||+ opacity(s, other) <= 0.02 || !transitionsOpacity(other)) return false+ const theirs = tokens(other)+ const shared = own.filter(t => theirs.includes(t)).length+ return shared > 0 && own.length - shared <= 1 && theirs.filter(t => !own.includes(t)).length === 1+ })+ return peers.length >= 2+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/index.ts b/plugins/omo/skills/frontend/scripts/detect/rules/index.tsnew file mode 100644index 00000000..08f8aa83--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/index.ts@@ -0,0 +1,16 @@+import type { Rule } from "../rule"+import { COLOR_RULES } from "./color"+import { TYPOGRAPHY_RULES } from "./typography"+import { LAYOUT_RULES } from "./layout"+import { DECORATION_RULES } from "./decoration"+import { COPY_RULES } from "./copy"+import { SOURCE_RULES } from "./source"++export const ALL_RULES: readonly Rule[] = [+ ...COLOR_RULES,+ ...TYPOGRAPHY_RULES,+ ...LAYOUT_RULES,+ ...DECORATION_RULES,+ ...COPY_RULES,+ ...SOURCE_RULES,+]diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/body-text-viewport-edge.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/body-text-viewport-edge.tsnew file mode 100644index 00000000..b23b6745--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/body-text-viewport-edge.ts@@ -0,0 +1,62 @@+import { childrenOf, fontSizePx, isIgnored, shortSnippet, styleOf } from "../../core/page"+import type { PageHit, PageRule } from "../../rule"+import { alpha, bounds, chain, clipsX, length, outOfFlow, painted, right, scrollsX, textLines } from "./support/geometry"+import { trackCuts } from "./support/clipping"+import { ridesRunningTrack } from "./support/motion"++export const bodyTextViewportEdge: PageRule = {+ meta: {+ id: "body-text-viewport-edge", name: "Body text touching viewport edge", category: "quality", severity: "warning", engine: "page",+ description: "Reading text touches the viewport edge without a usable gutter.",+ fixHint: "Keep at least 12px of horizontal space on phones and 16px on wider screens; constrain overflowing columns.",+ },+ check: ({ snapshot }) => {+ const width = snapshot.viewport.width+ const floor = width <= 480 ? 12 : 16+ const hits: PageHit[] = []+ let overflow = false+ for (const el of snapshot.elements) {+ if (isIgnored(snapshot, el, "body-text-viewport-edge")) continue+ const prose = ["p", "li"].includes(el.tag)+ const generic = ["div", "section", "article", "aside", "main"].includes(el.tag) &&+ el.ownText !== "" && fontSizePx(el) < 28 && ["block", "flow-root"].includes(styleOf(el, "display")) &&+ childrenOf(snapshot, el).every((c) => styleOf(c, "display") === "inline")+ if (!(prose || generic) || el.text.length <= 40 || !painted(snapshot, el) || outOfFlow(el) ||+ el.rect.width <= width * 0.5 || alpha(el, "background-color") > 0) continue+ if (ridesRunningTrack(snapshot, el)) continue+ const path = chain(snapshot, el)+ if (generic && path.some((n) => /^(a|button|label|summary|select|textarea)$/.test(n.tag) ||+ /^(button|link|tab|menuitem|option)$/.test(n.attributes["role"] ?? "") || n.attributes["contenteditable"] !== undefined)) continue+ if (path.some((n) => n.tag === "nav" || n.tag === "header" && n.rect.height <= snapshot.viewport.height ||+ scrollsX(n) || /^(pre|pre-wrap)$/.test(styleOf(n, "white-space")))) continue+ const lines = textLines(snapshot, el)+ const text = bounds(lines)+ if (!text && generic) continue+ if (text && trackCuts(snapshot, el, text)) continue+ let left = text?.x ?? el.rect.x+ let end = text ? right(text) : right(el.rect)+ if (clipsX(el) && !["", "clip"].includes(styleOf(el, "text-overflow"))) {+ left = Math.max(left, el.rect.x)+ end = Math.min(end, right(el.rect))+ }+ const contentLeft = el.rect.x + length(el, "padding-left") + length(el, "border-left-width")+ const contentEnd = right(el.rect) - length(el, "padding-right") - length(el, "border-right-width")+ if (text && lines.length >= 2 && text.width >= (contentEnd - contentLeft) * 0.9 &&+ !(styleOf(el, "text-align") !== "justify" && left >= 16 && end <= width - 16)) {+ left = contentLeft+ end = contentEnd+ } else if (styleOf(el, "display") === "list-item") {+ left = Math.min(left, contentLeft)+ }+ if (end <= 0 || left >= width) continue+ if (path.slice(1).some((n) => styleOf(n, "position") === "fixed" && n.rect.height < snapshot.viewport.height / 2) && Math.min(left, width - end) >= 4) continue+ if (Math.round(-left) > 0 || Math.round(end - width) > 0) overflow = true+ if (Math.round(left) >= 0 && left < floor || Math.round(width - end) >= 0 && width - end < floor) hits.push({ element: el, message: `Body copy keeps less than ${floor}px from the viewport edge.`, snippet: shortSnippet(el) })+ }+ if (overflow) {+ const widest = snapshot.elements.filter((el) => painted(snapshot, el) && !chain(snapshot, el).some(scrollsX)).sort((a, b) => right(b.rect) - right(a.rect))[0]+ hits.push({ element: null, message: `Body text runs outside the viewport${widest ? `; widest element ${widest.selector} ends at ${right(widest.rect)}px` : ""}.`, snippet: widest ? shortSnippet(widest) : "Page overflow" })+ }+ return hits+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/clipped-overflow-container.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/clipped-overflow-container.tsnew file mode 100644index 00000000..fd050f3b--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/clipped-overflow-container.ts@@ -0,0 +1,15 @@+import { shortSnippet } from "../../core/page"+import type { PageRule } from "../../rule"+import { clippedChild } from "./support/clipping"++export const clippedOverflowContainer: PageRule = {+ meta: {+ id: "clipped-overflow-container", name: "Positioned child clipped by overflow container", category: "quality", severity: "advisory", engine: "page",+ description: "A container cuts off a positioned menu, tooltip, or dialog that needs to escape it.",+ fixHint: "Render the popup outside the clipping box or remove the clip from its containing block.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap((el) => {+ const child = clippedChild(snapshot, el)+ return child ? [{ element: el, message: `${el.selector} clips positioned popup ${child.selector}.`, snippet: shortSnippet(el) }] : []+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/content-hidden-at-rest.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/content-hidden-at-rest.tsnew file mode 100644index 00000000..97f80bec--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/content-hidden-at-rest.ts@@ -0,0 +1,63 @@+import { childrenOf, descendants, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import type { ElementSnapshot, PageSnapshot } from "../../types"+import { bottom, chain, hasRole, right } from "./support/geometry"+import { classWords, closedClass, unstartedSlider } from "./support/hidden-interface"++function closed(s: PageSnapshot, el: ElementSnapshot): boolean {+ const controls = s.elements.filter((n) => (n.attributes["aria-controls"] ?? "").split(/\s+/).includes(el.attributes["id"] ?? "\u0000"))+ const labels = (el.attributes["aria-labelledby"] ?? "").split(/\s+/)+ const selected = (hasRole(el, ["tabpanel"]) || classWords(el).some((word) => ["tab", "tabs", "tabpanel", "tabpane"].includes(word))) &&+ (controls.some((n) => n.attributes["aria-selected"] === "true" || n.attributes["aria-expanded"] === "true") ||+ s.elements.some((n) => labels.includes(n.attributes["id"] ?? "\u0000") && n.attributes["aria-selected"] === "true"))+ if (!selected && controls.some((n) => n.attributes["aria-selected"] === "false" || n.attributes["aria-expanded"] === "false")) return true+ if (!selected && (hasRole(el, ["dialog", "alertdialog", "tabpanel"]) || closedClass(el))) return true+ if (styleOf(el, "position") === "fixed" && (right(el.rect) <= 0 || el.rect.x >= s.viewport.width)) return true+ const path = chain(s, el)+ if (path.some((n) => n.attributes["inert"] !== undefined || n.tag === "nav" || hasRole(n, ["navigation", "menu", "menubar"]))) return true+ if (styleOf(el, "position") === "fixed" && /^(hidden|collapse)$/.test(styleOf(el, "visibility")) &&+ el.rect.x <= 1 && el.rect.y <= 1 && right(el.rect) >= s.viewport.width - 1 && bottom(el.rect) >= s.viewport.height - 1) {+ const nodes = [el, ...descendants(s, el)]+ const chars = nodes.reduce((sum, n) => sum + n.ownText.length, 0)+ const pageChars = s.elements.reduce((sum, n) => sum + n.ownText.length, 0)+ if (chars * 2 < pageChars && !nodes.some((n) => n.tag === "main" || n.tag === "h1" || hasRole(n, ["main"]))) return true+ }+ if (path.some((n) => /^(absolute|fixed)$/.test(styleOf(n, "position")) &&+ !["", "none", "matrix(1, 0, 0, 1, 0, 0)"].includes(styleOf(n, "transform")) &&+ /\b(?:transform|all)\b/.test(styleOf(n, "transition-property")) &&+ (right(n.rect) <= 0 || n.rect.x >= s.viewport.width))) return true+ const p = el.parent === null ? undefined : s.elements[el.parent]+ const siblings = p ? childrenOf(s, p) : []+ const previous = siblings[siblings.indexOf(el) - 1]+ if (previous && (previous.attributes["aria-expanded"] === "false" ||+ childrenOf(s, previous).length === 1 && childrenOf(s, previous)[0]?.attributes["aria-expanded"] === "false")) return true+ return path.slice(1).some((n) => {+ const triggers = s.elements.filter((t) => (t.attributes["aria-controls"] ?? "").split(/\s+/).includes(n.attributes["id"] ?? "\u0000"))+ return triggers.some((t) => t.attributes["aria-expanded"] === "false" || t.attributes["aria-selected"] === "false") &&+ !triggers.some((t) => t.attributes["aria-expanded"] === "true" || t.attributes["aria-selected"] === "true")+ })+}++export const contentHiddenAtRest: PageRule = {+ meta: {+ id: "content-hidden-at-rest", name: "Content invisible at rest", category: "quality", severity: "error", engine: "page",+ description: "A large share of page text remains transparent or hidden instead of appearing as content.",+ fixHint: "Show content by default and enhance its entrance without making visibility depend on a reveal script.",+ },+ check: ({ snapshot }) => {+ let total = 0+ let hidden = 0+ for (const el of snapshot.elements) {+ if (el.ownText === "") continue+ const path = chain(snapshot, el)+ if (path.some((n) => /^(script|style|noscript|template|title|head|meta|link|option|optgroup|select|datalist|dialog)$/.test(n.tag) ||+ n.attributes["hidden"] !== undefined || n.attributes["aria-hidden"] === "true" || styleOf(n, "display") === "none")) continue+ const invisible = [...path].reverse().find((n) => Number.parseFloat(styleOf(n, "opacity")) <= 0.02 || /^(hidden|collapse)$/.test(styleOf(n, "visibility")))+ if (invisible && (closed(snapshot, invisible) || unstartedSlider(snapshot, invisible))) continue+ total += el.ownText.length+ if (invisible) hidden += el.ownText.length+ }+ if (total < 200 || hidden < 150 || hidden / total <= 0.3) return []+ return [{ element: null, message: `${hidden} of ${total} characters (${Math.round(hidden / total * 100)}%) remain hidden.`, snippet: `${hidden}/${total} hidden characters` }]+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/cramped-padding.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/cramped-padding.tsnew file mode 100644index 00000000..62098f65--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/cramped-padding.ts@@ -0,0 +1,97 @@+import { childrenOf, descendants, fontSizePx, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { fillDiffers } from "./support/cards"+import { alpha, borders, bottom, bounds, chain, clipsY, intersects, length, outOfFlow, painted, right } from "./support/geometry"+import { continuedFill, glyphBand, paddingBackdrop, paddingFill, paddingScale, uncut } from "./support/padding"++export const crampedPadding: PageRule = {+ meta: {+ id: "cramped-padding", name: "Cramped padding", category: "quality", severity: "warning", engine: "page",+ description: "Rendered text sits too close to a visible container boundary.",+ fixHint: "Inset text from the painted boundary; use at least 8px beside body text and scale the space with its font size.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap((el) => {+ if (!painted(snapshot, el) || styleOf(el, "display") === "inline" || el.rect.width <= 0 || el.rect.height <= 0) return []+ const drawn = borders(el)+ const fill = paddingFill(snapshot, el) && !paddingBackdrop(snapshot, el)+ const outline = length(el, "outline-width") > 0 && !["", "none"].includes(styleOf(el, "outline-style")) && alpha(el, "outline-color") > 0+ const fullBleed = el.rect.width >= snapshot.document.clientWidth * 0.94+ if (!fill && !drawn.some(Boolean) && !outline) return []+ const sides = ["top", "right", "bottom", "left"]+ const inset = (r: typeof el.rect): readonly number[] => [+ r.y - el.rect.y - length(el, "border-top-width"),+ right(el.rect) - right(r) - length(el, "border-right-width"),+ bottom(el.rect) - bottom(r) - length(el, "border-bottom-width"),+ r.x - el.rect.x - length(el, "border-left-width"),+ ]+ if (el.ownText.length > 20 && el.rect.width > 100 && el.rect.height > 30 &&+ !(el.tag === "code" && !snapshot.elements.some((a) => a.tag === "pre" && [...descendants(snapshot, a)].includes(el)))) {+ if (!fill && drawn.filter(Boolean).length < 2) return []+ const text = bounds(el.lineRects.filter((r) => intersects(r, el.rect)))+ if (!text) return []+ const band = glyphBand(el, text)+ const clipped = { x: Math.max(band.x, el.rect.x), y: Math.max(band.y, el.rect.y),+ width: Math.min(right(band), right(el.rect)) - Math.max(band.x, el.rect.x),+ height: Math.min(bottom(band), bottom(el.rect)) - Math.max(band.y, el.rect.y) }+ const insets = inset(clipped)+ const size = fontSizePx(el)+ const bad = sides.some((side, i) => {+ const vertical = i === 0 || i === 2+ const threshold = vertical ? Math.max(4, size * 0.3) : Math.max(8, size * 0.5)+ return (drawn[i] || fill && (vertical || !fullBleed)) &&+ length(el, `padding-${side}`) < threshold && (insets[i] ?? Infinity) < threshold+ })+ return bad ? [{ element: el, message: "The measured inset is too small for the text size.", snippet: shortSnippet(el) }] : []+ }+ if (el.ownText !== "" || outOfFlow(el) || /^(html|body|main|header|footer|nav|article|aside|button|a|label|summary|code|pre|input|textarea|select|form|figure|table|tbody|thead|tr|td|th)$/.test(el.tag)) return []+ let kids = childrenOf(snapshot, el)+ let unwrapped = false+ for (let depth = 0; depth < 3; depth++) {+ const only = kids.length === 1 ? kids[0] : undefined+ if (!only || only.ownText !== "" || borders(only).some(Boolean) || fillDiffers(snapshot, only) ||+ ["top", "right", "bottom", "left"].some((side) => length(only, `padding-${side}`) > 0) ||+ childrenOf(snapshot, only).length === 0) break+ kids = childrenOf(snapshot, only)+ unwrapped = true+ }+ const texts = [...descendants(snapshot, el)].filter((n) =>+ /^(a|button|code|dd|dt|figcaption|h[1-6]|li|p|pre|span|td|th)$/.test(n.tag) &&+ n.ownText.length > 4 && painted(snapshot, n) && !chain(snapshot, n).slice(0, chain(snapshot, n).indexOf(el))+ .some((c) => outOfFlow(c) || styleOf(c, "display") !== "inline" && paddingFill(snapshot, c)))+ const flush = sides.some((side, i) => {+ if (!(drawn[i] || outline || fill && (!(i === 1 || i === 3) || !fullBleed))) return false+ if (!drawn[i] && !outline && continuedFill(snapshot, el, i)) return false+ if (length(el, `padding-${side}`) > 2) return false+ if (i === 2 && [...descendants(snapshot, el)].some((n) => clipsY(n) &&+ n.scroll.scrollHeight > n.scroll.clientHeight + 1 && Math.abs(bottom(n.rect) - bottom(el.rect)) <= 2)) return false+ const textFlush = texts.some((n) => {+ let r = bounds(n.lineRects)+ if (!r) return false+ const scale = paddingScale(el)+ const small = el.rect.height / scale < 27.5+ if ((small || !fill && !outline && drawn.filter(Boolean).length === 1) && (i === 0 || i === 2)) r = glyphBand(n, r, scale)+ const x = Math.max(r.x, n.rect.x)+ const y = Math.max(r.y, n.rect.y)+ r = { x, y, width: Math.min(right(r), right(n.rect)) - x, height: Math.min(bottom(r), bottom(n.rect)) - y }+ if (r.width <= 0 || r.height <= 0) return false+ if (!uncut(snapshot, n, el, r, i)) return false+ const gap = inset(r)[i] ?? Infinity+ const threshold = (small ? Math.min(4, fontSizePx(n) * 0.25) : 4) * scale+ return gap >= -scale && gap < threshold+ })+ if (!textFlush) return false+ const insulated = (c: typeof el): boolean => {+ if (outOfFlow(c)) return true+ const gap = inset(c.rect)[i] ?? Infinity+ const offset = styleOf(c, "position") === "relative" &&+ ["top", "right", "bottom", "left"].some((p) => length(c, p) !== 0) ||+ !["", "none"].includes(styleOf(c, "transform"))+ if (offset) return gap >= 4+ return gap < -1 || gap >= 4 || styleOf(c, "position") === "static" &&+ (length(c, `padding-${side}`) >= 4 || length(c, `margin-${side}`) >= 4)+ }+ return unwrapped || !kids.some(insulated)+ })+ return flush ? [{ element: el, message: "Child text lands flush against a painted container edge.", snippet: shortSnippet(el) }] : []+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/edge-flush-cards.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/edge-flush-cards.tsnew file mode 100644index 00000000..2b79e471--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/edge-flush-cards.ts@@ -0,0 +1,47 @@+import { ancestors, descendants, isRendered, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { alpha, borders, chain, length, painted, right, scrollsX } from "./support/geometry"++export const edgeFlushCards: PageRule = {+ meta: {+ id: "edge-flush-cards", name: "Cards flush against the scroller edge", category: "quality", severity: "warning", engine: "page",+ description: "A card row keeps a gutter on one side but touches or slightly crosses the opposite clipping edge.",+ fixHint: "Size each panel to its scroll container and keep an equal inset at both edges.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap((scroller) => {+ if (scroller.tag === "body" || !scrollsX(scroller) || !painted(snapshot, scroller) ||+ scroller.scroll.scrollWidth <= scroller.scroll.clientWidth + 8 ||+ scroller.rect.width < 120 || scroller.rect.height < 60 || scroller.rect.y > snapshot.viewport.height * 2) return []+ const cards = [...descendants(snapshot, scroller)].filter((el) => {+ if (!isRendered(snapshot, el) || el.rect.width < 80 || el.rect.height < 40 ||+ /^(table|thead|tbody|tfoot|tr|td|th|col|colgroup)$/.test(el.tag) ||+ /^(row|cell|gridcell|rowgroup|columnheader|rowheader)$/.test(el.attributes["role"] ?? "")) return false+ if (alpha(el, "background-color") <= 0.5 && borders(el).filter(Boolean).length < 2) return false+ for (const a of ancestors(snapshot, el)) {+ if (a === scroller) return true+ if (scrollsX(a)) return false+ }+ return false+ })+ if (cards.length < 2 || Math.min(...cards.map((c) => right(c.rect))) > Math.max(...cards.map((c) => c.rect.x)) + 1) return []+ const left = scroller.rect.x + length(scroller, "border-left-width")+ const end = left + scroller.scroll.clientWidth+ const gutter = (side: "left" | "right"): boolean => {+ const inset = side === "left" ? scroller.rect.x : snapshot.viewport.width - right(scroller.rect)+ if (inset < 12 || inset > 48) return false+ return !chain(snapshot, scroller).slice(0, 7).some((n) => {+ if (n.tag === "body") return false+ const near = side === "left" ? Math.abs(n.rect.x - scroller.rect.x) <= 2 : Math.abs(right(n.rect) - right(scroller.rect)) <= 2+ return near && (alpha(n, "background-color") > 0 || !["", "none"].includes(styleOf(n, "background-image")) ||+ !["", "none"].includes(styleOf(n, "box-shadow")) || borders(n)[side === "left" ? 3 : 1])+ })+ }+ const flush = cards.filter((c) => {+ const start = c.rect.x - left+ const gap = end - right(c.rect)+ return (start >= 6 && gap < 8 && gap > -24 && !(gap >= 0 && gutter("right"))) ||+ (gap >= 6 && start < 8 && start > -24 && !(start >= 0 && gutter("left")))+ })+ return flush.length === 0 ? [] : [{ element: scroller, message: `${flush.length} cards touch a scroll edge while keeping an opposite gutter.`, snippet: shortSnippet(scroller) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/first-viewport-column-overflow.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/first-viewport-column-overflow.tsnew file mode 100644index 00000000..f4cf2f32--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/first-viewport-column-overflow.ts@@ -0,0 +1,43 @@+import { ancestors, childrenOf, descendants, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { bottom, chain, clipsY, hasRole, outOfFlow, painted, right } from "./support/geometry"++export const firstViewportColumnOverflow: PageRule = {+ meta: {+ id: "first-viewport-column-overflow", name: "One column stretches the first viewport", category: "quality", severity: "warning", engine: "page",+ description: "An opening row has one column extending far below the fold while its sibling fits on one screen.",+ fixHint: "Balance the opening columns, cap the longer one, or let its remaining content flow below the row.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap((el) => {+ const { width, height } = snapshot.viewport+ if (!/^(inline-)?(flex|grid)$/.test(styleOf(el, "display")) || !painted(snapshot, el) ||+ el.rect.width < width * 0.5 || el.rect.y >= height * 0.9 || bottom(el.rect) <= height) return []+ const rail = (n: typeof el): boolean => {+ if (n.tag === "nav" || hasRole(n, ["navigation", "tablist"]) || styleOf(n, "position") === "sticky") return true+ const nodes = [n, ...descendants(snapshot, n)].filter((c) => c.ownText !== "" && painted(snapshot, c))+ return nodes.length >= 3 && nodes.filter((c) => chain(snapshot, c).some((a) => a.tag === "a" || hasRole(a, ["tab", "menuitem"]))).length / nodes.length >= 0.8+ }+ const cols = childrenOf(snapshot, el).flatMap((child) => {+ const share = child.rect.width / el.rect.width+ if (!painted(snapshot, child) || outOfFlow(child) || rail(child) || share < 0.25 || share > 0.9 || child.rect.height < 40) return []+ let end = child.rect.y+ for (const d of descendants(snapshot, child)) {+ if (!painted(snapshot, d) || [d, ...ancestors(snapshot, d)].some((n) => n !== el && outOfFlow(n))) continue+ let visible = bottom(d.rect)+ for (const a of ancestors(snapshot, d)) {+ if (a === el) break+ if (clipsY(a)) visible = Math.min(visible, bottom(a.rect))+ }+ end = Math.max(end, visible)+ }+ return end - child.rect.y < 1 ? [] : [{ rect: child.rect, height: end - child.rect.y }]+ }).sort((a, b) => b.height - a.height)+ const tall = cols[0]+ if (!tall || tall.height <= height * 1.4) return []+ const short = cols.slice(1).filter((c) =>+ !(tall.rect.x < right(c.rect) - 1 && c.rect.x < right(tall.rect) - 1) &&+ Math.abs(tall.rect.y - c.rect.y) <= height * 0.25).sort((a, b) => a.height - b.height)[0]+ if (!short || short.height > height) return []+ return [{ element: el, message: `Opening columns use ${Math.round(tall.height / height * 100)}% and ${Math.round(short.height / height * 100)}% of the viewport height.`, snippet: shortSnippet(el) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/heading-rhythm.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/heading-rhythm.tsnew file mode 100644index 00000000..f4c13bad--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/heading-rhythm.ts@@ -0,0 +1,30 @@+import { fontSizePx, shortSnippet } from "../../core/page"+import type { PageRule } from "../../rule"+import { bottom, length } from "./support/geometry"+import { closesInProse, contentBottom, headingCluster, neighbour, paintsEdge, rhythmExempt, separatesBelow } from "./support/rhythm"++export const headingRhythm: PageRule = {+ meta: {+ id: "heading-rhythm", name: "Heading crowded against the previous block", category: "quality", severity: "warning", engine: "page",+ description: "Several headings sit closer to preceding content than to the content they introduce.",+ fixHint: "Give section headings more space above than below so each title binds to its own content.",+ },+ check: ({ snapshot }) => {+ const hits = snapshot.elements.flatMap((el) => {+ if (rhythmExempt(snapshot, el)) return []+ const next = neighbour(snapshot, el, false)+ if (!next) return []+ const below = Math.max(0, next.rect.y - bottom(el.rect))+ if (below < 6 || below > 160) return []+ const top = headingCluster(snapshot, el, below)+ const previous = neighbour(snapshot, el, true, top)+ if (!previous || separatesBelow(snapshot, previous)) return []+ const above = Math.max(0, top.rect.y - contentBottom(snapshot, previous) + (paintsEdge(top, "top") ? 0 : length(top, "padding-top")))+ const crowded = above < below * 0.75 && below - above >= 12+ const body = snapshot.elements.find((n) => n.tag === "body")+ const even = above <= below + 2 && closesInProse(snapshot, previous, el, Math.max(body ? fontSizePx(body) : 16, fontSizePx(next)))+ return crowded || even ? [{ element: el, message: `Heading has ${Math.round(above)}px above and ${Math.round(below)}px below.`, snippet: shortSnippet(el) }] : []+ })+ return hits.length >= 2 ? hits : []+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/index.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/index.tsnew file mode 100644index 00000000..359fb921--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/index.ts@@ -0,0 +1,21 @@+import type { Rule } from "../../rule"+import { bodyTextViewportEdge } from "./body-text-viewport-edge"+import { clippedOverflowContainer } from "./clipped-overflow-container"+import { contentHiddenAtRest } from "./content-hidden-at-rest"+import { crampedPadding } from "./cramped-padding"+import { edgeFlushCards } from "./edge-flush-cards"+import { firstViewportColumnOverflow } from "./first-viewport-column-overflow"+import { headingRhythm } from "./heading-rhythm"+import { monotonousSpacing } from "./monotonous-spacing"+import { nestedCards } from "./nested-cards"+import { straggler } from "./straggler"+import { textOcclusion } from "./text-occlusion"+import { textOverflow } from "./text-overflow"+import { unbalancedHeading } from "./unbalanced-heading"+import { viewportReflow } from "./viewport-reflow"++export const LAYOUT_RULES: readonly Rule[] = [+ nestedCards, monotonousSpacing, edgeFlushCards, textOcclusion, firstViewportColumnOverflow,+ crampedPadding, bodyTextViewportEdge, textOverflow, clippedOverflowContainer, headingRhythm,+ straggler, unbalancedHeading, contentHiddenAtRest, viewportReflow,+]diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/monotonous-spacing.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/monotonous-spacing.tsnew file mode 100644index 00000000..ec547e1b--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/monotonous-spacing.ts@@ -0,0 +1,32 @@+import type { PageRule } from "../../rule"++export const monotonousSpacing: PageRule = {+ meta: {+ id: "monotonous-spacing", name: "Monotonous spacing", category: "slop", severity: "warning", engine: "page",+ description: "One spacing value dominates the page instead of separating related groups from sections.",+ fixHint: "Keep related items close and give separate sections a larger gap.",+ },+ check: ({ snapshot }) => {+ const values: number[] = []+ const css = [...snapshot.cssText, ...snapshot.elements.map((el) => el.attributes["style"] ?? "")].join("\n")+ for (const m of css.matchAll(/(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi)) {+ const v = Number(m[1])+ if (v > 0 && v < 200) values.push(v)+ }+ for (const m of css.matchAll(/(?:gap|row-gap|column-gap)\s*:\s*(\d+)px/gi)) values.push(Number(m[1]))+ for (const el of snapshot.elements) {+ for (const m of (el.attributes["class"] ?? "").matchAll(/\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g)) values.push(Number(m[1]) * 4)+ }+ for (const m of css.matchAll(/(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d*\.?\d+)rem/gi)) {+ const v = Math.round(Number(m[1]) * 16)+ if (v > 0 && v < 200) values.push(v)+ }+ const rounded = values.map((v) => Math.round(v / 4) * 4)+ if (rounded.length < 10) return []+ const counts = new Map<number, number>()+ for (const v of rounded) counts.set(v, (counts.get(v) ?? 0) + 1)+ const dominant = [...counts].sort((a, b) => b[1] - a[1])[0]+ if (!dominant || dominant[0] === 0 || dominant[1] / rounded.length <= 0.6 || [...counts.keys()].filter((v) => v > 0).length > 3) return []+ return [{ element: null, message: `${dominant[0]}px accounts for ${dominant[1]} of ${rounded.length} spacing declarations.`, snippet: `${Math.round(dominant[1] / rounded.length * 100)}% repeated spacing` }]+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/nested-cards.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/nested-cards.tsnew file mode 100644index 00000000..e66379cf--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/nested-cards.ts@@ -0,0 +1,38 @@+import { ancestors, descendants, isIgnored, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { cardLike, controlStrip, dialogCard, embeddedFrame, fieldBox, hasBorderOrShadow, labelBox, pageFrame, sharesEdges } from "./support/cards"+import { hasRole, ident, outOfFlow, painted } from "./support/geometry"+import { declaredMockups } from "./support/declared-mockups"++export const nestedCards: PageRule = {+ meta: {+ id: "nested-cards", name: "Nested cards", category: "slop", severity: "warning", engine: "page",+ description: "A bordered or raised card sits inside another card and adds an unnecessary surface.",+ fixHint: "Flatten the inner group with spacing, typography, or a divider instead of another card frame.",+ },+ check: ({ snapshot }) => {+ const mockups = declaredMockups(snapshot)+ const candidates = snapshot.elements.filter((el) => {+ if ([el, ...ancestors(snapshot, el)].some((a) => mockups.has(a)) ||+ !painted(snapshot, el) || !cardLike(snapshot, el) || !hasBorderOrShadow(el) || outOfFlow(el) ||+ hasRole(el, ["menu", "listbox", "tablist", "radiogroup", "toolbar"]) ||+ /(?:^|[\s_-])(?:popover|dropdown|tooltip)(?:$|[\s_-])/.test(ident(el)) ||+ el.text.length < 10 || el.rect.width < 50 || el.rect.height < 30 ||+ /^(inline|contents)$/.test(styleOf(el, "display")) || labelBox(snapshot, el) || fieldBox(snapshot, el) || controlStrip(snapshot, el)) return false+ const outer = [...ancestors(snapshot, el)].find((a) => cardLike(snapshot, a) && !pageFrame(snapshot, a))+ return outer !== undefined && !sharesEdges(snapshot, el, outer) && !dialogCard(snapshot, outer) && !embeddedFrame(snapshot, el, outer)+ })+ const panels = new Set<string>()+ return candidates.filter((el) => ![...descendants(snapshot, el)].some((d) => candidates.includes(d)))+ .filter((el) => {+ if (isIgnored(snapshot, el, "nested-cards")) return false+ const outer = [...ancestors(snapshot, el)].find((a) => cardLike(snapshot, a) && !pageFrame(snapshot, a))+ const picture = [...ancestors(snapshot, el)].some((a) => a.tag !== "svg" && hasRole(a, ["img"]))+ const key = `${outer?.index}:${picture}`+ if (panels.has(key)) return false+ panels.add(key)+ return true+ })+ .map((el) => ({ element: el, message: "A separately framed card is nested inside another card.", snippet: shortSnippet(el) }))+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/straggler.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/straggler.tsnew file mode 100644index 00000000..480e45f0--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/straggler.ts@@ -0,0 +1,28 @@+import { shortSnippet } from "../../core/page"+import type { PageRule } from "../../rule"+import { measuredLines, oneFace, wordsOf, wrapIs } from "./support/line-breaks"++export const straggler: PageRule = {+ meta: {+ id: "straggler", name: "Straggler", category: "quality", severity: "advisory", engine: "page",+ description: "A paragraph leaves one short word on its last line.",+ fixHint: "Use text-wrap: pretty or edit the ending so the last line has company.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap((el) => {+ if (!["p", "li", "dd", "blockquote", "figcaption"].includes(el.tag) || wrapIs(el, "pretty") || !oneFace(snapshot, el)) return []+ const lines = measuredLines(snapshot, el)+ const tail = lines.at(-1)+ const words = wordsOf(el)+ const last = words.at(-1)+ const before = words.at(-2)+ if (lines.length < 2 || !tail || !last || !before || words.length < 3 ||+ /[\u3000-\u9fff\uac00-\ud7af]/.test(el.text) || lines.length <= 6 && wrapIs(el, "balance")) return []+ const widest = Math.max(...lines.map((l) => l.width))+ const sum = lines.reduce((n, l) => n + l.width, 0)+ const perPx = el.text.replace(/[\u00ad\u200b]/g, "").length / sum+ if (tail.width > widest * 0.3 || widest * perPx < 30 || el.text.endsWith(`${before}\u00a0${last}`)) return []+ const tailChars = tail.width * perPx+ if (tailChars > last.length + 1.5 || tailChars >= last.length + before.length + 1) return []+ return [{ element: el, message: `"${last}" appears alone on the last of ${lines.length} lines.`, snippet: shortSnippet(el) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/cards.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/cards.tsnew file mode 100644index 00000000..dda5da28--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/cards.ts@@ -0,0 +1,114 @@+import { ancestors, childrenOf, descendants, effectiveBackground, fontSizePx, parentOf, styleOf } from "../../../core/page"+import { blend, contrastRatio, parseColor, WHITE } from "../../../core/color"+import { parseShadow } from "../../../core/shadow"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { borders, bottom, chain, clipsX, clipsY, hasRole, length, lineHeight, painted, right, scrollsX } from "./geometry"++const shadowLayers = (el: ElementSnapshot) => parseShadow(styleOf(el, "box-shadow")).filter((s) => s.color.a >= 0.05)+export const hasBorderOrShadow = (el: ElementSnapshot): boolean =>+ borders(el).some(Boolean) || shadowLayers(el).some((s) => s.x !== 0 || s.y !== 0 || s.blur > 0 || s.spread !== 0)++export function fillDiffers(s: PageSnapshot, el: ElementSnapshot): boolean {+ if (!["none", ""].includes(styleOf(el, "background-image"))) return true+ const fill = parseColor(styleOf(el, "background-color"))+ if (!fill || fill.a === 0) return false+ const p = parentOf(s, el)+ const under = p ? effectiveBackground(s, p) : WHITE+ const shown = blend(fill, under)+ return Math.max(Math.abs(shown.r - under.r), Math.abs(shown.g - under.g), Math.abs(shown.b - under.b)) > 3+}++export function cardLike(s: PageSnapshot, el: ElementSnapshot): boolean {+ if (/^(a|button|label|input|select|textarea|img|video|canvas|picture|svg|path|span|code|pre)$/.test(el.tag)) return false+ const layers = shadowLayers(el)+ const shadow = layers.some((l) => l.x !== 0 || l.y !== 0 || l.blur > 0 || l.spread !== 0)+ const rounded = ["top-left", "top-right", "bottom-right", "bottom-left"].some((c) => Number.parseFloat(styleOf(el, `border-${c}-radius`)) > 0)+ if (!shadow && !rounded) return false+ const p = parentOf(s, el)+ const under = p ? effectiveBackground(s, p) : WHITE+ const ink = parseColor(styleOf(el, "color"))+ const canJudge = ink !== null && contrastRatio(blend(ink, under), under) >= 3+ const sides = borders(el).map((visible, i) => {+ const side = ["top", "right", "bottom", "left"][i] ?? "top"+ const color = parseColor(styleOf(el, `border-${side}-color`))+ if (!visible || !canJudge || !color) return visible+ const edge = blend(color, effectiveBackground(s, el))+ return Math.max(Math.abs(edge.r - under.r), Math.abs(edge.g - under.g), Math.abs(edge.b - under.b)) >= 8+ })+ for (const l of layers.filter((l) => !l.inset)) {+ const spread = l.spread + l.blur / 2+ for (const [i, reach] of [spread - l.y, spread + l.x, spread + l.y, spread - l.x].entries()) if (reach >= 1) sides[i] = true+ }+ return sides.filter(Boolean).length >= 3 || fillDiffers(s, el)+}++export function labelBox(s: PageSnapshot, el: ElementSnapshot): boolean {+ const radius = Number.parseFloat(styleOf(el, "border-top-left-radius"))+ if (radius >= el.rect.height / 2 - 0.5) return true+ const kids = childrenOf(s, el)+ const chrome = ["padding-top", "padding-bottom", "border-top-width", "border-bottom-width"].reduce((n, p) => n + length(el, p), 0)+ return (kids.length === 0 && el.lineRects.length === 1 && el.rect.height <= lineHeight(el) * 3) ||+ el.rect.height - chrome <= lineHeight(el) * 1.5+}++export function embeddedFrame(s: PageSnapshot, el: ElementSnapshot, outer: ElementSnapshot): boolean {+ const nodes = [...descendants(s, el)].filter((n) => painted(s, n))+ const controls = nodes.filter((n) => n.tag === "button" || hasRole(n, ["button"]) || n.tag === "input" || n.tag === "select")+ const realControls = controls.filter((n) => !/copy|more|play|pause|mute|volume|seek|fullscreen|speed/i.test(n.attributes["aria-label"] ?? n.text))+ if (realControls.length > 0) return false+ if ([...descendants(s, el)].some((n) => n.tag === "audio") && controls.length > 0 && nodes.some((n) => hasRole(n, ["slider"]))) return true+ const area = el.rect.width * el.rect.height+ if (nodes.some((n) => /^(svg|canvas|img|video|iframe|picture)$/.test(n.tag) && n.rect.width * n.rect.height >= area * 0.4) && el.text.length <= 300) return true+ if (nodes.some((n) => /^(video|audio)$/.test(n.tag) && n.rect.width >= 80) && controls.length > 0) return true+ if (!/monospace/i.test(styleOf(outer, "font-family"))) {+ const all = [el, ...nodes]+ const total = all.reduce((n, c) => n + c.ownText.replace(/\s/g, "").length, 0)+ const mono = all.filter((n) => /monospace/i.test(styleOf(n, "font-family"))).reduce((n, c) => n + c.ownText.replace(/\s/g, "").length, 0)+ if (total > 0 && mono / total >= 0.9 && all.some((n) => /^(pre|code|samp|kbd|output)$/.test(n.tag) || n.ownText.length >= el.text.length * 0.6 || /const |await |=>|[{};]/.test(n.text))) return true+ }+ return false+}++export function fieldBox(s: PageSnapshot, el: ElementSnapshot): boolean {+ const kids = childrenOf(s, el).filter((c) => painted(s, c))+ const field = (c: ElementSnapshot): boolean => /^(input|textarea|select)$/.test(c.tag) || c.attributes["contenteditable"] === "true"+ return kids.some(field) && kids.every((c) => field(c) || c.text.length <= 20 && [c, ...descendants(s, c)].some((n) => n.tag === "button"))+}++export function sharesEdges(s: PageSnapshot, el: ElementSnapshot, outer: ElementSnapshot): boolean {+ const a = el.rect+ const b = outer.rect+ const edges = [+ Math.abs(a.y - b.y - length(outer, "border-top-width")) <= 1.5,+ Math.abs(right(a) - right(b) + length(outer, "border-right-width")) <= 1.5,+ Math.abs(bottom(a) - bottom(b) + length(outer, "border-bottom-width")) <= 1.5,+ Math.abs(a.x - b.x - length(outer, "border-left-width")) <= 1.5,+ ]+ if (edges.filter(Boolean).length >= 3) return true+ if (!((edges[0] || edges[2]) && (edges[1] || edges[3]))) return false+ return [...ancestors(s, el)].some((c) => (clipsX(c) || clipsY(c)) &&+ ((Math.abs(a.width - c.rect.width) <= 1.5 && c.rect.height > a.height + 1.5) ||+ (Math.abs(a.height - c.rect.height) <= 1.5 && c.rect.width > a.width + 1.5)))+}++export function controlStrip(s: PageSnapshot, el: ElementSnapshot): boolean {+ const p = parentOf(s, el)+ if (p && scrollsX(p)) return true+ const kids = childrenOf(s, el)+ const first = kids[0]+ return first !== undefined && kids.length >= 3 && kids.every((c) =>+ (c.tag === "a" || c.tag === "button" || hasRole(c, ["link", "button", "tab"])) && c.rect.height <= 64 &&+ Math.min(bottom(c.rect), bottom(first.rect)) - Math.max(c.rect.y, first.rect.y) > Math.min(c.rect.height, first.rect.height) * 0.5)+}++export function dialogCard(s: PageSnapshot, el: ElementSnapshot): boolean {+ for (const a of chain(s, el)) {+ if (a.tag === "dialog" || hasRole(a, ["dialog", "alertdialog"])) return true+ if (a !== el && cardLike(s, a)) return false+ }+ return false+}++export const pageFrame = (s: PageSnapshot, el: ElementSnapshot): boolean =>+ el.rect.x <= 1 && el.rect.width >= s.document.clientWidth - 1 && el.rect.height >= s.document.scrollHeight * 0.75 &&+ !borders(el).some(Boolean) && !fillDiffers(s, el) && shadowLayers(el).every((l) => l.color.a <= 0.05)diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/clipping.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/clipping.tsnew file mode 100644index 00000000..4e3a47a8--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/clipping.ts@@ -0,0 +1,71 @@+import { ancestors, childrenOf, descendants, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot, Rect } from "../../../types"+import { bottom, chain, clipsX, hasRole, ident, outOfFlow, painted, right, scrollsX } from "./geometry"++export function trackCuts(s: PageSnapshot, el: ElementSnapshot, text: Rect): boolean {+ const path = [...ancestors(s, el)]+ return path.some((clip, index) => {+ if (clip.tag === "body" || !clipsX(clip) || text.x >= clip.rect.x - 1 && right(text) <= right(clip.rect) + 1) return false+ if (scrollsX(clip) && clip.scroll.scrollWidth > clip.scroll.clientWidth) return true+ return path.slice(0, index).some((track) => {+ if (["", "none"].includes(styleOf(track, "transform")) || track.scroll.scrollWidth <= clip.scroll.clientWidth + 1) return false+ const kids = childrenOf(s, track).filter((n) => n.rect.width > 0 && n.rect.height > 0)+ return kids.some((a, i) => kids.slice(i + 1).some((b) =>+ Math.min(bottom(a.rect), bottom(b.rect)) - Math.max(a.rect.y, b.rect.y) >= Math.min(a.rect.height, b.rect.height) * 0.5 &&+ (a.rect.x >= right(b.rect) - 1 || b.rect.x >= right(a.rect) - 1)))+ })+ })+}++const viewportTrack = (el: ElementSnapshot): boolean =>+ /(?:^|[\s_-])(?:carousel|comparison|compare|fisheye|flickity|marquee|owl|preview|reel|rolling|scroller|slick|slider|slideshow|splide|split|swiper|tempwrap|ticker|viewport)(?:$|[\s_-])/.test(+ `${el.attributes["class"] ?? ""} ${el.attributes["id"] ?? ""}`.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase()) ||+ /\b(?:carousel|slider)\b/i.test(el.attributes["aria-roledescription"] ?? "") ||+ /(?:^|[\s_-])demo[\s_-]+(?:area|stage|viewport)(?:$|[\s_-])/.test(ident(el))++export const shell = (s: PageSnapshot, el: ElementSnapshot): boolean =>+ el.tag === "body" || el.rect.x <= 1 && el.rect.y <= 1 && el.rect.width >= s.viewport.width * 0.98 && el.rect.height >= s.document.scrollHeight * 0.98++function clippedAxes(el: ElementSnapshot): readonly [boolean, boolean] | null {+ if (["contents", "none"].includes(styleOf(el, "display")) || el.rect.width <= 0 || el.rect.height <= 0 ||+ scrollsX(el) || /^(auto|scroll)$/.test(styleOf(el, "overflow-y"))) return null+ const x = /^(hidden|clip)$/.test(styleOf(el, "overflow-x"))+ const y = /^(hidden|clip)$/.test(styleOf(el, "overflow-y"))+ return x || y ? [x, y] : null+}++function traps(s: PageSnapshot, clip: ElementSnapshot, el: ElementSnapshot): boolean {+ if (el.modal) return false+ const axes = clippedAxes(clip)+ if (!axes) return false+ const parents = [...ancestors(s, el)]+ const between = parents.slice(0, parents.indexOf(clip) + 1)+ if (styleOf(el, "position") === "fixed" && !between.some((n) =>+ !["", "none"].includes(styleOf(n, "transform")) || /paint|layout|strict|content/.test(styleOf(n, "contain")) ||+ !["", "none"].includes(styleOf(n, "filter")))) return false+ if (styleOf(el, "position") === "absolute") {+ const cb = parents.find((n) => styleOf(n, "position") !== "static" || !["", "none"].includes(styleOf(n, "transform")))+ if (cb && !between.includes(cb)) return false+ }+ return axes[0] && (el.rect.x < clip.rect.x - 2 || right(el.rect) > right(clip.rect) + 2) ||+ axes[1] && (el.rect.y < clip.rect.y - 2 || bottom(el.rect) > bottom(clip.rect) + 2)+}++const popover = (el: ElementSnapshot): boolean =>+ hasRole(el, ["menu", "menubar", "listbox", "tooltip", "dialog"]) ||+ el.tag === "dialog" && el.attributes["open"] !== undefined || el.attributes["popover"] !== undefined++export function clippedChild(s: PageSnapshot, clip: ElementSnapshot): ElementSnapshot | undefined {+ if (!clippedAxes(clip) || shell(s, clip) || viewportTrack(clip) || childrenOf(s, clip).some(viewportTrack) || !painted(s, clip)) return undefined+ return [...descendants(s, clip)].find((el) => {+ if (chain(s, el).some((n) => n.attributes["aria-hidden"] === "true") || hasRole(el, ["none", "presentation"]) ||+ /^(img|svg|canvas|video)$/.test(el.tag)) return false+ if (!outOfFlow(el) || viewportTrack(el) || !(popover(el) || [...descendants(s, el)].some(popover))) return false+ if (!traps(s, clip, el)) return false+ const parents = [...ancestors(s, el)]+ const between = parents.slice(0, parents.indexOf(clip))+ if (between.some((n) => traps(s, n, el) || scrollsX(n) || /^(auto|scroll)$/.test(styleOf(n, "overflow-y")))) return false+ return chain(s, el).every((n) => styleOf(n, "display") !== "none" && styleOf(n, "visibility") !== "hidden" &&+ !(Number.parseFloat(styleOf(n, "opacity")) <= 0.01))+ })+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/declared-mockups.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/declared-mockups.tsnew file mode 100644index 00000000..78f766ec--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/declared-mockups.ts@@ -0,0 +1,46 @@+import { childrenOf, descendants, parentOf, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { chain, hasRole, ident } from "./geometry"++const hidden = (el: ElementSnapshot): boolean => el.attributes["inert"] !== undefined || el.attributes["aria-hidden"] === "true"+const shown = (s: PageSnapshot, el: ElementSnapshot): boolean =>+ el.rect.width > 0 && el.rect.height > 0 && styleOf(el, "visibility") !== "hidden" && chain(s, el).every((n) => styleOf(n, "display") !== "none")+const squash = (text: string): string => text.replace(/\s/g, "")+const parts = (el: ElementSnapshot): string[] =>+ `${el.attributes["class"] ?? ""} ${el.attributes["id"] ?? ""}`.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[\s_-]+/)++export function declaredMockups(s: PageSnapshot): ReadonlySet<ElementSnapshot> {+ const pageChars = s.elements.filter((n) => shown(s, n)).reduce((sum, n) => sum + squash(n.ownText).length, 0)+ const modals = s.elements.filter((n) => !hidden(n) && shown(s, n) &&+ (n.attributes["aria-modal"] === "true" || hasRole(n, ["dialog", "alertdialog"]) || n.tag === "dialog" && n.attributes["open"] !== undefined))+ return new Set(s.elements.filter((root) => {+ if (!hidden(root) || root.rect.width < 120 || root.rect.height < 80 ||+ /^(html|body|main|header|footer|nav|aside|section|article|form|dialog|li|tr|td|th|tbody|thead|table|details|summary)$/.test(root.tag)) return false+ if ((root.attributes["role"] ?? "").split(/\s+/).some((r) => r !== "" && !["presentation", "none", "img", "figure", "group"].includes(r))) return false+ if (root.attributes["aria-modal"] !== undefined || root.attributes["data-aria-hidden"] !== undefined || /^(fixed|sticky)$/.test(styleOf(root, "position"))) return false+ if (parts(root).some((p) => /^(clone|clones|cloned|copy|duplicate|dup|carousel|embla|flicking|glide|keen|slick|slide|slider|slides|splide|swiper|marquee|ticker|menu|submenu|dropdown|popup|popover|modal|drawer|dialog|tooltip|toast|offcanvas|overlay|nav|navbar|navigation|panel|tab|tabpanel|accordion|collapse|collapsible|intro|splash|loader|preloader|loading|banner|cookie|cookies|consent|sidebar|sidenav|toc)$/.test(p))) return false+ const path = chain(s, root).slice(1)+ if (path.some((n) => /^(h[1-6]|p|a|button|label|summary|legend|caption|figcaption|blockquote|q)$/.test(n.tag))) return false+ const nodes = [root, ...descendants(s, root)]+ if (nodes.length > 3000 || nodes.some((n) => n.tag === "h1")) return false+ const runs = nodes.filter((n) => shown(s, n) && squash(n.ownText) !== "")+ if (runs.length < 3 || runs.reduce((sum, n) => sum + squash(n.ownText).length, 0) * 2 >= pageChars) return false+ const fields = nodes.filter((n) => /^(input|select|textarea)$/.test(n.tag) && !(n.tag === "input" && n.attributes["type"] === "hidden"))+ const links = runs.filter((n) => chain(s, n).some((a) => a.tag === "a" && (a.attributes["href"] ?? "").trim() !== ""))+ if (fields.length >= 2 || fields.length > 0 && nodes.some((n) => n.tag === "label") || links.length * 2 >= runs.length) return false+ if (modals.some((n) => !nodes.includes(n) && !path.includes(n))) return false+ const text = squash(root.text)+ if (text !== "" && path.some((n) => squash(n.attributes["aria-label"] ?? "").includes(text))) return false+ const p = parentOf(s, root)+ return !p || !childrenOf(s, p).some((peer) => {+ if (peer === root) return false+ const classes = (root.attributes["class"] ?? "").split(/\s+/).filter(Boolean)+ const peerClasses = (peer.attributes["class"] ?? "").split(/\s+/).filter(Boolean)+ const sameShape = peer.tag === root.tag && (classes.length === 0) === (peerClasses.length === 0) && classes.every((c) => peerClasses.includes(c))+ if (shown(s, peer) && !hidden(peer) && sameShape || text !== "" && squash(peer.text) === text) return true+ const alternative = peer.rect.width <= 1 || peer.rect.height <= 1 || /sr-only|visually-?hidden|screen-?reader|a11y-hidden|hidden-visually/.test(ident(peer))+ return shown(s, peer) && alternative && peer.text.trim() !== "" &&+ !/\b(demo|demonstration|illustrat\w*|interface|screen ?shots?|mock-?ups?|graphic|animation|animated|preview|image|video|visual|diagram|depict\w*|shows|showing|displayed)\b/i.test(peer.text)+ })+ }))+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/geometry.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/geometry.tsnew file mode 100644index 00000000..be403be8--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/geometry.ts@@ -0,0 +1,73 @@+import { ancestors, childrenOf, descendants, fontSizePx, isRendered, px, styleOf } from "../../../core/page"+import { parseColor } from "../../../core/color"+import type { ElementSnapshot, PageSnapshot, Rect } from "../../../types"++export const right = (r: Rect): number => r.x + r.width+export const bottom = (r: Rect): number => r.y + r.height+export const length = (el: ElementSnapshot, prop: string): number => px(styleOf(el, prop)) ?? 0+export const chain = (s: PageSnapshot, el: ElementSnapshot): readonly ElementSnapshot[] => [el, ...ancestors(s, el)]+export const scrollsX = (el: ElementSnapshot): boolean => /^(auto|scroll)$/.test(styleOf(el, "overflow-x"))+export const clipsX = (el: ElementSnapshot): boolean => /^(hidden|clip|auto|scroll)$/.test(styleOf(el, "overflow-x"))+export const clipsY = (el: ElementSnapshot): boolean => /^(hidden|clip|auto|scroll)$/.test(styleOf(el, "overflow-y"))+export function clipRect(el: ElementSnapshot): Rect {+ const margin = Math.max(0, styleOf(el, "overflow-clip-margin").split(/\s+/).map(Number.parseFloat).find(Number.isFinite) ?? 0)+ const layoutWidth = el.scroll.clientWidth + length(el, "border-left-width") + length(el, "border-right-width")+ const layoutHeight = el.scroll.clientHeight + length(el, "border-top-width") + length(el, "border-bottom-width")+ const scaleX = layoutWidth > 0 && Math.abs(el.rect.width - layoutWidth) > 1 ? el.rect.width / layoutWidth : 1+ const scaleY = layoutHeight > 0 && Math.abs(el.rect.height - layoutHeight) > 1 ? el.rect.height / layoutHeight : 1+ const x = styleOf(el, "overflow-x") === "clip" ? margin * scaleX : 0+ const y = styleOf(el, "overflow-y") === "clip" ? margin * scaleY : 0+ return { x: el.rect.x - x, y: el.rect.y - y, width: el.rect.width + 2 * x, height: el.rect.height + 2 * y }+}+export const outOfFlow = (el: ElementSnapshot): boolean => /^(absolute|fixed)$/.test(styleOf(el, "position"))+export const hasRole = (el: ElementSnapshot, roles: readonly string[]): boolean =>+ (el.attributes["role"] ?? "").toLowerCase().split(/\s+/).some((r) => roles.includes(r))+export const ident = (el: ElementSnapshot): string => `${el.attributes["class"] ?? ""} ${el.attributes["id"] ?? ""}`.toLowerCase()+export const alpha = (el: ElementSnapshot, prop: string): number => parseColor(styleOf(el, prop))?.a ?? 0+export const borders = (el: ElementSnapshot): readonly boolean[] =>+ ["top", "right", "bottom", "left"].map((side) =>+ length(el, `border-${side}-width`) >= 0.5 &&+ !/^(none|hidden)$/.test(styleOf(el, `border-${side}-style`)) &&+ alpha(el, `border-${side}-color`) >= 0.05)+const screenReaderOnly = (el: ElementSnapshot): boolean =>+ styleOf(el, "clip-path") === "inset(50%)" ||+ (el.rect.width <= 1 && el.rect.height <= 1 && (clipsX(el) || clipsY(el)))++export function painted(s: PageSnapshot, el: ElementSnapshot): boolean {+ if (!isRendered(s, el) || screenReaderOnly(el)) return false+ for (const a of chain(s, el)) {+ if (styleOf(a, "display") === "none" || Number.parseFloat(styleOf(a, "opacity")) <= 0.01) return false+ if (a.tag === "details" && a.attributes["open"] === undefined) {+ const summary = childrenOf(s, a).find((c) => c.tag === "summary")+ if (!summary || !chain(s, el).includes(summary)) return false+ }+ const clip = clipRect(a)+ if (a !== el && ((clipsX(a) && (right(el.rect) <= clip.x || el.rect.x >= right(clip))) ||+ (clipsY(a) && (bottom(el.rect) <= clip.y || el.rect.y >= bottom(clip))))) return false+ }+ return true+}++export function textLines(s: PageSnapshot, el: ElementSnapshot): readonly Rect[] {+ const nodes = [el, ...descendants(s, el)].filter((n) => n === el || styleOf(n, "display") === "inline")+ const rects = nodes.flatMap((n) => n.lineRects).filter((r) => r.width > 0 && r.height > 0).sort((a, b) => a.y - b.y || a.x - b.x)+ const lines: Rect[] = []+ for (const r of rects) {+ const i = lines.findIndex((l) => Math.min(bottom(l), bottom(r)) - Math.max(l.y, r.y) > Math.min(l.height, r.height) / 2)+ const l = lines[i]+ if (l) lines[i] = { x: Math.min(l.x, r.x), y: Math.min(l.y, r.y), width: Math.max(right(l), right(r)) - Math.min(l.x, r.x), height: Math.max(bottom(l), bottom(r)) - Math.min(l.y, r.y) }+ else lines.push(r)+ }+ return lines+}++export function bounds(rects: readonly Rect[]): Rect | null {+ if (rects.length === 0) return null+ const x = Math.min(...rects.map((r) => r.x))+ const y = Math.min(...rects.map((r) => r.y))+ return { x, y, width: Math.max(...rects.map(right)) - x, height: Math.max(...rects.map(bottom)) - y }+}++export const lineHeight = (el: ElementSnapshot): number => px(styleOf(el, "line-height")) ?? fontSizePx(el) * 1.2+export const intersects = (a: Rect, b: Rect): boolean =>+ Math.min(right(a), right(b)) > Math.max(a.x, b.x) && Math.min(bottom(a), bottom(b)) > Math.max(a.y, b.y)diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/hidden-interface.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/hidden-interface.tsnew file mode 100644index 00000000..28beecd7--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/hidden-interface.ts@@ -0,0 +1,35 @@+import { descendants, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { chain } from "./geometry"++export const classWords = (el: ElementSnapshot): readonly string[] =>+ (el.attributes["class"] ?? "").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)++export function closedClass(el: ElementSnapshot): boolean {+ return (el.attributes["class"] ?? "").split(/\s+/).some((token) => {+ const words = classWords({ ...el, attributes: { class: token } })+ const pair = (a: string, b: string): boolean => words.some((word, i) => word === a && words[i + 1] === b)+ return words.some((word) => ["offcanvas", "drawer", "megamenu", "submenu", "dropdown", "flyout", "modal", "tabpanel", "tabpane"].includes(word)) ||+ pair("off", "canvas") || pair("mega", "menu") || pair("sub", "menu") ||+ words.some((word) => ["content", "panel", "pane", "body"].includes(word)) && words.some((word) => ["tab", "tabs", "accordion"].includes(word))+ })+}++export function unstartedSlider(s: PageSnapshot, el: ElementSnapshot): boolean {+ const slider = chain(s, el).slice(0, 7).find((n) => (n.attributes["class"] ?? "").split(/\s+/).some((token) => {+ const words = classWords({ ...n, attributes: { class: token } })+ return words.some((word) => ["slider", "carousel", "swiper", "slick", "splide", "glide", "flickity", "slideshow", "revslider"].includes(word)) &&+ !words.some((word) => ["slide", "item", "cell", "card", "pane", "caption"].includes(word))+ }))+ if (!slider) return false+ return ![slider, ...descendants(s, slider)].some((n) => {+ if (/^(hidden|collapse)$/.test(styleOf(n, "visibility"))) return false+ const path = chain(s, n)+ const upto = path.slice(0, path.indexOf(slider) + 1)+ const shows = (aria: boolean): boolean => upto.every((a) => styleOf(a, "display") !== "none" &&+ Number.parseFloat(styleOf(a, "opacity")) > 0.02 && !(aria && a.attributes["aria-hidden"] === "true"))+ if (n.ownText.trim() !== "" && shows(true)) return true+ return n !== slider && n.rect.width >= Math.max(1, slider.rect.width * 0.5) && n.rect.height >= 1 &&+ (/^(img|picture|video|canvas|svg)$/.test(n.tag) || styleOf(n, "background-image").includes("url(")) && shows(false)+ })+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/layout-cases.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/layout-cases.tsnew file mode 100644index 00000000..7842cbf3--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/layout-cases.ts@@ -0,0 +1,23 @@+import { lintSnapshot } from "../../../lint"+import type { PageRule } from "../../../rule"+import type { PageSnapshot } from "../../../types"+import { buildSnapshot, type NodeSpec } from "../../../testing/build-snapshot"++export const marked = (rule: PageRule, nodes: readonly NodeSpec[], options: Parameters<typeof buildSnapshot>[1] = {}): readonly string[] =>+ selectors(rule, buildSnapshot(nodes, options))++export const selectors = (rule: PageRule, snapshot: PageSnapshot): readonly string[] =>+ lintSnapshot(snapshot, { rules: [rule] }).map((f) => f.location.kind === "element" ? f.location.selector : "page")++export const border = {+ "border-top-width": "1px", "border-right-width": "1px", "border-bottom-width": "1px", "border-left-width": "1px",+ "border-top-style": "solid", "border-right-style": "solid", "border-bottom-style": "solid", "border-left-style": "solid",+ "border-top-color": "#333", "border-right-color": "#333", "border-bottom-color": "#333", "border-left-color": "#333",+}++export const rounded = {+ "border-top-left-radius": "12px", "border-top-right-radius": "12px", "border-bottom-right-radius": "12px", "border-bottom-left-radius": "12px",+}++export const lines = (widths: readonly number[], x = 24, y = 24, height = 20) =>+ widths.map((width, i) => ({ x, y: y + i * 24, width, height }))diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/line-breaks.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/line-breaks.tsnew file mode 100644index 00000000..453a2941--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/line-breaks.ts@@ -0,0 +1,32 @@+import { descendants, fontSizePx, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot, Rect } from "../../../types"+import { bottom, chain, length, painted, right, textLines } from "./geometry"++function authoredBreak(s: PageSnapshot, el: ElementSnapshot): boolean {+ if (/^(pre|pre-wrap|pre-line|break-spaces)$/.test(styleOf(el, "white-space"))) return true+ return [...descendants(s, el)].some((n) => n.tag === "br" || !["inline", "contents", "none"].includes(styleOf(n, "display")))+}++export function measuredLines(s: PageSnapshot, el: ElementSnapshot): readonly Rect[] {+ if (!painted(s, el) || authoredBreak(s, el)) return []+ const lines = textLines(s, el)+ const widest = [...lines].sort((a, b) => b.width - a.width)[0]+ if (!widest || lines.some((r) => right(r) <= widest.x || r.x >= right(widest))) return []+ for (const c of chain(s, el).slice(0, 5)) {+ if (/^(hidden|clip)$/.test(styleOf(c, "overflow-y")) &&+ lines.some((r) => r.y + r.height / 2 > bottom(c.rect) - length(c, "border-bottom-width"))) return []+ }+ return lines+}++export const wrapIs = (el: ElementSnapshot, value: string): boolean =>+ (styleOf(el, "text-wrap-style") || styleOf(el, "text-wrap")).split(/\s+/).includes(value)++export const wordsOf = (el: ElementSnapshot): readonly string[] =>+ el.text.replace(/[\u00ad\u200b]/g, "").trim().split(/\s+/).filter(Boolean)++export function oneFace(s: PageSnapshot, el: ElementSnapshot): boolean {+ return [...descendants(s, el)].every((n) =>+ !["img", "svg", "canvas", "video", "input"].includes(n.tag) &&+ (styleOf(n, "font-family") === styleOf(el, "font-family") && fontSizePx(n) === fontSizePx(el) || n.ownText === ""))+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/motion.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/motion.tsnew file mode 100644index 00000000..7a323b35--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/motion.ts@@ -0,0 +1,77 @@+import { childrenOf, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { keyframes } from "../../decoration/support/keyframes"+import { bottom, chain, right } from "./geometry"++const list = (el: ElementSnapshot, prop: string): readonly string[] => styleOf(el, prop).split(",").map((v) => v.trim())+const at = (values: readonly string[], index: number): string => values[index % values.length] ?? ""++function tracedToEnd(s: PageSnapshot, el: ElementSnapshot, prop: string): boolean {+ const counts = list(el, "animation-iteration-count")+ const states = list(el, "animation-play-state")+ const timelines = list(el, "animation-timeline")+ let setting = false+ for (const [i, name] of list(el, "animation-name").entries()) {+ if (name === "" || name === "none") continue+ const frames = keyframes(s, name)+ if (!frames) return false+ if (!frames.some((f) => f[prop] !== undefined)) continue+ setting = true+ const count = Number.parseFloat(at(counts, i))+ if (!Number.isFinite(count) || count <= 0 || at(states, i) === "paused" || !["", "auto"].includes(at(timelines, i))) return false+ }+ const durations = list(el, "transition-duration")+ return setting || list(el, "transition-property").some((p, i) => p === prop && Number.parseFloat(at(durations, i)) > 0)+}++export function openingWidth(s: PageSnapshot, el: ElementSnapshot): boolean {+ for (const node of chain(s, el).slice(0, 64)) {+ if (node.tag === "body" || node.tag === "html") return false+ if (node.motion.some((p) => /^(?:(?:min|max)-)?(?:width|inline-size)$/.test(p) && tracedToEnd(s, node, p))) return true+ }+ return false+}++function onlyScales(value: string): boolean {+ let rest = value.trim().replace(/\s*!important\s*$/, "")+ if (rest.toLowerCase() === "none") return true+ let found = false+ while (rest !== "") {+ const match = /^scale(?:[XYZ]|3d)?\(([^)]*)\)\s*/i.exec(rest)+ if (!match || (match[1] ?? "").split(/[\s,]+/).filter(Boolean).some((n) => !Number.isFinite(Number(n)))) return false+ found = true+ rest = rest.slice(match[0].length)+ }+ return found+}++function endlessTranslation(s: PageSnapshot, el: ElementSnapshot): boolean {+ if (!el.motion.some((p) => p === "transform" || p === "translate" || p === "-webkit-transform")) return false+ const counts = list(el, "animation-iteration-count")+ const states = list(el, "animation-play-state")+ return list(el, "animation-name").some((name, i) => {+ if (name === "" || name === "none" || at(counts, i) !== "infinite" || at(states, i) === "paused") return false+ const frames = keyframes(s, name)+ return frames === null || frames.some((f) => Object.entries(f).some(([prop, value]) =>+ prop.replace(/^-webkit-/, "") === "translate" || prop.replace(/^-webkit-/, "") === "transform" && !onlyScales(value)))+ })+}++export function ridesRunningTrack(s: PageSnapshot, el: ElementSnapshot): boolean {+ const parents = chain(s, el).slice(1)+ for (const [index, clip] of parents.entries()) {+ if (clip.tag === "body" || clip.tag === "html") break+ if (!/^(hidden|clip)$/.test(styleOf(clip, "overflow-x")) || clip.scroll.clientWidth <= 0) continue+ if (parents.slice(0, index).some((track) => {+ if (track.scroll.scrollWidth <= clip.scroll.clientWidth + 1 || !["transform", "translate"].some((p) =>+ !["", "none"].includes(styleOf(track, p))) || !endlessTranslation(s, track)) return false+ const kids = childrenOf(s, track).filter((n) => n.rect.width >= 1 && n.rect.height >= 1)+ return kids.some((a, i) => {+ const b = kids[i + 1]+ return b !== undefined && (b.rect.x >= right(a.rect) - 1 || right(b.rect) <= a.rect.x + 1) &&+ Math.min(bottom(a.rect), bottom(b.rect)) - Math.max(a.rect.y, b.rect.y) > 0+ })+ })) return true+ }+ return false+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/padding.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/padding.tsnew file mode 100644index 00000000..3f23f27e--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/padding.ts@@ -0,0 +1,93 @@+import { ancestors, childrenOf, descendants, fontSizePx, parentOf, styleOf } from "../../../core/page"+import { parseColor } from "../../../core/color"+import type { ElementSnapshot, PageSnapshot, Rect } from "../../../types"+import { fillDiffers } from "./cards"+import { alpha, bottom, chain, clipsX, clipsY, length, lineHeight, painted, right } from "./geometry"++const same = (a: string, b: string): boolean => {+ const x = parseColor(a)+ const y = parseColor(b)+ return x !== null && y !== null && Math.max(Math.abs(x.r - y.r), Math.abs(x.g - y.g), Math.abs(x.b - y.b), Math.abs(x.a - y.a) * 255) < 8+}++export function paddingFill(s: PageSnapshot, el: ElementSnapshot): boolean {+ if (alpha(el, "background-color") === 0 || !fillDiffers(s, el)) return false+ const fill = styleOf(el, "background-color")+ for (const p of ancestors(s, el)) {+ const image = styleOf(p, "background-image")+ const lead = /^linear-gradient\(to (right|left|bottom|top), rgba\(0, 0, 0, 0\) ([\d.]+)(px|%), (rgba?\([^)]*\)) ([\d.]+)(px|%)\)$/.exec(image)+ if (lead && same(fill, lead[4] ?? "") && lead[2] === lead[5] && lead[3] === lead[6]) {+ const vertical = lead[1] === "top" || lead[1] === "bottom"+ const span = vertical ? p.rect.height : p.rect.width+ const stop = Number(lead[2]) * (lead[3] === "%" ? span / 100 : 1)+ if (lead[1] === "right" && el.rect.x >= p.rect.x + stop - 0.5 ||+ lead[1] === "left" && right(el.rect) <= right(p.rect) - stop + 0.5 ||+ lead[1] === "bottom" && el.rect.y >= p.rect.y + stop - 0.5 ||+ lead[1] === "top" && bottom(el.rect) <= bottom(p.rect) - stop + 0.5) return false+ }+ if (alpha(p, "background-color") > 0) break+ }+ return true+}++export function paddingBackdrop(s: PageSnapshot, el: ElementSnapshot): boolean {+ for (const node of chain(s, el).slice(0, 12)) {+ const p = parentOf(s, node)+ if (!p) break+ for (const sibling of childrenOf(s, p).slice(0, childrenOf(s, p).indexOf(node)).reverse()) {+ const r = sibling.rect+ if (styleOf(sibling, "display") === "none" || r.x > el.rect.x + 1 || r.y > el.rect.y + 1 ||+ right(r) < right(el.rect) - 1 || bottom(r) < bottom(el.rect) - 1) continue+ if (alpha(sibling, "background-color") > 0) return same(styleOf(el, "background-color"), styleOf(sibling, "background-color"))+ if ([sibling, ...descendants(s, sibling)].some((n) => /^(img|video)$/.test(n.tag) && painted(s, n) &&+ n.rect.x <= el.rect.x + 1 && n.rect.y <= el.rect.y + 1 && right(n.rect) >= right(el.rect) - 1 && bottom(n.rect) >= bottom(el.rect) - 1)) return true+ }+ if (alpha(p, "background-color") > 0) break+ }+ return false+}++export function continuedFill(s: PageSnapshot, el: ElementSnapshot, side: number): boolean {+ const r = el.rect+ const reaches = (b: Rect): boolean => Math.abs([bottom(b) - r.y, b.x - right(r), b.y - bottom(r), right(b) - r.x][side] ?? Infinity) <= 1.5+ const along = (b: Rect): boolean => side % 2 === 0+ ? Math.min(right(r), right(b)) - Math.max(r.x, b.x) >= r.width * 0.9+ : Math.min(bottom(r), bottom(b)) - Math.max(r.y, b.y) >= r.height * 0.9+ const search = (node: ElementSnapshot, depth: number): boolean => {+ if (!reaches(node.rect) || !painted(s, node)) return false+ if (along(node.rect) && same(styleOf(el, "background-color"), styleOf(node, "background-color"))) return true+ return depth < 6 && childrenOf(s, node).some((n) => search(n, depth + 1))+ }+ for (const node of chain(s, el).slice(0, 5)) {+ const p = parentOf(s, node)+ if (p && childrenOf(s, p).some((n) => n !== node && search(n, 0))) return true+ }+ return false+}++export function glyphBand(el: ElementSnapshot, r: Rect, scale = 1): Rect {+ const size = fontSizePx(el) * scale+ const pitch = lineHeight(el) * scale+ const count = Math.max(1, Math.round((r.height - size) / pitch) + 1)+ const inset = Math.max(0, (r.height - (count - 1) * pitch - size) / 2)+ return { ...r, y: r.y + inset, height: r.height - inset * 2 }+}++export const paddingScale = (el: ElementSnapshot): number => {+ const layout = el.scroll.clientWidth + length(el, "border-left-width") + length(el, "border-right-width")+ const scale = el.rect.width / layout+ return scale > 0.05 && scale < 0.95 ? scale : 1+}++export function uncut(s: PageSnapshot, node: ElementSnapshot, wrapper: ElementSnapshot, r: Rect, side: number): boolean {+ for (const p of chain(s, node)) {+ if (styleOf(p, "display") !== "inline") {+ if (side === 1 && clipsX(p) && right(r) > right(p.rect) - length(p, "border-right-width") + 0.5 ||+ side === 3 && clipsX(p) && r.x < p.rect.x + length(p, "border-left-width") - 0.5 ||+ side === 0 && clipsY(p) && r.y < p.rect.y + length(p, "border-top-width") - 0.5 ||+ side === 2 && clipsY(p) && bottom(r) > bottom(p.rect) - length(p, "border-bottom-width") + 0.5) return false+ }+ if (p === wrapper) break+ }+ return true+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/rhythm.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/rhythm.tsnew file mode 100644index 00000000..c61ab2a3--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/support/rhythm.ts@@ -0,0 +1,161 @@+import { childrenOf, descendants, fontSizePx, isHeading, parentOf, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { cardLike, fillDiffers } from "./cards"+import { alpha, borders, bottom, chain, length, outOfFlow, painted, right, textLines } from "./geometry"++export const paintsEdge = (el: ElementSnapshot, side: string): boolean =>+ alpha(el, "background-color") > 0.05 || length(el, `border-${side}-width`) > 0 ||+ !["", "none"].includes(styleOf(el, "box-shadow")) ||+ !styleOf(el, "background-clip").includes("text") && !styleOf(el, "-webkit-background-clip").includes("text") &&+ !["", "none"].includes(styleOf(el, "background-image")) &&+ (styleOf(el, "background-size") === "cover" || styleOf(el, "background-image").includes("gradient(") &&+ ["auto", "auto auto", "100% 100%"].includes(styleOf(el, "background-size")))++const separates = (s: PageSnapshot, el: ElementSnapshot): boolean =>+ borders(el).some(Boolean) || fillDiffers(s, el) || !["", "none"].includes(styleOf(el, "box-shadow"))+const spacer = (s: PageSnapshot, el: ElementSnapshot): boolean =>+ el.text === "" && !separates(s, el) &&+ !(alpha(el, "background-color") > 0.05 && chain(s, el).slice(1).some((n) =>+ !["", "none"].includes(styleOf(n, "background-image")) && paintsEdge(n, "top"))) &&+ ![el, ...descendants(s, el)].some((n) =>+ /^(img|video|canvas|iframe|svg|input|button)$/.test(n.tag) || n !== el && separates(s, n))++const flow = (s: PageSnapshot, el: ElementSnapshot): boolean =>+ painted(s, el) && !outOfFlow(el) && styleOf(el, "position") !== "sticky" &&+ Number.parseFloat(styleOf(el, "opacity")) > 0.05 && !["inline", "none"].includes(styleOf(el, "display"))++function flowBoxes(s: PageSnapshot, el: ElementSnapshot, heading: ElementSnapshot): readonly ElementSnapshot[] {+ if (styleOf(el, "display") === "contents") return childrenOf(s, el).flatMap((c) => flowBoxes(s, c, heading))+ if (!flow(s, el) || spacer(s, el)) return []+ if (Math.min(right(el.rect), right(heading.rect)) - Math.max(el.rect.x, heading.rect.x) < 8) return []+ return [el]+}++function repeats(s: PageSnapshot, row: ElementSnapshot, heading: ElementSnapshot): boolean {+ const p = parentOf(s, row)+ if (!p) return false+ const kids = childrenOf(s, p)+ const i = kids.indexOf(row)+ const laysOut = (n: ElementSnapshot): boolean =>+ styleOf(n, "display") !== "none" && !outOfFlow(n) && n.rect.width >= 1 && n.rect.height >= 1 && !spacer(s, n)+ const neighbours = [kids.slice(0, i).reverse().find(laysOut), kids.slice(i + 1).find(laysOut)]+ const path = (n: ElementSnapshot, stop: ElementSnapshot): readonly string[] => {+ const steps: string[] = []+ let current = n+ while (current !== stop) {+ const parent = parentOf(s, current)+ if (!parent) return []+ steps.unshift(`${current.tag}:${childrenOf(s, parent).indexOf(current)}`)+ current = parent+ }+ return steps+ }+ const shape = (root: ElementSnapshot): string[] => {+ const tags: string[] = []+ let budget = 24+ const walk = (node: ElementSnapshot, depth: number): void => {+ tags.push(node.tag)+ if (depth === 0) return+ for (const child of childrenOf(s, node).filter((n) => styleOf(n, "display") !== "none" && !outOfFlow(n) && n.rect.width >= 1 && n.rect.height >= 1)) {+ if (budget-- <= 0) return+ walk(child, depth - 1)+ }+ }+ walk(root, 3)+ return tags+ }+ const ownPath = path(heading, row).join("/")+ const ownShape = shape(row)+ return neighbours.some((n) => {+ if (!n || n.tag !== row.tag || ![...descendants(s, n)].some((h) => h.tag === heading.tag && path(h, n).join("/") === ownPath)) return false+ const other = shape(n)+ const total = ownShape.length + other.length+ let shared = 0+ for (const tag of ownShape) {+ const at = other.indexOf(tag)+ if (at >= 0) { shared++; other.splice(at, 1) }+ }+ return shared * 2 / total >= 0.7+ })+}++export function neighbour(s: PageSnapshot, heading: ElementSnapshot, before: boolean, start = heading): ElementSnapshot | null {+ let cursor = start+ for (let depth = 0; depth < 20; depth++) {+ const parent = parentOf(s, cursor)+ if (!parent) return null+ const siblings = childrenOf(s, parent)+ if (!before && cursor !== heading && repeats(s, cursor, heading)) return null+ const i = siblings.indexOf(cursor)+ const choices = (before ? siblings.slice(0, i) : siblings.slice(i + 1))+ .flatMap((n) => flowBoxes(s, n, heading))+ .filter((n) => before ? bottom(n.rect) <= start.rect.y + 2 : n.rect.y >= bottom(heading.rect) - 2)+ .sort((a, b) => before ? bottom(b.rect) - bottom(a.rect) : a.rect.y - b.rect.y)+ const found = choices[0]+ if (found) return found+ if (parent.tag === "body" || separates(s, parent) || !before && (parent.tag === "main" || parent.attributes["role"] === "main")) return null+ cursor = parent+ }+ return null+}++export function headingCluster(s: PageSnapshot, heading: ElementSnapshot, below: number): ElementSnapshot {+ let top = heading+ for (let count = 0; count < 3; count++) {+ const previous = neighbour(s, heading, true, top)+ if (!previous || isHeading(previous) || previous.text.length === 0 || previous.text.length > 80 || previous.rect.height > 60) break+ const gap = top.rect.y - bottom(previous.rect)+ const words = [previous, ...descendants(s, previous)].filter((n) => n.ownText !== "")+ const word = words[0] ?? previous+ const p = parentOf(s, previous)+ const opens = p !== null && childrenOf(s, p).filter((n) => styleOf(n, "display") !== "none" && n.rect.width >= 1 && n.rect.height >= 1)[0] === previous+ const lines = words.flatMap((n) => textLines(s, n))+ const label = fontSizePx(word) <= fontSizePx(heading) && (fontSizePx(word) <= 14 || styleOf(word, "text-transform") === "uppercase" ||+ length(word, "letter-spacing") >= fontSizePx(word) * 0.05 || opens &&+ (styleOf(word, "font-style") === "italic" || Number.parseFloat(styleOf(word, "font-weight")) < 400 ||+ styleOf(word, "color") !== styleOf(heading, "color")))+ const subtitle = opens && gap <= 2 && fontSizePx(word) <= fontSizePx(heading) && lines.length <= 1+ if (gap < 0 || gap >= 28 && !(opens && gap < below && gap <= 64) || !(label || subtitle) || lines.length > 1) break+ top = previous+ }+ return top+}++export function rhythmExempt(s: PageSnapshot, el: ElementSnapshot): boolean {+ if (!flow(s, el) || el.text.length < 3 || !["h2", "h3", "h4"].includes(el.tag) || paintsEdge(el, "top")) return true+ return chain(s, el).some((a) => ["blockquote", "q", "nav", "footer"].includes(a.tag) ||+ a !== el && cardLike(s, a) && a.rect.height < 200)+}++export function closesInProse(s: PageSnapshot, el: ElementSnapshot, heading: ElementSnapshot, textSize: number): boolean {+ const blocks = [el, ...descendants(s, el)].filter((n) => ["p", "li", "dd", "div"].includes(n.tag) && n.ownText !== "" && flow(s, n))+ const last = blocks.sort((a, b) => bottom(b.rect) - bottom(a.rect))[0]+ return last !== undefined && last.text.length >= 80 && textLines(s, last).length >= 2 &&+ last.rect.width >= heading.rect.width * 0.5 && fontSizePx(last) < fontSizePx(heading) && fontSizePx(last) <= textSize * 1.25+}++export function separatesBelow(s: PageSnapshot, el: ElementSnapshot): boolean {+ if (el.tag === "hr" || el.rect.height <= 4) return true+ let node: ElementSnapshot | undefined = el+ let framed = false+ for (let depth = 0; depth < 8 && node; depth++) {+ const current = node+ framed ||= ["top", "left", "right"].some((side) => length(current, `border-${side}-width`) > 0)+ if (!framed && length(node, "border-bottom-width") > 0 && node.rect.width >= el.rect.width * 0.9 ||+ /^(img|picture|video|canvas|svg|iframe)$/.test(node.tag) && node.rect.width >= el.rect.width * 0.5 || isHeading(node)) return true+ node = [...childrenOf(s, node)].reverse().find((n) => styleOf(n, "display") !== "none" &&+ n.rect.width >= 1 && n.rect.height >= 1 && bottom(n.rect) >= bottom(el.rect) - 2)+ }+ return false+}++export function contentBottom(s: PageSnapshot, el: ElementSnapshot): number {+ let node = el+ for (let depth = 0; depth < 8; depth++) {+ if (paintsEdge(node, "bottom") || /^(img|picture|video|canvas|svg|iframe)$/.test(node.tag)) return Math.min(bottom(node.rect), bottom(el.rect))+ const lowest = childrenOf(s, node).filter((n) => flow(s, n) && !spacer(s, n)).sort((a, b) => bottom(b.rect) - bottom(a.rect))[0]+ if (!lowest) return Math.min(bottom(el.rect), bottom(node.rect) - Math.max(0, length(node, "padding-bottom")))+ node = lowest+ }+ return Math.min(bottom(el.rect), bottom(node.rect))+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/text-occlusion.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/text-occlusion.tsnew file mode 100644index 00000000..b5612a86--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/text-occlusion.ts@@ -0,0 +1,84 @@+import { descendants, fontSizePx, shortSnippet, styleOf } from "../../core/page"+import type { PageHit, PageRule } from "../../rule"+import type { ElementSnapshot, PageSnapshot, Rect } from "../../types"+import { alpha, borders, bottom, bounds, chain, clipsX, clipsY, intersects, length, painted, right } from "./support/geometry"++const layered = (s: PageSnapshot, el: ElementSnapshot): boolean =>+ chain(s, el).some((n) => /^(absolute|fixed|sticky)$/.test(styleOf(n, "position")))+const pinned = (s: PageSnapshot, el: ElementSnapshot): boolean =>+ chain(s, el).some((n) => /^(fixed|sticky)$/.test(styleOf(n, "position")))+const opaque = (el: ElementSnapshot): boolean =>+ alpha(el, "background-color") > 0.6 || borders(el).filter(Boolean).length >= 2+const z = (s: PageSnapshot, el: ElementSnapshot): number =>+ chain(s, el).reduce((sum, n) => sum + (Number.parseInt(styleOf(n, "z-index"), 10) || 0), 0)++function visibleLines(s: PageSnapshot, el: ElementSnapshot): readonly Rect[] {+ return el.lineRects.flatMap((line) => {+ let x = Math.max(0, line.x)+ let y = Math.max(0, line.y)+ let end = Math.min(s.viewport.width, right(line))+ let low = Math.min(s.viewport.height, bottom(line))+ for (const c of chain(s, el)) {+ if (clipsX(c)) { x = Math.max(x, c.rect.x); end = Math.min(end, right(c.rect)) }+ if (clipsY(c)) { y = Math.max(y, c.rect.y); low = Math.min(low, bottom(c.rect)) }+ }+ return end - x >= 6 && low - y >= 6 ? [{ x, y, width: end - x, height: low - y }] : []+ })+}++export const textOcclusion: PageRule = {+ meta: {+ id: "text-occlusion", name: "Text occluded by an overlapping element", category: "quality", severity: "warning", engine: "page",+ description: "An overlapping surface or text run covers readable words.",+ fixHint: "Separate the layers, remove leaking inline padding, or position the text outside the overlapping surface.",+ },+ check: ({ snapshot }) => {+ const hits: PageHit[] = []+ const nodes = snapshot.elements.filter((n) => painted(snapshot, n))+ for (const el of nodes) {+ if ([...el.ownText].length < 2 || el.rect.width < 6 || el.rect.height < 6 ||+ el.lineRects.every((r) => r.height <= 1) || alpha(el, "color") <= 0.02 ||+ chain(snapshot, el).reduce((opacity, n) => opacity * (Number.parseFloat(styleOf(n, "opacity")) || 0), 1) <= 0.02 ||+ /blur\((?:[4-9]|\d{2,})px\)/.test(styleOf(el, "filter"))) continue+ const lines = visibleLines(snapshot, el)+ const total = lines.reduce((n, r) => n + r.width * r.height, 0)+ if (total === 0) continue+ const full = bounds(el.lineRects)+ const visible = bounds(lines)+ if (full && visible && (visible.width / full.width < 0.25 || el.lineRects.length === 1 && visible.height / full.height < 0.5)) continue+ const related = new Set([...chain(snapshot, el), ...descendants(snapshot, el)])+ const cover = nodes.find((other) => {+ if (related.has(other) || pinned(snapshot, other) || /^(img|video|canvas|picture)$/.test(other.tag) ||+ styleOf(other, "pointer-events") === "none") return false+ const text = other.ownText.length >= 2 && other.lineRects.some((r) => r.height > 1)+ if (!opaque(other) && !text) return false+ if (text && !layered(snapshot, el) && !layered(snapshot, other)) return false+ if (z(snapshot, other) < z(snapshot, el) || z(snapshot, other) === z(snapshot, el) && other.index < el.index && !text) return false+ if (other.ownText === el.ownText && styleOf(other, "font-family") === styleOf(el, "font-family") &&+ Math.abs(other.rect.x - el.rect.x) < 1 && Math.abs(other.rect.y - el.rect.y) < 1 && !opaque(other)) return false+ const regions = opaque(other) ? [other.rect] : other.lineRects+ let covered = 0+ for (const line of lines) {+ for (const r of regions) {+ if (!intersects(line, r)) continue+ covered += (Math.min(right(line), right(r)) - Math.max(line.x, r.x)) *+ (Math.min(bottom(line), bottom(r)) - Math.max(line.y, r.y))+ }+ }+ return covered / total >= (opaque(other) ? 0.3 : 0.45)+ })+ if (cover) hits.push({ element: el, message: `Text overlaps ${cover.selector}.`, snippet: shortSnippet(el) })+ }+ for (const el of nodes) {+ if (styleOf(el, "display") !== "inline" || !opaque(el)) continue+ const padding = Math.max(length(el, "padding-top"), length(el, "padding-bottom"))+ if (padding < 12) continue+ const expanded = { ...el.rect, y: el.rect.y - padding, height: el.rect.height + padding * 2 }+ const siblings = nodes.filter((n) => n.parent === el.parent && n !== el)+ if (siblings.some((n) => n.lineRects.some((r) => intersects(expanded, r)))) {+ hits.push({ element: el, message: "Inline vertical padding paints over nearby content.", snippet: shortSnippet(el) })+ }+ }+ return hits+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/text-overflow.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/text-overflow.tsnew file mode 100644index 00000000..09f0bb18--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/text-overflow.ts@@ -0,0 +1,72 @@+import { descendants, fontSizePx, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import type { ElementSnapshot, PageSnapshot, Rect } from "../../types"+import { alpha, borders, bottom, bounds, chain, clipRect, clipsX, clipsY, intersects, length, painted, right, scrollsX, textLines } from "./support/geometry"+import { shell } from "./support/clipping"+import { openingWidth } from "./support/motion"++const truncates = (el: ElementSnapshot): boolean =>+ !["inline", "contents"].includes(styleOf(el, "display")) && clipsX(el) &&+ (!["", "clip"].includes(styleOf(el, "text-overflow")) || Number.parseInt(styleOf(el, "-webkit-line-clamp"), 10) > 0)++function harm(s: PageSnapshot, el: ElementSnapshot, box: Rect, text: Rect): boolean {+ const code = chain(s, el).some((n) => ["pre", "code"].includes(n.tag))+ const tolerance = fontSizePx(el) * 0.25+ let cut = false+ for (const c of chain(s, el)) {+ if (styleOf(c, "display") === "inline" || !clipsX(c)) continue+ const clip = clipRect(c)+ if (text.x < clip.x - 1 || right(text) > right(clip) + 1) {+ if (!code) return true+ if (text.x < clip.x - 1 && clip.x > tolerance ||+ right(text) > right(clip) + 1 && right(clip) < s.viewport.width - tolerance) cut = true+ }+ }+ if (cut) return false+ if (text.x <= tolerance || right(text) >= s.viewport.width - tolerance) return true+ const related = new Set([...chain(s, el), ...descendants(s, el)])+ return s.elements.some((other) => {+ if (related.has(other) || !painted(s, other) || other.rect.width <= 2 || other.rect.height <= 2) return false+ if (other.ownText === "" && !/^(img|video|canvas|svg|picture)$/.test(other.tag) && alpha(other, "background-color") < 0.25 && !borders(other).some(Boolean) &&+ ["", "none"].includes(styleOf(other, "background-image"))) return false+ const r = other.rect+ if (r.x <= box.x && right(r) >= right(box) && r.y <= box.y && bottom(r) >= bottom(box)) return false+ return intersects(text, r) && (right(r) > right(box) && r.x < right(text) || r.x < box.x && right(r) > text.x)+ })+}++export const textOverflow: PageRule = {+ meta: {+ id: "text-overflow", name: "Content overflowing its container", category: "quality", severity: "warning", engine: "page",+ description: "Text spills out of its box into a clip, another element, or the viewport edge.",+ fixHint: "Allow wrapping, constrain the content width, or provide a deliberate horizontal scroll region.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap((el) => {+ if (el.ownText === "" || /^(input|textarea|select|option|svg|path|script|style)$/.test(el.tag) || !painted(snapshot, el)) return []+ const path = chain(snapshot, el)+ if (path.some((n) => n.tag === "svg")) return []+ if (openingWidth(snapshot, el)) return []+ const code = path.some((n) => ["pre", "code", "samp", "kbd"].includes(n.tag))+ if (path.some((n) => scrollsX(n) && !(code && n !== el && shell(snapshot, n))) || path.some(truncates)) return []+ const text = bounds(textLines(snapshot, el))+ if (!text) return []+ if (path.some((c) => clipsY(c) && (text.y >= bottom(clipRect(c)) || bottom(text) <= clipRect(c).y))) return []+ if (path.some((c) => styleOf(c, "display") !== "inline" && clipsX(c) && (right(text) <= clipRect(c).x || text.x >= right(clipRect(c))))) return []+ const box = styleOf(el, "display") === "inline"+ ? path.slice(1).find((c) => c.scroll.clientWidth > 0 && styleOf(c, "display") !== "inline") ?? el+ : el+ const start = box.rect.x + length(box, "border-left-width")+ const end = start + (box.scroll.clientWidth > 0 ? box.scroll.clientWidth : box.rect.width)+ const generated = [el.before, el.after].some((p) => p !== null && /["'][^"']+["']/.test(p.style["content"] ?? "") &&+ p.style["display"] !== "none")+ const reach = generated && el.scroll.scrollWidth > el.scroll.clientWidth+ ? { ...text, width: Math.max(text.width, el.scroll.scrollWidth) } : text+ const delta = Math.max(right(reach) - end, start - reach.x)+ const drawn = alpha(box, "background-color") > 0 || borders(box).some(Boolean)+ const pastContent = Math.max(right(text) - end + length(box, "padding-right"), start + length(box, "padding-left") - text.x)+ const paintedSpill = !code && drawn && !clipsX(box) && delta < 16 &&+ delta >= Math.max(fontSizePx(el) * 0.25, 2) && pastContent >= 15+ if (!(delta >= 16 && harm(snapshot, el, box.rect, reach) || paintedSpill)) return []+ return [{ element: el, message: `Text extends ${Math.round(delta)}px past its container.`, snippet: shortSnippet(el) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/unbalanced-heading.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/unbalanced-heading.tsnew file mode 100644index 00000000..c4df29c6--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/unbalanced-heading.ts@@ -0,0 +1,22 @@+import { isHeading, shortSnippet } from "../../core/page"+import type { PageRule } from "../../rule"+import { measuredLines, oneFace, wordsOf, wrapIs } from "./support/line-breaks"++export const unbalancedHeading: PageRule = {+ meta: {+ id: "unbalanced-heading", name: "Unbalanced heading", category: "quality", severity: "advisory", engine: "page",+ description: "The last line of a heading is much shorter than the line above.",+ fixHint: "Use text-wrap: balance or rewrite the heading to keep its lines near even.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap((el) => {+ if (!isHeading(el) || wrapIs(el, "balance") || wordsOf(el).length < 3) return []+ const lines = measuredLines(snapshot, el)+ const tail = lines.at(-1)+ const above = lines.at(-2)+ if (lines.length < 2 || lines.length > 3 || !tail || !above || tail.width >= above.width * 0.35) return []+ const widest = Math.max(...lines.map((l) => l.width))+ const total = lines.reduce((n, l) => n + l.width, 0)+ if (oneFace(snapshot, el) && widest * el.text.length / total < 20) return []+ return [{ element: el, message: `The last line is ${Math.round(tail.width / above.width * 100)}% as wide as the line above.`, snippet: shortSnippet(el) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/layout/viewport-reflow.ts b/plugins/omo/skills/frontend/scripts/detect/rules/layout/viewport-reflow.tsnew file mode 100644index 00000000..5e75c99e--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/layout/viewport-reflow.ts@@ -0,0 +1,33 @@+import { shortSnippet } from "../../core/page"+import type { PageRule } from "../../rule"+import type { ElementSnapshot, PageSnapshot } from "../../types"+import { chain, clipsX, painted, right, scrollsX } from "./support/geometry"++function reaches(s: PageSnapshot, el: ElementSnapshot): number {+ let end = Math.max(right(el.rect), ...el.lineRects.map(right))+ if (clipsX(el)) end = right(el.rect)+ for (const ancestor of chain(s, el).slice(1)) {+ if (clipsX(ancestor) && ancestor.tag !== "body") end = Math.min(end, right(ancestor.rect))+ }+ return end+}++export const viewportReflow: PageRule = {+ meta: {+ id: "viewport-reflow", name: "Viewport reflow", category: "quality", severity: "error", engine: "page",+ description: "The document is wider than the viewport and requires sideways scrolling.",+ fixHint: "Constrain the widest content, allow long tokens to wrap, and keep intentional horizontal scrolling inside its own region.",+ },+ check: ({ snapshot }) => {+ if (snapshot.document.scrollWidth <= snapshot.document.clientWidth) return []+ const widest = snapshot.elements+ .filter((el) => painted(snapshot, el) && reaches(snapshot, el) > snapshot.document.clientWidth &&+ !chain(snapshot, el).slice(1).some((n) => n.tag !== "body" && scrollsX(n)))+ .sort((a, b) => reaches(snapshot, b) - reaches(snapshot, a))[0]+ return [{+ element: null,+ message: `Document width ${snapshot.document.scrollWidth}px exceeds ${snapshot.document.clientWidth}px${widest ? `; furthest element ${widest.selector} ends at ${reaches(snapshot, widest)}px` : ""}.`,+ snippet: widest ? shortSnippet(widest) : `${snapshot.document.scrollWidth}px / ${snapshot.document.clientWidth}px`,+ }]+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/ai-color-palette.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/ai-color-palette.tsnew file mode 100644index 00000000..7178cb22--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/ai-color-palette.ts@@ -0,0 +1,11 @@+import type { SourceRule } from "../../rule"+import { lineCheck, sourceExtensions } from "./support/source-text"++export const aiColorPalette: SourceRule = {+ meta: { id: "ai-color-palette", name: "AI color palette", category: "slop", severity: "warning", engine: "source", description: "Purple heading ink or a purple-to-cool gradient repeats a generic palette.", fixHint: "Choose colors from the product's visual identity." },+ extensions: sourceExtensions,+ check: lineCheck([/\btext-(?:purple|violet|indigo)-(\d+)\b/g, /\bfrom-(?:purple|violet|indigo)-(\d+)\b/g], ({ match, scope }) => {+ if (match[0].startsWith("text-")) return /\btext-[2-9]xl\b|<h[1-3]/i.test(scope) ? `${match[0]} on heading` : null+ return /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(scope) ? `${match[0]} gradient` : null+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/aphoristic-cadence.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/aphoristic-cadence.tsnew file mode 100644index 00000000..e6d6a304--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/aphoristic-cadence.ts@@ -0,0 +1,14 @@+import type { SourceRule } from "../../rule"+import { bodyText, componentExtensions, pageSource, sourceHit } from "./support/source-text"++export const aphoristicCadence: SourceRule = {+ meta: { id: "aphoristic-cadence", name: "Aphoristic-cadence copy", category: "slop", severity: "warning", engine: "source", description: "Several clipped rebuttals give page copy a repetitive slogan rhythm.", fixHint: "Replace repeated slogans with specific, naturally paced sentences." },+ extensions: componentExtensions,+ check: (context) => {+ const source = pageSource(context)+ if (source === null) return []+ const text = bodyText(source)+ const count = [...text.matchAll(/\bNot an? [a-z][^.!?]{1,40}[.!]\s+[A-Z][^.!?]{1,60}[.!]/g)].length + [...text.matchAll(/\b[A-Z][^.!?]{4,80}[.!]\s+(No|Just)\s+[a-z][^.!?]{2,60}[.!]/g)].length+ return count >= 3 ? [sourceHit(source, 0, `${count} clipped slogan constructions`)] : []+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/border-accent-on-rounded.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/border-accent-on-rounded.tsnew file mode 100644index 00000000..a75e40d2--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/border-accent-on-rounded.ts@@ -0,0 +1,20 @@+import type { SourceRule } from "../../rule"+import { cssScopes, selectorHost, selectorMatches } from "./support/css-scopes"+import { tagAt } from "./support/markup-scope"+import { lineCheck, sourceExtensions } from "./support/source-text"++export const borderAccentOnRounded: SourceRule = {+ meta: { id: "border-accent-on-rounded", name: "Border accent on rounded element", category: "slop", severity: "warning", engine: "source", description: "A thick top or bottom border meets a rounded element.", fixHint: "Remove the accent border or use square corners." },+ extensions: sourceExtensions,+ check: lineCheck([/\bborder-[tb]-(\d+)\b/g, /border-(?:top|bottom)\s*:\s*(\d+)px\s+solid/gi], ({ match, line, scope, offset, pass }) => {+ if (match[0].startsWith("border-t-") || match[0].startsWith("border-b-")) {+ const tag = tagAt(line, match.index ?? 0)+ return Number(match[1]) >= 1 && /\brounded(?!-none\b)(?:-\w+)?\b/.test(tag) && !/\banimate-spin\b/.test(tag) ? match[0] : null+ }+ if (Number(match[1]) < 3) return null+ const scopes = cssScopes(pass.text, pass.sass)+ const own = scopes.filter((s) => s.start <= offset && offset <= s.end).sort((a, b) => b.start - a.start)[0]+ const radius = own ? scopes.some((s) => selectorMatches(selectorHost(s), selectorHost(own)) && /(?:^|[;{\s])border[-\w]*radius\s*:/.test(s.body)) : /border-radius/i.test(scope)+ return radius ? match[0] : null+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/bounce-easing.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/bounce-easing.tsnew file mode 100644index 00000000..f380d375--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/bounce-easing.ts@@ -0,0 +1,21 @@+import type { SourceRule } from "../../rule"+import { lineCheck, sourceExtensions } from "./support/source-text"++export const bounceEasing: SourceRule = {+ meta: { id: "bounce-easing", name: "Bounce or elastic easing", category: "slop", severity: "advisory", engine: "source", description: "A named bounce animation or overshooting timing curve adds elastic motion.", fixHint: "Use a smooth deceleration, or allow an intentional timing function." },+ extensions: sourceExtensions,+ check: lineCheck([/\banimate-bounce\b/g, /animation(?:-name)?\s*:\s*([^;{}]*(?:bounce|elastic|wobble|jiggle|spring)[^;{}]*)/gi, /cubic-bezier\(\s*([0-9.-]+)\s*,\s*([0-9.-]+)\s*,\s*([0-9.-]+)\s*,\s*([0-9.-]+)\s*\)/g], ({ match, context }) => {+ const canonical = (s: string): string => s.replace(/\s/g, "").toLowerCase()+ const names = match[4] === undefined ? match[1]?.split(/[,\s]+/).filter((s) => /bounce|elastic|wobble|jiggle|spring/i.test(s)) ?? [] : []+ const name = names.find((candidate) => !context.config.allowEasings?.some((easing) => canonical(easing) === canonical(candidate)))+ if (context.config.allowEasings?.some((easing) => [match[0], match[1] ?? ""].some((value) => canonical(easing) === canonical(value)))+ || (names.length > 0 && name === undefined)) return null+ if (match[4] !== undefined) {+ const y1 = Number(match[2])+ const y2 = Number(match[4])+ return y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1 ? `cubic-bezier(${match.slice(1).join(", ")})` : null+ }+ if (match[1]) return `animation: ${name ?? match[1].trim()}`+ return "animate-bounce (Tailwind)"+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/broken-image.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/broken-image.tsnew file mode 100644index 00000000..ad907100--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/broken-image.ts@@ -0,0 +1,16 @@+import { extensionOf } from "../../core/source"+import type { SourceRule } from "../../rule"+import { imageTags, missingImageSource } from "./support/image-tags"+import { sheetExtensions, sourceExtensions, sourceHit, stripComments } from "./support/source-text"++export const brokenImage: SourceRule = {+ meta: { id: "broken-image", name: "Broken or placeholder image", category: "quality", severity: "warning", engine: "source", description: "An image tag has no statically usable source or source set.", fixHint: "Supply a real image source or remove the unused image element." },+ extensions: sourceExtensions,+ check: ({ file }) => {+ const ext = extensionOf(file.path)+ if (sheetExtensions.includes(ext)) return []+ const script = ["js", "jsx", "ts", "tsx", "mjs", "cjs"].includes(ext)+ const text = stripComments(file.text, script)+ return imageTags(text, script).filter((hit) => missingImageSource(hit.tag, ext)).map((hit) => sourceHit(file.text, hit.offset, "Image has no source", hit.tag.slice(0, 100)))+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/codex-grid-background.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/codex-grid-background.tsnew file mode 100644index 00000000..21c0c9be--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/codex-grid-background.ts@@ -0,0 +1,18 @@+import type { SourceRule } from "../../rule"+import { cssScopes } from "./support/css-scopes"+import { sourceExtensions, sourceHit, sourcePasses } from "./support/source-text"++export const codexGridBackground: SourceRule = {+ meta: { id: "codex-grid-background", name: "Decorative grid-line background", category: "slop", severity: "advisory", engine: "source", description: "Two tiled hairline gradients draw a decorative background grid.", fixHint: "Remove the grid unless it communicates structure or data." },+ extensions: sourceExtensions,+ check: (context) => {+ const text = sourcePasses(context)[0]?.text ?? ""+ const blocks = [...cssScopes(text).map((s) => ({ body: s.body, offset: text.indexOf("{", s.start) })), ...[...text.matchAll(/\bstyle\s*=\s*["']([^"']*)["']/gi)].map((m) => ({ body: m[1] ?? "", offset: m.index ?? 0 }))]+ for (const block of blocks) {+ const backgrounds = [...block.body.matchAll(/\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi)].map((m) => m[1] ?? "").join(";")+ const lines = [...backgrounds.matchAll(/\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px|transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi)].length+ if (lines >= 2 && (/background-size\s*:[^;{}"']*\b\d{1,3}px\b/i.test(block.body) || /\/\s*\d{1,3}px\b/.test(backgrounds))) return [sourceHit(context.file.text, block.offset, "Two-axis gradient background grid")]+ }+ return []+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/dark-glow.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/dark-glow.tsnew file mode 100644index 00000000..6d892bb9--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/dark-glow.ts@@ -0,0 +1,21 @@+import type { SourceRule } from "../../rule"+import { darkBackground, resolveValues } from "./support/css-effects"+import { componentExtensions, pageSource, sourceHit } from "./support/source-text"+import { sourceShadows } from "./support/source-shadow"++export const darkGlow: SourceRule = {+ meta: { id: "dark-glow", name: "Glowing shadow accents", category: "slop", severity: "warning", engine: "source", description: "A colored blurred shadow creates a visible glow.", fixHint: "Use neutral elevation shadows instead of chromatic halos." },+ extensions: componentExtensions,+ check: (context) => {+ const text = pageSource(context)+ if (text === null) return []+ const dark = darkBackground(text)+ for (const m of resolveValues(text).matchAll(/(?<![-\w])(?:box|text)-shadow\s*:\s*([^;{}]+)/gi)) {+ for (const s of sourceShadows(m[1] ?? "")) {+ if (Math.max(s.color.r, s.color.g, s.color.b) - Math.min(s.color.r, s.color.g, s.color.b) < 30 || s.blur <= 4 || s.blur * s.color.a < 3 || s.blur / 2 + s.spread <= 0) continue+ if (dark || (s.x === 0 && s.y === 0)) return [sourceHit(text, m.index ?? 0, "Colored shadow glow")]+ }+ }+ return []+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/em-dash-overuse.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/em-dash-overuse.tsnew file mode 100644index 00000000..0148a6dc--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/em-dash-overuse.ts@@ -0,0 +1,15 @@+import { EM_DASH } from "../../core/characters"+import type { SourceRule } from "../../rule"+import { bodyText, componentExtensions, pageSource, sourceHit } from "./support/source-text"++export const emDashOveruse: SourceRule = {+ meta: { id: "em-dash-overuse", name: "Em-dash overuse", category: "slop", severity: "advisory", engine: "source", description: "Body copy repeatedly uses em dashes in a short space.", fixHint: "Break repeated asides into sentences or use simpler punctuation." },+ extensions: componentExtensions,+ check: (context) => {+ const source = pageSource(context)+ if (source === null) return []+ const text = bodyText(source).replace(/—|�*8212;|�*2014;/gi, EM_DASH)+ const count = [...text.matchAll(/\u2014|(?<!-)--(?!-)/g)].length+ return count >= 8 && text.length <= count * 500 ? [sourceHit(source, 0, `${count} em dashes in body copy`)] : []+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/gradient-text.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/gradient-text.tsnew file mode 100644index 00000000..a11563ac--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/gradient-text.ts@@ -0,0 +1,11 @@+import type { SourceRule } from "../../rule"+import { lineCheck, sourceExtensions } from "./support/source-text"++export const gradientText: SourceRule = {+ meta: { id: "gradient-text", name: "Gradient text", category: "slop", severity: "warning", engine: "source", description: "Clipped text uses a decorative gradient fill.", fixHint: "Use a solid text color with a clear hierarchy." },+ extensions: sourceExtensions,+ check: lineCheck([/(?:-webkit-)?background-clip\s*:\s*text/gi, /\bbg-clip-text\b/g], ({ match, scope }) => {+ if (match[0] === "bg-clip-text") return /\bbg-gradient-to-/i.test(scope) ? "bg-clip-text + bg-gradient" : null+ return /gradient/i.test(scope) ? "background-clip: text + gradient" : null+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/gray-on-color.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/gray-on-color.tsnew file mode 100644index 00000000..66b4d193--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/gray-on-color.ts@@ -0,0 +1,13 @@+import type { SourceRule } from "../../rule"+import { exclusiveScopes, solidBackground, tagAt } from "./support/markup-scope"+import { lineCheck, sourceExtensions } from "./support/source-text"++export const grayOnColor: SourceRule = {+ meta: { id: "gray-on-color", name: "Gray text on colored background", category: "quality", severity: "warning", engine: "source", description: "Gray utility text shares an element and conditional branch with a solid colored fill.", fixHint: "Use ink derived from the surface hue, or a neutral surface." },+ extensions: sourceExtensions,+ check: lineCheck([/\btext-(?:gray|slate|zinc|neutral|stone)-(\d+)\b/g], ({ match, line }) => {+ if (Number(match[1]) >= 700) return null+ const bg = exclusiveScopes(tagAt(line, match.index ?? 0)).filter((scope) => scope.includes(match[0])).map((scope) => solidBackground(scope, true)).find((value) => value !== null)+ return bg ? `${match[0]} on ${bg}` : null+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/index.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/index.tsnew file mode 100644index 00000000..08fdb7cf--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/index.ts@@ -0,0 +1,19 @@+import type { SourceRule } from "../../rule"+import { aiColorPalette } from "./ai-color-palette"+import { aphoristicCadence } from "./aphoristic-cadence"+import { borderAccentOnRounded } from "./border-accent-on-rounded"+import { bounceEasing } from "./bounce-easing"+import { brokenImage } from "./broken-image"+import { codexGridBackground } from "./codex-grid-background"+import { darkGlow } from "./dark-glow"+import { emDashOveruse } from "./em-dash-overuse"+import { gradientText } from "./gradient-text"+import { grayOnColor } from "./gray-on-color"+import { marketingBuzzword } from "./marketing-buzzword"+import { marquee } from "./marquee"+import { monotonousSpacing } from "./monotonous-spacing"+import { overusedFont } from "./overused-font"+import { radialHalo } from "./radial-halo"+import { sideTab } from "./side-tab"++export const SOURCE_RULES: readonly SourceRule[] = [sideTab, borderAccentOnRounded, overusedFont, gradientText, grayOnColor, aiColorPalette, bounceEasing, brokenImage, codexGridBackground, monotonousSpacing, emDashOveruse, marketingBuzzword, aphoristicCadence, darkGlow, radialHalo, marquee]diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/marketing-buzzword.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/marketing-buzzword.tsnew file mode 100644index 00000000..2af2a72e--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/marketing-buzzword.ts@@ -0,0 +1,17 @@+import type { SourceRule } from "../../rule"+import { bodyText, componentExtensions, pageSource, sourceHit } from "./support/source-text"++const phrases = ["streamline your", "empower your", "supercharge your", "unleash your", "unleash the power", "leverage the power", "built for the modern", "trusted by leading", "trusted by the world", "best-in-class", "industry-leading", "world-class", "enterprise-grade", "next-generation", "cutting-edge", "transform your business", "revolutionize", "game-changer", "game changing", "mission-critical", "best of breed", "future-proof", "future proof", "seamless experience", "seamlessly integrate", "drive engagement", "drive growth", "drive results", "harness the power"]++export const marketingBuzzword: SourceRule = {+ meta: { id: "marketing-buzzword", name: "Marketing buzzword", category: "slop", severity: "warning", engine: "source", description: "Page copy contains generic promotional phrases instead of concrete information.", fixHint: "Describe what the product does and who it helps." },+ extensions: componentExtensions,+ check: (context) => {+ const source = pageSource(context)+ if (source === null) return []+ const text = bodyText(source).toLowerCase()+ let count = 0+ for (const phrase of phrases) count += text.split(phrase).length - 1+ return count > 0 ? [sourceHit(source, 0, `${count} generic promotional phrases`)] : []+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/marquee.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/marquee.tsnew file mode 100644index 00000000..6e913669--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/marquee.ts@@ -0,0 +1,12 @@+import type { SourceRule } from "../../rule"+import { marqueeSelectors } from "./support/css-effects"+import { componentExtensions, pageSource, sourceHit } from "./support/source-text"++export const marquee: SourceRule = {+ meta: { id: "marquee", name: "Auto-scrolling marquee", category: "slop", severity: "warning", engine: "source", description: "Content moves in a perpetual horizontal loop.", fixHint: "Keep content still or let the reader control scrolling." },+ extensions: componentExtensions,+ check: (context) => {+ const text = pageSource(context)+ return text === null ? [] : marqueeSelectors(text).map((selector) => sourceHit(text, 0, `Horizontal content loop: ${selector}`, selector))+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/monotonous-spacing.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/monotonous-spacing.tsnew file mode 100644index 00000000..09df66fb--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/monotonous-spacing.ts@@ -0,0 +1,22 @@+import type { SourceRule } from "../../rule"+import { pageSource, sourceHit, componentExtensions } from "./support/source-text"++export const monotonousSpacing: SourceRule = {+ meta: { id: "monotonous-spacing", name: "Monotonous spacing", category: "slop", severity: "warning", engine: "source", description: "One spacing value dominates a full page with little variation.", fixHint: "Vary spacing to distinguish groups from sections." },+ extensions: componentExtensions,+ check: (context) => {+ const text = pageSource(context)+ if (text === null) return []+ const vals: number[] = []+ for (const m of text.matchAll(/(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi)) { const v = Number(m[1]); if (v > 0 && v < 200) vals.push(v) }+ for (const m of text.matchAll(/(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi)) { const v = Math.round(Number(m[1]) * 16); if (v > 0 && v < 200) vals.push(v) }+ for (const m of text.matchAll(/gap\s*:\s*(\d+)px/gi)) vals.push(Number(m[1]))+ for (const m of text.matchAll(/\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g)) vals.push(Number(m[1]) * 4)+ if (vals.length < 10) return []+ const counts = new Map<number, number>()+ for (const value of vals) { const v = Math.round(value / 4) * 4; counts.set(v, (counts.get(v) ?? 0) + 1) }+ const [dominant, count] = [...counts].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0] ?? [0, 0]+ if (dominant === 0 || count / vals.length <= 0.6 || [...counts.keys()].filter((v) => v > 0).length > 3) return []+ return [sourceHit(text, 0, `${dominant}px appears ${count}/${vals.length} times`)]+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/overused-font.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/overused-font.tsnew file mode 100644index 00000000..3cbd5db6--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/overused-font.ts@@ -0,0 +1,16 @@+import type { SourceRule } from "../../rule"+import { lineCheck, sourceExtensions } from "./support/source-text"++const fonts = ["Inter", "Roboto", "Open Sans", "Lato", "Montserrat", "Arial", "Helvetica", "Fraunces", "Geist Sans", "Geist Mono", "Geist", "Mona Sans", "Plus Jakarta Sans", "Space Grotesk", "Recoleta", "Instrument Sans", "Instrument Serif"]++export const overusedFont: SourceRule = {+ meta: { id: "overused-font", name: "Overused font", category: "slop", severity: "warning", engine: "source", description: "A familiar default typeface appears in a font declaration or import.", fixHint: "Choose a typeface suited to the product, or allow the intentional family." },+ extensions: sourceExtensions,+ check: lineCheck([new RegExp(`font-family\\s*:\\s*['"]?(${fonts.join("|")})\\b`, "gi"), /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi], ({ match, context }) => {+ const query = new URLSearchParams(match[0].slice(match[0].indexOf("?") + 1))+ const family = match[1] ?? query.getAll("family").flatMap((value) => value.split("|")).map((f) => f.split(":")[0] ?? "")+ .find((f) => fonts.some((font) => font.toLowerCase() === f.toLowerCase()) && !context.config.allowFonts?.some((allowed) => allowed.toLowerCase() === f.toLowerCase()))+ if (!family || context.config.allowFonts?.some((f) => f.toLowerCase() === family.toLowerCase())) return null+ return match[1] ? match[0] : `Google Fonts: ${family.toLowerCase()}`+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/radial-halo.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/radial-halo.tsnew file mode 100644index 00000000..5c1f32a2--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/radial-halo.ts@@ -0,0 +1,14 @@+import type { SourceRule } from "../../rule"+import { haloOffsets } from "./support/css-effects"+import { componentExtensions, pageSource, sourceHit } from "./support/source-text"++export const radialHalo: SourceRule = {+ meta: { id: "radial-halo", name: "Radial-gradient background halo", category: "slop", severity: "warning", engine: "source", description: "A saturated radial gradient fades into a dark background.", fixHint: "Use a quieter solid background or purposeful imagery." },+ extensions: componentExtensions,+ check: (context) => {+ const text = pageSource(context)+ if (text === null) return []+ const offset = haloOffsets(text)[0]+ return offset === undefined ? [] : [sourceHit(text, offset, "Radial color halo on a dark page")]+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/side-tab.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/side-tab.tsnew file mode 100644index 00000000..45463b66--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/side-tab.ts@@ -0,0 +1,58 @@+import type { SourceRule } from "../../rule"+import { accentScans, safeSelector } from "./support/accent-scans"+import { chromatic } from "./support/source-color"+import { applyRadii, roundedAway, scopeCorners, tagCorners } from "./support/corners"+import { cssScopes, selectorHost } from "./support/css-scopes"+import { solidBackground, tagAt } from "./support/markup-scope"+import { lineCheck, sourceExtensions, sourcePasses } from "./support/source-text"++const borderCheck = lineCheck([+ /\bborder-([lrse])-(\d+)\b/g,+ /border-(left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,+ /border-(left|right|inline-start|inline-end)-width\s*:\s*(\d+)px/gi,+ /border-(inline-start|inline-end)\s*:\s*(\d+)px\s+solid/gi,+ /border(Left|Right)\s*[:=]\s*["'`](\d+)px\s+solid/g,+ /(?<![\w-])w-(?:0\.5|1(?:\.5)?|2(?:\.5)?|3|\[(?:[2-9]|1[0-2])px\])(?![\w./-])/g,+], ({ match, line, scope, offset, pass, context }) => {+ const tag = tagAt(line, match.index ?? 0)+ if (match[0].startsWith("w-")) {+ const bg = solidBackground(tag)+ const empty = !tag.startsWith("<") || /\/>$/.test(tag) || line.slice(line.indexOf(tag) + tag.length).trimStart().startsWith("</")+ if (!bg || !empty || !/(?<![\w-])(?:shrink-0|rounded-[lres](?:-\w+)?|left-0|right-0|inset-0|inset-y-0)(?![\w./-])/.test(tag) || /(?<![\w-])h-(?:px\b|[0-9]|\[)|\brounded-full\b|aria-(?:current|selected)/i.test(tag)) return null+ return `${match[0]} + ${bg} stripe child`+ }+ const side = (match[1] ?? "left").toLowerCase().replace("inline-", "")+ const width = Number(match[2])+ const utility = /^border-[lrse]-/.test(match[0])+ if (utility ? width < (/\brounded(?!-none)\b/.test(scope) ? 2 : 4) : width < (/^border-(?:left|right)\s*:/i.test(match[0]) && /border-radius/i.test(scope) ? 2 : 3)) return null+ if (!utility && /<(?:blockquote|nav[\s>]|pre[\s>]|code[\s>]|a\s|input[\s>]|span[\s>])/i.test(scope)) return null+ if (/^border-(?:left|right)\s*:/i.test(match[0])) {+ const color = /\bsolid\s+([\s\S]*)/i.exec(match[0])?.[1]?.trim() ?? ""+ if (color && !chromatic(color)) return null+ }+ const styles = sourcePasses(context).filter((p) => p.css).map((p) => p.text).join("\n")+ const imported = /(?:import|require\s*\()[^;\n]*\.(?:css|scss|sass|less)["']|<style[^>]*\bsrc\s*=|@import|@use\s+['"](?!sass:)/.test(context.file.text)+ if (utility || (tag.startsWith("<") && /border(?:Left|Right)\s*=|(?:style|sx)\s*=/.test(tag))) {+ const corners = tag === line && !line.trimStart().startsWith("<") ? [null, null, null, null] : tagCorners(tag, styles || context.file.text, imported)+ if (!roundedAway(corners, side)) return null+ } else {+ const embedded = sourcePasses(context).find((p) => p.css && p.offset <= pass.offset + offset && pass.offset + offset < p.offset + p.text.length)+ const ownPass = embedded ?? pass+ const localOffset = pass.offset + offset - ownPass.offset+ const scopes = cssScopes(ownPass.text, ownPass.sass)+ const block = scopes.filter((s) => s.start <= localOffset && localOffset <= s.end).sort((a, b) => b.start - a.start)[0]+ if (block) {+ const host = selectorHost(block)+ const corners = scopeCorners(block, scopes)+ const status = /(?:^|[ .>])(?:tr|td|th)\b|(?:error|danger|warning|success|broken|new)\b/.test(host)+ if (!roundedAway(corners, side) && (!status || safeSelector(host))) return null+ } else if (!roundedAway(applyRadii([0, 0, 0, 0], scope), side)) return null+ }+ return match[0].replace(/\s*;?\s*$/, "")+})++export const sideTab: SourceRule = {+ meta: { id: "side-tab", name: "Side-tab accent border", category: "slop", severity: "warning", engine: "source", description: "A colored stripe decorates a rounded card or status row.", fixHint: "Remove the stripe or use a quieter surface and text hierarchy." },+ extensions: sourceExtensions,+ check: (context) => [...borderCheck(context), ...accentScans(context)],+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/support/accent-scans.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/accent-scans.tsnew file mode 100644index 00000000..550f75d7--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/accent-scans.ts@@ -0,0 +1,78 @@+import type { SourceContext, SourceHit } from "../../../rule"+import { roundedAway, scopeCorners } from "./corners"+import { cleanSelector, cssScopes, declarations, selectorHost, type CssScope } from "./css-scopes"+import { sourceHit, sourcePasses } from "./source-text"+import { sourceShadows } from "./source-shadow"+import { chromatic } from "./source-color"++export const safeSelector = (selector: string): boolean => /:(?:hover|focus|active|visited)|aria-(?:selected|current)|(?:^|[.\s_-])(?:selected|current|active|checked)(?:$|[.\s_:-])|(?:^|[\s>+~])(?:blockquote|nav|pre|code|a|input|span)(?:$|[\s.#:[>])/i.test(selector)++function pseudoEdge(scope: CssScope): string | null {+ const d = declarations(scope.body)+ if (!/^(?:absolute|fixed)$/.test(d.get("position") ?? "")) return null+ const inset = d.get("inset")?.split(/\s+/)+ const [t = "", r = t, b = t, l = r] = inset ?? []+ const top = d.get("top") ?? t+ const right = d.get("right") ?? d.get("inset-inline-end") ?? r+ const bottom = d.get("bottom") ?? b+ const left = d.get("left") ?? d.get("inset-inline-start") ?? l+ const zero = (value: string): boolean => /^0(?:px|rem|em|%)?$/.test(value)+ const width = Number.parseFloat(d.get("width") ?? d.get("inline-size") ?? "")+ const height = Number.parseFloat(d.get("height") ?? d.get("block-size") ?? "")+ const fullHeight = (zero(top) && zero(bottom)) || d.get("height") === "100%" || [top, bottom].every((v) => /^\d+(?:px)?$/.test(v) && Number.parseFloat(v) <= 20)+ if (width >= 3 && width <= 12 && fullHeight) return zero(left) ? "left" : zero(right) ? "right" : null+ const fullWidth = (zero(left) && zero(right)) || d.get("width") === "100%"+ if (height >= 3 && height <= 12 && fullWidth && !safeSelector(scope.selector) && !/(?:^|[ .>])(?:button|summary|tr|td|th|table|li)(?:$|[.#:\s])/.test(scope.selector)) return zero(top) ? "top" : zero(bottom) ? "bottom" : null+ return null+}++function resolveTokens(value: string, text: string): string {+ const tokens = new Map([...text.matchAll(/(--[\w-]+)\s*:\s*([^;{}]+)/g)].map((m) => [m[1] ?? "", m[2] ?? ""]))+ let result = value+ for (let depth = 0; depth < 8; depth++) {+ const next = result.replace(/var\(\s*(--[\w-]+)\s*(?:,\s*([^)]*))?\)/g, (whole: string, key: string, fallback: string | undefined) => tokens.get(key) ?? fallback ?? whole)+ if (next === result) break+ result = next+ }+ return result+}++export function accentScans(context: SourceContext): readonly SourceHit[] {+ const hits: SourceHit[] = []+ const seen = new Set<string>()+ for (const pass of sourcePasses(context).filter((p) => p.css)) {+ const scopes = cssScopes(pass.text, pass.sass)+ for (const scope of scopes) {+ const selector = selectorHost(scope)+ const d = declarations(scope.body)+ const pseudo = /::?(?:before|after)\b/.test(selector)+ if (pseudo) {+ const side = pseudoEdge(scope)+ const bg = resolveTokens(d.get("background-color") ?? d.get("background") ?? "", context.file.text)+ if (!side || !bg || !chromatic(bg) || /(?:^|[ >])(?:blockquote|pre|code)\b/.test(selector)) continue+ const host = cleanSelector(selector)+ const hostScope = scopes.find((s) => cleanSelector(selectorHost(s)) === host && !/::?(?:before|after)/.test(s.selector)) ?? scope+ if ((side === "left" || side === "right") && !roundedAway(scopeCorners(hostScope, scopes, host), side)) continue+ const key = `${pass.offset}:${selector.includes("&") ? scope.start : selector}`+ if (seen.has(key)) continue+ seen.add(key)+ hits.push(sourceHit(context.file.text, pass.offset + scope.start, `${scope.selector} pseudo-element stripe (${side})`, scope.selector))+ continue+ }+ if (safeSelector(selector) || Number.parseFloat(d.get("width") ?? "999") <= 40) continue+ const shadow = resolveTokens(d.get("box-shadow") ?? "", context.file.text)+ const status = /(?:^|[ .>])(?:tr|td|th)\b|(?:error|danger|warning|success|broken|new)\b/.test(selector)+ for (const layer of sourceShadows(shadow, status)) {+ const ax = Math.abs(layer.x)+ const ay = Math.abs(layer.y)+ if (!layer.inset || layer.blur !== 0 || layer.spread !== 0 || layer.color.a < 0.1 || Math.max(layer.color.r, layer.color.g, layer.color.b) - Math.min(layer.color.r, layer.color.g, layer.color.b) < 30) continue+ if (!((ax >= 3 && ax <= 12 && ay === 0) || (ay >= 3 && ay <= 12 && ax === 0))) continue+ const side = ay === 0 ? layer.x > 0 ? "left" : "right" : layer.y > 0 ? "top" : "bottom"+ if (!(status && ay === 0) && !roundedAway(scopeCorners(scope, scopes), side)) continue+ hits.push(sourceHit(context.file.text, pass.offset + scope.start, `${scope.selector} inset stripe (${side})`, scope.selector))+ break+ }+ }+ }+ return hits+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/support/check-source.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/check-source.tsnew file mode 100644index 00000000..1f099064--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/check-source.ts@@ -0,0 +1,6 @@+import type { SourceHit, SourceRule } from "../../../rule"+import type { DetectConfig } from "../../../types"++export function checkSource(rule: SourceRule, text: string, options: { readonly path?: string; readonly config?: DetectConfig } = {}): readonly SourceHit[] {+ return rule.check({ file: { path: options.path ?? "fixture.tsx", text }, config: options.config ?? {} })+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/support/corners.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/corners.tsnew file mode 100644index 00000000..898036e4--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/corners.ts@@ -0,0 +1,105 @@+import { cleanSelector, cssScopes, declarations, selectorHost, selectorMatches, type CssScope } from "./css-scopes"++export type Corners = readonly (number | null)[]+const zero = (): (number | null)[] => [0, 0, 0, 0]+const unknown = (): (number | null)[] => [null, null, null, null]+const radiusIndices: Readonly<Record<string, readonly number[]>> = {+ tl: [0], tr: [1], br: [2], bl: [3], ss: [0], se: [1], ee: [2], es: [3], t: [0, 1], r: [1, 2], b: [2, 3], l: [0, 3], s: [0, 3], e: [1, 2],+}++function radiusPx(value: string): number | null {+ const v = value.trim().replace(/^['"`]|['"`]$/g, "")+ if (v === "0" || v === "none") return 0+ const m = /^(-?\d*\.?\d+)(px|rem|em|%)?$/.exec(v)+ if (!m) return null+ return Number(m[1]) * (m[2] === "rem" || m[2] === "em" ? 16 : m[2] === "%" ? 10 : 1)+}++export function applyRadii(base: Corners, body: string): Corners {+ let corners = [...base]+ if (/@include|@apply|\$\{|#\{|@\{|\.\.\.|(?:^|\n)\s*\+[\w-]+/.test(body)) corners = unknown()+ for (const [prop, value] of declarations(body)) {+ const key = prop.replace(/-/g, "").toLowerCase()+ if (key === "borderradius") {+ const vals = value.replace(/^['"`]|['"`]$/g, "").split("/")[0]?.trim().split(/\s+/).map(radiusPx) ?? []+ const [a = null, b = a, c = a, d = b] = vals+ corners = [a, b, c, d]+ } else {+ const at = ["bordertopleftradius", "bordertoprightradius", "borderbottomrightradius", "borderbottomleftradius"].indexOf(key)+ const logical = ["borderstartstartradius", "borderstartendradius", "borderendendradius", "borderendstartradius"].indexOf(key)+ if (at >= 0 || logical >= 0) corners[at >= 0 ? at : logical] = radiusPx(value)+ }+ }+ return corners+}++function utilityCorners(text: string): Corners {+ const entries = [...text.matchAll(/(?:^|[\s"'`{}])((?:[\w-]+:)*)(rounded(?:-(tl|tr|br|bl|ss|se|ee|es|t|r|b|l|s|e))?(?:-([a-z0-9-]+|\[[^\]]*\]|\([^)]*\)))?)(?=$|[\s"'`{}])/g)]+ let corners = zero()+ const scale: Readonly<Record<string, number>> = { none: 0, xs: 2, sm: 4, "": 4, md: 6, lg: 8, xl: 12, "2xl": 16, "3xl": 24, "4xl": 32, full: 9999 }+ entries.sort((a, b) => (a[3]?.length ?? 0) - (b[3]?.length ?? 0))+ for (const entry of entries) {+ const size = entry[4] ?? ""+ const value = scale[size] ?? (size.startsWith("[") ? radiusPx(size.slice(1, -1)) : null)+ const indices = radiusIndices[entry[3] ?? ""] ?? [0, 1, 2, 3]+ for (const i of indices) {+ const before = corners[i]+ corners[i] = entry[1] ? before === null || value === null ? null : Math.max(before ?? 0, value) : value+ }+ }+ return corners+}++export function roundedAway(corners: Corners, side: string): boolean {+ const away = side === "left" || side === "start" || side === "l" || side === "s" ? [1, 2] : side === "right" || side === "end" || side === "r" || side === "e" ? [0, 3] : side === "top" ? [3, 2] : [0, 1]+ return away.some((i) => corners[i] === null) || away.every((i) => (corners[i] ?? 0) >= 4)+}++export function scopeCorners(scope: CssScope, scopes: readonly CssScope[], host = selectorHost(scope)): Corners {+ let corners: Corners = zero()+ let declared = false+ for (const item of scopes) {+ if (selectorMatches(selectorHost(item), host)) {+ const body = item.body+ if (/\bborder[-\w]*radius\s*:|\bborder\w*Radius\s*:|@include|@apply|\$\{|(?:^|\n)\s*\+[\w-]+/.test(body)) declared = true+ corners = applyRadii(corners, body)+ }+ }+ if (declared) return corners+ const sheet: (number | null)[] = zero()+ for (const item of scopes) {+ const own = applyRadii(zero(), item.body)+ for (let i = 0; i < 4; i++) sheet[i] = sheet[i] === null || own[i] === null ? null : Math.max(sheet[i] ?? 0, own[i] ?? 0)+ }+ return sheet+}++export function tagCorners(tag: string, styleText: string, imports: boolean): Corners {+ let corners = utilityCorners(tag)+ if (/\{\s*\.\.\.|(?:className|class|tw)\s*=\s*\{[^}]*[?:]|(?:className|class|tw)\s*=\s*\{\s*[\w$]+\s*\}|(?:v-bind:class|:class|class:)/.test(tag)) corners = unknown()+ const classText = /(?:className|class|tw)\s*=\s*["']([^"']*)/.exec(tag)?.[1] ?? ""+ if (!/\brounded(?:[-\s"']|$)/.test(tag)) {+ const scopes = cssScopes(styleText)+ const tagName = /^<([\w-]+)/.exec(tag)?.[1] ?? ""+ const matching = scopes.filter((s) => {+ const host = cleanSelector(selectorHost(s))+ if (/::?(?:before|after)/.test(s.selector)) return false+ const tail = host.split(/[ >+~]+/).at(-1) ?? ""+ const classes = [...tail.matchAll(/\.([\w-]+)/g)].map((m) => m[1] ?? "")+ return classes.length > 0 ? classes.every((c) => classText.split(/\s/).includes(c)) : tail === tagName+ })+ const styled = new RegExp(`\\b(?:const|let)\\s+${tagName}\\s*=\\s*styled[^\\x60]*\\x60([^\\x60]*)\\x60`).exec(styleText)?.[1]+ if (styled) corners = applyRadii(corners, styled)+ else if (matching.length) for (const s of matching) corners = applyRadii(corners, s.body)+ else if (imports || /border-radius\s*:\s*(?:var|\$|@)|@apply|@include/.test(styleText)) corners = unknown()+ }+ for (const m of tag.matchAll(/\b(borderRadius|border(?:Top|Bottom)(?:Left|Right)Radius|rounded)\s*=\s*(?:["']([^"']*)["']|\{([^}]*)\})/g)) {+ const value = m[2] ?? m[3] ?? ""+ corners = m[1] === "rounded" ? value === "none" || value === "0" ? zero() : unknown() : applyRadii(corners, `${m[1]}:${value}`)+ }+ const style = /\bstyle\s*=\s*["']([^"']*)["']/.exec(tag)?.[1]+ const object = /\b(?:style|sx)\s*=\s*\{\{([\s\S]*)\}\}/.exec(tag)?.[1]+ if (style ?? object) corners = applyRadii(corners, style ?? object ?? "")+ else if (/\bstyle\s*=\s*\{/.test(tag)) corners = unknown()+ return corners+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/support/css-effects.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/css-effects.tsnew file mode 100644index 00000000..7a452e4a--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/css-effects.ts@@ -0,0 +1,81 @@+import { luminance } from "../../../core/color"+import { cssScopes, declarations } from "./css-scopes"+import { authoredColor, authoredColors } from "./source-color"++export function resolveValues(text: string): string {+ const tokens = new Map([...text.matchAll(/(--[\w-]+)\s*:\s*([^;{}]+)/g)].map((m) => [m[1] ?? "", m[2] ?? ""]))+ let out = text+ for (let i = 0; i < 8; i++) {+ const next = out.replace(/var\(\s*(--[\w-]+)\s*(?:,\s*([^)]*))?\)/g, (whole: string, name: string, fallback: string | undefined) => tokens.get(name) ?? fallback ?? whole)+ if (out === next) break+ out = next+ }+ return out+}++export function darkBackground(text: string): boolean {+ const resolved = resolveValues(text)+ if (/\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/.test(resolved)) return true+ const dark = (value: string): boolean => {+ const color = authoredColor(value.trim())+ return color !== null && color.a > 0.5 && luminance(color) < 0.1+ }+ for (const m of resolved.matchAll(/(?<![-\w])background(?:-color)?\s*:\s*([^;{}]+)/gi)) {+ const value = (m[1] ?? "").trim()+ if (/^(?:#(?:[01][0-9a-f]{5}|2[0-3][0-9a-f]{4}|[01][0-9a-f]{2})\b|rgb\(\s*\d{1,2}\s*,\s*\d{1,2}\s*,\s*\d{1,2}\s*\))/i.test(value) && dark(value)) return true+ }+ const roots = [+ ...[...resolved.matchAll(/(?:^|[}\s,;>])(?:body|html|:root)\s*(?:,[^{]*)?\{([^}]*)\}/gi)].map((m) => m[1] ?? ""),+ ...[...resolved.matchAll(/<body[^>]*\bstyle\s*=\s*"([^"]*)"/gi)].map((m) => m[1] ?? ""),+ ]+ return roots.some((scope) => [...scope.matchAll(/(?<![-\w])background(?:-color)?\s*:\s*([^;{}]+)/gi)].some((m) => dark(m[1] ?? "")))+}++export function haloOffsets(text: string): readonly number[] {+ if (!darkBackground(text)) return []+ const resolved = resolveValues(text)+ const offsets: number[] = []+ for (const m of resolved.matchAll(/(?<![-\w])background(?:-image)?\s*:\s*([^;{}]+)/gi)) {+ const value = m[1] ?? ""+ if (/url\s*\(/i.test(value)) continue+ for (const g of value.matchAll(/(?<!repeating-)radial-gradient\(/gi)) {+ let end = (g.index ?? 0) + g[0].length+ let depth = 1+ for (; end < value.length && depth > 0; end++) {+ if (value[end] === "(") depth+++ else if (value[end] === ")") depth--+ }+ const gradient = value.slice(g.index, end)+ if ([...gradient.matchAll(/(-?[\d.]+)px\b/g)].some((p) => Math.abs(Number(p[1])) <= 24)) continue+ const colors = authoredColors(gradient)+ const first = colors[0]+ const last = /\btransparent\s*(?:[\d.%\s]*)\)$/.test(gradient) ? { a: 0 } : colors.at(-1)+ if (!first || !last || first.a < 0.7 || last.a > 0.05 || Math.max(first.r, first.g, first.b) - Math.min(first.r, first.g, first.b) < 24) continue+ offsets.push(m.index ?? 0)+ }+ }+ return offsets+}++export function marqueeSelectors(text: string): readonly string[] {+ const names: string[] = []+ for (const m of text.matchAll(/@(?:-webkit-)?keyframes\s+([\w-]+)\s*\{/g)) {+ let depth = 1+ let end = (m.index ?? 0) + m[0].length+ for (; end < text.length && depth > 0; end++) {+ if (text[end] === "{") depth+++ else if (text[end] === "}") depth--+ }+ const body = text.slice((m.index ?? 0) + m[0].length, end)+ if (/\btranslate(?:X)?\([^)]*(?:-?100|-?50)%/i.test(body)) names.push(m[1] ?? "")+ }+ const found = new Set<string>()+ if (/<marquee\b/i.test(text)) found.add("marquee")+ for (const scope of cssScopes(text)) {+ const d = declarations(scope.body)+ const animation = d.get("animation") ?? ""+ if (!/\binfinite\b/.test(animation + " " + (d.get("animation-iteration-count") ?? ""))) continue+ for (const name of names) if ((animation + " " + (d.get("animation-name") ?? "")).split(/[,\s]+/).includes(name)) found.add(`${scope.selector} ${name}`)+ }+ return [...found]+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/support/css-scopes.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/css-scopes.tsnew file mode 100644index 00000000..63c29183--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/css-scopes.ts@@ -0,0 +1,131 @@+export type CssScope = {+ readonly selector: string+ readonly start: number+ readonly end: number+ readonly body: string+ readonly parent: CssScope | null+}++export function cssScopes(text: string, sass = false): readonly CssScope[] {+ if (sass) return sassScopes(text)+ const scopes: CssScope[] = []+ const stack: { selector: string; start: number; content: number; boundary: number; parent: number | null }[] = []+ let quote = ""+ let boundary = 0+ for (let i = 0; i < text.length; i++) {+ const ch = text[i]+ if (quote) {+ if (ch === "\\") i+++ else if (ch === quote) quote = ""+ continue+ }+ if (ch === '"' || ch === "'") { quote = ch; continue }+ if (ch === "{") {+ if (/[$#@]/.test(text[i - 1] ?? "")) {+ let depth = 1+ while (++i < text.length && depth > 0) {+ if (text[i] === "{") depth+++ if (text[i] === "}") depth--+ }+ if (/^\s*(?:&|@|[.#])/.test(text.slice(i))) {+ const parent = stack.at(-1)+ if (parent) parent.boundary = i+ else boundary = i+ }+ i--+ continue+ }+ const from = stack.at(-1)?.boundary ?? boundary+ const raw = text.slice(from, i)+ const selector = raw.trim()+ const at = from + raw.length - raw.trimStart().length+ stack.push({ selector, start: at, content: i + 1, boundary: i + 1, parent: stack.at(-1)?.content ?? null })+ } else if (ch === "}") {+ const open = stack.pop()+ if (open) scopes.push({ selector: open.selector, start: open.start, end: i, body: text.slice(open.content, i), parent: null })+ const parent = stack.at(-1)+ if (parent) parent.boundary = i + 1+ else boundary = i + 1+ } else if (ch === ";" || ch === "`") {+ const parent = stack.at(-1)+ if (parent) parent.boundary = i + 1+ else boundary = i + 1+ }+ }+ const rootBody = text.replace(/\{[\s\S]*\}/g, "")+ if (/^\s*(?:[-\w]+\s*:|\$\{)/.test(text) || /^\s*(?:position|border|padding|color|background)[-\w]*\s*:/.test(rootBody)) scopes.push({ selector: "&", start: 0, end: text.length, body: text, parent: null })+ const ordered: CssScope[] = []+ for (const scope of scopes.sort((a, b) => a.start - b.start || b.end - a.end)) {+ ordered.push({ ...scope, parent: ordered.filter((p) => p.start <= scope.start && p.end > scope.end).sort((a, b) => b.start - a.start)[0] ?? null })+ }+ return ordered+}++function sassScopes(text: string): readonly CssScope[] {+ const rows = [...text.matchAll(/^.*$/gm)].map((m) => ({ line: m[0], offset: m.index ?? 0 }))+ const scopes: CssScope[] = []+ for (const [i, row] of rows.entries()) {+ const selector = row.line.trim()+ if (!selector || /^(?:[-\w]+\s*:|\$|\/\/)/.test(selector)) continue+ const indent = row.line.length - row.line.trimStart().length+ let end = text.length+ for (const next of rows.slice(i + 1)) {+ if (next.line.trim() && next.line.length - next.line.trimStart().length <= indent) { end = next.offset; break }+ }+ const bodyRows = rows.slice(i + 1).filter((r) => r.offset < end && r.line.trim())+ const level = Math.min(...bodyRows.map((r) => r.line.length - r.line.trimStart().length))+ const body = bodyRows.filter((r) => r.line.length - r.line.trimStart().length === level).map((r) => r.line).join("\n")+ scopes.push({ selector, start: row.offset + indent, end, body, parent: null })+ }+ const ordered: CssScope[] = []+ for (const s of scopes) ordered.push({ ...s, parent: ordered.filter((p) => p.start < s.start && p.end >= s.end).sort((a, b) => b.start - a.start)[0] ?? null })+ return ordered+}++export function declarations(body: string): ReadonlyMap<string, string> {+ const out = new Map<string, string>()+ let quote = ""+ let parens = 0+ let braces = 0+ let start = 0+ const push = (end: number): void => {+ const m = /^\s*["']?([-\w]+)["']?\s*:\s*([\s\S]*)$/.exec(body.slice(start, end))+ if (m?.[1] && m[2] !== undefined) out.set(m[1], m[2].trim().replace(/\s*!important\s*$/i, ""))+ }+ for (let i = 0; i < body.length; i++) {+ const ch = body[i]+ if (quote) {+ if (ch === "\\") i+++ else if (ch === quote) quote = ""+ } else if (ch === "'" || ch === '"' || ch === "`") quote = ch+ else if (ch === "(" || ch === "[") parens+++ else if (ch === ")" || ch === "]") parens--+ else if (ch === "{") braces+++ else if (ch === "}") {+ braces--+ if (braces === 0) start = i + 1+ } else if ((ch === ";" || ch === "\n" || ch === ",") && parens === 0 && braces === 0) { push(i); start = i + 1 }+ }+ if (start < body.length) push(body.length)+ return out+}++export function selectorHost(scope: CssScope): string {+ if (!scope.parent) return scope.selector+ const parent = selectorHost(scope.parent)+ if (scope.selector.startsWith("@") || scope.selector.startsWith("+")) return parent+ return scope.selector.includes("&") ? scope.selector.replace(/&/g, parent) : scope.selector+}++export const cleanSelector = (selector: string): string => selector.replace(/::?(?:before|after)\b/g, "").replace(/:(?:hover|focus|active|visited)(?:-[\w-]+)?/g, "").trim()++export function selectorMatches(base: string, target: string): boolean {+ return base.split(",").some((part) => {+ const a = cleanSelector(part.trim())+ const b = cleanSelector(target.trim())+ if (/::?(?:before|after)/.test(part) !== /::?(?:before|after)/.test(target)) return false+ if (a === b) return true+ const tokens = a.match(/\[[^\]]+\]|[.#][\w-]+|^[a-z][\w-]*/g)+ return tokens !== null && tokens.every((token) => b.includes(token)) && !/[ >+~]/.test(a)+ })+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/support/image-tags.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/image-tags.tsnew file mode 100644index 00000000..ff108355--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/image-tags.ts@@ -0,0 +1,113 @@+function closingBrace(text: string, start: number): number {+ let depth = 0+ let quote = ""+ for (let i = start; i < text.length; i++) {+ const ch = text[i]+ if (quote) {+ if (ch === "\\") i+++ else if (ch === quote) quote = ""+ } else if (ch === "'" || ch === '"' || ch === "`") quote = ch+ else if (ch === "{") depth+++ else if (ch === "}" && --depth === 0) return i+ }+ return text.length+}++export function imageTags(text: string, script: boolean): readonly { readonly tag: string; readonly offset: number }[] {+ const images: { tag: string; offset: number }[] = []+ let depth = 0+ for (let i = 0; i < text.length; i++) {+ const ch = text[i]+ if (ch === "{" && depth > 0) {+ const end = closingBrace(text, i)+ images.push(...imageTags(text.slice(i + 1, end), true).map((hit) => ({ tag: hit.tag, offset: i + 1 + hit.offset })))+ i = end+ continue+ }+ if ((script && depth === 0) && (ch === '"' || ch === "'" || ch === "`")) {+ const quote = ch+ while (++i < text.length) {+ if (text[i] === "\\") i+++ else if (text[i] === quote) break+ }+ continue+ }+ if (script && depth === 0 && ch === "/" && /(?:^|[=(:,!&|?;{}]|\breturn)\s*$/.test(text.slice(0, i))) {+ let bracket = false+ while (++i < text.length) {+ if (text[i] === "\\") i+++ else if (text[i] === "[") bracket = true+ else if (text[i] === "]") bracket = false+ else if (text[i] === "/" && !bracket) break+ }+ continue+ }+ if (ch !== "<" || !/^<\/?[A-Za-z_$\u0080-\uffff>]/.test(text.slice(i, i + 3))) continue+ const start = i+ let quote = ""+ for (; i < text.length && i - start < 8192; i++) {+ const c = text[i]+ if (quote) {+ if (c === "\\") i+++ else if (c === quote) quote = ""+ } else if (c === '"' || c === "'") quote = c+ else if (c === "{") {+ const end = closingBrace(text, i)+ images.push(...imageTags(text.slice(i + 1, end), script).map((hit) => ({ tag: hit.tag, offset: i + 1 + hit.offset })))+ i = end+ } else if (c === ">") break+ }+ const tag = text.slice(start, i + 1)+ if (/^<img\b/i.test(tag) && tag.endsWith(">")) images.push({ tag, offset: start })+ if (/^<\/(?:[A-Za-z_$]|>)/.test(tag)) depth = Math.max(0, depth - 1)+ else if (!/\/>$/.test(tag) && !/^<(?:img|input|br|hr|meta|link)\b/i.test(tag)) depth+++ if (/^<(?:script|style)\b/i.test(tag)) {+ const end = new RegExp(`</${/^<(\w+)/.exec(tag)?.[1] ?? ""}\\s*>`, "gi")+ end.lastIndex = i + 1+ const close = end.exec(text)+ if (close) { i = close.index + close[0].length - 1; depth = Math.max(0, depth - 1) }+ }+ }+ return images+}++export function missingImageSource(tag: string, ext: string): boolean {+ let i = 4+ while (i < tag.length) {+ while (/[\s/]/.test(tag[i] ?? "")) i+++ if (i >= tag.length || tag[i] === ">") break+ if (tag[i] === "{") {+ const end = closingBrace(tag, i)+ const expression = tag.slice(i + 1, end).trim()+ if (/^\.\.\./.test(expression) || (["svelte", "astro"].includes(ext) && /^(?:src|srcset)$/.test(expression))) return false+ i = end + 1+ continue+ }+ const start = i+ while (i < tag.length && !/[\s=/>]/.test(tag[i] ?? "")) i+++ const name = tag.slice(start, i)+ const base = name.split(".")[0] ?? ""+ const source = /(?:^|[:-])(?:src|srcset)$/i.test(base)+ if (ext === "vue" && ((source && name.includes(":")) || name === "v-bind")) return false+ while (/\s/.test(tag[i] ?? "")) i+++ if (tag[i] !== "=") {+ if (source && name.includes(":")) return false+ if (i === start) i+++ continue+ }+ i+++ while (/\s/.test(tag[i] ?? "")) i+++ if (tag[i] === "{") {+ i = closingBrace(tag, i) + 1+ if (source) return false+ continue+ }+ const quote = tag[i] === "'" || tag[i] === '"' ? tag[i++] : null+ const valueStart = i+ while (i < tag.length && (quote ? tag[i] !== quote : !/[\s>]/.test(tag[i] ?? ""))) i+++ const value = tag.slice(valueStart, i).trim()+ if (quote) i+++ if (source && value && value !== "#") return false+ }+ return true+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/support/js-punctuation.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/js-punctuation.tsnew file mode 100644index 00000000..a8739cc3--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/js-punctuation.ts@@ -0,0 +1,34 @@+type Punctuation = { readonly ch: string; readonly at: number; readonly paren: number; readonly brace: number }++export function* jsPunctuation(text: string): Generator<Punctuation> {+ let quote = ""+ let template = false+ let paren = 0+ let brace = 0+ const interpolations: number[] = []+ for (let at = 0; at < text.length; at++) {+ const ch = text[at] ?? ""+ if (quote) {+ if (ch === "\\") at+++ else if (ch === quote) quote = ""+ continue+ }+ if (template && interpolations.length === 0) {+ if (ch === "\\") at+++ else if (ch === "$" && text[at + 1] === "{") { interpolations.push(++brace); at++ }+ else if (ch === "`") template = false+ continue+ }+ if (ch === '"' || ch === "'") { quote = ch; continue }+ if (ch === "`") { template = true; continue }+ if (ch === "(") { paren++; continue }+ if (ch === ")") { paren--; continue }+ if (ch === "{") { brace++; continue }+ if (ch === "}") {+ brace--+ if (interpolations.length > 0 && brace < (interpolations.at(-1) ?? 0)) interpolations.pop()+ continue+ }+ yield { ch, at, paren, brace }+ }+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/support/markup-scope.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/markup-scope.tsnew file mode 100644index 00000000..d921769d--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/markup-scope.ts@@ -0,0 +1,44 @@+import { jsPunctuation } from "./js-punctuation"++export function tagAt(text: string, index: number): string {+ for (const m of text.matchAll(/<[a-z][\w:.-]*(?:[^"'`{}>]|"[^"]*"|'[^']*'|`[^`]*`|\{(?:[^{}]|\{[^{}]*\})*\})*>/gi)) {+ if ((m.index ?? 0) <= index && index <= (m.index ?? 0) + m[0].length) return m[0]+ }+ return text+}++export function exclusiveScopes(text: string): readonly string[] {+ let question = -1+ let paren = 0+ let brace = 0+ let colon = -1+ let nested = 0+ let end = text.length+ for (const token of jsPunctuation(text)) {+ const sameDepth = token.paren === paren && token.brace === brace+ const isQuestion = token.ch === "?" && !/[?.]/.test(text[token.at - 1] ?? "") && !/[?.]/.test(text[token.at + 1] ?? "")+ if (colon >= 0) {+ if (token.ch === "," && sameDepth) { end = token.at; break }+ } else if (question < 0 && isQuestion) {+ question = token.at+ paren = token.paren+ brace = token.brace+ } else if (question >= 0 && isQuestion && sameDepth) nested+++ else if (question >= 0 && token.ch === ":" && sameDepth) {+ if (nested > 0) nested--+ else colon = token.at+ }+ }+ if (question < 0 || colon < 0) return [text]+ return [text.slice(question + 1, colon), text.slice(colon + 1, end)].flatMap((part) => exclusiveScopes(part).map((arm) => text.slice(0, question) + arm + text.slice(end)))+}++export function solidBackground(scope: string, gray = false): string | null {+ for (const m of scope.matchAll(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(\d+)\b/g)) {+ const at = m.index ?? 0+ const prefix = scope.slice(0, at).split(/\s/).at(-1) ?? ""+ const state = /(?:^|:)(?:!?hover|focus(?:-visible|-within)?|active|visited|disabled|checked|open|enabled|invalid|placeholder|group-[^:]*|peer-[^:]*|aria-[^:]*|data-[^:]*):$/.test(prefix)+ if (scope[at + m[0].length] !== "/" && !state && (!gray || Number(m[1]) >= 200)) return m[0]+ }+ return null+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/support/source-color.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/source-color.tsnew file mode 100644index 00000000..05e5edfe--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/source-color.ts@@ -0,0 +1,42 @@+import { parseColor, type Rgba } from "../../../core/color"++const named: Readonly<Record<string, string>> = {+ black: "#000", white: "#fff", gray: "#808080", grey: "#808080", silver: "#c0c0c0", dimgray: "#696969", dimgrey: "#696969", darkgray: "#a9a9a9", darkgrey: "#a9a9a9",+ lightgray: "#d3d3d3", lightgrey: "#d3d3d3", gainsboro: "#dcdcdc", whitesmoke: "#f5f5f5", red: "#f00", blue: "#00f", green: "#008000", lime: "#0f0", yellow: "#ff0",+ orange: "#ffa500", purple: "#800080", rebeccapurple: "#663399", pink: "#ffc0cb", teal: "#008080", cyan: "#0ff", aqua: "#0ff", magenta: "#f0f", fuchsia: "#f0f", coral: "#ff7f50", crimson: "#dc143c", navy: "#000080", maroon: "#800000", olive: "#808000",+}++export function authoredColor(value: string): Rgba | null {+ const text = value.trim().toLowerCase()+ const parsed = parseColor(named[text] ?? text)+ if (parsed) return parsed+ const match = /^(hsla?|hwb)\((.*)\)$/.exec(text)+ if (!match) return null+ const parts = (match[2] ?? "").replace(/[,/]/g, " ").split(/\s+/).filter(Boolean)+ const hue = Number.parseFloat(parts[0] ?? "0") / (parts[0]?.endsWith("turn") ? 1 : parts[0]?.endsWith("rad") ? 2 * Math.PI : 360)+ const s = Number.parseFloat(parts[1] ?? "0") / 100+ const l = Number.parseFloat(parts[2] ?? "0") / 100+ const alpha = parts[3]+ const a = alpha === undefined ? 1 : Number.parseFloat(alpha) / (alpha.endsWith("%") ? 100 : 1)+ const channel = (n: number): number => {+ const k = ((n + hue * 12) % 12 + 12) % 12+ return l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k - 3, 9 - k, 1))+ }+ if (match[1] !== "hwb") return { r: channel(0) * 255, g: channel(8) * 255, b: channel(4) * 255, a }+ if (s + l >= 1) return { r: 255 * s / (s + l), g: 255 * s / (s + l), b: 255 * s / (s + l), a }+ const pure = authoredColor(`hsl(${hue * 360} 100% 50%)`)+ return pure ? { r: pure.r * (1 - s - l) + 255 * s, g: pure.g * (1 - s - l) + 255 * s, b: pure.b * (1 - s - l) + 255 * s, a } : null+}++export function authoredColors(value: string): readonly Rgba[] {+ return [...value.matchAll(/(?:rgba?|hsla?|hwb|color|oklab|oklch)\([^()]*\)|#[0-9a-f]{3,8}\b|\b[a-z]+\b/gi)].flatMap((m) => {+ const color = authoredColor(m[0])+ return color ? [color] : []+ })+}++export function chromatic(value: string): boolean {+ const color = authoredColor(value) ?? authoredColors(value)[0]+ if (color) return color.a >= 0.1 && Math.max(color.r, color.g, color.b) - Math.min(color.r, color.g, color.b) >= 30+ return !/\b(?:transparent|currentcolor|black|white|gr[ae]y|silver|gainsboro|whitesmoke)\b|url\(/i.test(value)+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/support/source-shadow.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/source-shadow.tsnew file mode 100644index 00000000..85e4dec7--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/source-shadow.ts@@ -0,0 +1,15 @@+import { parseShadow, type ShadowLayer } from "../../../core/shadow"+import { authoredColor } from "./source-color"++export function sourceShadows(value: string, status = false): readonly ShadowLayer[] {+ const filled = value.replace(/var\([^)]*\)|(?:rgba?|hsla?|hwb|color|oklab|oklch)\([^()]*\)|#[0-9a-f]{3,8}\b|\b[a-z]+\b(?!\s*\()/gi, (token) => {+ if (token.toLowerCase() === "inset" || token.toLowerCase() === "px") return token+ if (token.startsWith("var(")) {+ const colored = /(?:^|-)(?:accent|kinpaku|patina|gold|red|orange|amber|yellow|lime|green|emerald|teal|cyan|blue|indigo|violet|purple|magenta|pink|rose|coral|aqua|mint|burgundy|crimson|scarlet)(?:-|[);])/i.test(token) || (status && /danger|error|warning|success|broken/.test(token))+ return colored ? "#d0342c" : "#000"+ }+ const c = authoredColor(token)+ return c ? `rgba(${c.r}, ${c.g}, ${c.b}, ${c.a})` : token+ })+ return parseShadow(filled)+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/source/support/source-text.ts b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/source-text.tsnew file mode 100644index 00000000..e12f1078--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/source/support/source-text.ts@@ -0,0 +1,110 @@+import { extensionOf, lineAt, positionAt } from "../../../core/source"+import type { SourceContext, SourceHit } from "../../../rule"++export const sourceExtensions = ["css", "scss", "sass", "less", "js", "jsx", "ts", "tsx", "mjs", "cjs", "vue", "svelte", "astro"]+export const componentExtensions = ["vue", "svelte", "astro"]+export const sheetExtensions = ["css", "scss", "sass", "less"]+export type SourcePass = { readonly text: string; readonly offset: number; readonly css: boolean; readonly sass: boolean }+export type LineMatch = {+ readonly match: RegExpMatchArray+ readonly line: string+ readonly scope: string+ readonly offset: number+ readonly pass: SourcePass+ readonly source: string+ readonly context: SourceContext+}++const blank = (text: string): string => text.replace(/[^\n\r]/g, " ")++export function stripComments(text: string, script: boolean): string {+ let out = ""+ let quote = ""+ for (let i = 0; i < text.length; i++) {+ const ch = text[i] ?? ""+ const next = text[i + 1]+ if (quote) {+ out += ch+ if (ch === "\\") out += text[++i] ?? ""+ else if (ch === quote) quote = ""+ continue+ }+ if (ch === '"' || ch === "'" || (script && ch === "`")) {+ quote = ch+ out += ch+ } else if (ch === "/" && next === "*") {+ const end = text.indexOf("*/", i + 2)+ const stop = end < 0 ? text.length : end + 2+ out += blank(text.slice(i, stop))+ i = stop - 1+ } else if (ch === "/" && next === "/" && text[i - 1] !== ":") {+ const end = text.indexOf("\n", i)+ const stop = end < 0 ? text.length : end+ out += blank(text.slice(i, stop))+ i = stop - 1+ } else if (text.startsWith("<!--", i)) {+ const end = text.indexOf("-->", i + 4)+ const stop = end < 0 ? text.length : end + 3+ out += blank(text.slice(i, stop))+ i = stop - 1+ } else out += ch+ }+ return out+}++export function sourcePasses(context: SourceContext): readonly SourcePass[] {+ const ext = extensionOf(context.file.path)+ const css = sheetExtensions.includes(ext)+ const text = stripComments(context.file.text, !css)+ const passes: SourcePass[] = [{ text, offset: 0, css, sass: ext === "sass" }]+ if (componentExtensions.includes(ext)) {+ for (const m of text.matchAll(/<style\b([^>]*)>([\s\S]*?)<\/style\s*>/gi)) {+ const body = m[2] ?? ""+ passes.push({ text: stripComments(body, false), offset: (m.index ?? 0) + m[0].indexOf(">") + 1, css: true, sass: /\blang\s*=\s*["']sass["']/.test(m[1] ?? "") })+ }+ }+ if (["js", "jsx", "ts", "tsx"].includes(ext)) {+ for (const m of text.matchAll(/(?:\bstyled(?:\s*\([^`]*?\)|\.[\w.]+)(?:\([^`]*?\))?|\bcss|\bcreateGlobalStyle|<style\s+jsx[^>]*>\s*\{)\s*`([\s\S]*?)`/g)) {+ const body = m[1] ?? ""+ passes.push({ text: stripComments(body, false), offset: (m.index ?? 0) + m[0].indexOf("`") + 1, css: true, sass: false })+ }+ }+ let source = text+ for (const pass of passes.slice(1)) source = source.slice(0, pass.offset) + pass.text + source.slice(pass.offset + pass.text.length)+ return [{ text: source, offset: 0, css, sass: ext === "sass" }, ...passes.slice(1)]+}++export function sourceHit(text: string, offset: number, message: string, snippet = lineAt(text, offset)): SourceHit {+ return { ...positionAt(text, offset), message, snippet }+}++export function lineCheck(patterns: readonly RegExp[], test: (match: LineMatch) => string | null): (context: SourceContext) => readonly SourceHit[] {+ return (context) => {+ const hits: SourceHit[] = []+ for (const pass of sourcePasses(context)) {+ const lines = pass.text.split("\n")+ let start = 0+ for (const [i, line] of lines.entries()) {+ const scope = pass.css ? lines.slice(Math.max(0, i - 3), i + 4).join(" ") : line+ for (const pattern of patterns) {+ for (const match of line.matchAll(pattern)) {+ const offset = start + (match.index ?? 0)+ const message = test({ match, line, scope, offset, pass, source: pass.text, context })+ if (message === null) continue+ const hit = sourceHit(context.file.text, pass.offset + offset, message, message)+ if (!hits.some((h) => h.snippet === hit.snippet && Math.abs(h.line - hit.line) <= 2)) hits.push(hit)+ }+ }+ start += line.length + 1+ }+ }+ return hits+ }+}++export function pageSource(context: SourceContext): string | null {+ if (!componentExtensions.includes(extensionOf(context.file.path))) return null+ return /<!doctype\s|<html[\s>]|<head[\s>]/i.test(context.file.text.replace(/<!--[\s\S]*?-->/g, "")) ? context.file.text : null+}++export const bodyText = (text: string): string => text.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, " ").replace(/<!--[\s\S]*?-->/g, " ").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ")diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/all-caps-body.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/all-caps-body.tsnew file mode 100644index 00000000..40dc09fd--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/all-caps-body.ts@@ -0,0 +1,15 @@+import { isHeading, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { visibleText } from "./support/text-context"++export const allCapsBody: PageRule = {+ meta: {+ id: "all-caps-body", name: "All-caps body text", category: "quality", severity: "warning", engine: "page",+ description: "Uppercase sentences lose the word shapes readers use to scan prose.",+ fixHint: "Set running copy in sentence case; keep uppercase for headings and short labels.",+ },+ check: ({ snapshot }) => snapshot.elements.filter(e =>+ visibleText(snapshot, e) && isHeading(e) === false && styleOf(e, "text-transform") === "uppercase" &&+ e.ownText.trim().replace(/\s+/g, " ").length >= 80)+ .map(element => ({ element, message: "Uppercase on 80 or more characters of body copy", snippet: shortSnippet(element) })),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/design-system-font-size.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/design-system-font-size.tsnew file mode 100644index 00000000..bf7897ea--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/design-system-font-size.ts@@ -0,0 +1,23 @@+import { fontSizePx, shortSnippet } from "../../core/page"+import type { PageRule } from "../../rule"+import { visibleText } from "./support/text-context"++export const designSystemFontSize: PageRule = {+ meta: {+ id: "design-system-font-size", name: "Font size outside DESIGN.md", category: "quality", severity: "advisory", engine: "page",+ description: "A rendered font size is outside the configured type ramp.",+ fixHint: "Use a configured size token or add the intentional step to designTokens.fontSizes.",+ },+ check: ({ snapshot, config }) => {+ const allowed = config.designTokens?.fontSizes+ if (allowed === undefined || allowed.length === 0) return []+ const seen = new Set<number>()+ return snapshot.elements.flatMap(element => {+ const size = fontSizePx(element)+ if (visibleText(snapshot, element) === false || element.ownText.trim() === "" ||+ size <= 0 || allowed.some(n => Math.abs(n - size) <= 0.5) || seen.has(size)) return []+ seen.add(size)+ return [{ element, message: `${size}px is outside configured type ramp`, snippet: shortSnippet(element) }]+ })+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/design-system-font.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/design-system-font.tsnew file mode 100644index 00000000..ebe28b69--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/design-system-font.ts@@ -0,0 +1,24 @@+import { shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { normalizeFont, primaryFont } from "./support/font-family"+import { visibleText } from "./support/text-context"++export const designSystemFont: PageRule = {+ meta: {+ id: "design-system-font", name: "Font outside DESIGN.md", category: "quality", severity: "warning", engine: "page",+ description: "A text face is absent from the configured typography tokens.",+ fixHint: "Use a configured font token or add the intentional face to designTokens.fonts.",+ },+ check: ({ snapshot, config }) => {+ const allowed = config.designTokens?.fonts?.map(normalizeFont)+ if (allowed === undefined || allowed.length === 0) return []+ const seen = new Set<string>()+ return snapshot.elements.flatMap(element => {+ const family = primaryFont(styleOf(element, "font-family"), true)+ if (visibleText(snapshot, element) === false || element.ownText.trim() === "" ||+ family === "" || allowed.includes(family) || seen.has(family)) return []+ seen.add(family)+ return [{ element, message: `Font ${family} is outside configured tokens`, snippet: shortSnippet(element) }]+ })+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/extreme-negative-tracking.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/extreme-negative-tracking.tsnew file mode 100644index 00000000..1bc55cf9--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/extreme-negative-tracking.ts@@ -0,0 +1,18 @@+import { fontSizePx, px, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { cjk, visibleText } from "./support/text-context"++export const extremeNegativeTracking: PageRule = {+ meta: {+ id: "extreme-negative-tracking", name: "Crushed letter spacing", category: "slop", severity: "warning", engine: "page",+ description: "Negative tracking beyond the reading or display threshold damages letter shapes.",+ fixHint: "Keep tracking at or above -0.07em for reading text and -0.09em for display type.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap(element => {+ const size = fontSizePx(element)+ const tracking = (px(styleOf(element, "letter-spacing")) ?? 0) / size+ if (visibleText(snapshot, element) === false || element.ownText.length <= 10 || element.text.length <= 20 ||+ size <= 0 || tracking >= (size >= 40 ? -0.09 : -0.07) || cjk(element.text)) return []+ return [{ element, message: `Letter spacing ${tracking.toFixed(2)}em at ${size}px`, snippet: shortSnippet(element) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/flat-type-hierarchy.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/flat-type-hierarchy.tsnew file mode 100644index 00000000..156193dd--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/flat-type-hierarchy.ts@@ -0,0 +1,26 @@+import { childrenOf, fontSizePx, isHeading } from "../../core/page"+import type { PageRule } from "../../rule"+import { readingTags, visibleText } from "./support/text-context"+import { flatHierarchy } from "./support/type-hierarchy"++export const flatTypeHierarchy: PageRule = {+ meta: {+ id: "flat-type-hierarchy", name: "Flat type hierarchy", category: "slop", severity: "warning", engine: "page",+ description: "Heading and body roles have no adjacent size step of at least 1.25.",+ fixHint: "Add a stronger size step between at least two heading or body roles.",+ },+ check: ({ snapshot }) => {+ const sampled = (tag: string): boolean => /^h[1-6]$/.test(tag) || readingTags.includes(tag)+ const ownChars = (e: (typeof snapshot.elements)[number]): number =>+ e.ownText.replace(/\s/g, "").length + childrenOf(snapshot, e)+ .filter(n => sampled(n.tag) === false && visibleText(snapshot, n))+ .reduce((count, n) => count + ownChars(n), 0)+ const samples = snapshot.elements.filter(e => sampled(e.tag) && e.text.trim() !== "" && visibleText(snapshot, e) &&+ fontSizePx(e) >= 8 && fontSizePx(e) < 200 &&+ (isHeading(e) || [1, 2].includes(ownChars(e)) === false))+ .map(e => ({ role: isHeading(e) ? e.tag : "body", size: fontSizePx(e), weight: Number.parseFloat(e.style["font-weight"] ?? "400") }))+ const roles = flatHierarchy(samples)+ if (roles.length === 0) return []+ return [{ element: null, message: `Flat role sizes: ${roles.map(([r, size]) => `${r} ${size}px`).join(", ")}`, snippet: "All adjacent type steps are below 1.25" }]+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/index.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/index.tsnew file mode 100644index 00000000..7ed69e65--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/index.ts@@ -0,0 +1,21 @@+import type { Rule } from "../../rule"+import { allCapsBody } from "./all-caps-body"+import { designSystemFont } from "./design-system-font"+import { designSystemFontSize } from "./design-system-font-size"+import { extremeNegativeTracking } from "./extreme-negative-tracking"+import { flatTypeHierarchy } from "./flat-type-hierarchy"+import { italicSerifDisplay } from "./italic-serif-display"+import { justifiedText } from "./justified-text"+import { lineLength } from "./line-length"+import { oversizedH1 } from "./oversized-h1"+import { overusedFont } from "./overused-font"+import { tightLeading } from "./tight-leading"+import { tinyText } from "./tiny-text"+import { undersizedUiText } from "./undersized-ui-text"+import { wideTracking } from "./wide-tracking"++export const TYPOGRAPHY_RULES: readonly Rule[] = [+ overusedFont, flatTypeHierarchy, italicSerifDisplay, oversizedH1, extremeNegativeTracking,+ tinyText, undersizedUiText, allCapsBody, wideTracking, tightLeading, justifiedText,+ lineLength, designSystemFont, designSystemFontSize,+]diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/italic-serif-display.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/italic-serif-display.tsnew file mode 100644index 00000000..01ff2668--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/italic-serif-display.ts@@ -0,0 +1,24 @@+import { descendants, fontSizePx, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { visibleText } from "./support/text-context"+import { primaryFont } from "./support/font-family"++const serifNames = ["fraunces", "recoleta", "newsreader", "playfair display", "playfair", "cormorant", "cormorant garamond", "garamond", "eb garamond", "tiempos", "tiempos headline", "tiempos text", "lora", "vollkorn", "spectral", "source serif pro", "source serif 4", "source serif", "ibm plex serif", "merriweather", "libre caslon", "libre baskerville", "baskerville", "georgia", "times new roman", "times", "dm serif display", "dm serif text", "instrument serif", "gt sectra", "ogg", "canela", "freight display", "freight text"]++export const italicSerifDisplay: PageRule = {+ meta: {+ id: "italic-serif-display", name: "Italic serif display headline", category: "slop", severity: "warning", engine: "page",+ description: "An italic serif at hero scale repeats a common landing-page treatment.",+ fixHint: "Use roman type or a non-serif display face unless the brief calls for editorial typography.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap(element => {+ if (["h1", "h2"].includes(element.tag) === false || visibleText(snapshot, element) === false) return []+ const italic = [element, ...descendants(snapshot, element)].some(n => {+ const families = styleOf(n, "font-family").toLowerCase().split(",").map(f => f.trim().replace(/^['"]|['"]$/g, ""))+ const primary = primaryFont(styleOf(n, "font-family"), true)+ return visibleText(snapshot, n) && n.ownText.trim() !== "" && styleOf(n, "font-style") === "italic" &&+ fontSizePx(n) >= 48 && primary !== "" && (serifNames.includes(primary) || families.includes("serif"))+ })+ return italic ? [{ element, message: "Italic serif heading at 48px or larger", snippet: shortSnippet(element) }] : []+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/justified-text.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/justified-text.tsnew file mode 100644index 00000000..9fc19062--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/justified-text.ts@@ -0,0 +1,32 @@+import { ancestors, fontSizePx, px, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { letters, visibleText } from "./support/text-context"+import { mergedLines, phrasingNodes } from "./support/text-lines"++export const justifiedText: PageRule = {+ meta: {+ id: "justified-text", name: "Justified text", category: "quality", severity: "warning", engine: "page",+ description: "Narrow justified columns without automatic hyphenation stretch word spaces into gaps.",+ fixHint: "Align text left, widen the column, or enable hyphens: auto.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap(element => {+ if (visibleText(snapshot, element) === false || element.ownText.length <= 10 ||+ styleOf(element, "text-align") !== "justify" || styleOf(element, "hyphens") === "auto") return []+ let block = element+ if (styleOf(element, "display") === "inline") {+ const ancestor = [...ancestors(snapshot, element)].find(n => ["inline", "contents"].includes(styleOf(n, "display")) === false)+ if (ancestor === undefined || ancestor.ownText.length > 10) return []+ block = ancestor+ }+ const size = fontSizePx(element)+ if (size <= 0 || block.rect.width <= 0 || block.rect.width / (size * 0.5) > 45) return []+ const lines = mergedLines(phrasingNodes(snapshot, block))+ const first = lines[0]+ if (first && Math.max(...lines.map(l => l.y + l.height)) - first.y <+ (px(styleOf(block, "line-height")) ?? size * 1.2) + size * 0.75) return []+ const chars = letters([...element.ownText].slice(0, 400).join(""))+ const exempt = chars.filter(c => /[\u0600-\u06ff\u0750-\u077f\u08a0-\u08ff\u0e00-\u0e7f\u1100-\u11ff\u2e80-\u9fff\ua960-\ud7ff\uf900-\ufaff\ufb50-\ufdff\ufe70-\ufeff\uff66-\uff9f\u{20000}-\u{3134f}]/u.test(c)).length+ if (exempt * 2 > chars.length) return []+ return [{ element, message: "Narrow justified text without automatic hyphenation", snippet: shortSnippet(element) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/line-length.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/line-length.tsnew file mode 100644index 00000000..f41bf4b2--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/line-length.ts@@ -0,0 +1,28 @@+import { childrenOf, fontSizePx, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { control, finePrintExempt, readingTags, visibleText } from "./support/text-context"+import { mergedLines, phrasingNodes, renderedCharacters } from "./support/text-lines"++export const lineLength: PageRule = {+ meta: {+ id: "line-length", name: "Line length too long", category: "quality", severity: "warning", engine: "page",+ description: "Multiple rendered lines longer than 80 characters make return sweeps difficult.",+ fixHint: "Constrain reading copy to a max-width around 65ch to 75ch.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap(element => {+ if (visibleText(snapshot, element) === false || finePrintExempt(snapshot, element)) return []+ const generic = ["div", "section", "article", "aside", "main"].includes(element.tag) &&+ element.ownText.length > 10 && fontSizePx(element) < 24 &&+ ["block", "flow-root"].includes(styleOf(element, "display")) &&+ styleOf(element, "white-space").startsWith("pre") === false && control(snapshot, element) === false &&+ childrenOf(snapshot, element).every(n => ["inline", "contents"].includes(styleOf(n, "display")) || ["br", "wbr"].includes(n.tag))+ if (readingTags.includes(element.tag) === false && generic === false) return []+ const nodes = phrasingNodes(snapshot, element)+ const count = renderedCharacters(nodes)+ if (count <= 80) return []+ const lines = mergedLines(nodes)+ const total = lines.reduce((n, l) => n + l.width, 0)+ if (total <= 0 || lines.filter(l => count * l.width / total > 85).length < 2) return []+ return [{ element, message: `Rendered lines exceed 80 characters (${Math.round(count * Math.max(...lines.map(l => l.width)) / total)} at widest)`, snippet: shortSnippet(element) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/oversized-h1.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/oversized-h1.tsnew file mode 100644index 00000000..d617ae28--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/oversized-h1.ts@@ -0,0 +1,20 @@+import { descendants, fontSizePx, shortSnippet } from "../../core/page"+import type { PageRule } from "../../rule"+import { visibleText } from "./support/text-context"++export const oversizedH1: PageRule = {+ meta: {+ id: "oversized-h1", name: "Oversized hero headline", category: "slop", severity: "warning", engine: "page",+ description: "A sentence-length display headline consumes too much of the first screen.",+ fixHint: "Shorten the headline or reduce its font size so supporting content fits above the fold.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap(element => {+ if (element.tag !== "h1" || visibleText(snapshot, element) === false ||+ fontSizePx(element) < 72 || element.rect.y >= snapshot.viewport.height) return []+ const text = [element, ...descendants(snapshot, element)].filter(e => visibleText(snapshot, e)).map(e => e.ownText).join(" ").trim().replace(/\s+/g, " ")+ const height = element.rect.height / snapshot.viewport.height+ const area = element.rect.width * element.rect.height / (snapshot.viewport.width * snapshot.viewport.height)+ if (text.length < 40 || (height < 0.28 && area < 0.25)) return []+ return [{ element, message: `Long display headline occupies ${Math.round(height * 100)}% of viewport height`, snippet: shortSnippet(element) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/overused-font.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/overused-font.tsnew file mode 100644index 00000000..0d89a230--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/overused-font.ts@@ -0,0 +1,45 @@+import { styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { brandDomain, canonicalFont, overusedFonts, primaryFont } from "./support/font-family"+import { cjkChar, letters, lineage } from "./support/text-context"++export const overusedFont: PageRule = {+ meta: {+ id: "overused-font", name: "Overused font", category: "slop", severity: "warning", engine: "page",+ description: "The page's dominant face comes from a frequently repeated set of interface fonts.",+ fixHint: "Choose a face suited to the project, or list the intentional choice in allowFonts.",+ },+ check: ({ snapshot, config }) => {+ const usage = new Map<string, { count: number; chars: number; latin: number }>()+ let total = 0+ let chars = 0+ let letterCount = 0+ let cjkCount = 0+ for (const e of snapshot.elements) {+ if (["p", "h1", "h2", "h3", "h4", "h5", "h6", "li", "td", "th", "dd", "blockquote", "figcaption", "a", "button", "label", "span"].includes(e.tag) === false ||+ e.ownText.trim() === "" || lineage(snapshot, e).some(n => /impeccable-(overlay|label|banner|tooltip)/.test(n.attributes["class"] ?? ""))) continue+ const font = canonicalFont(primaryFont(styleOf(e, "font-family")))+ if (font === "") continue+ const hasBox = lineage(snapshot, e).every(n => n.attributes["hidden"] === undefined &&+ styleOf(n, "display") !== "none" && ["hidden", "collapse"].includes(styleOf(n, "visibility")) === false &&+ styleOf(n, "content-visibility") !== "hidden")+ const weight = hasBox ? [...e.ownText].length : 0+ const alphabet = hasBox ? letters(e.ownText) : []+ const cjkLetters = alphabet.filter(cjkChar).length+ const value = usage.get(font) ?? { count: 0, chars: 0, latin: 0 }+ usage.set(font, { count: value.count + 1, chars: value.chars + weight, latin: value.latin + alphabet.length - cjkLetters })+ total+++ chars += weight+ letterCount += alphabet.length+ cjkCount += cjkLetters+ }+ const ranked = [...usage].sort((a, b) => b[1].count - a[1].count)+ const top = ranked[0]+ if (total < 20 || top === undefined || ranked[1]?.[1].count === top[1].count) return []+ const [font, value] = top+ if (overusedFonts.includes(font) === false || config.allowFonts?.some(f => canonicalFont(f) === font) ||+ brandDomain(font, snapshot.url) || (chars > 0 && value.chars / chars < 0.05) ||+ (cjkCount * 2 > letterCount && value.latin / letterCount < 0.05)) return []+ return [{ element: null, message: `Primary font: ${font} (${Math.round(value.count / total * 100)}% of text)`, snippet: font }]+ },+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/drawn-enlargement.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/drawn-enlargement.tsnew file mode 100644index 00000000..e16a384d--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/drawn-enlargement.ts@@ -0,0 +1,48 @@+import { ancestors, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"++function rotation(value: string): number | null {+ if (value === "" || value === "none") return 0+ const parts = value.toLowerCase().trim().split(/\s+/)+ const angle = parts.length === 1 ? parts[0] : parts.length === 2 && parts[0] === "z" ? parts[1] :+ parts.length === 4 && Number(parts[0]) === 0 && Number(parts[1]) === 0 && Number(parts[2]) > 0 ? parts[3] : undefined+ const match = /^([-+]?[\d.]+)(deg|grad|rad|turn)$/.exec(angle ?? "")+ if (!match) return null+ const factor = match[2] === "deg" ? Math.PI / 180 : match[2] === "grad" ? Math.PI / 200 : match[2] === "turn" ? Math.PI * 2 : 1+ const turn = Number(match[1]) * factor+ return Number.isFinite(turn) ? turn : null+}++export function drawnEnlargement(s: PageSnapshot, e: ElementSnapshot): number | null {+ const chain = [e, ...ancestors(s, e)]+ if (chain.length > 64 || chain.some(n => n.style["scale"] === undefined || n.style["rotate"] === undefined)) return null+ let a = 1, b = 0, c = 0, d = 1+ const multiply = (x: number, y: number, z: number, w: number): void => {+ const nextA = x * a + z * b, nextB = y * a + w * b+ const nextC = x * c + z * d, nextD = y * c + w * d+ a = nextA; b = nextB; c = nextC; d = nextD+ }+ for (const n of chain) {+ const transform = styleOf(n, "transform")+ if (transform !== "" && transform !== "none") {+ const matrix = /^matrix\(([^)]+)\)$/.exec(transform)+ if (!matrix) return null+ const values = (matrix[1] ?? "").split(",").map(Number)+ const [x, y, z, w] = values+ if (values.length !== 6 || x === undefined || y === undefined || z === undefined || w === undefined || !values.every(Number.isFinite)) return null+ multiply(x, y, z, w)+ }+ const scale = styleOf(n, "scale")+ if (scale !== "" && scale !== "none") {+ const values = scale.trim().split(/\s+/).map(v => v.endsWith("%") ? Number(v.slice(0, -1)) / 100 : Number(v))+ const x = values[0], y = values[1] ?? x+ if (values.length > 3 || x === undefined || y === undefined || !values.every(Number.isFinite)) return null+ multiply(x, 0, 0, y)+ }+ const angle = rotation(styleOf(n, "rotate"))+ if (angle === null) return null+ multiply(Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle))+ }+ const scale = Math.min(Math.hypot(a, b), Math.hypot(c, d))+ return Number.isFinite(scale) && scale > 1.05 ? scale : 1+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/fading-text.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/fading-text.tsnew file mode 100644index 00000000..7bb87990--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/fading-text.ts@@ -0,0 +1,48 @@+import { styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { keyframeSteps } from "../../decoration/support/keyframes"++const seconds = (value: string): number => {+ const match = /^([-+]?(?:\d*\.)?\d+)(ms|s)$/.exec(value)+ return match ? Number(match[1]) / (match[2] === "ms" ? 1000 : 1) : Number.NaN+}++export function fadesOutForGood(s: PageSnapshot, e: ElementSnapshot): boolean {+ if (!e.motion.includes("opacity")) return false+ const names = styleOf(e, "animation-name").split(",").map(n => n.trim())+ const entries = []+ for (const [index, name] of names.entries()) {+ if (name === "" || name === "none") continue+ const steps = keyframeSteps(s, name)+ if (steps === null) return false+ if (steps.some(step => step.declarations["opacity"] !== undefined)) entries.push({ index, steps })+ }+ const entry = entries[0]+ if (entries.length !== 1 || !entry) return false+ const value = (property: string): string => {+ const list = styleOf(e, "animation-" + property).split(",").map(v => v.trim().toLowerCase())+ return list[entry.index % list.length] ?? ""+ }+ if (value("play-state") !== "running" || !["forwards", "both"].includes(value("fill-mode")) ||+ !["", "auto"].includes(value("timeline")) || value("composition") !== "replace") return false+ const count = Number(value("iteration-count")), duration = seconds(value("duration")), delay = seconds(value("delay"))+ if (!Number.isInteger(count) || count < 1 || !(duration > 0) || !(Math.max(0, delay) + duration * count <= 60)) return false+ const direction = value("direction")+ if (!["normal", "reverse", "alternate", "alternate-reverse"].includes(direction)) return false+ const last = direction === "normal" || (direction === "alternate" && count % 2 === 1) ||+ (direction === "alternate-reverse" && count % 2 === 0)+ let opacity: number | undefined+ for (const step of entry.steps) {+ const endpoint = step.key.split(",").some(key => {+ const trimmed = key.trim().toLowerCase()+ const offset = trimmed === "from" ? 0 : trimmed === "to" ? 1 :+ trimmed.endsWith("%") ? Number(trimmed.slice(0, -1)) / 100 : Number.NaN+ return Math.abs(offset - (last ? 1 : 0)) < 1e-9+ })+ const raw = step.declarations["opacity"]+ if (!endpoint || raw === undefined) continue+ const number = raw.endsWith("%") ? Number(raw.slice(0, -1)) / 100 : Number(raw)+ if (Number.isFinite(number)) opacity = number+ }+ return opacity !== undefined && opacity <= 0.02+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/flex-runs.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/flex-runs.tsnew file mode 100644index 00000000..40d1a57d--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/flex-runs.ts@@ -0,0 +1,16 @@+import { px, styleOf } from "../../../core/page"+import type { ElementSnapshot } from "../../../types"++const WIDE = /[\u1100-\u115f\u2e80-\u303f\u3040-\u33ff\u3400-\u4dbf\u4e00-\u9fff\ua960-\ua97f\uac00-\ud7ff\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6]|[\u{20000}-\u{3ffff}]/u++const advanceBoundEm = (c: string): number => (WIDE.test(c) ? 1.05 : c !== c.toLowerCase() && c === c.toUpperCase() ? 0.8 : 0.7)++/** A wrapping flex row whose own text is two or more runs, each short enough to sit on one line of the row: the runs move whole, so no line of one run crowds another. */+export function itemsEachFitOneLine(element: ElementSnapshot, fontSize: number): boolean {+ if (!["flex", "inline-flex"].includes(styleOf(element, "display"))) return false+ if (!styleOf(element, "flex-wrap").startsWith("wrap")) return false+ if (element.textRuns.length < 2) return false+ const content = element.scroll.clientWidth - Math.max(0, px(styleOf(element, "padding-left")) ?? 0) - Math.max(0, px(styleOf(element, "padding-right")) ?? 0)+ if (!(Number.isFinite(content) && content > 0 && fontSize > 0)) return false+ return element.textRuns.every((run) => [...run].reduce((w, c) => w + advanceBoundEm(c), 0) * fontSize < content)+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/font-family.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/font-family.tsnew file mode 100644index 00000000..88396c31--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/font-family.ts@@ -0,0 +1,28 @@+export const overusedFonts = [+ "inter", "roboto", "open sans", "lato", "montserrat", "arial", "helvetica", "fraunces",+ "instrument sans", "instrument serif", "geist", "geist sans", "geist mono", "mona sans",+ "plus jakarta sans", "space grotesk", "recoleta",+]+const genericFonts = ["serif", "sans-serif", "monospace", "cursive", "fantasy", "inherit", "initial", "unset", "revert"]+const platformFonts = ["system-ui", "ui-serif", "ui-sans-serif", "ui-monospace", "ui-rounded", "-apple-system", "blinkmacsystemfont", "segoe ui"]++export const normalizeFont = (value: string): string => value.trim().replace(/^['"]|['"]$/g, "").replace(/\+/g, " ").replace(/\s+/g, " ").toLowerCase()+export const canonicalFont = (value: string): string => {+ const normalized = normalizeFont(value)+ const key = normalized.replace(/[-_ ]/g, "")+ return overusedFonts.find(f => f.replace(/[-_ ]/g, "") === key) ?? normalized+}+export function primaryFont(stack: string, skipPlatform = false): string {+ if (stack.includes("var(")) return ""+ const families = stack.match(/"[^"]*"|'[^']*'|[^,]+/g) ?? []+ return families.map(normalizeFont).find(f =>+ f !== "" && genericFonts.includes(f) === false && (skipPlatform === false || platformFonts.includes(f) === false)) ?? ""+}++export function brandDomain(font: string, url: string): boolean {+ const host = URL.canParse(url) ? new URL(url).hostname.toLowerCase() : ""+ const domains = font === "roboto" ? ["google.com", "youtube.com", "android.com", "chromium.org", "chrome.com", "web.dev", "gstatic.com", "firebase.google.com"] :+ ["geist", "geist sans", "geist mono"].includes(font) ? ["vercel.com", "nextjs.org", "v0.app"] :+ font === "mona sans" ? ["github.com", "githubnext.com"] : []+ return domains.some(d => host === d || host.endsWith(`.${d}`))+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/painted-text.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/painted-text.tsnew file mode 100644index 00000000..8a9201d6--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/painted-text.ts@@ -0,0 +1,81 @@+import { ancestors, childrenOf, descendants, fontSizePx, parentOf, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"+import { drawnEnlargement } from "./drawn-enlargement"+import { fadesOutForGood } from "./fading-text"++const squash = (text: string): string => text.replace(/\s/g, "")+const hidden = (e: ElementSnapshot): boolean => e.attributes["inert"] !== undefined || e.attributes["aria-hidden"] === "true"+const classes = (e: ElementSnapshot): readonly string[] => (e.attributes["class"] ?? "").split(/\s+/).filter(Boolean)+const shown = (s: PageSnapshot, e: ElementSnapshot): boolean => [e, ...ancestors(s, e)].every(n => styleOf(n, "display") !== "none") &&+ styleOf(e, "visibility") !== "hidden" && e.rect.width > 0 && e.rect.height > 0+const dialog = (e: ElementSnapshot): boolean => e.attributes["aria-modal"] === "true" ||+ ["dialog", "alertdialog"].includes(e.attributes["role"] ?? "") || (e.tag === "dialog" && e.attributes["open"] !== undefined)+const source = (e: ElementSnapshot): boolean => ["script", "style", "noscript", "template"].includes(e.tag)+const structuralTags = ["html", "body", "main", "header", "footer", "nav", "aside", "section", "article", "form",+ "dialog", "li", "tr", "td", "th", "tbody", "thead", "table", "details", "summary"]+const textHosts = ["h1", "h2", "h3", "h4", "h5", "h6", "p", "a", "button", "label", "summary", "legend", "caption", "figcaption", "blockquote", "q"]+const parkedParts = new Set(("clone clones cloned copy duplicate dup carousel embla flicking glide keen slick slide slider slides splide swiper " ++ "marquee ticker menu submenu dropdown popup popover modal drawer dialog tooltip toast offcanvas overlay nav navbar navigation panel tab " ++ "tabpanel accordion collapse collapsible intro splash loader preloader loading banner cookie cookies consent sidebar sidenav toc").split(" "))++function declaredMockup(s: PageSnapshot, e: ElementSnapshot): boolean {+ return [e, ...ancestors(s, e)].some(root => {+ if (!hidden(root) || root.rect.width < 120 || root.rect.height < 80 || structuralTags.includes(root.tag) ||+ ["fixed", "sticky"].includes(styleOf(root, "position")) || root.attributes["aria-modal"] !== undefined ||+ root.attributes["data-aria-hidden"] !== undefined ||+ (root.attributes["role"] ?? "").split(/\s+/).some(r => r !== "" && !["presentation", "none", "img", "figure", "group"].includes(r)) ||+ [...ancestors(s, root)].some(n => textHosts.includes(n.tag))) return false+ const parts = `${classes(root).join(" ")} ${root.attributes["id"] ?? ""}`.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase().split(/[\s_-]+/)+ if (parts.some(p => parkedParts.has(p))) return false+ const nodes = [root, ...descendants(s, root)]+ if (nodes.length > 3000 || nodes.some(n => n.tag === "h1")) return false+ const runs = nodes.filter(n => !source(n) && n.ownText.trim() !== "" &&+ styleOf(n, "visibility") !== "hidden" && [n, ...ancestors(s, n)].every(a => styleOf(a, "display") !== "none"))+ if (runs.length < 3) return false+ const fields = nodes.filter(n => ["input", "select", "textarea"].includes(n.tag) && (n.tag !== "input" || n.attributes["type"] !== "hidden"))+ const links = runs.filter(n => [n, ...ancestors(s, n)].some(a => a.tag === "a" && (a.attributes["href"] ?? "").trim() !== ""))+ if (fields.length >= 2 || (fields.length >= 1 && nodes.some(n => n.tag === "label")) || links.length * 2 >= runs.length) return false+ const text = squash(root.text)+ if ([...ancestors(s, root)].some(n => text !== "" && squash(n.attributes["aria-label"] ?? "").includes(text))) return false+ const parent = parentOf(s, root)+ if (parent && childrenOf(s, parent).some(n => {+ if (n.index === root.index) return false+ const theirs = classes(n), own = classes(root)+ const peer = n.tag === root.tag && own.every(c => theirs.includes(c)) && (own.length === 0) === (theirs.length === 0)+ const alternative = !source(n) && !hidden(n) && shown(s, n) &&+ (n.rect.width <= 1 || n.rect.height <= 1 || /sr-only|visually-?hidden/.test(classes(n).join(" "))) &&+ n.text.trim() !== "" && !/\b(?:demo|demonstration|illustrat\w*|interface|screen ?shots?|mock-?ups?|graphic|animation|animated|preview|image|video|visual|diagram|depict\w*|shows|showing|displayed)\b/i.test(n.text)+ return (peer && shown(s, n) && !hidden(n)) || (text !== "" && squash(n.text) === text) || alternative+ })) return false+ if (s.elements.some(n => dialog(n) && !hidden(n) && shown(s, n) &&+ ![n, ...ancestors(s, n)].some(a => a.index === root.index) &&+ ![root, ...ancestors(s, root)].some(a => a.index === n.index))) return false+ const pageChars = s.elements.filter(n => !source(n) && styleOf(n, "visibility") !== "hidden" &&+ [n, ...ancestors(s, n)].every(a => styleOf(a, "display") !== "none")).reduce((count, n) => count + squash(n.ownText).length, 0)+ const ownChars = runs.reduce((count, n) => count + squash(n.ownText).length, 0)+ return pageChars > 0 && ownChars * 2 < pageChars+ })+}++export function textPainted(s: PageSnapshot, e: ElementSnapshot): boolean {+ if ([e, ...ancestors(s, e)].some(n => fadesOutForGood(s, n))) return false+ if (declaredMockup(s, e)) return false+ for (const a of ancestors(s, e)) {+ if (a.tag === "details" && a.attributes["open"] === undefined) {+ const summary = childrenOf(s, a).find(n => n.tag === "summary")+ if (!summary || ![e, ...ancestors(s, e)].some(n => n.index === summary.index)) return false+ }+ }+ if (fontSizePx(e) <= 1) {+ const size = (n: ElementSnapshot): number | null => {+ const scale = drawnEnlargement(s, n)+ return scale === null ? null : fontSizePx(n) * scale+ }+ const own = size(e)+ if (own !== null && own <= 1 && ![...descendants(s, e)].some(n => {+ const drawn = size(n)+ return n.ownText !== "" && (drawn === null || drawn > 1)+ })) return false+ }+ return true+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/svg-size.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/svg-size.tsnew file mode 100644index 00000000..feeed634--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/svg-size.ts@@ -0,0 +1,57 @@+import { ancestors, fontSizePx, px, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"++const uniformScale = (value: string): number | null => {+ if (value === "" || value === "none") return 1+ if (/skew|matrix3d|rotate[XY]|perspective/i.test(value)) return null+ const matrix = /^matrix\(([^)]+)\)$/.exec(value)+ if (matrix?.[1]) {+ const [a, b, c, d] = matrix[1].split(/[\s,]+/).map(Number)+ if (a === undefined || b === undefined || c === undefined || d === undefined) return null+ const x = Math.hypot(a, b)+ const y = Math.hypot(c, d)+ return Math.abs(x - y) < 0.001 && Math.abs(a * c + b * d) < 0.001 ? x : null+ }+ let scale = 1+ for (const match of value.matchAll(/scale\(([^)]+)\)/g)) {+ const [x, y] = (match[1] ?? "").split(/[\s,]+/).map(Number)+ if (x === undefined || (y !== undefined && Math.abs(x - y) > 0.001)) return null+ scale *= Math.abs(x)+ }+ return scale+}++export function drawnFontSize(s: PageSnapshot, e: ElementSnapshot): number {+ const size = fontSizePx(e)+ if (["text", "tspan", "textpath"].includes(e.tag) === false) return size+ const chain = [e, ...ancestors(s, e)]+ const svg = chain.find(n => n.tag === "svg")+ if (svg === undefined) return size+ const box = (svg.attributes["viewBox"] ?? svg.attributes["viewbox"] ?? "").trim().split(/[\s,]+/).map(Number)+ const vw = box[2]+ const vh = box[3]+ if (box.length !== 4 || vw === undefined || vh === undefined || vw <= 0 || vh <= 0) return size+ let inner = 1+ for (const n of chain) {+ if (n === svg) break+ const computed = styleOf(n, "transform")+ const scale = uniformScale(computed === "" || computed === "none" ? n.attributes["transform"] ?? "" : computed)+ if (scale === null) return size+ inner *= scale+ }+ const content = (axis: "width" | "height", sides: readonly string[]): number | null => {+ const drawn = svg.rect[axis]+ const inset = sides.reduce((n, p) => n + (px(styleOf(svg, p)) ?? 0), 0)+ if (inset <= 0) return drawn+ const css = px(styleOf(svg, axis)) ?? 0+ if (Math.abs(css + inset - drawn) <= 1) return css+ if (Math.abs(css - drawn) <= 1) return css - inset+ return null+ }+ const w = content("width", ["padding-left", "padding-right", "border-left-width", "border-right-width"])+ const h = content("height", ["padding-top", "padding-bottom", "border-top-width", "border-bottom-width"])+ if (w === null || h === null || w <= 0 || h <= 0) return size+ const aspect = svg.attributes["preserveAspectRatio"] ?? svg.attributes["preserveaspectratio"] ?? ""+ const scale = aspect.includes("none") ? h / vh : aspect.includes("slice") ? Math.max(w / vw, h / vh) : Math.min(w / vw, h / vh)+ return size * scale * inner+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/text-context.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/text-context.tsnew file mode 100644index 00000000..6bd82ff6--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/text-context.ts@@ -0,0 +1,112 @@+import { ancestors, childrenOf, fontSizePx, isHeading, px, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot } from "../../../types"++export const readingTags = ["p", "li", "td", "th", "dd", "blockquote", "figcaption"]+export const lineage = (s: PageSnapshot, e: ElementSnapshot): readonly ElementSnapshot[] => [e, ...ancestors(s, e)]+export const className = (e: ElementSnapshot): string => e.attributes["class"] ?? ""+export const mono = (e: ElementSnapshot): boolean => {+ const first = (styleOf(e, "font-family").split(",")[0] ?? "").trim().replace(/^['"]|['"]$/g, "").toLowerCase()+ return ["courier", "courier new", "consolas", "menlo", "monaco", "andale mono", "lucida console"].includes(first) ||+ first.split(/[^a-z0-9]+/).some(w => ["mono", "monospace", "monospaced", "sfmono"].includes(w))+}+export const letters = (text: string): readonly string[] => [...text].filter(c => /\p{L}/u.test(c))+export const cjkChar = (c: string): boolean => /[\u1100-\u11ff\u3040-\u30ff\u3130-\u318f\u31f0-\u31ff\u3400-\u9fff\ua960-\ud7ff\uf900-\ufaff\uff66-\uff9f\u{20000}-\u{3ffff}]/u.test(c)+export const cjk = (text: string): boolean => {+ const sample = [...text].slice(0, 256)+ const count = sample.filter(cjkChar).length+ return count > 0 && count * 2 >= sample.filter(c => /\p{L}/u.test(c)).length+}+export const caps = (text: string): boolean => {+ const chars = letters(text)+ return chars.some(c => c.toUpperCase() !== c.toLowerCase()) && chars.every(c => /\p{Lu}/u.test(c))+}++export function visibleText(s: PageSnapshot, e: ElementSnapshot): boolean {+ const box = (e.rect.width > 0 && e.rect.height > 0) || e.lineRects.some(r => r.width > 0 && r.height > 0)+ return box && lineage(s, e).every(n =>+ n.attributes["hidden"] === undefined && styleOf(n, "display") !== "none" &&+ styleOf(n, "visibility") !== "collapse" && styleOf(n, "visibility") !== "hidden" &&+ styleOf(n, "content-visibility") !== "hidden" &&+ (Number.parseFloat(styleOf(n, "opacity")) <= 0.01) === false &&+ ((n.rect.width <= 0 || n.rect.height <= 0) &&+ ["overflow-x", "overflow-y"].some(p => ["hidden", "clip"].includes(styleOf(n, p)))) === false &&+ /sr-only|visually-?hidden|screen-?reader|a11y-hidden|hidden-visually/i.test(className(n)) === false &&+ /^(script|style|title|noscript|template|head|meta|link|base|param|source|track|datalist|col|colgroup|area)$/.test(n.tag) === false &&+ /inset\(\s*(50%|99|100%)/.test(styleOf(n, "clip-path")) === false)+}++export function control(s: PageSnapshot, e: ElementSnapshot): boolean {+ return lineage(s, e).some(n =>+ ["button", "summary", "label", "select", "textarea"].includes(n.tag) ||+ (n.tag === "a" && n.attributes["href"] !== undefined) ||+ /^(button|link|tab|menuitem|menuitemcheckbox|menuitemradio|option|checkbox|radio|switch|treeitem)$/.test(n.attributes["role"] ?? "") ||+ (n.attributes["tabindex"] !== undefined && Number(n.attributes["tabindex"]) >= 0 && n.text.length <= 80))+}++export function headingText(s: PageSnapshot, e: ElementSnapshot): boolean {+ for (const n of lineage(s, e)) {+ if (isHeading(n) || n.attributes["role"] === "heading") return true+ if (readingTags.includes(n.tag)) return false+ }+ return false+}++export function pitch(s: PageSnapshot, e: ElementSnapshot): number {+ let height = px(styleOf(e, "line-height")) ?? 0+ if (styleOf(e, "display") === "inline") {+ for (const n of ancestors(s, e)) {+ height = Math.max(height, px(styleOf(n, "line-height")) ?? 0)+ if (["inline", "contents"].includes(styleOf(n, "display")) === false) break+ }+ }+ return height+}++export const smallprint = (s: PageSnapshot, e: ElementSnapshot): boolean => lineage(s, e).some(n =>+ ["small", "footer"].includes(n.tag) || /legal|copyright|disclaimer|small-?print|fine-?print|disclosure|footnote/i.test(className(n)))++export function finePrintExempt(s: PageSnapshot, e: ElementSnapshot): boolean {+ if (fontSizePx(e) <= 0 || fontSizePx(e) >= 15 ||+ lineage(s, e).some(n => n.tag === "label" || isHeading(n)) ||+ childrenOf(s, e).some(n => ["input", "select", "textarea", "button"].includes(n.tag))) return false+ const marked: ElementSnapshot[] = []+ for (const n of lineage(s, e).slice(0, 4)) {+ if (["html", "body", "main", "article", "form"].includes(n.tag)) break+ const words = `${className(n)} ${n.attributes["id"] ?? ""}`.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()+ if (/(?:^|[-_\s])(legal|fine-?print|small-?print|disclaimers?|footnotes?|disclosures)(?:$|[-_\s])/.test(words) &&+ /(?:type|text|typography|font|fs)[-_]footnote/.test(words) === false) marked.push(n)+ }+ if (marked.length === 0 || marked.some(n => n.tag === "details" || n.tag === "summary" ||+ n.attributes["aria-expanded"] !== undefined || childrenOf(s, n).some(c => c.tag === "summary" || c.attributes["aria-expanded"] !== undefined))) return false+ const outer = marked[marked.length - 1]+ if (outer && outer.text.length >= 2000 &&+ outer.text.length >= (s.elements.find(n => n.tag === "body")?.text.length ?? 0) * 0.5 &&+ lineage(s, outer).some(n => n.tag === "footer" || n.attributes["role"] === "contentinfo") === false) return false+ return true+}++export const codeContext = (s: PageSnapshot, e: ElementSnapshot): boolean => lineage(s, e).some(n =>+ ["pre", "code", "kbd", "samp", "var", "svg"].includes(n.tag) ||+ n.attributes["aria-hidden"] === "true" || /terminal|console|code|mock|editor|syntax|diff/i.test(className(n)))++export const uiContext = (s: PageSnapshot, e: ElementSnapshot): boolean => lineage(s, e).some(n =>+ ["button", "a", "label", "summary", "pre", "nav", "footer"].includes(n.tag) ||+ n.attributes["aria-hidden"] === "true" ||+ /^(button|link|tab|menuitem|option)$/.test(n.attributes["role"] ?? "") ||+ /badge|caption|chip|code|console|diff|label|meta|mock|pill|preview|tag|terminal|writes/i.test(className(n)))++export function buttonBox(s: PageSnapshot, e: ElementSnapshot): boolean {+ for (const n of lineage(s, e).slice(0, 3)) {+ if (n !== e && n.text.length > 80) return false+ if (className(n).toLowerCase().split(/\s+/).some(t => t === "btn" || t.endsWith("-btn") || t.endsWith("_btn"))) return true+ }+ return false+}++export const furnitureClass = (value: string): boolean => value.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()+ .split(/[-_\s]+/).some(raw => {+ const part = raw.replace(/[^\p{L}\p{N}]/gu, "")+ return ["pillar", "pillars", "navy"].includes(part) === false &&+ ["meta", "label", "badge", "chip", "pill", "tag", "kicker", "eyebrow", "breadcrumb", "timestamp", "category", "caption", "nav"]+ .some(w => part.startsWith(w) || part.endsWith(w))+ })diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/text-lines.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/text-lines.tsnew file mode 100644index 00000000..b57f843e--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/text-lines.ts@@ -0,0 +1,43 @@+import { childrenOf, px, styleOf } from "../../../core/page"+import type { ElementSnapshot, PageSnapshot, Rect } from "../../../types"+import { visibleText } from "./text-context"++export function phrasingNodes(s: PageSnapshot, e: ElementSnapshot): readonly ElementSnapshot[] {+ const nodes: ElementSnapshot[] = []+ const walk = (n: ElementSnapshot): void => {+ if (visibleText(s, n) === false) return+ nodes.push(n)+ for (const c of childrenOf(s, n)) {+ if (["inline", "contents"].includes(styleOf(c, "display")) || ["br", "wbr"].includes(c.tag)) walk(c)+ }+ }+ walk(e)+ return nodes+}++export function mergedLines(nodes: readonly ElementSnapshot[]): readonly Rect[] {+ const lines: Rect[] = []+ for (const r of nodes.flatMap(n => n.lineRects).sort((a, b) => a.y - b.y || a.x - b.x)) {+ const match = lines.find(l => Math.abs(l.y - r.y) <= Math.max(2, Math.min(l.height, r.height) * 0.5))+ if (match) {+ const i = lines.indexOf(match)+ const x = Math.min(match.x, r.x)+ const y = Math.min(match.y, r.y)+ lines[i] = { x, y, width: Math.max(match.x + match.width, r.x + r.width) - x, height: Math.max(match.y + match.height, r.y + r.height) - y }+ } else lines.push(r)+ }+ return lines+}++export function renderedCharacters(nodes: readonly ElementSnapshot[]): number {+ return nodes.reduce((n, e) => n + [...e.ownText.normalize("NFC")].filter(c =>+ /[\p{M}\u200b-\u200f\u202a-\u202e\u2060-\u206f]/u.test(c) === false).length, 0)+}++export function shownLines(s: PageSnapshot, e: ElementSnapshot, lineHeight: number): number {+ const lines = mergedLines(phrasingNodes(s, e))+ const top = lines[0]?.y+ if (top === undefined || lineHeight <= 0) return 0+ const bottom = Math.max(...lines.map(r => r.y + r.height))+ return Math.max(1, Math.round((bottom - top - (px(styleOf(e, "font-size")) ?? 16)) / lineHeight) + 1)+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/type-hierarchy.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/type-hierarchy.tsnew file mode 100644index 00000000..4264dc70--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/support/type-hierarchy.ts@@ -0,0 +1,48 @@+export type TypeSample = { readonly role: string; readonly size: number; readonly weight: number }++function dominant(role: string, values: readonly number[]): number | null {+ const counts = new Map<number, number>()+ for (const n of values) counts.set(n, (counts.get(n) ?? 0) + 1)+ const ranked = [...counts].sort((a, b) => b[1] - a[1] || a[0] - b[0])+ const first = ranked[0]+ const second = ranked[1]+ if (first === undefined) return null+ if (second && first[1] === second[1]) {+ return role === "h1" ? Math.max(...ranked.filter(n => n[1] === first[1]).map(n => n[0])) : null+ }+ if (second && role !== "h1" && role !== "body" && second[1] >= first[1] * 0.75 && second[0] >= first[0] * 1.25) return null+ return first[0]+}++const largestStep = (values: readonly number[]): number => {+ const sorted = [...values].sort((a, b) => a - b)+ return sorted.reduce((n, v, i) => Math.max(n, v / (sorted[i - 1] ?? v)), 1)+}++export function flatHierarchy(samples: readonly TypeSample[]): readonly [string, number][] {+ const groups = new Map<string, number[]>()+ for (const s of samples) {+ const values = groups.get(s.role) ?? []+ values.push(Math.round(s.size * 10) / 10)+ groups.set(s.role, values)+ }+ const roles: [string, number][] = []+ const dropped: number[] = []+ let settled = 0+ for (const [role, values] of groups) {+ const size = dominant(role, values)+ if (size === null) {+ if (role !== "body") dropped.push(...values)+ } else {+ roles.push([role, size])+ if (role !== "body") settled += values.length+ }+ }+ if (roles.length < 3) return []+ const h1 = roles.find(r => r[0] === "h1")?.[1]+ const body = roles.find(r => r[0] === "body")?.[1]+ if (h1 !== undefined && body !== undefined && h1 < body) return []+ const sizes = roles.map(r => r[1])+ if (largestStep(sizes) >= 1.25 || (dropped.length > settled && dropped.some(n => largestStep([...sizes, n]) >= 1.25))) return []+ return roles+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/tight-leading.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/tight-leading.tsnew file mode 100644index 00000000..6101508c--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/tight-leading.ts@@ -0,0 +1,47 @@+import { fontSizePx, px, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { caps, headingText, lineage, mono, pitch, visibleText } from "./support/text-context"+import { itemsEachFitOneLine } from "./support/flex-runs"+import { mergedLines, phrasingNodes, shownLines } from "./support/text-lines"++export const tightLeading: PageRule = {+ meta: {+ id: "tight-leading", name: "Tight line height", category: "quality", severity: "warning", engine: "page",+ description: "Multiline reading copy with line height below 1.3 crowds adjacent lines.",+ fixHint: "Use line height around 1.5 to 1.7 for body copy.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap(element => {+ const size = fontSizePx(element)+ const height = pitch(snapshot, element)+ const ratio = Math.round(height / size * 100) / 100+ if (visibleText(snapshot, element) === false || element.ownText.length <= 10 || element.text.length <= 50 ||+ size <= 0 || size >= 24 || height <= 0 || ratio >= 1.3 || headingText(snapshot, element)) return []+ const lines = mergedLines(phrasingNodes(snapshot, element))+ const top = lines[0]?.y+ if (top === undefined) return []+ const bottom = Math.max(...lines.map(l => l.y + l.height))+ if (bottom - top < height * 1.5) return []+ let count = shownLines(snapshot, element, height)+ let clamped = false+ for (const n of lineage(snapshot, element).slice(0, 4)) {+ const display = styleOf(n, "display")+ const clamp = Number.parseFloat(styleOf(n, "-webkit-line-clamp"))+ if (["-webkit-box", "-webkit-inline-box"].includes(display) ||+ (["flow-root", "inline-block"].includes(display) && clamp > 0)) clamped = true+ if (["hidden", "clip"].includes(styleOf(n, "overflow-y"))) {+ count = Math.min(count, Math.max(1, Math.round((n.rect.y + n.rect.height - top) / height)))+ break+ }+ }+ const weight = Number.parseFloat(styleOf(element, "font-weight"))+ if (weight >= 600 && (clamped || count <= 2)) return []+ if (size >= 20 && ratio >= 1.15 && count <= 3) return []+ if (ratio >= 1 && ((styleOf(element, "text-transform") === "uppercase" && count <= 3) ||+ (element.text.length < 80 && caps(element.text)))) return []+ const ws = styleOf(element, "white-space")+ if (mono(element) && ((ws.startsWith("pre") && ws !== "pre-line") || ws === "break-spaces") &&+ (lineage(snapshot, element).some(n => ["pre", "code", "samp"].includes(n.tag)) || /[\u2500-\u257f]/.test(element.ownText))) return []+ if (itemsEachFitOneLine(element, size)) return []+ return [{ element, message: `Line height ${(height / size).toFixed(2)}x below 1.3`, snippet: shortSnippet(element) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/tiny-text.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/tiny-text.tsnew file mode 100644index 00000000..d3ebf527--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/tiny-text.ts@@ -0,0 +1,23 @@+import { shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { buttonBox, caps, finePrintExempt, mono, smallprint, uiContext, visibleText } from "./support/text-context"+import { drawnFontSize } from "./support/svg-size"+import { textPainted } from "./support/painted-text"++export const tinyText: PageRule = {+ meta: {+ id: "tiny-text", name: "Tiny body text", category: "quality", severity: "warning", engine: "page",+ description: "Running copy smaller than 12px is difficult to read.",+ fixHint: "Increase body copy to at least 14px, preferably 16px.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap(element => {+ if (visibleText(snapshot, element) === false || !textPainted(snapshot, element) || element.ownText.length <= 10 || element.text.length <= 20 ||+ drawnFontSize(snapshot, element) >= 12 ||+ ["sub", "sup", "code", "kbd", "samp", "var", "caption", "figcaption"].includes(element.tag) ||+ uiContext(snapshot, element) || (buttonBox(snapshot, element) && smallprint(snapshot, element) === false) || finePrintExempt(snapshot, element) ||+ styleOf(element, "text-transform") === "uppercase" ||+ (element.text.length < 80 && caps(element.text)) ||+ (mono(element) && styleOf(element, "white-space").startsWith("pre"))) return []+ return [{ element, message: `${drawnFontSize(snapshot, element).toFixed(2)}px body text`, snippet: shortSnippet(element) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/undersized-ui-text.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/undersized-ui-text.tsnew file mode 100644index 00000000..935e20dd--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/undersized-ui-text.ts@@ -0,0 +1,28 @@+import { fontSizePx, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { buttonBox, className, codeContext, control, furnitureClass, lineage, mono, smallprint, visibleText } from "./support/text-context"+import { textPainted } from "./support/painted-text"++export const undersizedUiText: PageRule = {+ meta: {+ id: "undersized-ui-text", name: "Undersized functional text", category: "quality", severity: "warning", engine: "page",+ description: "Functional labels below 11px are difficult to read and use.",+ fixHint: "Use at least 11px for functional text and at least 10px for noninteractive small print.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap(element => {+ const size = fontSizePx(element)+ const interactive = control(snapshot, element)+ const floor = interactive === false && smallprint(snapshot, element) ? 10 : 11+ const chain = lineage(snapshot, element)+ const furniture = chain.some(n => ["nav", "td", "th", "caption", "figcaption", "dt", "dd", "footer"].includes(n.tag) ||+ ["navigation", "gridcell", "cell"].includes(n.attributes["role"] ?? "") ||+ (n.tag !== "html" && furnitureClass(className(n))))+ const codeRun = mono(element) && styleOf(element, "white-space").startsWith("pre") && /[{}[\]<>=;"`\\_]/.test(element.ownText)+ if (visibleText(snapshot, element) === false || !textPainted(snapshot, element) || size <= 0 || Math.round((floor - size) * 1000) < 100 ||+ element.ownText.trim().length < 2 || ["sub", "sup", "option"].includes(element.tag) ||+ chain.some(n => ["sub", "sup"].includes(n.tag)) || codeContext(snapshot, element) || codeRun ||+ (interactive === false && furniture === false &&+ (buttonBox(snapshot, element) === false || smallprint(snapshot, element)) && element.ownText.length > 20)) return []+ return [{ element, message: `${size}px functional text below ${floor}px floor`, snippet: shortSnippet(element) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/rules/typography/wide-tracking.ts b/plugins/omo/skills/frontend/scripts/detect/rules/typography/wide-tracking.tsnew file mode 100644index 00000000..dbddc9ec--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/rules/typography/wide-tracking.ts@@ -0,0 +1,26 @@+import { fontSizePx, px, shortSnippet, styleOf } from "../../core/page"+import type { PageRule } from "../../rule"+import { caps, cjk, letters, lineage, visibleText } from "./support/text-context"+import { shownLines } from "./support/text-lines"++export const wideTracking: PageRule = {+ meta: {+ id: "wide-tracking", name: "Wide letter spacing on body text", category: "quality", severity: "warning", engine: "page",+ description: "Widely tracked reading text splits words into individual characters.",+ fixHint: "Keep body tracking at or below 0.05em; reserve wider spacing for capital labels.",+ },+ check: ({ snapshot }) => snapshot.elements.flatMap(element => {+ const size = fontSizePx(element)+ if (visibleText(snapshot, element) === false || element.ownText.length <= 10 || element.text.length <= 20 ||+ size <= 0 || (px(styleOf(element, "letter-spacing")) ?? 0) / size <= 0.05) return []+ const transform = styleOf(element, "text-transform")+ const count = shownLines(snapshot, element, px(styleOf(element, "line-height")) ?? size * 1.2)+ const capsLabel = transform === "uppercase" || (transform !== "lowercase" && caps(element.text) &&+ (element.text.length < 80 || (letters(element.text).length <= 40 && count <= 1)))+ const trackedControl = lineage(snapshot, element).some(n => n.tag === "button" ||+ (n.tag === "a" && n.attributes["href"] !== undefined) ||+ ["button", "link", "tab"].includes(n.attributes["role"] ?? ""))+ if (capsLabel || (trackedControl && letters(element.text).length <= 40 && count <= 1) || cjk(element.ownText)) return []+ return [{ element, message: "Letter spacing exceeds 0.05em on reading text", snippet: shortSnippet(element) }]+ }),+}diff --git a/plugins/omo/skills/frontend/scripts/detect/snapshot/collect.ts b/plugins/omo/skills/frontend/scripts/detect/snapshot/collect.tsnew file mode 100644index 00000000..e774c00b--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/snapshot/collect.ts@@ -0,0 +1,158 @@+import type { ElementSnapshot, PageSnapshot, PseudoSnapshot, Rect } from "../types"++// Runs inside the page: the renderer serializes this function with toString() and evaluates it there,+// so it must stay self-contained (no imports at runtime, no references to module scope).+export function collectPageSnapshot(props: readonly string[], maxElements: number): PageSnapshot {+ const collapse = (s: string): string => s.replace(/\s+/g, " ").trim()+ const toRect = (r: DOMRect): Rect => ({+ x: Math.round(r.x * 100) / 100,+ y: Math.round(r.y * 100) / 100,+ width: Math.round(r.width * 100) / 100,+ height: Math.round(r.height * 100) / 100,+ })+ const readStyle = (style: CSSStyleDeclaration): Record<string, string> => {+ const out: Record<string, string> = {}+ for (const p of props) out[p] = style.getPropertyValue(p)+ return out+ }+ const pseudo = (el: Element, which: "::before" | "::after"): PseudoSnapshot | null => {+ const style = getComputedStyle(el, which)+ const content = style.getPropertyValue("content")+ if (content === "none" || content === "normal" || content === "") return null+ return { style: readStyle(style), rect: null }+ }+ const cssEscape = (s: string): string => (typeof CSS !== "undefined" && CSS.escape ? CSS.escape(s) : s)+ const selectorOf = (el: Element): string => {+ const parts: string[] = []+ let node: Element | null = el+ while (node && node.nodeType === 1 && parts.length < 6) {+ if (node.id) {+ parts.unshift(`#${cssEscape(node.id)}`)+ break+ }+ const tag = node.tagName.toLowerCase()+ const parentEl: Element | null = node.parentElement+ if (!parentEl) {+ parts.unshift(tag)+ break+ }+ const current: Element = node+ const same = Array.from(parentEl.children).filter((c) => c.tagName === current.tagName)+ parts.unshift(same.length > 1 ? `${tag}:nth-of-type(${same.indexOf(current) + 1})` : tag)+ node = parentEl+ }+ return parts.join(" > ")+ }+ const lineRectsOf = (el: Element): Rect[] => {+ const rects: Rect[] = []+ for (const child of Array.from(el.childNodes)) {+ if (child.nodeType !== 3 || !child.textContent || child.textContent.trim() === "") continue+ const range = document.createRange()+ range.selectNodeContents(child)+ for (const r of Array.from(range.getClientRects())) {+ if (r.width === 0 && r.height === 0) continue+ const last = rects[rects.length - 1]+ if (last && Math.abs(last.y - r.y) < 2) {+ const right = Math.max(last.x + last.width, r.x + r.width)+ const x = Math.min(last.x, r.x)+ rects[rects.length - 1] = { x, y: last.y, width: right - x, height: Math.max(last.height, r.height) }+ } else rects.push(toRect(r))+ }+ }+ return rects+ }+ const kebab = (p: string): string => (p === "cssOffset" ? "offset" : p.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`))+ const motionOf = (el: Element): string[] => {+ const moving = new Set<string>()+ for (const anim of el.getAnimations()) {+ if (anim.playState !== "running") continue+ if (typeof CSSTransition !== "undefined" && anim instanceof CSSTransition) moving.add(anim.transitionProperty)+ const effect = anim.effect+ if (!(effect instanceof KeyframeEffect)) continue+ for (const frame of effect.getKeyframes()) {+ for (const key of Object.keys(frame)) if (!["offset", "computedOffset", "easing", "composite"].includes(key)) moving.add(kebab(key))+ }+ }+ return [...moving].sort()+ }+ const all = Array.from(document.querySelectorAll("body, body *"))+ .filter((el) => !["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "HEAD", "META", "LINK"].includes(el.tagName))+ .slice(0, maxElements)+ const indexOf = new Map<Element, number>()+ all.forEach((el, i) => indexOf.set(el, i))+ const elements: ElementSnapshot[] = all.map((el, index) => {+ const attributes: Record<string, string> = {}+ for (const a of Array.from(el.attributes)) attributes[a.name] = a.value.slice(0, 500)+ const parentIndex = el.parentElement ? indexOf.get(el.parentElement) : undefined+ const ownText = collapse(+ Array.from(el.childNodes)+ .filter((n) => n.nodeType === 3)+ .map((n) => n.textContent ?? "")+ .join(" "),+ )+ return {+ index,+ parent: parentIndex === undefined ? null : parentIndex,+ children: Array.from(el.children)+ .map((c) => indexOf.get(c))+ .filter((i): i is number => i !== undefined),+ tag: el.tagName.toLowerCase(),+ selector: selectorOf(el),+ attributes,+ rect: toRect(el.getBoundingClientRect()),+ ownText,+ textRuns: Array.from(el.childNodes)+ .filter((n) => n.nodeType === 3)+ .map((n) => collapse(n.textContent ?? ""))+ .filter((t) => t !== ""),+ text: collapse(el.textContent ?? "").slice(0, 2000),+ lineRects: ownText === "" ? [] : lineRectsOf(el),+ style: readStyle(getComputedStyle(el)),+ before: pseudo(el, "::before"),+ after: pseudo(el, "::after"),+ scroll: { scrollWidth: el.scrollWidth, clientWidth: el.clientWidth, scrollHeight: el.scrollHeight, clientHeight: el.clientHeight },+ motion: motionOf(el),+ placeholder: el.matches(":placeholder-shown") ? { style: readStyle(getComputedStyle(el, "::placeholder")), rect: null } : null,+ modal: (() => {+ try {+ return el.matches(":modal")+ } catch (error) {+ if (error instanceof DOMException) return false+ throw error+ }+ })(),+ }+ })+ const cssText: string[] = []+ for (const sheet of Array.from(document.styleSheets)) {+ const rules = (() => {+ try {+ return Array.from(sheet.cssRules)+ } catch (error) {+ if (error instanceof DOMException) return []+ throw error+ }+ })()+ cssText.push(rules.map((r) => r.cssText).join("\n"))+ }+ const root = document.documentElement+ const errors: unknown = Reflect.get(globalThis, "__detectScriptErrors")+ return {+ viewport: { width: window.innerWidth, height: window.innerHeight },+ url: location.href,+ title: document.title,+ lang: root.lang,+ document: { scrollWidth: root.scrollWidth, clientWidth: root.clientWidth, scrollHeight: root.scrollHeight },+ elements,+ cssText,+ scriptErrors: Array.isArray(errors) ? errors.filter((e): e is string => typeof e === "string") : [],+ scriptErrorsCaptured: Array.isArray(errors),+ }+}++/** Installed before page scripts run, so errors thrown during load reach the snapshot's scriptErrors. */+export const SCRIPT_ERROR_PROBE = `(() => {+ const sink = (globalThis.__detectScriptErrors = []);+ addEventListener("error", (e) => sink.push(String(e.message || e.error || "error")));+ addEventListener("unhandledrejection", (e) => sink.push(String(e.reason && e.reason.message || e.reason)));+})();`diff --git a/plugins/omo/skills/frontend/scripts/detect/snapshot/style-props.ts b/plugins/omo/skills/frontend/scripts/detect/snapshot/style-props.tsnew file mode 100644index 00000000..ddb4b6de--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/snapshot/style-props.ts@@ -0,0 +1,25 @@+export const STYLE_PROPS = [+ "display", "position", "visibility", "opacity", "z-index", "overflow-x", "overflow-y", "transform", "contain",+ "top", "left", "right", "bottom", "width", "height", "max-width", "min-width", "max-height",+ "color", "background-color", "background-image", "background-clip", "-webkit-background-clip", "-webkit-text-fill-color",+ "background-size", "background-repeat", "background-position",+ "font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "word-spacing",+ "text-transform", "text-align", "text-align-last", "text-decoration-line", "text-decoration-thickness", "text-underline-offset",+ "text-overflow", "text-wrap", "white-space", "word-break", "overflow-wrap", "hyphens", "font-variant-numeric", "font-feature-settings",+ "-webkit-line-clamp", "overflow-clip-margin", "font-variant", "font-variant-caps", "background-blend-mode", "mix-blend-mode", "scale", "rotate", "translate", "will-change",+ "border-top-width", "border-right-width", "border-bottom-width", "border-left-width",+ "border-top-style", "border-right-style", "border-bottom-style", "border-left-style",+ "border-top-color", "border-right-color", "border-bottom-color", "border-left-color",+ "border-top-left-radius", "border-top-right-radius", "border-bottom-right-radius", "border-bottom-left-radius",+ "border-image-source", "outline-style", "outline-width", "outline-color", "outline-offset",+ "box-shadow", "text-shadow", "filter", "backdrop-filter", "-webkit-backdrop-filter", "clip-path", "mask-image", "-webkit-mask-image",+ "padding-top", "padding-right", "padding-bottom", "padding-left",+ "margin-top", "margin-right", "margin-bottom", "margin-left",+ "row-gap", "column-gap", "grid-template-columns", "flex-direction", "flex-wrap", "justify-content", "align-items", "column-count",+ "animation-name", "animation-duration", "animation-iteration-count", "animation-timing-function", "animation-direction",+ "animation-delay", "animation-fill-mode", "animation-play-state", "animation-composition",+ "transition-property", "transition-duration", "transition-timing-function",+ "object-fit", "caret-color", "content", "list-style-type", "cursor", "pointer-events",+] as const++export type StyleProp = (typeof STYLE_PROPS)[number]diff --git a/plugins/omo/skills/frontend/scripts/detect/testing/build-snapshot.ts b/plugins/omo/skills/frontend/scripts/detect/testing/build-snapshot.tsnew file mode 100644index 00000000..eccd8296--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/testing/build-snapshot.ts@@ -0,0 +1,78 @@+import type { ElementSnapshot, PageSnapshot, PseudoSnapshot, Rect, Viewport } from "../types"++// Computed-style defaults a Chromium page reports for an unstyled element; a node spec overrides only what it sets.+const DEFAULT_STYLE: Readonly<Record<string, string>> = {+ display: "block", position: "static", visibility: "visible", opacity: "1", "z-index": "auto",+ "overflow-x": "visible", "overflow-y": "visible", transform: "none",+ color: "rgb(0, 0, 0)", "background-color": "rgba(0, 0, 0, 0)", "background-image": "none", "background-clip": "border-box",+ "-webkit-background-clip": "border-box", "-webkit-text-fill-color": "rgb(0, 0, 0)",+ "font-family": "Georgia, serif", "font-size": "16px", "font-weight": "400", "font-style": "normal", "line-height": "24px",+ "letter-spacing": "normal", "word-spacing": "0px", "text-transform": "none", "text-align": "start", "text-align-last": "auto",+ "text-decoration-line": "none", "text-overflow": "clip", "text-wrap": "wrap", "white-space": "normal",+ "border-top-width": "0px", "border-right-width": "0px", "border-bottom-width": "0px", "border-left-width": "0px",+ "border-top-style": "none", "border-right-style": "none", "border-bottom-style": "none", "border-left-style": "none",+ "border-top-color": "rgb(0, 0, 0)", "border-right-color": "rgb(0, 0, 0)", "border-bottom-color": "rgb(0, 0, 0)", "border-left-color": "rgb(0, 0, 0)",+ "border-top-left-radius": "0px", "border-top-right-radius": "0px", "border-bottom-right-radius": "0px", "border-bottom-left-radius": "0px",+ "border-image-source": "none", "outline-style": "none", "box-shadow": "none", "text-shadow": "none", filter: "none",+ "backdrop-filter": "none", "clip-path": "none", "mask-image": "none",+ "padding-top": "0px", "padding-right": "0px", "padding-bottom": "0px", "padding-left": "0px",+ "margin-top": "0px", "margin-right": "0px", "margin-bottom": "0px", "margin-left": "0px",+ "row-gap": "normal", "column-gap": "normal", "animation-name": "none", "animation-duration": "0s",+ "animation-iteration-count": "1", "animation-timing-function": "ease", "transition-property": "all",+ "transition-duration": "0s", "transition-timing-function": "ease", "object-fit": "fill", content: "normal",+}++export type NodeSpec = {+ readonly tag?: string+ readonly id?: string+ readonly attributes?: Readonly<Record<string, string>>+ readonly style?: Readonly<Record<string, string>>+ readonly text?: string+ readonly textRuns?: readonly string[]+ readonly rect?: Partial<Rect>+ readonly lineRects?: readonly Rect[]+ readonly before?: Readonly<Record<string, string>>+ readonly after?: Readonly<Record<string, string>>+ readonly scroll?: Partial<ElementSnapshot["scroll"]>+ readonly motion?: readonly string[]+ readonly modal?: boolean+ readonly placeholder?: Readonly<Record<string, string>>+ readonly children?: readonly NodeSpec[]+}++const pseudo = (style: Readonly<Record<string, string>> | undefined): PseudoSnapshot | null =>+ style ? { style: { ...DEFAULT_STYLE, content: '""', ...style }, rect: null } : null++/** Builds a PageSnapshot from a tree of node specs under <body>, filling Chromium's default computed values. */+export function buildSnapshot(body: readonly NodeSpec[], options: { readonly viewport?: Viewport; readonly cssText?: readonly string[]; readonly scriptErrors?: readonly string[]; readonly scriptErrorsCaptured?: boolean } = {}): PageSnapshot {+ const viewport = options.viewport ?? { width: 1280, height: 800 }+ const elements: ElementSnapshot[] = []+ const add = (spec: NodeSpec, parent: number | null, path: string): number => {+ const index = elements.length+ const tag = spec.tag ?? "div"+ const selector = spec.id ? `#${spec.id}` : `${path} > ${tag}:nth-of-type(${index})`+ const placeholder: ElementSnapshot = {+ index, parent, children: [], tag, selector,+ attributes: { ...(spec.id ? { id: spec.id } : {}), ...spec.attributes },+ rect: { x: 0, y: 0, width: 200, height: 40, ...spec.rect },+ ownText: spec.text ?? "", textRuns: spec.textRuns ?? (spec.text ? [spec.text] : []), text: "", lineRects: spec.lineRects ?? (spec.text ? [{ x: 0, y: 0, width: 160, height: 24, ...spec.rect }] : []),+ style: { ...DEFAULT_STYLE, ...(tag === "span" || tag === "a" ? { display: "inline" } : {}), ...spec.style },+ before: pseudo(spec.before), after: pseudo(spec.after),+ scroll: { scrollWidth: 200, clientWidth: 200, scrollHeight: 40, clientHeight: 40, ...spec.scroll },+ motion: spec.motion ?? [],+ modal: spec.modal ?? false,+ placeholder: spec.placeholder ? { style: { ...DEFAULT_STYLE, ...spec.placeholder }, rect: null } : null,+ }+ elements.push(placeholder)+ const children = (spec.children ?? []).map((c) => add(c, index, selector))+ const text = [spec.text ?? "", ...children.map((i) => elements[i]?.text ?? "")].filter(Boolean).join(" ")+ elements[index] = { ...placeholder, children, text }+ return index+ }+ add({ tag: "body", rect: { width: viewport.width, height: viewport.height }, children: body }, null, "html")+ return {+ viewport, url: "about:blank", title: "", lang: "en",+ document: { scrollWidth: viewport.width, clientWidth: viewport.width, scrollHeight: viewport.height },+ elements, cssText: options.cssText ?? [], scriptErrors: options.scriptErrors ?? [], scriptErrorsCaptured: options.scriptErrorsCaptured ?? true,+ }+}diff --git a/plugins/omo/skills/frontend/scripts/detect/tsconfig.json b/plugins/omo/skills/frontend/scripts/detect/tsconfig.jsonnew file mode 100644index 00000000..261c0d13--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/tsconfig.json@@ -0,0 +1,19 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "lib": ["ESNext", "DOM", "DOM.Iterable"],+ "types": ["bun-types"],+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "exactOptionalPropertyTypes": true,+ "noFallthroughCasesInSwitch": true,+ "noPropertyAccessFromIndexSignature": false,+ "verbatimModuleSyntax": true,+ "noEmit": true,+ "skipLibCheck": true,+ "allowImportingTsExtensions": true+ },+ "include": ["./**/*.ts"]+}diff --git a/plugins/omo/skills/frontend/scripts/detect/types.ts b/plugins/omo/skills/frontend/scripts/detect/types.tsnew file mode 100644index 00000000..75da9ea7--- /dev/null+++ b/plugins/omo/skills/frontend/scripts/detect/types.ts@@ -0,0 +1,124 @@+// Public types of the frontend detect SDK: rules, findings, snapshots, options.+// Rule semantics are adapted from Impeccable's detector (Apache-2.0, Copyright 2025 Paul Bakaus); see ATTRIBUTION.md sections 6-7.++export type Severity = "error" | "warning" | "advisory"+export type RuleCategory = "slop" | "quality"+export type RuleSetting = Severity | "off"++/** Where a rule reads from: the rendered page, or raw source text with no rendering. */+export type RuleEngine = "page" | "source"++export type RuleMeta = {+ readonly id: string+ readonly name: string+ readonly category: RuleCategory+ readonly severity: Severity+ readonly engine: RuleEngine+ readonly description: string+ readonly fixHint: string+}++export type Rect = { readonly x: number; readonly y: number; readonly width: number; readonly height: number }++export type ElementLocation = {+ readonly kind: "element"+ readonly file?: string+ readonly selector: string+ readonly rect: Rect+ readonly viewport: Viewport+}++export type SourceLocation = {+ readonly kind: "source"+ readonly file: string+ readonly line: number+ readonly column: number+}++export type PageLocation = { readonly kind: "page"; readonly file?: string; readonly viewport: Viewport }++export type FindingLocation = ElementLocation | SourceLocation | PageLocation++export type Finding = {+ readonly ruleId: string+ readonly name: string+ readonly category: RuleCategory+ readonly severity: Severity+ readonly message: string+ readonly fixHint: string+ readonly location: FindingLocation+ readonly snippet: string+}++export type Viewport = { readonly width: number; readonly height: number }++/** Computed style values, keyed by CSS property name (kebab-case), as getComputedStyle reports them. */+export type ComputedStyle = Readonly<Record<string, string>>++export type PseudoSnapshot = { readonly style: ComputedStyle; readonly rect: Rect | null }++export type ElementSnapshot = {+ readonly index: number+ readonly parent: number | null+ readonly children: readonly number[]+ readonly tag: string+ readonly selector: string+ readonly attributes: Readonly<Record<string, string>>+ readonly rect: Rect+ /** Text of this element's own direct text nodes, whitespace-collapsed. */+ readonly ownText: string+ /** Each non-empty direct text node of this element, trimmed and whitespace-collapsed, in document order. */+ readonly textRuns: readonly string[]+ /** Full text content, whitespace-collapsed, capped at 2000 characters. */+ readonly text: string+ /** Rendered line boxes of the element's own text nodes, top-down. */+ readonly lineRects: readonly Rect[]+ readonly style: ComputedStyle+ readonly before: PseudoSnapshot | null+ readonly after: PseudoSnapshot | null+ readonly scroll: { readonly scrollWidth: number; readonly clientWidth: number; readonly scrollHeight: number; readonly clientHeight: number }+ /** CSS properties a running animation or transition on this element is moving at capture time (kebab-case, deduplicated). */+ readonly motion: readonly string[]+ /** True when the element is in the top layer as a modal (matches `:modal`: a modal dialog or a fullscreen element). */+ readonly modal: boolean+ /** Computed `::placeholder` style of an input or textarea while it shows its placeholder (`:placeholder-shown`); null otherwise. */+ readonly placeholder: PseudoSnapshot | null+}++export type PageSnapshot = {+ readonly viewport: Viewport+ readonly url: string+ readonly title: string+ readonly lang: string+ readonly document: { readonly scrollWidth: number; readonly clientWidth: number; readonly scrollHeight: number }+ readonly elements: readonly ElementSnapshot[]+ /** Text of every same-origin stylesheet, in document order (for @keyframes, @font-face, raw declarations). */+ readonly cssText: readonly string[]+ /** Errors thrown by page scripts while the snapshot was taken. */+ readonly scriptErrors: readonly string[]+ /** False when the renderer could not install the error probe before page scripts (WebKit on an http(s) URL), so scriptErrors is not evidence of a clean load. */+ readonly scriptErrorsCaptured: boolean+}++export type SourceFile = { readonly path: string; readonly text: string }++export type DetectConfig = {+ /** Per-rule override: a severity, or "off". */+ readonly rules?: Readonly<Record<string, RuleSetting>>+ /** Typefaces the project chose on purpose; never reported as overused. Case-insensitive family names. */+ readonly allowFonts?: readonly string[]+ /** Timing functions the project's design tokens name on purpose (for example an intentional spring). */+ readonly allowEasings?: readonly string[]+ /** The project's design-system tokens; the design-system-* rules report values outside them and stay silent without them. */+ readonly designTokens?: DesignTokens+}++export type DesignTokens = {+ readonly fonts?: readonly string[]+ /** CSS colors (any form parseColor accepts). */+ readonly colors?: readonly string[]+ /** Border radii in px. */+ readonly radii?: readonly number[]+ /** Font sizes in px. */+ readonly fontSizes?: readonly number[]+}diff --git a/plugins/omo/skills/programming/SKILL.md b/plugins/omo/skills/programming/SKILL.mdindex e9413cf4..e0f46c12 100644--- a/plugins/omo/skills/programming/SKILL.md+++ b/plugins/omo/skills/programming/SKILL.md@@ -1,6 +1,6 @@---name: programming-description: "Applies strict, modern language practice (typed errors, exhaustive match, tests that can fail) for Python, Rust, TypeScript, JavaScript, and Go. Use for work on .py, .rs, .ts, .js, or .go files."+description: "Applies strict, modern language practice (typed errors, exhaustive match, tests that can fail) for Python, Rust, TypeScript, JavaScript, and Go. Use for work on .py, .rs, .ts, .js, or .go files, and whenever a test or spec file is written, reshaped, reviewed, or deleted: the four-question test authoring gate and the junk-test classes live here."---# Programming@@ -24,6 +24,7 @@ This skill is an index. The hard per-language rules live under `references/`. Lo| `.rs`, `Cargo.toml`, "Rust" | `references/rust/README.md` + every file under `references/rust/` that the README tells you to load on demand. **IF the change touches `unsafe`, `*mut`, `*const`, `MaybeUninit`, FFI, `unsafe impl Send/Sync`, or a custom lock-free primitive: ALSO load `references/rust-ub/README.md` plus every file under `references/rust-ub/`.** || `.ts`, `.tsx`, `.mts`, `.cts`, `.js`, `.jsx`, `.mjs`, `.cjs`, "TypeScript" / "JavaScript" | `references/typescript/README.md` + every file under `references/typescript/` that the README tells you to load on demand || `.go`, `go.mod`, `go.sum`, `.golangci.yml`, `*.proto` next to a Go module, "Go" / "Golang" | `references/go/README.md` + every file under `references/go/` that the README tells you to load on demand |+ | any test file (`*.test.*`, `*.spec.*`, `*_test.go`, `test_*.py`, `*_test.py`, under `test/`, `tests/` or `__tests__/`), or a change that adds, reshapes, or deletes a test | the language row above PLUS `references/testing/README.md` (the authoring gate) and `references/testing/junk-classes.md` (the table the gate reviewer applies) |3. Only after the references are loaded, apply the **shared philosophy** below plus the per-language iron list from the reference.@@ -31,7 +32,7 @@ This skill is an index. The hard per-language rules live under `references/`. Lo----## Shared philosophy (all three languages)+## Shared philosophy (all four languages)These are not style preferences. They are the seven axioms every recipe in `references/` derives from.@@ -47,82 +48,22 @@ These are not style preferences. They are the seven axioms every recipe in `refe5. **Trust framework guarantees. Validate only at boundaries.** No null checks for values the type system already proves non-null. No `try/except` around code that cannot raise. No `unwrap`/`!`/`as` to paper over a contract you should have encoded in types. No defensive layer for a scenario you cannot name.-6. **Tests are the behavior of record, and only tests that can fail count.** READ the tests covering the area BEFORE you change it: do they encode the intent, cover this path, pass? One wrong before your change is a FINDING — never edit it green. Reproduce a bug before fixing it. The run proves the change; add a test ONLY where the repository keeps tests for this behavior AND a regression would otherwise pass unnoticed — sized like its neighbors, never restating the change. See the test discipline below.+6. **Tests are the behavior of record, and only tests that can fail count.** READ the tests covering the area BEFORE you change it: do they encode the intent, cover this path, pass? One wrong before your change is a FINDING — never edit it green. Reproduce a bug before fixing it. The run proves the change; add a test ONLY where the repository keeps tests for this behavior AND a regression would otherwise pass unnoticed — sized like its neighbors, never restating the change. The authoring gate and the junk-class table are in `references/testing/`.---## TEST DISCIPLINE-### The shape of the test pyramid+Tests are code: the language gate above applies to them, plus [`references/testing/README.md`](references/testing/README.md) (the contract every language's recipes assume) and [`references/testing/junk-classes.md`](references/testing/junk-classes.md) (the table the gate reviewer applies to every test in a diff). Read both before adding, reshaping, or deleting a test.-Where the repository keeps these rungs, test at the cheapest rung that observes the behavior:+**The authoring gate.** Before a test exists, answer all four; a missing answer means do not add it yet.-| Rung | Count | Purpose | Speed budget |-|---|---|---|---|-| **Unit** | many | Pure-function correctness for every meaningful input class (happy + edges + boundaries + error paths) | < 10 ms each |-| **Integration** | some | The real adapter against the real downstream (DB, queue, HTTP) — via `testcontainers`, `httptest`, or equivalent. NEVER a unit test pretending to be integration. | < 1 s each |-| **E2E scenario** | few | One narrative per user-visible outcome. Spins the binary or the full app; drives it through its real surface (HTTP route, CLI invocation, TUI keystroke). Asserts the *observable outcome*, not internal state. | seconds, run on CI |+1. What observable behavior, invariant, or independent contract does it protect?+2. What credible regression makes it fail?+3. Why does existing coverage not already catch that failure? One primary owner per contract, at the strongest boundary; extend a table row before adding a near-duplicate, a copy in another package, or a replay through a wrapper.+4. Does it need a production seam (export, flag, getter, wrapper, injection hook) no production caller needs? Then test at the real boundary instead.-A user-visible outcome you never drove through its real surface is unverified — a green unit suite does not stand in for that run.--### Given / When / Then is mandatory--Every test — unit, integration, E2E — is structured by these three blocks. Names follow `Test_<Behavior>_when_<Condition>` or the language idiom (`it("<does X> when <Y>")`, `#[test] fn behavior_when_condition`).--```-Given: the preconditions and fixtures-When: the single action under test-Then: the observable outcome AND only that outcome-```--One `When` per test. Multiple `When`s = multiple tests. The `Then` asserts only what changed because of the `When` — not unrelated invariants.--### Less mock, the better--Mocks are a last resort, not a default. The priority order:--1. **Real object.** Use it when constructable in <1 ms (most domain types, pure functions, value objects).-2. **In-memory fake.** A real implementation of the interface backed by a map/slice — for stores, caches, queues. The fake has its OWN test that proves it behaves like the real one.-3. **Testcontainer / sandbox.** Real Postgres, real Redis, real S3-compatible (MinIO), via `testcontainers`. Slow but truthful.-4. **HTTP-level fake.** `httptest.Server` (Go), `respx` (Python), `msw` (TS) — fake at the wire, not at the SDK.-5. **Mock.** Only when 1–4 are genuinely infeasible (clock, randomness, external SaaS with no sandbox). Then mock the **narrowest** seam — never an entire service. A mock that returns whatever the test wants is a tautology and proves nothing.--**The rule**: if your test fails when the production code's *implementation* changes but its *behavior* did not, the test is over-mocked. Delete the mock; assert on observable outputs.--### Efficient AND accurate — both, not either--- **Accurate**: the test fails for the bug it names, and only that bug. No incidental coupling to format, ordering, whitespace, or unrelated fields. Assert on the *contract*, not on the dump.-- **Efficient**: the whole unit suite runs in < 30 seconds on a developer laptop. The whole integration suite in < 5 minutes. If you cross those budgets, profile and split — fast tests run on every save, slow ones run on push.-- **Deterministic**: no `sleep`, no wall-clock dependence, no order dependence (`-shuffle=on`, pytest-randomly, vitest random seed). Inject a `Clock`. Subscribe to the event, do not poll for it. Time-based flake is a bug, not a test issue.-- **Isolated**: every test starts from a known fixture and tears down. `t.TempDir()`, `t.Setenv()`, transactional rollback for DB tests. Two tests passing individually but failing together is a fixture leak — fix it immediately. Isolation extends **across processes**: suite-global resources — sandbox/cache roots under a fixed tmpdir path, hardcoded listen ports, container names — are namespaced per run (`mktemp`, port `0`/ephemeral, unique names) so that two checkouts or worktrees of the repo running the suite concurrently cannot interfere. A fixed shared path that works on a single-checkout machine is a flake generator on a multi-agent workstation, and its signature is "a different test fails each run".--### Prompt tests: NEVER assert prose--**FORBIDDEN — NO EXCEPTIONS: a test MUST NOT assert natural-language prompt text.** `expect(prompt).toContain("based on GPT-5.6")`, `not.toContain("old wording")`, `toMatchSnapshot()` on prose, grepping a sentence fragment — every one of these is pretend-coverage. It stays green while the behavior it claims to guard breaks, then blocks every legitimate rewording until someone bumps the pinned string. A reviewer MUST block it as HIGH; deleting such a test is a fix, not a coverage loss. "A nearby test already does it" is not a defense — that test is the disease, not the convention.--Assert ONLY what a machine consumes:--- the builder's routing decision — `expect(getPromptSource(model)).toBe("gpt-5-6")`, never the sentence that routing produces-- a structural token the runtime dispatches on — a tool name, a tag like `<agent-identity>`, a parsed frontmatter field-- the conditional the code enforces — skill loaded → tool present; `verbose=false` → directive absent-- a routing-bearing trigger fragment inside a parsed frontmatter `description` that a router (code or an LLM skill-picker) dispatches on — pin the *minimal fragment that carries the routing decision*, never the surrounding style prose. Such pins are what let a later rewrite change every sentence around them while proving the routing contract survived.--If no machine consumes the text, there is no seam: write NO test and say so in the PR; review guards prose. When you DELEGATE test-writing, hand the child the behavior the test must distinguish ("fails if override precedence breaks"), never a ready-made assertion string, prompt fragment, or marker to copy — a prescribed mechanism that is wrong gets implemented faithfully, and the error ships with a green suite.--### Anti-patterns the skill rejects--| Anti-pattern | Why it fails | Fix |-|---|---|---|-| A test that restates the change (pins a constant, a string, a rename, a call) | Cannot fail for any regression; certifies the diff, not the behavior. | The run is the proof. Delete the test. |-| One mega-test asserting 12 things | First failure hides the next 11. | Split by `Then` clause — one assertion class per test. |-| Mocking every collaborator | Test passes regardless of real behavior. | Use a fake or the real thing. Mock only true unmockables. |-| `time.sleep(0.1)` to "let it finish" | Flake guaranteed. | Subscribe to the completion signal; bounded await. |-| Snapshot tests for everything | Locks formatting, not behavior. | Snapshots for *structure* (CLI help, JSON shape). Assertions for *behavior*. |-| Removing a failing test to "unblock CI" | You just deleted a bug report. | Fix the code or fix the test — never delete to silence. |-| `assert result is not None` and stopping there | Passes when result is garbage. | Assert the *value*, not its existence. |-| Expected value derived from the output under test (`expect(config.prompt).toBe(getPrompt(config.model))` when the criterion is about `config.prompt`) | Recomputes a projection of the output and compares it to itself — passes even when the artifact is built from the wrong input. | Derive the expected value from the test's *input*: `expect(config.prompt).toBe(getPrompt(inputModel))` (independent known-good builder fed the fixture's input), or a stable builder routing decision. |-| Override/precedence fixture equal to its fallback (override == system default) | The assertion passes whether or not the code honored the override — precedence is never exercised. | Make every value the code must select, preserve, or override differ from its fallback. Prove it: temporarily force the regression the test names, watch it fail, revert. |-| Single happy-path E2E, no edges | Most bugs live on edges. | Edges are unit-test territory — but include at least one E2E that exercises an error path. |+The README owns the shape (Given / When / Then, the pyramid, the mock ladder, determinism, isolation, the prompt-test rule) and the "test your test" step: break the production owner, watch the test go red for the intended reason, restore byte for byte. A test that fails on the unchanged base is a bug to fix at its owner; one your own change turns red is fixed at the code or at the test; neither is deleted or edited green to unblock a run.---@@ -180,7 +121,7 @@ A bare default constructor for any of these (no timeouts, no pool tuning, no sch| Test runner | **pytest** | **cargo-nextest** | `bun test` / `vitest` | stdlib `go test -race -shuffle=on -count=1` + `goleak` || UB / soundness gate | (n/a) | **nightly miri** with strict provenance + Tree Borrows pass | (n/a) | **`nilaway`** + `-race` detector + `goleak` are the equivalent gate || Disposable scripts | **PEP 723** inline metadata + `uv run script.py` | **rust-script** with inline `Cargo.toml` block | `bun run script.ts` | `//go:build ignore` + `go run script.go` |-| Bootstrap a new project | `scripts/python/new-project.py` | `scripts/rust/new-project.py` | `scripts/typescript/new-project.ts` | `scripts/go/new-project.py` |+| Bootstrap a new project | `bun run scripts/python/new-project.ts` | `bun run scripts/rust/new-project.ts` | `bun run scripts/typescript/new-project.ts` | `bun run scripts/go/new-project.ts` || Pre-commit / CI gate | `ruff check . && basedpyright && pytest` | `cargo clippy --all-targets -- -D warnings && cargo nextest run && cargo test --doc && cargo +nightly miri nextest run` | `bunx oxlint --type-aware --deny-warnings && bunx oxfmt --check && bunx tsc --noEmit && bun test` | `gofumpt -l . && golangci-lint run ./... && nilaway ./... && go test -race -shuffle=on -count=1 ./...` |For TS/JS, **use oxlint + oxfmt with these two rules by default**: `no-em-dash-copy` and `require-suppression-reason`. Strongly prefer this OXC toolchain for new projects; retain ESLint, Prettier, or Biome only when the repository already uses them. Load [`references/typescript/oxc-lint.md`](references/typescript/oxc-lint.md) for the complete configs, plugin, and type-aware support requirements. Rewrite paired em dashes as asides using parentheses or commas, not colon chains.@@ -278,7 +219,7 @@ After every code-writing session, answer these out loud (in your reply) before d4. **Escape hatches?** Any `Any`, `# type: ignore`, `unwrap`, `expect` outside tests, `as` numeric cast, `!`, `@ts-ignore`, `@ts-expect-error`, a Rust `#[allow]` instead of `#[expect(lint, reason)]`? If yes, fix the type or document why with a comment.5. **Defensive layer?** Any null check, try/except, or `isinstance` guarding a value the type system already proves? If yes, delete.6. **Helpers for one-off?** Any function, class, or trait introduced for a single caller that will never get a second caller? If yes, inline — axiom 0 should have caught it pre-write; this is the backstop.-7. **Tests?** Is the behavior I just introduced locked by a test that would fail if I revert this commit?+7. **Tests?** Does every test I added or reshaped answer the four-question authoring gate (`references/testing/README.md`), go red when I break its production owner, and match no row of `references/testing/junk-classes.md`? Where the repository keeps tests for a behavior I introduced and a regression would otherwise pass unnoticed, is it covered at its owner, not by a copy or a change certificate?8. **Parameter bloat?** Any function I wrote or modified that takes more than 3 parameters — or smuggles them through a dict/kwargs/`...args`/throwaway options object? If yes, group related params into a typed value object. See [Smell 2](references/code-smells.md#smell-2--function-with-more-than-3-parameters).9. **Redundant verification?** Did I perform a destructive action (delete, remove, clear) and then immediately re-query to "confirm" it worked? Did I call a setter then a getter to "verify"? If yes, delete the verification — the operation's contract IS the proof. See [Smell 3](references/code-smells.md#smell-3--redundant-verification-after-a-destructive-action).10. **Negative naming?** Any variable, function, or flag named by the absence of a quality (`isNotValid`, `noErrors`, `DisableX`) when a positive name (`isValid`, `isClean`, `EnableX`) would work? If yes, rename to positive form and invert the branch. See [Smell 4](references/code-smells.md#smell-4--negative-form-names-and-conditions).@@ -300,7 +241,7 @@ These two skills are not optional cosmetics. They are the recovery path for the| Trigger | Skill to load | Why ||---|---|---|| Any [code smell](#code-smells--automatic-review-triggers) fires (250+ LOC, >3 params, redundant verification), OR the post-write loop surfaces 2+ issues, OR the user says "reshape this", "extract this", "clean this up" | `refactor` | Safe codemap-driven multi-step refactor with LSP + tests after each step. Never improvise a structural change. |-| Recent branch contains AI-authored patterns (broad except, dead helpers, vague comments, oversized files, redundant post-action verification), OR the user says "remove slop", "clean AI code", "deslop" | `remove-ai-slops` | Tests pinned FIRST, then categorized parallel cleanup, then quality gates. Behavior-preserving. |+| Recent branch contains AI-authored patterns (broad except, dead helpers, vague comments, oversized files, redundant post-action verification, junk tests), OR the user says "remove slop", "clean AI code", "deslop" | `remove-ai-slops` | Behavior locked by gate-passing tests FIRST, then categorized parallel cleanup (junk tests included, each cut proven by a mutation), then quality gates. Behavior-preserving. || Rust code touches `unsafe`, `*mut`, `*const`, `MaybeUninit`, FFI, `unsafe impl Send/Sync`, or a custom lock-free primitive | `references/rust-ub/` | Full UB taxonomy + Miri strictness escalation. Every `unsafe` block must survive Miri Level 3 (strict provenance + symbolic alignment + preemption) before it ships. |---@@ -389,6 +330,6 @@ These two skills are not optional cosmetics. They are the recovery path for the## Activation-This skill activates whenever you are writing or modifying any `.py`, `.pyi`, `.rs`, `.ts`, `.tsx`, `.mts`, `.cts`, `.js`, `.jsx`, `.mjs`, `.cjs`, `.go` file, or any project manifest (`pyproject.toml`, `Cargo.toml`, `package.json`, `tsconfig.json`, `.oxlintrc.json`, `.oxfmtrc.json`, `go.mod`, `go.sum`, `.golangci.yml`, `Taskfile.yml`, `buf.yaml`, `sqlc.yaml`). **Even one-off scripts get the full treatment** - that is the whole point of `uv run` + PEP 723, `rust-script`, `bun run`, and `go run` + `//go:build ignore`: production hygiene with throwaway ergonomics.+This skill activates whenever you are writing or modifying any `.py`, `.pyi`, `.rs`, `.ts`, `.tsx`, `.mts`, `.cts`, `.js`, `.jsx`, `.mjs`, `.cjs`, `.go` file, any test or spec file in those languages, or any project manifest (`pyproject.toml`, `Cargo.toml`, `package.json`, `tsconfig.json`, `.oxlintrc.json`, `.oxfmtrc.json`, `go.mod`, `go.sum`, `.golangci.yml`, `Taskfile.yml`, `buf.yaml`, `sqlc.yaml`). **Even one-off scripts get the full treatment** - that is the whole point of `uv run` + PEP 723, `rust-script`, `bun run`, and `go run` + `//go:build ignore`: production hygiene with throwaway ergonomics.The references contain the recipes. **Read them before writing code. Re-read them when the model drifts.** The post-write review loop is non-negotiable.diff --git a/plugins/omo/skills/programming/references/go/README.md b/plugins/omo/skills/programming/references/go/README.mdindex 41257132..f1973e55 100644--- a/plugins/omo/skills/programming/references/go/README.md+++ b/plugins/omo/skills/programming/references/go/README.md@@ -69,7 +69,7 @@ Read these per-file references for the canonical patterns:- **CLI** → `cobra-stack.md` — cobra layout, slog integration, graceful shutdown on signals, fang-style colored help.- **TUI** → `bubbletea-v2.md` — v2 model, `SetVirtualCursor(false)` + `tea.View{Cursor}` for CJK IME, why v1 was broken for Korean/Japanese/Chinese input.- **Testing** → `testing.md` — table-driven tests, `require` vs `assert`, `autogold` snapshots, `gopter` property tests, `testcontainers` for integration, `goleak` for goroutine leaks.-- **Bootstrap** → `bootstrap.md` — `new-project.go` invocation, project layout (`cmd/`, `internal/`, `pkg/`), Taskfile, CI.+- **Bootstrap** → `bootstrap.md` — `scripts/go/new-project.ts` invocation, project layout (`cmd/`, `internal/`, `pkg/`), Taskfile, CI.- **Strict config** → `golangci-strict.md` — the canonical `.golangci.yml` with the full linter whitelist and per-linter rationale.- **One-liners** → `one-liners.md` — `go run` scripts with `//go:build ignore`, `gorun`-style invocation.diff --git a/plugins/omo/skills/programming/references/go/bootstrap.md b/plugins/omo/skills/programming/references/go/bootstrap.mdindex ff44dbc3..941b5191 100644--- a/plugins/omo/skills/programming/references/go/bootstrap.md+++ b/plugins/omo/skills/programming/references/go/bootstrap.md@@ -1,6 +1,6 @@# Bootstrap — Project Layout, Toolchain, Taskfile, CI-What every new Go project gets in the first 60 seconds. Drop the script in `scripts/go/new-project.go` does all of this — this document explains *what* it produces and *why*.+What every new Go project gets in the first 60 seconds. The scaffold `bun run ../../scripts/go/new-project.ts <name>` does all of this — this document explains *what* it produces and *why*.## Toolchain pin@@ -318,7 +318,7 @@ Go 1.23+ HTTP service for {one-line purpose}.- 250 pure LOC ceiling per file — split before adding lines```-The skill's `cmd/new-project.go` writes this file with project-specific values filled in.+The skill's `scripts/go/new-project.ts` writes this file with project-specific values filled in.## Sourcesdiff --git a/plugins/omo/skills/programming/references/python/README.md b/plugins/omo/skills/programming/references/python/README.mdindex 0b3ebf64..bfcab9e9 100644--- a/plugins/omo/skills/programming/references/python/README.md+++ b/plugins/omo/skills/programming/references/python/README.md@@ -221,9 +221,9 @@ Canonical defaults (override only if `pyproject.toml` explicitly picks somethingScaffold a new project with all strict defaults pre-configured:```bash-uv run ../../scripts/python/new-project.py myproject-uv run ../../scripts/python/new-project.py myproject --path ./workspace-uv run ../../scripts/python/new-project.py myproject --lib # publishable library+bun run ../../scripts/python/new-project.ts myproject+bun run ../../scripts/python/new-project.ts myproject --path ./workspace+bun run ../../scripts/python/new-project.ts myproject --lib # publishable library```Creates via `uv init`, then injects basedpyright `typeCheckingMode = "all"` + ruff `select = ["ALL"]` + pytest strict. Cross-platform (macOS, Linux, Windows).@@ -234,7 +234,7 @@ For manual setup: `uv init --app myproject`, then load `pyproject-strict.md`.Every `.py` script — even throwaway — MUST use PEP 723 inline metadata with the `# ─── How to run ───` comment block. No venv, no `requirements.txt`. The script IS the environment spec. A script without the usage comment block is incomplete.-Scaffold with: `uv run ../../scripts/python/new-script.py <name> --deps "httpx2[http2,brotli,zstd]"` (writes to temp dir by default, `--output` for specific path).+Scaffold with: `bun run ../../scripts/python/new-script.ts <name> --deps "httpx2[http2,brotli,zstd]"` (writes to temp dir by default, `--output` for specific path).Load `one-liners.md` for full patterns, examples, and anti-patterns.diff --git a/plugins/omo/skills/programming/references/python/one-liners.md b/plugins/omo/skills/programming/references/python/one-liners.mdindex de1ddbc2..12a6c6e7 100644--- a/plugins/omo/skills/programming/references/python/one-liners.md+++ b/plugins/omo/skills/programming/references/python/one-liners.md@@ -87,17 +87,17 @@ Replace `<SCRIPT_NAME>` with the actual filename. Add argument descriptions if t## Template generator-Use `scripts/new-script.py` to scaffold a new PEP 723 script with all boilerplate pre-filled:+Use `../../scripts/python/new-script.ts` (Bun) to scaffold a new PEP 723 script with all boilerplate pre-filled:```bash# Generate to temp directory (default)-uv run scripts/new-script.py my_tool+bun run ../../scripts/python/new-script.ts my_tool# Generate to specific path-uv run scripts/new-script.py my_tool --output ./scripts/my_tool.py+bun run ../../scripts/python/new-script.ts my_tool --output ./scripts/my_tool.py-# With extra dependencies-uv run scripts/new-script.py my_tool --deps "polars" "duckdb" "rich"+# With extra dependencies (repeat --deps for each)+bun run ../../scripts/python/new-script.ts my_tool --deps polars --deps duckdb --deps rich```## Common dependency setsdiff --git a/plugins/omo/skills/programming/references/testing/README.md b/plugins/omo/skills/programming/references/testing/README.mdnew file mode 100644index 00000000..f66560ce--- /dev/null+++ b/plugins/omo/skills/programming/references/testing/README.md@@ -0,0 +1,82 @@+# Testing++Read this before creating or editing any test file (`*.test.*`, `*.spec.*`, `*_test.go`, `test_*.py`, `tests/`, `__tests__/`) and before deciding whether a change needs a test at all. The per-language recipes live beside their language (`../go/testing.md`, `../rust/proptest-insta.md`, the "In tests" sections of the other READMEs); this file is the language-independent contract they all assume. [`junk-classes.md`](junk-classes.md) is the companion table: every class there is a test this file tells you not to write.++## Before writing: the authoring gate++Answer all four; a missing answer means do not add the test yet.++1. **What observable behavior, invariant, or independent contract does it protect?** Name it in the test name.+2. **What credible regression makes it fail?** If no plausible edit to the production owner turns it red, it is a [change certificate or cannot-fail](junk-classes.md), not a test.+3. **Why does existing coverage not already catch that failure?** Each contract has one primary owner test at the strongest boundary. Extend a table row or a shared fixture instead of adding a near-duplicate, a copy in another package, or a replay through a wrapper.+4. **Does it need a production seam no production caller needs** (an export, flag, getter, reset hook, wrapper, injection point)? If yes, test at the real boundary instead; a seam that exists for one test is a [seam keeper](junk-classes.md).++The run proves the change; a test proves that the next change cannot silently undo it. So add a test only where the repository keeps tests for this behavior AND a regression would otherwise pass unnoticed by the run and the existing tests. A bug fix starts from a reproduction that fails on the pre-fix code for the intended reason (an existing owner test that already fails may serve as that proof). Prose has no behavioral seam ([Prompt tests](#prompt-tests-assert-behavior-never-text) below).++A test that fails on the unchanged base is a product bug to fix at its owner; a test your own change turns red is fixed at the code or at the test. Neither is deleted or edited green to unblock a run.++## Shape++### The pyramid, cheapest rung first++| Rung | Count | Purpose | Budget |+|---|---|---|---|+| Unit | many | pure-function correctness for every meaningful input class (happy, edge, boundary, error path) | < 10 ms each; whole unit suite < 30 s |+| Integration | some | the real adapter against the real downstream (DB, queue, HTTP) via `testcontainers`, `httptest`, or the equivalent; never a unit test pretending to be one | < 1 s each; suite < 5 min |+| E2E scenario | few | one narrative per user-visible outcome, driven through the real surface (HTTP route, CLI invocation, TUI keystroke), asserting the observable outcome, not internal state; include at least one error-path scenario | seconds, on CI |++A user-visible outcome never driven through its real surface is unverified; a green unit suite does not stand in for that run.++### Given / When / Then++Every test is three blocks: the preconditions and fixtures, the single action under test, the observable outcome AND only that outcome. One `When` per test; several `When`s are several tests. Names state behavior and condition (`it("<does X> when <Y>")`, `Test_<Subject>_<Outcome>_when_<Condition>`, `#[test] fn behavior_when_condition`) so a failure reads without the body. Twelve assertions in one test hide eleven failures behind the first: split by `Then`.++### Less mock, the better++1. **Real object** when constructable in under a millisecond (domain types, pure functions, value objects).+2. **In-memory fake**: a real implementation of the interface backed by a map or slice (stores, caches, queues), with its own test proving it behaves like the real one.+3. **Testcontainer or sandbox**: real Postgres, Redis, S3-compatible store.+4. **Wire-level fake**: `httptest.Server`, `respx`, `msw`; fake at the wire, not at the SDK.+5. **Mock**, only when 1-4 are infeasible (clock, randomness, an external SaaS with no sandbox), at the narrowest seam, never a whole service.++If the test fails when the owner's *implementation* changes but its *behavior* did not, it is over-mocked: delete the mock and assert on observable outputs. A mock that returns whatever the assertion then checks is a [mock echo](junk-classes.md). A boundary list (allowlist, flag filter) is tested with the real list imported from production, not a copy.++### Accurate, efficient, deterministic, isolated++- **Accurate**: the test fails for the bug it names and only that bug. Assert the contract, not a dump; no coupling to format, ordering, whitespace, or unrelated fields. Snapshots pin structure (CLI help, a JSON shape), never behavior or prose.+- **Efficient**: when a suite crosses its budget, profile and split it; fast tests run on every save, slow ones on push.+- **Deterministic**: no `sleep`, no wall-clock dependence, no order dependence (`-shuffle=on`, pytest-randomly, a random vitest seed). Inject a clock. For async behavior subscribe to the exact event or state change BEFORE triggering the action, then await it with a bounded timeout that fails with a message; the timeout is a circuit breaker, never the synchronization. A test that passes 9 of 10 runs is broken.+- **Isolated**: every test starts from a known fixture and tears down (`t.TempDir()`, `t.Setenv()`, transactional rollback). Two tests that pass alone and fail together are a fixture leak; fix the leak, never the order, and never `.only` / `.skip` / a separate process to hide it. Suite-global resources (sandbox roots, listen ports, container names) are namespaced per run (`mktemp`, port `0`, unique names) so two checkouts running the suite concurrently cannot interfere; the signature of that leak is "a different test fails each run".++### Prompt tests: assert behavior, never text++A prompt, skill, rule, or markdown file is prose; its wording changes every sprint. `toContain("<sentence>")`, `not.toContain("old wording")`, a snapshot of prose, a word count, a phrase-occurrence count: each stays green while the behavior it claims to guard breaks, then blocks every legitimate rewording. Assert only what a machine consumes: a builder's routing decision (`expect(getPromptSource(model)).toBe("gpt-5-6")`), a structural token the runtime dispatches on (a tool name, a tag, a parsed frontmatter field), the conditional the code enforces (skill loaded -> tool present; `verbose=false` -> directive absent), equality between two shipped copies of one artifact, or the minimal routing-bearing fragment of a parsed `description` that a router dispatches on (such a pin lets a later rewrite change every sentence around it while proving the routing contract survived). If nothing consumes the text, write no test. Nearby prose pins are existing violations, not a convention.++When delegating test-writing, hand the child the behavior the test must distinguish ("fails if override precedence breaks"), never a ready-made assertion string, prompt fragment, or marker to copy: a prescribed mechanism that is wrong gets implemented faithfully and ships behind a green suite.++## After writing: test your test++A test earns its place by failing. Before the PR, for each new or reshaped test:++1. **Break the owner** (flip the condition, drop the branch, return a constant, skip the write) and run the test. Confirm the mutated bytes are actually in the file before reading the result; a no-op edit "passes" identically to the original.+2. **Red for the intended reason?** Read the failure message: a loose pattern can match the base's generic error by coincidence (a false red), and a fake that simulates the failure by a different mechanism than the guard reads fails with the fix present.+3. **Still green?** Then one of: the test is vacuous (fix the assertion); the mutant is equivalent (a `try/catch`, fallback, or normalization maps it back to the same outcome: retarget the mutation at the observable claim); a second rule already produces the same outcome (make the input exercise only the rule under test and assert the recorded reason); or the mutated code is dead (delete the code, not the test's teeth).+4. **Restore byte for byte.** Never commit a mutation.++Assertion shapes that survive this step:++| Vacuous shape | Why it passes with the bug present | Discriminating shape |+|---|---|---|+| expected value derived from the output under test | compares a projection of the output to itself | derive the expected value from the test's input |+| override fixture equal to its fallback | precedence is never exercised | every value the code must select or override differs from the fallback |+| `>= n` / `> 0` over independently produced items | removing one item still satisfies the bound | pin the exact set |+| a count after deduplication where duplicates are byte-identical to a mandatory item | dropping all duplicates gives the same count | distinct payloads, assert retention and placement |+| the argv, flags, URL, or request handed to a child | an input transcript, not the child's outcome | drive the real component and assert the state it resolved, with a control case |+| a counter or filter keyed on a value the code path never produces | both sides count zero | count the operation itself |+| a copy of the production component, props, or allowlist | the copy passes while the shipped one is broken | mount or import the real one |+| a timing assertion for an off-thread or performance claim | passes on the base at fixture size | prove performance on the field harness; keep the unit test to behavior |+| a gated or fallback path tested without forcing it | the base's own error path produces the same side effect | force the path (flag, crash limit) and assert the reason the new path records |++## Delegation and review++The gate reviewer applies [`junk-classes.md`](junk-classes.md) to every test in the diff and blocks a prose pin as HIGH; a test that would be deleted there is a test not to write. Deleting such a test is a fix, not a coverage loss, and needs the proof rule in that file.diff --git a/plugins/omo/skills/programming/references/testing/junk-classes.md b/plugins/omo/skills/programming/references/testing/junk-classes.mdnew file mode 100644index 00000000..d81b1d7f--- /dev/null+++ b/plugins/omo/skills/programming/references/testing/junk-classes.md@@ -0,0 +1,56 @@+# Junk classes, retention bar, marks++One table for three jobs: writing a test (`programming`), cleaning a branch (`remove-ai-slops`), and auditing a suite. A test that matches a class below is junk unless the retention bar keeps it. The gate reviewer applies the same table; a test that would be deleted in review is a test not to write.++## Marks (one per test declaration; one per row when table rows differ)++| Mark | Meaning | What the ledger line names |+|---|---|---|+| `R` retain | guards a contract | the contract and the regression it catches |+| `F` fix | real contract, weak assertion (a negative that passes when only one of several items is missing; `toBeTruthy` on a value that is always an object; a lower bound over independently removable items) | the repaired assertion |+| `C` consolidate | the assertion moves into a keeper (a table row in a sibling, a stronger boundary suite); the declaration disappears | the keeper |+| `D` delete | no contract, or another test owns it | the owner test that still fails on the regression, or why no contract exists; plus a proof receipt |++## Junk classes (candidates for `D` or `C`)++| Class | What it looks like | Proof that it is junk |+|---|---|---|+| Cannot fail | no assertion; `expect(x).toBe(x)`; expected value computed by the code under test; `assert result is not None` and nothing else; an override fixture equal to its fallback; assertion inside a callback that never runs | a mutation of the owner the test survives |+| Change certificate | pins the diff, not a behavior: a constant, a string, a rename, a call, the shape of the edit the PR made | revert the change: the test fails for the diff, not for a regression; the run is the proof |+| Mock echo | the mock returns the value the test then asserts; the behavior lives in the mock | mutate the owner: test stays green |+| Implementation mirror | asserts call order, call count, private helper args, bracket-notation access to private members, internal state shape that a behavior-preserving refactor would break | a keeper at the real boundary catches the behavioral mutation |+| Prose pin | asserts wording, headings, section order, snapshots, phrase counts, or length of `SKILL.md`, prompts, `AGENTS.md`, docs, rule text | no runtime behavior to mutate; cite the repo's prose-test rule |+| Copied inventory | a hard-coded list of exports, files, tools, keys that mirrors the source and fails only when someone edits both | a generator or freshness check or a real consumer already owns it |+| Source grep | reads a source file and greps for a string or import | an identifier-only refactor turns it red for no reason; a behavior mutation it misses |+| Duplicate contract | the same input/output asserted at two or more layers with no distinct transport or lifecycle risk; an adapter package's copy of a Core package's test | the mutation is caught by both: keep the stronger boundary |+| Layer replay | a shared helper re-tested through every wrapper that calls it | one helper owner test plus one wiring test per real wrapper |+| Seam keeper | exists to keep a test-only export, flag, getter, or reset hook alive | `knip` or grep shows no production caller; delete test and seam together |+| Fabricated postcondition | the fixture supplies the receipt, ordering, or stored state the owner should produce; asserts a store nothing writes | mutate the writer: test stays green |+| Capability restatement | asserts a flag or capability is `true` instead of the delivery it promises | a delivery test owns it, or none exists (then `F`, not `D`) |+| Input transcript | asserts the argv, flags, URL, or request the code handed to a child, not the state the child resolved | mutate the child's handling of that input: test stays green; the witness drives the real component and asserts resolved state |+| Misnamed | the name promises a behavior its inputs never exercise | read the assertions; mark by what it actually checks |+| Near-duplicate cases | N tests differing only in input literals | `C` into one table (`it.each` / `test.each`, or a loop over a typed array where the package's test typings lack `.each`); typecheck after; every old assertion stays a row |++## Retention bar (these stay `R` even when they match a class above)++Keep a test that independently guards a public API, SDK, RPC or app-server protocol, config schema or default, migration, storage format, security boundary, platform behavior, prompt-byte or shipped-copy equality between real artifacts, generated or cross-language contract, package or install payload, release, or architecture invariant (meta-audits, tracked-artifact audits). Say which one in the test. Also keep:++- **Node-compat suites**: anything that runs shipped code under real Node is a platform contract even when a Bun run covers the same assertions.+- **Issue regressions**: a test naming an issue number stays until another test is shown to fail on that exact regression.+- **Machine-consumed text**: parsed fields, sentinel tokens, tool names, schema keys, a routing-bearing fragment of a parsed frontmatter `description`.+- **Baseline-red tests**: a test that fails on the unchanged base is a product bug to fix at its owner, never a deletion.++Outside that list, a source-inspection test survives only as the cheapest independent guard of a user-facing key, byte, or path that an identifier-only refactor leaves green. Static or slow is never a reason to delete.++## Proof rule for `D` and `C`++Break the production owner (flip a condition, drop a branch, return a constant, skip a write) and run the candidate and its named keeper on the unmodified test tree:++| Candidate | Keeper | Verdict |+|---|---|---|+| green | red | candidate cannot catch this: `D` proven |+| red | red | candidate redundant for this behavior: `D` or `C` proven |+| red | green | candidate is the ONLY proof: `R`, or `C` it into the keeper and re-run |+| green | green | the mutation missed the behavior: confirm the edit landed, then pick another mutation |++Restore the owner byte for byte; never commit a mutation. A prose pin needs no mutation: the receipt is the assertion line plus the repo rule. Coverage diffs prove lines still execute, not that anything still asserts on them; pair a coverage diff with at least one mutation per theme.diff --git a/plugins/omo/skills/programming/references/typescript/README.md b/plugins/omo/skills/programming/references/typescript/README.mdindex dea5d578..fcde2d2e 100644--- a/plugins/omo/skills/programming/references/typescript/README.md+++ b/plugins/omo/skills/programming/references/typescript/README.md@@ -184,10 +184,9 @@ Tests are strict too, with these exceptions (configure in `.oxlintrc.json` overr|---|---|| Use `expect()` assertions | That's how testing works || Use magic numbers | Test data |-| Access private members via bracket notation | Testing internals || Skip readonly on test fixtures | Mutable setup/teardown |-Tests still follow the iron list — branded types, typed errors, exhaustive switch.+Tests still follow the iron list — branded types, typed errors, exhaustive switch — and the authoring gate in [`../testing/README.md`](../testing/README.md). Private members are reached through the public boundary, never by bracket notation: a test on internals is an implementation mirror that a behavior-preserving refactor breaks.## Existing codebasesdiff --git a/plugins/omo/skills/programming/scripts/go/new-project.py b/plugins/omo/skills/programming/scripts/go/new-project.pydeleted file mode 100755index 6a5f9462..00000000--- a/plugins/omo/skills/programming/scripts/go/new-project.py+++ /dev/null@@ -1,138 +0,0 @@-#!/usr/bin/env -S uv run --script-# /// script-# requires-python = ">=3.11"-# dependencies = [-# "typer",-# "rich",-# ]-# ///--# ─── How to run ───-# 1. Install uv (if not installed):-# curl -LsSf https://astral.sh/uv/install.sh | sh-# 2. Run:-# uv run new-project.py myservice-# uv run new-project.py myservice --module github.com/your-org/myservice-# ──────────────────-#-# Creates a new Go project with the canonical strict layout:-# - go.mod with go 1.23-# - .golangci.yml (v2, strict bundle)-# - Taskfile.yml (fmt + lint + test + build)-# - cmd/server/main.go entrypoint-# - internal/{cmd,config,api,domain,obs} skeletons-# - .github/workflows/ci.yml-#-# Templates live in ./templates/ — keep this script under 250 pure LOC.--from __future__ import annotations--import subprocess-import sys-from pathlib import Path-from string import Template--import typer-from rich.console import Console--console = Console(stderr=True)--TEMPLATES_DIR = Path(__file__).parent / "templates"---def _render(template_file: str, **subs: str) -> str:- """Read a template file and apply $placeholder substitutions.-- Uses string.Template ($name) so Go/YAML curly braces stay literal.- """- raw = (TEMPLATES_DIR / template_file).read_text()- if not subs:- return raw- return Template(raw).substitute(**subs)---# (template-file → relative output path; is_format = .format() is run)-FILES: list[tuple[str, str, bool]] = [- (".golangci.yml", ".golangci.yml", False),- ("Taskfile.yml", "Taskfile.yml", False),- (".editorconfig", ".editorconfig", False),- ("gitignore", ".gitignore", False),- ("ci.yml", ".github/workflows/ci.yml", False),- ("run.go", "internal/cmd/run.go", False),- ("config.go", "internal/config/config.go", False),- ("main.go.tmpl", "cmd/server/main.go", True),- ("AGENTS.md.tmpl", "AGENTS.md", True),- ("README.md.tmpl", "README.md", True),-]---def _init_go_module(project_dir: Path, module: str) -> None:- try:- subprocess.run(- ["go", "mod", "init", module],- cwd=project_dir,- check=True,- capture_output=True,- )- console.print(f" [dim]ran[/] go mod init {module}")- except (subprocess.CalledProcessError, FileNotFoundError) as e:- console.print(f" [yellow]warn[/] go mod init failed ({e}); writing fallback go.mod")- (project_dir / "go.mod").write_text(f"module {module}\n\ngo 1.23\n")---def _create_layout(project_dir: Path) -> None:- """Create the canonical internal/ tree."""- subdirs = [- "cmd/server",- "internal/cmd",- "internal/config",- "internal/api",- "internal/domain",- "internal/obs",- ".github/workflows",- ]- for sd in subdirs:- (project_dir / sd).mkdir(parents=True)---def _write_files(project_dir: Path, name: str, module: str, purpose: str) -> None:- """Render every template into the project tree."""- for tmpl_name, out_rel, is_format in FILES:- subs = (- {"name": name, "module": module, "short_purpose": purpose}- if is_format- else {}- )- content = _render(tmpl_name, **subs)- out_path = project_dir / out_rel- out_path.parent.mkdir(parents=True, exist_ok=True)- out_path.write_text(content)- console.print(f" [dim]wrote[/] {out_rel}")---def main(- name: str,- path: str = typer.Option(".", help="Parent dir"),- module: str = typer.Option("", help="Go module path; default: <name>"),- purpose: str = typer.Option("HTTP", help="Short purpose for AGENTS.md"),-) -> None:- """Scaffold a new Go project with the strict toolchain."""- project_dir = Path(path) / name- if project_dir.exists():- console.print(f"[red]✗[/red] {project_dir} already exists")- sys.exit(1)-- module_path = module or name-- project_dir.mkdir(parents=True)- _create_layout(project_dir)- _init_go_module(project_dir, module_path)- _write_files(project_dir, name, module_path, purpose)-- console.print(f"\n[bold green]Done![/] cd {project_dir}")- console.print(" go get github.com/caarlos0/env/v11")- console.print(" task # fmt + lint + test")---if __name__ == "__main__":- typer.run(main)diff --git a/plugins/omo/skills/programming/scripts/go/new-project.ts b/plugins/omo/skills/programming/scripts/go/new-project.tsnew file mode 100644index 00000000..c4a85dab--- /dev/null+++ b/plugins/omo/skills/programming/scripts/go/new-project.ts@@ -0,0 +1,197 @@+#!/usr/bin/env bun+/**+ * Scaffold a new Go project with the canonical strict layout: go.mod (go 1.23),+ * .golangci.yml (v2 strict bundle), Taskfile.yml, cmd/server/main.go,+ * internal/{cmd,config,api,domain,obs} skeletons, and .github/workflows/ci.yml.+ *+ * ─── How to run ───+ * 1. Install Bun: curl -fsSL https://bun.sh/install | bash+ * 2. Run:+ * bun run new-project.ts myservice+ * bun run new-project.ts myservice --module github.com/your-org/myservice+ * ──────────────────+ *+ * Templates live in ./templates/. `.tmpl` files take Python string.Template+ * placeholders ($name, ${name}, $$ for a literal $); every other file is copied verbatim.+ * Exit codes: 0 created, 1 scaffold failure, 2 usage error.+ */++import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { parseArgs } from "node:util";+import { assertNever, runTool } from "../shared/run-tool.ts";++const USAGE = `Usage: bun run new-project.ts <name> [--path <dir>] [--module <path>] [--purpose <text>]++Arguments:+ name Project directory and default module name++Options:+ --path Parent dir (default: current dir)+ --module Go module path (default: <name>)+ --purpose Short purpose for AGENTS.md (default: HTTP)+ -h, --help Show this help`;++const TEMPLATES_DIR = join(import.meta.dir, "templates");++const LAYOUT = [+ "cmd/server",+ "internal/cmd",+ "internal/config",+ "internal/api",+ "internal/domain",+ "internal/obs",+ ".github/workflows",+] as const;++const FILES = [+ { template: ".golangci.yml", output: ".golangci.yml", substitute: false },+ { template: "Taskfile.yml", output: "Taskfile.yml", substitute: false },+ { template: ".editorconfig", output: ".editorconfig", substitute: false },+ { template: "gitignore", output: ".gitignore", substitute: false },+ { template: "ci.yml", output: ".github/workflows/ci.yml", substitute: false },+ { template: "run.go", output: "internal/cmd/run.go", substitute: false },+ { template: "config.go", output: "internal/config/config.go", substitute: false },+ { template: "main.go.tmpl", output: "cmd/server/main.go", substitute: true },+ { template: "AGENTS.md.tmpl", output: "AGENTS.md", substitute: true },+ { template: "README.md.tmpl", output: "README.md", substitute: true },+] as const;++// Python string.Template grammar: $$ escape, $identifier, ${identifier}, or a bare $ (invalid).+const PLACEHOLDER = /\$(?:(\$)|([_a-z][_a-z0-9]*)|\{([_a-z][_a-z0-9]*)\}|())/gi;++type ProjectOptions = {+ readonly name: string;+ readonly path: string;+ readonly module: string;+ readonly purpose: string;+};++type Cli =+ | { readonly kind: "run"; readonly options: ProjectOptions }+ | { readonly kind: "help" }+ | { readonly kind: "usage"; readonly problem: string };++class ScaffoldError extends Error {+ constructor(+ readonly kind: "exists" | "template",+ message: string,+ ) {+ super(message);+ this.name = "ScaffoldError";+ }+}++function parseCli(): Cli {+ try {+ const { values, positionals } = parseArgs({+ args: Bun.argv.slice(2),+ options: {+ path: { type: "string", default: "." },+ module: { type: "string", default: "" },+ purpose: { type: "string", default: "HTTP" },+ help: { type: "boolean", short: "h", default: false },+ },+ allowPositionals: true,+ strict: true,+ });+ if (values.help) return { kind: "help" };+ const [name, ...extra] = positionals;+ if (name === undefined || extra.length > 0) return { kind: "usage", problem: "expected exactly one project name" };+ const options = { name, path: values.path, module: values.module || name, purpose: values.purpose };+ return { kind: "run", options };+ } catch (error) {+ if (error instanceof TypeError) return { kind: "usage", problem: error.message };+ throw error;+ }+}++function substitute(template: string, file: string, values: ReadonlyMap<string, string>): string {+ return template.replace(+ PLACEHOLDER,+ (match: string, escaped: string | undefined, named: string | undefined, braced: string | undefined) => {+ if (escaped !== undefined) return "$";+ const key = named ?? braced;+ if (key === undefined) throw new ScaffoldError("template", `${file}: invalid placeholder near "${match}"`);+ const value = values.get(key);+ if (value === undefined) throw new ScaffoldError("template", `${file}: unknown placeholder $${key}`);+ return value;+ },+ );+}++function initGoModule(projectDir: string, module: string): void {+ const init = runTool("go", ["mod", "init", module], projectDir);+ switch (init.kind) {+ case "ok":+ console.error(` ran go mod init ${module}`);+ return;+ case "unavailable":+ case "failed": {+ const detail = init.kind === "unavailable" ? init.reason : `exit ${init.status}: ${init.stderr.trim()}`;+ console.error(` warn go mod init failed (${detail}); writing fallback go.mod`);+ writeFileSync(join(projectDir, "go.mod"), `module ${module}\n\ngo 1.23\n`);+ return;+ }+ default:+ return assertNever(init);+ }+}++function writeFiles(projectDir: string, { name, module, purpose }: ProjectOptions): void {+ const values = new Map([+ ["name", name],+ ["module", module],+ ["short_purpose", purpose],+ ]);+ for (const { template, output, substitute: render } of FILES) {+ // The generated project is LF (its .editorconfig says end_of_line = lf); a CRLF checkout of the templates must not leak in.+ const raw = readFileSync(join(TEMPLATES_DIR, template), "utf8").replace(/\r\n/g, "\n");+ const outPath = join(projectDir, output);+ mkdirSync(dirname(outPath), { recursive: true });+ writeFileSync(outPath, render ? substitute(raw, template, values) : raw);+ console.error(` wrote ${output}`);+ }+}++function scaffold(options: ProjectOptions): void {+ const projectDir = join(options.path, options.name);+ if (existsSync(projectDir)) throw new ScaffoldError("exists", `✗ ${projectDir} already exists`);++ mkdirSync(projectDir, { recursive: true });+ for (const dir of LAYOUT) mkdirSync(join(projectDir, dir), { recursive: true });+ initGoModule(projectDir, options.module);+ writeFiles(projectDir, options);++ console.error(`\nDone! cd ${projectDir}`);+ console.error(" go get github.com/caarlos0/env/v11");+ console.error(" task # fmt + lint + test");+}++function main(): number {+ const cli = parseCli();+ switch (cli.kind) {+ case "help":+ console.log(USAGE);+ return 0;+ case "usage":+ console.error(`Error: ${cli.problem}\n\n${USAGE}`);+ return 2;+ case "run":+ break;+ default:+ return assertNever(cli);+ }+ try {+ scaffold(cli.options);+ return 0;+ } catch (error) {+ if (error instanceof ScaffoldError) {+ console.error(error.message);+ return 1;+ }+ throw error;+ }+}++process.exit(main());diff --git a/plugins/omo/skills/programming/scripts/python/new-project.py b/plugins/omo/skills/programming/scripts/python/new-project.pydeleted file mode 100644index da0f74d3..00000000--- a/plugins/omo/skills/programming/scripts/python/new-project.py+++ /dev/null@@ -1,172 +0,0 @@-#!/usr/bin/env -S uv run --script-# /// script-# requires-python = ">=3.11"-# dependencies = [-# "typer",-# "rich",-# ]-# ///--# ─── How to run ───-# 1. Install uv (if not installed):-# curl -LsSf https://astral.sh/uv/install.sh | sh-# 2. Run:-# uv run new-project.py myproject-# uv run new-project.py myproject --path ./workspace-# uv run new-project.py myproject --lib # library (publishable)-# ──────────────────--"""Scaffold a new Python project with ultra-strict config from pyproject-strict.md.--Creates via `uv init`, then injects basedpyright + ruff ALL + pytest config.-"""--from __future__ import annotations--import subprocess-import sys-from pathlib import Path--import typer-from rich import print as rprint--# ── Strict tool config (from pyproject-strict.md) ──--TOOL_CONFIG = '''-[dependency-groups]-dev = [- "basedpyright>=1.21",- "ruff>=0.8",- "pytest>=8",- "pytest-cov>=5",-]--[tool.basedpyright]-typeCheckingMode = "all"-pythonVersion = "3.13"-reportMissingTypeStubs = false-reportUnknownMemberType = false-reportUnknownArgumentType = false-reportUnknownVariableType = false-reportUnknownLambdaType = false-reportUnknownParameterType = false-reportMissingParameterType = false-reportUnnecessaryIsInstance = false-reportUnusedCallResult = false-reportImplicitOverride = false--[tool.ruff]-target-version = "py313"-line-length = 120--[tool.ruff.lint]-select = ["ALL"]-ignore = [- "COM812", # trailing comma (conflicts with formatter)- "ISC001", # single-line string concat (conflicts with formatter)- "D1", # undocumented-public-* (too noisy early on)- "ANN101", # deprecated: self annotation- "ANN102", # deprecated: cls annotation- "S101", # assert used (pytest needs it)- "PLR2004", # magic-value-comparison (test data)- "FBT", # boolean-trap (too strict for CLIs)- "TD", # flake8-todos (noisy)- "FIX", # fixme (noisy)-]--[tool.ruff.lint.per-file-ignores]-"tests/**/*.py" = ["S101", "PLR2004", "SLF001", "D", "ARG", "ANN"]--[tool.ruff.lint.pydocstyle]-convention = "google"--[tool.pytest.ini_options]-testpaths = ["tests"]-addopts = "-ra --strict-markers --strict-config"-'''--GITIGNORE = """\-__pycache__/-*.py[cod]-*.so-.venv/-dist/-*.egg-info/-.coverage-htmlcov/-.basedpyright/-.ruff_cache/-"""---def main(- name: str = typer.Argument(help="Project name"),- path: Path = typer.Option(Path("."), "--path", "-p", help="Parent directory"),- lib: bool = typer.Option(False, "--lib", help="Create as publishable library (uv init --lib)"),-) -> None:- """Create a new Python project with ultra-strict config."""- project_dir = path / name-- if project_dir.exists():- rprint(f"[red]Error:[/red] {project_dir} already exists")- raise SystemExit(1)-- # Run uv init- cmd = ["uv", "init", "--lib" if lib else "--app", str(project_dir)]- result = subprocess.run(cmd, capture_output=True, text=True)- if result.returncode != 0:- rprint(f"[red]uv init failed:[/red] {result.stderr}")- raise SystemExit(1)-- # Read existing pyproject.toml- pyproject_path = project_dir / "pyproject.toml"- content = pyproject_path.read_text()-- # Remove the default [dependency-groups] if uv init created one- # (we'll replace it with our strict version)- lines = content.splitlines(keepends=True)- filtered: list[str] = []- skip = False- for line in lines:- if line.strip().startswith("[dependency-groups]"):- skip = True- continue- if skip and line.strip().startswith("["):- skip = False- if not skip:- filtered.append(line)-- content = "".join(filtered).rstrip("\n") + "\n"-- # Append strict tool config- content += TOOL_CONFIG-- pyproject_path.write_text(content)-- # Add dev dependencies- subprocess.run(- ["uv", "add", "--dev", "basedpyright", "ruff", "pytest", "pytest-cov"],- cwd=project_dir,- capture_output=True,- )-- # Create tests directory- tests_dir = project_dir / "tests"- tests_dir.mkdir(exist_ok=True)- (tests_dir / "__init__.py").touch()-- # Overwrite .gitignore- (project_dir / ".gitignore").write_text(GITIGNORE)-- # Create py.typed marker for libraries- if lib:- src_dir = project_dir / "src" / name.replace("-", "_")- if src_dir.exists():- (src_dir / "py.typed").touch()-- rprint(f"[green]✓[/green] Created: [bold]{project_dir}[/bold]")- rprint(f" cd {name} && uv sync && uv run basedpyright . && uv run ruff check .")---if __name__ == "__main__":- typer.run(main)diff --git a/plugins/omo/skills/programming/scripts/python/new-project.ts b/plugins/omo/skills/programming/scripts/python/new-project.tsnew file mode 100644index 00000000..2018a5f3--- /dev/null+++ b/plugins/omo/skills/programming/scripts/python/new-project.ts@@ -0,0 +1,231 @@+#!/usr/bin/env bun+/**+ * Scaffold a new Python project with ultra-strict config from pyproject-strict.md.+ *+ * ─── How to run ───+ * 1. Install Bun: curl -fsSL https://bun.sh/install | bash+ * 2. Install uv: curl -LsSf https://astral.sh/uv/install.sh | sh+ * 3. Run:+ * bun run new-project.ts myproject+ * bun run new-project.ts myproject --path ./workspace+ * bun run new-project.ts myproject --lib # library (publishable)+ * ──────────────────+ *+ * Creates via `uv init`, then injects basedpyright + ruff ALL + pytest config.+ * Exit codes: 0 created, 1 scaffold or uv failure, 2 usage error.+ */++import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { parseArgs } from "node:util";+import { assertNever, runTool } from "../shared/run-tool.ts";++const USAGE = `Usage: bun run new-project.ts <name> [--path <dir>] [--lib]++Arguments:+ name Project name++Options:+ -p, --path Parent directory (default: current dir)+ --lib Create as publishable library (uv init --lib)+ -h, --help Show this help`;++const TOOL_CONFIG = `+[dependency-groups]+dev = [+ "basedpyright>=1.21",+ "ruff>=0.8",+ "pytest>=8",+ "pytest-cov>=5",+]++[tool.basedpyright]+typeCheckingMode = "all"+pythonVersion = "3.13"+reportMissingTypeStubs = false+reportUnknownMemberType = false+reportUnknownArgumentType = false+reportUnknownVariableType = false+reportUnknownLambdaType = false+reportUnknownParameterType = false+reportMissingParameterType = false+reportUnnecessaryIsInstance = false+reportUnusedCallResult = false+reportImplicitOverride = false++[tool.ruff]+target-version = "py313"+line-length = 120++[tool.ruff.lint]+select = ["ALL"]+ignore = [+ "COM812", # trailing comma (conflicts with formatter)+ "ISC001", # single-line string concat (conflicts with formatter)+ "D1", # undocumented-public-* (too noisy early on)+ "ANN101", # deprecated: self annotation+ "ANN102", # deprecated: cls annotation+ "S101", # assert used (pytest needs it)+ "PLR2004", # magic-value-comparison (test data)+ "FBT", # boolean-trap (too strict for CLIs)+ "TD", # flake8-todos (noisy)+ "FIX", # fixme (noisy)+]++[tool.ruff.lint.per-file-ignores]+"tests/**/*.py" = ["S101", "PLR2004", "SLF001", "D", "ARG", "ANN"]++[tool.ruff.lint.pydocstyle]+convention = "google"++[tool.pytest.ini_options]+testpaths = ["tests"]+addopts = "-ra --strict-markers --strict-config"+`;++const GITIGNORE = `__pycache__/+*.py[cod]+*.so+.venv/+dist/+*.egg-info/+.coverage+htmlcov/+.basedpyright/+.ruff_cache/+`;++type ProjectOptions = { readonly name: string; readonly path: string; readonly lib: boolean };++type Cli =+ | { readonly kind: "run"; readonly options: ProjectOptions }+ | { readonly kind: "help" }+ | { readonly kind: "usage"; readonly problem: string };++class ScaffoldError extends Error {+ constructor(+ readonly kind: "exists" | "uv-unavailable" | "uv-init-failed",+ message: string,+ ) {+ super(message);+ this.name = "ScaffoldError";+ }+}++function parseCli(): Cli {+ try {+ const { values, positionals } = parseArgs({+ args: Bun.argv.slice(2),+ options: {+ path: { type: "string", short: "p", default: "." },+ lib: { type: "boolean", default: false },+ help: { type: "boolean", short: "h", default: false },+ },+ allowPositionals: true,+ strict: true,+ });+ if (values.help) return { kind: "help" };+ const [name, ...extra] = positionals;+ if (name === undefined || extra.length > 0) return { kind: "usage", problem: "expected exactly one project name" };+ return { kind: "run", options: { name, path: values.path, lib: values.lib } };+ } catch (error) {+ if (error instanceof TypeError) return { kind: "usage", problem: error.message };+ throw error;+ }+}++function withoutDependencyGroups(pyproject: string): string {+ const kept: string[] = [];+ let skipping = false;+ for (const line of pyproject.split(/(?<=\n)/)) {+ const trimmed = line.trim();+ if (trimmed.startsWith("[dependency-groups]")) {+ skipping = true;+ continue;+ }+ if (skipping && trimmed.startsWith("[")) skipping = false;+ if (!skipping) kept.push(line);+ }+ return `${kept.join("").replace(/\n+$/, "")}\n`;+}++function initProject(projectDir: string, lib: boolean): void {+ const init = runTool("uv", ["init", lib ? "--lib" : "--app", projectDir]);+ switch (init.kind) {+ case "ok":+ return;+ case "unavailable":+ throw new ScaffoldError(+ "uv-unavailable",+ `uv could not be started (${init.reason}); install it: curl -LsSf https://astral.sh/uv/install.sh | sh`,+ );+ case "failed":+ throw new ScaffoldError("uv-init-failed", `uv init failed: ${init.stderr}`);+ default:+ return assertNever(init);+ }+}++function addDevTools(projectDir: string): void {+ const added = runTool("uv", ["add", "--dev", "basedpyright", "ruff", "pytest", "pytest-cov"], projectDir);+ switch (added.kind) {+ case "ok":+ return;+ case "unavailable":+ console.error(`warn: uv add --dev could not start (${added.reason}); run it once uv is reachable`);+ return;+ case "failed":+ console.error(`warn: uv add --dev failed; pyproject.toml still lists the dev tools:\n${added.stderr}`);+ return;+ default:+ return assertNever(added);+ }+}++function scaffold({ name, path, lib }: ProjectOptions): void {+ const projectDir = join(path, name);+ if (existsSync(projectDir)) throw new ScaffoldError("exists", `${projectDir} already exists`);+ initProject(projectDir, lib);++ const pyprojectPath = join(projectDir, "pyproject.toml");+ writeFileSync(pyprojectPath, withoutDependencyGroups(readFileSync(pyprojectPath, "utf8")) + TOOL_CONFIG);+ addDevTools(projectDir);++ mkdirSync(join(projectDir, "tests"), { recursive: true });+ appendFileSync(join(projectDir, "tests", "__init__.py"), "");+ writeFileSync(join(projectDir, ".gitignore"), GITIGNORE);++ const srcDir = join(projectDir, "src", name.replaceAll("-", "_"));+ if (lib && existsSync(srcDir)) appendFileSync(join(srcDir, "py.typed"), "");++ console.log(`✓ Created: ${projectDir}`);+ console.log(` cd ${name} && uv sync && uv run basedpyright . && uv run ruff check .`);+}++function main(): number {+ const cli = parseCli();+ switch (cli.kind) {+ case "help":+ console.log(USAGE);+ return 0;+ case "usage":+ console.error(`Error: ${cli.problem}\n\n${USAGE}`);+ return 2;+ case "run":+ break;+ default:+ return assertNever(cli);+ }+ try {+ scaffold(cli.options);+ return 0;+ } catch (error) {+ if (error instanceof ScaffoldError) {+ console.error(`Error: ${error.message}`);+ return 1;+ }+ throw error;+ }+}++process.exit(main());diff --git a/plugins/omo/skills/programming/scripts/python/new-script.py b/plugins/omo/skills/programming/scripts/python/new-script.pydeleted file mode 100644index 3e997368..00000000--- a/plugins/omo/skills/programming/scripts/python/new-script.py+++ /dev/null@@ -1,116 +0,0 @@-#!/usr/bin/env -S uv run --script-# /// script-# requires-python = ">=3.11"-# dependencies = [-# "typer",-# "rich",-# ]-# ///--# ─── How to run ───-# 1. Install uv (if not installed):-# curl -LsSf https://astral.sh/uv/install.sh | sh-# 2. Run:-# uv run new-script.py my_tool-# uv run new-script.py my_tool --output ./scripts/my_tool.py-# uv run new-script.py my_tool --deps 'httpx2[http2,brotli,zstd]' --deps rich --deps polars-# uv run new-script.py my_tool --py 3.13-# ──────────────────--"""Generate a PEP 723 Python script with all boilerplate pre-filled.--Creates a new .py file with:- - uv shebang- - PEP 723 inline metadata (requires-python + dependencies)- - Mandatory "How to run" comment block- - from __future__ import annotations- - main() + if __name__ guard--By default writes to a temp directory and prints the path.-"""--from __future__ import annotations--import os-import stat-import sys-import tempfile-from pathlib import Path--import typer-from rich import print as rprint---TEMPLATE = '''\-#!/usr/bin/env -S uv run --script-# /// script-# requires-python = ">={python_version}"-# dependencies = [-{deps_block}# ]-# ///--# ─── How to run ───-# 1. Install uv (if not installed):-# curl -LsSf https://astral.sh/uv/install.sh | sh-# 2. Run directly (no venv, no pip install needed):-# uv run {filename} {args_hint}-# 3. Or make executable and run:-# chmod +x {filename} && ./{filename}-# ──────────────────--from __future__ import annotations---def main() -> None:- """TODO: implement."""---if __name__ == "__main__":- main()-'''---def main(- name: str = typer.Argument(help="Script name (without .py extension)"),- output: Path | None = typer.Option(None, "--output", "-o", help="Output path. Default: OS temp directory."),- deps: list[str] = typer.Option([], "--deps", "-d", help="Dependencies to include (repeat --deps for each)."),- py: str = typer.Option("3.13", "--py", help="Minimum Python version."),-) -> None:- """Generate a new PEP 723 script with all boilerplate pre-filled."""- filename = f"{name}.py" if not name.endswith(".py") else name- stem = filename.removesuffix(".py")-- if output is not None:- dest = Path(output)- else:- tmp_dir = Path(tempfile.gettempdir()) / "uv-scripts"- tmp_dir.mkdir(exist_ok=True)- dest = tmp_dir / filename-- dep_list = deps or []- if dep_list:- deps_block = "".join(f'# "{d}",\n' for d in dep_list)- else:- deps_block = '# # add deps here, e.g.: "httpx2[http2,brotli,zstd]"\n'-- content = TEMPLATE.format(- python_version=py,- deps_block=deps_block,- filename=filename,- args_hint="",- )-- dest.parent.mkdir(parents=True, exist_ok=True)- dest.write_text(content)-- # Make executable on Unix- if sys.platform != "win32":- st = dest.stat()- dest.chmod(st.st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)-- rprint(f"[green]✓[/green] Created: [bold]{dest}[/bold]")- rprint(f" Run: [cyan]uv run {dest}[/cyan]")---if __name__ == "__main__":- typer.run(main)diff --git a/plugins/omo/skills/programming/scripts/python/new-script.ts b/plugins/omo/skills/programming/scripts/python/new-script.tsnew file mode 100644index 00000000..623f6fab--- /dev/null+++ b/plugins/omo/skills/programming/scripts/python/new-script.ts@@ -0,0 +1,134 @@+#!/usr/bin/env bun+/**+ * Generate a PEP 723 Python script with all boilerplate pre-filled: uv shebang,+ * inline metadata (requires-python + dependencies), the mandatory "How to run"+ * block, `from __future__ import annotations`, and a main() guard.+ *+ * ─── How to run ───+ * 1. Install Bun: curl -fsSL https://bun.sh/install | bash+ * 2. Run:+ * bun run new-script.ts my_tool+ * bun run new-script.ts my_tool --output ./scripts/my_tool.py+ * bun run new-script.ts my_tool --deps 'httpx2[http2,brotli,zstd]' --deps rich --deps polars+ * bun run new-script.ts my_tool --py 3.13+ * ──────────────────+ *+ * Writes to <os tmpdir>/uv-scripts/<name>.py unless --output is given.+ * Exit codes: 0 written, 2 usage error.+ */++import { chmodSync, mkdirSync, statSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { parseArgs } from "node:util";+import { assertNever } from "../shared/run-tool.ts";++const USAGE = `Usage: bun run new-script.ts <name> [--output <path>] [--deps <dep>]... [--py <version>]++Arguments:+ name Script name (without .py extension)++Options:+ -o, --output Output path (default: OS temp directory)+ -d, --deps Dependency to include (repeat --deps for each)+ --py Minimum Python version (default: 3.13)+ -h, --help Show this help`;++type ScriptOptions = {+ readonly name: string;+ readonly output: string | undefined;+ readonly deps: readonly string[];+ readonly py: string;+};++type Cli =+ | { readonly kind: "run"; readonly options: ScriptOptions }+ | { readonly kind: "help" }+ | { readonly kind: "usage"; readonly problem: string };++function parseCli(): Cli {+ try {+ const { values, positionals } = parseArgs({+ args: Bun.argv.slice(2),+ options: {+ output: { type: "string", short: "o" },+ deps: { type: "string", short: "d", multiple: true, default: [] },+ py: { type: "string", default: "3.13" },+ help: { type: "boolean", short: "h", default: false },+ },+ allowPositionals: true,+ strict: true,+ });+ if (values.help) return { kind: "help" };+ const [name, ...extra] = positionals;+ if (name === undefined || extra.length > 0) return { kind: "usage", problem: "expected exactly one script name" };+ return { kind: "run", options: { name, output: values.output, deps: values.deps, py: values.py } };+ } catch (error) {+ if (error instanceof TypeError) return { kind: "usage", problem: error.message };+ throw error;+ }+}++function renderScript(pythonVersion: string, deps: readonly string[], filename: string): string {+ const depsBlock =+ deps.length > 0+ ? deps.map((dep) => `# "${dep}",\n`).join("")+ : '# # add deps here, e.g.: "httpx2[http2,brotli,zstd]"\n';+ const argsHint = "";+ return `#!/usr/bin/env -S uv run --script+# /// script+# requires-python = ">=${pythonVersion}"+# dependencies = [+${depsBlock}# ]+# ///++# ─── How to run ───+# 1. Install uv (if not installed):+# curl -LsSf https://astral.sh/uv/install.sh | sh+# 2. Run directly (no venv, no pip install needed):+# uv run ${filename} ${argsHint}+# 3. Or make executable and run:+# chmod +x ${filename} && ./${filename}+# ──────────────────++from __future__ import annotations+++def main() -> None:+ """TODO: implement."""+++if __name__ == "__main__":+ main()+`;+}++function writeScript({ name, output, deps, py }: ScriptOptions): void {+ const filename = name.endsWith(".py") ? name : `${name}.py`;+ const dest = output ?? join(tmpdir(), "uv-scripts", filename);+ mkdirSync(dirname(dest), { recursive: true });+ writeFileSync(dest, renderScript(py, deps, filename));+ if (process.platform !== "win32") chmodSync(dest, statSync(dest).mode | 0o111);++ console.log(`✓ Created: ${dest}`);+ console.log(` Run: uv run ${dest}`);+}++function main(): number {+ const cli = parseCli();+ switch (cli.kind) {+ case "help":+ console.log(USAGE);+ return 0;+ case "usage":+ console.error(`Error: ${cli.problem}\n\n${USAGE}`);+ return 2;+ case "run":+ writeScript(cli.options);+ return 0;+ default:+ return assertNever(cli);+ }+}++process.exit(main());diff --git a/plugins/omo/skills/programming/scripts/rust/new-project.py b/plugins/omo/skills/programming/scripts/rust/new-project.pydeleted file mode 100755index 832abfdc..00000000--- a/plugins/omo/skills/programming/scripts/rust/new-project.py+++ /dev/null@@ -1,178 +0,0 @@-#!/usr/bin/env -S uv run --script-# /// script-# requires-python = ">=3.11"-# dependencies = [-# "typer",-# "rich",-# ]-# ///--# ─── How to run ───-# 1. Install uv (if not installed):-# curl -LsSf https://astral.sh/uv/install.sh | sh-# 2. Run:-# uv run new-project.py myproject-# uv run new-project.py myproject --path ./workspace-# ──────────────────-#-# Creates a new Rust project with strict lints, deny.toml, rustfmt.toml, and-# rust-toolchain.toml pre-configured. The generated project passes its own-# fmt + clippy gate before any code is written.--from __future__ import annotations--import subprocess-import sys-from pathlib import Path--import typer-from rich.console import Console--console = Console(stderr=True)--# ── Embedded config contents ─────────────────────────────────────────────--RUST_TOOLCHAIN_TOML = """\-[toolchain]-channel = "stable"-components = ["rustfmt", "clippy", "rust-src"]-profile = "default"-"""--CARGO_TOML_LINTS = """-[lints.rust]-unsafe_op_in_unsafe_fn = "deny"-missing_docs = "warn"-missing_debug_implementations = "warn"-unreachable_pub = "warn"-unused_must_use = "deny"-elided_lifetimes_in_paths = "warn"-non_ascii_idents = "deny"-trivial_numeric_casts = "warn"-unused_lifetimes = "warn"-single_use_lifetimes = "warn"-unexpected_cfgs = { level = "deny", check-cfg = ["cfg(loom)"] }--[lints.clippy]-all = { level = "deny", priority = -1 }-pedantic = { level = "warn", priority = -1 }-nursery = { level = "warn", priority = -1 }-cargo = { level = "warn", priority = -1 }-undocumented_unsafe_blocks = "deny"-multiple_unsafe_ops_per_block = "deny"-unwrap_used = "deny"-expect_used = "deny"-panic = "deny"-todo = "deny"-unimplemented = "deny"-dbg_macro = "deny"-print_stdout = "warn"-print_stderr = "warn"-allow_attributes = "deny"-allow_attributes_without_reason = "deny"-let_underscore_must_use = "deny"-indexing_slicing = "deny"-mem_forget = "deny"-clone_on_ref_ptr = "warn"-module_name_repetitions = { level = "allow" }-must_use_candidate = { level = "allow" }-"""--DENY_TOML = """\-[advisories]-yanked = "deny"--[licenses]-private = { ignore = true } # publish = false crates carry no license field-allow = ["MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "ISC", "Unicode-3.0", "Zlib"]--[bans]-multiple-versions = "warn"-wildcards = "deny"--[sources]-unknown-registry = "deny"-unknown-git = "deny"-"""--MAIN_RS = """\-//! Command-line entry point.--use std::io::Write as _;--fn main() -> std::io::Result<()> {- writeln!(std::io::stdout().lock(), "Hello, world!")-}-"""--RUSTFMT_TOML = """\-edition = "2024"-max_width = 100-use_field_init_shorthand = true-use_try_shorthand = true-"""--# ── Main ─────────────────────────────────────────────────────────────────--app = typer.Typer(add_completion=False)---def main(- name: str = typer.Argument(help="Name of the new Rust project"),- path: Path = typer.Option(- Path.cwd(),- "--path",- "-p",- help="Parent directory where the project folder is created",- ),-) -> None:- """Scaffold a new Rust project with strict lints and tooling configs."""- project_dir = path / name-- # ── cargo init ───────────────────────────────────────────────────- console.print(f"[bold green]Creating[/] project [cyan]{name}[/] at [dim]{project_dir}[/]")- try:- subprocess.run(- ["cargo", "init", str(project_dir), "--name", name],- check=True,- capture_output=True,- text=True,- )- except FileNotFoundError:- console.print("[bold red]Error:[/] cargo not found. Install Rust via https://rustup.rs")- sys.exit(1)- except subprocess.CalledProcessError as exc:- console.print(f"[bold red]cargo init failed:[/]\n{exc.stderr}")- sys.exit(1)-- # ── rust-toolchain.toml ──────────────────────────────────────────- (project_dir / "rust-toolchain.toml").write_text(RUST_TOOLCHAIN_TOML)- console.print(" [dim]wrote[/] rust-toolchain.toml")-- # ── Declare the MSRV and append [lints] to Cargo.toml ────────────- cargo_toml = project_dir / "Cargo.toml"- manifest = cargo_toml.read_text()- if 'edition = "2024"\n' not in manifest:- console.print("[bold red]Error:[/] cargo did not create an edition 2024 package; install Rust >= 1.85")- sys.exit(1)- manifest = manifest.replace(- 'edition = "2024"\n', 'edition = "2024"\nrust-version = "1.85"\npublish = false\n', 1- )- cargo_toml.write_text(manifest + CARGO_TOML_LINTS)- (project_dir / "src" / "main.rs").write_text(MAIN_RS)- console.print(" [dim]appended[/] [lints] to Cargo.toml")-- # ── deny.toml ────────────────────────────────────────────────────- (project_dir / "deny.toml").write_text(DENY_TOML)- console.print(" [dim]wrote[/] deny.toml")-- # ── rustfmt.toml ─────────────────────────────────────────────────- (project_dir / "rustfmt.toml").write_text(RUSTFMT_TOML)- console.print(" [dim]wrote[/] rustfmt.toml")-- console.print(f"\n[bold green]Done![/] cd {project_dir} && cargo check")---if __name__ == "__main__":- app()diff --git a/plugins/omo/skills/programming/scripts/rust/new-project.ts b/plugins/omo/skills/programming/scripts/rust/new-project.tsnew file mode 100644index 00000000..1e0a703a--- /dev/null+++ b/plugins/omo/skills/programming/scripts/rust/new-project.ts@@ -0,0 +1,215 @@+#!/usr/bin/env bun+/**+ * Scaffold a new Rust project with strict lints, deny.toml, rustfmt.toml, and+ * rust-toolchain.toml pre-configured. The generated project passes its own+ * fmt + clippy gate before any code is written.+ *+ * ─── How to run ───+ * 1. Install Bun: curl -fsSL https://bun.sh/install | bash+ * 2. Install Rust: https://rustup.rs (cargo >= 1.85, edition 2024)+ * 3. Run:+ * bun run new-project.ts myproject+ * bun run new-project.ts myproject --path ./workspace+ * ──────────────────+ *+ * Exit codes: 0 created, 1 cargo or scaffold failure, 2 usage error.+ */++import { readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { parseArgs } from "node:util";+import { assertNever, runTool } from "../shared/run-tool.ts";++const USAGE = `Usage: bun run new-project.ts <name> [--path <dir>]++Arguments:+ name Name of the new Rust project++Options:+ -p, --path Parent directory where the project folder is created (default: cwd)+ -h, --help Show this help`;++const RUST_TOOLCHAIN_TOML = `[toolchain]+channel = "stable"+components = ["rustfmt", "clippy", "rust-src"]+profile = "default"+`;++const CARGO_TOML_LINTS = `+[lints.rust]+unsafe_op_in_unsafe_fn = "deny"+missing_docs = "warn"+missing_debug_implementations = "warn"+unreachable_pub = "warn"+unused_must_use = "deny"+elided_lifetimes_in_paths = "warn"+non_ascii_idents = "deny"+trivial_numeric_casts = "warn"+unused_lifetimes = "warn"+single_use_lifetimes = "warn"+unexpected_cfgs = { level = "deny", check-cfg = ["cfg(loom)"] }++[lints.clippy]+all = { level = "deny", priority = -1 }+pedantic = { level = "warn", priority = -1 }+nursery = { level = "warn", priority = -1 }+cargo = { level = "warn", priority = -1 }+undocumented_unsafe_blocks = "deny"+multiple_unsafe_ops_per_block = "deny"+unwrap_used = "deny"+expect_used = "deny"+panic = "deny"+todo = "deny"+unimplemented = "deny"+dbg_macro = "deny"+print_stdout = "warn"+print_stderr = "warn"+allow_attributes = "deny"+allow_attributes_without_reason = "deny"+let_underscore_must_use = "deny"+indexing_slicing = "deny"+mem_forget = "deny"+clone_on_ref_ptr = "warn"+module_name_repetitions = { level = "allow" }+must_use_candidate = { level = "allow" }+`;++const DENY_TOML = `[advisories]+yanked = "deny"++[licenses]+private = { ignore = true } # publish = false crates carry no license field+allow = ["MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "ISC", "Unicode-3.0", "Zlib"]++[bans]+multiple-versions = "warn"+wildcards = "deny"++[sources]+unknown-registry = "deny"+unknown-git = "deny"+`;++const MAIN_RS = `//! Command-line entry point.++use std::io::Write as _;++fn main() -> std::io::Result<()> {+ writeln!(std::io::stdout().lock(), "Hello, world!")+}+`;++const RUSTFMT_TOML = `edition = "2024"+max_width = 100+use_field_init_shorthand = true+use_try_shorthand = true+`;++const EDITION_LINE = 'edition = "2024"\n';++type ProjectOptions = { readonly name: string; readonly path: string };++type Cli =+ | { readonly kind: "run"; readonly options: ProjectOptions }+ | { readonly kind: "help" }+ | { readonly kind: "usage"; readonly problem: string };++class ScaffoldError extends Error {+ constructor(+ readonly kind: "cargo-unavailable" | "cargo-init-failed" | "edition-too-old",+ message: string,+ ) {+ super(message);+ this.name = "ScaffoldError";+ }+}++function parseCli(): Cli {+ try {+ const { values, positionals } = parseArgs({+ args: Bun.argv.slice(2),+ options: {+ path: { type: "string", short: "p", default: process.cwd() },+ help: { type: "boolean", short: "h", default: false },+ },+ allowPositionals: true,+ strict: true,+ });+ if (values.help) return { kind: "help" };+ const [name, ...extra] = positionals;+ if (name === undefined || extra.length > 0) return { kind: "usage", problem: "expected exactly one project name" };+ return { kind: "run", options: { name, path: values.path } };+ } catch (error) {+ if (error instanceof TypeError) return { kind: "usage", problem: error.message };+ throw error;+ }+}++function cargoInit(projectDir: string, name: string): void {+ const init = runTool("cargo", ["init", projectDir, "--name", name]);+ switch (init.kind) {+ case "ok":+ return;+ case "unavailable":+ throw new ScaffoldError("cargo-unavailable", `cargo not found (${init.reason}). Install Rust via https://rustup.rs`);+ case "failed":+ throw new ScaffoldError("cargo-init-failed", `cargo init failed:\n${init.stderr}`);+ default:+ return assertNever(init);+ }+}++function scaffold({ name, path }: ProjectOptions): void {+ const projectDir = join(path, name);+ console.error(`Creating project ${name} at ${projectDir}`);+ cargoInit(projectDir, name);++ writeFileSync(join(projectDir, "rust-toolchain.toml"), RUST_TOOLCHAIN_TOML);+ console.error(" wrote rust-toolchain.toml");++ const cargoToml = join(projectDir, "Cargo.toml");+ const manifest = readFileSync(cargoToml, "utf8");+ if (!manifest.includes(EDITION_LINE)) {+ throw new ScaffoldError("edition-too-old", "cargo did not create an edition 2024 package; install Rust >= 1.85");+ }+ const withMsrv = manifest.replace(EDITION_LINE, `${EDITION_LINE}rust-version = "1.85"\npublish = false\n`);+ writeFileSync(cargoToml, withMsrv + CARGO_TOML_LINTS);+ writeFileSync(join(projectDir, "src", "main.rs"), MAIN_RS);+ console.error(" appended [lints] to Cargo.toml");++ writeFileSync(join(projectDir, "deny.toml"), DENY_TOML);+ console.error(" wrote deny.toml");++ writeFileSync(join(projectDir, "rustfmt.toml"), RUSTFMT_TOML);+ console.error(" wrote rustfmt.toml");++ console.error(`\nDone! cd ${projectDir} && cargo check`);+}++function main(): number {+ const cli = parseCli();+ switch (cli.kind) {+ case "help":+ console.log(USAGE);+ return 0;+ case "usage":+ console.error(`Error: ${cli.problem}\n\n${USAGE}`);+ return 2;+ case "run":+ break;+ default:+ return assertNever(cli);+ }+ try {+ scaffold(cli.options);+ return 0;+ } catch (error) {+ if (error instanceof ScaffoldError) {+ console.error(`Error: ${error.message}`);+ return 1;+ }+ throw error;+ }+}++process.exit(main());diff --git a/plugins/omo/skills/programming/scripts/shared/run-tool.ts b/plugins/omo/skills/programming/scripts/shared/run-tool.tsnew file mode 100644index 00000000..af08c573--- /dev/null+++ b/plugins/omo/skills/programming/scripts/shared/run-tool.ts@@ -0,0 +1,19 @@+/** Shared by the Python, Rust, and Go scaffolders: run uv/cargo/go and classify the outcome. */++import { spawnSync } from "node:child_process";++export type ToolOutcome =+ | { readonly kind: "ok" }+ | { readonly kind: "unavailable"; readonly reason: string }+ | { readonly kind: "failed"; readonly status: number | null; readonly stderr: string };++export function runTool(command: string, args: readonly string[], cwd?: string): ToolOutcome {+ const result = spawnSync(command, args, { cwd, encoding: "utf8" });+ if (result.error !== undefined) return { kind: "unavailable", reason: result.error.message };+ if (result.status === 0) return { kind: "ok" };+ return { kind: "failed", status: result.status, stderr: result.stderr };+}++export function assertNever(value: never): never {+ throw new Error(`Unhandled variant: ${JSON.stringify(value)}`);+}diff --git a/plugins/omo/skills/visual-qa/SKILL.md b/plugins/omo/skills/visual-qa/SKILL.mdindex 91fa3a5b..944c2327 100644--- a/plugins/omo/skills/visual-qa/SKILL.md+++ b/plugins/omo/skills/visual-qa/SKILL.md@@ -66,6 +66,10 @@ The verdict is per page. One failing page fails the whole surface, so "most pageEvery gate runs on captures produced AFTER the last edit to the rendered source. If any screenshot, PDF, capture, or QA JSON is older than the source file it claims to verify, it is stale and invalid - regenerate it before trusting it. Never report a PASS from an artifact you did not just produce against the current build. Between review rounds, re-capture only the pages a fix touched; the final approving round always judges a complete fresh set. The one deliberately old artifact is the `before` set of Step 6, which is dated to the pre-edit build on purpose.+### Machine pre-check - the detect SDK before any reviewer++On a web surface, run the `frontend` skill's detect SDK on every enumerated page before capturing for reviewers (`frontend/references/perfection/detect.md`: `detectPage({ kind: "url", url }, { reflow: true })`, or `bun <frontend skill dir>/scripts/detect/cli.ts --reflow --json <url>`). It reads the rendered page and reports contrast against the painted background, the type scale and heading order, overflow at 320-1440 px under an unbroken stress string, and decoration and copy tells. An error or warning is a FAIL on the matching checklist item (E2 contrast, B8 type scale, A9 or A13 layout, F8/F9 surfaces and scaffolds, C4 wrapping) before either reviewer looks; fix it and rerun. Keep the JSON beside the captures and hand it to both reviewers as evidence. Advisories go to the verdict's taste findings.+### Capture hygiene - validate before dispatching reviewersBefore any reviewer sees an image, verify each capture yourself: the file signature matches its extension (a JPEG named `.png` is invalid), the frame is fully composited (no black or missing regions from the screenshot compositor), dimensions match the requested viewport, and the frame holds only the page - a capture showing the browser's tabs or address bar, or the capture tool's own UI, is a window grab, not evidence. A defective capture wastes an entire review round on the pipeline instead of the product - fix the capture tooling and re-shoot before dispatch, and record the tooling defect in the QA log instead of looping the reviewer on it.@@ -140,7 +144,7 @@ This is the platform baseline, distilled from Apple's Human Interface Guidelines**A. Layout and alignment**- A1 Content is anchored by intent, centred or on the layout grid; nothing sits in the top-left of an otherwise empty canvas.- A2 Backgrounds and scrolling layouts run full-bleed to the display edges; no stray inset margin.-- A3 Margins are symmetric; prose sits in a 45-75 character measure.+- A3 Margins are symmetric; prose sits in a 65-75 character measure on desktop and at least 45 on a phone.- A4 (phone) Safe areas respected: bars and content inset for the home indicator, notch and status bar.- A5 (phone) Scrollbars are overlay; no reserved right-hand gutter.- A6 One scroll owner per region, no nested same-direction scrolling; a sticky or floating bar stays legible over whatever scrolls under it.@@ -150,6 +154,7 @@ This is the platform baseline, distilled from Apple's Human Interface Guidelines- A10 Content that continues out of view shows a cue (partial item, fade, chevron).- A11 (mac) Nothing important lives only at the window's bottom edge; the minimum window size keeps toolbar and content legible; the sidebar collapses when the window narrows.- A12 (web and app screens; N/A for a TUI, a printed page, or a figure) Layout contract: every changed screen or region has a `Layout:` line (in `DESIGN.md`, or in the change description when the project has none; the `frontend` skill's Brief step); the capture shows that pattern's structure; the logged owner is the region's main scroller in the probe output, every other scroller listed is nested inside it for its own content (a code block, a dropdown, a composer) or is named in the line too; none of the line's anti-patterns appear. A missing line, a different main scroller, an unexplained sibling scroller, or a present anti-pattern is a FAIL; a logged skip still owes the scroll-owner check.+- A13 Spacing rhythm, read from computed values: the space above a section heading is at least 1.5x the space below it, and the gap between groups is at least 2x the gap inside a group (the `frontend` skill's `references/perfection/craft-floor.md`).**B. Hierarchy**- B1 One primary action per view, in the prominent style (accent on its background, not its glyph); peers differ by style, never by size.@@ -159,6 +164,7 @@ This is the platform baseline, distilled from Apple's Human Interface Guidelines- B5 One or two accents per screen; toolbars and tab bars stay monochrome over colourful content; nothing decorative carries accent.- B6 Type hierarchy comes from weight, size and colour, holds in both themes, and uses at most two typefaces.- B7 (web and app screens; N/A for a TUI, a printed page, or a figure) The screen matches its brief (the `frontend` skill's Brief step): the named primary action is the single prominent control, priorities 1-3 appear in that order in reading order on the first viewport, and nothing listed under "left out on purpose" is on the screen. A screen built or changed in this session with no brief is a FAIL; a pre-existing screen under audit with no brief is N/A.+- B8 Type scale floor, read from computed values: each heading step in use (display to h3, and the smallest heading to body) differs by at least 1.25x in size, and body-family roles (lead, body, small, caption, label) that sit closer also differ by weight, colour or case, a display heading stays at or under 6rem, and letter spacing never goes below -0.04em, unless the brief's chosen style route sets its own display scale or tracking (then that value is the check).**C. Text and copy**- C1 Body text is at least 17 pt-equivalent at 390 (15 pt for secondary text) and 14 px on desktop; no thin weights at small sizes.@@ -183,6 +189,7 @@ This is the platform baseline, distilled from Apple's Human Interface Guidelines- E4 One colour never means two things; status colours are consistent across the surface.- E5 Translucent surfaces keep text legible over any scrolled content: blur or vibrancy, not a plain alpha fill.- E6 The theme follows the system; an in-app theme control also offers "system".+- E7 Secondary text on a tinted or coloured surface is a shade of that hue or the foreground at reduced alpha, never neutral gray; a shadow carries a y-offset and a soft blur, never a zero-offset coloured glow unless the brief asked for glowing-border cards (the `frontend` skill's ambience route).**F. Consistency and brand**- F1 One icon set with one stroke, weight and size; icon weight matches adjacent text; no emoji used as an icon.@@ -192,6 +199,10 @@ This is the platform baseline, distilled from Apple's Human Interface Guidelines- F5 Selected or active state is a wash plus a glyph; focus is a focus-visible ring on fields and a row highlight in lists; no coloured accent side-border marks state.- F6 Standard glyphs for standard actions (share, close, back, search, more) in their standard places.- F7 Windows, sheets and popovers use system shapes; one sheet or popover at a time; a popover's arrow points at its source; only an alert may appear over a popover.+- F8 Browser surfaces carry the palette in both themes: text selection, caret, visible scrollbars, focus ring, link underline offset, and tabular numerals in changing or aligned numbers; none shows the browser default (select text and focus a field in the capture to prove it).+- F9 None of the generated scaffolds: a kicker label above a heading, an icon tile stacked over a heading in a grid of same-size cards, a hero metric with no decision behind it, a card nested in a card, monospace used as a "technical" costume. One the brief or its chosen route asked for, recorded as such, passes.++A13, B8, E7, F8 and F9 are adapted from the craft floor of [pbakaus/impeccable](https://github.com/pbakaus/impeccable) (Apache-2.0, Copyright 2025 Paul Bakaus); the license and the list of changes are in the `frontend` skill's `ATTRIBUTION.md` section 6.**G. Motion and feedback**- G1 Every animation has a cause - an interaction, a state change, an arrival; no motion on non-interactive elements, no hover that changes nothing, no permanent loop.