oh-my-opencode 5.1.83 → 5.1.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (442) hide show
  1. package/.agents/command/remove-deadcode.md +1 -1
  2. package/.agents/skills/remove-deadcode/SKILL.md +1 -1
  3. package/.agents/skills/work-with-pr/SKILL.md +2 -2
  4. package/.opencode/command/remove-deadcode.md +1 -1
  5. package/.opencode/skills/work-with-pr/SKILL.md +2 -2
  6. package/THIRD-PARTY-NOTICES.md +9 -3
  7. package/dist/cli/cli-program.d.ts +3 -0
  8. package/dist/cli/index.js +1197 -1008
  9. package/dist/cli/service-auth/devices.d.ts +5 -2
  10. package/dist/cli-node/index.js +1197 -1008
  11. package/dist/config/schema/agent-names.d.ts +1 -0
  12. package/dist/index.js +194 -213
  13. package/dist/skills/browser/SKILL.md +100 -91
  14. package/dist/skills/browser/references/commands.md +92 -27
  15. package/dist/skills/browser/references/desktop.md +22 -0
  16. package/dist/skills/browser/references/install.md +18 -0
  17. package/dist/skills/browser/references/owned-engine/README.md +7 -2
  18. package/dist/skills/browser/references/owned-engine/frames-and-humans.md +9 -2
  19. package/dist/skills/browser/references/owned-engine/network.md +13 -7
  20. package/dist/skills/browser/references/recipes/1password.md +6 -2
  21. package/dist/skills/browser/runtime/omowright/index.js +15 -15
  22. package/dist/skills/browser/runtime/omowright/manifest.json +4 -4
  23. package/dist/skills/debugging/SKILL.md +1 -1
  24. package/dist/skills/debugging/references/tools/browser-qa.md +1 -1
  25. package/dist/skills/git/SKILL.md +62 -0
  26. package/dist/skills/git/agents/openai.yaml +13 -0
  27. package/dist/skills/github/SKILL.md +94 -0
  28. package/dist/skills/github/references/branch-rules.md +129 -0
  29. package/dist/skills/github/references/evidence-attachments.md +16 -0
  30. package/dist/skills/github/references/repo-setup.md +152 -0
  31. package/dist/skills/github/references/waiting.md +52 -0
  32. package/dist/skills/github/references/workflows.md +161 -0
  33. package/dist/skills/github/scripts/cli.ts +8 -0
  34. package/dist/skills/github/scripts/package.json +12 -0
  35. package/dist/skills/github/scripts/sdk.ts +11 -0
  36. package/dist/skills/github/scripts/src/account.ts +243 -0
  37. package/dist/skills/github/scripts/src/actions-write.ts +86 -0
  38. package/dist/skills/github/scripts/src/actions.ts +210 -0
  39. package/dist/skills/github/scripts/src/attestations.ts +136 -0
  40. package/dist/skills/github/scripts/src/blake2b.ts +102 -0
  41. package/dist/skills/github/scripts/src/branch-protection.ts +192 -0
  42. package/dist/skills/github/scripts/src/caches.ts +105 -0
  43. package/dist/skills/github/scripts/src/checks.ts +107 -0
  44. package/dist/skills/github/scripts/src/codespaces.ts +230 -0
  45. package/dist/skills/github/scripts/src/conversation-lock.ts +50 -0
  46. package/dist/skills/github/scripts/src/discussion-list.ts +126 -0
  47. package/dist/skills/github/scripts/src/discussion-lookup.ts +127 -0
  48. package/dist/skills/github/scripts/src/discussions.ts +234 -0
  49. package/dist/skills/github/scripts/src/env.ts +100 -0
  50. package/dist/skills/github/scripts/src/errors.ts +79 -0
  51. package/dist/skills/github/scripts/src/fields.ts +27 -0
  52. package/dist/skills/github/scripts/src/gist-shape.ts +58 -0
  53. package/dist/skills/github/scripts/src/gists-write.ts +130 -0
  54. package/dist/skills/github/scripts/src/gists.ts +118 -0
  55. package/dist/skills/github/scripts/src/git-auth.ts +46 -0
  56. package/dist/skills/github/scripts/src/http.ts +159 -0
  57. package/dist/skills/github/scripts/src/issue-develop.ts +118 -0
  58. package/dist/skills/github/scripts/src/issues-extra.ts +135 -0
  59. package/dist/skills/github/scripts/src/issues-write.ts +174 -0
  60. package/dist/skills/github/scripts/src/issues.ts +156 -0
  61. package/dist/skills/github/scripts/src/keys.ts +176 -0
  62. package/dist/skills/github/scripts/src/labels.ts +209 -0
  63. package/dist/skills/github/scripts/src/merge.ts +115 -0
  64. package/dist/skills/github/scripts/src/poly1305.ts +22 -0
  65. package/dist/skills/github/scripts/src/pr-checkout.ts +92 -0
  66. package/dist/skills/github/scripts/src/pr-view.ts +106 -0
  67. package/dist/skills/github/scripts/src/project-fields.ts +144 -0
  68. package/dist/skills/github/scripts/src/project-item-edit.ts +153 -0
  69. package/dist/skills/github/scripts/src/project-items.ts +191 -0
  70. package/dist/skills/github/scripts/src/project-links.ts +104 -0
  71. package/dist/skills/github/scripts/src/project-ref.ts +145 -0
  72. package/dist/skills/github/scripts/src/project-state.ts +99 -0
  73. package/dist/skills/github/scripts/src/projects.ts +158 -0
  74. package/dist/skills/github/scripts/src/pulls-extra.ts +165 -0
  75. package/dist/skills/github/scripts/src/pulls-read.ts +176 -0
  76. package/dist/skills/github/scripts/src/pulls-review.ts +206 -0
  77. package/dist/skills/github/scripts/src/pulls-write.ts +187 -0
  78. package/dist/skills/github/scripts/src/raw.ts +78 -0
  79. package/dist/skills/github/scripts/src/read.ts +77 -0
  80. package/dist/skills/github/scripts/src/release-assets.ts +111 -0
  81. package/dist/skills/github/scripts/src/release-download.ts +151 -0
  82. package/dist/skills/github/scripts/src/release-write.ts +197 -0
  83. package/dist/skills/github/scripts/src/repo-admin.ts +112 -0
  84. package/dist/skills/github/scripts/src/repo-content.ts +187 -0
  85. package/dist/skills/github/scripts/src/repo-create.ts +139 -0
  86. package/dist/skills/github/scripts/src/repo-extras.ts +217 -0
  87. package/dist/skills/github/scripts/src/repo-list.ts +143 -0
  88. package/dist/skills/github/scripts/src/repo-settings.ts +176 -0
  89. package/dist/skills/github/scripts/src/repo-sync.ts +81 -0
  90. package/dist/skills/github/scripts/src/repo-url.ts +104 -0
  91. package/dist/skills/github/scripts/src/repos.ts +87 -0
  92. package/dist/skills/github/scripts/src/ruleset-shape.ts +96 -0
  93. package/dist/skills/github/scripts/src/rulesets-write.ts +124 -0
  94. package/dist/skills/github/scripts/src/rulesets.ts +80 -0
  95. package/dist/skills/github/scripts/src/run-download.ts +88 -0
  96. package/dist/skills/github/scripts/src/salsa20.ts +97 -0
  97. package/dist/skills/github/scripts/src/scopes.ts +165 -0
  98. package/dist/skills/github/scripts/src/sealed-box.ts +75 -0
  99. package/dist/skills/github/scripts/src/search-commits.ts +114 -0
  100. package/dist/skills/github/scripts/src/search.ts +116 -0
  101. package/dist/skills/github/scripts/src/secrets.ts +131 -0
  102. package/dist/skills/github/scripts/src/snappy.ts +57 -0
  103. package/dist/skills/github/scripts/src/status-search.ts +55 -0
  104. package/dist/skills/github/scripts/src/transfer.ts +97 -0
  105. package/dist/skills/github/scripts/src/types.ts +75 -0
  106. package/dist/skills/github/scripts/src/variables.ts +86 -0
  107. package/dist/skills/github/scripts/src/wait.ts +164 -0
  108. package/dist/skills/github/scripts/src/wire.ts +159 -0
  109. package/dist/skills/github/scripts/src/workflows.ts +144 -0
  110. package/dist/skills/github/scripts/src/zip.ts +104 -0
  111. package/dist/skills/github/scripts/surface.ts +106 -0
  112. package/dist/skills/github/scripts/vendor/surface/SOURCE.json +15 -0
  113. package/dist/skills/github/scripts/vendor/surface/cli.ts +203 -0
  114. package/dist/skills/github/scripts/vendor/surface/flags.ts +195 -0
  115. package/dist/skills/github/scripts/vendor/surface/help.ts +89 -0
  116. package/dist/skills/github/scripts/vendor/surface/http.ts +180 -0
  117. package/dist/skills/github/scripts/vendor/surface/index.ts +44 -0
  118. package/dist/skills/github/scripts/vendor/surface/mcp.ts +241 -0
  119. package/dist/skills/github/scripts/vendor/surface/schema.ts +200 -0
  120. package/dist/skills/github/scripts/vendor/surface/stdio.ts +54 -0
  121. package/dist/skills/github/scripts/vendor/surface/surface.ts +250 -0
  122. package/dist/skills/github/scripts/vendor/surface/tools.ts +80 -0
  123. package/dist/skills/programming/SKILL.md +51 -320
  124. package/dist/skills/programming/references/go/README.md +1 -0
  125. package/dist/skills/programming/references/python/README.md +21 -3
  126. package/dist/skills/programming/references/python/error-handling.md +14 -0
  127. package/dist/skills/programming/references/rust/README.md +5 -1
  128. package/dist/skills/programming/references/typescript/README.md +9 -3
  129. package/dist/skills/programming/references/typescript/error-handling.md +18 -0
  130. package/dist/skills/ultimate-browsing/SKILL.md +1 -1
  131. package/dist/skills/ulw-execute/SKILL.md +1 -1
  132. package/dist/skills/visual-qa/references/browser-setup.md +5 -5
  133. package/dist/tui.js +32 -29
  134. package/package.json +28 -26
  135. package/packages/omo-codex/plugin/.codex-plugin/plugin.json +1 -1
  136. package/packages/omo-codex/plugin/components/bootstrap/dist/cli.js +2 -2
  137. package/packages/omo-codex/plugin/components/bootstrap/hooks/hooks.json +1 -1
  138. package/packages/omo-codex/plugin/components/bootstrap/package.json +1 -1
  139. package/packages/omo-codex/plugin/components/comment-checker/hooks/hooks.json +1 -1
  140. package/packages/omo-codex/plugin/components/comment-checker/package.json +1 -1
  141. package/packages/omo-codex/plugin/components/git-bash/hooks/hooks.json +2 -2
  142. package/packages/omo-codex/plugin/components/git-bash/package.json +1 -1
  143. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/hooks/hooks.json +1 -1
  144. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/package.json +1 -1
  145. package/packages/omo-codex/plugin/components/lsp/dist/.omo-runtime-manifest.json +2 -2
  146. package/packages/omo-codex/plugin/components/lsp/hooks/hooks.json +2 -2
  147. package/packages/omo-codex/plugin/components/lsp/package.json +1 -1
  148. package/packages/omo-codex/plugin/components/rules/hooks/hooks.json +4 -4
  149. package/packages/omo-codex/plugin/components/rules/package.json +1 -1
  150. package/packages/omo-codex/plugin/components/teammode/hooks/hooks.json +1 -1
  151. package/packages/omo-codex/plugin/components/teammode/package.json +1 -1
  152. package/packages/omo-codex/plugin/components/telemetry/dist/cli.js +8711 -172
  153. package/packages/omo-codex/plugin/components/telemetry/dist/posthog.js +8660 -121
  154. package/packages/omo-codex/plugin/components/telemetry/hooks/hooks.json +1 -1
  155. package/packages/omo-codex/plugin/components/telemetry/package.json +1 -1
  156. package/packages/omo-codex/plugin/components/telemetry/src/posthog.ts +5 -0
  157. package/packages/omo-codex/plugin/components/telemetry/tsconfig.json +2 -2
  158. package/packages/omo-codex/plugin/components/ultrawork/hooks/hooks.json +1 -1
  159. package/packages/omo-codex/plugin/components/ultrawork/package.json +1 -1
  160. package/packages/omo-codex/plugin/components/ulw-execute-continuation/hooks/hooks.json +1 -1
  161. package/packages/omo-codex/plugin/components/ulw-execute-continuation/package.json +1 -1
  162. package/packages/omo-codex/plugin/components/ulw-loop/hooks/hooks.json +5 -5
  163. package/packages/omo-codex/plugin/components/ulw-loop/package.json +1 -1
  164. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/SKILL.md +1 -1
  165. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/references/full-workflow.md +3 -3
  166. package/packages/omo-codex/plugin/hooks/post-compact-resetting-git-bash-mcp-reminder.json +1 -1
  167. package/packages/omo-codex/plugin/hooks/post-compact-resetting-lsp-diagnostics-cache.json +1 -1
  168. package/packages/omo-codex/plugin/hooks/post-compact-resetting-project-rule-cache.json +1 -1
  169. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-comments.json +1 -1
  170. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-lsp-diagnostics.json +1 -1
  171. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-thread-title-hygiene.json +1 -1
  172. package/packages/omo-codex/plugin/hooks/post-tool-use-matching-project-rules.json +1 -1
  173. package/packages/omo-codex/plugin/hooks/post-tool-use-recording-spawn-admission.json +1 -1
  174. package/packages/omo-codex/plugin/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json +1 -1
  175. package/packages/omo-codex/plugin/hooks/pre-tool-use-guarding-ulw-loop-spawns.json +1 -1
  176. package/packages/omo-codex/plugin/hooks/pre-tool-use-recommending-git-bash-mcp.json +1 -1
  177. package/packages/omo-codex/plugin/hooks/session-start-checking-auto-update.json +1 -1
  178. package/packages/omo-codex/plugin/hooks/session-start-checking-bootstrap-provisioning.json +1 -1
  179. package/packages/omo-codex/plugin/hooks/session-start-loading-project-rules.json +1 -1
  180. package/packages/omo-codex/plugin/hooks/session-start-recording-session-telemetry.json +1 -1
  181. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-execute-continuation.json +1 -1
  182. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-loop-resume.json +1 -1
  183. package/packages/omo-codex/plugin/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json +1 -1
  184. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ultrawork-trigger.json +1 -1
  185. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ulw-loop-steering.json +1 -1
  186. package/packages/omo-codex/plugin/hooks/user-prompt-submit-loading-project-rules.json +1 -1
  187. package/packages/omo-codex/plugin/package-lock.json +12 -12
  188. package/packages/omo-codex/plugin/package.json +1 -1
  189. package/packages/omo-codex/plugin/shared/src/config-loader.ts +15 -1
  190. package/packages/omo-codex/plugin/skills/browser/SKILL.md +100 -91
  191. package/packages/omo-codex/plugin/skills/browser/references/commands.md +92 -27
  192. package/packages/omo-codex/plugin/skills/browser/references/desktop.md +22 -0
  193. package/packages/omo-codex/plugin/skills/browser/references/install.md +18 -0
  194. package/packages/omo-codex/plugin/skills/browser/references/owned-engine/README.md +7 -2
  195. package/packages/omo-codex/plugin/skills/browser/references/owned-engine/frames-and-humans.md +9 -2
  196. package/packages/omo-codex/plugin/skills/browser/references/owned-engine/network.md +13 -7
  197. package/packages/omo-codex/plugin/skills/browser/references/recipes/1password.md +6 -2
  198. package/packages/omo-codex/plugin/skills/browser/runtime/omowright/index.js +15 -15
  199. package/packages/omo-codex/plugin/skills/browser/runtime/omowright/manifest.json +4 -4
  200. package/packages/omo-codex/plugin/skills/debugging/SKILL.md +1 -1
  201. package/packages/omo-codex/plugin/skills/debugging/references/tools/browser-qa.md +1 -1
  202. package/packages/omo-codex/plugin/skills/git/SKILL.md +62 -0
  203. package/packages/omo-codex/plugin/skills/git/agents/openai.yaml +13 -0
  204. package/packages/omo-codex/plugin/skills/github/SKILL.md +94 -0
  205. package/packages/omo-codex/plugin/skills/github/agents/openai.yaml +2 -0
  206. package/packages/omo-codex/plugin/skills/github/references/branch-rules.md +129 -0
  207. package/packages/omo-codex/plugin/skills/github/references/evidence-attachments.md +16 -0
  208. package/packages/omo-codex/plugin/skills/github/references/repo-setup.md +152 -0
  209. package/packages/omo-codex/plugin/skills/github/references/waiting.md +52 -0
  210. package/packages/omo-codex/plugin/skills/github/references/workflows.md +161 -0
  211. package/packages/omo-codex/plugin/skills/github/scripts/cli.ts +8 -0
  212. package/packages/omo-codex/plugin/skills/github/scripts/package.json +12 -0
  213. package/packages/omo-codex/plugin/skills/github/scripts/sdk.ts +11 -0
  214. package/packages/omo-codex/plugin/skills/github/scripts/src/account.ts +243 -0
  215. package/packages/omo-codex/plugin/skills/github/scripts/src/actions-write.ts +86 -0
  216. package/packages/omo-codex/plugin/skills/github/scripts/src/actions.ts +210 -0
  217. package/packages/omo-codex/plugin/skills/github/scripts/src/attestations.ts +136 -0
  218. package/packages/omo-codex/plugin/skills/github/scripts/src/blake2b.ts +102 -0
  219. package/packages/omo-codex/plugin/skills/github/scripts/src/branch-protection.ts +192 -0
  220. package/packages/omo-codex/plugin/skills/github/scripts/src/caches.ts +105 -0
  221. package/packages/omo-codex/plugin/skills/github/scripts/src/checks.ts +107 -0
  222. package/packages/omo-codex/plugin/skills/github/scripts/src/codespaces.ts +230 -0
  223. package/packages/omo-codex/plugin/skills/github/scripts/src/conversation-lock.ts +50 -0
  224. package/packages/omo-codex/plugin/skills/github/scripts/src/discussion-list.ts +126 -0
  225. package/packages/omo-codex/plugin/skills/github/scripts/src/discussion-lookup.ts +127 -0
  226. package/packages/omo-codex/plugin/skills/github/scripts/src/discussions.ts +234 -0
  227. package/packages/omo-codex/plugin/skills/github/scripts/src/env.ts +100 -0
  228. package/packages/omo-codex/plugin/skills/github/scripts/src/errors.ts +79 -0
  229. package/packages/omo-codex/plugin/skills/github/scripts/src/fields.ts +27 -0
  230. package/packages/omo-codex/plugin/skills/github/scripts/src/gist-shape.ts +58 -0
  231. package/packages/omo-codex/plugin/skills/github/scripts/src/gists-write.ts +130 -0
  232. package/packages/omo-codex/plugin/skills/github/scripts/src/gists.ts +118 -0
  233. package/packages/omo-codex/plugin/skills/github/scripts/src/git-auth.ts +46 -0
  234. package/packages/omo-codex/plugin/skills/github/scripts/src/http.ts +159 -0
  235. package/packages/omo-codex/plugin/skills/github/scripts/src/issue-develop.ts +118 -0
  236. package/packages/omo-codex/plugin/skills/github/scripts/src/issues-extra.ts +135 -0
  237. package/packages/omo-codex/plugin/skills/github/scripts/src/issues-write.ts +174 -0
  238. package/packages/omo-codex/plugin/skills/github/scripts/src/issues.ts +156 -0
  239. package/packages/omo-codex/plugin/skills/github/scripts/src/keys.ts +176 -0
  240. package/packages/omo-codex/plugin/skills/github/scripts/src/labels.ts +209 -0
  241. package/packages/omo-codex/plugin/skills/github/scripts/src/merge.ts +115 -0
  242. package/packages/omo-codex/plugin/skills/github/scripts/src/poly1305.ts +22 -0
  243. package/packages/omo-codex/plugin/skills/github/scripts/src/pr-checkout.ts +92 -0
  244. package/packages/omo-codex/plugin/skills/github/scripts/src/pr-view.ts +106 -0
  245. package/packages/omo-codex/plugin/skills/github/scripts/src/project-fields.ts +144 -0
  246. package/packages/omo-codex/plugin/skills/github/scripts/src/project-item-edit.ts +153 -0
  247. package/packages/omo-codex/plugin/skills/github/scripts/src/project-items.ts +191 -0
  248. package/packages/omo-codex/plugin/skills/github/scripts/src/project-links.ts +104 -0
  249. package/packages/omo-codex/plugin/skills/github/scripts/src/project-ref.ts +145 -0
  250. package/packages/omo-codex/plugin/skills/github/scripts/src/project-state.ts +99 -0
  251. package/packages/omo-codex/plugin/skills/github/scripts/src/projects.ts +158 -0
  252. package/packages/omo-codex/plugin/skills/github/scripts/src/pulls-extra.ts +165 -0
  253. package/packages/omo-codex/plugin/skills/github/scripts/src/pulls-read.ts +176 -0
  254. package/packages/omo-codex/plugin/skills/github/scripts/src/pulls-review.ts +206 -0
  255. package/packages/omo-codex/plugin/skills/github/scripts/src/pulls-write.ts +187 -0
  256. package/packages/omo-codex/plugin/skills/github/scripts/src/raw.ts +78 -0
  257. package/packages/omo-codex/plugin/skills/github/scripts/src/read.ts +77 -0
  258. package/packages/omo-codex/plugin/skills/github/scripts/src/release-assets.ts +111 -0
  259. package/packages/omo-codex/plugin/skills/github/scripts/src/release-download.ts +151 -0
  260. package/packages/omo-codex/plugin/skills/github/scripts/src/release-write.ts +197 -0
  261. package/packages/omo-codex/plugin/skills/github/scripts/src/repo-admin.ts +112 -0
  262. package/packages/omo-codex/plugin/skills/github/scripts/src/repo-content.ts +187 -0
  263. package/packages/omo-codex/plugin/skills/github/scripts/src/repo-create.ts +139 -0
  264. package/packages/omo-codex/plugin/skills/github/scripts/src/repo-extras.ts +217 -0
  265. package/packages/omo-codex/plugin/skills/github/scripts/src/repo-list.ts +143 -0
  266. package/packages/omo-codex/plugin/skills/github/scripts/src/repo-settings.ts +176 -0
  267. package/packages/omo-codex/plugin/skills/github/scripts/src/repo-sync.ts +81 -0
  268. package/packages/omo-codex/plugin/skills/github/scripts/src/repo-url.ts +104 -0
  269. package/packages/omo-codex/plugin/skills/github/scripts/src/repos.ts +87 -0
  270. package/packages/omo-codex/plugin/skills/github/scripts/src/ruleset-shape.ts +96 -0
  271. package/packages/omo-codex/plugin/skills/github/scripts/src/rulesets-write.ts +124 -0
  272. package/packages/omo-codex/plugin/skills/github/scripts/src/rulesets.ts +80 -0
  273. package/packages/omo-codex/plugin/skills/github/scripts/src/run-download.ts +88 -0
  274. package/packages/omo-codex/plugin/skills/github/scripts/src/salsa20.ts +97 -0
  275. package/packages/omo-codex/plugin/skills/github/scripts/src/scopes.ts +165 -0
  276. package/packages/omo-codex/plugin/skills/github/scripts/src/sealed-box.ts +75 -0
  277. package/packages/omo-codex/plugin/skills/github/scripts/src/search-commits.ts +114 -0
  278. package/packages/omo-codex/plugin/skills/github/scripts/src/search.ts +116 -0
  279. package/packages/omo-codex/plugin/skills/github/scripts/src/secrets.ts +131 -0
  280. package/packages/omo-codex/plugin/skills/github/scripts/src/snappy.ts +57 -0
  281. package/packages/omo-codex/plugin/skills/github/scripts/src/status-search.ts +55 -0
  282. package/packages/omo-codex/plugin/skills/github/scripts/src/transfer.ts +97 -0
  283. package/packages/omo-codex/plugin/skills/github/scripts/src/types.ts +75 -0
  284. package/packages/omo-codex/plugin/skills/github/scripts/src/variables.ts +86 -0
  285. package/packages/omo-codex/plugin/skills/github/scripts/src/wait.ts +164 -0
  286. package/packages/omo-codex/plugin/skills/github/scripts/src/wire.ts +159 -0
  287. package/packages/omo-codex/plugin/skills/github/scripts/src/workflows.ts +144 -0
  288. package/packages/omo-codex/plugin/skills/github/scripts/src/zip.ts +104 -0
  289. package/packages/omo-codex/plugin/skills/github/scripts/surface.ts +106 -0
  290. package/packages/omo-codex/plugin/skills/github/scripts/vendor/surface/SOURCE.json +15 -0
  291. package/packages/omo-codex/plugin/skills/github/scripts/vendor/surface/cli.ts +203 -0
  292. package/packages/omo-codex/plugin/skills/github/scripts/vendor/surface/flags.ts +195 -0
  293. package/packages/omo-codex/plugin/skills/github/scripts/vendor/surface/help.ts +89 -0
  294. package/packages/omo-codex/plugin/skills/github/scripts/vendor/surface/http.ts +180 -0
  295. package/packages/omo-codex/plugin/skills/github/scripts/vendor/surface/index.ts +44 -0
  296. package/packages/omo-codex/plugin/skills/github/scripts/vendor/surface/mcp.ts +241 -0
  297. package/packages/omo-codex/plugin/skills/github/scripts/vendor/surface/schema.ts +200 -0
  298. package/packages/omo-codex/plugin/skills/github/scripts/vendor/surface/stdio.ts +54 -0
  299. package/packages/omo-codex/plugin/skills/github/scripts/vendor/surface/surface.ts +250 -0
  300. package/packages/omo-codex/plugin/skills/github/scripts/vendor/surface/tools.ts +80 -0
  301. package/packages/omo-codex/plugin/skills/programming/SKILL.md +51 -320
  302. package/packages/omo-codex/plugin/skills/programming/references/go/README.md +1 -0
  303. package/packages/omo-codex/plugin/skills/programming/references/python/README.md +21 -3
  304. package/packages/omo-codex/plugin/skills/programming/references/python/error-handling.md +14 -0
  305. package/packages/omo-codex/plugin/skills/programming/references/rust/README.md +5 -1
  306. package/packages/omo-codex/plugin/skills/programming/references/typescript/README.md +9 -3
  307. package/packages/omo-codex/plugin/skills/programming/references/typescript/error-handling.md +18 -0
  308. package/packages/omo-codex/plugin/skills/ultimate-browsing/SKILL.md +1 -1
  309. package/packages/omo-codex/plugin/skills/ulw-execute/SKILL.md +1 -1
  310. package/packages/omo-codex/plugin/skills/ulw-loop/SKILL.md +1 -1
  311. package/packages/omo-codex/plugin/skills/ulw-loop/references/full-workflow.md +3 -3
  312. package/packages/omo-codex/plugin/skills/visual-qa/references/browser-setup.md +5 -5
  313. package/packages/omo-codex/plugin/test/sync-skills-codex-compatibility.test.mjs +1 -1
  314. package/packages/omo-codex/plugin/test/sync-skills-test-support.mjs +2 -1
  315. package/packages/omo-codex/plugin/test/sync-skills.test.mjs +5 -5
  316. package/packages/omo-codex/scripts/install-dist/install-local.mjs +21279 -20738
  317. package/packages/shared-skills/skills/browser/SKILL.md +100 -91
  318. package/packages/shared-skills/skills/browser/references/commands.md +92 -27
  319. package/packages/shared-skills/skills/browser/references/desktop.md +22 -0
  320. package/packages/shared-skills/skills/browser/references/install.md +18 -0
  321. package/packages/shared-skills/skills/browser/references/owned-engine/README.md +7 -2
  322. package/packages/shared-skills/skills/browser/references/owned-engine/frames-and-humans.md +9 -2
  323. package/packages/shared-skills/skills/browser/references/owned-engine/network.md +13 -7
  324. package/packages/shared-skills/skills/browser/references/recipes/1password.md +6 -2
  325. package/packages/shared-skills/skills/browser/runtime/omowright/index.js +15 -15
  326. package/packages/shared-skills/skills/browser/runtime/omowright/manifest.json +4 -4
  327. package/packages/shared-skills/skills/debugging/SKILL.md +1 -1
  328. package/packages/shared-skills/skills/debugging/references/tools/browser-qa.md +1 -1
  329. package/packages/shared-skills/skills/git/SKILL.md +62 -0
  330. package/packages/shared-skills/skills/git/agents/openai.yaml +13 -0
  331. package/packages/shared-skills/skills/github/SKILL.md +94 -0
  332. package/packages/shared-skills/skills/github/references/branch-rules.md +129 -0
  333. package/packages/shared-skills/skills/github/references/evidence-attachments.md +16 -0
  334. package/packages/shared-skills/skills/github/references/repo-setup.md +152 -0
  335. package/packages/shared-skills/skills/github/references/waiting.md +52 -0
  336. package/packages/shared-skills/skills/github/references/workflows.md +161 -0
  337. package/packages/shared-skills/skills/github/scripts/cli.ts +8 -0
  338. package/packages/shared-skills/skills/github/scripts/package.json +12 -0
  339. package/packages/shared-skills/skills/github/scripts/sdk.ts +11 -0
  340. package/packages/shared-skills/skills/github/scripts/src/account.ts +243 -0
  341. package/packages/shared-skills/skills/github/scripts/src/actions-write.ts +86 -0
  342. package/packages/shared-skills/skills/github/scripts/src/actions.ts +210 -0
  343. package/packages/shared-skills/skills/github/scripts/src/attestations.ts +136 -0
  344. package/packages/shared-skills/skills/github/scripts/src/blake2b.ts +102 -0
  345. package/packages/shared-skills/skills/github/scripts/src/branch-protection.ts +192 -0
  346. package/packages/shared-skills/skills/github/scripts/src/caches.ts +105 -0
  347. package/packages/shared-skills/skills/github/scripts/src/checks.ts +107 -0
  348. package/packages/shared-skills/skills/github/scripts/src/codespaces.ts +230 -0
  349. package/packages/shared-skills/skills/github/scripts/src/conversation-lock.ts +50 -0
  350. package/packages/shared-skills/skills/github/scripts/src/discussion-list.ts +126 -0
  351. package/packages/shared-skills/skills/github/scripts/src/discussion-lookup.ts +127 -0
  352. package/packages/shared-skills/skills/github/scripts/src/discussions.ts +234 -0
  353. package/packages/shared-skills/skills/github/scripts/src/env.ts +100 -0
  354. package/packages/shared-skills/skills/github/scripts/src/errors.ts +79 -0
  355. package/packages/shared-skills/skills/github/scripts/src/fields.ts +27 -0
  356. package/packages/shared-skills/skills/github/scripts/src/gist-shape.ts +58 -0
  357. package/packages/shared-skills/skills/github/scripts/src/gists-write.ts +130 -0
  358. package/packages/shared-skills/skills/github/scripts/src/gists.ts +118 -0
  359. package/packages/shared-skills/skills/github/scripts/src/git-auth.ts +46 -0
  360. package/packages/shared-skills/skills/github/scripts/src/http.ts +159 -0
  361. package/packages/shared-skills/skills/github/scripts/src/issue-develop.ts +118 -0
  362. package/packages/shared-skills/skills/github/scripts/src/issues-extra.ts +135 -0
  363. package/packages/shared-skills/skills/github/scripts/src/issues-write.ts +174 -0
  364. package/packages/shared-skills/skills/github/scripts/src/issues.ts +156 -0
  365. package/packages/shared-skills/skills/github/scripts/src/keys.ts +176 -0
  366. package/packages/shared-skills/skills/github/scripts/src/labels.ts +209 -0
  367. package/packages/shared-skills/skills/github/scripts/src/merge.ts +115 -0
  368. package/packages/shared-skills/skills/github/scripts/src/poly1305.ts +22 -0
  369. package/packages/shared-skills/skills/github/scripts/src/pr-checkout.ts +92 -0
  370. package/packages/shared-skills/skills/github/scripts/src/pr-view.ts +106 -0
  371. package/packages/shared-skills/skills/github/scripts/src/project-fields.ts +144 -0
  372. package/packages/shared-skills/skills/github/scripts/src/project-item-edit.ts +153 -0
  373. package/packages/shared-skills/skills/github/scripts/src/project-items.ts +191 -0
  374. package/packages/shared-skills/skills/github/scripts/src/project-links.ts +104 -0
  375. package/packages/shared-skills/skills/github/scripts/src/project-ref.ts +145 -0
  376. package/packages/shared-skills/skills/github/scripts/src/project-state.ts +99 -0
  377. package/packages/shared-skills/skills/github/scripts/src/projects.ts +158 -0
  378. package/packages/shared-skills/skills/github/scripts/src/pulls-extra.ts +165 -0
  379. package/packages/shared-skills/skills/github/scripts/src/pulls-read.ts +176 -0
  380. package/packages/shared-skills/skills/github/scripts/src/pulls-review.ts +206 -0
  381. package/packages/shared-skills/skills/github/scripts/src/pulls-write.ts +187 -0
  382. package/packages/shared-skills/skills/github/scripts/src/raw.ts +78 -0
  383. package/packages/shared-skills/skills/github/scripts/src/read.ts +77 -0
  384. package/packages/shared-skills/skills/github/scripts/src/release-assets.ts +111 -0
  385. package/packages/shared-skills/skills/github/scripts/src/release-download.ts +151 -0
  386. package/packages/shared-skills/skills/github/scripts/src/release-write.ts +197 -0
  387. package/packages/shared-skills/skills/github/scripts/src/repo-admin.ts +112 -0
  388. package/packages/shared-skills/skills/github/scripts/src/repo-content.ts +187 -0
  389. package/packages/shared-skills/skills/github/scripts/src/repo-create.ts +139 -0
  390. package/packages/shared-skills/skills/github/scripts/src/repo-extras.ts +217 -0
  391. package/packages/shared-skills/skills/github/scripts/src/repo-list.ts +143 -0
  392. package/packages/shared-skills/skills/github/scripts/src/repo-settings.ts +176 -0
  393. package/packages/shared-skills/skills/github/scripts/src/repo-sync.ts +81 -0
  394. package/packages/shared-skills/skills/github/scripts/src/repo-url.ts +104 -0
  395. package/packages/shared-skills/skills/github/scripts/src/repos.ts +87 -0
  396. package/packages/shared-skills/skills/github/scripts/src/ruleset-shape.ts +96 -0
  397. package/packages/shared-skills/skills/github/scripts/src/rulesets-write.ts +124 -0
  398. package/packages/shared-skills/skills/github/scripts/src/rulesets.ts +80 -0
  399. package/packages/shared-skills/skills/github/scripts/src/run-download.ts +88 -0
  400. package/packages/shared-skills/skills/github/scripts/src/salsa20.ts +97 -0
  401. package/packages/shared-skills/skills/github/scripts/src/scopes.ts +165 -0
  402. package/packages/shared-skills/skills/github/scripts/src/sealed-box.ts +75 -0
  403. package/packages/shared-skills/skills/github/scripts/src/search-commits.ts +114 -0
  404. package/packages/shared-skills/skills/github/scripts/src/search.ts +116 -0
  405. package/packages/shared-skills/skills/github/scripts/src/secrets.ts +131 -0
  406. package/packages/shared-skills/skills/github/scripts/src/snappy.ts +57 -0
  407. package/packages/shared-skills/skills/github/scripts/src/status-search.ts +55 -0
  408. package/packages/shared-skills/skills/github/scripts/src/transfer.ts +97 -0
  409. package/packages/shared-skills/skills/github/scripts/src/types.ts +75 -0
  410. package/packages/shared-skills/skills/github/scripts/src/variables.ts +86 -0
  411. package/packages/shared-skills/skills/github/scripts/src/wait.ts +164 -0
  412. package/packages/shared-skills/skills/github/scripts/src/wire.ts +159 -0
  413. package/packages/shared-skills/skills/github/scripts/src/workflows.ts +144 -0
  414. package/packages/shared-skills/skills/github/scripts/src/zip.ts +104 -0
  415. package/packages/shared-skills/skills/github/scripts/surface.ts +106 -0
  416. package/packages/shared-skills/skills/github/scripts/vendor/surface/SOURCE.json +15 -0
  417. package/packages/shared-skills/skills/github/scripts/vendor/surface/cli.ts +203 -0
  418. package/packages/shared-skills/skills/github/scripts/vendor/surface/flags.ts +195 -0
  419. package/packages/shared-skills/skills/github/scripts/vendor/surface/help.ts +89 -0
  420. package/packages/shared-skills/skills/github/scripts/vendor/surface/http.ts +180 -0
  421. package/packages/shared-skills/skills/github/scripts/vendor/surface/index.ts +44 -0
  422. package/packages/shared-skills/skills/github/scripts/vendor/surface/mcp.ts +241 -0
  423. package/packages/shared-skills/skills/github/scripts/vendor/surface/schema.ts +200 -0
  424. package/packages/shared-skills/skills/github/scripts/vendor/surface/stdio.ts +54 -0
  425. package/packages/shared-skills/skills/github/scripts/vendor/surface/surface.ts +250 -0
  426. package/packages/shared-skills/skills/github/scripts/vendor/surface/tools.ts +80 -0
  427. package/packages/shared-skills/skills/programming/SKILL.md +51 -320
  428. package/packages/shared-skills/skills/programming/references/go/README.md +1 -0
  429. package/packages/shared-skills/skills/programming/references/python/README.md +21 -3
  430. package/packages/shared-skills/skills/programming/references/python/error-handling.md +14 -0
  431. package/packages/shared-skills/skills/programming/references/rust/README.md +5 -1
  432. package/packages/shared-skills/skills/programming/references/typescript/README.md +9 -3
  433. package/packages/shared-skills/skills/programming/references/typescript/error-handling.md +18 -0
  434. package/packages/shared-skills/skills/ultimate-browsing/SKILL.md +1 -1
  435. package/packages/shared-skills/skills/ulw-execute/SKILL.md +1 -1
  436. package/packages/shared-skills/skills/visual-qa/references/browser-setup.md +5 -5
  437. package/dist/skills/git-master/SKILL.md +0 -114
  438. package/dist/skills/git-master/agents/openai.yaml +0 -13
  439. package/packages/omo-codex/plugin/skills/git-master/SKILL.md +0 -114
  440. package/packages/omo-codex/plugin/skills/git-master/agents/openai.yaml +0 -13
  441. package/packages/shared-skills/skills/git-master/SKILL.md +0 -114
  442. package/packages/shared-skills/skills/git-master/agents/openai.yaml +0 -13
@@ -1,4 +1,4 @@
1
- var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};import path from"node:path";async function openNtdll(){const{dlopen,ptr}=await import("bun:ffi");const systemRoot=process.env["SystemRoot"]||process.env["windir"]||"C:\\Windows";const{symbols}=dlopen(path.win32.join(systemRoot,"System32","ntdll.dll"),{NtCreateFile:{args:["buffer","u32","buffer","buffer","ptr","u32","u32","u32","u32","ptr","u32"],returns:"u32"},NtClose:{args:["u64"],returns:"u32"},RtlNtStatusToDosError:{args:["u32"],returns:"u32"}});return{symbols,ptr}}function loadNtdll(){ntdll??=openNtdll().catch((error)=>{ntdll=undefined;throw error});return ntdll}function nativeError(symbols,operation,lockPath,status){const error=symbols.RtlNtStatusToDosError(status);return Object.assign(new Error(`instance lock ${operation} failed for ${lockPath} (Windows error ${error}, NTSTATUS 0x${status.toString(16)})`),{code:"ERR_INSTANCE_LOCK"})}async function tryAcquireWindows(lockPath){const{symbols,ptr}=await loadNtdll();const filename=Buffer.from(`${path.toNamespacedPath(path.resolve(lockPath)).replace(/^\\\\\?\\/,"\\??\\")}\x00`,"utf16le");const name=Buffer.alloc(16);name.writeUInt16LE(filename.length-2,0);name.writeUInt16LE(filename.length,2);name.writeBigUInt64LE(BigInt(ptr(filename)),8);const attributes=Buffer.alloc(48);attributes.writeUInt32LE(48,0);attributes.writeBigUInt64LE(BigInt(ptr(name)),16);attributes.writeUInt32LE(64,24);const handleOut=Buffer.alloc(8);const ioStatus=Buffer.alloc(16);const status=symbols.NtCreateFile(handleOut,3222274048,attributes,ioStatus,null,128,0,3,96,null,0);if(status===3221225539)return null;if(status>=2147483648)throw nativeError(symbols,"NtCreateFile",lockPath,status);const handle=handleOut.readBigUInt64LE();return{release(){const closeStatus=symbols.NtClose(handle);if(closeStatus>=2147483648)throw nativeError(symbols,"NtClose",lockPath,closeStatus)}}}var ntdll;var init_lock_backend_win32_xbcm60vz=()=>{};import{createRequire}from"node:module";import path3 from"node:path";import{mkdir as mkdir4}from"node:fs/promises";import path2 from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{createReadStream,promises}from"node:fs";import*as fs$16 from"node:fs/promises";import{spawn}from"node:child_process";import{tmpdir}from"node:os";import{readFileSync}from"node:fs";import{readFile}from"node:fs/promises";import{readFile as readFile2}from"node:fs/promises";import{randomUUID}from"node:crypto";import{isDeepStrictEqual}from"node:util";import{mkdir as mkdir3,writeFile as writeFile2}from"node:fs/promises";import path22 from"node:path";import{spawn as spawn3}from"node:child_process";import{finished}from"node:stream/promises";import{mkdirSync,readFileSync as readFileSync2,rmSync,writeFileSync}from"node:fs";import path5 from"node:path";import{setTimeout as sleep2}from"node:timers/promises";import{unlink as unlink2}from"node:fs/promises";import{setTimeout as sleep}from"node:timers/promises";import{spawn as spawn2}from"node:child_process";import{constants}from"node:fs";import{open as open2}from"node:fs/promises";import{execFile}from"node:child_process";import{readFile as readFile3}from"node:fs/promises";import path4 from"node:path";import{promisify}from"node:util";import{spawn as spawn4}from"node:child_process";import{createHash,randomUUID as randomUUID2}from"node:crypto";import{mkdir as mkdir5,open as open3,readFile as readFile6,readdir,rename,unlink as unlink3}from"node:fs/promises";import os from"node:os";import path8 from"node:path";import{watch}from"node:fs";import{readFile as readFile4,stat}from"node:fs/promises";import path6 from"node:path";import{execFile as execFile2}from"node:child_process";import{chmod,mkdtemp,readFile as readFile5,rm,stat as stat2}from"node:fs/promises";import{tmpdir as tmpdir2}from"node:os";import path7 from"node:path";import{promisify as promisify2}from"node:util";import{readFile as readFile7}from"node:fs/promises";import{connect as connectTcp}from"node:net";import path10 from"node:path";import{existsSync}from"node:fs";import{homedir}from"node:os";import path9 from"node:path";import{randomInt}from"node:crypto";import{mkdir as mkdir6,open as open4,readFile as readFile8,unlink as unlink4}from"node:fs/promises";import{globSync}from"node:fs";import os2 from"node:os";import path11 from"node:path";import{spawn as spawn5}from"node:child_process";import{mkdtempSync,writeFileSync as writeFileSync2,rmSync as rmSync2}from"node:fs";import{tmpdir as tmpdir3}from"node:os";import path12 from"node:path";import{randomUUID as randomUUID3}from"node:crypto";import path16 from"node:path";import{mkdir as mkdir8,open as open5,readFile as readFile9,readlink,realpath,rename as rename2,lstat,chmod as chmod2}from"node:fs/promises";import{homedir as homedir2}from"node:os";import{TextDecoder as TextDecoder2}from"node:util";import{mkdirSync as mkdirSync2}from"node:fs";import path14 from"node:path";import{tmpdir as tmpdir4}from"node:os";import{existsSync as existsSync2,readFileSync as readFileSync3}from"node:fs";import path13 from"node:path";import{execFile as execFile3}from"node:child_process";import{existsSync as existsSync3}from"node:fs";import{mkdir as mkdir7,rmdir,unlink as unlink5}from"node:fs/promises";import path15 from"node:path";import{mkdir as mkdir9,writeFile as writeFile3}from"node:fs/promises";import path17 from"node:path";import{connect as connect2}from"node:net";import{existsSync as existsSync6,readdirSync}from"node:fs";import path20 from"node:path";import{randomBytes}from"node:crypto";import{existsSync as existsSync5,readFileSync as readFileSync5}from"node:fs";import{homedir as homedir4}from"node:os";import path19 from"node:path";import{spawn as spawn7}from"node:child_process";import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync4,readFileSync as readFileSync4,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{homedir as homedir3}from"node:os";import path18 from"node:path";import{spawn as spawn6}from"node:child_process";import{spawn as spawnChild}from"node:child_process";import{randomBytes as randomBytes2}from"node:crypto";import{existsSync as existsSync8,readFileSync as readFileSync6}from"node:fs";import{homedir as homedir6}from"node:os";import path222 from"node:path";import{spawn as spawn8}from"node:child_process";import{existsSync as existsSync7}from"node:fs";import{homedir as homedir5}from"node:os";import path21 from"node:path";import{randomInt as randomInt2}from"node:crypto";import{existsSync as existsSync9,mkdirSync as mkdirSync3,readFileSync as readFileSync7,rmSync as rmSync4,writeFileSync as writeFileSync4}from"node:fs";import{spawn as spawn9}from"node:child_process";import path23 from"node:path";import{execFile as execFile4}from"node:child_process";import{statSync}from"node:fs";import{homedir as homedir7}from"node:os";import path24 from"node:path";import{homedir as homedir8}from"node:os";import{existsSync as existsSync10,readFileSync as readFileSync8}from"node:fs";var __create=Object.create;var __getProtoOf=Object.getPrototypeOf;var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node;var __toESMCache_esm;var __toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap;var cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};const to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:true}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:true})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true,configurable:true,set:__exportSetter.bind(all,name)})};var __require=createRequire(import.meta.url);var require_constants=__commonJS(function(exports,module){var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"];var hasBlob=typeof Blob!=="undefined";if(hasBlob)BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var require_buffer_util=__commonJS(function(exports,module){var{websocketMask,websocketUnmask}=__require("http");var{EMPTY_BUFFER}=require_constants();var FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i<list.length;i++){const buf=list[i];target.set(buf,offset);offset+=buf.length}if(offset<totalLength){return new FastBuffer(target.buffer,target.byteOffset,offset)}return target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++){output[offset+i]=source[i]^mask[i&3]}}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++){buffer[i]^=mask[i&3]}}function toArrayBuffer(buf){if(buf.length===buf.buffer.byteLength){return buf.buffer}return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){toBuffer.readOnly=true;if(Buffer.isBuffer(data))return data;let buf;if(data instanceof ArrayBuffer){buf=new FastBuffer(data)}else if(ArrayBuffer.isView(data)){buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength)}else{buf=Buffer.from(data);toBuffer.readOnly=false}return buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(websocketMask){module.exports.mask=function(source,mask,output,offset,length){if(length<24)_mask(source,mask,output,offset,length);else websocketMask(source,mask,output,offset,length)};module.exports.unmask=function(buffer,mask){if(buffer.length<24)_unmask(buffer,mask);else websocketUnmask(buffer,mask)}}else if(!process.env.WS_NO_BUFFER_UTIL){try{const bufferUtil=(()=>{throw new Error("Cannot require module "+"bufferutil")})();module.exports.mask=function(source,mask2,output,offset,length){if(length<48)_mask(source,mask2,output,offset,length);else bufferUtil.mask(source,mask2,output,offset,length)};module.exports.unmask=function(buffer,mask){if(buffer.length<32)_unmask(buffer,mask);else bufferUtil.unmask(buffer,mask)}}catch(e){}}});var require_limiter=__commonJS(function(exports,module){var kDone=Symbol("kDone");var kRun=Symbol("kRun");class Limiter{constructor(concurrency){this[kDone]=()=>{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}}module.exports=Limiter});var require_permessage_deflate=__commonJS(function(exports,module){var zlib=__require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants();var FastBuffer=Buffer[Symbol.species];var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("error");var zlibLimiter;class PerMessageDeflate{constructor(options){this._options=options||{};this._threshold=this._options.threshold!==undefined?this._options.threshold:1024;this._maxPayload=this._options.maxPayload|0;this._isServer=!!this._options.isServer;this._deflate=null;this._inflate=null;this.params=null;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==undefined?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.find((params)=>{if(opts.serverNoContextTakeover===false&&params.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&(typeof params.client_max_window_bits==="number"?opts.clientMaxWindowBits>params.client_max_window_bits:!params.client_max_window_bits)){return false}return true});if(!accepted){throw new Error("None of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&&params.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&&params.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach((params)=>{Object.keys(params).forEach((key)=>{let value=params[key];if(value.length>1){throw new Error(`Parameter "${key}" must have only a single value`)}value=value[0];if(key==="client_max_window_bits"){if(value!==true){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else if(key==="server_max_window_bits"){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else{throw new Error(`Unknown parameter "${key}"`)}params[key]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add((done)=>{this._decompress(data,fin,(err,result)=>{done();callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add((done)=>{this._compress(data,fin,(err,result)=>{done();callback(err,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err=this._inflate[kError];if(err){this._inflate.close();this._inflate=null;callback(err);return}const data=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin){data=new FastBuffer(data.buffer,data.byteOffset,data.length-4)}this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data)})}}module.exports=PerMessageDeflate;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err){this[kPerMessageDeflate]._inflate=null;if(this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007;this[kCallback](err)}});var require_validation=__commonJS(function(exports,module){var{isUtf8}=__require("buffer");var{hasBlob}=require_constants();var tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1000&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3000&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i<len){if((buf[i]&128)===0){i++}else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192){return false}i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}function isBlob(value){return hasBlob&&typeof value==="object"&&typeof value.arrayBuffer==="function"&&typeof value.type==="string"&&typeof value.stream==="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8){module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=(()=>{throw new Error("Cannot require module "+"utf-8-validate")})();module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e){}}});var require_receiver=__commonJS(function(exports,module){var{Writable}=__require("stream");var PerMessageDeflate=require_permessage_deflate();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants();var{concat,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var FastBuffer=Buffer[Symbol.species];var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;var INFLATING=5;var DEFER_EVENT=6;class Receiver extends Writable{constructor(options={}){super();this._allowSynchronousEvents=options.allowSynchronousEvents!==undefined?options.allowSynchronousEvents:true;this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxBufferedChunks=options.maxBufferedChunks|0;this._maxFragments=options.maxFragments|0;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.skipUTF8Validation;this[kWebSocket]=undefined;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=undefined;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._numFragments=0;this._fragments=[];this._errored=false;this._loop=false;this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){const buf=this._buffers[0];this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n);return new FastBuffer(buf.buffer,buf.byteOffset,n)}const dst=Buffer.allocUnsafe(n);do{const buf=this._buffers[0];const offset=dst.length-n;if(n>=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)}n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=true;do{switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=false;return}}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){const error=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate.extensionName]){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){const error=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const error=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){const error=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){const error=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num=buf.readUInt32BE(0);if(num>Math.pow(2,53-32)-1){const error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4);this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;return}data=this.consume(this._payloadLength);if(this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0){unmask(data,this._mask)}}this._mask=undefined;if(this._opcode>7){this.controlMessage(data,cb);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){const error=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){this._messageLength=this._totalPayloadLength;this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];perMessageDeflate.decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb);if(this._state===GET_INFO)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._numFragments=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat(fragments,messageLength))}else if(this._binaryType==="blob"){data=new Blob(fragments)}else{data=fragments}if(this._allowSynchronousEvents){this.emit("message",data,true);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",data,true);this._state=GET_INFO;this.startLoop(cb)})}}else{const buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",buf,false);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",buf,false);this._state=GET_INFO;this.startLoop(cb)})}}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0){this._loop=false;this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){const error=this.createError(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}const buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=false;this.emit("conclude",code,buf);this.end()}this._state=GET_INFO;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO;this.startLoop(cb)})}}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=false;this._errored=true;const err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);Error.captureStackTrace(err,this.createError);err.code=errorCode;err[kStatusCode]=statusCode;return err}}module.exports=Receiver});var require_sender=__commonJS(function(exports,module){var{Duplex}=__require("stream");var{randomFillSync}=__require("crypto");var{types:{isUint8Array}}=__require("util");var PerMessageDeflate=require_permessage_deflate();var{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants();var{isBlob,isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var RANDOM_POOL_SIZE=8*1024;var randomPool;var randomPoolPointer=RANDOM_POOL_SIZE;var DEFAULT=0;var DEFLATING=1;var GET_BLOB_DATA=2;class Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._queue=[];this._state=DEFAULT;this.onerror=NOOP;this[kWebSocket]=undefined}static frame(data,options){let mask;let merge=false;let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{if(randomPoolPointer===RANDOM_POOL_SIZE){if(randomPool===undefined){randomPool=Buffer.alloc(RANDOM_POOL_SIZE)}randomFillSync(randomPool,0,RANDOM_POOL_SIZE);randomPoolPointer=0}mask[0]=randomPool[randomPoolPointer++];mask[1]=randomPool[randomPoolPointer++];mask[2]=randomPool[randomPoolPointer++];mask[3]=randomPool[randomPoolPointer++]}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==undefined){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge?dataLength+offset:offset);target[0]=options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask){return dataLength?[target,data]:[target]}target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(!dataLength)return[target];if(skipMasking)return[target,data];if(merge){applyMask(data,mask,target,offset,dataLength);return[target]}applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===undefined){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===undefined||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else if(isUint8Array(data)){buf.set(data,2)}else{throw new TypeError("Second argument must be a string or a Uint8Array")}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._state!==DEFAULT){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(Sender.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender.frame(data,options),cb)}}send(data,options,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,this._compress,opts,cb])}else{this.getBlobData(data,this._compress,opts,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength];this._state=GET_BLOB_DATA;blob.arrayBuffer().then((arrayBuffer)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];const data=toBuffer(arrayBuffer);if(!compress){this._state=DEFAULT;this.sendFrame(Sender.frame(data,options),cb);this.dequeue()}else{this.dispatch(data,compress,options,cb)}}).catch((err)=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(Sender.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];this._bufferedBytes+=options[kByteLength];this._state=DEFLATING;perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength];this._state=DEFAULT;options.readOnly=false;this.sendFrame(Sender.frame(buf,options),cb);this.dequeue()})}dequeue(){while(this._state===DEFAULT&&this._queue.length){const params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength];Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength];this._queue.push(params)}sendFrame(list,cb){if(list.length===2){this._socket.cork();this._socket.write(list[0]);this._socket.write(list[1],cb);this._socket.uncork()}else{this._socket.write(list[0],cb)}}}module.exports=Sender;function callCallbacks(sender,err,cb){if(typeof cb==="function")cb(err);for(let i=0;i<sender._queue.length;i++){const params=sender._queue[i];const callback=params[params.length-1];if(typeof callback==="function")callback(err)}}function onError(sender,err,cb){callCallbacks(sender,err,cb);sender.onerror(err)}});var require_event_target=__commonJS(function(exports,module){var{kForOnEventAttribute,kListener}=require_constants();var kCode=Symbol("kCode");var kData=Symbol("kData");var kError=Symbol("kError");var kMessage=Symbol("kMessage");var kReason=Symbol("kReason");var kTarget=Symbol("kTarget");var kType=Symbol("kType");var kWasClean=Symbol("kWasClean");class Event{constructor(type){this[kTarget]=null;this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}}Object.defineProperty(Event.prototype,"target",{enumerable:true});Object.defineProperty(Event.prototype,"type",{enumerable:true});class CloseEvent extends Event{constructor(type,options={}){super(type);this[kCode]=options.code===undefined?0:options.code;this[kReason]=options.reason===undefined?"":options.reason;this[kWasClean]=options.wasClean===undefined?false:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}}Object.defineProperty(CloseEvent.prototype,"code",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:true});class ErrorEvent extends Event{constructor(type,options={}){super(type);this[kError]=options.error===undefined?null:options.error;this[kMessage]=options.message===undefined?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:true});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:true});class MessageEvent extends Event{constructor(type,options={}){super(type);this[kData]=options.data===undefined?null:options.data}get data(){return this[kData]}}Object.defineProperty(MessageEvent.prototype,"data",{enumerable:true});var EventTarget={addEventListener(type,handler,options={}){for(const listener of this.listeners(type)){if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute]){return}}let wrapper;if(type==="message"){wrapper=function onMessage(data,isBinary){const event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="close"){wrapper=function onClose(code,message){const event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="error"){wrapper=function onError(error){const event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="open"){wrapper=function onOpen(){const event=new Event("open");event[kTarget]=this;callListener(handler,this,event)}}else{return}wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute];wrapper[kListener]=handler;if(options.once){this.once(type,wrapper)}else{this.on(type,wrapper)}},removeEventListener(type,handler){for(const listener of this.listeners(type)){if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){if(typeof listener==="object"&&listener.handleEvent){listener.handleEvent.call(listener,event)}else{listener.call(thisArg,event)}}});var require_extension=__commonJS(function(exports,module){var{tokenChars}=require_validation();function push(dest,name,elem){if(dest[name]===undefined)dest[name]=[elem];else dest[name].push(elem)}function parse(header){const offers=Object.create(null);let params=Object.create(null);let mustUnescape=false;let isEscaping=false;let inQuotes=false;let extensionName;let paramName;let start=-1;let code=-1;let end=-1;let i=0;for(;i<header.length;i++){code=header.charCodeAt(i);if(extensionName===undefined){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const name=header.slice(start,end);if(code===44){push(offers,name,params);params=Object.create(null)}else{extensionName=name}start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(paramName===undefined){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(code===32||code===9){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;push(params,header.slice(start,end),true);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=undefined}start=end=-1}else if(code===61&&start!==-1&&end===-1){paramName=header.slice(start,i);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else{if(isEscaping){if(tokenChars[code]!==1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1)start=i;else if(!mustUnescape)mustUnescape=true;isEscaping=false}else if(inQuotes){if(tokenChars[code]===1){if(start===-1)start=i}else if(code===34&&start!==-1){inQuotes=false;end=i}else if(code===92){isEscaping=true}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(code===34&&header.charCodeAt(i-1)===61){inQuotes=true}else if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(start!==-1&&(code===32||code===9)){if(end===-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;let value=header.slice(start,end);if(mustUnescape){value=value.replace(/\\/g,"");mustUnescape=false}push(params,paramName,value);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=undefined}paramName=undefined;start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}}if(start===-1||inQuotes||code===32||code===9){throw new SyntaxError("Unexpected end of input")}if(end===-1)end=i;const token=header.slice(start,end);if(extensionName===undefined){push(offers,token,params)}else{if(paramName===undefined){push(params,token,true)}else if(mustUnescape){push(params,paramName,token.replace(/\\/g,""))}else{push(params,paramName,token)}push(offers,extensionName,params)}return offers}function format(extensions){return Object.keys(extensions).map((extension)=>{let configurations=extensions[extension];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map((params)=>{return[extension].concat(Object.keys(params).map((k)=>{let values=params[k];if(!Array.isArray(values))values=[values];return values.map((v)=>v===true?k:`${k}=${v}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module.exports={format,parse}});var require_websocket=__commonJS(function(exports,module){var EventEmitter=__require("events");var https=__require("https");var http=__require("http");var net=__require("net");var querystring=__require("querystring");var tls=__require("tls");var{randomBytes,createHash}=__require("crypto");var{Duplex,Readable}=__require("stream");var{URL:URL2}=__require("url");var PerMessageDeflate=require_permessage_deflate();var Receiver=require_receiver();var Sender=require_sender();var{isBlob}=require_validation();var{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants();var{EventTarget:{addEventListener,removeEventListener}}=require_event_target();var{format,parse}=require_extension();var{toBuffer}=require_buffer_util();var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class WebSocket extends EventEmitter{constructor(address,protocols,options){super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._errorEmitted=false;this._extensions={};this._paused=false;this._protocol="";this._readyState=WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===undefined){if(!options||options.protocols===undefined){protocols=[]}else if(Array.isArray(options.protocols)){protocols=options.protocols}else{protocols=[options.protocols]}}else if(!Array.isArray(protocols)){if(typeof protocols==="object"&&protocols!==null){options=protocols;if(options.protocols===undefined){protocols=[]}else if(Array.isArray(options.protocols)){protocols=options.protocols}else{protocols=[options.protocols]}}else{protocols=[protocols]}}options=initAsClient(this,address,protocols,options)}else{this._isServer=true}if(options.autoPong){this._autoPong=true;this._autoPongComplete=()=>autoPongComplete(this);this._pendingAutoPongs=0;this._maxPendingAutoPongs=options.maxPendingAutoPongs|0}this._closeTimeout=options.closeTimeout}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){const receiver=new Receiver({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});const sender=new Sender(socket,this._extensions,options.generateMask);this._receiver=receiver;this._sender=sender;this._socket=socket;receiver[kWebSocket]=this;sender[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);sender.onerror=senderOnError;if(socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate.extensionName]){this._extensions[PerMessageDeflate.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this.readyState===WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._sender.close(code,data,!this._isServer,(err)=>{if(err)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});this._readyState=WebSocket.CLOSING;setCloseTimer(this)}pause(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=undefined}else if(typeof mask==="function"){cb=mask;mask=undefined}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===undefined)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=undefined}else if(typeof mask==="function"){cb=mask;mask=undefined}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===undefined)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this._isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this._socket){this._readyState=WebSocket.CLOSING;this._socket.destroy()}}}Object.defineProperty(WebSocket,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket.prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((property)=>{Object.defineProperty(WebSocket.prototype,property,{enumerable:true})});["open","error","close","message"].forEach((method)=>{Object.defineProperty(WebSocket.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket.prototype.addEventListener=addEventListener;WebSocket.prototype.removeEventListener=removeEventListener;module.exports=WebSocket;function initAsClient(websocket,address,protocols,options){const opts={allowSynchronousEvents:true,autoPong:true,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,maxPendingAutoPongs:60,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,socketPath:undefined,hostname:undefined,protocol:undefined,protocols:undefined,timeout:undefined,method:"GET",host:undefined,path:undefined,port:undefined};if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} `+`(supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address instanceof URL2){parsedUrl=address}else{try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}}if(parsedUrl.protocol==="http:"||parsedUrl.protocol==="https:"){parsedUrl=new URL2(parsedUrl);parsedUrl.protocol=parsedUrl.protocol==="http:"?"ws:":"wss:"}websocket._url=parsedUrl.href;const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", `+'"http:", "https:", or "ws+unix:"'}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="The URL contains a fragment identifier"}if(invalidUrlMessage){const err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err}else{emitErrorAndClose(websocket,err);return}}const defaultPort=isSecure?443:80;const key=randomBytes(16).toString("base64");const request3=isSecure?https.request:http.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect);opts.defaultPort=opts.defaultPort||defaultPort;opts.port=parsedUrl.port||defaultPort;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate({...opts.perMessageDeflate,isServer:false,maxPayload:opts.maxPayload});opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){const username=querystring.unescape(parsedUrl.username);const password=querystring.unescape(parsedUrl.password);opts.auth=`${username}:${password}`}if(isIpcUrl){const i=opts.path.indexOf(":");if(i===-1){opts.socketPath=opts.path;opts.path=""}else{opts.socketPath=opts.path.slice(0,i);opts.path=opts.path.slice(i+1)}}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){for(const[key,value]of Object.entries(headers)){options.headers[key.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=undefined}}if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request3(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request3(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",(err)=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err)});req.on("response",(res)=>{const location2=res.headers.location;const statusCode=res.statusCode;if(location2&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location2,address)}catch(e){const err=new SyntaxError(`Invalid URL: ${location2}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket.CONNECTING)return;req=websocket._req=null;const upgrade=res.headers.upgrade;if(upgrade===undefined||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==undefined){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==undefined){if(!perMessageDeflate){const message="Server sent a Sec-WebSocket-Extensions header but no extension "+"was requested";abortHandshake(websocket,socket,message);return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}const extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate.extensionName){const message="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName])}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}websocket._extensions[PerMessageDeflate.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});if(opts.finishRequest){opts.finishRequest(req,websocket)}else{req.end()}return opts}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket.CLOSING;websocket._errorEmitted=true;websocket.emit("error",err);websocket.emitClose()}function netConnect(options){options.path=options.socketPath;return net.connect(options)}function tlsConnect(options){options.path=undefined;if(!options.servername&&options.servername!==""){options.servername=net.isIP(options.host)?"":options.host}return tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket.CLOSING;const err=new Error(message);Error.captureStackTrace(err,abortHandshake);if(stream.setHeader){stream[kAborted]=true;stream.abort();if(stream.socket&&!stream.socket.destroyed){stream.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err)}else{stream.destroy(err);stream.once("error",websocket.emit.bind(websocket,"error"));stream.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=isBlob(data)?data.size:toBuffer(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err=new Error(`WebSocket is not open: readyState ${websocket.readyState} `+`(${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeCode=code;if(reason.length===0){websocket._closeMessage=EMPTY_BUFFER}else{websocket._closeMessage=Buffer.allocUnsafeSlow(reason.length);websocket._closeMessage.set(reason)}if(websocket._socket[kWebSocket]===undefined)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==undefined){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);websocket.close(err[kStatusCode])}if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];if(websocket._autoPong&&websocket.readyState===WebSocket.OPEN){if(websocket._maxPendingAutoPongs>0&&websocket._pendingAutoPongs>=websocket._maxPendingAutoPongs){websocket.terminate()}else{websocket._pendingAutoPongs++;websocket.pong(data,!this._isServer,websocket._autoPongComplete)}}websocket.emit("ping",data)}function autoPongComplete(websocket){websocket._pendingAutoPongs--}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function senderOnError(err){const websocket=this[kWebSocket];if(websocket.readyState===WebSocket.CLOSED)return;if(websocket.readyState===WebSocket.OPEN){websocket._readyState=WebSocket.CLOSING;setCloseTimer(websocket)}this._socket.end();if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket.CLOSING;if(!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){const chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=undefined;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket.CLOSING;this.destroy()}}});var require_stream=__commonJS(function(exports,module){var WebSocket=require_websocket();var{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err)}}function createWebSocketStream(ws,options){let terminateOnDestroy=true;const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws.on("message",function message(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws.pause()});ws.once("error",function error(err){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err)});ws.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err);process.nextTick(emitClose,duplex);return}let called=false;ws.once("error",function error(err){called=true;callback(err)});ws.once("close",function close(){if(!called)callback(err);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws.terminate()};duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._final(callback)});return}if(ws._socket===null)return;if(ws._socket._writableState.finished){callback();if(duplex._readableState.endEmitted)duplex.destroy()}else{ws._socket.once("finish",function finish(){callback()});ws.close()}};duplex._read=function(){if(ws.isPaused)ws.resume()};duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module.exports=createWebSocketStream});var require_subprotocol=__commonJS(function(exports,module){var{tokenChars}=require_validation();function parse(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i<header.length;i++){const code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const protocol=header.slice(start,end);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}if(start===-1||end!==-1){throw new SyntaxError("Unexpected end of input")}const protocol=header.slice(start,i);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);return protocols}module.exports={parse}});var require_websocket_server=__commonJS(function(exports,module){var EventEmitter=__require("events");var http=__require("http");var{Duplex}=__require("stream");var{createHash}=__require("crypto");var extension=require_extension();var PerMessageDeflate=require_permessage_deflate();var subprotocol=require_subprotocol();var WebSocket=require_websocket();var{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants();var keyRegex=/^[+/0-9A-Za-z]{22}==$/;var RUNNING=0;var CLOSING=1;var CLOSED=2;class WebSocketServer extends EventEmitter{constructor(options,callback){super();options={allowSynchronousEvents:true,autoPong:true,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,maxPendingAutoPongs:60,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket,...options};if(options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer){throw new TypeError('One and only one of the "port", "server", or "noServer" options '+"must be specified")}if(options.port!=null){this._server=http.createServer((req,res)=>{const body=http.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server=this._server;this._removeListeners();this._removeListeners=this._server=null;server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);const key=req.headers["sec-websocket-key"];const upgrade=req.headers.upgrade;const version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message);return}if(upgrade===undefined||upgrade.toLowerCase()!=="websocket"){const message="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(key===undefined||!keyRegex.test(key)){const message="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(version!==13&&version!==8){const message="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message,{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==undefined){try{protocols=subprotocol.parse(secWebSocketProtocol)}catch(err){const message="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==undefined){const perMessageDeflate=new PerMessageDeflate({...this.options.perMessageDeflate,isServer:true,maxPayload:this.options.maxPayload});try{const offers=extension.parse(secWebSocketExtensions);if(offers[PerMessageDeflate.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);extensions[PerMessageDeflate.extensionName]=perMessageDeflate}}catch(err){const message="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}if(this.options.verifyClient){const info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified){return abortHandshake(socket,code||401,message,headers)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same "+"socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash("sha1").update(key+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws=new this.options.WebSocket(null,undefined,this.options);if(protocols.size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws._protocol=protocol}}if(extensions[PerMessageDeflate.extensionName]){const params=extensions[PerMessageDeflate.extensionName].params;const value=extension.format({[PerMessageDeflate.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws._extensions=extensions}this.emit("headers",headers,req);socket.write(headers.concat(`\r
1
+ var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};import path from"node:path";async function openNtdll(){const{dlopen,ptr}=await import("bun:ffi");const systemRoot=process.env["SystemRoot"]||process.env["windir"]||"C:\\Windows";const{symbols}=dlopen(path.win32.join(systemRoot,"System32","ntdll.dll"),{NtCreateFile:{args:["buffer","u32","buffer","buffer","ptr","u32","u32","u32","u32","ptr","u32"],returns:"u32"},NtClose:{args:["u64"],returns:"u32"},RtlNtStatusToDosError:{args:["u32"],returns:"u32"}});return{symbols,ptr}}function loadNtdll(){ntdll??=openNtdll().catch((error)=>{ntdll=undefined;throw error});return ntdll}function nativeError(symbols,operation,lockPath,status){const error=symbols.RtlNtStatusToDosError(status);return Object.assign(new Error(`instance lock ${operation} failed for ${lockPath} (Windows error ${error}, NTSTATUS 0x${status.toString(16)})`),{code:"ERR_INSTANCE_LOCK"})}async function tryAcquireWindows(lockPath){const{symbols,ptr}=await loadNtdll();const filename=Buffer.from(`${path.toNamespacedPath(path.resolve(lockPath)).replace(/^\\\\\?\\/,"\\??\\")}\x00`,"utf16le");const name=Buffer.alloc(16);name.writeUInt16LE(filename.length-2,0);name.writeUInt16LE(filename.length,2);name.writeBigUInt64LE(BigInt(ptr(filename)),8);const attributes=Buffer.alloc(48);attributes.writeUInt32LE(48,0);attributes.writeBigUInt64LE(BigInt(ptr(name)),16);attributes.writeUInt32LE(64,24);const handleOut=Buffer.alloc(8);const ioStatus=Buffer.alloc(16);const status=symbols.NtCreateFile(handleOut,3222274048,attributes,ioStatus,null,128,0,3,96,null,0);if(status===3221225539)return null;if(status>=2147483648)throw nativeError(symbols,"NtCreateFile",lockPath,status);const handle=handleOut.readBigUInt64LE();return{release(){const closeStatus=symbols.NtClose(handle);if(closeStatus>=2147483648)throw nativeError(symbols,"NtClose",lockPath,closeStatus)}}}var ntdll;var init_lock_backend_win32_xbcm60vz=()=>{};import{createRequire}from"node:module";import path3 from"node:path";import{mkdir as mkdir4}from"node:fs/promises";import path2 from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{createReadStream,promises}from"node:fs";import*as fs$16 from"node:fs/promises";import{spawn}from"node:child_process";import{tmpdir}from"node:os";import{readFileSync}from"node:fs";import{readFile}from"node:fs/promises";import{readFile as readFile2}from"node:fs/promises";import{randomUUID}from"node:crypto";import{types}from"node:util";import{isDeepStrictEqual}from"node:util";import{mkdir as mkdir3,writeFile as writeFile2}from"node:fs/promises";import path22 from"node:path";import{spawn as spawn3}from"node:child_process";import{finished}from"node:stream/promises";import{mkdirSync,readFileSync as readFileSync2,rmSync,writeFileSync}from"node:fs";import path5 from"node:path";import{setTimeout as sleep2}from"node:timers/promises";import{unlink as unlink2}from"node:fs/promises";import{setTimeout as sleep}from"node:timers/promises";import{spawn as spawn2}from"node:child_process";import{constants}from"node:fs";import{open as open2}from"node:fs/promises";import{execFile}from"node:child_process";import{readFile as readFile3}from"node:fs/promises";import{promisify}from"node:util";import{execFile as execFile2}from"node:child_process";import{readFile as readFile4}from"node:fs/promises";import path4 from"node:path";import{promisify as promisify2}from"node:util";import{spawn as spawn4}from"node:child_process";import{createHash,randomUUID as randomUUID2}from"node:crypto";import{mkdir as mkdir5,open as open3,readFile as readFile7,readdir,rename,unlink as unlink3}from"node:fs/promises";import os from"node:os";import path8 from"node:path";import{watch}from"node:fs";import{readFile as readFile5,stat}from"node:fs/promises";import path6 from"node:path";import{execFile as execFile3}from"node:child_process";import{chmod,mkdtemp,readFile as readFile6,rm,stat as stat2}from"node:fs/promises";import{tmpdir as tmpdir2}from"node:os";import path7 from"node:path";import{promisify as promisify3}from"node:util";import{readFile as readFile8}from"node:fs/promises";import{connect as connectTcp}from"node:net";import path10 from"node:path";import{existsSync}from"node:fs";import{homedir}from"node:os";import path9 from"node:path";import{randomInt}from"node:crypto";import{mkdir as mkdir6,open as open4,readFile as readFile9,unlink as unlink4}from"node:fs/promises";import{globSync}from"node:fs";import os2 from"node:os";import path11 from"node:path";import{spawn as spawn5}from"node:child_process";import{mkdtempSync,writeFileSync as writeFileSync2,rmSync as rmSync2}from"node:fs";import{tmpdir as tmpdir3}from"node:os";import path12 from"node:path";import{randomUUID as randomUUID3}from"node:crypto";import path16 from"node:path";import{mkdir as mkdir8,open as open5,readFile as readFile10,readlink,realpath,rename as rename2,lstat,chmod as chmod2}from"node:fs/promises";import{homedir as homedir2}from"node:os";import{TextDecoder as TextDecoder2}from"node:util";import{mkdirSync as mkdirSync2}from"node:fs";import path14 from"node:path";import{tmpdir as tmpdir4}from"node:os";import{existsSync as existsSync2,readFileSync as readFileSync3}from"node:fs";import path13 from"node:path";import{execFile as execFile4}from"node:child_process";import{existsSync as existsSync3}from"node:fs";import{mkdir as mkdir7,rmdir,unlink as unlink5}from"node:fs/promises";import path15 from"node:path";import{mkdir as mkdir9,writeFile as writeFile3}from"node:fs/promises";import path17 from"node:path";import{connect as connect2}from"node:net";import{existsSync as existsSync6,readdirSync}from"node:fs";import path20 from"node:path";import{randomBytes}from"node:crypto";import{existsSync as existsSync5,readFileSync as readFileSync5}from"node:fs";import{homedir as homedir4}from"node:os";import path19 from"node:path";import{spawn as spawn7}from"node:child_process";import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync4,readFileSync as readFileSync4,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{homedir as homedir3}from"node:os";import path18 from"node:path";import{spawn as spawn6}from"node:child_process";import{spawn as spawnChild}from"node:child_process";import{randomBytes as randomBytes2}from"node:crypto";import{existsSync as existsSync8,readFileSync as readFileSync6}from"node:fs";import{homedir as homedir6}from"node:os";import path222 from"node:path";import{spawn as spawn8}from"node:child_process";import{existsSync as existsSync7}from"node:fs";import{homedir as homedir5}from"node:os";import path21 from"node:path";import{randomInt as randomInt2}from"node:crypto";import{existsSync as existsSync9,mkdirSync as mkdirSync3,readFileSync as readFileSync7,rmSync as rmSync4,writeFileSync as writeFileSync4}from"node:fs";import{spawn as spawn9}from"node:child_process";import path23 from"node:path";import{execFile as execFile5}from"node:child_process";import{statSync}from"node:fs";import{homedir as homedir7}from"node:os";import path24 from"node:path";import{homedir as homedir8}from"node:os";import{existsSync as existsSync10,readFileSync as readFileSync8}from"node:fs";var __create=Object.create;var __getProtoOf=Object.getPrototypeOf;var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node;var __toESMCache_esm;var __toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap;var cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};const to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:true}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:true})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true,configurable:true,set:__exportSetter.bind(all,name)})};var __require=createRequire(import.meta.url);var require_constants=__commonJS(function(exports,module){var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"];var hasBlob=typeof Blob!=="undefined";if(hasBlob)BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var require_buffer_util=__commonJS(function(exports,module){var{websocketMask,websocketUnmask}=__require("http");var{EMPTY_BUFFER}=require_constants();var FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i<list.length;i++){const buf=list[i];target.set(buf,offset);offset+=buf.length}if(offset<totalLength){return new FastBuffer(target.buffer,target.byteOffset,offset)}return target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++){output[offset+i]=source[i]^mask[i&3]}}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++){buffer[i]^=mask[i&3]}}function toArrayBuffer(buf){if(buf.length===buf.buffer.byteLength){return buf.buffer}return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){toBuffer.readOnly=true;if(Buffer.isBuffer(data))return data;let buf;if(data instanceof ArrayBuffer){buf=new FastBuffer(data)}else if(ArrayBuffer.isView(data)){buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength)}else{buf=Buffer.from(data);toBuffer.readOnly=false}return buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(websocketMask){module.exports.mask=function(source,mask,output,offset,length){if(length<24)_mask(source,mask,output,offset,length);else websocketMask(source,mask,output,offset,length)};module.exports.unmask=function(buffer,mask){if(buffer.length<24)_unmask(buffer,mask);else websocketUnmask(buffer,mask)}}else if(!process.env.WS_NO_BUFFER_UTIL){try{const bufferUtil=(()=>{throw new Error("Cannot require module "+"bufferutil")})();module.exports.mask=function(source,mask2,output,offset,length){if(length<48)_mask(source,mask2,output,offset,length);else bufferUtil.mask(source,mask2,output,offset,length)};module.exports.unmask=function(buffer,mask){if(buffer.length<32)_unmask(buffer,mask);else bufferUtil.unmask(buffer,mask)}}catch(e){}}});var require_limiter=__commonJS(function(exports,module){var kDone=Symbol("kDone");var kRun=Symbol("kRun");class Limiter{constructor(concurrency){this[kDone]=()=>{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}}module.exports=Limiter});var require_permessage_deflate=__commonJS(function(exports,module){var zlib=__require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants();var FastBuffer=Buffer[Symbol.species];var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("error");var zlibLimiter;class PerMessageDeflate{constructor(options){this._options=options||{};this._threshold=this._options.threshold!==undefined?this._options.threshold:1024;this._maxPayload=this._options.maxPayload|0;this._isServer=!!this._options.isServer;this._deflate=null;this._inflate=null;this.params=null;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==undefined?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.find((params)=>{if(opts.serverNoContextTakeover===false&&params.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&(typeof params.client_max_window_bits==="number"?opts.clientMaxWindowBits>params.client_max_window_bits:!params.client_max_window_bits)){return false}return true});if(!accepted){throw new Error("None of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&&params.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&&params.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach((params)=>{Object.keys(params).forEach((key)=>{let value=params[key];if(value.length>1){throw new Error(`Parameter "${key}" must have only a single value`)}value=value[0];if(key==="client_max_window_bits"){if(value!==true){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else if(key==="server_max_window_bits"){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else{throw new Error(`Unknown parameter "${key}"`)}params[key]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add((done)=>{this._decompress(data,fin,(err,result)=>{done();callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add((done)=>{this._compress(data,fin,(err,result)=>{done();callback(err,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err=this._inflate[kError];if(err){this._inflate.close();this._inflate=null;callback(err);return}const data=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin){data=new FastBuffer(data.buffer,data.byteOffset,data.length-4)}this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data)})}}module.exports=PerMessageDeflate;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err){this[kPerMessageDeflate]._inflate=null;if(this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007;this[kCallback](err)}});var require_validation=__commonJS(function(exports,module){var{isUtf8}=__require("buffer");var{hasBlob}=require_constants();var tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1000&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3000&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i<len){if((buf[i]&128)===0){i++}else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192){return false}i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}function isBlob(value){return hasBlob&&typeof value==="object"&&typeof value.arrayBuffer==="function"&&typeof value.type==="string"&&typeof value.stream==="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8){module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=(()=>{throw new Error("Cannot require module "+"utf-8-validate")})();module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e){}}});var require_receiver=__commonJS(function(exports,module){var{Writable}=__require("stream");var PerMessageDeflate=require_permessage_deflate();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants();var{concat,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var FastBuffer=Buffer[Symbol.species];var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;var INFLATING=5;var DEFER_EVENT=6;class Receiver extends Writable{constructor(options={}){super();this._allowSynchronousEvents=options.allowSynchronousEvents!==undefined?options.allowSynchronousEvents:true;this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxBufferedChunks=options.maxBufferedChunks|0;this._maxFragments=options.maxFragments|0;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.skipUTF8Validation;this[kWebSocket]=undefined;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=undefined;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._numFragments=0;this._fragments=[];this._errored=false;this._loop=false;this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){const buf=this._buffers[0];this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n);return new FastBuffer(buf.buffer,buf.byteOffset,n)}const dst=Buffer.allocUnsafe(n);do{const buf=this._buffers[0];const offset=dst.length-n;if(n>=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)}n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=true;do{switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=false;return}}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){const error=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate.extensionName]){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){const error=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const error=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){const error=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){const error=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num=buf.readUInt32BE(0);if(num>Math.pow(2,53-32)-1){const error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4);this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;return}data=this.consume(this._payloadLength);if(this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0){unmask(data,this._mask)}}this._mask=undefined;if(this._opcode>7){this.controlMessage(data,cb);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){const error=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){this._messageLength=this._totalPayloadLength;this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];perMessageDeflate.decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb);if(this._state===GET_INFO)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._numFragments=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat(fragments,messageLength))}else if(this._binaryType==="blob"){data=new Blob(fragments)}else{data=fragments}if(this._allowSynchronousEvents){this.emit("message",data,true);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",data,true);this._state=GET_INFO;this.startLoop(cb)})}}else{const buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",buf,false);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",buf,false);this._state=GET_INFO;this.startLoop(cb)})}}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0){this._loop=false;this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){const error=this.createError(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}const buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=false;this.emit("conclude",code,buf);this.end()}this._state=GET_INFO;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO;this.startLoop(cb)})}}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=false;this._errored=true;const err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);Error.captureStackTrace(err,this.createError);err.code=errorCode;err[kStatusCode]=statusCode;return err}}module.exports=Receiver});var require_sender=__commonJS(function(exports,module){var{Duplex}=__require("stream");var{randomFillSync}=__require("crypto");var{types:{isUint8Array}}=__require("util");var PerMessageDeflate=require_permessage_deflate();var{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants();var{isBlob,isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var RANDOM_POOL_SIZE=8*1024;var randomPool;var randomPoolPointer=RANDOM_POOL_SIZE;var DEFAULT=0;var DEFLATING=1;var GET_BLOB_DATA=2;class Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._queue=[];this._state=DEFAULT;this.onerror=NOOP;this[kWebSocket]=undefined}static frame(data,options){let mask;let merge=false;let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{if(randomPoolPointer===RANDOM_POOL_SIZE){if(randomPool===undefined){randomPool=Buffer.alloc(RANDOM_POOL_SIZE)}randomFillSync(randomPool,0,RANDOM_POOL_SIZE);randomPoolPointer=0}mask[0]=randomPool[randomPoolPointer++];mask[1]=randomPool[randomPoolPointer++];mask[2]=randomPool[randomPoolPointer++];mask[3]=randomPool[randomPoolPointer++]}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==undefined){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge?dataLength+offset:offset);target[0]=options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask){return dataLength?[target,data]:[target]}target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(!dataLength)return[target];if(skipMasking)return[target,data];if(merge){applyMask(data,mask,target,offset,dataLength);return[target]}applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===undefined){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===undefined||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else if(isUint8Array(data)){buf.set(data,2)}else{throw new TypeError("Second argument must be a string or a Uint8Array")}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._state!==DEFAULT){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(Sender.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(Sender.frame(data,options),cb)}}send(data,options,cb){const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,this._compress,opts,cb])}else{this.getBlobData(data,this._compress,opts,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength];this._state=GET_BLOB_DATA;blob.arrayBuffer().then((arrayBuffer)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];const data=toBuffer(arrayBuffer);if(!compress){this._state=DEFAULT;this.sendFrame(Sender.frame(data,options),cb);this.dequeue()}else{this.dispatch(data,compress,options,cb)}}).catch((err)=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(Sender.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate.extensionName];this._bufferedBytes+=options[kByteLength];this._state=DEFLATING;perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength];this._state=DEFAULT;options.readOnly=false;this.sendFrame(Sender.frame(buf,options),cb);this.dequeue()})}dequeue(){while(this._state===DEFAULT&&this._queue.length){const params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength];Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength];this._queue.push(params)}sendFrame(list,cb){if(list.length===2){this._socket.cork();this._socket.write(list[0]);this._socket.write(list[1],cb);this._socket.uncork()}else{this._socket.write(list[0],cb)}}}module.exports=Sender;function callCallbacks(sender,err,cb){if(typeof cb==="function")cb(err);for(let i=0;i<sender._queue.length;i++){const params=sender._queue[i];const callback=params[params.length-1];if(typeof callback==="function")callback(err)}}function onError(sender,err,cb){callCallbacks(sender,err,cb);sender.onerror(err)}});var require_event_target=__commonJS(function(exports,module){var{kForOnEventAttribute,kListener}=require_constants();var kCode=Symbol("kCode");var kData=Symbol("kData");var kError=Symbol("kError");var kMessage=Symbol("kMessage");var kReason=Symbol("kReason");var kTarget=Symbol("kTarget");var kType=Symbol("kType");var kWasClean=Symbol("kWasClean");class Event{constructor(type){this[kTarget]=null;this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}}Object.defineProperty(Event.prototype,"target",{enumerable:true});Object.defineProperty(Event.prototype,"type",{enumerable:true});class CloseEvent extends Event{constructor(type,options={}){super(type);this[kCode]=options.code===undefined?0:options.code;this[kReason]=options.reason===undefined?"":options.reason;this[kWasClean]=options.wasClean===undefined?false:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}}Object.defineProperty(CloseEvent.prototype,"code",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:true});class ErrorEvent extends Event{constructor(type,options={}){super(type);this[kError]=options.error===undefined?null:options.error;this[kMessage]=options.message===undefined?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}}Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:true});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:true});class MessageEvent extends Event{constructor(type,options={}){super(type);this[kData]=options.data===undefined?null:options.data}get data(){return this[kData]}}Object.defineProperty(MessageEvent.prototype,"data",{enumerable:true});var EventTarget={addEventListener(type,handler,options={}){for(const listener of this.listeners(type)){if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute]){return}}let wrapper;if(type==="message"){wrapper=function onMessage(data,isBinary){const event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="close"){wrapper=function onClose(code,message){const event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="error"){wrapper=function onError(error){const event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="open"){wrapper=function onOpen(){const event=new Event("open");event[kTarget]=this;callListener(handler,this,event)}}else{return}wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute];wrapper[kListener]=handler;if(options.once){this.once(type,wrapper)}else{this.on(type,wrapper)}},removeEventListener(type,handler){for(const listener of this.listeners(type)){if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){if(typeof listener==="object"&&listener.handleEvent){listener.handleEvent.call(listener,event)}else{listener.call(thisArg,event)}}});var require_extension=__commonJS(function(exports,module){var{tokenChars}=require_validation();function push(dest,name,elem){if(dest[name]===undefined)dest[name]=[elem];else dest[name].push(elem)}function parse(header){const offers=Object.create(null);let params=Object.create(null);let mustUnescape=false;let isEscaping=false;let inQuotes=false;let extensionName;let paramName;let start=-1;let code=-1;let end=-1;let i=0;for(;i<header.length;i++){code=header.charCodeAt(i);if(extensionName===undefined){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const name=header.slice(start,end);if(code===44){push(offers,name,params);params=Object.create(null)}else{extensionName=name}start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(paramName===undefined){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(code===32||code===9){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;push(params,header.slice(start,end),true);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=undefined}start=end=-1}else if(code===61&&start!==-1&&end===-1){paramName=header.slice(start,i);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else{if(isEscaping){if(tokenChars[code]!==1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1)start=i;else if(!mustUnescape)mustUnescape=true;isEscaping=false}else if(inQuotes){if(tokenChars[code]===1){if(start===-1)start=i}else if(code===34&&start!==-1){inQuotes=false;end=i}else if(code===92){isEscaping=true}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(code===34&&header.charCodeAt(i-1)===61){inQuotes=true}else if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(start!==-1&&(code===32||code===9)){if(end===-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;let value=header.slice(start,end);if(mustUnescape){value=value.replace(/\\/g,"");mustUnescape=false}push(params,paramName,value);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=undefined}paramName=undefined;start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}}if(start===-1||inQuotes||code===32||code===9){throw new SyntaxError("Unexpected end of input")}if(end===-1)end=i;const token=header.slice(start,end);if(extensionName===undefined){push(offers,token,params)}else{if(paramName===undefined){push(params,token,true)}else if(mustUnescape){push(params,paramName,token.replace(/\\/g,""))}else{push(params,paramName,token)}push(offers,extensionName,params)}return offers}function format(extensions){return Object.keys(extensions).map((extension)=>{let configurations=extensions[extension];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map((params)=>{return[extension].concat(Object.keys(params).map((k)=>{let values=params[k];if(!Array.isArray(values))values=[values];return values.map((v)=>v===true?k:`${k}=${v}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module.exports={format,parse}});var require_websocket=__commonJS(function(exports,module){var EventEmitter=__require("events");var https=__require("https");var http=__require("http");var net=__require("net");var querystring=__require("querystring");var tls=__require("tls");var{randomBytes,createHash}=__require("crypto");var{Duplex,Readable}=__require("stream");var{URL:URL2}=__require("url");var PerMessageDeflate=require_permessage_deflate();var Receiver=require_receiver();var Sender=require_sender();var{isBlob}=require_validation();var{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants();var{EventTarget:{addEventListener,removeEventListener}}=require_event_target();var{format,parse}=require_extension();var{toBuffer}=require_buffer_util();var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class WebSocket extends EventEmitter{constructor(address,protocols,options){super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._errorEmitted=false;this._extensions={};this._paused=false;this._protocol="";this._readyState=WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===undefined){if(!options||options.protocols===undefined){protocols=[]}else if(Array.isArray(options.protocols)){protocols=options.protocols}else{protocols=[options.protocols]}}else if(!Array.isArray(protocols)){if(typeof protocols==="object"&&protocols!==null){options=protocols;if(options.protocols===undefined){protocols=[]}else if(Array.isArray(options.protocols)){protocols=options.protocols}else{protocols=[options.protocols]}}else{protocols=[protocols]}}options=initAsClient(this,address,protocols,options)}else{this._isServer=true}if(options.autoPong){this._autoPong=true;this._autoPongComplete=()=>autoPongComplete(this);this._pendingAutoPongs=0;this._maxPendingAutoPongs=options.maxPendingAutoPongs|0}this._closeTimeout=options.closeTimeout}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){const receiver=new Receiver({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});const sender=new Sender(socket,this._extensions,options.generateMask);this._receiver=receiver;this._sender=sender;this._socket=socket;receiver[kWebSocket]=this;sender[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);sender.onerror=senderOnError;if(socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate.extensionName]){this._extensions[PerMessageDeflate.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this.readyState===WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._sender.close(code,data,!this._isServer,(err)=>{if(err)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});this._readyState=WebSocket.CLOSING;setCloseTimer(this)}pause(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=undefined}else if(typeof mask==="function"){cb=mask;mask=undefined}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===undefined)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=undefined}else if(typeof mask==="function"){cb=mask;mask=undefined}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===undefined)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===WebSocket.CONNECTING||this.readyState===WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==WebSocket.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this._isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===WebSocket.CLOSED)return;if(this.readyState===WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this._socket){this._readyState=WebSocket.CLOSING;this._socket.destroy()}}}Object.defineProperty(WebSocket,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket.prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((property)=>{Object.defineProperty(WebSocket.prototype,property,{enumerable:true})});["open","error","close","message"].forEach((method)=>{Object.defineProperty(WebSocket.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket.prototype.addEventListener=addEventListener;WebSocket.prototype.removeEventListener=removeEventListener;module.exports=WebSocket;function initAsClient(websocket,address,protocols,options){const opts={allowSynchronousEvents:true,autoPong:true,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,maxPendingAutoPongs:60,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,socketPath:undefined,hostname:undefined,protocol:undefined,protocols:undefined,timeout:undefined,method:"GET",host:undefined,path:undefined,port:undefined};if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} `+`(supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address instanceof URL2){parsedUrl=address}else{try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}}if(parsedUrl.protocol==="http:"||parsedUrl.protocol==="https:"){parsedUrl=new URL2(parsedUrl);parsedUrl.protocol=parsedUrl.protocol==="http:"?"ws:":"wss:"}websocket._url=parsedUrl.href;const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", `+'"http:", "https:", or "ws+unix:"'}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="The URL contains a fragment identifier"}if(invalidUrlMessage){const err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err}else{emitErrorAndClose(websocket,err);return}}const defaultPort=isSecure?443:80;const key=randomBytes(16).toString("base64");const request3=isSecure?https.request:http.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect);opts.defaultPort=opts.defaultPort||defaultPort;opts.port=parsedUrl.port||defaultPort;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate({...opts.perMessageDeflate,isServer:false,maxPayload:opts.maxPayload});opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){const username=querystring.unescape(parsedUrl.username);const password=querystring.unescape(parsedUrl.password);opts.auth=`${username}:${password}`}if(isIpcUrl){const i=opts.path.indexOf(":");if(i===-1){opts.socketPath=opts.path;opts.path=""}else{opts.socketPath=opts.path.slice(0,i);opts.path=opts.path.slice(i+1)}}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){for(const[key,value]of Object.entries(headers)){options.headers[key.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=undefined}}if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request3(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request3(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",(err)=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err)});req.on("response",(res)=>{const location2=res.headers.location;const statusCode=res.statusCode;if(location2&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location2,address)}catch(e){const err=new SyntaxError(`Invalid URL: ${location2}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket.CONNECTING)return;req=websocket._req=null;const upgrade=res.headers.upgrade;if(upgrade===undefined||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==undefined){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==undefined){if(!perMessageDeflate){const message="Server sent a Sec-WebSocket-Extensions header but no extension "+"was requested";abortHandshake(websocket,socket,message);return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}const extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate.extensionName){const message="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName])}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}websocket._extensions[PerMessageDeflate.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});if(opts.finishRequest){opts.finishRequest(req,websocket)}else{req.end()}return opts}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket.CLOSING;websocket._errorEmitted=true;websocket.emit("error",err);websocket.emitClose()}function netConnect(options){options.path=options.socketPath;return net.connect(options)}function tlsConnect(options){options.path=undefined;if(!options.servername&&options.servername!==""){options.servername=net.isIP(options.host)?"":options.host}return tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket.CLOSING;const err=new Error(message);Error.captureStackTrace(err,abortHandshake);if(stream.setHeader){stream[kAborted]=true;stream.abort();if(stream.socket&&!stream.socket.destroyed){stream.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err)}else{stream.destroy(err);stream.once("error",websocket.emit.bind(websocket,"error"));stream.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=isBlob(data)?data.size:toBuffer(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err=new Error(`WebSocket is not open: readyState ${websocket.readyState} `+`(${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeCode=code;if(reason.length===0){websocket._closeMessage=EMPTY_BUFFER}else{websocket._closeMessage=Buffer.allocUnsafeSlow(reason.length);websocket._closeMessage.set(reason)}if(websocket._socket[kWebSocket]===undefined)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==undefined){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);websocket.close(err[kStatusCode])}if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];if(websocket._autoPong&&websocket.readyState===WebSocket.OPEN){if(websocket._maxPendingAutoPongs>0&&websocket._pendingAutoPongs>=websocket._maxPendingAutoPongs){websocket.terminate()}else{websocket._pendingAutoPongs++;websocket.pong(data,!this._isServer,websocket._autoPongComplete)}}websocket.emit("ping",data)}function autoPongComplete(websocket){websocket._pendingAutoPongs--}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function senderOnError(err){const websocket=this[kWebSocket];if(websocket.readyState===WebSocket.CLOSED)return;if(websocket.readyState===WebSocket.OPEN){websocket._readyState=WebSocket.CLOSING;setCloseTimer(websocket)}this._socket.end();if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket.CLOSING;if(!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){const chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=undefined;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket.CLOSING;this.destroy()}}});var require_stream=__commonJS(function(exports,module){var WebSocket=require_websocket();var{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err)}}function createWebSocketStream(ws,options){let terminateOnDestroy=true;const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws.on("message",function message(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws.pause()});ws.once("error",function error(err){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err)});ws.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err);process.nextTick(emitClose,duplex);return}let called=false;ws.once("error",function error(err){called=true;callback(err)});ws.once("close",function close(){if(!called)callback(err);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws.terminate()};duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._final(callback)});return}if(ws._socket===null)return;if(ws._socket._writableState.finished){callback();if(duplex._readableState.endEmitted)duplex.destroy()}else{ws._socket.once("finish",function finish(){callback()});ws.close()}};duplex._read=function(){if(ws.isPaused)ws.resume()};duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module.exports=createWebSocketStream});var require_subprotocol=__commonJS(function(exports,module){var{tokenChars}=require_validation();function parse(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i<header.length;i++){const code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const protocol=header.slice(start,end);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}if(start===-1||end!==-1){throw new SyntaxError("Unexpected end of input")}const protocol=header.slice(start,i);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);return protocols}module.exports={parse}});var require_websocket_server=__commonJS(function(exports,module){var EventEmitter=__require("events");var http=__require("http");var{Duplex}=__require("stream");var{createHash}=__require("crypto");var extension=require_extension();var PerMessageDeflate=require_permessage_deflate();var subprotocol=require_subprotocol();var WebSocket=require_websocket();var{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants();var keyRegex=/^[+/0-9A-Za-z]{22}==$/;var RUNNING=0;var CLOSING=1;var CLOSED=2;class WebSocketServer extends EventEmitter{constructor(options,callback){super();options={allowSynchronousEvents:true,autoPong:true,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,maxPendingAutoPongs:60,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket,...options};if(options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer){throw new TypeError('One and only one of the "port", "server", or "noServer" options '+"must be specified")}if(options.port!=null){this._server=http.createServer((req,res)=>{const body=http.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server=this._server;this._removeListeners();this._removeListeners=this._server=null;server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);const key=req.headers["sec-websocket-key"];const upgrade=req.headers.upgrade;const version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message);return}if(upgrade===undefined||upgrade.toLowerCase()!=="websocket"){const message="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(key===undefined||!keyRegex.test(key)){const message="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(version!==13&&version!==8){const message="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message,{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==undefined){try{protocols=subprotocol.parse(secWebSocketProtocol)}catch(err){const message="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==undefined){const perMessageDeflate=new PerMessageDeflate({...this.options.perMessageDeflate,isServer:true,maxPayload:this.options.maxPayload});try{const offers=extension.parse(secWebSocketExtensions);if(offers[PerMessageDeflate.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);extensions[PerMessageDeflate.extensionName]=perMessageDeflate}}catch(err){const message="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}if(this.options.verifyClient){const info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified){return abortHandshake(socket,code||401,message,headers)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same "+"socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash("sha1").update(key+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws=new this.options.WebSocket(null,undefined,this.options);if(protocols.size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws._protocol=protocol}}if(extensions[PerMessageDeflate.extensionName]){const params=extensions[PerMessageDeflate.extensionName].params;const value=extension.format({[PerMessageDeflate.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws._extensions=extensions}this.emit("headers",headers,req);socket.write(headers.concat(`\r
2
2
  `).join(`\r
3
3
  `));socket.removeListener("error",socketOnError);ws.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation});if(this.clients){this.clients.add(ws);ws.on("close",()=>{this.clients.delete(ws);if(this._shouldEmitClose&&!this.clients.size){process.nextTick(emitClose,this)}})}cb(ws,req)}}module.exports=WebSocketServer;function addListeners(server,map){for(const event of Object.keys(map))server.on(event,map[event]);return function removeListeners(){for(const event of Object.keys(map)){server.removeListener(event,map[event])}}}function emitClose(server){server._state=CLOSED;server.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message,headers){message=message||http.STATUS_CODES[code];headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message),...headers};socket.once("finish",socket.destroy);socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
4
4
  `+Object.keys(headers).map((h)=>`${h}: ${headers[h]}`).join(`\r
@@ -63,7 +63,7 @@ ${content.join(`
63
63
  `);const fullCode=options?.debug?constantNames.length>0?`// Constants: ${constantNames.join(", ")}
64
64
  ${code}`:code:"";const F=Function;const factoryCode=`return (input) => {
65
65
  ${code}
66
- }`;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 generateSizeGate(doc,schema,size){for(const[max,check]of sizeCaps(schema._zod.def.checks)){doc.write(`if (${size} > ${numericOperand(max,check._zod.def.check)}) return INVALID;`)}}function generateArrayCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);generateSizeGate(doc,schema,`${accessor}.length`);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;`);generateSizeGate(doc,schema,`${accessor}.size`);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;`);generateSizeGate(doc,schema,`${accessor}.size`);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)}var pageBundle=readFileSync(new URL("./page-bundle.js",import.meta.url),"utf8");function queryOpenShadowAll(root,selector){const defined=(value,reading)=>{if(value===undefined)throw new TypeError(`Cannot read properties of undefined (reading '${reading}')`);return value};const groups=[];let parts=[],token="",depth=0,quote="",escaped=false,combinator=" ";const flush=()=>{if(!token.trim())return;parts.push({selector:token.trim(),combinator});token="";combinator=" "};for(const char of selector){if(escaped){token+=char;escaped=false;continue}if(char==="\\"){token+=char;escaped=true;continue}if(quote){token+=char;if(char===quote)quote="";continue}if(char==='"'||char==="'"){quote=char;token+=char;continue}if(char==="["||char==="(")depth++;if(char==="]"||char===")")depth--;if(!depth&&(char===","||char===">"||char==="+"||char==="~"||/\s/.test(char))){flush();if(char===","){groups.push(parts);parts=[];combinator=" "}else if(!/\s/.test(char))combinator=char}else token+=char}flush();groups.push(parts);const simple=groups.every((group)=>group.length===1&&!/^:scope\b/.test(defined(group[0],"selector").selector));let rootSelector=selector;if(!simple&&root instanceof Element){const scopedSelectors=[];for(const group of groups){const first=defined(group[0],"selector").selector;const rest=group.slice(1).map((part)=>`${part.combinator} ${part.selector}`).join(" ");const scoped=/^:scope\b/.test(first);scopedSelectors.push(`${scoped?"":":scope "}${first} ${rest}`);if(!scoped&&group.length>1&&root.matches(first))scopedSelectors.push(`:scope ${rest}`)}rootSelector=scopedSelectors.join(", ")}const rootElements=root.querySelectorAll("*");const rootMatches=rootSelector==="*"?rootElements:root.querySelectorAll(rootSelector);const pending=[];for(let index=rootElements.length-1;index>=0;index--){const element=defined(rootElements[index],"shadowRoot");if(element.shadowRoot)pending.push(element.shadowRoot)}if(root instanceof Element&&root.shadowRoot)pending.push(root.shadowRoot);if(pending.length===0)return Array.from(rootMatches);const results=[];for(let index=0;index<rootMatches.length;index++)results.push(defined(rootMatches[index],"index"));const rootOf=(node)=>node.getRootNode();const parent=(node)=>node.parentElement??rootOf(node).host??null;const scope=root instanceof Element?root:root.documentElement;const matches=(node,group,index)=>{if(node===root&&index>0)return false;const part=defined(group[index],"selector");const scoped=/^:scope\b/.test(part.selector);const compound=scoped?part.selector.replace(/^:scope\b/,"*"):part.selector;if(scoped&&node!==scope)return false;if(!node.matches(compound))return false;if(index===0)return true;if(part.combinator===">"){const ancestor=parent(node);return!!ancestor&&matches(ancestor,group,index-1)}if(part.combinator==="+")return!!node.previousElementSibling&&matches(node.previousElementSibling,group,index-1);if(part.combinator==="~"){for(let sibling=node.previousElementSibling;sibling;sibling=sibling.previousElementSibling){if(matches(sibling,group,index-1))return true}return false}for(let ancestor=parent(node);ancestor;ancestor=parent(ancestor)){if(matches(ancestor,group,index-1))return true;if(ancestor===root)break}return false};while(pending.length){const shadow=defined(pending.pop(),"querySelectorAll");const elements=shadow.querySelectorAll("*");for(let index=elements.length-1;index>=0;index--){const element=defined(elements[index],"shadowRoot");if(element.shadowRoot)pending.push(element.shadowRoot)}if(simple){const found=selector==="*"?elements:shadow.querySelectorAll(selector);for(let index=0;index<found.length;index++)results.push(defined(found[index],"index"));continue}for(let index=0;index<elements.length;index++){const node=defined(elements[index],"index");if(groups.some((group)=>matches(node,group,group.length-1)))results.push(node)}}return results}function isElementHiddenForAria(element,cache){const isElement=(node)=>node.nodeType===1;const isFragment=(node)=>node?.nodeType===11;const getStyle=(node)=>node.ownerDocument?.defaultView?.getComputedStyle(node);const isVisibleTextNode=(text)=>{const ownerDocument=text.ownerDocument;if(ownerDocument===null)throw new TypeError("Cannot read properties of null (reading 'createRange')");const range=ownerDocument.createRange();range.selectNode(text);const rect=range.getBoundingClientRect();return rect.width>0&&rect.height>0};const belongsToDisplayNoneOrAriaHiddenOrNonSlotted=(node)=>{let hidden=cache.get(node);if(hidden===undefined){hidden=!!(node.parentElement&&node.parentElement.shadowRoot&&!node.assignedSlot);if(!hidden){const style=getStyle(node);hidden=!style||style.display==="none"||node.getAttribute("aria-hidden")?.toLowerCase()==="true"}if(!hidden){const parentNode=node.parentNode;const parent=node.parentElement??(isFragment(parentNode)?parentNode.host:null);if(parent)hidden=belongsToDisplayNoneOrAriaHiddenOrNonSlotted(parent)}cache.set(node,hidden)}return hidden};const tagName=typeof element.tagName==="string"?element.tagName.toUpperCase():"FORM";if(["STYLE","SCRIPT","NOSCRIPT","TEMPLATE"].includes(tagName))return true;const style=getStyle(element);const isSlot=element.nodeName==="SLOT";if(style?.display==="contents"&&!isSlot){for(let child=element.firstChild;child;child=child.nextSibling){if(isElement(child)&&!isElementHiddenForAria(child,cache))return false;if(child.nodeType===3&&isVisibleTextNode(child))return false}return true}const isOptionInsideSelect=element.nodeName==="OPTION"&&!!element.closest("select");if(!isOptionInsideSelect&&!isSlot&&style&&(!element.checkVisibility()||style.visibility!=="visible"))return true;return belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element)}function createTextMatching(isHidden=()=>false,getRole=()=>"",includeHidden=false){const isElement=(node)=>node.nodeType===1;const isInput=(node)=>node.nodeName==="INPUT";const isSlot=(node)=>node.nodeName==="SLOT";const isFormField=(node)=>node.nodeName==="INPUT"||node.nodeName==="TEXTAREA"||node.nodeName==="SELECT";const viewOf=(document2)=>{const view=document2.defaultView;if(view===null)throw new TypeError("Cannot read properties of null (reading 'getComputedStyle')");return view};const scopeOf=(node)=>node.getRootNode();const buttonDefaults={submit:"Submit",reset:"Reset"};const nativeCaptions={FIELDSET:"LEGEND",FIGURE:"FIGCAPTION",TABLE:"CAPTION",SVG:"title"};const normalize=(value)=>String(value??"").replace(/[\u200b\u00ad]/g,"").trim().replace(/\s+/g," ");const matches=(value,matcher)=>{if(matcher instanceof RegExp){matcher.lastIndex=0;return matcher.test(value)}const text=normalize(value);return"exact"in matcher?text===normalize(matcher.exact):text.toLowerCase().includes(normalize(matcher.contains).toLowerCase())};const skipped=(node)=>["SCRIPT","STYLE","TEMPLATE","NOSCRIPT"].includes(node.nodeName)||!!node.ownerDocument?.head?.contains(node);const textCache=new Map;const text=(node)=>{const cached=textCache.get(node);if(cached!==undefined)return cached;let value="";if(!skipped(node)){if(isInput(node)&&["submit","button","reset"].includes(node.type))value=node.value;else{for(const child of node.childNodes){if(child.nodeType===3)value+=child.nodeValue;else if(isElement(child))value+=text(child)}if(node.shadowRoot)value+=text(node.shadowRoot)}}textCache.set(node,value);return value};const matchesText=(node,matcher)=>!skipped(node)&&matches(text(node),matcher);const labelledBy=(node)=>{const refs=node.ariaLabelledByElements??(node.getAttribute("aria-labelledby")??"").trim().split(/\s+/).filter(Boolean).map((id)=>scopeOf(node).getElementById?.(id)).filter((ref)=>ref!==null&&ref!==undefined);return refs.length?[...new Set(refs)]:null};const labels=(node)=>{const refs=labelledBy(node);if(refs)return refs.map(text);const ariaLabel=node.getAttribute("aria-label");if(ariaLabel?.trim())return[ariaLabel];return Array.from(node.labels??[],text)};const contentRoles=new Set(["button","cell","checkbox","columnheader","gridcell","heading","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","row","rowheader","switch","tab","tooltip","treeitem"]);const prohibitedRoles=new Set(["caption","code","definition","deletion","emphasis","generic","insertion","mark","paragraph","presentation","strong","subscript","suggestion","superscript","term","time"]);const accessibleName=(node)=>{const visited=new Set;const alternative=(element,referenced=false,hiddenReference=false,descendant=false,inLabelledBy=false)=>{if(visited.has(element)||skipped(element))return"";if(!includeHidden&&!hiddenReference&&isHidden(element))return"";visited.add(element);const refs=labelledBy(element);if(refs&&!inLabelledBy){const value=refs.map((ref)=>alternative(ref,true,isHidden(ref),false,true)).join(" ");if(value)return value}const ariaLabel=element.getAttribute("aria-label");if(ariaLabel?.trim())return ariaLabel;const tag=element.nodeName;if(isInput(element)&&["button","submit","reset"].includes(element.type))return element.value||buttonDefaults[element.type]||element.getAttribute("title")||"";if(element.labels?.length&&!inLabelledBy)return Array.from(element.labels,(label)=>alternative(label,true,isHidden(label))).join(" ");if(tag==="IMG"||tag==="AREA"||isInput(element)&&element.type==="image")return element.getAttribute("alt")||element.getAttribute("title")||(tag==="INPUT"?"Submit":"");if(isFormField(element)){if(descendant&&["INPUT","TEXTAREA"].includes(tag))return element.value;if(tag==="INPUT"&&element.type==="file")return"Choose File";const usePlaceholder=tag==="TEXTAREA"||["text","password","number","search","tel","email","url"].includes(element.type);return element.getAttribute("title")||(usePlaceholder?element.getAttribute("placeholder"):"")||""}const nativeChild=nativeCaptions[tag];const child=nativeChild&&Array.from(element.children).find((candidate)=>candidate.nodeName===nativeChild);if(child)return alternative(child,true,isHidden(child));if(referenced||descendant||tag==="SUMMARY"||contentRoles.has(getRole(element))){let value="";const assigned=isSlot(element)?element.assignedNodes():[];const children=assigned.length?assigned:[...element.childNodes,...element.shadowRoot?.childNodes??[]];for(const childNode of children){if(!assigned.length&&childNode.assignedSlot)continue;if(childNode.nodeType===3)value+=childNode.nodeValue;else if(isElement(childNode)){const token=alternative(childNode,referenced,hiddenReference,true,inLabelledBy);const display=viewOf(childNode.ownerDocument).getComputedStyle(childNode).display;value+=display!=="inline"||childNode.nodeName==="BR"?` ${token} `:token}}if(normalize(value))return value}return element.getAttribute("title")||""};return prohibitedRoles.has(getRole(node))?"":normalize(alternative(node))};return{normalize,matches,skipped,text,matchesText,labels,accessibleName}}function defined(value,what){if(value===undefined)throw new RangeError(`${what} is missing`);return value}var isInteger=(value)=>Number.isInteger(value);var baselines=new WeakMap;var REF_LINE=/^(\s*)- [^\s"]+(?: "(?:\\.|[^"\\])*")? \[ref=((?:f\d+)?e\d+)\]/;function indexTree(tree){const nodes=new Map;const unreferenced=[];const parents=[];let focused=null;for(const line of tree.split(`
66
+ }`;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 generateSizeGate(doc,schema,size){for(const[max,check]of sizeCaps(schema._zod.def.checks)){doc.write(`if (${size} > ${numericOperand(max,check._zod.def.check)}) return INVALID;`)}}function generateArrayCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);generateSizeGate(doc,schema,`${accessor}.length`);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;`);generateSizeGate(doc,schema,`${accessor}.size`);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;`);generateSizeGate(doc,schema,`${accessor}.size`);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(types2,params){return new $ZodCheckMimeType({check:"mime_type",mime:types2,...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 types2=[];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(!types2.includes(member))types2.push(member)}}delete schema.anyOf;schema.type=types2.length===1?types2[0]:types2}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 types2=Array.isArray(json.type)?json.type:[json.type];const numericType=!types2.includes("string")&&types2.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=(types2.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=(types2,params)=>inst.check(_mime(Array.isArray(types2)?types2:[types2],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)}var pageBundle=readFileSync(new URL("./page-bundle.js",import.meta.url),"utf8");function queryOpenShadowAll(root,selector){const defined=(value,reading)=>{if(value===undefined)throw new TypeError(`Cannot read properties of undefined (reading '${reading}')`);return value};const groups=[];let parts=[],token="",depth=0,quote="",escaped=false,combinator=" ";const flush=()=>{if(!token.trim())return;parts.push({selector:token.trim(),combinator});token="";combinator=" "};for(const char of selector){if(escaped){token+=char;escaped=false;continue}if(char==="\\"){token+=char;escaped=true;continue}if(quote){token+=char;if(char===quote)quote="";continue}if(char==='"'||char==="'"){quote=char;token+=char;continue}if(char==="["||char==="(")depth++;if(char==="]"||char===")")depth--;if(!depth&&(char===","||char===">"||char==="+"||char==="~"||/\s/.test(char))){flush();if(char===","){groups.push(parts);parts=[];combinator=" "}else if(!/\s/.test(char))combinator=char}else token+=char}flush();groups.push(parts);const simple=groups.every((group)=>group.length===1&&!/^:scope\b/.test(defined(group[0],"selector").selector));let rootSelector=selector;if(!simple&&root instanceof Element){const scopedSelectors=[];for(const group of groups){const first=defined(group[0],"selector").selector;const rest=group.slice(1).map((part)=>`${part.combinator} ${part.selector}`).join(" ");const scoped=/^:scope\b/.test(first);scopedSelectors.push(`${scoped?"":":scope "}${first} ${rest}`);if(!scoped&&group.length>1&&root.matches(first))scopedSelectors.push(`:scope ${rest}`)}rootSelector=scopedSelectors.join(", ")}const rootElements=root.querySelectorAll("*");const rootMatches=rootSelector==="*"?rootElements:root.querySelectorAll(rootSelector);const pending=[];for(let index=rootElements.length-1;index>=0;index--){const element=defined(rootElements[index],"shadowRoot");if(element.shadowRoot)pending.push(element.shadowRoot)}if(root instanceof Element&&root.shadowRoot)pending.push(root.shadowRoot);if(pending.length===0)return Array.from(rootMatches);const results=[];for(let index=0;index<rootMatches.length;index++)results.push(defined(rootMatches[index],"index"));const rootOf=(node)=>node.getRootNode();const parent=(node)=>node.parentElement??rootOf(node).host??null;const scope=root instanceof Element?root:root.documentElement;const matches=(node,group,index)=>{if(node===root&&index>0)return false;const part=defined(group[index],"selector");const scoped=/^:scope\b/.test(part.selector);const compound=scoped?part.selector.replace(/^:scope\b/,"*"):part.selector;if(scoped&&node!==scope)return false;if(!node.matches(compound))return false;if(index===0)return true;if(part.combinator===">"){const ancestor=parent(node);return!!ancestor&&matches(ancestor,group,index-1)}if(part.combinator==="+")return!!node.previousElementSibling&&matches(node.previousElementSibling,group,index-1);if(part.combinator==="~"){for(let sibling=node.previousElementSibling;sibling;sibling=sibling.previousElementSibling){if(matches(sibling,group,index-1))return true}return false}for(let ancestor=parent(node);ancestor;ancestor=parent(ancestor)){if(matches(ancestor,group,index-1))return true;if(ancestor===root)break}return false};while(pending.length){const shadow=defined(pending.pop(),"querySelectorAll");const elements=shadow.querySelectorAll("*");for(let index=elements.length-1;index>=0;index--){const element=defined(elements[index],"shadowRoot");if(element.shadowRoot)pending.push(element.shadowRoot)}if(simple){const found=selector==="*"?elements:shadow.querySelectorAll(selector);for(let index=0;index<found.length;index++)results.push(defined(found[index],"index"));continue}for(let index=0;index<elements.length;index++){const node=defined(elements[index],"index");if(groups.some((group)=>matches(node,group,group.length-1)))results.push(node)}}return results}function isElementHiddenForAria(element,cache){const isElement=(node)=>node.nodeType===1;const isFragment=(node)=>node?.nodeType===11;const getStyle=(node)=>node.ownerDocument?.defaultView?.getComputedStyle(node);const isVisibleTextNode=(text)=>{const ownerDocument=text.ownerDocument;if(ownerDocument===null)throw new TypeError("Cannot read properties of null (reading 'createRange')");const range=ownerDocument.createRange();range.selectNode(text);const rect=range.getBoundingClientRect();return rect.width>0&&rect.height>0};const belongsToDisplayNoneOrAriaHiddenOrNonSlotted=(node)=>{let hidden=cache.get(node);if(hidden===undefined){hidden=!!(node.parentElement&&node.parentElement.shadowRoot&&!node.assignedSlot);if(!hidden){const style=getStyle(node);hidden=!style||style.display==="none"||node.getAttribute("aria-hidden")?.toLowerCase()==="true"}if(!hidden){const parentNode=node.parentNode;const parent=node.parentElement??(isFragment(parentNode)?parentNode.host:null);if(parent)hidden=belongsToDisplayNoneOrAriaHiddenOrNonSlotted(parent)}cache.set(node,hidden)}return hidden};const tagName=typeof element.tagName==="string"?element.tagName.toUpperCase():"FORM";if(["STYLE","SCRIPT","NOSCRIPT","TEMPLATE"].includes(tagName))return true;const style=getStyle(element);const isSlot=element.nodeName==="SLOT";if(style?.display==="contents"&&!isSlot){for(let child=element.firstChild;child;child=child.nextSibling){if(isElement(child)&&!isElementHiddenForAria(child,cache))return false;if(child.nodeType===3&&isVisibleTextNode(child))return false}return true}const isOptionInsideSelect=element.nodeName==="OPTION"&&!!element.closest("select");if(!isOptionInsideSelect&&!isSlot&&style&&(!element.checkVisibility()||style.visibility!=="visible"))return true;return belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element)}function createTextMatching(isHidden=()=>false,getRole=()=>"",includeHidden=false){const isElement=(node)=>node.nodeType===1;const isInput=(node)=>node.nodeName==="INPUT";const isSlot=(node)=>node.nodeName==="SLOT";const isFormField=(node)=>node.nodeName==="INPUT"||node.nodeName==="TEXTAREA"||node.nodeName==="SELECT";const viewOf=(document2)=>{const view=document2.defaultView;if(view===null)throw new TypeError("Cannot read properties of null (reading 'getComputedStyle')");return view};const scopeOf=(node)=>node.getRootNode();const buttonDefaults={submit:"Submit",reset:"Reset"};const nativeCaptions={FIELDSET:"LEGEND",FIGURE:"FIGCAPTION",TABLE:"CAPTION",SVG:"title"};const normalize=(value)=>String(value??"").replace(/[\u200b\u00ad]/g,"").trim().replace(/\s+/g," ");const matches=(value,matcher)=>{if(matcher instanceof RegExp){matcher.lastIndex=0;return matcher.test(value)}const text=normalize(value);return"exact"in matcher?text===normalize(matcher.exact):text.toLowerCase().includes(normalize(matcher.contains).toLowerCase())};const skipped=(node)=>["SCRIPT","STYLE","TEMPLATE","NOSCRIPT"].includes(node.nodeName)||!!node.ownerDocument?.head?.contains(node);const textCache=new Map;const text=(node)=>{const cached=textCache.get(node);if(cached!==undefined)return cached;let value="";if(!skipped(node)){if(isInput(node)&&["submit","button","reset"].includes(node.type))value=node.value;else{for(const child of node.childNodes){if(child.nodeType===3)value+=child.nodeValue;else if(isElement(child))value+=text(child)}if(node.shadowRoot)value+=text(node.shadowRoot)}}textCache.set(node,value);return value};const matchesText=(node,matcher)=>!skipped(node)&&matches(text(node),matcher);const labelledBy=(node)=>{const refs=node.ariaLabelledByElements??(node.getAttribute("aria-labelledby")??"").trim().split(/\s+/).filter(Boolean).map((id)=>scopeOf(node).getElementById?.(id)).filter((ref)=>ref!==null&&ref!==undefined);return refs.length?[...new Set(refs)]:null};const labels=(node)=>{const refs=labelledBy(node);if(refs)return refs.map(text);const ariaLabel=node.getAttribute("aria-label");if(ariaLabel?.trim())return[ariaLabel];return Array.from(node.labels??[],text)};const contentRoles=new Set(["button","cell","checkbox","columnheader","gridcell","heading","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","row","rowheader","switch","tab","tooltip","treeitem"]);const prohibitedRoles=new Set(["caption","code","definition","deletion","emphasis","generic","insertion","mark","paragraph","presentation","strong","subscript","suggestion","superscript","term","time"]);const accessibleName=(node)=>{const visited=new Set;const alternative=(element,referenced=false,hiddenReference=false,descendant=false,inLabelledBy=false)=>{if(visited.has(element)||skipped(element))return"";if(!includeHidden&&!hiddenReference&&isHidden(element))return"";visited.add(element);const refs=labelledBy(element);if(refs&&!inLabelledBy){const value=refs.map((ref)=>alternative(ref,true,isHidden(ref),false,true)).join(" ");if(value)return value}const ariaLabel=element.getAttribute("aria-label");if(ariaLabel?.trim())return ariaLabel;const tag=element.nodeName;if(isInput(element)&&["button","submit","reset"].includes(element.type))return element.value||buttonDefaults[element.type]||element.getAttribute("title")||"";if(element.labels?.length&&!inLabelledBy)return Array.from(element.labels,(label)=>alternative(label,true,isHidden(label))).join(" ");if(tag==="IMG"||tag==="AREA"||isInput(element)&&element.type==="image")return element.getAttribute("alt")||element.getAttribute("title")||(tag==="INPUT"?"Submit":"");if(isFormField(element)){if(descendant&&["INPUT","TEXTAREA"].includes(tag))return element.value;if(tag==="INPUT"&&element.type==="file")return"Choose File";const usePlaceholder=tag==="TEXTAREA"||["text","password","number","search","tel","email","url"].includes(element.type);return element.getAttribute("title")||(usePlaceholder?element.getAttribute("placeholder"):"")||""}const nativeChild=nativeCaptions[tag];const child=nativeChild&&Array.from(element.children).find((candidate)=>candidate.nodeName===nativeChild);if(child)return alternative(child,true,isHidden(child));if(referenced||descendant||tag==="SUMMARY"||contentRoles.has(getRole(element))){let value="";const assigned=isSlot(element)?element.assignedNodes():[];const children=assigned.length?assigned:[...element.childNodes,...element.shadowRoot?.childNodes??[]];for(const childNode of children){if(!assigned.length&&childNode.assignedSlot)continue;if(childNode.nodeType===3)value+=childNode.nodeValue;else if(isElement(childNode)){const token=alternative(childNode,referenced,hiddenReference,true,inLabelledBy);const display=viewOf(childNode.ownerDocument).getComputedStyle(childNode).display;value+=display!=="inline"||childNode.nodeName==="BR"?` ${token} `:token}}if(normalize(value))return value}return element.getAttribute("title")||""};return prohibitedRoles.has(getRole(node))?"":normalize(alternative(node))};return{normalize,matches,skipped,text,matchesText,labels,accessibleName}}function defined(value,what){if(value===undefined)throw new RangeError(`${what} is missing`);return value}var isInteger=(value)=>Number.isInteger(value);var baselines=new WeakMap;var REF_LINE=/^(\s*)- [^\s"]+(?: "(?:\\.|[^"\\])*")? \[ref=((?:f\d+)?e\d+)\]/;function indexTree(tree){const nodes=new Map;const unreferenced=[];const parents=[];let focused=null;for(const line of tree.split(`
67
67
  `)){if(!line)continue;const depth=line.search(/\S/);while(parents.length&&defined(parents.at(-1),"open parent").depth>=depth)parents.pop();const match=REF_LINE.exec(line);if(match){const ref=defined(match[2],"ref group");const node={ref,tree:line.trim().slice(2)};nodes.set(ref,node);parents.push({depth,node});const state=line.slice(match[0].length).match(/"(?:\\.|[^"\\])*"|\[focused\]/g)??[];if(state.includes("[focused]"))focused=ref}else if(parents.length){defined(parents.at(-1),"open parent").node.tree+=` | ${line.trim().slice(2)}`}else if(!/^\s*- [\w-]+:?$/.test(line)){unreferenced.push(line)}}return{nodes,focused,unreferenced:unreferenced.join(`
68
68
  `)}}var REF_ATTR=/\[ref=((?:f\d+)?e\d+)\]/g;var QUOTED=/"(?:\\.|[^"\\])*"/g;function validateSnapshotOptions(options){const{diff,find,context}=options;if(find===undefined){if(context!==undefined)throw new TypeError("snapshot({ context }) needs find");return}if(diff===true)throw new TypeError("snapshot() accepts diff or find, not both");if(!(find instanceof RegExp)&&(typeof find!=="string"||find==="")){throw new TypeError("snapshot({ find }) needs a non-empty string or a RegExp")}if(context!==undefined&&(!isInteger(context)||context<0||context>10)){throw new TypeError("snapshot({ context }) must be an integer from 0 to 10")}}function findSnapshotLines(snapshot,find,context=2){const query=find instanceof RegExp?{pattern:new RegExp(find.source,find.flags.replace(/[gy]/g,"")),needle:null}:{pattern:null,needle:find.toLowerCase()};const lines=snapshot.tree?snapshot.tree.split(`
69
69
  `):[];const matched=[];lines.forEach((line,index)=>{if(query.pattern?query.pattern.test(line):line.toLowerCase().includes(query.needle))matched.push(index)});const included=new Set;for(const index of matched){for(let i=Math.max(0,index-context);i<=Math.min(lines.length-1,index+context);i++)included.add(i)}const out=[];let previous=-1;for(const index of[...included].toSorted((a,b)=>a-b)){if(out.length&&index>previous+1)out.push("...");out.push(defined(lines[index],"line"));previous=index}const tree=out.join(`
@@ -93,7 +93,7 @@ ${code}
93
93
  callback.reject(error);
94
94
  } else if (result.thrown) callback.reject(state.bindingValue(result.thrown, true));
95
95
  else callback.resolve(state.bindingValue(result.value, true));
96
- })()`},sessionId)}async function installScripts(page,state,sessionId,session){for(const script of state.scripts){if(session.scripts.has(script))continue;const{identifier}=await page.cdp.send("Page.addScriptToEvaluateOnNewDocument",{source:script.source,runImmediately:script.binding},sessionId);session.scripts.set(script,identifier)}}function initializeSession(page,state,sessionId){let existing=state.sessions.get(sessionId);if(!existing){existing={scripts:new Map,bindings:new Set,ready:Promise.resolve()};state.sessions.set(sessionId,existing)}const session=existing;const operation=session.ready.then(async()=>{for(const[name]of state.bindings){if(session.bindings.has(name))continue;await page.cdp.send("Runtime.addBinding",{name},sessionId);session.bindings.add(name)}if(state.bindings.size&&!session.runtimeEnabled){await page.cdp.send("Runtime.enable",undefined,sessionId);session.runtimeEnabled=true}await installScripts(page,state,sessionId,session);if(state.headers!==null){session.releaseNetwork??=acquireNetwork(page.cdp,sessionId);await session.releaseNetwork.ready;await page.cdp.send("Network.setExtraHTTPHeaders",{headers:state.headers},sessionId)}if(state.media)await page.cdp.send("Emulation.setEmulatedMedia",state.media,sessionId)});session.ready=operation.catch(()=>{});return operation}async function updateSessions(page,state){const main=await page.resolveSessionId();const sessions=new Set([main,...[...page.frameManager.frames.values()].map((frame)=>frame.sessionId)]);for(const sessionId of sessions){await initializeSession(page,state,sessionId);await page.cdp.send("Target.setAutoAttach",{autoAttach:true,waitForDebuggerOnStart:true,flatten:true},sessionId)}}async function addInitScript(script,arg){let source;if(typeof script==="function"){source=`(() => { const __name = value => value; (${script.toString()})(${JSON.stringify(arg)??"undefined"}); })()`}else if(typeof script==="string")source=script;else if(typeof script?.content==="string")source=script.content;else if(typeof script?.path==="string")source=await readFile2(script.path,"utf8");else throw new TypeError("addInitScript requires a function, string, or { path | content }");const state=setupState(this);state.scripts.push({source,binding:false});await updateSessions(this,state)}async function exposeFunction(name,callback){await registerBinding(this,name,callback,false)}async function exposeBinding(name,callback){await registerBinding(this,name,callback,true)}async function registerBinding(page,name,callback,source){if(typeof name!=="string"||typeof callback!=="function")throw new TypeError(`${source?"exposeBinding":"exposeFunction"} requires a name and function`);const state=setupState(page);if([...state.bindings.values()].some((binding)=>binding.name===name))throw Error(`Function "${name}" has already been registered`);const internalName=`__omowright_binding_${randomUUID().replaceAll("-","")}`;const invoke=(...args)=>Reflect.apply(callback,undefined,args);state.bindings.set(internalName,{name,callback:invoke,source});state.scripts.push({source:bindingScript(name,internalName),binding:true});await updateSessions(page,state)}async function setExtraHTTPHeaders(headers){if(!headers||typeof headers!=="object"||Array.isArray(headers))throw new TypeError("headers must be an object of strings");const checked={};for(const[name,value]of Object.entries(headers)){if(typeof value!=="string")throw new TypeError(`Header "${name}" value must be a string`);checked[name]=value}const state=setupState(this);state.headers=checked;await updateSessions(this,state)}async function setViewportSize(viewport){const size=validateViewport(viewport);const hostSetViewportSize=readProperty(this.browser,"setViewportSize");if(hostSetViewportSize){if(typeof hostSetViewportSize!=="function")throw new TypeError("this.browser.setViewportSize is not a function");await Reflect.apply(hostSetViewportSize,this.browser,[size])}else await repinViewport(this,size)}var mediaFeatures={colorScheme:["prefers-color-scheme",["light","dark","no-preference"]],reducedMotion:["prefers-reduced-motion",["reduce","no-preference"]],forcedColors:["forced-colors",["active","none"]],contrast:["prefers-contrast",["more","no-preference"]]};var mediaFeatureKeys=["colorScheme","reducedMotion","forcedColors","contrast"];async function emulateMedia(options={}){if(options.media!==undefined&&options.media!==null&&!["screen","print"].includes(options.media))throw new TypeError("media must be screen, print or null");for(const key of mediaFeatureKeys){const[,allowed]=mediaFeatures[key];const value=options[key];if(value!==undefined&&value!==null&&!allowed.includes(value))throw new TypeError(`${key} must be ${allowed.join(", ")} or null`)}const state=setupState(this);const previous=new Map(state.media?.features.map((feature)=>[feature.name,feature.value]));for(const key of mediaFeatureKeys){const[name]=mediaFeatures[key];if(options[key]!==undefined)previous.set(name,options[key]??"")}state.media={media:options.media===undefined?state.media?.media??"":options.media??"",features:[...previous].map(([name,value])=>({name,value}))};await updateSessions(this,state)}function definedOrThrow(value){if(value===undefined)throw new TypeError(`Cannot read properties of undefined`);return value}function readOptionalProperty(value,key){return value===null||value===undefined?undefined:readProperty(value,key)}var __defProp2=Object.defineProperty;function __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=unsetResolver;let reject=unsetResolver;const promise=new Promise((res,rej)=>{resolve=res;reject=rej});return{promise,resolve,reject}}}function unsetResolver(){}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()}listenerCount(name){return this.#listeners.get(name)?.size??0}}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=path2.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,..._options){throw new UnsupportedOperationError(`Extension command is unavailable: ${command.method}`)}class UnsupportedOperationError extends Error{constructor(message){super(message);this.name="UnsupportedOperationError"}}var WAIT_FOR_FUNCTION_SOURCE_LIMIT=200;var WAIT_FOR_FUNCTION_RAF_FALLBACK_MS=100;var WAIT_FOR_FUNCTION_CALL_MARGIN_MS=1000;class WaitForFunctionTimeoutError extends Error{constructor(source,timeoutMs){const compact=source.replace(/\s+/g," ").trim();const shown=compact.length>WAIT_FOR_FUNCTION_SOURCE_LIMIT?`${compact.slice(0,WAIT_FOR_FUNCTION_SOURCE_LIMIT)}…`:compact;super(`page.waitForFunction: timed out after ${timeoutMs}ms waiting for ${shown}`);this.name="WaitForFunctionTimeoutError";this.timeoutMs=timeoutMs}}function isNavigationInterruptedError(error){const message=error instanceof Error?error.message:String(error);return isContextDestroyedError(error)||message.includes("Cannot find object with given id")||message.includes("Inspected target navigated or closed")}function isUnserializableResultError(error){const message=error instanceof Error?error.message:String(error);return message.includes("Object reference chain is too long")||message.includes("Object couldn't be returned by value")}function isSessionDetachedError(error){return error instanceof Error&&error.name==="CdpSessionDetachedError"}class VideoRecordingError extends Error{constructor(message,options){super(message,options);this.name="VideoRecordingError"}}function spawnCommand([command,...args],options){const child=spawn(command,args,options);const process2={child,stdin:child.stdin,stderr:"",error:null,ready:new Promise((resolve)=>{child.once("spawn",resolve);child.once("error",resolve)}),exited:new Promise((resolve)=>child.once("close",resolve))};child.once("error",(error)=>{process2.error=error});child.stdin.on("error",(error)=>{if(!isProcessInputClosedError(error))process2.error??=error});child.stderr.setEncoding("utf8");child.stderr.on("data",(chunk)=>{process2.stderr+=chunk});return process2}async function disposeProcess(process2){process2.stdin.destroy();if(process2.child.exitCode===null&&process2.child.signalCode===null)process2.child.kill("SIGKILL");await process2.exited}var ENCODER_EXIT_TIMEOUT_MS=1e4;async function waitForExitCode(process2,timeoutMs){const stalled=Symbol("stalled");let timer;const deadline=new Promise((resolve)=>{timer=setTimeout(resolve,timeoutMs,stalled)});const code=await Promise.race([process2.exited,deadline]).finally(()=>clearTimeout(timer));if(code===stalled){await disposeProcess(process2);throw new Error(`ffmpeg did not exit within ${timeoutMs}ms after its input closed; it was killed.`)}if(process2.error)throw process2.error;return code}function writeProcessChunk(stdin,chunk){if(stdin.destroyed||stdin.writableEnded)return Promise.resolve();return new Promise((resolve,reject)=>stdin.write(chunk,(error)=>error&&!isProcessInputClosedError(error)?reject(error):resolve()))}function endProcessInput(stdin){if(stdin.destroyed||stdin.writableEnded)return Promise.resolve();return new Promise((resolve,reject)=>stdin.end((error)=>error&&!isProcessInputClosedError(error)?reject(error):resolve()))}function isProcessInputClosedError(error){return error?.code==="EPIPE"||error?.code==="ERR_STREAM_DESTROYED"||error?.code==="ERR_STREAM_WRITE_AFTER_END"}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 readProperty(Vn,"status")==`number`&&(readProperty(Vn,"status")===401||readProperty(Vn,"status")===403)||typeof readOptionalProperty(readProperty(Vn,"response"),"status")==`number`&&(readProperty(readProperty(Vn,"response"),"status")===401||readProperty(readProperty(Vn,"response"),"status")===403)||typeof readOptionalProperty(readProperty(Vn,"error"),"status")==`number`&&(readProperty(readProperty(Vn,"error"),"status")===401||readProperty(readProperty(Vn,"error"),"status")===403)||typeof readOptionalProperty(readProperty(Vn,"cause"),"status")==`number`&&(readProperty(readProperty(Vn,"cause"),"status")===401||readProperty(readProperty(Vn,"cause"),"status")===403)||String(readOptionalProperty(readProperty(Vn,"error"),"message")??``).includes(`Missing or invalid Authorization header.`)||String(readOptionalProperty(readProperty(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}function dialogOpeningParams(params){return typeof params==`object`?params:undefined}function isCdpWireResponse(message){return typeof message.id==`number`}function createBrowserCdpCommandErrorClass(){return class BrowserCdpCommandError 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}}}function createCdpClientClass(){return class CdpClient{cdpUrl;logId;#dialogPolicy;#e;#t;#n;#r=null;#i=null;#a=null;#o=false;#s=1;#c=new Map;#closedSessions=new Set;#l=new Emittery;#u=false;#closedEpoch=0;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===import_websocket.default.OPEN}start(){let Kn=this.#closedEpoch;this.#o||(this.#o=true,this.ensureConnected().catch((xn)=>{this.#closedEpoch===Kn&&(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();if(this.#closedSessions.has(Vn)&&xn!==`Page.close`)throw new CdpSessionDetachedError(`Page closed: ${xn}`,{method:xn,sessionId:Vn});let Yn=this.#r;if(!Yn||Yn.readyState!==import_websocket.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),sessionId:Vn,reject:ti,resolve:ni,timeout:ii}),Jn?.addEventListener(`abort`,ai??noop,{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)}}closeSession(sessionId){this.#closedSessions.add(sessionId);for(const[id,entry]of this.#c){if(entry.sessionId!==sessionId)continue;clearTimeout(entry.timeout);this.#c.delete(id);entry.reject(new CdpSessionDetachedError(`Page closed: ${entry.method}`,{method:entry.method,sessionId}))}}on(xn,jn){return this.#l.on(xn,({data:xn})=>jn(xn.payload,xn.meta))}async close(){this.#o=false,this.#closedEpoch++,this.#i=null,this.#a&&=(clearTimeout(this.#a),null);let xn=this.#r;if(this.#r=null,this.#x(Error(`CDP client closed`)),xn&&xn.readyState<=import_websocket.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,Kn=this.#closedEpoch;for(let Vn of this.#n){if(Vn>0&&await sleep$12(Vn),this.#closedEpoch!==Kn)throw Error(`CDP client closed`);try{await this.#_({forceRefresh:jn},Kn);return}catch(Vn){if(this.#closedEpoch!==Kn)throw Error(`CDP client closed`);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={},Kn=this.#closedEpoch){let{headers:jn,wsUrl:Vn}=await this.#m(xn);if(this.#closedEpoch!==Kn)throw Error(`CDP client closed`);await new Promise((xn,qn)=>{let Jn=new import_websocket.default(Vn,{headers:jn}),Yn=false,Zn=(xn)=>{Yn||(Yn=true,qn(xn))};Jn.addEventListener(`open`,()=>{if(!Yn){if(Yn=true,this.#closedEpoch!==Kn){try{Jn.close(1000,`client closed`)}catch{}qn(Error(`CDP client closed`));return}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<=import_websocket.default.OPEN)try{jn?.close(1000,`replaced`)}catch{}}#y(xn){let Kn=this.#closedEpoch;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)=>{this.#closedEpoch===Kn&&(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;let Kn=this.#closedEpoch;this.#a=setTimeout(()=>{this.#a=null,this.ensureConnected().catch((xn)=>{this.#closedEpoch===Kn&&(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(isCdpWireResponse(Vn)){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,jn={payload:Vn.params,meta:{sessionId:Vn.sessionId}};if(xn===`Page.javascriptDialogOpening`&&Vn.sessionId){let dialogSessionId=Vn.sessionId;jn.meta.dialog=new Dialog(dialogOpeningParams(Vn.params),(dialogAction)=>this.send(`Page.handleJavaScriptDialog`,dialogAction,dialogSessionId))}let dialog=jn.meta.dialog,emitted=this.#l.emit(xn,jn).catch((jn)=>{console.warn(`[${this.logId}] CDP event listener failed for ${xn}`,jn)});dialog&&emitted.then(()=>answerWithPolicy(dialog,this.#dialogPolicy,dialogPolicyParams(Vn.params))).catch(()=>{})}}}}}function createSessionManagerClass(){return class SessionManager{#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)}}}function createPageConsoleClass(){return class PageConsole{#e;constructor(xn){this.#e=xn}async logs(xn={}){return await this.#e.evaluate((xn)=>window.__omowrightConsole?.drain(xn)??[],xn)}async clear(){await this.#e.evaluate(`(window).__omowrightConsole?.clear()`)}}}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=createBrowserCdpCommandErrorClass(),CdpClient=createCdpClientClass()});var SessionManager;var init_session_manager=__esmMin(()=>{init_client$6(),SessionManager=createSessionManagerClass()});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(){
96
+ })()`},sessionId)}async function installScripts(page,state,sessionId,session){for(const script of state.scripts){if(session.scripts.has(script))continue;const{identifier}=await page.cdp.send("Page.addScriptToEvaluateOnNewDocument",{source:script.source,runImmediately:script.binding},sessionId);session.scripts.set(script,identifier)}}function initializeSession(page,state,sessionId){let existing=state.sessions.get(sessionId);if(!existing){existing={scripts:new Map,bindings:new Set,ready:Promise.resolve()};state.sessions.set(sessionId,existing)}const session=existing;const operation=session.ready.then(async()=>{for(const[name]of state.bindings){if(session.bindings.has(name))continue;await page.cdp.send("Runtime.addBinding",{name},sessionId);session.bindings.add(name)}if(state.bindings.size&&!session.runtimeEnabled){await page.cdp.send("Runtime.enable",undefined,sessionId);session.runtimeEnabled=true}await installScripts(page,state,sessionId,session);if(state.headers!==null){session.releaseNetwork??=acquireNetwork(page.cdp,sessionId);await session.releaseNetwork.ready;await page.cdp.send("Network.setExtraHTTPHeaders",{headers:state.headers},sessionId)}if(state.media)await page.cdp.send("Emulation.setEmulatedMedia",state.media,sessionId)});session.ready=operation.catch(()=>{});return operation}async function updateSessions(page,state){const main=await page.resolveSessionId();const sessions=new Set([main,...[...page.frameManager.frames.values()].map((frame)=>frame.sessionId)]);for(const sessionId of sessions){await initializeSession(page,state,sessionId);await page.cdp.send("Target.setAutoAttach",{autoAttach:true,waitForDebuggerOnStart:true,flatten:true},sessionId)}}async function addInitScript(script,arg){let source;if(typeof script==="function"){source=`(() => { const __name = value => value; (${script.toString()})(${JSON.stringify(arg)??"undefined"}); })()`}else if(typeof script==="string")source=script;else if(typeof script?.content==="string")source=script.content;else if(typeof script?.path==="string")source=await readFile2(script.path,"utf8");else throw new TypeError("addInitScript requires a function, string, or { path | content }");const state=setupState(this);state.scripts.push({source,binding:false});await updateSessions(this,state)}async function exposeFunction(name,callback){await registerBinding(this,name,callback,false)}async function exposeBinding(name,callback){await registerBinding(this,name,callback,true)}async function registerBinding(page,name,callback,source){if(typeof name!=="string"||typeof callback!=="function")throw new TypeError(`${source?"exposeBinding":"exposeFunction"} requires a name and function`);const state=setupState(page);if([...state.bindings.values()].some((binding)=>binding.name===name))throw Error(`Function "${name}" has already been registered`);const internalName=`__omowright_binding_${randomUUID().replaceAll("-","")}`;const invoke=(...args)=>Reflect.apply(callback,undefined,args);state.bindings.set(internalName,{name,callback:invoke,source});state.scripts.push({source:bindingScript(name,internalName),binding:true});await updateSessions(page,state)}async function setExtraHTTPHeaders(headers){if(!headers||typeof headers!=="object"||Array.isArray(headers))throw new TypeError("headers must be an object of strings");const checked={};for(const[name,value]of Object.entries(headers)){if(typeof value!=="string")throw new TypeError(`Header "${name}" value must be a string`);checked[name]=value}const state=setupState(this);state.headers=checked;await updateSessions(this,state)}async function setViewportSize(viewport){const size=validateViewport(viewport);const hostSetViewportSize=readProperty(this.browser,"setViewportSize");if(hostSetViewportSize){if(typeof hostSetViewportSize!=="function")throw new TypeError("this.browser.setViewportSize is not a function");await Reflect.apply(hostSetViewportSize,this.browser,[size])}else await repinViewport(this,size)}var mediaFeatures={colorScheme:["prefers-color-scheme",["light","dark","no-preference"]],reducedMotion:["prefers-reduced-motion",["reduce","no-preference"]],forcedColors:["forced-colors",["active","none"]],contrast:["prefers-contrast",["more","no-preference"]]};var mediaFeatureKeys=["colorScheme","reducedMotion","forcedColors","contrast"];async function emulateMedia(options={}){if(options.media!==undefined&&options.media!==null&&!["screen","print"].includes(options.media))throw new TypeError("media must be screen, print or null");for(const key of mediaFeatureKeys){const[,allowed]=mediaFeatures[key];const value=options[key];if(value!==undefined&&value!==null&&!allowed.includes(value))throw new TypeError(`${key} must be ${allowed.join(", ")} or null`)}const state=setupState(this);const previous=new Map(state.media?.features.map((feature)=>[feature.name,feature.value]));for(const key of mediaFeatureKeys){const[name]=mediaFeatures[key];if(options[key]!==undefined)previous.set(name,options[key]??"")}state.media={media:options.media===undefined?state.media?.media??"":options.media??"",features:[...previous].map(([name,value])=>({name,value}))};await updateSessions(this,state)}var REMOVED_ANYWHERE_FROM_LENGTH=4;function redactValue(error,value){if(value.length===0)return error;const codePoints=[...value].length;const replacement=`<redacted, ${codePoints} chars>`;const forms=[...new Set([value,JSON.stringify(value).slice(1,-1)])].toSorted((left,right)=>right.length-left.length).map((form)=>form.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));const anyForm=`(?:${forms.join("|")})`;const pattern=new RegExp(codePoints>=REMOVED_ANYWHERE_FROM_LENGTH?anyForm:`(?<![\\p{L}\\p{N}])${anyForm}(?![\\p{L}\\p{N}])`,"gu");const scrub=(text)=>text.replace(pattern,replacement);const read=new Map;const entriesOf=(holder)=>{const known=read.get(holder);if(known!==undefined)return known;const entries=ownEntries(holder);read.set(holder,entries);return entries};try{return carries(error,scrub,entriesOf)?scrubbed(error,scrub,replacement,entriesOf):error}catch{return new Error("omowright: the error a failed fill raised could not be read for redaction, so it is withheld")}}function isError(member){return types.isNativeError(member)||member instanceof Error}function unboxed(member){if(types.isStringObject(member))return String.prototype.valueOf.call(member);if(types.isNumberObject(member))return Number.prototype.valueOf.call(member);return types.isBigIntObject(member)?BigInt.prototype.valueOf.call(member):member}function mapEntries(map){return[...Map.prototype.entries.call(map)]}function setValues(set){return[...Set.prototype.values.call(set)]}function isOpaque(member){return ArrayBuffer.isView(member)||types.isAnyArrayBuffer(member)||types.isDate(member)||types.isRegExp(member)||types.isPromise(member)||types.isWeakMap(member)||types.isWeakSet(member)}function ownValue(holder,key){const descriptor=Reflect.getOwnPropertyDescriptor(holder,key);if(descriptor===undefined)return{readable:false};if("value"in descriptor)return{readable:true,value:descriptor.value};try{return{readable:true,value:descriptor.get?.call(holder)}}catch{return{readable:false}}}function ownEntries(holder){const entries=[];for(const key of Reflect.ownKeys(holder)){if(Array.isArray(holder)&&key==="length")continue;const own=ownValue(holder,key);if(own.readable)entries.push([key,own.value])}if(isError(holder)&&Reflect.getOwnPropertyDescriptor(holder,"message")===undefined){try{entries.push(["message",Reflect.get(holder,"message")])}catch{}}return entries}function carries(root,scrub,entriesOf){const seen=new Set;const visit=(boxed)=>{const member=unboxed(boxed);if(typeof member==="string")return scrub(member)!==member;if(typeof member==="number"||typeof member==="bigint")return scrub(String(member))!==String(member);if(typeof member!=="object"||member===null||seen.has(member)||isOpaque(member))return false;seen.add(member);if(types.isMap(member)&&mapEntries(member).some(([key,entry])=>visit(key)||visit(entry)))return true;if(types.isSet(member)&&setValues(member).some((entry)=>visit(entry)))return true;return entriesOf(member).some(([,entry])=>visit(entry))};return visit(root)}function rewritable(error){if(Object.isFrozen(error))return false;return Reflect.ownKeys(error).every((key)=>{const descriptor=Reflect.getOwnPropertyDescriptor(error,key);return descriptor===undefined||descriptor.configurable===true||descriptor.writable===true})}function emptyLike(member){const prototype=Reflect.getPrototypeOf(member);let copy;if(Array.isArray(member)){const list=[];list.length=member.length;copy=list}else if(isError(member)){copy=new Error;for(const key of Reflect.ownKeys(copy))Reflect.deleteProperty(copy,key)}else if(types.isMap(member))copy=new Map;else if(types.isSet(member))copy=new Set;else return Object.create(prototype);Reflect.setPrototypeOf(copy,prototype);return copy}function scrubbed(root,scrub,replacement,entriesOf){const results=new Map;const clean=(boxed)=>{const member=unboxed(boxed);if(typeof member==="string")return scrub(member)===member?boxed:scrub(member);if(typeof member==="number"||typeof member==="bigint"){return scrub(String(member))===String(member)?boxed:replacement}if(typeof member!=="object"||member===null||isOpaque(member))return member;const known=results.get(member);if(known!==undefined)return known;const inPlace=isError(member)&&rewritable(member);if(!inPlace&&!carries(member,scrub,entriesOf))return member;const target=inPlace?member:emptyLike(member);results.set(member,target);if(types.isMap(member)&&types.isMap(target)){for(const[key,entry]of mapEntries(member))Map.prototype.set.call(target,clean(key),clean(entry))}if(types.isSet(member)&&types.isSet(target)){for(const entry of setValues(member))Set.prototype.add.call(target,clean(entry))}for(const[key,entry]of entriesOf(member)){const next=clean(entry);if(inPlace&&Object.is(next,entry))continue;const descriptor=Reflect.getOwnPropertyDescriptor(member,key);if(inPlace&&descriptor!==undefined&&"value"in descriptor)Reflect.defineProperty(target,key,{value:next});else{const enumerable=descriptor?.enumerable===true;Reflect.defineProperty(target,key,{value:next,writable:true,enumerable,configurable:true})}}if(inPlace)return target;for(const key of Reflect.ownKeys(member)){const descriptor=Reflect.getOwnPropertyDescriptor(member,key);const copied=Reflect.getOwnPropertyDescriptor(target,key)!==undefined;if(descriptor!==undefined&&!copied)Reflect.defineProperty(target,key,descriptor)}return target};return clean(root)}function definedOrThrow(value){if(value===undefined)throw new TypeError(`Cannot read properties of undefined`);return value}function readOptionalProperty(value,key){return value===null||value===undefined?undefined:readProperty(value,key)}var __defProp2=Object.defineProperty;function __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=unsetResolver;let reject=unsetResolver;const promise=new Promise((res,rej)=>{resolve=res;reject=rej});return{promise,resolve,reject}}}function unsetResolver(){}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()}listenerCount(name){return this.#listeners.get(name)?.size??0}}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=path2.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,..._options){throw new UnsupportedOperationError(`Extension command is unavailable: ${command.method}`)}class UnsupportedOperationError extends Error{constructor(message){super(message);this.name="UnsupportedOperationError"}}var WAIT_FOR_FUNCTION_SOURCE_LIMIT=200;var WAIT_FOR_FUNCTION_RAF_FALLBACK_MS=100;var WAIT_FOR_FUNCTION_CALL_MARGIN_MS=1000;class WaitForFunctionTimeoutError extends Error{constructor(source,timeoutMs){const compact=source.replace(/\s+/g," ").trim();const shown=compact.length>WAIT_FOR_FUNCTION_SOURCE_LIMIT?`${compact.slice(0,WAIT_FOR_FUNCTION_SOURCE_LIMIT)}…`:compact;super(`page.waitForFunction: timed out after ${timeoutMs}ms waiting for ${shown}`);this.name="WaitForFunctionTimeoutError";this.timeoutMs=timeoutMs}}function isNavigationInterruptedError(error){const message=error instanceof Error?error.message:String(error);return isContextDestroyedError(error)||message.includes("Cannot find object with given id")||message.includes("Inspected target navigated or closed")}function isUnserializableResultError(error){const message=error instanceof Error?error.message:String(error);return message.includes("Object reference chain is too long")||message.includes("Object couldn't be returned by value")}function isSessionDetachedError(error){return error instanceof Error&&error.name==="CdpSessionDetachedError"}class VideoRecordingError extends Error{constructor(message,options){super(message,options);this.name="VideoRecordingError"}}function spawnCommand([command,...args],options){const child=spawn(command,args,options);const process2={child,stdin:child.stdin,stderr:"",error:null,ready:new Promise((resolve)=>{child.once("spawn",resolve);child.once("error",resolve)}),exited:new Promise((resolve)=>child.once("close",resolve))};child.once("error",(error)=>{process2.error=error});child.stdin.on("error",(error)=>{if(!isProcessInputClosedError(error))process2.error??=error});child.stderr.setEncoding("utf8");child.stderr.on("data",(chunk)=>{process2.stderr+=chunk});return process2}async function disposeProcess(process2){process2.stdin.destroy();if(process2.child.exitCode===null&&process2.child.signalCode===null)process2.child.kill("SIGKILL");await process2.exited}var ENCODER_EXIT_TIMEOUT_MS=1e4;async function waitForExitCode(process2,timeoutMs){const stalled=Symbol("stalled");let timer;const deadline=new Promise((resolve)=>{timer=setTimeout(resolve,timeoutMs,stalled)});const code=await Promise.race([process2.exited,deadline]).finally(()=>clearTimeout(timer));if(code===stalled){await disposeProcess(process2);throw new Error(`ffmpeg did not exit within ${timeoutMs}ms after its input closed; it was killed.`)}if(process2.error)throw process2.error;return code}function writeProcessChunk(stdin,chunk){if(stdin.destroyed||stdin.writableEnded)return Promise.resolve();return new Promise((resolve,reject)=>stdin.write(chunk,(error)=>error&&!isProcessInputClosedError(error)?reject(error):resolve()))}function endProcessInput(stdin){if(stdin.destroyed||stdin.writableEnded)return Promise.resolve();return new Promise((resolve,reject)=>stdin.end((error)=>error&&!isProcessInputClosedError(error)?reject(error):resolve()))}function isProcessInputClosedError(error){return error?.code==="EPIPE"||error?.code==="ERR_STREAM_DESTROYED"||error?.code==="ERR_STREAM_WRITE_AFTER_END"}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 readProperty(Vn,"status")==`number`&&(readProperty(Vn,"status")===401||readProperty(Vn,"status")===403)||typeof readOptionalProperty(readProperty(Vn,"response"),"status")==`number`&&(readProperty(readProperty(Vn,"response"),"status")===401||readProperty(readProperty(Vn,"response"),"status")===403)||typeof readOptionalProperty(readProperty(Vn,"error"),"status")==`number`&&(readProperty(readProperty(Vn,"error"),"status")===401||readProperty(readProperty(Vn,"error"),"status")===403)||typeof readOptionalProperty(readProperty(Vn,"cause"),"status")==`number`&&(readProperty(readProperty(Vn,"cause"),"status")===401||readProperty(readProperty(Vn,"cause"),"status")===403)||String(readOptionalProperty(readProperty(Vn,"error"),"message")??``).includes(`Missing or invalid Authorization header.`)||String(readOptionalProperty(readProperty(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}function dialogOpeningParams(params){return typeof params==`object`?params:undefined}function isCdpWireResponse(message){return typeof message.id==`number`}function createBrowserCdpCommandErrorClass(){return class BrowserCdpCommandError 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}}}function createCdpClientClass(){return class CdpClient{cdpUrl;logId;#dialogPolicy;#e;#t;#n;#r=null;#i=null;#a=null;#o=false;#s=1;#c=new Map;#closedSessions=new Set;#l=new Emittery;#u=false;#closedEpoch=0;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===import_websocket.default.OPEN}start(){let Kn=this.#closedEpoch;this.#o||(this.#o=true,this.ensureConnected().catch((xn)=>{this.#closedEpoch===Kn&&(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();if(this.#closedSessions.has(Vn)&&xn!==`Page.close`)throw new CdpSessionDetachedError(`Page closed: ${xn}`,{method:xn,sessionId:Vn});let Yn=this.#r;if(!Yn||Yn.readyState!==import_websocket.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),sessionId:Vn,reject:ti,resolve:ni,timeout:ii}),Jn?.addEventListener(`abort`,ai??noop,{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)}}closeSession(sessionId){this.#closedSessions.add(sessionId);for(const[id,entry]of this.#c){if(entry.sessionId!==sessionId)continue;clearTimeout(entry.timeout);this.#c.delete(id);entry.reject(new CdpSessionDetachedError(`Page closed: ${entry.method}`,{method:entry.method,sessionId}))}}on(xn,jn){return this.#l.on(xn,({data:xn})=>jn(xn.payload,xn.meta))}async close(){this.#o=false,this.#closedEpoch++,this.#i=null,this.#a&&=(clearTimeout(this.#a),null);let xn=this.#r;if(this.#r=null,this.#x(Error(`CDP client closed`)),xn&&xn.readyState<=import_websocket.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,Kn=this.#closedEpoch;for(let Vn of this.#n){if(Vn>0&&await sleep$12(Vn),this.#closedEpoch!==Kn)throw Error(`CDP client closed`);try{await this.#_({forceRefresh:jn},Kn);return}catch(Vn){if(this.#closedEpoch!==Kn)throw Error(`CDP client closed`);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={},Kn=this.#closedEpoch){let{headers:jn,wsUrl:Vn}=await this.#m(xn);if(this.#closedEpoch!==Kn)throw Error(`CDP client closed`);await new Promise((xn,qn)=>{let Jn=new import_websocket.default(Vn,{headers:jn}),Yn=false,Zn=(xn)=>{Yn||(Yn=true,qn(xn))};Jn.addEventListener(`open`,()=>{if(!Yn){if(Yn=true,this.#closedEpoch!==Kn){try{Jn.close(1000,`client closed`)}catch{}qn(Error(`CDP client closed`));return}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<=import_websocket.default.OPEN)try{jn?.close(1000,`replaced`)}catch{}}#y(xn){let Kn=this.#closedEpoch;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)=>{this.#closedEpoch===Kn&&(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;let Kn=this.#closedEpoch;this.#a=setTimeout(()=>{this.#a=null,this.ensureConnected().catch((xn)=>{this.#closedEpoch===Kn&&(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(isCdpWireResponse(Vn)){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,jn={payload:Vn.params,meta:{sessionId:Vn.sessionId}};if(xn===`Page.javascriptDialogOpening`&&Vn.sessionId){let dialogSessionId=Vn.sessionId;jn.meta.dialog=new Dialog(dialogOpeningParams(Vn.params),(dialogAction)=>this.send(`Page.handleJavaScriptDialog`,dialogAction,dialogSessionId))}let dialog=jn.meta.dialog,emitted=this.#l.emit(xn,jn).catch((jn)=>{console.warn(`[${this.logId}] CDP event listener failed for ${xn}`,jn)});dialog&&emitted.then(()=>answerWithPolicy(dialog,this.#dialogPolicy,dialogPolicyParams(Vn.params))).catch(()=>{})}}}}}function createSessionManagerClass(){return class SessionManager{#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)}}}function createPageConsoleClass(){return class PageConsole{#e;constructor(xn){this.#e=xn}async logs(xn={}){return await this.#e.evaluate((xn)=>window.__omowrightConsole?.drain(xn)??[],xn)}async clear(){await this.#e.evaluate(`(window).__omowrightConsole?.clear()`)}}}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=createBrowserCdpCommandErrorClass(),CdpClient=createCdpClientClass()});var SessionManager;var init_session_manager=__esmMin(()=>{init_client$6(),SessionManager=createSessionManagerClass()});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(){
97
97
  if(window.__omowrightConsole)return;
98
98
  var logs=[];
99
99
  var orig={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug};
@@ -710,7 +710,7 @@ ${qn.join(`
710
710
  }
711
711
  this.dispatchEvent(new DragEvent('dragend', { bubbles: true, cancelable: true, dataTransfer }));
712
712
  delete globalThis.__omowrightDragDataTransfer;
713
- }`).catch(()=>{}))}function createOmOFrameClass(){return class xn{#e;frameId;constructor(xn,jn){this.#e=xn,this.frameId=jn}async resolveFrameId(){return this.frameId}label(){let xn=this.#t();return`frame ${xn.name||xn.url||xn.frameId}`}locator(xn,jn={}){return new Locator(this.#e,xn,this).filter(jn)}getByRole(xn,jn={}){return this.locator(Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return this.locator(`internal:label:/${xn.source.replaceAll(">>",">\\x3e")}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return this.locator(`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(xn){return new FrameLocator(this.#e,this,xn)}async evaluate(xn,jn){return await this.#e.evaluateInFrame(this.frameId,xn,jn)}async $$eval(xn,jn,Vn){return await this.locator(xn).evaluateAll(jn,Vn)}url(){return this.#t().url}name(){return this.#t().name}parentFrame(){let jn=this.#t().parentFrameId;return jn?new xn(this.#e,jn):null}#t(){let xn=this.#e.frameManager.getFrame(this.frameId);if(!xn)throw Error(`Frame is no longer available: ${this.frameId}`);return xn}}}function createFrameLocatorClass(){return class xn{#e;#t;#n;constructor(xn,jn,Vn){this.#e=xn,this.#t=jn,this.#n=Vn}async resolveFrameId(){let xn=await this.#t.resolveFrameId(),jn=await new OmOFrame(this.#e,xn).locator(this.#n).elementHandle().then((xn)=>xn.contentFrame());if(!jn)throw Error(`Frame locator "${this.#n}" did not resolve to an iframe`);return jn.frameId}label(){return`frameLocator(${this.#n})`}locator(xn,jn={}){return new Locator(this.#e,xn,this).filter(jn)}getByRole(xn,jn={}){return this.locator(Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return this.locator(`internal:label:/${xn.source.replaceAll(">>",">\\x3e")}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return this.locator(`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(jn){return new xn(this.#e,this,jn)}owner(){return new Locator(this.#e,this.#n,this.#t)}first(){return this.nth(0)}nth(jn){return new xn(this.#e,this.#t,`${this.#n}:nth(${jn})`)}last(){return new xn(this.#e,this.#t,`${this.#n}:nth(last)`)}}}var defaultModifierState;var kSetValueInputTypes;var kTypeIntoInputTypes;var ACTIONABILITY_RETRY_DELAYS_MS;var init_actions=__esmMin(()=>{init_context(),init_utils$13(),init_errors$3(),init_types$4(),init_keyboard(),init_wait(),defaultModifierState=new ModifierState,kSetValueInputTypes=[`color`,`date`,`datetime-local`,`month`,`range`,`time`,`week`],kTypeIntoInputTypes=[``,`email`,`number`,`password`,`search`,`tel`,`text`,`url`],ACTIONABILITY_RETRY_DELAYS_MS=[0,100,200]});var frame_exports=__exportAll({OmOFrame:()=>OmOFrame,FrameLocator:()=>FrameLocator});var OmOFrame;var FrameLocator;var init_frame=__esmMin(()=>{init_locator(),OmOFrame=createOmOFrameClass(),FrameLocator=createFrameLocatorClass()});function parseBackendNodeSelector(xn){if(!xn.startsWith(BACKEND_NODE_SELECTOR_PREFIX))return null;let jn=xn.slice(25),Vn=jn.indexOf(`:`);if(Vn<=0)throw Error(`Invalid backend node selector: ${xn}`);let qn=jn.slice(0,Vn),Jn=Number(jn.slice(Vn+1));if(!Number.isInteger(Jn)||Jn<=0)throw Error(`Invalid backend node selector: ${xn}`);return{frameId:qn,backendNodeId:Jn}}function createBackendNodeLocatorSelector(xn,jn){return`${BACKEND_NODE_SELECTOR_PREFIX}${xn}:${jn}`}function isLocatorResolutionMiss(xn){return xn instanceof RefStaleError?true:xn instanceof Error?xn.message.startsWith(`Selector "`)||xn.message.startsWith(`Role selector not found: `):false}function createLocatorClass(){return class xn{#e;#t;#n;#composition;constructor(xn,jn,Vn,composition){if(typeof jn!=`string`||jn.trim().length===0)throw Error(`Locator selector must be a non-empty string. Take a fresh snapshot and verify the ref exists.`);this.#e=xn,this.#n=Vn;let qn=jn.trim();this.#t=qn.replace(REF_SELECTOR_ALIAS_PATTERN,`$1`);this.#composition=composition;for(const name of Object.getOwnPropertyNames(Object.getPrototypeOf(xn))){if(name.startsWith(`getBy`)&&typeof Reflect.get(xn,name)===`function`)Reflect.set(this,name,(...args)=>{const child=Reflect.apply(Reflect.get(xn,name),xn,args);return this.locator(this.#selectorOf(child))})}}#selectorOf(child){if(typeof child==`object`&&child!==null&&#t in child)return child.#t;throw new TypeError(`Cannot read private member #t from an object whose class did not declare it`)}static createRoleSelector(xn,jn={}){let Vn=`role:${xn}`,qn=(xn,jn)=>{Vn+=`[${xn}=${jn}]`};if(jn.checked!==undefined&&qn(`checked`,String(jn.checked)),jn.disabled!==undefined&&qn(`disabled`,String(jn.disabled)),jn.expanded!==undefined&&qn(`expanded`,String(jn.expanded)),jn.includeHidden!==undefined&&qn(`include-hidden`,String(jn.includeHidden)),jn.level!==undefined&&qn(`level`,String(jn.level)),jn.pressed!==undefined&&qn(`pressed`,String(jn.pressed)),jn.selected!==undefined&&qn(`selected`,String(jn.selected)),jn.name!==undefined){let xn=jn.name;if(isRegExpValue(xn)){let jn=xn;qn(`name-regex`,encodeURIComponent(jn.source)),jn.flags&&qn(`name-regex-flags`,encodeURIComponent(jn.flags))}else qn(jn.exact?`name`:`name*`,encodeURIComponent(String(xn)))}return Vn}async#r(){if(this.#composition){const nodes=await this.#collect();if(!nodes.length)throw Error(`Selector "${this.#t}" not found`);return definedOrThrow(nodes[0])}let xn=parseBackendNodeSelector(this.#t);return xn?await this.#o(xn):isRef2(this.#t)?await this.#a(this.#t):isRoleSelector(this.#t)?await this.#l(this.#t):await this.#c(this.#t)}async#i(xn){try{let jn=await this.#r();if(xn===`attached`)return true;if(xn===`detached`)return false;let Vn=await isVisibleElement(this.#e,jn);return xn===`visible`?Vn:!Vn}catch(jn){if(!isLocatorResolutionMiss(jn))throw jn;return xn===`detached`||xn===`hidden`}}async click(xn){let jn=await this.#r();await clickElement(this.#e,jn,xn,this.#e.modifierState)}async fill(xn){let jn=await this.#r();await fillElement(this.#e,jn,xn)}async selectOption(xn){let jn=await this.#r();return await selectOptionElement(this.#e,jn,xn)}async check(xn){let jn=await this.#r();await checkElement(this.#e,jn,xn?.checked)}async scrollIntoViewIfNeeded(){let xn=await this.#r();await scrollIntoViewElement(this.#e,xn)}async press(xn){let jn=await this.#r();await pressElement(this.#e,jn,xn,this.#e.keyboard)}async pressSequentially(xn,jn={}){let Vn=await this.#r();await pressSequentiallyElement(this.#e,Vn,xn,jn.delay,this.#e.keyboard)}async hover(){let xn=await this.#r();await hoverElement(this.#e,xn)}async dblclick(xn){let jn=await this.#r();await clickElement(this.#e,jn,{...xn,dblClick:true},this.#e.modifierState)}async focus(){let xn=await this.#r();await focusResolvedElement(this.#e,xn)}async blur(){let xn=await this.#r();await blurResolvedElement(this.#e,xn)}async tap(){let xn=await this.#r();await tapElement(this.#e,xn)}async clear(){await this.fill(``)}async type(xn,jn={}){await this.pressSequentially(xn,jn)}async uncheck(){let xn=await this.#r();await checkElement(this.#e,xn,false)}async setChecked(xn){if(xn){await this.check();return}await this.uncheck()}async setInputFiles(xn){let jn=await this.#r();if(xn===null){await setInputFilesElement(this.#e,jn,[]);return}if(typeof xn==`string`){let Vn=await this.#e.browser.ensurePath(xn,`read`,`locator.setInputFiles`);await setInputFilesElement(this.#e,jn,[Vn]);return}if(xn.length===0){await setInputFilesElement(this.#e,jn,[]);return}if(startsWithFilePath(xn)){let Vn=await Promise.all(xn.map((xn)=>this.#e.browser.ensurePath(xn,`read`,`locator.setInputFiles`)));await setInputFilesElement(this.#e,jn,Vn);return}await setInputFilesElement(this.#e,jn,xn.map((xn)=>({name:xn.name,mimeType:xn.mimeType,base64:Buffer.from(xn.buffer).toString(`base64`)})))}async dragTo(xn,jn={}){let Vn=await this.#r(),qn=await xn.#r();await dragToElement(this.#e,Vn,qn,jn)}async evaluate(xn,jn){let Vn=await this.#r(),qn=typeof xn==`function`?xn.toString():xn;return await evaluateOnElement(this.#e,Vn,qn,jn)}async evaluateAll(xn,jn){if(!this.#composition&&isRoleSelector(this.#t))throw Error(`locator.evaluateAll() does not support role selectors yet; use a CSS selector.`);let Vn=this.#composition?[]:isRef2(this.#t)||parseBackendNodeSelector(this.#t)?[this]:await this.all(),qn=this.#composition?await this.#collect():await Promise.all(Vn.map((xn)=>xn.#r())),Jn=qn[0]??await this.#s();if(qn.some((xn)=>xn.contextId!==Jn.contextId))throw Error(`locator.evaluateAll() cannot pass elements from multiple frames to one page function.`);let Yn=typeof xn==`function`?xn.toString():xn,Zn=[{value:jn},...qn.map((xn)=>({objectId:xn.objectId}))],{result:Qn,exceptionDetails:ei}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`async function(arg, ...elements) {
713
+ }`).catch(()=>{}))}function createOmOFrameClass(){return class xn{#e;frameId;constructor(xn,jn){this.#e=xn,this.frameId=jn}async resolveFrameId(){return this.frameId}label(){let xn=this.#t();return`frame ${xn.name||xn.url||xn.frameId}`}locator(xn,jn={}){return new Locator(this.#e,xn,this).filter(jn)}getByRole(xn,jn={}){return this.locator(Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return this.locator(`internal:label:/${xn.source.replaceAll(">>",">\\x3e")}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return this.locator(`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(xn){return new FrameLocator(this.#e,this,xn)}async evaluate(xn,jn){return await this.#e.evaluateInFrame(this.frameId,xn,jn)}async $$eval(xn,jn,Vn){return await this.locator(xn).evaluateAll(jn,Vn)}url(){return this.#t().url}name(){return this.#t().name}parentFrame(){let jn=this.#t().parentFrameId;return jn?new xn(this.#e,jn):null}#t(){let xn=this.#e.frameManager.getFrame(this.frameId);if(!xn)throw Error(`Frame is no longer available: ${this.frameId}`);return xn}}}function createFrameLocatorClass(){return class xn{#e;#t;#n;constructor(xn,jn,Vn){this.#e=xn,this.#t=jn,this.#n=Vn}async resolveFrameId(){let xn=await this.#t.resolveFrameId(),jn=await new OmOFrame(this.#e,xn).locator(this.#n).elementHandle().then((xn)=>xn.contentFrame());if(!jn)throw Error(`Frame locator "${this.#n}" did not resolve to an iframe`);return jn.frameId}label(){return`frameLocator(${this.#n})`}locator(xn,jn={}){return new Locator(this.#e,xn,this).filter(jn)}getByRole(xn,jn={}){return this.locator(Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return this.locator(`internal:label:/${xn.source.replaceAll(">>",">\\x3e")}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return this.locator(`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return this.locator(jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(jn){return new xn(this.#e,this,jn)}owner(){return new Locator(this.#e,this.#n,this.#t)}first(){return this.nth(0)}nth(jn){return new xn(this.#e,this.#t,`${this.#n}:nth(${jn})`)}last(){return new xn(this.#e,this.#t,`${this.#n}:nth(last)`)}}}var defaultModifierState;var kSetValueInputTypes;var kTypeIntoInputTypes;var ACTIONABILITY_RETRY_DELAYS_MS;var init_actions=__esmMin(()=>{init_context(),init_utils$13(),init_errors$3(),init_types$4(),init_keyboard(),init_wait(),defaultModifierState=new ModifierState,kSetValueInputTypes=[`color`,`date`,`datetime-local`,`month`,`range`,`time`,`week`],kTypeIntoInputTypes=[``,`email`,`number`,`password`,`search`,`tel`,`text`,`url`],ACTIONABILITY_RETRY_DELAYS_MS=[0,100,200]});var frame_exports=__exportAll({OmOFrame:()=>OmOFrame,FrameLocator:()=>FrameLocator});var OmOFrame;var FrameLocator;var init_frame=__esmMin(()=>{init_locator(),OmOFrame=createOmOFrameClass(),FrameLocator=createFrameLocatorClass()});function parseBackendNodeSelector(xn){if(!xn.startsWith(BACKEND_NODE_SELECTOR_PREFIX))return null;let jn=xn.slice(25),Vn=jn.indexOf(`:`);if(Vn<=0)throw Error(`Invalid backend node selector: ${xn}`);let qn=jn.slice(0,Vn),Jn=Number(jn.slice(Vn+1));if(!Number.isInteger(Jn)||Jn<=0)throw Error(`Invalid backend node selector: ${xn}`);return{frameId:qn,backendNodeId:Jn}}function createBackendNodeLocatorSelector(xn,jn){return`${BACKEND_NODE_SELECTOR_PREFIX}${xn}:${jn}`}function isLocatorResolutionMiss(xn){return xn instanceof RefStaleError?true:xn instanceof Error?xn.message.startsWith(`Selector "`)||xn.message.startsWith(`Role selector not found: `):false}function createLocatorClass(){return class xn{#e;#t;#n;#composition;constructor(xn,jn,Vn,composition){if(typeof jn!=`string`||jn.trim().length===0)throw Error(`Locator selector must be a non-empty string. Take a fresh snapshot and verify the ref exists.`);this.#e=xn,this.#n=Vn;let qn=jn.trim();this.#t=qn.replace(REF_SELECTOR_ALIAS_PATTERN,`$1`);this.#composition=composition;for(const name of Object.getOwnPropertyNames(Object.getPrototypeOf(xn))){if(name.startsWith(`getBy`)&&typeof Reflect.get(xn,name)===`function`)Reflect.set(this,name,(...args)=>{const child=Reflect.apply(Reflect.get(xn,name),xn,args);return this.locator(this.#selectorOf(child))})}}#selectorOf(child){if(typeof child==`object`&&child!==null&&#t in child)return child.#t;throw new TypeError(`Cannot read private member #t from an object whose class did not declare it`)}static createRoleSelector(xn,jn={}){let Vn=`role:${xn}`,qn=(xn,jn)=>{Vn+=`[${xn}=${jn}]`};if(jn.checked!==undefined&&qn(`checked`,String(jn.checked)),jn.disabled!==undefined&&qn(`disabled`,String(jn.disabled)),jn.expanded!==undefined&&qn(`expanded`,String(jn.expanded)),jn.includeHidden!==undefined&&qn(`include-hidden`,String(jn.includeHidden)),jn.level!==undefined&&qn(`level`,String(jn.level)),jn.pressed!==undefined&&qn(`pressed`,String(jn.pressed)),jn.selected!==undefined&&qn(`selected`,String(jn.selected)),jn.name!==undefined){let xn=jn.name;if(isRegExpValue(xn)){let jn=xn;qn(`name-regex`,encodeURIComponent(jn.source)),jn.flags&&qn(`name-regex-flags`,encodeURIComponent(jn.flags))}else qn(jn.exact?`name`:`name*`,encodeURIComponent(String(xn)))}return Vn}async#r(){if(this.#composition){const nodes=await this.#collect();if(!nodes.length)throw Error(`Selector "${this.#t}" not found`);return definedOrThrow(nodes[0])}let xn=parseBackendNodeSelector(this.#t);return xn?await this.#o(xn):isRef2(this.#t)?await this.#a(this.#t):isRoleSelector(this.#t)?await this.#l(this.#t):await this.#c(this.#t)}async#i(xn){try{let jn=await this.#r();if(xn===`attached`)return true;if(xn===`detached`)return false;let Vn=await isVisibleElement(this.#e,jn);return xn===`visible`?Vn:!Vn}catch(jn){if(!isLocatorResolutionMiss(jn))throw jn;return xn===`detached`||xn===`hidden`}}async click(xn){let jn=await this.#r();await clickElement(this.#e,jn,xn,this.#e.modifierState)}async fill(xn){try{let jn=await this.#r();await fillElement(this.#e,jn,xn)}catch(jn){throw redactValue(jn,xn)}}async selectOption(xn){let jn=await this.#r();return await selectOptionElement(this.#e,jn,xn)}async check(xn){let jn=await this.#r();await checkElement(this.#e,jn,xn?.checked)}async scrollIntoViewIfNeeded(){let xn=await this.#r();await scrollIntoViewElement(this.#e,xn)}async press(xn){let jn=await this.#r();await pressElement(this.#e,jn,xn,this.#e.keyboard)}async pressSequentially(xn,jn={}){try{let Vn=await this.#r();await pressSequentiallyElement(this.#e,Vn,xn,jn.delay,this.#e.keyboard)}catch(Vn){throw redactValue(Vn,xn)}}async hover(){let xn=await this.#r();await hoverElement(this.#e,xn)}async dblclick(xn){let jn=await this.#r();await clickElement(this.#e,jn,{...xn,dblClick:true},this.#e.modifierState)}async focus(){let xn=await this.#r();await focusResolvedElement(this.#e,xn)}async blur(){let xn=await this.#r();await blurResolvedElement(this.#e,xn)}async tap(){let xn=await this.#r();await tapElement(this.#e,xn)}async clear(){await this.fill(``)}async type(xn,jn={}){await this.pressSequentially(xn,jn)}async uncheck(){let xn=await this.#r();await checkElement(this.#e,xn,false)}async setChecked(xn){if(xn){await this.check();return}await this.uncheck()}async setInputFiles(xn){let jn=await this.#r();if(xn===null){await setInputFilesElement(this.#e,jn,[]);return}if(typeof xn==`string`){let Vn=await this.#e.browser.ensurePath(xn,`read`,`locator.setInputFiles`);await setInputFilesElement(this.#e,jn,[Vn]);return}if(xn.length===0){await setInputFilesElement(this.#e,jn,[]);return}if(startsWithFilePath(xn)){let Vn=await Promise.all(xn.map((xn)=>this.#e.browser.ensurePath(xn,`read`,`locator.setInputFiles`)));await setInputFilesElement(this.#e,jn,Vn);return}await setInputFilesElement(this.#e,jn,xn.map((xn)=>({name:xn.name,mimeType:xn.mimeType,base64:Buffer.from(xn.buffer).toString(`base64`)})))}async dragTo(xn,jn={}){let Vn=await this.#r(),qn=await xn.#r();await dragToElement(this.#e,Vn,qn,jn)}async evaluate(xn,jn){let Vn=await this.#r(),qn=typeof xn==`function`?xn.toString():xn;return await evaluateOnElement(this.#e,Vn,qn,jn)}async evaluateAll(xn,jn){if(!this.#composition&&isRoleSelector(this.#t))throw Error(`locator.evaluateAll() does not support role selectors yet; use a CSS selector.`);let Vn=this.#composition?[]:isRef2(this.#t)||parseBackendNodeSelector(this.#t)?[this]:await this.all(),qn=this.#composition?await this.#collect():await Promise.all(Vn.map((xn)=>xn.#r())),Jn=qn[0]??await this.#s();if(qn.some((xn)=>xn.contextId!==Jn.contextId))throw Error(`locator.evaluateAll() cannot pass elements from multiple frames to one page function.`);let Yn=typeof xn==`function`?xn.toString():xn,Zn=[{value:jn},...qn.map((xn)=>({objectId:xn.objectId}))],{result:Qn,exceptionDetails:ei}=await this.#e.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`async function(arg, ...elements) {
714
714
  var __name = (target) => target;
715
715
  const pageFunction = (${Yn});
716
716
  if (typeof pageFunction !== 'function') {
@@ -1322,8 +1322,8 @@ ${qn.join(`
1322
1322
  }`,arguments:[{value:ai}],executionContextId:ii,returnByValue:true,awaitPromise:false,userGesture:false},jn.getFrame(qn)?.sessionId),Yn=pageResult(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) {
1323
1323
  return globalThis.__omowright.elementRegistry.get(ref);
1324
1324
  }`,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].toSorted((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 snapshotResult(jn,Vn,{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 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 init_annotate_screenshot=__esmMin(()=>{});var AI_TAB_STABLE_VIEWPORT;var init_browser=__esmMin(()=>{init_context(),init_cdp(),init_directory(),init_event_bus(),init_extension_bridge(),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}});function errorMessageOf(error){const message=readProperty(error,`message`);return message===undefined?undefined:String(message)}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(path2.dirname(xn),{recursive:true})}async function readProcessStderr(xn){return xn.stderr}function createFfmpegVideoRecorderClass(){return class FfmpegVideoRecorder{#e;#t;#n=0;#r=false;#i=null;#a=Promise.resolve();#o=0;#s=[];#failure=null;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`]})}async ready(){await this.#t.ready;if(this.#t.error){await this.dispose();throw new VideoRecordingError(this.#t.error.message,{cause:this.#t.error})}}async dispose(){await disposeProcess(this.#t)}writeFrame(xn,jn){if(this.#r||this.#failure)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()).catch(async(error)=>{this.#failure??=error;await this.dispose()})}this.#i={buffer:xn,frameNumber:Vn,timestamp:jn},this.#o=Date.now()}async stop(xn){try{if(this.#r)return;if(this.#failure)throw this.#failure;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.#failure)throw this.#failure;if(!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,ENCODER_EXIT_TIMEOUT_MS));if(Jn!==0){let xn=await readProcessStderr(this.#t);throw Error(xn.trim()||`ffmpeg exited with code ${Jn}`)}}catch(error){throw new VideoRecordingError(errorMessageOf(error),{cause:error})}finally{await this.dispose()}}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))}}}}}function createOmOVideoClass(){return class OmOVideo{#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);await ei.ready();let{promise:ti,resolve:ni}=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:(error)=>ni({error}),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,await ei.dispose(),ni({error: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({path:qn})}catch(xn){throw this.#n=null,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);let result=await this.#t.completion;if(result.error)throw result.error;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(()=>{})})}}}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=createFfmpegVideoRecorderClass(),OmOVideo=createOmOVideoClass()});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}function createOmOPageClass(){return class OmOPage{#networkCount=0;#networkOff=null;#closeRequested=false;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;#runtimeListeners=0;#runtimeEpoch=0;#runtimeReady=Promise.resolve();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(){this.#networkCount>0&&(this.#networkOff=subscribePageNetworkEvents(this));this.#a.push(subscribeConsoleEvents(this),subscribePageErrors(this));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.#a.push(this.cdp.on(`Page.javascriptDialogOpening`,(xn,Vn)=>{if(Vn.sessionId===this.#n)return this.events.emit(`dialog`,Vn.dialog??new Dialog(xn,(dialogAction)=>this.cdp.send(`Page.handleJavaScriptDialog`,dialogAction,this.#n))).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.listenerCount(`popup`)||this.browser.resolvePopup(xn).then((xn)=>xn&&this.events.emit(`popup`,xn)).catch((xn)=>this.events.emit(`popupError`,xn).catch(jn))})),this.#u(`Inspector.targetCrashed`,()=>{this.events.emit(`crash`).catch(jn)}),this.#a.push(this.cdp.on(`Target.targetDestroyed`,(xn)=>{xn.targetId===this.targetId&&this.dispose().catch(jn)}),this.cdp.on(`Target.detachedFromTarget`,(xn)=>{xn.targetId===this.targetId&&this.cdp.send(`Target.getTargetInfo`,{targetId:this.targetId}).then(()=>{},()=>this.dispose()).catch(jn)})),this.frameManager.onSessionInitialized=(xn)=>{this.#c>0&&this.#p(true,[xn]),this.#runtimeListeners>0&&this.#setRuntimeCapture(true,[xn])}}#u(xn,jn){this.#a.push(this.cdp.on(xn,(xn,Vn)=>{Vn.sessionId===this.#n&&jn(xn)}))}on(xn,jn){assertPageEvent(xn);let Vn=this.#e.get(xn)??new WeakMap,qn=this.events.on(xn,({data:xn})=>jn(xn)),active=true,isNetwork=xn===`request`||xn===`response`;if(isNetwork&&this.#networkCount++===0)this.#networkOff=subscribePageNetworkEvents(this);xn===`filechooser`&&this.#m();RUNTIME_PAGE_EVENTS.has(xn)&&this.#addRuntimeListener();const off=()=>{if(!active)return;active=false;qn();Vn.get(jn)===off&&Vn.delete(jn);if(isNetwork&&--this.#networkCount===0){this.#networkOff?.();this.#networkOff=null}xn===`filechooser`&&this.#h();RUNTIME_PAGE_EVENTS.has(xn)&&this.#removeRuntimeListener()};Vn.set(jn,off);this.#e.set(xn,Vn);return off}off(xn,jn){assertPageEvent(xn);this.#e.get(xn)?.get(jn)?.()}waitForResponse(match,options={}){return this.waitForEvent(`response`,{...options,predicate:networkPredicate(match)})}waitForRequest(match,options={}){return this.waitForEvent(`request`,{...options,predicate:networkPredicate(match)})}async waitForEvent(xn,jn={}){if(typeof jn===`function`)jn={predicate:jn};assertPageEvent(xn);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:path2.basename(xn.absolutePath),url:this.url()}))}).catch(()=>{})})}return await new Promise((qn,Jn)=>{let Yn=false,Zn=null,ri=()=>{},Qn=()=>{ni(),ri(),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))))}})()});xn===`popup`&&(ri=this.events.on(`popupError`,({data:xn})=>ei(()=>Jn(xn))))})}#d(){this.#networkOff?.();this.#networkOff=null;disposeNetwork(this);for(let xn of this.#a)xn();this.#a=[]}async dispose(){this.#s||(this.#s=true,await this.#o?.stop().catch(()=>{}),++this.#runtimeEpoch,this.#runtimeListeners>0&&await this.#setRuntimeCapture(false),this.#runtimeListeners=0,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.#runtimeEpoch,this.#d(),this.#l(),this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??this.#r,this.#c>0&&this.#p(true),this.#runtimeListeners>0&&this.#setRuntimeCapture(true,undefined,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))}#setRuntimeCapture(enabled,sessions=this.#f(),clearEntries=false){const epoch=this.#runtimeEpoch;return this.#runtimeReady=this.#runtimeReady.then(()=>withoutReplContext(async()=>{await Promise.allSettled(sessions.map(async(session)=>{if(enabled){if(clearEntries)await this.cdp.send(`Runtime.discardConsoleEntries`,undefined,session).catch(()=>{});if(epoch!==this.#runtimeEpoch||this.#runtimeListeners===0)return}await this.cdp.send(enabled||hasPageBindings(this)?`Runtime.enable`:`Runtime.disable`,undefined,session)}))}))}#addRuntimeListener(){this.#runtimeListeners+=1,this.#runtimeListeners===1&&(++this.#runtimeEpoch,this.#setRuntimeCapture(true,undefined,true))}#removeRuntimeListener(){this.#runtimeListeners!==0&&(--this.#runtimeListeners,this.#runtimeListeners===0&&(++this.#runtimeEpoch,this.#setRuntimeCapture(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(this.#runtimeListeners>0)await this.#runtimeReady;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={}){await networkReady(this);const releaseNetwork=[`interactive`,`stable`,`networkidle`].includes(jn.waitUntil??`interactive`)?acquireNetwork(this.cdp,await this.resolveSessionId()):null;const documents=trackDocumentResponses(this,this.frameManager.mainFrameId);const readinessController=new AbortController;let readiness;try{await releaseNetwork?.ready;await documents.ready;let Vn=jn.waitUntil??`interactive`,qn=await this.resolveSessionId(this.#n),Jn=()=>{},Yn=Vn===`commit`?null:Vn===`interactive`||Vn===`stable`?readiness=waitForNavigationReadiness(this,Vn,DEFAULT_WAIT_TIMEOUT_MS,readinessController.signal).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)});Yn?.catch(()=>{});const Zn=await this.cdp.send(`Page.navigate`,{url:xn},qn);if(Zn.errorText)throw Error(Zn.errorText);this.#r=(await this.cdp.send(`Page.getFrameTree`,{},qn)).frameTree.frame.url;if(Vn===`domcontentloaded`&&Yn){if(!Zn.loaderId){Jn(),await this.#v(`Timed out waiting for "${Vn}" after goto`);return null}try{await Yn}catch(xn){if(!await this.#_())throw xn}return documents.response(Zn.loaderId)}Yn&&await Yn;return documents.response(Zn.loaderId)}finally{readinessController.abort();await readiness?.catch(()=>{});documents.dispose(),releaseNetwork?.()}}async goBack(){return await this.#historyStep(-1)}async goForward(){return await this.#historyStep(1)}async#historyStep(delta){let history=await this._sendToTarget(`Page.getNavigationHistory`),entry=history.entries[history.currentIndex+delta];if(!entry)return null;return await this.#navigationResponse(()=>this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:entry.id}))}async reload(){return await this.#navigationResponse(()=>this._sendToTarget(`Page.reload`))}async waitForTimeout(timeout){await sleep$12(timeout)}async setContent(html,options={}){const waitUntil=options.waitUntil??`load`,timeout=options.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(![`load`,`domcontentloaded`,`networkidle`,`commit`].includes(waitUntil))throw Error(`page.setContent: waitUntil must be one of load, domcontentloaded, networkidle, commit; got "${waitUntil}"`);let timer;const deadline=new Promise((_,reject)=>{if(timeout>0)timer=setTimeout(()=>reject(Error(`page.setContent: Timeout ${timeout}ms exceeded waiting for "${waitUntil}"`)),timeout)});const idle=waitUntil===`networkidle`?this.#S(timeout>0?timeout:2147483647):null;idle?.catch(()=>{});try{await Promise.race([deadline,(async()=>{await this.evaluate(({html,waitUntil})=>{document.open();const ready=waitUntil===`commit`?null:new Promise((resolve)=>waitUntil===`domcontentloaded`?document.addEventListener(`DOMContentLoaded`,()=>resolve(),{once:true}):window.addEventListener(`load`,()=>resolve(),{once:true}));document.write(html);document.close();return ready},{html,waitUntil});await idle})()])}finally{clearTimeout(timer)}}async waitForLoadState(state=`interactive`,options=DEFAULT_WAIT_TIMEOUT_MS){let timeout=typeof options==`number`?options:options?.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(state===`interactive`||state===`stable`){await waitForNavigationReadiness(this,state,timeout);return}if(state===`commit`)return;if(state===`networkidle`){await this.#S(timeout);return}if(state!==`load`&&state!==`domcontentloaded`)throw Error(`waitForLoadState: unsupported state "${state}"; expected load, domcontentloaded, networkidle, commit, interactive or stable`);let sessionId=await this.resolveSessionId(this.#n),reached=state===`load`?(xn)=>xn===`complete`:(xn)=>xn!==`loading`,unsubscribe=()=>{},timer;try{await new Promise((resolve,reject)=>{timer=setTimeout(()=>reject(Error(`Timed out waiting for load state "${state}"`)),timeout),unsubscribe=this.cdp.on(state===`load`?`Page.loadEventFired`:`Page.domContentEventFired`,(xn,meta)=>{meta.sessionId===sessionId&&resolve()}),this.evaluate(`document.readyState`).then((xn)=>{reached(xn)&&resolve()},()=>{})})}finally{clearTimeout(timer),unsubscribe()}}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(match,options={}){let timeout=options.timeout??DEFAULT_WAIT_TIMEOUT_MS,start=Date.now();for(;Date.now()-start<timeout;){if(await urlMatches(this.url(),match)){options.waitUntil&&await this.waitForLoadState(options.waitUntil,{timeout:Math.max(0,timeout-(Date.now()-start))});return}await sleep$12(100)}throw Error(`Timed out waiting for URL match: ${String(match)}`)}async waitForFunction(xn,jn,Vn){let qn=Vn?.polling??`raf`,Jn=Vn?.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(qn!==`raf`&&!(typeof qn==`number`&&Number.isFinite(qn)&&qn>0))throw Error(`page.waitForFunction: polling must be "raf" or a positive number of milliseconds`);if(!(typeof Jn==`number`&&Number.isFinite(Jn)&&Jn>=0))throw Error(`page.waitForFunction: timeout must be a non-negative number of milliseconds (0 waits forever)`);let Yn=typeof xn==`function`?xn.toString():String(xn),Zn=Jn>0?Date.now()+Jn:1/0,Qn=`async function(arg, polling, remainingMs) { var __name = (t) => t; const predicate = (a) => { const value = (${Yn}); return typeof value === 'function' ? value(a) : value; }; const start = performance.now(); const next = () => new Promise((resolve) => { if (polling !== 'raf') { setTimeout(resolve, polling); return; } let frame; const fallback = setTimeout(() => { resolve(); cancelAnimationFrame(frame); }, ${WAIT_FOR_FUNCTION_RAF_FALLBACK_MS}); frame = requestAnimationFrame(() => { clearTimeout(fallback); resolve(); }); }); for (;;) { const value = await predicate(arg); if (value) return { done: true, value }; if (remainingMs > 0 && performance.now() - start >= remainingMs) return { done: false }; await next(); } }`,Cn,$n=new Promise((jn,qn)=>{Cn=this.events.on(`close`,()=>qn(Error(`page.waitForFunction: the page closed while waiting`)))});$n.catch(()=>{});try{for(;;){let xn=Zn-Date.now();if(xn<=0)throw new WaitForFunctionTimeoutError(Yn,Jn);let Vn,Xn=new Promise((jn,qn)=>{Number.isFinite(xn)&&(Vn=setTimeout(()=>qn(new WaitForFunctionTimeoutError(Yn,Jn)),xn))}),ei=(async()=>{let Vn=await this.#x(),{result:Jn,exceptionDetails:Zn}=await this._sendToTarget(`Runtime.callFunctionOn`,{objectId:Vn,functionDeclaration:Qn,arguments:[{value:jn},{value:qn},{value:Number.isFinite(xn)?xn:0}],returnByValue:true,awaitPromise:true},{timeoutMs:Number.isFinite(xn)?xn+WAIT_FOR_FUNCTION_CALL_MARGIN_MS:0});if(Zn)throw Error(formatRuntimeException(Zn,`page.waitForFunction: the page function threw`));return Jn.value})();ei.catch(()=>{});try{let xn=await Promise.race([ei,Xn,$n]);if(readOptionalProperty(xn,`done`))return readProperty(xn,`value`)}catch(xn){if(isUnserializableResultError(xn))return true;if(this.#s||this.#closeRequested&&isSessionDetachedError(xn))throw Error(`page.waitForFunction: the page closed while waiting`);if(!isNavigationInterruptedError(xn))throw xn;await Promise.race([sleep$12(20),$n])}finally{clearTimeout(Vn)}}}finally{definedOrThrow(Cn)()}}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.replaceAll(">>",">\\x3e")}/${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)}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)}
1325
- 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=path2.join(jn,path2.basename(xn.path));await mkdir(path2.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(path2.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(path2.dirname(jn),{recursive:true}).catch(()=>{}),await writeFile(jn,Jn)),Jn}async close(xn={}){this.#closeRequested=true;for(const sessionId of this.#f())this.cdp.closeSession?.(sessionId);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){let jn=await this.resolveSessionId(this.#n),releaseNetwork=acquireNetwork(this.cdp,jn);await releaseNetwork.ready;await new Promise((Vn,qn)=>{let Jn=new Set,Yn=null,Zn=null,Qn=()=>{ti(),ri(),ii(),releaseNetwork(),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#navigationResponse(trigger){let frameId=this.frameManager.mainFrameId,documents=trackDocumentResponses(this,frameId),offs=[],timer;try{await documents.ready;let sessionId=await this.resolveSessionId(this.#n),deadline=new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error(`Timed out waiting for navigation`)),DEFAULT_WAIT_TIMEOUT_MS)}),committed=new Promise((resolve)=>{offs.push(this.cdp.on(`Page.frameNavigated`,(params,meta)=>{meta.sessionId===sessionId&&!params.frame.parentId&&resolve(params.frame.loaderId)}),this.cdp.on(`Page.navigatedWithinDocument`,(params,meta)=>{meta.sessionId===sessionId&&params.frameId===frameId&&resolve(null)}))});deadline.catch(()=>{});let[,loaderId]=await Promise.race([Promise.all([trigger(),committed]),deadline]);if(!loaderId)return null;await Promise.race([this.cdp.send(`Page.getFrameTree`,undefined,sessionId),deadline]);return documents.response(loaderId)}finally{clearTimeout(timer);for(let off of offs)off();documents.dispose()}}async _sendToTarget(xn,jn,Vn={}){await networkReady(this);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}}}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=createOmOPageClass()});init_client$6();init_session_manager();init_frame_manager();init_page();Object.assign(initialized(()=>OmOPage).prototype,{addInitScript,exposeFunction,exposeBinding,setExtraHTTPHeaders,setViewportSize,emulateMedia});var testIdAttributeName="data-testid";var selectors={setTestIdAttribute(attributeName){if(typeof attributeName!=="string"||!/^[^\s"'>/=[\]]+$/.test(attributeName)){throw new TypeError(`selectors.setTestIdAttribute: invalid attribute name ${JSON.stringify(attributeName)}`)}testIdAttributeName=attributeName}};function isRegExpValue(value){return Object.prototype.toString.call(value)==="[object RegExp]"}function attributeSelector(name,value,exact){if(isRegExpValue(value))return`internal:attr=[${name}=/${value.source.replaceAll(">>",">\\x3e")}/${value.flags}]`;return`internal:attr=[${name}=${JSON.stringify(String(value)).replaceAll(">","\\u003e")}${exact?"s":"i"}]`}class AttributeLocatorGetters{getByAltText(text,options={}){return this.locator(attributeSelector("alt",text,options.exact))}getByPlaceholder(text,options={}){return this.locator(attributeSelector("placeholder",text,options.exact))}getByTestId(testId){return this.locator(attributeSelector(testIdAttributeName,testId,true))}getByTitle(text,options={}){return this.locator(attributeSelector("title",text,options.exact))}}for(const Container of[initialized(()=>OmOPage),initialized(()=>OmOFrame),initialized(()=>FrameLocator)]){for(const name of Object.getOwnPropertyNames(AttributeLocatorGetters.prototype)){if(name!=="constructor")Object.defineProperty(Container.prototype,name,definedOrThrow(Object.getOwnPropertyDescriptor(AttributeLocatorGetters.prototype,name)))}}initialized(()=>OmOPage).prototype.route=function(url,handler,options){return pageRoute(this,url,handler,options)};initialized(()=>OmOPage).prototype.unroute=function(url,handler){return pageUnroute(this,url,handler)};initialized(()=>OmOPage).prototype.unrouteAll=function(){return pageUnrouteAll(this)};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 readOnly(what,get){return{get,set:refuse(what),defineProperty:refuse(what),deleteProperty:refuse(what)}}function lease(key,entry,connection){let closed;const overlay=Object.create(null);const subscriptions=new Set;const transportSubscriptions=new Set;const unsubscribeAll=(set)=>{for(const unsubscribe of[...set])unsubscribe()};const ensureOpen=(property)=>{if(closed&&typeof property==="string"&&property!=="then"){throw new Error("this browser connection handle was closed")}};const close=()=>{if(!closed){unsubscribeAll(subscriptions);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,...sets)=>(...args)=>{const remove=subscribe(...args);let removed=false;const unsubscribe=()=>{if(removed)return;removed=true;for(const set of sets)set.delete(unsubscribe);remove()};for(const set of sets)set.add(unsubscribe);return unsubscribe};const client=connection.cdp;const sharedTransportEvents=client.transportEvents;if(sharedTransportEvents===undefined)throw new TypeError("Cannot create proxy with a non-object as target or handler");const transportEvents=new Proxy(sharedTransportEvents,readOnly("the shared transport events",(target,property)=>{ensureOpen(property);if(property==="on"){const on=(name,listener)=>target.on(name,(event)=>listener(event));return tracked(on,subscriptions,transportSubscriptions)}if(property==="clearListeners")return()=>unsubscribeAll(transportSubscriptions);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),subscriptions);if(property==="transportEvents")return transportEvents;return bindTo(target,Reflect.get(target,property,target))}));return new Proxy(connection,{get(target,property){if(property==="close"||property===Symbol.asyncDispose)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(!readProperty(descriptor,"enumerable")||descriptor===undefined||!("value"in descriptor))return false;if(!isPlainData(descriptor.value,path))return false}return true}finally{path.delete(value)}}function frozenCopy(value){if(value===null||typeof value!=="object")return value;let copy;if(Array.isArray(value)){const sparse=[];sparse.length=value.length;copy=sparse}else copy=Object.create(Object.getPrototypeOf(value));for(const key of Object.keys(value)){Object.defineProperty(copy,key,{value:frozenCopy(readProperty(value,key)),enumerable:true})}return Object.freeze(copy)}function openingOptions(snapshot){if(snapshot?.dialogPolicy!=null||snapshot?.client?.dialogPolicy!=null)return snapshot;return Object.freeze({...snapshot,dialogPolicy:Object.freeze({accept:true})})}function canShareConnection(options){return options?.client?.authorizer===undefined&&isPlainData(options)}async function acquireSharedConnection(webSocketDebuggerUrl,options,{open,timeoutMs}){if(!canShareConnection(options))return open(options);const snapshot=frozenCopy(options);let entry=shared.get(webSocketDebuggerUrl);if(entry&&!isDeepStrictEqual(entry.options,snapshot))return open(openingOptions(snapshot));if(!entry){entry={options:snapshot,refs:0,ready:open(openingOptions(snapshot))};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}}var managers=new WeakMap;var CAPABILITY=targetCreationCapability;function optionsKey(options={}){return JSON.stringify({viewport:{...DEFAULT_AGENT_VIEWPORT,...options.viewport},closeTimeoutMs:options.closeTimeoutMs??5000})}class AgentTabManager{#connection;#owned=new Map;#unsubscribers=[];#disposed=false;#closing=new Map;viewport;closeTimeoutMs;ready;constructor(connection,options={}){if(!connection?.cdp)throw new TypeError("createAgentTabs requires a browser connection");this.#connection=connection;this.viewport=Object.freeze({...DEFAULT_AGENT_VIEWPORT,...options.viewport});this.closeTimeoutMs=options.closeTimeoutMs??5000;this.#unsubscribers.push(connection.cdp.on("Target.targetDestroyed",(info)=>this.#destroyed(info?.targetId)));this.#unsubscribers.push(connection.cdp.on("Target.targetCrashed",(info)=>this.#destroyed(info?.targetId)));this.#unsubscribers.push(connection.cdp.transportEvents?.on?.("disconnected",()=>{for(const id of[...this.#owned.keys()])this.#destroyed(id,Error("Browser transport disconnected"))}));this.ready=Promise.resolve(connection.cdp.ensureConnected?.())}async create(url="about:blank",options={}){if(this.#disposed)throw Error("Agent tab manager is disposed");await this.ready;const viewport={...this.viewport,...options.viewport};const result=await this.#connection.cdp.send("Target.createTarget",{url:"about:blank",background:true,newWindow:true,...options.browserContextId?{browserContextId:options.browserContextId}:{}},undefined,{capability:CAPABILITY});const targetId=result.targetId;if(await this.#isHeadless())await this.#connection.cdp.send("Target.activateTarget",{targetId});const tab=await this.adopt(targetId,{viewport});if(tab.page===null)throw new TypeError(`Target ${targetId} is still being adopted`);if(url!=="about:blank")await tab.page.goto(url);return Object.freeze({...tab,page:tab.page})}async adopt(targetId,options={}){if(this.#disposed)throw Error("Agent tab manager is disposed");const existing=this.#owned.get(targetId);if(existing)return this.#public(existing);const viewport={...this.viewport,...options.viewport};const record={targetId,page:null,viewport:Object.freeze({...viewport}),repinQueue:Promise.resolve()};this.#owned.set(targetId,record);try{const page=await this.#connection.attachPage(targetId);record.page=page;await repinViewport(page,record.viewport);record.navigationOff=page.on?.("framenavigated",(event)=>{if(!event.parentFrameId)this.#repin(record)});return this.#public(record,page)}catch(error){await this.#connection.cdp.send("Target.closeTarget",{targetId}).catch(()=>{});throw error}}#public(record,page=record.page){return Object.freeze({targetId:record.targetId,page,viewport:{...record.viewport},close:(options)=>this.close(record.targetId,options)})}get(targetId){const record=targetId===undefined?undefined:this.#owned.get(targetId);return record?this.#public(record):null}list(){return[...this.#owned.values()].map((record)=>this.#public(record))}async#isHeadless(){if(typeof this.#connection.cdp.isHeadless==="boolean")return this.#connection.cdp.isHeadless;const version=await this.#connection.cdp.send("Browser.getVersion").catch(()=>null);return/Headless/i.test(version?.product??"")}#queueRepin(record,viewport,reportErrors=false){const size={...viewport};const operation=record.repinQueue.then(async()=>{try{if(record.page===null)throw new TypeError("Cannot read properties of null (reading 'resolveSessionId')");await repinViewport(record.page,size)}catch(error){if(reportErrors)console.warn(`[agent-tabs] viewport repin failed for ${record.targetId}`,error);else throw error}record.viewport=Object.freeze(size);return{...size}});record.repinQueue=operation.catch(()=>{});return operation}async#repin(record){await this.#queueRepin(record,record.viewport,true)}async repin(tabOrTargetId,viewport=this.viewport){const id=typeof tabOrTargetId==="string"?tabOrTargetId:tabOrTargetId?.targetId;const record=id===undefined?undefined:this.#owned.get(id);if(!record)throw Error(`Target ${id} is not owned by this manager`);return this.#queueRepin(record,viewport)}async close(tabOrTargetId,options={}){const id=typeof tabOrTargetId==="string"?tabOrTargetId:tabOrTargetId?.targetId;const record=id===undefined?undefined:this.#owned.get(id);if(!record||id===undefined)throw Error(`Target ${id} is not owned by this manager`);const existing=this.#closing.get(id);if(existing)return existing.promise;const{promise,resolve:resolveOperation,reject:rejectOperation}=Promise.withResolvers();const entry={promise,reject:rejectOperation};this.#closing.set(id,entry);this.#close(record,options).then(resolveOperation,rejectOperation).finally(()=>{if(this.#closing.get(id)===entry)this.#closing.delete(id)});return promise}async#close(record,options){const{promise:destroyed,resolve:resolveDestroy,reject:rejectDestroy}=Promise.withResolvers();const timeout=setTimeout(()=>rejectDestroy(Error(`Timed out waiting for target ${record.targetId} to close`)),options.timeoutMs??this.closeTimeoutMs);const off=this.#connection.cdp.on("Target.targetDestroyed",(info)=>{if(info?.targetId===record.targetId)resolveDestroy()});const offDisconnect=this.#connection.cdp.transportEvents?.on?.("disconnected",()=>rejectDestroy(Error("Browser transport disconnected")));try{if(options.runBeforeUnload&&record.page)await record.page.cdp.send("Page.close",undefined,await record.page.resolveSessionId()).catch(()=>this.#connection.cdp.send("Target.closeTarget",{targetId:record.targetId}));else await this.#connection.cdp.send("Target.closeTarget",{targetId:record.targetId});if(this.#owned.has(record.targetId))await destroyed}finally{clearTimeout(timeout);off();offDisconnect?.();if(!this.#owned.has(record.targetId))record.navigationOff?.()}}#destroyed(id,error){if(id===undefined)return;const record=this.#owned.get(id);if(!record)return;record.navigationOff?.();this.#owned.delete(id);if(error)this.#closing.get(id)?.reject(error)}async closeAll(options={}){const results=await Promise.allSettled([...this.#owned.keys()].map((id)=>this.close(id,options)));const failures=results.filter((result)=>result.status==="rejected").map((result)=>result.reason);if(failures.length)throw new AggregateError(failures,"Failed to close one or more agent tabs")}async dispose(options={closeOwned:true}){if(this.#disposed)return;let failure;if(options.closeOwned!==false)try{await this.closeAll(options)}catch(error){failure=error}this.#disposed=true;for(const off of this.#unsubscribers){if(off===undefined)throw new TypeError("off is not a function");off()}this.#unsubscribers=[];if(failure)throw failure}}function getAgentTabs(connection){return managers.get(connection)}function createAgentTabs(connection,options={}){const current=managers.get(connection);if(current){if(current._optionsKey!==optionsKey(options))throw new TypeError("Conflicting AgentTabManager options");return current}const manager=new AgentTabManager(connection,options);Object.defineProperty(manager,"_optionsKey",{value:optionsKey(options)});managers.set(connection,manager);return manager}function cookieToCdp(cookie){const{name,value,url,domain,path,httpOnly,secure,sameSite}=cookie;const out={name,value,url,domain,path,httpOnly,secure,sameSite};if(cookie.expires!==undefined&&cookie.expires!==-1)out.expires=cookie.expires;if(cookie.partitionKey!==undefined){out.partitionKey={topLevelSite:cookie.partitionKey,hasCrossSiteAncestor:true}}return out}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).map(cookieToCdp)})}var isCookieFilterKey=(key)=>["name","domain","path"].includes(key);class BrowserContext{#connection;#scope;#origins=new Set;constructor(connection,browserContextId){this.#connection=connection;this.#scope=browserContextId?{browserContextId}:{}}trackOrigin(url){if(!/^https?:\/\//.test(url??""))return;this.#origins.add(new URL(url).origin)}async cookies(urls=[]){const{cookies}=await this.#connection.cdp.send("Storage.getCookies",this.#scope);const parsed=(typeof urls==="string"?[urls]:urls).map((url)=>new URL(url));return cookies.filter((cookie)=>!parsed.length||parsed.some((url)=>{const domain=cookie.domain.startsWith(".")?cookie.domain.slice(1):cookie.domain;if(url.hostname!==domain&&!(cookie.domain.startsWith(".")&&url.hostname.endsWith(`.${domain}`)))return false;if(cookie.secure&&url.protocol!=="https:"&&url.hostname!=="localhost")return false;const pathname=cookie.path.endsWith("/")?cookie.path:`${cookie.path}/`;return url.pathname===cookie.path||`${url.pathname}/`.startsWith(pathname)})).map((cookie)=>{const{name,value,domain,path:cookiePath,expires,httpOnly,secure}=cookie;const out={name,value,domain,path:cookiePath,expires,httpOnly,secure,sameSite:cookie.sameSite??"Lax"};if(cookie.partitionKey)out.partitionKey=cookie.partitionKey.topLevelSite;return out})}async addCookies(cookies){const normalized=cookies.map((cookie)=>{if(typeof cookie.name!=="string"||typeof cookie.value!=="string"){throw new TypeError("Cookie name and value must be strings")}if(cookie.url!==undefined){if(cookie.domain!==undefined||cookie.path!==undefined)throw new Error("Cookie must have either url or domain and path");const url=new URL(cookie.url);if(!/^https?:$/.test(url.protocol))throw new Error("Cookie url must be HTTP or HTTPS");return cookieToCdp({...cookie,domain:url.hostname,path:url.pathname.slice(0,url.pathname.lastIndexOf("/")+1),secure:cookie.secure??url.protocol==="https:"})}if(!cookie.domain||!cookie.path)throw new Error("Cookie must have either url or domain and path");return cookieToCdp(cookie)});await this.#connection.cdp.send("Storage.setCookies",{...this.#scope,cookies:normalized})}async clearCookies(options={}){const filters=Object.entries(options).filter((entry)=>isCookieFilterKey(entry[0]));if(!filters.length){await this.#connection.cdp.send("Storage.clearCookies",this.#scope);return}const survivors=(await this.cookies()).filter((cookie)=>!filters.every(([key,filter])=>filter instanceof RegExp?new RegExp(filter.source,filter.flags.replace(/[gy]/g,"")).test(cookie[key]):cookie[key]===filter));await this.#connection.cdp.send("Storage.clearCookies",this.#scope);await this.addCookies(survivors)}async newPage(){return(await(getAgentTabs(this.#connection)??createAgentTabs(this.#connection)).create("about:blank",this.#scope)).page}async storageState(options={}){const state={cookies:await this.cookies(),origins:[]};if(this.#origins.size){const page=await this.newPage();try{await page.route("**/*",(route)=>route.fulfill({contentType:"text/html",body:"<html></html>"}));for(const origin of this.#origins){await page.goto(origin,{waitUntil:"domcontentloaded"});const{entries}=await page._sendToTarget("DOMStorage.getDOMStorageItems",{storageId:{securityOrigin:origin,isLocalStorage:true}});if(entries.length)state.origins.push({origin,localStorage:entries.map(([name,value])=>({name,value}))})}}finally{await page.close()}}if(options.path!==undefined){await mkdir3(path22.dirname(path22.resolve(options.path)),{recursive:true});await writeFile2(options.path,JSON.stringify(state,null,2))}return state}}class TabRepository{#client;constructor(client){this.#client=client}async listTargets(){return this.#client.discoverTargets()}}class BrowserConnection{#client;#sessions;#pages=new Map;#contexts=new Map;#storageRoot;#popups=new Map;#popupTargets=new Map;#attachingPopups=new Map;#ownedPopups=new Set;#popupOff=[];tabs;constructor(client,options={}){this.#client=client;this.#sessions=new SessionManager(client);this.tabs=new TabRepository(client);this.#storageRoot=path3.resolve(options.storageRoot??process.cwd());this.#popupOff.push(client.on("Target.targetCreated",({targetInfo})=>{const openerId=targetInfo?.openerId;if(targetInfo?.type!=="page"||!this.#acceptsPopup(openerId))return;const targets=this.#popupTargets.get(openerId)??[];targets.push({targetId:targetInfo.targetId});this.#popupTargets.set(openerId,targets);this.#matchPopups(openerId)}));this.#popupOff.push(client.on("Target.targetDestroyed",({targetId})=>{this.#ownedPopups.delete(targetId);const error=Error("Popup closed before attachment completed");this.#attachingPopups.get(targetId)?.reject(error);for(const targets of this.#popupTargets.values()){const target=targets.find((candidate)=>candidate.targetId===targetId);if(target)target.error=error}}))}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"){return(await(getAgentTabs(this)??createAgentTabs(this)).create(url)).page}#acceptsPopup(openerId){return openerId!==undefined&&!!getAgentTabs(this)?.get(openerId)&&(this.#pages.get(openerId)?.page.events.listenerCount("popup")??0)>0}#matchPopups(openerId){const targets=this.#popupTargets.get(openerId);const queue=this.#popups.get(openerId);while(targets?.length&&queue?.length){const target=targets.shift();const pending=queue.shift();if(target===undefined||pending===undefined)break;if(target.error)pending.reject(target.error);else{this.#attachingPopups.set(target.targetId,pending);this.#ownedPopups.add(target.targetId);pending.operation=this.#attachPopup(target.targetId,pending).catch(pending.reject).finally(()=>{this.#attachingPopups.delete(target.targetId)})}}if(!targets?.length)this.#popupTargets.delete(openerId);if(!queue?.length)this.#popups.delete(openerId)}async#attachPopup(targetId,pending){const tabs=getAgentTabs(this)??createAgentTabs(this);const{page}=await tabs.adopt(targetId);if(page===null)throw new TypeError(`Popup target ${targetId} is still being adopted`);Object.assign(page,{popupMetadata:Object.freeze(pending.metadata)});await page.waitForLoadState("interactive");pending.resolve(page)}async attachPage(targetId){const attached=this.#pages.get(targetId);if(attached)return attached.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);const{targetInfo}=await this.#client.send("Target.getTargetInfo",{targetId});const contextId=targetInfo.browserContextId;let context=this.#contexts.get(contextId);if(!context){context=new BrowserContext(this,contextId);this.#contexts.set(contextId,context)}const pageContext=context;Object.assign(page,{context:()=>pageContext});for(const frame of frames.frames.values())pageContext.trackOrigin(frame.url);page.on("framenavigated",(frame)=>pageContext.trackOrigin(frame.url));const attachedEntry=Object.assign(entry,{page});this.#pages.set(targetId,attachedEntry);return page}#createPageHost(targetId,entry){return{daemonSession:{accountId:0,id:"standalone"},extensionBridgeRoute:{},page:null,resolvePageSession:(id,preferred)=>this.#sessions.resolvePageSession(id,preferred),setViewportSize:async(size)=>{const tabs=getAgentTabs(this);if(tabs?.get(targetId))await tabs.repin(targetId,size);else{if(entry.page===null)throw new TypeError("Cannot read properties of null (reading 'resolveSessionId')");await repinViewport(entry.page,size)}},resolvePath:(value)=>path3.resolve(this.#storageRoot,value),ensurePath:async(value)=>{const resolved=path3.resolve(this.#storageRoot,value);await mkdir4(path3.dirname(resolved),{recursive:true});return resolved},registerReadableDownloadPath:(value)=>value,isReadableDownload:()=>false,resolvePopup:async(metadata)=>{if(!this.#acceptsPopup(targetId))return;const queue=this.#popups.get(targetId)??[];const promise=new Promise((resolve,reject)=>queue.push({resolve,reject,metadata:{url:metadata.url,windowName:metadata.windowName}}));this.#popups.set(targetId,queue);this.#matchPopups(targetId);return promise},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 off of this.#popupOff)off();for(const queue of this.#popups.values()){for(const pending of queue)pending.reject(Error("Browser connection closed"))}this.#popups.clear();this.#popupTargets.clear();for(const pending of this.#attachingPopups.values())pending.reject(Error("Browser connection closed"));await Promise.all([...this.#attachingPopups.values()].map((pending)=>pending.operation));const tabs=getAgentTabs(this);if(tabs){await Promise.all([...this.#ownedPopups].filter((id)=>tabs.get(id)).map((id)=>tabs.close(id)));await tabs.dispose({closeOwned:false})}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[Symbol.asyncDispose](){await this.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:(snapshot)=>openConnection(key,snapshot)})}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","Emulation.setEmulatedMedia","Input.dispatchKeyEvent","Input.dispatchMouseEvent","Input.insertText","Inspector.enable","Network.disable","Network.enable","Network.getResponseBody","Network.setExtraHTTPHeaders","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.addBinding","Runtime.disable","Runtime.discardConsoleEntries","Runtime.enable","Runtime.evaluate","Runtime.releaseObject","Runtime.removeBinding","Runtime.runIfWaitingForDebugger","Target.activateTarget","Target.attachToTarget","Target.closeTarget","Target.createTarget","Target.detachFromTarget","Target.getTargetInfo","Target.getTargets","Target.setAutoAttach","Target.setDiscoverTargets"]);var DARWIN_EXCLUSIVE_NONBLOCK=32|4;var WINDOWS_EXCLUSIVE=268435456;var probedPaths=new Set;var DARWIN_BUSY_CODES=new Set(["EAGAIN","EWOULDBLOCK"]);async function lockLinux(fd){return new Promise((resolve,reject)=>{const child=spawn2("flock",["-n","3"],{stdio:["ignore","ignore","pipe",fd]});let stderr="";const stderrStream=child.stderr;if(stderrStream===null)throw new TypeError("flock child has no stderr pipe");stderrStream.setEncoding("utf8");stderrStream.on("data",(chunk)=>{stderr+=chunk});child.once("error",(error)=>{reject(error.code==="ENOENT"?new Error(`instance lock needs the flock utility (util-linux or busybox) on Linux: ${error.message}`,{cause:error}):error)});child.once("close",(code,signal)=>{if(code===0)resolve(true);else if(code===1&&stderr.trim()==="")resolve(false);else reject(Object.assign(new Error(`instance lock flock failed (${signal??code}): ${stderr.trim()}`),{code:"ERR_INSTANCE_LOCK"}))})})}async function tryAcquire(lockPath){const platform=process.platform;if(platform==="win32"&&process.versions.bun){await Promise.resolve().then(() => init_lock_backend_win32_xbcm60vz());return tryAcquireWindows(lockPath)}let flags=constants.O_RDWR|constants.O_CREAT;if(platform==="darwin")flags|=DARWIN_EXCLUSIVE_NONBLOCK;else if(platform==="win32")flags|=WINDOWS_EXCLUSIVE;else if(platform!=="linux")throw new Error(`instance lock is unsupported on ${platform}`);let handle;try{handle=await open2(lockPath,flags,384)}catch(error){if(platform==="darwin"&&DARWIN_BUSY_CODES.has(readProperty(error,"code")))return null;if(platform==="win32"&&readProperty(error,"code")==="EBUSY")return null;throw error}try{if(platform==="linux"&&!await lockLinux(handle.fd)){await handle.close();return null}}catch(error){await handle.close();throw error}return{release:()=>handle.close()}}async function probeOnce(lockPath){if(probedPaths.has(lockPath))return;const second=await tryAcquire(lockPath);if(second!==null){await second.release();throw new Error(`instance lock is not enforced for ${lockPath} on this runtime and filesystem`)}probedPaths.add(lockPath)}var localLocks=new Map;function errorCode(error){return error===null||error===undefined?undefined:readProperty(error,"code")}function isPidAlive(pid){try{process.kill(pid,0);return true}catch(error){if(errorCode(error)==="EPERM")return true;if(errorCode(error)==="ESRCH")return false;throw error}}async function unlinkIfPresent(target){await unlink2(target).catch((error)=>{if(errorCode(error)!=="ENOENT")throw error})}async function acquireLock(lockPath,timeoutMs){const deadline=performance.now()+timeoutMs;let delay=10;for(;;){const held=await tryAcquire(lockPath);if(held){try{await probeOnce(lockPath);return held}catch(error){await held.release();throw error}}const remaining=deadline-performance.now();if(remaining<=0)throw new Error(`timed out waiting for instance lock ${lockPath}`);await sleep(Math.min(remaining,delay*(0.75+Math.random()*0.5)));delay=Math.min(delay*2,250)}}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},run){const releaseLocal=await acquireLocalLock(lockPath);try{const held=await acquireLock(lockPath,timeoutMs);try{return await run()}finally{await held.release()}}finally{releaseLocal()}}var execFileAsync=promisify(execFile);var WINDOWS_START_TIME_TIMEOUT_MS=15000;var ownStartTime;async function processStartTime(pid){if(process.platform==="win32"){if(!Number.isInteger(pid)||pid<=0)return null;const systemRoot=process.env["SystemRoot"]||process.env["windir"]||"C:\\Windows";try{const{stdout}=await execFileAsync(path4.win32.join(systemRoot,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToFileTimeUtc()`],{timeout:WINDOWS_START_TIME_TIMEOUT_MS,windowsHide:true});const ticks=String(stdout).trim();return/^\d+$/.test(ticks)?ticks:null}catch{return null}}if(process.platform==="linux"){try{const text=await readFile3(`/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}}function ownProcessStartTime(){ownStartTime??=processStartTime(process.pid);return ownStartTime}var TERM_GRACE_MS=5000;var PID_FILE_NAME="omowright-browser.pid";var REAP_POLL_MS=50;var browserSpawnDetached=process.platform!=="win32";function profileDirFromArgs(browserArgs){for(const[index,argument]of browserArgs.entries()){const next=browserArgs[index+1];if(argument==="--user-data-dir"&&next)return path5.resolve(next);if(argument.startsWith("--user-data-dir="))return path5.resolve(argument.slice("--user-data-dir=".length))}return null}var signalsCanAskToQuit=process.platform!=="win32";async function terminateChild(child,{quitRequested=false}={}){if(child.pid===undefined)return;if(child.exitCode!==null||child.signalCode!==null)return;const exited=new Promise((resolve)=>child.once("exit",resolve));if(signalsCanAskToQuit){try{child.kill("SIGTERM")}catch{}}if(signalsCanAskToQuit||quitRequested){let timer;const graceOver=new Promise((resolve)=>{timer=setTimeout(resolve,TERM_GRACE_MS)});await Promise.race([exited,graceOver]);clearTimeout(timer)}if(child.exitCode===null&&child.signalCode===null){try{child.kill("SIGKILL")}catch{}await exited}}function pidFilePath(profileDir){return path5.join(profileDir,PID_FILE_NAME)}async function writeBrowserPidFile(profileDir,pid){if(!profileDir||!pid)return;const[start,ownerStart]=await Promise.all([processStartTime(pid),ownProcessStartTime()]);mkdirSync(profileDir,{recursive:true});const record={pid,start,profileDir,owner:{pid:process.pid,start:ownerStart}};writeFileSync(pidFilePath(profileDir),`${JSON.stringify(record)}
1326
- `,{mode:384})}function removeBrowserPidFile(profileDir,pid){if(!profileDir)return;try{const recorded=JSON.parse(readFileSync2(pidFilePath(profileDir),"utf8"));if(readProperty(recorded,"pid")!==pid)return}catch{return}rmSync(pidFilePath(profileDir),{force:true})}async function sameProcessAlive(pid,start){if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0)return null;if(!isPidAlive(pid))return false;if(start===null||start===undefined)return null;const now=await processStartTime(pid);if(now===null)return null;return now===start}async function reapOrphanedBrowser(profileDir){if(!profileDir)return;let recorded;try{recorded=JSON.parse(readFileSync2(pidFilePath(profileDir),"utf8"))}catch{return}const pid=readProperty(recorded,"pid");const start=readProperty(recorded,"start");const owner=readProperty(recorded,"owner");if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0){rmSync(pidFilePath(profileDir),{force:true});return}const browserAlive=await sameProcessAlive(pid,start);if(browserAlive===false){rmSync(pidFilePath(profileDir),{force:true});return}if(browserAlive===null||pid===process.pid)return;const ownerAlive=owner===null||owner===undefined?await sameProcessAlive(undefined,undefined):await sameProcessAlive(readProperty(owner,"pid"),readProperty(owner,"start"));if(ownerAlive!==false)return;try{process.kill(pid,"SIGTERM")}catch{}const deadline=Date.now()+TERM_GRACE_MS;while(isPidAlive(pid)&&Date.now()<deadline)await sleep2(REAP_POLL_MS);if(isPidAlive(pid)){try{process.kill(pid,"SIGKILL")}catch{}}rmSync(pidFilePath(profileDir),{force:true})}class NulFrameReader{#parts=[];push(chunk){const frames=[];let start=0;let end;while((end=chunk.indexOf(0,start))!==-1){const tail=chunk.subarray(start,end);let frame=tail;if(this.#parts.length>0){this.#parts.push(tail);frame=Buffer.concat(this.#parts);this.#parts=[]}frames.push(frame.toString("utf8"));start=end+1}if(start<chunk.length)this.#parts.push(chunk.subarray(start));return frames}}class SerialEmitter{#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;var EXIT_STDERR_DRAIN_MS=1000;class PipeCdpClient{#child;#writeStream;#readStream;#frames=new NulFrameReader;#seq=1;#pending=new Map;#closedSessions=new Set;#sessionTargets=new Map;#launch;#launchId;#launchedAt=0;#receivedBytes=0;#malformedFrameCount=0;#events=new SerialEmitter;#connected=false;#closedByCaller=false;#commandTimeoutMs;#readinessTimeoutMs;#browserPath;#browserArgs;#spawnOptions;#stdioTail="";#stderrHead="";#dialogPolicy;transportEvents=new SerialEmitter;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(){this.#closedByCaller=false;if(this.#connected)return;const stdio=["ignore","pipe","pipe","pipe","pipe"];const profileDir=profileDirFromArgs(this.#browserArgs);await reapOrphanedBrowser(profileDir);const child=spawn3(this.#browserPath,[...this.#browserArgs,"--remote-debugging-pipe"],{detached:browserSpawnDetached,...this.#spawnOptions,stdio});this.#child=child;const spawnFailed=new Promise((resolve)=>child.once("error",resolve));if(child.pid===undefined){const error=await spawnFailed;this.#child=undefined;throw error}const browserPid=child.pid;const launch={};this.#launch=launch;const owned=(listener)=>(...args)=>{if(this.#launch===launch)listener(...args)};this.#launchId=`${this.logId}:${browserPid}`;this.#launchedAt=performance.now();this.#receivedBytes=0;this.#malformedFrameCount=0;this.#frames=new NulFrameReader;this.#sessionTargets.clear();this.#closedSessions.clear();child.once("exit",()=>removeBrowserPidFile(profileDir,browserPid));this.#stdioTail="";this.#stderrHead="";const stderr=child.stderr;for(const stream of[child.stdout,stderr]){if(!stream)continue;stream.setEncoding("utf8");stream.on("data",(chunk)=>{this.#stdioTail=(this.#stdioTail+chunk).slice(-STDIO_TAIL_LIMIT);if(stream===stderr&&this.#stderrHead.length<STDIO_TAIL_LIMIT&&!this.#stderrHead.trimStart().includes(`
1325
+ 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=path2.join(jn,path2.basename(xn.path));await mkdir(path2.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(path2.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(path2.dirname(jn),{recursive:true}).catch(()=>{}),await writeFile(jn,Jn)),Jn}async close(xn={}){this.#closeRequested=true;for(const sessionId of this.#f())this.cdp.closeSession?.(sessionId);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){let jn=await this.resolveSessionId(this.#n),releaseNetwork=acquireNetwork(this.cdp,jn);await releaseNetwork.ready;await new Promise((Vn,qn)=>{let Jn=new Set,Yn=null,Zn=null,Qn=()=>{ti(),ri(),ii(),releaseNetwork(),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#navigationResponse(trigger){let frameId=this.frameManager.mainFrameId,documents=trackDocumentResponses(this,frameId),offs=[],timer;try{await documents.ready;let sessionId=await this.resolveSessionId(this.#n),deadline=new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error(`Timed out waiting for navigation`)),DEFAULT_WAIT_TIMEOUT_MS)}),committed=new Promise((resolve)=>{offs.push(this.cdp.on(`Page.frameNavigated`,(params,meta)=>{meta.sessionId===sessionId&&!params.frame.parentId&&resolve(params.frame.loaderId)}),this.cdp.on(`Page.navigatedWithinDocument`,(params,meta)=>{meta.sessionId===sessionId&&params.frameId===frameId&&resolve(null)}))});deadline.catch(()=>{});let[,loaderId]=await Promise.race([Promise.all([trigger(),committed]),deadline]);if(!loaderId)return null;await Promise.race([this.cdp.send(`Page.getFrameTree`,undefined,sessionId),deadline]);return documents.response(loaderId)}finally{clearTimeout(timer);for(let off of offs)off();documents.dispose()}}async _sendToTarget(xn,jn,Vn={}){await networkReady(this);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}}}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=createOmOPageClass()});init_client$6();init_session_manager();init_frame_manager();init_page();Object.assign(initialized(()=>OmOPage).prototype,{addInitScript,exposeFunction,exposeBinding,setExtraHTTPHeaders,setViewportSize,emulateMedia});var testIdAttributeName="data-testid";var selectors={setTestIdAttribute(attributeName){if(typeof attributeName!=="string"||!/^[^\s"'>/=[\]]+$/.test(attributeName)){throw new TypeError(`selectors.setTestIdAttribute: invalid attribute name ${JSON.stringify(attributeName)}`)}testIdAttributeName=attributeName}};function isRegExpValue(value){return Object.prototype.toString.call(value)==="[object RegExp]"}function attributeSelector(name,value,exact){if(isRegExpValue(value))return`internal:attr=[${name}=/${value.source.replaceAll(">>",">\\x3e")}/${value.flags}]`;return`internal:attr=[${name}=${JSON.stringify(String(value)).replaceAll(">","\\u003e")}${exact?"s":"i"}]`}class AttributeLocatorGetters{getByAltText(text,options={}){return this.locator(attributeSelector("alt",text,options.exact))}getByPlaceholder(text,options={}){return this.locator(attributeSelector("placeholder",text,options.exact))}getByTestId(testId){return this.locator(attributeSelector(testIdAttributeName,testId,true))}getByTitle(text,options={}){return this.locator(attributeSelector("title",text,options.exact))}}for(const Container of[initialized(()=>OmOPage),initialized(()=>OmOFrame),initialized(()=>FrameLocator)]){for(const name of Object.getOwnPropertyNames(AttributeLocatorGetters.prototype)){if(name!=="constructor")Object.defineProperty(Container.prototype,name,definedOrThrow(Object.getOwnPropertyDescriptor(AttributeLocatorGetters.prototype,name)))}}initialized(()=>OmOPage).prototype.route=function(url,handler,options){return pageRoute(this,url,handler,options)};initialized(()=>OmOPage).prototype.unroute=function(url,handler){return pageUnroute(this,url,handler)};initialized(()=>OmOPage).prototype.unrouteAll=function(){return pageUnrouteAll(this)};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 readOnly(what,get){return{get,set:refuse(what),defineProperty:refuse(what),deleteProperty:refuse(what)}}function lease(key,entry,connection){let closed;const overlay=Object.create(null);const subscriptions=new Set;const transportSubscriptions=new Set;const unsubscribeAll=(set)=>{for(const unsubscribe of[...set])unsubscribe()};const ensureOpen=(property)=>{if(closed&&typeof property==="string"&&property!=="then"){throw new Error("this browser connection handle was closed")}};const close=()=>{if(!closed){unsubscribeAll(subscriptions);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,...sets)=>(...args)=>{const remove=subscribe(...args);let removed=false;const unsubscribe=()=>{if(removed)return;removed=true;for(const set of sets)set.delete(unsubscribe);remove()};for(const set of sets)set.add(unsubscribe);return unsubscribe};const client=connection.cdp;const sharedTransportEvents=client.transportEvents;if(sharedTransportEvents===undefined)throw new TypeError("Cannot create proxy with a non-object as target or handler");const transportEvents=new Proxy(sharedTransportEvents,readOnly("the shared transport events",(target,property)=>{ensureOpen(property);if(property==="on"){const on=(name,listener)=>target.on(name,(event)=>listener(event));return tracked(on,subscriptions,transportSubscriptions)}if(property==="clearListeners")return()=>unsubscribeAll(transportSubscriptions);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),subscriptions);if(property==="transportEvents")return transportEvents;return bindTo(target,Reflect.get(target,property,target))}));return new Proxy(connection,{get(target,property){if(property==="close"||property===Symbol.asyncDispose)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(!readProperty(descriptor,"enumerable")||descriptor===undefined||!("value"in descriptor))return false;if(!isPlainData(descriptor.value,path))return false}return true}finally{path.delete(value)}}function frozenCopy(value){if(value===null||typeof value!=="object")return value;let copy;if(Array.isArray(value)){const sparse=[];sparse.length=value.length;copy=sparse}else copy=Object.create(Object.getPrototypeOf(value));for(const key of Object.keys(value)){Object.defineProperty(copy,key,{value:frozenCopy(readProperty(value,key)),enumerable:true})}return Object.freeze(copy)}function openingOptions(snapshot){if(snapshot?.dialogPolicy!=null||snapshot?.client?.dialogPolicy!=null)return snapshot;return Object.freeze({...snapshot,dialogPolicy:Object.freeze({accept:true})})}function canShareConnection(options){return options?.client?.authorizer===undefined&&isPlainData(options)}async function acquireSharedConnection(webSocketDebuggerUrl,options,{open,timeoutMs}){if(!canShareConnection(options))return open(options);const snapshot=frozenCopy(options);let entry=shared.get(webSocketDebuggerUrl);if(entry&&!isDeepStrictEqual(entry.options,snapshot))return open(openingOptions(snapshot));if(!entry){entry={options:snapshot,refs:0,ready:open(openingOptions(snapshot))};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}}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 presetsByName=DEVICE_PRESETS;var originalUAs=new WeakMap;var emulatedDevices=new WeakMap;function emulatedDevice(page){return emulatedDevices.get(page)}async function emulate(page,presetNameOrObject){let preset;if(presetNameOrObject===null){preset=null}else if(typeof presetNameOrObject==="string"){const named=presetsByName[presetNameOrObject];if(!named){throw new Error(`unknown device preset: ${presetNameOrObject}`)}preset=named}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);emulatedDevices.delete(page);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);emulatedDevices.set(page,preset);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 managers=new WeakMap;var CAPABILITY=targetCreationCapability;function optionsKey(options={}){return JSON.stringify({viewport:{...DEFAULT_AGENT_VIEWPORT,...options.viewport},closeTimeoutMs:options.closeTimeoutMs??5000})}class AgentTabManager{#connection;#owned=new Map;#unsubscribers=[];#disposed=false;#closing=new Map;viewport;closeTimeoutMs;ready;constructor(connection,options={}){if(!connection?.cdp)throw new TypeError("createAgentTabs requires a browser connection");this.#connection=connection;this.viewport=Object.freeze({...DEFAULT_AGENT_VIEWPORT,...options.viewport});this.closeTimeoutMs=options.closeTimeoutMs??5000;this.#unsubscribers.push(connection.cdp.on("Target.targetDestroyed",(info)=>this.#destroyed(info?.targetId)));this.#unsubscribers.push(connection.cdp.on("Target.targetCrashed",(info)=>this.#destroyed(info?.targetId)));this.#unsubscribers.push(connection.cdp.transportEvents?.on?.("disconnected",()=>{for(const id of[...this.#owned.keys()])this.#destroyed(id,Error("Browser transport disconnected"))}));this.ready=Promise.resolve(connection.cdp.ensureConnected?.())}async create(url="about:blank",options={}){if(this.#disposed)throw Error("Agent tab manager is disposed");await this.ready;const viewport={...this.viewport,...options.viewport};const result=await this.#connection.cdp.send("Target.createTarget",{url:"about:blank",background:true,newWindow:true,...options.browserContextId?{browserContextId:options.browserContextId}:{}},undefined,{capability:CAPABILITY});const targetId=result.targetId;if(await this.#isHeadless())await this.#connection.cdp.send("Target.activateTarget",{targetId});const tab=await this.adopt(targetId,{viewport});if(tab.page===null)throw new TypeError(`Target ${targetId} is still being adopted`);if(url!=="about:blank")await tab.page.goto(url);return Object.freeze({...tab,page:tab.page})}async adopt(targetId,options={}){if(this.#disposed)throw Error("Agent tab manager is disposed");const existing=this.#owned.get(targetId);if(existing)return this.#public(existing);const viewport={...this.viewport,...options.viewport};const record={targetId,page:null,viewport:Object.freeze({...viewport}),repinQueue:Promise.resolve()};this.#owned.set(targetId,record);try{const page=await this.#connection.attachPage(targetId);record.page=page;await repinViewport(page,record.viewport);record.navigationOff=page.on?.("framenavigated",(event)=>{if(!event.parentFrameId)this.#repin(record)});return this.#public(record,page)}catch(error){await this.#connection.cdp.send("Target.closeTarget",{targetId}).catch(()=>{});throw error}}#public(record,page=record.page){return Object.freeze({targetId:record.targetId,page,viewport:{...record.viewport},close:(options)=>this.close(record.targetId,options)})}get(targetId){const record=targetId===undefined?undefined:this.#owned.get(targetId);return record?this.#public(record):null}list(){return[...this.#owned.values()].map((record)=>this.#public(record))}async#isHeadless(){if(typeof this.#connection.cdp.isHeadless==="boolean")return this.#connection.cdp.isHeadless;const version=await this.#connection.cdp.send("Browser.getVersion").catch(()=>null);return/Headless/i.test(version?.product??"")}#queueRepin(record,viewport,reportErrors=false,device){const size={...viewport};const operation=record.repinQueue.then(async()=>{try{if(record.page===null)throw new TypeError("Cannot read properties of null (reading 'resolveSessionId')");await repinViewport(record.page,device??size,device)}catch(error){if(reportErrors)console.warn(`[agent-tabs] viewport repin failed for ${record.targetId}`,error);else throw error}record.viewport=Object.freeze(size);return{...size}});record.repinQueue=operation.catch(()=>{});return operation}async#repin(record){await this.#queueRepin(record,record.viewport,true,record.page===null?undefined:emulatedDevice(record.page))}async repin(tabOrTargetId,viewport=this.viewport){const id=typeof tabOrTargetId==="string"?tabOrTargetId:tabOrTargetId?.targetId;const record=id===undefined?undefined:this.#owned.get(id);if(!record)throw Error(`Target ${id} is not owned by this manager`);return this.#queueRepin(record,viewport)}async close(tabOrTargetId,options={}){const id=typeof tabOrTargetId==="string"?tabOrTargetId:tabOrTargetId?.targetId;const record=id===undefined?undefined:this.#owned.get(id);if(!record||id===undefined)throw Error(`Target ${id} is not owned by this manager`);const existing=this.#closing.get(id);if(existing)return existing.promise;const{promise,resolve:resolveOperation,reject:rejectOperation}=Promise.withResolvers();const entry={promise,reject:rejectOperation};this.#closing.set(id,entry);this.#close(record,options).then(resolveOperation,rejectOperation).finally(()=>{if(this.#closing.get(id)===entry)this.#closing.delete(id)});return promise}async#close(record,options){const{promise:destroyed,resolve:resolveDestroy,reject:rejectDestroy}=Promise.withResolvers();const timeout=setTimeout(()=>rejectDestroy(Error(`Timed out waiting for target ${record.targetId} to close`)),options.timeoutMs??this.closeTimeoutMs);const off=this.#connection.cdp.on("Target.targetDestroyed",(info)=>{if(info?.targetId===record.targetId)resolveDestroy()});const offDisconnect=this.#connection.cdp.transportEvents?.on?.("disconnected",()=>rejectDestroy(Error("Browser transport disconnected")));try{if(options.runBeforeUnload&&record.page)await record.page.cdp.send("Page.close",undefined,await record.page.resolveSessionId()).catch(()=>this.#connection.cdp.send("Target.closeTarget",{targetId:record.targetId}));else await this.#connection.cdp.send("Target.closeTarget",{targetId:record.targetId});if(this.#owned.has(record.targetId))await destroyed}finally{clearTimeout(timeout);off();offDisconnect?.();if(!this.#owned.has(record.targetId))record.navigationOff?.()}}#destroyed(id,error){if(id===undefined)return;const record=this.#owned.get(id);if(!record)return;record.navigationOff?.();this.#owned.delete(id);if(error)this.#closing.get(id)?.reject(error)}async closeAll(options={}){const results=await Promise.allSettled([...this.#owned.keys()].map((id)=>this.close(id,options)));const failures=results.filter((result)=>result.status==="rejected").map((result)=>result.reason);if(failures.length)throw new AggregateError(failures,"Failed to close one or more agent tabs")}async dispose(options={closeOwned:true}){if(this.#disposed)return;let failure;if(options.closeOwned!==false)try{await this.closeAll(options)}catch(error){failure=error}this.#disposed=true;for(const off of this.#unsubscribers){if(off===undefined)throw new TypeError("off is not a function");off()}this.#unsubscribers=[];if(failure)throw failure}}function getAgentTabs(connection){return managers.get(connection)}function createAgentTabs(connection,options={}){const current=managers.get(connection);if(current){if(current._optionsKey!==optionsKey(options))throw new TypeError("Conflicting AgentTabManager options");return current}const manager=new AgentTabManager(connection,options);Object.defineProperty(manager,"_optionsKey",{value:optionsKey(options)});managers.set(connection,manager);return manager}function cookieToCdp(cookie){const{name,value,url,domain,path,httpOnly,secure,sameSite}=cookie;const out={name,value,url,domain,path,httpOnly,secure,sameSite};if(cookie.expires!==undefined&&cookie.expires!==-1)out.expires=cookie.expires;if(cookie.partitionKey!==undefined){out.partitionKey={topLevelSite:cookie.partitionKey,hasCrossSiteAncestor:true}}return out}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).map(cookieToCdp)})}var isCookieFilterKey=(key)=>["name","domain","path"].includes(key);class BrowserContext{#connection;#scope;#origins=new Set;constructor(connection,browserContextId){this.#connection=connection;this.#scope=browserContextId?{browserContextId}:{}}trackOrigin(url){if(!/^https?:\/\//.test(url??""))return;this.#origins.add(new URL(url).origin)}async cookies(urls=[]){const{cookies}=await this.#connection.cdp.send("Storage.getCookies",this.#scope);const parsed=(typeof urls==="string"?[urls]:urls).map((url)=>new URL(url));return cookies.filter((cookie)=>!parsed.length||parsed.some((url)=>{const domain=cookie.domain.startsWith(".")?cookie.domain.slice(1):cookie.domain;if(url.hostname!==domain&&!(cookie.domain.startsWith(".")&&url.hostname.endsWith(`.${domain}`)))return false;if(cookie.secure&&url.protocol!=="https:"&&url.hostname!=="localhost")return false;const pathname=cookie.path.endsWith("/")?cookie.path:`${cookie.path}/`;return url.pathname===cookie.path||`${url.pathname}/`.startsWith(pathname)})).map((cookie)=>{const{name,value,domain,path:cookiePath,expires,httpOnly,secure}=cookie;const out={name,value,domain,path:cookiePath,expires,httpOnly,secure,sameSite:cookie.sameSite??"Lax"};if(cookie.partitionKey)out.partitionKey=cookie.partitionKey.topLevelSite;return out})}async addCookies(cookies){const normalized=cookies.map((cookie)=>{if(typeof cookie.name!=="string"||typeof cookie.value!=="string"){throw new TypeError("Cookie name and value must be strings")}if(cookie.url!==undefined){if(cookie.domain!==undefined||cookie.path!==undefined)throw new Error("Cookie must have either url or domain and path");const url=new URL(cookie.url);if(!/^https?:$/.test(url.protocol))throw new Error("Cookie url must be HTTP or HTTPS");return cookieToCdp({...cookie,domain:url.hostname,path:url.pathname.slice(0,url.pathname.lastIndexOf("/")+1),secure:cookie.secure??url.protocol==="https:"})}if(!cookie.domain||!cookie.path)throw new Error("Cookie must have either url or domain and path");return cookieToCdp(cookie)});await this.#connection.cdp.send("Storage.setCookies",{...this.#scope,cookies:normalized})}async clearCookies(options={}){const filters=Object.entries(options).filter((entry)=>isCookieFilterKey(entry[0]));if(!filters.length){await this.#connection.cdp.send("Storage.clearCookies",this.#scope);return}const survivors=(await this.cookies()).filter((cookie)=>!filters.every(([key,filter])=>filter instanceof RegExp?new RegExp(filter.source,filter.flags.replace(/[gy]/g,"")).test(cookie[key]):cookie[key]===filter));await this.#connection.cdp.send("Storage.clearCookies",this.#scope);await this.addCookies(survivors)}async newPage(){return(await(getAgentTabs(this.#connection)??createAgentTabs(this.#connection)).create("about:blank",this.#scope)).page}async storageState(options={}){const state={cookies:await this.cookies(),origins:[]};if(this.#origins.size){const page=await this.newPage();try{await page.route("**/*",(route)=>route.fulfill({contentType:"text/html",body:"<html></html>"}));for(const origin of this.#origins){await page.goto(origin,{waitUntil:"domcontentloaded"});const{entries}=await page._sendToTarget("DOMStorage.getDOMStorageItems",{storageId:{securityOrigin:origin,isLocalStorage:true}});if(entries.length)state.origins.push({origin,localStorage:entries.map(([name,value])=>({name,value}))})}}finally{await page.close()}}if(options.path!==undefined){await mkdir3(path22.dirname(path22.resolve(options.path)),{recursive:true});await writeFile2(options.path,JSON.stringify(state,null,2))}return state}}class TabRepository{#client;constructor(client){this.#client=client}async listTargets(){return this.#client.discoverTargets()}}class BrowserConnection{#client;#sessions;#pages=new Map;#contexts=new Map;#storageRoot;#popups=new Map;#popupTargets=new Map;#attachingPopups=new Map;#ownedPopups=new Set;#popupOff=[];tabs;constructor(client,options={}){this.#client=client;this.#sessions=new SessionManager(client);this.tabs=new TabRepository(client);this.#storageRoot=path3.resolve(options.storageRoot??process.cwd());this.#popupOff.push(client.on("Target.targetCreated",({targetInfo})=>{const openerId=targetInfo?.openerId;if(targetInfo?.type!=="page"||!this.#acceptsPopup(openerId))return;const targets=this.#popupTargets.get(openerId)??[];targets.push({targetId:targetInfo.targetId});this.#popupTargets.set(openerId,targets);this.#matchPopups(openerId)}));this.#popupOff.push(client.on("Target.targetDestroyed",({targetId})=>{this.#ownedPopups.delete(targetId);const error=Error("Popup closed before attachment completed");this.#attachingPopups.get(targetId)?.reject(error);for(const targets of this.#popupTargets.values()){const target=targets.find((candidate)=>candidate.targetId===targetId);if(target)target.error=error}}))}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"){return(await(getAgentTabs(this)??createAgentTabs(this)).create(url)).page}#acceptsPopup(openerId){return openerId!==undefined&&!!getAgentTabs(this)?.get(openerId)&&(this.#pages.get(openerId)?.page.events.listenerCount("popup")??0)>0}#matchPopups(openerId){const targets=this.#popupTargets.get(openerId);const queue=this.#popups.get(openerId);while(targets?.length&&queue?.length){const target=targets.shift();const pending=queue.shift();if(target===undefined||pending===undefined)break;if(target.error)pending.reject(target.error);else{this.#attachingPopups.set(target.targetId,pending);this.#ownedPopups.add(target.targetId);pending.operation=this.#attachPopup(target.targetId,pending).catch(pending.reject).finally(()=>{this.#attachingPopups.delete(target.targetId)})}}if(!targets?.length)this.#popupTargets.delete(openerId);if(!queue?.length)this.#popups.delete(openerId)}async#attachPopup(targetId,pending){const tabs=getAgentTabs(this)??createAgentTabs(this);const{page}=await tabs.adopt(targetId);if(page===null)throw new TypeError(`Popup target ${targetId} is still being adopted`);Object.assign(page,{popupMetadata:Object.freeze(pending.metadata)});await page.waitForLoadState("interactive");pending.resolve(page)}async attachPage(targetId){const attached=this.#pages.get(targetId);if(attached)return attached.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);const{targetInfo}=await this.#client.send("Target.getTargetInfo",{targetId});const contextId=targetInfo.browserContextId;let context=this.#contexts.get(contextId);if(!context){context=new BrowserContext(this,contextId);this.#contexts.set(contextId,context)}const pageContext=context;Object.assign(page,{context:()=>pageContext});for(const frame of frames.frames.values())pageContext.trackOrigin(frame.url);page.on("framenavigated",(frame)=>pageContext.trackOrigin(frame.url));const attachedEntry=Object.assign(entry,{page});this.#pages.set(targetId,attachedEntry);return page}#createPageHost(targetId,entry){return{daemonSession:{accountId:0,id:"standalone"},extensionBridgeRoute:{},page:null,resolvePageSession:(id,preferred)=>this.#sessions.resolvePageSession(id,preferred),setViewportSize:async(size)=>{const tabs=getAgentTabs(this);if(tabs?.get(targetId))await tabs.repin(targetId,size);else{if(entry.page===null)throw new TypeError("Cannot read properties of null (reading 'resolveSessionId')");await repinViewport(entry.page,size)}},resolvePath:(value)=>path3.resolve(this.#storageRoot,value),ensurePath:async(value)=>{const resolved=path3.resolve(this.#storageRoot,value);await mkdir4(path3.dirname(resolved),{recursive:true});return resolved},registerReadableDownloadPath:(value)=>value,isReadableDownload:()=>false,resolvePopup:async(metadata)=>{if(!this.#acceptsPopup(targetId))return;const queue=this.#popups.get(targetId)??[];const promise=new Promise((resolve,reject)=>queue.push({resolve,reject,metadata:{url:metadata.url,windowName:metadata.windowName}}));this.#popups.set(targetId,queue);this.#matchPopups(targetId);return promise},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 off of this.#popupOff)off();for(const queue of this.#popups.values()){for(const pending of queue)pending.reject(Error("Browser connection closed"))}this.#popups.clear();this.#popupTargets.clear();for(const pending of this.#attachingPopups.values())pending.reject(Error("Browser connection closed"));await Promise.all([...this.#attachingPopups.values()].map((pending)=>pending.operation));const tabs=getAgentTabs(this);if(tabs){await Promise.all([...this.#ownedPopups].filter((id)=>tabs.get(id)).map((id)=>tabs.close(id)));await tabs.dispose({closeOwned:false})}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[Symbol.asyncDispose](){await this.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:(snapshot)=>openConnection(key,snapshot)})}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","Emulation.setEmulatedMedia","Input.dispatchKeyEvent","Input.dispatchMouseEvent","Input.insertText","Inspector.enable","Network.disable","Network.enable","Network.getResponseBody","Network.setExtraHTTPHeaders","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.addBinding","Runtime.disable","Runtime.discardConsoleEntries","Runtime.enable","Runtime.evaluate","Runtime.releaseObject","Runtime.removeBinding","Runtime.runIfWaitingForDebugger","Target.activateTarget","Target.attachToTarget","Target.closeTarget","Target.createTarget","Target.detachFromTarget","Target.getTargetInfo","Target.getTargets","Target.setAutoAttach","Target.setDiscoverTargets"]);var DARWIN_EXCLUSIVE_NONBLOCK=32|4;var WINDOWS_EXCLUSIVE=268435456;var probedPaths=new Set;var DARWIN_BUSY_CODES=new Set(["EAGAIN","EWOULDBLOCK"]);async function lockLinux(fd){return new Promise((resolve,reject)=>{const child=spawn2("flock",["-n","3"],{stdio:["ignore","ignore","pipe",fd]});let stderr="";const stderrStream=child.stderr;if(stderrStream===null)throw new TypeError("flock child has no stderr pipe");stderrStream.setEncoding("utf8");stderrStream.on("data",(chunk)=>{stderr+=chunk});child.once("error",(error)=>{reject(error.code==="ENOENT"?new Error(`instance lock needs the flock utility (util-linux or busybox) on Linux: ${error.message}`,{cause:error}):error)});child.once("close",(code,signal)=>{if(code===0)resolve(true);else if(code===1&&stderr.trim()==="")resolve(false);else reject(Object.assign(new Error(`instance lock flock failed (${signal??code}): ${stderr.trim()}`),{code:"ERR_INSTANCE_LOCK"}))})})}async function tryAcquire(lockPath){const platform=process.platform;if(platform==="win32"&&process.versions.bun){await Promise.resolve().then(() => init_lock_backend_win32_xbcm60vz());return tryAcquireWindows(lockPath)}let flags=constants.O_RDWR|constants.O_CREAT;if(platform==="darwin")flags|=DARWIN_EXCLUSIVE_NONBLOCK;else if(platform==="win32")flags|=WINDOWS_EXCLUSIVE;else if(platform!=="linux")throw new Error(`instance lock is unsupported on ${platform}`);let handle;try{handle=await open2(lockPath,flags,384)}catch(error){if(platform==="darwin"&&DARWIN_BUSY_CODES.has(readProperty(error,"code")))return null;if(platform==="win32"&&readProperty(error,"code")==="EBUSY")return null;throw error}try{if(platform==="linux"&&!await lockLinux(handle.fd)){await handle.close();return null}}catch(error){await handle.close();throw error}return{release:()=>handle.close()}}async function probeOnce(lockPath){if(probedPaths.has(lockPath))return;const second=await tryAcquire(lockPath);if(second!==null){await second.release();throw new Error(`instance lock is not enforced for ${lockPath} on this runtime and filesystem`)}probedPaths.add(lockPath)}var localLocks=new Map;function errorCode(error){return error===null||error===undefined?undefined:readProperty(error,"code")}function isPidAlive(pid){try{process.kill(pid,0);return true}catch(error){if(errorCode(error)==="EPERM")return true;if(errorCode(error)==="ESRCH")return false;throw error}}async function unlinkIfPresent(target){await unlink2(target).catch((error)=>{if(errorCode(error)!=="ENOENT")throw error})}async function acquireLock(lockPath,timeoutMs){const deadline=performance.now()+timeoutMs;let delay=10;for(;;){const held=await tryAcquire(lockPath);if(held){try{await probeOnce(lockPath);return held}catch(error){await held.release();throw error}}const remaining=deadline-performance.now();if(remaining<=0)throw new Error(`timed out waiting for instance lock ${lockPath}`);await sleep(Math.min(remaining,delay*(0.75+Math.random()*0.5)));delay=Math.min(delay*2,250)}}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},run){const releaseLocal=await acquireLocalLock(lockPath);try{const held=await acquireLock(lockPath,timeoutMs);try{return await run()}finally{await held.release()}}finally{releaseLocal()}}var execFileAsync=promisify(execFile);async function processIsDefunct(pid){if(process.platform==="win32")return false;if(process.platform==="linux"){try{const text=await readFile3(`/proc/${pid}/stat`,"utf8");return text.slice(text.lastIndexOf(")")+2).startsWith("Z")}catch{return false}}try{const{stdout}=await execFileAsync("ps",["-o","stat=","-p",String(pid)],{env:{...process.env,LC_ALL:"C"}});return stdout.trim().startsWith("Z")}catch{return false}}var execFileAsync2=promisify2(execFile2);var WINDOWS_START_TIME_TIMEOUT_MS=15000;var ownStartTime;async function processStartTime(pid){if(process.platform==="win32"){if(!Number.isInteger(pid)||pid<=0)return null;const systemRoot=process.env["SystemRoot"]||process.env["windir"]||"C:\\Windows";try{const{stdout}=await execFileAsync2(path4.win32.join(systemRoot,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId=${pid}').CreationDate.ToFileTimeUtc()`],{timeout:WINDOWS_START_TIME_TIMEOUT_MS,windowsHide:true});const ticks=String(stdout).trim();return/^\d+$/.test(ticks)?ticks:null}catch{return null}}if(process.platform==="linux"){try{const text=await readFile4(`/proc/${pid}/stat`,"utf8");return text.slice(text.lastIndexOf(")")+2).split(" ")[19]??null}catch{return null}}try{const{stdout}=await execFileAsync2("ps",["-o","lstart=","-p",String(pid)],{env:{...process.env,LC_ALL:"C",TZ:"UTC"}});return stdout.trim()||null}catch{return null}}function ownProcessStartTime(){ownStartTime??=processStartTime(process.pid);return ownStartTime}var TERM_GRACE_MS=5000;var PID_FILE_NAME="omowright-browser.pid";var REAP_POLL_MS=50;var KILL_SETTLE_MS=2000;var browserSpawnDetached=process.platform!=="win32";function profileDirFromArgs(browserArgs){for(const[index,argument]of browserArgs.entries()){const next=browserArgs[index+1];if(argument==="--user-data-dir"&&next)return path5.resolve(next);if(argument.startsWith("--user-data-dir="))return path5.resolve(argument.slice("--user-data-dir=".length))}return null}var signalsCanAskToQuit=process.platform!=="win32";async function terminateChild(child,{quitRequested=false}={}){if(child.pid===undefined)return;if(child.exitCode!==null||child.signalCode!==null)return;const exited=new Promise((resolve)=>child.once("exit",resolve));if(signalsCanAskToQuit){try{child.kill("SIGTERM")}catch{}}if(signalsCanAskToQuit||quitRequested){let timer;const graceOver=new Promise((resolve)=>{timer=setTimeout(resolve,TERM_GRACE_MS)});await Promise.race([exited,graceOver]);clearTimeout(timer)}if(child.exitCode===null&&child.signalCode===null){try{child.kill("SIGKILL")}catch{}await exited}}function pidFilePath(profileDir){return path5.join(profileDir,PID_FILE_NAME)}async function writeBrowserPidFile(profileDir,pid){if(!profileDir||!pid)return;const[start,ownerStart]=await Promise.all([processStartTime(pid),ownProcessStartTime()]);mkdirSync(profileDir,{recursive:true});const record={pid,start,profileDir,owner:{pid:process.pid,start:ownerStart}};writeFileSync(pidFilePath(profileDir),`${JSON.stringify(record)}
1326
+ `,{mode:384})}function removeBrowserPidFile(profileDir,pid){if(!profileDir)return;try{const recorded=JSON.parse(readFileSync2(pidFilePath(profileDir),"utf8"));if(readProperty(recorded,"pid")!==pid)return}catch{return}rmSync(pidFilePath(profileDir),{force:true})}async function sameProcessAlive(pid,start){if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0)return null;if(!isPidAlive(pid))return false;if(start===null||start===undefined)return null;const now=await processStartTime(pid);if(now===null)return null;return now===start}async function reapOrphanedBrowser(profileDir){if(!profileDir)return;let recorded;try{recorded=JSON.parse(readFileSync2(pidFilePath(profileDir),"utf8"))}catch{return}const pid=readProperty(recorded,"pid");const start=readProperty(recorded,"start");const owner=readProperty(recorded,"owner");if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0){rmSync(pidFilePath(profileDir),{force:true});return}const browserAlive=await sameProcessAlive(pid,start);if(browserAlive===false){rmSync(pidFilePath(profileDir),{force:true});return}if(browserAlive===null||pid===process.pid)return;const ownerAlive=owner===null||owner===undefined?await sameProcessAlive(undefined,undefined):await sameProcessAlive(readProperty(owner,"pid"),readProperty(owner,"start"));if(ownerAlive!==false)return;try{process.kill(pid,"SIGTERM")}catch{}if(!await processGone(pid,TERM_GRACE_MS)&&!await processIsDefunct(pid)){const stillTheBrowser=await sameProcessAlive(pid,start);if(stillTheBrowser===true){try{process.kill(pid,"SIGKILL")}catch{}}const stillRunning=stillTheBrowser!==false&&!await processGone(pid,KILL_SETTLE_MS)&&!await processIsDefunct(pid)&&isPidAlive(pid);if(stillRunning){const sent=stillTheBrowser===true?"SIGTERM and SIGKILL":"SIGTERM";throw new Error(`omowright: the orphaned browser (pid ${pid}) is still running after ${sent}; its profile ${profileDir} is not reused`)}}rmSync(pidFilePath(profileDir),{force:true})}async function processGone(pid,withinMs){const deadline=Date.now()+withinMs;while(isPidAlive(pid)&&Date.now()<deadline)await sleep2(REAP_POLL_MS);return!isPidAlive(pid)}class NulFrameReader{#parts=[];push(chunk){const frames=[];let start=0;let end;while((end=chunk.indexOf(0,start))!==-1){const tail=chunk.subarray(start,end);let frame=tail;if(this.#parts.length>0){this.#parts.push(tail);frame=Buffer.concat(this.#parts);this.#parts=[]}frames.push(frame.toString("utf8"));start=end+1}if(start<chunk.length)this.#parts.push(chunk.subarray(start));return frames}}class SerialEmitter{#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;var EXIT_STDERR_DRAIN_MS=1000;class PipeCdpClient{#child;#writeStream;#readStream;#frames=new NulFrameReader;#seq=1;#pending=new Map;#closedSessions=new Set;#sessionTargets=new Map;#launch;#launchId;#launchedAt=0;#receivedBytes=0;#malformedFrameCount=0;#events=new SerialEmitter;#connected=false;#closedByCaller=false;#commandTimeoutMs;#readinessTimeoutMs;#browserPath;#browserArgs;#spawnOptions;#stdioTail="";#stderrHead="";#dialogPolicy;transportEvents=new SerialEmitter;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(){this.#closedByCaller=false;if(this.#connected)return;const stdio=["ignore","pipe","pipe","pipe","pipe"];const profileDir=profileDirFromArgs(this.#browserArgs);await reapOrphanedBrowser(profileDir);const child=spawn3(this.#browserPath,[...this.#browserArgs,"--remote-debugging-pipe"],{detached:browserSpawnDetached,...this.#spawnOptions,stdio});this.#child=child;const spawnFailed=new Promise((resolve)=>child.once("error",resolve));if(child.pid===undefined){const error=await spawnFailed;this.#child=undefined;throw error}const browserPid=child.pid;const launch={};this.#launch=launch;const owned=(listener)=>(...args)=>{if(this.#launch===launch)listener(...args)};this.#launchId=`${this.logId}:${browserPid}`;this.#launchedAt=performance.now();this.#receivedBytes=0;this.#malformedFrameCount=0;this.#frames=new NulFrameReader;this.#sessionTargets.clear();this.#closedSessions.clear();child.once("exit",()=>removeBrowserPidFile(profileDir,browserPid));this.#stdioTail="";this.#stderrHead="";const stderr=child.stderr;for(const stream of[child.stdout,stderr]){if(!stream)continue;stream.setEncoding("utf8");stream.on("data",(chunk)=>{this.#stdioTail=(this.#stdioTail+chunk).slice(-STDIO_TAIL_LIMIT);if(stream===stderr&&this.#stderrHead.length<STDIO_TAIL_LIMIT&&!this.#stderrHead.trimStart().includes(`
1327
1327
  `)){this.#stderrHead=(this.#stderrHead+chunk).slice(0,STDIO_TAIL_LIMIT)}});stream.on("error",()=>{})}const writeStream=child.stdio[3];const readStream=child.stdio[4];if(!writeStream||!("write"in writeStream))throw new TypeError("CDP pipe write stream (fd 3) is missing");if(!readStream||!("read"in readStream))throw new TypeError("CDP pipe read stream (fd 4) is missing");this.#writeStream=writeStream;this.#readStream=readStream;readStream.on("data",owned((chunk)=>this.#onData(chunk)));for(const event of["end","close"]){readStream.on(event,owned(()=>this.#failCommands(CdpPipeClosedError,`CDP pipe read stream ${event}`)))}for(const stream of[writeStream,readStream]){stream.on("error",owned((error)=>this.#failAll(Error(`CDP pipe error: ${error.code??error.message}`))))}child.on("exit",owned(()=>{this.#connected=false;this.#failAll(Error("CDP pipe browser exited"));this.transportEvents.emit("disconnected").catch(()=>{})}));try{await writeBrowserPidFile(profileDir,browserPid)}catch(error){await this.#quitFailedLaunch();throw error}this.#connected=true;try{await this.#awaitReady();await this.#dispatch("Target.setDiscoverTargets",{discover:true}).catch(()=>{});await this.transportEvents.emit("connected")}catch(error){await this.#quitFailedLaunch();throw error}}async#quitFailedLaunch(){const child=this.#child;this.#child=undefined;this.#connected=false;this.#failAll(Error("CDP pipe launch failed"));if(child===undefined)throw new TypeError("Cannot read properties of undefined (reading 'pid')");await terminateChild(child)}async#awaitReady(){const child=this.#child;if(child===undefined)throw new TypeError("Cannot read properties of undefined (reading 'exitCode')");const deadline=Date.now()+this.#readinessTimeoutMs;const exited=child.exitCode!==null||child.signalCode!==null?Promise.resolve("exited"):new Promise((resolve)=>child.once("exit",()=>resolve("exited")));let lastError;while(Date.now()<deadline){try{const outcome=await Promise.race([this.#dispatch("Browser.getVersion",undefined,undefined,{timeoutMs:1000}),exited]);if(outcome!=="exited")return}catch(error){lastError=error}if(child.exitCode!==null||child.signalCode!==null)throw await this.#exitedBeforeReady(child,deadline);let timer;try{await Promise.race([new Promise((resolve)=>{timer=setTimeout(resolve,100)}),exited])}finally{clearTimeout(timer)}}const reason=lastError?String(readProperty(lastError,"message")??lastError):"no response";const tail=this.#stdioTail.trim();throw Error(`Browser did not become ready over the CDP pipe (${reason})`+(tail?`
1328
1328
  Browser stdio tail:
1329
1329
  ${tail}`:""))}async#exitedBeforeReady(child,deadline){if(child.stderr){let timer;await Promise.race([finished(child.stderr).catch(()=>{}),new Promise((resolve)=>{timer=setTimeout(resolve,Math.max(0,Math.min(EXIT_STDERR_DRAIN_MS,deadline-Date.now())))})]);clearTimeout(timer)}const how=child.signalCode?`signal ${child.signalCode}`:`exit code ${child.exitCode}`;const firstLine=this.#stderrHead.split(`
@@ -1331,10 +1331,10 @@ ${tail}`:""))}async#exitedBeforeReady(child,deadline){if(child.stderr){let timer
1331
1331
  `);const repeat=tailLines.findIndex((line)=>line.trim()===firstLine);if(repeat!==-1)tailLines.splice(repeat,1);const tail=tailLines.join(`
1332
1332
  `).trim();return Error(`Browser exited before it became ready over the CDP pipe (${how})`+(firstLine?`: ${firstLine}`:"")+(tail?`
1333
1333
  Browser stdio tail:
1334
- ${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}`)}if(this.#closedByCaller){throw this.#commandError(CdpPipeClosedError,"CDP pipe client closed",{method,sessionId,targetId:this.#sessionTargets.get(sessionId),sentAt:performance.now(),receivedBytes:this.#receivedBytes})}await this.ensureConnected();return this.#dispatch(method,params,sessionId,opts)}async#dispatch(method,params,sessionId,opts={}){const id=this.#seq++;const msg={id,method};if(params!==undefined)msg.params=params;if(sessionId)msg.sessionId=sessionId;const entry={method,sessionId,targetId:(params===undefined||params===null?undefined:readProperty(params,"targetId"))??this.#sessionTargets.get(sessionId),sentAt:performance.now(),receivedBytes:this.#receivedBytes};if(this.#closedSessions.has(sessionId)&&method!=="Page.close"){throw this.#commandError(CdpSessionDetachedError,"Page closed",entry)}const readStream=this.#readStream;if(readStream===undefined)throw new TypeError("Cannot read properties of undefined (reading 'readableEnded')");if(readStream.readableEnded||readStream.destroyed){throw this.#commandError(CdpPipeClosedError,"CDP pipe read stream closed",entry)}const{promise,resolve,reject}=Promise.withResolvers();const timeoutMs=opts.timeoutMs??this.#commandTimeoutMs;const timeout=timeoutMs>0?setTimeout(()=>{this.#pending.delete(id);reject(this.#commandError(CdpCommandTimeoutError,"CDP command timeout",entry))},timeoutMs):undefined;this.#pending.set(id,{...entry,resolve,reject,timeout});if(this.#writeStream===undefined)throw new TypeError("Cannot read properties of undefined (reading 'write')");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}))}closeSession(sessionId){this.#closedSessions.add(sessionId);this.#failCommands(CdpSessionDetachedError,"Page closed",sessionId)}async close(){this.#closedByCaller=true;const child=this.#child;this.#child=undefined;if(child&&child.exitCode===null){const exited=new Promise((resolve)=>child.once("exit",resolve));let quitRequested=false;if(this.#connected){await Promise.race([this.#dispatch("Browser.close",undefined,undefined,{timeoutMs:GRACEFUL_CLOSE_TIMEOUT_MS}).then(()=>{quitRequested=true},()=>{}),exited])}this.#connected=false;this.#failAll(Error("CDP pipe client closed"));if(child.exitCode===null){let timer;try{await Promise.race([exited,new Promise((resolve)=>{timer=setTimeout(resolve,GRACEFUL_CLOSE_TIMEOUT_MS)})])}finally{clearTimeout(timer)}}await terminateChild(child,{quitRequested});return}this.#connected=false;this.#failAll(Error("CDP pipe client closed"))}#onData(chunk){this.#receivedBytes+=chunk.length;for(const raw of this.#frames.push(chunk)){if(raw.length===0)continue;let msg;try{msg=JSON.parse(raw)}catch{this.#malformedFrameCount++;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{if(entry.method==="Target.attachToTarget"&&msg.result?.sessionId){this.#sessionTargets.set(msg.result.sessionId,entry.targetId)}entry.resolve(msg.result)}return}if(typeof msg.method==="string"){if(msg.method==="Target.attachedToTarget"&&msg.params?.sessionId&&msg.params.targetInfo?.targetId){this.#sessionTargets.set(msg.params.sessionId,msg.params.targetInfo.targetId)}else if(msg.method==="Target.detachedFromTarget"&&msg.params?.sessionId){this.#failCommands(CdpSessionDetachedError,"CDP session detached",msg.params.sessionId);this.#sessionTargets.delete(msg.params.sessionId)}else if(msg.method==="Inspector.targetCrashed"&&msg.sessionId){this.#failCommands(CdpSessionCrashedError,"CDP session crashed",msg.sessionId,"Page.reload")}const meta={sessionId:msg.sessionId};const dialogSessionId=msg.sessionId;if(msg.method==="Page.javascriptDialogOpening"&&dialogSessionId){meta.dialog=new Dialog(msg.params,(action)=>this.send("Page.handleJavaScriptDialog",action,dialogSessionId))}const emitted=this.#events.emit(msg.method,{data:{payload:msg.params,meta}}).catch(()=>{});const{dialog}=meta;return dialog?emitted.then(()=>answerWithPolicy(dialog,this.#dialogPolicy,msg.params)).catch(()=>{}):undefined}}#commandError(ErrorType,reason,entry){const now=performance.now();const receivedBytesSinceSend=this.#receivedBytes-entry.receivedBytes;const details={method:entry.method,launchId:this.#launchId,sessionId:entry.sessionId??null,targetId:entry.targetId??this.#sessionTargets.get(entry.sessionId)??null,elapsedSinceLaunchMs:Math.round(now-this.#launchedAt),commandElapsedMs:Math.round(now-entry.sentAt),receivedReplyBytes:receivedBytesSinceSend>0,receivedBytesSinceSend,malformedFrameCount:this.#malformedFrameCount};const context=Object.entries(details).map(([key,value])=>`${key}=${value}`).join(", ");return new ErrorType(`${reason}: ${entry.method} (${context})`,details)}#failCommands(ErrorType,reason,sessionId,sparedMethod){for(const[id,entry]of this.#pending){if(sessionId!==undefined&&entry.sessionId!==sessionId)continue;if(entry.method===sparedMethod)continue;if(entry.timeout)clearTimeout(entry.timeout);this.#pending.delete(id);entry.reject(this.#commandError(ErrorType,reason,entry))}}#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}function errorCode2(error){return error===null||error===undefined?undefined:readProperty(error,"code")}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;const activePortPath=path6.join(profileDir,"DevToolsActivePort");try{const identity=activePortIdentity(await stat(activePortPath));return{...identity,text:await readFile4(activePortPath,"utf8")}}catch(error){if(errorCode2(error)==="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?path6.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(portPath)=>{const info=await stat(portPath);if(isSameFile(activePortIdentity(info),previousActivePort))return;const text=await readFile4(portPath,"utf8");if(previousActivePort!==null&&text===previousActivePort.text)return;const report=parseActivePort(text);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(activePortPath)}while(activePortChangedWhileReading&&!settled)}catch(error){if(errorCode2(error)!=="ENOENT")finish(error)}finally{activePortReading=false}};const onStderr=(chunk)=>{stderr=`${stderr}${chunk}`.slice(-16384);const match=/DevTools listening on (ws:\/\/\S+)/.exec(stderr);const webSocketUrl=match?.[1];if(webSocketUrl!==undefined){finish(null,{endpoint:httpEndpointFromWebSocket(webSocketUrl),browserPath:new URL(webSocketUrl).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?`
1334
+ ${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}`)}if(this.#closedByCaller){throw this.#commandError(CdpPipeClosedError,"CDP pipe client closed",{method,sessionId,targetId:this.#sessionTargets.get(sessionId),sentAt:performance.now(),receivedBytes:this.#receivedBytes})}await this.ensureConnected();return this.#dispatch(method,params,sessionId,opts)}async#dispatch(method,params,sessionId,opts={}){const id=this.#seq++;const msg={id,method};if(params!==undefined)msg.params=params;if(sessionId)msg.sessionId=sessionId;const entry={method,sessionId,targetId:(params===undefined||params===null?undefined:readProperty(params,"targetId"))??this.#sessionTargets.get(sessionId),sentAt:performance.now(),receivedBytes:this.#receivedBytes};if(this.#closedSessions.has(sessionId)&&method!=="Page.close"){throw this.#commandError(CdpSessionDetachedError,"Page closed",entry)}const readStream=this.#readStream;if(readStream===undefined)throw new TypeError("Cannot read properties of undefined (reading 'readableEnded')");if(readStream.readableEnded||readStream.destroyed){throw this.#commandError(CdpPipeClosedError,"CDP pipe read stream closed",entry)}const{promise,resolve,reject}=Promise.withResolvers();const timeoutMs=opts.timeoutMs??this.#commandTimeoutMs;const timeout=timeoutMs>0?setTimeout(()=>{this.#pending.delete(id);reject(this.#commandError(CdpCommandTimeoutError,"CDP command timeout",entry))},timeoutMs):undefined;this.#pending.set(id,{...entry,resolve,reject,timeout});if(this.#writeStream===undefined)throw new TypeError("Cannot read properties of undefined (reading 'write')");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}))}closeSession(sessionId){this.#closedSessions.add(sessionId);this.#failCommands(CdpSessionDetachedError,"Page closed",sessionId)}async close(){this.#closedByCaller=true;const child=this.#child;this.#child=undefined;if(child&&child.exitCode===null){const exited=new Promise((resolve)=>child.once("exit",resolve));let quitRequested=false;if(this.#connected){await Promise.race([this.#dispatch("Browser.close",undefined,undefined,{timeoutMs:GRACEFUL_CLOSE_TIMEOUT_MS}).then(()=>{quitRequested=true},()=>{}),exited])}this.#connected=false;this.#failAll(Error("CDP pipe client closed"));if(child.exitCode===null){let timer;try{await Promise.race([exited,new Promise((resolve)=>{timer=setTimeout(resolve,GRACEFUL_CLOSE_TIMEOUT_MS)})])}finally{clearTimeout(timer)}}await terminateChild(child,{quitRequested});return}this.#connected=false;this.#failAll(Error("CDP pipe client closed"))}#onData(chunk){this.#receivedBytes+=chunk.length;for(const raw of this.#frames.push(chunk)){if(raw.length===0)continue;let msg;try{msg=JSON.parse(raw)}catch{this.#malformedFrameCount++;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{if(entry.method==="Target.attachToTarget"&&msg.result?.sessionId){this.#sessionTargets.set(msg.result.sessionId,entry.targetId)}entry.resolve(msg.result)}return}if(typeof msg.method==="string"){if(msg.method==="Target.attachedToTarget"&&msg.params?.sessionId&&msg.params.targetInfo?.targetId){this.#sessionTargets.set(msg.params.sessionId,msg.params.targetInfo.targetId)}else if(msg.method==="Target.detachedFromTarget"&&msg.params?.sessionId){this.#failCommands(CdpSessionDetachedError,"CDP session detached",msg.params.sessionId);this.#sessionTargets.delete(msg.params.sessionId)}else if(msg.method==="Inspector.targetCrashed"&&msg.sessionId){this.#failCommands(CdpSessionCrashedError,"CDP session crashed",msg.sessionId,"Page.reload")}const meta={sessionId:msg.sessionId};const dialogSessionId=msg.sessionId;if(msg.method==="Page.javascriptDialogOpening"&&dialogSessionId){meta.dialog=new Dialog(msg.params,(action)=>this.send("Page.handleJavaScriptDialog",action,dialogSessionId))}const emitted=this.#events.emit(msg.method,{data:{payload:msg.params,meta}}).catch(()=>{});const{dialog}=meta;return dialog?emitted.then(()=>answerWithPolicy(dialog,this.#dialogPolicy,msg.params)).catch(()=>{}):undefined}}#commandError(ErrorType,reason,entry){const now=performance.now();const receivedBytesSinceSend=this.#receivedBytes-entry.receivedBytes;const details={method:entry.method,launchId:this.#launchId,sessionId:entry.sessionId??null,targetId:entry.targetId??this.#sessionTargets.get(entry.sessionId)??null,elapsedSinceLaunchMs:Math.round(now-this.#launchedAt),commandElapsedMs:Math.round(now-entry.sentAt),receivedReplyBytes:receivedBytesSinceSend>0,receivedBytesSinceSend,malformedFrameCount:this.#malformedFrameCount};const context=Object.entries(details).map(([key,value])=>`${key}=${value}`).join(", ");return new ErrorType(`${reason}: ${entry.method} (${context})`,details)}#failCommands(ErrorType,reason,sessionId,sparedMethod){for(const[id,entry]of this.#pending){if(sessionId!==undefined&&entry.sessionId!==sessionId)continue;if(entry.method===sparedMethod)continue;if(entry.timeout)clearTimeout(entry.timeout);this.#pending.delete(id);entry.reject(this.#commandError(ErrorType,reason,entry))}}#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}function errorCode2(error){return error===null||error===undefined?undefined:readProperty(error,"code")}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;const activePortPath=path6.join(profileDir,"DevToolsActivePort");try{const identity=activePortIdentity(await stat(activePortPath));return{...identity,text:await readFile5(activePortPath,"utf8")}}catch(error){if(errorCode2(error)==="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?path6.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(portPath)=>{const info=await stat(portPath);if(isSameFile(activePortIdentity(info),previousActivePort))return;const text=await readFile5(portPath,"utf8");if(previousActivePort!==null&&text===previousActivePort.text)return;const report=parseActivePort(text);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(activePortPath)}while(activePortChangedWhileReading&&!settled)}catch(error){if(errorCode2(error)!=="ENOENT")finish(error)}finally{activePortReading=false}};const onStderr=(chunk)=>{stderr=`${stderr}${chunk}`.slice(-16384);const match=/DevTools listening on (ws:\/\/\S+)/.exec(stderr);const webSocketUrl=match?.[1];if(webSocketUrl!==undefined){finish(null,{endpoint:httpEndpointFromWebSocket(webSocketUrl),browserPath:new URL(webSocketUrl).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?`
1335
1335
  ${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&&profileDir){try{activePortWatcher=watch(profileDir,(event,filename)=>{if((event==="rename"||event==="change")&&(!filename||filename.toString()===path6.basename(activePortPath))){tryActivePort()}})}catch(error){if(errorCode2(error)!=="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?`
1336
- ${stderr}`:""}`))},timeoutMs);cleanups.push(()=>clearTimeout(timeout))})}var execFileAsync2=promisify2(execFile2);var WINDOWS_COMMAND_TIMEOUT_MS=15000;var ownerOnlyDirectories=new Set;var TRUSTED_TRUSTEES=new Set(["SY","S-1-5-18","BA","S-1-5-32-544","S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464","OW","S-1-3-4","CO","S-1-3-0"]);var DENY_ACE_TYPES=new Set(["D","OD","XD"]);var currentUserSid;function windowsSystemTool(name,env=process.env){return path7.win32.join(env["SystemRoot"]||env["windir"]||"C:\\Windows","System32",name)}async function readCurrentUserSid(run){const{stdout}=await run(windowsSystemTool("whoami.exe"),["/user","/fo","csv","/nh"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true});const sid=/"(S-1-[\d-]+)"\s*$/.exec(String(stdout).trim())?.[1];if(!sid)throw new Error(`cannot read the current user's SID from whoami: ${String(stdout).trim()}`);return sid}function cachedCurrentUserSid(){currentUserSid??=readCurrentUserSid(execFileAsync2).catch((error)=>{currentUserSid=undefined;throw error});return currentUserSid}async function readDirectoryDacl(dir,run){const scratch=await mkdtemp(path7.join(tmpdir2(),"omowright-acl-"));try{const saved=path7.join(scratch,"acl");await run(windowsSystemTool("icacls.exe"),[dir,"/save",saved,"/Q"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true});const bytes=await readFile5(saved);const text=bytes.length>1&&bytes[1]===0?bytes.toString("utf16le"):bytes.toString("utf8");return/D:[^\r\n]*/.exec(text)?.[0]??""}finally{await rm(scratch,{recursive:true,force:true})}}function parseDacl(dacl){const head=/^D:([A-Z]*)/.exec(dacl);if(!head)return null;const aces=[];let depth=0;let start=0;let i=head[0].length;for(;i<dacl.length;i++){const c=dacl[i];if(c==='"'&&depth>0){i=dacl.indexOf('"',i+1);if(i===-1)return null}else if(c==="("){if(depth++===0)start=i+1}else if(c===")"){if(depth===0)return null;if(--depth===0)aces.push(dacl.slice(start,i).split(";"))}else if(depth===0){break}}if(depth!==0||i<dacl.length&&!dacl.startsWith("S:",i))return null;return{flags:dacl.slice("D:".length,head[0].length),aces}}function inspectDirectoryDacl(text,sid){const dacl=parseDacl(text);if(!dacl)return{parsed:false,ownerOnly:false,foreign:[]};const isUser=(trustee)=>trustee===sid||trustee==="LA"&&sid.endsWith("-500")||trustee==="LG"&&sid.endsWith("-501");const own=dacl.aces.filter((fields)=>isUser(fields[5]));const others=dacl.aces.filter(([type,,,,,trustee])=>!isUser(trustee)&&!TRUSTED_TRUSTEES.has(trustee)&&!DENY_ACE_TYPES.has(type));return{parsed:true,ownerOnly:dacl.flags.includes("P")&&others.length===0&&own.length===1&&own[0]?.[0]==="A"&&own[0]?.[1]==="OICI"&&own[0]?.[2]==="FA",foreign:[...new Set(others.filter(([,flags])=>!String.prototype.includes.call(flags,"ID")).map(([,,,,,trustee])=>trustee))]}}async function directoryIdentity(dir){const{dev,ino,birthtimeNs}=await stat2(dir,{bigint:true});return ino===0n?null:`${dev}:${ino}:${birthtimeNs}`}async function rememberOwnerOnlyDirectory(dir){const identity=await directoryIdentity(dir).catch(()=>null);if(identity)ownerOnlyDirectories.add(identity)}async function restrictToOwner(target,kind,{platform=process.platform,run}={}){if(platform!=="win32"){await chmod(target,kind==="directory"?448:384);return}const command=run??execFileAsync2;const sid=run?await readCurrentUserSid(run):await cachedCurrentUserSid();const dacl=kind==="directory"?inspectDirectoryDacl(await readDirectoryDacl(target,command),sid):null;if(dacl?.ownerOnly){await rememberOwnerOnlyDirectory(target);return}const grant=kind==="directory"?`*${sid}:(OI)(CI)F`:`*${sid}:F`;await command(windowsSystemTool("icacls.exe"),[target,"/inheritance:r","/grant:r",grant,"/Q"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true});if(!dacl)return;if(dacl.foreign.length>0){await command(windowsSystemTool("icacls.exe"),[target,"/remove:g",...dacl.foreign.map((trustee)=>`*${trustee}`),"/Q"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true})}if(dacl.parsed)await rememberOwnerOnlyDirectory(target)}var RECORD_VERSION=2;var DEFAULT_REGISTRY_ROOT=path8.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 BROWSER_CLOSE_TIMEOUT_MS=2000;var LOCK_TIMEOUT_MARGIN_MS=5000;var DEFAULT_LOCK_TIMEOUT_MS=resolveLockTimeoutMs({});function errorCode3(error){return error===null||error===undefined?undefined:readProperty(error,"code")}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=path8.resolve(registryRoot??DEFAULT_REGISTRY_ROOT);return{root,recordPath:path8.join(root,`${name}.json`),lockPath:path8.join(root,`${name}.flock`)}}async function ensureRegistryRoot(root){await mkdir5(root,{recursive:true,mode:448});await restrictToOwner(root,"directory")}function isRecord(value,expectedName){if(value===null||typeof value!=="object")return false;const pid=readProperty(value,"pid");const endpoint=readProperty(value,"endpoint");const webSocketDebuggerUrl=readProperty(value,"webSocketDebuggerUrl");const profileDir=readProperty(value,"profileDir");const browserPath=readProperty(value,"browserPath");const startedAt=readProperty(value,"startedAt");return readProperty(value,"version")===RECORD_VERSION&&readProperty(value,"name")===expectedName&&typeof pid==="number"&&Number.isInteger(pid)&&pid>0&&typeof endpoint==="string"&&endpoint.length>0&&typeof webSocketDebuggerUrl==="string"&&webSocketDebuggerUrl.length>0&&(typeof profileDir==="string"||profileDir===null)&&typeof browserPath==="string"&&browserPath.length>0&&typeof startedAt==="string"&&!Number.isNaN(Date.parse(startedAt))}async function readRecord(recordPath,expectedName){let text;try{text=await readFile6(recordPath,"utf8")}catch(error){if(errorCode3(error)==="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=path8.join(root,`.${record.name}.${process.pid}.${randomUUID2()}.tmp`);let handle;try{handle=await open3(tempPath,"wx",384);await handle.writeFile(`${JSON.stringify(record,null,2)}
1337
- `,"utf8");await handle.close();handle=null;await restrictToOwner(tempPath,"file");await rename(tempPath,recordPath);await restrictToOwner(recordPath,"file")}catch(error){await handle?.close().catch(()=>{});await unlink3(tempPath).catch(()=>{});throw error}}function isConnectionRefused(error){for(let cause=error;cause;cause=readProperty(cause,"cause")){const code=readProperty(cause,"code");if(code==="ECONNREFUSED"||code==="ENOTFOUND"||code==="ConnectionRefused"){return true}}return false}function isBrowserVersion(value){if(value===null||value===undefined)return false;const webSocketDebuggerUrl=readProperty(value,"webSocketDebuggerUrl");return typeof webSocketDebuggerUrl==="string"&&webSocketDebuggerUrl.length>0}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(!isBrowserVersion(version)){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??resolveConnectTimeoutMs(options))+resolveConnectTimeoutMs(options)+LOCK_TIMEOUT_MARGIN_MS}function nameLockOptions(options){return{timeoutMs:resolveLockTimeoutMs(options)}}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 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 askBrowserToQuit(connection,child,disconnect){if(child.exitCode!==null||child.signalCode!==null||!readProperty(connection.cdp,"isConnected")){await disconnect();return false}const exited=new Promise((resolve)=>child.once("exit",resolve));const quitRequested=await Promise.race([connection.cdp.send("Browser.close",undefined,undefined,{timeoutMs:BROWSER_CLOSE_TIMEOUT_MS}).then(()=>true,()=>false),exited.then(()=>true)]);await disconnect();if(child.exitCode===null&&child.signalCode===null){let timer;await Promise.race([exited,new Promise((resolve)=>{timer=setTimeout(resolve,BROWSER_CLOSE_TIMEOUT_MS)})]);clearTimeout(timer)}return quitRequested}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?path8.resolve(options.profileDir):profileDirFromArgs(browserArgs);const previousActivePort=await snapshotActivePort(profileDir);const child=spawn4(options.browserPath,[...browserArgs,"--remote-debugging-address=127.0.0.1","--remote-debugging-port=0"],{...process.platform==="win32"?{detached:true}:{},...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});if(report===undefined)throw new TypeError("launch endpoint discovery settled without a report");const{endpoint}=report;const{webSocketDebuggerUrl}=await probeEndpoint(endpoint,launchTimeoutMs);assertLaunchedBrowser(child,report,webSocketDebuggerUrl);const opened=await connectWithin(endpoint,connectionOptions(options,profileDir),resolveConnectTimeoutMs(options));connection=opened;const record={version:RECORD_VERSION,name,pid:child.pid,endpoint,webSocketDebuggerUrl,profileDir,browserPath:path8.resolve(options.browserPath),startedAt:new Date().toISOString()};await writeRecordAtomic(root,recordPath,record);opened.browserProcess=child;const disconnect=opened.close.bind(opened);opened.close=async()=>{let failure;const quitRequested=await askBrowserToQuit(opened,child,async()=>{try{await disconnect()}catch(error){failure=error}});await terminateChild(child,{quitRequested});try{await withLock(lockPath,nameLockOptions(options),()=>removeOwnedRecord(recordPath,name,child.pid))}catch(error){failure??=error}if(failure)throw failure};return opened}catch(error){await connection?.close().catch(()=>{});await terminateChild(child);throw error}}async function withEngineLock(registryRoot,engineKey,run){const root=path8.resolve(registryRoot??DEFAULT_REGISTRY_ROOT);await ensureRegistryRoot(root);const digest=createHash("sha256").update(path8.resolve(engineKey)).digest("hex").slice(0,16);const lockPath=path8.join(root,`_engine-${digest}.flock`);return withLock(lockPath,{timeoutMs:DEFAULT_LOCK_TIMEOUT_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 restrictToOwner(paths.recordPath,"file");if(isPidAlive(loaded.record.pid)){let version=null;try{version=await probeEndpoint(loaded.record.endpoint,options.probeTimeoutMs??resolveConnectTimeoutMs(options))}catch(error){if(!isConnectionRefused(error)){throw new Error(`unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${readProperty(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}: ${readProperty(error,"message")}`,{cause:error})}}}}if(loaded.exists){await unlink3(paths.recordPath).catch((error)=>{if(errorCode3(error)!=="ENOENT")throw error})}return await launchNamed(normalizedName,paths,options)}async function listInstances(options={}){const root=path8.resolve(options.registryRoot??DEFAULT_REGISTRY_ROOT);await ensureRegistryRoot(root);const entries=await readdir(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=path8.join(root,entry.name);const{record}=await readRecord(recordPath,expectedName);if(!record)return null;await restrictToOwner(recordPath,"file");const alive=isPidAlive(record.pid);let responsive=false;if(alive){responsive=await probeEndpoint(record.endpoint,options.probeTimeoutMs??DEFAULT_PROBE_TIMEOUT_MS).then((version)=>version.webSocketDebuggerUrl===record.webSocketDebuggerUrl,()=>false)}return Object.assign(record,{alive,responsive})}));return records.filter((record)=>record!==null).toSorted((left,right)=>left.name.localeCompare(right.name))}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))]);var pathFor=(platform)=>platform==="win32"?path9.win32:path9.posix;function macRow(b,home,exists){const{join}=path9.posix;const apps=[join("/Applications",`${b.app}.app`),join(home,"Applications",`${b.app}.app`)];const appPath=apps.find((p)=>exists(p))??null;const userDataDir=join(home,b.userData);return{id:b.id,label:b.label,store:b.store,userDataDir,binary:join(appPath??apps[0],"Contents","MacOS",b.app),bundleId:b.bundleId,processNames:apps.map((a)=>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=path9.posix.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{join}=path9.win32;const localAppData=env["LOCALAPPDATA"]??join(home,"AppData","Local");const programFiles=[localAppData,env["PROGRAMFILES"],env["PROGRAMFILES(X86)"],"C:\\Program Files","C:\\Program Files (x86)"].filter((root)=>Boolean(root));const userDataDir=join(localAppData,b.userData);const binary=programFiles.map((root)=>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=homedir(),env=process.env,exists=existsSync}={}){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 DEFAULT_PORT_CHECK_MS=1000;class RunningBrowserError extends Error{constructor(code,message,candidates=[]){super(message);this.name="RunningBrowserError";this.code=code;this.candidates=candidates}}async function readDevToolsActivePort(userDataDir){const text=await readFile7(path10.join(userDataDir,"DevToolsActivePort"),"utf8").catch(()=>null);if(text===null)return null;const[portLine="",wsPath=""]=text.split(/\r?\n/);const port=Number(portLine.trim());if(!Number.isInteger(port)||port<=0||port>65535)return null;const pathPart=wsPath.trim();return{port,wsPath:pathPart.startsWith("/devtools/browser")?pathPart:null}}function portIsListening(port,timeoutMs){return new Promise((resolve)=>{const socket=connectTcp({host:"127.0.0.1",port});const done=(live)=>{socket.destroy();resolve(live)};socket.setTimeout(timeoutMs,()=>done(false));socket.once("connect",()=>done(true));socket.once("error",()=>done(false))})}function candidateDirs({browser,userDataDirs,catalog}){if(userDataDirs)return userDataDirs.map((dir)=>({id:path10.basename(dir),label:dir,userDataDir:dir}));const rows=catalog().filter((row)=>row.hasProfile);return browser?rows.filter((row)=>row.id===browser):rows}async function findRunningBrowser({browser,userDataDirs,portCheckMs=DEFAULT_PORT_CHECK_MS,catalog=catalogBrowsers}={}){const live=[];for(const candidate of candidateDirs({browser,userDataDirs,catalog})){const active=await readDevToolsActivePort(candidate.userDataDir);if(!active||!active.wsPath)continue;if(!await portIsListening(active.port,portCheckMs))continue;live.push({...candidate,port:active.port,wsUrl:`ws://127.0.0.1:${active.port}${active.wsPath}`})}const[only]=live;if(live.length===1&&only!==undefined)return only;if(live.length===0){throw new RunningBrowserError("not_found","No running browser has remote debugging on. Ask the user to open chrome://inspect/#remote-debugging and allow it, then retry.")}throw new RunningBrowserError("choose_browser",`More than one browser has remote debugging on (${live.map((row)=>row.id).join(", ")}); pass { browser: "<id>" }.`,live)}async function connectRunningBrowser(options={}){const found=await findRunningBrowser(options);const browser=await connect(found.wsUrl,options.connect??{});return{browser,found}}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=path11.join(os2.homedir(),".local","share","omowright-cloak");function errorField(error,key){return error===null||error===undefined?undefined:readProperty(error,key)}function normalizeFingerprintSeed(value){const seed=typeof value==="string"&&value.trim()!==""?Number(value):value;if(typeof seed!=="number"||!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=path11.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 readFile8(metadataPath,"utf8"));return normalizeFingerprintSeed(readProperty(parsed,"fingerprintSeed"))}catch(error){if(errorField(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)}
1336
+ ${stderr}`:""}`))},timeoutMs);cleanups.push(()=>clearTimeout(timeout))})}var execFileAsync3=promisify3(execFile3);var WINDOWS_COMMAND_TIMEOUT_MS=15000;var ownerOnlyDirectories=new Set;var TRUSTED_TRUSTEES=new Set(["SY","S-1-5-18","BA","S-1-5-32-544","S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464","OW","S-1-3-4","CO","S-1-3-0"]);var DENY_ACE_TYPES=new Set(["D","OD","XD"]);var currentUserSid;function windowsSystemTool(name,env=process.env){return path7.win32.join(env["SystemRoot"]||env["windir"]||"C:\\Windows","System32",name)}async function readCurrentUserSid(run){const{stdout}=await run(windowsSystemTool("whoami.exe"),["/user","/fo","csv","/nh"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true});const sid=/"(S-1-[\d-]+)"\s*$/.exec(String(stdout).trim())?.[1];if(!sid)throw new Error(`cannot read the current user's SID from whoami: ${String(stdout).trim()}`);return sid}function cachedCurrentUserSid(){currentUserSid??=readCurrentUserSid(execFileAsync3).catch((error)=>{currentUserSid=undefined;throw error});return currentUserSid}async function readDirectoryDacl(dir,run){const scratch=await mkdtemp(path7.join(tmpdir2(),"omowright-acl-"));try{const saved=path7.join(scratch,"acl");await run(windowsSystemTool("icacls.exe"),[dir,"/save",saved,"/Q"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true});const bytes=await readFile6(saved);const text=bytes.length>1&&bytes[1]===0?bytes.toString("utf16le"):bytes.toString("utf8");return/D:[^\r\n]*/.exec(text)?.[0]??""}finally{await rm(scratch,{recursive:true,force:true})}}function parseDacl(dacl){const head=/^D:([A-Z]*)/.exec(dacl);if(!head)return null;const aces=[];let depth=0;let start=0;let i=head[0].length;for(;i<dacl.length;i++){const c=dacl[i];if(c==='"'&&depth>0){i=dacl.indexOf('"',i+1);if(i===-1)return null}else if(c==="("){if(depth++===0)start=i+1}else if(c===")"){if(depth===0)return null;if(--depth===0)aces.push(dacl.slice(start,i).split(";"))}else if(depth===0){break}}if(depth!==0||i<dacl.length&&!dacl.startsWith("S:",i))return null;return{flags:dacl.slice("D:".length,head[0].length),aces}}function inspectDirectoryDacl(text,sid){const dacl=parseDacl(text);if(!dacl)return{parsed:false,ownerOnly:false,foreign:[]};const isUser=(trustee)=>trustee===sid||trustee==="LA"&&sid.endsWith("-500")||trustee==="LG"&&sid.endsWith("-501");const own=dacl.aces.filter((fields)=>isUser(fields[5]));const others=dacl.aces.filter(([type,,,,,trustee])=>!isUser(trustee)&&!TRUSTED_TRUSTEES.has(trustee)&&!DENY_ACE_TYPES.has(type));return{parsed:true,ownerOnly:dacl.flags.includes("P")&&others.length===0&&own.length===1&&own[0]?.[0]==="A"&&own[0]?.[1]==="OICI"&&own[0]?.[2]==="FA",foreign:[...new Set(others.filter(([,flags])=>!String.prototype.includes.call(flags,"ID")).map(([,,,,,trustee])=>trustee))]}}async function directoryIdentity(dir){const{dev,ino,birthtimeNs}=await stat2(dir,{bigint:true});return ino===0n?null:`${dev}:${ino}:${birthtimeNs}`}async function rememberOwnerOnlyDirectory(dir){const identity=await directoryIdentity(dir).catch(()=>null);if(identity)ownerOnlyDirectories.add(identity)}async function restrictToOwner(target,kind,{platform=process.platform,run}={}){if(platform!=="win32"){await chmod(target,kind==="directory"?448:384);return}const command=run??execFileAsync3;const sid=run?await readCurrentUserSid(run):await cachedCurrentUserSid();const dacl=kind==="directory"?inspectDirectoryDacl(await readDirectoryDacl(target,command),sid):null;if(dacl?.ownerOnly){await rememberOwnerOnlyDirectory(target);return}const grant=kind==="directory"?`*${sid}:(OI)(CI)F`:`*${sid}:F`;await command(windowsSystemTool("icacls.exe"),[target,"/inheritance:r","/grant:r",grant,"/Q"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true});if(!dacl)return;if(dacl.foreign.length>0){await command(windowsSystemTool("icacls.exe"),[target,"/remove:g",...dacl.foreign.map((trustee)=>`*${trustee}`),"/Q"],{timeout:WINDOWS_COMMAND_TIMEOUT_MS,windowsHide:true})}if(dacl.parsed)await rememberOwnerOnlyDirectory(target)}var RECORD_VERSION=2;var DEFAULT_REGISTRY_ROOT=path8.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 BROWSER_CLOSE_TIMEOUT_MS=2000;var LOCK_TIMEOUT_MARGIN_MS=5000;var DEFAULT_LOCK_TIMEOUT_MS=resolveLockTimeoutMs({});function errorCode3(error){return error===null||error===undefined?undefined:readProperty(error,"code")}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=path8.resolve(registryRoot??DEFAULT_REGISTRY_ROOT);return{root,recordPath:path8.join(root,`${name}.json`),lockPath:path8.join(root,`${name}.flock`)}}async function ensureRegistryRoot(root){await mkdir5(root,{recursive:true,mode:448});await restrictToOwner(root,"directory")}function isRecord(value,expectedName){if(value===null||typeof value!=="object")return false;const pid=readProperty(value,"pid");const endpoint=readProperty(value,"endpoint");const webSocketDebuggerUrl=readProperty(value,"webSocketDebuggerUrl");const profileDir=readProperty(value,"profileDir");const browserPath=readProperty(value,"browserPath");const startedAt=readProperty(value,"startedAt");return readProperty(value,"version")===RECORD_VERSION&&readProperty(value,"name")===expectedName&&typeof pid==="number"&&Number.isInteger(pid)&&pid>0&&typeof endpoint==="string"&&endpoint.length>0&&typeof webSocketDebuggerUrl==="string"&&webSocketDebuggerUrl.length>0&&(typeof profileDir==="string"||profileDir===null)&&typeof browserPath==="string"&&browserPath.length>0&&typeof startedAt==="string"&&!Number.isNaN(Date.parse(startedAt))}async function readRecord(recordPath,expectedName){let text;try{text=await readFile7(recordPath,"utf8")}catch(error){if(errorCode3(error)==="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=path8.join(root,`.${record.name}.${process.pid}.${randomUUID2()}.tmp`);let handle;try{handle=await open3(tempPath,"wx",384);await handle.writeFile(`${JSON.stringify(record,null,2)}
1337
+ `,"utf8");await handle.close();handle=null;await restrictToOwner(tempPath,"file");await rename(tempPath,recordPath);await restrictToOwner(recordPath,"file")}catch(error){await handle?.close().catch(()=>{});await unlink3(tempPath).catch(()=>{});throw error}}function isConnectionRefused(error){for(let cause=error;cause;cause=readProperty(cause,"cause")){const code=readProperty(cause,"code");if(code==="ECONNREFUSED"||code==="ENOTFOUND"||code==="ConnectionRefused"){return true}}return false}function isBrowserVersion(value){if(value===null||value===undefined)return false;const webSocketDebuggerUrl=readProperty(value,"webSocketDebuggerUrl");return typeof webSocketDebuggerUrl==="string"&&webSocketDebuggerUrl.length>0}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(!isBrowserVersion(version)){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??resolveConnectTimeoutMs(options))+resolveConnectTimeoutMs(options)+LOCK_TIMEOUT_MARGIN_MS}function nameLockOptions(options){return{timeoutMs:resolveLockTimeoutMs(options)}}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 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 askBrowserToQuit(connection,child,disconnect){if(child.exitCode!==null||child.signalCode!==null||!readProperty(connection.cdp,"isConnected")){await disconnect();return false}const exited=new Promise((resolve)=>child.once("exit",resolve));const quitRequested=await Promise.race([connection.cdp.send("Browser.close",undefined,undefined,{timeoutMs:BROWSER_CLOSE_TIMEOUT_MS}).then(()=>true,()=>false),exited.then(()=>true)]);await disconnect();if(child.exitCode===null&&child.signalCode===null){let timer;await Promise.race([exited,new Promise((resolve)=>{timer=setTimeout(resolve,BROWSER_CLOSE_TIMEOUT_MS)})]);clearTimeout(timer)}return quitRequested}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?path8.resolve(options.profileDir):profileDirFromArgs(browserArgs);const previousActivePort=await snapshotActivePort(profileDir);const child=spawn4(options.browserPath,[...browserArgs,"--remote-debugging-address=127.0.0.1","--remote-debugging-port=0"],{...process.platform==="win32"?{detached:true}:{},...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});if(report===undefined)throw new TypeError("launch endpoint discovery settled without a report");const{endpoint}=report;const{webSocketDebuggerUrl}=await probeEndpoint(endpoint,launchTimeoutMs);assertLaunchedBrowser(child,report,webSocketDebuggerUrl);const opened=await connectWithin(endpoint,connectionOptions(options,profileDir),resolveConnectTimeoutMs(options));connection=opened;const record={version:RECORD_VERSION,name,pid:child.pid,endpoint,webSocketDebuggerUrl,profileDir,browserPath:path8.resolve(options.browserPath),startedAt:new Date().toISOString()};await writeRecordAtomic(root,recordPath,record);opened.browserProcess=child;const disconnect=opened.close.bind(opened);opened.close=async()=>{let failure;const quitRequested=await askBrowserToQuit(opened,child,async()=>{try{await disconnect()}catch(error){failure=error}});await terminateChild(child,{quitRequested});try{await withLock(lockPath,nameLockOptions(options),()=>removeOwnedRecord(recordPath,name,child.pid))}catch(error){failure??=error}if(failure)throw failure};return opened}catch(error){await connection?.close().catch(()=>{});await terminateChild(child);throw error}}async function withEngineLock(registryRoot,engineKey,run){const root=path8.resolve(registryRoot??DEFAULT_REGISTRY_ROOT);await ensureRegistryRoot(root);const digest=createHash("sha256").update(path8.resolve(engineKey)).digest("hex").slice(0,16);const lockPath=path8.join(root,`_engine-${digest}.flock`);return withLock(lockPath,{timeoutMs:DEFAULT_LOCK_TIMEOUT_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 restrictToOwner(paths.recordPath,"file");if(isPidAlive(loaded.record.pid)){let version=null;try{version=await probeEndpoint(loaded.record.endpoint,options.probeTimeoutMs??resolveConnectTimeoutMs(options))}catch(error){if(!isConnectionRefused(error)){throw new Error(`unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${readProperty(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}: ${readProperty(error,"message")}`,{cause:error})}}}}if(loaded.exists){await unlink3(paths.recordPath).catch((error)=>{if(errorCode3(error)!=="ENOENT")throw error})}return await launchNamed(normalizedName,paths,options)}async function listInstances(options={}){const root=path8.resolve(options.registryRoot??DEFAULT_REGISTRY_ROOT);await ensureRegistryRoot(root);const entries=await readdir(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=path8.join(root,entry.name);const{record}=await readRecord(recordPath,expectedName);if(!record)return null;await restrictToOwner(recordPath,"file");const alive=isPidAlive(record.pid);let responsive=false;if(alive){responsive=await probeEndpoint(record.endpoint,options.probeTimeoutMs??DEFAULT_PROBE_TIMEOUT_MS).then((version)=>version.webSocketDebuggerUrl===record.webSocketDebuggerUrl,()=>false)}return Object.assign(record,{alive,responsive})}));return records.filter((record)=>record!==null).toSorted((left,right)=>left.name.localeCompare(right.name))}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))]);var pathFor=(platform)=>platform==="win32"?path9.win32:path9.posix;function macRow(b,home,exists){const{join}=path9.posix;const apps=[join("/Applications",`${b.app}.app`),join(home,"Applications",`${b.app}.app`)];const appPath=apps.find((p)=>exists(p))??null;const userDataDir=join(home,b.userData);return{id:b.id,label:b.label,store:b.store,userDataDir,binary:join(appPath??apps[0],"Contents","MacOS",b.app),bundleId:b.bundleId,processNames:apps.map((a)=>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=path9.posix.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{join}=path9.win32;const localAppData=env["LOCALAPPDATA"]??join(home,"AppData","Local");const programFiles=[localAppData,env["PROGRAMFILES"],env["PROGRAMFILES(X86)"],"C:\\Program Files","C:\\Program Files (x86)"].filter((root)=>Boolean(root));const userDataDir=join(localAppData,b.userData);const binary=programFiles.map((root)=>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=homedir(),env=process.env,exists=existsSync}={}){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 DEFAULT_PORT_CHECK_MS=1000;class RunningBrowserError extends Error{constructor(code,message,candidates=[]){super(message);this.name="RunningBrowserError";this.code=code;this.candidates=candidates}}async function readDevToolsActivePort(userDataDir){const text=await readFile8(path10.join(userDataDir,"DevToolsActivePort"),"utf8").catch(()=>null);if(text===null)return null;const[portLine="",wsPath=""]=text.split(/\r?\n/);const port=Number(portLine.trim());if(!Number.isInteger(port)||port<=0||port>65535)return null;const pathPart=wsPath.trim();return{port,wsPath:pathPart.startsWith("/devtools/browser")?pathPart:null}}function portIsListening(port,timeoutMs){return new Promise((resolve)=>{const socket=connectTcp({host:"127.0.0.1",port});const done=(live)=>{socket.destroy();resolve(live)};socket.setTimeout(timeoutMs,()=>done(false));socket.once("connect",()=>done(true));socket.once("error",()=>done(false))})}function candidateDirs({browser,userDataDirs,catalog}){if(userDataDirs)return userDataDirs.map((dir)=>({id:path10.basename(dir),label:dir,userDataDir:dir}));const rows=catalog().filter((row)=>row.hasProfile);return browser?rows.filter((row)=>row.id===browser):rows}async function findRunningBrowser({browser,userDataDirs,portCheckMs=DEFAULT_PORT_CHECK_MS,catalog=catalogBrowsers}={}){const live=[];for(const candidate of candidateDirs({browser,userDataDirs,catalog})){const active=await readDevToolsActivePort(candidate.userDataDir);if(!active||!active.wsPath)continue;if(!await portIsListening(active.port,portCheckMs))continue;live.push({...candidate,port:active.port,wsUrl:`ws://127.0.0.1:${active.port}${active.wsPath}`})}const[only]=live;if(live.length===1&&only!==undefined)return only;if(live.length===0){throw new RunningBrowserError("not_found","No running browser has remote debugging on. Ask the user to open chrome://inspect/#remote-debugging and allow it, then retry.")}throw new RunningBrowserError("choose_browser",`More than one browser has remote debugging on (${live.map((row)=>row.id).join(", ")}); pass { browser: "<id>" }.`,live)}async function connectRunningBrowser(options={}){const found=await findRunningBrowser(options);const browser=await connect(found.wsUrl,options.connect??{});return{browser,found}}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=path11.join(os2.homedir(),".local","share","omowright-cloak");function errorField(error,key){return error===null||error===undefined?undefined:readProperty(error,key)}function normalizeFingerprintSeed(value){const seed=typeof value==="string"&&value.trim()!==""?Number(value):value;if(typeof seed!=="number"||!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=path11.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 readFile9(metadataPath,"utf8"));return normalizeFingerprintSeed(readProperty(parsed,"fingerprintSeed"))}catch(error){if(errorField(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)}
1338
1338
  `,"utf8")}finally{await handle.close()}try{await restrictToOwner(metadataPath,"file")}catch(error){await unlink4(metadataPath).catch(()=>{});throw error}}async function resolveCloakProfile({profileDir=DEFAULT_PROFILE_DIR,fingerprintSeed,randomSeed=()=>randomInt(MIN_FINGERPRINT_SEED,MAX_FINGERPRINT_SEED+1)}={}){const resolvedProfile=path11.resolve(profileDir);const metadataPath=path11.join(resolvedProfile,METADATA_FILE);await mkdir6(resolvedProfile,{recursive:true,mode:448});await restrictToOwner(resolvedProfile,"directory");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(errorField(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 restrictToOwner(metadataPath,"file");return{profileDir:resolvedProfile,metadataPath,fingerprintSeed:stored,browserArgs:buildCloakBrowserArgs({profileDir:resolvedProfile,fingerprintSeed:stored})}}function findCloakBrowserPath({browserRoot=path11.join(os2.homedir(),".cloakbrowser")}={}){const candidates=globSync(path11.join(path11.resolve(browserRoot),"chromium-*","Chromium.app","Contents","MacOS","Chromium")).toSorted();const browserPath=candidates.at(-1);if(!browserPath){throw new Error(`CloakBrowser binary not found under ${path11.resolve(browserRoot)}; set CLOAKBROWSER_BIN`)}return browserPath}async function assertCloakLaunchClear({browserPath,profileDir,registryRoot,legacyProbeUrl,probeTimeoutMs}){const records=await listInstances({registryRoot,probeTimeoutMs});for(const record of records){if(!record.alive||!record.responsive)continue;if(!record.profileDir)continue;if(path11.resolve(record.profileDir)===path11.resolve(profileDir))continue;if(path11.resolve(record.browserPath)!==path11.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`)}if(legacyProbeUrl===undefined)return;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 ${String(legacyProbeUrl)} — attach with connect("${String(legacyProbeUrl)}") or close it before launching`)}}catch(error){const unreachable=error instanceof TypeError||errorField(error,"name")==="TimeoutError"||errorField(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 isSnapshotLike(value){return typeof value==="object"&&value!==null||typeof value==="function"}function compactSnapshot(snapshot){const parsed=typeof snapshot==="string"?JSON.parse(snapshot):snapshot;const obj=isSnapshotLike(parsed)?parsed:undefined;if(obj?.full===false&&obj.diff){const{added,changed,removed,focused}=obj.diff;const lines=[...added.map((node)=>`+ ${node.tree}`),...changed.map((node)=>`~ ${node.tree}`)];if(removed.length)lines.push(`- ${refRanges(removed)}`);lines.push(`@focused ${focused??"none"}`);return lines.join(`
1339
1339
  `)}if(!obj||typeof obj.tree!=="string")throw new TypeError(SNAPSHOT_PARSE_ERROR);if(obj.find){const{query,matches}=obj.find;const header=`${matches} matching ${matches===1?"line":"lines"} for ${query}`;return obj.tree?`${header}:
1340
1340
  ${obj.tree}`:header}return obj.tree}function refRanges(refs){const sorted=refs.map((ref)=>{const match=/^((?:f\d+)?e)(\d+)$/.exec(ref);if(match===null)throw new TypeError(`Cannot destructure a malformed snapshot ref: ${ref}`);const[,prefix="",number=""]=match;return{prefix,number:Number(number)}}).toSorted((a,b)=>a.prefix.localeCompare(b.prefix)||a.number-b.number);const ranges=[];for(let i=0;i<sorted.length;i++){const first=sorted[i];if(first===undefined)break;let last=first;let next=sorted[i+1];while(next?.prefix===first.prefix&&next.number===last.number+1){last=next;i+=1;next=sorted[i+1]}ranges.push(first===last?`${first.prefix}${first.number}`:`${first.prefix}${first.number}-${last.prefix}${last.number}`)}return ranges.join(", ")}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. Snapshot once, act on refs, re-read with {diff:true} (fallback: full:true, reason) or {find} to search. Options: diff, find, context, 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:"Compact page.snapshot() before reading: full results become raw trees; diffs use +/~ lines and removed ref ranges. Refs resolve in-page.",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.toReversed())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)}}}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;const{promise:stopped,resolve:resolveStopped}=Promise.withResolvers();const stop=()=>resolveStopped(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();let evaluated=false;for(;;){let accepted;try{accepted=await Promise.race([Promise.resolve().then(()=>(evaluated?terminal():signal?.aborted)?STOP:until(page,{signal:operation.signal})),stopped])}catch(error){const outcome=terminal();if(outcome)return result(outcome);throw error}evaluated=true;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 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}}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=`
@@ -1363,7 +1363,7 @@ print(text)
1363
1363
  a.href = ${JSON.stringify(downloadOptions.url)};
1364
1364
  document.body.appendChild(a);
1365
1365
  a.click();
1366
- })()`);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:path14.join(downloadDir,filename??"download"),state:"complete"}}finally{clearTimeout(timer);offBegin();offProgress();await page.close().catch(()=>{})}},async pause(..._args){throw new UnsupportedOperationError(`chrome.downloads.pause ${EXTENSION_BRIDGE_REQUIRED2}`)},async resume(..._args){throw new UnsupportedOperationError(`chrome.downloads.resume ${EXTENSION_BRIDGE_REQUIRED2}`)},async cancel(..._args){throw new UnsupportedOperationError(`chrome.downloads.cancel ${EXTENSION_BRIDGE_REQUIRED2}`)},async erase(..._args){throw new UnsupportedOperationError(`chrome.downloads.erase ${EXTENSION_BRIDGE_REQUIRED2}`)}};return{tabs,windows,downloads,bookmarks:profile.bookmarks,history:profile.history,topSites:profile.topSites}}var SYSTEM="S-1-5-18";var ADMINISTRATORS="S-1-5-32-544";var TRUSTED_INSTALLER="S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";var OWNER_RIGHTS="S-1-3-4";var CREATOR_OWNER="S-1-3-0";var WRITE_DATA=2;var APPEND_DATA=4;var WRITE_EA=16;var DELETE_CHILD=64;var WRITE_ATTRIBUTES=256;var DELETE=65536;var WRITE_DAC=262144;var WRITE_OWNER=524288;var GENERIC_ALL=268435456;var GENERIC_WRITE=1073741824;var MODIFY=WRITE_DATA|APPEND_DATA|WRITE_EA|WRITE_ATTRIBUTES|DELETE|WRITE_DAC|WRITE_OWNER|GENERIC_ALL|GENERIC_WRITE;var FORBIDDEN={executable:MODIFY,manifest:MODIFY,final:MODIFY|DELETE_CHILD,ancestor:DELETE_CHILD|DELETE|WRITE_DAC|WRITE_OWNER|GENERIC_ALL};var WIN32_REGISTRY_KEYS=Object.freeze({chrome:"HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts",chromium:"HKCU\\Software\\Chromium\\NativeMessagingHosts"});var isWin32RegistryKey=(key)=>typeof key==="string"&&/^HKCU\\Software(\\[^\\/:*?"<>|\r\n]+)*\\NativeMessagingHosts$/i.test(key);function win32PathRisk(item,kind,userSid){const trusted=new Set([userSid,SYSTEM,ADMINISTRATORS,TRUSTED_INSTALLER]);if(item?.inaccessible)return"could not be inspected";if(!item?.exists)return"is missing";if(item.reparse)return"is a symlink, junction or other reparse point";if(kind==="executable"||kind==="manifest"){if(item.directory)return"is not a regular file";if(kind==="executable"&&!/\.(exe|cmd|bat|com)$/i.test(item.path))return"is not a .exe, .cmd, .bat or .com file"}else if(!item.directory)return"is not a directory";if(!trusted.has(item.owner))return`is owned by untrusted ${item.owner}`;trusted.add(OWNER_RIGHTS).add(CREATOR_OWNER);for(const ace of item.aces??[]){if(!readProperty(ace,"allow")||trusted.has(readProperty(ace,"sid")))continue;const mask=!readProperty(ace,"inheritOnly")?FORBIDDEN[kind]:kind==="final"&&readProperty(ace,"objectInherit")?MODIFY:0;if((Number(readProperty(ace,"rights"))&mask)!==0)return`grants ${readProperty(ace,"sid")} write access`}return null}var systemBinary=(...segments)=>{const file=path15.win32.join(process.env["SystemRoot"]||"C:\\Windows","System32",...segments);if(!existsSync3(file))throw new Error(`${file} is missing`);return file};var RUN_TIMEOUT_MS=60000;function run(file,args){return new Promise((resolve,reject)=>{execFile3(file,args,{timeout:RUN_TIMEOUT_MS,windowsHide:true,maxBuffer:4194304,encoding:"utf8"},(error,stdout,stderr)=>{if(error&&(typeof error.code!=="number"||error.killed))reject(error);else resolve({code:error?error.code:0,stdout,stderr})})})}var INSPECT=`$ErrorActionPreference = 'Stop'
1366
+ })()`);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:path14.join(downloadDir,filename??"download"),state:"complete"}}finally{clearTimeout(timer);offBegin();offProgress();await page.close().catch(()=>{})}},async pause(..._args){throw new UnsupportedOperationError(`chrome.downloads.pause ${EXTENSION_BRIDGE_REQUIRED2}`)},async resume(..._args){throw new UnsupportedOperationError(`chrome.downloads.resume ${EXTENSION_BRIDGE_REQUIRED2}`)},async cancel(..._args){throw new UnsupportedOperationError(`chrome.downloads.cancel ${EXTENSION_BRIDGE_REQUIRED2}`)},async erase(..._args){throw new UnsupportedOperationError(`chrome.downloads.erase ${EXTENSION_BRIDGE_REQUIRED2}`)}};return{tabs,windows,downloads,bookmarks:profile.bookmarks,history:profile.history,topSites:profile.topSites}}var SYSTEM="S-1-5-18";var ADMINISTRATORS="S-1-5-32-544";var TRUSTED_INSTALLER="S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";var OWNER_RIGHTS="S-1-3-4";var CREATOR_OWNER="S-1-3-0";var WRITE_DATA=2;var APPEND_DATA=4;var WRITE_EA=16;var DELETE_CHILD=64;var WRITE_ATTRIBUTES=256;var DELETE=65536;var WRITE_DAC=262144;var WRITE_OWNER=524288;var GENERIC_ALL=268435456;var GENERIC_WRITE=1073741824;var MODIFY=WRITE_DATA|APPEND_DATA|WRITE_EA|WRITE_ATTRIBUTES|DELETE|WRITE_DAC|WRITE_OWNER|GENERIC_ALL|GENERIC_WRITE;var FORBIDDEN={executable:MODIFY,manifest:MODIFY,final:MODIFY|DELETE_CHILD,ancestor:DELETE_CHILD|DELETE|WRITE_DAC|WRITE_OWNER|GENERIC_ALL};var WIN32_REGISTRY_KEYS=Object.freeze({chrome:"HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts",chromium:"HKCU\\Software\\Chromium\\NativeMessagingHosts"});var isWin32RegistryKey=(key)=>typeof key==="string"&&/^HKCU\\Software(\\[^\\/:*?"<>|\r\n]+)*\\NativeMessagingHosts$/i.test(key);function win32PathRisk(item,kind,userSid){const trusted=new Set([userSid,SYSTEM,ADMINISTRATORS,TRUSTED_INSTALLER]);if(item?.inaccessible)return"could not be inspected";if(!item?.exists)return"is missing";if(item.reparse)return"is a symlink, junction or other reparse point";if(kind==="executable"||kind==="manifest"){if(item.directory)return"is not a regular file";if(kind==="executable"&&!/\.(exe|cmd|bat|com)$/i.test(item.path))return"is not a .exe, .cmd, .bat or .com file"}else if(!item.directory)return"is not a directory";if(!trusted.has(item.owner))return`is owned by untrusted ${item.owner}`;trusted.add(OWNER_RIGHTS).add(CREATOR_OWNER);for(const ace of item.aces??[]){if(!readProperty(ace,"allow")||trusted.has(readProperty(ace,"sid")))continue;const mask=!readProperty(ace,"inheritOnly")?FORBIDDEN[kind]:kind==="final"&&readProperty(ace,"objectInherit")?MODIFY:0;if((Number(readProperty(ace,"rights"))&mask)!==0)return`grants ${readProperty(ace,"sid")} write access`}return null}var systemBinary=(...segments)=>{const file=path15.win32.join(process.env["SystemRoot"]||"C:\\Windows","System32",...segments);if(!existsSync3(file))throw new Error(`${file} is missing`);return file};var RUN_TIMEOUT_MS=60000;function run(file,args){return new Promise((resolve,reject)=>{execFile4(file,args,{timeout:RUN_TIMEOUT_MS,windowsHide:true,maxBuffer:4194304,encoding:"utf8"},(error,stdout,stderr)=>{if(error&&(typeof error.code!=="number"||error.killed))reject(error);else resolve({code:error?error.code:0,stdout,stderr})})})}var INSPECT=`$ErrorActionPreference = 'Stop'
1367
1367
  $paths = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PATHS__')))
1368
1368
  $sid = [System.Security.Principal.SecurityIdentifier]
1369
1369
  $items = @(foreach ($p in $paths) {
@@ -1384,15 +1384,15 @@ ConvertTo-Json -Depth 6 -Compress @{ user = [System.Security.Principal.WindowsId
1384
1384
  `)}}};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=randomUUID3();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})}const frameType=readProperty(raw,"type");if(frameType==="event")return dispatchEvent(checked(EventSchema,raw,"invalid event"));if(frameType==="response"){const parsed=checked(ResponseSchema,raw,"invalid response");if(parsed.name==="protocolError")throw Object.assign(new BridgeProtocolError(parsed.error?.message??"protocol error"),{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: ${messageOf(error)}
1385
1385
  `);disconnect(error)})}catch(error){stderr.write?.(`bridge: ${messageOf(error)}
1386
1386
  `);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:randomUUID3(),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:()=>{},settled:false};const cleanup=()=>{if(item.timer!==null)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){if(platform==="win32"){if(WIN32_REGISTRY_KEYS[browser]===undefined)throw new BridgeProtocolError("custom browser requires nativeMessagingHostDir");return path16.win32.join(process.env["LOCALAPPDATA"]||path16.win32.join(homedir2(),"AppData","Local"),"omowright","NativeMessagingHosts",browser)}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 path16.join(homedir2(),...segments,"NativeMessagingHosts")}async function secureDirectory(dir){const absolute=path16.resolve(dir);const parts=absolute.split(path16.sep).filter(Boolean);let current=path16.parse(absolute).root;let final;while(parts.length){const part=parts.shift();if(part===undefined)break;current=path16.join(current,part);let info=await lstat(current).catch(()=>null);if(!info){await mkdir8(current,{mode:448});info=await lstat(current)}if(info.isSymbolicLink()){if(process.platform!=="darwin"||!["/tmp","/var","/etc"].includes(current)||info.uid!==0)throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: symlink is not a root-owned macOS system alias`);let target,resolved;try{target=await readlink(current);resolved=await realpath(current)}catch(error){throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: system alias could not be resolved (${String(readProperty(error,"code")??readProperty(error,"message"))})`)}if(!resolved.startsWith("/private/"))throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: system alias target is outside /private`);parts.unshift(...target.split(path16.sep).filter(Boolean));current=path16.isAbsolute(target)?path16.parse(target).root:path16.dirname(current);continue}if(!info.isDirectory())throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: not a directory`);if(info.uid!==process.getuid?.()&&info.uid!==0)throw new BridgeProtocolError(`nativeMessagingHostDir ownership rejected at ${current}: not owned by the current user or root`);const stickyRootAncestor=parts.length>0&&info.uid===0&&(info.mode&512)!==0;if(!stickyRootAncestor&&(info.mode&18)!==0)throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: writable by others`);final=info}if(!final||final.uid!==process.getuid?.()&&final.uid!==0)throw new BridgeProtocolError(`nativeMessagingHostDir ownership rejected at ${current}: not owned by the current user or root`);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,registryKey}={}){const win32=process.platform==="win32";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(hostPath===undefined||!path16.isAbsolute(hostPath))throw new BridgeProtocolError("hostPath must be absolute");if(!win32)await secureExecutable(hostPath);if(extensionId===undefined||!/^[a-p]{32}$/.test(extensionId))throw new BridgeProtocolError("invalid extensionId");if(!nativeMessagingHostDir&&browser==="cloakbrowser")throw new BridgeProtocolError("CloakBrowser nativeMessagingHostDir must be explicit and verified");if(registryKey!==undefined&&!win32)throw new BridgeProtocolError("registryKey is only used on win32");const dir=nativeMessagingHostDir??defaultNativeMessagingHostDir(browser);const manifest={name:hostName,description:"OmOWright internal CloakBrowser native messaging bridge.",path:hostPath,type:"stdio",allowed_origins:[`chrome-extension://${extensionId}/`]};const writeManifest=async(file)=>{if(!force&&await lstat(file).catch(()=>null))throw new BridgeProtocolError("registration manifest already exists; use force");const temp=`${file}.${process.pid}.${randomUUID3()}.tmp`;const handle=await open5(temp,"wx",384);try{await handle.writeFile(JSON.stringify(manifest,null,2)+`
1387
- `);await handle.sync()}finally{await handle.close()}await rename2(temp,file);return JSON.parse(await readFile9(file,"utf8"))};if(win32){const key=registryKey??WIN32_REGISTRY_KEYS[browser];if(!isWin32RegistryKey(key))throw new BridgeProtocolError(registryKey===undefined?"custom browser requires registryKey on win32":"registryKey must be HKCU\\Software\\...\\NativeMessagingHosts");try{return await installWin32NativeHost({hostName,hostPath,dir,registryKey:key,force,writeManifest})}catch(error){throw error instanceof BridgeProtocolError?error:new BridgeProtocolError(String(readProperty(error,"message")))}}await secureDirectory(dir);const file=path16.join(dir,`${hostName}.json`);const parsed=await writeManifest(file);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}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 presetsByName=DEVICE_PRESETS;var originalUAs=new WeakMap;async function emulate(page,presetNameOrObject){let preset;if(presetNameOrObject===null){preset=null}else if(typeof presetNameOrObject==="string"){const named=presetsByName[presetNameOrObject];if(!named){throw new Error(`unknown device preset: ${presetNameOrObject}`)}preset=named}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 package_default={name:"omowright",version:"0.3.2",description:"OmOWright browser automation for standard Chromium CDP endpoints.",keywords:["accessibility-snapshot","ai-agent","browser-automation","bun","cdp","chrome-devtools-protocol","chromium","llm"],homepage:"https://github.com/code-yeongyu/omowright#readme",bugs:{url:"https://github.com/code-yeongyu/omowright/issues"},license:"MIT",repository:{type:"git",url:"git+https://github.com/code-yeongyu/omowright.git"},bin:{"omowright-cloak":"./dist/bin/omowright-cloak.js"},files:["dist/","skills/","presets/","README.md","LICENSE","TOOLS.md"],type:"module",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",default:"./dist/index.js"},"./package.json":"./package.json"},publishConfig:{access:"public",provenance:true},scripts:{test:"bun test --parallel","test:node":"bun scripts/node-test.ts","test:cloak-profile":"bun test test/cloak-profile.test.ts test/cloak-profile.integration.test.ts",typecheck:"bun check --no-script --no-pretty -p tsconfig.json","typecheck:control":"bun scripts/typecheck-control.ts",check:"bun run typecheck:control && bun run typecheck && bun run lint && bun run fmt:check",lint:"oxlint --deny-warnings src bin bridge test scripts && bun scripts/lint-ratchet.ts","lint:ratchet:update":"bun scripts/lint-ratchet.ts --update","lint:fix":"oxlint --fix src bin bridge test scripts",fmt:"bun fmt --no-script --write src bin bridge test scripts","fmt:check":"bun fmt --no-script --check src bin bridge test scripts",format:"bun run fmt","format:check":"bun run fmt:check",verify:"bun run check","check:push":"bun run check && bun run build && git diff --exit-code HEAD --",prepare:"husky",build:"bun build.ts","build:extension":"bun bridge/build-extension.ts",prepack:"bun run build",preversion:"git diff --quiet HEAD --"},dependencies:{ws:"^8.23.0",zod:"^4.6.7"},devDependencies:{"@types/bun":"1.4.5",acorn:"8.19.0","gpt-tokenizer":"4.1.2",husky:"9.1.7","oxc-parser":"0.159.0",oxlint:"^1.94.0","typescript-5":"npm:typescript@5.9.3"},engines:{bun:">=1.4",node:">=22"}};var HTTP_VERSION="HTTP/1.1";var CREATOR=Object.freeze({name:"omowright",version:package_default.version});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)Object.assign(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 sleep3(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(await matchesUntil(page,until))return finish("continued","until");if(await isDone(page))return finish("continued","done-button");if(Date.now()-started>=timeoutMs)return finish("timed_out","timed_out");await ensureBanner(page,prompt);const remaining=timeoutMs-(Date.now()-started);if(remaining<=0)return finish("timed_out","timed_out");await sleep3(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 instanceof ShadowRoot?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 instanceof HTMLElement?el.innerText:undefined)||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}}).toSorted((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);if(typeof snapshot!=="object"||snapshot===null||!("tree"in snapshot)||typeof snapshot.tree!=="string"){throw new TypeError("snapshotWithLayers needs the full snapshot (no diff or find options)")}const layers=await describeLayers(page);return{...snapshot,layers,tree:`${layersHeader(layers)}
1387
+ `);await handle.sync()}finally{await handle.close()}await rename2(temp,file);return JSON.parse(await readFile10(file,"utf8"))};if(win32){const key=registryKey??WIN32_REGISTRY_KEYS[browser];if(!isWin32RegistryKey(key))throw new BridgeProtocolError(registryKey===undefined?"custom browser requires registryKey on win32":"registryKey must be HKCU\\Software\\...\\NativeMessagingHosts");try{return await installWin32NativeHost({hostName,hostPath,dir,registryKey:key,force,writeManifest})}catch(error){throw error instanceof BridgeProtocolError?error:new BridgeProtocolError(String(readProperty(error,"message")))}}await secureDirectory(dir);const file=path16.join(dir,`${hostName}.json`);const parsed=await writeManifest(file);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}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 package_default={name:"omowright",version:"0.3.10",description:"OmOWright browser automation for standard Chromium CDP endpoints.",keywords:["accessibility-snapshot","ai-agent","browser-automation","bun","cdp","chrome-devtools-protocol","chromium","llm"],homepage:"https://github.com/code-yeongyu/omowright#readme",bugs:{url:"https://github.com/code-yeongyu/omowright/issues"},license:"MIT",repository:{type:"git",url:"git+https://github.com/code-yeongyu/omowright.git"},bin:{"omowright-cloak":"./dist/bin/omowright-cloak.js"},files:["dist/","skills/","presets/","README.md","LICENSE","TOOLS.md"],type:"module",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",default:"./dist/index.js"},"./package.json":"./package.json"},publishConfig:{access:"public",provenance:true},scripts:{test:"bun test --parallel","test:node":"bun scripts/node-test.ts","test:cloak-profile":"bun test test/cloak-profile.test.ts test/cloak-profile.integration.test.ts",typecheck:"bun check --no-script --no-pretty -p tsconfig.json","typecheck:control":"bun scripts/typecheck-control.ts",check:"bun scripts/bsk-protocol.ts --check && bun run typecheck:control && bun run typecheck && bun run lint && bun run fmt:check",lint:"oxlint --deny-warnings src bin bridge test scripts && bun scripts/lint-ratchet.ts","lint:ratchet:update":"bun scripts/lint-ratchet.ts --update","lint:fix":"oxlint --fix src bin bridge test scripts",fmt:"bun fmt --no-script --write src bin bridge test scripts","fmt:check":"bun fmt --no-script --check src bin bridge test scripts",format:"bun run fmt","format:check":"bun run fmt:check",verify:"bun run check","check:push":"bun run check && bun run build && git diff --exit-code HEAD --",prepare:"husky",build:"bun build.ts","build:extension":"bun bridge/build-extension.ts",prepack:"bun run build",preversion:"git diff --quiet HEAD --"},dependencies:{ws:"^8.23.0",zod:"^4.6.7"},devDependencies:{"@types/bun":"1.4.5",acorn:"8.19.0","gpt-tokenizer":"4.1.2",husky:"9.1.7","oxc-parser":"0.159.0",oxlint:"^1.94.0","typescript-5":"npm:typescript@5.9.3"},engines:{bun:">=1.4",node:">=22"}};var HTTP_VERSION="HTTP/1.1";var CREATOR=Object.freeze({name:"omowright",version:package_default.version});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)Object.assign(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 sleep3(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(await matchesUntil(page,until))return finish("continued","until");if(await isDone(page))return finish("continued","done-button");if(Date.now()-started>=timeoutMs)return finish("timed_out","timed_out");await ensureBanner(page,prompt);const remaining=timeoutMs-(Date.now()-started);if(remaining<=0)return finish("timed_out","timed_out");await sleep3(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 instanceof ShadowRoot?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 instanceof HTMLElement?el.innerText:undefined)||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}}).toSorted((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);if(typeof snapshot!=="object"||snapshot===null||!("tree"in snapshot)||typeof snapshot.tree!=="string"){throw new TypeError("snapshotWithLayers needs the full snapshot (no diff or find options)")}const layers=await describeLayers(page);return{...snapshot,layers,tree:`${layersHeader(layers)}
1388
1388
  ${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 handlers={};let disposed=false;let queue=Promise.resolve();function subscribe(method,handler){handlers[method]=handler}function enqueue(task){queue=queue.then(task).catch((error)=>console.warn("[network-snoop] entry processing failed",error))}async function loadBody(entry,record){if(entry.encodedDataLength>maxBodyBytes){entry.bodySkipped=true;return}try{if(record===undefined)throw new TypeError("Cannot read properties of undefined (reading 'rawBody')");const result=await record.rawBody();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,record)=>{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,record);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(readProperty(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(entryMatch,{timeoutMs=DEFAULT_TIMEOUT_MS}={}){if(disposed)return Promise.reject(Error("Network snoop is disposed"));const predicate=toPredicate(entryMatch);return new Promise((resolve,reject)=>{let settled=false;const finish=(callback)=>(value)=>{if(settled)return;settled=true;clearTimeout(timer);waiters.delete(waiter);callback(value)};const waiter={resolve:finish(resolve),reject:finish(reject),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(`
1389
- `)}function dispose(){if(disposed)return;disposed=true;unsubscribe();for(const waiter of[...waiters])waiter.reject(Error("Network snoop disposed"));waiters.clear();inflight.clear()}const unsubscribe=subscribeNetwork(page,handlers);return{pop,peek,popJson,waitFor,summary,dispose}}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(()=>{const element=document.scrollingElement;if(!element)throw new TypeError("Cannot read properties of null (reading 'scrollHeight')");scrollTo(0,element.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(()=>{const element=document.scrollingElement;if(!element)throw new TypeError("Cannot read properties of null (reading 'scrollHeight')");return element.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}}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 messageOf2(error){return error instanceof Error?error.message:String(error)}async function readConsole(page){const api=page.console;let entries;if(typeof api==="function")entries=await api.call(page);else{const logs=api===null||api===undefined?undefined:readProperty(api,"logs");if(logs!==null&&logs!==undefined){if(typeof logs!=="function")throw new TypeError("api.logs is not a function");entries=await logs.call(api)}}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 traceDir=dir;const shotDir=path17.join(dir,"screenshots");const ready=mkdir9(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:messageOf2(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.defaultValue(),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(stepRecord,phase){const file=path17.join(shotDir,`${stepRecord.seq}-${slug(stepRecord.name)}-${phase}.png`);try{await writeFile3(file,await page.screenshot({type:"png"}));stepRecord.screenshots[phase]=file}catch(error){record({kind:"warning",scope:`screenshot:${phase}`,step:stepRecord.seq,message:messageOf2(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(Object.assign({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=messageOf2(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.toSorted((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 writeFile3(path17.join(traceDir,"trace.jsonl"),ordered.map((entry)=>`${JSON.stringify(entry)}
1389
+ `)}function dispose(){if(disposed)return;disposed=true;unsubscribe();for(const waiter of[...waiters])waiter.reject(Error("Network snoop disposed"));waiters.clear();inflight.clear()}const unsubscribe=subscribeNetwork(page,handlers);return{pop,peek,popJson,waitFor,summary,dispose}}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(()=>{const element=document.scrollingElement;if(!element)throw new TypeError("Cannot read properties of null (reading 'scrollHeight')");scrollTo(0,element.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;const clock=options.clock??globalThis;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(()=>{const element=document.scrollingElement;if(!element)throw new TypeError("Cannot read properties of null (reading 'scrollHeight')");return element.scrollHeight});if(lastHeight!==null&&height===lastHeight){unchanged+=1;if(unchanged>=2){stoppedBecause="noGrowth";break}}else{unchanged=0}lastHeight=height;let timer;const deadline=new Promise((resolve)=>{timer=clock.setTimeout(resolve,settleMs)});const response=snoop.waitFor((entry)=>JSON_MIME.test(String(entry.mimeType??"")),{timeoutMs:settleMs}).catch(()=>deadline);const growth=page.evaluate(({baseline,cleanupMs})=>new Promise((resolve)=>{const element=document.scrollingElement;if(!element)throw new TypeError("Cannot read properties of null (reading 'scrollHeight')");const finish=(grew)=>{observer.disconnect();clearTimeout(cleanup);resolve(grew)};const observer=new ResizeObserver(()=>{if(element.scrollHeight>baseline)finish(true)});const cleanup=setTimeout(()=>finish(false),cleanupMs);observer.observe(element);if(element.scrollHeight>baseline)finish(true)}),{baseline:height,cleanupMs:settleMs}).then((grew)=>grew?undefined:deadline,()=>deadline);await scrollOnce(page,scroll);rounds+=1;await Promise.race([deadline,response,growth]);clock.clearTimeout(timer)}return{rounds,total,stoppedBecause}}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 messageOf2(error){return error instanceof Error?error.message:String(error)}async function readConsole(page){const api=page.console;let entries;if(typeof api==="function")entries=await api.call(page);else{const logs=api===null||api===undefined?undefined:readProperty(api,"logs");if(logs!==null&&logs!==undefined){if(typeof logs!=="function")throw new TypeError("api.logs is not a function");entries=await logs.call(api)}}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 traceDir=dir;const shotDir=path17.join(dir,"screenshots");const ready=mkdir9(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:messageOf2(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.defaultValue(),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(stepRecord,phase){const file=path17.join(shotDir,`${stepRecord.seq}-${slug(stepRecord.name)}-${phase}.png`);try{await writeFile3(file,await page.screenshot({type:"png"}));stepRecord.screenshots[phase]=file}catch(error){record({kind:"warning",scope:`screenshot:${phase}`,step:stepRecord.seq,message:messageOf2(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(Object.assign({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=messageOf2(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.toSorted((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 writeFile3(path17.join(traceDir,"trace.jsonl"),ordered.map((entry)=>`${JSON.stringify(entry)}
1390
1390
  `).join(""));await writeFile3(path17.join(traceDir,"trace.har"),`${JSON.stringify(toHar(netEntries),null,2)}
1391
1391
  `);await writeFile3(path17.join(traceDir,"summary.json"),`${JSON.stringify(summary,null,2)}
1392
1392
  `);return summary}function stop(){return stopping??=finish()}return{step,mark,stop,get dir(){return dir}}}var BSK_CLI_VERSION="0.5.0";var RELEASE_TAG=`cli-v${BSK_CLI_VERSION}`;var INSTALL_SH=`https://raw.githubusercontent.com/Tencent/BrowserSkill/${RELEASE_TAG}/install.sh`;var INSTALL_PS1=`https://raw.githubusercontent.com/Tencent/BrowserSkill/${RELEASE_TAG}/install.ps1`;var BSK_PINNED_MANIFEST_URL=`https://github.com/Tencent/BrowserSkill/releases/download/${RELEASE_TAG}/version.json`;var RC_FILES=[".zshrc",".bashrc",".profile"];function windowsPowerShellEnv(env){const key=Object.keys(process.env).find((name)=>name.toUpperCase()==="PSMODULEPATH");if(!key)return env;const value=process.env[key];if(value===undefined)throw new TypeError(`${key} has no value`);const kept=value.split(";").filter((entry)=>entry&&!/[\\/]PowerShell[\\/]/i.test(entry));return{...env,[key]:kept.length>0?kept.join(";"):undefined}}function cliInstallCommand({platform=process.platform,installDir,version=BSK_CLI_VERSION}={}){const env={BSK_INSTALL_DIR:installDir,BSK_VERSION:version};if(platform==="win32"){return{command:windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe"),args:["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${INSTALL_PS1} | iex`],env:windowsPowerShellEnv(env)}}return{command:"sh",args:["-c",`curl -fsSL ${INSTALL_SH} | sh`],env}}function runDefault(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=path18.join(home,name);snapshot.set(file,existsSync4(file)?readFileSync4(file):null)}return snapshot}function restoreRcFiles(snapshot){const restored=[];for(const[file,before]of snapshot){const after=existsSync4(file)?readFileSync4(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=homedir3(),installDir=path18.join(home,".local","bin"),version,run=runDefault}={}){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=path18.join(installDir,platform==="win32"?"bsk.exe":"bsk");const installed=result.code===0&&existsSync4(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))})}function isDaemonInfo(value){if(!value||typeof value!=="object"||!("sock_path"in value))return false;return typeof value.sock_path==="string"&&value.sock_path.length>0}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"]:homedir4();return path19.join(home,".bsk")}function daemonInfoPath(home){return path19.join(home,"daemon.json")}function readDaemonInfo(home){let raw;try{raw=readFileSync5(daemonInfoPath(home),"utf8")}catch{return null}let info;try{info=JSON.parse(raw)}catch{return null}if(!isDaemonInfo(info))return null;return info}function findBskBinary(env=process.env){const home=env["HOME"]&&env["HOME"].length>0?env["HOME"]:homedir4();const candidates=[env["BSK_BIN"],path19.join(home,".local","bin",process.platform==="win32"?"bsk.exe":"bsk")].filter((candidate)=>Boolean(candidate));for(const candidate of candidates)if(existsSync5(candidate))return candidate;return"bsk"}var NO_BREAKAWAY=/Job Object/;function windowsDaemonTaskName(home){return`bsk-daemon-${createHash2("sha256").update(path19.resolve(home).toLowerCase()).digest("hex").slice(0,12)}`}var powershellLiteral=(value)=>`'${value.replace(/['\u2018\u2019\u201A\u201B]/g,(quote)=>quote+quote)}'`;function daemonEnv(env,home){return{...env,BSK_HOME:home,BSK_AUTO_UPDATE:env["BSK_AUTO_UPDATE"]??"off",BSK_UPDATE_MANIFEST_URL:env["BSK_UPDATE_MANIFEST_URL"]??BSK_PINNED_MANIFEST_URL}}function windowsDaemonLaunch(env,bskBin){const assignments=["BSK_HOME","BSK_AUTO_UPDATE","BSK_UPDATE_MANIFEST_URL"].map((name)=>`$env:${name} = ${powershellLiteral(env[name]??"")}; `).join("");const script=`${assignments}& ${powershellLiteral(bskBin)} daemon start --foreground; exit $LASTEXITCODE`;return`--headless "${windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe")}" -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function startDaemonInWindowsTask({home,env,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(windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe"),["-NoProfile","-NonInteractive","-Command",script],{env:{...process.env,BSK_TASK_NAME:windowsDaemonTaskName(home),BSK_TASK_ARGUMENT:windowsDaemonLaunch(env,bskBin)},timeoutMs,label:"registering the bsk daemon task"})}function runToExit(command,args,{env,timeoutMs,label}){return new Promise((resolve,reject)=>{const child=spawn7(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 daemon=daemonEnv(env,home);const status=await runToExit(bskBin,["status","--json"],{env:daemon,timeoutMs,label:"bsk status"});if(status.code===0)return;if(process.platform==="win32"&&NO_BREAKAWAY.test(status.output)){if(home===undefined)throw new TypeError("startDaemonWithCli needs a home to register the Windows daemon task");const task=await startDaemonInWindowsTask({home,env:daemon,bskBin,timeoutMs});if(task.code===0)return;throw new Error(`${status.output}; 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}`:""}`)}function optionalProperty(value,key){return value===null||value===undefined?undefined:readProperty(value,key)}function listOrEmpty(value,what){if(value===null||value===undefined)return[];if(!Array.isArray(value))throw new TypeError(`${what} is not a list`);const list=value;return list}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=[optionalProperty(params,"timeout_ms"),optionalProperty(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,env=process.env){if(process.platform!=="win32")return path20.join(home,"run","daemon.sock");return`\\\\.\\pipe\\bsk-daemon-${rustStrHash(env["USERNAME"]??"default",home)}`}function rustStrHash(...values){const bytes=Buffer.concat(values.flatMap((value)=>[Buffer.from(value,"utf8"),Buffer.from([255])]));const mask=(1n<<64n)-1n;const rotl=(x,b)=>(x<<b|x>>64n-b)&mask;let[v0,v1,v2,v3]=[0x736f6d6570736575n,0x646f72616e646f6dn,0x6c7967656e657261n,0x7465646279746573n];const round=()=>{v0=v0+v1&mask;v1=rotl(v1,13n)^v0;v0=rotl(v0,32n);v2=v2+v3&mask;v3=rotl(v3,16n)^v2;v0=v0+v3&mask;v3=rotl(v3,21n)^v0;v2=v2+v1&mask;v1=rotl(v1,17n)^v2;v2=rotl(v2,32n)};const compress=(word)=>{v3^=word;round();v0^=word};const whole=bytes.length-bytes.length%8;for(let i=0;i<whole;i+=8)compress(bytes.readBigUInt64LE(i));let last=BigInt(bytes.length&255)<<56n;for(let i=whole;i<bytes.length;i+=1)last|=BigInt(bytes.readUInt8(i))<<BigInt(8*(i-whole));compress(last);v2^=0xffn;round();round();round();return((v0^v1^v2^v3)&mask).toString(16).padStart(16,"0")}function socketExists(sockPath){if(process.platform!=="win32")return existsSync6(sockPath);try{return readdirSync("\\\\.\\pipe\\").includes(path20.win32.basename(sockPath))}catch{return false}}function probeSocket(sockPath){if(!socketExists(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"})+`
1393
1393
  `));socket.on("data",()=>done(true))})}class BskRpcError extends Error{constructor(code,message,data){super(message);this.name="BskRpcError";this.code=code;this.data=data}}var noop2=()=>{};function shortId(){return randomBytes(6).toString("hex")}function sleep4(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}var NO_LISTENER=new Set(["ENOENT","ECONNREFUSED"]);function sameRecord(info,stale){return Boolean(stale)&&JSON.stringify(info)===JSON.stringify(stale?.info)}class BskIpcClient{#home;#env;#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;this.#env=env}get home(){return this.#home}async resolveSocket({isAborted=()=>false,stale}={}){if(this.#sockPath)return this.#sockPath;const found=readDaemonInfo(this.#home);if(found&&!sameRecord(found,stale))return found.sock_path;const orphan=defaultSocketPath(this.#home,this.#env);if(socketExists(orphan)){if(await probeSocket(orphan))return orphan;if(isAborted())throw new BskRpcError("cancelled","cancelled before the daemon was located")}if(!this.#autoStart){if(stale){throw new BskRpcError("no_daemon",`${this.#home}/daemon.json names a BrowserSkill daemon at ${stale.info.sock_path} that is no longer listening (${stale.code}) and automatic start is disabled (BSK_AUTO_START=0); run \`bsk daemon start\` in the environment that owns it`)}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&&!sameRecord(info,stale))return info.sock_path;await sleep4(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=noop2;const exchange=(sockPath,onNoListener)=>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)=>{if(error.code!==undefined&&NO_LISTENER.has(error.code))onNoListener(error.code);finish(reject,new BskRpcError("no_daemon",`IPC socket ${sockPath}: ${error.code??error.message}`))});socket.setEncoding("utf8");socket.on("connect",()=>socket.write(JSON.stringify(frame)+`
1394
1394
  `));socket.on("data",(chunk)=>{buffer+=chunk;const idx=buffer.indexOf(`
1395
- `);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`)))});const promise=(async()=>{let stale;for(;;){const sockPath=await this.resolveSocket({isAborted:()=>aborted,stale});if(aborted)throw new BskRpcError("cancelled",`${method} cancelled by caller`);let refused;try{return await exchange(sockPath,(code)=>{refused=code})}catch(error){const info=refused&&!stale&&!this.#sockPath?readDaemonInfo(this.#home):null;if(info?.sock_path!==sockPath)throw error;stale={info,code:refused}}}})();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 replyId=readProperty(reply,"id");const replyError=readProperty(reply,"error");const undecodableFrame=replyId==="0"&&replyError;if(replyId!==rpcId&&!undecodableFrame){throw new BskRpcError("protocol_error",`${method}: reply id ${replyId} does not match request ${rpcId}`)}if(replyError){const code=readProperty(replyError,"code");const message=readProperty(replyError,"message");throw new BskRpcError(code===undefined?"protocol_error":String(code),message===undefined?"daemon error":String(message),readProperty(replyError,"data"))}return readProperty(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"){const spec=target;if(typeof spec.ref==="string")return{ref:spec.ref};if(typeof spec.selector==="string")return{selector:spec.selector};if(typeof spec.captureId==="string"){return{capture_id:spec.captureId,image_x:spec.x,image_y:spec.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}function fromBase64(value,field){if(typeof value!=="string")throw new TypeError(`${field} is not base64 text`);return Buffer.from(value,"base64")}async function captureScreenshot(session,{ref,tabId,fullPage=false,scope,timeoutMs,context,dependsOn}={}){if(!fullPage){const result=await session.tool("screenshot",{ref,tab_id:tabId});return{buffer:fromBase64(readProperty(result,"image_base64"),"image_base64"),width:readProperty(result,"width"),height:readProperty(result,"height"),format:readProperty(result,"format"),captureId:readProperty(result,"capture_id")??null,captureUnavailable:readProperty(result,"capture_unavailable")??null,tabId:readProperty(result,"tab_id"),dialogs:readProperty(result,"dialogs")??[]}}const started=await session.tool("screenshot_full_page",{scope,tab_id:tabId,timeout_ms:timeoutMs,context_id:context,depends_on:dependsOn});const buffer=await readCapture(session,readProperty(started,"capture_id"),readProperty(started,"byte_size"));return{buffer,width:readProperty(started,"width"),height:readProperty(started,"height"),format:readProperty(started,"format"),captureId:readProperty(started,"capture_id"),scope:readProperty(started,"scope")??scope??null,tabId:readProperty(started,"tab_id"),dialogs:readProperty(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=fromBase64(readProperty(chunk,"data_base64")??"","data_base64");chunks.push(bytes);if(readProperty(chunk,"eof")||bytes.length===0)break;const nextOffset=readProperty(chunk,"next_offset");if(typeof nextOffset!=="number"||nextOffset<=offset)throw new Error(`screenshot_read did not advance past offset ${offset}`);offset=nextOffset}}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;function sharedTab({context,dependsOn,...unknown}){const extra=Object.keys(unknown);if(extra.length>0){throw new TypeError(`unknown option ${extra.map((key)=>JSON.stringify(key)).join(", ")}: a shared-tab action takes { context, dependsOn } besides its own options`)}return{context_id:context,depends_on:dependsOn}}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,"-")})}cooperate(action,{tabId,timeoutMs,maxTokens}={}){return this.tool("cooperate",{action,tab_id:tabId,timeout_ms:timeoutMs,max_tokens:maxTokens})}navigate(url,{tabId,waitUntil,timeoutMs,...shared}={}){return this.tool("navigate",{url,tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,...sharedTab(shared)})}back({tabId,waitUntil,timeoutMs,...shared}={}){return this.tool("navigate_back",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,...sharedTab(shared)})}forward({tabId,waitUntil,timeoutMs,...shared}={}){return this.tool("navigate_forward",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,...sharedTab(shared)})}reload({tabId,waitUntil,timeoutMs,hard,...shared}={}){return this.tool("reload",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,hard,...sharedTab(shared)})}observe({cursor,tabId,maxDepth,maxTokens,debugSurfaces,probeHover,...shared}={}){return this.tool("observe",{cursor,tab_id:tabId,max_depth:maxDepth,max_tokens:maxTokens,debug_surfaces:debugSurfaces,probe_hover:probeHover,...sharedTab(shared)})}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,...shared}={}){return this.tool("click",{...resolveTarget(target),button,click_count:clickCount,modifiers,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}hover(target,{modifiers,settleMs,tabId,timeoutMs,...shared}={}){return this.tool("hover",{...resolveTarget(target),modifiers,settle_ms:settleMs,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}focus(target,{tabId,timeoutMs,...shared}={}){return this.tool("focus",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}blur(target,{tabId,timeoutMs,...shared}={}){return this.tool("blur",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}fill(target,value,{clearBefore,tabId,timeoutMs,...shared}={}){return this.tool("fill",{...resolveTarget(target),value,clear_before:clearBefore,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}press(key,{target,modifiers,holdMs,tabId,timeoutMs,...shared}={}){return this.tool("press",{key,...optionalTarget(target),modifiers,hold_ms:holdMs,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}select(target,values,{tabId,timeoutMs,...shared}={}){return this.tool("select",{...resolveTarget(target),values:Array.isArray(values)?values:[values],tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}scrollTo(target,{tabId,timeoutMs,...shared}={}){return this.tool("scroll_to",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}wheel({deltaX=0,deltaY=0,target,modifiers,tabId,timeoutMs,...shared}={}){return this.tool("wheel",{...optionalTarget(target),delta_x:deltaX,delta_y:deltaY,modifiers,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)})}evaluate(expression,{tabId,awaitPromise,returnByValue,timeoutMs,...shared}={}){return this.tool("evaluate",{expression,tab_id:tabId,await_promise:awaitPromise,return_by_value:returnByValue,timeout_ms:timeoutMs,...sharedTab(shared)})}tabList({scope}={}){return this.tool("tab_list",{scope})}tabCreate({url,active,index}={}){return this.tool("tab_create",{url,active,index})}tabClose(tabId,shared={}){return this.tool("tab_close",{tab_id:tabId,...sharedTab(shared)})}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,shared={}){return this.tool("window_resize",{width,height,...sharedTab(shared)})}emulate({tabId,off,overrides,...shared}={}){return this.tool("emulate",{tab_id:tabId,off,overrides,...sharedTab(shared)})}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;var TAB_GROUPING_EXTENSION_VERSIONS=new Set(["0.4.0"]);function isTabGroupingExtension(browser){return TAB_GROUPING_EXTENSION_VERSIONS.has(optionalProperty(browser,"extension_version"))}var TAB_GROUPING_EXTENSION_STEP=`Update the BrowserSkill extension to 0.4.1 or later (chrome://extensions -> Developer mode -> Update, or wait for the store update). Version 0.4.0 puts each task's tabs into a "BrowserSkill" tab group that the browser saves and syncs, so the group stays after the task ends; delete any saved "BrowserSkill" tab groups by hand.`;function outdatedError(browser){return new BskRpcError("extension_outdated",`the BrowserSkill extension in ${textField(browser,"browser_name")??"the browser"} [${textField(browser,"instance_id")??"unknown id"}] is 0.4.0, which leaves a "BrowserSkill" tab group behind in the user's browser after each task. ${TAB_GROUPING_EXTENSION_STEP}`)}function namesBrowser(b,browser){return readProperty(b,"instance_id")===browser||Boolean(readProperty(b,"label")&&readProperty(b,"label")===browser)}function chooseBrowser(browser,browsers){const resolved=resolveBrowser(browser,browsers);if(resolved!==undefined&&resolved!==null){const entry=browsers.find((b)=>namesBrowser(b,resolved));if(entry&&isTabGroupingExtension(entry))throw outdatedError(entry);return resolved}const outdated=browsers.filter(isTabGroupingExtension);if(outdated.length===0)return resolved;const usable=browsers.find((b)=>!isTabGroupingExtension(b));if(!usable)throw outdatedError(outdated[0]);return readProperty(usable,"instance_id")}async function listBrowsers(client,{waitForBrowserMs}={}){const status=await client.call("system.status",compact({wait_for_browser_ms:waitForBrowserMs}),{idPrefix:"status"});return listOrEmpty(readProperty(status,"browsers"),"system.status browsers")}function resolveBrowser(browser,browsers){if(browser===undefined||browser===null)return browser;if(browsers.some((b)=>namesBrowser(b,browser)))return browser;const named=browsers.filter((b)=>readProperty(b,"browser_name")===browser);if(named.length>1){throw new BskRpcError("invalid_params",`browser "${browser}" matches ${named.length} connected browsers (${named.map((b)=>textField(b,"instance_id")??"unknown id").join(", ")}); pass the instance id instead`)}return named.length===1?readProperty(named[0],"instance_id"):browser}function textField(b,key){const value=optionalProperty(b,key);if(typeof value==="string")return value;if(typeof value==="number"&&Number.isFinite(value))return String(value);return}function describeBrowser(b){const name=textField(b,"browser_name");const parts=[`${textField(b,"label")||name||"browser"} [${textField(b,"instance_id")??"unknown id"}]`,[name,textField(b,"browser_version")].filter(Boolean).join(" ")];const sessions=optionalProperty(b,"session_count");if(typeof sessions==="number"&&Number.isFinite(sessions))parts.push(`${sessions} session${sessions===1?"":"s"}`);const since=optionalProperty(b,"connected_at_ms");if(typeof since==="number"&&Number.isFinite(since)&&Math.abs(since)<=8640000000000000){parts.push(`online since ${new Date(since).toISOString()}`)}return parts.filter(Boolean).join(", ")}function multipleBrowsersError(error,statusBrowsers){const listed=optionalProperty(error.data,"browsers");const browsers=Array.isArray(listed)?listed:statusBrowsers;const data=error.data;const extra=typeof data==="object"&&data!==null?data:{};return new BskRpcError(error.code,`more than one browser is online; pass browser: "<instance_id or label>" to connectBrowserSkill(). Online: ${browsers.map(describeBrowser).join("; ")}. Tabs are only visible inside a session: ask the user which browser holds the page, or open a session per browser and read tabList({ scope: "user" }) before stopping it.`,{...extra,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); never substitute another browser for the user's without telling them")}const browserInstanceId=chooseBrowser(browser,browsers);let started;try{started=await ipc.call("session.start",compact({task_name:name,browser_instance_id:browserInstanceId,width,height,focused}),{idPrefix:"session-start"})}catch(error){if(error instanceof BskRpcError&&error.code==="multiple_browsers_online"){throw multipleBrowsersError(error,browsers)}throw error}return new BskSession(ipc,{sessionId:readProperty(started,"session_id"),browserInstanceId:readProperty(started,"browser_instance_id")??null,agentWindowId:readProperty(started,"agent_window_id")??null,interaction:readProperty(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===part);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 () {
1395
+ `);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`)))});const promise=(async()=>{let stale;for(;;){const sockPath=await this.resolveSocket({isAborted:()=>aborted,stale});if(aborted)throw new BskRpcError("cancelled",`${method} cancelled by caller`);let refused;try{return await exchange(sockPath,(code)=>{refused=code})}catch(error){const info=refused&&!stale&&!this.#sockPath?readDaemonInfo(this.#home):null;if(info?.sock_path!==sockPath)throw error;stale={info,code:refused}}}})();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 replyId=readProperty(reply,"id");const replyError=readProperty(reply,"error");const undecodableFrame=replyId==="0"&&replyError;if(replyId!==rpcId&&!undecodableFrame){throw new BskRpcError("protocol_error",`${method}: reply id ${replyId} does not match request ${rpcId}`)}if(replyError){const code=readProperty(replyError,"code");const message=readProperty(replyError,"message");throw new BskRpcError(code===undefined?"protocol_error":String(code),message===undefined?"daemon error":String(message),readProperty(replyError,"data"))}return readProperty(reply,"result")}var REF_SHAPE=/^@?e\d+$/;function elementTarget(target){if(typeof target==="string"){return REF_SHAPE.test(target)?{ref:target}:{selector:target}}if(target&&typeof target==="object"){const spec=target;if(typeof spec.ref==="string")return{ref:spec.ref};if(typeof spec.selector==="string")return{selector:spec.selector}}return}function resolveTarget(target){const element=elementTarget(target);if(element)return element;if(target&&typeof target==="object"){const spec=target;if(typeof spec.captureId==="string"){if(typeof spec.x!=="number"||typeof spec.y!=="number")throw new TypeError("a {captureId, x, y} target needs numeric x and y image coordinates");return{capture_id:spec.captureId,image_x:spec.x,image_y:spec.y}}}throw new TypeError("target must be a ref ('e3' / '@e3'), a CSS selector, or {captureId, x, y}")}function resolveElementTarget(target){const element=elementTarget(target);if(element)return element;throw new TypeError("target must be a ref ('e3' / '@e3') or a CSS selector")}function optionalElementTarget(target){return target===undefined?{}:resolveElementTarget(target)}function compact(params){const out={};for(const[key,value]of Object.entries(params))if(value!==undefined)out[key]=value;return out}function sharedTab({context,observation,expect,dependsOn,...unknown}){const extra=Object.keys(unknown);if(extra.length>0){throw new TypeError(`unknown option ${extra.map((key)=>JSON.stringify(key)).join(", ")}: a shared-tab action takes { context, observation, expect, dependsOn } besides its own options`)}return{context_id:context,observation_id:observation,expect,depends_on:dependsOn}}function fromBase64(value,field){if(typeof value!=="string")throw new TypeError(`${field} is not base64 text`);return Buffer.from(value,"base64")}async function captureScreenshot(session,{ref,tabId,fullPage=false,scope,timeoutMs,...shared}={}){if(!fullPage){const result=await session.tool("screenshot",{ref,tab_id:tabId});return{buffer:fromBase64(readProperty(result,"image_base64"),"image_base64"),width:readProperty(result,"width"),height:readProperty(result,"height"),format:readProperty(result,"format"),captureId:readProperty(result,"capture_id")??null,captureUnavailable:readProperty(result,"capture_unavailable")??null,tabId:readProperty(result,"tab_id"),dialogs:readProperty(result,"dialogs")??[]}}const started=await session.tool("screenshot_full_page",{scope,tab_id:tabId,timeout_ms:timeoutMs,...sharedTab(shared)});const captureId=readProperty(started,"capture_id");if(typeof captureId!=="string")throw new TypeError("screenshot_full_page returned no capture_id");const buffer=await readCapture(session,captureId,readProperty(started,"byte_size"));return{buffer,width:readProperty(started,"width"),height:readProperty(started,"height"),format:readProperty(started,"format"),captureId,scope:readProperty(started,"scope")??scope??null,tabId:readProperty(started,"tab_id"),dialogs:readProperty(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=fromBase64(readProperty(chunk,"data_base64")??"","data_base64");chunks.push(bytes);if(readProperty(chunk,"eof")||bytes.length===0)break;const nextOffset=readProperty(chunk,"next_offset");if(typeof nextOffset!=="number"||nextOffset<=offset)throw new Error(`screenshot_read did not advance past offset ${offset}`);offset=nextOffset}}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 BOOTSTRAP_REFUSAL="The initial task tab changed; synchronize before acting";var BOOTSTRAP_SETTLE_TIMEOUT_MS=1e4;var INITIAL_BLANK_URLS=new Set(["","about:blank"]);function isBootstrapRefusal(error){return error instanceof BskRpcError&&error.code==="permission_denied"&&error.message===BOOTSTRAP_REFUSAL&&optionalProperty(error.data,"reason")==="cooperation_sync_required"&&optionalProperty(error.data,"effect_state")==="none"}function taskTab(tabs,tabId){const list=listOrEmpty(readProperty(tabs,"tabs"),"tab_list tabs");return tabId===undefined?list.find((tab)=>optionalProperty(tab,"active")===true):list.find((tab)=>optionalProperty(tab,"tab_id")===tabId)}async function settleInitialTab(session,refusal,tabId){const waited=await session.waitForNavigation({...tabId===undefined?{}:{tabId},waitUntil:"load",timeoutMs:BOOTSTRAP_SETTLE_TIMEOUT_MS});const reached=optionalProperty(waited,"reached");const tab=taskTab(await session.tabList({scope:"agent"}),tabId);const url=optionalProperty(tab,"url");if(reached==="load"&&INITIAL_BLANK_URLS.has(url))return;const where=tab===undefined?"no task tab is listed":`tab ${String(optionalProperty(tab,"tab_id"))} is at ${url===""?"(no URL yet)":String(url)}`;throw new BskRpcError(refusal.code,`${refusal.message}: the first navigate was refused before the task tab settled, and it was not sent again because wait_for_navigation reached ${JSON.stringify(reached)} and ${where}`,refusal.data)}function readNodes(session,target,{fields,maxNodes,maxBytes,tabId,timeoutMs,context}={}){return session.tool("read",{...optionalElementTarget(target),fields,max_nodes:maxNodes,max_bytes:maxBytes,tab_id:tabId,timeout_ms:timeoutMs,context_id:context})}function extractItems(session,action,{target,itemSelector,fields,maxRows,maxColumns,maxBytes,targetId,tabId,timeoutMs}={}){return session.tool("extract",{action,...optionalElementTarget(target),item_selector:itemSelector,fields,max_rows:maxRows,max_columns:maxColumns,max_bytes:maxBytes,target_id:targetId,tab_id:tabId,timeout_ms:timeoutMs})}function waitForElement(session,target,{state,pollMs,tabId,timeoutMs}){return session.tool("wait_for_element",{...resolveElementTarget(target),state,poll_ms:pollMs,tab_id:tabId,timeout_ms:timeoutMs})}var SESSION_STOP_TIMEOUT_MS=3600000;var text=(value)=>typeof value==="string"?value:undefined;function cooperateReply(reply){const fields=typeof reply==="object"&&reply!==null?reply:{};const nested=optionalProperty(optionalProperty(reply,"observation"),"observation_id");return{...fields,context_id:text(optionalProperty(reply,"context_id")),observation_id:text(optionalProperty(reply,"observation_id"))??text(nested)}}class BskSession{#client;#stopped=false;#acted=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}#call(name,params){return this.tool(name,params)}#act(name,params,shared){const wire={...params,...sharedTab(shared)};this.#acted=true;return this.tool(name,wire)}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,"-")})}cooperate(action,{tabId,timeoutMs,maxTokens,controlPolicy}={}){return this.#call("cooperate",{action,tab_id:tabId,timeout_ms:timeoutMs,max_tokens:maxTokens,control_policy:controlPolicy}).then(cooperateReply,(error)=>{if(error instanceof BskRpcError&&error.code==="unknown_method")return{context_id:undefined,observation_id:undefined,supported:false,ready:true};throw error})}async navigate(url,{tabId,waitUntil,timeoutMs,...shared}={}){const send=()=>this.#act("navigate",{url,tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs},shared);const first=!this.#acted&&shared.context===undefined;try{return await send()}catch(error){if(!first||!isBootstrapRefusal(error))throw error;await settleInitialTab(this,error,tabId);return send()}}back({tabId,waitUntil,timeoutMs,...shared}={}){return this.#act("navigate_back",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs},shared)}forward({tabId,waitUntil,timeoutMs,...shared}={}){return this.#act("navigate_forward",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs},shared)}reload({tabId,waitUntil,timeoutMs,hard,...shared}={}){return this.#act("reload",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,hard},shared)}observe({cursor,tabId,maxDepth,maxTokens,debugSurfaces,probeHover,...shared}={}){return this.#act("observe",{cursor,tab_id:tabId,max_depth:maxDepth,max_tokens:maxTokens,debug_surfaces:debugSurfaces,probe_hover:probeHover},shared)}snapshot({tabId,maxDepth,maxTokens}={}){return this.#call("snapshot",{tab_id:tabId,max_depth:maxDepth,max_tokens:maxTokens})}getHtml({ref,tabId,maxBytes}={}){return this.#call("get_html",{ref,tab_id:tabId,max_bytes:maxBytes})}screenshot(options){return captureScreenshot(this,options)}click(target,{button,clickCount,modifiers,tabId,timeoutMs,...shared}={}){return this.#act("click",{...resolveTarget(target),button,click_count:clickCount,modifiers,tab_id:tabId,timeout_ms:timeoutMs},shared)}hover(target,{modifiers,settleMs,tabId,timeoutMs,...shared}={}){return this.#act("hover",{...resolveElementTarget(target),modifiers,settle_ms:settleMs,tab_id:tabId,timeout_ms:timeoutMs},shared)}focus(target,{tabId,timeoutMs,...shared}={}){return this.#act("focus",{...resolveElementTarget(target),tab_id:tabId,timeout_ms:timeoutMs},shared)}blur(target,{tabId,timeoutMs,...shared}={}){return this.#act("blur",{...resolveElementTarget(target),tab_id:tabId,timeout_ms:timeoutMs},shared)}fill(target,value,{clearBefore,tabId,timeoutMs,...shared}={}){return this.#act("fill",{...resolveElementTarget(target),value,clear_before:clearBefore,tab_id:tabId,timeout_ms:timeoutMs},shared).catch((error)=>{throw redactValue(error,value)})}press(key,{target,modifiers,holdMs,tabId,timeoutMs,...shared}={}){return this.#act("press",{key,...optionalElementTarget(target),modifiers,hold_ms:holdMs,tab_id:tabId,timeout_ms:timeoutMs},shared)}select(target,values,{tabId,timeoutMs,...shared}={}){return this.#act("select",{...resolveElementTarget(target),values:Array.isArray(values)?values:[values],tab_id:tabId,timeout_ms:timeoutMs},shared)}scrollTo(target,{tabId,timeoutMs,...shared}={}){return this.#act("scroll_to",{...resolveElementTarget(target),tab_id:tabId,timeout_ms:timeoutMs},shared)}wheel({deltaX=0,deltaY=0,target,modifiers,tabId,timeoutMs,...shared}={}){return this.#act("wheel",{...optionalElementTarget(target),delta_x:deltaX,delta_y:deltaY,modifiers,tab_id:tabId,timeout_ms:timeoutMs},shared)}evaluate(expression,{tabId,awaitPromise,returnByValue,timeoutMs,unverified,...shared}={}){return this.#act("evaluate",{expression,tab_id:tabId,await_promise:awaitPromise,return_by_value:returnByValue,timeout_ms:timeoutMs,unverified},shared)}read(target,options){return readNodes(this,target,options)}extract(action,options){return extractItems(this,action,options)}waitForElement(target,options){return waitForElement(this,target,options)}drag(source,{target,delta,mode,button,durationMs,holdMs,modifiers,tabId,timeoutMs,...shared}={}){return this.#act("drag",{source,target,delta,mode,button,duration_ms:durationMs,hold_ms:holdMs,modifiers,tab_id:tabId,timeout_ms:timeoutMs},shared)}tabList({scope}={}){return this.#call("tab_list",{scope})}tabCreate({url,active,index}={}){return this.#call("tab_create",{url,active,index})}tabClose(tabId,shared={}){return this.#act("tab_close",{tab_id:tabId},shared)}tabSelect(tabId){return this.#call("tab_select",{tab_id:tabId})}tabBorrow(tabId,{confirmationTimeoutMs}={}){return this.#call("tab_borrow",{tab_id:tabId,confirmation_timeout_ms:confirmationTimeoutMs})}tabReturn(tabId){return this.#call("tab_return",{tab_id:tabId})}waitForNavigation({tabId,waitUntil,timeoutMs}={}){return this.#call("wait_for_navigation",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs})}requestHelp({prompt,title,targets,completionCriteria,tabId,timeoutMs}){return this.#call("request_help",{prompt,title,tab_id:tabId,timeout_ms:timeoutMs,targets:targets?.map((t)=>resolveElementTarget(t)),completion_criteria:completionCriteria})}console({tabId,since,limit,maxTextChars,includeStack}={}){return this.#call("console",{tab_id:tabId,since,limit,max_text_chars:maxTextChars,include_stack:includeStack})}network({tabId,since,limit,maxTextChars}={}){return this.#call("network",{tab_id:tabId,since,limit,max_text_chars:maxTextChars})}resize(width,height,shared={}){return this.#act("window_resize",{width,height},shared)}emulate({tabId,off,overrides,...shared}={}){return this.#act("emulate",{tab_id:tabId,off,overrides},shared)}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;var TAB_GROUPING_EXTENSION_VERSIONS=new Set(["0.4.0"]);function isTabGroupingExtension(browser){return TAB_GROUPING_EXTENSION_VERSIONS.has(optionalProperty(browser,"extension_version"))}var TAB_GROUPING_EXTENSION_STEP=`Update the BrowserSkill extension to 0.4.1 or later (chrome://extensions -> Developer mode -> Update, or wait for the store update). Version 0.4.0 puts each task's tabs into a "BrowserSkill" tab group that the browser saves and syncs, so the group stays after the task ends; delete any saved "BrowserSkill" tab groups by hand.`;function outdatedError(browser){return new BskRpcError("extension_outdated",`the BrowserSkill extension in ${textField(browser,"browser_name")??"the browser"} [${textField(browser,"instance_id")??"unknown id"}] is 0.4.0, which leaves a "BrowserSkill" tab group behind in the user's browser after each task. ${TAB_GROUPING_EXTENSION_STEP}`)}function namesBrowser(b,browser){return readProperty(b,"instance_id")===browser||Boolean(readProperty(b,"label")&&readProperty(b,"label")===browser)}function chooseBrowser(browser,browsers){const resolved=resolveBrowser(browser,browsers);if(resolved!==undefined&&resolved!==null){const entry=browsers.find((b)=>namesBrowser(b,resolved));if(entry&&isTabGroupingExtension(entry))throw outdatedError(entry);return resolved}const outdated=browsers.filter(isTabGroupingExtension);if(outdated.length===0)return resolved;const usable=browsers.find((b)=>!isTabGroupingExtension(b));if(!usable)throw outdatedError(outdated[0]);return readProperty(usable,"instance_id")}async function listBrowsers(client,{waitForBrowserMs}={}){const status=await client.call("system.status",compact({wait_for_browser_ms:waitForBrowserMs}),{idPrefix:"status"});return listOrEmpty(readProperty(status,"browsers"),"system.status browsers")}function resolveBrowser(browser,browsers){if(browser===undefined||browser===null)return browser;if(browsers.some((b)=>namesBrowser(b,browser)))return browser;const named=browsers.filter((b)=>readProperty(b,"browser_name")===browser);if(named.length>1){throw new BskRpcError("invalid_params",`browser "${browser}" matches ${named.length} connected browsers (${named.map((b)=>textField(b,"instance_id")??"unknown id").join(", ")}); pass the instance id instead`)}return named.length===1?readProperty(named[0],"instance_id"):browser}function textField(b,key){const value=optionalProperty(b,key);if(typeof value==="string")return value;if(typeof value==="number"&&Number.isFinite(value))return String(value);return}function describeBrowser(b){const name=textField(b,"browser_name");const parts=[`${textField(b,"label")||name||"browser"} [${textField(b,"instance_id")??"unknown id"}]`,[name,textField(b,"browser_version")].filter(Boolean).join(" ")];const sessions=optionalProperty(b,"session_count");if(typeof sessions==="number"&&Number.isFinite(sessions))parts.push(`${sessions} session${sessions===1?"":"s"}`);const since=optionalProperty(b,"connected_at_ms");if(typeof since==="number"&&Number.isFinite(since)&&Math.abs(since)<=8640000000000000){parts.push(`online since ${new Date(since).toISOString()}`)}return parts.filter(Boolean).join(", ")}function multipleBrowsersError(error,statusBrowsers){const listed=optionalProperty(error.data,"browsers");const browsers=Array.isArray(listed)?listed:statusBrowsers;const data=error.data;const extra=typeof data==="object"&&data!==null?data:{};return new BskRpcError(error.code,`more than one browser is online; pass browser: "<instance_id or label>" to connectBrowserSkill(). Online: ${browsers.map(describeBrowser).join("; ")}. Tabs are only visible inside a session: ask the user which browser holds the page, or open a session per browser and read tabList({ scope: "user" }) before stopping it.`,{...extra,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); never substitute another browser for the user's without telling them")}const browserInstanceId=chooseBrowser(browser,browsers);let started;try{started=await ipc.call("session.start",compact({task_name:name,browser_instance_id:browserInstanceId,width,height,focused}),{idPrefix:"session-start"})}catch(error){if(error instanceof BskRpcError&&error.code==="multiple_browsers_online"){throw multipleBrowsersError(error,browsers)}throw error}return new BskSession(ipc,{sessionId:readProperty(started,"session_id"),browserInstanceId:readProperty(started,"browser_instance_id")??null,agentWindowId:readProperty(started,"agent_window_id")??null,interaction:readProperty(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===part);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 () {
1396
1396
  const globalThis = {};
1397
1397
  ${pageBundle}
1398
1398
  const api = globalThis.__omowright;
@@ -1401,7 +1401,7 @@ ${snapshot.tree}`}}var DEFAULT_TIMEOUT_MS=30000;var JSON_MIME=/^application\/jso
1401
1401
  const css = {};
1402
1402
  for (const ref of Object.keys(result.refs || {})) css[ref] = cssPath(api.elementRegistry.get(ref));
1403
1403
  return { tree: result.tree, refs: result.refs || {}, css, error: result.error };
1404
- })()`}async function bskSnapshot(session,{tabId,timeoutMs,context,dependsOn,...snapshotOptions}={}){const reply=await session.evaluate(buildSnapshotExpression(snapshotOptions),{tabId,timeoutMs,context,dependsOn,awaitPromise:false,returnByValue:true});if(!reply||readProperty(reply,"ok")===false){const text=optionalProperty(optionalProperty(reply,"error"),"text")??"unknown error";throw new Error(`bskSnapshot failed inside the page: ${text}`)}const value=readProperty(reply,"value");const tree=value?readProperty(value,"tree"):undefined;if(!value||typeof tree!=="string")throw new Error("bskSnapshot: page returned no tree");const error=readProperty(value,"error");if(error)throw new Error(`bskSnapshot: ${error}`);return{tree,refs:readProperty(value,"refs"),css:readProperty(value,"css")}}var SCRIPT_AT_EOF=/piped stdin runs as one script/i;var LISTS_REPL_TOOL=/^\s*repl(?:[ \t]|$)/m;function captureCli({spawn,command,args,env,timeoutMs}){return new Promise((resolve)=>{const[bin,...lead]=command;let child;try{child=spawn(bin,[...lead,...args],{env,stdio:["ignore","pipe","pipe"],windowsHide:true})}catch{resolve({out:null,timedOut:false});return}let out="";const timer=setTimeout(()=>{child.kill();resolve({out:null,timedOut:true})},timeoutMs);child.stdout?.setEncoding("utf8");child.stdout?.on("data",(chunk)=>{out+=chunk});child.stderr?.setEncoding("utf8");child.stderr?.on("data",(chunk)=>{out+=chunk});child.once("error",()=>{clearTimeout(timer);resolve({out:null,timedOut:false})});child.once("close",(code)=>{clearTimeout(timer);resolve({out:code===0?out:null,timedOut:false})})})}async function replTransportFor(options){const help=await captureCli({...options,args:["repl","--help"]});if(help.out!==null)return SCRIPT_AT_EOF.test(help.out)?"mcp":"line";if(!help.timedOut)return"line";const mcpHelp=await captureCli({...options,args:["mcp","--help"]});return mcpHelp.out!==null&&LISTS_REPL_TOOL.test(mcpHelp.out)?"mcp":"line"}async function asideCliVersion(options){const{out}=await captureCli({...options,args:["--version"]});return out?.trim()||null}class AsideReplError extends Error{constructor(code,message,{output=[],setup}={}){super(message);this.name="AsideReplError";this.code=code;this.output=output;if(setup)this.setup=setup}}var CLOSE_TIMEOUT_MS=5000;var KILL_GRACE_MS=2000;var PROMPT="repl > ";var MARKER=/^\[(ok|error) \| \d+ms\]$/;var ANSI=/\x1B\[[0-9;?]*[ -/]*[@-~]/g;var plain=(text)=>text.replace(ANSI,"");var finished2=(lines,tag)=>MARKER.test(lines.at(-1)??"")&&(lines.at(-2)??"").startsWith(tag);class LineTransport{#child;#buffer="";#lines=[];#waiter=null;#closed=false;#exited=false;#terminated=false;#exit;constructor(child){this.#child=child;this.#exit=new Promise((resolve)=>child.once("exit",(code,signal)=>{this.#closed=true;this.#exited=true;this.#settle(new AsideReplError("repl_closed",`aside repl exited (code ${code}, signal ${signal})`,{output:this.#lines.splice(0)}));resolve()}));child.stdout.setEncoding("utf8");child.stdout.on("data",(chunk)=>this.#onData(chunk));child.stderr?.setEncoding("utf8");child.stderr?.on("data",(chunk)=>this.#onData(chunk));child.stdin.on?.("error",(error)=>{if(error.code!=="EPIPE"){this.#settle(new AsideReplError("repl_closed",`aside repl stdin failed: ${error.message}`,{output:this.#lines.splice(0)}))}})}async ready(timeoutMs){const banner=await this.#waitFor((pending)=>pending.endsWith(PROMPT),timeoutMs,"repl_start_timeout");const info={};for(const line of banner){const account=/^account: (\S+)/.exec(line)?.[1];if(account!==undefined)info.account=account;const dir=/^sessionDir: (.+)$/.exec(line)?.[1];if(dir!==undefined)info.sessionDir=dir.trim()}return info}async call(line,{tag,timeoutMs}){if(this.#closed)throw new AsideReplError("repl_closed","aside repl session is closed");this.#child.stdin.write(`${line}
1404
+ })()`}async function bskSnapshot(session,{tabId,timeoutMs,context,observation,expect,dependsOn,...snapshotOptions}={}){const reply=await session.evaluate(buildSnapshotExpression(snapshotOptions),{tabId,timeoutMs,context,observation,expect,dependsOn,awaitPromise:false,returnByValue:true});if(!reply||readProperty(reply,"ok")===false){const text=optionalProperty(optionalProperty(reply,"error"),"text")??"unknown error";throw new Error(`bskSnapshot failed inside the page: ${text}`)}const value=readProperty(reply,"value");const tree=value?readProperty(value,"tree"):undefined;if(!value||typeof tree!=="string")throw new Error("bskSnapshot: page returned no tree");const error=readProperty(value,"error");if(error)throw new Error(`bskSnapshot: ${error}`);return{tree,refs:readProperty(value,"refs"),css:readProperty(value,"css")}}var SCRIPT_AT_EOF=/piped stdin runs as one script/i;var LISTS_REPL_TOOL=/^\s*repl(?:[ \t]|$)/m;function captureCli({spawn,command,args,env,timeoutMs}){return new Promise((resolve)=>{const[bin,...lead]=command;let child;try{child=spawn(bin,[...lead,...args],{env,stdio:["ignore","pipe","pipe"],windowsHide:true})}catch{resolve({out:null,timedOut:false});return}let out="";const timer=setTimeout(()=>{child.kill();resolve({out:null,timedOut:true})},timeoutMs);child.stdout?.setEncoding("utf8");child.stdout?.on("data",(chunk)=>{out+=chunk});child.stderr?.setEncoding("utf8");child.stderr?.on("data",(chunk)=>{out+=chunk});child.once("error",()=>{clearTimeout(timer);resolve({out:null,timedOut:false})});child.once("close",(code)=>{clearTimeout(timer);resolve({out:code===0?out:null,timedOut:false})})})}async function replTransportFor(options){const help=await captureCli({...options,args:["repl","--help"]});if(help.out!==null)return SCRIPT_AT_EOF.test(help.out)?"mcp":"line";if(!help.timedOut)return"line";const mcpHelp=await captureCli({...options,args:["mcp","--help"]});return mcpHelp.out!==null&&LISTS_REPL_TOOL.test(mcpHelp.out)?"mcp":"line"}async function asideCliVersion(options){const{out}=await captureCli({...options,args:["--version"]});return out?.trim()||null}class AsideReplError extends Error{constructor(code,message,{output=[],setup}={}){super(message);this.name="AsideReplError";this.code=code;this.output=output;if(setup)this.setup=setup}}var CLOSE_TIMEOUT_MS=5000;var KILL_GRACE_MS=2000;var PROMPT="repl > ";var MARKER=/^\[(ok|error) \| \d+ms\]$/;var ANSI=/\x1B\[[0-9;?]*[ -/]*[@-~]/g;var plain=(text)=>text.replace(ANSI,"");var finished2=(lines,tag)=>MARKER.test(lines.at(-1)??"")&&(lines.at(-2)??"").startsWith(tag);class LineTransport{#child;#buffer="";#lines=[];#waiter=null;#closed=false;#exited=false;#terminated=false;#exit;constructor(child){this.#child=child;this.#exit=new Promise((resolve)=>child.once("exit",(code,signal)=>{this.#closed=true;this.#exited=true;this.#settle(new AsideReplError("repl_closed",`aside repl exited (code ${code}, signal ${signal})`,{output:this.#lines.splice(0)}));resolve()}));child.stdout.setEncoding("utf8");child.stdout.on("data",(chunk)=>this.#onData(chunk));child.stderr?.setEncoding("utf8");child.stderr?.on("data",(chunk)=>this.#onData(chunk));child.stdin.on?.("error",(error)=>{if(error.code!=="EPIPE"){this.#settle(new AsideReplError("repl_closed",`aside repl stdin failed: ${error.message}`,{output:this.#lines.splice(0)}))}})}async ready(timeoutMs){const banner=await this.#waitFor((pending)=>pending.endsWith(PROMPT),timeoutMs,"repl_start_timeout");const info={};for(const line of banner){const account=/^account: (\S+)/.exec(line)?.[1];if(account!==undefined)info.account=account;const dir=/^sessionDir: (.+)$/.exec(line)?.[1];if(dir!==undefined)info.sessionDir=dir.trim()}return info}async call(line,{tag,timeoutMs}){if(this.#closed)throw new AsideReplError("repl_closed","aside repl session is closed");this.#child.stdin.write(`${line}
1405
1405
  `);const output=await this.#waitFor((pending,lines)=>pending.endsWith(PROMPT)&&finished2(lines,tag),timeoutMs,"repl_timeout");const markerAt=output.findLastIndex((entry)=>MARKER.test(entry));if(markerAt===-1)throw new AsideReplError("repl_protocol","aside repl answered without an [ok|error] marker",{output});const body=output.slice(0,markerAt);if(output[markerAt]?.startsWith("[error")){throw new AsideReplError("repl_error",body.join(`
1406
1406
  `)||"aside repl reported an error",{output:body})}return body}async close(){this.#closed=true;if(this.#exited)return;if(!this.#terminated){this.#child.stdin.end(`exit
1407
1407
  `);if(await this.#exitsWithin(CLOSE_TIMEOUT_MS))return;this.#terminate()}if(await this.#exitsWithin(KILL_GRACE_MS))return;this.#child.kill("SIGKILL");await this.#exit}async#exitsWithin(ms){let timer;const timedOut=new Promise((resolve)=>{timer=setTimeout(()=>resolve(false),ms)});const exited=await Promise.race([this.#exit.then(()=>true),timedOut]);clearTimeout(timer);return exited}#terminate(){this.#closed=true;this.#terminated=true;this.#child.kill()}#onData(chunk){this.#buffer+=chunk;let newline;while((newline=this.#buffer.indexOf(`
@@ -1415,4 +1415,4 @@ ${code}
1415
1415
  return { url: omowTab.url(), title: await omowTab.title() };`)}async snapshot({find,context,interactive,showHidden,selector,ref}={}){validateSnapshotOptions({find,context});const options=Object.fromEntries(Object.entries({interactive,showHidden,selector,ref}).filter(([,value])=>value!==undefined));const result=await this.run(`if (!page) throw new Error("no current page: call open(url) first");
1416
1416
  const omowSnap = await snapshot(page, ${JSON.stringify(options)});
1417
1417
  return { tree: omowSnap.tree, diff: omowSnap.diff };`);if(find===undefined)return result;const tree=isObject2(result)&&typeof result["tree"]==="string"?result["tree"]:undefined;const found=findSnapshotLines({tree,refs:{}},find,context);return{tree:found.tree,find:found.find}}async close(){await this.#transport.close()}#call(line,tag){const run=this.#queue.then(()=>this.#transport.call(line,{tag,timeoutMs:this.#callTimeoutMs}));this.#queue=run.catch(()=>{});return run}}async function connectAside({account,host,asideCommand,autoSetup=true,env=process.env,home,startTimeoutMs=DEFAULT_START_TIMEOUT_MS,callTimeoutMs=DEFAULT_CALL_TIMEOUT_MS,spawn=spawnChild}={}){let command=asideCommand;if(!command&&autoSetup){const setup=await asideOnboard({env,account,installOnlyWithApp:true,...home?{home}:{}});if(!setup.ready)throw new AsideReplError("aside_not_ready",String(setup.nextStep),{setup});command=[setup.cli.bin]}command??=[findAsideBinary({env,...home?{home}:{}})];const[bin,...lead]=command;if(!bin){throw new AsideReplError("aside_not_found","the Aside CLI is not installed: install it from Aside Settings > Developers, or set ASIDE_BIN")}const cliCommand=[bin,...lead];const cli={spawn,command:cliCommand,env};const protocol=await replTransportFor({...cli,timeoutMs:CLI_PROBE_TIMEOUT_MS});const subcommand=protocol==="mcp"?"mcp":"repl";const args=[...lead,subcommand];if(account)args.push("--account",account);if(host)args.push("--host",host);const childEnv=protocol==="mcp"&&env["ASIDE_MCP_REPL_IDLE_TIMEOUT_MS"]===undefined?{...env,ASIDE_MCP_REPL_IDLE_TIMEOUT_MS:"0"}:env;const child=spawn(bin,args,{env:childEnv,stdio:["pipe","pipe","pipe"],windowsHide:true});const spawned=new Promise((resolve,reject)=>{child.once("spawn",resolve);child.once("error",(error)=>reject(new AsideReplError("repl_start_failed",`could not start aside ${subcommand}: ${error.message}`)))});await spawned;if(!hasPipes(child)){child.kill();throw new AsideReplError("repl_start_failed",`aside ${subcommand} started without stdin and stdout pipes`)}const session=new AsideSession(child,{callTimeoutMs,protocol,account:account??null});try{return await session.ready(startTimeoutMs)}catch(error){await session.close();if(!(error instanceof AsideReplError)||error.code!=="repl_start_timeout")throw error;const version=await asideCliVersion({...cli,timeoutMs:CLI_PROBE_TIMEOUT_MS});throw new AsideReplError("repl_start_timeout",`aside ${subcommand} (Aside CLI ${version??"of unknown version"}) did not answer within ${startTimeoutMs} ms`,{output:error.output})}}function requireEgo(ego){if(!ego||typeof ego.sendCDPMessage!=="function"){throw new EgoCdpError("ego_unavailable","Ego Lite bindings are unavailable: run inside `ego-browser nodejs`, or pass { ego }")}return ego}class EgoCdpError extends Error{constructor(code,message,{method}={}){super(message);this.name="EgoCdpError";this.code=code;if(method)this.method=method}}var DEFAULT_COMMAND_TIMEOUT_MS3=30000;var isObject3=(value)=>typeof value==="object"&&value!==null;var sessionIdOf=(value)=>typeof value==="string"?value:undefined;var stringOr=(value,fallback)=>typeof value==="string"?value:fallback;class EgoCdpClient{#ego;#seq=randomInt2(1,1073741824);#onMessageHandler=(payload)=>this.#onMessage(payload);#onSendErrorHandler=(message,code)=>this.#onSendError(message,code);#pending=new Map;#closedSessions=new Set;#events=new SerialEmitter;#connected=false;#commandTimeoutMs;#dialogPolicy;transportEvents=new SerialEmitter;logId;isHeadless=false;constructor({ego=globalThis.ego,commandTimeoutMs,logId,dialogPolicy}={}){this.#ego=requireEgo(ego);this.#commandTimeoutMs=commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS3;this.logId=logId??`cdp-ego-${Date.now()}`;this.#dialogPolicy=normalizeDialogPolicy(dialogPolicy)}get isConnected(){return this.#connected}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(policy){this.#dialogPolicy=normalizeDialogPolicy(policy)}async ensureConnected(){if(this.#connected)return;if(this.#ego.onCDPMessage||this.#ego.onSendCDPMessageError){throw new EgoCdpError("ego_busy","another client already holds Ego's CDP callbacks in this runtime; close it first")}this.#ego.onCDPMessage=this.#onMessageHandler;this.#ego.onSendCDPMessageError=this.#onSendErrorHandler;this.#connected=true;await this.#dispatch("Target.setDiscoverTargets",{discover:true}).catch(()=>{});await this.transportEvents.emit("connected",undefined)}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 the Ego transport: ${method}`);await this.ensureConnected();return this.#dispatch(method,params,sessionId,opts)}#dispatch(method,params,sessionId,opts={}){if(!this.#connected)return Promise.reject(new EgoCdpError("ego_closed",`Ego CDP client is closed: ${method}`,{method}));if(sessionId&&this.#closedSessions.has(sessionId)&&method!=="Page.close"){return Promise.reject(new CdpSessionDetachedError(`Page closed: ${method}`,{method,sessionId}))}const id=this.#seq++;const message={id,method};if(params!==undefined)message.params=params;if(sessionId)message.sessionId=sessionId;const{promise,resolve,reject}=Promise.withResolvers();const timeoutMs=opts.timeoutMs??this.#commandTimeoutMs;const timeout=timeoutMs>0?setTimeout(()=>{this.#pending.delete(id);reject(new CdpCommandTimeoutError(`CDP command timeout: ${method}`,{method,sessionId:sessionId??null}))},timeoutMs):undefined;this.#pending.set(id,{method,sessionId,resolve,reject,timeout});try{this.#ego.sendCDPMessage(JSON.stringify(message))}catch(error){this.#take(id);const errorCode=isObject3(error)?error["error_code"]:undefined;const errorMessage=isObject3(error)?error["message"]:undefined;return Promise.reject(new EgoCdpError(String(errorCode??"ego_send_failed"),String(errorMessage??String(error)),{method}))}return promise}on(method,fn){return this.#events.on(method,({data})=>fn(data.payload,data.meta))}async discoverTargets(){const result=await this.send("Target.getTargets");const targetInfos=isObject3(result)?result.targetInfos:undefined;if(!Array.isArray(targetInfos))throw new TypeError("Target.getTargets returned no targetInfos array");return targetInfos.map((t)=>{const info=isObject3(t)?t:{};return{id:stringOr(info["targetId"],""),type:stringOr(info["type"],""),url:stringOr(info["url"],""),title:stringOr(info["title"],""),description:stringOr(info["description"],undefined),faviconUrl:stringOr(info["faviconUrl"],undefined),parentId:stringOr(info["openerId"],undefined)}})}closeSession(sessionId){this.#closedSessions.add(sessionId);this.#failWhere((entry)=>entry.sessionId===sessionId,(entry)=>new CdpSessionDetachedError(`Page closed: ${entry.method}`,{method:entry.method,sessionId}))}async close(){if(!this.#connected)return;this.#connected=false;if(this.#ego.onCDPMessage===this.#onMessageHandler)this.#ego.onCDPMessage=undefined;if(this.#ego.onSendCDPMessageError===this.#onSendErrorHandler)this.#ego.onSendCDPMessageError=undefined;this.#failWhere(()=>true,(entry)=>new EgoCdpError("ego_closed",`Ego CDP client closed: ${entry.method}`,{method:entry.method}));await this.transportEvents.emit("disconnected",undefined).catch(()=>{})}#take(id){const entry=this.#pending.get(id);if(!entry)return null;this.#pending.delete(id);if(entry.timeout)clearTimeout(entry.timeout);return entry}#failWhere(match,makeError){for(const[id,entry]of this.#pending){if(!match(entry))continue;this.#take(id);entry.reject(makeError(entry))}}#onSendError(message,code){let id;try{const parsed=JSON.parse(message);id=isObject3(parsed)?parsed["id"]:undefined}catch{id=undefined}const reason=`Ego refused the CDP send (${code??"unknown"})`;if(typeof id==="number"){const entry=this.#take(id);if(entry)entry.reject(new EgoCdpError(code??"ego_send_refused",`${reason}: ${entry.method}`,{method:entry.method}));return}this.#failWhere(()=>true,(entry)=>new EgoCdpError(code??"ego_send_refused",`${reason}: ${entry.method}`,{method:entry.method}))}#onMessage(payload){let msg;try{msg=JSON.parse(payload)}catch{return}if(msg===null)throw new TypeError("Cannot read properties of null (reading 'id')");if(!isObject3(msg))return;if(typeof msg["id"]==="number"){const entry=this.#take(msg["id"]);if(!entry)return;if(msg["error"]){const cdpError=isObject3(msg["error"])?msg["error"]:{};const error=Object.assign(Error(String(cdpError["message"]??`CDP command failed: ${entry.method}`)),{code:cdpError["code"],data:cdpError["data"]});entry.reject(error)}else{entry.resolve(msg["result"])}return}const method=msg["method"];if(typeof method!=="string")return;const params=msg["params"];const sessionId=sessionIdOf(msg["sessionId"]);const detachedSessionId=isObject3(params)?params["sessionId"]:undefined;if(method==="Target.detachedFromTarget"&&detachedSessionId){this.#failWhere((entry)=>entry.sessionId===detachedSessionId,(entry)=>new CdpSessionDetachedError(`CDP session detached: ${entry.method}`,{method:entry.method,sessionId:detachedSessionId}))}else if(method==="Inspector.targetCrashed"&&sessionId){this.#failWhere((entry)=>entry.sessionId===sessionId&&entry.method!=="Page.reload",(entry)=>new CdpSessionCrashedError(`CDP session crashed: ${entry.method}`,{method:entry.method,sessionId}))}const meta={sessionId};const dialog=method==="Page.javascriptDialogOpening"&&sessionId?new Dialog(dialogPolicyParams(params),(action)=>this.send("Page.handleJavaScriptDialog",action,sessionId)):undefined;if(dialog)meta.dialog=dialog;const emitted=this.#events.emit(method,{data:{payload:params,meta}}).catch(()=>{});return dialog?emitted.then(()=>answerWithPolicy(dialog,this.#dialogPolicy,dialogPolicyParams(params))).catch(()=>{}):undefined}}async function selectTaskSpace(ego,{taskSpace,taskName,profileId}){if(taskSpace!==undefined){if(!Number.isInteger(taskSpace))throw new TypeError("taskSpace is Ego's numeric task-space id (ego.listTaskSpaces()[i].id)");ego.useTaskSpace(taskSpace);return{id:taskSpace}}if(typeof ego.createTaskSpace!=="function"||typeof ego.useTaskSpace!=="function"){throw new EgoCdpError("ego_task_space_unsupported","this Ego runtime has no createTaskSpace/useTaskSpace; pass taskSpace with an id the agent already claimed")}const created=await ego.createTaskSpace(taskName??`omowright-${Date.now()}`,...profileId?[profileId]:[]);if(!created||created.error){throw new EgoCdpError(String(created?.error_code??"ego_task_space_failed"),`Ego could not create a task space: ${created?.error??"no result"}`)}ego.useTaskSpace(created.id);return created}async function connectEgo({ego:egoOption=globalThis.ego,taskSpace,taskName,profileId,storageRoot,commandTimeoutMs,logId,dialogPolicy}={}){const ego=requireEgo(egoOption);const client=new EgoCdpClient({ego,commandTimeoutMs,logId,dialogPolicy});if(ego.onCDPMessage||ego.onSendCDPMessageError){throw new EgoCdpError("ego_busy","another client already holds Ego's CDP callbacks in this runtime; close it first")}const space=await selectTaskSpace(ego,{taskSpace,taskName,profileId});await client.ensureConnected();const connection=new BrowserConnection(client,{storageRoot});await connection.initialize();return Object.assign(connection,{engine:"ego",taskSpace:space})}function requireDir(dir,join){if(typeof dir==="string")return dir;Reflect.apply(join,undefined,[dir]);throw new TypeError(`path.join accepted a ${typeof dir} directory`)}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)+`
1418
- `;if(platform==="linux"&&!browser.userExternalDir){return{kind:"file",path:pathFor(platform).join(requireDir(browser.externalDir,pathFor(platform).join),`${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:pathFor(platform).join(requireDir(browser.userDataDir,pathFor(platform).join),"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=readFileSync7}={}){if(!browser.userDataDir)return false;for(const profile of["Default","Profile 1","Profile 2","Profile 3"]){const file=path23.join(browser.userDataDir,profile,"Preferences");let prefs;try{prefs=JSON.parse(readFile(file,"utf8"))}catch{continue}const uninstalls=optionalProperty(optionalProperty(prefs,"extensions"),"external_uninstalls");if(Array.isArray(uninstalls)&&uninstalls.includes(id))return true}return false}function runRegDefault(args){return new Promise((resolve)=>{const child=spawn9(windowsSystemTool("reg.exe"),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=writeFileSync4,readFile=readFileSync7,runReg=runRegDefault}={}){if(browser===undefined)throw readProperty(browser,"store");const entry=externalExtensionEntry({platform,browser});const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const label=browser.label??browser.id;const storeHint=`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. ${storeHint}`}}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:storeHint};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{mkdirSync3(path23.dirname(entry.path),{recursive:true});writeFile(entry.path,entry.content)}catch(error){const code=readProperty(error,"code");if(code==="EACCES"||code==="EPERM"||code==="EROFS"){return{...entry,registered:false,alreadyPresent:false,reason:"not_writable",humanStep:`${entry.path} is not writable without administrator rights. ${storeHint}`}}throw error}return{...entry,registered:true,alreadyPresent:false}}async function unregisterExternalExtension({platform=process.platform,browser,runReg=runRegDefault}={}){if(browser===undefined)throw readProperty(browser,"store");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=existsSync9(entry.path);if(present)rmSync4(entry.path,{force:true});return{...entry,removed:present}}var PROBE_TIMEOUT_MS2=3000;function runDefault2(command,args){return new Promise((resolve)=>{execFile4(command,args,{timeout:PROBE_TIMEOUT_MS2,windowsHide:true,maxBuffer:8388608},(error,stdout)=>{resolve(error?null:String(stdout))})})}function parseMacDefaultBrowser(plistJson){let handlers;try{handlers=optionalProperty(JSON.parse(plistJson),"LSHandlers")}catch{return null}if(!Array.isArray(handlers))return null;const list=handlers;const pick=(scheme)=>{const handler=list.find((h)=>optionalProperty(h,"LSHandlerURLScheme")===scheme&&typeof readProperty(h,"LSHandlerRoleAll")==="string");return handler===undefined?undefined:readProperty(handler,"LSHandlerRoleAll")};const role=pick("https")??pick("http");return typeof role==="string"?role.toLowerCase():"com.apple.safari"}function parseWindowsProgId(regOutput){const match=/ProgId\s+REG_SZ\s+(\S+)/i.exec(regOutput??"");return 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(path24.posix.basename(line))}}return[...names]}async function probeDefault({platform,home,run}){if(platform==="darwin"){const plist=path24.posix.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(windowsSystemTool("reg.exe"),["query",key,"/v","ProgId"]))}return null}async function probeRunning({platform,run}){const out=platform==="win32"?await run(windowsSystemTool("tasklist.exe"),["/fo","csv","/nh"]):await run("ps",platform==="darwin"?["-axo","comm="]:["-eo","comm="]);return out===null?null:parseProcessNames(platform,out)}function lastUsedAt(browser,stat,{join}){let latest=null;for(const rel of[["Local State"],["Default","History"],["Default","Preferences"]]){try{const mtime=stat(join(browser.userDataDir,...rel)).mtimeMs;if(latest===null||mtime>latest)latest=mtime}catch{}}return latest}async function probeBrowserSignals({platform=process.platform,home=homedir7(),browsers=[],run=runDefault2,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,pathFor(platform))]));return{defaultBrowser,running,lastUsed}}var RECENT_USE_MS=604800000;var OWN_TOKEN_NAMES=new Set(["edge","opera","brave","arc"]);var FAMILY_NAMES=new Set(["chrome","chromium"]);var ALWAYS_SEND_OWN_TOKEN=new Set(["edge","opera"]);function sentBy(name,candidates){if(OWN_TOKEN_NAMES.has(name))return candidates.filter((c)=>c.id===name);if(!FAMILY_NAMES.has(name))return[];const running=candidates.filter((c)=>!ALWAYS_SEND_OWN_TOKEN.has(c.id)&&c.running===true);return running.length===1?running:[]}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((signal)=>Boolean(signal));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:_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:_browser,...row})=>row)}}function identifyBrowser({catalog,signals={},explicit=null,connected=[],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 attached=[...new Set(connected.flatMap((name)=>sentBy(name,candidates)))];const firstAttached=attached[0];if(attached.length===1&&firstAttached)return choose(candidates,firstAttached,"connected",`${firstAttached.label} has the BrowserSkill extension connected`,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);const firstInUse=inUse[0];if(defaultBrowser.supported===false){const suggested=inUse.length===1?firstInUse?.id??null: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);const firstRunning=runningNow[0];const onlyCandidate=candidates[0];if(inUse.length===1&&firstInUse)return choose(candidates,firstInUse,"only-in-use",`${firstInUse.label} is the only browser ${firstInUse.signals.join(", ")}`,defaultBrowser);if(runningNow.length===1&&firstRunning)return choose(candidates,firstRunning,"only-running",`${firstRunning.label} is the only browser running now`,defaultBrowser);if(inUse.length===0&&candidates.length===1&&onlyCandidate)return choose(candidates,onlyCandidate,"only-installed",`${onlyCandidate.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)}function requirePrimary(primary){if(!primary)throw new TypeError("identifyBrowser chose no primary browser without asking for a choice");return primary}var DEFAULT_WAIT_TOTAL_MS=180000;function resolveBskBin(bskBin,env){if(bskBin===null)return null;return bskBin??findBskBinary(env)}async function cliReport2({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:readProperty(status,"daemon_version"),protocolVersion:readProperty(status,"protocol_version"),browsers:readProperty(status,"browsers")??[],sessions:readProperty(status,"sessions")??[]}}catch(error){const message=readProperty(error,"message");return{running:false,error:message,code:readProperty(error,"code"),startBlocked:NO_BREAKAWAY2.test(String(message)),browsers:[],sessions:[]}}}var NO_BREAKAWAY2=/Job Object|breakaway/i;var FOREGROUND_STEP="run `bsk daemon start --foreground` in a persistent background session of the agent host (one that outlives the command, not a one-shot shell call), then check it with `bsk status` from a separate call";function daemonStep(daemon){if(daemon.startBlocked)return`Start the BrowserSkill daemon: this host does not let a command detach it (Windows Job Object breakaway is prohibited), so retrying \`bsk status\` or \`bsk daemon start\` fails the same way; ${FOREGROUND_STEP}.`;return`Start the BrowserSkill daemon: bskOnboard() (or \`bsk status\` once) starts it. If the host reaps background processes or the start fails, ${FOREGROUND_STEP}; do not retry a detached \`bsk daemon start\`.`}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"&&existsSync10(entry.path)&&readFileSync8(entry.path,"utf8")===entry.content;return{...browser,registration:entry,extensionRegistered}}async function identify({platform,home,env,exists,browser,connected,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,connected,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 nextStepFor2({cli,daemon,browsers,browsersConnected,identification,primary:chosen}){if(browsersConnected.length>0)return browsersConnected.every(isTabGroupingExtension)?TAB_GROUPING_EXTENSION_STEP:null;if(!cli.installed)return"Install the bsk CLI (bskOnboard() runs the official installer).";if(!daemon.running)return daemonStep(daemon);if(browsers.length===0&&!chosen)return NO_BROWSER_STEP;if(identification.needsChoice)return choiceStep(identification);const primary=requirePrimary(chosen);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=homedir8(),env=process.env,client,bskBin,cliVersion=cliVersionDefault,waitForBrowserMs=0,exists=existsSync10,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){const cli=await cliReport2({bskBin,env,cliVersion});const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:false});const daemon=await daemonReport(ipc,waitForBrowserMs);const browsersConnected=listOrEmpty(daemon.browsers,"system.status browsers");const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,connected:browsersConnected.map((b)=>readProperty(b,"browser_name")),signals,probeSignals,now});const outdatedExtensions=browsersConnected.filter(isTabGroupingExtension);const report={cli,daemon,browsers,primary:primary??null,identification,browsersConnected,outdatedExtensions,ready:browsersConnected.length>outdatedExtensions.length};report.nextStep=nextStepFor2(report);return report}async function bskOnboard({platform=process.platform,home=homedir8(),env=process.env,client,bskBin,installDir,installCli=installBskCli,cliVersion=cliVersionDefault,onHumanStep=()=>{},waitForBrowserMs=15000,waitTotalMs=DEFAULT_WAIT_TOTAL_MS,exists=existsSync10,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){let cli=await cliReport2({bskBin,env,cliVersion});let install=null;if(!cli.installed){install=await installCli({platform,home,installDir});cli=install.installed?await cliReport2({bskBin:install.bskBin,env,cliVersion}):cli}const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:true});let daemon=await daemonReport(ipc,0);let browsersConnected=listOrEmpty(daemon.browsers,"system.status browsers");const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,connected:browsersConnected.map((b)=>readProperty(b,"browser_name")),signals,probeSignals,now});const registrations=[];let humanStep=null;let needsChoice=false;if(browsersConnected.length===0){if(browsers.length===0&&!primary){humanStep=NO_BROWSER_STEP}else if(identification.needsChoice){needsChoice=true;humanStep=choiceStep(identification)}else if(daemon.running){const chosen=requirePrimary(primary);const registration=await registerExternalExtension({platform,browser:chosen});registrations.push({browser:chosen.id,...registration});humanStep=registration.humanStep;onHumanStep({browser:chosen.id,step:registration.humanStep,registered:registration.registered,needsRestart:registration.needsRestart})}}const deadline=Date.now()+waitTotalMs;while(!needsChoice&&browsersConnected.length===0&&daemon.running&&Date.now()<deadline){browsersConnected=await listBrowsers(ipc,{waitForBrowserMs});if(waitForBrowserMs===0)break}daemon={...daemon,browsers:browsersConnected};const outdatedExtensions=browsersConnected.filter(isTabGroupingExtension);const ready=browsersConnected.length>outdatedExtensions.length;if(!ready&&outdatedExtensions.length>0){humanStep=TAB_GROUPING_EXTENSION_STEP;onHumanStep({browser:readProperty(outdatedExtensions[0],"browser_name"),step:humanStep,registered:true,needsRestart:false})}const nextStep=ready?null:humanStep??nextStepFor2({cli,daemon,browsers,browsersConnected,identification,primary});return{cli,install,daemon,browsers,primary:primary??null,identification,needsChoice,registrations,humanStep:ready?null:humanStep,nextStep,browsersConnected,outdatedExtensions,ready}}var ENGINE_ORDER=Object.freeze(["aside","ego","bsk","cloak"]);var ENGINE_NAMES=new Set(ENGINE_ORDER);var isEngineName=(name)=>ENGINE_NAMES.has(name);function engineName(name){if(!isEngineName(name))throw new TypeError(`unknown browser engine "${name}"; expected one of ${ENGINE_ORDER.join(", ")}`);return name}class NoBrowserEngineError extends Error{constructor(attempts){super(`no browser engine connected: ${attempts.map((a)=>`${a.engine}: ${a.reason}`).join("; ")}`);this.name="NoBrowserEngineError";this.code="no_engine";this.attempts=attempts}}async function targetCount(handle){try{return(await handle.listTargets()).length}catch(error){await handle.close().catch(()=>{});throw error}}var ENGINES={aside:async(options)=>{let handle;try{handle=await connectAside(options)}catch(error){if(error instanceof AsideReplError&&error.code==="aside_not_ready")return{skipped:error.message};throw error}try{if(await handle.run("return true")!==true)throw new Error("aside repl did not echo a probe value")}catch(error){await handle.close().catch(()=>{});throw error}return{handle,verified:"aside repl evaluated a probe call"}},ego:async(options)=>{const ego=options.ego??globalThis.ego;if(!ego||typeof ego.sendCDPMessage!=="function")return{skipped:"Ego Lite bindings are absent (only inside `ego-browser nodejs`)"};const handle=await connectEgo({...options,ego});return{handle,verified:`CDP listed ${await targetCount(handle)} targets in task space ${handle.taskSpace?.id??"?"}`}},bsk:async(options)=>{const handle=await connectBrowserSkill(options);return{handle,verified:`BrowserSkill started session ${handle.sessionId} in browser ${String(handle.browserInstanceId??"?")}`}},cloak:async(options)=>{const handle=await connectCloakProfile(options);return{handle,verified:`CDP listed ${await targetCount(handle)} targets in the CloakBrowser profile`}}};function runEngine(engine,options){return ENGINES[engine](options)}function reasonOf(error){const code=optionalProperty(error,"code");return`${code?`${code}: `:""}${optionalProperty(error,"message")??String(error)}`}function closeHandle(handle){return handle instanceof BskSession?handle.stop():handle.close()}async function connectBrowser({prefer,allow=ENGINE_ORDER,crossCheck=false,...perEngine}={}){for(const name of[prefer,...allow].filter(Boolean))engineName(name);const order=prefer?[engineName(prefer),...ENGINE_ORDER.filter((name)=>name!==prefer)]:[...ENGINE_ORDER];const attempts=[];let primary=null;const extra=[];for(const engine of order){if(!allow.includes(engine)){attempts.push({engine,ok:false,reason:"not allowed by the caller"});continue}if(primary&&!crossCheck){attempts.push({engine,ok:false,reason:`not tried: ${primary.engine} connected first`});continue}const started=performance.now();try{const result=await runEngine(engine,perEngine[engine]??{});const ms=Math.round(performance.now()-started);if(result.skipped!==undefined){attempts.push({engine,ok:false,ms,reason:result.skipped});continue}attempts.push({engine,ok:true,ms,verified:result.verified});if(primary)extra.push({engine,handle:result.handle});else primary={engine,handle:result.handle}}catch(error){attempts.push({engine,ok:false,ms:Math.round(performance.now()-started),reason:reasonOf(error)})}}if(!primary)throw new NoBrowserEngineError(attempts);const opened=[primary,...extra];return{engine:primary.engine,handle:primary.handle,attempts,attached:opened.map((entry)=>entry.engine),crossCheck:extra,closeAll:async()=>{const failures=(await Promise.all(opened.map(async({engine,handle})=>{try{await closeHandle(handle);return null}catch(cause){return new Error(`${engine} failed to close: ${reasonOf(cause)}`,{cause})}}))).filter((error)=>error!==null);if(failures.length)throw new AggregateError(failures,failures.map((error)=>error.message).join("; "))}}}/*! omowright | MIT License | Copyright (c) 2026 Yeongyu Kim | https://github.com/code-yeongyu/omowright */export{AgentTabManager,AsideReplError,AsideSession,BROWSERSKILL_EXTENSION_IDS,BROWSER_EVENT_NAMES,BridgeProtocolError,BridgeUnavailableError,BrowserCdpCommandError,BrowserConnection,BskIpcClient,BskRpcError,BskSession,CdpClient,CdpCommandTimeoutError,CdpPipeClosedError,CdpSessionCrashedError,CdpSessionDetachedError,CommandSchema,DEFAULT_AGENT_VIEWPORT,DEVICE_PRESETS,ENGINE_ORDER,EgoCdpClient,EgoCdpError,ElementHandle,EventSchema,ExtensionHelloSchema,FrameLocator,FrameManager,HostHelloSchema,Locator,ModifierState,NetworkBodyUnavailableError,NoBrowserEngineError,OMOWRIGHT_PAGE_CDP_METHODS,OmOKeyboard,OmOMouse,OmOPage,PAGE_EVENT_NAMES,PipeCdpClient,ResponseSchema,RunningBrowserError,STORE_PAGE_URLS,SessionManager,SharedConnectionError,TabRepository,UnsupportedOperationError,VideoRecordingError,WaitForFunctionTimeoutError,asideDoctor,asideOnboard,bskDoctor,bskOnboard,bskSnapshot,buildCloakBrowserArgs,buildSnapshotExpression,catalogBrowsers,collectWhileScrolling,compactSnapshot,connect,connectAside,connectBrowser,connectBrowserSkill,connectCloakProfile,connectEgo,connectNamed,connectPipe,connectRunningBrowser,createAgentTabs,createBridgeClient,createCaptcha,createChromeApi2 as createChromeApi,createCua,createEvents,createNativeMessagingHost,createNetworkSnoop,createRoutes,createTrace,decodeFrames,describeLayers,detectBrowsers,emulate,encodeFrame,externalExtensionEntry,findAsideBinary,findCloakBrowserPath,findRunningBrowser,identifyBrowser,injectCookies,installAsideCli,installBskCli,installNativeMessagingHost,layersHeader,listBrowsers,listInstances,macOSVisionOcr,normalizeDialogPolicy,pageBundle,probeBrowserSignals,readDaemonInfo,readDevToolsActivePort,reconcileFrames,registerExternalExtension,repinViewport,requestHuman,resolveBskHome,resolveCloakProfile,resolveDialogAction,sanitizeCookies,selectors,snapshotTokens,snapshotWithFrames,snapshotWithLayers,takeSnapshot,toHar,toolSchemas,unregisterExternalExtension};
1418
+ `;if(platform==="linux"&&!browser.userExternalDir){return{kind:"file",path:pathFor(platform).join(requireDir(browser.externalDir,pathFor(platform).join),`${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:pathFor(platform).join(requireDir(browser.userDataDir,pathFor(platform).join),"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=readFileSync7}={}){if(!browser.userDataDir)return false;for(const profile of["Default","Profile 1","Profile 2","Profile 3"]){const file=path23.join(browser.userDataDir,profile,"Preferences");let prefs;try{prefs=JSON.parse(readFile(file,"utf8"))}catch{continue}const uninstalls=optionalProperty(optionalProperty(prefs,"extensions"),"external_uninstalls");if(Array.isArray(uninstalls)&&uninstalls.includes(id))return true}return false}function runRegDefault(args){return new Promise((resolve)=>{const child=spawn9(windowsSystemTool("reg.exe"),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=writeFileSync4,readFile=readFileSync7,runReg=runRegDefault}={}){if(browser===undefined)throw readProperty(browser,"store");const entry=externalExtensionEntry({platform,browser});const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const label=browser.label??browser.id;const storeHint=`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. ${storeHint}`}}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:storeHint};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{mkdirSync3(path23.dirname(entry.path),{recursive:true});writeFile(entry.path,entry.content)}catch(error){const code=readProperty(error,"code");if(code==="EACCES"||code==="EPERM"||code==="EROFS"){return{...entry,registered:false,alreadyPresent:false,reason:"not_writable",humanStep:`${entry.path} is not writable without administrator rights. ${storeHint}`}}throw error}return{...entry,registered:true,alreadyPresent:false}}async function unregisterExternalExtension({platform=process.platform,browser,runReg=runRegDefault}={}){if(browser===undefined)throw readProperty(browser,"store");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=existsSync9(entry.path);if(present)rmSync4(entry.path,{force:true});return{...entry,removed:present}}var PROBE_TIMEOUT_MS2=3000;function runDefault2(command,args){return new Promise((resolve)=>{execFile5(command,args,{timeout:PROBE_TIMEOUT_MS2,windowsHide:true,maxBuffer:8388608},(error,stdout)=>{resolve(error?null:String(stdout))})})}function parseMacDefaultBrowser(plistJson){let handlers;try{handlers=optionalProperty(JSON.parse(plistJson),"LSHandlers")}catch{return null}if(!Array.isArray(handlers))return null;const list=handlers;const pick=(scheme)=>{const handler=list.find((h)=>optionalProperty(h,"LSHandlerURLScheme")===scheme&&typeof readProperty(h,"LSHandlerRoleAll")==="string");return handler===undefined?undefined:readProperty(handler,"LSHandlerRoleAll")};const role=pick("https")??pick("http");return typeof role==="string"?role.toLowerCase():"com.apple.safari"}function parseWindowsProgId(regOutput){const match=/ProgId\s+REG_SZ\s+(\S+)/i.exec(regOutput??"");return 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(path24.posix.basename(line))}}return[...names]}async function probeDefault({platform,home,run}){if(platform==="darwin"){const plist=path24.posix.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(windowsSystemTool("reg.exe"),["query",key,"/v","ProgId"]))}return null}async function probeRunning({platform,run}){const out=platform==="win32"?await run(windowsSystemTool("tasklist.exe"),["/fo","csv","/nh"]):await run("ps",platform==="darwin"?["-axo","comm="]:["-eo","comm="]);return out===null?null:parseProcessNames(platform,out)}function lastUsedAt(browser,stat,{join}){let latest=null;for(const rel of[["Local State"],["Default","History"],["Default","Preferences"]]){try{const mtime=stat(join(browser.userDataDir,...rel)).mtimeMs;if(latest===null||mtime>latest)latest=mtime}catch{}}return latest}async function probeBrowserSignals({platform=process.platform,home=homedir7(),browsers=[],run=runDefault2,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,pathFor(platform))]));return{defaultBrowser,running,lastUsed}}var RECENT_USE_MS=604800000;var OWN_TOKEN_NAMES=new Set(["edge","opera","brave","arc"]);var FAMILY_NAMES=new Set(["chrome","chromium"]);var ALWAYS_SEND_OWN_TOKEN=new Set(["edge","opera"]);function sentBy(name,candidates){if(OWN_TOKEN_NAMES.has(name))return candidates.filter((c)=>c.id===name);if(!FAMILY_NAMES.has(name))return[];const running=candidates.filter((c)=>!ALWAYS_SEND_OWN_TOKEN.has(c.id)&&c.running===true);return running.length===1?running:[]}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((signal)=>Boolean(signal));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:_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:_browser,...row})=>row)}}function identifyBrowser({catalog,signals={},explicit=null,connected=[],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 attached=[...new Set(connected.flatMap((name)=>sentBy(name,candidates)))];const firstAttached=attached[0];if(attached.length===1&&firstAttached)return choose(candidates,firstAttached,"connected",`${firstAttached.label} has the BrowserSkill extension connected`,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);const firstInUse=inUse[0];if(defaultBrowser.supported===false){const suggested=inUse.length===1?firstInUse?.id??null: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);const firstRunning=runningNow[0];const onlyCandidate=candidates[0];if(inUse.length===1&&firstInUse)return choose(candidates,firstInUse,"only-in-use",`${firstInUse.label} is the only browser ${firstInUse.signals.join(", ")}`,defaultBrowser);if(runningNow.length===1&&firstRunning)return choose(candidates,firstRunning,"only-running",`${firstRunning.label} is the only browser running now`,defaultBrowser);if(inUse.length===0&&candidates.length===1&&onlyCandidate)return choose(candidates,onlyCandidate,"only-installed",`${onlyCandidate.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)}function requirePrimary(primary){if(!primary)throw new TypeError("identifyBrowser chose no primary browser without asking for a choice");return primary}var DEFAULT_WAIT_TOTAL_MS=180000;function resolveBskBin(bskBin,env){if(bskBin===null)return null;return bskBin??findBskBinary(env)}async function cliReport2({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:readProperty(status,"daemon_version"),protocolVersion:readProperty(status,"protocol_version"),browsers:readProperty(status,"browsers")??[],sessions:readProperty(status,"sessions")??[]}}catch(error){const message=readProperty(error,"message");return{running:false,error:message,code:readProperty(error,"code"),startBlocked:NO_BREAKAWAY2.test(String(message)),browsers:[],sessions:[]}}}var NO_BREAKAWAY2=/Job Object|breakaway/i;var FOREGROUND_STEP="run `bsk daemon start --foreground` in a persistent background session of the agent host (one that outlives the command, not a one-shot shell call), then check it with `bsk status` from a separate call";function daemonStep(daemon){if(daemon.startBlocked)return`Start the BrowserSkill daemon: this host does not let a command detach it (Windows Job Object breakaway is prohibited), so retrying \`bsk status\` or \`bsk daemon start\` fails the same way; ${FOREGROUND_STEP}.`;return`Start the BrowserSkill daemon: bskOnboard() (or \`bsk status\` once) starts it. If the host reaps background processes or the start fails, ${FOREGROUND_STEP}; do not retry a detached \`bsk daemon start\`.`}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"&&existsSync10(entry.path)&&readFileSync8(entry.path,"utf8")===entry.content;return{...browser,registration:entry,extensionRegistered}}async function identify({platform,home,env,exists,browser,connected,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,connected,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 nextStepFor2({cli,daemon,browsers,browsersConnected,identification,primary:chosen}){if(browsersConnected.length>0)return browsersConnected.every(isTabGroupingExtension)?TAB_GROUPING_EXTENSION_STEP:null;if(!cli.installed)return"Install the bsk CLI (bskOnboard() runs the official installer).";if(!daemon.running)return daemonStep(daemon);if(browsers.length===0&&!chosen)return NO_BROWSER_STEP;if(identification.needsChoice)return choiceStep(identification);const primary=requirePrimary(chosen);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=homedir8(),env=process.env,client,bskBin,cliVersion=cliVersionDefault,waitForBrowserMs=0,exists=existsSync10,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){const cli=await cliReport2({bskBin,env,cliVersion});const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:false});const daemon=await daemonReport(ipc,waitForBrowserMs);const browsersConnected=listOrEmpty(daemon.browsers,"system.status browsers");const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,connected:browsersConnected.map((b)=>readProperty(b,"browser_name")),signals,probeSignals,now});const outdatedExtensions=browsersConnected.filter(isTabGroupingExtension);const report={cli,daemon,browsers,primary:primary??null,identification,browsersConnected,outdatedExtensions,ready:browsersConnected.length>outdatedExtensions.length};report.nextStep=nextStepFor2(report);return report}async function bskOnboard({platform=process.platform,home=homedir8(),env=process.env,client,bskBin,installDir,installCli=installBskCli,cliVersion=cliVersionDefault,onHumanStep=()=>{},waitForBrowserMs=15000,waitTotalMs=DEFAULT_WAIT_TOTAL_MS,exists=existsSync10,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){let cli=await cliReport2({bskBin,env,cliVersion});let install=null;if(!cli.installed){install=await installCli({platform,home,installDir});cli=install.installed?await cliReport2({bskBin:install.bskBin,env,cliVersion}):cli}const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:true});let daemon=await daemonReport(ipc,0);let browsersConnected=listOrEmpty(daemon.browsers,"system.status browsers");const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,connected:browsersConnected.map((b)=>readProperty(b,"browser_name")),signals,probeSignals,now});const registrations=[];let humanStep=null;let needsChoice=false;if(browsersConnected.length===0){if(browsers.length===0&&!primary){humanStep=NO_BROWSER_STEP}else if(identification.needsChoice){needsChoice=true;humanStep=choiceStep(identification)}else if(daemon.running){const chosen=requirePrimary(primary);const registration=await registerExternalExtension({platform,browser:chosen});registrations.push({browser:chosen.id,...registration});humanStep=registration.humanStep;onHumanStep({browser:chosen.id,step:registration.humanStep,registered:registration.registered,needsRestart:registration.needsRestart})}}const deadline=Date.now()+waitTotalMs;while(!needsChoice&&browsersConnected.length===0&&daemon.running&&Date.now()<deadline){browsersConnected=await listBrowsers(ipc,{waitForBrowserMs});if(waitForBrowserMs===0)break}daemon={...daemon,browsers:browsersConnected};const outdatedExtensions=browsersConnected.filter(isTabGroupingExtension);const ready=browsersConnected.length>outdatedExtensions.length;if(!ready&&outdatedExtensions.length>0){humanStep=TAB_GROUPING_EXTENSION_STEP;onHumanStep({browser:readProperty(outdatedExtensions[0],"browser_name"),step:humanStep,registered:true,needsRestart:false})}const nextStep=ready?null:humanStep??nextStepFor2({cli,daemon,browsers,browsersConnected,identification,primary});return{cli,install,daemon,browsers,primary:primary??null,identification,needsChoice,registrations,humanStep:ready?null:humanStep,nextStep,browsersConnected,outdatedExtensions,ready}}var ENGINE_ORDER=Object.freeze(["aside","ego","bsk","cloak"]);var ENGINE_NAMES=new Set(ENGINE_ORDER);var isEngineName=(name)=>ENGINE_NAMES.has(name);function engineName(name){if(!isEngineName(name))throw new TypeError(`unknown browser engine "${name}"; expected one of ${ENGINE_ORDER.join(", ")}`);return name}class NoBrowserEngineError extends Error{constructor(attempts){super(`no browser engine connected: ${attempts.map((a)=>`${a.engine}: ${a.reason}`).join("; ")}`);this.name="NoBrowserEngineError";this.code="no_engine";this.attempts=attempts}}async function targetCount(handle){try{return(await handle.listTargets()).length}catch(error){await handle.close().catch(()=>{});throw error}}var ENGINES={aside:async(options)=>{let handle;try{handle=await connectAside(options)}catch(error){if(error instanceof AsideReplError&&error.code==="aside_not_ready")return{skipped:error.message};throw error}try{if(await handle.run("return true")!==true)throw new Error("aside repl did not echo a probe value")}catch(error){await handle.close().catch(()=>{});throw error}return{handle,verified:"aside repl evaluated a probe call"}},ego:async(options)=>{const ego=options.ego??globalThis.ego;if(!ego||typeof ego.sendCDPMessage!=="function")return{skipped:"Ego Lite bindings are absent (only inside `ego-browser nodejs`)"};const handle=await connectEgo({...options,ego});return{handle,verified:`CDP listed ${await targetCount(handle)} targets in task space ${handle.taskSpace?.id??"?"}`}},bsk:async(options)=>{const handle=await connectBrowserSkill(options);return{handle,verified:`BrowserSkill started session ${handle.sessionId} in browser ${String(handle.browserInstanceId??"?")}`}},cloak:async(options)=>{const handle=await connectCloakProfile(options);return{handle,verified:`CDP listed ${await targetCount(handle)} targets in the CloakBrowser profile`}}};function runEngine(engine,options){return ENGINES[engine](options)}function reasonOf(error){const code=optionalProperty(error,"code");return`${code?`${code}: `:""}${optionalProperty(error,"message")??String(error)}`}function closeHandle(handle){return handle instanceof BskSession?handle.stop():handle.close()}async function connectBrowser({prefer,allow=ENGINE_ORDER,crossCheck=false,...perEngine}={}){for(const name of[prefer,...allow].filter(Boolean))engineName(name);const order=prefer?[engineName(prefer),...ENGINE_ORDER.filter((name)=>name!==prefer)]:[...ENGINE_ORDER];const attempts=[];let primary=null;const extra=[];for(const engine of order){if(!allow.includes(engine)){attempts.push({engine,ok:false,reason:"not allowed by the caller"});continue}if(primary&&!crossCheck){attempts.push({engine,ok:false,reason:`not tried: ${primary.engine} connected first`});continue}const started=performance.now();try{const result=await runEngine(engine,perEngine[engine]??{});const ms=Math.round(performance.now()-started);if(result.skipped!==undefined){attempts.push({engine,ok:false,ms,reason:result.skipped});continue}attempts.push({engine,ok:true,ms,verified:result.verified});if(primary)extra.push({engine,handle:result.handle});else primary={engine,handle:result.handle}}catch(error){attempts.push({engine,ok:false,ms:Math.round(performance.now()-started),reason:reasonOf(error)})}}if(!primary)throw new NoBrowserEngineError(attempts);const opened=[primary,...extra];return{engine:primary.engine,handle:primary.handle,attempts,attached:opened.map((entry)=>entry.engine),crossCheck:extra,closeAll:async()=>{const failures=(await Promise.all(opened.map(async({engine,handle})=>{try{await closeHandle(handle);return null}catch(cause){return new Error(`${engine} failed to close: ${reasonOf(cause)}`,{cause})}}))).filter((error)=>error!==null);if(failures.length)throw new AggregateError(failures,failures.map((error)=>error.message).join("; "))}}}/*! omowright | MIT License | Copyright (c) 2026 Yeongyu Kim | https://github.com/code-yeongyu/omowright */export{AgentTabManager,AsideReplError,AsideSession,BROWSERSKILL_EXTENSION_IDS,BROWSER_EVENT_NAMES,BridgeProtocolError,BridgeUnavailableError,BrowserCdpCommandError,BrowserConnection,BskIpcClient,BskRpcError,BskSession,CdpClient,CdpCommandTimeoutError,CdpPipeClosedError,CdpSessionCrashedError,CdpSessionDetachedError,CommandSchema,DEFAULT_AGENT_VIEWPORT,DEVICE_PRESETS,ENGINE_ORDER,EgoCdpClient,EgoCdpError,ElementHandle,EventSchema,ExtensionHelloSchema,FrameLocator,FrameManager,HostHelloSchema,Locator,ModifierState,NetworkBodyUnavailableError,NoBrowserEngineError,OMOWRIGHT_PAGE_CDP_METHODS,OmOKeyboard,OmOMouse,OmOPage,PAGE_EVENT_NAMES,PipeCdpClient,ResponseSchema,RunningBrowserError,STORE_PAGE_URLS,SessionManager,SharedConnectionError,TabRepository,UnsupportedOperationError,VideoRecordingError,WaitForFunctionTimeoutError,asideDoctor,asideOnboard,bskDoctor,bskOnboard,bskSnapshot,buildCloakBrowserArgs,buildSnapshotExpression,catalogBrowsers,collectWhileScrolling,compactSnapshot,connect,connectAside,connectBrowser,connectBrowserSkill,connectCloakProfile,connectEgo,connectNamed,connectPipe,connectRunningBrowser,createAgentTabs,createBridgeClient,createCaptcha,createChromeApi2 as createChromeApi,createCua,createEvents,createNativeMessagingHost,createNetworkSnoop,createRoutes,createTrace,decodeFrames,describeLayers,detectBrowsers,emulate,encodeFrame,externalExtensionEntry,findAsideBinary,findCloakBrowserPath,findRunningBrowser,identifyBrowser,injectCookies,installAsideCli,installBskCli,installNativeMessagingHost,layersHeader,listBrowsers,listInstances,macOSVisionOcr,normalizeDialogPolicy,pageBundle,probeBrowserSignals,readDaemonInfo,readDevToolsActivePort,reconcileFrames,registerExternalExtension,repinViewport,requestHuman,resolveBskHome,resolveCloakProfile,resolveDialogAction,sanitizeCookies,selectors,snapshotTokens,snapshotWithFrames,snapshotWithLayers,takeSnapshot,toHar,toolSchemas,unregisterExternalExtension};