oh-my-opencode 5.1.48 → 5.1.54

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 (1312) hide show
  1. package/dist/agents/atlas/agent.d.ts +5 -5
  2. package/dist/agents/dynamic-agent-core-sections.d.ts +0 -1
  3. package/dist/agents/dynamic-agent-prompt-builder.d.ts +1 -1
  4. package/dist/agents/gpt-apply-patch-guard.d.ts +0 -1
  5. package/dist/agents/hephaestus/agent.d.ts +3 -7
  6. package/dist/agents/hephaestus/model-support.d.ts +6 -0
  7. package/dist/agents/metis.d.ts +0 -15
  8. package/dist/agents/native-model-prompt.d.ts +9 -0
  9. package/dist/agents/native-prompt-frame.d.ts +20 -0
  10. package/dist/agents/native-tool-snippet.d.ts +6 -0
  11. package/dist/agents/refusal-rule.d.ts +7 -0
  12. package/dist/agents/sisyphus/default.d.ts +0 -1
  13. package/dist/agents/sisyphus-agent-factory.d.ts +2 -11
  14. package/dist/agents/sisyphus-junior/agent.d.ts +2 -20
  15. package/dist/agents/sisyphus-junior/index.d.ts +1 -11
  16. package/dist/agents/sisyphus-runtime-prompt-reconciler.d.ts +6 -0
  17. package/dist/agents/types.d.ts +2 -2
  18. package/dist/cli/index.js +2255 -1044
  19. package/dist/cli/service-auth/accounts-gate.d.ts +11 -0
  20. package/dist/cli/service-auth/commands.d.ts +2 -4
  21. package/dist/cli/service-auth/credential-lock.d.ts +11 -0
  22. package/dist/cli/service-auth/credential-owner.d.ts +10 -0
  23. package/dist/cli/service-auth/index.d.ts +3 -1
  24. package/dist/cli/service-auth/keystore.d.ts +33 -2
  25. package/dist/cli/service-auth/owned-refresh.d.ts +21 -0
  26. package/dist/cli/service-auth/protocol-v2.d.ts +27 -0
  27. package/dist/cli/service-auth/protocol.d.ts +32 -2
  28. package/dist/cli/service-auth/recovery-clock.d.ts +7 -0
  29. package/dist/cli/service-auth/refresh-attempt.d.ts +34 -0
  30. package/dist/cli/service-auth/session.d.ts +15 -2
  31. package/dist/cli/service-auth/signed-out-marker.d.ts +11 -0
  32. package/dist/cli-node/index.js +2255 -1044
  33. package/dist/config/schema/hooks.d.ts +1 -0
  34. package/dist/create-hooks.d.ts +1 -0
  35. package/dist/features/boulder-state/storage.d.ts +1 -1
  36. package/dist/features/boulder-state/types.d.ts +1 -1
  37. package/dist/hooks/atlas/idle-continuation.d.ts +2 -1
  38. package/dist/hooks/atlas/types.d.ts +9 -1
  39. package/dist/hooks/index.d.ts +1 -0
  40. package/dist/hooks/momus-review-persistence/hook.d.ts +19 -0
  41. package/dist/hooks/momus-review-persistence/index.d.ts +1 -0
  42. package/dist/hooks/momus-review-persistence/review-resolution.d.ts +20 -0
  43. package/dist/hooks/native-edition-nudge/hook.d.ts +3 -4
  44. package/dist/hooks/prometheus-md-only/constants.d.ts +2 -0
  45. package/dist/hooks/prometheus-md-only/fixtures/denial-log.d.ts +1 -0
  46. package/dist/hooks/prometheus-md-only/fixtures/guarded-hashline.d.ts +1 -0
  47. package/dist/hooks/prometheus-md-only/fixtures/invoke-before.d.ts +7 -0
  48. package/dist/hooks/prometheus-md-only/fixtures/opencode-patch-parser.d.ts +2 -0
  49. package/dist/hooks/prometheus-md-only/hook.d.ts +5 -1
  50. package/dist/hooks/prometheus-md-only/path-policy.d.ts +2 -9
  51. package/dist/hooks/prometheus-md-only/vendor/opencode-patch-parser.d.ts +22 -0
  52. package/dist/index.js +17483 -9494
  53. package/dist/plugin/hooks/create-core-hooks.d.ts +1 -0
  54. package/dist/plugin/hooks/create-tool-guard-hooks.d.ts +2 -1
  55. package/dist/plugin/session-tool-permissions.d.ts +10 -0
  56. package/dist/plugin/system-transform.d.ts +2 -1
  57. package/dist/plugin/tool-definition.d.ts +1 -0
  58. package/dist/shared/bun-ffi-shim.d.ts +29 -0
  59. package/dist/shared/json-file-cache-store.d.ts +11 -0
  60. package/dist/shared/posthog-activity-state.d.ts +1 -0
  61. package/dist/shared/posthog.d.ts +1 -2
  62. package/dist/shared/resolve-file-write-path.d.ts +6 -0
  63. package/dist/skills/ast-grep/README.md +1 -1
  64. package/dist/skills/ast-grep/install.ps1 +5 -3
  65. package/dist/skills/ast-grep/install.sh +4 -5
  66. package/dist/skills/ast-grep/references/install.md +2 -2
  67. package/dist/skills/ast-grep/scripts/ast_grep_helper.py +13 -3
  68. package/dist/skills/browser/runtime/omowright/index.js +24 -33
  69. package/dist/skills/browser/runtime/omowright/manifest.json +3 -3
  70. package/dist/skills/coding-agent-sessions/AGENTS.md +5 -4
  71. package/dist/skills/coding-agent-sessions/SKILL.md +11 -11
  72. package/dist/skills/coding-agent-sessions/references/all-platforms.md +2 -2
  73. package/dist/skills/coding-agent-sessions/references/codex.md +4 -4
  74. package/dist/skills/coding-agent-sessions/scripts/agent_sessions/cli.py +1 -1
  75. package/dist/skills/coding-agent-sessions/scripts/find-agent-sessions.py +6 -3
  76. package/dist/skills/frontend/ATTRIBUTION.md +105 -2
  77. package/dist/skills/frontend/SKILL.md +40 -14
  78. package/dist/skills/frontend/references/design/README.md +2 -2
  79. package/dist/skills/frontend/references/design/_INDEX.md +2 -1
  80. package/dist/skills/frontend/references/design/component-catalogs.md +14 -10
  81. package/dist/skills/frontend/references/design/design-system-architecture.md +22 -9
  82. package/dist/skills/frontend/references/design/grounding.md +29 -0
  83. package/dist/skills/frontend/references/perfection/craft-floor.md +59 -0
  84. package/dist/skills/frontend/references/perfection/detect.md +52 -0
  85. package/dist/skills/frontend/references/ui-ux-db/scripts/design_system.py +2 -0
  86. package/dist/skills/frontend/references/ui-ux-db/scripts/search.py +2 -0
  87. package/dist/skills/frontend/scripts/detect/cli.ts +70 -0
  88. package/dist/skills/frontend/scripts/detect/config.test.ts +26 -0
  89. package/dist/skills/frontend/scripts/detect/config.ts +53 -0
  90. package/dist/skills/frontend/scripts/detect/core/characters.ts +2 -0
  91. package/dist/skills/frontend/scripts/detect/core/color.test.ts +29 -0
  92. package/dist/skills/frontend/scripts/detect/core/color.ts +150 -0
  93. package/dist/skills/frontend/scripts/detect/core/page.ts +84 -0
  94. package/dist/skills/frontend/scripts/detect/core/shadow.ts +40 -0
  95. package/dist/skills/frontend/scripts/detect/core/source.ts +33 -0
  96. package/dist/skills/frontend/scripts/detect/detect.ts +77 -0
  97. package/dist/skills/frontend/scripts/detect/index.ts +23 -0
  98. package/dist/skills/frontend/scripts/detect/lint.test.ts +27 -0
  99. package/dist/skills/frontend/scripts/detect/lint.ts +98 -0
  100. package/dist/skills/frontend/scripts/detect/render/probe-placement.test.ts +19 -0
  101. package/dist/skills/frontend/scripts/detect/render/probe-placement.ts +50 -0
  102. package/dist/skills/frontend/scripts/detect/render/renderer.ts +37 -0
  103. package/dist/skills/frontend/scripts/detect/render/webview.ts +71 -0
  104. package/dist/skills/frontend/scripts/detect/report.ts +29 -0
  105. package/dist/skills/frontend/scripts/detect/rule.ts +42 -0
  106. package/dist/skills/frontend/scripts/detect/rules/color/ai-color-palette.test.ts +74 -0
  107. package/dist/skills/frontend/scripts/detect/rules/color/ai-color-palette.ts +83 -0
  108. package/dist/skills/frontend/scripts/detect/rules/color/cream-palette.test.ts +24 -0
  109. package/dist/skills/frontend/scripts/detect/rules/color/cream-palette.ts +35 -0
  110. package/dist/skills/frontend/scripts/detect/rules/color/dark-glow.test.ts +47 -0
  111. package/dist/skills/frontend/scripts/detect/rules/color/dark-glow.ts +44 -0
  112. package/dist/skills/frontend/scripts/detect/rules/color/design-system-color.test.ts +26 -0
  113. package/dist/skills/frontend/scripts/detect/rules/color/design-system-color.ts +35 -0
  114. package/dist/skills/frontend/scripts/detect/rules/color/gradient-text.test.ts +24 -0
  115. package/dist/skills/frontend/scripts/detect/rules/color/gradient-text.ts +59 -0
  116. package/dist/skills/frontend/scripts/detect/rules/color/gray-on-color.test.ts +39 -0
  117. package/dist/skills/frontend/scripts/detect/rules/color/gray-on-color.ts +38 -0
  118. package/dist/skills/frontend/scripts/detect/rules/color/index.ts +15 -0
  119. package/dist/skills/frontend/scripts/detect/rules/color/low-contrast.test.ts +209 -0
  120. package/dist/skills/frontend/scripts/detect/rules/color/low-contrast.ts +57 -0
  121. package/dist/skills/frontend/scripts/detect/rules/color/placeholder-contrast.test.ts +62 -0
  122. package/dist/skills/frontend/scripts/detect/rules/color/radial-halo.test.ts +40 -0
  123. package/dist/skills/frontend/scripts/detect/rules/color/radial-halo.ts +31 -0
  124. package/dist/skills/frontend/scripts/detect/rules/color/radial-spotlight-glow.test.ts +27 -0
  125. package/dist/skills/frontend/scripts/detect/rules/color/radial-spotlight-glow.ts +33 -0
  126. package/dist/skills/frontend/scripts/detect/rules/color/support/animation-opacity.ts +78 -0
  127. package/dist/skills/frontend/scripts/detect/rules/color/support/color-path.ts +15 -0
  128. package/dist/skills/frontend/scripts/detect/rules/color/support/contrast-pairs.ts +54 -0
  129. package/dist/skills/frontend/scripts/detect/rules/color/support/contrast-role.ts +76 -0
  130. package/dist/skills/frontend/scripts/detect/rules/color/support/glow-forms.ts +56 -0
  131. package/dist/skills/frontend/scripts/detect/rules/color/support/gradient-samples.ts +134 -0
  132. package/dist/skills/frontend/scripts/detect/rules/color/support/gradients.ts +91 -0
  133. package/dist/skills/frontend/scripts/detect/rules/color/support/mockup-roots.ts +63 -0
  134. package/dist/skills/frontend/scripts/detect/rules/color/support/page-ignore.ts +7 -0
  135. package/dist/skills/frontend/scripts/detect/rules/color/support/painted-text.ts +141 -0
  136. package/dist/skills/frontend/scripts/detect/rules/color/support/palette-roles.ts +58 -0
  137. package/dist/skills/frontend/scripts/detect/rules/color/support/placeholder-contrast.ts +25 -0
  138. package/dist/skills/frontend/scripts/detect/rules/color/support/stock-accent.ts +31 -0
  139. package/dist/skills/frontend/scripts/detect/rules/color/support/text-colors.ts +80 -0
  140. package/dist/skills/frontend/scripts/detect/rules/copy/aphoristic-cadence.test.ts +18 -0
  141. package/dist/skills/frontend/scripts/detect/rules/copy/aphoristic-cadence.ts +20 -0
  142. package/dist/skills/frontend/scripts/detect/rules/copy/broken-image.test.ts +25 -0
  143. package/dist/skills/frontend/scripts/detect/rules/copy/broken-image.ts +17 -0
  144. package/dist/skills/frontend/scripts/detect/rules/copy/em-dash-overuse.test.ts +39 -0
  145. package/dist/skills/frontend/scripts/detect/rules/copy/em-dash-overuse.ts +46 -0
  146. package/dist/skills/frontend/scripts/detect/rules/copy/index.ts +15 -0
  147. package/dist/skills/frontend/scripts/detect/rules/copy/marketing-buzzword.test.ts +18 -0
  148. package/dist/skills/frontend/scripts/detect/rules/copy/marketing-buzzword.ts +33 -0
  149. package/dist/skills/frontend/scripts/detect/rules/copy/numbered-section-labels.test.ts +58 -0
  150. package/dist/skills/frontend/scripts/detect/rules/copy/numbered-section-labels.ts +34 -0
  151. package/dist/skills/frontend/scripts/detect/rules/copy/repeated-container-text.test.ts +43 -0
  152. package/dist/skills/frontend/scripts/detect/rules/copy/repeated-container-text.ts +56 -0
  153. package/dist/skills/frontend/scripts/detect/rules/copy/script-error.test.ts +48 -0
  154. package/dist/skills/frontend/scripts/detect/rules/copy/script-error.ts +38 -0
  155. package/dist/skills/frontend/scripts/detect/rules/copy/skipped-heading.test.ts +49 -0
  156. package/dist/skills/frontend/scripts/detect/rules/copy/skipped-heading.ts +81 -0
  157. package/dist/skills/frontend/scripts/detect/rules/copy/support/numbered-label.ts +94 -0
  158. package/dist/skills/frontend/scripts/detect/rules/copy/support/page-text.ts +37 -0
  159. package/dist/skills/frontend/scripts/detect/rules/copy/theater-slop-phrase.test.ts +17 -0
  160. package/dist/skills/frontend/scripts/detect/rules/copy/theater-slop-phrase.ts +21 -0
  161. package/dist/skills/frontend/scripts/detect/rules/decoration/blinking-cursor.test.ts +43 -0
  162. package/dist/skills/frontend/scripts/detect/rules/decoration/blinking-cursor.ts +48 -0
  163. package/dist/skills/frontend/scripts/detect/rules/decoration/border-accent-on-rounded.test.ts +33 -0
  164. package/dist/skills/frontend/scripts/detect/rules/decoration/border-accent-on-rounded.ts +14 -0
  165. package/dist/skills/frontend/scripts/detect/rules/decoration/bounce-easing.test.ts +72 -0
  166. package/dist/skills/frontend/scripts/detect/rules/decoration/bounce-easing.ts +83 -0
  167. package/dist/skills/frontend/scripts/detect/rules/decoration/buried-raster.test.ts +95 -0
  168. package/dist/skills/frontend/scripts/detect/rules/decoration/buried-raster.ts +72 -0
  169. package/dist/skills/frontend/scripts/detect/rules/decoration/codex-grid-background.test.ts +28 -0
  170. package/dist/skills/frontend/scripts/detect/rules/decoration/codex-grid-background.ts +34 -0
  171. package/dist/skills/frontend/scripts/detect/rules/decoration/design-system-radius.test.ts +37 -0
  172. package/dist/skills/frontend/scripts/detect/rules/decoration/design-system-radius.ts +31 -0
  173. package/dist/skills/frontend/scripts/detect/rules/decoration/gpt-thin-border-wide-shadow.test.ts +59 -0
  174. package/dist/skills/frontend/scripts/detect/rules/decoration/gpt-thin-border-wide-shadow.ts +66 -0
  175. package/dist/skills/frontend/scripts/detect/rules/decoration/hard-offset-shadow.test.ts +45 -0
  176. package/dist/skills/frontend/scripts/detect/rules/decoration/hard-offset-shadow.ts +31 -0
  177. package/dist/skills/frontend/scripts/detect/rules/decoration/hero-eyebrow-chip.test.ts +76 -0
  178. package/dist/skills/frontend/scripts/detect/rules/decoration/hero-eyebrow-chip.ts +19 -0
  179. package/dist/skills/frontend/scripts/detect/rules/decoration/icon-tile-stack.test.ts +67 -0
  180. package/dist/skills/frontend/scripts/detect/rules/decoration/icon-tile-stack.ts +92 -0
  181. package/dist/skills/frontend/scripts/detect/rules/decoration/index.ts +38 -0
  182. package/dist/skills/frontend/scripts/detect/rules/decoration/kicker-above-heading.test.ts +126 -0
  183. package/dist/skills/frontend/scripts/detect/rules/decoration/kicker-above-heading.ts +69 -0
  184. package/dist/skills/frontend/scripts/detect/rules/decoration/marquee.test.ts +63 -0
  185. package/dist/skills/frontend/scripts/detect/rules/decoration/marquee.ts +51 -0
  186. package/dist/skills/frontend/scripts/detect/rules/decoration/organic-clip-path.test.ts +67 -0
  187. package/dist/skills/frontend/scripts/detect/rules/decoration/organic-clip-path.ts +41 -0
  188. package/dist/skills/frontend/scripts/detect/rules/decoration/pulsing-dot.test.ts +58 -0
  189. package/dist/skills/frontend/scripts/detect/rules/decoration/pulsing-dot.ts +72 -0
  190. package/dist/skills/frontend/scripts/detect/rules/decoration/repeating-stripes-gradient.test.ts +26 -0
  191. package/dist/skills/frontend/scripts/detect/rules/decoration/repeating-stripes-gradient.ts +25 -0
  192. package/dist/skills/frontend/scripts/detect/rules/decoration/shape-assembled-illustration.test.ts +59 -0
  193. package/dist/skills/frontend/scripts/detect/rules/decoration/shape-assembled-illustration.ts +58 -0
  194. package/dist/skills/frontend/scripts/detect/rules/decoration/side-tab.test.ts +91 -0
  195. package/dist/skills/frontend/scripts/detect/rules/decoration/side-tab.ts +17 -0
  196. package/dist/skills/frontend/scripts/detect/rules/decoration/support/appearance.ts +110 -0
  197. package/dist/skills/frontend/scripts/detect/rules/decoration/support/assert-cases.ts +25 -0
  198. package/dist/skills/frontend/scripts/detect/rules/decoration/support/borders.ts +150 -0
  199. package/dist/skills/frontend/scripts/detect/rules/decoration/support/clip-geometry.ts +151 -0
  200. package/dist/skills/frontend/scripts/detect/rules/decoration/support/css-candidates.ts +66 -0
  201. package/dist/skills/frontend/scripts/detect/rules/decoration/support/curve-samples.ts +55 -0
  202. package/dist/skills/frontend/scripts/detect/rules/decoration/support/gradient-pattern.ts +40 -0
  203. package/dist/skills/frontend/scripts/detect/rules/decoration/support/keyframes.ts +134 -0
  204. package/dist/skills/frontend/scripts/detect/rules/decoration/support/labels.ts +85 -0
  205. package/dist/skills/frontend/scripts/detect/rules/decoration/support/raster-state.ts +51 -0
  206. package/dist/skills/frontend/scripts/detect/rules/index.ts +16 -0
  207. package/dist/skills/frontend/scripts/detect/rules/layout/body-text-viewport-edge.test.ts +64 -0
  208. package/dist/skills/frontend/scripts/detect/rules/layout/body-text-viewport-edge.ts +62 -0
  209. package/dist/skills/frontend/scripts/detect/rules/layout/clipped-overflow-container.test.ts +40 -0
  210. package/dist/skills/frontend/scripts/detect/rules/layout/clipped-overflow-container.ts +15 -0
  211. package/dist/skills/frontend/scripts/detect/rules/layout/content-hidden-at-rest.test.ts +62 -0
  212. package/dist/skills/frontend/scripts/detect/rules/layout/content-hidden-at-rest.ts +63 -0
  213. package/dist/skills/frontend/scripts/detect/rules/layout/cramped-padding.test.ts +61 -0
  214. package/dist/skills/frontend/scripts/detect/rules/layout/cramped-padding.ts +97 -0
  215. package/dist/skills/frontend/scripts/detect/rules/layout/edge-flush-cards.test.ts +43 -0
  216. package/dist/skills/frontend/scripts/detect/rules/layout/edge-flush-cards.ts +47 -0
  217. package/dist/skills/frontend/scripts/detect/rules/layout/first-viewport-column-overflow.test.ts +28 -0
  218. package/dist/skills/frontend/scripts/detect/rules/layout/first-viewport-column-overflow.ts +43 -0
  219. package/dist/skills/frontend/scripts/detect/rules/layout/heading-rhythm.test.ts +67 -0
  220. package/dist/skills/frontend/scripts/detect/rules/layout/heading-rhythm.ts +30 -0
  221. package/dist/skills/frontend/scripts/detect/rules/layout/index.ts +21 -0
  222. package/dist/skills/frontend/scripts/detect/rules/layout/monotonous-spacing.test.ts +19 -0
  223. package/dist/skills/frontend/scripts/detect/rules/layout/monotonous-spacing.ts +32 -0
  224. package/dist/skills/frontend/scripts/detect/rules/layout/nested-cards.test.ts +60 -0
  225. package/dist/skills/frontend/scripts/detect/rules/layout/nested-cards.ts +38 -0
  226. package/dist/skills/frontend/scripts/detect/rules/layout/straggler.test.ts +33 -0
  227. package/dist/skills/frontend/scripts/detect/rules/layout/straggler.ts +28 -0
  228. package/dist/skills/frontend/scripts/detect/rules/layout/support/cards.ts +114 -0
  229. package/dist/skills/frontend/scripts/detect/rules/layout/support/clipping.ts +71 -0
  230. package/dist/skills/frontend/scripts/detect/rules/layout/support/declared-mockups.ts +46 -0
  231. package/dist/skills/frontend/scripts/detect/rules/layout/support/geometry.ts +73 -0
  232. package/dist/skills/frontend/scripts/detect/rules/layout/support/hidden-interface.ts +35 -0
  233. package/dist/skills/frontend/scripts/detect/rules/layout/support/layout-cases.ts +23 -0
  234. package/dist/skills/frontend/scripts/detect/rules/layout/support/line-breaks.ts +32 -0
  235. package/dist/skills/frontend/scripts/detect/rules/layout/support/motion.ts +77 -0
  236. package/dist/skills/frontend/scripts/detect/rules/layout/support/padding.ts +93 -0
  237. package/dist/skills/frontend/scripts/detect/rules/layout/support/rhythm.ts +161 -0
  238. package/dist/skills/frontend/scripts/detect/rules/layout/text-occlusion.test.ts +37 -0
  239. package/dist/skills/frontend/scripts/detect/rules/layout/text-occlusion.ts +84 -0
  240. package/dist/skills/frontend/scripts/detect/rules/layout/text-overflow.test.ts +83 -0
  241. package/dist/skills/frontend/scripts/detect/rules/layout/text-overflow.ts +72 -0
  242. package/dist/skills/frontend/scripts/detect/rules/layout/unbalanced-heading.test.ts +22 -0
  243. package/dist/skills/frontend/scripts/detect/rules/layout/unbalanced-heading.ts +22 -0
  244. package/dist/skills/frontend/scripts/detect/rules/layout/viewport-reflow.test.ts +34 -0
  245. package/dist/skills/frontend/scripts/detect/rules/layout/viewport-reflow.ts +33 -0
  246. package/dist/skills/frontend/scripts/detect/rules/source/ai-color-palette.test.ts +13 -0
  247. package/dist/skills/frontend/scripts/detect/rules/source/ai-color-palette.ts +11 -0
  248. package/dist/skills/frontend/scripts/detect/rules/source/aphoristic-cadence.test.ts +12 -0
  249. package/dist/skills/frontend/scripts/detect/rules/source/aphoristic-cadence.ts +14 -0
  250. package/dist/skills/frontend/scripts/detect/rules/source/border-accent-on-rounded.test.ts +14 -0
  251. package/dist/skills/frontend/scripts/detect/rules/source/border-accent-on-rounded.ts +20 -0
  252. package/dist/skills/frontend/scripts/detect/rules/source/bounce-easing.test.ts +19 -0
  253. package/dist/skills/frontend/scripts/detect/rules/source/bounce-easing.ts +21 -0
  254. package/dist/skills/frontend/scripts/detect/rules/source/broken-image.test.ts +27 -0
  255. package/dist/skills/frontend/scripts/detect/rules/source/broken-image.ts +16 -0
  256. package/dist/skills/frontend/scripts/detect/rules/source/codex-grid-background.test.ts +11 -0
  257. package/dist/skills/frontend/scripts/detect/rules/source/codex-grid-background.ts +18 -0
  258. package/dist/skills/frontend/scripts/detect/rules/source/dark-glow.test.ts +15 -0
  259. package/dist/skills/frontend/scripts/detect/rules/source/dark-glow.ts +21 -0
  260. package/dist/skills/frontend/scripts/detect/rules/source/em-dash-overuse.test.ts +13 -0
  261. package/dist/skills/frontend/scripts/detect/rules/source/em-dash-overuse.ts +15 -0
  262. package/dist/skills/frontend/scripts/detect/rules/source/gradient-text.test.ts +12 -0
  263. package/dist/skills/frontend/scripts/detect/rules/source/gradient-text.ts +11 -0
  264. package/dist/skills/frontend/scripts/detect/rules/source/gray-on-color.test.ts +20 -0
  265. package/dist/skills/frontend/scripts/detect/rules/source/gray-on-color.ts +13 -0
  266. package/dist/skills/frontend/scripts/detect/rules/source/index.ts +19 -0
  267. package/dist/skills/frontend/scripts/detect/rules/source/marketing-buzzword.test.ts +12 -0
  268. package/dist/skills/frontend/scripts/detect/rules/source/marketing-buzzword.ts +17 -0
  269. package/dist/skills/frontend/scripts/detect/rules/source/marquee.test.ts +12 -0
  270. package/dist/skills/frontend/scripts/detect/rules/source/marquee.ts +12 -0
  271. package/dist/skills/frontend/scripts/detect/rules/source/monotonous-spacing.test.ts +13 -0
  272. package/dist/skills/frontend/scripts/detect/rules/source/monotonous-spacing.ts +22 -0
  273. package/dist/skills/frontend/scripts/detect/rules/source/overused-font.test.ts +21 -0
  274. package/dist/skills/frontend/scripts/detect/rules/source/overused-font.ts +16 -0
  275. package/dist/skills/frontend/scripts/detect/rules/source/radial-halo.test.ts +16 -0
  276. package/dist/skills/frontend/scripts/detect/rules/source/radial-halo.ts +14 -0
  277. package/dist/skills/frontend/scripts/detect/rules/source/side-tab.test.ts +29 -0
  278. package/dist/skills/frontend/scripts/detect/rules/source/side-tab.ts +58 -0
  279. package/dist/skills/frontend/scripts/detect/rules/source/support/accent-scans.ts +78 -0
  280. package/dist/skills/frontend/scripts/detect/rules/source/support/check-source.ts +6 -0
  281. package/dist/skills/frontend/scripts/detect/rules/source/support/corners.ts +105 -0
  282. package/dist/skills/frontend/scripts/detect/rules/source/support/css-effects.ts +81 -0
  283. package/dist/skills/frontend/scripts/detect/rules/source/support/css-scopes.ts +131 -0
  284. package/dist/skills/frontend/scripts/detect/rules/source/support/image-tags.ts +113 -0
  285. package/dist/skills/frontend/scripts/detect/rules/source/support/js-punctuation.ts +34 -0
  286. package/dist/skills/frontend/scripts/detect/rules/source/support/markup-scope.ts +44 -0
  287. package/dist/skills/frontend/scripts/detect/rules/source/support/source-color.ts +42 -0
  288. package/dist/skills/frontend/scripts/detect/rules/source/support/source-shadow.ts +15 -0
  289. package/dist/skills/frontend/scripts/detect/rules/source/support/source-text.ts +110 -0
  290. package/dist/skills/frontend/scripts/detect/rules/typography/all-caps-body.test.ts +24 -0
  291. package/dist/skills/frontend/scripts/detect/rules/typography/all-caps-body.ts +15 -0
  292. package/dist/skills/frontend/scripts/detect/rules/typography/design-system-font-size.test.ts +21 -0
  293. package/dist/skills/frontend/scripts/detect/rules/typography/design-system-font-size.ts +23 -0
  294. package/dist/skills/frontend/scripts/detect/rules/typography/design-system-font.test.ts +22 -0
  295. package/dist/skills/frontend/scripts/detect/rules/typography/design-system-font.ts +24 -0
  296. package/dist/skills/frontend/scripts/detect/rules/typography/extreme-negative-tracking.test.ts +23 -0
  297. package/dist/skills/frontend/scripts/detect/rules/typography/extreme-negative-tracking.ts +18 -0
  298. package/dist/skills/frontend/scripts/detect/rules/typography/flat-type-hierarchy.test.ts +33 -0
  299. package/dist/skills/frontend/scripts/detect/rules/typography/flat-type-hierarchy.ts +26 -0
  300. package/dist/skills/frontend/scripts/detect/rules/typography/index.ts +21 -0
  301. package/dist/skills/frontend/scripts/detect/rules/typography/italic-serif-display.test.ts +24 -0
  302. package/dist/skills/frontend/scripts/detect/rules/typography/italic-serif-display.ts +24 -0
  303. package/dist/skills/frontend/scripts/detect/rules/typography/justified-text.test.ts +31 -0
  304. package/dist/skills/frontend/scripts/detect/rules/typography/justified-text.ts +32 -0
  305. package/dist/skills/frontend/scripts/detect/rules/typography/line-length.test.ts +43 -0
  306. package/dist/skills/frontend/scripts/detect/rules/typography/line-length.ts +28 -0
  307. package/dist/skills/frontend/scripts/detect/rules/typography/oversized-h1.test.ts +26 -0
  308. package/dist/skills/frontend/scripts/detect/rules/typography/oversized-h1.ts +20 -0
  309. package/dist/skills/frontend/scripts/detect/rules/typography/overused-font.test.ts +35 -0
  310. package/dist/skills/frontend/scripts/detect/rules/typography/overused-font.ts +45 -0
  311. package/dist/skills/frontend/scripts/detect/rules/typography/support/drawn-enlargement.ts +48 -0
  312. package/dist/skills/frontend/scripts/detect/rules/typography/support/fading-text.ts +48 -0
  313. package/dist/skills/frontend/scripts/detect/rules/typography/support/flex-runs.ts +16 -0
  314. package/dist/skills/frontend/scripts/detect/rules/typography/support/font-family.ts +28 -0
  315. package/dist/skills/frontend/scripts/detect/rules/typography/support/painted-text.test.ts +63 -0
  316. package/dist/skills/frontend/scripts/detect/rules/typography/support/painted-text.ts +81 -0
  317. package/dist/skills/frontend/scripts/detect/rules/typography/support/svg-size.ts +57 -0
  318. package/dist/skills/frontend/scripts/detect/rules/typography/support/text-context.ts +112 -0
  319. package/dist/skills/frontend/scripts/detect/rules/typography/support/text-lines.ts +43 -0
  320. package/dist/skills/frontend/scripts/detect/rules/typography/support/type-hierarchy.ts +48 -0
  321. package/dist/skills/frontend/scripts/detect/rules/typography/tight-leading.test.ts +54 -0
  322. package/dist/skills/frontend/scripts/detect/rules/typography/tight-leading.ts +47 -0
  323. package/dist/skills/frontend/scripts/detect/rules/typography/tiny-text.test.ts +60 -0
  324. package/dist/skills/frontend/scripts/detect/rules/typography/tiny-text.ts +23 -0
  325. package/dist/skills/frontend/scripts/detect/rules/typography/undersized-ui-text.test.ts +98 -0
  326. package/dist/skills/frontend/scripts/detect/rules/typography/undersized-ui-text.ts +28 -0
  327. package/dist/skills/frontend/scripts/detect/rules/typography/wide-tracking.test.ts +26 -0
  328. package/dist/skills/frontend/scripts/detect/rules/typography/wide-tracking.ts +26 -0
  329. package/dist/skills/frontend/scripts/detect/snapshot/collect.ts +158 -0
  330. package/dist/skills/frontend/scripts/detect/snapshot/style-props.ts +25 -0
  331. package/dist/skills/frontend/scripts/detect/testing/build-snapshot.ts +78 -0
  332. package/dist/skills/frontend/scripts/detect/tsconfig.json +19 -0
  333. package/dist/skills/frontend/scripts/detect/types.ts +124 -0
  334. package/dist/skills/programming/SKILL.md +15 -74
  335. package/dist/skills/programming/references/go/README.md +1 -1
  336. package/dist/skills/programming/references/go/bootstrap.md +2 -2
  337. package/dist/skills/programming/references/python/README.md +4 -4
  338. package/dist/skills/programming/references/python/one-liners.md +5 -5
  339. package/dist/skills/programming/references/testing/README.md +82 -0
  340. package/dist/skills/programming/references/testing/junk-classes.md +56 -0
  341. package/dist/skills/programming/references/typescript/README.md +1 -2
  342. package/dist/skills/programming/scripts/go/new-project.ts +197 -0
  343. package/dist/skills/programming/scripts/python/new-project.ts +231 -0
  344. package/dist/skills/programming/scripts/python/new-script.ts +134 -0
  345. package/dist/skills/programming/scripts/rust/new-project.ts +215 -0
  346. package/dist/skills/programming/scripts/scaffolders.test.ts +96 -0
  347. package/dist/skills/programming/scripts/shared/run-tool.ts +19 -0
  348. package/dist/skills/ultimate-browsing/SKILL.md +5 -4
  349. package/dist/skills/ultimate-browsing/engine/AGENTS.md +2 -2
  350. package/dist/skills/ultimate-browsing/engine/__main__.py +9 -6
  351. package/dist/skills/ultimate-browsing/engine/summary.py +1 -1
  352. package/dist/skills/ultimate-browsing/references/insane-search/README.md +4 -4
  353. package/dist/skills/ultimate-browsing/scripts/extract_cookies.py +4 -2
  354. package/dist/skills/ulw-research/AGENTS.md +8 -4
  355. package/dist/skills/ulw-research/SKILL.md +7 -316
  356. package/dist/skills/ulw-research/references/deliverable-phase.md +23 -21
  357. package/dist/skills/ulw-research/references/fact-ledger-grammar.md +7 -3
  358. package/dist/skills/ulw-research/references/fact-ledger.md +42 -8
  359. package/dist/skills/ulw-research/references/fidelity-claim-kinds.md +1 -1
  360. package/dist/skills/ulw-research/references/markdown-blocks.md +12 -0
  361. package/dist/skills/ulw-research/references/report-gates.md +12 -5
  362. package/dist/skills/ulw-research/references/research-collection.md +195 -0
  363. package/dist/skills/ulw-research/references/research-delivery.md +123 -0
  364. package/dist/skills/ulw-research/scripts/claim-kinds.mjs +33 -5
  365. package/dist/skills/ulw-research/scripts/claim-kinds.test.ts +37 -2
  366. package/dist/skills/ulw-research/scripts/claim-prefix.test.ts +76 -0
  367. package/dist/skills/ulw-research/scripts/contracts-validation.test.ts +83 -0
  368. package/dist/skills/ulw-research/scripts/contracts.mjs +13 -4
  369. package/dist/skills/ulw-research/scripts/contracts.test.ts +6 -110
  370. package/dist/skills/ulw-research/scripts/conversion-altered.test.ts +154 -0
  371. package/dist/skills/ulw-research/scripts/conversion-originals.test.ts +297 -0
  372. package/dist/skills/ulw-research/scripts/conversion-probe-classes.test.ts +361 -0
  373. package/dist/skills/ulw-research/scripts/conversion-probe.mjs +229 -0
  374. package/dist/skills/ulw-research/scripts/conversion-probe.test.ts +218 -0
  375. package/dist/skills/ulw-research/scripts/copy-returns-polish.test.ts +4 -3
  376. package/dist/skills/ulw-research/scripts/css-hiding.mjs +158 -0
  377. package/dist/skills/ulw-research/scripts/css-lite.mjs +4 -2
  378. package/dist/skills/ulw-research/scripts/delivery-barrier-meaning.test.ts +186 -0
  379. package/dist/skills/ulw-research/scripts/delivery-barrier.test.ts +40 -87
  380. package/dist/skills/ulw-research/scripts/entities.mjs +13 -4
  381. package/dist/skills/ulw-research/scripts/fact-commands-fill.mjs +11 -1
  382. package/dist/skills/ulw-research/scripts/fact-commands-meaning.mjs +13 -9
  383. package/dist/skills/ulw-research/scripts/fact-commands-polish.mjs +40 -18
  384. package/dist/skills/ulw-research/scripts/fact-commands-verify.mjs +25 -8
  385. package/dist/skills/ulw-research/scripts/fact-commands.mjs +35 -16
  386. package/dist/skills/ulw-research/scripts/fact-derive-2.test.ts +149 -0
  387. package/dist/skills/ulw-research/scripts/fact-derive.mjs +7 -2
  388. package/dist/skills/ulw-research/scripts/fact-derive.test.ts +7 -192
  389. package/dist/skills/ulw-research/scripts/fact-fill.mjs +6 -4
  390. package/dist/skills/ulw-research/scripts/fact-ledger-kinds.mjs +6 -7
  391. package/dist/skills/ulw-research/scripts/fact-ledger-kinds.test.ts +2 -1
  392. package/dist/skills/ulw-research/scripts/fact-ledger-legacy.test.ts +2 -1
  393. package/dist/skills/ulw-research/scripts/fact-locate.mjs +15 -9
  394. package/dist/skills/ulw-research/scripts/fact-unit-dimensions-2.test.ts +149 -0
  395. package/dist/skills/ulw-research/scripts/fact-unit-dimensions.test.ts +4 -168
  396. package/dist/skills/ulw-research/scripts/fact-unit-rules.test.ts +3 -229
  397. package/dist/skills/ulw-research/scripts/fidelity-claims.mjs +4 -3
  398. package/dist/skills/ulw-research/scripts/fidelity-csv.mjs +32 -0
  399. package/dist/skills/ulw-research/scripts/fidelity-lexicon.mjs +1 -1
  400. package/dist/skills/ulw-research/scripts/fidelity-originals.mjs +161 -0
  401. package/dist/skills/ulw-research/scripts/fidelity-policy.mjs +4 -4
  402. package/dist/skills/ulw-research/scripts/fidelity-records.mjs +81 -14
  403. package/dist/skills/ulw-research/scripts/fidelity-snapshot-readability.mjs +49 -0
  404. package/dist/skills/ulw-research/scripts/fidelity-sources.mjs +76 -0
  405. package/dist/skills/ulw-research/scripts/fidelity-trace.mjs +25 -11
  406. package/dist/skills/ulw-research/scripts/fidelity-value-unit.mjs +202 -0
  407. package/dist/skills/ulw-research/scripts/fidelity-values.mjs +40 -39
  408. package/dist/skills/ulw-research/scripts/fidelity-values.test.ts +8 -29
  409. package/dist/skills/ulw-research/scripts/gates-fidelity.mjs +8 -6
  410. package/dist/skills/ulw-research/scripts/gates-static-headings.test.ts +17 -0
  411. package/dist/skills/ulw-research/scripts/gates-static.mjs +10 -1
  412. package/dist/skills/ulw-research/scripts/html-lite.mjs +6 -2
  413. package/dist/skills/ulw-research/scripts/html-markup.mjs +2 -2
  414. package/dist/skills/ulw-research/scripts/html-text-map.mjs +140 -0
  415. package/dist/skills/ulw-research/scripts/html-text-map.test.ts +148 -0
  416. package/dist/skills/ulw-research/scripts/markdown-closers.mjs +126 -0
  417. package/dist/skills/ulw-research/scripts/md-lite-boundaries.test.ts +46 -0
  418. package/dist/skills/ulw-research/scripts/md-lite.mjs +1 -1
  419. package/dist/skills/ulw-research/scripts/number-grammar.mjs +33 -0
  420. package/dist/skills/ulw-research/scripts/number-grammar.test.ts +36 -0
  421. package/dist/skills/ulw-research/scripts/numerals.mjs +18 -7
  422. package/dist/skills/ulw-research/scripts/numerals.test.ts +3 -0
  423. package/dist/skills/ulw-research/scripts/outcome-start.mjs +66 -0
  424. package/dist/skills/ulw-research/scripts/outcome-start.test.ts +109 -0
  425. package/dist/skills/ulw-research/scripts/outcome.mjs +11 -22
  426. package/dist/skills/ulw-research/scripts/page-source-locator.test.ts +187 -0
  427. package/dist/skills/ulw-research/scripts/placeholder.mjs +18 -6
  428. package/dist/skills/ulw-research/scripts/polish-apply.mjs +3 -2
  429. package/dist/skills/ulw-research/scripts/polish-markup.test.ts +15 -1
  430. package/dist/skills/ulw-research/scripts/polish-partial.test.ts +42 -0
  431. package/dist/skills/ulw-research/scripts/raw-decode.mjs +110 -0
  432. package/dist/skills/ulw-research/scripts/raw-locator.mjs +47 -0
  433. package/dist/skills/ulw-research/scripts/raw-snapshot.test.ts +139 -0
  434. package/dist/skills/ulw-research/scripts/report-tools-2.test.ts +233 -0
  435. package/dist/skills/ulw-research/scripts/report-tools-3.test.ts +141 -0
  436. package/dist/skills/ulw-research/scripts/report-tools-4.test.ts +135 -0
  437. package/dist/skills/ulw-research/scripts/report-tools-5.test.ts +231 -0
  438. package/dist/skills/ulw-research/scripts/report-tools-commands.mjs +1 -1
  439. package/dist/skills/ulw-research/scripts/report-tools.mjs +7 -1
  440. package/dist/skills/ulw-research/scripts/report-tools.test.ts +5 -800
  441. package/dist/skills/ulw-research/scripts/snapshot-readability.test.ts +116 -0
  442. package/dist/skills/ulw-research/scripts/source-commands.mjs +79 -26
  443. package/dist/skills/ulw-research/scripts/source-integrity.test.ts +243 -0
  444. package/dist/skills/ulw-research/scripts/source-refresh.mjs +82 -0
  445. package/dist/skills/ulw-research/scripts/source-snapshot.mjs +73 -69
  446. package/dist/skills/ulw-research/scripts/source-snapshot.test.ts +7 -4
  447. package/dist/skills/ulw-research/scripts/source-view.mjs +89 -0
  448. package/dist/skills/ulw-research/scripts/sources-citation.mjs +203 -0
  449. package/dist/skills/ulw-research/scripts/sources-citation.test.ts +236 -0
  450. package/dist/skills/ulw-research/scripts/tests/contracts-support.ts +147 -0
  451. package/dist/skills/ulw-research/scripts/tests/delivery-barrier-session.ts +59 -0
  452. package/dist/skills/ulw-research/scripts/tests/derive-clock.ts +4 -0
  453. package/dist/skills/ulw-research/scripts/tests/fact-derive-support.ts +65 -0
  454. package/dist/skills/ulw-research/scripts/tests/fact-unit-dimensions-support.ts +41 -0
  455. package/dist/skills/ulw-research/scripts/tests/fact-unit-rules-support.ts +241 -0
  456. package/dist/skills/ulw-research/scripts/tests/fidelity-values-support.ts +30 -0
  457. package/dist/skills/ulw-research/scripts/tests/fixtures/conversion-probe.html +14 -0
  458. package/dist/skills/ulw-research/scripts/tests/fixtures/sources-shapes.html +20 -0
  459. package/dist/skills/ulw-research/scripts/tests/numeral-classes.ts +196 -0
  460. package/dist/skills/ulw-research/scripts/tests/report-tools-support.ts +182 -0
  461. package/dist/skills/ulw-research/scripts/tests/value-mode-support.ts +48 -0
  462. package/dist/skills/ulw-research/scripts/units.mjs +14 -3
  463. package/dist/skills/ulw-research/scripts/units.test.ts +10 -0
  464. package/dist/skills/ulw-research/scripts/value-mode-unit-classes.test.ts +255 -0
  465. package/dist/skills/ulw-research/scripts/value-mode-unit.test.ts +179 -0
  466. package/dist/skills/ulw-research/scripts/value-rules-cli.test.ts +157 -0
  467. package/dist/skills/ulw-research/scripts/value-rules-followups.test.ts +72 -0
  468. package/dist/skills/ulw-research/scripts/value-rules-priority.test.ts +80 -0
  469. package/dist/skills/visual-qa/SKILL.md +12 -1
  470. package/dist/tools/delegate-task/executor-types.d.ts +1 -0
  471. package/dist/tools/delegate-task/sync-session-existence.d.ts +4 -0
  472. package/dist/tools/delegate-task/types.d.ts +1 -0
  473. package/dist/tools/skill/description-formatter.d.ts +2 -1
  474. package/dist/tools/skill/types.d.ts +6 -0
  475. package/dist/tui.js +245 -58
  476. package/package.json +24 -20
  477. package/packages/git-bash-mcp/package.json +1 -1
  478. package/packages/lsp-core/src/lsp/config-loader.ts +18 -2
  479. package/packages/lsp-core/src/lsp/host-js-runtime.test.ts +150 -0
  480. package/packages/lsp-core/src/lsp/host-js-runtime.ts +57 -0
  481. package/packages/lsp-core/src/lsp/server-definitions.ts +10 -0
  482. package/packages/lsp-core/src/lsp/server-resolution.ts +9 -1
  483. package/packages/lsp-core/src/lsp/typescript-server-defaults.test.ts +84 -0
  484. package/packages/lsp-daemon/dist/cli.js +81 -15
  485. package/packages/lsp-daemon/dist/client.js +74 -8
  486. package/packages/lsp-daemon/dist/index.js +76 -10
  487. package/packages/lsp-tools-mcp/dist/cli.js +74 -8
  488. package/packages/lsp-tools-mcp/dist/mcp.js +74 -8
  489. package/packages/lsp-tools-mcp/dist/tools.js +74 -8
  490. package/packages/omo-codex/plugin/.codex-plugin/plugin.json +1 -1
  491. package/packages/omo-codex/plugin/README.md +1 -1
  492. package/packages/omo-codex/plugin/components/bootstrap/dist/cli.js +20 -4
  493. package/packages/omo-codex/plugin/components/bootstrap/hooks/hooks.json +1 -1
  494. package/packages/omo-codex/plugin/components/bootstrap/package.json +1 -1
  495. package/packages/omo-codex/plugin/components/comment-checker/hooks/hooks.json +1 -1
  496. package/packages/omo-codex/plugin/components/comment-checker/package.json +1 -1
  497. package/packages/omo-codex/plugin/components/git-bash/hooks/hooks.json +2 -2
  498. package/packages/omo-codex/plugin/components/git-bash/package.json +1 -1
  499. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/hooks/hooks.json +1 -1
  500. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/package.json +1 -1
  501. package/packages/omo-codex/plugin/components/lcx/skills/lcx-contribute-bug-fix/SKILL.md +51 -55
  502. package/packages/omo-codex/plugin/components/lcx/skills/lcx-contribute-bug-fix/agents/openai.yaml +1 -1
  503. package/packages/omo-codex/plugin/components/lcx/skills/lcx-report-bug/SKILL.md +7 -7
  504. package/packages/omo-codex/plugin/components/lcx/skills/lcx-report-bug/agents/openai.yaml +1 -1
  505. package/packages/omo-codex/plugin/components/lsp/dist/.omo-runtime-manifest.json +3 -3
  506. package/packages/omo-codex/plugin/components/lsp/dist/cli.js +77 -13
  507. package/packages/omo-codex/plugin/components/lsp/hooks/hooks.json +2 -2
  508. package/packages/omo-codex/plugin/components/lsp/package.json +1 -1
  509. package/packages/omo-codex/plugin/components/rules/hooks/hooks.json +4 -4
  510. package/packages/omo-codex/plugin/components/rules/package.json +1 -1
  511. package/packages/omo-codex/plugin/components/teammode/hooks/hooks.json +1 -1
  512. package/packages/omo-codex/plugin/components/teammode/package.json +2 -2
  513. package/packages/omo-codex/plugin/components/telemetry/README.md +2 -2
  514. package/packages/omo-codex/plugin/components/telemetry/dist/cli.js +85 -16
  515. package/packages/omo-codex/plugin/components/telemetry/dist/posthog.js +85 -20
  516. package/packages/omo-codex/plugin/components/telemetry/hooks/hooks.json +1 -1
  517. package/packages/omo-codex/plugin/components/telemetry/package.json +1 -1
  518. package/packages/omo-codex/plugin/components/telemetry/src/codex-hook.ts +2 -9
  519. package/packages/omo-codex/plugin/components/telemetry/src/posthog.ts +4 -13
  520. package/packages/omo-codex/plugin/components/telemetry/src/product-identity.ts +0 -2
  521. package/packages/omo-codex/plugin/components/telemetry/test/codex-hook-diagnostics.test.ts +0 -3
  522. package/packages/omo-codex/plugin/components/telemetry/test/codex-hook.test.ts +17 -9
  523. package/packages/omo-codex/plugin/components/ultrawork/dist/cli.js +3 -0
  524. package/packages/omo-codex/plugin/components/ultrawork/hooks/hooks.json +1 -1
  525. package/packages/omo-codex/plugin/components/ultrawork/package.json +1 -1
  526. package/packages/omo-codex/plugin/components/ultrawork/src/directive-content.ts +1 -1
  527. package/packages/omo-codex/plugin/components/ulw-execute-continuation/hooks/hooks.json +1 -1
  528. package/packages/omo-codex/plugin/components/ulw-execute-continuation/package.json +1 -1
  529. package/packages/omo-codex/plugin/components/ulw-loop/directive.md +3 -0
  530. package/packages/omo-codex/plugin/components/ulw-loop/hooks/hooks.json +5 -5
  531. package/packages/omo-codex/plugin/components/ulw-loop/package.json +1 -1
  532. package/packages/omo-codex/plugin/hooks/post-compact-resetting-git-bash-mcp-reminder.json +1 -1
  533. package/packages/omo-codex/plugin/hooks/post-compact-resetting-lsp-diagnostics-cache.json +1 -1
  534. package/packages/omo-codex/plugin/hooks/post-compact-resetting-project-rule-cache.json +1 -1
  535. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-comments.json +1 -1
  536. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-lsp-diagnostics.json +1 -1
  537. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-thread-title-hygiene.json +1 -1
  538. package/packages/omo-codex/plugin/hooks/post-tool-use-matching-project-rules.json +1 -1
  539. package/packages/omo-codex/plugin/hooks/post-tool-use-recording-spawn-admission.json +1 -1
  540. package/packages/omo-codex/plugin/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json +1 -1
  541. package/packages/omo-codex/plugin/hooks/pre-tool-use-guarding-ulw-loop-spawns.json +1 -1
  542. package/packages/omo-codex/plugin/hooks/pre-tool-use-recommending-git-bash-mcp.json +1 -1
  543. package/packages/omo-codex/plugin/hooks/session-start-checking-auto-update.json +1 -1
  544. package/packages/omo-codex/plugin/hooks/session-start-checking-bootstrap-provisioning.json +1 -1
  545. package/packages/omo-codex/plugin/hooks/session-start-loading-project-rules.json +1 -1
  546. package/packages/omo-codex/plugin/hooks/session-start-recording-session-telemetry.json +1 -1
  547. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-execute-continuation.json +1 -1
  548. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-loop-resume.json +1 -1
  549. package/packages/omo-codex/plugin/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json +1 -1
  550. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ultrawork-trigger.json +1 -1
  551. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ulw-loop-steering.json +1 -1
  552. package/packages/omo-codex/plugin/hooks/user-prompt-submit-loading-project-rules.json +1 -1
  553. package/packages/omo-codex/plugin/package-lock.json +16 -16
  554. package/packages/omo-codex/plugin/package.json +1 -1
  555. package/packages/omo-codex/plugin/scripts/auto-update-plan.mjs +16 -1
  556. package/packages/omo-codex/plugin/shared/package.json +1 -1
  557. package/packages/omo-codex/plugin/skills/ast-grep/README.md +1 -1
  558. package/packages/omo-codex/plugin/skills/ast-grep/install.ps1 +5 -3
  559. package/packages/omo-codex/plugin/skills/ast-grep/install.sh +4 -5
  560. package/packages/omo-codex/plugin/skills/ast-grep/references/install.md +2 -2
  561. package/packages/omo-codex/plugin/skills/ast-grep/scripts/ast_grep_helper.py +13 -3
  562. package/packages/omo-codex/plugin/skills/browser/runtime/omowright/index.js +24 -33
  563. package/packages/omo-codex/plugin/skills/browser/runtime/omowright/manifest.json +3 -3
  564. package/packages/omo-codex/plugin/skills/coding-agent-sessions/AGENTS.md +5 -4
  565. package/packages/omo-codex/plugin/skills/coding-agent-sessions/SKILL.md +11 -11
  566. package/packages/omo-codex/plugin/skills/coding-agent-sessions/references/all-platforms.md +2 -2
  567. package/packages/omo-codex/plugin/skills/coding-agent-sessions/references/codex.md +4 -4
  568. package/packages/omo-codex/plugin/skills/coding-agent-sessions/scripts/agent_sessions/cli.py +1 -1
  569. package/packages/omo-codex/plugin/skills/coding-agent-sessions/scripts/find-agent-sessions.py +6 -3
  570. package/packages/omo-codex/plugin/skills/frontend/ATTRIBUTION.md +105 -2
  571. package/packages/omo-codex/plugin/skills/frontend/SKILL.md +40 -14
  572. package/packages/omo-codex/plugin/skills/frontend/references/design/README.md +2 -2
  573. package/packages/omo-codex/plugin/skills/frontend/references/design/_INDEX.md +2 -1
  574. package/packages/omo-codex/plugin/skills/frontend/references/design/component-catalogs.md +14 -10
  575. package/packages/omo-codex/plugin/skills/frontend/references/design/design-system-architecture.md +22 -9
  576. package/packages/omo-codex/plugin/skills/frontend/references/design/grounding.md +29 -0
  577. package/packages/omo-codex/plugin/skills/frontend/references/perfection/craft-floor.md +59 -0
  578. package/packages/omo-codex/plugin/skills/frontend/references/perfection/detect.md +52 -0
  579. package/packages/omo-codex/plugin/skills/frontend/references/ui-ux-db/scripts/design_system.py +2 -0
  580. package/packages/omo-codex/plugin/skills/frontend/references/ui-ux-db/scripts/search.py +2 -0
  581. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/cli.ts +70 -0
  582. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/config.ts +53 -0
  583. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/core/characters.ts +2 -0
  584. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/core/color.ts +150 -0
  585. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/core/page.ts +84 -0
  586. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/core/shadow.ts +40 -0
  587. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/core/source.ts +33 -0
  588. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/detect.ts +77 -0
  589. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/index.ts +23 -0
  590. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/lint.ts +98 -0
  591. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/render/probe-placement.ts +50 -0
  592. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/render/renderer.ts +37 -0
  593. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/render/webview.ts +71 -0
  594. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/report.ts +29 -0
  595. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rule.ts +42 -0
  596. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/ai-color-palette.ts +83 -0
  597. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/cream-palette.ts +35 -0
  598. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/dark-glow.ts +44 -0
  599. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/design-system-color.ts +35 -0
  600. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/gradient-text.ts +59 -0
  601. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/gray-on-color.ts +38 -0
  602. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/index.ts +15 -0
  603. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/low-contrast.ts +57 -0
  604. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/radial-halo.ts +31 -0
  605. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/radial-spotlight-glow.ts +33 -0
  606. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/animation-opacity.ts +78 -0
  607. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/color-path.ts +15 -0
  608. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/contrast-pairs.ts +54 -0
  609. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/contrast-role.ts +76 -0
  610. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/glow-forms.ts +56 -0
  611. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/gradient-samples.ts +134 -0
  612. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/gradients.ts +91 -0
  613. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/mockup-roots.ts +63 -0
  614. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/page-ignore.ts +7 -0
  615. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/painted-text.ts +141 -0
  616. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/palette-roles.ts +58 -0
  617. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/placeholder-contrast.ts +25 -0
  618. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/stock-accent.ts +31 -0
  619. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/color/support/text-colors.ts +80 -0
  620. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/copy/aphoristic-cadence.ts +20 -0
  621. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/copy/broken-image.ts +17 -0
  622. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/copy/em-dash-overuse.ts +46 -0
  623. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/copy/index.ts +15 -0
  624. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/copy/marketing-buzzword.ts +33 -0
  625. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/copy/numbered-section-labels.ts +34 -0
  626. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/copy/repeated-container-text.ts +56 -0
  627. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/copy/script-error.ts +38 -0
  628. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/copy/skipped-heading.ts +81 -0
  629. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/copy/support/numbered-label.ts +94 -0
  630. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/copy/support/page-text.ts +37 -0
  631. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/copy/theater-slop-phrase.ts +21 -0
  632. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/blinking-cursor.ts +48 -0
  633. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/border-accent-on-rounded.ts +14 -0
  634. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/bounce-easing.ts +83 -0
  635. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/buried-raster.ts +72 -0
  636. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/codex-grid-background.ts +34 -0
  637. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/design-system-radius.ts +31 -0
  638. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/gpt-thin-border-wide-shadow.ts +66 -0
  639. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/hard-offset-shadow.ts +31 -0
  640. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/hero-eyebrow-chip.ts +19 -0
  641. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/icon-tile-stack.ts +92 -0
  642. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/index.ts +38 -0
  643. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/kicker-above-heading.ts +69 -0
  644. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/marquee.ts +51 -0
  645. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/organic-clip-path.ts +41 -0
  646. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/pulsing-dot.ts +72 -0
  647. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/repeating-stripes-gradient.ts +25 -0
  648. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/shape-assembled-illustration.ts +58 -0
  649. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/side-tab.ts +17 -0
  650. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/support/appearance.ts +110 -0
  651. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/support/assert-cases.ts +25 -0
  652. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/support/borders.ts +150 -0
  653. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/support/clip-geometry.ts +151 -0
  654. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/support/css-candidates.ts +66 -0
  655. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/support/curve-samples.ts +55 -0
  656. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/support/gradient-pattern.ts +40 -0
  657. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/support/keyframes.ts +134 -0
  658. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/support/labels.ts +85 -0
  659. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/decoration/support/raster-state.ts +51 -0
  660. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/index.ts +16 -0
  661. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/body-text-viewport-edge.ts +62 -0
  662. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/clipped-overflow-container.ts +15 -0
  663. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/content-hidden-at-rest.ts +63 -0
  664. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/cramped-padding.ts +97 -0
  665. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/edge-flush-cards.ts +47 -0
  666. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/first-viewport-column-overflow.ts +43 -0
  667. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/heading-rhythm.ts +30 -0
  668. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/index.ts +21 -0
  669. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/monotonous-spacing.ts +32 -0
  670. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/nested-cards.ts +38 -0
  671. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/straggler.ts +28 -0
  672. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/support/cards.ts +114 -0
  673. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/support/clipping.ts +71 -0
  674. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/support/declared-mockups.ts +46 -0
  675. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/support/geometry.ts +73 -0
  676. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/support/hidden-interface.ts +35 -0
  677. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/support/layout-cases.ts +23 -0
  678. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/support/line-breaks.ts +32 -0
  679. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/support/motion.ts +77 -0
  680. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/support/padding.ts +93 -0
  681. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/support/rhythm.ts +161 -0
  682. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/text-occlusion.ts +84 -0
  683. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/text-overflow.ts +72 -0
  684. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/unbalanced-heading.ts +22 -0
  685. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/layout/viewport-reflow.ts +33 -0
  686. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/ai-color-palette.ts +11 -0
  687. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/aphoristic-cadence.ts +14 -0
  688. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/border-accent-on-rounded.ts +20 -0
  689. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/bounce-easing.ts +21 -0
  690. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/broken-image.ts +16 -0
  691. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/codex-grid-background.ts +18 -0
  692. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/dark-glow.ts +21 -0
  693. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/em-dash-overuse.ts +15 -0
  694. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/gradient-text.ts +11 -0
  695. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/gray-on-color.ts +13 -0
  696. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/index.ts +19 -0
  697. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/marketing-buzzword.ts +17 -0
  698. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/marquee.ts +12 -0
  699. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/monotonous-spacing.ts +22 -0
  700. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/overused-font.ts +16 -0
  701. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/radial-halo.ts +14 -0
  702. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/side-tab.ts +58 -0
  703. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/support/accent-scans.ts +78 -0
  704. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/support/check-source.ts +6 -0
  705. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/support/corners.ts +105 -0
  706. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/support/css-effects.ts +81 -0
  707. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/support/css-scopes.ts +131 -0
  708. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/support/image-tags.ts +113 -0
  709. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/support/js-punctuation.ts +34 -0
  710. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/support/markup-scope.ts +44 -0
  711. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/support/source-color.ts +42 -0
  712. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/support/source-shadow.ts +15 -0
  713. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/source/support/source-text.ts +110 -0
  714. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/all-caps-body.ts +15 -0
  715. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/design-system-font-size.ts +23 -0
  716. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/design-system-font.ts +24 -0
  717. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/extreme-negative-tracking.ts +18 -0
  718. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/flat-type-hierarchy.ts +26 -0
  719. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/index.ts +21 -0
  720. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/italic-serif-display.ts +24 -0
  721. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/justified-text.ts +32 -0
  722. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/line-length.ts +28 -0
  723. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/oversized-h1.ts +20 -0
  724. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/overused-font.ts +45 -0
  725. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/support/drawn-enlargement.ts +48 -0
  726. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/support/fading-text.ts +48 -0
  727. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/support/flex-runs.ts +16 -0
  728. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/support/font-family.ts +28 -0
  729. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/support/painted-text.ts +81 -0
  730. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/support/svg-size.ts +57 -0
  731. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/support/text-context.ts +112 -0
  732. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/support/text-lines.ts +43 -0
  733. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/support/type-hierarchy.ts +48 -0
  734. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/tight-leading.ts +47 -0
  735. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/tiny-text.ts +23 -0
  736. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/undersized-ui-text.ts +28 -0
  737. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/rules/typography/wide-tracking.ts +26 -0
  738. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/snapshot/collect.ts +158 -0
  739. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/snapshot/style-props.ts +25 -0
  740. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/testing/build-snapshot.ts +78 -0
  741. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/tsconfig.json +19 -0
  742. package/packages/omo-codex/plugin/skills/frontend/scripts/detect/types.ts +124 -0
  743. package/packages/omo-codex/plugin/skills/lcx-contribute-bug-fix/SKILL.md +51 -55
  744. package/packages/omo-codex/plugin/skills/lcx-contribute-bug-fix/agents/openai.yaml +1 -1
  745. package/packages/omo-codex/plugin/skills/lcx-report-bug/SKILL.md +7 -7
  746. package/packages/omo-codex/plugin/skills/lcx-report-bug/agents/openai.yaml +1 -1
  747. package/packages/omo-codex/plugin/skills/programming/SKILL.md +15 -74
  748. package/packages/omo-codex/plugin/skills/programming/references/go/README.md +1 -1
  749. package/packages/omo-codex/plugin/skills/programming/references/go/bootstrap.md +2 -2
  750. package/packages/omo-codex/plugin/skills/programming/references/python/README.md +4 -4
  751. package/packages/omo-codex/plugin/skills/programming/references/python/one-liners.md +5 -5
  752. package/packages/omo-codex/plugin/skills/programming/references/testing/README.md +82 -0
  753. package/packages/omo-codex/plugin/skills/programming/references/testing/junk-classes.md +56 -0
  754. package/packages/omo-codex/plugin/skills/programming/references/typescript/README.md +1 -2
  755. package/packages/omo-codex/plugin/skills/programming/scripts/go/new-project.ts +197 -0
  756. package/packages/omo-codex/plugin/skills/programming/scripts/python/new-project.ts +231 -0
  757. package/packages/omo-codex/plugin/skills/programming/scripts/python/new-script.ts +134 -0
  758. package/packages/omo-codex/plugin/skills/programming/scripts/rust/new-project.ts +215 -0
  759. package/packages/omo-codex/plugin/skills/programming/scripts/shared/run-tool.ts +19 -0
  760. package/packages/omo-codex/plugin/skills/ultimate-browsing/SKILL.md +5 -4
  761. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/AGENTS.md +2 -2
  762. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/__main__.py +9 -6
  763. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/summary.py +1 -1
  764. package/packages/omo-codex/plugin/skills/ultimate-browsing/references/insane-search/README.md +4 -4
  765. package/packages/omo-codex/plugin/skills/ultimate-browsing/scripts/extract_cookies.py +4 -2
  766. package/packages/omo-codex/plugin/skills/ultrawork/SKILL.md +3 -0
  767. package/packages/omo-codex/plugin/skills/ulw-research/AGENTS.md +8 -4
  768. package/packages/omo-codex/plugin/skills/ulw-research/SKILL.md +7 -316
  769. package/packages/omo-codex/plugin/skills/ulw-research/references/deliverable-phase.md +23 -21
  770. package/packages/omo-codex/plugin/skills/ulw-research/references/fact-ledger-grammar.md +7 -3
  771. package/packages/omo-codex/plugin/skills/ulw-research/references/fact-ledger.md +42 -8
  772. package/packages/omo-codex/plugin/skills/ulw-research/references/fidelity-claim-kinds.md +1 -1
  773. package/packages/omo-codex/plugin/skills/ulw-research/references/markdown-blocks.md +12 -0
  774. package/packages/omo-codex/plugin/skills/ulw-research/references/report-gates.md +12 -5
  775. package/packages/omo-codex/plugin/skills/ulw-research/references/research-collection.md +195 -0
  776. package/packages/omo-codex/plugin/skills/ulw-research/references/research-delivery.md +123 -0
  777. package/packages/omo-codex/plugin/skills/ulw-research/scripts/claim-kinds.mjs +33 -5
  778. package/packages/omo-codex/plugin/skills/ulw-research/scripts/contracts.mjs +13 -4
  779. package/packages/omo-codex/plugin/skills/ulw-research/scripts/conversion-probe.mjs +229 -0
  780. package/packages/omo-codex/plugin/skills/ulw-research/scripts/css-hiding.mjs +158 -0
  781. package/packages/omo-codex/plugin/skills/ulw-research/scripts/css-lite.mjs +4 -2
  782. package/packages/omo-codex/plugin/skills/ulw-research/scripts/entities.mjs +13 -4
  783. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fact-commands-fill.mjs +11 -1
  784. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fact-commands-meaning.mjs +13 -9
  785. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fact-commands-polish.mjs +40 -18
  786. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fact-commands-verify.mjs +25 -8
  787. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fact-commands.mjs +35 -16
  788. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fact-derive.mjs +7 -2
  789. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fact-fill.mjs +6 -4
  790. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fact-ledger-kinds.mjs +6 -7
  791. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fact-locate.mjs +15 -9
  792. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fidelity-claims.mjs +4 -3
  793. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fidelity-csv.mjs +32 -0
  794. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fidelity-lexicon.mjs +1 -1
  795. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fidelity-originals.mjs +161 -0
  796. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fidelity-policy.mjs +4 -4
  797. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fidelity-records.mjs +81 -14
  798. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fidelity-snapshot-readability.mjs +49 -0
  799. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fidelity-sources.mjs +76 -0
  800. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fidelity-trace.mjs +25 -11
  801. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fidelity-value-unit.mjs +202 -0
  802. package/packages/omo-codex/plugin/skills/ulw-research/scripts/fidelity-values.mjs +40 -39
  803. package/packages/omo-codex/plugin/skills/ulw-research/scripts/gates-fidelity.mjs +8 -6
  804. package/packages/omo-codex/plugin/skills/ulw-research/scripts/gates-static.mjs +10 -1
  805. package/packages/omo-codex/plugin/skills/ulw-research/scripts/html-lite.mjs +6 -2
  806. package/packages/omo-codex/plugin/skills/ulw-research/scripts/html-markup.mjs +2 -2
  807. package/packages/omo-codex/plugin/skills/ulw-research/scripts/html-text-map.mjs +140 -0
  808. package/packages/omo-codex/plugin/skills/ulw-research/scripts/markdown-closers.mjs +126 -0
  809. package/packages/omo-codex/plugin/skills/ulw-research/scripts/md-lite.mjs +1 -1
  810. package/packages/omo-codex/plugin/skills/ulw-research/scripts/number-grammar.mjs +33 -0
  811. package/packages/omo-codex/plugin/skills/ulw-research/scripts/numerals.mjs +18 -7
  812. package/packages/omo-codex/plugin/skills/ulw-research/scripts/outcome-start.mjs +66 -0
  813. package/packages/omo-codex/plugin/skills/ulw-research/scripts/outcome.mjs +11 -22
  814. package/packages/omo-codex/plugin/skills/ulw-research/scripts/placeholder.mjs +18 -6
  815. package/packages/omo-codex/plugin/skills/ulw-research/scripts/polish-apply.mjs +3 -2
  816. package/packages/omo-codex/plugin/skills/ulw-research/scripts/raw-decode.mjs +110 -0
  817. package/packages/omo-codex/plugin/skills/ulw-research/scripts/raw-locator.mjs +47 -0
  818. package/packages/omo-codex/plugin/skills/ulw-research/scripts/report-tools-commands.mjs +1 -1
  819. package/packages/omo-codex/plugin/skills/ulw-research/scripts/report-tools.mjs +7 -1
  820. package/packages/omo-codex/plugin/skills/ulw-research/scripts/source-commands.mjs +79 -26
  821. package/packages/omo-codex/plugin/skills/ulw-research/scripts/source-refresh.mjs +82 -0
  822. package/packages/omo-codex/plugin/skills/ulw-research/scripts/source-snapshot.mjs +73 -69
  823. package/packages/omo-codex/plugin/skills/ulw-research/scripts/source-view.mjs +89 -0
  824. package/packages/omo-codex/plugin/skills/ulw-research/scripts/sources-citation.mjs +203 -0
  825. package/packages/omo-codex/plugin/skills/ulw-research/scripts/units.mjs +14 -3
  826. package/packages/omo-codex/plugin/skills/visual-qa/SKILL.md +12 -1
  827. package/packages/omo-codex/plugin/test/auto-update.test.mjs +62 -0
  828. package/packages/omo-codex/plugin/test/payload-equivalence.test.mjs +18 -6
  829. package/packages/omo-codex/plugin/test/sync-skills.test.mjs +4 -3
  830. package/packages/omo-codex/scripts/install-dist/install-local.mjs +413 -245
  831. package/packages/prompts-core/prompts/ultrawork/codex.md +3 -0
  832. package/packages/shared-skills/skill-source-filter.mjs +6 -2
  833. package/packages/shared-skills/skills/ast-grep/README.md +1 -1
  834. package/packages/shared-skills/skills/ast-grep/install.ps1 +5 -3
  835. package/packages/shared-skills/skills/ast-grep/install.sh +4 -5
  836. package/packages/shared-skills/skills/ast-grep/references/install.md +2 -2
  837. package/packages/shared-skills/skills/ast-grep/scripts/ast_grep_helper.py +13 -3
  838. package/packages/shared-skills/skills/browser/runtime/omowright/index.js +24 -33
  839. package/packages/shared-skills/skills/browser/runtime/omowright/manifest.json +3 -3
  840. package/packages/shared-skills/skills/coding-agent-sessions/AGENTS.md +5 -4
  841. package/packages/shared-skills/skills/coding-agent-sessions/SKILL.md +11 -11
  842. package/packages/shared-skills/skills/coding-agent-sessions/references/all-platforms.md +2 -2
  843. package/packages/shared-skills/skills/coding-agent-sessions/references/codex.md +4 -4
  844. package/packages/shared-skills/skills/coding-agent-sessions/scripts/agent_sessions/cli.py +1 -1
  845. package/packages/shared-skills/skills/coding-agent-sessions/scripts/find-agent-sessions.py +6 -3
  846. package/packages/shared-skills/skills/frontend/ATTRIBUTION.md +105 -2
  847. package/packages/shared-skills/skills/frontend/SKILL.md +40 -14
  848. package/packages/shared-skills/skills/frontend/references/design/README.md +2 -2
  849. package/packages/shared-skills/skills/frontend/references/design/_INDEX.md +2 -1
  850. package/packages/shared-skills/skills/frontend/references/design/component-catalogs.md +14 -10
  851. package/packages/shared-skills/skills/frontend/references/design/design-system-architecture.md +22 -9
  852. package/packages/shared-skills/skills/frontend/references/design/grounding.md +29 -0
  853. package/packages/shared-skills/skills/frontend/references/perfection/craft-floor.md +59 -0
  854. package/packages/shared-skills/skills/frontend/references/perfection/detect.md +52 -0
  855. package/packages/shared-skills/skills/frontend/references/ui-ux-db/scripts/design_system.py +2 -0
  856. package/packages/shared-skills/skills/frontend/references/ui-ux-db/scripts/search.py +2 -0
  857. package/packages/shared-skills/skills/frontend/scripts/detect/cli.ts +70 -0
  858. package/packages/shared-skills/skills/frontend/scripts/detect/config.test.ts +26 -0
  859. package/packages/shared-skills/skills/frontend/scripts/detect/config.ts +53 -0
  860. package/packages/shared-skills/skills/frontend/scripts/detect/core/characters.ts +2 -0
  861. package/packages/shared-skills/skills/frontend/scripts/detect/core/color.test.ts +29 -0
  862. package/packages/shared-skills/skills/frontend/scripts/detect/core/color.ts +150 -0
  863. package/packages/shared-skills/skills/frontend/scripts/detect/core/page.ts +84 -0
  864. package/packages/shared-skills/skills/frontend/scripts/detect/core/shadow.ts +40 -0
  865. package/packages/shared-skills/skills/frontend/scripts/detect/core/source.ts +33 -0
  866. package/packages/shared-skills/skills/frontend/scripts/detect/detect.ts +77 -0
  867. package/packages/shared-skills/skills/frontend/scripts/detect/index.ts +23 -0
  868. package/packages/shared-skills/skills/frontend/scripts/detect/lint.test.ts +27 -0
  869. package/packages/shared-skills/skills/frontend/scripts/detect/lint.ts +98 -0
  870. package/packages/shared-skills/skills/frontend/scripts/detect/render/probe-placement.test.ts +19 -0
  871. package/packages/shared-skills/skills/frontend/scripts/detect/render/probe-placement.ts +50 -0
  872. package/packages/shared-skills/skills/frontend/scripts/detect/render/renderer.ts +37 -0
  873. package/packages/shared-skills/skills/frontend/scripts/detect/render/webview.ts +71 -0
  874. package/packages/shared-skills/skills/frontend/scripts/detect/report.ts +29 -0
  875. package/packages/shared-skills/skills/frontend/scripts/detect/rule.ts +42 -0
  876. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/ai-color-palette.test.ts +74 -0
  877. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/ai-color-palette.ts +83 -0
  878. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/cream-palette.test.ts +24 -0
  879. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/cream-palette.ts +35 -0
  880. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/dark-glow.test.ts +47 -0
  881. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/dark-glow.ts +44 -0
  882. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/design-system-color.test.ts +26 -0
  883. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/design-system-color.ts +35 -0
  884. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/gradient-text.test.ts +24 -0
  885. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/gradient-text.ts +59 -0
  886. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/gray-on-color.test.ts +39 -0
  887. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/gray-on-color.ts +38 -0
  888. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/index.ts +15 -0
  889. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/low-contrast.test.ts +209 -0
  890. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/low-contrast.ts +57 -0
  891. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/placeholder-contrast.test.ts +62 -0
  892. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/radial-halo.test.ts +40 -0
  893. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/radial-halo.ts +31 -0
  894. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/radial-spotlight-glow.test.ts +27 -0
  895. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/radial-spotlight-glow.ts +33 -0
  896. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/animation-opacity.ts +78 -0
  897. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/color-path.ts +15 -0
  898. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/contrast-pairs.ts +54 -0
  899. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/contrast-role.ts +76 -0
  900. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/glow-forms.ts +56 -0
  901. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/gradient-samples.ts +134 -0
  902. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/gradients.ts +91 -0
  903. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/mockup-roots.ts +63 -0
  904. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/page-ignore.ts +7 -0
  905. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/painted-text.ts +141 -0
  906. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/palette-roles.ts +58 -0
  907. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/placeholder-contrast.ts +25 -0
  908. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/stock-accent.ts +31 -0
  909. package/packages/shared-skills/skills/frontend/scripts/detect/rules/color/support/text-colors.ts +80 -0
  910. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/aphoristic-cadence.test.ts +18 -0
  911. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/aphoristic-cadence.ts +20 -0
  912. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/broken-image.test.ts +25 -0
  913. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/broken-image.ts +17 -0
  914. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/em-dash-overuse.test.ts +39 -0
  915. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/em-dash-overuse.ts +46 -0
  916. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/index.ts +15 -0
  917. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/marketing-buzzword.test.ts +18 -0
  918. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/marketing-buzzword.ts +33 -0
  919. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/numbered-section-labels.test.ts +58 -0
  920. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/numbered-section-labels.ts +34 -0
  921. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/repeated-container-text.test.ts +43 -0
  922. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/repeated-container-text.ts +56 -0
  923. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/script-error.test.ts +48 -0
  924. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/script-error.ts +38 -0
  925. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/skipped-heading.test.ts +49 -0
  926. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/skipped-heading.ts +81 -0
  927. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/support/numbered-label.ts +94 -0
  928. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/support/page-text.ts +37 -0
  929. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/theater-slop-phrase.test.ts +17 -0
  930. package/packages/shared-skills/skills/frontend/scripts/detect/rules/copy/theater-slop-phrase.ts +21 -0
  931. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/blinking-cursor.test.ts +43 -0
  932. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/blinking-cursor.ts +48 -0
  933. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/border-accent-on-rounded.test.ts +33 -0
  934. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/border-accent-on-rounded.ts +14 -0
  935. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/bounce-easing.test.ts +72 -0
  936. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/bounce-easing.ts +83 -0
  937. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/buried-raster.test.ts +95 -0
  938. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/buried-raster.ts +72 -0
  939. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/codex-grid-background.test.ts +28 -0
  940. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/codex-grid-background.ts +34 -0
  941. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/design-system-radius.test.ts +37 -0
  942. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/design-system-radius.ts +31 -0
  943. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/gpt-thin-border-wide-shadow.test.ts +59 -0
  944. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/gpt-thin-border-wide-shadow.ts +66 -0
  945. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/hard-offset-shadow.test.ts +45 -0
  946. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/hard-offset-shadow.ts +31 -0
  947. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/hero-eyebrow-chip.test.ts +76 -0
  948. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/hero-eyebrow-chip.ts +19 -0
  949. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/icon-tile-stack.test.ts +67 -0
  950. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/icon-tile-stack.ts +92 -0
  951. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/index.ts +38 -0
  952. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/kicker-above-heading.test.ts +126 -0
  953. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/kicker-above-heading.ts +69 -0
  954. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/marquee.test.ts +63 -0
  955. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/marquee.ts +51 -0
  956. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/organic-clip-path.test.ts +67 -0
  957. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/organic-clip-path.ts +41 -0
  958. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/pulsing-dot.test.ts +58 -0
  959. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/pulsing-dot.ts +72 -0
  960. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/repeating-stripes-gradient.test.ts +26 -0
  961. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/repeating-stripes-gradient.ts +25 -0
  962. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/shape-assembled-illustration.test.ts +59 -0
  963. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/shape-assembled-illustration.ts +58 -0
  964. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/side-tab.test.ts +91 -0
  965. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/side-tab.ts +17 -0
  966. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/support/appearance.ts +110 -0
  967. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/support/assert-cases.ts +25 -0
  968. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/support/borders.ts +150 -0
  969. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/support/clip-geometry.ts +151 -0
  970. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/support/css-candidates.ts +66 -0
  971. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/support/curve-samples.ts +55 -0
  972. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/support/gradient-pattern.ts +40 -0
  973. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/support/keyframes.ts +134 -0
  974. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/support/labels.ts +85 -0
  975. package/packages/shared-skills/skills/frontend/scripts/detect/rules/decoration/support/raster-state.ts +51 -0
  976. package/packages/shared-skills/skills/frontend/scripts/detect/rules/index.ts +16 -0
  977. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/body-text-viewport-edge.test.ts +64 -0
  978. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/body-text-viewport-edge.ts +62 -0
  979. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/clipped-overflow-container.test.ts +40 -0
  980. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/clipped-overflow-container.ts +15 -0
  981. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/content-hidden-at-rest.test.ts +62 -0
  982. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/content-hidden-at-rest.ts +63 -0
  983. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/cramped-padding.test.ts +61 -0
  984. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/cramped-padding.ts +97 -0
  985. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/edge-flush-cards.test.ts +43 -0
  986. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/edge-flush-cards.ts +47 -0
  987. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/first-viewport-column-overflow.test.ts +28 -0
  988. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/first-viewport-column-overflow.ts +43 -0
  989. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/heading-rhythm.test.ts +67 -0
  990. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/heading-rhythm.ts +30 -0
  991. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/index.ts +21 -0
  992. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/monotonous-spacing.test.ts +19 -0
  993. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/monotonous-spacing.ts +32 -0
  994. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/nested-cards.test.ts +60 -0
  995. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/nested-cards.ts +38 -0
  996. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/straggler.test.ts +33 -0
  997. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/straggler.ts +28 -0
  998. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/support/cards.ts +114 -0
  999. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/support/clipping.ts +71 -0
  1000. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/support/declared-mockups.ts +46 -0
  1001. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/support/geometry.ts +73 -0
  1002. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/support/hidden-interface.ts +35 -0
  1003. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/support/layout-cases.ts +23 -0
  1004. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/support/line-breaks.ts +32 -0
  1005. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/support/motion.ts +77 -0
  1006. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/support/padding.ts +93 -0
  1007. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/support/rhythm.ts +161 -0
  1008. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/text-occlusion.test.ts +37 -0
  1009. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/text-occlusion.ts +84 -0
  1010. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/text-overflow.test.ts +83 -0
  1011. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/text-overflow.ts +72 -0
  1012. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/unbalanced-heading.test.ts +22 -0
  1013. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/unbalanced-heading.ts +22 -0
  1014. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/viewport-reflow.test.ts +34 -0
  1015. package/packages/shared-skills/skills/frontend/scripts/detect/rules/layout/viewport-reflow.ts +33 -0
  1016. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/ai-color-palette.test.ts +13 -0
  1017. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/ai-color-palette.ts +11 -0
  1018. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/aphoristic-cadence.test.ts +12 -0
  1019. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/aphoristic-cadence.ts +14 -0
  1020. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/border-accent-on-rounded.test.ts +14 -0
  1021. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/border-accent-on-rounded.ts +20 -0
  1022. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/bounce-easing.test.ts +19 -0
  1023. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/bounce-easing.ts +21 -0
  1024. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/broken-image.test.ts +27 -0
  1025. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/broken-image.ts +16 -0
  1026. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/codex-grid-background.test.ts +11 -0
  1027. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/codex-grid-background.ts +18 -0
  1028. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/dark-glow.test.ts +15 -0
  1029. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/dark-glow.ts +21 -0
  1030. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/em-dash-overuse.test.ts +13 -0
  1031. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/em-dash-overuse.ts +15 -0
  1032. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/gradient-text.test.ts +12 -0
  1033. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/gradient-text.ts +11 -0
  1034. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/gray-on-color.test.ts +20 -0
  1035. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/gray-on-color.ts +13 -0
  1036. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/index.ts +19 -0
  1037. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/marketing-buzzword.test.ts +12 -0
  1038. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/marketing-buzzword.ts +17 -0
  1039. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/marquee.test.ts +12 -0
  1040. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/marquee.ts +12 -0
  1041. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/monotonous-spacing.test.ts +13 -0
  1042. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/monotonous-spacing.ts +22 -0
  1043. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/overused-font.test.ts +21 -0
  1044. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/overused-font.ts +16 -0
  1045. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/radial-halo.test.ts +16 -0
  1046. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/radial-halo.ts +14 -0
  1047. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/side-tab.test.ts +29 -0
  1048. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/side-tab.ts +58 -0
  1049. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/support/accent-scans.ts +78 -0
  1050. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/support/check-source.ts +6 -0
  1051. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/support/corners.ts +105 -0
  1052. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/support/css-effects.ts +81 -0
  1053. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/support/css-scopes.ts +131 -0
  1054. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/support/image-tags.ts +113 -0
  1055. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/support/js-punctuation.ts +34 -0
  1056. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/support/markup-scope.ts +44 -0
  1057. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/support/source-color.ts +42 -0
  1058. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/support/source-shadow.ts +15 -0
  1059. package/packages/shared-skills/skills/frontend/scripts/detect/rules/source/support/source-text.ts +110 -0
  1060. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/all-caps-body.test.ts +24 -0
  1061. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/all-caps-body.ts +15 -0
  1062. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/design-system-font-size.test.ts +21 -0
  1063. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/design-system-font-size.ts +23 -0
  1064. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/design-system-font.test.ts +22 -0
  1065. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/design-system-font.ts +24 -0
  1066. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/extreme-negative-tracking.test.ts +23 -0
  1067. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/extreme-negative-tracking.ts +18 -0
  1068. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/flat-type-hierarchy.test.ts +33 -0
  1069. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/flat-type-hierarchy.ts +26 -0
  1070. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/index.ts +21 -0
  1071. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/italic-serif-display.test.ts +24 -0
  1072. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/italic-serif-display.ts +24 -0
  1073. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/justified-text.test.ts +31 -0
  1074. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/justified-text.ts +32 -0
  1075. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/line-length.test.ts +43 -0
  1076. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/line-length.ts +28 -0
  1077. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/oversized-h1.test.ts +26 -0
  1078. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/oversized-h1.ts +20 -0
  1079. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/overused-font.test.ts +35 -0
  1080. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/overused-font.ts +45 -0
  1081. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/support/drawn-enlargement.ts +48 -0
  1082. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/support/fading-text.ts +48 -0
  1083. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/support/flex-runs.ts +16 -0
  1084. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/support/font-family.ts +28 -0
  1085. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/support/painted-text.test.ts +63 -0
  1086. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/support/painted-text.ts +81 -0
  1087. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/support/svg-size.ts +57 -0
  1088. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/support/text-context.ts +112 -0
  1089. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/support/text-lines.ts +43 -0
  1090. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/support/type-hierarchy.ts +48 -0
  1091. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/tight-leading.test.ts +54 -0
  1092. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/tight-leading.ts +47 -0
  1093. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/tiny-text.test.ts +60 -0
  1094. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/tiny-text.ts +23 -0
  1095. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/undersized-ui-text.test.ts +98 -0
  1096. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/undersized-ui-text.ts +28 -0
  1097. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/wide-tracking.test.ts +26 -0
  1098. package/packages/shared-skills/skills/frontend/scripts/detect/rules/typography/wide-tracking.ts +26 -0
  1099. package/packages/shared-skills/skills/frontend/scripts/detect/snapshot/collect.ts +158 -0
  1100. package/packages/shared-skills/skills/frontend/scripts/detect/snapshot/style-props.ts +25 -0
  1101. package/packages/shared-skills/skills/frontend/scripts/detect/testing/build-snapshot.ts +78 -0
  1102. package/packages/shared-skills/skills/frontend/scripts/detect/tsconfig.json +19 -0
  1103. package/packages/shared-skills/skills/frontend/scripts/detect/types.ts +124 -0
  1104. package/packages/shared-skills/skills/programming/SKILL.md +15 -74
  1105. package/packages/shared-skills/skills/programming/references/go/README.md +1 -1
  1106. package/packages/shared-skills/skills/programming/references/go/bootstrap.md +2 -2
  1107. package/packages/shared-skills/skills/programming/references/python/README.md +4 -4
  1108. package/packages/shared-skills/skills/programming/references/python/one-liners.md +5 -5
  1109. package/packages/shared-skills/skills/programming/references/testing/README.md +82 -0
  1110. package/packages/shared-skills/skills/programming/references/testing/junk-classes.md +56 -0
  1111. package/packages/shared-skills/skills/programming/references/typescript/README.md +1 -2
  1112. package/packages/shared-skills/skills/programming/scripts/go/new-project.ts +197 -0
  1113. package/packages/shared-skills/skills/programming/scripts/python/new-project.ts +231 -0
  1114. package/packages/shared-skills/skills/programming/scripts/python/new-script.ts +134 -0
  1115. package/packages/shared-skills/skills/programming/scripts/rust/new-project.ts +215 -0
  1116. package/packages/shared-skills/skills/programming/scripts/scaffolders.test.ts +96 -0
  1117. package/packages/shared-skills/skills/programming/scripts/shared/run-tool.ts +19 -0
  1118. package/packages/shared-skills/skills/ultimate-browsing/SKILL.md +5 -4
  1119. package/packages/shared-skills/skills/ultimate-browsing/engine/AGENTS.md +2 -2
  1120. package/packages/shared-skills/skills/ultimate-browsing/engine/__main__.py +9 -6
  1121. package/packages/shared-skills/skills/ultimate-browsing/engine/summary.py +1 -1
  1122. package/packages/shared-skills/skills/ultimate-browsing/references/insane-search/README.md +4 -4
  1123. package/packages/shared-skills/skills/ultimate-browsing/scripts/extract_cookies.py +4 -2
  1124. package/packages/shared-skills/skills/ulw-research/AGENTS.md +8 -4
  1125. package/packages/shared-skills/skills/ulw-research/SKILL.md +7 -316
  1126. package/packages/shared-skills/skills/ulw-research/references/deliverable-phase.md +23 -21
  1127. package/packages/shared-skills/skills/ulw-research/references/fact-ledger-grammar.md +7 -3
  1128. package/packages/shared-skills/skills/ulw-research/references/fact-ledger.md +42 -8
  1129. package/packages/shared-skills/skills/ulw-research/references/fidelity-claim-kinds.md +1 -1
  1130. package/packages/shared-skills/skills/ulw-research/references/markdown-blocks.md +12 -0
  1131. package/packages/shared-skills/skills/ulw-research/references/report-gates.md +12 -5
  1132. package/packages/shared-skills/skills/ulw-research/references/research-collection.md +195 -0
  1133. package/packages/shared-skills/skills/ulw-research/references/research-delivery.md +123 -0
  1134. package/packages/shared-skills/skills/ulw-research/scripts/claim-kinds.mjs +33 -5
  1135. package/packages/shared-skills/skills/ulw-research/scripts/claim-kinds.test.ts +37 -2
  1136. package/packages/shared-skills/skills/ulw-research/scripts/claim-prefix.test.ts +76 -0
  1137. package/packages/shared-skills/skills/ulw-research/scripts/contracts-validation.test.ts +83 -0
  1138. package/packages/shared-skills/skills/ulw-research/scripts/contracts.mjs +13 -4
  1139. package/packages/shared-skills/skills/ulw-research/scripts/contracts.test.ts +6 -110
  1140. package/packages/shared-skills/skills/ulw-research/scripts/conversion-altered.test.ts +154 -0
  1141. package/packages/shared-skills/skills/ulw-research/scripts/conversion-originals.test.ts +297 -0
  1142. package/packages/shared-skills/skills/ulw-research/scripts/conversion-probe-classes.test.ts +361 -0
  1143. package/packages/shared-skills/skills/ulw-research/scripts/conversion-probe.mjs +229 -0
  1144. package/packages/shared-skills/skills/ulw-research/scripts/conversion-probe.test.ts +218 -0
  1145. package/packages/shared-skills/skills/ulw-research/scripts/copy-returns-polish.test.ts +4 -3
  1146. package/packages/shared-skills/skills/ulw-research/scripts/css-hiding.mjs +158 -0
  1147. package/packages/shared-skills/skills/ulw-research/scripts/css-lite.mjs +4 -2
  1148. package/packages/shared-skills/skills/ulw-research/scripts/delivery-barrier-meaning.test.ts +186 -0
  1149. package/packages/shared-skills/skills/ulw-research/scripts/delivery-barrier.test.ts +40 -87
  1150. package/packages/shared-skills/skills/ulw-research/scripts/entities.mjs +13 -4
  1151. package/packages/shared-skills/skills/ulw-research/scripts/fact-commands-fill.mjs +11 -1
  1152. package/packages/shared-skills/skills/ulw-research/scripts/fact-commands-meaning.mjs +13 -9
  1153. package/packages/shared-skills/skills/ulw-research/scripts/fact-commands-polish.mjs +40 -18
  1154. package/packages/shared-skills/skills/ulw-research/scripts/fact-commands-verify.mjs +25 -8
  1155. package/packages/shared-skills/skills/ulw-research/scripts/fact-commands.mjs +35 -16
  1156. package/packages/shared-skills/skills/ulw-research/scripts/fact-derive-2.test.ts +149 -0
  1157. package/packages/shared-skills/skills/ulw-research/scripts/fact-derive.mjs +7 -2
  1158. package/packages/shared-skills/skills/ulw-research/scripts/fact-derive.test.ts +7 -192
  1159. package/packages/shared-skills/skills/ulw-research/scripts/fact-fill.mjs +6 -4
  1160. package/packages/shared-skills/skills/ulw-research/scripts/fact-ledger-kinds.mjs +6 -7
  1161. package/packages/shared-skills/skills/ulw-research/scripts/fact-ledger-kinds.test.ts +2 -1
  1162. package/packages/shared-skills/skills/ulw-research/scripts/fact-ledger-legacy.test.ts +2 -1
  1163. package/packages/shared-skills/skills/ulw-research/scripts/fact-locate.mjs +15 -9
  1164. package/packages/shared-skills/skills/ulw-research/scripts/fact-unit-dimensions-2.test.ts +149 -0
  1165. package/packages/shared-skills/skills/ulw-research/scripts/fact-unit-dimensions.test.ts +4 -168
  1166. package/packages/shared-skills/skills/ulw-research/scripts/fact-unit-rules.test.ts +3 -229
  1167. package/packages/shared-skills/skills/ulw-research/scripts/fidelity-claims.mjs +4 -3
  1168. package/packages/shared-skills/skills/ulw-research/scripts/fidelity-csv.mjs +32 -0
  1169. package/packages/shared-skills/skills/ulw-research/scripts/fidelity-lexicon.mjs +1 -1
  1170. package/packages/shared-skills/skills/ulw-research/scripts/fidelity-originals.mjs +161 -0
  1171. package/packages/shared-skills/skills/ulw-research/scripts/fidelity-policy.mjs +4 -4
  1172. package/packages/shared-skills/skills/ulw-research/scripts/fidelity-records.mjs +81 -14
  1173. package/packages/shared-skills/skills/ulw-research/scripts/fidelity-snapshot-readability.mjs +49 -0
  1174. package/packages/shared-skills/skills/ulw-research/scripts/fidelity-sources.mjs +76 -0
  1175. package/packages/shared-skills/skills/ulw-research/scripts/fidelity-trace.mjs +25 -11
  1176. package/packages/shared-skills/skills/ulw-research/scripts/fidelity-value-unit.mjs +202 -0
  1177. package/packages/shared-skills/skills/ulw-research/scripts/fidelity-values.mjs +40 -39
  1178. package/packages/shared-skills/skills/ulw-research/scripts/fidelity-values.test.ts +8 -29
  1179. package/packages/shared-skills/skills/ulw-research/scripts/gates-fidelity.mjs +8 -6
  1180. package/packages/shared-skills/skills/ulw-research/scripts/gates-static-headings.test.ts +17 -0
  1181. package/packages/shared-skills/skills/ulw-research/scripts/gates-static.mjs +10 -1
  1182. package/packages/shared-skills/skills/ulw-research/scripts/html-lite.mjs +6 -2
  1183. package/packages/shared-skills/skills/ulw-research/scripts/html-markup.mjs +2 -2
  1184. package/packages/shared-skills/skills/ulw-research/scripts/html-text-map.mjs +140 -0
  1185. package/packages/shared-skills/skills/ulw-research/scripts/html-text-map.test.ts +148 -0
  1186. package/packages/shared-skills/skills/ulw-research/scripts/markdown-closers.mjs +126 -0
  1187. package/packages/shared-skills/skills/ulw-research/scripts/md-lite-boundaries.test.ts +46 -0
  1188. package/packages/shared-skills/skills/ulw-research/scripts/md-lite.mjs +1 -1
  1189. package/packages/shared-skills/skills/ulw-research/scripts/number-grammar.mjs +33 -0
  1190. package/packages/shared-skills/skills/ulw-research/scripts/number-grammar.test.ts +36 -0
  1191. package/packages/shared-skills/skills/ulw-research/scripts/numerals.mjs +18 -7
  1192. package/packages/shared-skills/skills/ulw-research/scripts/numerals.test.ts +3 -0
  1193. package/packages/shared-skills/skills/ulw-research/scripts/outcome-start.mjs +66 -0
  1194. package/packages/shared-skills/skills/ulw-research/scripts/outcome-start.test.ts +109 -0
  1195. package/packages/shared-skills/skills/ulw-research/scripts/outcome.mjs +11 -22
  1196. package/packages/shared-skills/skills/ulw-research/scripts/page-source-locator.test.ts +187 -0
  1197. package/packages/shared-skills/skills/ulw-research/scripts/placeholder.mjs +18 -6
  1198. package/packages/shared-skills/skills/ulw-research/scripts/polish-apply.mjs +3 -2
  1199. package/packages/shared-skills/skills/ulw-research/scripts/polish-markup.test.ts +15 -1
  1200. package/packages/shared-skills/skills/ulw-research/scripts/polish-partial.test.ts +42 -0
  1201. package/packages/shared-skills/skills/ulw-research/scripts/raw-decode.mjs +110 -0
  1202. package/packages/shared-skills/skills/ulw-research/scripts/raw-locator.mjs +47 -0
  1203. package/packages/shared-skills/skills/ulw-research/scripts/raw-snapshot.test.ts +139 -0
  1204. package/packages/shared-skills/skills/ulw-research/scripts/report-tools-2.test.ts +233 -0
  1205. package/packages/shared-skills/skills/ulw-research/scripts/report-tools-3.test.ts +141 -0
  1206. package/packages/shared-skills/skills/ulw-research/scripts/report-tools-4.test.ts +135 -0
  1207. package/packages/shared-skills/skills/ulw-research/scripts/report-tools-5.test.ts +231 -0
  1208. package/packages/shared-skills/skills/ulw-research/scripts/report-tools-commands.mjs +1 -1
  1209. package/packages/shared-skills/skills/ulw-research/scripts/report-tools.mjs +7 -1
  1210. package/packages/shared-skills/skills/ulw-research/scripts/report-tools.test.ts +5 -800
  1211. package/packages/shared-skills/skills/ulw-research/scripts/snapshot-readability.test.ts +116 -0
  1212. package/packages/shared-skills/skills/ulw-research/scripts/source-commands.mjs +79 -26
  1213. package/packages/shared-skills/skills/ulw-research/scripts/source-integrity.test.ts +243 -0
  1214. package/packages/shared-skills/skills/ulw-research/scripts/source-refresh.mjs +82 -0
  1215. package/packages/shared-skills/skills/ulw-research/scripts/source-snapshot.mjs +73 -69
  1216. package/packages/shared-skills/skills/ulw-research/scripts/source-snapshot.test.ts +7 -4
  1217. package/packages/shared-skills/skills/ulw-research/scripts/source-view.mjs +89 -0
  1218. package/packages/shared-skills/skills/ulw-research/scripts/sources-citation.mjs +203 -0
  1219. package/packages/shared-skills/skills/ulw-research/scripts/sources-citation.test.ts +236 -0
  1220. package/packages/shared-skills/skills/ulw-research/scripts/tests/contracts-support.ts +147 -0
  1221. package/packages/shared-skills/skills/ulw-research/scripts/tests/delivery-barrier-session.ts +59 -0
  1222. package/packages/shared-skills/skills/ulw-research/scripts/tests/derive-clock.ts +4 -0
  1223. package/packages/shared-skills/skills/ulw-research/scripts/tests/fact-derive-support.ts +65 -0
  1224. package/packages/shared-skills/skills/ulw-research/scripts/tests/fact-unit-dimensions-support.ts +41 -0
  1225. package/packages/shared-skills/skills/ulw-research/scripts/tests/fact-unit-rules-support.ts +241 -0
  1226. package/packages/shared-skills/skills/ulw-research/scripts/tests/fidelity-values-support.ts +30 -0
  1227. package/packages/shared-skills/skills/ulw-research/scripts/tests/fixtures/conversion-probe.html +14 -0
  1228. package/packages/shared-skills/skills/ulw-research/scripts/tests/fixtures/sources-shapes.html +20 -0
  1229. package/packages/shared-skills/skills/ulw-research/scripts/tests/numeral-classes.ts +196 -0
  1230. package/packages/shared-skills/skills/ulw-research/scripts/tests/report-tools-support.ts +182 -0
  1231. package/packages/shared-skills/skills/ulw-research/scripts/tests/value-mode-support.ts +48 -0
  1232. package/packages/shared-skills/skills/ulw-research/scripts/units.mjs +14 -3
  1233. package/packages/shared-skills/skills/ulw-research/scripts/units.test.ts +10 -0
  1234. package/packages/shared-skills/skills/ulw-research/scripts/value-mode-unit-classes.test.ts +255 -0
  1235. package/packages/shared-skills/skills/ulw-research/scripts/value-mode-unit.test.ts +179 -0
  1236. package/packages/shared-skills/skills/ulw-research/scripts/value-rules-cli.test.ts +157 -0
  1237. package/packages/shared-skills/skills/ulw-research/scripts/value-rules-followups.test.ts +72 -0
  1238. package/packages/shared-skills/skills/ulw-research/scripts/value-rules-priority.test.ts +80 -0
  1239. package/packages/shared-skills/skills/visual-qa/SKILL.md +12 -1
  1240. package/dist/agents/gpt-prompt-identity.d.ts +0 -3
  1241. package/dist/agents/hephaestus/gpt-5-4.d.ts +0 -24
  1242. package/dist/agents/hephaestus/gpt-5-5.d.ts +0 -2
  1243. package/dist/agents/hephaestus/gpt-5-6.d.ts +0 -2
  1244. package/dist/agents/kimi-tool-loop-guard.d.ts +0 -1
  1245. package/dist/agents/sisyphus/claude-fable-5.d.ts +0 -19
  1246. package/dist/agents/sisyphus/claude-opus-4-7.d.ts +0 -22
  1247. package/dist/agents/sisyphus/claude-opus-4-8.d.ts +0 -19
  1248. package/dist/agents/sisyphus/claude-opus-5.d.ts +0 -33
  1249. package/dist/agents/sisyphus/gemini.d.ts +0 -20
  1250. package/dist/agents/sisyphus/glm-5-2.d.ts +0 -4
  1251. package/dist/agents/sisyphus/gpt-5-4.d.ts +0 -26
  1252. package/dist/agents/sisyphus/gpt-5-5.d.ts +0 -6
  1253. package/dist/agents/sisyphus/gpt-task-system-guide.d.ts +0 -1
  1254. package/dist/agents/sisyphus/grok-4.d.ts +0 -21
  1255. package/dist/agents/sisyphus/index.d.ts +0 -31
  1256. package/dist/agents/sisyphus/kimi-k2-6.d.ts +0 -32
  1257. package/dist/agents/sisyphus/kimi-k2-7.d.ts +0 -17
  1258. package/dist/agents/sisyphus/kimi-k3-1.d.ts +0 -9
  1259. package/dist/agents/sisyphus/kimi-k3.d.ts +0 -19
  1260. package/dist/agents/sisyphus-dynamic-prompt-builder.d.ts +0 -2
  1261. package/dist/agents/sisyphus-dynamic-prompt-execution.d.ts +0 -2
  1262. package/dist/agents/sisyphus-dynamic-prompt-exploration.d.ts +0 -2
  1263. package/dist/agents/sisyphus-dynamic-prompt-role.d.ts +0 -2
  1264. package/dist/agents/sisyphus-dynamic-prompt-sections.d.ts +0 -18
  1265. package/dist/agents/sisyphus-dynamic-prompt-style.d.ts +0 -2
  1266. package/dist/agents/sisyphus-dynamic-prompt.d.ts +0 -3
  1267. package/dist/agents/sisyphus-gemini-fallback-overrides.d.ts +0 -1
  1268. package/dist/agents/sisyphus-junior/gemini.d.ts +0 -10
  1269. package/dist/agents/sisyphus-junior/glm-5-2.d.ts +0 -1
  1270. package/dist/agents/sisyphus-junior/gpt-5-4.d.ts +0 -11
  1271. package/dist/agents/sisyphus-junior/gpt-5-5.d.ts +0 -5
  1272. package/dist/agents/sisyphus-junior/gpt.d.ts +0 -9
  1273. package/dist/agents/sisyphus-junior/kimi-k2-6.d.ts +0 -13
  1274. package/dist/agents/sisyphus-junior/kimi-k2-7.d.ts +0 -11
  1275. package/dist/agents/sisyphus-junior/kimi-k3-1.d.ts +0 -6
  1276. package/dist/agents/sisyphus-junior/kimi-k3.d.ts +0 -12
  1277. package/dist/features/claude-code-agent-loader/opencode-config-agents-reader.d.ts +0 -1
  1278. package/dist/features/claude-code-command-loader/loader-cache.d.ts +0 -1
  1279. package/dist/features/claude-code-command-loader/loader.d.ts +0 -1
  1280. package/dist/features/opencode-skill-loader/config-source-discovery.d.ts +0 -1
  1281. package/dist/features/opencode-skill-loader/merger/config-skill-entry-loader.d.ts +0 -1
  1282. package/dist/features/opencode-skill-loader/opencode-config-skills-reader.d.ts +0 -1
  1283. package/dist/features/team-mode/team-layout-tmux/resolve-caller-tmux-session.d.ts +0 -1
  1284. package/dist/features/team-mode/team-registry/team-spec-input-normalizer.d.ts +0 -1
  1285. package/dist/shared/git-worktree/collect-git-diff-stats.d.ts +0 -1
  1286. package/dist/shared/git-worktree/parse-status-porcelain-line.d.ts +0 -1
  1287. package/dist/shared/migration/agent-names.d.ts +0 -1
  1288. package/dist/shared/migration/migrations-sidecar.d.ts +0 -1
  1289. package/dist/shared/skill-path-resolver.d.ts +0 -1
  1290. package/dist/shared/zip-entry-listing/powershell-zip-entry-listing.d.ts +0 -1
  1291. package/dist/shared/zip-entry-listing/zipinfo-zip-entry-listing.d.ts +0 -1
  1292. package/dist/skills/programming/scripts/go/new-project.py +0 -138
  1293. package/dist/skills/programming/scripts/python/new-project.py +0 -172
  1294. package/dist/skills/programming/scripts/python/new-script.py +0 -116
  1295. package/dist/skills/programming/scripts/rust/new-project.py +0 -178
  1296. package/packages/omo-codex/plugin/skills/programming/scripts/go/new-project.py +0 -138
  1297. package/packages/omo-codex/plugin/skills/programming/scripts/python/new-project.py +0 -172
  1298. package/packages/omo-codex/plugin/skills/programming/scripts/python/new-script.py +0 -116
  1299. package/packages/omo-codex/plugin/skills/programming/scripts/rust/new-project.py +0 -178
  1300. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/tests/fixtures/amp_redirect_stub.html +0 -7
  1301. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/tests/fixtures/search_interstitial.html +0 -19
  1302. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/tests/fixtures/wayback_available.json +0 -1
  1303. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/tests/fixtures/wayback_snapshot.html +0 -1128
  1304. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/tests/test_fetch_chain.py +0 -77
  1305. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/tests/test_playwright_stealth.py +0 -86
  1306. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/tests/test_playwright_templates.py +0 -279
  1307. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/tests/test_surrogate.py +0 -252
  1308. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/tests/test_surrogate_validators.py +0 -78
  1309. package/packages/shared-skills/skills/programming/scripts/go/new-project.py +0 -138
  1310. package/packages/shared-skills/skills/programming/scripts/python/new-project.py +0 -172
  1311. package/packages/shared-skills/skills/programming/scripts/python/new-script.py +0 -116
  1312. package/packages/shared-skills/skills/programming/scripts/rust/new-project.py +0 -178
@@ -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 generateArrayCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);const outputVar=buildsValue?newVar(ctx):null;const iVar=newVar(ctx);const elemVar=newVar(ctx);if(outputVar)doc.write(`const ${outputVar} = new Array(${accessor}.length);`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);const elemOutput=compileChild(d,ctx,def.element,elemVar,buildsValue);if(outputVar&&elemOutput!==null)d.write(`${outputVar}[${iVar}] = ${elemOutput};`)});doc.write(`}`);return outputVar}function generateLiteralCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const values=def.values;if(values.length!==1){const literalSet=addConstant(ctx,new Set(values));doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);return accessor}const value=values[0];if(typeof value==="number"&&Number.isNaN(value)){const literalSet=addConstant(ctx,new Set(values));doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);return accessor}if(typeof value==="string"){doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`)}else if(typeof value==="number"||typeof value==="boolean"){doc.write(`if (${accessor} !== ${value}) return INVALID;`)}else if(value===null){doc.write(`if (${accessor} !== null) return INVALID;`)}else if(value===undefined){doc.write(`if (${accessor} !== undefined) return INVALID;`)}else if(typeof value==="bigint"){doc.write(`if (${accessor} !== ${value}n) return INVALID;`)}else{throw new ZodCompileUnsupportedError(`literal type ${typeof value}`)}return accessor}function generateEnumCheck(doc,ctx,schema,accessor){const values=schema._zod.values;if(!values){throw new ZodCompileUnsupportedError("enum schema without enumerated values")}const enumSet=addConstant(ctx,values);doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`);return accessor}function generateWrapperCheck(doc,ctx,schema,accessor){const def=schema._zod.def;return generateCheck(doc,ctx,def.innerType,accessor)}function generateDefaultCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const descriptor=Object.getOwnPropertyDescriptor(schema._zod.def,"defaultValue");const defaultGetter=descriptor?()=>schema._zod.def.defaultValue:undefined;if(schema._zod.def.type==="prefault"){if(!defaultGetter){return generateCheck(doc,ctx,def.innerType,accessor)}const defaultFn=addConstant(ctx,defaultGetter);const inputVar=newVar(ctx);doc.write(`let ${inputVar} = ${accessor};`);doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`);return generateCheck(doc,ctx,def.innerType,inputVar)}const outputVar=newVar(ctx);if(defaultGetter){const defaultFn=addConstant(ctx,defaultGetter);const cloneFn=addConstant(ctx,shallowClone);doc.write(`let ${outputVar};`);doc.write(`if (${accessor} === undefined) {`);doc.indented((d)=>{d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`)});doc.write(`} else {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`)});doc.write(`}`)}else{doc.write(`let ${outputVar};`);doc.write(`if (${accessor} !== undefined) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`)}return outputVar}function generateNonOptionalCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const innerOutput=generateCheck(doc,ctx,def.innerType,accessor);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${innerOutput};`);doc.write(`if (${outputVar} === undefined) return INVALID;`);return outputVar}function generateTupleCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const items=def.items;const rest=def.rest;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);const optinStart=getTupleOptStart2(items,"optin");const optoutStart=getTupleOptStart2(items,"optout");if(rest){doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`)}else{doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`)}const outputVar=newVar(ctx);doc.write(`const ${outputVar} = [];`);for(let i=0;i<items.length;i++){const itemSchema=items[i];if(i>=optoutStart){doc.write(`if (${outputVar}.length === ${i}) {`);doc.indented((d)=>{d.write(`if (${i} < ${accessor}.length) {`);d.indented((d2)=>{const elemVar=newVar(ctx);d2.write(`const ${elemVar} = ${accessor}[${i}];`);const elemOutput=compileChild(d2,ctx,itemSchema,elemVar);d2.write(`${outputVar}[${i}] = ${elemOutput};`)});d.write(`} else {`);d.indented((d2)=>{if(dropsWhenAbsent(itemSchema)){d2.write(`${outputVar}.length = ${i};`);return}const elemVar=newVar(ctx);const branchVar=newVar(ctx);d2.write(`const ${elemVar} = undefined;`);d2.write(`const ${branchVar} = (() => {`);d2.indented((d3)=>{const elemOutput=compileChild(d3,ctx,itemSchema,elemVar);d3.write(`return ${elemOutput};`)});d2.write(`})();`);d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`);d2.write(`else ${outputVar}[${i}] = ${branchVar};`)});d.write(`}`)});doc.write(`}`)}else{const elemVar=newVar(ctx);doc.write(`const ${elemVar} = ${accessor}[${i}];`);const elemOutput=compileChild(doc,ctx,itemSchema,elemVar);doc.write(`${outputVar}[${i}] = ${elemOutput};`)}}if(rest){const iVar=newVar(ctx);const elemVar=newVar(ctx);doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);const elemOutput=compileChild(d,ctx,rest,elemVar);d.write(`${outputVar}[${iVar}] = ${elemOutput};`)});doc.write(`}`)}return outputVar}function getTupleOptStart2(items,key){for(let i=items.length-1;i>=0;i--){const omittable=key==="optin"?items[i]._zod.optin!==undefined:items[i]._zod.optout==="optional";if(!omittable)return i+1}return 0}function generateUnionCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const options=def.options;if(def.discriminator){return generateDiscriminatedUnionCheck(doc,ctx,def,accessor)}if(def.inclusive===false){throw new ZodCompileUnsupportedError("exclusive unions (z.xor)")}if(options.length===0){doc.write("return INVALID;");return accessor}if(options.length===1){return generateCheck(doc,ctx,options[0],accessor)}const allLiterals=options.every((opt)=>opt._zod.def.type==="literal"&&!opt._zod.def.checks?.length);if(allLiterals){const values=new Set(options.flatMap((opt)=>opt._zod.def.values));const valuesConst=addConstant(ctx,values);doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`);return accessor}const outputVar=newVar(ctx);doc.write(`let ${outputVar};`);for(let i=0;i<options.length;i++){const opt=options[i];if(i===0){doc.write(`${outputVar} = (() => {`)}else{doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`)}doc.indented((d)=>{const branchOutput=generateCheck(d,ctx,opt,accessor);d.write(`return ${branchOutput};`)});doc.write(`})();`)}doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}function generateDiscriminatedUnionCheck(doc,ctx,def,accessor){if(def.unionFallback){throw new ZodCompileUnsupportedError("discriminated union with unionFallback")}if(def.options.length===0){doc.write("return INVALID;");return accessor}const discVar=newVar(ctx);const outputVar=newVar(ctx);doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`);doc.write(`let ${outputVar};`);let firstBranch=true;const claimed=new Set;for(const option of def.options){const values=option._zod.propValues?.[def.discriminator];if(!values||values.size===0){throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values")}for(const value of values){if(claimed.has(value)){throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`)}claimed.add(value)}const conditions=Array.from(values,(value)=>literalEquality(ctx,discVar,value));const prefix=firstBranch?"if":"else if";doc.write(`${prefix} (${conditions.join(" || ")}) {`);doc.indented((d)=>{const branchOutput=generateCheck(d,ctx,option,accessor);d.write(`${outputVar} = ${branchOutput};`)});doc.write(`}`);firstBranch=false}doc.write(`else { return INVALID; }`);return outputVar}function literalEquality(ctx,accessor,value){if(typeof value==="string")return`${accessor} === ${esc(value)}`;if(typeof value==="number"){if(Number.isNaN(value))return`Number.isNaN(${accessor})`;return`${accessor} === ${value}`}if(typeof value==="boolean")return`${accessor} === ${value}`;if(value===null)return`${accessor} === null`;if(value===undefined)return`${accessor} === undefined`;if(typeof value==="bigint")return`${accessor} === ${value}n`;if(typeof value==="symbol"){const symbolConst=addConstant(ctx,value);return`${accessor} === ${symbolConst}`}throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`)}function generateIntersectionCheck(doc,ctx,schema,accessor){const def=schema._zod.def;ctx.definite=false;const leftOutput=compileChild(doc,ctx,def.left,accessor);const rightOutput=compileChild(doc,ctx,def.right,accessor);const mergeConst=addConstant(ctx,mergeValues);const mergedVar=newVar(ctx);doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`);doc.write(`if (!${mergedVar}.valid) return INVALID;`);return`${mergedVar}.data`}function generateRecordCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const isPlainObjectConst=addConstant(ctx,isPlainObject);doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`);const outputVar=newVar(ctx);const kVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = {};`);const recordDef=def;const keyValues=recordDef.partial?undefined:def.keyType._zod.values;if(keyValues){const inputKeys=[];for(const key of keyValues){if(!(typeof key==="string"||typeof key==="number"||typeof key==="symbol")){throw new ZodCompileUnsupportedError(`record key value ${String(key)}`)}const inputKey=typeof key==="number"?key.toString():key;if(inputKey==="__proto__"){throw new ZodCompileUnsupportedError('record key "__proto__"')}inputKeys.push(inputKey);const keyConst=addConstant(ctx,key);const outKey=generateCheck(doc,ctx,def.keyType,keyConst);const valueVar=newVar(ctx);doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx,inputKey)}];`);const valOutput=compileChild(doc,ctx,def.valueType,valueVar);doc.write(`${outputVar}[${outKey}] = ${valOutput};`)}const knownKeysConst=addConstant(ctx,new Set(inputKeys));doc.write(`for (const ${kVar} in ${accessor}) {`);doc.indented((d)=>{d.write(`if (${knownKeysConst}.has(${kVar})) continue;`);if(recordDef.mode==="loose"){d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`)}else{d.write(`return INVALID;`)}});doc.write(`}`);return outputVar}const keyDef=def.keyType._zod.def;const keyIsBareString=keyDef.type==="string"&&keyDef.format===undefined&&!keyDef.coerce&&(keyDef.checks?.length??0)===0;if(!keyIsBareString){const isLoose=def.mode==="loose";const keyFn=compileFn(def.keyType);if(keyFn.definite===false)ctx.definite=false;const keyFast=addConstant(ctx,keyFn);const numericConst=addConstant(ctx,number);const outKeyVar=newVar(ctx);emitOwnKeys(doc,ctx,accessor,kVar,(d)=>{d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`);d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`);if(isLoose){d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`)}else{d.write(`if (${outKeyVar} === INVALID) return INVALID;`)}d.write(`if (${outKeyVar} === "__proto__") continue;`);const valueVar=newVar(ctx);d.write(`const ${valueVar} = ${accessor}[${kVar}];`);const valOutput=compileChild(d,ctx,def.valueType,valueVar);d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`)});return outputVar}emitOwnKeys(doc,ctx,accessor,kVar,(d)=>{d.write(`const ${valVar} = ${accessor}[${kVar}];`);const valOutput=compileChild(d,ctx,def.valueType,valVar);d.write(`${outputVar}[${kVar}] = ${valOutput};`)},`return INVALID;`);return outputVar}function emitOwnKeys(doc,ctx,accessor,kVar,body,onSymbol){const propIsEnumerableConst=addConstant(ctx,Object.prototype.propertyIsEnumerable);const symsVar=newVar(ctx);const keysVar=newVar(ctx);const iVar=newVar(ctx);doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`);doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${kVar} = ${keysVar}[${iVar}];`);d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);body(d)});doc.write(`}`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${kVar} = ${symsVar}[${iVar}];`);d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);if(onSymbol)d.write(onSymbol);else body(d)});doc.write(`}`)}function literalPropertyKey(ctx,key){if(typeof key==="string")return esc(key);return addConstant(ctx,key)}function generateMapCheck(doc,ctx,schema,accessor){const def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`);const outputVar=newVar(ctx);const kVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = new Map();`);doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`);doc.indented((d)=>{const keyOutput=generateCheck(d,ctx,def.keyType,kVar);const valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`)});doc.write(`}`);return outputVar}function generateSetCheck(doc,ctx,schema,accessor){const def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`);const outputVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = new Set();`);doc.write(`for (const ${valVar} of ${accessor}) {`);doc.indented((d)=>{const valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.add(${valOutput});`)});doc.write(`}`);return outputVar}function generateFileCheck(doc,accessor){doc.write(`if (!(${accessor} instanceof File)) return INVALID;`);return accessor}function generateTemplateLiteralCheck(doc,ctx,schema,accessor){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);const pattern=schema._zod.pattern;if(pattern){const patternConst=addConstant(ctx,pattern);doc.write(`${patternConst}.lastIndex = 0;`);doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`)}return accessor}function generateLazyCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const getterConst=addUserConstant(ctx,def.getter);const cacheConst=addConstant(ctx,{parser:null});doc.write(`if (!${cacheConst}.parser) {`);doc.indented((d)=>{d.write(`const inner = ${getterConst}();`);d.write(`${cacheConst}.parser = function(input) {`);d.indented((d2)=>{d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`);d2.write(`return result.issues.length === 0 ? result.value : INVALID;`)});d.write(`};`)});doc.write(`}`);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`);doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}function generatePipeCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const inputOutput=generateCheck(doc,ctx,def.in,accessor);if(def.transform){if(isAsyncFunction(def.transform)){throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported")}const transformFn=def.transform;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=transformFn(value,fakePayload);if(result instanceof Promise)return INVALID;return fakePayload.issues.length===0?result:INVALID};const helperConst=addUserConstant(ctx,helperFn);const transformedVar=newVar(ctx);doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`);doc.write(`if (${transformedVar} === INVALID) return INVALID;`);return generateCheck(doc,ctx,def.out,transformedVar)}else{return generateCheck(doc,ctx,def.out,inputOutput)}}function isAsyncFunction(fn){return typeof fn==="function"&&(fn.constructor.name==="AsyncFunction"||fn[Symbol.toStringTag]==="AsyncFunction")}function generateCustomCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(def.fn){if(isAsyncFunction(def.fn)){throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported")}const fnConst=addUserConstant(ctx,def.fn);const throwAsyncConst=addConstant(ctx,throwAsync);const resVar=newVar(ctx);doc.write(`const ${resVar} = ${fnConst}(${accessor});`);doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);doc.write(`if (!${resVar}) return INVALID;`)}else{throw new ZodCompileUnsupportedError("custom schema without a predicate function")}return accessor}function runtimeCatch(innerSchema,catchValue,value){const result=innerSchema._zod.run({value,issues:[]},{});if(result&&typeof result.then==="function")return INVALID;const r=result;if(r.issues.length===0)return r.value;return catchValue()}function generateCatchCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(!def.catchValue[CONSTANT_CATCH]){throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)",false)}const outputVar=newVar(ctx);doc.write(`let ${outputVar} = (() => {`);doc.indented((d)=>{const innerOut=compileChild(d,ctx,def.innerType,accessor);d.write(`return ${innerOut};`)});doc.write(`})();`);const innerConst=addConstant(ctx,def.innerType);const catchConst=addUserConstant(ctx,def.catchValue);const catchHelperConst=addConstant(ctx,runtimeCatch);doc.write(`if (${outputVar} === INVALID) {`);doc.indented((d)=>{d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`);d.write(`if (${outputVar} === INVALID) return INVALID;`)});doc.write(`}`);return outputVar}function generateTransformCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(def.transform){if(isAsyncFunction(def.transform)){throw new ZodCompileAsyncError("z.compile: async transforms are not supported")}const transformFn=def.transform;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=transformFn(value,fakePayload);if(result instanceof Promise)return INVALID;return fakePayload.issues.length===0?result:INVALID};const helperConst=addUserConstant(ctx,helperFn);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${helperConst}(${accessor});`);doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}return accessor}function snapshotChecks(def){if(def.checks)def.checks=[...def.checks];return def}function _string(Class,params){return new Class(snapshotChecks({type:"string",...normalizeParams(params)}))}function _coercedString(Class,params){return new Class(snapshotChecks({type:"string",coerce:true,...normalizeParams(params)}))}function _email(Class,params){return new Class({type:"string",format:"email",check:"string_format",abort:false,...normalizeParams(params)})}function _guid(Class,params){return new Class({type:"string",format:"guid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuid(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuidv4(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v4",...normalizeParams(params)})}function _uuidv6(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v6",...normalizeParams(params)})}function _uuidv7(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v7",...normalizeParams(params)})}function _url(Class,params){return new Class({type:"string",format:"url",check:"string_format",abort:false,...normalizeParams(params)})}function _emoji2(Class,params){return new Class({type:"string",format:"emoji",check:"string_format",abort:false,...normalizeParams(params)})}function _nanoid(Class,params){return new Class({type:"string",format:"nanoid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid(Class,params){return new Class({type:"string",format:"cuid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid2(Class,params){return new Class({type:"string",format:"cuid2",check:"string_format",abort:false,...normalizeParams(params)})}function _ulid(Class,params){return new Class({type:"string",format:"ulid",check:"string_format",abort:false,...normalizeParams(params)})}function _xid(Class,params){return new Class({type:"string",format:"xid",check:"string_format",abort:false,...normalizeParams(params)})}function _ksuid(Class,params){return new Class({type:"string",format:"ksuid",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv4(Class,params){return new Class({type:"string",format:"ipv4",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv6(Class,params){return new Class({type:"string",format:"ipv6",check:"string_format",abort:false,...normalizeParams(params)})}function _mac(Class,params){return new Class({type:"string",format:"mac",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv4(Class,params){return new Class({type:"string",format:"cidrv4",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv6(Class,params){return new Class({type:"string",format:"cidrv6",check:"string_format",abort:false,...normalizeParams(params)})}function _base64(Class,params){return new Class({type:"string",format:"base64",check:"string_format",abort:false,...normalizeParams(params)})}function _base64url(Class,params){return new Class({type:"string",format:"base64url",check:"string_format",abort:false,...normalizeParams(params)})}function _e164(Class,params){return new Class({type:"string",format:"e164",check:"string_format",abort:false,...normalizeParams(params)})}function _creditCard(Class,params){return new Class({type:"string",format:"credit_card",check:"string_format",abort:false,...normalizeParams(params)})}function _iban(Class,params){return new Class({type:"string",format:"iban",check:"string_format",abort:false,...normalizeParams(params)})}function _jwt(Class,params){return new Class({type:"string",format:"jwt",check:"string_format",abort:false,...normalizeParams(params)})}var TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function _isoDateTime(Class,params){return new Class({type:"string",format:"datetime",check:"string_format",offset:false,local:false,precision:null,...normalizeParams(params)})}function _isoDate(Class,params){return new Class({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class,params){return new Class({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class,params){return new Class({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class,params){return new Class(snapshotChecks({type:"number",checks:[],...normalizeParams(params)}))}function _coercedNumber(Class,params){return new Class(snapshotChecks({type:"number",coerce:true,checks:[],...normalizeParams(params)}))}function _int(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"safeint",...normalizeParams(params)})}function _float32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"float32",...normalizeParams(params)})}function _float64(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"float64",...normalizeParams(params)})}function _int32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"int32",...normalizeParams(params)})}function _uint32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"uint32",...normalizeParams(params)})}function _boolean(Class,params){return new Class({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class,params){return new Class({type:"boolean",coerce:true,...normalizeParams(params)})}function _bigint(Class,params){return new Class({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class,params){return new Class({type:"bigint",coerce:true,...normalizeParams(params)})}function _int64(Class,params){return new Class({type:"bigint",check:"bigint_format",abort:false,format:"int64",...normalizeParams(params)})}function _uint64(Class,params){return new Class({type:"bigint",check:"bigint_format",abort:false,format:"uint64",...normalizeParams(params)})}function _symbol(Class,params){return new Class({type:"symbol",...normalizeParams(params)})}function _undefined2(Class,params){return new Class({type:"undefined",...normalizeParams(params)})}function _null2(Class,params){return new Class({type:"null",...normalizeParams(params)})}function _any(Class){return new Class({type:"any"})}function _unknown(Class){return new Class({type:"unknown"})}function _never(Class,params){return new Class({type:"never",...normalizeParams(params)})}function _void(Class,params){return new Class({type:"void",...normalizeParams(params)})}function _date(Class,params){return new Class({type:"date",...normalizeParams(params)})}function _coercedDate(Class,params){return new Class({type:"date",coerce:true,...normalizeParams(params)})}function _nan(Class,params){return new Class({type:"nan",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:false})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:true})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:false})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:true})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size})}function _maxLength(maximum,params){const ch=new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum});return ch}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _properties(shape,params){return new $ZodCheckProperties({check:"properties",shape,...normalizeParams(params)})}function _mime(types,params){return new $ZodCheckMimeType({check:"mime_type",mime:types,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite((input)=>input.normalize(form))}function _trim(){return _overwrite((input)=>input.trim())}function _toLowerCase(){return _overwrite((input)=>input.toLowerCase())}function _toUpperCase(){return _overwrite((input)=>input.toUpperCase())}function _slugify(){return _overwrite((input)=>slugify(input))}function _array(Class,element,params){return new Class({type:"array",element,...normalizeParams(params)})}function _union(Class,options,params){return new Class({type:"union",options,...normalizeParams(params)})}function _xor(Class,options,params){return new Class({type:"union",options,inclusive:false,...normalizeParams(params)})}function _discriminatedUnion(Class,discriminator,options,params){return new Class({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class,left,right){return new Class({type:"intersection",left,right})}function _tuple(Class,items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new Class({type:"tuple",items,rest,...normalizeParams(params)})}function _record(Class,keyType,valueType,params){return new Class({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class,keyType,valueType,params){return new Class({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class,valueType,params){return new Class({type:"set",valueType,...normalizeParams(params)})}function _enum(Class,values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new Class({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class,entries,params){return new Class({type:"enum",entries,...normalizeParams(params)})}function _literal(Class,value,params){return new Class({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function _file(Class,params){return new Class({type:"file",...normalizeParams(params)})}function _transform(Class,fn){return new Class({type:"transform",transform:fn})}function _optional(Class,innerType){return new Class({type:"optional",innerType})}function _nullable(Class,innerType){return new Class({type:"nullable",innerType})}function _default(Class,innerType,defaultValue){return new Class({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class,innerType,params){return new Class({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class,innerType){return new Class({type:"success",innerType})}function _catch(Class,innerType,catchValue){return new Class({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}function _pipe(Class,in_,out){return new Class({type:"pipe",in:in_,out})}function _readonly(Class,innerType){return new Class({type:"readonly",innerType})}function _templateLiteral(Class,parts,params){return new Class({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class,getter){return new Class({type:"lazy",getter})}function _promise(Class,innerType){return new Class({type:"promise",innerType})}function _custom(Class,fn,_params){const norm=normalizeParams(_params);norm.abort??(norm.abort=true);const schema=new Class({type:"custom",check:"custom",fn,...norm});return schema}function _refine(Class,fn,_params){const schema=new Class({type:"custom",check:"custom",fn,...normalizeParams(_params)});return schema}function _superRefine(fn,params){const ch=_check((payload)=>{payload.addIssue=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,ch._zod.def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");if(!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=ch);_issue.continue??(_issue.continue=!ch._zod.def.abort);payload.issues.push(issue(_issue))}};return fn(payload.value,payload)},params);return ch}function _check(fn,params){const ch=new $ZodCheck({check:"custom",...normalizeParams(params)});ch._zod.check=fn;return ch}function describe(description){const ch=new $ZodCheck({check:"describe"});ch._zod.onattach=[(inst)=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}];ch._zod.check=()=>{};return ch}function meta(metadata){const ch=new $ZodCheck({check:"meta"});ch._zod.onattach=[(inst)=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}];ch._zod.check=()=>{};return ch}function _stringbool(Classes,_params){const params=normalizeParams(_params);let truthyArray=params.truthy??["true","1","yes","on","y","enabled"];let falsyArray=params.falsy??["false","0","no","off","n","disabled"];if(params.case!=="sensitive"){truthyArray=truthyArray.map((v)=>typeof v==="string"?v.toLowerCase():v);falsyArray=falsyArray.map((v)=>typeof v==="string"?v.toLowerCase():v)}const truthySet=new Set(truthyArray);const falsySet=new Set(falsyArray);const _Codec=Classes.Codec??$ZodCodec;const _Boolean=Classes.Boolean??$ZodBoolean;const _String=Classes.String??$ZodString;const stringSchema=new _String({type:"string",error:params.error});const booleanSchema=new _Boolean({type:"boolean",error:params.error});const codec=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:(input,payload)=>{let data=input;if(params.case!=="sensitive")data=data.toLowerCase();if(truthySet.has(data)){return true}else if(falsySet.has(data)){return false}else{payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec,continue:false});return{}}},reverseTransform:(input,_payload)=>{if(input===true){return truthyArray[0]||"true"}else{return falsyArray[0]||"false"}},error:params.error});codec._zod.bag.truthy=truthyArray;codec._zod.bag.falsy=falsyArray;codec._zod.bag.case=params.case??"insensitive";return codec}function _stringFormat(Class,format,fnOrRegex,_params={}){const params=normalizeParams(_params);const def={check:"string_format",type:"string",format,fn:typeof fnOrRegex==="function"?fnOrRegex:(val)=>fnOrRegex.test(val),...params};if(fnOrRegex instanceof RegExp){def.pattern=fnOrRegex}const inst=new Class(def);return inst}function assignProps(target,...sources){for(const source of sources){for(const key of Reflect.ownKeys(source)){if(Object.prototype.propertyIsEnumerable.call(source,key)){assignProp(target,key,source[key])}}}return target}function initializeContext(params){let target=params?.target??"draft-2020-12";if(target==="draft-4")target="draft-04";if(target==="draft-7")target="draft-07";return{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:undefined,sharedEmitDoneFor:undefined,cycles:params?.cycles??"ref",reused:params?.reused??"inline",intersections:[],deferred:[],external:params?.external??undefined}}function handleUnrepresentable(schema,ctx,json,params,message){const result=typeof ctx.unrepresentable==="function"?ctx.unrepresentable({zodSchema:schema,path:params.path,message}):ctx.unrepresentable;if(result==="any")return false;if(result===undefined||result==="throw")throw new Error(message);Object.assign(json,result);return true}function processSchema(schema,ctx,_params={path:[],schemaPath:[]}){var _a;const def=schema._zod.def;const seen=ctx.seen.get(schema);if(seen){seen.count++;const isCycle=_params.schemaPath.includes(schema);if(isCycle){seen.cycle=_params.path}return seen.schema}const result={schema:{},count:1,cycle:undefined,path:_params.path};ctx.seen.set(schema,result);ctx.sharedDefsExtractedFor=undefined;ctx.sharedEmitDoneFor=undefined;const overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema){result.schema=overrideSchema}else{const params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema){schema._zod.processJSONSchema(ctx,result.schema,params)}else{const _json=result.schema;const processor=ctx.processors[def.type];if(!processor){throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`)}processor(schema,ctx,_json,params)}const parent=schema._zod.parent;if(parent){if(!result.ref)result.ref=parent;processSchema(parent,ctx,params);ctx.seen.get(parent).isParent=true}}const meta=ctx.metadataRegistry.get(schema);if(meta)assignProps(result.schema,meta);if(ctx.io==="input"&&isTransforming(schema)){delete result.schema.examples;delete result.schema.default}if(ctx.io==="input"&&"_prefault"in result.schema)(_a=result.schema).default??(_a.default=result.schema._prefault);delete result.schema._prefault;const _result=ctx.seen.get(schema);return _result.schema}function encodeJSONPointerSegment(segment){return segment.replace(/~/g,"~0").replace(/\//g,"~1")}function extractDefs(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");if(ctx.external&&ctx.sharedDefsExtractedFor===ctx.external)return;const idToSchema=new Map;for(const entry of ctx.seen.entries()){const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){const existing=idToSchema.get(id);if(existing&&existing!==entry[0]){throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`)}idToSchema.set(id,entry[0])}}const makeURI=(entry)=>{const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){const externalId=ctx.external.registry.get(entry[0])?.id;const uriGenerator=ctx.external.uri??((id)=>id);if(externalId){return{ref:uriGenerator(externalId)}}const id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;entry[1].defId=id;return{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}`}}const uriPrefix=`#`;const defUriPrefix=`${uriPrefix}/${defsSegment}/`;if(entry[1]===root&&!entry[1].schema.id){return{ref:uriPrefix}}const defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+encodeJSONPointerSegment(defId)}};const extractToDef=(entry)=>{if(entry[1].schema.$ref){return}const seen=entry[1];const{ref,defId}=makeURI(entry);seen.def={...seen.schema};if(defId)seen.defId=defId;const schema=seen.schema;for(const key in schema){delete schema[key]}schema.$ref=ref};if(ctx.cycles==="throw"){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.cycle){throw new Error("Cycle detected: "+`#/${seen.cycle?.join("/")}/<root>`+'\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.')}}}for(const entry of ctx.seen.entries()){const seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){const ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry)}}}if(ctx.external)ctx.sharedDefsExtractedFor=ctx.external}function compactTypeUnion(schema){const options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==undefined)return;const types=[];for(const option of options){if(!option||typeof option!=="object")return;compactTypeUnion(option);const keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;const type=option.type;for(const member of Array.isArray(type)?type:[type]){if(typeof member!=="string")return;if(!types.includes(member))types.push(member)}}delete schema.anyOf;schema.type=types.length===1?types[0]:types}var FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]);var UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){const extra=member.additionalProperties;if(extra===undefined||extra===false||typeof extra!=="object"||extra===null)return null;return Object.keys(extra).length?extra:null}function foldObjects(members){const objects=[];for(const member of members){if(typeof member!=="object"||member.type!=="object")return null;for(const key in member){if(!FOLDABLE_KEYS.has(key))return null}objects.push(member)}const properties={};const required=new Set;for(const object of objects){for(const key in object.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;const parts=[];for(const other of objects){const part=other.properties?.[key]??undeclaredConstraint(other);if(part===null||part===undefined)continue;if(!parts.some((seen)=>JSON.stringify(seen)===JSON.stringify(part)))parts.push(part)}const merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(const key of object.required??[])required.add(key)}const folded={type:"object",properties};if(required.size)folded.required=[...required];if(objects.every((object)=>object.additionalProperties===false)){folded.additionalProperties=false}else{const constraints=[];for(const object of objects){const constraint=undeclaredConstraint(object);if(constraint&&!constraints.some((seen)=>JSON.stringify(seen)===JSON.stringify(constraint)))constraints.push(constraint)}if(constraints.length===1)folded.additionalProperties=constraints[0];else if(constraints.length>1)folded.additionalProperties={allOf:constraints}}return folded}function foldIntersection(json){const allOf=json.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(const key of FOLDABLE_KEYS)if(key in json)return;const unions=allOf.filter((m)=>UNION_KEYS.some((k)=>Array.isArray(m[k])));let folded=null;if(!unions.length){folded=foldObjects(allOf)}else{const union=unions[0];const keyword=UNION_KEYS.find((k)=>Array.isArray(union[k]));if(Object.keys(union).length!==1)return;const rest=allOf.filter((m)=>m!==union);const branches=union[keyword].map((branch)=>foldObjects([...rest,branch]));if(branches.some((b)=>!b))return;folded={[keyword]:branches}}if(!folded)return;delete json.allOf;assignProps(json,folded)}function finalize(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");const flattenRef=(zodSchema)=>{const seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;const schema=seen.def??seen.schema;const _cached={...schema};const ref=seen.ref;seen.ref=null;if(ref){flattenRef(ref);const refSeen=ctx.seen.get(ref);const refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")){schema.allOf=schema.allOf??[];schema.allOf.push(refSchema)}else{assignProps(schema,refSchema)}assignProps(schema,_cached);const isParentRef=zodSchema._zod.parent===ref;if(isParentRef){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached)){delete schema[key]}}}if(refSchema.$ref&&refSeen.def){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema[key])===JSON.stringify(refSeen.def[key])){delete schema[key]}}}}const parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);const parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){schema.$ref=parentSeen.schema.$ref;if(parentSeen.def){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema[key])===JSON.stringify(parentSeen.def[key])){delete schema[key]}}}}}ctx.override({zodSchema,jsonSchema:schema,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(const entry of[...ctx.seen.entries()].reverse()){flattenRef(entry[0])}if(ctx.target!=="openapi-3.0"){for(const entry of ctx.seen.entries()){compactTypeUnion(entry[1].def??entry[1].schema)}}for(const rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){const carriers=new Map;for(const seen of ctx.seen.values()){for(const json of[seen.schema,seen.def]){const allOf=json?.allOf;if(!Array.isArray(allOf))continue;const existing=carriers.get(allOf);if(existing)existing.push(json);else carriers.set(allOf,[json])}}for(const allOf of ctx.intersections){for(const json of carriers.get(allOf)??[])foldIntersection(json)}}}const result={};if(ctx.target==="draft-2020-12"){result.$schema="https://json-schema.org/draft/2020-12/schema"}else if(ctx.target==="draft-07"){result.$schema="http://json-schema.org/draft-07/schema#"}else if(ctx.target==="draft-04"){result.$schema="http://json-schema.org/draft-04/schema#"}else if(ctx.target==="openapi-3.0"){}if(ctx.external?.uri){const id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);const rootMetaId=ctx.metadataRegistry.get(schema)?.id;if(rootMetaId!==undefined&&result.id===rootMetaId)delete result.id;const defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.def&&seen.defId){if(seen.def.id===seen.defId)delete seen.def.id;assignProp(defs,seen.defId,seen.def)}}}if(ctx.external)ctx.sharedEmitDoneFor=ctx.external;if(ctx.external){}else{if(Object.keys(defs).length>0){if(ctx.target==="draft-2020-12"){result.$defs=defs}else{result.definitions=defs}}}try{const finalized=JSON.parse(JSON.stringify(result));Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:false,writable:false});return finalized}catch(_err){throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){const ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return false;ctx.seen.add(_schema);const def=_schema._zod.def;if(def.type==="transform")return true;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch"){return isTransforming(def.innerType,ctx)}if(def.type==="intersection"){return isTransforming(def.left,ctx)||isTransforming(def.right,ctx)}if(def.type==="record"||def.type==="map"){return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx)}if(def.type==="pipe"){if(_schema._zod.traits.has("$ZodCodec"))return true;return isTransforming(def.in,ctx)||isTransforming(def.out,ctx)}if(def.type==="object"){for(const key in def.shape){if(isTransforming(def.shape[key],ctx))return true}return false}if(def.type==="union"){for(const option of def.options){if(isTransforming(option,ctx))return true}return false}if(def.type==="tuple"){for(const item of def.items){if(isTransforming(item,ctx))return true}if(def.rest&&isTransforming(def.rest,ctx))return true;return false}return false}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{const ctx=initializeContext({...params,processors});processSchema(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{const{libraryOptions,target}=params??{};const ctx=initializeContext({...libraryOptions??{},target,io,processors});processSchema(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var narrowMin=(agg,key,value)=>{if(agg[key]===undefined||value>agg[key])agg[key]=value};var narrowMax=(agg,key,value)=>{if(agg[key]===undefined||value<agg[key])agg[key]=value};var narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value);narrowMax(agg,"maximum",value)};var addDivisor=(agg,value)=>{agg.multipleOf??(agg.multipleOf=[]);if(!agg.multipleOf.includes(value))agg.multipleOf.push(value)};var addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set);agg.patterns.add(pattern)};var intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter((m)=>mime.includes(m)):[...mime]};var setFormat=(agg,format)=>{agg.format=format;if(format.includes("int"))agg.isInt=true};var minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum);var maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum);var formatContributor=(ranges)=>(agg,def)=>{setFormat(agg,def.format);const[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum);narrowMax(agg,"maximum",maximum)};var contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format);if(def.pattern)addPattern(agg,def.pattern);if(def.format==="base64"||def.format==="base64url")agg.contentEncoding=def.format;if(def.local||def.precision===-1)agg.laxFormat=true},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){const agg={};const def=schema._zod.def;const list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(const ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);const bag=schema._zod.bag;if(bag.minimum!==undefined)narrowMin(agg,"minimum",bag.minimum);if(bag.exclusiveMinimum!==undefined)narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum);if(bag.maximum!==undefined)narrowMax(agg,"maximum",bag.maximum);if(bag.exclusiveMaximum!==undefined)narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum);if(bag.multipleOf!==undefined)addDivisor(agg,bag.multipleOf);if(bag.format!==undefined){agg.format??(agg.format=bag.format);if(bag.format.includes("int"))agg.isInt=true}if(bag.mime)intersectMime(agg,bag.mime);for(const pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""};var exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]);var exactPattern=(p)=>exactPatterns.get(p)??p;var stringProcessor=(schema,ctx,_json,_params)=>{const json=_json;json.type="string";const{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){json.format=formatMap[format]??format;if(json.format==="")delete json.format;if(format==="time"||laxFormat){delete json.format}}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){const patternList=[...patterns].map(exactPattern);if(patternList.length===1)json.pattern=patternList[0].source;else if(patternList.length>1){json.allOf=[...patternList.map((regex)=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}}};var numberProcessor=(schema,ctx,_json,params)=>{const json=_json;const{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json.type=isInt?"integer":"number";const exMin=typeof exclusiveMinimum==="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY);const exMax=typeof exclusiveMaximum==="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY);const legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin){if(legacy){json.minimum=exclusiveMinimum;json.exclusiveMinimum=true}else{json.exclusiveMinimum=exclusiveMinimum}}else if(typeof minimum==="number"){json.minimum=minimum}if(exMax){if(legacy){json.maximum=exclusiveMaximum;json.exclusiveMaximum=true}else{json.exclusiveMaximum=exclusiveMaximum}}else if(typeof maximum==="number"){json.maximum=maximum}if(multipleOf){const divisors=new Set;for(const divisor of multipleOf){if(Number.isFinite(divisor)&&divisor!==0)divisors.add(Math.abs(divisor));else handleUnrepresentable(schema,ctx,json,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`)}const[first,...rest]=divisors;if(first!==undefined)json.multipleOf=first;if(rest.length)json.allOf=[...json.allOf??[],...rest.map((m)=>({multipleOf:m}))]}};var booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var bigintProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"BigInt cannot be represented in JSON Schema")};var symbolProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Symbols cannot be represented in JSON Schema")};var nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0"){json.type="string";json.nullable=true;json.enum=[null]}else{json.type="null"}};var undefinedProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Undefined cannot be represented in JSON Schema")};var voidProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Void cannot be represented in JSON Schema")};var neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}};var anyProcessor=(_schema,_ctx,_json,_params)=>{};var unknownProcessor=(_schema,_ctx,_json,_params)=>{};var dateProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Date cannot be represented in JSON Schema")};var enumProcessor=(schema,_ctx,json,_params)=>{const def=schema._zod.def;const values=getEnumValues(def.entries);if(values.length===0){json.not={};return}if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values};var literalProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;if(def.values.length===0){json.not={};return}const vals=[];for(const val of def.values){if(val===undefined){if(handleUnrepresentable(schema,ctx,json,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val==="bigint"){if(handleUnrepresentable(schema,ctx,json,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else{vals.push(val)}}if(vals.length===0){}else if(vals.length===1){const val=vals[0];json.type=val===null?"null":typeof val;if(ctx.target==="draft-04"||ctx.target==="openapi-3.0"){json.enum=[val]}else{json.const=val}}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}};var nanProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"NaN cannot be represented in JSON Schema")};var templateLiteralProcessor=(schema,_ctx,json,_params)=>{const _json=json;const pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string";_json.pattern=pattern.source};var fileProcessor=(schema,_ctx,json,_params)=>{const _json=json;_json.type="string";_json.format="binary";_json.contentEncoding="binary";const{minimum,maximum,mime}=aggregateChecks(schema);if(minimum!==undefined)_json.minLength=minimum;if(maximum!==undefined)_json.maxLength=maximum;if(!mime)return;if(mime.length===0)_json.not={};else if(mime.length===1)_json.contentMediaType=mime[0];else _json.anyOf=mime.map((m)=>({contentMediaType:m}))};var successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var customProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Custom types cannot be represented in JSON Schema")};var functionProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Function types cannot be represented in JSON Schema")};var transformProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Transforms cannot be represented in JSON Schema")};var mapProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Map cannot be represented in JSON Schema")};var setProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Set cannot be represented in JSON Schema")};var arrayProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;const{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array";json.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};function inputOptin(schema){const def=schema._zod.def;if(def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")){return inputOptin(def.out)}if(def.type==="catch"){return inputOptin(def.innerType)}return schema._zod.optin}var objectProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;const shape=def.shape;const symbolKeys=Object.getOwnPropertySymbols(shape);if(symbolKeys.length&&handleUnrepresentable(schema,ctx,json,params,"Symbol keys cannot be represented in JSON Schema")){return}json.type="object";json.properties={};for(const key in shape){assignProp(json.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}))}const requiredKeys=[];for(const key of Object.keys(shape)){const field=def.shape[key];if(ctx.io==="input"?inputOptin(field)===undefined:field._zod.optout===undefined){requiredKeys.push(key)}}if(requiredKeys.length>0){json.required=requiredKeys}if(def.catchall?._zod.def.type==="never"){json.additionalProperties=false}else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=false}else if(def.catchall){json.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})}};var unionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const isExclusive=def.inclusive===false;const options=def.options.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive){json.oneOf=options}else{json.anyOf=options}};var intersectionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]});const b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]});const isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1;const allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf;ctx.intersections.push(allOf)};var tupleProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="array";const prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items";const restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems";const prefixItems=def.items.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,prefixPath,i]}));const rest=def.rest?processSchema(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;let minItems=def.items.length;while(minItems>0){const item=def.items[minItems-1];const optional=ctx.io==="input"?inputOptin(item)!==undefined:item._zod.optout==="optional";if(!optional)break;minItems--}const maxItems=def.items.length;const isClosed=!def.rest;if(ctx.target==="draft-2020-12"){json.prefixItems=prefixItems;if(isClosed){json.items=false}else if(rest){json.items=rest}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else if(ctx.target==="openapi-3.0"){json.items={anyOf:prefixItems};if(rest){json.items.anyOf.push(rest)}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else{json.items=prefixItems;if(isClosed){json.additionalItems=false}else if(rest){json.additionalItems=rest}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}const{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum};function stringifyKeyNames(bySchema,json,visited){if(json.$ref){if(visited.has(json))return json;visited.add(json);const def=bySchema.get(json)?.def;if(!def)return json;const inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json:inlined}for(const keyword of["anyOf","oneOf"]){const branches=json[keyword];if(!Array.isArray(branches))continue;const mapped=branches.map((branch)=>stringifyKeyNames(bySchema,branch,visited));if(mapped.some((branch,i)=>branch!==branches[i]))json={...json,[keyword]:mapped}}const types=Array.isArray(json.type)?json.type:[json.type];const numericType=!types.includes("string")&&types.some((t)=>t==="number"||t==="integer");const values=json.enum??(json.const!==undefined?[json.const]:undefined);if(!numericType&&!values?.some((v)=>typeof v==="number"))return json;const{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json;if(rest.enum)rest.enum=rest.enum.map((v)=>typeof v==="number"?String(v):v);else if(typeof rest.const==="number")rest.const=String(rest.const);if(!numericType)return rest;rest.type="string";if(!values)rest.pattern=(types.includes("number")?number:integer).source;return rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){const bySchema=new Map;for(const entry of ctx.seen.values()){if(entry.def&&!bySchema.has(entry.schema))bySchema.set(entry.schema,entry)}const rewrites=new Map;for(const record of pendingRecords.get(ctx)??[]){const seen=ctx.seen.get(record);const names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===true||rewrites.has(names))continue;const rewritten=stringifyKeyNames(bySchema,names,new Set);if(rewritten!==names)rewrites.set(names,rewritten)}if(!rewrites.size)return;for(const entry of ctx.seen.values()){for(const carrier of[entry.schema,entry.def]){const rewritten=carrier&&rewrites.get(carrier.propertyNames);if(rewritten)carrier.propertyNames=rewritten}}}var recordProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="object";const keyType=def.keyType;const patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){const valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(const pattern of patterns){assignProp(json.patternProperties,exactPattern(pattern).source,valueSchema)}}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending=pendingRecords.get(ctx);if(!pending){pending=[];pendingRecords.set(ctx,pending);ctx.deferred.push(()=>rewriteKeyNames(ctx))}pending.push(schema)}json.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}const keyValues=keyType._zod.values;const omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==undefined;if(keyValues&&!def.partial&&!omittableOnInput){const validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0){json.required=validKeyValues.map(String)}}};var nullableProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const inner=processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0"){seen.ref=def.innerType;json.nullable=true}else{json.anyOf=[inner,{type:"null"}]}};var nonoptionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value,schema,ctx,json,params){let unrepresentable=false;const serialized=JSON.stringify(value,(_,val)=>{if(typeof val!=="bigint")return val;unrepresentable=true;return null});if(!unrepresentable)return JSON.parse(serialized);handleUnrepresentable(schema,ctx,json,params,"BigInt defaults cannot be represented in JSON Schema");return UNREPRESENTABLE_DEFAULT}var defaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;const value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json.default=value};var prefaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;if(ctx.io!=="input")return;const value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json._prefault=value};var catchProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(undefined)}catch{handleUnrepresentable(schema,ctx,json,params,"Dynamic catch values are not supported in JSON Schema");return}json.default=catchValue};var pipeProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;const inIsTransform=def.in._zod.traits.has("$ZodTransform");const innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};var readonlyProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json.readOnly=true};var promiseProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var optionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var lazyProcessor=(schema,ctx,_json,params)=>{const innerType=schema._zod.innerType;processSchema(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};var allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(input,params){if("_idmap"in input){const registry=input;const ctx=initializeContext({...params,processors:allProcessors});const defs={};for(const entry of registry._idmap.entries()){const[_,schema]=entry;processSchema(schema,ctx)}const schemas={};const external={registry,uri:params?.uri,defs};ctx.external=external;for(const entry of registry._idmap.entries()){const[key,schema]=entry;extractDefs(ctx,schema);assignProp(schemas,key,finalize(ctx,schema))}if(Object.keys(defs).length>0){const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}const ctx=initializeContext({...params,processors:allProcessors});processSchema(input,ctx);extractDefs(ctx,input);return finalize(ctx,input)}class JSONSchemaGenerator{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return processSchema(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}this.ctx.sharedDefsExtractedFor=undefined;this.ctx.sharedEmitDoneFor=undefined;extractDefs(this.ctx,schema);const result=finalize(this.ctx,schema);const{"~standard":_,...plainResult}=result;return plainResult}}var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:true,enumerable:false,get(){const value=make(this);Object.defineProperty(this,key,{value,configurable:true,writable:true});return value},set(value){Object.defineProperty(this,key,{value,configurable:true,writable:true})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues);inst.name="ZodError";const proto=Object.getPrototypeOf(inst);if(_installedErrorProtos.has(proto))return;_installedErrorProtos.add(proto);_lazyMethod(proto,"format",(self)=>(mapper)=>formatError(self,mapper));_lazyMethod(proto,"flatten",(self)=>(mapper)=>flattenError(self,mapper));_lazyMethod(proto,"addIssue",(self)=>(issue)=>{self.issues.push(issue);self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)});_lazyMethod(proto,"addIssues",(self)=>(issues)=>{self.issues.push(...issues);self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)});Object.defineProperty(proto,"isEmpty",{configurable:true,enumerable:false,get(){return this.issues.length===0}})};var ZodError=$constructor("ZodError",initializer2);var ZodRealError=$constructor("ZodError",initializer2,undefined,{Parent:Error});var parse3=_parse(ZodRealError);var parseAsync2=_parseAsync(ZodRealError);var safeParse2=_safeParse(ZodRealError);var safeParseAsync2=_safeParseAsync(ZodRealError);var encode2=_encode(ZodRealError);var decode2=_decode(ZodRealError);var encodeAsync2=_encodeAsync(ZodRealError);var decodeAsync2=_decodeAsync(ZodRealError);var safeEncode2=_safeEncode(ZodRealError);var safeDecode2=_safeDecode(ZodRealError);var safeEncodeAsync2=_safeEncodeAsync(ZodRealError);var safeDecodeAsync2=_safeDecodeAsync(ZodRealError);function _ensureDefaultLocale(){if(!globalConfig.localeError)config(en_default())}function _ensureDefaultMemoizer(){if(!globalConfig.memoizer)config({memoizer:memoizer()})}var ZodType=$constructor("ZodType",(inst,def)=>{_ensureDefaultLocale();$ZodType.init(inst,def);inst.def=def;inst.type=def.type;return inst},{check(...chks){const def=this.def;return this.clone(mergeDefs(def,{checks:[...def.checks??[],...chks.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:true})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta){reg.add(this,meta);return this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){const cl=this.clone();globalRegistry.add(cl,{description});return cl},meta(...args){if(args.length===0)return globalRegistry.get(this);const cl=this.clone();globalRegistry.add(cl,args[0]);return cl},isOptional(){return this.safeParse(undefined).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get "~standard"(){return hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set "~standard"(value){own(this,"~standard",value)},parse:function _parse(data,params){return parse3(this,data,params,{callee:_parse})},parseAsync:async function _parseAsync(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value){own(this,"spa",value)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode(data,params){return encode2(this,data,params,{callee:_encode})},decode:function _decode(data,params){return decode2(this,data,params,{callee:_decode})},encodeAsync:async function _encodeAsync(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}});var _ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params)},derived({format:(inst)=>aggregateChecks(inst).format??null,minLength:(inst)=>aggregateChecks(inst).minimum??null,maxLength:(inst)=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}}));var ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def);_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def);_ZodString.init(inst,def)});var ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def);ZodStringFormat.init(inst,def)});var ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def);ZodStringFormat.init(inst,def)});function email2(params){return _email(ZodEmail,params)}var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def);ZodStringFormat.init(inst,def)});function guid2(params){return _guid(ZodGUID,params)}var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def);ZodStringFormat.init(inst,def)});function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def);ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:httpProtocol,hostname:domain,...normalizeParams(params)})}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def);ZodStringFormat.init(inst,def)});function emoji2(params){return _emoji2(ZodEmoji,params)}var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def);ZodStringFormat.init(inst,def)});function nanoid2(params){return _nanoid(ZodNanoID,params)}var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def);ZodStringFormat.init(inst,def)});function cuid3(params){return _cuid(ZodCUID,params)}var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def);ZodStringFormat.init(inst,def)});function cuid22(params){return _cuid2(ZodCUID2,params)}var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def);ZodStringFormat.init(inst,def)});function ulid2(params){return _ulid(ZodULID,params)}var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def);ZodStringFormat.init(inst,def)});function xid2(params){return _xid(ZodXID,params)}var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def);ZodStringFormat.init(inst,def)});function ksuid2(params){return _ksuid(ZodKSUID,params)}var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def);ZodStringFormat.init(inst,def)});function ipv42(params){return _ipv4(ZodIPv4,params)}var ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def);ZodStringFormat.init(inst,def)});function mac2(params){return _mac(ZodMAC,params)}var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def);ZodStringFormat.init(inst,def)});function ipv62(params){return _ipv6(ZodIPv6,params)}var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def);ZodStringFormat.init(inst,def)});function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def);ZodStringFormat.init(inst,def)});function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def);ZodStringFormat.init(inst,def)});function base642(params){return _base64(ZodBase64,params)}var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def);ZodStringFormat.init(inst,def)});function base64url2(params){return _base64url(ZodBase64URL,params)}var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def);ZodStringFormat.init(inst,def)});function e1642(params){return _e164(ZodE164,params)}var ZodCreditCard=$constructor("ZodCreditCard",(inst,def)=>{$ZodCreditCard.init(inst,def);ZodStringFormat.init(inst,def)});function creditCard2(params){return _creditCard(ZodCreditCard,params)}var ZodIBAN=$constructor("ZodIBAN",(inst,def)=>{$ZodIBAN.init(inst,def);ZodStringFormat.init(inst,def)});function iban2(params){return _iban(ZodIBAN,params)}var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def);ZodStringFormat.init(inst,def)});function jwt(params){return _jwt(ZodJWT,params)}var ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def);ZodStringFormat.init(inst,def)});function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",hex,_params)}function currencyCode2(_params){return _stringFormat(ZodCustomStringFormat,"currency_code",currencyCode,_params)}function hash(alg,params){const enc=params?.enc??"hex";const format=`${alg}_${enc}`;const regex=exports_regexes[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params);inst.isFinite=true},derived({minValue:(inst)=>{const{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:(inst)=>{const{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:(inst)=>{const{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:(inst)=>aggregateChecks(inst).format??null},{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}}));function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def);ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params)},derived({minValue:(inst)=>aggregateChecks(inst).minimum??null,maxValue:(inst)=>aggregateChecks(inst).maximum??null,format:(inst)=>aggregateChecks(inst).format??null},{gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},gt(value,params){return this.check(_gt(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},positive(params){return this.check(_gt(BigInt(0),params))},negative(params){return this.check(_lt(BigInt(0),params))},nonpositive(params){return this.check(_lte(BigInt(0),params))},nonnegative(params){return this.check(_gte(BigInt(0),params))},multipleOf(value,params){return this.check(_multipleOf(value,params))}}));function bigint2(params){return _bigint(ZodBigInt,params)}var ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def);ZodBigInt.init(inst,def)});function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}var ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});function symbol(params){return _symbol(ZodSymbol,params)}var ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});function _undefined3(params){return _undefined2(ZodUndefined,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});function _null3(params){return _null2(ZodNull,params)}var ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});function any(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});function never(params){return _never(ZodNever,params)}var ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});function _void2(params){return _void(ZodVoid,params)}var ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params);inst.min=(value,params)=>inst.check(_gte(value,params));inst.max=(value,params)=>inst.check(_lte(value,params))},derived({minDate:(inst)=>{const{minimum}=aggregateChecks(inst);return minimum?new Date(minimum):null},maxDate:(inst)=>{const{maximum}=aggregateChecks(inst);return maximum?new Date(maximum):null}},{}));function date2(params){return _date(ZodDate,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer();$ZodArray.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params);inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){const shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer();$ZodObjectJIT.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params);installLazyProp(inst,"shape",(self)=>self._zod.def.shape,false)},{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(mergeDefs(this._zod.def,{catchall:undefined}))},extend(incoming){return extend(this,incoming)},safeExtend(incoming){return safeExtend(this,incoming)},merge(other){return merge(this,other)},pick(mask){return pick(this,mask)},omit(mask){return omit(this,mask)},partial(...args){return partial(ZodOptional,this,args[0])},exactPartial(...args){return partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return required(ZodNonOptional,this,args[0])}});function object(shape,params){const def={type:"object",shape:shape??{},...normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...normalizeParams(params)})}var ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def);$ZodXor.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});function xor(options,params){return new ZodXor({type:"union",options,inclusive:false,...normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def);$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodTuple=$constructor("ZodTuple",(inst,def)=>{_ensureDefaultMemoizer();$ZodTuple.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params)},{rest(rest){return this.clone({...this._zod.def,rest})},partial(){const def=this._zod.def;if(def.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...def,items:def.items.map((item)=>new ZodOptional({type:"optional",innerType:item}))})}});function tuple(items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...normalizeParams(params)})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer();$ZodRecord.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType});function record(keyType,valueType,params){if(!valueType||!valueType._zod){return new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...normalizeParams(valueType)})}return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params)})}function partialRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params),partial:true})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...normalizeParams(params)})}var ZodMap=$constructor("ZodMap",(inst,def)=>{_ensureDefaultMemoizer();$ZodMap.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType;inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=(params)=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...normalizeParams(params)})}var ZodSet=$constructor("ZodSet",(inst,def)=>{_ensureDefaultMemoizer();$ZodSet.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params);inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=(params)=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});function set(valueType,params){return new ZodSet({type:"set",valueType,...normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params);inst.enum=def.entries;inst.options=[...inst._zod.values];const keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{const newEntries={};for(const value of values){if(keys.has(value)){newEntries[value]=def.entries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})};inst.exclude=(values,params)=>{const newEntries={...def.entries};for(const value of values){if(keys.has(value)){delete newEntries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})}});function _enum2(values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params);inst.values=new Set(def.values);Object.defineProperty(inst,"value",{get(){if(def.values.length>1){throw new Error("This schema contains multiple valid literal values. Use `.values` instead.")}return def.values[0]}})});function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}var ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params);inst.min=(size,params)=>inst.check(_minSize(size,params));inst.max=(size,params)=>inst.check(_maxSize(size,params));inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});function file(params){return _file(ZodFile,params)}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer();$ZodTransform.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params);inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward"){throw new $ZodEncodeError(inst.constructor.name)}payload.addIssue=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");if(!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=inst);payload.issues.push(issue(_issue))}};const output=def.transform(payload.value,payload);if(output instanceof Promise){return output.then((output)=>{payload.value=output;return payload})}payload.value=output;return payload}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeDefault=inst.unwrap});function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...normalizeParams(params)})}var ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function success(innerType){return new ZodSuccess({type:"success",innerType})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeCatch=inst.unwrap});function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}var ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});function nan(params){return _nan(ZodNaN,params)}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params);inst.in=def.in;inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def);$ZodCodec.init(inst,def)});function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){const def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def);$ZodPreprocess.init(inst,def)});var ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...normalizeParams(params)})}var ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.getter()});function lazy(getter){return new ZodLazy({type:"lazy",getter})}var ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function promise(innerType){return new ZodPromise({type:"promise",innerType})}var ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});function check(fn){const ch=new $ZodCheck({check:"custom"});ch._zod.check=fn;return ch}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>true),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}var describe2=describe;var meta2=meta;var ZodInstanceOf=$constructor("ZodInstanceOf",(inst,def)=>{ZodCustom.init(inst,def)},{properties(shape,params){return this.check(_properties(shape,params))}});function _instanceof(cls,params={}){const inst=new ZodInstanceOf({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:true,...normalizeParams(params)});inst._zod.bag.Class=cls;inst._zod.check=(payload)=>{if(!(payload.value instanceof cls)){payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})}};return inst}var stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args);function json(params){const jsonSchema=lazy(()=>{return union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function setErrorMap(map){config({customError:map})}function getErrorMap(){return config().customError}var ZodFirstPartyTypeKind;(function(ZodFirstPartyTypeKind){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date3(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var z={...exports_schemas2,...exports_checks2,iso:exports_iso};var RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function detectVersion(schema,defaultTarget){const $schema=schema.$schema;if($schema==="https://json-schema.org/draft/2020-12/schema"){return"draft-2020-12"}if($schema==="http://json-schema.org/draft-07/schema#"){return"draft-7"}if($schema==="http://json-schema.org/draft-04/schema#"){return"draft-4"}return defaultTarget??"draft-2020-12"}function applyMinItems(items,minItems){return items.map((item,index)=>index<minItems?item:item.optional())}function decodeJSONPointerSegment(segment){return segment.replace(/~1/g,"/").replace(/~0/g,"~")}function resolveRef(ref,ctx){if(!ref.startsWith("#")){throw new Error("External $ref is not supported, only local refs (#/...) are allowed")}const path=ref.slice(1).split("/").filter(Boolean);if(path.length===0){return ctx.rootSchema}const defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path[0]===defsKey){const key=path[1]===undefined?undefined:decodeJSONPointerSegment(path[1]);if(!key||!ctx.defs[key]){throw new Error(`Reference not found: ${ref}`)}return ctx.defs[key]}throw new Error(`Reference not found: ${ref}`)}function checkObjectGuards(objectSchema,guards){const guard=z.transform((value)=>value).check((payload)=>{const value=payload.value;if(typeof value!=="object"||value===null||Array.isArray(value))return;const keys=Object.getOwnPropertyNames(value);if(guards.minProperties!==undefined&&keys.length<guards.minProperties){payload.issues.push({origin:"object",code:"too_small",minimum:guards.minProperties,inclusive:true,message:`Too small: expected object to have >=${guards.minProperties} properties`,input:value,inst:objectSchema,continue:true})}if(guards.maxProperties!==undefined&&keys.length>guards.maxProperties){payload.issues.push({origin:"object",code:"too_big",maximum:guards.maxProperties,inclusive:true,message:`Too big: expected object to have <=${guards.maxProperties} properties`,input:value,inst:objectSchema,continue:true})}if(guards.keySchema){for(const key of keys){const result=guards.keySchema.safeParse(key);if(result.success)continue;payload.issues.push({code:"invalid_key",origin:"record",issues:result.error.issues,input:key,path:[key],continue:true})}}});return guard.pipe(objectSchema)}function canonicalKey(value,seen){if(value===null)return"z";const type=typeof value;if(type!=="object"){if(type==="number"&&Number.isNaN(value))return null;const raw=String(value);return`${type[0]}${raw.length}:${raw}`}if(seen.has(value))return null;seen.add(value);try{if(Array.isArray(value)){const parts=[];for(const item of value){const key=canonicalKey(item,seen);if(key===null)return null;parts.push(key)}return`a${parts.length}:[${parts.join(",")}]`}const keys=Object.keys(value).sort();const parts=[];for(const k of keys){const key=canonicalKey(value[k],seen);if(key===null)return null;parts.push(`${k.length}:${k}=${key}`)}return`o${parts.length}:{${parts.join(",")}}`}finally{seen.delete(value)}}var SCHEMA_KEYWORDS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]);var SCHEMA_MAP_KEYWORDS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function containsRef(value){if(typeof value!=="object"||value===null)return false;if(Array.isArray(value))return value.some(containsRef);if(typeof value.$ref==="string")return true;return Object.entries(value).some(([key,sub])=>{if(SCHEMA_KEYWORDS.has(key))return containsRef(sub);if(!SCHEMA_MAP_KEYWORDS.has(key)||typeof sub!=="object"||sub===null)return false;return Object.values(sub).some(containsRef)})}function plural(n){return n===1?"element":"elements"}function checkArrayGuards(arraySchema,guards){const guard=z.transform((value)=>value).check((payload)=>{const items=payload.value;if(!Array.isArray(items))return;if(guards.uniqueItems===true){const firstSeen=new Map;for(let i=0;i<items.length;i++){const key=canonicalKey(items[i],new Set);if(key===null)continue;const first=firstSeen.get(key);if(first===undefined){firstSeen.set(key,i);continue}payload.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${first}`,input:items,path:[i],continue:true})}}if(guards.containsSchema){const minContains=guards.minContains??1;const ceiling=guards.maxContains!==undefined?guards.maxContains+1:Number.POSITIVE_INFINITY;let matches=0;for(const item of items){if(guards.containsSchema.safeParse(item).success&&++matches>=ceiling)break}if(matches<minContains){payload.issues.push({code:"custom",message:`Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,input:items,continue:true})}if(guards.maxContains!==undefined&&matches>guards.maxContains){payload.issues.push({code:"custom",message:`Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,input:items,continue:true})}}});return guard.pipe(arraySchema)}function getTupleRest(restSchema,ctx){if(restSchema===false){return}if(restSchema===undefined||restSchema===true){return z.any()}return convertSchema(restSchema,ctx)}var fullTime=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function convertBaseSchema(schema,ctx){if(schema.not!==undefined){if(typeof schema.not==="object"&&Object.keys(schema.not).length===0){return z.never()}throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==undefined){throw new Error("unevaluatedItems is not supported")}if(schema.unevaluatedProperties!==undefined){throw new Error("unevaluatedProperties is not supported")}if(schema.if!==undefined||schema.then!==undefined||schema.else!==undefined){throw new Error("Conditional schemas (if/then/else) are not supported")}if(schema.dependentSchemas!==undefined||schema.dependentRequired!==undefined){throw new Error("dependentSchemas and dependentRequired are not supported")}if(schema.$ref){const refPath=schema.$ref;if(ctx.refs.has(refPath)){return ctx.refs.get(refPath)}if(ctx.processing.has(refPath)){return z.lazy(()=>{if(!ctx.refs.has(refPath)){throw new Error(`Circular reference not resolved: ${refPath}`)}return ctx.refs.get(refPath)})}ctx.processing.add(refPath);const resolved=resolveRef(refPath,ctx);const zodSchema=convertSchema(resolved,ctx);ctx.refs.set(refPath,zodSchema);ctx.processing.delete(refPath);return zodSchema}if(schema.enum!==undefined){const enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===true&&enumValues.length===1&&enumValues[0]===null){return z.null()}if(enumValues.length===0){return z.never()}if(enumValues.length===1){return z.literal(enumValues[0])}if(enumValues.every((v)=>typeof v==="string")){return z.enum(enumValues)}const literalSchemas=enumValues.map((v)=>z.literal(v));if(literalSchemas.length<2){return literalSchemas[0]}return z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==undefined){return z.literal(schema.const)}const type=schema.type;if(Array.isArray(type)){const typeSchemas=type.map((t)=>{const typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});if(typeSchemas.length===0){return z.never()}if(typeSchemas.length===1){return typeSchemas[0]}return z.union(typeSchemas)}if(!type){return z.any()}let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){const format=schema.format;if(format==="email"){stringSchema=stringSchema.check(z.email())}else if(format==="uri"||format==="uri-reference"){stringSchema=stringSchema.check(z.url())}else if(format==="uuid"||format==="guid"){stringSchema=stringSchema.check(z.uuid())}else if(format==="date-time"){stringSchema=stringSchema.check(z.iso.datetime({offset:true}))}else if(format==="date"){stringSchema=stringSchema.check(z.iso.date())}else if(format==="time"){stringSchema=stringSchema.check(z.regex(fullTime))}else if(format==="duration"){stringSchema=stringSchema.check(z.iso.duration())}else if(format==="hostname"){stringSchema=stringSchema.check(z.hostname())}else if(format==="ipv4"){stringSchema=stringSchema.check(z.ipv4())}else if(format==="ipv6"){stringSchema=stringSchema.check(z.ipv6())}else if(format==="mac"){stringSchema=stringSchema.check(z.mac())}else if(format==="cidr"){stringSchema=stringSchema.check(z.cidrv4())}else if(format==="cidr-v6"){stringSchema=stringSchema.check(z.cidrv6())}else if(format==="base64"){stringSchema=stringSchema.check(z.base64())}else if(format==="base64url"){stringSchema=stringSchema.check(z.base64url())}else if(format==="e164"){stringSchema=stringSchema.check(z.e164())}else if(format==="credit_card"){stringSchema=stringSchema.check(z.creditCard())}else if(format==="iban"){stringSchema=stringSchema.check(z.iban())}else if(format==="jwt"){stringSchema=stringSchema.check(z.jwt())}else if(format==="emoji"){stringSchema=stringSchema.check(z.emoji())}else if(format==="nanoid"){stringSchema=stringSchema.check(z.nanoid())}else if(format==="cuid"){stringSchema=stringSchema.check(z.cuid())}else if(format==="cuid2"){stringSchema=stringSchema.check(z.cuid2())}else if(format==="ulid"){stringSchema=stringSchema.check(z.ulid())}else if(format==="xid"){stringSchema=stringSchema.check(z.xid())}else if(format==="ksuid"){stringSchema=stringSchema.check(z.ksuid())}}if(typeof schema.minLength==="number"){stringSchema=stringSchema.min(schema.minLength)}if(typeof schema.maxLength==="number"){stringSchema=stringSchema.max(schema.maxLength)}if(schema.pattern){stringSchema=stringSchema.regex(new RegExp(schema.pattern))}zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();if(typeof schema.minimum==="number"&&schema.exclusiveMinimum!==true){numberSchema=numberSchema.min(schema.minimum)}if(typeof schema.maximum==="number"&&schema.exclusiveMaximum!==true){numberSchema=numberSchema.max(schema.maximum)}if(typeof schema.exclusiveMinimum==="number"){numberSchema=numberSchema.gt(schema.exclusiveMinimum)}else if(schema.exclusiveMinimum===true&&typeof schema.minimum==="number"){numberSchema=numberSchema.gt(schema.minimum)}if(typeof schema.exclusiveMaximum==="number"){numberSchema=numberSchema.lt(schema.exclusiveMaximum)}else if(schema.exclusiveMaximum===true&&typeof schema.maximum==="number"){numberSchema=numberSchema.lt(schema.maximum)}if(typeof schema.multipleOf==="number"){numberSchema=numberSchema.multipleOf(schema.multipleOf)}zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{const shape={};const properties=schema.properties||{};const requiredSet=new Set(schema.required||[]);const additionalSchema=typeof schema.additionalProperties==="object"?convertSchema(schema.additionalProperties,ctx):undefined;for(const[key,propSchema]of Object.entries(properties)){const propZodSchema=convertSchema(propSchema,ctx);assignProp(shape,key,requiredSet.has(key)?propZodSchema:propZodSchema.optional())}if(schema.patternProperties){const patternProps=schema.patternProperties;const patternKeys=Object.keys(patternProps);const looseRecords=[];for(const pattern of patternKeys){const patternValue=convertSchema(patternProps[pattern],ctx);const keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}const schemasToIntersect=[];if(Object.keys(shape).length>0){schemasToIntersect.push(z.object(shape).passthrough())}schemasToIntersect.push(...looseRecords);if(schemasToIntersect.length===0){zodSchema=z.object({}).passthrough()}else if(schemasToIntersect.length===1){zodSchema=schemasToIntersect[0]}else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++){result=z.intersection(result,schemasToIntersect[i])}zodSchema=result}if(schema.additionalProperties===false){const propertyKeys=Object.keys(shape);const patterns=patternKeys.map((p)=>new RegExp(p));const basePatternSchema=zodSchema;zodSchema=zodSchema.check((payload)=>{if(!isPlainObject(payload.value))return;const unrecognized=[];for(const key of Object.keys(payload.value)){if(propertyKeys.includes(key))continue;if(patterns.some((regex)=>regex.test(key)))continue;unrecognized.push(key)}if(unrecognized.length){payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input:payload.value,inst:basePatternSchema})}})}}else{const objectSchema=z.object(shape);if(schema.additionalProperties===false){zodSchema=objectSchema.strict()}else if(additionalSchema){zodSchema=objectSchema.catchall(additionalSchema)}else{zodSchema=objectSchema.passthrough()}}const hasKeyGuard=schema.propertyNames!==undefined&&schema.propertyNames!==true;const minProperties=typeof schema.minProperties==="number"?schema.minProperties:undefined;const maxProperties=typeof schema.maxProperties==="number"?schema.maxProperties:undefined;if(hasKeyGuard||minProperties!==undefined||maxProperties!==undefined){let keySchema;if(hasKeyGuard){const keyJSONSchema=typeof schema.propertyNames==="object"&&schema.propertyNames.type===undefined?{type:"string",...schema.propertyNames}:schema.propertyNames;keySchema=convertSchema(keyJSONSchema,ctx)}zodSchema=checkObjectGuards(zodSchema,{keySchema,minProperties,maxProperties})}break}case"array":{const prefixItems=schema.prefixItems;const items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){const minItems=typeof schema.minItems==="number"?schema.minItems:0;const tupleItems=prefixItems.map((item)=>convertSchema(item,ctx));const positionalItems=applyMinItems(tupleItems,minItems);const rest=!Array.isArray(items)?getTupleRest(items,ctx):undefined;const tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema;if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(Array.isArray(items)){const minItems=typeof schema.minItems==="number"?schema.minItems:0;const tupleItems=items.map((item)=>convertSchema(item,ctx));const positionalItems=applyMinItems(tupleItems,minItems);const rest=getTupleRest(schema.additionalItems,ctx);const tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema;if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(items!==undefined){const element=convertSchema(items,ctx);let arraySchema=z.array(element);if(typeof schema.minItems==="number"){arraySchema=arraySchema.min(schema.minItems)}if(typeof schema.maxItems==="number"){arraySchema=arraySchema.max(schema.maxItems)}zodSchema=arraySchema}else{zodSchema=z.array(z.any())}if(schema.uniqueItems===true||schema.contains!==undefined){zodSchema=checkArrayGuards(zodSchema,{uniqueItems:schema.uniqueItems===true,containsSchema:schema.contains!==undefined?convertSchema(schema.contains,ctx):undefined,minContains:typeof schema.minContains==="number"?schema.minContains:undefined,maxContains:typeof schema.maxContains==="number"?schema.maxContains:undefined})}break}default:throw new Error(`Unsupported type: ${type}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema==="boolean"){return schema?z.any():z.never()}let baseSchema=convertBaseSchema(schema,ctx);const hasExplicitType=schema.type||schema.enum!==undefined||schema.const!==undefined;if(schema.anyOf&&Array.isArray(schema.anyOf)){const options=schema.anyOf.map((s)=>convertSchema(s,ctx));const anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){const options=schema.oneOf.map((s)=>convertSchema(s,ctx));const oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf)){if(schema.allOf.length===0){baseSchema=hasExplicitType?baseSchema:z.any()}else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx);const startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++){result=z.intersection(result,convertSchema(schema.allOf[i],ctx))}baseSchema=result}}if(schema.nullable===true&&ctx.version==="openapi-3.0"){baseSchema=z.nullable(baseSchema)}if(schema.readOnly===true){baseSchema=z.readonly(baseSchema)}if(schema.default!==undefined){baseSchema=baseSchema.default(schema.default)}const extraMeta={};const coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const key of coreMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}const contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(const key of contentMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}if(schema.type==="object"&&schema.$ref===undefined){if(schema.propertyNames!==undefined&&!containsRef(schema.propertyNames)){extraMeta.propertyNames=schema.propertyNames}for(const key of["minProperties","maxProperties"]){if(schema[key]!==undefined)extraMeta[key]=schema[key]}}if(schema.type==="array"&&schema.$ref===undefined){if(schema.contains!==undefined&&!containsRef(schema.contains)){extraMeta.contains=schema.contains}for(const key of["uniqueItems","minContains","maxContains"]){if(schema[key]!==undefined)extraMeta[key]=schema[key]}}for(const key of Object.keys(schema)){if(!RECOGNIZED_KEYS.has(key)){assignProp(extraMeta,key,schema[key])}}if(Object.keys(extraMeta).length>0){ctx.registry.add(baseSchema,extraMeta)}if(schema.description){baseSchema=baseSchema.describe(schema.description)}return baseSchema}function fromJSONSchema(schema,params){if(typeof schema==="boolean"){return schema?z.any():z.never()}let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}const version=detectVersion(normalized,params?.defaultTarget);const defs=normalized.$defs||normalized.definitions||{};const ctx={version,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var RESOLVING=Symbol("z.visit/resolving");function visit(schema,fnOrHandlers){const fn=typeof fnOrHandlers==="function"?fnOrHandlers:(node,rewritten)=>{const h=fnOrHandlers[node._zod.def.type];return h?h(node,rewritten):node};const cache=new Map;function run(s){const cached=cache.get(s);if(cached===RESOLVING){return new $ZodLazy({type:"lazy",getter:()=>cache.get(s)})}if(cached!==undefined)return cached;cache.set(s,RESOLVING);const inner=mapInner(s);const mapped=fn(inner,inner!==s);cache.set(s,mapped);return mapped}function mapInner(s){const def=s._zod.def;const kind=def.type;switch(kind){case"object":{const oldShape=def.shape;const keys=Object.keys(oldShape);let changed=false;const newShape={};for(const k of keys){const mapped=run(oldShape[k]);if(mapped!==oldShape[k])changed=true;newShape[k]=mapped}let newCatchall=def.catchall;if(def.catchall){newCatchall=run(def.catchall);if(newCatchall!==def.catchall)changed=true}return changed?clone(s,{...def,shape:newShape,catchall:newCatchall}):s}case"array":{const mapped=run(def.element);return mapped===def.element?s:clone(s,{...def,element:mapped})}case"tuple":{const oldItems=def.items;let changed=false;const newItems=[];for(const item of oldItems){const mapped=run(item);if(mapped!==item)changed=true;newItems.push(mapped)}let newRest=def.rest;if(def.rest){newRest=run(def.rest);if(newRest!==def.rest)changed=true}return changed?clone(s,{...def,items:newItems,rest:newRest}):s}case"record":case"map":{const newKey=run(def.keyType);const newVal=run(def.valueType);return newKey===def.keyType&&newVal===def.valueType?s:clone(s,{...def,keyType:newKey,valueType:newVal})}case"set":{const newVal=run(def.valueType);return newVal===def.valueType?s:clone(s,{...def,valueType:newVal})}case"union":{const oldOptions=def.options;let changed=false;const newOptions=[];for(const opt of oldOptions){const mapped=run(opt);if(mapped!==opt)changed=true;newOptions.push(mapped)}return changed?clone(s,{...def,options:newOptions}):s}case"intersection":{const newLeft=run(def.left);const newRight=run(def.right);return newLeft===def.left&&newRight===def.right?s:clone(s,{...def,left:newLeft,right:newRight})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{const newInner=run(def.innerType);return newInner===def.innerType?s:clone(s,{...def,innerType:newInner})}case"pipe":{const newIn=run(def.in);const newOut=run(def.out);return newIn===def.in&&newOut===def.out?s:clone(s,{...def,in:newIn,out:newOut})}case"function":{const newInput=run(def.input);const newOutput=run(def.output);return newInput===def.input&&newOutput===def.output?s:clone(s,{...def,input:newInput,output:newOutput})}case"lazy":{const original=def.getter;const{_cachedInner,...rest}=def;return clone(s,{...rest,getter:()=>run(original())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:{return s}}}return run(schema)}function deepPartial(schema){return visit(schema,{object:(s)=>s.partial(),union:(s)=>{const def=s._zod.def;return def.discriminator===undefined?s:union(def.options)}})}function withChecks(side,checks){if(!checks?.length)return side;const def=side._zod.def;return clone(side,mergeDefs(def,{checks:[...def.checks??[],...checks]}),{parent:true})}function outSide(def){return withChecks(def.out,def.checks)}function inSide(def){return def.in._zod.traits.has("$ZodTransform")?outSide(def):def.in}function input(schema){return visit(schema,{pipe:(s)=>inSide(s._zod.def),default:(s,rewritten)=>rewritten?optional(s._zod.def.innerType):s,catch:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function output(schema){return visit(schema,{pipe:(s)=>outSide(s._zod.def),prefault:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}import path from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{createReadStream}from"node:fs";import{tmpdir}from"node:os";import{readFileSync}from"node:fs";var pageBundle=readFileSync(new URL("./page-bundle.js",import.meta.url),"utf8");init_internal_capability();var __defProp2=Object.defineProperty;var __exportAll=(definitions,namespace)=>{const exports={};for(const name in definitions)__defProp2(exports,name,{get:definitions[name],enumerable:true});if(!namespace)__defProp2(exports,Symbol.toStringTag,{value:"Module"});return exports};var __esmMin=(factory,value,error)=>()=>{if(error)throw error[0];try{return factory&&(value=factory(factory=0)),value}catch(caught){error=[caught];throw caught}};if(!Promise.withResolvers){Promise.withResolvers=()=>{let resolve,reject;const promise=new Promise((res,rej)=>{resolve=res;reject=rej});return{promise,resolve,reject}}}class Emittery{#listeners=new Map;on(name,listener){const listeners=this.#listeners.get(name)??new Set;listeners.add(listener);this.#listeners.set(name,listeners);return()=>{listeners.delete(listener)}}async emit(name,data){const event={data,eventName:name};await Promise.all([...this.#listeners.get(name)??[]].map((listener)=>listener(event)))}clearListeners(){this.#listeners.clear()}}var{object:object2,string:string$2,number:number$2,array:array2,union:union$1,unknown:unknown$1,null:_null4}=exports_zod;var OMOWRIGHT_BROWSER_CDP_HOST="127.0.0.1:9222";var SESSION_ARTIFACTS_DIR=path.join(tmpdir(),"omowright-artifacts");var noop=()=>{};var init_emittery=noop;var init_zod=noop;var init_context=noop;var init_utils$13=noop;var init_config=noop;var init_extension_bridge=noop;var init_commands$1=noop;var init_directory=noop;var init_process=noop;var init_event_bus=noop;var init_state_db=noop;var init_schema=noop;var init_store$1=noop;var init_drizzle_orm=noop;var init_types$8=noop;var init_agent_session_server=noop;var init_nanoid=noop;function sleep$12(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted)return reject(signal.reason??Error("Aborted"));const onAbort=()=>{clearTimeout(timer);reject(signal.reason??Error("Aborted"))};const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);signal?.addEventListener("abort",onAbort,{once:true})})}function getCurrentReplAbortSignal(){return}function getCurrentReplToolCallId(){return}function hasActiveReplContext(){return false}function withCurrentReplAbort(fn){return fn()}function withoutReplContext(fn){return fn()}function replPrint(...values){console.warn(...values)}async function sendCommandToExtension(command){throw new UnsupportedOperationError(`Extension command is unavailable: ${command.method}`)}class UnsupportedOperationError extends Error{constructor(message){super(message);this.name="UnsupportedOperationError"}}function nanoid3(){return crypto.randomUUID()}var EventBus={emit:async()=>{}};var SessionStore={get:()=>{return},update:()=>{return}};var stateDb=()=>{throw new UnsupportedOperationError("Daemon persistence is unavailable")};var NotificationGrantTable={};function resolveSessionPath(_session,value){return path.resolve(String(value))}function getSessionStorageDir(){return process.cwd()}function getSharedSessionStorageDir(){return process.cwd()}function spawnCommand(){throw new UnsupportedOperationError("Video recording is unavailable")}async function waitForExitCode(){return 1}function isWebSocketUrl(xn){return xn.startsWith(`ws://`)||xn.startsWith(`wss://`)}function isAuthorizationError(xn){let jn=xn instanceof Error?xn.message:String(xn),Vn=xn;return jn.includes(`401`)||jn.includes(`403`)||jn.includes(`Missing or invalid Authorization header.`)||jn.includes(`Unauthorized`)||jn.includes(`Forbidden`)||typeof Vn.status==`number`&&(Vn.status===401||Vn.status===403)||typeof Vn.response?.status==`number`&&(Vn.response.status===401||Vn.response.status===403)||typeof Vn.error?.status==`number`&&(Vn.error.status===401||Vn.error.status===403)||typeof Vn.cause?.status==`number`&&(Vn.cause.status===401||Vn.cause.status===403)||String(Vn.error?.message??``).includes(`Missing or invalid Authorization header.`)||String(Vn.cause?.message??``).includes(`Missing or invalid Authorization header.`)}function normalizeBaseUrl(xn){return xn.replace(/\/$/,``)}function createAbortError$1(){let xn=Error(`Operation aborted`);return xn.name=`AbortError`,xn}var DEFAULT_COMMAND_TIMEOUT_MS;var DEFAULT_RECONNECT_DELAYS_MS;var jsonVersionSchema;var jsonTargetSchema;var cdpWireMessageSchema;var BrowserCdpCommandError;var CdpClient;var init_client$6=__esmMin(()=>{init_emittery(),init_zod(),init_context(),init_utils$13(),init_config(),init_extension_bridge(),init_commands$1(),DEFAULT_COMMAND_TIMEOUT_MS=30000,DEFAULT_RECONNECT_DELAYS_MS=[0,250,750,1500,3000],jsonVersionSchema=object2({Browser:string$2().optional(),"Protocol-Version":string$2().optional(),"User-Agent":string$2().optional(),"V8-Version":string$2().optional(),"WebKit-Version":string$2().optional(),webSocketDebuggerUrl:string$2()}).loose(),jsonTargetSchema=object2({description:string$2().optional(),devtoolsFrontendUrl:string$2().optional(),faviconUrl:string$2().optional(),id:string$2(),parentId:string$2().optional(),title:string$2().default(``),type:string$2(),url:string$2().default(``),webSocketDebuggerUrl:string$2().optional()}).loose(),cdpWireMessageSchema=union$1([object2({id:number$2(),sessionId:string$2().optional(),error:object2({code:number$2().optional(),data:unknown$1().optional(),message:string$2()}).loose().optional(),result:unknown$1().optional()}).loose(),object2({method:string$2(),params:unknown$1().optional(),sessionId:string$2().optional()}).loose(),_null4()]),BrowserCdpCommandError=class extends Error{method;code;data;constructor(xn,jn,Vn,qn){super(qn??`CDP command failed: ${xn}`),this.method=xn,this.code=jn,this.data=Vn}},CdpClient=class{cdpUrl;logId;#e;#t;#n;#r=null;#i=null;#a=null;#o=false;#s=1;#c=new Map;#l=new Emittery;#u=false;transportEvents=new Emittery;constructor(xn={}){this.cdpUrl=normalizeBaseUrl(xn.cdpUrl??`http://${OMOWRIGHT_BROWSER_CDP_HOST}`),this.logId=xn.logId??`cdp-${Date.now()}`,this.#e=xn.authorizer,this.#t=xn.commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS,this.#n=xn.reconnectDelaysMs??DEFAULT_RECONNECT_DELAYS_MS}get isConnected(){return this.#r?.readyState===wrapper_default.OPEN}start(){this.#o||(this.#o=true,this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] Initial CDP connect failed`,xn),this.#b()}))}async discoverVersion(xn={}){return await this.#f(this.#d(`/json/version`),jsonVersionSchema,xn)}async discoverTargets(xn={}){return await this.#f(this.#d(`/json/list`),array2(jsonTargetSchema),xn)}async ensureConnected(){if(this.#o=true,this.isConnected)return;if(this.#i){await this.#i;return}let xn=this.#g();this.#i=xn;try{await xn}finally{this.#i===xn&&(this.#i=null)}}async send(xn,jn,Vn,qn={}){if(xn===`Target.createTarget`&&qn.capability!==targetCreationCapability)throw Error(`Target.createTarget is reserved for createAgentTabs`);let Jn=getCurrentReplAbortSignal();if(Jn?.aborted)throw createAbortError$1();if(xn.startsWith(`OmO.`)){let Vn=await sendCommandToExtension({method:xn,params:jn},{...qn.extensionBridge,signal:Jn});if(Jn?.aborted)throw createAbortError$1();return Vn}await this.ensureConnected();let Yn=this.#r;if(!Yn||Yn.readyState!==wrapper_default.OPEN)throw Error(`CDP websocket is not connected`);let Zn=this.#s++,Qn={id:Zn,method:xn};jn!==undefined&&(Qn.params=jn),Vn&&(Qn.sessionId=Vn);let{promise:ei,reject:ti,resolve:ni}=Promise.withResolvers(),ri=qn.timeoutMs??this.#t,ii=ri>0?setTimeout(()=>{this.#c.delete(Zn),ti(Error(`CDP command timeout: ${String(xn)}`))},ri):undefined,ai=Jn?()=>{ii&&clearTimeout(ii),this.#c.delete(Zn),ti(createAbortError$1())}:undefined;if(this.#c.set(Zn,{method:String(xn),reject:ti,resolve:ni,timeout:ii}),Jn?.addEventListener(`abort`,ai,{once:true}),Jn?.aborted)return ai?.(),await ei;try{Yn.send(JSON.stringify(Qn))}catch(xn){throw ii&&clearTimeout(ii),this.#c.delete(Zn),ai&&Jn?.removeEventListener(`abort`,ai),xn instanceof Error?xn:Error(String(xn))}try{return await ei}finally{ai&&Jn?.removeEventListener(`abort`,ai)}}on(xn,jn){return this.#l.on(xn,({data:xn})=>jn(xn.payload,xn.meta))}async close(){this.#o=false,this.#a&&=(clearTimeout(this.#a),null);let xn=this.#r;if(this.#r=null,this.#x(Error(`CDP client closed`)),xn&&xn.readyState<=wrapper_default.OPEN)try{xn.close(1000,`client closing`)}catch{}}#d(xn){let jn=new URL(this.cdpUrl);return isWebSocketUrl(this.cdpUrl)?(jn.protocol=jn.protocol===`wss:`?`https:`:`http:`,jn.pathname=xn,jn.search=``,jn.toString()):(jn.pathname=xn,jn.search=``,jn.toString())}async#f(xn,jn,Vn={}){let qn=await this.#p(Vn),Jn=await fetch(xn,{headers:qn});if((Jn.status===401||Jn.status===403)&&this.#e&&!Vn.forceRefresh)return await this.#f(xn,jn,{forceRefresh:true});if(!Jn.ok)throw Error(`CDP discovery request failed (${Jn.status} ${Jn.statusText})`);return jn.parse(await Jn.json())}async#p(xn={}){return this.#e?{Authorization:await this.#e.resolveAuthorization(xn)}:{}}async#m(xn={}){let jn=await this.#p(xn);return isWebSocketUrl(this.cdpUrl)?{headers:jn,wsUrl:this.cdpUrl}:{headers:jn,wsUrl:(await this.discoverVersion(xn)).webSocketDebuggerUrl}}#h(){return this.cdpUrl!==`http://${OMOWRIGHT_BROWSER_CDP_HOST}`}async#g(){let xn=null,jn=false;for(let Vn of this.#n){Vn>0&&await sleep$12(Vn);try{await this.#_({forceRefresh:jn});return}catch(Vn){let qn=Vn??Error(`Unknown error`);xn=qn,isAuthorizationError(qn)&&(jn=true)}}throw xn instanceof Error?xn:Error(String(xn??`Failed to connect CDP websocket`))}async#_(xn={}){let{headers:jn,wsUrl:Vn}=await this.#m(xn);await new Promise((xn,qn)=>{let Jn=new wrapper_default(Vn,{headers:jn}),Yn=false,Zn=(xn)=>{Yn||(Yn=true,qn(xn))};Jn.addEventListener(`open`,()=>{Yn||(Yn=true,this.#v(Jn),xn())}),Jn.addEventListener(`message`,(xn)=>{this.#r===Jn&&this.#S(xn.data).catch(()=>{})}),Jn.addEventListener(`close`,(xn)=>{this.#r===Jn&&this.#y(Jn),Yn||Zn(Error(`CDP websocket closed during connect (${xn.code} ${xn.reason||`no reason`})`))}),Jn.addEventListener(`error`,()=>{Zn(Error(`Failed to connect CDP websocket: ${Vn}`))})})}#v(xn){this.#a&&=(clearTimeout(this.#a),null);let jn=this.#r;if(this.#r=xn,this.send(`Target.setDiscoverTargets`,{discover:true}).catch(()=>{}),this.transportEvents.emit(this.#u?`reconnected`:`connected`).catch((xn)=>{console.warn(`[${this.logId}] CDP transport listener failed`,xn)}),this.#u=true,jn&&jn!==xn&&jn.readyState<=wrapper_default.OPEN)try{jn.close(1000,`replaced`)}catch{}}#y(xn){this.#r===xn&&(this.#r=null,this.#x(Error(`CDP websocket disconnected`)),this.transportEvents.emit(`disconnected`).catch((xn)=>{console.warn(`[${this.logId}] CDP disconnect listener failed`,xn)}),this.#o&&this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] CDP reconnect failed`,xn),this.#b()}))}#b(){if(!this.#o||this.isConnected||this.#i||this.#a)return;let xn=this.#n[this.#n.length-1]??3000;this.#a=setTimeout(()=>{this.#a=null,this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] Scheduled CDP reconnect failed`,xn),this.#b()})},xn)}#x(xn){for(let jn of this.#c.values())jn.timeout&&clearTimeout(jn.timeout),jn.reject(xn);this.#c.clear()}async#S(xn){let jn=typeof xn==`string`?xn:xn instanceof Blob?await xn.text():new TextDecoder().decode(xn),{data:Vn}=cdpWireMessageSchema.safeParse(JSON.parse(jn));if(Vn){if(typeof Vn.id==`number`){let xn=this.#c.get(Vn.id);if(!xn)return;if(this.#c.delete(Vn.id),xn.timeout&&clearTimeout(xn.timeout),Vn.error){let jn=Vn.error;xn.reject(new BrowserCdpCommandError(xn.method,jn.code,jn.data,jn.message??`CDP command failed: ${xn.method}`));return}xn.resolve(Vn.result);return}if(typeof Vn.method==`string`){let xn=Vn.method;if(xn===`Page.javascriptDialogOpening`&&Vn.sessionId){let xn=this.#r;xn?.readyState===wrapper_default.OPEN&&xn.send(JSON.stringify({id:this.#s++,method:`Page.handleJavaScriptDialog`,params:{accept:true},sessionId:Vn.sessionId}))}let jn={payload:Vn.params,meta:{sessionId:Vn.sessionId}};this.#l.emit(xn,jn).catch((jn)=>{console.warn(`[${this.logId}] CDP event listener failed for ${xn}`,jn)})}}}}});var SessionManager;var init_session_manager=__esmMin(()=>{init_client$6(),SessionManager=class{#e;#t=new Map;#n=new Map;#r=new Map;#i=new Set;#a;constructor(xn){this.#e=xn,this.#a=[this.#e.on(`Target.attachedToTarget`,(xn)=>{let jn=xn.targetInfo.targetId;jn&&this.#s(jn,xn.sessionId)}),this.#e.on(`Target.detachedFromTarget`,(xn)=>{let jn=xn.targetId??this.#n.get(xn.sessionId);this.#n.delete(xn.sessionId),jn&&this.#t.get(jn)===xn.sessionId&&this.#t.delete(jn)})]}clear(){this.#t.clear(),this.#n.clear(),this.#r.clear()}async dispose(){for(let xn of this.#a)xn();await Promise.allSettled([...this.#i].map((xn)=>this.#e.send(`Target.detachFromTarget`,{sessionId:xn}).catch(()=>{}))),this.#i.clear(),this.clear()}async discoverTargets(){return await this.#e.discoverTargets()}async getPageTarget(xn){return(await this.discoverTargets()).find((jn)=>jn.id===xn&&jn.type===`page`)??null}hasTargetSession(xn,jn){return this.#t.get(xn)===jn}getTargetSession(xn){return this.#t.get(xn)}async resolvePageSession(xn,jn){if(jn&&this.hasTargetSession(xn,jn))return jn;let Vn=this.#t.get(xn);if(Vn)return Vn;let qn=this.#r.get(xn);if(qn)return await qn;let Jn=this.#o(xn).finally(()=>{this.#r.delete(xn)});return this.#r.set(xn,Jn),await Jn}async#o(xn){if(!await this.getPageTarget(xn))throw Error(`Tab ${xn} is no longer available.`);let jn=await this.#e.send(`Target.attachToTarget`,{targetId:xn,flatten:true});return this.#i.add(jn.sessionId),this.#s(xn,jn.sessionId),jn.sessionId}#s(xn,jn){this.#t.set(xn,jn),this.#n.set(jn,xn)}}});var globalCdpClient;var init_cdp=__esmMin(()=>{init_client$6(),init_session_manager(),globalCdpClient=new CdpClient});var BUNDLE$1;var init_omowright_world_bundle=__esmMin(()=>{BUNDLE$1=pageBundle});var MAX_BUFFER_SIZE;var CONSOLE_INTERCEPTOR_SCRIPT;var PageConsole;var init_console_capture=__esmMin(()=>{MAX_BUFFER_SIZE=1000,CONSOLE_INTERCEPTOR_SCRIPT=`(function(){
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 generateArrayCheck(doc,ctx,schema,accessor,buildsValue=true){const def=schema._zod.def;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);const outputVar=buildsValue?newVar(ctx):null;const iVar=newVar(ctx);const elemVar=newVar(ctx);if(outputVar)doc.write(`const ${outputVar} = new Array(${accessor}.length);`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${accessor}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);const elemOutput=compileChild(d,ctx,def.element,elemVar,buildsValue);if(outputVar&&elemOutput!==null)d.write(`${outputVar}[${iVar}] = ${elemOutput};`)});doc.write(`}`);return outputVar}function generateLiteralCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const values=def.values;if(values.length!==1){const literalSet=addConstant(ctx,new Set(values));doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);return accessor}const value=values[0];if(typeof value==="number"&&Number.isNaN(value)){const literalSet=addConstant(ctx,new Set(values));doc.write(`if (!${literalSet}.has(${accessor})) return INVALID;`);return accessor}if(typeof value==="string"){doc.write(`if (${accessor} !== ${esc(value)}) return INVALID;`)}else if(typeof value==="number"||typeof value==="boolean"){doc.write(`if (${accessor} !== ${value}) return INVALID;`)}else if(value===null){doc.write(`if (${accessor} !== null) return INVALID;`)}else if(value===undefined){doc.write(`if (${accessor} !== undefined) return INVALID;`)}else if(typeof value==="bigint"){doc.write(`if (${accessor} !== ${value}n) return INVALID;`)}else{throw new ZodCompileUnsupportedError(`literal type ${typeof value}`)}return accessor}function generateEnumCheck(doc,ctx,schema,accessor){const values=schema._zod.values;if(!values){throw new ZodCompileUnsupportedError("enum schema without enumerated values")}const enumSet=addConstant(ctx,values);doc.write(`if (!${enumSet}.has(${accessor})) return INVALID;`);return accessor}function generateWrapperCheck(doc,ctx,schema,accessor){const def=schema._zod.def;return generateCheck(doc,ctx,def.innerType,accessor)}function generateDefaultCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const descriptor=Object.getOwnPropertyDescriptor(schema._zod.def,"defaultValue");const defaultGetter=descriptor?()=>schema._zod.def.defaultValue:undefined;if(schema._zod.def.type==="prefault"){if(!defaultGetter){return generateCheck(doc,ctx,def.innerType,accessor)}const defaultFn=addConstant(ctx,defaultGetter);const inputVar=newVar(ctx);doc.write(`let ${inputVar} = ${accessor};`);doc.write(`if (${accessor} === undefined) ${inputVar} = ${defaultFn}();`);return generateCheck(doc,ctx,def.innerType,inputVar)}const outputVar=newVar(ctx);if(defaultGetter){const defaultFn=addConstant(ctx,defaultGetter);const cloneFn=addConstant(ctx,shallowClone);doc.write(`let ${outputVar};`);doc.write(`if (${accessor} === undefined) {`);doc.indented((d)=>{d.write(`${outputVar} = ${cloneFn}(${defaultFn}());`)});doc.write(`} else {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput} === undefined ? ${cloneFn}(${defaultFn}()) : ${innerOutput};`)});doc.write(`}`)}else{doc.write(`let ${outputVar};`);doc.write(`if (${accessor} !== undefined) {`);doc.indented((d)=>{const innerOutput=generateCheck(d,ctx,def.innerType,accessor);d.write(`${outputVar} = ${innerOutput};`)});doc.write(`}`)}return outputVar}function generateNonOptionalCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const innerOutput=generateCheck(doc,ctx,def.innerType,accessor);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${innerOutput};`);doc.write(`if (${outputVar} === undefined) return INVALID;`);return outputVar}function generateTupleCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const items=def.items;const rest=def.rest;doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);const optinStart=getTupleOptStart2(items,"optin");const optoutStart=getTupleOptStart2(items,"optout");if(rest){doc.write(`if (${accessor}.length < ${optinStart}) return INVALID;`)}else{doc.write(`if (${accessor}.length < ${optinStart} || ${accessor}.length > ${items.length}) return INVALID;`)}const outputVar=newVar(ctx);doc.write(`const ${outputVar} = [];`);for(let i=0;i<items.length;i++){const itemSchema=items[i];if(i>=optoutStart){doc.write(`if (${outputVar}.length === ${i}) {`);doc.indented((d)=>{d.write(`if (${i} < ${accessor}.length) {`);d.indented((d2)=>{const elemVar=newVar(ctx);d2.write(`const ${elemVar} = ${accessor}[${i}];`);const elemOutput=compileChild(d2,ctx,itemSchema,elemVar);d2.write(`${outputVar}[${i}] = ${elemOutput};`)});d.write(`} else {`);d.indented((d2)=>{if(dropsWhenAbsent(itemSchema)){d2.write(`${outputVar}.length = ${i};`);return}const elemVar=newVar(ctx);const branchVar=newVar(ctx);d2.write(`const ${elemVar} = undefined;`);d2.write(`const ${branchVar} = (() => {`);d2.indented((d3)=>{const elemOutput=compileChild(d3,ctx,itemSchema,elemVar);d3.write(`return ${elemOutput};`)});d2.write(`})();`);d2.write(`if (${branchVar} === INVALID || ${branchVar} === undefined) ${outputVar}.length = ${i};`);d2.write(`else ${outputVar}[${i}] = ${branchVar};`)});d.write(`}`)});doc.write(`}`)}else{const elemVar=newVar(ctx);doc.write(`const ${elemVar} = ${accessor}[${i}];`);const elemOutput=compileChild(doc,ctx,itemSchema,elemVar);doc.write(`${outputVar}[${i}] = ${elemOutput};`)}}if(rest){const iVar=newVar(ctx);const elemVar=newVar(ctx);doc.write(`for (let ${iVar} = ${items.length}; ${iVar} < ${accessor}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${elemVar} = ${accessor}[${iVar}];`);const elemOutput=compileChild(d,ctx,rest,elemVar);d.write(`${outputVar}[${iVar}] = ${elemOutput};`)});doc.write(`}`)}return outputVar}function getTupleOptStart2(items,key){for(let i=items.length-1;i>=0;i--){const omittable=key==="optin"?items[i]._zod.optin!==undefined:items[i]._zod.optout==="optional";if(!omittable)return i+1}return 0}function generateUnionCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const options=def.options;if(def.discriminator){return generateDiscriminatedUnionCheck(doc,ctx,def,accessor)}if(def.inclusive===false){throw new ZodCompileUnsupportedError("exclusive unions (z.xor)")}if(options.length===0){doc.write("return INVALID;");return accessor}if(options.length===1){return generateCheck(doc,ctx,options[0],accessor)}const allLiterals=options.every((opt)=>opt._zod.def.type==="literal"&&!opt._zod.def.checks?.length);if(allLiterals){const values=new Set(options.flatMap((opt)=>opt._zod.def.values));const valuesConst=addConstant(ctx,values);doc.write(`if (!${valuesConst}.has(${accessor})) return INVALID;`);return accessor}const outputVar=newVar(ctx);doc.write(`let ${outputVar};`);for(let i=0;i<options.length;i++){const opt=options[i];if(i===0){doc.write(`${outputVar} = (() => {`)}else{doc.write(`if (${outputVar} === INVALID) ${outputVar} = (() => {`)}doc.indented((d)=>{const branchOutput=generateCheck(d,ctx,opt,accessor);d.write(`return ${branchOutput};`)});doc.write(`})();`)}doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}function generateDiscriminatedUnionCheck(doc,ctx,def,accessor){if(def.unionFallback){throw new ZodCompileUnsupportedError("discriminated union with unionFallback")}if(def.options.length===0){doc.write("return INVALID;");return accessor}const discVar=newVar(ctx);const outputVar=newVar(ctx);doc.write(`const ${discVar} = ${accessor}?.[${esc(def.discriminator)}];`);doc.write(`let ${outputVar};`);let firstBranch=true;const claimed=new Set;for(const option of def.options){const values=option._zod.propValues?.[def.discriminator];if(!values||values.size===0){throw new ZodCompileUnsupportedError("discriminated union option without static discriminator values")}for(const value of values){if(claimed.has(value)){throw new ZodCompileUnsupportedError(`duplicate discriminator value ${String(value)}`)}claimed.add(value)}const conditions=Array.from(values,(value)=>literalEquality(ctx,discVar,value));const prefix=firstBranch?"if":"else if";doc.write(`${prefix} (${conditions.join(" || ")}) {`);doc.indented((d)=>{const branchOutput=generateCheck(d,ctx,option,accessor);d.write(`${outputVar} = ${branchOutput};`)});doc.write(`}`);firstBranch=false}doc.write(`else { return INVALID; }`);return outputVar}function literalEquality(ctx,accessor,value){if(typeof value==="string")return`${accessor} === ${esc(value)}`;if(typeof value==="number"){if(Number.isNaN(value))return`Number.isNaN(${accessor})`;return`${accessor} === ${value}`}if(typeof value==="boolean")return`${accessor} === ${value}`;if(value===null)return`${accessor} === null`;if(value===undefined)return`${accessor} === undefined`;if(typeof value==="bigint")return`${accessor} === ${value}n`;if(typeof value==="symbol"){const symbolConst=addConstant(ctx,value);return`${accessor} === ${symbolConst}`}throw new ZodCompileUnsupportedError(`literal discriminator value ${String(value)}`)}function generateIntersectionCheck(doc,ctx,schema,accessor){const def=schema._zod.def;ctx.definite=false;const leftOutput=compileChild(doc,ctx,def.left,accessor);const rightOutput=compileChild(doc,ctx,def.right,accessor);const mergeConst=addConstant(ctx,mergeValues);const mergedVar=newVar(ctx);doc.write(`const ${mergedVar} = ${mergeConst}(${leftOutput}, ${rightOutput});`);doc.write(`if (!${mergedVar}.valid) return INVALID;`);return`${mergedVar}.data`}function generateRecordCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const isPlainObjectConst=addConstant(ctx,isPlainObject);doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`);const outputVar=newVar(ctx);const kVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = {};`);const recordDef=def;const keyValues=recordDef.partial?undefined:def.keyType._zod.values;if(keyValues){const inputKeys=[];for(const key of keyValues){if(!(typeof key==="string"||typeof key==="number"||typeof key==="symbol")){throw new ZodCompileUnsupportedError(`record key value ${String(key)}`)}const inputKey=typeof key==="number"?key.toString():key;if(inputKey==="__proto__"){throw new ZodCompileUnsupportedError('record key "__proto__"')}inputKeys.push(inputKey);const keyConst=addConstant(ctx,key);const outKey=generateCheck(doc,ctx,def.keyType,keyConst);const valueVar=newVar(ctx);doc.write(`const ${valueVar} = ${accessor}[${literalPropertyKey(ctx,inputKey)}];`);const valOutput=compileChild(doc,ctx,def.valueType,valueVar);doc.write(`${outputVar}[${outKey}] = ${valOutput};`)}const knownKeysConst=addConstant(ctx,new Set(inputKeys));doc.write(`for (const ${kVar} in ${accessor}) {`);doc.indented((d)=>{d.write(`if (${knownKeysConst}.has(${kVar})) continue;`);if(recordDef.mode==="loose"){d.write(`if (${kVar} !== "__proto__") ${outputVar}[${kVar}] = ${accessor}[${kVar}];`)}else{d.write(`return INVALID;`)}});doc.write(`}`);return outputVar}const keyDef=def.keyType._zod.def;const keyIsBareString=keyDef.type==="string"&&keyDef.format===undefined&&!keyDef.coerce&&(keyDef.checks?.length??0)===0;if(!keyIsBareString){const isLoose=def.mode==="loose";const keyFn=compileFn(def.keyType);if(keyFn.definite===false)ctx.definite=false;const keyFast=addConstant(ctx,keyFn);const numericConst=addConstant(ctx,number);const outKeyVar=newVar(ctx);emitOwnKeys(doc,ctx,accessor,kVar,(d)=>{d.write(`let ${outKeyVar} = ${keyFast}(${kVar});`);d.write(`if (${outKeyVar} === INVALID && typeof ${kVar} === "string" && ${numericConst}.test(${kVar})) ${outKeyVar} = ${keyFast}(Number(${kVar}));`);if(isLoose){d.write(`if (${outKeyVar} === INVALID) { ${outputVar}[${kVar}] = ${accessor}[${kVar}]; continue; }`)}else{d.write(`if (${outKeyVar} === INVALID) return INVALID;`)}d.write(`if (${outKeyVar} === "__proto__") continue;`);const valueVar=newVar(ctx);d.write(`const ${valueVar} = ${accessor}[${kVar}];`);const valOutput=compileChild(d,ctx,def.valueType,valueVar);d.write(`${outputVar}[${outKeyVar}] = ${valOutput};`)});return outputVar}emitOwnKeys(doc,ctx,accessor,kVar,(d)=>{d.write(`const ${valVar} = ${accessor}[${kVar}];`);const valOutput=compileChild(d,ctx,def.valueType,valVar);d.write(`${outputVar}[${kVar}] = ${valOutput};`)},`return INVALID;`);return outputVar}function emitOwnKeys(doc,ctx,accessor,kVar,body,onSymbol){const propIsEnumerableConst=addConstant(ctx,Object.prototype.propertyIsEnumerable);const symsVar=newVar(ctx);const keysVar=newVar(ctx);const iVar=newVar(ctx);doc.write(`const ${symsVar} = Object.getOwnPropertySymbols(${accessor});`);doc.write(`const ${keysVar} = Object.getOwnPropertyNames(${accessor});`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${keysVar}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${kVar} = ${keysVar}[${iVar}];`);d.write(`if (${kVar} === "__proto__" || !${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);body(d)});doc.write(`}`);doc.write(`for (let ${iVar} = 0; ${iVar} < ${symsVar}.length; ${iVar}++) {`);doc.indented((d)=>{d.write(`const ${kVar} = ${symsVar}[${iVar}];`);d.write(`if (!${propIsEnumerableConst}.call(${accessor}, ${kVar})) continue;`);if(onSymbol)d.write(onSymbol);else body(d)});doc.write(`}`)}function literalPropertyKey(ctx,key){if(typeof key==="string")return esc(key);return addConstant(ctx,key)}function generateMapCheck(doc,ctx,schema,accessor){const def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`);const outputVar=newVar(ctx);const kVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = new Map();`);doc.write(`for (const [${kVar}, ${valVar}] of ${accessor}) {`);doc.indented((d)=>{const keyOutput=generateCheck(d,ctx,def.keyType,kVar);const valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.set(${keyOutput}, ${valOutput});`)});doc.write(`}`);return outputVar}function generateSetCheck(doc,ctx,schema,accessor){const def=schema._zod.def;doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`);const outputVar=newVar(ctx);const valVar=newVar(ctx);doc.write(`const ${outputVar} = new Set();`);doc.write(`for (const ${valVar} of ${accessor}) {`);doc.indented((d)=>{const valOutput=generateCheck(d,ctx,def.valueType,valVar);d.write(`${outputVar}.add(${valOutput});`)});doc.write(`}`);return outputVar}function generateFileCheck(doc,accessor){doc.write(`if (!(${accessor} instanceof File)) return INVALID;`);return accessor}function generateTemplateLiteralCheck(doc,ctx,schema,accessor){doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);const pattern=schema._zod.pattern;if(pattern){const patternConst=addConstant(ctx,pattern);doc.write(`${patternConst}.lastIndex = 0;`);doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`)}return accessor}function generateLazyCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const getterConst=addUserConstant(ctx,def.getter);const cacheConst=addConstant(ctx,{parser:null});doc.write(`if (!${cacheConst}.parser) {`);doc.indented((d)=>{d.write(`const inner = ${getterConst}();`);d.write(`${cacheConst}.parser = function(input) {`);d.indented((d2)=>{d2.write(`const result = inner._zod.run({ value: input, issues: [] }, {});`);d2.write(`return result.issues.length === 0 ? result.value : INVALID;`)});d.write(`};`)});doc.write(`}`);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${cacheConst}.parser(${accessor});`);doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}function generatePipeCheck(doc,ctx,schema,accessor){const def=schema._zod.def;const inputOutput=generateCheck(doc,ctx,def.in,accessor);if(def.transform){if(isAsyncFunction(def.transform)){throw new ZodCompileAsyncError("z.compile: async transforms in pipes are not supported")}const transformFn=def.transform;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=transformFn(value,fakePayload);if(result instanceof Promise)return INVALID;return fakePayload.issues.length===0?result:INVALID};const helperConst=addUserConstant(ctx,helperFn);const transformedVar=newVar(ctx);doc.write(`const ${transformedVar} = ${helperConst}(${inputOutput});`);doc.write(`if (${transformedVar} === INVALID) return INVALID;`);return generateCheck(doc,ctx,def.out,transformedVar)}else{return generateCheck(doc,ctx,def.out,inputOutput)}}function isAsyncFunction(fn){return typeof fn==="function"&&(fn.constructor.name==="AsyncFunction"||fn[Symbol.toStringTag]==="AsyncFunction")}function generateCustomCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(def.fn){if(isAsyncFunction(def.fn)){throw new ZodCompileAsyncError("z.compile: async custom predicates are not supported")}const fnConst=addUserConstant(ctx,def.fn);const throwAsyncConst=addConstant(ctx,throwAsync);const resVar=newVar(ctx);doc.write(`const ${resVar} = ${fnConst}(${accessor});`);doc.write(`if (${resVar} instanceof Promise) ${throwAsyncConst}();`);doc.write(`if (!${resVar}) return INVALID;`)}else{throw new ZodCompileUnsupportedError("custom schema without a predicate function")}return accessor}function runtimeCatch(innerSchema,catchValue,value){const result=innerSchema._zod.run({value,issues:[]},{});if(result&&typeof result.then==="function")return INVALID;const r=result;if(r.issues.length===0)return r.value;return catchValue()}function generateCatchCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(!def.catchValue[CONSTANT_CATCH]){throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)",false)}const outputVar=newVar(ctx);doc.write(`let ${outputVar} = (() => {`);doc.indented((d)=>{const innerOut=compileChild(d,ctx,def.innerType,accessor);d.write(`return ${innerOut};`)});doc.write(`})();`);const innerConst=addConstant(ctx,def.innerType);const catchConst=addUserConstant(ctx,def.catchValue);const catchHelperConst=addConstant(ctx,runtimeCatch);doc.write(`if (${outputVar} === INVALID) {`);doc.indented((d)=>{d.write(`${outputVar} = ${catchHelperConst}(${innerConst}, ${catchConst}, ${accessor});`);d.write(`if (${outputVar} === INVALID) return INVALID;`)});doc.write(`}`);return outputVar}function generateTransformCheck(doc,ctx,schema,accessor){const def=schema._zod.def;if(def.transform){if(isAsyncFunction(def.transform)){throw new ZodCompileAsyncError("z.compile: async transforms are not supported")}const transformFn=def.transform;const helperFn=(value)=>{const fakePayload={value,issues:[],addIssue:pushIssue};const result=transformFn(value,fakePayload);if(result instanceof Promise)return INVALID;return fakePayload.issues.length===0?result:INVALID};const helperConst=addUserConstant(ctx,helperFn);const outputVar=newVar(ctx);doc.write(`const ${outputVar} = ${helperConst}(${accessor});`);doc.write(`if (${outputVar} === INVALID) return INVALID;`);return outputVar}return accessor}function snapshotChecks(def){if(def.checks)def.checks=[...def.checks];return def}function _string(Class,params){return new Class(snapshotChecks({type:"string",...normalizeParams(params)}))}function _coercedString(Class,params){return new Class(snapshotChecks({type:"string",coerce:true,...normalizeParams(params)}))}function _email(Class,params){return new Class({type:"string",format:"email",check:"string_format",abort:false,...normalizeParams(params)})}function _guid(Class,params){return new Class({type:"string",format:"guid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuid(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuidv4(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v4",...normalizeParams(params)})}function _uuidv6(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v6",...normalizeParams(params)})}function _uuidv7(Class,params){return new Class({type:"string",format:"uuid",check:"string_format",abort:false,version:"v7",...normalizeParams(params)})}function _url(Class,params){return new Class({type:"string",format:"url",check:"string_format",abort:false,...normalizeParams(params)})}function _emoji2(Class,params){return new Class({type:"string",format:"emoji",check:"string_format",abort:false,...normalizeParams(params)})}function _nanoid(Class,params){return new Class({type:"string",format:"nanoid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid(Class,params){return new Class({type:"string",format:"cuid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid2(Class,params){return new Class({type:"string",format:"cuid2",check:"string_format",abort:false,...normalizeParams(params)})}function _ulid(Class,params){return new Class({type:"string",format:"ulid",check:"string_format",abort:false,...normalizeParams(params)})}function _xid(Class,params){return new Class({type:"string",format:"xid",check:"string_format",abort:false,...normalizeParams(params)})}function _ksuid(Class,params){return new Class({type:"string",format:"ksuid",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv4(Class,params){return new Class({type:"string",format:"ipv4",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv6(Class,params){return new Class({type:"string",format:"ipv6",check:"string_format",abort:false,...normalizeParams(params)})}function _mac(Class,params){return new Class({type:"string",format:"mac",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv4(Class,params){return new Class({type:"string",format:"cidrv4",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv6(Class,params){return new Class({type:"string",format:"cidrv6",check:"string_format",abort:false,...normalizeParams(params)})}function _base64(Class,params){return new Class({type:"string",format:"base64",check:"string_format",abort:false,...normalizeParams(params)})}function _base64url(Class,params){return new Class({type:"string",format:"base64url",check:"string_format",abort:false,...normalizeParams(params)})}function _e164(Class,params){return new Class({type:"string",format:"e164",check:"string_format",abort:false,...normalizeParams(params)})}function _creditCard(Class,params){return new Class({type:"string",format:"credit_card",check:"string_format",abort:false,...normalizeParams(params)})}function _iban(Class,params){return new Class({type:"string",format:"iban",check:"string_format",abort:false,...normalizeParams(params)})}function _jwt(Class,params){return new Class({type:"string",format:"jwt",check:"string_format",abort:false,...normalizeParams(params)})}var TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function _isoDateTime(Class,params){return new Class({type:"string",format:"datetime",check:"string_format",offset:false,local:false,precision:null,...normalizeParams(params)})}function _isoDate(Class,params){return new Class({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class,params){return new Class({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class,params){return new Class({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class,params){return new Class(snapshotChecks({type:"number",checks:[],...normalizeParams(params)}))}function _coercedNumber(Class,params){return new Class(snapshotChecks({type:"number",coerce:true,checks:[],...normalizeParams(params)}))}function _int(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"safeint",...normalizeParams(params)})}function _float32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"float32",...normalizeParams(params)})}function _float64(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"float64",...normalizeParams(params)})}function _int32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"int32",...normalizeParams(params)})}function _uint32(Class,params){return new Class({type:"number",check:"number_format",abort:false,format:"uint32",...normalizeParams(params)})}function _boolean(Class,params){return new Class({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class,params){return new Class({type:"boolean",coerce:true,...normalizeParams(params)})}function _bigint(Class,params){return new Class({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class,params){return new Class({type:"bigint",coerce:true,...normalizeParams(params)})}function _int64(Class,params){return new Class({type:"bigint",check:"bigint_format",abort:false,format:"int64",...normalizeParams(params)})}function _uint64(Class,params){return new Class({type:"bigint",check:"bigint_format",abort:false,format:"uint64",...normalizeParams(params)})}function _symbol(Class,params){return new Class({type:"symbol",...normalizeParams(params)})}function _undefined2(Class,params){return new Class({type:"undefined",...normalizeParams(params)})}function _null2(Class,params){return new Class({type:"null",...normalizeParams(params)})}function _any(Class){return new Class({type:"any"})}function _unknown(Class){return new Class({type:"unknown"})}function _never(Class,params){return new Class({type:"never",...normalizeParams(params)})}function _void(Class,params){return new Class({type:"void",...normalizeParams(params)})}function _date(Class,params){return new Class({type:"date",...normalizeParams(params)})}function _coercedDate(Class,params){return new Class({type:"date",coerce:true,...normalizeParams(params)})}function _nan(Class,params){return new Class({type:"nan",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:false})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:true})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:false})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:true})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size})}function _maxLength(maximum,params){const ch=new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum});return ch}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _properties(shape,params){return new $ZodCheckProperties({check:"properties",shape,...normalizeParams(params)})}function _mime(types,params){return new $ZodCheckMimeType({check:"mime_type",mime:types,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite((input)=>input.normalize(form))}function _trim(){return _overwrite((input)=>input.trim())}function _toLowerCase(){return _overwrite((input)=>input.toLowerCase())}function _toUpperCase(){return _overwrite((input)=>input.toUpperCase())}function _slugify(){return _overwrite((input)=>slugify(input))}function _array(Class,element,params){return new Class({type:"array",element,...normalizeParams(params)})}function _union(Class,options,params){return new Class({type:"union",options,...normalizeParams(params)})}function _xor(Class,options,params){return new Class({type:"union",options,inclusive:false,...normalizeParams(params)})}function _discriminatedUnion(Class,discriminator,options,params){return new Class({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class,left,right){return new Class({type:"intersection",left,right})}function _tuple(Class,items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new Class({type:"tuple",items,rest,...normalizeParams(params)})}function _record(Class,keyType,valueType,params){return new Class({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class,keyType,valueType,params){return new Class({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class,valueType,params){return new Class({type:"set",valueType,...normalizeParams(params)})}function _enum(Class,values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new Class({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class,entries,params){return new Class({type:"enum",entries,...normalizeParams(params)})}function _literal(Class,value,params){return new Class({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function _file(Class,params){return new Class({type:"file",...normalizeParams(params)})}function _transform(Class,fn){return new Class({type:"transform",transform:fn})}function _optional(Class,innerType){return new Class({type:"optional",innerType})}function _nullable(Class,innerType){return new Class({type:"nullable",innerType})}function _default(Class,innerType,defaultValue){return new Class({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class,innerType,params){return new Class({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class,innerType){return new Class({type:"success",innerType})}function _catch(Class,innerType,catchValue){return new Class({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}function _pipe(Class,in_,out){return new Class({type:"pipe",in:in_,out})}function _readonly(Class,innerType){return new Class({type:"readonly",innerType})}function _templateLiteral(Class,parts,params){return new Class({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class,getter){return new Class({type:"lazy",getter})}function _promise(Class,innerType){return new Class({type:"promise",innerType})}function _custom(Class,fn,_params){const norm=normalizeParams(_params);norm.abort??(norm.abort=true);const schema=new Class({type:"custom",check:"custom",fn,...norm});return schema}function _refine(Class,fn,_params){const schema=new Class({type:"custom",check:"custom",fn,...normalizeParams(_params)});return schema}function _superRefine(fn,params){const ch=_check((payload)=>{payload.addIssue=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,ch._zod.def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");if(!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=ch);_issue.continue??(_issue.continue=!ch._zod.def.abort);payload.issues.push(issue(_issue))}};return fn(payload.value,payload)},params);return ch}function _check(fn,params){const ch=new $ZodCheck({check:"custom",...normalizeParams(params)});ch._zod.check=fn;return ch}function describe(description){const ch=new $ZodCheck({check:"describe"});ch._zod.onattach=[(inst)=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}];ch._zod.check=()=>{};return ch}function meta(metadata){const ch=new $ZodCheck({check:"meta"});ch._zod.onattach=[(inst)=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}];ch._zod.check=()=>{};return ch}function _stringbool(Classes,_params){const params=normalizeParams(_params);let truthyArray=params.truthy??["true","1","yes","on","y","enabled"];let falsyArray=params.falsy??["false","0","no","off","n","disabled"];if(params.case!=="sensitive"){truthyArray=truthyArray.map((v)=>typeof v==="string"?v.toLowerCase():v);falsyArray=falsyArray.map((v)=>typeof v==="string"?v.toLowerCase():v)}const truthySet=new Set(truthyArray);const falsySet=new Set(falsyArray);const _Codec=Classes.Codec??$ZodCodec;const _Boolean=Classes.Boolean??$ZodBoolean;const _String=Classes.String??$ZodString;const stringSchema=new _String({type:"string",error:params.error});const booleanSchema=new _Boolean({type:"boolean",error:params.error});const codec=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:(input,payload)=>{let data=input;if(params.case!=="sensitive")data=data.toLowerCase();if(truthySet.has(data)){return true}else if(falsySet.has(data)){return false}else{payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec,continue:false});return{}}},reverseTransform:(input,_payload)=>{if(input===true){return truthyArray[0]||"true"}else{return falsyArray[0]||"false"}},error:params.error});codec._zod.bag.truthy=truthyArray;codec._zod.bag.falsy=falsyArray;codec._zod.bag.case=params.case??"insensitive";return codec}function _stringFormat(Class,format,fnOrRegex,_params={}){const params=normalizeParams(_params);const def={check:"string_format",type:"string",format,fn:typeof fnOrRegex==="function"?fnOrRegex:(val)=>fnOrRegex.test(val),...params};if(fnOrRegex instanceof RegExp){def.pattern=fnOrRegex}const inst=new Class(def);return inst}function assignProps(target,...sources){for(const source of sources){for(const key of Reflect.ownKeys(source)){if(Object.prototype.propertyIsEnumerable.call(source,key)){assignProp(target,key,source[key])}}}return target}function initializeContext(params){let target=params?.target??"draft-2020-12";if(target==="draft-4")target="draft-04";if(target==="draft-7")target="draft-07";return{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:undefined,sharedEmitDoneFor:undefined,cycles:params?.cycles??"ref",reused:params?.reused??"inline",intersections:[],deferred:[],external:params?.external??undefined}}function handleUnrepresentable(schema,ctx,json,params,message){const result=typeof ctx.unrepresentable==="function"?ctx.unrepresentable({zodSchema:schema,path:params.path,message}):ctx.unrepresentable;if(result==="any")return false;if(result===undefined||result==="throw")throw new Error(message);Object.assign(json,result);return true}function processSchema(schema,ctx,_params={path:[],schemaPath:[]}){var _a;const def=schema._zod.def;const seen=ctx.seen.get(schema);if(seen){seen.count++;const isCycle=_params.schemaPath.includes(schema);if(isCycle){seen.cycle=_params.path}return seen.schema}const result={schema:{},count:1,cycle:undefined,path:_params.path};ctx.seen.set(schema,result);ctx.sharedDefsExtractedFor=undefined;ctx.sharedEmitDoneFor=undefined;const overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema){result.schema=overrideSchema}else{const params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema){schema._zod.processJSONSchema(ctx,result.schema,params)}else{const _json=result.schema;const processor=ctx.processors[def.type];if(!processor){throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`)}processor(schema,ctx,_json,params)}const parent=schema._zod.parent;if(parent){if(!result.ref)result.ref=parent;processSchema(parent,ctx,params);ctx.seen.get(parent).isParent=true}}const meta=ctx.metadataRegistry.get(schema);if(meta)assignProps(result.schema,meta);if(ctx.io==="input"&&isTransforming(schema)){delete result.schema.examples;delete result.schema.default}if(ctx.io==="input"&&"_prefault"in result.schema)(_a=result.schema).default??(_a.default=result.schema._prefault);delete result.schema._prefault;const _result=ctx.seen.get(schema);return _result.schema}function encodeJSONPointerSegment(segment){return segment.replace(/~/g,"~0").replace(/\//g,"~1")}function extractDefs(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");if(ctx.external&&ctx.sharedDefsExtractedFor===ctx.external)return;const idToSchema=new Map;for(const entry of ctx.seen.entries()){const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){const existing=idToSchema.get(id);if(existing&&existing!==entry[0]){throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`)}idToSchema.set(id,entry[0])}}const makeURI=(entry)=>{const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){const externalId=ctx.external.registry.get(entry[0])?.id;const uriGenerator=ctx.external.uri??((id)=>id);if(externalId){return{ref:uriGenerator(externalId)}}const id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;entry[1].defId=id;return{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}`}}const uriPrefix=`#`;const defUriPrefix=`${uriPrefix}/${defsSegment}/`;if(entry[1]===root&&!entry[1].schema.id){return{ref:uriPrefix}}const defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+encodeJSONPointerSegment(defId)}};const extractToDef=(entry)=>{if(entry[1].schema.$ref){return}const seen=entry[1];const{ref,defId}=makeURI(entry);seen.def={...seen.schema};if(defId)seen.defId=defId;const schema=seen.schema;for(const key in schema){delete schema[key]}schema.$ref=ref};if(ctx.cycles==="throw"){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.cycle){throw new Error("Cycle detected: "+`#/${seen.cycle?.join("/")}/<root>`+'\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.')}}}for(const entry of ctx.seen.entries()){const seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){const ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry)}}}if(ctx.external)ctx.sharedDefsExtractedFor=ctx.external}function compactTypeUnion(schema){const options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==undefined)return;const types=[];for(const option of options){if(!option||typeof option!=="object")return;compactTypeUnion(option);const keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;const type=option.type;for(const member of Array.isArray(type)?type:[type]){if(typeof member!=="string")return;if(!types.includes(member))types.push(member)}}delete schema.anyOf;schema.type=types.length===1?types[0]:types}var FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]);var UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){const extra=member.additionalProperties;if(extra===undefined||extra===false||typeof extra!=="object"||extra===null)return null;return Object.keys(extra).length?extra:null}function foldObjects(members){const objects=[];for(const member of members){if(typeof member!=="object"||member.type!=="object")return null;for(const key in member){if(!FOLDABLE_KEYS.has(key))return null}objects.push(member)}const properties={};const required=new Set;for(const object of objects){for(const key in object.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;const parts=[];for(const other of objects){const part=other.properties?.[key]??undeclaredConstraint(other);if(part===null||part===undefined)continue;if(!parts.some((seen)=>JSON.stringify(seen)===JSON.stringify(part)))parts.push(part)}const merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(const key of object.required??[])required.add(key)}const folded={type:"object",properties};if(required.size)folded.required=[...required];if(objects.every((object)=>object.additionalProperties===false)){folded.additionalProperties=false}else{const constraints=[];for(const object of objects){const constraint=undeclaredConstraint(object);if(constraint&&!constraints.some((seen)=>JSON.stringify(seen)===JSON.stringify(constraint)))constraints.push(constraint)}if(constraints.length===1)folded.additionalProperties=constraints[0];else if(constraints.length>1)folded.additionalProperties={allOf:constraints}}return folded}function foldIntersection(json){const allOf=json.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(const key of FOLDABLE_KEYS)if(key in json)return;const unions=allOf.filter((m)=>UNION_KEYS.some((k)=>Array.isArray(m[k])));let folded=null;if(!unions.length){folded=foldObjects(allOf)}else{const union=unions[0];const keyword=UNION_KEYS.find((k)=>Array.isArray(union[k]));if(Object.keys(union).length!==1)return;const rest=allOf.filter((m)=>m!==union);const branches=union[keyword].map((branch)=>foldObjects([...rest,branch]));if(branches.some((b)=>!b))return;folded={[keyword]:branches}}if(!folded)return;delete json.allOf;assignProps(json,folded)}function finalize(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");const flattenRef=(zodSchema)=>{const seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;const schema=seen.def??seen.schema;const _cached={...schema};const ref=seen.ref;seen.ref=null;if(ref){flattenRef(ref);const refSeen=ctx.seen.get(ref);const refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")){schema.allOf=schema.allOf??[];schema.allOf.push(refSchema)}else{assignProps(schema,refSchema)}assignProps(schema,_cached);const isParentRef=zodSchema._zod.parent===ref;if(isParentRef){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached)){delete schema[key]}}}if(refSchema.$ref&&refSeen.def){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema[key])===JSON.stringify(refSeen.def[key])){delete schema[key]}}}}const parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);const parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){schema.$ref=parentSeen.schema.$ref;if(parentSeen.def){for(const key in schema){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema[key])===JSON.stringify(parentSeen.def[key])){delete schema[key]}}}}}ctx.override({zodSchema,jsonSchema:schema,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(const entry of[...ctx.seen.entries()].reverse()){flattenRef(entry[0])}if(ctx.target!=="openapi-3.0"){for(const entry of ctx.seen.entries()){compactTypeUnion(entry[1].def??entry[1].schema)}}for(const rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){const carriers=new Map;for(const seen of ctx.seen.values()){for(const json of[seen.schema,seen.def]){const allOf=json?.allOf;if(!Array.isArray(allOf))continue;const existing=carriers.get(allOf);if(existing)existing.push(json);else carriers.set(allOf,[json])}}for(const allOf of ctx.intersections){for(const json of carriers.get(allOf)??[])foldIntersection(json)}}}const result={};if(ctx.target==="draft-2020-12"){result.$schema="https://json-schema.org/draft/2020-12/schema"}else if(ctx.target==="draft-07"){result.$schema="http://json-schema.org/draft-07/schema#"}else if(ctx.target==="draft-04"){result.$schema="http://json-schema.org/draft-04/schema#"}else if(ctx.target==="openapi-3.0"){}if(ctx.external?.uri){const id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);const rootMetaId=ctx.metadataRegistry.get(schema)?.id;if(rootMetaId!==undefined&&result.id===rootMetaId)delete result.id;const defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.def&&seen.defId){if(seen.def.id===seen.defId)delete seen.def.id;assignProp(defs,seen.defId,seen.def)}}}if(ctx.external)ctx.sharedEmitDoneFor=ctx.external;if(ctx.external){}else{if(Object.keys(defs).length>0){if(ctx.target==="draft-2020-12"){result.$defs=defs}else{result.definitions=defs}}}try{const finalized=JSON.parse(JSON.stringify(result));Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:false,writable:false});return finalized}catch(_err){throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){const ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return false;ctx.seen.add(_schema);const def=_schema._zod.def;if(def.type==="transform")return true;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch"){return isTransforming(def.innerType,ctx)}if(def.type==="intersection"){return isTransforming(def.left,ctx)||isTransforming(def.right,ctx)}if(def.type==="record"||def.type==="map"){return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx)}if(def.type==="pipe"){if(_schema._zod.traits.has("$ZodCodec"))return true;return isTransforming(def.in,ctx)||isTransforming(def.out,ctx)}if(def.type==="object"){for(const key in def.shape){if(isTransforming(def.shape[key],ctx))return true}return false}if(def.type==="union"){for(const option of def.options){if(isTransforming(option,ctx))return true}return false}if(def.type==="tuple"){for(const item of def.items){if(isTransforming(item,ctx))return true}if(def.rest&&isTransforming(def.rest,ctx))return true;return false}return false}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{const ctx=initializeContext({...params,processors});processSchema(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{const{libraryOptions,target}=params??{};const ctx=initializeContext({...libraryOptions??{},target,io,processors});processSchema(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var narrowMin=(agg,key,value)=>{if(agg[key]===undefined||value>agg[key])agg[key]=value};var narrowMax=(agg,key,value)=>{if(agg[key]===undefined||value<agg[key])agg[key]=value};var narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value);narrowMax(agg,"maximum",value)};var addDivisor=(agg,value)=>{agg.multipleOf??(agg.multipleOf=[]);if(!agg.multipleOf.includes(value))agg.multipleOf.push(value)};var addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set);agg.patterns.add(pattern)};var intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter((m)=>mime.includes(m)):[...mime]};var setFormat=(agg,format)=>{agg.format=format;if(format.includes("int"))agg.isInt=true};var minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum);var maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum);var formatContributor=(ranges)=>(agg,def)=>{setFormat(agg,def.format);const[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum);narrowMax(agg,"maximum",maximum)};var contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format);if(def.pattern)addPattern(agg,def.pattern);if(def.format==="base64"||def.format==="base64url")agg.contentEncoding=def.format;if(def.local||def.precision===-1)agg.laxFormat=true},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){const agg={};const def=schema._zod.def;const list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(const ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);const bag=schema._zod.bag;if(bag.minimum!==undefined)narrowMin(agg,"minimum",bag.minimum);if(bag.exclusiveMinimum!==undefined)narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum);if(bag.maximum!==undefined)narrowMax(agg,"maximum",bag.maximum);if(bag.exclusiveMaximum!==undefined)narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum);if(bag.multipleOf!==undefined)addDivisor(agg,bag.multipleOf);if(bag.format!==undefined){agg.format??(agg.format=bag.format);if(bag.format.includes("int"))agg.isInt=true}if(bag.mime)intersectMime(agg,bag.mime);for(const pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""};var exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]);var exactPattern=(p)=>exactPatterns.get(p)??p;var stringProcessor=(schema,ctx,_json,_params)=>{const json=_json;json.type="string";const{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){json.format=formatMap[format]??format;if(json.format==="")delete json.format;if(format==="time"||laxFormat){delete json.format}}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){const patternList=[...patterns].map(exactPattern);if(patternList.length===1)json.pattern=patternList[0].source;else if(patternList.length>1){json.allOf=[...patternList.map((regex)=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}}};var numberProcessor=(schema,ctx,_json,params)=>{const json=_json;const{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json.type=isInt?"integer":"number";const exMin=typeof exclusiveMinimum==="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY);const exMax=typeof exclusiveMaximum==="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY);const legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin){if(legacy){json.minimum=exclusiveMinimum;json.exclusiveMinimum=true}else{json.exclusiveMinimum=exclusiveMinimum}}else if(typeof minimum==="number"){json.minimum=minimum}if(exMax){if(legacy){json.maximum=exclusiveMaximum;json.exclusiveMaximum=true}else{json.exclusiveMaximum=exclusiveMaximum}}else if(typeof maximum==="number"){json.maximum=maximum}if(multipleOf){const divisors=new Set;for(const divisor of multipleOf){if(Number.isFinite(divisor)&&divisor!==0)divisors.add(Math.abs(divisor));else handleUnrepresentable(schema,ctx,json,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`)}const[first,...rest]=divisors;if(first!==undefined)json.multipleOf=first;if(rest.length)json.allOf=[...json.allOf??[],...rest.map((m)=>({multipleOf:m}))]}};var booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var bigintProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"BigInt cannot be represented in JSON Schema")};var symbolProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Symbols cannot be represented in JSON Schema")};var nullProcessor=(_schema,ctx,json,_params)=>{if(ctx.target==="openapi-3.0"){json.type="string";json.nullable=true;json.enum=[null]}else{json.type="null"}};var undefinedProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Undefined cannot be represented in JSON Schema")};var voidProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Void cannot be represented in JSON Schema")};var neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}};var anyProcessor=(_schema,_ctx,_json,_params)=>{};var unknownProcessor=(_schema,_ctx,_json,_params)=>{};var dateProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Date cannot be represented in JSON Schema")};var enumProcessor=(schema,_ctx,json,_params)=>{const def=schema._zod.def;const values=getEnumValues(def.entries);if(values.length===0){json.not={};return}if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values};var literalProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;if(def.values.length===0){json.not={};return}const vals=[];for(const val of def.values){if(val===undefined){if(handleUnrepresentable(schema,ctx,json,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val==="bigint"){if(handleUnrepresentable(schema,ctx,json,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else{vals.push(val)}}if(vals.length===0){}else if(vals.length===1){const val=vals[0];json.type=val===null?"null":typeof val;if(ctx.target==="draft-04"||ctx.target==="openapi-3.0"){json.enum=[val]}else{json.const=val}}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}};var nanProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"NaN cannot be represented in JSON Schema")};var templateLiteralProcessor=(schema,_ctx,json,_params)=>{const _json=json;const pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string";_json.pattern=pattern.source};var fileProcessor=(schema,_ctx,json,_params)=>{const _json=json;_json.type="string";_json.format="binary";_json.contentEncoding="binary";const{minimum,maximum,mime}=aggregateChecks(schema);if(minimum!==undefined)_json.minLength=minimum;if(maximum!==undefined)_json.maxLength=maximum;if(!mime)return;if(mime.length===0)_json.not={};else if(mime.length===1)_json.contentMediaType=mime[0];else _json.anyOf=mime.map((m)=>({contentMediaType:m}))};var successProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var customProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Custom types cannot be represented in JSON Schema")};var functionProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Function types cannot be represented in JSON Schema")};var transformProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Transforms cannot be represented in JSON Schema")};var mapProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Map cannot be represented in JSON Schema")};var setProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Set cannot be represented in JSON Schema")};var arrayProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;const{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array";json.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};function inputOptin(schema){const def=schema._zod.def;if(def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")){return inputOptin(def.out)}if(def.type==="catch"){return inputOptin(def.innerType)}return schema._zod.optin}var objectProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;const shape=def.shape;const symbolKeys=Object.getOwnPropertySymbols(shape);if(symbolKeys.length&&handleUnrepresentable(schema,ctx,json,params,"Symbol keys cannot be represented in JSON Schema")){return}json.type="object";json.properties={};for(const key in shape){assignProp(json.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}))}const requiredKeys=[];for(const key of Object.keys(shape)){const field=def.shape[key];if(ctx.io==="input"?inputOptin(field)===undefined:field._zod.optout===undefined){requiredKeys.push(key)}}if(requiredKeys.length>0){json.required=requiredKeys}if(def.catchall?._zod.def.type==="never"){json.additionalProperties=false}else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=false}else if(def.catchall){json.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})}};var unionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const isExclusive=def.inclusive===false;const options=def.options.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive){json.oneOf=options}else{json.anyOf=options}};var intersectionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]});const b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]});const isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1;const allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf;ctx.intersections.push(allOf)};var tupleProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="array";const prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items";const restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems";const prefixItems=def.items.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,prefixPath,i]}));const rest=def.rest?processSchema(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;let minItems=def.items.length;while(minItems>0){const item=def.items[minItems-1];const optional=ctx.io==="input"?inputOptin(item)!==undefined:item._zod.optout==="optional";if(!optional)break;minItems--}const maxItems=def.items.length;const isClosed=!def.rest;if(ctx.target==="draft-2020-12"){json.prefixItems=prefixItems;if(isClosed){json.items=false}else if(rest){json.items=rest}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else if(ctx.target==="openapi-3.0"){json.items={anyOf:prefixItems};if(rest){json.items.anyOf.push(rest)}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}else{json.items=prefixItems;if(isClosed){json.additionalItems=false}else if(rest){json.additionalItems=rest}if(minItems>0)json.minItems=minItems;if(isClosed)json.maxItems=maxItems}const{minimum,maximum}=aggregateChecks(schema);if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum};function stringifyKeyNames(bySchema,json,visited){if(json.$ref){if(visited.has(json))return json;visited.add(json);const def=bySchema.get(json)?.def;if(!def)return json;const inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json:inlined}for(const keyword of["anyOf","oneOf"]){const branches=json[keyword];if(!Array.isArray(branches))continue;const mapped=branches.map((branch)=>stringifyKeyNames(bySchema,branch,visited));if(mapped.some((branch,i)=>branch!==branches[i]))json={...json,[keyword]:mapped}}const types=Array.isArray(json.type)?json.type:[json.type];const numericType=!types.includes("string")&&types.some((t)=>t==="number"||t==="integer");const values=json.enum??(json.const!==undefined?[json.const]:undefined);if(!numericType&&!values?.some((v)=>typeof v==="number"))return json;const{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json;if(rest.enum)rest.enum=rest.enum.map((v)=>typeof v==="number"?String(v):v);else if(typeof rest.const==="number")rest.const=String(rest.const);if(!numericType)return rest;rest.type="string";if(!values)rest.pattern=(types.includes("number")?number:integer).source;return rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){const bySchema=new Map;for(const entry of ctx.seen.values()){if(entry.def&&!bySchema.has(entry.schema))bySchema.set(entry.schema,entry)}const rewrites=new Map;for(const record of pendingRecords.get(ctx)??[]){const seen=ctx.seen.get(record);const names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===true||rewrites.has(names))continue;const rewritten=stringifyKeyNames(bySchema,names,new Set);if(rewritten!==names)rewrites.set(names,rewritten)}if(!rewrites.size)return;for(const entry of ctx.seen.values()){for(const carrier of[entry.schema,entry.def]){const rewritten=carrier&&rewrites.get(carrier.propertyNames);if(rewritten)carrier.propertyNames=rewritten}}}var recordProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="object";const keyType=def.keyType;const patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){const valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(const pattern of patterns){assignProp(json.patternProperties,exactPattern(pattern).source,valueSchema)}}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending=pendingRecords.get(ctx);if(!pending){pending=[];pendingRecords.set(ctx,pending);ctx.deferred.push(()=>rewriteKeyNames(ctx))}pending.push(schema)}json.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}const keyValues=keyType._zod.values;const omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==undefined;if(keyValues&&!def.partial&&!omittableOnInput){const validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0){json.required=validKeyValues.map(String)}}};var nullableProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const inner=processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0"){seen.ref=def.innerType;json.nullable=true}else{json.anyOf=[inner,{type:"null"}]}};var nonoptionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value,schema,ctx,json,params){let unrepresentable=false;const serialized=JSON.stringify(value,(_,val)=>{if(typeof val!=="bigint")return val;unrepresentable=true;return null});if(!unrepresentable)return JSON.parse(serialized);handleUnrepresentable(schema,ctx,json,params,"BigInt defaults cannot be represented in JSON Schema");return UNREPRESENTABLE_DEFAULT}var defaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;const value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json.default=value};var prefaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;if(ctx.io!=="input")return;const value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);if(value!==UNREPRESENTABLE_DEFAULT)json._prefault=value};var catchProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(undefined)}catch{handleUnrepresentable(schema,ctx,json,params,"Dynamic catch values are not supported in JSON Schema");return}json.default=catchValue};var pipeProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;const inIsTransform=def.in._zod.traits.has("$ZodTransform");const innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};var readonlyProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json.readOnly=true};var promiseProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var optionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;processSchema(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var lazyProcessor=(schema,ctx,_json,params)=>{const innerType=schema._zod.innerType;processSchema(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};var allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor};function toJSONSchema(input,params){if("_idmap"in input){const registry=input;const ctx=initializeContext({...params,processors:allProcessors});const defs={};for(const entry of registry._idmap.entries()){const[_,schema]=entry;processSchema(schema,ctx)}const schemas={};const external={registry,uri:params?.uri,defs};ctx.external=external;for(const entry of registry._idmap.entries()){const[key,schema]=entry;extractDefs(ctx,schema);assignProp(schemas,key,finalize(ctx,schema))}if(Object.keys(defs).length>0){const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}const ctx=initializeContext({...params,processors:allProcessors});processSchema(input,ctx);extractDefs(ctx,input);return finalize(ctx,input)}class JSONSchemaGenerator{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return processSchema(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}this.ctx.sharedDefsExtractedFor=undefined;this.ctx.sharedEmitDoneFor=undefined;extractDefs(this.ctx,schema);const result=finalize(this.ctx,schema);const{"~standard":_,...plainResult}=result;return plainResult}}var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:true,enumerable:false,get(){const value=make(this);Object.defineProperty(this,key,{value,configurable:true,writable:true});return value},set(value){Object.defineProperty(this,key,{value,configurable:true,writable:true})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues);inst.name="ZodError";const proto=Object.getPrototypeOf(inst);if(_installedErrorProtos.has(proto))return;_installedErrorProtos.add(proto);_lazyMethod(proto,"format",(self)=>(mapper)=>formatError(self,mapper));_lazyMethod(proto,"flatten",(self)=>(mapper)=>flattenError(self,mapper));_lazyMethod(proto,"addIssue",(self)=>(issue)=>{self.issues.push(issue);self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)});_lazyMethod(proto,"addIssues",(self)=>(issues)=>{self.issues.push(...issues);self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)});Object.defineProperty(proto,"isEmpty",{configurable:true,enumerable:false,get(){return this.issues.length===0}})};var ZodError=$constructor("ZodError",initializer2);var ZodRealError=$constructor("ZodError",initializer2,undefined,{Parent:Error});var parse3=_parse(ZodRealError);var parseAsync2=_parseAsync(ZodRealError);var safeParse2=_safeParse(ZodRealError);var safeParseAsync2=_safeParseAsync(ZodRealError);var encode2=_encode(ZodRealError);var decode2=_decode(ZodRealError);var encodeAsync2=_encodeAsync(ZodRealError);var decodeAsync2=_decodeAsync(ZodRealError);var safeEncode2=_safeEncode(ZodRealError);var safeDecode2=_safeDecode(ZodRealError);var safeEncodeAsync2=_safeEncodeAsync(ZodRealError);var safeDecodeAsync2=_safeDecodeAsync(ZodRealError);function _ensureDefaultLocale(){if(!globalConfig.localeError)config(en_default())}function _ensureDefaultMemoizer(){if(!globalConfig.memoizer)config({memoizer:memoizer()})}var ZodType=$constructor("ZodType",(inst,def)=>{_ensureDefaultLocale();$ZodType.init(inst,def);inst.def=def;inst.type=def.type;return inst},{check(...chks){const def=this.def;return this.clone(mergeDefs(def,{checks:[...def.checks??[],...chks.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:true})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta){reg.add(this,meta);return this},refine(check2,params){return this.check(refine(check2,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default2(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch2(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){const cl=this.clone();globalRegistry.add(cl,{description});return cl},meta(...args){if(args.length===0)return globalRegistry.get(this);const cl=this.clone();globalRegistry.add(cl,args[0]);return cl},isOptional(){return this.safeParse(undefined).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get "~standard"(){return hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set "~standard"(value){own(this,"~standard",value)},parse:function _parse(data,params){return parse3(this,data,params,{callee:_parse})},parseAsync:async function _parseAsync(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync})},safeParse(data,params){return safeParse2(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value){own(this,"spa",value)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode(data,params){return encode2(this,data,params,{callee:_encode})},decode:function _decode(data,params){return decode2(this,data,params,{callee:_decode})},encodeAsync:async function _encodeAsync(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}});var _ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>stringProcessor(inst,ctx,json2,params)},derived({format:(inst)=>aggregateChecks(inst).format??null,minLength:(inst)=>aggregateChecks(inst).minimum??null,maxLength:(inst)=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}}));var ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def);_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def);_ZodString.init(inst,def)});var ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def);ZodStringFormat.init(inst,def)});var ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def);ZodStringFormat.init(inst,def)});var ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def);ZodStringFormat.init(inst,def)});function email2(params){return _email(ZodEmail,params)}var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def);ZodStringFormat.init(inst,def)});function guid2(params){return _guid(ZodGUID,params)}var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def);ZodStringFormat.init(inst,def)});function uuid2(params){return _uuid(ZodUUID,params)}function uuidv4(params){return _uuidv4(ZodUUID,params)}function uuidv6(params){return _uuidv6(ZodUUID,params)}function uuidv7(params){return _uuidv7(ZodUUID,params)}var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def);ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}function httpUrl(params){return _url(ZodURL,{protocol:httpProtocol,hostname:domain,...normalizeParams(params)})}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def);ZodStringFormat.init(inst,def)});function emoji2(params){return _emoji2(ZodEmoji,params)}var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def);ZodStringFormat.init(inst,def)});function nanoid2(params){return _nanoid(ZodNanoID,params)}var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def);ZodStringFormat.init(inst,def)});function cuid3(params){return _cuid(ZodCUID,params)}var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def);ZodStringFormat.init(inst,def)});function cuid22(params){return _cuid2(ZodCUID2,params)}var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def);ZodStringFormat.init(inst,def)});function ulid2(params){return _ulid(ZodULID,params)}var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def);ZodStringFormat.init(inst,def)});function xid2(params){return _xid(ZodXID,params)}var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def);ZodStringFormat.init(inst,def)});function ksuid2(params){return _ksuid(ZodKSUID,params)}var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def);ZodStringFormat.init(inst,def)});function ipv42(params){return _ipv4(ZodIPv4,params)}var ZodMAC=$constructor("ZodMAC",(inst,def)=>{$ZodMAC.init(inst,def);ZodStringFormat.init(inst,def)});function mac2(params){return _mac(ZodMAC,params)}var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def);ZodStringFormat.init(inst,def)});function ipv62(params){return _ipv6(ZodIPv6,params)}var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def);ZodStringFormat.init(inst,def)});function cidrv42(params){return _cidrv4(ZodCIDRv4,params)}var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def);ZodStringFormat.init(inst,def)});function cidrv62(params){return _cidrv6(ZodCIDRv6,params)}var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def);ZodStringFormat.init(inst,def)});function base642(params){return _base64(ZodBase64,params)}var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def);ZodStringFormat.init(inst,def)});function base64url2(params){return _base64url(ZodBase64URL,params)}var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def);ZodStringFormat.init(inst,def)});function e1642(params){return _e164(ZodE164,params)}var ZodCreditCard=$constructor("ZodCreditCard",(inst,def)=>{$ZodCreditCard.init(inst,def);ZodStringFormat.init(inst,def)});function creditCard2(params){return _creditCard(ZodCreditCard,params)}var ZodIBAN=$constructor("ZodIBAN",(inst,def)=>{$ZodIBAN.init(inst,def);ZodStringFormat.init(inst,def)});function iban2(params){return _iban(ZodIBAN,params)}var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def);ZodStringFormat.init(inst,def)});function jwt(params){return _jwt(ZodJWT,params)}var ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def);ZodStringFormat.init(inst,def)});function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodCustomStringFormat,format,fnOrRegex,_params)}function hostname2(_params){return _stringFormat(ZodCustomStringFormat,"hostname",hostname,_params)}function hex2(_params){return _stringFormat(ZodCustomStringFormat,"hex",hex,_params)}function currencyCode2(_params){return _stringFormat(ZodCustomStringFormat,"currency_code",currencyCode,_params)}function hash(alg,params){const enc=params?.enc??"hex";const format=`${alg}_${enc}`;const regex=exports_regexes[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodCustomStringFormat,format,regex,params)}var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>numberProcessor(inst,ctx,json2,params);inst.isFinite=true},derived({minValue:(inst)=>{const{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:(inst)=>{const{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:(inst)=>{const{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:(inst)=>aggregateChecks(inst).format??null},{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}}));function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def);ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}function float32(params){return _float32(ZodNumberFormat,params)}function float64(params){return _float64(ZodNumberFormat,params)}function int32(params){return _int32(ZodNumberFormat,params)}function uint32(params){return _uint32(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>booleanProcessor(inst,ctx,json2,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>bigintProcessor(inst,ctx,json2,params)},derived({minValue:(inst)=>aggregateChecks(inst).minimum??null,maxValue:(inst)=>aggregateChecks(inst).maximum??null,format:(inst)=>aggregateChecks(inst).format??null},{gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},gt(value,params){return this.check(_gt(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},positive(params){return this.check(_gt(BigInt(0),params))},negative(params){return this.check(_lt(BigInt(0),params))},nonpositive(params){return this.check(_lte(BigInt(0),params))},nonnegative(params){return this.check(_gte(BigInt(0),params))},multipleOf(value,params){return this.check(_multipleOf(value,params))}}));function bigint2(params){return _bigint(ZodBigInt,params)}var ZodBigIntFormat=$constructor("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def);ZodBigInt.init(inst,def)});function int64(params){return _int64(ZodBigIntFormat,params)}function uint64(params){return _uint64(ZodBigIntFormat,params)}var ZodSymbol=$constructor("ZodSymbol",(inst,def)=>{$ZodSymbol.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>symbolProcessor(inst,ctx,json2,params)});function symbol(params){return _symbol(ZodSymbol,params)}var ZodUndefined=$constructor("ZodUndefined",(inst,def)=>{$ZodUndefined.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>undefinedProcessor(inst,ctx,json2,params)});function _undefined3(params){return _undefined2(ZodUndefined,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullProcessor(inst,ctx,json2,params)});function _null3(params){return _null2(ZodNull,params)}var ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>anyProcessor(inst,ctx,json2,params)});function any(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unknownProcessor(inst,ctx,json2,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>neverProcessor(inst,ctx,json2,params)});function never(params){return _never(ZodNever,params)}var ZodVoid=$constructor("ZodVoid",(inst,def)=>{$ZodVoid.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>voidProcessor(inst,ctx,json2,params)});function _void2(params){return _void(ZodVoid,params)}var ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>dateProcessor(inst,ctx,json2,params);inst.min=(value,params)=>inst.check(_gte(value,params));inst.max=(value,params)=>inst.check(_lte(value,params))},derived({minDate:(inst)=>{const{minimum}=aggregateChecks(inst);return minimum?new Date(minimum):null},maxDate:(inst)=>{const{maximum}=aggregateChecks(inst);return maximum?new Date(maximum):null}},{}));function date2(params){return _date(ZodDate,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer();$ZodArray.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>arrayProcessor(inst,ctx,json2,params);inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});function array(element,params){return _array(ZodArray,element,params)}function keyof(schema){const shape=schema._zod.def.shape;return _enum2(Object.keys(shape))}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer();$ZodObjectJIT.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>objectProcessor(inst,ctx,json2,params);installLazyProp(inst,"shape",(self)=>self._zod.def.shape,false)},{keyof(){return _enum2(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(mergeDefs(this._zod.def,{catchall:undefined}))},extend(incoming){return extend(this,incoming)},safeExtend(incoming){return safeExtend(this,incoming)},merge(other){return merge(this,other)},pick(mask){return pick(this,mask)},omit(mask){return omit(this,mask)},partial(...args){return partial(ZodOptional,this,args[0])},exactPartial(...args){return partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return required(ZodNonOptional,this,args[0])}});function object(shape,params){const def={type:"object",shape:shape??{},...normalizeParams(params)};return new ZodObject(def)}function strictObject(shape,params){return new ZodObject({type:"object",shape,catchall:never(),...normalizeParams(params)})}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...normalizeParams(params)})}var ZodXor=$constructor("ZodXor",(inst,def)=>{ZodUnion.init(inst,def);$ZodXor.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>unionProcessor(inst,ctx,json2,params);inst.options=def.options});function xor(options,params){return new ZodXor({type:"union",options,inclusive:false,...normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def);$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>intersectionProcessor(inst,ctx,json2,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodTuple=$constructor("ZodTuple",(inst,def)=>{_ensureDefaultMemoizer();$ZodTuple.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>tupleProcessor(inst,ctx,json2,params)},{rest(rest){return this.clone({...this._zod.def,rest})},partial(){const def=this._zod.def;if(def.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...def,items:def.items.map((item)=>new ZodOptional({type:"optional",innerType:item}))})}});function tuple(items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new ZodTuple({type:"tuple",items,rest,...normalizeParams(params)})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer();$ZodRecord.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>recordProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType});function record(keyType,valueType,params){if(!valueType||!valueType._zod){return new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...normalizeParams(valueType)})}return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params)})}function partialRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...normalizeParams(params),partial:true})}function looseRecord(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,mode:"loose",...normalizeParams(params)})}var ZodMap=$constructor("ZodMap",(inst,def)=>{_ensureDefaultMemoizer();$ZodMap.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>mapProcessor(inst,ctx,json2,params);inst.keyType=def.keyType;inst.valueType=def.valueType;inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=(params)=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});function map(keyType,valueType,params){return new ZodMap({type:"map",keyType,valueType,...normalizeParams(params)})}var ZodSet=$constructor("ZodSet",(inst,def)=>{_ensureDefaultMemoizer();$ZodSet.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>setProcessor(inst,ctx,json2,params);inst.min=(...args)=>inst.check(_minSize(...args));inst.nonempty=(params)=>inst.check(_minSize(1,params));inst.max=(...args)=>inst.check(_maxSize(...args));inst.size=(...args)=>inst.check(_size(...args))});function set(valueType,params){return new ZodSet({type:"set",valueType,...normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>enumProcessor(inst,ctx,json2,params);inst.enum=def.entries;inst.options=[...inst._zod.values];const keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{const newEntries={};for(const value of values){if(keys.has(value)){newEntries[value]=def.entries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})};inst.exclude=(values,params)=>{const newEntries={...def.entries};for(const value of values){if(keys.has(value)){delete newEntries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...normalizeParams(params),entries:newEntries})}});function _enum2(values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...normalizeParams(params)})}function nativeEnum(entries,params){return new ZodEnum({type:"enum",entries,...normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>literalProcessor(inst,ctx,json2,params);inst.values=new Set(def.values);Object.defineProperty(inst,"value",{get(){if(def.values.length>1){throw new Error("This schema contains multiple valid literal values. Use `.values` instead.")}return def.values[0]}})});function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}var ZodFile=$constructor("ZodFile",(inst,def)=>{$ZodFile.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>fileProcessor(inst,ctx,json2,params);inst.min=(size,params)=>inst.check(_minSize(size,params));inst.max=(size,params)=>inst.check(_maxSize(size,params));inst.mime=(types,params)=>inst.check(_mime(Array.isArray(types)?types:[types],params))});function file(params){return _file(ZodFile,params)}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer();$ZodTransform.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>transformProcessor(inst,ctx,json2,params);inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward"){throw new $ZodEncodeError(inst.constructor.name)}payload.addIssue=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");if(!("input"in _issue))_issue.input=payload.value;_issue.inst??(_issue.inst=inst);payload.issues.push(issue(_issue))}};const output=def.transform(payload.value,payload);if(output instanceof Promise){return output.then((output)=>{payload.value=output;return payload})}payload.value=output;return payload}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>optionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nullableProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>defaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeDefault=inst.unwrap});function _default2(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>prefaultProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nonoptionalProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...normalizeParams(params)})}var ZodSuccess=$constructor("ZodSuccess",(inst,def)=>{$ZodSuccess.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>successProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function success(innerType){return new ZodSuccess({type:"success",innerType})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>catchProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType;inst.removeCatch=inst.unwrap});function _catch2(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:constantCatch(catchValue)})}var ZodNaN=$constructor("ZodNaN",(inst,def)=>{$ZodNaN.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>nanProcessor(inst,ctx,json2,params)});function nan(params){return _nan(ZodNaN,params)}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>pipeProcessor(inst,ctx,json2,params);inst.in=def.in;inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodCodec=$constructor("ZodCodec",(inst,def)=>{ZodPipe.init(inst,def);$ZodCodec.init(inst,def)});function codec(in_,out,params){return new ZodCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){const def=codec2._zod.def;return new ZodCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def);$ZodPreprocess.init(inst,def)});var ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>readonlyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>templateLiteralProcessor(inst,ctx,json2,params)});function templateLiteral(parts,params){return new ZodTemplateLiteral({type:"template_literal",parts,...normalizeParams(params)})}var ZodLazy=$constructor("ZodLazy",(inst,def)=>{$ZodLazy.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>lazyProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.getter()});function lazy(getter){return new ZodLazy({type:"lazy",getter})}var ZodPromise=$constructor("ZodPromise",(inst,def)=>{$ZodPromise.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>promiseProcessor(inst,ctx,json2,params);inst.unwrap=()=>inst._zod.def.innerType});function promise(innerType){return new ZodPromise({type:"promise",innerType})}var ZodFunction=$constructor("ZodFunction",(inst,def)=>{$ZodFunction.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>functionProcessor(inst,ctx,json2,params)});function _function(params){return new ZodFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json2,params)=>customProcessor(inst,ctx,json2,params)});function check(fn){const ch=new $ZodCheck({check:"custom"});ch._zod.check=fn;return ch}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>true),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}var describe2=describe;var meta2=meta;var ZodInstanceOf=$constructor("ZodInstanceOf",(inst,def)=>{ZodCustom.init(inst,def)},{properties(shape,params){return this.check(_properties(shape,params))}});function _instanceof(cls,params={}){const inst=new ZodInstanceOf({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:true,...normalizeParams(params)});inst._zod.bag.Class=cls;inst._zod.check=(payload)=>{if(!(payload.value instanceof cls)){payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})}};return inst}var stringbool=(...args)=>_stringbool({Codec:ZodCodec,Boolean:ZodBoolean,String:ZodString},...args);function json(params){const jsonSchema=lazy(()=>{return union([string2(params),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function setErrorMap(map){config({customError:map})}function getErrorMap(){return config().customError}var ZodFirstPartyTypeKind;(function(ZodFirstPartyTypeKind){})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date3(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var z={...exports_schemas2,...exports_checks2,iso:exports_iso};var RECOGNIZED_KEYS=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function detectVersion(schema,defaultTarget){const $schema=schema.$schema;if($schema==="https://json-schema.org/draft/2020-12/schema"){return"draft-2020-12"}if($schema==="http://json-schema.org/draft-07/schema#"){return"draft-7"}if($schema==="http://json-schema.org/draft-04/schema#"){return"draft-4"}return defaultTarget??"draft-2020-12"}function applyMinItems(items,minItems){return items.map((item,index)=>index<minItems?item:item.optional())}function decodeJSONPointerSegment(segment){return segment.replace(/~1/g,"/").replace(/~0/g,"~")}function resolveRef(ref,ctx){if(!ref.startsWith("#")){throw new Error("External $ref is not supported, only local refs (#/...) are allowed")}const path=ref.slice(1).split("/").filter(Boolean);if(path.length===0){return ctx.rootSchema}const defsKey=ctx.version==="draft-2020-12"?"$defs":"definitions";if(path[0]===defsKey){const key=path[1]===undefined?undefined:decodeJSONPointerSegment(path[1]);if(!key||!ctx.defs[key]){throw new Error(`Reference not found: ${ref}`)}return ctx.defs[key]}throw new Error(`Reference not found: ${ref}`)}function checkObjectGuards(objectSchema,guards){const guard=z.transform((value)=>value).check((payload)=>{const value=payload.value;if(typeof value!=="object"||value===null||Array.isArray(value))return;const keys=Object.getOwnPropertyNames(value);if(guards.minProperties!==undefined&&keys.length<guards.minProperties){payload.issues.push({origin:"object",code:"too_small",minimum:guards.minProperties,inclusive:true,message:`Too small: expected object to have >=${guards.minProperties} properties`,input:value,inst:objectSchema,continue:true})}if(guards.maxProperties!==undefined&&keys.length>guards.maxProperties){payload.issues.push({origin:"object",code:"too_big",maximum:guards.maxProperties,inclusive:true,message:`Too big: expected object to have <=${guards.maxProperties} properties`,input:value,inst:objectSchema,continue:true})}if(guards.keySchema){for(const key of keys){const result=guards.keySchema.safeParse(key);if(result.success)continue;payload.issues.push({code:"invalid_key",origin:"record",issues:result.error.issues,input:key,path:[key],continue:true})}}});return guard.pipe(objectSchema)}function canonicalKey(value,seen){if(value===null)return"z";const type=typeof value;if(type!=="object"){if(type==="number"&&Number.isNaN(value))return null;const raw=String(value);return`${type[0]}${raw.length}:${raw}`}if(seen.has(value))return null;seen.add(value);try{if(Array.isArray(value)){const parts=[];for(const item of value){const key=canonicalKey(item,seen);if(key===null)return null;parts.push(key)}return`a${parts.length}:[${parts.join(",")}]`}const keys=Object.keys(value).sort();const parts=[];for(const k of keys){const key=canonicalKey(value[k],seen);if(key===null)return null;parts.push(`${k.length}:${k}=${key}`)}return`o${parts.length}:{${parts.join(",")}}`}finally{seen.delete(value)}}var SCHEMA_KEYWORDS=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]);var SCHEMA_MAP_KEYWORDS=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function containsRef(value){if(typeof value!=="object"||value===null)return false;if(Array.isArray(value))return value.some(containsRef);if(typeof value.$ref==="string")return true;return Object.entries(value).some(([key,sub])=>{if(SCHEMA_KEYWORDS.has(key))return containsRef(sub);if(!SCHEMA_MAP_KEYWORDS.has(key)||typeof sub!=="object"||sub===null)return false;return Object.values(sub).some(containsRef)})}function plural(n){return n===1?"element":"elements"}function checkArrayGuards(arraySchema,guards){const guard=z.transform((value)=>value).check((payload)=>{const items=payload.value;if(!Array.isArray(items))return;if(guards.uniqueItems===true){const firstSeen=new Map;for(let i=0;i<items.length;i++){const key=canonicalKey(items[i],new Set);if(key===null)continue;const first=firstSeen.get(key);if(first===undefined){firstSeen.set(key,i);continue}payload.issues.push({code:"custom",message:`Array items must be unique: element at index ${i} duplicates the one at index ${first}`,input:items,path:[i],continue:true})}}if(guards.containsSchema){const minContains=guards.minContains??1;const ceiling=guards.maxContains!==undefined?guards.maxContains+1:Number.POSITIVE_INFINITY;let matches=0;for(const item of items){if(guards.containsSchema.safeParse(item).success&&++matches>=ceiling)break}if(matches<minContains){payload.issues.push({code:"custom",message:`Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,input:items,continue:true})}if(guards.maxContains!==undefined&&matches>guards.maxContains){payload.issues.push({code:"custom",message:`Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,input:items,continue:true})}}});return guard.pipe(arraySchema)}function getTupleRest(restSchema,ctx){if(restSchema===false){return}if(restSchema===undefined||restSchema===true){return z.any()}return convertSchema(restSchema,ctx)}var fullTime=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function convertBaseSchema(schema,ctx){if(schema.not!==undefined){if(typeof schema.not==="object"&&Object.keys(schema.not).length===0){return z.never()}throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(schema.unevaluatedItems!==undefined){throw new Error("unevaluatedItems is not supported")}if(schema.unevaluatedProperties!==undefined){throw new Error("unevaluatedProperties is not supported")}if(schema.if!==undefined||schema.then!==undefined||schema.else!==undefined){throw new Error("Conditional schemas (if/then/else) are not supported")}if(schema.dependentSchemas!==undefined||schema.dependentRequired!==undefined){throw new Error("dependentSchemas and dependentRequired are not supported")}if(schema.$ref){const refPath=schema.$ref;if(ctx.refs.has(refPath)){return ctx.refs.get(refPath)}if(ctx.processing.has(refPath)){return z.lazy(()=>{if(!ctx.refs.has(refPath)){throw new Error(`Circular reference not resolved: ${refPath}`)}return ctx.refs.get(refPath)})}ctx.processing.add(refPath);const resolved=resolveRef(refPath,ctx);const zodSchema=convertSchema(resolved,ctx);ctx.refs.set(refPath,zodSchema);ctx.processing.delete(refPath);return zodSchema}if(schema.enum!==undefined){const enumValues=schema.enum;if(ctx.version==="openapi-3.0"&&schema.nullable===true&&enumValues.length===1&&enumValues[0]===null){return z.null()}if(enumValues.length===0){return z.never()}if(enumValues.length===1){return z.literal(enumValues[0])}if(enumValues.every((v)=>typeof v==="string")){return z.enum(enumValues)}const literalSchemas=enumValues.map((v)=>z.literal(v));if(literalSchemas.length<2){return literalSchemas[0]}return z.union([literalSchemas[0],literalSchemas[1],...literalSchemas.slice(2)])}if(schema.const!==undefined){return z.literal(schema.const)}const type=schema.type;if(Array.isArray(type)){const typeSchemas=type.map((t)=>{const typeSchema={...schema,type:t};return convertBaseSchema(typeSchema,ctx)});if(typeSchemas.length===0){return z.never()}if(typeSchemas.length===1){return typeSchemas[0]}return z.union(typeSchemas)}if(!type){return z.any()}let zodSchema;switch(type){case"string":{let stringSchema=z.string();if(schema.format){const format=schema.format;if(format==="email"){stringSchema=stringSchema.check(z.email())}else if(format==="uri"||format==="uri-reference"){stringSchema=stringSchema.check(z.url())}else if(format==="uuid"||format==="guid"){stringSchema=stringSchema.check(z.uuid())}else if(format==="date-time"){stringSchema=stringSchema.check(z.iso.datetime({offset:true}))}else if(format==="date"){stringSchema=stringSchema.check(z.iso.date())}else if(format==="time"){stringSchema=stringSchema.check(z.regex(fullTime))}else if(format==="duration"){stringSchema=stringSchema.check(z.iso.duration())}else if(format==="hostname"){stringSchema=stringSchema.check(z.hostname())}else if(format==="ipv4"){stringSchema=stringSchema.check(z.ipv4())}else if(format==="ipv6"){stringSchema=stringSchema.check(z.ipv6())}else if(format==="mac"){stringSchema=stringSchema.check(z.mac())}else if(format==="cidr"){stringSchema=stringSchema.check(z.cidrv4())}else if(format==="cidr-v6"){stringSchema=stringSchema.check(z.cidrv6())}else if(format==="base64"){stringSchema=stringSchema.check(z.base64())}else if(format==="base64url"){stringSchema=stringSchema.check(z.base64url())}else if(format==="e164"){stringSchema=stringSchema.check(z.e164())}else if(format==="credit_card"){stringSchema=stringSchema.check(z.creditCard())}else if(format==="iban"){stringSchema=stringSchema.check(z.iban())}else if(format==="jwt"){stringSchema=stringSchema.check(z.jwt())}else if(format==="emoji"){stringSchema=stringSchema.check(z.emoji())}else if(format==="nanoid"){stringSchema=stringSchema.check(z.nanoid())}else if(format==="cuid"){stringSchema=stringSchema.check(z.cuid())}else if(format==="cuid2"){stringSchema=stringSchema.check(z.cuid2())}else if(format==="ulid"){stringSchema=stringSchema.check(z.ulid())}else if(format==="xid"){stringSchema=stringSchema.check(z.xid())}else if(format==="ksuid"){stringSchema=stringSchema.check(z.ksuid())}}if(typeof schema.minLength==="number"){stringSchema=stringSchema.min(schema.minLength)}if(typeof schema.maxLength==="number"){stringSchema=stringSchema.max(schema.maxLength)}if(schema.pattern){stringSchema=stringSchema.regex(new RegExp(schema.pattern))}zodSchema=stringSchema;break}case"number":case"integer":{let numberSchema=type==="integer"?z.number().int():z.number();if(typeof schema.minimum==="number"&&schema.exclusiveMinimum!==true){numberSchema=numberSchema.min(schema.minimum)}if(typeof schema.maximum==="number"&&schema.exclusiveMaximum!==true){numberSchema=numberSchema.max(schema.maximum)}if(typeof schema.exclusiveMinimum==="number"){numberSchema=numberSchema.gt(schema.exclusiveMinimum)}else if(schema.exclusiveMinimum===true&&typeof schema.minimum==="number"){numberSchema=numberSchema.gt(schema.minimum)}if(typeof schema.exclusiveMaximum==="number"){numberSchema=numberSchema.lt(schema.exclusiveMaximum)}else if(schema.exclusiveMaximum===true&&typeof schema.maximum==="number"){numberSchema=numberSchema.lt(schema.maximum)}if(typeof schema.multipleOf==="number"){numberSchema=numberSchema.multipleOf(schema.multipleOf)}zodSchema=numberSchema;break}case"boolean":{zodSchema=z.boolean();break}case"null":{zodSchema=z.null();break}case"object":{const shape={};const properties=schema.properties||{};const requiredSet=new Set(schema.required||[]);const additionalSchema=typeof schema.additionalProperties==="object"?convertSchema(schema.additionalProperties,ctx):undefined;for(const[key,propSchema]of Object.entries(properties)){const propZodSchema=convertSchema(propSchema,ctx);assignProp(shape,key,requiredSet.has(key)?propZodSchema:propZodSchema.optional())}if(schema.patternProperties){const patternProps=schema.patternProperties;const patternKeys=Object.keys(patternProps);const looseRecords=[];for(const pattern of patternKeys){const patternValue=convertSchema(patternProps[pattern],ctx);const keySchema=z.string().regex(new RegExp(pattern));looseRecords.push(z.looseRecord(keySchema,patternValue))}const schemasToIntersect=[];if(Object.keys(shape).length>0){schemasToIntersect.push(z.object(shape).passthrough())}schemasToIntersect.push(...looseRecords);if(schemasToIntersect.length===0){zodSchema=z.object({}).passthrough()}else if(schemasToIntersect.length===1){zodSchema=schemasToIntersect[0]}else{let result=z.intersection(schemasToIntersect[0],schemasToIntersect[1]);for(let i=2;i<schemasToIntersect.length;i++){result=z.intersection(result,schemasToIntersect[i])}zodSchema=result}if(schema.additionalProperties===false){const propertyKeys=Object.keys(shape);const patterns=patternKeys.map((p)=>new RegExp(p));const basePatternSchema=zodSchema;zodSchema=zodSchema.check((payload)=>{if(!isPlainObject(payload.value))return;const unrecognized=[];for(const key of Object.keys(payload.value)){if(propertyKeys.includes(key))continue;if(patterns.some((regex)=>regex.test(key)))continue;unrecognized.push(key)}if(unrecognized.length){payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input:payload.value,inst:basePatternSchema})}})}}else{const objectSchema=z.object(shape);if(schema.additionalProperties===false){zodSchema=objectSchema.strict()}else if(additionalSchema){zodSchema=objectSchema.catchall(additionalSchema)}else{zodSchema=objectSchema.passthrough()}}const hasKeyGuard=schema.propertyNames!==undefined&&schema.propertyNames!==true;const minProperties=typeof schema.minProperties==="number"?schema.minProperties:undefined;const maxProperties=typeof schema.maxProperties==="number"?schema.maxProperties:undefined;if(hasKeyGuard||minProperties!==undefined||maxProperties!==undefined){let keySchema;if(hasKeyGuard){const keyJSONSchema=typeof schema.propertyNames==="object"&&schema.propertyNames.type===undefined?{type:"string",...schema.propertyNames}:schema.propertyNames;keySchema=convertSchema(keyJSONSchema,ctx)}zodSchema=checkObjectGuards(zodSchema,{keySchema,minProperties,maxProperties})}break}case"array":{const prefixItems=schema.prefixItems;const items=schema.items;if(prefixItems&&Array.isArray(prefixItems)){const minItems=typeof schema.minItems==="number"?schema.minItems:0;const tupleItems=prefixItems.map((item)=>convertSchema(item,ctx));const positionalItems=applyMinItems(tupleItems,minItems);const rest=!Array.isArray(items)?getTupleRest(items,ctx):undefined;const tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema;if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(Array.isArray(items)){const minItems=typeof schema.minItems==="number"?schema.minItems:0;const tupleItems=items.map((item)=>convertSchema(item,ctx));const positionalItems=applyMinItems(tupleItems,minItems);const rest=getTupleRest(schema.additionalItems,ctx);const tupleSchema=z.tuple(positionalItems);zodSchema=rest?tupleSchema.rest(rest):tupleSchema;if(typeof schema.minItems==="number"){zodSchema=zodSchema.check(z.minLength(schema.minItems))}if(typeof schema.maxItems==="number"){zodSchema=zodSchema.check(z.maxLength(schema.maxItems))}}else if(items!==undefined){const element=convertSchema(items,ctx);let arraySchema=z.array(element);if(typeof schema.minItems==="number"){arraySchema=arraySchema.min(schema.minItems)}if(typeof schema.maxItems==="number"){arraySchema=arraySchema.max(schema.maxItems)}zodSchema=arraySchema}else{zodSchema=z.array(z.any())}if(schema.uniqueItems===true||schema.contains!==undefined){zodSchema=checkArrayGuards(zodSchema,{uniqueItems:schema.uniqueItems===true,containsSchema:schema.contains!==undefined?convertSchema(schema.contains,ctx):undefined,minContains:typeof schema.minContains==="number"?schema.minContains:undefined,maxContains:typeof schema.maxContains==="number"?schema.maxContains:undefined})}break}default:throw new Error(`Unsupported type: ${type}`)}return zodSchema}function convertSchema(schema,ctx){if(typeof schema==="boolean"){return schema?z.any():z.never()}let baseSchema=convertBaseSchema(schema,ctx);const hasExplicitType=schema.type||schema.enum!==undefined||schema.const!==undefined;if(schema.anyOf&&Array.isArray(schema.anyOf)){const options=schema.anyOf.map((s)=>convertSchema(s,ctx));const anyOfUnion=z.union(options);baseSchema=hasExplicitType?z.intersection(baseSchema,anyOfUnion):anyOfUnion}if(schema.oneOf&&Array.isArray(schema.oneOf)){const options=schema.oneOf.map((s)=>convertSchema(s,ctx));const oneOfUnion=z.xor(options);baseSchema=hasExplicitType?z.intersection(baseSchema,oneOfUnion):oneOfUnion}if(schema.allOf&&Array.isArray(schema.allOf)){if(schema.allOf.length===0){baseSchema=hasExplicitType?baseSchema:z.any()}else{let result=hasExplicitType?baseSchema:convertSchema(schema.allOf[0],ctx);const startIdx=hasExplicitType?0:1;for(let i=startIdx;i<schema.allOf.length;i++){result=z.intersection(result,convertSchema(schema.allOf[i],ctx))}baseSchema=result}}if(schema.nullable===true&&ctx.version==="openapi-3.0"){baseSchema=z.nullable(baseSchema)}if(schema.readOnly===true){baseSchema=z.readonly(baseSchema)}if(schema.default!==undefined){baseSchema=baseSchema.default(schema.default)}const extraMeta={};const coreMetadataKeys=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const key of coreMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}const contentMetadataKeys=["contentEncoding","contentMediaType","contentSchema"];for(const key of contentMetadataKeys){if(key in schema){extraMeta[key]=schema[key]}}if(schema.type==="object"&&schema.$ref===undefined){if(schema.propertyNames!==undefined&&!containsRef(schema.propertyNames)){extraMeta.propertyNames=schema.propertyNames}for(const key of["minProperties","maxProperties"]){if(schema[key]!==undefined)extraMeta[key]=schema[key]}}if(schema.type==="array"&&schema.$ref===undefined){if(schema.contains!==undefined&&!containsRef(schema.contains)){extraMeta.contains=schema.contains}for(const key of["uniqueItems","minContains","maxContains"]){if(schema[key]!==undefined)extraMeta[key]=schema[key]}}for(const key of Object.keys(schema)){if(!RECOGNIZED_KEYS.has(key)){assignProp(extraMeta,key,schema[key])}}if(Object.keys(extraMeta).length>0){ctx.registry.add(baseSchema,extraMeta)}if(schema.description){baseSchema=baseSchema.describe(schema.description)}return baseSchema}function fromJSONSchema(schema,params){if(typeof schema==="boolean"){return schema?z.any():z.never()}let normalized;try{normalized=JSON.parse(JSON.stringify(schema))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}const version=detectVersion(normalized,params?.defaultTarget);const defs=normalized.$defs||normalized.definitions||{};const ctx={version,defs,refs:new Map,processing:new Set,rootSchema:normalized,registry:params?.registry??globalRegistry};return convertSchema(normalized,ctx)}var RESOLVING=Symbol("z.visit/resolving");function visit(schema,fnOrHandlers){const fn=typeof fnOrHandlers==="function"?fnOrHandlers:(node,rewritten)=>{const h=fnOrHandlers[node._zod.def.type];return h?h(node,rewritten):node};const cache=new Map;function run(s){const cached=cache.get(s);if(cached===RESOLVING){return new $ZodLazy({type:"lazy",getter:()=>cache.get(s)})}if(cached!==undefined)return cached;cache.set(s,RESOLVING);const inner=mapInner(s);const mapped=fn(inner,inner!==s);cache.set(s,mapped);return mapped}function mapInner(s){const def=s._zod.def;const kind=def.type;switch(kind){case"object":{const oldShape=def.shape;const keys=Object.keys(oldShape);let changed=false;const newShape={};for(const k of keys){const mapped=run(oldShape[k]);if(mapped!==oldShape[k])changed=true;newShape[k]=mapped}let newCatchall=def.catchall;if(def.catchall){newCatchall=run(def.catchall);if(newCatchall!==def.catchall)changed=true}return changed?clone(s,{...def,shape:newShape,catchall:newCatchall}):s}case"array":{const mapped=run(def.element);return mapped===def.element?s:clone(s,{...def,element:mapped})}case"tuple":{const oldItems=def.items;let changed=false;const newItems=[];for(const item of oldItems){const mapped=run(item);if(mapped!==item)changed=true;newItems.push(mapped)}let newRest=def.rest;if(def.rest){newRest=run(def.rest);if(newRest!==def.rest)changed=true}return changed?clone(s,{...def,items:newItems,rest:newRest}):s}case"record":case"map":{const newKey=run(def.keyType);const newVal=run(def.valueType);return newKey===def.keyType&&newVal===def.valueType?s:clone(s,{...def,keyType:newKey,valueType:newVal})}case"set":{const newVal=run(def.valueType);return newVal===def.valueType?s:clone(s,{...def,valueType:newVal})}case"union":{const oldOptions=def.options;let changed=false;const newOptions=[];for(const opt of oldOptions){const mapped=run(opt);if(mapped!==opt)changed=true;newOptions.push(mapped)}return changed?clone(s,{...def,options:newOptions}):s}case"intersection":{const newLeft=run(def.left);const newRight=run(def.right);return newLeft===def.left&&newRight===def.right?s:clone(s,{...def,left:newLeft,right:newRight})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{const newInner=run(def.innerType);return newInner===def.innerType?s:clone(s,{...def,innerType:newInner})}case"pipe":{const newIn=run(def.in);const newOut=run(def.out);return newIn===def.in&&newOut===def.out?s:clone(s,{...def,in:newIn,out:newOut})}case"function":{const newInput=run(def.input);const newOutput=run(def.output);return newInput===def.input&&newOutput===def.output?s:clone(s,{...def,input:newInput,output:newOutput})}case"lazy":{const original=def.getter;const{_cachedInner,...rest}=def;return clone(s,{...rest,getter:()=>run(original())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:{return s}}}return run(schema)}function deepPartial(schema){return visit(schema,{object:(s)=>s.partial(),union:(s)=>{const def=s._zod.def;return def.discriminator===undefined?s:union(def.options)}})}function withChecks(side,checks){if(!checks?.length)return side;const def=side._zod.def;return clone(side,mergeDefs(def,{checks:[...def.checks??[],...checks]}),{parent:true})}function outSide(def){return withChecks(def.out,def.checks)}function inSide(def){return def.in._zod.traits.has("$ZodTransform")?outSide(def):def.in}function input(schema){return visit(schema,{pipe:(s)=>inSide(s._zod.def),default:(s,rewritten)=>rewritten?optional(s._zod.def.innerType):s,catch:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function output(schema){return visit(schema,{pipe:(s)=>outSide(s._zod.def),prefault:(s,rewritten)=>rewritten?s._zod.def.innerType:s})}function string3(params){return _coercedString(ZodString,params)}function number3(params){return _coercedNumber(ZodNumber,params)}function boolean3(params){return _coercedBoolean(ZodBoolean,params)}function bigint3(params){return _coercedBigint(ZodBigInt,params)}function date4(params){return _coercedDate(ZodDate,params)}import path from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{createReadStream}from"node:fs";import{tmpdir}from"node:os";import{readFileSync}from"node:fs";var pageBundle=readFileSync(new URL("./page-bundle.js",import.meta.url),"utf8");init_internal_capability();function normalizeDialogPolicy(policy){return policy??{accept:true}}function dialogFromOpening(params={}){return{type:params.type,message:params.message,defaultPrompt:params.defaultPrompt??"",url:params.url}}function decisionFromResult(result){if(typeof result==="boolean")return{accept:result};if(result&&typeof result==="object"){const decision={accept:result.accept!==false};if(result.promptText!==undefined)decision.promptText=result.promptText;return decision}return{accept:true}}async function resolveDialogAction(policy,params={}){try{const result=typeof policy==="function"?await policy(dialogFromOpening(params)):policy;return decisionFromResult(result)}catch{return{accept:true}}}var __defProp2=Object.defineProperty;var __exportAll=(definitions,namespace)=>{const exports={};for(const name in definitions)__defProp2(exports,name,{get:definitions[name],enumerable:true});if(!namespace)__defProp2(exports,Symbol.toStringTag,{value:"Module"});return exports};var __esmMin=(factory,value,error)=>()=>{if(error)throw error[0];try{return factory&&(value=factory(factory=0)),value}catch(caught){error=[caught];throw caught}};if(!Promise.withResolvers){Promise.withResolvers=()=>{let resolve,reject;const promise=new Promise((res,rej)=>{resolve=res;reject=rej});return{promise,resolve,reject}}}class Emittery{#listeners=new Map;on(name,listener){const listeners=this.#listeners.get(name)??new Set;listeners.add(listener);this.#listeners.set(name,listeners);return()=>{listeners.delete(listener)}}async emit(name,data){const event={data,eventName:name};await Promise.all([...this.#listeners.get(name)??[]].map((listener)=>listener(event)))}clearListeners(){this.#listeners.clear()}}var{object:object2,string:string$2,number:number$2,array:array2,union:union$1,unknown:unknown$1,null:_null4}=exports_zod;var SESSION_ARTIFACTS_DIR=path.join(tmpdir(),"omowright-artifacts");var noop=()=>{};var init_emittery=noop;var init_zod=noop;var init_context=noop;var init_utils$13=noop;var init_config=noop;var init_extension_bridge=noop;var init_commands$1=noop;var init_directory=noop;var init_process=noop;var init_event_bus=noop;var init_state_db=noop;var init_schema=noop;var init_store$1=noop;var init_drizzle_orm=noop;var init_types$8=noop;var init_nanoid=noop;function sleep$12(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted)return reject(signal.reason??Error("Aborted"));const onAbort=()=>{clearTimeout(timer);reject(signal.reason??Error("Aborted"))};const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);signal?.addEventListener("abort",onAbort,{once:true})})}function getCurrentReplAbortSignal(){return}function withCurrentReplAbort(fn){return fn()}function withoutReplContext(fn){return fn()}function replPrint(...values){console.warn(...values)}async function sendCommandToExtension(command){throw new UnsupportedOperationError(`Extension command is unavailable: ${command.method}`)}class UnsupportedOperationError extends Error{constructor(message){super(message);this.name="UnsupportedOperationError"}}var stateDb=()=>{throw new UnsupportedOperationError("Daemon persistence is unavailable")};var NotificationGrantTable={};function spawnCommand(){throw new UnsupportedOperationError("Video recording is unavailable")}async function waitForExitCode(){return 1}function isWebSocketUrl(xn){return xn.startsWith(`ws://`)||xn.startsWith(`wss://`)}function isAuthorizationError(xn){let jn=xn instanceof Error?xn.message:String(xn),Vn=xn;return jn.includes(`401`)||jn.includes(`403`)||jn.includes(`Missing or invalid Authorization header.`)||jn.includes(`Unauthorized`)||jn.includes(`Forbidden`)||typeof Vn.status==`number`&&(Vn.status===401||Vn.status===403)||typeof Vn.response?.status==`number`&&(Vn.response.status===401||Vn.response.status===403)||typeof Vn.error?.status==`number`&&(Vn.error.status===401||Vn.error.status===403)||typeof Vn.cause?.status==`number`&&(Vn.cause.status===401||Vn.cause.status===403)||String(Vn.error?.message??``).includes(`Missing or invalid Authorization header.`)||String(Vn.cause?.message??``).includes(`Missing or invalid Authorization header.`)}function normalizeBaseUrl(xn){return xn.replace(/\/$/,``)}function createAbortError$1(){let xn=Error(`Operation aborted`);return xn.name=`AbortError`,xn}var DEFAULT_COMMAND_TIMEOUT_MS;var DEFAULT_RECONNECT_DELAYS_MS;var jsonVersionSchema;var jsonTargetSchema;var cdpWireMessageSchema;var BrowserCdpCommandError;var CdpClient;var init_client$6=__esmMin(()=>{init_emittery(),init_zod(),init_context(),init_utils$13(),init_config(),init_extension_bridge(),init_commands$1(),DEFAULT_COMMAND_TIMEOUT_MS=30000,DEFAULT_RECONNECT_DELAYS_MS=[0,250,750,1500,3000],jsonVersionSchema=object2({Browser:string$2().optional(),"Protocol-Version":string$2().optional(),"User-Agent":string$2().optional(),"V8-Version":string$2().optional(),"WebKit-Version":string$2().optional(),webSocketDebuggerUrl:string$2()}).loose(),jsonTargetSchema=object2({description:string$2().optional(),devtoolsFrontendUrl:string$2().optional(),faviconUrl:string$2().optional(),id:string$2(),parentId:string$2().optional(),title:string$2().default(``),type:string$2(),url:string$2().default(``),webSocketDebuggerUrl:string$2().optional()}).loose(),cdpWireMessageSchema=union$1([object2({id:number$2(),sessionId:string$2().optional(),error:object2({code:number$2().optional(),data:unknown$1().optional(),message:string$2()}).loose().optional(),result:unknown$1().optional()}).loose(),object2({method:string$2(),params:unknown$1().optional(),sessionId:string$2().optional()}).loose(),_null4()]),BrowserCdpCommandError=class extends Error{method;code;data;constructor(xn,jn,Vn,qn){super(qn??`CDP command failed: ${xn}`),this.method=xn,this.code=jn,this.data=Vn}},CdpClient=class{cdpUrl;logId;#dialogPolicy;#e;#t;#n;#r=null;#i=null;#a=null;#o=false;#s=1;#c=new Map;#l=new Emittery;#u=false;transportEvents=new Emittery;constructor(xn={}){if(typeof xn.cdpUrl!=`string`||xn.cdpUrl===``)throw TypeError(`CdpClient requires a cdpUrl: there is no default endpoint, so a missing URL can never reach a browser on 127.0.0.1:9222`);this.cdpUrl=normalizeBaseUrl(xn.cdpUrl),this.logId=xn.logId??`cdp-${Date.now()}`,this.#e=xn.authorizer,this.#t=xn.commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS,this.#n=xn.reconnectDelaysMs??DEFAULT_RECONNECT_DELAYS_MS,this.#dialogPolicy=normalizeDialogPolicy(xn.dialogPolicy)}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(xn){this.#dialogPolicy=normalizeDialogPolicy(xn)}get isConnected(){return this.#r?.readyState===wrapper_default.OPEN}start(){this.#o||(this.#o=true,this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] Initial CDP connect failed`,xn),this.#b()}))}async discoverVersion(xn={}){return await this.#f(this.#d(`/json/version`),jsonVersionSchema,xn)}async discoverTargets(xn={}){return await this.#f(this.#d(`/json/list`),array2(jsonTargetSchema),xn)}async ensureConnected(){if(this.#o=true,this.isConnected)return;if(this.#i){await this.#i;return}let xn=this.#g();this.#i=xn;try{await xn}finally{this.#i===xn&&(this.#i=null)}}async send(xn,jn,Vn,qn={}){if(xn===`Target.createTarget`&&qn.capability!==targetCreationCapability)throw Error(`Target.createTarget is reserved for createAgentTabs`);let Jn=getCurrentReplAbortSignal();if(Jn?.aborted)throw createAbortError$1();if(xn.startsWith(`OmO.`)){let Vn=await sendCommandToExtension({method:xn,params:jn},{...qn.extensionBridge,signal:Jn});if(Jn?.aborted)throw createAbortError$1();return Vn}await this.ensureConnected();let Yn=this.#r;if(!Yn||Yn.readyState!==wrapper_default.OPEN)throw Error(`CDP websocket is not connected`);let Zn=this.#s++,Qn={id:Zn,method:xn};jn!==undefined&&(Qn.params=jn),Vn&&(Qn.sessionId=Vn);let{promise:ei,reject:ti,resolve:ni}=Promise.withResolvers(),ri=qn.timeoutMs??this.#t,ii=ri>0?setTimeout(()=>{this.#c.delete(Zn),ti(Error(`CDP command timeout: ${String(xn)}`))},ri):undefined,ai=Jn?()=>{ii&&clearTimeout(ii),this.#c.delete(Zn),ti(createAbortError$1())}:undefined;if(this.#c.set(Zn,{method:String(xn),reject:ti,resolve:ni,timeout:ii}),Jn?.addEventListener(`abort`,ai,{once:true}),Jn?.aborted)return ai?.(),await ei;try{Yn.send(JSON.stringify(Qn))}catch(xn){throw ii&&clearTimeout(ii),this.#c.delete(Zn),ai&&Jn?.removeEventListener(`abort`,ai),xn instanceof Error?xn:Error(String(xn))}try{return await ei}finally{ai&&Jn?.removeEventListener(`abort`,ai)}}on(xn,jn){return this.#l.on(xn,({data:xn})=>jn(xn.payload,xn.meta))}async close(){this.#o=false,this.#a&&=(clearTimeout(this.#a),null);let xn=this.#r;if(this.#r=null,this.#x(Error(`CDP client closed`)),xn&&xn.readyState<=wrapper_default.OPEN)try{xn.close(1000,`client closing`)}catch{}}#d(xn){let jn=new URL(this.cdpUrl);return isWebSocketUrl(this.cdpUrl)?(jn.protocol=jn.protocol===`wss:`?`https:`:`http:`,jn.pathname=xn,jn.search=``,jn.toString()):(jn.pathname=xn,jn.search=``,jn.toString())}async#f(xn,jn,Vn={}){let qn=await this.#p(Vn),Jn=await fetch(xn,{headers:qn});if((Jn.status===401||Jn.status===403)&&this.#e&&!Vn.forceRefresh)return await this.#f(xn,jn,{forceRefresh:true});if(!Jn.ok)throw Error(`CDP discovery request failed (${Jn.status} ${Jn.statusText})`);return jn.parse(await Jn.json())}async#p(xn={}){return this.#e?{Authorization:await this.#e.resolveAuthorization(xn)}:{}}async#m(xn={}){let jn=await this.#p(xn);return isWebSocketUrl(this.cdpUrl)?{headers:jn,wsUrl:this.cdpUrl}:{headers:jn,wsUrl:(await this.discoverVersion(xn)).webSocketDebuggerUrl}}async#g(){let xn=null,jn=false;for(let Vn of this.#n){Vn>0&&await sleep$12(Vn);try{await this.#_({forceRefresh:jn});return}catch(Vn){let qn=Vn??Error(`Unknown error`);xn=qn,isAuthorizationError(qn)&&(jn=true)}}throw xn instanceof Error?xn:Error(String(xn??`Failed to connect CDP websocket`))}async#_(xn={}){let{headers:jn,wsUrl:Vn}=await this.#m(xn);await new Promise((xn,qn)=>{let Jn=new wrapper_default(Vn,{headers:jn}),Yn=false,Zn=(xn)=>{Yn||(Yn=true,qn(xn))};Jn.addEventListener(`open`,()=>{Yn||(Yn=true,this.#v(Jn),xn())}),Jn.addEventListener(`message`,(xn)=>{this.#r===Jn&&this.#S(xn.data).catch(()=>{})}),Jn.addEventListener(`close`,(xn)=>{this.#r===Jn&&this.#y(Jn),Yn||Zn(Error(`CDP websocket closed during connect (${xn.code} ${xn.reason||`no reason`})`))}),Jn.addEventListener(`error`,()=>{Zn(Error(`Failed to connect CDP websocket: ${Vn}`))})})}#v(xn){this.#a&&=(clearTimeout(this.#a),null);let jn=this.#r;if(this.#r=xn,this.send(`Target.setDiscoverTargets`,{discover:true}).catch(()=>{}),this.transportEvents.emit(this.#u?`reconnected`:`connected`).catch((xn)=>{console.warn(`[${this.logId}] CDP transport listener failed`,xn)}),this.#u=true,jn&&jn!==xn&&jn.readyState<=wrapper_default.OPEN)try{jn.close(1000,`replaced`)}catch{}}#y(xn){this.#r===xn&&(this.#r=null,this.#x(Error(`CDP websocket disconnected`)),this.transportEvents.emit(`disconnected`).catch((xn)=>{console.warn(`[${this.logId}] CDP disconnect listener failed`,xn)}),this.#o&&this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] CDP reconnect failed`,xn),this.#b()}))}#b(){if(!this.#o||this.isConnected||this.#i||this.#a)return;let xn=this.#n[this.#n.length-1]??3000;this.#a=setTimeout(()=>{this.#a=null,this.ensureConnected().catch((xn)=>{console.warn(`[${this.logId}] Scheduled CDP reconnect failed`,xn),this.#b()})},xn)}#x(xn){for(let jn of this.#c.values())jn.timeout&&clearTimeout(jn.timeout),jn.reject(xn);this.#c.clear()}async#S(xn){let jn=typeof xn==`string`?xn:xn instanceof Blob?await xn.text():new TextDecoder().decode(xn),{data:Vn}=cdpWireMessageSchema.safeParse(JSON.parse(jn));if(Vn){if(typeof Vn.id==`number`){let xn=this.#c.get(Vn.id);if(!xn)return;if(this.#c.delete(Vn.id),xn.timeout&&clearTimeout(xn.timeout),Vn.error){let jn=Vn.error;xn.reject(new BrowserCdpCommandError(xn.method,jn.code,jn.data,jn.message??`CDP command failed: ${xn.method}`));return}xn.resolve(Vn.result);return}if(typeof Vn.method==`string`){let xn=Vn.method;if(xn===`Page.javascriptDialogOpening`&&Vn.sessionId){let dialogSessionId=Vn.sessionId;resolveDialogAction(this.#dialogPolicy,Vn.params).then((dialogAction)=>{let xn=this.#r;xn?.readyState===wrapper_default.OPEN&&xn.send(JSON.stringify({id:this.#s++,method:`Page.handleJavaScriptDialog`,params:dialogAction,sessionId:dialogSessionId}))})}let jn={payload:Vn.params,meta:{sessionId:Vn.sessionId}};this.#l.emit(xn,jn).catch((jn)=>{console.warn(`[${this.logId}] CDP event listener failed for ${xn}`,jn)})}}}}});var SessionManager;var init_session_manager=__esmMin(()=>{init_client$6(),SessionManager=class{#e;#t=new Map;#n=new Map;#r=new Map;#i=new Set;#a;constructor(xn){this.#e=xn,this.#a=[this.#e.on(`Target.attachedToTarget`,(xn)=>{let jn=xn.targetInfo.targetId;jn&&this.#s(jn,xn.sessionId)}),this.#e.on(`Target.detachedFromTarget`,(xn)=>{let jn=xn.targetId??this.#n.get(xn.sessionId);this.#n.delete(xn.sessionId),jn&&this.#t.get(jn)===xn.sessionId&&this.#t.delete(jn)})]}clear(){this.#t.clear(),this.#n.clear(),this.#r.clear()}async dispose(){for(let xn of this.#a)xn();await Promise.allSettled([...this.#i].map((xn)=>this.#e.send(`Target.detachFromTarget`,{sessionId:xn}).catch(()=>{}))),this.#i.clear(),this.clear()}async discoverTargets(){return await this.#e.discoverTargets()}async getPageTarget(xn){return(await this.discoverTargets()).find((jn)=>jn.id===xn&&jn.type===`page`)??null}hasTargetSession(xn,jn){return this.#t.get(xn)===jn}getTargetSession(xn){return this.#t.get(xn)}async resolvePageSession(xn,jn){if(jn&&this.hasTargetSession(xn,jn))return jn;let Vn=this.#t.get(xn);if(Vn)return Vn;let qn=this.#r.get(xn);if(qn)return await qn;let Jn=this.#o(xn).finally(()=>{this.#r.delete(xn)});return this.#r.set(xn,Jn),await Jn}async#o(xn){if(!await this.getPageTarget(xn))throw Error(`Tab ${xn} is no longer available.`);let jn=await this.#e.send(`Target.attachToTarget`,{targetId:xn,flatten:true});return this.#i.add(jn.sessionId),this.#s(xn,jn.sessionId),jn.sessionId}#s(xn,jn){this.#t.set(xn,jn),this.#n.set(jn,xn)}}});var init_cdp=__esmMin(()=>{init_client$6(),init_session_manager()});var BUNDLE$1;var init_omowright_world_bundle=__esmMin(()=>{BUNDLE$1=pageBundle});var MAX_BUFFER_SIZE;var CONSOLE_INTERCEPTOR_SCRIPT;var PageConsole;var init_console_capture=__esmMin(()=>{MAX_BUFFER_SIZE=1000,CONSOLE_INTERCEPTOR_SCRIPT=`(function(){
67
67
  if(window.__omowrightConsole)return;
68
68
  var logs=[];
69
69
  var orig={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug};
@@ -232,7 +232,6 @@ ${qn.join(`
232
232
  const isComboboxLike = !!this.matches?.('[role="combobox"], [aria-haspopup="listbox"], summary');
233
233
  const isLink = this.tagName?.toUpperCase() === 'A';
234
234
  const href = isLink ? (this.getAttribute?.('href') || '') : '';
235
- const absoluteHref = isLink ? this.href : '';
236
235
  const role = String(this.getAttribute?.('role') || '').toLowerCase();
237
236
  const nativeCheckable = this instanceof HTMLInputElement
238
237
  ? this
@@ -263,7 +262,6 @@ ${qn.join(`
263
262
  isComboboxLike,
264
263
  isCheckable: isNativeCheckable || checked !== null,
265
264
  isRadio: nativeType === 'radio' || role === 'radio',
266
- popupUrl: prefersDomActivation && this.target === '_blank' ? absoluteHref : null,
267
265
  prefersDomActivation,
268
266
  expanded: isComboboxLike ? this.getAttribute?.('aria-expanded') ?? null : null,
269
267
  };
@@ -309,7 +307,7 @@ ${qn.join(`
309
307
  if (target && 'blur' in target && typeof target.blur === 'function') {
310
308
  target.blur();
311
309
  }
312
- }`)}async function readComboboxState(xn,jn){let Vn=await readClickTargetState(xn,jn);return{hasComboboxTarget:Vn.isComboboxLike,expanded:Vn.expanded}}async function clickComboboxFallback(xn,jn){await domClickTarget(xn,jn)}async function clickElement(xn,jn,Vn={},qn=defaultModifierState){let Jn=await resolveClickTarget(xn,jn),Yn=Vn.modifiers??[],Zn=[],Qn=await xn.resolveSessionId(),ei=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:false,expanded:null})),ti=await readClickTargetState(xn,Jn).catch(()=>({expanded:null,checked:null,isComboboxLike:false,isCheckable:false,isRadio:false,popupUrl:null,prefersDomActivation:false}));try{let jn=async()=>{let jn=async()=>!ti.isCheckable||ti.checked===null||ti.isRadio&&ti.checked?true:(await readClickTargetState(xn,Jn).catch(()=>null))?.checked!==ti.checked,ni=async()=>{if(ti.popupUrl&&xn.openPopupUrl){await xn.openPopupUrl(ti.popupUrl);return}await domClickTarget(xn,Jn)};if(ti.prefersDomActivation){if(await ni(),!await jn())throw Error(`Checkbox click did not change checked state`);return}let ri;try{let jn=Vn.force?await getPointerDispatchTarget(xn,Jn):await ensurePointerActionable(xn,Jn);ri=jn.point,Qn=jn.sessionId}catch(qn){let Yn=qn instanceof Error?qn.message:String(qn);if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;if(!Vn.force&&Yn.includes(`obscured`)){await domClickTarget(xn,Jn);return}throw qn}let{x:ii,y:ai}=ri;try{for(let jn of Yn)await keyDown(xn,Qn,jn,qn),Zn.push(jn);Vn.moveBeforeClick!==false&&await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:ii,y:ai,button:`none`,modifiers:qn.toModifiersMask()},Qn);let jn=Vn.dblClick?2:1;await xn.prepareForPotentialFileChooser?.();for(let Vn=1;Vn<=jn;Vn+=1)await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:ii,y:ai,button:`left`,buttons:1,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn),await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:ii,y:ai,button:`left`,buttons:0,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn)}catch(xn){if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;throw xn}ei.hasComboboxTarget&&ei.expanded===`false`&&await sleep$12(80);let oi=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:false,expanded:null}));if(ei.hasComboboxTarget&&ei.expanded===`false`&&oi.expanded===`false`&&await clickComboboxFallback(xn,Jn),!await jn()&&(await ni(),!await jn()))throw Error(`Checkbox click did not change checked state`)};if(Vn.waitAfter===false)await jn();else try{await performActionAndWait(xn,jn,{frameSessionId:Jn.frameSessionId})}catch(xn){if(xn instanceof NavigationReadinessTimeoutError&&xn.mode===`interactive`){replPrint(`[warning] Waited ${xn.timeoutMs}ms for the page to become ready after the click.`);return}throw xn}}finally{for(let jn=Zn.length-1;jn>=0;--jn)await keyUp(xn,Qn,Zn[jn],qn).catch(()=>{})}}async function fillElement(xn,jn,Vn){let qn=await resolveActionSessionId(xn,jn),Jn=await callOnElementSync(xn,jn,`function(nextValue, setValueTypes, typeIntoTypes) {
310
+ }`)}async function readComboboxState(xn,jn){let Vn=await readClickTargetState(xn,jn);return{hasComboboxTarget:Vn.isComboboxLike,expanded:Vn.expanded}}async function clickComboboxFallback(xn,jn){await domClickTarget(xn,jn)}async function clickElement(xn,jn,Vn={},qn=defaultModifierState){let Jn=await resolveClickTarget(xn,jn),Yn=Vn.modifiers??[],Zn=[],Qn=await xn.resolveSessionId(),ei=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:false,expanded:null})),ti=await readClickTargetState(xn,Jn).catch(()=>({expanded:null,checked:null,isComboboxLike:false,isCheckable:false,isRadio:false,prefersDomActivation:false}));try{let jn=async()=>{let jn=async()=>!ti.isCheckable||ti.checked===null||ti.isRadio&&ti.checked?true:(await readClickTargetState(xn,Jn).catch(()=>null))?.checked!==ti.checked,ni=async()=>{await domClickTarget(xn,Jn)};if(ti.prefersDomActivation){if(await ni(),!await jn())throw Error(`Checkbox click did not change checked state`);return}let ri;try{let jn=Vn.force?await getPointerDispatchTarget(xn,Jn):await ensurePointerActionable(xn,Jn);ri=jn.point,Qn=jn.sessionId}catch(qn){let Yn=qn instanceof Error?qn.message:String(qn);if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;if(!Vn.force&&Yn.includes(`obscured`)){await domClickTarget(xn,Jn);return}throw qn}let{x:ii,y:ai}=ri;try{for(let jn of Yn)await keyDown(xn,Qn,jn,qn),Zn.push(jn);Vn.moveBeforeClick!==false&&await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:ii,y:ai,button:`none`,modifiers:qn.toModifiersMask()},Qn);let jn=Vn.dblClick?2:1;await xn.prepareForPotentialFileChooser?.();for(let Vn=1;Vn<=jn;Vn+=1)await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:ii,y:ai,button:`left`,buttons:1,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn),await xn.cdp.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:ii,y:ai,button:`left`,buttons:0,clickCount:Vn,modifiers:qn.toModifiersMask()},Qn)}catch(xn){if(ti.isCheckable&&(await jn()||(await ni(),await jn())))return;throw xn}ei.hasComboboxTarget&&ei.expanded===`false`&&await sleep$12(80);let oi=await readComboboxState(xn,Jn).catch(()=>({hasComboboxTarget:false,expanded:null}));if(ei.hasComboboxTarget&&ei.expanded===`false`&&oi.expanded===`false`&&await clickComboboxFallback(xn,Jn),!await jn()&&(await ni(),!await jn()))throw Error(`Checkbox click did not change checked state`)};if(Vn.waitAfter===false)await jn();else try{await performActionAndWait(xn,jn,{frameSessionId:Jn.frameSessionId})}catch(xn){if(xn instanceof NavigationReadinessTimeoutError&&xn.mode===`interactive`){replPrint(`[warning] Waited ${xn.timeoutMs}ms for the page to become ready after the click.`);return}throw xn}}finally{for(let jn=Zn.length-1;jn>=0;--jn)await keyUp(xn,Qn,Zn[jn],qn).catch(()=>{})}}async function fillElement(xn,jn,Vn){let qn=await resolveActionSessionId(xn,jn),Jn=await callOnElementSync(xn,jn,`function(nextValue, setValueTypes, typeIntoTypes) {
313
311
  const target = globalThis.__omowright?.retarget(this, 'follow-label');
314
312
  if (!target) {
315
313
  return { mode: 'needsinput', kind: 'input', expectedValue: '', error: 'Unable to retarget element' };
@@ -679,7 +677,7 @@ ${qn.join(`
679
677
  throw new Error('$$eval pageFunction must evaluate to a function');
680
678
  }
681
679
  return await pageFunction(elements, arg);
682
- }`,arguments:Zn,executionContextId:Jn.contextId,returnByValue:true,awaitPromise:true,userGesture:false},await this.#e.resolveSessionId(Jn.frameSessionId));if(ei)throw Error(formatRuntimeException(ei,`$$eval failed`));return Qn.value}async boundingBox(){let xn=await this.#r();return await boundingBoxElement(this.#e,xn)}async screenshot(xn={}){let jn=xn.margin??DEFAULT_SCREENSHOT_MARGIN;if(!Number.isFinite(jn)||jn<0)throw Error(`locator.screenshot: margin must be a non-negative number`);let Vn=await this.#r(),qn=await evaluateOnElement(this.#e,Vn,`function(margin) {
680
+ }`,arguments:Zn,executionContextId:Jn.contextId,returnByValue:true,awaitPromise:true,userGesture:false},await this.#e.resolveSessionId(Jn.frameSessionId));if(ei)throw Error(formatRuntimeException(ei,`$$eval failed`));return Qn.value}async boundingBox(){let xn=await this.#r();return await boundingBoxElement(this.#e,xn)}async screenshot(xn={}){let jn=xn.margin??DEFAULT_SCREENSHOT_MARGIN;if(!Number.isFinite(jn)||jn<0)throw Error(`locator.screenshot: margin must be a non-negative number`);let Vn=await this.#r(),qn=await evaluateOnElement(this.#e,Vn,`function(_, margin) {
683
681
  const rect = this.getBoundingClientRect();
684
682
  if (rect.width <= 0 || rect.height <= 0) {
685
683
  return null;
@@ -1466,22 +1464,15 @@ ${qn.join(`
1466
1464
  return globalThis.__omowright.takeSnapshot(opts);
1467
1465
  }`,arguments:[{value:ai}],executionContextId:ii,returnByValue:true,awaitPromise:false,userGesture:false},jn.getFrame(qn)?.sessionId),Yn=Vn.value;if(Yn){if(Yn.error){Jn&&(ri=Yn.error);return}ni.set(qn,Yn);return}}catch(xn){Qn=xn,isContextDestroyedError(xn)&&jn.invalidateContext(qn)}Jn&&Zn-1}Jn&&(ri=Qn)}));let ii=ni.get(ei);if(!ii){let xn=ri;throw xn instanceof Error?xn:typeof xn==`string`&&xn.length>0?Error(xn):Error(ei===qn?`Main frame snapshot failed`:`Ref subtree snapshot failed`)}let ai=new Map,oi=new Map;await Promise.all(ti.map(async({frameId:Vn})=>{let qn=ni.get(Vn),Jn=jn.getFrame(Vn);if(!qn||!Jn?.isolatedContextId)return;let Yn=Object.entries(qn.refs).filter(([,xn])=>xn.tagName.toLowerCase()===`iframe`).map(([xn])=>xn);if(Yn.length===0)return;let Zn=await Promise.all(Yn.map(async(qn)=>{let{result:Yn}=await xn.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(ref) {
1468
1466
  return globalThis.__omowright.elementRegistry.get(ref);
1469
- }`,arguments:[{value:qn}],executionContextId:Jn.isolatedContextId,returnByValue:false},Jn.sessionId).catch((xn)=>(isContextDestroyedError(xn)&&jn.invalidateContext(Vn),{result:{}})),Zn=typeof Yn==`object`&&Yn&&`objectId`in Yn?Yn.objectId:undefined;if(!Zn)return null;try{let{node:Vn}=await xn.send(`DOM.describeNode`,{objectId:Zn},Jn.sessionId),Yn=Vn.frameId?jn.getFrame(Vn.frameId)?.url:null,Qn=getCdpNodeAttribute(Vn.attributes,`src`),ei=getKnownIframeOriginLabel(Yn??``)??getKnownIframeOriginLabel(Qn??``);return{childFrameId:Vn.frameId,iframeRef:qn,originLabel:ei}}catch{return null}finally{await xn.send(`Runtime.releaseObject`,{objectId:Zn},Jn.sessionId).catch(()=>{})}})),Qn=new Map,ei=new Map;for(let xn of Zn)xn&&(xn.childFrameId&&Qn.set(xn.childFrameId,xn.iframeRef),xn.originLabel&&ei.set(xn.iframeRef,xn.originLabel));ai.set(Vn,Qn),ei.size>0&&oi.set(Vn,ei)}));let si=[...ti].sort((xn,jn)=>jn.depth-xn.depth),ci={};for(let xn of ni.values())Object.assign(ci,xn.refs);for(let[xn,jn]of oi){let Vn=ni.get(xn);if(Vn)for(let[xn,qn]of jn)Vn.tree=tagIframeLine(Vn.tree,xn,qn)}for(let xn of si){if(xn.frameId===qn||!xn.parentFrameId)continue;let Vn=ni.get(xn.frameId),Jn=ni.get(xn.parentFrameId);if(!Vn||!Jn||!Vn.tree)continue;let Yn=ai.get(xn.parentFrameId)?.get(xn.frameId),Zn=getKnownIframeOriginLabel(jn.getFrame(xn.frameId)?.url??``);Jn.tree=Yn?inlineChildTree(Jn.tree,Yn,Vn.tree):appendOrphanChildTree(Jn.tree,Vn.tree,Zn)}return{tree:ii.tree,refs:ci}}var KNOWN_IFRAME_ORIGINS;var SNAPSHOT_RETRY_DELAY_MS;var SNAPSHOT_MAX_RETRIES;var init_snapshot=__esmMin(()=>{init_extension_ids(),init_utils$13(),init_client$6(),init_frame_manager(),KNOWN_IFRAME_ORIGINS=[{urlPrefix:`chrome-extension://aeblfdkhhhdcdjpifhhbdiojplfjncoa/`,label:`1Password`},{urlPrefix:`chrome-extension://nngceckbapebfimnlniiiahkandclblb/`,label:`Bitwarden`},{urlPrefix:`chrome-extension://fdjamakpfbbddfjaooikfcpapjohcfmg/`,label:`Dashlane`},{urlPrefix:`chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/`,label:`LastPass`},{urlPrefix:`${PASSWORD_MANAGER_EXTENSION_ORIGIN}/`,label:`OmO Password Manager`}],SNAPSHOT_RETRY_DELAY_MS=300,SNAPSHOT_MAX_RETRIES=3});function diffLines(xn,jn){let Vn=xn.length,qn=jn.length,Jn=Vn+qn;if(Jn===0)return[];if(Vn===qn&&xn.every((xn,Vn)=>xn===jn[Vn]))return xn.map((xn)=>({type:`equal`,line:xn}));let Yn=Jn,Zn=new Int32Array(2*Jn+1);Zn.fill(-1),Zn[Yn+1]=0;let Qn=[];for(let ei=0;ei<=Jn;ei+=1){Qn.push(new Int32Array(Zn));for(let Jn=-ei;Jn<=ei;Jn+=2){let ti=Jn+Yn,ni=Jn===-ei||Jn!==ei&&Zn[ti-1]<Zn[ti+1]?Zn[ti+1]:Zn[ti-1]+1,ri=ni-Jn;for(;ni<Vn&&ri<qn&&xn[ni]===jn[ri];)ni+=1,ri+=1;if(Zn[ti]=ni,ni>=Vn&&ri>=qn)return buildEditScript(Qn,xn,jn,Yn)}}return buildEditScript(Qn,xn,jn,Yn)}function buildEditScript(xn,jn,Vn,qn){let Jn=[],Yn=jn.length,Zn=Vn.length;for(let Qn=xn.length-1;Qn>0;--Qn){let ei=xn[Qn],ti=Yn-Zn,ni=ti+qn,ri=ti===-Qn||ti!==Qn&&ei[ni-1]<ei[ni+1]?ti+1:ti-1,ii=ei[ri+qn],ai=ii-ri;for(;Yn>ii&&Zn>ai;)--Yn,--Zn,Jn.push({type:`equal`,line:jn[Yn]});if(Yn===ii){--Zn,Jn.push({type:`insert`,line:Vn[Zn]});continue}--Yn,Jn.push({type:`delete`,line:jn[Yn]})}for(;Yn>0&&Zn>0;)--Yn,--Zn,Jn.push({type:`equal`,line:jn[Yn]});return Jn.reverse()}function toUnifiedDiffHunks(xn){let jn=[],Vn=null,qn=1,Jn=1,Yn=()=>{Vn&&=(jn.push(Vn),null)};for(let jn of xn){if(jn.type===`equal`){Yn(),qn+=1,Jn+=1;continue}if(Vn||={oldStart:qn,oldCount:0,newStart:Jn,newCount:0,lines:[]},jn.type===`delete`){Vn.oldCount+=1,Vn.lines.push(`-${jn.line}`),qn+=1;continue}Vn.newCount+=1,Vn.lines.push(`+${jn.line}`),Jn+=1}return Yn(),jn}function diff(xn,jn){let Vn=toUnifiedDiffHunks(diffLines(xn.trim().split(`
1470
- `),jn.trim().split(`
1471
- `)));return Vn.length===0?`No changes detected
1472
- `:`${Vn.map((xn)=>[`@@ -${formatRange(xn.oldStart,xn.oldCount)} +${formatRange(xn.newStart,xn.newCount)} @@`,...xn.lines].join(`
1473
- `)).join(`
1474
- `)}
1475
- `}var formatRange;var init_diff=__esmMin(()=>{formatRange=(xn,jn)=>jn===1?String(xn):`${xn},${jn}`});function toSessionTab(xn){return nullToUndefined(xn)}function emitSessionTabsUpdated(xn,jn){EventBus.emit(`session:tabs-updated`,{sessionId:jn});let Vn=SessionStore.get(xn,jn)?.parentId;Vn&&EventBus.emit(`session:tabs-updated`,{sessionId:Vn})}function getSessionTab(xn,jn){let Vn=stateDb(xn).select().from(SessionTabTable).where(eq(SessionTabTable.id,jn)).get();return Vn?toSessionTab(Vn):null}function listSessionTabs(xn,jn,Vn={}){let qn=stateDb(xn);if(!Vn.includeChildSessions)return qn.select().from(SessionTabTable).where(eq(SessionTabTable.sessionId,jn)).all().map(toSessionTab);let Jn=qn.select({id:SessionTable.id}).from(SessionTable).where(eq(SessionTable.parentId,jn)).all().map((xn)=>xn.id);return qn.select().from(SessionTabTable).where(inArray(SessionTabTable.sessionId,[jn,...Jn])).all().map(toSessionTab)}function insertSessionTab(xn,jn){let Vn=nanoid3(),qn=new Date;return stateDb(xn).insert(SessionTabTable).values({...jn,id:Vn,createdAt:qn,updatedAt:qn}).run(),SessionStore.touch(xn,jn.sessionId),emitSessionTabsUpdated(xn,jn.sessionId),getSessionTab(xn,Vn)}function updateSessionTab(xn,jn,Vn){let qn=getSessionTab(xn,jn);return qn?(stateDb(xn).update(SessionTabTable).set({...Vn,updatedAt:new Date}).where(eq(SessionTabTable.id,jn)).run(),SessionStore.touch(xn,qn.sessionId),emitSessionTabsUpdated(xn,qn.sessionId),getSessionTab(xn,jn)):null}function removeSessionTab(xn,jn){let Vn=getSessionTab(xn,jn);stateDb(xn).delete(SessionTabTable).where(eq(SessionTabTable.id,jn)).run(),Vn&&(SessionStore.get(xn,Vn.sessionId)?.activeTabTargetId===Vn.targetId&&SessionStore.update(xn,Vn.sessionId,{activeTabTargetId:null}),SessionStore.touch(xn,Vn.sessionId),emitSessionTabsUpdated(xn,Vn.sessionId))}function getSessionTabByTargetId(xn,jn,Vn){let qn=stateDb(xn).select().from(SessionTabTable).where(and(eq(SessionTabTable.sessionId,jn),eq(SessionTabTable.targetId,Vn))).get();return qn?toSessionTab(qn):null}var init_session_tab_queries=__esmMin(()=>{init_drizzle_orm(),init_event_bus(),init_extension_bridge(),init_schema(),init_state_db(),init_nanoid(),init_utils$13(),init_store$1()});async function injectAnnotationOverlay(xn,jn){return await xn(({refIds:xn,overlayId:jn})=>{let Vn=document.getElementById(jn);Vn&&Vn.remove();let qn=[];for(let jn of xn){let xn=jn.match(/^(?:.*?)e(\d+)$/);if(!xn)continue;let Vn=parseInt(xn[1],10),Jn=globalThis.__omowright?.deref(jn)??null;if(!Jn)continue;let Yn=Jn.getBoundingClientRect();Yn.width<=0||Yn.height<=0||qn.push({number:Vn,x:Math.round(Yn.x),y:Math.round(Yn.y),width:Math.round(Yn.width),height:Math.round(Yn.height)})}if(qn.length===0)return 0;qn.sort((xn,jn)=>xn.number-jn.number);let Jn=window.scrollX||0,Yn=window.scrollY||0,Zn=document.createElement(`div`);Zn.id=jn,Zn.style.cssText=`position:absolute;top:0;left:0;width:0;height:0;pointer-events:none;z-index:2147483647;`;for(let xn of qn){let jn=xn.x+Jn,Vn=xn.y+Yn,qn=document.createElement(`div`);qn.style.cssText=`position:absolute;left:${jn}px;top:${Vn}px;width:${xn.width}px;height:${xn.height}px;border:2px solid rgba(255,0,0,0.8);box-sizing:border-box;pointer-events:none;`;let Qn=document.createElement(`div`);Qn.textContent=String(xn.number);let ei=Vn<14?`2px`:`-14px`;Qn.style.cssText=`position:absolute;top:${ei};left:-2px;background:rgba(255,0,0,0.9);color:#fff;font:bold 11px/14px monospace;padding:0 4px;border-radius:2px;white-space:nowrap;`,qn.appendChild(Qn),Zn.appendChild(qn)}return document.documentElement.appendChild(Zn),qn.length},{refIds:jn,overlayId:ANNOTATION_OVERLAY_ID})}async function removeAnnotationOverlay(xn){await xn((xn)=>{let jn=document.getElementById(xn);jn&&jn.remove()},ANNOTATION_OVERLAY_ID)}var ANNOTATION_OVERLAY_ID;var init_annotate_screenshot=__esmMin(()=>{ANNOTATION_OVERLAY_ID=`__omowright_annotations__`});function isStableAiTabViewport(xn){return!!xn&&xn.width>=MIN_STABLE_AI_TAB_VIEWPORT.width&&xn.height>=MIN_STABLE_AI_TAB_VIEWPORT.height}function normalizeOpenUrl(xn){return/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(xn)?xn:`https://${xn}`}function urlsMatchPopupTarget(xn,jn){if(!xn||!jn||jn===`about:blank`)return false;try{return new URL(xn).href===new URL(jn).href}catch{return xn===jn}}function isPlaceholderPopupUrl(xn){return xn===`:`||xn===`about:blank`||xn.trim()===``}function isTransientPageScriptError(xn){let jn=(xn instanceof Error?xn.message:String(xn)).toLowerCase();return jn.includes(`execution context was destroyed`)||jn.includes(`cannot find context with specified id`)||jn.includes(`frame was detached`)||jn.includes(`frame has been detached`)||jn.includes(`navigating frame was detached`)||jn.includes(`most likely because of a navigation`)||jn.includes(`target page, context or browser has been closed`)||jn.includes(`target closed`)}var PAGE_SCRIPT_RETRY_COUNT;var PAGE_SCRIPT_RETRY_DELAY_MS;var OPEN_TAB_WARNING_THRESHOLD;var DEFAULT_BROWSER_FETCH_USER_AGENT;var AI_TAB_STABLE_VIEWPORT;var MIN_STABLE_AI_TAB_VIEWPORT;var OmOBrowser;var init_browser=__esmMin(()=>{init_context(),init_cdp(),init_directory(),init_event_bus(),init_extension_bridge(),init_diff(),init_utils$13(),init_session_tab_queries(),init_store$1(),init_types$8(),init_utils$4(),init_annotate_screenshot(),init_frame_manager(),init_page(),init_snapshot(),PAGE_SCRIPT_RETRY_COUNT=10,PAGE_SCRIPT_RETRY_DELAY_MS=200,OPEN_TAB_WARNING_THRESHOLD=5,DEFAULT_BROWSER_FETCH_USER_AGENT=`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36`,AI_TAB_STABLE_VIEWPORT={width:1440,height:900},MIN_STABLE_AI_TAB_VIEWPORT={width:960,height:540},OmOBrowser=class{#e;#t;#n;#r;#i;#a=new Map;#o=new WeakMap;#s=[];#c=[];#l=new Map;#u=[];#d=[];#f=null;#p=[];#m=null;#h=null;#g;#_=new Set;#v=false;constructor(xn,jn,Vn,qn){this.#e=xn,this.#t=new SessionManager(xn),this.#n=jn,this.#r=Vn,this.#i=qn,this.#s.push(this.#e.transportEvents.on(`reconnected`,()=>{this.#g=undefined,this.#E()}),this.#e.on(`Target.targetInfoChanged`,(xn)=>{this.#y(xn.targetInfo),withoutReplContext(()=>this.#b(xn.targetInfo,{notifyRepl:false})).catch(()=>{})}),this.#e.on(`Target.targetCreated`,(xn)=>{withoutReplContext(()=>this.#b(xn.targetInfo,{notifyRepl:false})).catch(()=>{})}),this.#e.on(`Target.targetDestroyed`,(xn)=>{this.#R(xn.targetId).catch(()=>{})}))}get state(){if(!this.#m){let xn=this.#r.id,jn=SessionStore.get(this.#n,xn),Vn=listSessionTabs(this.#n,xn).map((xn)=>({sessionTabId:xn.id,targetId:xn.targetId,url:xn.url,ownership:xn.ownership,source:xn.source,...xn.data}));this.#m={activePage:Vn.find((xn)=>xn.targetId===jn?.activeTabTargetId),tabs:Vn},jn?.activeTabTargetId&&!this.#m.activePage&&console.warn(`[OmOBrowser.state] Stale activeTabTargetId ${jn.activeTabTargetId} for session ${xn}`)}return this.#m}setActiveTab(xn){SessionStore.update(this.#n,this.#r.id,{activeTabTargetId:xn}),this.#m=null}addNewTabState(xn){let jn=this.#r.id;if(!SessionStore.get(this.#n,jn))throw Error(`Cannot create session tab: parent session ${jn} no longer exists`);if(xn.targetId){let Vn=getSessionTabByTargetId(this.#n,jn,xn.targetId);if(Vn)return this.#m=null,Vn}let Vn=insertSessionTab(this.#n,{sessionId:jn,targetId:xn.targetId,url:xn.url,ownership:xn.ownership,source:xn.source,data:{title:xn.title??``,viewport:xn.viewport??AI_TAB_STABLE_VIEWPORT,...xn.iconUrl===undefined?{}:{iconUrl:xn.iconUrl}}});return this.#m=null,Vn}#y(xn){if(xn.type!==`page`||!xn.targetId)return;let jn=getSessionTabByTargetId(this.#n,this.#r.id,xn.targetId);if(!jn)return;let Vn=xn.url?.trim()||jn.url,qn=Vn!==jn.url,Jn=xn.title?.trim()||(qn?``:jn.data.title),Yn=xn.faviconUrl?.trim(),Zn=xn.faviconUrl!==undefined||qn,Qn=Zn?{...jn.data}:jn.data;Zn&&(delete Qn.iconUrl,Yn&&(Qn.iconUrl=Yn)),!(jn.url===Vn&&jn.data.title===Jn&&jn.data.iconUrl===Qn.iconUrl)&&(qn&&delete Qn.snapshot,updateSessionTab(this.#n,jn.id,{url:Vn,data:{...Qn,title:Jn}}),qn&&this.setActiveTab(jn.targetId),this.#m=null)}async#b(xn,jn={}){let Vn=xn.targetId;if(xn.type!==`page`||!Vn||this.#B(Vn))return;let qn=xn.openerId,Jn=this.#S({openerFrameId:xn.openerFrameId,openerTargetId:qn});if(Jn){await this.#L(Vn,Jn,jn);return}let Yn=this.#z(xn.url??``);Yn&&await this.#L(Vn,Yn.openerTargetId,jn)}async#x(xn={}){let{targetInfos:jn}=await this.#e.send(`Target.getTargets`).catch(()=>({targetInfos:[]}));await Promise.all(jn.map((jn)=>this.#b(jn,xn)))}#S({openerFrameId:xn,openerTargetId:jn}){if(jn){if(this.#a.has(jn)||this.state.tabs.some((xn)=>xn.targetId===jn))return jn;for(let[xn,Vn]of this.#a)if(Vn.frameManager.getFrame(jn))return xn}if(!xn)return null;for(let[jn,Vn]of this.#a)if(Vn.frameManager.getFrame(xn))return jn;return null}async updateTabState(xn,jn={}){if(!this.#a.has(xn.targetId))return null;let[Vn,qn]=await Promise.all([xn.title().catch(()=>``),this.#O(xn)]);xn.setCachedViewportSize(qn);let Jn=this.#B(xn.targetId);if(!Jn)return null;let Yn=getSessionTab(this.#n,Jn);if(!Yn)return null;let Zn=updateSessionTab(this.#n,Jn,{targetId:xn.targetId,url:jn.url??xn.url(),data:{...Yn.data,title:jn.title??Vn,viewport:jn.viewport??qn,...jn.iconUrl===undefined?{}:{iconUrl:jn.iconUrl},...jn.latestScreenshotPath===undefined?{}:{latestScreenshotPath:jn.latestScreenshotPath},...jn.snapshot===undefined?{}:{snapshot:jn.snapshot}}});return this.#m=null,Zn}removeTab(xn,jn){let Vn=getSessionTab(this.#n,xn);if(!Vn)return;let qn=SessionStore.get(this.#n,Vn.sessionId);removeSessionTab(this.#n,xn),qn?.activeTabTargetId===Vn.targetId&&(this.setActiveTab(null),!jn?.agentInitiated&&qn.status===`running`&&Promise.resolve().then(()=>(init_agent_session_server(),agent_session_server_exports)).then(({GlobalAgentSessionServer:xn})=>xn.sendSystemMessage(this.#n,Vn.sessionId,`The active browser tab for this session just closed.
1476
- Closed tab: ${Vn.data.title??`Unknown`} (${Vn.url})`,{kind:`tab_lifecycle`,mode:`steer`})).catch((xn)=>{console.warn(`[OmOBrowser] Failed to send tab lifecycle system message`,xn)})),this.#m=null}get page(){return this.#f}set page(xn){if(xn!==null&&!(xn instanceof OmOPage))throw Error(`page must be set to null or an OmOPage instance`);this.#f=xn,this.setActiveTab(xn?.targetId??null)}get tabs(){return this.#p}get extensionBridgeRoute(){return this.#j()}refreshBrowserBinding(xn){this.#r.browserBinding=xn,this.#g=undefined}async resolvePageSession(xn,jn){return await this.#t.resolvePageSession(xn,jn)}async ensurePage(xn){let jn=this.#a.get(xn);if(jn)return jn.page;if(this.#v)throw Error(`Browser is disposed`);if(!await this.#t.getPageTarget(xn))throw Error(`Tab ${xn} is no longer available.`);await this.#F(xn);let Vn=await this.resolvePageSession(xn),qn=new FrameManager(this.#e,xn,Vn);await qn.initialize();let Jn=new OmOPage(this.#e,qn,xn,Vn,this),Yn={frameManager:qn,page:Jn,unsubscribers:this.#V(Jn,Vn)};return this.#a.set(xn,Yn),Jn}async syncVmContext(xn,jn={}){for(let xn of this.#d.splice(0))replPrint(xn);if(await this.#x({notifyRepl:jn.notifyRecoveredPopups}),jn.notifyRecoveredPopups)for(let xn of this.#u.splice(0))replPrint(xn);this.#m=null;let Vn=this.state.tabs.map((xn)=>xn.targetId).filter((xn)=>!!xn),qn=(await Promise.all(Vn.map((xn)=>this.ensurePage(xn).catch(()=>null)))).filter((xn)=>xn!==null);this.#p=qn,xn.tabs=qn;let Jn=this.#f&&qn.some((xn)=>xn.targetId===this.#f.targetId),Yn=qn.find((xn)=>xn.targetId===this.state.activePage?.targetId)??null,Zn=Jn?this.#f:Yn;xn.page=Zn,this.#f=Zn}#C(){let{tabs:xn,activePage:jn}=this.state;if(xn.length===0){this.#T(`[system] no current open tabs in this session.`);return}this.#T(`[system] current open tabs in this session (${xn.length}):
1477
- `+xn.map(({title:xn,url:Vn,targetId:qn},Jn)=>` - \`tabs[${Jn}]\`: ${qn===jn?.targetId?`(active) `:``}${xn} (${truncateUrlForLLM(Vn)})`).join(`
1478
- `))}async openTab(xn){if(this.#v)throw Error(`Browser is disposed`);let jn=this.state.activePage?.targetId??this.#f?.targetId??this.#r.browserBinding?.anchorTargetId,{targetId:Vn}=await sendCommandToExtension({method:`OmO.createAgentTab`,params:{url:normalizeOpenUrl(xn),...jn?{anchorTargetId:jn}:{}}},this.#j());try{let jn=await this.ensurePage(Vn),qn=await this.#O(jn),Jn=this.addNewTabState({targetId:jn.targetId,url:xn,viewport:qn,ownership:`owned`,source:`open_tab`});this.setActiveTab(Jn.targetId),this.#p=[...this.#p.filter((xn)=>xn.targetId!==Vn),jn],await jn.waitForLoadState(`stable`,5000).catch((jn)=>{console.warn(`[browser] openTab: waitForLoadState failed`,{targetId:Vn,url:xn,error:jn instanceof Error?jn.message:String(jn)})});let Yn=await this.updateTabState(jn);await this.#w(Vn,xn,`openTab`),this.page=jn;let Zn=this.#p.length-1;return this.#T(`✔︎ Opened a new tab and set it active: tabs[${Zn}], page → ${Yn?.data?.title??`(no title)`} (${jn.url({truncate:true})})`),this.#p.length>=OPEN_TAB_WARNING_THRESHOLD&&this.#T(`[warning] ${this.#p.length} tabs are open. Close tabs you do not need as you work.`),jn}catch(jn){throw await this.#A(Vn),sendCommandToExtension({method:`OmO.controlTab`,params:{action:`close`,targetId:Vn,url:xn}},this.#j()).catch(()=>{}),jn}}async openPopupTab(xn,jn){if(this.#v)throw Error(`Browser is disposed`);let Vn=normalizeOpenUrl(xn);await this.#F(jn);let{targetId:qn}=await sendCommandToExtension({method:`OmO.createAgentTab`,params:{url:Vn,anchorTargetId:jn}},this.#j());try{await this.#L(qn,jn)}catch(xn){throw await this.#A(qn),sendCommandToExtension({method:`OmO.controlTab`,params:{action:`close`,targetId:qn,url:Vn}},this.#j()).catch(()=>{}),xn}}async closeTab(xn,jn={}){let Vn=xn.targetId,qn=this.state.tabs.find((xn)=>xn.targetId===Vn);if(!qn)throw Error(`Tab ${Vn} is not tracked in this session.`);if(qn.ownership!==`owned`){let xn=this.#B(Vn);xn&&this.removeTab(xn,{agentInitiated:true}),await this.#R(Vn);return}let Jn=this.#B(Vn);Jn&&this.removeTab(Jn,{agentInitiated:true});let Yn=false,Zn=false,Qn=this.#e.on(`Target.targetDestroyed`,(xn)=>{xn.targetId===Vn&&(Yn=true)});try{let qn=sendCommandToExtension({method:`OmO.controlTab`,params:{action:`close`,targetId:Vn,url:xn.url()}},this.#j()).catch(async(xn)=>{if(!Yn&&await this.#t.getPageTarget(Vn).catch(()=>null))throw xn}).finally(()=>{Zn=true});if(jn.runBeforeUnload)await qn;else{for(;!Yn&&!Zn&&await this.#t.getPageTarget(Vn).catch(()=>null);)await sleep$12(50);await Promise.race([qn,sleep$12(Yn?250:0)]),Yn||await qn}}finally{Qn()}await this.#R(Vn)}async closeOwnedTabs(){let xn=this.state.tabs.filter((xn)=>xn.ownership===`owned`&&xn.targetId);await Promise.allSettled(xn.map(async(xn)=>{let jn=xn.targetId;await this.#A(jn),await sendCommandToExtension({method:`OmO.controlTab`,params:{action:`close`,targetId:jn,url:xn.url,skipIfActive:true}},this.#j()).catch(()=>{})})),this.#m=null}async dispose(xn={}){let{closeOwnedTabs:jn=true}=xn;if(!this.#v){this.#v=true,this.#h=null;for(let xn of this.#s)xn();this.#s.length=0,jn&&await this.closeOwnedTabs().catch(()=>{});for(let xn of this.#a.keys())await this.#A(xn);await this.#t.dispose(),this.#p=[],this.#f=null}}async installPageScript(xn,jn,Vn){let qn;for(let Jn=0;Jn<PAGE_SCRIPT_RETRY_COUNT;Jn+=1)try{let qn=this.#o.get(xn)??new Map,Jn=qn.get(jn);if(Jn){await Jn;return}let Yn=xn.evaluate(Vn).then(()=>{});qn.set(jn,Yn),this.#o.set(xn,qn),await Yn;return}catch(Vn){if(qn=Vn,this.#o.get(xn)?.delete(jn),Jn===PAGE_SCRIPT_RETRY_COUNT-1||!isTransientPageScriptError(Vn))throw Vn;await sleep$12(PAGE_SCRIPT_RETRY_DELAY_MS)}if(qn)throw qn}async snapshot(xn,jn={}){if(jn.selector&&!await xn.evaluate((xn)=>!!document.querySelector(xn),jn.selector))throw Error(`Selector "${jn.selector}" matched no elements on page.`);let Vn=xn.targetId,qn=xn.url();this.#r.runtimeConfig.takeScreenshotOnEverySnapshot&&withoutReplContext(async()=>{let jn=`./tmp/screenshot-${Date.now()}.webp`;await mkdir(path.dirname(this.resolvePath(jn)),{recursive:true});let Vn=await this.#O(xn);await xn.screenshot({type:`webp`,path:jn,clip:{x:0,y:0,width:Vn.width,height:Vn.height}}),await this.updateTabState(xn,{latestScreenshotPath:jn})}).catch((xn)=>{console.warn(`[OmOBrowser] Failed to capture automatic snapshot screenshot`,xn)});let[Jn,Yn]=await Promise.all([takeSnapshot(this.#e,xn.frameManager,jn),xn.title().catch(()=>``)]),Zn=this.state.tabs.find((xn)=>xn.targetId===Vn)?.snapshot?.tree??``;await this.updateTabState(xn,{snapshot:Jn}),this.emitBrowserEvent(`browser:snapshot`,{targetId:Vn,url:qn,options:jn,snapshot:Jn});let Qn=[jn.interactive&&`# note: interactive (clickable / focusable) elements only.`,jn.showHidden&&`# note: hidden elements are shown.`,`- title: "${Yn}" [url=${truncateUrlForLLM(qn)}]`,Jn.tree].filter((xn)=>!!xn).join(`
1479
- `),ei=diff(Zn,Jn.tree);return{tree:Qn,refs:Jn.refs,diff:ei.length>Qn.length?Qn:ei}}async annotatedScreenshot(xn){let jn=await xn.snapshot({interactive:true}),Vn=await xn.frameManager.ensureInjected(xn.frameManager.mainFrameId),qn=async(jn,qn)=>{let{result:Jn,exceptionDetails:Yn}=await xn._sendToTarget(`Runtime.callFunctionOn`,{functionDeclaration:`function(arg) { return (${jn.toString()})(arg); }`,arguments:[{value:qn}],executionContextId:Vn,returnByValue:true,awaitPromise:true});if(Yn)throw Error(Yn.text??`Annotation overlay failed`);return Jn.value},Jn=false;try{return Jn=await injectAnnotationOverlay(qn,Object.keys(jn.refs))>0,{base64Image:(await xn.screenshot({type:`png`})).toString(`base64`)}}finally{Jn&&await removeAnnotationOverlay(qn).catch(()=>{})}}async getUserAgent(){return(await this.#e.send(`Browser.getVersion`,undefined).catch(()=>null))?.userAgent}async fetch(xn,jn={}){let Vn=xn.toString(),[qn,Jn]=await Promise.all([this.getCookiesForUrl(Vn),this.getUserAgent()]),Yn=new Headers(jn.headers);return qn&&!Yn.has(`Cookie`)&&Yn.set(`Cookie`,qn),Yn.has(`User-Agent`)||Yn.set(`User-Agent`,Jn??DEFAULT_BROWSER_FETCH_USER_AGENT),fetch(Vn,{...jn,headers:Yn})}async getCookiesForUrl(xn){let jn=this.#f?.targetId??this.state.activePage?.targetId??this.#r.browserBinding?.anchorTargetId;if(!jn)return;let Vn=await(this.#a.get(jn)?.page??await this.ensurePage(jn))._sendToTarget(`Network.getCookies`,{urls:[xn]});if(Vn.cookies.length)return Vn.cookies.map((xn)=>`${xn.name}=${xn.value}`).join(`; `).trim()||undefined}getPageSnapshot(xn){let jn=`targetId`in xn?xn.targetId:xn.page?.targetId;if(jn)return this.state.tabs.find((xn)=>xn.targetId===jn)?.snapshot}resolvePath(xn){return resolveSessionPath(getSessionStorageDir(this.#r,this.#n),xn,getSharedSessionStorageDir(this.#r,this.#n))}registerReadableDownloadPath(xn){let jn=path.resolve(xn);return this.#_.add(jn),jn}isReadableDownloadPath(xn){return this.#_.has(path.resolve(xn))}async ensurePath(xn,jn,Vn){let qn=this.resolvePath(xn),Jn=getCurrentReplToolCallId();if(!this.#i||!Jn)return qn;let Yn={toolCallId:Jn,path:qn,mode:jn,source:Vn};return await this.#i.trigger(`file.access`,Yn,Yn),qn}get daemonSession(){return{accountId:this.#n,id:this.#r.id,projectId:this.#r.projectId}}async#w(xn,jn,Vn){try{await sendCommandToExtension({method:`OmO.ensureTabInAiTabsGroup`,params:{targetId:xn}},this.#j())}catch(qn){let Jn=qn instanceof Error?qn.message:String(qn);console.warn(`[browser] ${Vn}: failed to move tab into Agent Tabs group`,{targetId:xn,url:jn,error:Jn}),this.#T(`[warning] Failed to move tab into Agent Tabs group: ${Jn}`)}}#T(xn){hasActiveReplContext()?replPrint(xn):this.#d.push(xn)}emitBrowserEvent(xn,jn){EventBus.emit(xn,[jn,{session:this.#r}]).catch((jn)=>{console.warn(`[omowright-browser] Failed to emit ${xn}`,jn)})}#E(){this.#v||this.#h||(this.#h=this.#D().finally(()=>{this.#h=null}))}async#D(){if(!this.#v){this.#t.clear();for(let[xn,jn]of this.#a)try{if(!await this.#t.getPageTarget(xn)){await this.#I(xn);continue}let Vn=await this.resolvePageSession(xn);for(let xn of jn.unsubscribers)xn();jn.unsubscribers=this.#V(jn.page,Vn),await jn.frameManager.reconnect(Vn),jn.page.reconnect(Vn),await this.updateTabState(jn.page).catch(()=>{})}catch{await this.#I(xn)}this.#p=this.#p.filter((xn)=>this.#a.has(xn.targetId)),this.#f&&!this.#a.has(this.#f.targetId)&&(this.#f=null)}}async#O(xn){let jn=this.#k(xn),Vn=await xn.refreshViewportSize().catch(()=>jn);return isStableAiTabViewport(Vn)?Vn:(xn.setCachedViewportSize(jn),jn)}#k(xn){let jn=xn.viewportSize();if(isStableAiTabViewport(jn))return jn;let Vn=getSessionTabByTargetId(this.#n,this.#r.id,xn.targetId)?.data.viewport;return isStableAiTabViewport(Vn)?Vn:AI_TAB_STABLE_VIEWPORT}async#A(xn){let jn=this.#a.get(xn),Vn=this.#t.getTargetSession(xn);if(Vn&&await this.#e.send(`Target.detachFromTarget`,{sessionId:Vn}).catch(()=>{}),jn){this.#a.delete(xn);for(let xn of jn.unsubscribers)xn();await jn.page.dispose().catch(()=>{}),await jn.frameManager.dispose().catch(()=>{})}}#j(){let xn=this.#r.browserBinding;if(!xn)throw Error(BROWSER_BINDING_REQUIRED_MESSAGE);return{accountId:this.#n,profileId:xn.profileId,windowId:xn.windowId}}async#M(xn){return(await this.#e.send(`Target.getTargetInfo`,{targetId:xn}).catch(()=>null))?.targetInfo.browserContextId}async#N(xn){let{owned:jn}=await sendCommandToExtension({method:`OmO.ownsTarget`,params:{targetId:xn}},this.#j());return jn}async#P(){if(this.#g)return this.#g;let xn=this.#r.browserBinding,jn=new Set([this.#r.activeTabTargetId,xn?.anchorTargetId].filter((xn)=>!!xn));for(let xn of jn){if(!await this.#N(xn))continue;let jn=await this.#M(xn);if(jn)return this.#g=jn,jn}}async#F(xn){if(!await this.#N(xn))throw Error(`Tab ${xn} belongs to a different browser profile.`);let jn=await this.#M(xn);if(!jn)throw Error(`Unable to verify the browser profile for tab ${xn}.`);let Vn=await this.#P();if(Vn&&jn!==Vn)throw Error(`Tab ${xn} belongs to a different browser profile.`);this.#g??=jn}async#I(xn){await this.#A(xn),this.#p=this.#p.filter((jn)=>jn.targetId!==xn),this.#f?.targetId===xn&&(this.#f=null)}async#L(xn,jn,Vn={}){let qn=this.#l.get(xn);if(qn){await qn;return}if(this.#B(xn))return;let Jn=(async()=>{this.#m=null;let qn=await this.ensurePage(xn);await this.#w(xn,qn.url(),`trackPopupTarget`),await qn.waitForLoadState(`stable`,5000).catch(()=>{});let[Jn,Yn]=await Promise.all([qn.title().catch(()=>``),this.#O(qn)]),Zn=qn.url();if(isPlaceholderPopupUrl(Zn)){await this.#A(xn),sendCommandToExtension({method:`OmO.controlTab`,params:{action:`close`,targetId:xn,url:Zn}},this.#j()).catch(()=>{});return}qn.setCachedViewportSize(Yn),this.addNewTabState({targetId:xn,url:Zn,title:Jn,viewport:Yn,ownership:`owned`,source:`popup`}),this.#p=[...this.#p.filter((jn)=>jn.targetId!==xn),qn];let Qn=this.#p.length-1,ei=`[system] popup opened: ${Jn??`(no title)`} (${truncateUrlForLLM(Zn)})
1480
- to use, explicitly access it via \`tabs[${Qn}]\` or switch it with \`page = tabs[${Qn}];\``;Vn.notifyRepl??true?this.#T(ei):this.#u.push(ei),this.emitBrowserEvent(`browser:popup`,{targetId:xn,openerTargetId:jn,url:Zn})})().finally(()=>{this.#l.delete(xn)});this.#l.set(xn,Jn),await Jn}async#R(xn){if(!this.#p.find((jn)=>jn.targetId===xn)&&!this.#a.has(xn))return;let jn=this.#B(xn),Vn=this.#f?.targetId===xn;if(await this.#A(xn),jn&&(this.removeTab(jn),this.#m=null),this.#p=this.#p.filter((jn)=>jn.targetId!==xn),Vn){let xn=(this.#p.length>0?this.#p[this.#p.length-1]:null)??null;this.#f=xn,xn?(this.setActiveTab(xn.targetId),this.#T(`[system] tab closed. \`page\` is changed to the last tab: ${xn.url({truncate:true})}`)):this.#T("[system] last tab closed. `page` is now null. call openTab(url) to open a new one."),this.#C()}else{let xn=this.state.activePage?.targetId;this.#f=xn?this.#p.find((jn)=>jn.targetId===xn)??null:null}}#z(xn){let jn=Date.now();for(;this.#c.length>0&&jn-this.#c[0].timestamp>1e4;)this.#c.shift();if(this.#c.length===1&&(!xn||xn===`about:blank`))return this.#c.shift()??null;let Vn=this.#c.findIndex((jn)=>urlsMatchPopupTarget(jn.url,xn));if(Vn===-1)return null;let[qn]=this.#c.splice(Vn,1);return qn??null}#B(xn){return xn?getSessionTabByTargetId(this.#n,this.#r.id,xn)?.id??null:null}#V(xn,jn){return[xn.on(`framenavigated`,(jn)=>{(!xn.frameManager.mainFrameId||jn.frameId===xn.frameManager.mainFrameId)&&this.updateTabState(xn).then(async(jn)=>{if(!jn)return;let Vn=xn.url(),qn=this.#i?await this.#i.trigger(`browser.navigation`,{page:xn,url:Vn},{url:Vn}):{url:Vn},Jn=this.#p.findIndex((jn)=>jn.targetId===xn.targetId),Yn=this.#f?.targetId===xn.targetId?`page`:`tabs[${Jn}]`;this.#T(`[system] \`${Yn}\` navigated to: [${jn.data.title}](${truncateUrlForLLM(Vn)}) `),this.emitBrowserEvent(`browser:navigation`,{targetId:xn.targetId,url:qn.url})}).catch(()=>{})}),this.#e.on(`Page.javascriptDialogOpening`,(jn,Vn)=>{if(!Vn.sessionId||!xn.frameManager.hasSession(Vn.sessionId))return;let qn={targetId:xn.targetId,url:jn.url,type:jn.type,message:jn.message,defaultPrompt:jn.defaultPrompt??``};this.emitBrowserEvent(`browser:alert`,qn);let Jn=this.#p.findIndex((jn)=>jn.targetId===xn.targetId),Yn=this.#f?.targetId===xn.targetId?`page`:`tabs[${Jn}]`,Zn=qn.type===`prompt`?`[system] \`${Yn}\` showed a prompt dialog: "${qn.message}" (default: "${qn.defaultPrompt}"). options: [OK (text input)] [Cancel]. auto-accepted with default value.`:qn.type===`confirm`?`[system] \`${Yn}\` showed a confirm dialog: "${qn.message}". options: [OK] [Cancel]. auto-accepted (OK).`:`[system] \`${Yn}\` showed an alert: "${qn.message}". auto-accepted.`;this.#T(Zn),this.updateTabState(xn,{url:jn.url}).catch(()=>{})}),xn.on(`popup`,(jn)=>{this.#c.push({openerTargetId:xn.targetId,url:jn.url,timestamp:Date.now()})}),xn.on(`download`,async(jn)=>{let Vn=await withoutReplContext(()=>jn.path()).catch((xn)=>{let Vn=xn instanceof Error?xn.message:String(xn);try{this.#T(`[system] download started: ${jn.suggestedFilename()} (${Vn})`)}catch{}return null});if(!Vn)return;let qn=jn.url();this.#i&&await this.#i.trigger(`browser.download`,{page:xn,url:qn,path:Vn},{path:Vn}),this.#T(`[system] downloading file: ${jn.suggestedFilename()} to ${Vn}`),this.emitBrowserEvent(`browser:download`,{targetId:xn.targetId,url:qn,path:Vn,suggestedFilename:jn.suggestedFilename()})})]}}});function defaultVideoSize(xn){let jn=Math.min(1,DEFAULT_VIDEO_MAX_EDGE/xn.width,DEFAULT_VIDEO_MAX_EDGE/xn.height),Vn=Math.max(2,Math.round(xn.width*jn)),qn=Math.max(2,Math.round(xn.height*jn));return{height:qn%2==0?qn:qn+1,width:Vn%2==0?Vn:Vn+1}}function inferVideoFormat(xn){return xn.format?xn.format:xn.path?.toLowerCase().endsWith(`.mp4`)?`mp4`:DEFAULT_VIDEO_FORMAT}async function ensureDirForFile(xn){await fs$16.mkdir(path.dirname(xn),{recursive:true})}async function readProcessStderr(xn){return await readProcessStream(xn.stderr).catch(()=>``)}var DEFAULT_VIDEO_FORMAT;var DEFAULT_VIDEO_FRAMERATE;var DEFAULT_VIDEO_JPEG_QUALITY;var DEFAULT_VIDEO_MAX_EDGE;var FfmpegVideoRecorder;var OmOVideo;var init_video=__esmMin(()=>{init_context(),init_process(),init_browser(),DEFAULT_VIDEO_FORMAT=`webm`,DEFAULT_VIDEO_FRAMERATE=25,DEFAULT_VIDEO_JPEG_QUALITY=90,DEFAULT_VIDEO_MAX_EDGE=800,FfmpegVideoRecorder=class{#e;#t;#n=0;#r=false;#i=null;#a=Promise.resolve();#o=0;#s=[];constructor(xn,jn,Vn,qn){this.#e=Vn;let Jn=qn===`mp4`?[`-c:v`,`libx264`,`-movflags`,`+faststart`]:[`-c:v`,`libvpx`,`-qmin`,`0`,`-qmax`,`50`,`-crf`,`8`,`-deadline`,`realtime`,`-speed`,`8`,`-b:v`,`1M`];this.#t=spawnCommand([`ffmpeg`,`-loglevel`,`error`,`-f`,`image2pipe`,`-avioflags`,`direct`,`-fpsprobesize`,`0`,`-probesize`,`32`,`-analyzeduration`,`0`,`-c:v`,`mjpeg`,`-i`,`pipe:0`,`-y`,`-an`,`-r`,String(Vn),...Jn,`-threads`,`1`,`-vf`,`scale=${jn.width}:${jn.height}:force_original_aspect_ratio=decrease,pad=${jn.width}:${jn.height}:(ow-iw)/2:(oh-ih)/2:gray`,`-pix_fmt`,`yuv420p`,xn],{stdio:[`pipe`,`ignore`,`pipe`]})}writeFrame(xn,jn){if(this.#r)return;this.#n||=jn;let Vn=Math.floor((jn-this.#n)*this.#e);if(this.#i){let xn=Vn-this.#i.frameNumber;for(let jn=0;jn<xn;jn+=1)this.#s.push(this.#i.buffer);this.#a=this.#a.then(()=>this.#c())}this.#i={buffer:xn,frameNumber:Vn,timestamp:jn},this.#o=Date.now()}async stop(xn){if(this.#r)return;if(!this.#i){if(!xn)throw Error(`Video recorder did not capture any frames.`);this.writeFrame(xn,Date.now()/1000)}let jn=this.#i;if(!jn)throw Error(`Video recorder did not capture any frames.`);let Vn=Math.max((Date.now()-this.#o)/1000,1);if(this.writeFrame(Buffer.from([]),jn.timestamp+Vn),this.#r=true,await withCurrentReplAbort(async()=>await this.#a),!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let qn=this.#t.stdin;await withCurrentReplAbort(async()=>await endProcessInput(qn));let Jn=await withCurrentReplAbort(async()=>await waitForExitCode(this.#t));if(Jn!==0){let xn=await readProcessStderr(this.#t);throw Error(xn.trim()||`ffmpeg exited with code ${Jn}`)}}async#c(){if(!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let xn=this.#t.stdin;for(;this.#s.length>0;){let jn=this.#s.shift();if(!(!jn||jn.length===0))try{await withCurrentReplAbort(async()=>await writeProcessChunk(xn,jn))}catch(xn){let jn=(await readProcessStderr(this.#t)).trim();throw Error(jn.length>0?`ffmpeg rejected video frame input: ${jn}`:xn instanceof Error?xn.message:String(xn))}}}},OmOVideo=class{#e;#t=null;#n=null;constructor(xn){this.#e=xn}async start(xn={}){return await withCurrentReplAbort(async()=>{if(this.#t)throw Error(`Video recording is already active.`);let jn=await this.#e.resolveSessionId(),Vn=this.#e.viewportSize()??await this.#e.refreshViewportSize().catch(()=>null)??AI_TAB_STABLE_VIEWPORT,qn=inferVideoFormat(xn),Jn=xn.size??defaultVideoSize(Vn),Yn=await this.#e.browser.ensurePath(xn.path??`video-${Date.now()}.${qn}`,`write`,`page.video.start`),Zn=xn.quality??DEFAULT_VIDEO_JPEG_QUALITY,Qn=xn.framerate??DEFAULT_VIDEO_FRAMERATE;await ensureDirForFile(Yn);let ei=new FfmpegVideoRecorder(Yn,Jn,Qn,qn),{promise:ti,resolve:ni,reject:ri}=Promise.withResolvers(),ii=this.#e.cdp.on(`Page.screencastFrame`,(xn,Vn)=>{if(Vn.sessionId!==jn)return;let qn=Buffer.from(xn.data,`base64`),Jn=xn.metadata?.timestamp??Date.now()/1000;ei.writeFrame(qn,Jn),this.#e.cdp.send(`Page.screencastFrameAck`,{sessionId:xn.sessionId},jn).catch(()=>{})});this.#t={completion:ti,format:qn,outputPath:Yn,pendingCopies:new Set,recorder:ei,rejectCompletion:ri,resolveCompletion:ni,sessionId:jn,unsubscribe:ii},this.#n=Yn;try{await this.#e.cdp.send(`Page.startScreencast`,{everyNthFrame:1,format:`jpeg`,maxHeight:Jn.height,maxWidth:Jn.width,quality:Zn},jn)}catch(xn){throw ii(),this.#t=null,this.#n=null,ri(xn),xn}})}async stop(xn={}){return await withCurrentReplAbort(async()=>{let jn=this.#t;if(!jn)throw Error(`Video recording has not been started.`);this.#t=null,jn.unsubscribe(),await this.#e.cdp.send(`Page.stopScreencast`,undefined,jn.sessionId).catch(()=>{});try{let Vn=await this.#e.screenshot({type:`jpeg`}).catch(()=>{return}),qn=xn.path?await this.#e.browser.ensurePath(xn.path,`write`,`page.video.stop`):jn.outputPath;await jn.recorder.stop(Vn),qn!==jn.outputPath&&(await ensureDirForFile(qn),await fs$16.copyFile(jn.outputPath,qn)),this.#n=qn;for(let xn of jn.pendingCopies){let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);jn!==qn&&(await ensureDirForFile(jn),await fs$16.copyFile(qn,jn))}jn.resolveCompletion(qn)}catch(xn){throw jn.rejectCompletion(xn),xn}})}async path(){if(this.#t)return this.#t.outputPath;if(this.#n)return this.#n;throw Error(`Video recording has not been started.`)}async saveAs(xn){return await withCurrentReplAbort(async()=>{let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);if(this.#t){this.#t.pendingCopies.add(xn),await this.#t.completion;return}if(!this.#n)throw Error(`Video recording has not been started.`);await ensureDirForFile(jn),await fs$16.copyFile(this.#n,jn)})}async delete(){return await withCurrentReplAbort(async()=>{if(this.#t&&await this.stop(),!this.#n)throw Error(`Video recording has not been started.`);let xn=this.#n;this.#n=null,await fs$16.unlink(xn).catch(()=>{})})}}});function isOmOEvaluateOptions(xn){if(typeof xn!=`object`||!xn||Array.isArray(xn))return false;let jn=Object.keys(xn);return jn.length===1&&jn[0]===`userGesture`}function resolveEvaluateCall(xn,jn,Vn){if(Vn!==undefined&&!isOmOEvaluateOptions(Vn))throw Error(`page.evaluate() accepts a single optional argument. Pass multiple values as one object or array, e.g. page.evaluate(fn, [a, b]).`);return typeof xn==`string`&&isOmOEvaluateOptions(jn)?{actualArg:undefined,evaluateOptions:jn}:{actualArg:jn,evaluateOptions:Vn??{}}}function clampScreenshotClipToTextureLimit(xn,jn){let Vn=Math.max(1,Math.floor(MAX_SCREENSHOT_TEXTURE_SIZE/(Number.isFinite(jn)&&jn>0?jn:1)));return{...xn,width:Math.max(1,Math.min(xn.width,Vn)),height:Math.max(1,Math.min(xn.height,Vn))}}function normalizeScreenshotTimeout(xn){if(xn!==undefined){if(!Number.isFinite(xn)||xn<0)throw Error(`page.screenshot: timeout must be a non-negative number`);return xn}}function screenshotCaptureLabel(xn){return xn.clip?`clipped screenshot`:xn.fullPage?`full-page screenshot`:`viewport screenshot`}function formatScreenshotError(xn){return xn instanceof Error?xn.message:String(xn)}function rewriteCaptureScreenshotError(xn,jn,Vn){let qn=formatScreenshotError(xn);if(qn!==`CDP command timeout: Page.captureScreenshot`)return xn instanceof Error?xn:Error(qn);let Jn=jn===undefined?`the default screenshot timeout`:jn===0?`a disabled page.screenshot timeout`:`the requested ${jn}ms page.screenshot timeout`;return Error(`page.screenshot: browser CDP command timed out while capturing ${Vn} before ${Jn} completed`)}function isCaptureScreenshotTimeout(xn){let jn=formatScreenshotError(xn);return jn===`CDP command timeout: Page.captureScreenshot`||jn.startsWith(`page.screenshot: browser CDP command timed out while capturing `)}function formatPdfLength(xn){if(xn!==undefined)return typeof xn==`number`?`${xn}px`:xn}var DEFAULT_WAIT_TIMEOUT_MS;var NETWORK_IDLE_MS;var MAX_SCREENSHOT_TEXTURE_SIZE;var FILECHOOSER_OOPIF_FALLBACK_MS;var OmOPage;var init_page=__esmMin(()=>{init_emittery(),init_context(),init_extension_bridge(),init_notification_grants(),init_utils$13(),init_client$6(),init_errors$3(),init_utils$4(),init_console_capture(),init_download(),init_file_chooser(),init_frame(),init_frame_manager(),init_keyboard(),init_locator(),init_mouse(),init_snapshot(),init_video(),init_wait(),DEFAULT_WAIT_TIMEOUT_MS=30000,NETWORK_IDLE_MS=500,MAX_SCREENSHOT_TEXTURE_SIZE=16384,FILECHOOSER_OOPIF_FALLBACK_MS=2000,OmOPage=class{cdp;frameManager;targetId;modifierState;mouse;keyboard;events=new Emittery;browser;#e=new Map;#t=null;#n;#r=``;#i=null;#a=[];#o=null;#s=false;#c=0;constructor(xn,jn,Vn,qn,Jn){this.cdp=xn,this.frameManager=jn,this.targetId=Vn,this.modifierState=new ModifierState,this.mouse=new OmOMouse(this,this.modifierState),this.keyboard=new OmOKeyboard(this,this.modifierState),this.browser=Jn,this.#n=qn,this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??``,this.#l()}#l(){let xn=new Set,jn=(xn)=>{replPrint(`[error] page event listener threw: ${xn instanceof Error?xn.message:xn}`)};this.#u(`Page.frameNavigated`,(xn)=>{xn.frame.parentId||(this.#r=xn.frame.url)}),this.#u(`Page.loadEventFired`,()=>{this.events.emit(`load`).catch(jn)}),this.#u(`Page.domContentEventFired`,()=>{this.events.emit(`domcontentloaded`).catch(jn)}),this.#u(`Page.javascriptDialogOpening`,(xn)=>{this.events.emit(`dialog`,{type:xn.type,message:xn.message,defaultPrompt:xn.defaultPrompt??``,url:xn.url}).catch(jn)}),this.#a.push(this.cdp.on(`Page.fileChooserOpened`,(xn,Vn)=>{!Vn.sessionId||!xn.backendNodeId||this.events.emit(`filechooser`,new FileChooser(this,xn.frameId,xn.backendNodeId,xn.mode===`selectMultiple`)).catch(jn)})),this.#u(`Page.frameAttached`,(xn)=>{this.events.emit(`frameattached`,{frameId:xn.frameId,parentFrameId:xn.parentFrameId}).catch(jn)}),this.#u(`Page.frameDetached`,(xn)=>{this.events.emit(`framedetached`,{frameId:xn.frameId}).catch(jn)}),this.#u(`Page.frameNavigated`,(xn)=>{this.events.emit(`framenavigated`,{frameId:xn.frame.id,url:xn.frame.url,name:xn.frame.name??``}).catch(jn)});let Vn=(Vn)=>{xn.has(Vn.guid)||this.frameManager.getFrame(Vn.frameId)&&(xn.add(Vn.guid),this.events.emit(`download`,new OmODownload(this,{guid:Vn.guid,startedAfterMs:Date.now(),suggestedFilename:Vn.suggestedFilename,url:Vn.url})).catch(jn))};this.#a.push(this.cdp.on(`Browser.downloadWillBegin`,(xn)=>Vn(xn))),this.#u(`Page.downloadWillBegin`,(xn)=>{Vn(xn)}),this.#a.push(this.cdp.on(`Page.windowOpen`,(xn,Vn)=>{!Vn.sessionId||!this.frameManager.hasSession(Vn.sessionId)||this.events.emit(`popup`,{url:xn.url,windowName:xn.windowName}).catch(jn)})),this.#u(`Inspector.targetCrashed`,()=>{this.events.emit(`crash`).catch(jn)}),this.frameManager.onSessionInitialized=(xn)=>{this.#c>0&&this.#p(true,[xn])}}#u(xn,jn){this.#a.push(this.cdp.on(xn,(xn,Vn)=>{Vn.sessionId===this.#n&&jn(xn)}))}on(xn,jn){let Vn=this.#e.get(xn)??new WeakMap,qn=this.events.on(xn,({data:xn})=>jn(xn));return Vn.set(jn,qn),this.#e.set(xn,Vn),xn===`filechooser`&&this.#m(),()=>{qn(),Vn.delete(jn),xn===`filechooser`&&this.#h()}}off(xn,jn){let Vn=this.#e.get(xn),qn=Vn?.get(jn);qn?.(),Vn?.delete(jn),qn&&xn===`filechooser`&&this.#h()}async waitForEvent(xn,jn={}){let Vn=jn.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(xn===`download`){let qn=Date.now();return await new Promise((Jn,Yn)=>{let Zn=false,Qn=()=>{ri(),clearTimeout(ni)},ei=(xn)=>{Zn||(Zn=true,Qn(),xn())},ti=(xn)=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>Jn(xn))}catch(xn){ei(()=>Yn(xn instanceof Error?xn:Error(String(xn))))}})()},ni=setTimeout(()=>{ei(()=>Yn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn),ri=this.on(`download`,ti);this.cdp.send(`OmO.waitForDownload`,{startedAfterMs:qn,timeoutMs:Vn},undefined,{extensionBridge:this.browser.extensionBridgeRoute}).then((xn)=>{ti(new OmODownload(this,{guid:String(xn.downloadId),sourcePath:xn.absolutePath,startedAfterMs:qn,suggestedFilename:path.basename(xn.absolutePath),url:this.url()}))}).catch(()=>{})})}return await new Promise((qn,Jn)=>{let Yn=false,Zn=null,Qn=()=>{ni(),clearTimeout(ti),Zn&&clearTimeout(Zn)},ei=(xn)=>{Yn||(Yn=true,Qn(),xn())},ti=setTimeout(()=>{ei(()=>Jn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn);xn===`filechooser`&&Vn>FILECHOOSER_OOPIF_FALLBACK_MS&&(Zn=setTimeout(()=>{Yn||this.#g().then((xn)=>{xn&&!Yn&&ei(()=>qn(xn))})},FILECHOOSER_OOPIF_FALLBACK_MS));let ni=this.on(xn,(xn)=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>qn(xn))}catch(xn){ei(()=>Jn(xn instanceof Error?xn:Error(String(xn))))}})()})})}#d(){for(let xn of this.#a)xn();this.#a=[]}async dispose(){this.#s||(this.#s=true,await this.#o?.stop().catch(()=>{}),this.#d(),this.#c=0,await this.events.emit(`close`),this.events.clearListeners(),this.#e.clear())}reconnect(xn){this.#n=xn,this.#s=false,this.#d(),this.#l(),this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??this.#r,this.#c>0&&this.#p(true)}#f(){return[...new Set([this.#n,...[...this.frameManager.frames.values()].map((xn)=>xn.sessionId)])]}async prepareForPotentialFileChooser(){this.#c!==0&&await this.#p(true)}#p(xn,jn=this.#f()){return withoutReplContext(async()=>{await Promise.allSettled(jn.map((jn)=>this.cdp.send(`Page.setInterceptFileChooserDialog`,{enabled:xn},jn)))})}#m(){this.#c+=1,this.#c===1&&this.#p(true)}#h(){this.#c!==0&&(--this.#c,this.#c===0&&this.#p(false))}async#g(){for(let xn of this.frameManager.frames.values())if(xn.sessionId!==this.#n)try{let{root:jn}=await this.cdp.send(`DOM.getDocument`,{depth:0},xn.sessionId),{nodeIds:Vn}=await this.cdp.send(`DOM.querySelectorAll`,{nodeId:jn.nodeId,selector:`input[type=file]`},xn.sessionId);if(Vn.length===0)continue;let qn=Vn[Vn.length-1],{node:Jn}=await this.cdp.send(`DOM.describeNode`,{nodeId:qn},xn.sessionId),Yn=(Jn.attributes??[]).includes(`multiple`);return new FileChooser(this,xn.frameId,Jn.backendNodeId,Yn)}catch{}return null}async resolveSessionId(xn){if(xn&&this.frameManager.hasSession(xn))return xn;let jn=await this.browser.resolvePageSession(this.targetId,this.#n);return jn!==this.#n&&(this.#n=jn),jn}async goto(xn,jn={}){let Vn=jn.waitUntil??`interactive`,qn=await this.resolveSessionId(this.#n),Jn=()=>{},Yn=Vn===`commit`?null:Vn===`interactive`||Vn===`stable`?waitForNavigationReadiness(this,Vn,DEFAULT_WAIT_TIMEOUT_MS).then(()=>{}):Vn===`networkidle`?this.#S(DEFAULT_WAIT_TIMEOUT_MS):new Promise((xn,jn)=>{let Yn=false,Zn,Qn=()=>{},ei=(xn)=>{Yn||(Yn=true,clearTimeout(Zn),Qn(),xn())};Zn=setTimeout(()=>{ei(()=>jn(Error(`Timed out waiting for "${Vn}" after goto`)))},DEFAULT_WAIT_TIMEOUT_MS);let ti=Vn===`load`?`Page.loadEventFired`:`Page.domContentEventFired`;Qn=this.cdp.on(ti,(jn,Vn)=>{Vn.sessionId===qn&&ei(xn)}),Jn=()=>ei(xn)}),Zn=await this.cdp.send(`Page.navigate`,{url:xn},qn);if(Zn.errorText)throw Error(Zn.errorText);if(this.#r=xn,Vn===`domcontentloaded`&&Yn){if(!Zn.loaderId){Jn(),await this.#v(`Timed out waiting for "${Vn}" after goto`);return}try{await Yn}catch(xn){if(await this.#_())return;throw xn}return}Yn&&await Yn}async goBack(){let xn=await this._sendToTarget(`Page.getNavigationHistory`),jn=xn.currentIndex-1;if(jn<0)return;let Vn=xn.entries[jn];if(!Vn)return;let qn=this.#C();await this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:Vn.id}),await qn}async goForward(){let xn=await this._sendToTarget(`Page.getNavigationHistory`),jn=xn.currentIndex+1;if(jn>=xn.entries.length)return;let Vn=xn.entries[jn];if(!Vn)return;let qn=this.#C();await this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:Vn.id}),await qn}async reload(){let xn=this.#C();await this._sendToTarget(`Page.reload`),await xn}async waitForLoadState(xn=`interactive`,jn=DEFAULT_WAIT_TIMEOUT_MS){if(xn===`interactive`||xn===`stable`){await waitForNavigationReadiness(this,xn,jn);return}if(xn===`networkidle`||xn===`load`){replPrint(`[system] this is redundant wait; openTab() already waits for the page to become usable. Falling back to 'stable' with 5s timeout.`),await waitForNavigationReadiness(this,`stable`,5000).catch(()=>{});return}if(await this.#_())return;let Vn=`Page.domContentEventFired`,qn=await this.resolveSessionId(this.#n);await new Promise((jn,Vn)=>{let Jn=setTimeout(()=>{Yn(),Vn(Error(`Timed out waiting for load state "${xn}"`))},DEFAULT_WAIT_TIMEOUT_MS),Yn=this.cdp.on(`Page.domContentEventFired`,(xn,Vn)=>{Vn.sessionId===qn&&(clearTimeout(Jn),Yn(),jn())})})}async#_(){return await this.evaluate(`document.readyState`).catch(()=>`loading`)!==`loading`}async#v(xn,jn=DEFAULT_WAIT_TIMEOUT_MS){let Vn=Date.now();for(;Date.now()-Vn<jn;){if(await this.#_())return;await sleep$12(50)}throw Error(xn)}async waitForURL(xn,jn={}){let Vn=jn.timeout??DEFAULT_WAIT_TIMEOUT_MS,qn=Date.now();for(;Date.now()-qn<Vn;){let jn=this.url();if(typeof xn==`string`?jn===xn:xn.test(jn))return;await sleep$12(100)}throw Error(`Timed out waiting for URL match: ${String(xn)}`)}async waitForSelector(xn,jn={}){let Vn=jn.state??`visible`,qn=jn.timeout??3000,Jn=[0,20,50,100,100,500],Yn=Date.now(),Zn=0;for(;;){if(Date.now()-Yn>=qn)throw Error(`waitForSelector: timed out after ${qn}ms waiting for "${xn}" to be ${Vn}`);let jn=await this.evaluate((xn)=>{let jn=document.querySelector(xn);if(!jn)return{attached:false,visible:false};let Vn=jn.getBoundingClientRect(),qn=window.getComputedStyle(jn);return{attached:true,visible:qn.visibility!==`hidden`&&qn.display!==`none`&&parseFloat(qn.opacity)!==0&&Vn.width>0&&Vn.height>0}},xn);if(Vn===`attached`?jn.attached:Vn===`detached`?!jn.attached:Vn===`visible`?jn.visible:!jn.visible)return;let Qn=Jn[Math.min(Zn++,Jn.length-1)];await sleep$12(Qn)}}locator(xn,jn={}){return new Locator(this,xn).filter(jn)}async click(xn,jn){await this.locator(xn).click(jn)}async fill(xn,jn){await this.locator(xn).fill(jn)}async $(xn){return replPrint(`warn`,`page.$() is deprecated in OmOWright — use page.locator(selector).first() instead`),this.locator(xn).first()}async $$(xn){return replPrint(`warn`,`page.$$() is deprecated in OmOWright — use page.locator(selector).all() instead`),await this.locator(xn).all()}async $$eval(xn,jn,Vn){return await this.locator(xn).evaluateAll(jn,Vn)}getByRole(xn,jn={}){return new Locator(this,Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`internal:label=/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(xn){return new FrameLocator(this,this.mainFrame(),xn)}async evaluate(xn,jn,Vn){let{actualArg:qn,evaluateOptions:Jn}=resolveEvaluateCall(xn,jn,Vn);if(typeof xn==`string`&&qn===undefined){let{result:jn,exceptionDetails:Vn}=await this._sendToTarget(`Runtime.evaluate`,{expression:xn,returnByValue:true,awaitPromise:true,userGesture:Jn.userGesture});if(Vn)throw Error(formatRuntimeException(Vn,`Evaluation failed`));return jn.value}let Yn=typeof xn==`function`?xn.toString():xn,Zn=await this.#x();try{let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.callFunctionOn`,{objectId:Zn,functionDeclaration:`function(arg) { var __name = (t) => t; return (${Yn})(arg); }`,arguments:[{value:qn}],returnByValue:true,awaitPromise:true,userGesture:Jn.userGesture});if(jn)throw Error(formatRuntimeException(jn,`Evaluation failed`));return xn.value}finally{await this._sendToTarget(`Runtime.releaseObject`,{objectId:Zn}).catch(()=>{})}}async evaluateInFrame(xn,jn,Vn,qn){let Jn=this.frameManager.getFrame(xn);if(!Jn)throw Error(`Frame is not available: ${xn}`);let{actualArg:Yn,evaluateOptions:Zn}=resolveEvaluateCall(jn,Vn,qn),Qn=await this.resolveSessionId(Jn.sessionId);if(typeof jn==`string`&&Yn===undefined){let Vn=await this.frameManager.ensureInjected(xn);if(!Vn)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:qn,exceptionDetails:Jn}=await this.cdp.send(`Runtime.evaluate`,{expression:jn,contextId:Vn,returnByValue:true,awaitPromise:true,userGesture:Zn.userGesture},Qn);if(Jn)throw Error(formatRuntimeException(Jn,`Evaluation failed`));return qn.value}let ei=typeof jn==`function`?jn.toString():jn,ti=await this.frameManager.ensureInjected(xn);if(!ti)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:ni,exceptionDetails:ri}=await this.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(arg) { var __name = (t) => t; return (${ei})(arg); }`,arguments:[{value:Yn}],executionContextId:ti,returnByValue:true,awaitPromise:true,userGesture:Zn.userGesture},Qn);if(ri)throw Error(formatRuntimeException(ri,`Evaluation failed`));return ni.value}async grantNotificationPermission(){await sendCommandToExtension({method:`OmO.grantNotificationPermission`,params:{targetId:this.targetId}},this.browser.extensionBridgeRoute);let xn=new URL(this.#r).origin,jn=this.browser.daemonSession;upsertNotificationGrant({accountId:jn.accountId,origin:xn,grantedBySessionId:jn.id})}url({truncate:xn=false}={}){return xn?truncateUrlForLLM(this.#r):this.#r}async title(){return await this.evaluate(`document.title`).catch(()=>``)}async content(){return await this.evaluate(`document.documentElement.outerHTML`)}async screenshot(xn={}){let jn=normalizeScreenshotTimeout(xn.timeout),Vn=jn&&jn>0?Date.now()+jn:undefined,qn;if(xn.clip)qn={x:xn.clip.x,y:xn.clip.y,width:xn.clip.width,height:xn.clip.height,scale:1};else if(xn.fullPage){let xn=await this._sendToTarget(`Page.getLayoutMetrics`),jn=xn.cssContentSize??xn.contentSize;qn={x:0,y:0,width:jn.width,height:jn.height,scale:1}}qn&&=clampScreenshotClipToTextureLimit(qn,await this.#y());let Jn={format:xn.type??`png`,captureBeyondViewport:!!xn.fullPage,quality:xn.quality,...qn?{clip:qn}:{}},Yn;try{({data:Yn}=await this.#b(Jn,jn,screenshotCaptureLabel(xn)))}catch(jn){if(!xn.fullPage||xn.clip||!isCaptureScreenshotTimeout(jn))throw jn;let qn=Vn?Math.max(0,Vn-Date.now()):undefined;if(qn===0)throw jn;let Jn={format:xn.type??`png`,captureBeyondViewport:false,quality:xn.quality};try{({data:Yn}=await this.#b(Jn,qn,`viewport fallback screenshot`)),replPrint(`[system] full-page screenshot failed; returned viewport fallback. ${formatScreenshotError(jn)}`)}catch(xn){throw Error(`${formatScreenshotError(jn)}
1481
- Viewport fallback also failed: ${formatScreenshotError(xn)}`)}}let Zn=Buffer.from(Yn,`base64`);if(xn.path)if(xn.path.startsWith(`/tmp`)){let jn=this.browser.resolvePath(`tmp`),Vn=path.join(jn,path.basename(xn.path));await mkdir(path.dirname(Vn),{recursive:true}),await writeFile(Vn,Zn),replPrint(`[WARN] Use ${jn} instead of /tmp. Saved it to ${Vn}`)}else{let jn=this.browser.resolvePath(xn.path);await mkdir(path.dirname(jn),{recursive:true}),await writeFile(jn,Zn)}return Zn}async#y(){return await this.evaluate(`window.devicePixelRatio`).catch(()=>1)}async#b(xn,jn,Vn){try{return await this._sendToTarget(`Page.captureScreenshot`,xn,{timeoutMs:jn})}catch(xn){throw rewriteCaptureScreenshotError(xn,jn,Vn)}}async snapshot(xn={}){return await takeSnapshot(this.cdp,this.frameManager,xn)}frames(){return this.frameManager.collectDescendantFrames(this.frameManager.mainFrameId).map(({frameId:xn})=>new OmOFrame(this,xn))}mainFrame(){let xn=this.frameManager.getFrame(this.frameManager.mainFrameId);if(!xn)throw Error(`Main frame is not available`);return new OmOFrame(this,xn.frameId)}async bringToFront(){this.browser.page=this,replPrint(`page is now [${await this.title().catch(()=>``)}](${this.url()})`)}async openPopupUrl(xn){await this.browser.openPopupTab(xn,this.targetId)}get console(){return this.#t??=new PageConsole(this)}video(){return this.#w()}viewportSize(){return this.#i?{...this.#i}:null}async refreshViewportSize(){let xn=await this.evaluate(()=>({width:Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0),height:Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0)}));if(xn.width<=0||xn.height<=0)throw Error(`Measured viewport size is invalid: ${JSON.stringify(xn)}`);return this.#i=xn,xn}setCachedViewportSize(xn){this.#i=xn?{...xn}:null}async pdf(xn={}){let jn=xn.path?await this.browser.ensurePath(xn.path,`write`,`page.pdf`):undefined,Vn={...xn,height:formatPdfLength(xn.height),margin:xn.margin?{bottom:formatPdfLength(xn.margin.bottom),left:formatPdfLength(xn.margin.left),right:formatPdfLength(xn.margin.right),top:formatPdfLength(xn.margin.top)}:undefined,printBackground:xn.printBackground??true,transferMode:`ReturnAsBase64`,width:formatPdfLength(xn.width)},{data:qn}=await this._sendToTarget(`Page.printToPDF`,Vn),Jn=Buffer.from(qn,`base64`);return jn&&(await mkdir(path.dirname(jn),{recursive:true}).catch(()=>{}),await writeFile(jn,Jn)),Jn}async close(xn={}){if(await this.#w().stop().catch(()=>{}),xn.runBeforeUnload){let jn=await this.resolveSessionId(this.#n);await this.cdp.send(`Page.close`,undefined,jn).catch(async()=>{await this.browser.closeTab(this,xn)});return}await this.browser.closeTab(this,xn)}async#x(){let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.evaluate`,{expression:`globalThis`,serializationOptions:{serialization:`idOnly`}});if(jn)throw Error(formatRuntimeException(jn,`Failed to resolve main world`));if(!xn.objectId)throw Error(`Main world object is not available`);return xn.objectId}async#S(xn){await this._sendToTarget(`Network.enable`).catch(()=>{});let jn=await this.resolveSessionId(this.#n);await new Promise((Vn,qn)=>{let Jn=new Set,Yn=null,Zn=null,Qn=()=>{ti(),ri(),ii(),Yn&&=(clearTimeout(Yn),null),Zn&&=(clearTimeout(Zn),null)},ei=()=>{Yn&&clearTimeout(Yn),Jn.size===0&&(Yn=setTimeout(()=>{Qn(),Vn()},NETWORK_IDLE_MS))},ti=this.cdp.on(`Network.requestWillBeSent`,(xn,Vn)=>{Vn.sessionId===jn&&(xn.request.url.startsWith(`data:`)||Jn.add(xn.requestId))}),ni=(xn)=>{Jn.delete(xn),ei()},ri=this.cdp.on(`Network.loadingFinished`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)}),ii=this.cdp.on(`Network.loadingFailed`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)});Zn=setTimeout(()=>{Qn(),qn(Error(`Timed out waiting for load state "networkidle"`))},xn),ei()})}async#C(){let xn=await this.resolveSessionId(this.#n);await new Promise((jn,Vn)=>{let qn=setTimeout(()=>{Jn(),Vn(Error(`Timed out waiting for navigation`))},DEFAULT_WAIT_TIMEOUT_MS),Jn=this.cdp.on(`Page.frameNavigated`,(Vn,Yn)=>{Yn.sessionId===xn&&(Vn.frame.parentId||(clearTimeout(qn),Jn(),jn()))})})}async _sendToTarget(xn,jn,Vn={}){if(this.#s)throw Error(`Page ${this.targetId} is disposed`);let{preferredSessionId:qn,...Jn}=Vn;if(qn!==undefined){if(!this.frameManager.hasSession(qn))throw Error(`Frame is stale or detached: CDP session ${qn} is unavailable`);return await this.cdp.send(xn,jn,qn,Jn)}let Yn=await this.resolveSessionId(this.#n);return await this.cdp.send(xn,jn,Yn,Jn)}#w(){return this.#o??=new OmOVideo(this),this.#o}}});init_client$6();init_session_manager();init_frame_manager();init_page();class TabRepository{#client;constructor(client){this.#client=client}async listTargets(){return this.#client.discoverTargets()}}class BrowserConnection{#client;#sessions;#pages=new Map;#storageRoot;constructor(client,options={}){this.#client=client;this.#sessions=new SessionManager(client);this.tabs=new TabRepository(client);this.#storageRoot=path2.resolve(options.storageRoot??process.cwd())}async initialize(){await this.#client.ensureConnected();return this}get cdp(){return this.#client}setDialogPolicy(policy){if(typeof this.#client.setDialogPolicy!=="function"){throw new Error("dialog policy is not supported by this transport")}this.#client.setDialogPolicy(policy)}async listTargets(){return this.tabs.listTargets()}async attachPage(targetId){if(this.#pages.has(targetId))return this.#pages.get(targetId).page;const sessionId=await this.#sessions.resolvePageSession(targetId);const frames=new FrameManager(this.#client,targetId,sessionId);await frames.initialize();const entry={frames,page:null};const host=this.#createPageHost(targetId,entry);const page=new OmOPage(this.#client,frames,targetId,sessionId,host);entry.page=page;this.#pages.set(targetId,entry);return page}#createPageHost(targetId,entry){return{daemonSession:{accountId:0,id:"standalone"},extensionBridgeRoute:{},page:null,resolvePageSession:(id,preferred)=>this.#sessions.resolvePageSession(id,preferred),resolvePath:(value)=>path2.resolve(this.#storageRoot,value),ensurePath:async(value)=>{const resolved=path2.resolve(this.#storageRoot,value);await mkdir2(path2.dirname(resolved),{recursive:true});return resolved},registerReadableDownload:(value)=>value,isReadableDownload:()=>false,openPopupTab:async()=>{throw Error("Popup tab control requires the extension bridge")},closeTab:async(_page,options={})=>{if(options.runBeforeUnload){await this.#client.send("Page.close",undefined,await this.#sessions.resolvePageSession(targetId))}else{await this.#client.send("Target.closeTarget",{targetId})}await entry.page?.dispose();await entry.frames.dispose();this.#pages.delete(targetId)}}}async close(){for(const[targetId,entry]of[...this.#pages]){await entry.page.dispose().catch(()=>{});await entry.frames.dispose().catch(()=>{});this.#pages.delete(targetId)}await this.#sessions.dispose();await this.#client.close()}}async function connect(cdpHttpUrl,options={}){if(typeof cdpHttpUrl!=="string"||cdpHttpUrl.length===0){throw new TypeError("connect(cdpHttpUrl) requires a Chromium CDP HTTP URL")}const client=new CdpClient({cdpUrl:cdpHttpUrl,...options.client});return new BrowserConnection(client,options).initialize()}import{spawn}from"node:child_process";function normalizeDialogPolicy(policy){return policy??{accept:true}}function dialogFromOpening(params={}){return{type:params.type,message:params.message,defaultPrompt:params.defaultPrompt??"",url:params.url}}function decisionFromResult(result){if(typeof result==="boolean")return{accept:result};if(result&&typeof result==="object"){const decision={accept:result.accept!==false};if(result.promptText!==undefined)decision.promptText=result.promptText;return decision}return{accept:true}}async function resolveDialogAction(policy,params={}){try{const result=typeof policy==="function"?await policy(dialogFromOpening(params)):policy;return decisionFromResult(result)}catch{return{accept:true}}}init_internal_capability();class Emittery2{#listeners=new Map;on(event,fn){const list=this.#listeners.get(event)??[];list.push(fn);this.#listeners.set(event,list);return()=>{const cur=this.#listeners.get(event)??[];this.#listeners.set(event,cur.filter((f)=>f!==fn))}}async emit(event,data){for(const fn of this.#listeners.get(event)??[])await fn(data)}}var DEFAULT_COMMAND_TIMEOUT_MS2=30000;var DEFAULT_READINESS_TIMEOUT_MS=1e4;var GRACEFUL_CLOSE_TIMEOUT_MS=2000;var STDIO_TAIL_LIMIT=16384;class PipeCdpClient{#child;#writeStream;#readStream;#buffer=Buffer.alloc(0);#seq=1;#pending=new Map;#events=new Emittery2;#connected=false;#commandTimeoutMs;#readinessTimeoutMs;#browserPath;#browserArgs;#spawnOptions;#stdioTail="";#dialogPolicy;transportEvents=new Emittery2;logId;constructor({browserPath,browserArgs=[],spawnOptions={},commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy}){if(!browserPath)throw new TypeError("PipeCdpClient requires browserPath");this.#browserPath=browserPath;this.#browserArgs=browserArgs;this.#spawnOptions=spawnOptions;this.#commandTimeoutMs=commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS2;this.#readinessTimeoutMs=readinessTimeoutMs??DEFAULT_READINESS_TIMEOUT_MS;this.logId=logId??`cdp-pipe-${Date.now()}`;this.#dialogPolicy=normalizeDialogPolicy(dialogPolicy)}get isConnected(){return this.#connected}get isHeadless(){return this.#browserArgs.some((arg)=>/^--headless(?:=|$)/.test(arg))}get childProcess(){return this.#child}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(policy){this.#dialogPolicy=normalizeDialogPolicy(policy)}async ensureConnected(){if(this.#connected)return;const stdio=["ignore","pipe","pipe","pipe","pipe"];this.#child=spawn(this.#browserPath,[...this.#browserArgs,"--remote-debugging-pipe"],{...this.#spawnOptions,stdio});this.#stdioTail="";for(const stream of[this.#child.stdout,this.#child.stderr]){if(!stream)continue;stream.setEncoding("utf8");stream.on("data",(chunk)=>{this.#stdioTail=(this.#stdioTail+chunk).slice(-STDIO_TAIL_LIMIT)});stream.on("error",()=>{})}this.#writeStream=this.#child.stdio[3];this.#readStream=this.#child.stdio[4];this.#readStream.on("data",(chunk)=>this.#onData(chunk));for(const stream of[this.#writeStream,this.#readStream]){stream.on("error",(error)=>this.#failAll(Error(`CDP pipe error: ${error.code??error.message}`)))}this.#child.on("exit",()=>{this.#connected=false;this.#failAll(Error("CDP pipe browser exited"));this.transportEvents.emit("disconnected").catch(()=>{})});this.#connected=true;await this.#awaitReady();await this.send("Target.setDiscoverTargets",{discover:true}).catch(()=>{});await this.transportEvents.emit("connected")}async#awaitReady(){const deadline=Date.now()+this.#readinessTimeoutMs;let lastError;while(Date.now()<deadline){try{await this.send("Browser.getVersion",undefined,undefined,{timeoutMs:1000});return}catch(error){lastError=error;await new Promise((resolve)=>setTimeout(resolve,100))}}const reason=lastError?String(lastError.message??lastError):"no response";const tail=this.#stdioTail.trim();throw Error(`Browser did not become ready over the CDP pipe (${reason})`+(tail?`
1467
+ }`,arguments:[{value:qn}],executionContextId:Jn.isolatedContextId,returnByValue:false},Jn.sessionId).catch((xn)=>(isContextDestroyedError(xn)&&jn.invalidateContext(Vn),{result:{}})),Zn=typeof Yn==`object`&&Yn&&`objectId`in Yn?Yn.objectId:undefined;if(!Zn)return null;try{let{node:Vn}=await xn.send(`DOM.describeNode`,{objectId:Zn},Jn.sessionId),Yn=Vn.frameId?jn.getFrame(Vn.frameId)?.url:null,Qn=getCdpNodeAttribute(Vn.attributes,`src`),ei=getKnownIframeOriginLabel(Yn??``)??getKnownIframeOriginLabel(Qn??``);return{childFrameId:Vn.frameId,iframeRef:qn,originLabel:ei}}catch{return null}finally{await xn.send(`Runtime.releaseObject`,{objectId:Zn},Jn.sessionId).catch(()=>{})}})),Qn=new Map,ei=new Map;for(let xn of Zn)xn&&(xn.childFrameId&&Qn.set(xn.childFrameId,xn.iframeRef),xn.originLabel&&ei.set(xn.iframeRef,xn.originLabel));ai.set(Vn,Qn),ei.size>0&&oi.set(Vn,ei)}));let si=[...ti].sort((xn,jn)=>jn.depth-xn.depth),ci={};for(let xn of ni.values())Object.assign(ci,xn.refs);for(let[xn,jn]of oi){let Vn=ni.get(xn);if(Vn)for(let[xn,qn]of jn)Vn.tree=tagIframeLine(Vn.tree,xn,qn)}for(let xn of si){if(xn.frameId===qn||!xn.parentFrameId)continue;let Vn=ni.get(xn.frameId),Jn=ni.get(xn.parentFrameId);if(!Vn||!Jn||!Vn.tree)continue;let Yn=ai.get(xn.parentFrameId)?.get(xn.frameId),Zn=getKnownIframeOriginLabel(jn.getFrame(xn.frameId)?.url??``);Jn.tree=Yn?inlineChildTree(Jn.tree,Yn,Vn.tree):appendOrphanChildTree(Jn.tree,Vn.tree,Zn)}return{tree:ii.tree,refs:ci}}var KNOWN_IFRAME_ORIGINS;var SNAPSHOT_RETRY_DELAY_MS;var SNAPSHOT_MAX_RETRIES;var init_snapshot=__esmMin(()=>{init_extension_ids(),init_utils$13(),init_client$6(),init_frame_manager(),KNOWN_IFRAME_ORIGINS=[{urlPrefix:`chrome-extension://aeblfdkhhhdcdjpifhhbdiojplfjncoa/`,label:`1Password`},{urlPrefix:`chrome-extension://nngceckbapebfimnlniiiahkandclblb/`,label:`Bitwarden`},{urlPrefix:`chrome-extension://fdjamakpfbbddfjaooikfcpapjohcfmg/`,label:`Dashlane`},{urlPrefix:`chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/`,label:`LastPass`},{urlPrefix:`${PASSWORD_MANAGER_EXTENSION_ORIGIN}/`,label:`OmO Password Manager`}],SNAPSHOT_RETRY_DELAY_MS=300,SNAPSHOT_MAX_RETRIES=3});var formatRange;var init_diff=__esmMin(()=>{formatRange=(xn,jn)=>jn===1?String(xn):`${xn},${jn}`});var init_session_tab_queries=__esmMin(()=>{init_drizzle_orm(),init_event_bus(),init_extension_bridge(),init_schema(),init_state_db(),init_nanoid(),init_utils$13(),init_store$1()});var ANNOTATION_OVERLAY_ID;var init_annotate_screenshot=__esmMin(()=>{ANNOTATION_OVERLAY_ID=`__omowright_annotations__`});var AI_TAB_STABLE_VIEWPORT;var MIN_STABLE_AI_TAB_VIEWPORT;var init_browser=__esmMin(()=>{init_context(),init_cdp(),init_directory(),init_event_bus(),init_extension_bridge(),init_diff(),init_utils$13(),init_session_tab_queries(),init_store$1(),init_types$8(),init_utils$4(),init_annotate_screenshot(),init_frame_manager(),init_page(),init_snapshot(),AI_TAB_STABLE_VIEWPORT={width:1440,height:900},MIN_STABLE_AI_TAB_VIEWPORT={width:960,height:540}});function defaultVideoSize(xn){let jn=Math.min(1,DEFAULT_VIDEO_MAX_EDGE/xn.width,DEFAULT_VIDEO_MAX_EDGE/xn.height),Vn=Math.max(2,Math.round(xn.width*jn)),qn=Math.max(2,Math.round(xn.height*jn));return{height:qn%2==0?qn:qn+1,width:Vn%2==0?Vn:Vn+1}}function inferVideoFormat(xn){return xn.format?xn.format:xn.path?.toLowerCase().endsWith(`.mp4`)?`mp4`:DEFAULT_VIDEO_FORMAT}async function ensureDirForFile(xn){await fs$16.mkdir(path.dirname(xn),{recursive:true})}async function readProcessStderr(xn){return await readProcessStream(xn.stderr).catch(()=>``)}var DEFAULT_VIDEO_FORMAT;var DEFAULT_VIDEO_FRAMERATE;var DEFAULT_VIDEO_JPEG_QUALITY;var DEFAULT_VIDEO_MAX_EDGE;var FfmpegVideoRecorder;var OmOVideo;var init_video=__esmMin(()=>{init_context(),init_process(),init_browser(),DEFAULT_VIDEO_FORMAT=`webm`,DEFAULT_VIDEO_FRAMERATE=25,DEFAULT_VIDEO_JPEG_QUALITY=90,DEFAULT_VIDEO_MAX_EDGE=800,FfmpegVideoRecorder=class{#e;#t;#n=0;#r=false;#i=null;#a=Promise.resolve();#o=0;#s=[];constructor(xn,jn,Vn,qn){this.#e=Vn;let Jn=qn===`mp4`?[`-c:v`,`libx264`,`-movflags`,`+faststart`]:[`-c:v`,`libvpx`,`-qmin`,`0`,`-qmax`,`50`,`-crf`,`8`,`-deadline`,`realtime`,`-speed`,`8`,`-b:v`,`1M`];this.#t=spawnCommand([`ffmpeg`,`-loglevel`,`error`,`-f`,`image2pipe`,`-avioflags`,`direct`,`-fpsprobesize`,`0`,`-probesize`,`32`,`-analyzeduration`,`0`,`-c:v`,`mjpeg`,`-i`,`pipe:0`,`-y`,`-an`,`-r`,String(Vn),...Jn,`-threads`,`1`,`-vf`,`scale=${jn.width}:${jn.height}:force_original_aspect_ratio=decrease,pad=${jn.width}:${jn.height}:(ow-iw)/2:(oh-ih)/2:gray`,`-pix_fmt`,`yuv420p`,xn],{stdio:[`pipe`,`ignore`,`pipe`]})}writeFrame(xn,jn){if(this.#r)return;this.#n||=jn;let Vn=Math.floor((jn-this.#n)*this.#e);if(this.#i){let xn=Vn-this.#i.frameNumber;for(let jn=0;jn<xn;jn+=1)this.#s.push(this.#i.buffer);this.#a=this.#a.then(()=>this.#c())}this.#i={buffer:xn,frameNumber:Vn,timestamp:jn},this.#o=Date.now()}async stop(xn){if(this.#r)return;if(!this.#i){if(!xn)throw Error(`Video recorder did not capture any frames.`);this.writeFrame(xn,Date.now()/1000)}let jn=this.#i;if(!jn)throw Error(`Video recorder did not capture any frames.`);let Vn=Math.max((Date.now()-this.#o)/1000,1);if(this.writeFrame(Buffer.from([]),jn.timestamp+Vn),this.#r=true,await withCurrentReplAbort(async()=>await this.#a),!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let qn=this.#t.stdin;await withCurrentReplAbort(async()=>await endProcessInput(qn));let Jn=await withCurrentReplAbort(async()=>await waitForExitCode(this.#t));if(Jn!==0){let xn=await readProcessStderr(this.#t);throw Error(xn.trim()||`ffmpeg exited with code ${Jn}`)}}async#c(){if(!this.#t.stdin)throw Error(`ffmpeg stdin is unavailable.`);let xn=this.#t.stdin;for(;this.#s.length>0;){let jn=this.#s.shift();if(!(!jn||jn.length===0))try{await withCurrentReplAbort(async()=>await writeProcessChunk(xn,jn))}catch(xn){let jn=(await readProcessStderr(this.#t)).trim();throw Error(jn.length>0?`ffmpeg rejected video frame input: ${jn}`:xn instanceof Error?xn.message:String(xn))}}}},OmOVideo=class{#e;#t=null;#n=null;constructor(xn){this.#e=xn}async start(xn={}){return await withCurrentReplAbort(async()=>{if(this.#t)throw Error(`Video recording is already active.`);let jn=await this.#e.resolveSessionId(),Vn=this.#e.viewportSize()??await this.#e.refreshViewportSize().catch(()=>null)??AI_TAB_STABLE_VIEWPORT,qn=inferVideoFormat(xn),Jn=xn.size??defaultVideoSize(Vn),Yn=await this.#e.browser.ensurePath(xn.path??`video-${Date.now()}.${qn}`,`write`,`page.video.start`),Zn=xn.quality??DEFAULT_VIDEO_JPEG_QUALITY,Qn=xn.framerate??DEFAULT_VIDEO_FRAMERATE;await ensureDirForFile(Yn);let ei=new FfmpegVideoRecorder(Yn,Jn,Qn,qn),{promise:ti,resolve:ni,reject:ri}=Promise.withResolvers(),ii=this.#e.cdp.on(`Page.screencastFrame`,(xn,Vn)=>{if(Vn.sessionId!==jn)return;let qn=Buffer.from(xn.data,`base64`),Jn=xn.metadata?.timestamp??Date.now()/1000;ei.writeFrame(qn,Jn),this.#e.cdp.send(`Page.screencastFrameAck`,{sessionId:xn.sessionId},jn).catch(()=>{})});this.#t={completion:ti,format:qn,outputPath:Yn,pendingCopies:new Set,recorder:ei,rejectCompletion:ri,resolveCompletion:ni,sessionId:jn,unsubscribe:ii},this.#n=Yn;try{await this.#e.cdp.send(`Page.startScreencast`,{everyNthFrame:1,format:`jpeg`,maxHeight:Jn.height,maxWidth:Jn.width,quality:Zn},jn)}catch(xn){throw ii(),this.#t=null,this.#n=null,ri(xn),xn}})}async stop(xn={}){return await withCurrentReplAbort(async()=>{let jn=this.#t;if(!jn)throw Error(`Video recording has not been started.`);this.#t=null,jn.unsubscribe(),await this.#e.cdp.send(`Page.stopScreencast`,undefined,jn.sessionId).catch(()=>{});try{let Vn=await this.#e.screenshot({type:`jpeg`}).catch(()=>{return}),qn=xn.path?await this.#e.browser.ensurePath(xn.path,`write`,`page.video.stop`):jn.outputPath;await jn.recorder.stop(Vn),qn!==jn.outputPath&&(await ensureDirForFile(qn),await fs$16.copyFile(jn.outputPath,qn)),this.#n=qn;for(let xn of jn.pendingCopies){let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);jn!==qn&&(await ensureDirForFile(jn),await fs$16.copyFile(qn,jn))}jn.resolveCompletion(qn)}catch(xn){throw jn.rejectCompletion(xn),xn}})}async path(){if(this.#t)return this.#t.outputPath;if(this.#n)return this.#n;throw Error(`Video recording has not been started.`)}async saveAs(xn){return await withCurrentReplAbort(async()=>{let jn=await this.#e.browser.ensurePath(xn,`write`,`page.video.saveAs`);if(this.#t){this.#t.pendingCopies.add(xn),await this.#t.completion;return}if(!this.#n)throw Error(`Video recording has not been started.`);await ensureDirForFile(jn),await fs$16.copyFile(this.#n,jn)})}async delete(){return await withCurrentReplAbort(async()=>{if(this.#t&&await this.stop(),!this.#n)throw Error(`Video recording has not been started.`);let xn=this.#n;this.#n=null,await fs$16.unlink(xn).catch(()=>{})})}}});function isOmOEvaluateOptions(xn){if(typeof xn!=`object`||!xn||Array.isArray(xn))return false;let jn=Object.keys(xn);return jn.length===1&&jn[0]===`userGesture`}function resolveEvaluateCall(xn,jn,Vn){if(Vn!==undefined&&!isOmOEvaluateOptions(Vn))throw Error(`page.evaluate() accepts a single optional argument. Pass multiple values as one object or array, e.g. page.evaluate(fn, [a, b]).`);return typeof xn==`string`&&isOmOEvaluateOptions(jn)?{actualArg:undefined,evaluateOptions:jn}:{actualArg:jn,evaluateOptions:Vn??{}}}function clampScreenshotClipToTextureLimit(xn,jn){let Vn=Math.max(1,Math.floor(MAX_SCREENSHOT_TEXTURE_SIZE/(Number.isFinite(jn)&&jn>0?jn:1)));return{...xn,width:Math.max(1,Math.min(xn.width,Vn)),height:Math.max(1,Math.min(xn.height,Vn))}}function normalizeScreenshotTimeout(xn){if(xn!==undefined){if(!Number.isFinite(xn)||xn<0)throw Error(`page.screenshot: timeout must be a non-negative number`);return xn}}function screenshotCaptureLabel(xn){return xn.clip?`clipped screenshot`:xn.fullPage?`full-page screenshot`:`viewport screenshot`}function formatScreenshotError(xn){return xn instanceof Error?xn.message:String(xn)}function rewriteCaptureScreenshotError(xn,jn,Vn){let qn=formatScreenshotError(xn);if(qn!==`CDP command timeout: Page.captureScreenshot`)return xn instanceof Error?xn:Error(qn);let Jn=jn===undefined?`the default screenshot timeout`:jn===0?`a disabled page.screenshot timeout`:`the requested ${jn}ms page.screenshot timeout`;return Error(`page.screenshot: browser CDP command timed out while capturing ${Vn} before ${Jn} completed`)}function isCaptureScreenshotTimeout(xn){let jn=formatScreenshotError(xn);return jn===`CDP command timeout: Page.captureScreenshot`||jn.startsWith(`page.screenshot: browser CDP command timed out while capturing `)}function formatPdfLength(xn){if(xn!==undefined)return typeof xn==`number`?`${xn}px`:xn}var DEFAULT_WAIT_TIMEOUT_MS;var NETWORK_IDLE_MS;var MAX_SCREENSHOT_TEXTURE_SIZE;var FILECHOOSER_OOPIF_FALLBACK_MS;var OmOPage;var init_page=__esmMin(()=>{init_emittery(),init_context(),init_extension_bridge(),init_notification_grants(),init_utils$13(),init_client$6(),init_errors$3(),init_utils$4(),init_console_capture(),init_download(),init_file_chooser(),init_frame(),init_frame_manager(),init_keyboard(),init_locator(),init_mouse(),init_snapshot(),init_video(),init_wait(),DEFAULT_WAIT_TIMEOUT_MS=30000,NETWORK_IDLE_MS=500,MAX_SCREENSHOT_TEXTURE_SIZE=16384,FILECHOOSER_OOPIF_FALLBACK_MS=2000,OmOPage=class{cdp;frameManager;targetId;modifierState;mouse;keyboard;events=new Emittery;browser;#e=new Map;#t=null;#n;#r=``;#i=null;#a=[];#o=null;#s=false;#c=0;constructor(xn,jn,Vn,qn,Jn){this.cdp=xn,this.frameManager=jn,this.targetId=Vn,this.modifierState=new ModifierState,this.mouse=new OmOMouse(this,this.modifierState),this.keyboard=new OmOKeyboard(this,this.modifierState),this.browser=Jn,this.#n=qn,this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??``,this.#l()}#l(){let xn=new Set,jn=(xn)=>{replPrint(`[error] page event listener threw: ${xn instanceof Error?xn.message:xn}`)};this.#u(`Page.frameNavigated`,(xn)=>{xn.frame.parentId||(this.#r=xn.frame.url)}),this.#u(`Page.loadEventFired`,()=>{this.events.emit(`load`).catch(jn)}),this.#u(`Page.domContentEventFired`,()=>{this.events.emit(`domcontentloaded`).catch(jn)}),this.#u(`Page.javascriptDialogOpening`,(xn)=>{this.events.emit(`dialog`,{type:xn.type,message:xn.message,defaultPrompt:xn.defaultPrompt??``,url:xn.url}).catch(jn)}),this.#a.push(this.cdp.on(`Page.fileChooserOpened`,(xn,Vn)=>{!Vn.sessionId||!xn.backendNodeId||this.events.emit(`filechooser`,new FileChooser(this,xn.frameId,xn.backendNodeId,xn.mode===`selectMultiple`)).catch(jn)})),this.#u(`Page.frameAttached`,(xn)=>{this.events.emit(`frameattached`,{frameId:xn.frameId,parentFrameId:xn.parentFrameId}).catch(jn)}),this.#u(`Page.frameDetached`,(xn)=>{this.events.emit(`framedetached`,{frameId:xn.frameId}).catch(jn)}),this.#u(`Page.frameNavigated`,(xn)=>{this.events.emit(`framenavigated`,{frameId:xn.frame.id,url:xn.frame.url,name:xn.frame.name??``}).catch(jn)});let Vn=(Vn)=>{xn.has(Vn.guid)||this.frameManager.getFrame(Vn.frameId)&&(xn.add(Vn.guid),this.events.emit(`download`,new OmODownload(this,{guid:Vn.guid,startedAfterMs:Date.now(),suggestedFilename:Vn.suggestedFilename,url:Vn.url})).catch(jn))};this.#a.push(this.cdp.on(`Browser.downloadWillBegin`,(xn)=>Vn(xn))),this.#u(`Page.downloadWillBegin`,(xn)=>{Vn(xn)}),this.#a.push(this.cdp.on(`Page.windowOpen`,(xn,Vn)=>{!Vn.sessionId||!this.frameManager.hasSession(Vn.sessionId)||this.events.emit(`popup`,{url:xn.url,windowName:xn.windowName}).catch(jn)})),this.#u(`Inspector.targetCrashed`,()=>{this.events.emit(`crash`).catch(jn)}),this.frameManager.onSessionInitialized=(xn)=>{this.#c>0&&this.#p(true,[xn])}}#u(xn,jn){this.#a.push(this.cdp.on(xn,(xn,Vn)=>{Vn.sessionId===this.#n&&jn(xn)}))}on(xn,jn){let Vn=this.#e.get(xn)??new WeakMap,qn=this.events.on(xn,({data:xn})=>jn(xn));return Vn.set(jn,qn),this.#e.set(xn,Vn),xn===`filechooser`&&this.#m(),()=>{qn(),Vn.delete(jn),xn===`filechooser`&&this.#h()}}off(xn,jn){let Vn=this.#e.get(xn),qn=Vn?.get(jn);qn?.(),Vn?.delete(jn),qn&&xn===`filechooser`&&this.#h()}async waitForEvent(xn,jn={}){let Vn=jn.timeout??DEFAULT_WAIT_TIMEOUT_MS;if(xn===`download`){let qn=Date.now();return await new Promise((Jn,Yn)=>{let Zn=false,Qn=()=>{ri(),clearTimeout(ni)},ei=(xn)=>{Zn||(Zn=true,Qn(),xn())},ti=(xn)=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>Jn(xn))}catch(xn){ei(()=>Yn(xn instanceof Error?xn:Error(String(xn))))}})()},ni=setTimeout(()=>{ei(()=>Yn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn),ri=this.on(`download`,ti);this.cdp.send(`OmO.waitForDownload`,{startedAfterMs:qn,timeoutMs:Vn},undefined,{extensionBridge:this.browser.extensionBridgeRoute}).then((xn)=>{ti(new OmODownload(this,{guid:String(xn.downloadId),sourcePath:xn.absolutePath,startedAfterMs:qn,suggestedFilename:path.basename(xn.absolutePath),url:this.url()}))}).catch(()=>{})})}return await new Promise((qn,Jn)=>{let Yn=false,Zn=null,Qn=()=>{ni(),clearTimeout(ti),Zn&&clearTimeout(Zn)},ei=(xn)=>{Yn||(Yn=true,Qn(),xn())},ti=setTimeout(()=>{ei(()=>Jn(Error(`Timed out waiting for page event "${String(xn)}"`)))},Vn);xn===`filechooser`&&Vn>FILECHOOSER_OOPIF_FALLBACK_MS&&(Zn=setTimeout(()=>{Yn||this.#g().then((xn)=>{xn&&!Yn&&ei(()=>qn(xn))})},FILECHOOSER_OOPIF_FALLBACK_MS));let ni=this.on(xn,(xn)=>{(async()=>{try{if(jn.predicate&&!await jn.predicate(xn))return;ei(()=>qn(xn))}catch(xn){ei(()=>Jn(xn instanceof Error?xn:Error(String(xn))))}})()})})}#d(){for(let xn of this.#a)xn();this.#a=[]}async dispose(){this.#s||(this.#s=true,await this.#o?.stop().catch(()=>{}),this.#d(),this.#c=0,await this.events.emit(`close`),this.events.clearListeners(),this.#e.clear())}reconnect(xn){this.#n=xn,this.#s=false,this.#d(),this.#l(),this.#r=this.frameManager.getFrame(this.frameManager.mainFrameId)?.url??this.#r,this.#c>0&&this.#p(true)}#f(){return[...new Set([this.#n,...[...this.frameManager.frames.values()].map((xn)=>xn.sessionId)])]}async prepareForPotentialFileChooser(){this.#c!==0&&await this.#p(true)}#p(xn,jn=this.#f()){return withoutReplContext(async()=>{await Promise.allSettled(jn.map((jn)=>this.cdp.send(`Page.setInterceptFileChooserDialog`,{enabled:xn},jn)))})}#m(){this.#c+=1,this.#c===1&&this.#p(true)}#h(){this.#c!==0&&(--this.#c,this.#c===0&&this.#p(false))}async#g(){for(let xn of this.frameManager.frames.values())if(xn.sessionId!==this.#n)try{let{root:jn}=await this.cdp.send(`DOM.getDocument`,{depth:0},xn.sessionId),{nodeIds:Vn}=await this.cdp.send(`DOM.querySelectorAll`,{nodeId:jn.nodeId,selector:`input[type=file]`},xn.sessionId);if(Vn.length===0)continue;let qn=Vn[Vn.length-1],{node:Jn}=await this.cdp.send(`DOM.describeNode`,{nodeId:qn},xn.sessionId),Yn=(Jn.attributes??[]).includes(`multiple`);return new FileChooser(this,xn.frameId,Jn.backendNodeId,Yn)}catch{}return null}async resolveSessionId(xn){if(xn&&this.frameManager.hasSession(xn))return xn;let jn=await this.browser.resolvePageSession(this.targetId,this.#n);return jn!==this.#n&&(this.#n=jn),jn}async goto(xn,jn={}){let Vn=jn.waitUntil??`interactive`,qn=await this.resolveSessionId(this.#n),Jn=()=>{},Yn=Vn===`commit`?null:Vn===`interactive`||Vn===`stable`?waitForNavigationReadiness(this,Vn,DEFAULT_WAIT_TIMEOUT_MS).then(()=>{}):Vn===`networkidle`?this.#S(DEFAULT_WAIT_TIMEOUT_MS):new Promise((xn,jn)=>{let Yn=false,Zn,Qn=()=>{},ei=(xn)=>{Yn||(Yn=true,clearTimeout(Zn),Qn(),xn())};Zn=setTimeout(()=>{ei(()=>jn(Error(`Timed out waiting for "${Vn}" after goto`)))},DEFAULT_WAIT_TIMEOUT_MS);let ti=Vn===`load`?`Page.loadEventFired`:`Page.domContentEventFired`;Qn=this.cdp.on(ti,(jn,Vn)=>{Vn.sessionId===qn&&ei(xn)}),Jn=()=>ei(xn)}),Zn=await this.cdp.send(`Page.navigate`,{url:xn},qn);if(Zn.errorText)throw Error(Zn.errorText);if(this.#r=xn,Vn===`domcontentloaded`&&Yn){if(!Zn.loaderId){Jn(),await this.#v(`Timed out waiting for "${Vn}" after goto`);return}try{await Yn}catch(xn){if(await this.#_())return;throw xn}return}Yn&&await Yn}async goBack(){let xn=await this._sendToTarget(`Page.getNavigationHistory`),jn=xn.currentIndex-1;if(jn<0)return;let Vn=xn.entries[jn];if(!Vn)return;let qn=this.#C();await this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:Vn.id}),await qn}async goForward(){let xn=await this._sendToTarget(`Page.getNavigationHistory`),jn=xn.currentIndex+1;if(jn>=xn.entries.length)return;let Vn=xn.entries[jn];if(!Vn)return;let qn=this.#C();await this._sendToTarget(`Page.navigateToHistoryEntry`,{entryId:Vn.id}),await qn}async reload(){let xn=this.#C();await this._sendToTarget(`Page.reload`),await xn}async waitForLoadState(xn=`interactive`,jn=DEFAULT_WAIT_TIMEOUT_MS){if(xn===`interactive`||xn===`stable`){await waitForNavigationReadiness(this,xn,jn);return}if(xn===`networkidle`||xn===`load`){replPrint(`[system] this is redundant wait; openTab() already waits for the page to become usable. Falling back to 'stable' with 5s timeout.`),await waitForNavigationReadiness(this,`stable`,5000).catch(()=>{});return}if(await this.#_())return;let Vn=`Page.domContentEventFired`,qn=await this.resolveSessionId(this.#n);await new Promise((jn,Vn)=>{let Jn=setTimeout(()=>{Yn(),Vn(Error(`Timed out waiting for load state "${xn}"`))},DEFAULT_WAIT_TIMEOUT_MS),Yn=this.cdp.on(`Page.domContentEventFired`,(xn,Vn)=>{Vn.sessionId===qn&&(clearTimeout(Jn),Yn(),jn())})})}async#_(){return await this.evaluate(`document.readyState`).catch(()=>`loading`)!==`loading`}async#v(xn,jn=DEFAULT_WAIT_TIMEOUT_MS){let Vn=Date.now();for(;Date.now()-Vn<jn;){if(await this.#_())return;await sleep$12(50)}throw Error(xn)}async waitForURL(xn,jn={}){let Vn=jn.timeout??DEFAULT_WAIT_TIMEOUT_MS,qn=Date.now();for(;Date.now()-qn<Vn;){let jn=this.url();if(typeof xn==`string`?jn===xn:xn.test(jn))return;await sleep$12(100)}throw Error(`Timed out waiting for URL match: ${String(xn)}`)}async waitForSelector(xn,jn={}){let Vn=jn.state??`visible`,qn=jn.timeout??3000,Jn=[0,20,50,100,100,500],Yn=Date.now(),Zn=0;for(;;){if(Date.now()-Yn>=qn)throw Error(`waitForSelector: timed out after ${qn}ms waiting for "${xn}" to be ${Vn}`);let jn=await this.evaluate((xn)=>{let jn=document.querySelector(xn);if(!jn)return{attached:false,visible:false};let Vn=jn.getBoundingClientRect(),qn=window.getComputedStyle(jn);return{attached:true,visible:qn.visibility!==`hidden`&&qn.display!==`none`&&parseFloat(qn.opacity)!==0&&Vn.width>0&&Vn.height>0}},xn);if(Vn===`attached`?jn.attached:Vn===`detached`?!jn.attached:Vn===`visible`?jn.visible:!jn.visible)return;let Qn=Jn[Math.min(Zn++,Jn.length-1)];await sleep$12(Qn)}}locator(xn,jn={}){return new Locator(this,xn).filter(jn)}async click(xn,jn){await this.locator(xn).click(jn)}async fill(xn,jn){await this.locator(xn).fill(jn)}async $(xn){return replPrint(`warn`,`page.$() is deprecated in OmOWright — use page.locator(selector).first() instead`),this.locator(xn).first()}async $$(xn){return replPrint(`warn`,`page.$$() is deprecated in OmOWright — use page.locator(selector).all() instead`),await this.locator(xn).all()}async $$eval(xn,jn,Vn){return await this.locator(xn).evaluateAll(jn,Vn)}getByRole(xn,jn={}){return new Locator(this,Locator.createRoleSelector(xn,jn))}getByLabel(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`internal:label=/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`internal:label:exact:${Vn}`:`internal:label:${Vn}`)}getByText(xn,jn={}){if(xn instanceof RegExp)return new Locator(this,`text:/${xn.source}/${xn.flags}`);let Vn=JSON.stringify(xn);return new Locator(this,jn.exact?`text:exact:${Vn}`:`text:${Vn}`)}frameLocator(xn){return new FrameLocator(this,this.mainFrame(),xn)}async evaluate(xn,jn,Vn){let{actualArg:qn,evaluateOptions:Jn}=resolveEvaluateCall(xn,jn,Vn);if(typeof xn==`string`&&qn===undefined){let{result:jn,exceptionDetails:Vn}=await this._sendToTarget(`Runtime.evaluate`,{expression:xn,returnByValue:true,awaitPromise:true,userGesture:Jn.userGesture});if(Vn)throw Error(formatRuntimeException(Vn,`Evaluation failed`));return jn.value}let Yn=typeof xn==`function`?xn.toString():xn,Zn=await this.#x();try{let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.callFunctionOn`,{objectId:Zn,functionDeclaration:`function(arg) { var __name = (t) => t; return (${Yn})(arg); }`,arguments:[{value:qn}],returnByValue:true,awaitPromise:true,userGesture:Jn.userGesture});if(jn)throw Error(formatRuntimeException(jn,`Evaluation failed`));return xn.value}finally{await this._sendToTarget(`Runtime.releaseObject`,{objectId:Zn}).catch(()=>{})}}async evaluateInFrame(xn,jn,Vn,qn){let Jn=this.frameManager.getFrame(xn);if(!Jn)throw Error(`Frame is not available: ${xn}`);let{actualArg:Yn,evaluateOptions:Zn}=resolveEvaluateCall(jn,Vn,qn),Qn=await this.resolveSessionId(Jn.sessionId);if(typeof jn==`string`&&Yn===undefined){let Vn=await this.frameManager.ensureInjected(xn);if(!Vn)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:qn,exceptionDetails:Jn}=await this.cdp.send(`Runtime.evaluate`,{expression:jn,contextId:Vn,returnByValue:true,awaitPromise:true,userGesture:Zn.userGesture},Qn);if(Jn)throw Error(formatRuntimeException(Jn,`Evaluation failed`));return qn.value}let ei=typeof jn==`function`?jn.toString():jn,ti=await this.frameManager.ensureInjected(xn);if(!ti)throw Error(`Frame isolated world is not ready: ${xn}`);let{result:ni,exceptionDetails:ri}=await this.cdp.send(`Runtime.callFunctionOn`,{functionDeclaration:`function(arg) { var __name = (t) => t; return (${ei})(arg); }`,arguments:[{value:Yn}],executionContextId:ti,returnByValue:true,awaitPromise:true,userGesture:Zn.userGesture},Qn);if(ri)throw Error(formatRuntimeException(ri,`Evaluation failed`));return ni.value}async grantNotificationPermission(){await sendCommandToExtension({method:`OmO.grantNotificationPermission`,params:{targetId:this.targetId}},this.browser.extensionBridgeRoute);let xn=new URL(this.#r).origin,jn=this.browser.daemonSession;upsertNotificationGrant({accountId:jn.accountId,origin:xn,grantedBySessionId:jn.id})}url({truncate:xn=false}={}){return xn?truncateUrlForLLM(this.#r):this.#r}async title(){return await this.evaluate(`document.title`).catch(()=>``)}async content(){return await this.evaluate(`document.documentElement.outerHTML`)}async screenshot(xn={}){let jn=normalizeScreenshotTimeout(xn.timeout),Vn=jn&&jn>0?Date.now()+jn:undefined,qn;if(xn.clip)qn={x:xn.clip.x,y:xn.clip.y,width:xn.clip.width,height:xn.clip.height,scale:1};else if(xn.fullPage){let xn=await this._sendToTarget(`Page.getLayoutMetrics`),jn=xn.cssContentSize??xn.contentSize;qn={x:0,y:0,width:jn.width,height:jn.height,scale:1}}qn&&=clampScreenshotClipToTextureLimit(qn,await this.#y());let Jn={format:xn.type??`png`,captureBeyondViewport:!!xn.fullPage,quality:xn.quality,...qn?{clip:qn}:{}},Yn;try{({data:Yn}=await this.#b(Jn,jn,screenshotCaptureLabel(xn)))}catch(jn){if(!xn.fullPage||xn.clip||!isCaptureScreenshotTimeout(jn))throw jn;let qn=Vn?Math.max(0,Vn-Date.now()):undefined;if(qn===0)throw jn;let Jn={format:xn.type??`png`,captureBeyondViewport:false,quality:xn.quality};try{({data:Yn}=await this.#b(Jn,qn,`viewport fallback screenshot`)),replPrint(`[system] full-page screenshot failed; returned viewport fallback. ${formatScreenshotError(jn)}`)}catch(xn){throw Error(`${formatScreenshotError(jn)}
1468
+ Viewport fallback also failed: ${formatScreenshotError(xn)}`)}}let Zn=Buffer.from(Yn,`base64`);if(xn.path)if(xn.path.startsWith(`/tmp`)){let jn=this.browser.resolvePath(`tmp`),Vn=path.join(jn,path.basename(xn.path));await mkdir(path.dirname(Vn),{recursive:true}),await writeFile(Vn,Zn),replPrint(`[WARN] Use ${jn} instead of /tmp. Saved it to ${Vn}`)}else{let jn=this.browser.resolvePath(xn.path);await mkdir(path.dirname(jn),{recursive:true}),await writeFile(jn,Zn)}return Zn}async#y(){return await this.evaluate(`window.devicePixelRatio`).catch(()=>1)}async#b(xn,jn,Vn){try{return await this._sendToTarget(`Page.captureScreenshot`,xn,{timeoutMs:jn})}catch(xn){throw rewriteCaptureScreenshotError(xn,jn,Vn)}}async snapshot(xn={}){return await takeSnapshot(this.cdp,this.frameManager,xn)}frames(){return this.frameManager.collectDescendantFrames(this.frameManager.mainFrameId).map(({frameId:xn})=>new OmOFrame(this,xn))}mainFrame(){let xn=this.frameManager.getFrame(this.frameManager.mainFrameId);if(!xn)throw Error(`Main frame is not available`);return new OmOFrame(this,xn.frameId)}async bringToFront(){this.browser.page=this,replPrint(`page is now [${await this.title().catch(()=>``)}](${this.url()})`)}async openPopupUrl(xn){await this.browser.openPopupTab(xn,this.targetId)}get console(){return this.#t??=new PageConsole(this)}video(){return this.#w()}viewportSize(){return this.#i?{...this.#i}:null}async refreshViewportSize(){let xn=await this.evaluate(()=>({width:Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0),height:Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0)}));if(xn.width<=0||xn.height<=0)throw Error(`Measured viewport size is invalid: ${JSON.stringify(xn)}`);return this.#i=xn,xn}setCachedViewportSize(xn){this.#i=xn?{...xn}:null}async pdf(xn={}){let jn=xn.path?await this.browser.ensurePath(xn.path,`write`,`page.pdf`):undefined,Vn={...xn,height:formatPdfLength(xn.height),margin:xn.margin?{bottom:formatPdfLength(xn.margin.bottom),left:formatPdfLength(xn.margin.left),right:formatPdfLength(xn.margin.right),top:formatPdfLength(xn.margin.top)}:undefined,printBackground:xn.printBackground??true,transferMode:`ReturnAsBase64`,width:formatPdfLength(xn.width)},{data:qn}=await this._sendToTarget(`Page.printToPDF`,Vn),Jn=Buffer.from(qn,`base64`);return jn&&(await mkdir(path.dirname(jn),{recursive:true}).catch(()=>{}),await writeFile(jn,Jn)),Jn}async close(xn={}){if(await this.#w().stop().catch(()=>{}),xn.runBeforeUnload){let jn=await this.resolveSessionId(this.#n);await this.cdp.send(`Page.close`,undefined,jn).catch(async()=>{await this.browser.closeTab(this,xn)});return}await this.browser.closeTab(this,xn)}async#x(){let{result:xn,exceptionDetails:jn}=await this._sendToTarget(`Runtime.evaluate`,{expression:`globalThis`,serializationOptions:{serialization:`idOnly`}});if(jn)throw Error(formatRuntimeException(jn,`Failed to resolve main world`));if(!xn.objectId)throw Error(`Main world object is not available`);return xn.objectId}async#S(xn){await this._sendToTarget(`Network.enable`).catch(()=>{});let jn=await this.resolveSessionId(this.#n);await new Promise((Vn,qn)=>{let Jn=new Set,Yn=null,Zn=null,Qn=()=>{ti(),ri(),ii(),Yn&&=(clearTimeout(Yn),null),Zn&&=(clearTimeout(Zn),null)},ei=()=>{Yn&&clearTimeout(Yn),Jn.size===0&&(Yn=setTimeout(()=>{Qn(),Vn()},NETWORK_IDLE_MS))},ti=this.cdp.on(`Network.requestWillBeSent`,(xn,Vn)=>{Vn.sessionId===jn&&(xn.request.url.startsWith(`data:`)||Jn.add(xn.requestId))}),ni=(xn)=>{Jn.delete(xn),ei()},ri=this.cdp.on(`Network.loadingFinished`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)}),ii=this.cdp.on(`Network.loadingFailed`,(xn,Vn)=>{Vn.sessionId===jn&&ni(xn.requestId)});Zn=setTimeout(()=>{Qn(),qn(Error(`Timed out waiting for load state "networkidle"`))},xn),ei()})}async#C(){let xn=await this.resolveSessionId(this.#n);await new Promise((jn,Vn)=>{let qn=setTimeout(()=>{Jn(),Vn(Error(`Timed out waiting for navigation`))},DEFAULT_WAIT_TIMEOUT_MS),Jn=this.cdp.on(`Page.frameNavigated`,(Vn,Yn)=>{Yn.sessionId===xn&&(Vn.frame.parentId||(clearTimeout(qn),Jn(),jn()))})})}async _sendToTarget(xn,jn,Vn={}){if(this.#s)throw Error(`Page ${this.targetId} is disposed`);let{preferredSessionId:qn,...Jn}=Vn;if(qn!==undefined){if(!this.frameManager.hasSession(qn))throw Error(`Frame is stale or detached: CDP session ${qn} is unavailable`);return await this.cdp.send(xn,jn,qn,Jn)}let Yn=await this.resolveSessionId(this.#n);return await this.cdp.send(xn,jn,Yn,Jn)}#w(){return this.#o??=new OmOVideo(this),this.#o}}});init_client$6();init_session_manager();init_frame_manager();init_page();import{isDeepStrictEqual}from"node:util";var shared=new Map;function withinTimeout(pending,timeoutMs,message){let timer;return Promise.race([pending,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message)),timeoutMs)})]).finally(()=>clearTimeout(timer))}function release(key,entry){entry.refs-=1;if(entry.refs>0)return Promise.resolve();if(shared.get(key)===entry)shared.delete(key);return entry.ready.then((connection)=>connection.close(),()=>{})}function bindTo(target,value){return typeof value==="function"?value.bind(target):value}class SharedConnectionError extends Error{constructor(){super("this browser connection is shared; pass dialogPolicy to connect()/connectNamed() so this holder gets its own connection");this.name="SharedConnectionError";this.code="shared_connection"}}var RESERVED=new Set(["cdp","close","setDialogPolicy"]);function refuse(what){return(_target,property)=>{throw new TypeError(`cannot change ${String(property)} on ${what} through a handle: every holder of this connection uses it`)}}function lease(key,entry,connection){let closed;const overlay=Object.create(null);const subscriptions=[];const ensureOpen=(property)=>{if(closed&&typeof property==="string"&&property!=="then"){throw new Error("this browser connection handle was closed")}};const close=()=>{if(!closed){for(const unsubscribe of subscriptions.splice(0))unsubscribe();closed=release(key,entry)}return closed};const setDialogPolicy=(policy)=>{ensureOpen("setDialogPolicy");if(entry.refs>1)throw new SharedConnectionError;if(shared.get(key)===entry)shared.delete(key);return connection.setDialogPolicy(policy)};const tracked=(subscribe)=>(...args)=>{const unsubscribe=subscribe(...args);subscriptions.push(unsubscribe);return unsubscribe};const readOnly=(what,get)=>({get,set:refuse(what),defineProperty:refuse(what),deleteProperty:refuse(what)});const client=connection.cdp;const transportSubscriptions=[];const transportEvents=new Proxy(client.transportEvents,readOnly("the shared transport events",(target,property)=>{ensureOpen(property);if(property==="on"){return(...args)=>{const unsubscribe=tracked(target.on.bind(target))(...args);transportSubscriptions.push(unsubscribe);return unsubscribe}}if(property==="clearListeners"){return()=>{for(const unsubscribe of transportSubscriptions.splice(0))unsubscribe()}}if(property==="emit"){return()=>{throw new TypeError("cannot emit transport events through a handle: every holder of this connection hears them")}}return bindTo(target,Reflect.get(target,property,target))}));const clientView=new Proxy(client,readOnly("the shared CDP client",(target,property)=>{ensureOpen(property);if(property==="setDialogPolicy")return setDialogPolicy;if(property==="close")return close;if(property==="on")return tracked(target.on.bind(target));if(property==="transportEvents")return transportEvents;return bindTo(target,Reflect.get(target,property,target))}));return new Proxy(connection,{get(target,property){if(property==="close")return close;ensureOpen(property);if(property==="setDialogPolicy")return setDialogPolicy;if(property==="cdp")return clientView;if(Object.hasOwn(overlay,property))return overlay[property];return bindTo(target,Reflect.get(target,property,target))},set(target,property,value){ensureOpen(property);if(RESERVED.has(property))return refuse("a handle")(target,property);return Reflect.set(overlay,property,value)},defineProperty(target,property,descriptor){ensureOpen(property);if(RESERVED.has(property))return refuse("a handle")(target,property);if(descriptor.configurable!==true)return false;return Reflect.defineProperty(overlay,property,descriptor)},deleteProperty(target,property){ensureOpen(property);if(Object.hasOwn(overlay,property))return Reflect.deleteProperty(overlay,property);return refuse("the shared connection")(target,property)},has(target,property){return Object.hasOwn(overlay,property)||Reflect.has(target,property)},ownKeys(target){return[...new Set([...Reflect.ownKeys(target),...Reflect.ownKeys(overlay)])]},getOwnPropertyDescriptor(target,property){return Object.hasOwn(overlay,property)?Reflect.getOwnPropertyDescriptor(overlay,property):Reflect.getOwnPropertyDescriptor(target,property)}})}function isPlainData(value,path=new Set){if(typeof value==="function"||value===null||typeof value!=="object")return true;if(path.has(value))return false;const prototype=Object.getPrototypeOf(value);const isArray=Array.isArray(value);if(isArray?prototype!==Array.prototype:prototype!==Object.prototype&&prototype!==null){return false}path.add(value);try{for(const key of Reflect.ownKeys(value)){if(isArray&&key==="length")continue;if(typeof key==="symbol")return false;const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor.enumerable||!("value"in descriptor))return false;if(!isPlainData(descriptor.value,path))return false}return true}finally{path.delete(value)}}function canShareConnection(options){return options?.client?.authorizer===undefined&&isPlainData(options)}async function acquireSharedConnection(webSocketDebuggerUrl,options,{open,timeoutMs}){if(!canShareConnection(options))return open(options);let entry=shared.get(webSocketDebuggerUrl);if(entry&&!isDeepStrictEqual(entry.options,options))return open(options);if(!entry){entry={options,refs:0,ready:open(options)};shared.set(webSocketDebuggerUrl,entry)}entry.refs+=1;try{const connection=await entry.ready;const reconnected=connection.cdp.ensureConnected();await(timeoutMs===undefined?reconnected:withinTimeout(reconnected,timeoutMs,`timed out after ${timeoutMs}ms reconnecting the CDP session on ${webSocketDebuggerUrl}`));return lease(webSocketDebuggerUrl,entry,connection)}catch(error){if(shared.get(webSocketDebuggerUrl)===entry)shared.delete(webSocketDebuggerUrl);await release(webSocketDebuggerUrl,entry);throw error}}class TabRepository{#client;constructor(client){this.#client=client}async listTargets(){return this.#client.discoverTargets()}}class BrowserConnection{#client;#sessions;#pages=new Map;#storageRoot;constructor(client,options={}){this.#client=client;this.#sessions=new SessionManager(client);this.tabs=new TabRepository(client);this.#storageRoot=path2.resolve(options.storageRoot??process.cwd())}async initialize(){await this.#client.ensureConnected();return this}get cdp(){return this.#client}setDialogPolicy(policy){if(typeof this.#client.setDialogPolicy!=="function"){throw new Error("dialog policy is not supported by this transport")}this.#client.setDialogPolicy(policy)}async listTargets(){return this.tabs.listTargets()}async newTab(url="about:blank"){await Promise.resolve().then(() => init_agent_tabs());return(await createAgentTabs(this).create(url)).page}async attachPage(targetId){if(this.#pages.has(targetId))return this.#pages.get(targetId).page;const sessionId=await this.#sessions.resolvePageSession(targetId);const frames=new FrameManager(this.#client,targetId,sessionId);await frames.initialize();const entry={frames,page:null};const host=this.#createPageHost(targetId,entry);const page=new OmOPage(this.#client,frames,targetId,sessionId,host);entry.page=page;this.#pages.set(targetId,entry);return page}#createPageHost(targetId,entry){return{daemonSession:{accountId:0,id:"standalone"},extensionBridgeRoute:{},page:null,resolvePageSession:(id,preferred)=>this.#sessions.resolvePageSession(id,preferred),resolvePath:(value)=>path2.resolve(this.#storageRoot,value),ensurePath:async(value)=>{const resolved=path2.resolve(this.#storageRoot,value);await mkdir2(path2.dirname(resolved),{recursive:true});return resolved},registerReadableDownload:(value)=>value,isReadableDownload:()=>false,openPopupTab:async()=>{throw Error("Popup tab control requires the extension bridge")},closeTab:async(_page,options={})=>{if(options.runBeforeUnload){await this.#client.send("Page.close",undefined,await this.#sessions.resolvePageSession(targetId))}else{await this.#client.send("Target.closeTarget",{targetId})}await entry.page?.dispose();await entry.frames.dispose();this.#pages.delete(targetId)}}}async close(){for(const[targetId,entry]of[...this.#pages]){await entry.page.dispose().catch(()=>{});await entry.frames.dispose().catch(()=>{});this.#pages.delete(targetId)}await this.#sessions.dispose();await this.#client.close()}}async function browserKey(client,cdpUrl){if(/^wss?:\/\//.test(cdpUrl))return cdpUrl;return(await client.discoverVersion()).webSocketDebuggerUrl}function createClient(cdpHttpUrl,options){if(typeof cdpHttpUrl!=="string"||cdpHttpUrl.length===0){throw new TypeError("connect(cdpHttpUrl) requires a Chromium CDP HTTP URL")}return new CdpClient({cdpUrl:cdpHttpUrl,...options.client,dialogPolicy:options.dialogPolicy??options.client?.dialogPolicy})}async function openConnection(cdpHttpUrl,options={}){return new BrowserConnection(createClient(cdpHttpUrl,options),options).initialize()}async function connect(cdpHttpUrl,options={}){const client=createClient(cdpHttpUrl,options);if(!canShareConnection(options))return new BrowserConnection(client,options).initialize();const key=await browserKey(client,cdpHttpUrl);return acquireSharedConnection(key,options,{open:()=>openConnection(key,options)})}var OMOWRIGHT_PAGE_CDP_METHODS=Object.freeze(["Browser.getVersion","DOM.describeNode","DOM.enable","DOM.getBoxModel","DOM.getContentQuads","DOM.getDocument","DOM.querySelectorAll","DOM.resolveNode","DOM.scrollIntoViewIfNeeded","DOM.setFileInputFiles","Emulation.setDeviceMetricsOverride","Emulation.setFocusEmulationEnabled","Input.dispatchKeyEvent","Input.dispatchMouseEvent","Input.insertText","Inspector.enable","Network.enable","Page.addScriptToEvaluateOnNewDocument","Page.captureScreenshot","Page.close","Page.createIsolatedWorld","Page.enable","Page.getFrameTree","Page.getLayoutMetrics","Page.getNavigationHistory","Page.handleJavaScriptDialog","Page.navigate","Page.navigateToHistoryEntry","Page.printToPDF","Page.reload","Page.removeScriptToEvaluateOnNewDocument","Page.screencastFrameAck","Page.setInterceptFileChooserDialog","Page.setWebLifecycleState","Page.startScreencast","Page.stopScreencast","Runtime.callFunctionOn","Runtime.evaluate","Runtime.releaseObject","Target.activateTarget","Target.attachToTarget","Target.closeTarget","Target.createTarget","Target.detachFromTarget","Target.getTargetInfo","Target.getTargets","Target.setAutoAttach","Target.setDiscoverTargets"]);import{spawn}from"node:child_process";init_internal_capability();class Emittery2{#listeners=new Map;on(event,fn){const list=this.#listeners.get(event)??[];list.push(fn);this.#listeners.set(event,list);return()=>{const cur=this.#listeners.get(event)??[];this.#listeners.set(event,cur.filter((f)=>f!==fn))}}async emit(event,data){for(const fn of this.#listeners.get(event)??[])await fn(data)}}var DEFAULT_COMMAND_TIMEOUT_MS2=30000;var DEFAULT_READINESS_TIMEOUT_MS=1e4;var GRACEFUL_CLOSE_TIMEOUT_MS=2000;var STDIO_TAIL_LIMIT=16384;class PipeCdpClient{#child;#writeStream;#readStream;#buffer=Buffer.alloc(0);#seq=1;#pending=new Map;#events=new Emittery2;#connected=false;#commandTimeoutMs;#readinessTimeoutMs;#browserPath;#browserArgs;#spawnOptions;#stdioTail="";#dialogPolicy;transportEvents=new Emittery2;logId;constructor({browserPath,browserArgs=[],spawnOptions={},commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy}){if(!browserPath)throw new TypeError("PipeCdpClient requires browserPath");this.#browserPath=browserPath;this.#browserArgs=browserArgs;this.#spawnOptions=spawnOptions;this.#commandTimeoutMs=commandTimeoutMs??DEFAULT_COMMAND_TIMEOUT_MS2;this.#readinessTimeoutMs=readinessTimeoutMs??DEFAULT_READINESS_TIMEOUT_MS;this.logId=logId??`cdp-pipe-${Date.now()}`;this.#dialogPolicy=normalizeDialogPolicy(dialogPolicy)}get isConnected(){return this.#connected}get isHeadless(){return this.#browserArgs.some((arg)=>/^--headless(?:=|$)/.test(arg))}get childProcess(){return this.#child}get dialogPolicy(){return this.#dialogPolicy}setDialogPolicy(policy){this.#dialogPolicy=normalizeDialogPolicy(policy)}async ensureConnected(){if(this.#connected)return;const stdio=["ignore","pipe","pipe","pipe","pipe"];this.#child=spawn(this.#browserPath,[...this.#browserArgs,"--remote-debugging-pipe"],{...this.#spawnOptions,stdio});this.#stdioTail="";for(const stream of[this.#child.stdout,this.#child.stderr]){if(!stream)continue;stream.setEncoding("utf8");stream.on("data",(chunk)=>{this.#stdioTail=(this.#stdioTail+chunk).slice(-STDIO_TAIL_LIMIT)});stream.on("error",()=>{})}this.#writeStream=this.#child.stdio[3];this.#readStream=this.#child.stdio[4];this.#readStream.on("data",(chunk)=>this.#onData(chunk));for(const stream of[this.#writeStream,this.#readStream]){stream.on("error",(error)=>this.#failAll(Error(`CDP pipe error: ${error.code??error.message}`)))}this.#child.on("exit",()=>{this.#connected=false;this.#failAll(Error("CDP pipe browser exited"));this.transportEvents.emit("disconnected").catch(()=>{})});this.#connected=true;await this.#awaitReady();await this.send("Target.setDiscoverTargets",{discover:true}).catch(()=>{});await this.transportEvents.emit("connected")}async#awaitReady(){const deadline=Date.now()+this.#readinessTimeoutMs;let lastError;while(Date.now()<deadline){try{await this.send("Browser.getVersion",undefined,undefined,{timeoutMs:1000});return}catch(error){lastError=error;await new Promise((resolve)=>setTimeout(resolve,100))}}const reason=lastError?String(lastError.message??lastError):"no response";const tail=this.#stdioTail.trim();throw Error(`Browser did not become ready over the CDP pipe (${reason})`+(tail?`
1482
1469
  Browser stdio tail:
1483
- ${tail}`:""))}async send(method,params,sessionId,opts={}){if(method==="Target.createTarget"&&opts.capability!==targetCreationCapability)throw Error("Target.createTarget is reserved for createAgentTabs");if(String(method).startsWith("OmO.")){throw Error(`Extension commands are unavailable over pipe transport: ${method}`)}await this.ensureConnected();const id=this.#seq++;const msg={id,method};if(params!==undefined)msg.params=params;if(sessionId)msg.sessionId=sessionId;const{promise,resolve,reject}=Promise.withResolvers();const timeoutMs=opts.timeoutMs??this.#commandTimeoutMs;const timeout=timeoutMs>0?setTimeout(()=>{this.#pending.delete(id);reject(Error(`CDP command timeout: ${method}`))},timeoutMs):undefined;this.#pending.set(id,{method,resolve,reject,timeout});this.#writeStream.write(JSON.stringify(msg)+"\x00");return promise}on(method,fn){return this.#events.on(method,({data})=>fn(data.payload,data.meta))}async discoverTargets(){const{targetInfos}=await this.send("Target.getTargets");return targetInfos.map((t)=>({id:t.targetId,type:t.type,url:t.url??"",title:t.title??"",description:t.description,faviconUrl:t.faviconUrl,parentId:t.openerId}))}async close(){const child=this.#child;this.#child=undefined;if(child&&child.exitCode===null){const exited=new Promise((resolve)=>child.once("exit",resolve));if(this.#connected){await Promise.race([this.send("Browser.close",undefined,undefined,{timeoutMs:GRACEFUL_CLOSE_TIMEOUT_MS}).catch(()=>{}),exited])}this.#connected=false;this.#failAll(Error("CDP pipe client closed"));if(child.exitCode===null){await Promise.race([exited,new Promise((resolve)=>setTimeout(resolve,GRACEFUL_CLOSE_TIMEOUT_MS))])}if(child.exitCode===null){try{child.kill("SIGKILL")}catch{}await exited}return}this.#connected=false;this.#failAll(Error("CDP pipe client closed"))}#onData(chunk){this.#buffer=Buffer.concat([this.#buffer,chunk]);let idx;while((idx=this.#buffer.indexOf(0))!==-1){const raw=this.#buffer.subarray(0,idx).toString("utf8");this.#buffer=this.#buffer.subarray(idx+1);if(raw.length===0)continue;let msg;try{msg=JSON.parse(raw)}catch{continue}this._handleTransportMessage(msg)}}_handleTransportMessage(msg){if(typeof msg.id==="number"){const entry=this.#pending.get(msg.id);if(!entry)return;this.#pending.delete(msg.id);if(entry.timeout)clearTimeout(entry.timeout);if(msg.error){const err=Error(msg.error.message??`CDP command failed: ${entry.method}`);err.code=msg.error.code;err.data=msg.error.data;entry.reject(err)}else{entry.resolve(msg.result)}return}if(typeof msg.method==="string"){const handled=msg.method==="Page.javascriptDialogOpening"&&msg.sessionId?this.#handleJavaScriptDialog(msg).catch(()=>{}):undefined;this.#events.emit(msg.method,{data:{payload:msg.params,meta:{sessionId:msg.sessionId}}}).catch(()=>{});return handled}}async#handleJavaScriptDialog(msg){const params=await resolveDialogAction(this.#dialogPolicy,msg.params);await this.send("Page.handleJavaScriptDialog",params,msg.sessionId)}#failAll(err){for(const entry of this.#pending.values()){if(entry.timeout)clearTimeout(entry.timeout);entry.reject(err)}this.#pending.clear()}}async function connectPipe({browserPath,browserArgs=[],spawnOptions,storageRoot,commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy}={}){const client=new PipeCdpClient({browserPath,browserArgs,spawnOptions,commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy});await client.ensureConnected();const connection=new BrowserConnection(client,{storageRoot});await connection.initialize();connection.browserProcess=client.childProcess;connection.newTab=async(url="about:blank")=>{await Promise.resolve().then(() => init_agent_tabs());return(await createAgentTabs(connection).create(url)).page};return connection}import{randomInt}from"node:crypto";import{chmod,mkdir as mkdir3,open as open2,readFile}from"node:fs/promises";import{globSync}from"node:fs";import os from"node:os";import path3 from"node:path";var MIN_FINGERPRINT_SEED=1e4;var MAX_FINGERPRINT_SEED=99999;var METADATA_FILE=".omowright-cloak.json";var DEFAULT_PROFILE_DIR=path3.join(os.homedir(),".local","share","omowright-cloak");function normalizeFingerprintSeed(value){const seed=typeof value==="string"&&value.trim()!==""?Number(value):value;if(!Number.isInteger(seed)||seed<MIN_FINGERPRINT_SEED||seed>MAX_FINGERPRINT_SEED){throw new RangeError(`fingerprint seed must be an integer from ${MIN_FINGERPRINT_SEED} to ${MAX_FINGERPRINT_SEED}`)}return seed}function platformFingerprint(){return process.platform==="darwin"?"macos":"windows"}function identityFlag(value){return/^(--user-data-dir|--fingerprint|--fingerprint-platform)(?:=|$)/.test(value)}function buildCloakBrowserArgs({profileDir,fingerprintSeed,extraArgs=[]}={}){const profile=path3.resolve(profileDir??DEFAULT_PROFILE_DIR);const seed=normalizeFingerprintSeed(fingerprintSeed);const conflicting=extraArgs.filter(identityFlag);if(conflicting.length>0){throw new Error(`extraArgs cannot override fixed profile identity: ${conflicting.join(", ")}`)}return["--no-first-run","--no-default-browser-check","--disable-session-crashed-bubble",`--user-data-dir=${profile}`,`--fingerprint=${seed}`,`--fingerprint-platform=${platformFingerprint()}`,...extraArgs]}async function readMetadata(metadataPath){try{const parsed=JSON.parse(await readFile(metadataPath,"utf8"));return normalizeFingerprintSeed(parsed.fingerprintSeed)}catch(error){if(error?.code==="ENOENT")return null;if(error instanceof SyntaxError){throw new Error(`invalid CloakBrowser profile metadata: ${metadataPath}`)}throw error}}async function writeMetadata(metadataPath,fingerprintSeed){const handle=await open2(metadataPath,"wx",384);try{await handle.writeFile(`${JSON.stringify({fingerprintSeed},null,2)}
1484
- `,"utf8")}finally{await handle.close()}await chmod(metadataPath,384)}async function resolveCloakProfile({profileDir=DEFAULT_PROFILE_DIR,fingerprintSeed,randomSeed=()=>randomInt(MIN_FINGERPRINT_SEED,MAX_FINGERPRINT_SEED+1)}={}){const resolvedProfile=path3.resolve(profileDir);const metadataPath=path3.join(resolvedProfile,METADATA_FILE);await mkdir3(resolvedProfile,{recursive:true,mode:448});await chmod(resolvedProfile,448);const requested=fingerprintSeed===undefined?null:normalizeFingerprintSeed(fingerprintSeed);let stored=await readMetadata(metadataPath);if(stored===null){const candidate=requested??normalizeFingerprintSeed(randomSeed());try{await writeMetadata(metadataPath,candidate);stored=candidate}catch(error){if(error?.code!=="EEXIST")throw error;stored=await readMetadata(metadataPath);if(stored===null){throw new Error(`CloakBrowser profile seed metadata disappeared: ${metadataPath}`)}}}if(requested!==null&&requested!==stored){throw new Error(`fingerprint seed mismatch: profile is fixed at ${stored}, requested ${requested}`)}await chmod(metadataPath,384);return{profileDir:resolvedProfile,metadataPath,fingerprintSeed:stored,browserArgs:buildCloakBrowserArgs({profileDir:resolvedProfile,fingerprintSeed:stored})}}function findCloakBrowserPath({browserRoot=path3.join(os.homedir(),".cloakbrowser")}={}){const candidates=globSync(path3.join(path3.resolve(browserRoot),"chromium-*","Chromium.app","Contents","MacOS","Chromium")).sort();const browserPath=candidates.at(-1);if(!browserPath){throw new Error(`CloakBrowser binary not found under ${path3.resolve(browserRoot)}; set CLOAKBROWSER_BIN`)}return browserPath}async function connectCloakProfile({browserPath=process.env.CLOAKBROWSER_BIN??findCloakBrowserPath(),profileDir=process.env.CLOAK_PROFILE_DIR??DEFAULT_PROFILE_DIR,fingerprintSeed=process.env.CLOAK_FINGERPRINT_SEED,browserArgs=[],storageRoot,...options}={}){const profile=await resolveCloakProfile({profileDir,fingerprintSeed});return connectPipe({browserPath,browserArgs:buildCloakBrowserArgs({profileDir:profile.profileDir,fingerprintSeed:profile.fingerprintSeed,extraArgs:browserArgs}),storageRoot:storageRoot??profile.profileDir,...options})}var SNAPSHOT_PARSE_ERROR="compactSnapshot expected a snapshot() result (JSON string or {tree, refs} object)";function compactSnapshot(snapshot){const obj=typeof snapshot==="string"?JSON.parse(snapshot):snapshot;if(!obj||typeof obj.tree!=="string")throw new TypeError(SNAPSHOT_PARSE_ERROR);return obj.tree}function snapshotTokens(snapshot){const text=typeof snapshot==="string"?snapshot:JSON.stringify(snapshot);return{bytes:Buffer.byteLength(text,"utf8"),estTokens:Math.ceil(Buffer.byteLength(text,"utf8")/4)}}var toolSchemas=[{name:"newTab",description:"Open a tab and return its page. Waits for interactivity.",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"]}},{name:"attachPage",description:"Attach to an existing tab by targetId from listTargets().",parameters:{type:"object",properties:{targetId:{type:"string"}},required:["targetId"]}},{name:"page.goto",description:"Navigate the page; resolves when the page looks interactive.",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"]}},{name:"page.snapshot",description:"PRIMARY page read. Returns a compact a11y tree; interactive elements carry [ref=eN] ids for page.locator. Options: maxDepth, maxChars, interactive, showHidden, selector, ref.",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"page.locator",description:"Resolve a ref id (e.g. 'e1') or CSS selector to a Locator: click, fill, press, hover, check, selectOption, dragTo, setInputFiles, textContent, isVisible, waitFor.",parameters:{type:"object",properties:{selectorOrRef:{type:"string"}},required:["selectorOrRef"]}},{name:"page.evaluate",description:"Run JS in the page and return the result.",parameters:{type:"object",properties:{expression:{type:"string"}},required:["expression"]}},{name:"page.screenshot",description:"Capture page image bytes (path, fullPage, clip, type, quality).",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"page.pdf",description:"Print the page to PDF bytes (path, format, margin, printBackground).",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"compactSnapshot",description:"Pass page.snapshot() output through this before reading: returns the raw tree without the refs map (refs resolve in-page; the map is ~54% of bytes on real pages).",parameters:{type:"object",properties:{snapshot:{}},required:["snapshot"]}},{name:"createCua",description:"Coordinate fallback for UI that refs cannot target: click/doubleClick/drag/move/scroll/type/keypress at viewport points, getVisibleScreenshot() as base64 PNG.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"createCaptcha",description:"Captcha helpers: click(bounds) and drag(from,to) return a post-action snapshot tree; readText(bounds?) OCRs a screenshot region (macOS Vision default, custom ocr injectable).",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"createChromeApi",description:"Chrome MV3-shaped APIs: tabs.query/get, windows.*, bookmarks/history/topSites (read-only from profile files), downloads.search/download. Writes throw UnsupportedOperationError.",parameters:{type:"object",properties:{connection:{},options:{type:"object"}},required:["connection"]}},{name:"injectCookies",description:"Inject raw cookie exports into a page with CDP sanitization handled (negative expires dropped, __Host- forced secure+root path+url-scoped, SameSite=None dropped when not secure, name+domain deduped).",parameters:{type:"object",properties:{page:{},cookies:{type:"array"}},required:["page","cookies"]}},{name:"createNetworkSnoop",description:"Buffer a page's CDP network traffic and return {pop,peek,popJson,waitFor,summary,dispose}; match is a predicate or {url,method,mimeType,resourceType}.",parameters:{type:"object",properties:{page:{},match:{},bodies:{type:"boolean"},maxEntries:{type:"number"},maxBodyBytes:{type:"number"}},required:["page"]}},{name:"snoop.waitFor",description:"Wait until a finished entry matches a predicate or {url,method,mimeType,resourceType}; timeoutMs defaults to 30000.",parameters:{type:"object",properties:{match:{},timeoutMs:{type:"number"}}}},{name:"snoop.popJson",description:"Drain the buffer and parse JSON bodies; skips non-JSON mime types and payloads that fail to parse.",parameters:{type:"object",properties:{}}},{name:"snoop.summary",description:"Return a compact text view of buffered entries (method, status, mimeType, size, url) capped by {max}.",parameters:{type:"object",properties:{max:{type:"number"}}}},{name:"collectWhileScrolling",description:"Async generator that scrolls the page, drains snoop.popJson(), and yields extracted items until minItems, maxScrolls, or noGrowth.",parameters:{type:"object",properties:{page:{},snoop:{},minItems:{type:"number"},maxScrolls:{type:"number"},extract:{},scroll:{type:"string",enum:["wheel","end"]},settleMs:{type:"number"}},required:["page","snoop"]}},{name:"createTrace",description:"Start a page flight recorder that writes dir/trace.jsonl, dir/trace.har, dir/summary.json and screenshots; never sends Runtime.enable.",parameters:{type:"object",properties:{page:{},dir:{type:"string"},screenshots:{type:"boolean"},network:{type:"boolean"},console:{type:"boolean"},maxBodyBytes:{type:"number"},events:{}},required:["page","dir"]}},{name:"trace.step",description:"Run named fn as a traced step with optional before/after screenshots; records the error and rethrows on failure.",parameters:{type:"object",properties:{name:{type:"string"},fn:{}},required:["name","fn"]}},{name:"trace.stop",description:"Flush listeners, write summary.json and trace.har, dispose the snoop, and return the summary for dir.",parameters:{type:"object",properties:{}}},{name:"reconcileFrames",description:"Adopt OOPIF iframe targets missing from FrameManager so later snapshots include them; returns the frames that were added.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"snapshotWithFrames",description:"Reconcile missing OOPIF frames then snapshot; refs stay page-level: page.locator(ref), never frame.locator.",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"connectPipe.dialogPolicy",description:"Wire connectPipe({dialogPolicy}) and client.setDialogPolicy to {accept,promptText} or (dialog)=>boolean|{accept,promptText}; throwing policy accepts. WebSocket connect() keeps auto-accept.",parameters:{type:"object",properties:{accept:{type:"boolean"},promptText:{type:"string"}}}},{name:"requestHuman",description:"Pause for a human: inject a shadow-DOM Done banner, bringToFront first, and remove the banner on every path; until is {url}|{selector}|async predicate.",parameters:{type:"object",properties:{page:{},prompt:{type:"string"},until:{},timeoutMs:{type:"number"},pollMs:{type:"number"},signal:{}},required:["page"]}},{name:"describeLayers",description:"Sample a viewport grid and return {blocking,candidates,viewport} so overlay coverage and selectorHint are visible.",parameters:{type:"object",properties:{page:{},grid:{type:"number"}},required:["page"]}},{name:"snapshotWithLayers",description:"Prepend a @layers header to the snapshot tree and attach a layers field so overlays are visible before the a11y tree.",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"emulate",description:"Apply a DEVICE_PRESETS name, a custom metrics object, or null to restore the original UA captured on first call.",parameters:{type:"object",properties:{page:{},preset:{}},required:["page","preset"]}},{name:"createRoutes",description:"Install page request interception; Fetch.enable is sent only on the first route(); interception is fingerprintable, keep it off by default.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"route.continue",description:"Continue an intercepted request, optionally overriding url, method, headers, or postData.",parameters:{type:"object",properties:{url:{type:"string"},method:{type:"string"},headers:{type:"object"},postData:{}}}},{name:"route.fulfill",description:"Fulfill an intercepted request with {status,headers,contentType,body} instead of hitting the network.",parameters:{type:"object",properties:{status:{type:"number"},headers:{type:"object"},contentType:{type:"string"},body:{}}}},{name:"route.abort",description:"Abort an intercepted request with a CDP errorReason (defaults to Failed).",parameters:{type:"object",properties:{reason:{type:"string"}}}}];var MODIFIER_KEYS2=new Set(["Alt","Control","Meta","Shift"]);function splitModifiers(keys=[]){const modifiers=keys.filter((key)=>MODIFIER_KEYS2.has(key)||/^(cmd|command|ctrl|option|controlormeta)$/i.test(key));const rest=keys.filter((key)=>!modifiers.includes(key));return{modifiers,rest}}function createCua(page){async function holdModifiers(keys,fn){const{modifiers}=splitModifiers(keys);for(const key of modifiers)await page.keyboard.down(key);try{return await fn()}finally{for(const key of[...modifiers].reverse())await page.keyboard.up(key)}}return{page,async click({x,y,button="left",keypress}){await holdModifiers(keypress,()=>page.mouse.click(x,y,{button}))},async doubleClick({x,y,keypress}){await holdModifiers(keypress,()=>page.mouse.click(x,y,{clickCount:2}))},async drag({path,keys}){if(!Array.isArray(path)||path.length<2){throw new TypeError("cua.drag requires path with at least two points")}await holdModifiers(keys,async()=>{const[first,...rest]=path;await page.mouse.move(first.x,first.y);await page.mouse.down();try{for(const point of rest)await page.mouse.move(point.x,point.y)}finally{await page.mouse.up()}})},async getVisibleScreenshot(){const buffer=await page.screenshot({type:"png"});return buffer.toString("base64")},async keypress({keys}){if(!Array.isArray(keys)||keys.length===0){throw new TypeError("cua.keypress requires a non-empty keys array")}await page.keyboard.press(keys.join("+"))},async move({x,y,keys}){await holdModifiers(keys,()=>page.mouse.move(x,y))},async scroll({x,y,scrollX,scrollY,keypress}){await holdModifiers(keypress,async()=>{await page.mouse.move(x,y);await page.mouse.wheel(scrollX,scrollY)})},async type({text}){await page.keyboard.type(text)}}}import{spawn as spawn2}from"node:child_process";import{mkdtempSync,writeFileSync,rmSync}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import path4 from"node:path";var MAX_TIMER_MS=2147483647;var STOP=Symbol("wait stopped");async function waitForCaptcha(page,{until,timeoutMs=1e4,pollMs=100,signal}={}){if(typeof until!=="function")throw new TypeError("until must be a function");if(!Number.isFinite(timeoutMs)||timeoutMs<0||timeoutMs>MAX_TIMER_MS){throw new RangeError("timeoutMs must be between 0 and 2147483647")}if(!Number.isFinite(pollMs)||pollMs<=0||pollMs>MAX_TIMER_MS){throw new RangeError("pollMs must be greater than 0 and at most 2147483647")}if(signal!==undefined&&(typeof signal?.aborted!=="boolean"||typeof signal.addEventListener!=="function"||typeof signal.removeEventListener!=="function")){throw new TypeError("signal must be AbortSignal-compatible")}const started=performance.now();const deadline=started+timeoutMs;const operation=new AbortController;let deadlineTimer;let pollTimer;let stop;const stopped=new Promise((resolve)=>{stop=()=>resolve(STOP)});const terminal=()=>signal?.aborted?"cancelled":performance.now()>=deadline?"timed_out":null;const result=(outcome)=>({outcome,elapsedMs:performance.now()-started});const scheduleDeadline=()=>{const remaining=deadline-performance.now();if(remaining<=0)stop();else deadlineTimer=setTimeout(scheduleDeadline,Math.ceil(remaining))};try{const initial=terminal();if(initial)return result(initial);signal?.addEventListener("abort",stop,{once:true});scheduleDeadline();for(;;){let accepted;try{accepted=await Promise.race([Promise.resolve().then(()=>terminal()?STOP:until(page,{signal:operation.signal})),stopped])}catch(error){const outcome=terminal();if(outcome)return result(outcome);throw error}const outcome=terminal();if(outcome)return result(outcome);if(accepted===true)return result("matched");await Promise.race([new Promise((resolve)=>{pollTimer=setTimeout(resolve,Math.ceil(Math.min(pollMs,deadline-performance.now())))}),stopped]);clearTimeout(pollTimer);const afterDelay=terminal();if(afterDelay)return result(afterDelay)}}finally{clearTimeout(deadlineTimer);clearTimeout(pollTimer);signal?.removeEventListener("abort",stop);operation.abort();stop()}}var DEFAULT_DRAG_STEPS=20;var POST_ACTION_SETTLE_MS=3000;function validatePoint(point){if(!Number.isFinite(point?.x)||!Number.isFinite(point?.y)){throw new TypeError("point coordinates must be finite numbers")}}function validateSteps(steps){if(!Number.isSafeInteger(steps)||steps<=0){throw new RangeError("steps must be a positive safe integer")}}function validateSettleMs(value){if(!Number.isFinite(value)||value<0||value>2147483647){throw new RangeError("settleMs must be between 0 and 2147483647")}}var MACOS_VISION_OCR_SWIFT=`
1470
+ ${tail}`:""))}async send(method,params,sessionId,opts={}){if(method==="Target.createTarget"&&opts.capability!==targetCreationCapability)throw Error("Target.createTarget is reserved for createAgentTabs");if(String(method).startsWith("OmO.")){throw Error(`Extension commands are unavailable over pipe transport: ${method}`)}await this.ensureConnected();const id=this.#seq++;const msg={id,method};if(params!==undefined)msg.params=params;if(sessionId)msg.sessionId=sessionId;const{promise,resolve,reject}=Promise.withResolvers();const timeoutMs=opts.timeoutMs??this.#commandTimeoutMs;const timeout=timeoutMs>0?setTimeout(()=>{this.#pending.delete(id);reject(Error(`CDP command timeout: ${method}`))},timeoutMs):undefined;this.#pending.set(id,{method,resolve,reject,timeout});this.#writeStream.write(JSON.stringify(msg)+"\x00");return promise}on(method,fn){return this.#events.on(method,({data})=>fn(data.payload,data.meta))}async discoverTargets(){const{targetInfos}=await this.send("Target.getTargets");return targetInfos.map((t)=>({id:t.targetId,type:t.type,url:t.url??"",title:t.title??"",description:t.description,faviconUrl:t.faviconUrl,parentId:t.openerId}))}async close(){const child=this.#child;this.#child=undefined;if(child&&child.exitCode===null){const exited=new Promise((resolve)=>child.once("exit",resolve));if(this.#connected){await Promise.race([this.send("Browser.close",undefined,undefined,{timeoutMs:GRACEFUL_CLOSE_TIMEOUT_MS}).catch(()=>{}),exited])}this.#connected=false;this.#failAll(Error("CDP pipe client closed"));if(child.exitCode===null){await Promise.race([exited,new Promise((resolve)=>setTimeout(resolve,GRACEFUL_CLOSE_TIMEOUT_MS))])}if(child.exitCode===null){try{child.kill("SIGKILL")}catch{}await exited}return}this.#connected=false;this.#failAll(Error("CDP pipe client closed"))}#onData(chunk){this.#buffer=Buffer.concat([this.#buffer,chunk]);let idx;while((idx=this.#buffer.indexOf(0))!==-1){const raw=this.#buffer.subarray(0,idx).toString("utf8");this.#buffer=this.#buffer.subarray(idx+1);if(raw.length===0)continue;let msg;try{msg=JSON.parse(raw)}catch{continue}this._handleTransportMessage(msg)}}_handleTransportMessage(msg){if(typeof msg.id==="number"){const entry=this.#pending.get(msg.id);if(!entry)return;this.#pending.delete(msg.id);if(entry.timeout)clearTimeout(entry.timeout);if(msg.error){const err=Error(msg.error.message??`CDP command failed: ${entry.method}`);err.code=msg.error.code;err.data=msg.error.data;entry.reject(err)}else{entry.resolve(msg.result)}return}if(typeof msg.method==="string"){const handled=msg.method==="Page.javascriptDialogOpening"&&msg.sessionId?this.#handleJavaScriptDialog(msg).catch(()=>{}):undefined;this.#events.emit(msg.method,{data:{payload:msg.params,meta:{sessionId:msg.sessionId}}}).catch(()=>{});return handled}}async#handleJavaScriptDialog(msg){const params=await resolveDialogAction(this.#dialogPolicy,msg.params);await this.send("Page.handleJavaScriptDialog",params,msg.sessionId)}#failAll(err){for(const entry of this.#pending.values()){if(entry.timeout)clearTimeout(entry.timeout);entry.reject(err)}this.#pending.clear()}}async function connectPipe({browserPath,browserArgs=[],spawnOptions,storageRoot,commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy}={}){const client=new PipeCdpClient({browserPath,browserArgs,spawnOptions,commandTimeoutMs,readinessTimeoutMs,logId,dialogPolicy});await client.ensureConnected();const connection=new BrowserConnection(client,{storageRoot});await connection.initialize();connection.browserProcess=client.childProcess;return connection}import{spawn as spawn2}from"node:child_process";import{createHash,randomUUID as randomUUID3}from"node:crypto";import{chmod as chmod2,mkdir as mkdir3,open as open3,readFile as readFile3,readdir as readdir2,rename as rename2,unlink as unlink3}from"node:fs/promises";import os from"node:os";import path5 from"node:path";import{randomUUID as randomUUID2}from"node:crypto";import{watch}from"node:fs";import{link as link2,readdir,rename,stat,unlink as unlink2}from"node:fs/promises";import path3 from"node:path";import{setTimeout as sleep}from"node:timers/promises";import{execFile}from"node:child_process";import{randomUUID}from"node:crypto";import{chmod,link,open as open2,readFile,unlink}from"node:fs/promises";import{promisify}from"node:util";var execFileAsync=promisify(execFile);var ownStartTime;async function processStartTime(pid){if(process.platform==="win32")return null;if(process.platform==="linux"){try{const text=await readFile(`/proc/${pid}/stat`,"utf8");return text.slice(text.lastIndexOf(")")+2).split(" ")[19]??null}catch{return null}}try{const{stdout}=await execFileAsync("ps",["-o","lstart=","-p",String(pid)],{env:{...process.env,LC_ALL:"C",TZ:"UTC"}});return stdout.trim()||null}catch{return null}}async function createLock(lockPath){ownStartTime??=processStartTime(process.pid);const token=randomUUID();const tempPath=`${lockPath}.${process.pid}.${randomUUID()}.tmp`;let handle;try{handle=await open2(tempPath,"wx",384);await handle.writeFile(`${JSON.stringify({pid:process.pid,start:await ownStartTime,token,acquiredAt:new Date().toISOString()})}
1471
+ `,"utf8");const{ino}=await handle.stat();await handle.close();handle=null;await chmod(tempPath,384);try{await link(tempPath,lockPath)}catch(error){if(error?.code==="EEXIST")return null;throw error}return{ino,token}}finally{await handle?.close().catch(()=>{});await unlink(tempPath).catch(()=>{})}}async function readLockState(lockPath){let handle;try{handle=await open2(lockPath,"r")}catch(error){if(error?.code==="ENOENT")return null;throw error}try{const stats=await handle.stat();const text=await handle.readFile("utf8");const state={ino:stats.ino,mtimeMs:stats.mtimeMs,pid:null,start:null,token:null};try{const value=JSON.parse(text);if(Number.isInteger(value?.pid)&&value.pid>0)state.pid=value.pid;if(typeof value?.start==="string")state.start=value.start;if(typeof value?.token==="string")state.token=value.token}catch{}return state}finally{await handle.close().catch(()=>{})}}function isSameLock(state,ino,token){return state!==null&&state.ino===ino&&state.token===token}var LOCK_POLL_INTERVAL_MS=250;var LOCK_RETRY_JITTER_MS=25;var LOCK_PUT_BACK_TIMEOUT_MS=30000;var localLocks=new Map;function isPidAlive(pid){try{process.kill(pid,0);return true}catch(error){if(error?.code==="EPERM")return true;if(error?.code==="ESRCH")return false;throw error}}async function unlinkIfPresent(target){await unlink2(target).catch((error)=>{if(error?.code!=="ENOENT")throw error})}async function isAbandoned(state,staleGraceMs){if(state.pid===null)return Date.now()-state.mtimeMs>=staleGraceMs;if(!isPidAlive(state.pid))return true;if(state.start===null)return false;const start=await processStartTime(state.pid);return start!==null&&start!==state.start}async function reclaimLock(lockPath,ino,token,{deadline=Date.now()+LOCK_PUT_BACK_TIMEOUT_MS,hooks={}}={}){if(!isSameLock(await readLockState(lockPath),ino,token)){return await stat(lockPath).catch(()=>null)===null}const movedPath=`${lockPath}.${process.pid}.${randomUUID2()}.stale`;await hooks.beforeMove?.();try{await rename(lockPath,movedPath)}catch(error){if(error?.code==="ENOENT")return true;throw error}await hooks.afterMove?.();if(isSameLock(await readLockState(movedPath).catch(()=>null),ino,token)){await unlinkIfPresent(movedPath);return true}await putBack(movedPath,lockPath,deadline,hooks);return false}async function putBack(movedPath,lockPath,deadline,hooks){for(;;){try{await link2(movedPath,lockPath);await unlinkIfPresent(movedPath);return}catch(error){if(error?.code==="ENOENT")return;if(error?.code!=="EEXIST")throw error}await hooks.onPutBackBlocked?.();if(await stat(movedPath).catch(()=>null)===null)return;const remainingMs=deadline-Date.now();if(remainingMs<=0)return;await waitForLockRelease(lockPath,Math.min(remainingMs,LOCK_POLL_INTERVAL_MS))}}async function releaseLock(lockPath,ino,token){const prefix=`${path3.basename(lockPath)}.`;const entries=await readdir(path3.dirname(lockPath)).catch(()=>[]);for(const entry of entries){if(!entry.startsWith(prefix)||!entry.endsWith(".stale"))continue;const moved=path3.join(path3.dirname(lockPath),entry);if(isSameLock(await readLockState(moved).catch(()=>null),ino,token)){await unlinkIfPresent(moved)}}if(!isSameLock(await readLockState(lockPath),ino,token))return;await unlinkIfPresent(lockPath)}function waitForLockRelease(lockPath,timeoutMs){return new Promise((resolve,reject)=>{let settled=false;let watcher;let timer;const finish=(error,released)=>{if(settled)return;settled=true;clearTimeout(timer);watcher?.close();if(error)reject(error);else resolve(released)};const check=()=>{stat(lockPath).then(()=>{},(error)=>{if(error?.code==="ENOENT")finish(null,true);else finish(error)})};try{watcher=watch(path3.dirname(lockPath),(event,filename)=>{if((event==="rename"||event==="change")&&(!filename||filename.toString()===path3.basename(lockPath))){check()}})}catch(error){if(error?.code!=="ENOENT"){finish(error);return}}timer=setTimeout(()=>finish(null,false),timeoutMs);check()})}async function acquireLock(lockPath,timeoutMs,staleGraceMs){const deadline=Date.now()+timeoutMs;let holderPid=null;for(;;){const ours=await createLock(lockPath);if(ours!==null)return()=>releaseLock(lockPath,ours.ino,ours.token);if(Date.now()>=deadline){throw new Error(`timed out waiting for instance lock held by pid ${holderPid??"unknown"}`)}const state=await readLockState(lockPath);if(state===null)continue;holderPid=state.pid??holderPid;if(await isAbandoned(state,staleGraceMs)){await reclaimLock(lockPath,state.ino,state.token,{deadline});await sleep(Math.random()*LOCK_RETRY_JITTER_MS);continue}const remainingMs=deadline-Date.now();if(remainingMs>0){await waitForLockRelease(lockPath,Math.min(remainingMs,LOCK_POLL_INTERVAL_MS))}}}async function acquireLocalLock(key){const previous=localLocks.get(key)??Promise.resolve();let releaseCurrent;const current=new Promise((resolve)=>{releaseCurrent=resolve});const tail=previous.then(()=>current);localLocks.set(key,tail);await previous;return()=>{releaseCurrent();if(localLocks.get(key)===tail)localLocks.delete(key)}}async function withLock(lockPath,{timeoutMs,staleGraceMs},run){const releaseLocal=await acquireLocalLock(lockPath);try{const release=await acquireLock(lockPath,timeoutMs,staleGraceMs);try{return await run()}finally{await release()}}finally{releaseLocal()}}import{watch as watch2}from"node:fs";import{readFile as readFile2,stat as stat2}from"node:fs/promises";import path4 from"node:path";var ACTIVE_PORT_POLL_MS=100;function httpEndpointFromWebSocket(webSocketUrl){const endpoint=new URL(webSocketUrl);endpoint.protocol=endpoint.protocol==="wss:"?"https:":"http:";endpoint.pathname="/";endpoint.search="";endpoint.hash="";return endpoint.toString().replace(/\/$/,"")}function parseActivePort(text){const[portLine,browserPath]=text.trim().split(/\r?\n/);const port=Number(portLine);if(!Number.isInteger(port)||port<1||port>65535)return null;return{endpoint:`http://127.0.0.1:${port}`,browserPath:browserPath?.trim()||null}}function activePortIdentity(info){return{ino:info.ino,mtimeMs:info.mtimeMs,size:info.size}}async function snapshotActivePort(profileDir){if(!profileDir)return null;try{return activePortIdentity(await stat2(path4.join(profileDir,"DevToolsActivePort")))}catch(error){if(error?.code==="ENOENT")return null;throw error}}function isSameFile(info,previous){return previous!==null&&info.ino===previous.ino&&info.mtimeMs===previous.mtimeMs&&info.size===previous.size}function assertLaunchedBrowser(child,report,webSocketDebuggerUrl){if(child.exitCode!==null||child.signalCode!==null){throw new Error(`browser exited before its DevTools endpoint ${report.endpoint} could be verified`)}const answered=new URL(webSocketDebuggerUrl).pathname;if(report.browserPath===null||answered!==report.browserPath){throw new Error(`DevTools endpoint ${report.endpoint} answers as ${answered}, not as the launched browser (${report.browserPath??"no browser id reported"})`)}}async function discoverLaunchedEndpoint(child,{profileDir,timeoutMs,previousActivePort=null}={}){const activePortPath=profileDir?path4.join(profileDir,"DevToolsActivePort"):null;return new Promise((resolve,reject)=>{let settled=false;let stderr="";let activePortWatcher;let activePortReading=false;let activePortChangedWhileReading=false;const cleanups=[];const finish=(error,endpoint)=>{if(settled)return;settled=true;for(const cleanup of cleanups.splice(0))cleanup();activePortWatcher?.close();if(error)reject(error);else resolve(endpoint)};const readActivePort=async()=>{const info=await stat2(activePortPath);if(isSameFile(activePortIdentity(info),previousActivePort))return;const report=parseActivePort(await readFile2(activePortPath,"utf8"));if(report)finish(null,report)};const tryActivePort=async()=>{if(!activePortPath||settled)return;if(activePortReading){activePortChangedWhileReading=true;return}activePortReading=true;try{do{activePortChangedWhileReading=false;await readActivePort()}while(activePortChangedWhileReading&&!settled)}catch(error){if(error?.code!=="ENOENT")finish(error)}finally{activePortReading=false}};const onStderr=(chunk)=>{stderr=`${stderr}${chunk}`.slice(-16384);const match=/DevTools listening on (ws:\/\/\S+)/.exec(stderr);if(match){finish(null,{endpoint:httpEndpointFromWebSocket(match[1]),browserPath:new URL(match[1]).pathname})}else tryActivePort()};const onError=(error)=>finish(error);const onExit=(code,signal)=>{finish(new Error(`browser exited before exposing DevTools (code ${code}, signal ${signal??"none"})${stderr?`
1472
+ ${stderr}`:""}`))};child.stderr.setEncoding("utf8");child.stderr.on("data",onStderr);child.once("error",onError);child.once("exit",onExit);cleanups.push(()=>child.stderr.off("data",onStderr));cleanups.push(()=>child.off("error",onError));cleanups.push(()=>child.off("exit",onExit));if(activePortPath){try{activePortWatcher=watch2(profileDir,(event,filename)=>{if((event==="rename"||event==="change")&&(!filename||filename.toString()===path4.basename(activePortPath))){tryActivePort()}})}catch(error){if(error?.code!=="ENOENT")finish(error)}tryActivePort();const poll=setInterval(()=>void tryActivePort(),ACTIVE_PORT_POLL_MS);cleanups.push(()=>clearInterval(poll))}const timeout=setTimeout(()=>{finish(new Error(`browser did not expose a DevTools endpoint within ${timeoutMs}ms${stderr?`
1473
+ ${stderr}`:""}`))},timeoutMs);cleanups.push(()=>clearTimeout(timeout))})}var RECORD_VERSION=2;var DEFAULT_REGISTRY_ROOT=path5.join(os.homedir(),".local","share","omowright","instances");var DEFAULT_PROBE_TIMEOUT_MS=1000;var DEFAULT_LAUNCH_TIMEOUT_MS=1e4;var DEFAULT_CONNECT_TIMEOUT_MS=1e4;var LOCK_TIMEOUT_MARGIN_MS=5000;var DEFAULT_LOCK_TIMEOUT_MS=resolveLockTimeoutMs({});var STALE_LOCK_GRACE_MS=DEFAULT_LOCK_TIMEOUT_MS;function normalizeName(name){if(typeof name!=="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)){throw new TypeError("instance name must start with a letter or number and contain only letters, numbers, dots, dashes, or underscores")}return name}function registryPaths(registryRoot,name){const root=path5.resolve(registryRoot??DEFAULT_REGISTRY_ROOT);return{root,recordPath:path5.join(root,`${name}.json`),lockPath:path5.join(root,`${name}.lock`)}}async function ensureRegistryRoot(root){await mkdir3(root,{recursive:true,mode:448});await chmod2(root,448)}function isRecord(value,expectedName){return value!==null&&typeof value==="object"&&value.version===RECORD_VERSION&&value.name===expectedName&&Number.isInteger(value.pid)&&value.pid>0&&typeof value.endpoint==="string"&&value.endpoint.length>0&&typeof value.webSocketDebuggerUrl==="string"&&value.webSocketDebuggerUrl.length>0&&(typeof value.profileDir==="string"||value.profileDir===null)&&typeof value.browserPath==="string"&&value.browserPath.length>0&&typeof value.startedAt==="string"&&!Number.isNaN(Date.parse(value.startedAt))}async function readRecord(recordPath,expectedName){let text;try{text=await readFile3(recordPath,"utf8")}catch(error){if(error?.code==="ENOENT")return{exists:false,record:null};throw error}try{const record=JSON.parse(text);return{exists:true,record:isRecord(record,expectedName)?record:null}}catch{return{exists:true,record:null}}}async function writeRecordAtomic(root,recordPath,record){const tempPath=path5.join(root,`.${record.name}.${process.pid}.${randomUUID3()}.tmp`);let handle;try{handle=await open3(tempPath,"wx",384);await handle.writeFile(`${JSON.stringify(record,null,2)}
1474
+ `,"utf8");await handle.close();handle=null;await chmod2(tempPath,384);await rename2(tempPath,recordPath);await chmod2(recordPath,384)}catch(error){await handle?.close().catch(()=>{});await unlink3(tempPath).catch(()=>{});throw error}}function isConnectionRefused(error){for(let cause=error;cause;cause=cause?.cause){if(cause.code==="ECONNREFUSED"||cause.code==="ENOTFOUND"||cause.code==="ConnectionRefused"){return true}}return false}async function probeEndpoint(endpoint,timeoutMs){const versionUrl=new URL("/json/version",endpoint);const response=await fetch(versionUrl,{signal:AbortSignal.timeout(timeoutMs)});if(!response.ok){throw new Error(`CDP discovery request failed (${response.status} ${response.statusText})`)}const version=await response.json();if(typeof version?.webSocketDebuggerUrl!=="string"||version.webSocketDebuggerUrl.length===0){throw new Error("CDP discovery response lacks webSocketDebuggerUrl")}return version}function resolveConnectTimeoutMs(options){return options.connectTimeoutMs??DEFAULT_CONNECT_TIMEOUT_MS}function resolveLockTimeoutMs(options){if(options.lockTimeoutMs!==undefined)return options.lockTimeoutMs;return(options.launchTimeoutMs??DEFAULT_LAUNCH_TIMEOUT_MS)+(options.probeTimeoutMs??DEFAULT_PROBE_TIMEOUT_MS)+resolveConnectTimeoutMs(options)+LOCK_TIMEOUT_MARGIN_MS}function nameLockOptions(options){return{timeoutMs:resolveLockTimeoutMs(options),staleGraceMs:STALE_LOCK_GRACE_MS}}async function connectWithin(endpoint,options,timeoutMs){const pending=openConnection(endpoint,options);let timer;try{return await Promise.race([pending,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`timed out after ${timeoutMs}ms opening a CDP session on ${endpoint}`)),timeoutMs)})])}catch(error){pending.then((connection)=>connection.close().catch(()=>{}),()=>{});throw error}finally{clearTimeout(timer)}}async function removeOwnedRecord(recordPath,name,pid){const loaded=await readRecord(recordPath,name);if(loaded.record?.pid!==pid)return;await unlinkIfPresent(recordPath)}function profileDirFromArgs(browserArgs){for(let index=0;index<browserArgs.length;index+=1){const argument=browserArgs[index];if(argument==="--user-data-dir"&&browserArgs[index+1]){return path5.resolve(browserArgs[index+1])}if(argument.startsWith("--user-data-dir=")){return path5.resolve(argument.slice("--user-data-dir=".length))}}return null}async function terminateBrowser(child){if(!child||child.exitCode!==null||child.signalCode!==null)return;const exited=new Promise((resolve)=>child.once("exit",resolve));child.kill("SIGTERM");let forceTimer;const force=new Promise((resolve)=>{forceTimer=setTimeout(()=>{if(child.exitCode===null&&child.signalCode===null){child.kill("SIGKILL")}resolve()},5000)});await Promise.race([exited,force]);clearTimeout(forceTimer);if(child.exitCode===null&&child.signalCode===null)await exited}function connectionOptions(options,profileDir){const result={...options.connectionOptions??{}};if(options.storageRoot!==undefined)result.storageRoot=options.storageRoot;else if(result.storageRoot===undefined&&profileDir){result.storageRoot=profileDir}if(options.client!==undefined){result.client={...result.client??{},...options.client}}if(options.dialogPolicy!==undefined)result.dialogPolicy=options.dialogPolicy;return result}async function launchNamed(name,{root,recordPath,lockPath},options){if(typeof options.browserPath!=="string"||options.browserPath.length===0){throw new TypeError(`connectNamed("${name}") requires browserPath when no healthy instance is registered`)}const browserArgs=[...options.browserArgs??[]];const profileDir=options.profileDir?path5.resolve(options.profileDir):profileDirFromArgs(browserArgs);const previousActivePort=await snapshotActivePort(profileDir);const child=spawn2(options.browserPath,[...browserArgs,"--remote-debugging-address=127.0.0.1","--remote-debugging-port=0"],{...options.spawnOptions??{},stdio:["ignore","ignore","pipe"]});let connection;try{const launchTimeoutMs=options.launchTimeoutMs??DEFAULT_LAUNCH_TIMEOUT_MS;const report=await discoverLaunchedEndpoint(child,{profileDir,timeoutMs:launchTimeoutMs,previousActivePort});const{endpoint}=report;const{webSocketDebuggerUrl}=await probeEndpoint(endpoint,launchTimeoutMs);assertLaunchedBrowser(child,report,webSocketDebuggerUrl);connection=await connectWithin(endpoint,connectionOptions(options,profileDir),resolveConnectTimeoutMs(options));const record={version:RECORD_VERSION,name,pid:child.pid,endpoint,webSocketDebuggerUrl,profileDir,browserPath:path5.resolve(options.browserPath),startedAt:new Date().toISOString()};await writeRecordAtomic(root,recordPath,record);connection.browserProcess=child;const disconnect=connection.close.bind(connection);connection.close=async()=>{let failure;try{await disconnect()}catch(error){failure=error}await terminateBrowser(child);try{await withLock(lockPath,nameLockOptions(options),()=>removeOwnedRecord(recordPath,name,child.pid))}catch(error){failure??=error}if(failure)throw failure};return connection}catch(error){await connection?.close().catch(()=>{});await terminateBrowser(child);throw error}}async function withEngineLock(registryRoot,engineKey,run){const root=path5.resolve(registryRoot??DEFAULT_REGISTRY_ROOT);await ensureRegistryRoot(root);const digest=createHash("sha256").update(path5.resolve(engineKey)).digest("hex").slice(0,16);const lockPath=path5.join(root,`_engine-${digest}.lock`);return withLock(lockPath,{timeoutMs:DEFAULT_LOCK_TIMEOUT_MS,staleGraceMs:STALE_LOCK_GRACE_MS},run)}async function connectNamed(name,options={}){const normalizedName=normalizeName(name);const paths=registryPaths(options.registryRoot,normalizedName);await ensureRegistryRoot(paths.root);return withLock(paths.lockPath,nameLockOptions(options),()=>attachOrLaunch(normalizedName,paths,options))}async function attachOrLaunch(normalizedName,paths,options){const loaded=await readRecord(paths.recordPath,normalizedName);if(loaded.record){await chmod2(paths.recordPath,384);if(isPidAlive(loaded.record.pid)){let version=null;try{version=await probeEndpoint(loaded.record.endpoint,options.probeTimeoutMs??DEFAULT_PROBE_TIMEOUT_MS)}catch(error){if(!isConnectionRefused(error)){throw new Error(`unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${error.message}`,{cause:error})}}if(version?.webSocketDebuggerUrl===loaded.record.webSocketDebuggerUrl){const{webSocketDebuggerUrl}=loaded.record;const timeoutMs=resolveConnectTimeoutMs(options);try{return await acquireSharedConnection(webSocketDebuggerUrl,connectionOptions(options,loaded.record.profileDir),{open:(shared)=>connectWithin(webSocketDebuggerUrl,shared,timeoutMs),timeoutMs})}catch(error){throw new Error(`unresponsive holder "${normalizedName}" pid ${loaded.record.pid} endpoint ${loaded.record.endpoint}: ${error.message}`,{cause:error})}}}}if(loaded.exists){await unlink3(paths.recordPath).catch((error)=>{if(error?.code!=="ENOENT")throw error})}return await launchNamed(normalizedName,paths,options)}async function listInstances(options={}){const root=path5.resolve(options.registryRoot??DEFAULT_REGISTRY_ROOT);await ensureRegistryRoot(root);const entries=await readdir2(root,{withFileTypes:true});const records=await Promise.all(entries.filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).map(async(entry)=>{const expectedName=entry.name.slice(0,-".json".length);const recordPath=path5.join(root,entry.name);const loaded=await readRecord(recordPath,expectedName);if(!loaded.record)return null;await chmod2(recordPath,384);const alive=isPidAlive(loaded.record.pid);let responsive=false;if(alive){responsive=await probeEndpoint(loaded.record.endpoint,options.probeTimeoutMs??DEFAULT_PROBE_TIMEOUT_MS).then((version)=>version.webSocketDebuggerUrl===loaded.record.webSocketDebuggerUrl,()=>false)}return{...loaded.record,alive,responsive}}));return records.filter((record)=>record!==null).sort((left,right)=>left.name.localeCompare(right.name))}import{randomInt}from"node:crypto";import{chmod as chmod3,mkdir as mkdir4,open as open4,readFile as readFile4}from"node:fs/promises";import{globSync}from"node:fs";import os2 from"node:os";import path6 from"node:path";var LEGACY_CLOAK_PROBE_URL="http://127.0.0.1:9242";var LEGACY_PROBE_TIMEOUT_MS=1500;var MIN_FINGERPRINT_SEED=1e4;var MAX_FINGERPRINT_SEED=99999;var METADATA_FILE=".omowright-cloak.json";var DEFAULT_PROFILE_DIR=path6.join(os2.homedir(),".local","share","omowright-cloak");function normalizeFingerprintSeed(value){const seed=typeof value==="string"&&value.trim()!==""?Number(value):value;if(!Number.isInteger(seed)||seed<MIN_FINGERPRINT_SEED||seed>MAX_FINGERPRINT_SEED){throw new RangeError(`fingerprint seed must be an integer from ${MIN_FINGERPRINT_SEED} to ${MAX_FINGERPRINT_SEED}`)}return seed}function platformFingerprint(){return process.platform==="darwin"?"macos":"windows"}function identityFlag(value){return/^(--user-data-dir|--fingerprint|--fingerprint-platform)(?:=|$)/.test(value)}function buildCloakBrowserArgs({profileDir,fingerprintSeed,extraArgs=[]}={}){const profile=path6.resolve(profileDir??DEFAULT_PROFILE_DIR);const seed=normalizeFingerprintSeed(fingerprintSeed);const conflicting=extraArgs.filter(identityFlag);if(conflicting.length>0){throw new Error(`extraArgs cannot override fixed profile identity: ${conflicting.join(", ")}`)}return["--no-first-run","--no-default-browser-check","--disable-session-crashed-bubble",`--user-data-dir=${profile}`,`--fingerprint=${seed}`,`--fingerprint-platform=${platformFingerprint()}`,...extraArgs]}async function readMetadata(metadataPath){try{const parsed=JSON.parse(await readFile4(metadataPath,"utf8"));return normalizeFingerprintSeed(parsed.fingerprintSeed)}catch(error){if(error?.code==="ENOENT")return null;if(error instanceof SyntaxError){throw new Error(`invalid CloakBrowser profile metadata: ${metadataPath}`)}throw error}}async function writeMetadata(metadataPath,fingerprintSeed){const handle=await open4(metadataPath,"wx",384);try{await handle.writeFile(`${JSON.stringify({fingerprintSeed},null,2)}
1475
+ `,"utf8")}finally{await handle.close()}await chmod3(metadataPath,384)}async function resolveCloakProfile({profileDir=DEFAULT_PROFILE_DIR,fingerprintSeed,randomSeed=()=>randomInt(MIN_FINGERPRINT_SEED,MAX_FINGERPRINT_SEED+1)}={}){const resolvedProfile=path6.resolve(profileDir);const metadataPath=path6.join(resolvedProfile,METADATA_FILE);await mkdir4(resolvedProfile,{recursive:true,mode:448});await chmod3(resolvedProfile,448);const requested=fingerprintSeed===undefined?null:normalizeFingerprintSeed(fingerprintSeed);let stored=await readMetadata(metadataPath);if(stored===null){const candidate=requested??normalizeFingerprintSeed(randomSeed());try{await writeMetadata(metadataPath,candidate);stored=candidate}catch(error){if(error?.code!=="EEXIST")throw error;stored=await readMetadata(metadataPath);if(stored===null){throw new Error(`CloakBrowser profile seed metadata disappeared: ${metadataPath}`)}}}if(requested!==null&&requested!==stored){throw new Error(`fingerprint seed mismatch: profile is fixed at ${stored}, requested ${requested}`)}await chmod3(metadataPath,384);return{profileDir:resolvedProfile,metadataPath,fingerprintSeed:stored,browserArgs:buildCloakBrowserArgs({profileDir:resolvedProfile,fingerprintSeed:stored})}}function findCloakBrowserPath({browserRoot=path6.join(os2.homedir(),".cloakbrowser")}={}){const candidates=globSync(path6.join(path6.resolve(browserRoot),"chromium-*","Chromium.app","Contents","MacOS","Chromium")).sort();const browserPath=candidates.at(-1);if(!browserPath){throw new Error(`CloakBrowser binary not found under ${path6.resolve(browserRoot)}; set CLOAKBROWSER_BIN`)}return browserPath}async function assertCloakLaunchClear({browserPath,profileDir,registryRoot,legacyProbeUrl=LEGACY_CLOAK_PROBE_URL,probeTimeoutMs}){const records=await listInstances({registryRoot,probeTimeoutMs});for(const record of records){if(!record.alive||!record.responsive)continue;if(!record.profileDir)continue;if(path6.resolve(record.profileDir)===path6.resolve(profileDir))continue;if(path6.resolve(record.browserPath)!==path6.resolve(browserPath))continue;throw new Error(`CloakBrowser allows one instance: "${record.name}" (pid ${record.pid}, profile ${record.profileDir}) is live — connectNamed("${record.name}") to reuse it or close it first`)}const legacyHost=new URL(legacyProbeUrl).host;const explainedByRecord=records.some((record)=>record.alive&&record.responsive&&new URL(record.endpoint).host===legacyHost);if(explainedByRecord)return;try{const response=await fetch(new URL("/json/version",legacyProbeUrl),{signal:AbortSignal.timeout(probeTimeoutMs??LEGACY_PROBE_TIMEOUT_MS)});if(response.ok){throw new Error(`an unregistered CloakBrowser is answering on ${legacyProbeUrl} — attach with connect("${legacyProbeUrl}") or close it before launching`)}}catch(error){const unreachable=error instanceof TypeError||error?.name==="TimeoutError"||error?.name==="AbortError";if(!unreachable)throw error}}async function connectCloakProfile({browserPath=process.env.CLOAKBROWSER_BIN??findCloakBrowserPath(),profileDir=process.env.CLOAK_PROFILE_DIR??DEFAULT_PROFILE_DIR,fingerprintSeed=process.env.CLOAK_FINGERPRINT_SEED,browserArgs=[],storageRoot,name,...options}={}){const profile=await resolveCloakProfile({profileDir,fingerprintSeed});const resolvedBrowserArgs=buildCloakBrowserArgs({profileDir:profile.profileDir,fingerprintSeed:profile.fingerprintSeed,extraArgs:browserArgs});if(name===undefined){return connectPipe({browserPath,browserArgs:resolvedBrowserArgs,storageRoot:storageRoot??profile.profileDir,...options})}const{legacyProbeUrl,...connectOptions}=options;return withEngineLock(connectOptions.registryRoot,browserPath,async()=>{await assertCloakLaunchClear({browserPath,profileDir:profile.profileDir,registryRoot:connectOptions.registryRoot,legacyProbeUrl,probeTimeoutMs:connectOptions.probeTimeoutMs});return connectNamed(name,{browserPath,browserArgs:resolvedBrowserArgs,profileDir:profile.profileDir,storageRoot:storageRoot??profile.profileDir,...connectOptions})})}var SNAPSHOT_PARSE_ERROR="compactSnapshot expected a snapshot() result (JSON string or {tree, refs} object)";function compactSnapshot(snapshot){const obj=typeof snapshot==="string"?JSON.parse(snapshot):snapshot;if(!obj||typeof obj.tree!=="string")throw new TypeError(SNAPSHOT_PARSE_ERROR);return obj.tree}function snapshotTokens(snapshot){const text=typeof snapshot==="string"?snapshot:JSON.stringify(snapshot);return{bytes:Buffer.byteLength(text,"utf8"),estTokens:Math.ceil(Buffer.byteLength(text,"utf8")/4)}}var toolSchemas=[{name:"newTab",description:"Open a tab and return its page. Waits for interactivity.",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"]}},{name:"attachPage",description:"Attach to an existing tab by targetId from listTargets().",parameters:{type:"object",properties:{targetId:{type:"string"}},required:["targetId"]}},{name:"page.goto",description:"Navigate the page; resolves when the page looks interactive.",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"]}},{name:"page.snapshot",description:"PRIMARY page read. Returns a compact a11y tree; interactive elements carry [ref=eN] ids for page.locator. Options: maxDepth, maxChars, interactive, showHidden, selector, ref.",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"page.locator",description:"Resolve a ref id (e.g. 'e1') or CSS selector to a Locator: click, fill, press, hover, check, selectOption, dragTo, setInputFiles, textContent, isVisible, waitFor.",parameters:{type:"object",properties:{selectorOrRef:{type:"string"}},required:["selectorOrRef"]}},{name:"page.evaluate",description:"Run JS in the page and return the result.",parameters:{type:"object",properties:{expression:{type:"string"}},required:["expression"]}},{name:"page.screenshot",description:"Capture page image bytes (path, fullPage, clip, type, quality).",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"page.pdf",description:"Print the page to PDF bytes (path, format, margin, printBackground).",parameters:{type:"object",properties:{options:{type:"object"}}}},{name:"compactSnapshot",description:"Pass page.snapshot() output through this before reading: returns the raw tree without the refs map (refs resolve in-page; the map is ~54% of bytes on real pages).",parameters:{type:"object",properties:{snapshot:{}},required:["snapshot"]}},{name:"createCua",description:"Coordinate fallback for UI that refs cannot target: click/doubleClick/drag/move/scroll/type/keypress at viewport points, getVisibleScreenshot() as base64 PNG.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"createCaptcha",description:"Captcha helpers: click(bounds) and drag(from,to) return a post-action snapshot tree; readText(bounds?) OCRs a screenshot region (macOS Vision default, custom ocr injectable).",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"createChromeApi",description:"Chrome MV3-shaped APIs: tabs.query/get, windows.*, bookmarks/history/topSites (read-only from profile files), downloads.search/download. Writes throw UnsupportedOperationError.",parameters:{type:"object",properties:{connection:{},options:{type:"object"}},required:["connection"]}},{name:"injectCookies",description:"Inject raw cookie exports into a page with CDP sanitization handled (negative expires dropped, __Host- forced secure+root path+url-scoped, SameSite=None dropped when not secure, name+domain deduped).",parameters:{type:"object",properties:{page:{},cookies:{type:"array"}},required:["page","cookies"]}},{name:"createNetworkSnoop",description:"Buffer a page's CDP network traffic and return {pop,peek,popJson,waitFor,summary,dispose}; match is a predicate or {url,method,mimeType,resourceType}.",parameters:{type:"object",properties:{page:{},match:{},bodies:{type:"boolean"},maxEntries:{type:"number"},maxBodyBytes:{type:"number"}},required:["page"]}},{name:"snoop.waitFor",description:"Wait until a finished entry matches a predicate or {url,method,mimeType,resourceType}; timeoutMs defaults to 30000.",parameters:{type:"object",properties:{match:{},timeoutMs:{type:"number"}}}},{name:"snoop.popJson",description:"Drain the buffer and parse JSON bodies; skips non-JSON mime types and payloads that fail to parse.",parameters:{type:"object",properties:{}}},{name:"snoop.summary",description:"Return a compact text view of buffered entries (method, status, mimeType, size, url) capped by {max}.",parameters:{type:"object",properties:{max:{type:"number"}}}},{name:"collectWhileScrolling",description:"Async generator that scrolls the page, drains snoop.popJson(), and yields extracted items until minItems, maxScrolls, or noGrowth.",parameters:{type:"object",properties:{page:{},snoop:{},minItems:{type:"number"},maxScrolls:{type:"number"},extract:{},scroll:{type:"string",enum:["wheel","end"]},settleMs:{type:"number"}},required:["page","snoop"]}},{name:"createTrace",description:"Start a page flight recorder that writes dir/trace.jsonl, dir/trace.har, dir/summary.json and screenshots; never sends Runtime.enable.",parameters:{type:"object",properties:{page:{},dir:{type:"string"},screenshots:{type:"boolean"},network:{type:"boolean"},console:{type:"boolean"},maxBodyBytes:{type:"number"},events:{}},required:["page","dir"]}},{name:"trace.step",description:"Run named fn as a traced step with optional before/after screenshots; records the error and rethrows on failure.",parameters:{type:"object",properties:{name:{type:"string"},fn:{}},required:["name","fn"]}},{name:"trace.stop",description:"Flush listeners, write summary.json and trace.har, dispose the snoop, and return the summary for dir.",parameters:{type:"object",properties:{}}},{name:"reconcileFrames",description:"Adopt OOPIF iframe targets missing from FrameManager so later snapshots include them; returns the frames that were added.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"snapshotWithFrames",description:"Reconcile missing OOPIF frames then snapshot; refs stay page-level: page.locator(ref), never frame.locator.",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"connectPipe.dialogPolicy",description:"Wire connectPipe({dialogPolicy}), connect(url, {dialogPolicy}) and setDialogPolicy to {accept,promptText} or (dialog)=>boolean|{accept,promptText}; a throwing policy accepts.",parameters:{type:"object",properties:{accept:{type:"boolean"},promptText:{type:"string"}}}},{name:"requestHuman",description:"Pause for a human: inject a shadow-DOM Done banner, bringToFront first, and remove the banner on every path; until is {url}|{selector}|async predicate.",parameters:{type:"object",properties:{page:{},prompt:{type:"string"},until:{},timeoutMs:{type:"number"},pollMs:{type:"number"},signal:{}},required:["page"]}},{name:"describeLayers",description:"Sample a viewport grid and return {blocking,candidates,viewport} so overlay coverage and selectorHint are visible.",parameters:{type:"object",properties:{page:{},grid:{type:"number"}},required:["page"]}},{name:"snapshotWithLayers",description:"Prepend a @layers header to the snapshot tree and attach a layers field so overlays are visible before the a11y tree.",parameters:{type:"object",properties:{page:{},options:{type:"object"}},required:["page"]}},{name:"emulate",description:"Apply a DEVICE_PRESETS name, a custom metrics object, or null to restore the original UA captured on first call.",parameters:{type:"object",properties:{page:{},preset:{}},required:["page","preset"]}},{name:"createRoutes",description:"Install page request interception; Fetch.enable is sent only on the first route(); interception is fingerprintable, keep it off by default.",parameters:{type:"object",properties:{page:{}},required:["page"]}},{name:"route.continue",description:"Continue an intercepted request, optionally overriding url, method, headers, or postData.",parameters:{type:"object",properties:{url:{type:"string"},method:{type:"string"},headers:{type:"object"},postData:{}}}},{name:"route.fulfill",description:"Fulfill an intercepted request with {status,headers,contentType,body} instead of hitting the network.",parameters:{type:"object",properties:{status:{type:"number"},headers:{type:"object"},contentType:{type:"string"},body:{}}}},{name:"route.abort",description:"Abort an intercepted request with a CDP errorReason (defaults to Failed).",parameters:{type:"object",properties:{reason:{type:"string"}}}}];var MODIFIER_KEYS2=new Set(["Alt","Control","Meta","Shift"]);function splitModifiers(keys=[]){const modifiers=keys.filter((key)=>MODIFIER_KEYS2.has(key)||/^(cmd|command|ctrl|option|controlormeta)$/i.test(key));const rest=keys.filter((key)=>!modifiers.includes(key));return{modifiers,rest}}function createCua(page){async function holdModifiers(keys,fn){const{modifiers}=splitModifiers(keys);for(const key of modifiers)await page.keyboard.down(key);try{return await fn()}finally{for(const key of[...modifiers].reverse())await page.keyboard.up(key)}}return{page,async click({x,y,button="left",keypress}){await holdModifiers(keypress,()=>page.mouse.click(x,y,{button}))},async doubleClick({x,y,keypress}){await holdModifiers(keypress,()=>page.mouse.click(x,y,{clickCount:2}))},async drag({path,keys}){if(!Array.isArray(path)||path.length<2){throw new TypeError("cua.drag requires path with at least two points")}await holdModifiers(keys,async()=>{const[first,...rest]=path;await page.mouse.move(first.x,first.y);await page.mouse.down();try{for(const point of rest)await page.mouse.move(point.x,point.y)}finally{await page.mouse.up()}})},async getVisibleScreenshot(){const buffer=await page.screenshot({type:"png"});return buffer.toString("base64")},async keypress({keys}){if(!Array.isArray(keys)||keys.length===0){throw new TypeError("cua.keypress requires a non-empty keys array")}await page.keyboard.press(keys.join("+"))},async move({x,y,keys}){await holdModifiers(keys,()=>page.mouse.move(x,y))},async scroll({x,y,scrollX,scrollY,keypress}){await holdModifiers(keypress,async()=>{await page.mouse.move(x,y);await page.mouse.wheel(scrollX,scrollY)})},async type({text}){await page.keyboard.type(text)}}}import{spawn as spawn3}from"node:child_process";import{mkdtempSync,writeFileSync,rmSync}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import path7 from"node:path";var MAX_TIMER_MS=2147483647;var STOP=Symbol("wait stopped");async function waitForCaptcha(page,{until,timeoutMs=1e4,pollMs=100,signal}={}){if(typeof until!=="function")throw new TypeError("until must be a function");if(!Number.isFinite(timeoutMs)||timeoutMs<0||timeoutMs>MAX_TIMER_MS){throw new RangeError("timeoutMs must be between 0 and 2147483647")}if(!Number.isFinite(pollMs)||pollMs<=0||pollMs>MAX_TIMER_MS){throw new RangeError("pollMs must be greater than 0 and at most 2147483647")}if(signal!==undefined&&(typeof signal?.aborted!=="boolean"||typeof signal.addEventListener!=="function"||typeof signal.removeEventListener!=="function")){throw new TypeError("signal must be AbortSignal-compatible")}const started=performance.now();const deadline=started+timeoutMs;const operation=new AbortController;let deadlineTimer;let pollTimer;let stop;const stopped=new Promise((resolve)=>{stop=()=>resolve(STOP)});const terminal=()=>signal?.aborted?"cancelled":performance.now()>=deadline?"timed_out":null;const result=(outcome)=>({outcome,elapsedMs:performance.now()-started});const scheduleDeadline=()=>{const remaining=deadline-performance.now();if(remaining<=0)stop();else deadlineTimer=setTimeout(scheduleDeadline,Math.ceil(remaining))};try{const initial=terminal();if(initial)return result(initial);signal?.addEventListener("abort",stop,{once:true});scheduleDeadline();for(;;){let accepted;try{accepted=await Promise.race([Promise.resolve().then(()=>terminal()?STOP:until(page,{signal:operation.signal})),stopped])}catch(error){const outcome=terminal();if(outcome)return result(outcome);throw error}const outcome=terminal();if(outcome)return result(outcome);if(accepted===true)return result("matched");await Promise.race([new Promise((resolve)=>{pollTimer=setTimeout(resolve,Math.ceil(Math.min(pollMs,deadline-performance.now())))}),stopped]);clearTimeout(pollTimer);const afterDelay=terminal();if(afterDelay)return result(afterDelay)}}finally{clearTimeout(deadlineTimer);clearTimeout(pollTimer);signal?.removeEventListener("abort",stop);operation.abort();stop()}}var DEFAULT_DRAG_STEPS=20;var POST_ACTION_SETTLE_MS=3000;function validatePoint(point){if(!Number.isFinite(point?.x)||!Number.isFinite(point?.y)){throw new TypeError("point coordinates must be finite numbers")}}function validateSteps(steps){if(!Number.isSafeInteger(steps)||steps<=0){throw new RangeError("steps must be a positive safe integer")}}function validateSettleMs(value){if(!Number.isFinite(value)||value<0||value>2147483647){throw new RangeError("settleMs must be between 0 and 2147483647")}}var MACOS_VISION_OCR_SWIFT=`
1485
1476
  import Vision
1486
1477
  import AppKit
1487
1478
  let path = CommandLine.arguments[1]
@@ -1496,31 +1487,31 @@ let text = (request.results ?? [])
1496
1487
  .compactMap { $0.topCandidates(1).first?.string }
1497
1488
  .joined(separator: " ")
1498
1489
  print(text)
1499
- `;async function macOSVisionOcr(pngBuffer){if(process.platform!=="darwin"){throw new Error("macOSVisionOcr is only available on macOS; pass a custom ocr(buffer) instead")}const dir=mkdtempSync(path4.join(tmpdir2(),"omowright-ocr-"));try{const imagePath=path4.join(dir,"region.png");const scriptPath=path4.join(dir,"ocr.swift");writeFileSync(imagePath,pngBuffer);writeFileSync(scriptPath,MACOS_VISION_OCR_SWIFT);return await new Promise((resolve,reject)=>{const child=spawn2("swift",[scriptPath,imagePath],{stdio:["ignore","pipe","pipe"]});let stdout="";let stderr="";child.stdout.on("data",(chunk)=>{stdout+=chunk});child.stderr.on("data",(chunk)=>{stderr+=chunk});child.on("error",reject);child.on("close",(code)=>{if(code===0){const text=stdout.trim();resolve(text.length>0?text:null)}else{reject(new Error(`Vision OCR failed (exit ${code}): ${stderr.trim()}`))}})})}finally{rmSync(dir,{recursive:true,force:true})}}function createCaptcha(page,options={}){const ocr=options.ocr??macOSVisionOcr;function centerOf(bounds){validatePoint(bounds);if(!Number.isFinite(bounds.width)||bounds.width<=0||!Number.isFinite(bounds.height)||bounds.height<=0||!Number.isFinite(bounds.x+bounds.width)||!Number.isFinite(bounds.y+bounds.height)){throw new RangeError("bounds must have positive finite dimensions and finite edges")}return{x:bounds.x+bounds.width/2,y:bounds.y+bounds.height/2}}async function settleAndSnapshot(settleMs){await new Promise((resolve)=>setTimeout(resolve,settleMs));return compactSnapshot(await page.snapshot())}return{page,waitFor(opts){return waitForCaptcha(page,opts)},async click(bounds,opts={}){const center=centerOf(bounds);const point=opts.point===undefined?center:opts.point;validatePoint(point);if(point.x<bounds.x||point.x>=bounds.x+bounds.width||point.y<bounds.y||point.y>=bounds.y+bounds.height){throw new RangeError("point must be inside bounds")}const settleMs=opts.settleMs===undefined?POST_ACTION_SETTLE_MS:opts.settleMs;validateSettleMs(settleMs);if(opts.approachSteps!==undefined){validateSteps(opts.approachSteps);await page.mouse.move(point.x,point.y,{steps:opts.approachSteps})}await page.mouse.click(point.x,point.y);return settleAndSnapshot(settleMs)},async drag(from,to,opts={}){validatePoint(from);validatePoint(to);const steps=opts.steps===undefined?DEFAULT_DRAG_STEPS:opts.steps;validateSteps(steps);const settleMs=opts.settleMs===undefined?POST_ACTION_SETTLE_MS:opts.settleMs;validateSettleMs(settleMs);await page.mouse.move(from.x,from.y);await page.mouse.down();try{await page.mouse.move(to.x,to.y,{steps})}finally{await page.mouse.up()}return settleAndSnapshot(settleMs)},async readText(bounds){const buffer=await page.screenshot(bounds?{type:"png",clip:bounds}:{type:"png"});return ocr(buffer)}}}var EVENT_NAMES=["tabOpened","tabClosed","popupOpened","downloadStarted","downloadProgress","downloadFinished"];var BROWSER_EVENT_NAMES=Object.freeze([...EVENT_NAMES]);var DEFAULT_TIMEOUT=30000;var TERMINAL_LIMIT=4096;function pageTarget(info){return info?.type==="page"&&info?.targetId?info:null}function normalizeTarget(info){return{targetId:String(info.targetId),type:"page",url:info.url??"about:blank",title:info.title??"",openerId:info.openerId??null,openerFrameId:info.openerFrameId??null,browserContextId:info.browserContextId??null,attached:Boolean(info.attached),subtype:info.subtype??null}}function errorValue(value){return value instanceof Error?value:Error(String(value))}class BrowserEventBridge{#cdp;#options;#listeners=new Map;#unsubscribers=[];#targetInfos=new Map;#crashes=new Map;#downloads=new Map;#terminalDownloads=new Map;#terminal=new Set;#frameToTarget=new Map;#sessionToTarget=new Map;#waits=new Set;#disposed=false;#explicitDispose=false;ready;constructor(connection,options){if(!connection?.cdp)throw new TypeError("createEvents requires a browser connection");this.#cdp=connection.cdp;this.#options=this.#validate(options);this.#register();this.ready=this.#initialize()}#validate(options){const behavior=options.downloadBehavior??"default";if(!["default","allow","deny","allowAndName"].includes(behavior))throw new TypeError("Invalid downloadBehavior");if(behavior==="allow"&&!pathIsAbsolute(options.downloadPath))throw new TypeError("downloadPath must be an absolute path for allow");return{...options,downloadBehavior:behavior}}#register(){const on=(method,fn)=>this.#unsubscribers.push(this.#cdp.on(method,fn));on("Target.targetCreated",(info)=>this.#created(info,false));on("Target.targetDestroyed",(info)=>this.#destroyed(info));on("Target.targetInfoChanged",(info)=>{const target=pageTarget(info?.targetInfo);if(target&&this.#targetInfos.has(target.targetId))this.#targetInfos.set(target.targetId,normalizeTarget(target))});on("Target.targetCrashed",(info)=>{if(info?.targetId)this.#crashes.set(info.targetId,{status:info.status??"",errorCode:info.errorCode??0})});on("Target.attachedToTarget",(info,meta)=>{const targetId=info?.targetInfo?.targetId;const sessionId=info?.sessionId??meta?.sessionId;if(targetId&&sessionId){this.#sessionToTarget.set(sessionId,targetId)}});on("Target.detachedFromTarget",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId)this.#sessionToTarget.delete(sessionId)});on("Browser.downloadWillBegin",(info)=>this.#downloadBegin(info));on("Browser.downloadProgress",(info)=>this.#downloadProgress(info));on("Page.frameAttached",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId&&info?.frameId)this.#mapFrame(info.frameId,sessionId)});on("Page.frameNavigated",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId&&info?.frame?.id)this.#mapFrame(info.frame.id,sessionId)});if(this.#cdp.transportEvents?.on){this.#unsubscribers.push(this.#cdp.transportEvents.on("disconnected",()=>{this.#disconnectDownloads();this.#cancelWaits(Error("Browser transport disconnected"))}));this.#unsubscribers.push(this.#cdp.transportEvents.on("reconnected",()=>{this.#reconcile().catch((error)=>console.warn("[events] target reconciliation failed",error));this.#configureDownloads().catch((error)=>console.warn("[events] download reconfiguration failed",error))}))}}async#initialize(){await this.#cdp.ensureConnected();await this.#cdp.send("Target.setDiscoverTargets",{discover:true});const result=await this.#cdp.send("Target.getTargets");await this.#configureDownloads();const targets=(result?.targetInfos??[]).filter((info)=>pageTarget(info));targets.sort((a,b)=>Boolean(a.openerId)-Boolean(b.openerId));for(const info of targets)this.#created(info,true)}async#reconcile(){const result=await this.#cdp.send("Target.getTargets");const current=new Set((result?.targetInfos??[]).filter((info)=>pageTarget(info)).map((info)=>String(info.targetId)));for(const id of[...this.#targetInfos.keys()])if(!current.has(id))this.#destroyed({targetId:id});const targets=(result?.targetInfos??[]).filter((info)=>pageTarget(info));targets.sort((a,b)=>Boolean(a.openerId)-Boolean(b.openerId));for(const info of targets)this.#created(info,true)}async#configureDownloads(){const params={behavior:this.#options.downloadBehavior,eventsEnabled:true};if(this.#options.downloadBehavior==="allow"||this.#options.downloadBehavior==="allowAndName")params.downloadPath=this.#options.downloadPath;await this.#cdp.send("Browser.setDownloadBehavior",params)}#mapFrame(frameId,sessionId){const targetId=this.#sessionToTarget.get(sessionId)??[...this.#targetInfos.values()].find((info)=>info.attached&&info.targetId===sessionId)?.targetId;if(targetId)this.#frameToTarget.set(frameId,targetId)}#created(info,initial){const target=pageTarget(info?.targetInfo??info);if(!target)return;const normalized=normalizeTarget(target);const id=normalized.targetId;if(this.#targetInfos.has(id))return;this.#targetInfos.set(id,normalized);const popup=Boolean(normalized.openerId&&this.#targetInfos.has(normalized.openerId));this.#dispatch("tabOpened",{...normalized,popup,initial:Boolean(initial)});if(popup)this.#dispatch("popupOpened",{targetId:id,openerTargetId:normalized.openerId,openerFrameId:normalized.openerFrameId,url:normalized.url,title:normalized.title,initial:Boolean(initial)})}#destroyed(info){const id=info?.targetId;const last=this.#targetInfos.get(id);if(!last)return;this.#targetInfos.delete(id);const crash=this.#crashes.get(id)??null;this.#crashes.delete(id);for(const[frame,targetId]of this.#frameToTarget)if(targetId===id)this.#frameToTarget.delete(frame);this.#dispatch("tabClosed",{targetId:id,reason:crash?"crashed":"destroyed",lastKnown:last,crash})}#rememberTerminal(guid){this.#terminal.delete(guid);this.#terminal.add(guid);if(this.#terminal.size>TERMINAL_LIMIT){const oldest=this.#terminal.values().next().value;this.#terminal.delete(oldest);this.#terminalDownloads.delete(oldest)}}#downloadBegin(info={}){if(!info.guid||this.#terminal.has(info.guid))return;const record={guid:info.guid,url:info.url??null,suggestedFilename:info.suggestedFilename??"",frameId:info.frameId??null,targetId:this.#frameToTarget.get(info.frameId)??null,totalBytes:0,receivedBytes:0,filePath:null};this.#downloads.set(info.guid,record);this.#dispatch("downloadStarted",{guid:record.guid,url:record.url,suggestedFilename:record.suggestedFilename,frameId:record.frameId,targetId:record.targetId})}#downloadProgress(info={}){if(!info.guid)return;const alreadyTerminal=this.#terminal.has(info.guid);const record=this.#downloads.get(info.guid)??this.#terminalDownloads.get(info.guid);if(!record)return;Object.assign(record,{totalBytes:Number(info.totalBytes??0),receivedBytes:Number(info.receivedBytes??0),filePath:info.filePath??null});this.#dispatch("downloadProgress",{guid:info.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:info.state,filePath:record.filePath,targetId:record.targetId});if((info.state==="completed"||info.state==="canceled")&&!alreadyTerminal){this.#rememberTerminal(info.guid);this.#downloads.delete(info.guid);this.#terminalDownloads.set(info.guid,record);this.#dispatch("downloadFinished",{guid:info.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:info.state,cdpState:info.state,filePath:record.filePath,targetId:record.targetId,error:null})}}#disconnectDownloads(){if(this.#explicitDispose)return;for(const record of this.#downloads.values()){this.#rememberTerminal(record.guid);this.#dispatch("downloadFinished",{guid:record.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:"failed",cdpState:null,filePath:record.filePath,targetId:record.targetId,error:{code:"browserDisconnected",message:"Browser transport disconnected"}})}this.#downloads.clear()}#dispatch(name,payload){const listeners=[...this.#listeners.get(name)??[]];Promise.allSettled(listeners.map((listener)=>Promise.resolve().then(()=>listener(payload)))).then((results)=>results.filter((r)=>r.status==="rejected").forEach((r)=>console.warn(`[events] ${name} listener failed`,r.reason)))}on(name,listener){this.#assertName(name);if(typeof listener!=="function")throw new TypeError("listener must be a function");const set=this.#listeners.get(name)??new Set;set.add(listener);this.#listeners.set(name,set);return()=>this.off(name,listener)}off(name,listener){this.#assertName(name);this.#listeners.get(name)?.delete(listener)}#cancelWaits(error){for(const cancel of this.#waits)cancel(error);this.#waits.clear()}waitForEvent(name,options={}){this.#assertName(name);if(this.#disposed)return Promise.reject(Error("Events bridge is disposed"));const timeout=options.timeout??DEFAULT_TIMEOUT;return new Promise((resolve,reject)=>{let done=false;let timer;const off=this.on(name,async(value)=>{try{if(options.predicate&&!await options.predicate(value))return;if(done)return;done=true;clearTimeout(timer);this.#waits.delete(cancel);off();resolve(value)}catch(error){if(!done){done=true;clearTimeout(timer);this.#waits.delete(cancel);off();reject(errorValue(error))}}});const cancel=(error)=>{if(!done){done=true;clearTimeout(timer);this.#waits.delete(cancel);off();reject(error??Error("Events bridge disposed"))}};this.#waits.add(cancel);timer=setTimeout(()=>cancel(Error(`Timed out waiting for browser event "${name}"`)),timeout)})}#assertName(name){if(!EVENT_NAMES.includes(name))throw new TypeError(`Unknown browser event: ${String(name)}`)}async dispose(){if(this.#disposed)return;this.#disposed=true;this.#explicitDispose=true;this.#cancelWaits();for(const off of this.#unsubscribers)off();this.#unsubscribers=[];this.#listeners.clear();await this.ready.catch(()=>{})}}function pathIsAbsolute(value){return typeof value==="string"&&(value.startsWith("/")||/^[A-Za-z]:[\\/]/.test(value))}function createEvents(connection,options={}){return new BrowserEventBridge(connection,options)}init_agent_tabs();init_viewport();import{randomUUID}from"node:crypto";import path7 from"node:path";import{mkdir as mkdir4,open as open3,readFile as readFile2,rename,lstat,chmod as chmod2}from"node:fs/promises";import{homedir}from"node:os";import{TextDecoder as TextDecoder2}from"node:util";import{mkdirSync}from"node:fs";import path6 from"node:path";import{tmpdir as tmpdir3}from"node:os";import{existsSync,readFileSync as readFileSync2}from"node:fs";import path5 from"node:path";var DatabaseCtor;async function loadSqlite(){if(DatabaseCtor)return DatabaseCtor;try{const mod=await import("node:sqlite");DatabaseCtor=(file)=>new mod.DatabaseSync(file,{readOnly:true,readBigInts:true})}catch{const mod=await import("bun:sqlite");DatabaseCtor=(file)=>new mod.Database(file,{readonly:true})}return DatabaseCtor}var CHROME_EPOCH_OFFSET_MS=11644473600000;var chromeTimeToMs=(time)=>Number(BigInt(time)/1000n)-CHROME_EPOCH_OFFSET_MS;var msToChromeTime=(ms)=>BigInt(Math.floor((ms+CHROME_EPOCH_OFFSET_MS)*1000));var EXTENSION_BRIDGE_REQUIRED="requires the extension bridge in standalone OmOWright";function createProfileApis(profilePath){function profileDir(){if(!profilePath){throw new UnsupportedOperationError("chrome.bookmarks/history/topSites need a profilePath (the browser's user-data-dir); pass it to createChromeApi(connection, { profilePath })")}return path5.join(profilePath,"Default")}async function openDb(fileName){const file=path5.join(profileDir(),fileName);if(!existsSync(file))return null;const ctor=await loadSqlite();return ctor(file)}async function withDb(fileName,fn){const db=await openDb(fileName);if(!db)return[];try{return fn(db)}finally{db.close()}}function bookmarkRoots(){const file=path5.join(profileDir(),"Bookmarks");if(!existsSync(file))return[];const parsed=JSON.parse(readFileSync2(file,"utf8"));return Object.values(parsed.roots??{}).filter((node)=>node&&typeof node==="object"&&node.id)}function walkBookmarks(nodes,visit,acc=[]){for(const node of nodes){visit(node,acc);if(Array.isArray(node.children))walkBookmarks(node.children,visit,acc)}return acc}function findBookmark(id){for(const root of bookmarkRoots()){const found=walkBookmarks([root],(node,acc)=>{if(node.id===String(id))acc.push(node)});if(found.length>0)return found[0]}return null}function toBookmark(node){const out={id:node.id,title:node.name??"",type:node.type};if(node.url)out.url=node.url;if(node.date_added)out.dateAdded=chromeTimeToMs(node.date_added);if(node.children)out.children=node.children.map(toBookmark);return out}const bookmarks={async get(idOrIdList){const ids=Array.isArray(idOrIdList)?idOrIdList:[idOrIdList];return ids.map(findBookmark).filter(Boolean).map(toBookmark)},async getChildren(id){const node=findBookmark(id);return(node?.children??[]).map(toBookmark)},async getRecent(numberOfItems){const urls=walkBookmarks(bookmarkRoots(),(node,acc)=>{if(node.type==="url")acc.push(node)});return urls.sort((a,b)=>Number(b.date_added??0)-Number(a.date_added??0)).slice(0,numberOfItems).map(toBookmark)},async getSubTree(id){const node=findBookmark(id);return node?[toBookmark(node)]:[]},async getTree(){return bookmarkRoots().map(toBookmark)},async search(query){const needle=typeof query==="string"?query.toLowerCase():(query.query??"").toLowerCase();const url=typeof query==="object"?query.url?.toLowerCase():undefined;const title=typeof query==="object"?query.title?.toLowerCase():undefined;return walkBookmarks(bookmarkRoots(),(node,acc)=>{if(node.type!=="url")return;const name=(node.name??"").toLowerCase();const href=(node.url??"").toLowerCase();const ok=needle&&(name.includes(needle)||href.includes(needle))||url&&href.includes(url)||title&&name.includes(title);if(ok)acc.push(node)}).map(toBookmark)},async create(){throw new UnsupportedOperationError(`chrome.bookmarks.create ${EXTENSION_BRIDGE_REQUIRED}`)},async update(){throw new UnsupportedOperationError(`chrome.bookmarks.update ${EXTENSION_BRIDGE_REQUIRED}`)},async move(){throw new UnsupportedOperationError(`chrome.bookmarks.move ${EXTENSION_BRIDGE_REQUIRED}`)},async remove(){throw new UnsupportedOperationError(`chrome.bookmarks.remove ${EXTENSION_BRIDGE_REQUIRED}`)},async removeTree(){throw new UnsupportedOperationError(`chrome.bookmarks.removeTree ${EXTENSION_BRIDGE_REQUIRED}`)}};const history={async search(query){const text=`%${query.text??""}%`;const start=query.startTime!=null?msToChromeTime(query.startTime):0n;const end=query.endTime!=null?msToChromeTime(query.endTime):99999999999999999n;const max=query.maxResults??100;return await withDb("History",(db)=>db.prepare(`SELECT id, url, title, visit_count, last_visit_time FROM urls
1490
+ `;async function macOSVisionOcr(pngBuffer){if(process.platform!=="darwin"){throw new Error("macOSVisionOcr is only available on macOS; pass a custom ocr(buffer) instead")}const dir=mkdtempSync(path7.join(tmpdir2(),"omowright-ocr-"));try{const imagePath=path7.join(dir,"region.png");const scriptPath=path7.join(dir,"ocr.swift");writeFileSync(imagePath,pngBuffer);writeFileSync(scriptPath,MACOS_VISION_OCR_SWIFT);return await new Promise((resolve,reject)=>{const child=spawn3("swift",[scriptPath,imagePath],{stdio:["ignore","pipe","pipe"]});let stdout="";let stderr="";child.stdout.on("data",(chunk)=>{stdout+=chunk});child.stderr.on("data",(chunk)=>{stderr+=chunk});child.on("error",reject);child.on("close",(code)=>{if(code===0){const text=stdout.trim();resolve(text.length>0?text:null)}else{reject(new Error(`Vision OCR failed (exit ${code}): ${stderr.trim()}`))}})})}finally{rmSync(dir,{recursive:true,force:true})}}function createCaptcha(page,options={}){const ocr=options.ocr??macOSVisionOcr;function centerOf(bounds){validatePoint(bounds);if(!Number.isFinite(bounds.width)||bounds.width<=0||!Number.isFinite(bounds.height)||bounds.height<=0||!Number.isFinite(bounds.x+bounds.width)||!Number.isFinite(bounds.y+bounds.height)){throw new RangeError("bounds must have positive finite dimensions and finite edges")}return{x:bounds.x+bounds.width/2,y:bounds.y+bounds.height/2}}async function settleAndSnapshot(settleMs){await new Promise((resolve)=>setTimeout(resolve,settleMs));return compactSnapshot(await page.snapshot())}return{page,waitFor(opts){return waitForCaptcha(page,opts)},async click(bounds,opts={}){const center=centerOf(bounds);const point=opts.point===undefined?center:opts.point;validatePoint(point);if(point.x<bounds.x||point.x>=bounds.x+bounds.width||point.y<bounds.y||point.y>=bounds.y+bounds.height){throw new RangeError("point must be inside bounds")}const settleMs=opts.settleMs===undefined?POST_ACTION_SETTLE_MS:opts.settleMs;validateSettleMs(settleMs);if(opts.approachSteps!==undefined){validateSteps(opts.approachSteps);await page.mouse.move(point.x,point.y,{steps:opts.approachSteps})}await page.mouse.click(point.x,point.y);return settleAndSnapshot(settleMs)},async drag(from,to,opts={}){validatePoint(from);validatePoint(to);const steps=opts.steps===undefined?DEFAULT_DRAG_STEPS:opts.steps;validateSteps(steps);const settleMs=opts.settleMs===undefined?POST_ACTION_SETTLE_MS:opts.settleMs;validateSettleMs(settleMs);await page.mouse.move(from.x,from.y);await page.mouse.down();try{await page.mouse.move(to.x,to.y,{steps})}finally{await page.mouse.up()}return settleAndSnapshot(settleMs)},async readText(bounds){const buffer=await page.screenshot(bounds?{type:"png",clip:bounds}:{type:"png"});return ocr(buffer)}}}var EVENT_NAMES=["tabOpened","tabClosed","popupOpened","downloadStarted","downloadProgress","downloadFinished"];var BROWSER_EVENT_NAMES=Object.freeze([...EVENT_NAMES]);var DEFAULT_TIMEOUT=30000;var TERMINAL_LIMIT=4096;function pageTarget(info){return info?.type==="page"&&info?.targetId?info:null}function normalizeTarget(info){return{targetId:String(info.targetId),type:"page",url:info.url??"about:blank",title:info.title??"",openerId:info.openerId??null,openerFrameId:info.openerFrameId??null,browserContextId:info.browserContextId??null,attached:Boolean(info.attached),subtype:info.subtype??null}}function errorValue(value){return value instanceof Error?value:Error(String(value))}class BrowserEventBridge{#cdp;#options;#listeners=new Map;#unsubscribers=[];#targetInfos=new Map;#crashes=new Map;#downloads=new Map;#terminalDownloads=new Map;#terminal=new Set;#frameToTarget=new Map;#sessionToTarget=new Map;#waits=new Set;#disposed=false;#explicitDispose=false;ready;constructor(connection,options){if(!connection?.cdp)throw new TypeError("createEvents requires a browser connection");this.#cdp=connection.cdp;this.#options=this.#validate(options);this.#register();this.ready=this.#initialize()}#validate(options){const behavior=options.downloadBehavior??"default";if(!["default","allow","deny","allowAndName"].includes(behavior))throw new TypeError("Invalid downloadBehavior");if(behavior==="allow"&&!pathIsAbsolute(options.downloadPath))throw new TypeError("downloadPath must be an absolute path for allow");return{...options,downloadBehavior:behavior}}#register(){const on=(method,fn)=>this.#unsubscribers.push(this.#cdp.on(method,fn));on("Target.targetCreated",(info)=>this.#created(info,false));on("Target.targetDestroyed",(info)=>this.#destroyed(info));on("Target.targetInfoChanged",(info)=>{const target=pageTarget(info?.targetInfo);if(target&&this.#targetInfos.has(target.targetId))this.#targetInfos.set(target.targetId,normalizeTarget(target))});on("Target.targetCrashed",(info)=>{if(info?.targetId)this.#crashes.set(info.targetId,{status:info.status??"",errorCode:info.errorCode??0})});on("Target.attachedToTarget",(info,meta)=>{const targetId=info?.targetInfo?.targetId;const sessionId=info?.sessionId??meta?.sessionId;if(targetId&&sessionId){this.#sessionToTarget.set(sessionId,targetId)}});on("Target.detachedFromTarget",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId)this.#sessionToTarget.delete(sessionId)});on("Browser.downloadWillBegin",(info)=>this.#downloadBegin(info));on("Browser.downloadProgress",(info)=>this.#downloadProgress(info));on("Page.frameAttached",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId&&info?.frameId)this.#mapFrame(info.frameId,sessionId)});on("Page.frameNavigated",(info,meta)=>{const sessionId=info?.sessionId??meta?.sessionId;if(sessionId&&info?.frame?.id)this.#mapFrame(info.frame.id,sessionId)});if(this.#cdp.transportEvents?.on){this.#unsubscribers.push(this.#cdp.transportEvents.on("disconnected",()=>{this.#disconnectDownloads();this.#cancelWaits(Error("Browser transport disconnected"))}));this.#unsubscribers.push(this.#cdp.transportEvents.on("reconnected",()=>{this.#reconcile().catch((error)=>console.warn("[events] target reconciliation failed",error));this.#configureDownloads().catch((error)=>console.warn("[events] download reconfiguration failed",error))}))}}async#initialize(){await this.#cdp.ensureConnected();await this.#cdp.send("Target.setDiscoverTargets",{discover:true});const result=await this.#cdp.send("Target.getTargets");await this.#configureDownloads();const targets=(result?.targetInfos??[]).filter((info)=>pageTarget(info));targets.sort((a,b)=>Boolean(a.openerId)-Boolean(b.openerId));for(const info of targets)this.#created(info,true)}async#reconcile(){const result=await this.#cdp.send("Target.getTargets");const current=new Set((result?.targetInfos??[]).filter((info)=>pageTarget(info)).map((info)=>String(info.targetId)));for(const id of[...this.#targetInfos.keys()])if(!current.has(id))this.#destroyed({targetId:id});const targets=(result?.targetInfos??[]).filter((info)=>pageTarget(info));targets.sort((a,b)=>Boolean(a.openerId)-Boolean(b.openerId));for(const info of targets)this.#created(info,true)}async#configureDownloads(){const params={behavior:this.#options.downloadBehavior,eventsEnabled:true};if(this.#options.downloadBehavior==="allow"||this.#options.downloadBehavior==="allowAndName")params.downloadPath=this.#options.downloadPath;await this.#cdp.send("Browser.setDownloadBehavior",params)}#mapFrame(frameId,sessionId){const targetId=this.#sessionToTarget.get(sessionId)??[...this.#targetInfos.values()].find((info)=>info.attached&&info.targetId===sessionId)?.targetId;if(targetId)this.#frameToTarget.set(frameId,targetId)}#created(info,initial){const target=pageTarget(info?.targetInfo??info);if(!target)return;const normalized=normalizeTarget(target);const id=normalized.targetId;if(this.#targetInfos.has(id))return;this.#targetInfos.set(id,normalized);const popup=Boolean(normalized.openerId&&this.#targetInfos.has(normalized.openerId));this.#dispatch("tabOpened",{...normalized,popup,initial:Boolean(initial)});if(popup)this.#dispatch("popupOpened",{targetId:id,openerTargetId:normalized.openerId,openerFrameId:normalized.openerFrameId,url:normalized.url,title:normalized.title,initial:Boolean(initial)})}#destroyed(info){const id=info?.targetId;const last=this.#targetInfos.get(id);if(!last)return;this.#targetInfos.delete(id);const crash=this.#crashes.get(id)??null;this.#crashes.delete(id);for(const[frame,targetId]of this.#frameToTarget)if(targetId===id)this.#frameToTarget.delete(frame);this.#dispatch("tabClosed",{targetId:id,reason:crash?"crashed":"destroyed",lastKnown:last,crash})}#rememberTerminal(guid){this.#terminal.delete(guid);this.#terminal.add(guid);if(this.#terminal.size>TERMINAL_LIMIT){const oldest=this.#terminal.values().next().value;this.#terminal.delete(oldest);this.#terminalDownloads.delete(oldest)}}#downloadBegin(info={}){if(!info.guid||this.#terminal.has(info.guid))return;const record={guid:info.guid,url:info.url??null,suggestedFilename:info.suggestedFilename??"",frameId:info.frameId??null,targetId:this.#frameToTarget.get(info.frameId)??null,totalBytes:0,receivedBytes:0,filePath:null};this.#downloads.set(info.guid,record);this.#dispatch("downloadStarted",{guid:record.guid,url:record.url,suggestedFilename:record.suggestedFilename,frameId:record.frameId,targetId:record.targetId})}#downloadProgress(info={}){if(!info.guid)return;const alreadyTerminal=this.#terminal.has(info.guid);const record=this.#downloads.get(info.guid)??this.#terminalDownloads.get(info.guid);if(!record)return;Object.assign(record,{totalBytes:Number(info.totalBytes??0),receivedBytes:Number(info.receivedBytes??0),filePath:info.filePath??null});this.#dispatch("downloadProgress",{guid:info.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:info.state,filePath:record.filePath,targetId:record.targetId});if((info.state==="completed"||info.state==="canceled")&&!alreadyTerminal){this.#rememberTerminal(info.guid);this.#downloads.delete(info.guid);this.#terminalDownloads.set(info.guid,record);this.#dispatch("downloadFinished",{guid:info.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:info.state,cdpState:info.state,filePath:record.filePath,targetId:record.targetId,error:null})}}#disconnectDownloads(){if(this.#explicitDispose)return;for(const record of this.#downloads.values()){this.#rememberTerminal(record.guid);this.#dispatch("downloadFinished",{guid:record.guid,totalBytes:record.totalBytes,receivedBytes:record.receivedBytes,state:"failed",cdpState:null,filePath:record.filePath,targetId:record.targetId,error:{code:"browserDisconnected",message:"Browser transport disconnected"}})}this.#downloads.clear()}#dispatch(name,payload){const listeners=[...this.#listeners.get(name)??[]];Promise.allSettled(listeners.map((listener)=>Promise.resolve().then(()=>listener(payload)))).then((results)=>results.filter((r)=>r.status==="rejected").forEach((r)=>console.warn(`[events] ${name} listener failed`,r.reason)))}on(name,listener){this.#assertName(name);if(typeof listener!=="function")throw new TypeError("listener must be a function");const set=this.#listeners.get(name)??new Set;set.add(listener);this.#listeners.set(name,set);return()=>this.off(name,listener)}off(name,listener){this.#assertName(name);this.#listeners.get(name)?.delete(listener)}#cancelWaits(error){for(const cancel of this.#waits)cancel(error);this.#waits.clear()}waitForEvent(name,options={}){this.#assertName(name);if(this.#disposed)return Promise.reject(Error("Events bridge is disposed"));const timeout=options.timeout??DEFAULT_TIMEOUT;return new Promise((resolve,reject)=>{let done=false;let timer;const off=this.on(name,async(value)=>{try{if(options.predicate&&!await options.predicate(value))return;if(done)return;done=true;clearTimeout(timer);this.#waits.delete(cancel);off();resolve(value)}catch(error){if(!done){done=true;clearTimeout(timer);this.#waits.delete(cancel);off();reject(errorValue(error))}}});const cancel=(error)=>{if(!done){done=true;clearTimeout(timer);this.#waits.delete(cancel);off();reject(error??Error("Events bridge disposed"))}};this.#waits.add(cancel);timer=setTimeout(()=>cancel(Error(`Timed out waiting for browser event "${name}"`)),timeout)})}#assertName(name){if(!EVENT_NAMES.includes(name))throw new TypeError(`Unknown browser event: ${String(name)}`)}async dispose(){if(this.#disposed)return;this.#disposed=true;this.#explicitDispose=true;this.#cancelWaits();for(const off of this.#unsubscribers)off();this.#unsubscribers=[];this.#listeners.clear();await this.ready.catch(()=>{})}}function pathIsAbsolute(value){return typeof value==="string"&&(value.startsWith("/")||/^[A-Za-z]:[\\/]/.test(value))}function createEvents(connection,options={}){return new BrowserEventBridge(connection,options)}init_agent_tabs();init_viewport();import{randomUUID as randomUUID4}from"node:crypto";import path10 from"node:path";import{mkdir as mkdir5,open as open5,readFile as readFile5,rename as rename3,lstat,chmod as chmod4}from"node:fs/promises";import{homedir}from"node:os";import{TextDecoder as TextDecoder2}from"node:util";import{mkdirSync}from"node:fs";import path9 from"node:path";import{tmpdir as tmpdir3}from"node:os";import{existsSync,readFileSync as readFileSync2}from"node:fs";import path8 from"node:path";var DatabaseCtor;async function loadSqlite(){if(DatabaseCtor)return DatabaseCtor;try{const mod=await import("node:sqlite");DatabaseCtor=(file)=>new mod.DatabaseSync(file,{readOnly:true,readBigInts:true})}catch{const mod=await import("bun:sqlite");DatabaseCtor=(file)=>new mod.Database(file,{readonly:true})}return DatabaseCtor}var CHROME_EPOCH_OFFSET_MS=11644473600000;var chromeTimeToMs=(time)=>Number(BigInt(time)/1000n)-CHROME_EPOCH_OFFSET_MS;var msToChromeTime=(ms)=>BigInt(Math.floor((ms+CHROME_EPOCH_OFFSET_MS)*1000));var EXTENSION_BRIDGE_REQUIRED="requires the extension bridge in standalone OmOWright";function createProfileApis(profilePath){function profileDir(){if(!profilePath){throw new UnsupportedOperationError("chrome.bookmarks/history/topSites need a profilePath (the browser's user-data-dir); pass it to createChromeApi(connection, { profilePath })")}return path8.join(profilePath,"Default")}async function openDb(fileName){const file=path8.join(profileDir(),fileName);if(!existsSync(file))return null;const ctor=await loadSqlite();return ctor(file)}async function withDb(fileName,fn){const db=await openDb(fileName);if(!db)return[];try{return fn(db)}finally{db.close()}}function bookmarkRoots(){const file=path8.join(profileDir(),"Bookmarks");if(!existsSync(file))return[];const parsed=JSON.parse(readFileSync2(file,"utf8"));return Object.values(parsed.roots??{}).filter((node)=>node&&typeof node==="object"&&node.id)}function walkBookmarks(nodes,visit,acc=[]){for(const node of nodes){visit(node,acc);if(Array.isArray(node.children))walkBookmarks(node.children,visit,acc)}return acc}function findBookmark(id){for(const root of bookmarkRoots()){const found=walkBookmarks([root],(node,acc)=>{if(node.id===String(id))acc.push(node)});if(found.length>0)return found[0]}return null}function toBookmark(node){const out={id:node.id,title:node.name??"",type:node.type};if(node.url)out.url=node.url;if(node.date_added)out.dateAdded=chromeTimeToMs(node.date_added);if(node.children)out.children=node.children.map(toBookmark);return out}const bookmarks={async get(idOrIdList){const ids=Array.isArray(idOrIdList)?idOrIdList:[idOrIdList];return ids.map(findBookmark).filter(Boolean).map(toBookmark)},async getChildren(id){const node=findBookmark(id);return(node?.children??[]).map(toBookmark)},async getRecent(numberOfItems){const urls=walkBookmarks(bookmarkRoots(),(node,acc)=>{if(node.type==="url")acc.push(node)});return urls.sort((a,b)=>Number(b.date_added??0)-Number(a.date_added??0)).slice(0,numberOfItems).map(toBookmark)},async getSubTree(id){const node=findBookmark(id);return node?[toBookmark(node)]:[]},async getTree(){return bookmarkRoots().map(toBookmark)},async search(query){const needle=typeof query==="string"?query.toLowerCase():(query.query??"").toLowerCase();const url=typeof query==="object"?query.url?.toLowerCase():undefined;const title=typeof query==="object"?query.title?.toLowerCase():undefined;return walkBookmarks(bookmarkRoots(),(node,acc)=>{if(node.type!=="url")return;const name=(node.name??"").toLowerCase();const href=(node.url??"").toLowerCase();const ok=needle&&(name.includes(needle)||href.includes(needle))||url&&href.includes(url)||title&&name.includes(title);if(ok)acc.push(node)}).map(toBookmark)},async create(){throw new UnsupportedOperationError(`chrome.bookmarks.create ${EXTENSION_BRIDGE_REQUIRED}`)},async update(){throw new UnsupportedOperationError(`chrome.bookmarks.update ${EXTENSION_BRIDGE_REQUIRED}`)},async move(){throw new UnsupportedOperationError(`chrome.bookmarks.move ${EXTENSION_BRIDGE_REQUIRED}`)},async remove(){throw new UnsupportedOperationError(`chrome.bookmarks.remove ${EXTENSION_BRIDGE_REQUIRED}`)},async removeTree(){throw new UnsupportedOperationError(`chrome.bookmarks.removeTree ${EXTENSION_BRIDGE_REQUIRED}`)}};const history={async search(query){const text=`%${query.text??""}%`;const start=query.startTime!=null?msToChromeTime(query.startTime):0n;const end=query.endTime!=null?msToChromeTime(query.endTime):99999999999999999n;const max=query.maxResults??100;return await withDb("History",(db)=>db.prepare(`SELECT id, url, title, visit_count, last_visit_time FROM urls
1500
1491
  WHERE (url LIKE ? OR title LIKE ?) AND last_visit_time BETWEEN ? AND ?
1501
1492
  ORDER BY last_visit_time DESC LIMIT ?`).all(text,text,start,end,max).map((row)=>({id:String(row.id),url:row.url,title:row.title??"",visitCount:Number(row.visit_count),lastVisitTime:chromeTimeToMs(row.last_visit_time)})))},async getVisits(details){return await withDb("History",(db)=>db.prepare(`SELECT v.id, v.visit_time, v.transition FROM visits v
1502
1493
  JOIN urls u ON u.id = v.url WHERE u.url = ?
1503
1494
  ORDER BY v.visit_time DESC`).all(details.url).map((row)=>({id:String(row.id),url:details.url,visitTime:chromeTimeToMs(row.visit_time),transition:Number(row.transition)})))},async addUrl(){throw new UnsupportedOperationError(`chrome.history.addUrl ${EXTENSION_BRIDGE_REQUIRED}`)},async deleteUrl(){throw new UnsupportedOperationError(`chrome.history.deleteUrl ${EXTENSION_BRIDGE_REQUIRED}`)},async deleteRange(){throw new UnsupportedOperationError(`chrome.history.deleteRange ${EXTENSION_BRIDGE_REQUIRED}`)}};const topSites={async get(){return(await withDb("Top Sites",(db)=>db.prepare(`SELECT url, title, url_rank FROM top_sites ORDER BY url_rank ASC LIMIT 50`).all())).map((row)=>({url:row.url,title:row.title??""}))}};return{bookmarks,history,topSites,withDb}}var EXTENSION_BRIDGE_REQUIRED2="requires the extension bridge in standalone OmOWright";var DOWNLOAD_TIMEOUT_MS=30000;function matchUrlPattern(url,pattern){const patterns=Array.isArray(pattern)?pattern:[pattern];return patterns.some((item)=>{if(!item.includes("*"))return url.startsWith(item);const regex=new RegExp(`^${item.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`);return regex.test(url)})}function createChromeApi(connection,options={}){const profile=createProfileApis(options.profilePath);const cdp=connection.cdp;async function pageTargets(){return(await connection.listTargets()).filter((target)=>target.type==="page")}async function toTab(target){let windowId=0;try{const win=await cdp.send("Browser.getWindowForTarget",{targetId:target.targetId??target.id});windowId=win.windowId}catch{}return{id:target.targetId??target.id,url:target.url??"",title:target.title??"",windowId,active:false,pinned:false,audible:false,discarded:false,groupId:-1,index:-1}}const tabs={async query(queryInfo={}){let targets=await pageTargets();if(queryInfo.url)targets=targets.filter((t)=>matchUrlPattern(t.url??"",queryInfo.url));if(queryInfo.title)targets=targets.filter((t)=>(t.title??"").includes(queryInfo.title));const out=[];for(const target of targets){const tab=await toTab(target);if(queryInfo.windowId!=null&&tab.windowId!==queryInfo.windowId)continue;out.push(tab)}return out},async get(tabId){const targets=await pageTargets();const target=targets.find((t)=>(t.targetId??t.id)===tabId);if(!target)throw new Error(`No tab with id: ${tabId}`);return toTab(target)}};async function collectWindows(queryOptions={}){const byWindow=new Map;for(const target of await pageTargets()){const tab=await toTab(target);const list=byWindow.get(tab.windowId)??[];list.push(tab);byWindow.set(tab.windowId,list)}return[...byWindow.entries()].map(([windowId,windowTabs],index)=>{const win={id:windowId,focused:index===0,type:"normal",state:"normal",alwaysOnTop:false,incognito:false};if(queryOptions.populate)win.tabs=windowTabs;return win})}const windows={async get(windowId,queryOptions={}){const all=await collectWindows(queryOptions);const win=all.find((item)=>item.id===windowId);if(!win)throw new Error(`No window with id: ${windowId}`);return win},async getCurrent(queryOptions={}){const all=await collectWindows(queryOptions);if(all.length===0)throw new Error("No browser window found");return all[0]},async getLastFocused(queryOptions={}){const all=await collectWindows(queryOptions);if(all.length===0)throw new Error("No browser window found");return all[0]},async getAll(queryOptions={}){return collectWindows(queryOptions)}};const downloads={async search(query={}){return profile.withDb("History",(db)=>{const rows=db.prepare(`SELECT d.id, d.target_path, d.start_time, d.received_bytes, d.total_bytes, d.state,
1504
1495
  (SELECT url FROM downloads_url_chains c WHERE c.id = d.id AND c.chain_index = 0) AS url
1505
- FROM downloads d ORDER BY d.start_time DESC LIMIT ?`).all(query.limit??100);return rows.map((row)=>({id:Number(row.id),url:row.url??"",filename:row.target_path,startTime:row.start_time?new Date(chromeTimeToMs(row.start_time)).toISOString():null,bytesReceived:Number(row.received_bytes),totalBytes:Number(row.total_bytes),state:Number(row.state)===1?"complete":Number(row.state)===2?"canceled":Number(row.state)===3?"interrupted":"in_progress"})).filter((item)=>!query.url||item.url.includes(query.url)).filter((item)=>!query.filename||item.filename.includes(query.filename))})},async download(downloadOptions){const downloadDir=options.downloadDir??path6.join(tmpdir3(),"omowright-downloads");mkdirSync(downloadDir,{recursive:true});let resolveBegin;let resolveDone;let rejectDone;const began=new Promise((resolve)=>{resolveBegin=resolve});const done=new Promise((resolve,reject)=>{resolveDone=resolve;rejectDone=reject});const offBegin=cdp.on("Browser.downloadWillBegin",(params)=>resolveBegin(params));const offProgress=cdp.on("Browser.downloadProgress",(params)=>{if(params.state==="completed")resolveDone(params);else if(params.state==="canceled")rejectDone(new Error("Download was canceled"))});const timer=setTimeout(()=>rejectDone(new Error(`chrome.downloads.download timed out after ${DOWNLOAD_TIMEOUT_MS}ms`)),DOWNLOAD_TIMEOUT_MS);const page=await connection.newTab("about:blank");try{await cdp.send("Browser.setDownloadBehavior",{behavior:"allow",downloadPath:downloadDir,eventsEnabled:true});await page.evaluate(`(() => {
1496
+ FROM downloads d ORDER BY d.start_time DESC LIMIT ?`).all(query.limit??100);return rows.map((row)=>({id:Number(row.id),url:row.url??"",filename:row.target_path,startTime:row.start_time?new Date(chromeTimeToMs(row.start_time)).toISOString():null,bytesReceived:Number(row.received_bytes),totalBytes:Number(row.total_bytes),state:Number(row.state)===1?"complete":Number(row.state)===2?"canceled":Number(row.state)===3?"interrupted":"in_progress"})).filter((item)=>!query.url||item.url.includes(query.url)).filter((item)=>!query.filename||item.filename.includes(query.filename))})},async download(downloadOptions){const downloadDir=options.downloadDir??path9.join(tmpdir3(),"omowright-downloads");mkdirSync(downloadDir,{recursive:true});let resolveBegin;let resolveDone;let rejectDone;const began=new Promise((resolve)=>{resolveBegin=resolve});const done=new Promise((resolve,reject)=>{resolveDone=resolve;rejectDone=reject});const offBegin=cdp.on("Browser.downloadWillBegin",(params)=>resolveBegin(params));const offProgress=cdp.on("Browser.downloadProgress",(params)=>{if(params.state==="completed")resolveDone(params);else if(params.state==="canceled")rejectDone(new Error("Download was canceled"))});const timer=setTimeout(()=>rejectDone(new Error(`chrome.downloads.download timed out after ${DOWNLOAD_TIMEOUT_MS}ms`)),DOWNLOAD_TIMEOUT_MS);const page=await connection.newTab("about:blank");try{await cdp.send("Browser.setDownloadBehavior",{behavior:"allow",downloadPath:downloadDir,eventsEnabled:true});await page.evaluate(`(() => {
1506
1497
  const a = document.createElement("a");
1507
1498
  a.href = ${JSON.stringify(downloadOptions.url)};
1508
1499
  document.body.appendChild(a);
1509
1500
  a.click();
1510
- })()`);const begin=await Promise.race([began,done.then(()=>null)]);if(!begin)throw new Error("No download started for the given URL");await done;const filename=downloadOptions.filename??begin.suggestedFilename;return{id:begin.guid,url:begin.url??downloadOptions.url,filename:path6.join(downloadDir,filename??"download"),state:"complete"}}finally{clearTimeout(timer);offBegin();offProgress();await page.close().catch(()=>{})}},async pause(){throw new UnsupportedOperationError(`chrome.downloads.pause ${EXTENSION_BRIDGE_REQUIRED2}`)},async resume(){throw new UnsupportedOperationError(`chrome.downloads.resume ${EXTENSION_BRIDGE_REQUIRED2}`)},async cancel(){throw new UnsupportedOperationError(`chrome.downloads.cancel ${EXTENSION_BRIDGE_REQUIRED2}`)},async erase(){throw new UnsupportedOperationError(`chrome.downloads.erase ${EXTENSION_BRIDGE_REQUIRED2}`)}};return{tabs,windows,downloads,bookmarks:profile.bookmarks,history:profile.history,topSites:profile.topSites}}var HOST_NAME="com.omowright.cloakbridge";var PROTOCOL=1;var MAX_MESSAGE_BYTES=1024*1024;var EVENT_NAMES2=Object.freeze(["notifications.shown","notifications.clicked","notifications.closed","tabGroups.created","tabGroups.updated","tabGroups.moved","tabs.activated","windows.focusChanged"]);var COMMAND_NAMES=Object.freeze(["bookmarks.create","bookmarks.move","bookmarks.remove","history.deleteUrl","history.deleteRange","tabGroups.update","debugger.attach","debugger.detach"]);var MUTATING_COMMANDS=new Set(COMMAND_NAMES);var id=string2().min(1).max(128);var uuid3=string2().regex(/^[0-9a-fA-F-]{16,128}$/);var finite=number2().finite();var color=_enum2(["grey","blue","red","yellow","green","pink","purple","cyan","orange"]);var group=object({id:number2().int().min(0),collapsed:boolean2(),color,title:string2().max(1024).nullable().optional(),windowId:number2().int().min(-1)}).strict();var bookmarkNode=lazy(()=>object({id:string2().min(1),parentId:string2().min(1).optional(),index:number2().int().min(0).optional(),title:string2(),url:string2().optional(),dateAdded:finite.min(0).optional(),dateGroupModified:finite.min(0).optional(),dateLastUsed:finite.min(0).optional(),folderType:string2().optional(),syncing:boolean2().optional(),unmodifiable:string2().optional(),type:_enum2(["bookmark","folder","url"]).optional(),children:array(bookmarkNode).optional()}).strict());var empty=object({}).strict();var payloadSchemas={"notifications.shown":object({notificationId:string2().min(1).max(1024)}).strict(),"notifications.clicked":object({notificationId:string2().min(1).max(1024)}).strict(),"notifications.closed":object({notificationId:string2().min(1).max(1024),byUser:boolean2()}).strict(),"tabGroups.created":object({group}).strict(),"tabGroups.updated":object({group}).strict(),"tabGroups.moved":object({group}).strict(),"tabs.activated":object({tabId:number2().int().min(0),windowId:number2().int().min(-1),previousTabId:number2().int().min(0).optional()}).strict(),"windows.focusChanged":object({windowId:number2().int().min(-1)}).strict()};var commandParams={"bookmarks.create":object({details:object({parentId:string2().min(1).optional(),index:number2().int().min(0).optional(),title:string2().max(8192),url:string2().url().max(8192).optional()}).strict()}).strict(),"bookmarks.move":object({details:object({id:string2().min(1),parentId:string2().min(1).optional(),index:number2().int().min(0).optional()}).strict()}).strict(),"bookmarks.remove":object({details:object({id:string2().min(1)}).strict()}).strict(),"history.deleteUrl":object({details:object({url:string2().url().max(8192)}).strict()}).strict(),"history.deleteRange":object({details:object({startTime:finite.min(0),endTime:finite.min(0)}).strict()}).strict().refine((v)=>v.details.startTime<=v.details.endTime,"startTime must not exceed endTime"),"tabGroups.update":object({details:object({groupId:number2().int().min(0),updateProperties:object({collapsed:boolean2().optional(),color:color.optional(),title:string2().max(1024).nullable().optional()}).strict().refine((v)=>Object.keys(v).length>0,"updateProperties must not be empty")}).strict()}).strict(),"debugger.attach":object({details:object({tabId:number2().int().min(0),requiredVersion:string2().regex(/^\d+\.\d+$/)}).strict()}).strict(),"debugger.detach":object({details:object({tabId:number2().int().min(0)}).strict()}).strict()};var resultSchemas={"bookmarks.create":bookmarkNode,"bookmarks.move":bookmarkNode,"bookmarks.remove":empty,"history.deleteUrl":empty,"history.deleteRange":empty,"tabGroups.update":group,"debugger.attach":object({tabId:number2().int().min(0),attached:literal(true),requiredVersion:string2()}).strict(),"debugger.detach":object({tabId:number2().int().min(0),detached:literal(true)}).strict()};var base={protocol:literal(PROTOCOL)};function unique(values,ctx){if(new Set(values).size!==values.length)ctx.addIssue({code:ZodIssueCode.custom,message:"array entries must be unique"})}var names=(allowed)=>array(_enum2([...allowed])).superRefine(unique);var ExtensionHelloSchema=object({...base,type:literal("hello"),role:literal("extension"),connectionId:id,extensionId:string2().regex(/^[a-p]{32}$/),extensionVersion:string2().min(1).max(64),events:names(EVENT_NAMES2),commands:names(COMMAND_NAMES),maxMessageBytes:number2().int().min(1).max(MAX_MESSAGE_BYTES)}).strict();var HostHelloSchema=object({...base,type:literal("hello"),role:literal("host"),connectionId:id,hostName:literal(HOST_NAME),hostVersion:string2().min(1).max(64),events:names(EVENT_NAMES2),commands:names(COMMAND_NAMES),maxMessageBytes:number2().int().min(1).max(MAX_MESSAGE_BYTES)}).strict();var EventSchema=object({...base,type:literal("event"),connectionId:id,seq:number2().int().min(1),occurredAt:number2().int().min(0),name:_enum2(EVENT_NAMES2),payload:record(string2(),unknown())}).strict().superRefine((v,ctx)=>{if(!payloadSchemas[v.name].safeParse(v.payload).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid event payload"})});var CommandSchema=object({...base,type:literal("command"),requestId:uuid3,name:_enum2(COMMAND_NAMES),params:record(string2(),unknown()),deadlineAt:number2().int().min(0).optional()}).strict().superRefine((v,ctx)=>{if(!commandParams[v.name].safeParse(v.params).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid command parameters"})});var errorSchema=object({code:_enum2(["INVALID_MESSAGE","UNKNOWN_COMMAND","UNSUPPORTED_COMMAND","CHROME_ERROR","DEBUGGER_ERROR","NATIVE_HOST_DISCONNECTED","TIMEOUT","PAYLOAD_TOO_LARGE","INTERNAL_ERROR"]),message:string2().min(1).max(512),details:record(string2(),unknown()).optional()}).strict();var responseNames=[...COMMAND_NAMES,"protocolError"];var ResponseSchema=object({...base,type:literal("response"),requestId:uuid3,name:_enum2(responseNames),ok:boolean2(),result:unknown().optional(),error:errorSchema.optional()}).strict().superRefine((v,ctx)=>{const valid=v.ok?v.result!==undefined&&v.error===undefined&&v.name!=="protocolError":v.error!==undefined&&v.result===undefined;if(!valid)ctx.addIssue({code:ZodIssueCode.custom,message:"response must contain exactly one result or error"});if(v.ok&&resultSchemas[v.name]&&!resultSchemas[v.name].safeParse(v.result).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid command result"})});class BridgeUnavailableError extends Error{constructor(message="Cloak bridge is unavailable"){super(message);this.name="BridgeUnavailableError"}}class BridgeProtocolError extends Error{constructor(message){super(message);this.name="BridgeProtocolError"}}var decoder=new TextDecoder2("utf-8",{fatal:true});var checked=(schema,value,message)=>{const result=schema.safeParse(value);if(!result.success)throw new BridgeProtocolError(message);return result.data};function schemaFor(value){if(value.type==="hello")return value.role==="host"?HostHelloSchema:ExtensionHelloSchema;if(value.type==="event")return EventSchema;if(value.type==="command")return CommandSchema;if(value.type==="response")return ResponseSchema;return null}function encodeFrame(value,maxMessageBytes=MAX_MESSAGE_BYTES){const schema=schemaFor(value);if(schema)checked(schema,value,"invalid outbound message");let json;try{json=JSON.stringify(value)}catch{throw new BridgeProtocolError("invalid JSON")}const body=Buffer.from(json,"utf8");if(body.length===0||body.length>maxMessageBytes)throw new BridgeProtocolError("PAYLOAD_TOO_LARGE");const frame=Buffer.allocUnsafe(4+body.length);frame.writeUInt32LE(body.length,0);body.copy(frame,4);return frame}function decodeFrames(buffer,maxMessageBytes=MAX_MESSAGE_BYTES){const frames=[];let offset=0;while(buffer.length-offset>=4){const length=buffer.readUInt32LE(offset);if(!length||length>maxMessageBytes)throw new BridgeProtocolError("PAYLOAD_TOO_LARGE");if(buffer.length-offset<length+4)break;const body=buffer.subarray(offset+4,offset+4+length);let text;try{text=decoder.decode(body)}catch{throw new BridgeProtocolError("invalid UTF-8")}try{frames.push(JSON.parse(text))}catch{throw new BridgeProtocolError("invalid JSON")}offset+=length+4}return{frames,remainder:buffer.subarray(offset)}}function createNativeMessagingHost({stdin=process.stdin,stdout=process.stdout,stderr=process.stderr,extensionId,hostName=HOST_NAME,maxMessageBytes=MAX_MESSAGE_BYTES,commandTimeoutMs=30000,maxPendingWrites=256,onEvent,onDisconnect}={}){if(!/^[a-p]{32}$/.test(extensionId??""))throw new BridgeProtocolError("a valid extensionId is required");if(!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName)||hostName!==HOST_NAME)throw new BridgeProtocolError("invalid hostName");let buffer=Buffer.alloc(0),closed=false,hello=null,hostConnectionId=null,effectiveMax=maxMessageBytes,lastEventSeq=0,sequence=0,mutationBusy=false;const pending=new Map,listeners=new Map,commandQueue=[],writeQueue=[];let writing=false;const disconnect=(reason)=>{if(closed)return;closed=true;const error=reason instanceof Error?reason:new BridgeUnavailableError(reason??"native host disconnected");for(const item of pending.values()){item.cleanup?.();item.reject(error)}pending.clear();for(const item of commandQueue.splice(0)){item.cleanup?.();item.reject(error)}for(const item of writeQueue.splice(0))item.reject(error);onDisconnect?.(error)};const write=(value)=>{if(closed)return Promise.reject(new BridgeUnavailableError);let frame;try{const schema=schemaFor(value);if(!schema)throw new BridgeProtocolError("invalid outbound message type");checked(schema,value,"invalid outbound message");frame=encodeFrame(value,effectiveMax)}catch(error){return Promise.reject(error)}if(writeQueue.length+(writing?1:0)>=maxPendingWrites)return Promise.reject(new BridgeProtocolError("BOUNDED_TRANSPORT"));return new Promise((resolve,reject)=>{writeQueue.push({frame,resolve,reject});pumpWrites()})};const pumpWrites=()=>{if(writing||closed||!writeQueue.length)return;writing=true;const item=writeQueue.shift();let finished=false;const done=(error)=>{if(finished)return;finished=true;writing=false;if(error){item.reject(error);disconnect(error)}else item.resolve();pumpWrites()};try{const result=stdout.write(item.frame,(error)=>done(error));if(result===false&&stdout.once)stdout.once("error",done)}catch(error){done(error)}};const pumpCommands=()=>{if(closed||mutationBusy||!commandQueue.length)return;const item=commandQueue.shift();item.started=true;mutationBusy=true;pending.set(item.requestId,item);write(item.command).catch((error)=>{if(pending.delete(item.requestId)){item.settled=true;item.cleanup();item.reject(error)}disconnect(error)})};const dispatchEvent=(event)=>{if(!hello||event.connectionId!==hello.connectionId||event.seq<=lastEventSeq||!hello.events.includes(event.name))throw new BridgeProtocolError("invalid event ordering or capability");lastEventSeq=event.seq;try{Promise.resolve(onEvent?.(event)).catch((error)=>stderr.write?.(`bridge listener: ${error.message}
1501
+ })()`);const begin=await Promise.race([began,done.then(()=>null)]);if(!begin)throw new Error("No download started for the given URL");await done;const filename=downloadOptions.filename??begin.suggestedFilename;return{id:begin.guid,url:begin.url??downloadOptions.url,filename:path9.join(downloadDir,filename??"download"),state:"complete"}}finally{clearTimeout(timer);offBegin();offProgress();await page.close().catch(()=>{})}},async pause(){throw new UnsupportedOperationError(`chrome.downloads.pause ${EXTENSION_BRIDGE_REQUIRED2}`)},async resume(){throw new UnsupportedOperationError(`chrome.downloads.resume ${EXTENSION_BRIDGE_REQUIRED2}`)},async cancel(){throw new UnsupportedOperationError(`chrome.downloads.cancel ${EXTENSION_BRIDGE_REQUIRED2}`)},async erase(){throw new UnsupportedOperationError(`chrome.downloads.erase ${EXTENSION_BRIDGE_REQUIRED2}`)}};return{tabs,windows,downloads,bookmarks:profile.bookmarks,history:profile.history,topSites:profile.topSites}}var HOST_NAME="com.omowright.cloakbridge";var PROTOCOL=1;var MAX_MESSAGE_BYTES=1024*1024;var EVENT_NAMES2=Object.freeze(["notifications.shown","notifications.clicked","notifications.closed","tabGroups.created","tabGroups.updated","tabGroups.moved","tabs.activated","windows.focusChanged"]);var COMMAND_NAMES=Object.freeze(["bookmarks.create","bookmarks.move","bookmarks.remove","history.deleteUrl","history.deleteRange","tabGroups.update","debugger.attach","debugger.detach"]);var MUTATING_COMMANDS=new Set(COMMAND_NAMES);var id=string2().min(1).max(128);var uuid3=string2().regex(/^[0-9a-fA-F-]{16,128}$/);var finite=number2().finite();var color=_enum2(["grey","blue","red","yellow","green","pink","purple","cyan","orange"]);var group=object({id:number2().int().min(0),collapsed:boolean2(),color,title:string2().max(1024).nullable().optional(),windowId:number2().int().min(-1)}).strict();var bookmarkNode=lazy(()=>object({id:string2().min(1),parentId:string2().min(1).optional(),index:number2().int().min(0).optional(),title:string2(),url:string2().optional(),dateAdded:finite.min(0).optional(),dateGroupModified:finite.min(0).optional(),dateLastUsed:finite.min(0).optional(),folderType:string2().optional(),syncing:boolean2().optional(),unmodifiable:string2().optional(),type:_enum2(["bookmark","folder","url"]).optional(),children:array(bookmarkNode).optional()}).strict());var empty=object({}).strict();var payloadSchemas={"notifications.shown":object({notificationId:string2().min(1).max(1024)}).strict(),"notifications.clicked":object({notificationId:string2().min(1).max(1024)}).strict(),"notifications.closed":object({notificationId:string2().min(1).max(1024),byUser:boolean2()}).strict(),"tabGroups.created":object({group}).strict(),"tabGroups.updated":object({group}).strict(),"tabGroups.moved":object({group}).strict(),"tabs.activated":object({tabId:number2().int().min(0),windowId:number2().int().min(-1),previousTabId:number2().int().min(0).optional()}).strict(),"windows.focusChanged":object({windowId:number2().int().min(-1)}).strict()};var commandParams={"bookmarks.create":object({details:object({parentId:string2().min(1).optional(),index:number2().int().min(0).optional(),title:string2().max(8192),url:string2().url().max(8192).optional()}).strict()}).strict(),"bookmarks.move":object({details:object({id:string2().min(1),parentId:string2().min(1).optional(),index:number2().int().min(0).optional()}).strict()}).strict(),"bookmarks.remove":object({details:object({id:string2().min(1)}).strict()}).strict(),"history.deleteUrl":object({details:object({url:string2().url().max(8192)}).strict()}).strict(),"history.deleteRange":object({details:object({startTime:finite.min(0),endTime:finite.min(0)}).strict()}).strict().refine((v)=>v.details.startTime<=v.details.endTime,"startTime must not exceed endTime"),"tabGroups.update":object({details:object({groupId:number2().int().min(0),updateProperties:object({collapsed:boolean2().optional(),color:color.optional(),title:string2().max(1024).nullable().optional()}).strict().refine((v)=>Object.keys(v).length>0,"updateProperties must not be empty")}).strict()}).strict(),"debugger.attach":object({details:object({tabId:number2().int().min(0),requiredVersion:string2().regex(/^\d+\.\d+$/)}).strict()}).strict(),"debugger.detach":object({details:object({tabId:number2().int().min(0)}).strict()}).strict()};var resultSchemas={"bookmarks.create":bookmarkNode,"bookmarks.move":bookmarkNode,"bookmarks.remove":empty,"history.deleteUrl":empty,"history.deleteRange":empty,"tabGroups.update":group,"debugger.attach":object({tabId:number2().int().min(0),attached:literal(true),requiredVersion:string2()}).strict(),"debugger.detach":object({tabId:number2().int().min(0),detached:literal(true)}).strict()};var base={protocol:literal(PROTOCOL)};function unique(values,ctx){if(new Set(values).size!==values.length)ctx.addIssue({code:ZodIssueCode.custom,message:"array entries must be unique"})}var names=(allowed)=>array(_enum2([...allowed])).superRefine(unique);var ExtensionHelloSchema=object({...base,type:literal("hello"),role:literal("extension"),connectionId:id,extensionId:string2().regex(/^[a-p]{32}$/),extensionVersion:string2().min(1).max(64),events:names(EVENT_NAMES2),commands:names(COMMAND_NAMES),maxMessageBytes:number2().int().min(1).max(MAX_MESSAGE_BYTES)}).strict();var HostHelloSchema=object({...base,type:literal("hello"),role:literal("host"),connectionId:id,hostName:literal(HOST_NAME),hostVersion:string2().min(1).max(64),events:names(EVENT_NAMES2),commands:names(COMMAND_NAMES),maxMessageBytes:number2().int().min(1).max(MAX_MESSAGE_BYTES)}).strict();var EventSchema=object({...base,type:literal("event"),connectionId:id,seq:number2().int().min(1),occurredAt:number2().int().min(0),name:_enum2(EVENT_NAMES2),payload:record(string2(),unknown())}).strict().superRefine((v,ctx)=>{if(!payloadSchemas[v.name].safeParse(v.payload).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid event payload"})});var CommandSchema=object({...base,type:literal("command"),requestId:uuid3,name:_enum2(COMMAND_NAMES),params:record(string2(),unknown()),deadlineAt:number2().int().min(0).optional()}).strict().superRefine((v,ctx)=>{if(!commandParams[v.name].safeParse(v.params).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid command parameters"})});var errorSchema=object({code:_enum2(["INVALID_MESSAGE","UNKNOWN_COMMAND","UNSUPPORTED_COMMAND","CHROME_ERROR","DEBUGGER_ERROR","NATIVE_HOST_DISCONNECTED","TIMEOUT","PAYLOAD_TOO_LARGE","INTERNAL_ERROR"]),message:string2().min(1).max(512),details:record(string2(),unknown()).optional()}).strict();var responseNames=[...COMMAND_NAMES,"protocolError"];var ResponseSchema=object({...base,type:literal("response"),requestId:uuid3,name:_enum2(responseNames),ok:boolean2(),result:unknown().optional(),error:errorSchema.optional()}).strict().superRefine((v,ctx)=>{const valid=v.ok?v.result!==undefined&&v.error===undefined&&v.name!=="protocolError":v.error!==undefined&&v.result===undefined;if(!valid)ctx.addIssue({code:ZodIssueCode.custom,message:"response must contain exactly one result or error"});if(v.ok&&resultSchemas[v.name]&&!resultSchemas[v.name].safeParse(v.result).success)ctx.addIssue({code:ZodIssueCode.custom,message:"invalid command result"})});class BridgeUnavailableError extends Error{constructor(message="Cloak bridge is unavailable"){super(message);this.name="BridgeUnavailableError"}}class BridgeProtocolError extends Error{constructor(message){super(message);this.name="BridgeProtocolError"}}var decoder=new TextDecoder2("utf-8",{fatal:true});var checked=(schema,value,message)=>{const result=schema.safeParse(value);if(!result.success)throw new BridgeProtocolError(message);return result.data};function schemaFor(value){if(value.type==="hello")return value.role==="host"?HostHelloSchema:ExtensionHelloSchema;if(value.type==="event")return EventSchema;if(value.type==="command")return CommandSchema;if(value.type==="response")return ResponseSchema;return null}function encodeFrame(value,maxMessageBytes=MAX_MESSAGE_BYTES){const schema=schemaFor(value);if(schema)checked(schema,value,"invalid outbound message");let json;try{json=JSON.stringify(value)}catch{throw new BridgeProtocolError("invalid JSON")}const body=Buffer.from(json,"utf8");if(body.length===0||body.length>maxMessageBytes)throw new BridgeProtocolError("PAYLOAD_TOO_LARGE");const frame=Buffer.allocUnsafe(4+body.length);frame.writeUInt32LE(body.length,0);body.copy(frame,4);return frame}function decodeFrames(buffer,maxMessageBytes=MAX_MESSAGE_BYTES){const frames=[];let offset=0;while(buffer.length-offset>=4){const length=buffer.readUInt32LE(offset);if(!length||length>maxMessageBytes)throw new BridgeProtocolError("PAYLOAD_TOO_LARGE");if(buffer.length-offset<length+4)break;const body=buffer.subarray(offset+4,offset+4+length);let text;try{text=decoder.decode(body)}catch{throw new BridgeProtocolError("invalid UTF-8")}try{frames.push(JSON.parse(text))}catch{throw new BridgeProtocolError("invalid JSON")}offset+=length+4}return{frames,remainder:buffer.subarray(offset)}}function createNativeMessagingHost({stdin=process.stdin,stdout=process.stdout,stderr=process.stderr,extensionId,hostName=HOST_NAME,maxMessageBytes=MAX_MESSAGE_BYTES,commandTimeoutMs=30000,maxPendingWrites=256,onEvent,onDisconnect}={}){if(!/^[a-p]{32}$/.test(extensionId??""))throw new BridgeProtocolError("a valid extensionId is required");if(!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName)||hostName!==HOST_NAME)throw new BridgeProtocolError("invalid hostName");let buffer=Buffer.alloc(0),closed=false,hello=null,hostConnectionId=null,effectiveMax=maxMessageBytes,lastEventSeq=0,sequence=0,mutationBusy=false;const pending=new Map,listeners=new Map,commandQueue=[],writeQueue=[];let writing=false;const disconnect=(reason)=>{if(closed)return;closed=true;const error=reason instanceof Error?reason:new BridgeUnavailableError(reason??"native host disconnected");for(const item of pending.values()){item.cleanup?.();item.reject(error)}pending.clear();for(const item of commandQueue.splice(0)){item.cleanup?.();item.reject(error)}for(const item of writeQueue.splice(0))item.reject(error);onDisconnect?.(error)};const write=(value)=>{if(closed)return Promise.reject(new BridgeUnavailableError);let frame;try{const schema=schemaFor(value);if(!schema)throw new BridgeProtocolError("invalid outbound message type");checked(schema,value,"invalid outbound message");frame=encodeFrame(value,effectiveMax)}catch(error){return Promise.reject(error)}if(writeQueue.length+(writing?1:0)>=maxPendingWrites)return Promise.reject(new BridgeProtocolError("BOUNDED_TRANSPORT"));return new Promise((resolve,reject)=>{writeQueue.push({frame,resolve,reject});pumpWrites()})};const pumpWrites=()=>{if(writing||closed||!writeQueue.length)return;writing=true;const item=writeQueue.shift();let finished=false;const done=(error)=>{if(finished)return;finished=true;writing=false;if(error){item.reject(error);disconnect(error)}else item.resolve();pumpWrites()};try{const result=stdout.write(item.frame,(error)=>done(error));if(result===false&&stdout.once)stdout.once("error",done)}catch(error){done(error)}};const pumpCommands=()=>{if(closed||mutationBusy||!commandQueue.length)return;const item=commandQueue.shift();item.started=true;mutationBusy=true;pending.set(item.requestId,item);write(item.command).catch((error)=>{if(pending.delete(item.requestId)){item.settled=true;item.cleanup();item.reject(error)}disconnect(error)})};const dispatchEvent=(event)=>{if(!hello||event.connectionId!==hello.connectionId||event.seq<=lastEventSeq||!hello.events.includes(event.name))throw new BridgeProtocolError("invalid event ordering or capability");lastEventSeq=event.seq;try{Promise.resolve(onEvent?.(event)).catch((error)=>stderr.write?.(`bridge listener: ${error.message}
1511
1502
  `))}catch(error){stderr.write?.(`bridge listener: ${error.message}
1512
1503
  `)}for(const fn of listeners.get(event.name)??[]){try{Promise.resolve(fn(event.payload)).catch((error)=>stderr.write?.(`bridge listener: ${error.message}
1513
1504
  `))}catch(error){stderr.write?.(`bridge listener: ${error.message}
1514
- `)}}};const handle=(raw)=>{if(!hello){const parsed=checked(ExtensionHelloSchema,raw,"extension hello rejected");if(parsed.extensionId!==extensionId)throw new BridgeProtocolError("extension hello rejected");hello=parsed;hostConnectionId=randomUUID();effectiveMax=Math.min(maxMessageBytes,parsed.maxMessageBytes);lastEventSeq=0;return write({protocol:PROTOCOL,type:"hello",role:"host",connectionId:hostConnectionId,hostName,hostVersion:"0.1.0",events:EVENT_NAMES2.filter((x)=>parsed.events.includes(x)),commands:COMMAND_NAMES.filter((x)=>parsed.commands.includes(x)),maxMessageBytes:effectiveMax})}if(raw.type==="event")return dispatchEvent(checked(EventSchema,raw,"invalid event"));if(raw.type==="response"){const parsed=checked(ResponseSchema,raw,"invalid response");if(parsed.name==="protocolError")throw Object.assign(new BridgeProtocolError(parsed.error.message),{code:parsed.error.code,details:parsed.error.details});const item=pending.get(parsed.requestId);if(!item||item.name!==parsed.name)throw new BridgeProtocolError("invalid or unknown response");item.settled=true;pending.delete(parsed.requestId);item.cleanup();mutationBusy=false;if(parsed.ok)item.resolve(parsed.result);else item.reject(Object.assign(new Error(parsed.error.message),{code:parsed.error.code,details:parsed.error.details}));pumpCommands();return}throw new BridgeProtocolError("unexpected message")};const onData=(chunk)=>{try{buffer=Buffer.concat([buffer,Buffer.from(chunk)]);const out=decodeFrames(buffer,effectiveMax);buffer=out.remainder;for(const raw of out.frames)Promise.resolve(handle(raw)).catch((error)=>{stderr.write?.(`bridge: ${error.message}
1505
+ `)}}};const handle=(raw)=>{if(!hello){const parsed=checked(ExtensionHelloSchema,raw,"extension hello rejected");if(parsed.extensionId!==extensionId)throw new BridgeProtocolError("extension hello rejected");hello=parsed;hostConnectionId=randomUUID4();effectiveMax=Math.min(maxMessageBytes,parsed.maxMessageBytes);lastEventSeq=0;return write({protocol:PROTOCOL,type:"hello",role:"host",connectionId:hostConnectionId,hostName,hostVersion:"0.1.0",events:EVENT_NAMES2.filter((x)=>parsed.events.includes(x)),commands:COMMAND_NAMES.filter((x)=>parsed.commands.includes(x)),maxMessageBytes:effectiveMax})}if(raw.type==="event")return dispatchEvent(checked(EventSchema,raw,"invalid event"));if(raw.type==="response"){const parsed=checked(ResponseSchema,raw,"invalid response");if(parsed.name==="protocolError")throw Object.assign(new BridgeProtocolError(parsed.error.message),{code:parsed.error.code,details:parsed.error.details});const item=pending.get(parsed.requestId);if(!item||item.name!==parsed.name)throw new BridgeProtocolError("invalid or unknown response");item.settled=true;pending.delete(parsed.requestId);item.cleanup();mutationBusy=false;if(parsed.ok)item.resolve(parsed.result);else item.reject(Object.assign(new Error(parsed.error.message),{code:parsed.error.code,details:parsed.error.details}));pumpCommands();return}throw new BridgeProtocolError("unexpected message")};const onData=(chunk)=>{try{buffer=Buffer.concat([buffer,Buffer.from(chunk)]);const out=decodeFrames(buffer,effectiveMax);buffer=out.remainder;for(const raw of out.frames)Promise.resolve(handle(raw)).catch((error)=>{stderr.write?.(`bridge: ${error.message}
1515
1506
  `);disconnect(error)})}catch(error){stderr.write?.(`bridge: ${error.message}
1516
- `);disconnect(error)}};stdin.on("data",onData);stdin.once?.("end",()=>disconnect());stdin.once?.("error",disconnect);return{get isConnected(){return!closed&&!!hello},get capabilities(){return{commands:new Set(hello?.commands??[]),events:new Set(hello?.events??[])}},send:write,request(name,params,{signal,timeoutMs=commandTimeoutMs}={}){if(!hello||!hello.commands.includes(name))return Promise.reject(new BridgeUnavailableError(`unsupported bridge command: ${name}`));let command;try{command=checked(CommandSchema,{protocol:PROTOCOL,type:"command",requestId:randomUUID(),name,params},"invalid command parameters")}catch(error){return Promise.reject(error)}return new Promise((resolve,reject)=>{if(commandQueue.length+pending.size>=maxPendingWrites){reject(new BridgeProtocolError("BOUNDED_TRANSPORT"));return}const item={requestId:command.requestId,name,command,resolve,reject,timer:null,abortHandler:null,cleanup:null,settled:false};const cleanup=()=>{clearTimeout(item.timer);if(item.abortHandler){signal?.removeEventListener("abort",item.abortHandler);item.abortHandler=null}};item.cleanup=cleanup;const failIndeterminate=(code,reason=null)=>{if(item.settled)return;item.settled=true;cleanup();if(pending.delete(item.requestId)||commandQueue.includes(item)){const i=commandQueue.indexOf(item);if(i>=0)commandQueue.splice(i,1);item.reject(reason??Object.assign(new Error(`bridge command timed out: ${name}`),{code}))}if(item.started)disconnect(Object.assign(new Error("mutation completion is indeterminate"),{code}))};item.timer=setTimeout(()=>failIndeterminate("TIMEOUT"),timeoutMs);if(signal?.aborted){item.settled=true;cleanup();reject(signal.reason??Object.assign(new Error(`bridge command aborted: ${name}`),{code:"ABORT_ERR"}));return}item.abortHandler=()=>failIndeterminate("ABORT_ERR",signal.reason);signal?.addEventListener("abort",item.abortHandler,{once:true});commandQueue.push(item);pumpCommands()})},on(name,listener){if(!EVENT_NAMES2.includes(name))throw new BridgeProtocolError("invalid event name");const set=listeners.get(name)??new Set;set.add(listener);listeners.set(name,set);return()=>{set.delete(listener);if(!set.size)listeners.delete(name)}},emitEvent(name,payload){if(!hello?.events.includes(name))return Promise.reject(new BridgeUnavailableError("unsupported bridge event"));const checkedPayload=payloadSchemas[name].safeParse(payload);if(!checkedPayload.success)return Promise.reject(new BridgeProtocolError("invalid event payload"));sequence+=1;return write({protocol:PROTOCOL,type:"event",connectionId:hostConnectionId,seq:sequence,occurredAt:Date.now(),name,payload:checkedPayload.data})},close(){disconnect("closed");stdin.removeListener?.("data",onData)}}}var NATIVE_HOST_DIRS={darwin:{chrome:["Library","Application Support","Google","Chrome"],chromium:["Library","Application Support","Chromium"]},linux:{chrome:[".config","google-chrome"],chromium:[".config","chromium"]}};function defaultNativeMessagingHostDir(browser="chrome",platform=process.platform){const byBrowser=NATIVE_HOST_DIRS[platform];if(!byBrowser)throw new BridgeProtocolError(`no default nativeMessagingHostDir on ${platform}; pass nativeMessagingHostDir`);const segments=byBrowser[browser];if(!segments)throw new BridgeProtocolError("custom browser requires nativeMessagingHostDir");return path7.join(homedir(),...segments,"NativeMessagingHosts")}async function secureDirectory(dir){const absolute=path7.resolve(dir);const parts=absolute.split(path7.sep).filter(Boolean);let current=path7.parse(absolute).root;let final;for(const[index,part]of parts.entries()){current=path7.join(current,part);let info=await lstat(current).catch(()=>null);if(!info){await mkdir4(current,{mode:448});info=await lstat(current)}if(current!=="/var"&&(info.isSymbolicLink()||!info.isDirectory()))throw new BridgeProtocolError("nativeMessagingHostDir security rejected");if(current!=="/var"&&info.uid!==process.getuid?.()&&info.uid!==0)throw new BridgeProtocolError("nativeMessagingHostDir ownership rejected");const stickyRootAncestor=index<parts.length-1&&info.uid===0&&(info.mode&512)!==0;if(current!=="/var"&&!stickyRootAncestor&&(info.mode&18)!==0)throw new BridgeProtocolError("nativeMessagingHostDir security rejected");final=info}if(!final||final.uid!==process.getuid?.()&&final.uid!==0)throw new BridgeProtocolError("nativeMessagingHostDir ownership rejected");if((final.mode&63)!==0)await chmod2(absolute,448)}async function secureExecutable(hostPath){const info=await lstat(hostPath).catch(()=>null);if(!info?.isFile()||info.isSymbolicLink()||info.uid!==process.getuid?.()||(info.mode&73)===0||(info.mode&18)!==0)throw new BridgeProtocolError("hostPath must be a securely owned executable file")}async function installNativeMessagingHost({hostName=HOST_NAME,hostPath,extensionId,browser="chrome",nativeMessagingHostDir,force=false,endpointPath}={}){if(endpointPath!==undefined)throw new BridgeProtocolError("endpointPath is not supported");if(hostName!==HOST_NAME||!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName))throw new BridgeProtocolError("invalid hostName");if(!path7.isAbsolute(hostPath??""))throw new BridgeProtocolError("hostPath must be absolute");await secureExecutable(hostPath);if(!/^[a-p]{32}$/.test(extensionId??""))throw new BridgeProtocolError("invalid extensionId");if(!nativeMessagingHostDir&&browser==="cloakbrowser")throw new BridgeProtocolError("CloakBrowser nativeMessagingHostDir must be explicit and verified");const dir=nativeMessagingHostDir??defaultNativeMessagingHostDir(browser);await secureDirectory(dir);const manifest={name:hostName,description:"OmOWright internal CloakBrowser native messaging bridge.",path:hostPath,type:"stdio",allowed_origins:[`chrome-extension://${extensionId}/`]};const file=path7.join(dir,`${hostName}.json`);if(!force&&await lstat(file).catch(()=>null))throw new BridgeProtocolError("registration manifest already exists; use force");const temp=`${file}.${process.pid}.${randomUUID()}.tmp`;const handle=await open3(temp,"wx",384);try{await handle.writeFile(JSON.stringify(manifest,null,2)+`
1517
- `);await handle.sync()}finally{await handle.close()}await rename(temp,file);const parsed=JSON.parse(await readFile2(file,"utf8"));await chmod2(file,384);return{path:file,manifest:parsed}}function createBridgeClient(options={}){return createNativeMessagingHost(options)}function createChromeApi2(connection,options={}){const chrome=createChromeApi(connection,options);const bridge=options.bridge;const request=(wire,params)=>bridge?.isConnected&&bridge.capabilities?.commands?.has(wire)?bridge.request(wire,params):Promise.reject(new UnsupportedOperationError(`chrome.${wire} requires the extension bridge in standalone OmOWright`));chrome.bookmarks.create=(details)=>request("bookmarks.create",{details});chrome.bookmarks.move=(id,details={})=>request("bookmarks.move",{details:{...details,id:String(id)}});chrome.bookmarks.remove=(id)=>request("bookmarks.remove",{details:{id:String(id)}});chrome.history.deleteUrl=(details)=>request("history.deleteUrl",{details});chrome.history.deleteRange=(details)=>request("history.deleteRange",{details});chrome.tabGroups={update:(groupId,updateProperties)=>request("tabGroups.update",{details:{groupId,updateProperties}})};chrome.debugger={attach:(target,requiredVersion)=>request("debugger.attach",{details:{tabId:target.tabId??target,requiredVersion}}),detach:(target)=>request("debugger.detach",{details:{tabId:target.tabId??target}})};const eventMap={notifications:["onShown","onClicked","onClosed"],tabGroups:["onCreated","onUpdated","onMoved"],tabs:["onActivated"],windows:["onFocusChanged"]};for(const[namespace,events]of Object.entries(eventMap)){chrome[namespace]??={};for(const event of events){const wire=`${namespace}.${event.slice(2,3).toLowerCase()+event.slice(3)}`;const subscriptions=new Map;chrome[namespace][event]={addListener(listener){if(!bridge?.on)return;const unsubscribe=bridge.on(wire,(payload)=>listener(...namespace==="notifications"&&event==="onClosed"?[payload.notificationId,payload.byUser]:namespace==="notifications"?[payload.notificationId]:namespace==="tabGroups"?[payload.group]:namespace==="windows"?[payload.windowId]:[payload]));subscriptions.set(listener,unsubscribe);return unsubscribe},removeListener(listener){const unsubscribe=subscriptions.get(listener);if(unsubscribe){unsubscribe();subscriptions.delete(listener)}}}}}return chrome}function sanitizeCookies(cookies){const byKey=new Map;for(const cookie of cookies){const out={name:cookie.name,value:cookie.value,path:cookie.path||"/",secure:Boolean(cookie.secure),httpOnly:Boolean(cookie.httpOnly)};if(cookie.name.startsWith("__Host-")){out.secure=true;out.path="/";out.url=`https://${cookie.domain.replace(/^\./,"")}`}else{out.domain=cookie.domain}if(cookie.expires&&cookie.expires>0)out.expires=cookie.expires;if(cookie.sameSite&&(cookie.sameSite!=="None"||out.secure))out.sameSite=cookie.sameSite;const key=`${out.name}|${out.domain??out.url}`;const prev=byKey.get(key);if(!prev||(out.expires??0)>(prev.expires??0))byKey.set(key,out)}return[...byKey.values()]}async function injectCookies(page,cookies){await page._sendToTarget("Network.setCookies",{cookies:sanitizeCookies(cookies)})}var DEVICE_PRESETS=Object.freeze({"iphone-14":{width:390,height:844,deviceScaleFactor:3,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"iPhone"},"pixel-7":{width:412,height:915,deviceScaleFactor:2.625,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",platform:"Linux armv8l"},"ipad-air":{width:820,height:1180,deviceScaleFactor:2,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"MacIntel"},"desktop-1440":{width:1440,height:900,deviceScaleFactor:1,mobile:false,hasTouch:false,userAgent:undefined,platform:undefined}});var originalUAs=new WeakMap;async function emulate(page,presetNameOrObject){let preset;if(presetNameOrObject===null){preset=null}else if(typeof presetNameOrObject==="string"){if(!DEVICE_PRESETS[presetNameOrObject]){throw new Error(`unknown device preset: ${presetNameOrObject}`)}preset=DEVICE_PRESETS[presetNameOrObject]}else{preset=presetNameOrObject}const sessionId=await page.resolveSessionId();if(preset===null){await page.cdp.send("Emulation.clearDeviceMetricsOverride",{},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:false},sessionId);const originalUA=originalUAs.get(page);if(originalUA){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:originalUA},sessionId)}}else{if(!originalUAs.has(page)){const ua=await page.evaluate(()=>navigator.userAgent);originalUAs.set(page,ua)}await page.cdp.send("Emulation.setDeviceMetricsOverride",{width:preset.width,height:preset.height,deviceScaleFactor:preset.deviceScaleFactor,mobile:preset.mobile,screenWidth:preset.width,screenHeight:preset.height},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:preset.hasTouch,maxTouchPoints:preset.hasTouch?5:1},sessionId);if(preset.userAgent!==undefined){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:preset.userAgent,platform:preset.platform},sessionId)}}if(page.refreshViewportSize){await page.refreshViewportSize()}return preset}var AUTO_ATTACH={autoAttach:true,waitForDebuggerOnStart:false,flatten:true};var REF_PATTERN2=/^(f\d+)?e\d+$/;function detach(page,sessionId){return page.cdp.send("Target.detachFromTarget",{sessionId}).catch(()=>{})}async function iframeTargets(page){const{targetInfo}=await page.cdp.send("Target.getTargetInfo",{targetId:page.targetId});const browserContextId=targetInfo?.browserContextId;const{targetInfos}=await page.cdp.send("Target.getTargets",{filter:[{type:"iframe"}]});return targetInfos.filter((info)=>info.type==="iframe"&&(!browserContextId||!info.browserContextId||info.browserContextId===browserContextId))}function isAttributed(fm,frameId){const seen=new Set;let frame=fm.frames.get(frameId);while(frame&&!seen.has(frame.frameId)){if(frame.frameId===fm.mainFrameId)return true;seen.add(frame.frameId);frame=frame.parentFrameId?fm.frames.get(frame.parentFrameId):null}return false}async function describeTarget(page,targetId){const{sessionId}=await page.cdp.send("Target.attachToTarget",{targetId,flatten:true});try{await page.cdp.send("Page.enable",undefined,sessionId);const{frameTree}=await page.cdp.send("Page.getFrameTree",undefined,sessionId);return{sessionId,frame:frameTree.frame}}catch(error){await detach(page,sessionId);throw error}}async function adopt(page,sessionId,frame,parentFrameId){await page.cdp.send("DOM.enable",undefined,sessionId);await page.cdp.send("Target.setAutoAttach",AUTO_ATTACH,sessionId).catch(()=>{});page.frameManager.frames.set(frame.id,{frameId:frame.id,parentFrameId,url:frame.url??"",name:frame.name??"",sessionId});const isolatedContextId=await page.frameManager.ensureInjected(frame.id);return{frameId:frame.id,parentFrameId,url:frame.url??"",sessionId,isolatedContextId}}async function reconcileFrames(page){const fm=page.frameManager;const added=[];let pending=(await iframeTargets(page)).filter((info)=>!isAttributed(fm,info.targetId));let progress=true;while(progress&&pending.length>0){progress=false;const retry=[];for(const target of pending){if(isAttributed(fm,target.targetId))continue;const{sessionId,frame}=await describeTarget(page,target.targetId);const parentFrameId=frame.parentId??null;if(!parentFrameId||!isAttributed(fm,parentFrameId)){await detach(page,sessionId);if(parentFrameId)retry.push(target);continue}added.push(await adopt(page,sessionId,frame,parentFrameId));progress=true}pending=retry}return added}function framePrefixes(fm){let counter=1;return fm.collectDescendantFrames(fm.mainFrameId).map(({frameId})=>({frameId,prefix:frameId===fm.mainFrameId?"":`f${counter++}`}))}function collectMissingFrames(page,refs){const seen=new Set(Object.keys(refs??{}).map((ref)=>ref.match(REF_PATTERN2)?.[1]??""));const missing=[];for(const{frameId,prefix}of framePrefixes(page.frameManager)){if(prefix===""||seen.has(prefix))continue;const frame=page.frameManager.getFrame(frameId);if(frame?.isolatedContextId)continue;missing.push({frameId,url:frame?.url??"",injected:false})}return missing}async function snapshotWithFrames(page,opts={}){await reconcileFrames(page);const result=await page.snapshot(opts);const missingFrames=collectMissingFrames(page,result.refs);return missingFrames.length>0?{...result,missingFrames}:result}var HTTP_VERSION="HTTP/1.1";var CREATOR=Object.freeze({name:"omowright",version:"0.0.1"});function headerList(headers){return Object.entries(headers??{}).map(([name,value])=>({name,value:String(value)}))}function headerValue(headers,name){for(const[key,value]of Object.entries(headers??{})){if(key.toLowerCase()===name)return String(value)}return null}function queryString(url){try{return[...new URL(String(url)).searchParams].map(([name,value])=>({name,value}))}catch{return[]}}function elapsed(entry){const started=Number(entry.startedAt);const finished=Number(entry.finishedAt);if(!Number.isFinite(started)||!Number.isFinite(finished))return 0;return Math.max(0,finished-started)}function requestOf(entry){const postData=entry.postData??null;const request={method:entry.method??"GET",url:entry.url??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.requestHeaders),queryString:queryString(entry.url),headersSize:-1,bodySize:postData===null?0:Buffer.byteLength(postData)};if(postData!==null){request.postData={mimeType:headerValue(entry.requestHeaders,"content-type")??"",text:postData}}return request}function contentOf(entry){const content={size:Number(entry.encodedDataLength??0),mimeType:entry.mimeType??""};if(typeof entry.body==="string")content.text=entry.body;if(entry.base64Encoded)content.encoding="base64";return content}function responseOf(entry){return{status:entry.failed?0:Number(entry.status??0),statusText:entry.statusText??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.responseHeaders),content:contentOf(entry),redirectURL:headerValue(entry.responseHeaders,"location")??"",headersSize:-1,bodySize:Number(entry.encodedDataLength??0)}}function toHar(entries,{creator=CREATOR,pages=[]}={}){const log={version:"1.2",creator,pages,entries:[...entries??[]].map((entry)=>{const time=elapsed(entry);const har={startedDateTime:new Date(Number(entry.startedAt)||0).toISOString(),time,request:requestOf(entry),response:responseOf(entry),cache:{},timings:{send:0,wait:time,receive:0}};if(entry.failed)har._errorText=entry.errorText??"";return har})};return{log}}function injectHumanBanner(prompt){if(document.querySelector('[data-omowright-human="1"]'))return true;const host=document.createElement("div");host.setAttribute("data-omowright-human","1");host.style.cssText="position:fixed;top:0;left:0;right:0;z-index:2147483647;display:block;visibility:visible;opacity:1;pointer-events:auto;";const root=host.attachShadow({mode:"open"});const bar=document.createElement("div");bar.setAttribute("style","display:flex;align-items:center;gap:12px;padding:10px 16px;background:#111;color:#fff;font:14px/1.4 system-ui,sans-serif;");const message=document.createElement("span");message.textContent=prompt==null?"":String(prompt);const button=document.createElement("button");button.textContent="Done";button.addEventListener("click",()=>{window.__omowrightHumanDone=true});bar.append(message,button);root.append(bar);(document.documentElement??document.body).appendChild(host);return true}function humanBannerPresent(){return document.querySelector('[data-omowright-human="1"]')!==null}function humanDoneFlag(){return window.__omowrightHumanDone===true}function querySelectorExists(selector){return document.querySelector(selector)!==null}function removeHumanBanner(){document.querySelectorAll('[data-omowright-human="1"]').forEach((node)=>node.remove());try{delete window.__omowrightHumanDone}catch{window.__omowrightHumanDone=undefined}}function sleep(ms,signal){return new Promise((resolve)=>{if(signal?.aborted){resolve();return}const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);function onAbort(){clearTimeout(timer);resolve()}signal?.addEventListener("abort",onAbort,{once:true})})}async function ensureBanner(page,prompt){try{if(await page.evaluate(humanBannerPresent))return;await page.evaluate(injectHumanBanner,prompt??"")}catch{}}async function matchesUntil(page,until){if(until==null)return false;if(typeof until==="function")return Boolean(await until(page));if(typeof until==="object"){if(Object.prototype.hasOwnProperty.call(until,"url")){const current=page.url();const expected=until.url;if(expected instanceof RegExp)return expected.test(current);return String(current).includes(String(expected))}if(typeof until.selector==="string"){try{return Boolean(await page.evaluate(querySelectorExists,until.selector))}catch{return false}}}return false}async function isDone(page){try{return await page.evaluate(humanDoneFlag)===true}catch{return false}}async function requestHuman(page,{prompt,until,timeoutMs=300000,pollMs=500,signal}={}){const started=Date.now();const finish=(outcome,reason)=>({outcome,elapsedMs:Date.now()-started,reason});try{await page.bringToFront().catch(()=>{});await ensureBanner(page,prompt);for(;;){if(signal?.aborted)return finish("cancelled","signal");if(Date.now()-started>=timeoutMs)return finish("timed_out","timed_out");if(await matchesUntil(page,until))return finish("continued","until");if(await isDone(page))return finish("continued","done-button");await ensureBanner(page,prompt);const remaining=timeoutMs-(Date.now()-started);if(remaining<=0)return finish("timed_out","timed_out");await sleep(Math.min(pollMs,remaining),signal)}}finally{await page.evaluate(removeHumanBanner).catch(()=>{})}}async function describeLayers(page,{grid=5}={}){return page.evaluate((gridSize)=>{const width=Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0);const height=Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0);const viewport={width,height};const total=gridSize*gridSize;const hits=new Map;function pierceTopmost(x,y){const stack=document.elementsFromPoint(x,y);let el=stack[0]??null;const seen=new Set;while(el?.shadowRoot&&typeof el.shadowRoot.elementsFromPoint==="function"){if(seen.has(el))break;seen.add(el);const inner=el.shadowRoot.elementsFromPoint(x,y)??[];const next=inner.find((node)=>node&&node!==el);if(!next)break;el=next}return el}function parentOf(node){if(!node)return null;if(node.parentElement)return node.parentElement;const root=node.getRootNode?.();return root?.host??null}function promote(el){const minArea=0.5*width*height;let node=el;while(node&&node.nodeType===1){const position=getComputedStyle(node).position;if(position==="fixed"||position==="sticky"||position==="absolute"){const rect=node.getBoundingClientRect();if(rect.width*rect.height>=minArea)return node}node=parentOf(node)}return el}function labelledByText(el){const ids=(el.getAttribute("aria-labelledby")||"").trim();if(!ids)return"";return ids.split(/\s+/).map((id)=>document.getElementById(id)?.textContent?.trim()??"").filter(Boolean).join(" ")}function elementName(el){const ariaLabel=el.getAttribute("aria-label");if(ariaLabel)return ariaLabel;const labelled=labelledByText(el);if(labelled)return labelled;const heading=el.querySelector("h1,h2,h3,h4,h5,h6")?.textContent?.trim();if(heading)return heading;return(el.innerText||el.textContent||"").trim().replace(/\s+/g," ").slice(0,80)}function selectorHint(el){if(el.id)return`#${el.id}`;const classes=[...el.classList].join(".");return classes?`${el.tagName.toLowerCase()}.${classes}`:el.tagName.toLowerCase()}function describe(el,coverage){return{tagName:el.tagName,role:el.getAttribute("role")||"",name:elementName(el),coverage,position:getComputedStyle(el).position,selectorHint:selectorHint(el),ariaModal:el.getAttribute("aria-modal")==="true"}}function isMainContent(el){if(el===document.documentElement||el===document.body)return true;if(el.tagName==="MAIN")return true;return(el.getAttribute("role")||"").toLowerCase()==="main"}function isBlocking(el,info){if(info.coverage<0.6)return false;if(getComputedStyle(el).pointerEvents==="none")return false;const role=(info.role||"").toLowerCase();if(role==="dialog"||role==="alertdialog")return true;if(info.ariaModal)return true;if(isMainContent(el))return false;return info.position==="fixed"||info.position==="absolute"}const insetX=width*0.05;const insetY=height*0.05;const spanX=width*0.9;const spanY=height*0.9;for(let row=0;row<gridSize;row++){for(let col=0;col<gridSize;col++){const x=insetX+(col+0.5)*spanX/gridSize;const y=insetY+(row+0.5)*spanY/gridSize;const top=pierceTopmost(x,y);if(!top)continue;const candidate=promote(top);hits.set(candidate,(hits.get(candidate)??0)+1)}}const candidates=[...hits.entries()].map(([el,count])=>{const info=describe(el,total>0?count/total:0);return{el,info}}).sort((a,b)=>b.info.coverage-a.info.coverage);const blockingEntry=candidates.find((entry)=>isBlocking(entry.el,entry.info));return{blocking:blockingEntry?blockingEntry.info:null,candidates:candidates.map((entry)=>entry.info),viewport}},grid)}function layersHeader(result){const blocking=result?.blocking;if(!blocking)return"@layers none";const who=blocking.role||blocking.tagName;const pct=Math.round(blocking.coverage*100);return`@layers blocking=${who} "${blocking.name}" coverage=${pct}% hint=${blocking.selectorHint}`}async function snapshotWithLayers(page,snapshotOptions){const snapshot=await page.snapshot(snapshotOptions);const layers=await describeLayers(page);return{...snapshot,layers,tree:`${layersHeader(layers)}
1507
+ `);disconnect(error)}};stdin.on("data",onData);stdin.once?.("end",()=>disconnect());stdin.once?.("error",disconnect);return{get isConnected(){return!closed&&!!hello},get capabilities(){return{commands:new Set(hello?.commands??[]),events:new Set(hello?.events??[])}},send:write,request(name,params,{signal,timeoutMs=commandTimeoutMs}={}){if(!hello||!hello.commands.includes(name))return Promise.reject(new BridgeUnavailableError(`unsupported bridge command: ${name}`));let command;try{command=checked(CommandSchema,{protocol:PROTOCOL,type:"command",requestId:randomUUID4(),name,params},"invalid command parameters")}catch(error){return Promise.reject(error)}return new Promise((resolve,reject)=>{if(commandQueue.length+pending.size>=maxPendingWrites){reject(new BridgeProtocolError("BOUNDED_TRANSPORT"));return}const item={requestId:command.requestId,name,command,resolve,reject,timer:null,abortHandler:null,cleanup:null,settled:false};const cleanup=()=>{clearTimeout(item.timer);if(item.abortHandler){signal?.removeEventListener("abort",item.abortHandler);item.abortHandler=null}};item.cleanup=cleanup;const failIndeterminate=(code,reason=null)=>{if(item.settled)return;item.settled=true;cleanup();if(pending.delete(item.requestId)||commandQueue.includes(item)){const i=commandQueue.indexOf(item);if(i>=0)commandQueue.splice(i,1);item.reject(reason??Object.assign(new Error(`bridge command timed out: ${name}`),{code}))}if(item.started)disconnect(Object.assign(new Error("mutation completion is indeterminate"),{code}))};item.timer=setTimeout(()=>failIndeterminate("TIMEOUT"),timeoutMs);if(signal?.aborted){item.settled=true;cleanup();reject(signal.reason??Object.assign(new Error(`bridge command aborted: ${name}`),{code:"ABORT_ERR"}));return}item.abortHandler=()=>failIndeterminate("ABORT_ERR",signal.reason);signal?.addEventListener("abort",item.abortHandler,{once:true});commandQueue.push(item);pumpCommands()})},on(name,listener){if(!EVENT_NAMES2.includes(name))throw new BridgeProtocolError("invalid event name");const set=listeners.get(name)??new Set;set.add(listener);listeners.set(name,set);return()=>{set.delete(listener);if(!set.size)listeners.delete(name)}},emitEvent(name,payload){if(!hello?.events.includes(name))return Promise.reject(new BridgeUnavailableError("unsupported bridge event"));const checkedPayload=payloadSchemas[name].safeParse(payload);if(!checkedPayload.success)return Promise.reject(new BridgeProtocolError("invalid event payload"));sequence+=1;return write({protocol:PROTOCOL,type:"event",connectionId:hostConnectionId,seq:sequence,occurredAt:Date.now(),name,payload:checkedPayload.data})},close(){disconnect("closed");stdin.removeListener?.("data",onData)}}}var NATIVE_HOST_DIRS={darwin:{chrome:["Library","Application Support","Google","Chrome"],chromium:["Library","Application Support","Chromium"]},linux:{chrome:[".config","google-chrome"],chromium:[".config","chromium"]}};function defaultNativeMessagingHostDir(browser="chrome",platform=process.platform){const byBrowser=NATIVE_HOST_DIRS[platform];if(!byBrowser)throw new BridgeProtocolError(`no default nativeMessagingHostDir on ${platform}; pass nativeMessagingHostDir`);const segments=byBrowser[browser];if(!segments)throw new BridgeProtocolError("custom browser requires nativeMessagingHostDir");return path10.join(homedir(),...segments,"NativeMessagingHosts")}async function secureDirectory(dir){const absolute=path10.resolve(dir);const parts=absolute.split(path10.sep).filter(Boolean);let current=path10.parse(absolute).root;let final;for(const[index,part]of parts.entries()){current=path10.join(current,part);let info=await lstat(current).catch(()=>null);if(!info){await mkdir5(current,{mode:448});info=await lstat(current)}if(current!=="/var"&&(info.isSymbolicLink()||!info.isDirectory()))throw new BridgeProtocolError("nativeMessagingHostDir security rejected");if(current!=="/var"&&info.uid!==process.getuid?.()&&info.uid!==0)throw new BridgeProtocolError("nativeMessagingHostDir ownership rejected");const stickyRootAncestor=index<parts.length-1&&info.uid===0&&(info.mode&512)!==0;if(current!=="/var"&&!stickyRootAncestor&&(info.mode&18)!==0)throw new BridgeProtocolError("nativeMessagingHostDir security rejected");final=info}if(!final||final.uid!==process.getuid?.()&&final.uid!==0)throw new BridgeProtocolError("nativeMessagingHostDir ownership rejected");if((final.mode&63)!==0)await chmod4(absolute,448)}async function secureExecutable(hostPath){const info=await lstat(hostPath).catch(()=>null);if(!info?.isFile()||info.isSymbolicLink()||info.uid!==process.getuid?.()||(info.mode&73)===0||(info.mode&18)!==0)throw new BridgeProtocolError("hostPath must be a securely owned executable file")}async function installNativeMessagingHost({hostName=HOST_NAME,hostPath,extensionId,browser="chrome",nativeMessagingHostDir,force=false,endpointPath}={}){if(endpointPath!==undefined)throw new BridgeProtocolError("endpointPath is not supported");if(hostName!==HOST_NAME||!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName))throw new BridgeProtocolError("invalid hostName");if(!path10.isAbsolute(hostPath??""))throw new BridgeProtocolError("hostPath must be absolute");await secureExecutable(hostPath);if(!/^[a-p]{32}$/.test(extensionId??""))throw new BridgeProtocolError("invalid extensionId");if(!nativeMessagingHostDir&&browser==="cloakbrowser")throw new BridgeProtocolError("CloakBrowser nativeMessagingHostDir must be explicit and verified");const dir=nativeMessagingHostDir??defaultNativeMessagingHostDir(browser);await secureDirectory(dir);const manifest={name:hostName,description:"OmOWright internal CloakBrowser native messaging bridge.",path:hostPath,type:"stdio",allowed_origins:[`chrome-extension://${extensionId}/`]};const file=path10.join(dir,`${hostName}.json`);if(!force&&await lstat(file).catch(()=>null))throw new BridgeProtocolError("registration manifest already exists; use force");const temp=`${file}.${process.pid}.${randomUUID4()}.tmp`;const handle=await open5(temp,"wx",384);try{await handle.writeFile(JSON.stringify(manifest,null,2)+`
1508
+ `);await handle.sync()}finally{await handle.close()}await rename3(temp,file);const parsed=JSON.parse(await readFile5(file,"utf8"));await chmod4(file,384);return{path:file,manifest:parsed}}function createBridgeClient(options={}){return createNativeMessagingHost(options)}function createChromeApi2(connection,options={}){const chrome=createChromeApi(connection,options);const bridge=options.bridge;const request=(wire,params)=>bridge?.isConnected&&bridge.capabilities?.commands?.has(wire)?bridge.request(wire,params):Promise.reject(new UnsupportedOperationError(`chrome.${wire} requires the extension bridge in standalone OmOWright`));chrome.bookmarks.create=(details)=>request("bookmarks.create",{details});chrome.bookmarks.move=(id,details={})=>request("bookmarks.move",{details:{...details,id:String(id)}});chrome.bookmarks.remove=(id)=>request("bookmarks.remove",{details:{id:String(id)}});chrome.history.deleteUrl=(details)=>request("history.deleteUrl",{details});chrome.history.deleteRange=(details)=>request("history.deleteRange",{details});chrome.tabGroups={update:(groupId,updateProperties)=>request("tabGroups.update",{details:{groupId,updateProperties}})};chrome.debugger={attach:(target,requiredVersion)=>request("debugger.attach",{details:{tabId:target.tabId??target,requiredVersion}}),detach:(target)=>request("debugger.detach",{details:{tabId:target.tabId??target}})};const eventMap={notifications:["onShown","onClicked","onClosed"],tabGroups:["onCreated","onUpdated","onMoved"],tabs:["onActivated"],windows:["onFocusChanged"]};for(const[namespace,events]of Object.entries(eventMap)){chrome[namespace]??={};for(const event of events){const wire=`${namespace}.${event.slice(2,3).toLowerCase()+event.slice(3)}`;const subscriptions=new Map;chrome[namespace][event]={addListener(listener){if(!bridge?.on)return;const unsubscribe=bridge.on(wire,(payload)=>listener(...namespace==="notifications"&&event==="onClosed"?[payload.notificationId,payload.byUser]:namespace==="notifications"?[payload.notificationId]:namespace==="tabGroups"?[payload.group]:namespace==="windows"?[payload.windowId]:[payload]));subscriptions.set(listener,unsubscribe);return unsubscribe},removeListener(listener){const unsubscribe=subscriptions.get(listener);if(unsubscribe){unsubscribe();subscriptions.delete(listener)}}}}}return chrome}function sanitizeCookies(cookies){const byKey=new Map;for(const cookie of cookies){const out={name:cookie.name,value:cookie.value,path:cookie.path||"/",secure:Boolean(cookie.secure),httpOnly:Boolean(cookie.httpOnly)};if(cookie.name.startsWith("__Host-")){out.secure=true;out.path="/";out.url=`https://${cookie.domain.replace(/^\./,"")}`}else{out.domain=cookie.domain}if(cookie.expires&&cookie.expires>0)out.expires=cookie.expires;if(cookie.sameSite&&(cookie.sameSite!=="None"||out.secure))out.sameSite=cookie.sameSite;const key=`${out.name}|${out.domain??out.url}`;const prev=byKey.get(key);if(!prev||(out.expires??0)>(prev.expires??0))byKey.set(key,out)}return[...byKey.values()]}async function injectCookies(page,cookies){await page._sendToTarget("Network.setCookies",{cookies:sanitizeCookies(cookies)})}var DEVICE_PRESETS=Object.freeze({"iphone-14":{width:390,height:844,deviceScaleFactor:3,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"iPhone"},"pixel-7":{width:412,height:915,deviceScaleFactor:2.625,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Mobile Safari/537.36",platform:"Linux armv8l"},"ipad-air":{width:820,height:1180,deviceScaleFactor:2,mobile:true,hasTouch:true,userAgent:"Mozilla/5.0 (iPad; CPU OS 16_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1",platform:"MacIntel"},"desktop-1440":{width:1440,height:900,deviceScaleFactor:1,mobile:false,hasTouch:false,userAgent:undefined,platform:undefined}});var originalUAs=new WeakMap;async function emulate(page,presetNameOrObject){let preset;if(presetNameOrObject===null){preset=null}else if(typeof presetNameOrObject==="string"){if(!DEVICE_PRESETS[presetNameOrObject]){throw new Error(`unknown device preset: ${presetNameOrObject}`)}preset=DEVICE_PRESETS[presetNameOrObject]}else{preset=presetNameOrObject}const sessionId=await page.resolveSessionId();if(preset===null){await page.cdp.send("Emulation.clearDeviceMetricsOverride",{},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:false},sessionId);const originalUA=originalUAs.get(page);if(originalUA){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:originalUA},sessionId)}}else{if(!originalUAs.has(page)){const ua=await page.evaluate(()=>navigator.userAgent);originalUAs.set(page,ua)}await page.cdp.send("Emulation.setDeviceMetricsOverride",{width:preset.width,height:preset.height,deviceScaleFactor:preset.deviceScaleFactor,mobile:preset.mobile,screenWidth:preset.width,screenHeight:preset.height},sessionId);await page.cdp.send("Emulation.setTouchEmulationEnabled",{enabled:preset.hasTouch,maxTouchPoints:preset.hasTouch?5:1},sessionId);if(preset.userAgent!==undefined){await page.cdp.send("Emulation.setUserAgentOverride",{userAgent:preset.userAgent,platform:preset.platform},sessionId)}}if(page.refreshViewportSize){await page.refreshViewportSize()}return preset}var AUTO_ATTACH={autoAttach:true,waitForDebuggerOnStart:false,flatten:true};var REF_PATTERN2=/^(f\d+)?e\d+$/;function detach(page,sessionId){return page.cdp.send("Target.detachFromTarget",{sessionId}).catch(()=>{})}async function iframeTargets(page){const{targetInfo}=await page.cdp.send("Target.getTargetInfo",{targetId:page.targetId});const browserContextId=targetInfo?.browserContextId;const{targetInfos}=await page.cdp.send("Target.getTargets",{filter:[{type:"iframe"}]});return targetInfos.filter((info)=>info.type==="iframe"&&(!browserContextId||!info.browserContextId||info.browserContextId===browserContextId))}function isAttributed(fm,frameId){const seen=new Set;let frame=fm.frames.get(frameId);while(frame&&!seen.has(frame.frameId)){if(frame.frameId===fm.mainFrameId)return true;seen.add(frame.frameId);frame=frame.parentFrameId?fm.frames.get(frame.parentFrameId):null}return false}async function describeTarget(page,targetId){const{sessionId}=await page.cdp.send("Target.attachToTarget",{targetId,flatten:true});try{await page.cdp.send("Page.enable",undefined,sessionId);const{frameTree}=await page.cdp.send("Page.getFrameTree",undefined,sessionId);return{sessionId,frame:frameTree.frame}}catch(error){await detach(page,sessionId);throw error}}async function adopt(page,sessionId,frame,parentFrameId){await page.cdp.send("DOM.enable",undefined,sessionId);await page.cdp.send("Target.setAutoAttach",AUTO_ATTACH,sessionId).catch(()=>{});page.frameManager.frames.set(frame.id,{frameId:frame.id,parentFrameId,url:frame.url??"",name:frame.name??"",sessionId});const isolatedContextId=await page.frameManager.ensureInjected(frame.id);return{frameId:frame.id,parentFrameId,url:frame.url??"",sessionId,isolatedContextId}}async function reconcileFrames(page){const fm=page.frameManager;const added=[];let pending=(await iframeTargets(page)).filter((info)=>!isAttributed(fm,info.targetId));let progress=true;while(progress&&pending.length>0){progress=false;const retry=[];for(const target of pending){if(isAttributed(fm,target.targetId))continue;const{sessionId,frame}=await describeTarget(page,target.targetId);const parentFrameId=frame.parentId??null;if(!parentFrameId||!isAttributed(fm,parentFrameId)){await detach(page,sessionId);if(parentFrameId)retry.push(target);continue}added.push(await adopt(page,sessionId,frame,parentFrameId));progress=true}pending=retry}return added}function framePrefixes(fm){let counter=1;return fm.collectDescendantFrames(fm.mainFrameId).map(({frameId})=>({frameId,prefix:frameId===fm.mainFrameId?"":`f${counter++}`}))}function collectMissingFrames(page,refs){const seen=new Set(Object.keys(refs??{}).map((ref)=>ref.match(REF_PATTERN2)?.[1]??""));const missing=[];for(const{frameId,prefix}of framePrefixes(page.frameManager)){if(prefix===""||seen.has(prefix))continue;const frame=page.frameManager.getFrame(frameId);if(frame?.isolatedContextId)continue;missing.push({frameId,url:frame?.url??"",injected:false})}return missing}async function snapshotWithFrames(page,opts={}){await reconcileFrames(page);const result=await page.snapshot(opts);const missingFrames=collectMissingFrames(page,result.refs);return missingFrames.length>0?{...result,missingFrames}:result}var HTTP_VERSION="HTTP/1.1";var CREATOR=Object.freeze({name:"omowright",version:"0.0.1"});function headerList(headers){return Object.entries(headers??{}).map(([name,value])=>({name,value:String(value)}))}function headerValue(headers,name){for(const[key,value]of Object.entries(headers??{})){if(key.toLowerCase()===name)return String(value)}return null}function queryString(url){try{return[...new URL(String(url)).searchParams].map(([name,value])=>({name,value}))}catch{return[]}}function elapsed(entry){const started=Number(entry.startedAt);const finished=Number(entry.finishedAt);if(!Number.isFinite(started)||!Number.isFinite(finished))return 0;return Math.max(0,finished-started)}function requestOf(entry){const postData=entry.postData??null;const request={method:entry.method??"GET",url:entry.url??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.requestHeaders),queryString:queryString(entry.url),headersSize:-1,bodySize:postData===null?0:Buffer.byteLength(postData)};if(postData!==null){request.postData={mimeType:headerValue(entry.requestHeaders,"content-type")??"",text:postData}}return request}function contentOf(entry){const content={size:Number(entry.encodedDataLength??0),mimeType:entry.mimeType??""};if(typeof entry.body==="string")content.text=entry.body;if(entry.base64Encoded)content.encoding="base64";return content}function responseOf(entry){return{status:entry.failed?0:Number(entry.status??0),statusText:entry.statusText??"",httpVersion:HTTP_VERSION,cookies:[],headers:headerList(entry.responseHeaders),content:contentOf(entry),redirectURL:headerValue(entry.responseHeaders,"location")??"",headersSize:-1,bodySize:Number(entry.encodedDataLength??0)}}function toHar(entries,{creator=CREATOR,pages=[]}={}){const log={version:"1.2",creator,pages,entries:[...entries??[]].map((entry)=>{const time=elapsed(entry);const har={startedDateTime:new Date(Number(entry.startedAt)||0).toISOString(),time,request:requestOf(entry),response:responseOf(entry),cache:{},timings:{send:0,wait:time,receive:0}};if(entry.failed)har._errorText=entry.errorText??"";return har})};return{log}}function injectHumanBanner(prompt){if(document.querySelector('[data-omowright-human="1"]'))return true;const host=document.createElement("div");host.setAttribute("data-omowright-human","1");host.style.cssText="position:fixed;top:0;left:0;right:0;z-index:2147483647;display:block;visibility:visible;opacity:1;pointer-events:auto;";const root=host.attachShadow({mode:"open"});const bar=document.createElement("div");bar.setAttribute("style","display:flex;align-items:center;gap:12px;padding:10px 16px;background:#111;color:#fff;font:14px/1.4 system-ui,sans-serif;");const message=document.createElement("span");message.textContent=prompt==null?"":String(prompt);const button=document.createElement("button");button.textContent="Done";button.addEventListener("click",()=>{window.__omowrightHumanDone=true});bar.append(message,button);root.append(bar);(document.documentElement??document.body).appendChild(host);return true}function humanBannerPresent(){return document.querySelector('[data-omowright-human="1"]')!==null}function humanDoneFlag(){return window.__omowrightHumanDone===true}function querySelectorExists(selector){return document.querySelector(selector)!==null}function removeHumanBanner(){document.querySelectorAll('[data-omowright-human="1"]').forEach((node)=>node.remove());try{delete window.__omowrightHumanDone}catch{window.__omowrightHumanDone=undefined}}function sleep2(ms,signal){return new Promise((resolve)=>{if(signal?.aborted){resolve();return}const timer=setTimeout(()=>{signal?.removeEventListener("abort",onAbort);resolve()},ms);function onAbort(){clearTimeout(timer);resolve()}signal?.addEventListener("abort",onAbort,{once:true})})}async function ensureBanner(page,prompt){try{if(await page.evaluate(humanBannerPresent))return;await page.evaluate(injectHumanBanner,prompt??"")}catch{}}async function matchesUntil(page,until){if(until==null)return false;if(typeof until==="function")return Boolean(await until(page));if(typeof until==="object"){if(Object.prototype.hasOwnProperty.call(until,"url")){const current=page.url();const expected=until.url;if(expected instanceof RegExp)return expected.test(current);return String(current).includes(String(expected))}if(typeof until.selector==="string"){try{return Boolean(await page.evaluate(querySelectorExists,until.selector))}catch{return false}}}return false}async function isDone(page){try{return await page.evaluate(humanDoneFlag)===true}catch{return false}}async function requestHuman(page,{prompt,until,timeoutMs=300000,pollMs=500,signal}={}){const started=Date.now();const finish=(outcome,reason)=>({outcome,elapsedMs:Date.now()-started,reason});try{await page.bringToFront().catch(()=>{});await ensureBanner(page,prompt);for(;;){if(signal?.aborted)return finish("cancelled","signal");if(Date.now()-started>=timeoutMs)return finish("timed_out","timed_out");if(await matchesUntil(page,until))return finish("continued","until");if(await isDone(page))return finish("continued","done-button");await ensureBanner(page,prompt);const remaining=timeoutMs-(Date.now()-started);if(remaining<=0)return finish("timed_out","timed_out");await sleep2(Math.min(pollMs,remaining),signal)}}finally{await page.evaluate(removeHumanBanner).catch(()=>{})}}async function describeLayers(page,{grid=5}={}){return page.evaluate((gridSize)=>{const width=Math.round(globalThis.visualViewport?.width??globalThis.innerWidth??0);const height=Math.round(globalThis.visualViewport?.height??globalThis.innerHeight??0);const viewport={width,height};const total=gridSize*gridSize;const hits=new Map;function pierceTopmost(x,y){const stack=document.elementsFromPoint(x,y);let el=stack[0]??null;const seen=new Set;while(el?.shadowRoot&&typeof el.shadowRoot.elementsFromPoint==="function"){if(seen.has(el))break;seen.add(el);const inner=el.shadowRoot.elementsFromPoint(x,y)??[];const next=inner.find((node)=>node&&node!==el);if(!next)break;el=next}return el}function parentOf(node){if(!node)return null;if(node.parentElement)return node.parentElement;const root=node.getRootNode?.();return root?.host??null}function promote(el){const minArea=0.5*width*height;let node=el;while(node&&node.nodeType===1){const position=getComputedStyle(node).position;if(position==="fixed"||position==="sticky"||position==="absolute"){const rect=node.getBoundingClientRect();if(rect.width*rect.height>=minArea)return node}node=parentOf(node)}return el}function labelledByText(el){const ids=(el.getAttribute("aria-labelledby")||"").trim();if(!ids)return"";return ids.split(/\s+/).map((id)=>document.getElementById(id)?.textContent?.trim()??"").filter(Boolean).join(" ")}function elementName(el){const ariaLabel=el.getAttribute("aria-label");if(ariaLabel)return ariaLabel;const labelled=labelledByText(el);if(labelled)return labelled;const heading=el.querySelector("h1,h2,h3,h4,h5,h6")?.textContent?.trim();if(heading)return heading;return(el.innerText||el.textContent||"").trim().replace(/\s+/g," ").slice(0,80)}function selectorHint(el){if(el.id)return`#${el.id}`;const classes=[...el.classList].join(".");return classes?`${el.tagName.toLowerCase()}.${classes}`:el.tagName.toLowerCase()}function describe(el,coverage){return{tagName:el.tagName,role:el.getAttribute("role")||"",name:elementName(el),coverage,position:getComputedStyle(el).position,selectorHint:selectorHint(el),ariaModal:el.getAttribute("aria-modal")==="true"}}function isMainContent(el){if(el===document.documentElement||el===document.body)return true;if(el.tagName==="MAIN")return true;return(el.getAttribute("role")||"").toLowerCase()==="main"}function isBlocking(el,info){if(info.coverage<0.6)return false;if(getComputedStyle(el).pointerEvents==="none")return false;const role=(info.role||"").toLowerCase();if(role==="dialog"||role==="alertdialog")return true;if(info.ariaModal)return true;if(isMainContent(el))return false;return info.position==="fixed"||info.position==="absolute"}const insetX=width*0.05;const insetY=height*0.05;const spanX=width*0.9;const spanY=height*0.9;for(let row=0;row<gridSize;row++){for(let col=0;col<gridSize;col++){const x=insetX+(col+0.5)*spanX/gridSize;const y=insetY+(row+0.5)*spanY/gridSize;const top=pierceTopmost(x,y);if(!top)continue;const candidate=promote(top);hits.set(candidate,(hits.get(candidate)??0)+1)}}const candidates=[...hits.entries()].map(([el,count])=>{const info=describe(el,total>0?count/total:0);return{el,info}}).sort((a,b)=>b.info.coverage-a.info.coverage);const blockingEntry=candidates.find((entry)=>isBlocking(entry.el,entry.info));return{blocking:blockingEntry?blockingEntry.info:null,candidates:candidates.map((entry)=>entry.info),viewport}},grid)}function layersHeader(result){const blocking=result?.blocking;if(!blocking)return"@layers none";const who=blocking.role||blocking.tagName;const pct=Math.round(blocking.coverage*100);return`@layers blocking=${who} "${blocking.name}" coverage=${pct}% hint=${blocking.selectorHint}`}async function snapshotWithLayers(page,snapshotOptions){const snapshot=await page.snapshot(snapshotOptions);const layers=await describeLayers(page);return{...snapshot,layers,tree:`${layersHeader(layers)}
1518
1509
  ${snapshot.tree}`}}var DEFAULT_TIMEOUT_MS=30000;var JSON_MIME=/^application\/json\s*(;|$)|\+json\s*(;|$)/i;function matchesText(value,pattern){if(pattern===undefined)return true;if(value===null||value===undefined)return false;if(pattern instanceof RegExp)return pattern.test(String(value));return String(value).includes(String(pattern))}function matchesToken(value,expected){if(expected===undefined)return true;if(value===null||value===undefined)return false;return String(value).toLowerCase()===String(expected).toLowerCase()}function toPredicate(match){if(match===undefined||match===null)return()=>true;if(typeof match==="function")return match;if(typeof match!=="object")throw new TypeError("match must be a predicate function or a descriptor object");return(entry)=>matchesText(entry.url,match.url)&&matchesToken(entry.method,match.method)&&matchesText(entry.mimeType,match.mimeType)&&matchesToken(entry.resourceType,match.resourceType)}function startedAtOf(params){const wallTime=Number(params?.wallTime);return Number.isFinite(wallTime)&&wallTime>0?Math.round(wallTime*1000):Date.now()}function decodeBody(entry){if(typeof entry.body!=="string")return null;return entry.base64Encoded?Buffer.from(entry.body,"base64").toString("utf8"):entry.body}function createNetworkSnoop(page,options={}){if(!page?.cdp||typeof page.resolveSessionId!=="function"){throw new TypeError("createNetworkSnoop requires a page with cdp and resolveSessionId")}const{match,bodies=true,maxEntries=500,maxBodyBytes=5000000}=options;const wanted=toPredicate(match);const inflight=new Map;const buffer=[];const waiters=new Set;const unsubscribers=[];let sessionId=null;let disposed=false;let queue=Promise.resolve();const ready=Promise.resolve(page.resolveSessionId()).then((id)=>{sessionId=id});ready.catch((error)=>console.warn("[network-snoop] failed to resolve the page session",error));function subscribe(method,handler){unsubscribers.push(page.cdp.on(method,(params,meta)=>{if(disposed)return;if(sessionId===null){ready.then(()=>{if(!disposed&&meta?.sessionId===sessionId)handler(params)}).catch(()=>{});return}if(meta?.sessionId!==sessionId)return;handler(params)}))}function enqueue(task){queue=queue.then(task).catch((error)=>console.warn("[network-snoop] entry processing failed",error))}async function loadBody(entry){if(entry.encodedDataLength>maxBodyBytes){entry.bodySkipped=true;return}try{const result=await page.cdp.send("Network.getResponseBody",{requestId:entry.requestId},sessionId);entry.body=result?.body??null;entry.base64Encoded=Boolean(result?.base64Encoded)}catch{entry.body=null}}function commit(entry){buffer.push(entry);while(buffer.length>maxEntries)buffer.shift();for(const waiter of[...waiters])if(waiter.test(entry))waiter.resolve(entry)}subscribe("Network.requestWillBeSent",(params)=>{const requestId=params?.requestId;if(!requestId)return;inflight.set(requestId,{requestId,url:params.request?.url??params.documentURL??"",method:params.request?.method??"GET",resourceType:params.type??null,status:null,statusText:null,mimeType:null,requestHeaders:params.request?.headers??{},responseHeaders:null,remoteIPAddress:null,postData:params.request?.postData??null,encodedDataLength:0,body:null,base64Encoded:false,bodySkipped:false,failed:false,errorText:null,startedAt:startedAtOf(params),finishedAt:null})});subscribe("Network.responseReceived",(params)=>{const entry=inflight.get(params?.requestId);if(!entry)return;const response=params.response??{};entry.status=response.status??null;entry.statusText=response.statusText??"";entry.mimeType=response.mimeType??null;entry.responseHeaders=response.headers??{};entry.remoteIPAddress=response.remoteIPAddress??null;if(params.type)entry.resourceType=params.type});subscribe("Network.loadingFinished",(params)=>{const entry=inflight.get(params?.requestId);if(!entry)return;inflight.delete(entry.requestId);entry.encodedDataLength=Number(params.encodedDataLength??0);entry.finishedAt=Date.now();enqueue(async()=>{if(!wanted(entry))return;if(bodies)await loadBody(entry);commit(entry)})});subscribe("Network.loadingFailed",(params)=>{const entry=inflight.get(params?.requestId);if(!entry)return;inflight.delete(entry.requestId);entry.failed=true;entry.errorText=params.errorText??"";entry.encodedDataLength=Number(params.encodedDataLength??entry.encodedDataLength);entry.finishedAt=Date.now();enqueue(async()=>{if(wanted(entry))commit(entry)})});function pop(){return buffer.splice(0,buffer.length)}function peek(){return[...buffer]}function popJson(){const values=[];for(const entry of pop()){if(!JSON_MIME.test(String(entry.mimeType??"")))continue;const text=decodeBody(entry);if(text===null)continue;try{values.push(JSON.parse(text))}catch{}}return values}function waitFor(match,{timeoutMs=DEFAULT_TIMEOUT_MS}={}){if(disposed)return Promise.reject(Error("Network snoop is disposed"));const predicate=toPredicate(match);return new Promise((resolve,reject)=>{let settled=false;const waiter={};const finish=(callback)=>(value)=>{if(settled)return;settled=true;clearTimeout(timer);waiters.delete(waiter);callback(value)};waiter.resolve=finish(resolve);waiter.reject=finish(reject);waiter.test=(entry)=>{try{return Boolean(predicate(entry))}catch(error){waiter.reject(error instanceof Error?error:Error(String(error)));return false}};const timer=setTimeout(()=>waiter.reject(Error(`Timed out waiting for network response after ${timeoutMs}ms`)),timeoutMs);waiters.add(waiter)})}function summary({max=50}={}){const shown=buffer.slice(0,max);const lines=shown.map((entry)=>[entry.method,entry.status??(entry.failed?"FAILED":"-"),entry.mimeType??"-",`${entry.encodedDataLength}B`,entry.url].join(" "));const hidden=buffer.length-shown.length;if(hidden>0)lines.push(`... +${hidden} more`);return lines.join(`
1519
- `)}function dispose(){if(disposed)return;disposed=true;for(const off of unsubscribers.splice(0,unsubscribers.length))off();for(const waiter of[...waiters])waiter.reject(Error("Network snoop disposed"));waiters.clear();inflight.clear()}return{pop,peek,popJson,waitFor,summary,dispose}}function globToRegExp(glob){let source="";for(const char of glob){if(char==="*")source+=".*";else if(char==="?")source+=".";else if("\\^$+{}[]()|.".includes(char))source+=`\\${char}`;else source+=char}return new RegExp(`^${source}$`)}function hasGlobChars(value){return value.includes("*")||value.includes("?")}function matches(match,request){if(typeof match==="function"){return Boolean(match({url:request.url,method:request.method,resourceType:request.resourceType,headers:request.headers}))}if(match instanceof RegExp)return match.test(request.url);if(typeof match==="string"){if(hasGlobChars(match))return globToRegExp(match).test(request.url);return request.url.includes(match)}return false}function sameMatch(left,right){if(left===right)return true;if(left instanceof RegExp&&right instanceof RegExp)return left.source===right.source&&left.flags===right.flags;return false}function toHeaderEntries(headers){if(!headers)return[];if(Array.isArray(headers)){return headers.map((header)=>({name:String(header.name),value:String(header.value??"")}))}return Object.entries(headers).map(([name,value])=>({name,value:String(value??"")}))}function encodeBody(body){if(body==null)return"";if(Buffer.isBuffer(body))return body.toString("base64");if(body instanceof Uint8Array)return Buffer.from(body).toString("base64");return Buffer.from(String(body)).toString("base64")}function buildContinue(requestId,{url,method,headers,postData}={}){const params={requestId};if(url!==undefined)params.url=url;if(method!==undefined)params.method=method;if(headers!==undefined)params.headers=toHeaderEntries(headers);if(postData!==undefined)params.postData=encodeBody(postData);return params}function buildFulfill(requestId,{status=200,headers={},contentType,body=""}={}){const responseHeaders=toHeaderEntries(headers);if(contentType!=null&&String(contentType).length>0){const hasType=responseHeaders.some((header)=>header.name.toLowerCase()==="content-type");if(!hasType)responseHeaders.push({name:"content-type",value:String(contentType)})}return{requestId,responseCode:status,responseHeaders,body:encodeBody(body)}}function createRoutes(page){if(!page?.cdp)throw new TypeError("createRoutes requires a page with cdp");const entries=[];const warned=new WeakSet;const settledIds=new Set;let enabled=false;let sessionId;let unsubscribe=null;let enablePromise=null;function warnOnce(handler,error){if(typeof handler==="function"){if(warned.has(handler))return;warned.add(handler)}if(error)console.warn("[routes] route handler failed; continuing request",error);else console.warn("[routes] route handler did not settle the request; continuing")}function findHandler(request){for(const entry of entries){if(matches(entry.match,request))return entry.handler}return}async function handlePaused(params,meta){if(!sessionId||meta?.sessionId!==sessionId)return;const requestId=params?.requestId;if(!requestId||settledIds.has(requestId))return;const request={url:params.request?.url??"",method:params.request?.method??"GET",headers:params.request?.headers??{},postData:params.request?.postData,resourceType:params.resourceType};let settled=false;const settle=(method,cdpParams)=>{if(settled)return Promise.resolve();settled=true;settledIds.add(requestId);return page.cdp.send(method,cdpParams,sessionId)};const route={request,continue(overrides={}){return settle("Fetch.continueRequest",buildContinue(requestId,overrides))},fulfill(options={}){return settle("Fetch.fulfillRequest",buildFulfill(requestId,options))},abort(errorReason="Failed"){return settle("Fetch.failRequest",{requestId,errorReason})}};const handler=findHandler(request);if(!handler){await settle("Fetch.continueRequest",{requestId});return}try{await handler(route)}catch(error){warnOnce(handler,error)}if(!settled){warnOnce(handler);await settle("Fetch.continueRequest",{requestId})}}function onPaused(params,meta){handlePaused(params,meta).catch((error)=>{console.warn("[routes] requestPaused handling failed",error)})}async function ensureEnabled(){if(enabled)return;if(!enablePromise){enablePromise=(async()=>{sessionId=await page.resolveSessionId();if(!unsubscribe)unsubscribe=page.cdp.on("Fetch.requestPaused",onPaused);await page.cdp.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]},sessionId);enabled=true})()}try{await enablePromise}catch(error){enablePromise=null;throw error}}async function disableFetch(){const pending=enablePromise;enablePromise=null;if(pending)await pending.catch(()=>{});if(unsubscribe){unsubscribe();unsubscribe=null}if(!enabled)return;enabled=false;await page.cdp.send("Fetch.disable",{},sessionId)}async function route(match,handler){if(typeof handler!=="function")throw new TypeError("handler must be a function");entries.push({match,handler});await ensureEnabled()}async function unroute(match){if(match===undefined)entries.length=0;else{for(let index=entries.length-1;index>=0;index-=1){if(sameMatch(entries[index].match,match))entries.splice(index,1)}}if(entries.length===0)await disableFetch()}async function dispose(){entries.length=0;await disableFetch()}return{route,unroute,dispose,get enabled(){return enabled}}}async function viewportOf(page){return page.viewportSize()??await page.evaluate(()=>({width:innerWidth,height:innerHeight}))}async function scrollOnce(page,mode){if(mode==="end"){await page.evaluate(()=>scrollTo(0,document.scrollingElement.scrollHeight));return}const viewport=await viewportOf(page);await page.mouse.move(Math.floor(viewport.width/2),Math.floor(viewport.height/2));await page.mouse.wheel(0,Math.floor(viewport.height*0.9))}async function*collectWhileScrolling(page,snoop,options={}){const{minItems=Infinity,maxScrolls=10,extract=(json)=>Array.isArray(json)?json:[],scroll="wheel",settleMs=800}=options;if(scroll!=="wheel"&&scroll!=="end")throw new TypeError(`Unknown scroll mode: ${String(scroll)}`);let rounds=0;let total=0;let lastHeight=null;let unchanged=0;let stoppedBecause="maxScrolls";for(;;){for(const json of snoop.popJson()){for(const item of extract(json)){total+=1;yield item}}if(total>=minItems){stoppedBecause="minItems";break}if(rounds>=maxScrolls){stoppedBecause="maxScrolls";break}const height=await page.evaluate(()=>document.scrollingElement.scrollHeight);if(lastHeight!==null&&height===lastHeight){unchanged+=1;if(unchanged>=2){stoppedBecause="noGrowth";break}}else{unchanged=0}lastHeight=height;await scrollOnce(page,scroll);rounds+=1;await new Promise((resolve)=>setTimeout(resolve,settleMs))}return{rounds,total,stoppedBecause}}import{mkdir as mkdir5,writeFile as writeFile2}from"node:fs/promises";import path8 from"node:path";var SLUG_MAX=48;var SNOOP_MAX_ENTRIES=5000;function slug(name){const value=String(name??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return(value||"step").slice(0,SLUG_MAX)}function messageOf(error){return error instanceof Error?error.message:String(error)}async function readConsole(page){const api=page.console;const entries=typeof api==="function"?await api.call(page):await api?.logs?.();return Array.isArray(entries)?entries:[]}function createTrace(page,options={}){if(!page?.cdp||typeof page.resolveSessionId!=="function"){throw new TypeError("createTrace requires a page with cdp and resolveSessionId")}const{dir,screenshots=true,network=true,console:consoleLogs=true,maxBodyBytes=1e6,events}=options;if(typeof dir!=="string"||dir.length===0)throw new TypeError("createTrace requires a dir");const shotDir=path8.join(dir,"screenshots");const ready=mkdir5(shotDir,{recursive:true});const startedAt=Date.now();const records=[];const netEntries=[];const unsubscribers=[];const snoop=network?createNetworkSnoop(page,{bodies:true,maxBodyBytes,maxEntries:SNOOP_MAX_ENTRIES}):null;let seq=0;let consoleSeen=0;let sessionId=null;let stopped=false;let stopping=null;function record(event){const entry={...event,ts:Date.now(),seq:seq++};records.push(entry);return entry}const sessionReady=Promise.resolve(page.resolveSessionId()).then((id)=>{sessionId=id});sessionReady.catch((error)=>record({kind:"warning",scope:"session",message:messageOf(error)}));unsubscribers.push(page.cdp.on("Page.frameNavigated",(params,meta)=>{if(stopped||params?.frame?.parentId)return;const add=()=>record({kind:"navigation",url:params?.frame?.url??"",frameId:params?.frame?.id??null});if(sessionId===null){sessionReady.then(()=>{if(!stopped&&meta?.sessionId===sessionId)add()}).catch(()=>{});return}if(meta?.sessionId===sessionId)add()}));unsubscribers.push(page.on("dialog",(dialog)=>record({kind:"dialog",type:dialog?.type??null,message:dialog?.message??"",defaultPrompt:dialog?.defaultPrompt??"",url:dialog?.url??null})));if(events){unsubscribers.push(events.on("downloadStarted",(payload)=>record({kind:"download",phase:"started",...payload})));unsubscribers.push(events.on("downloadFinished",(payload)=>record({kind:"download",phase:"finished",...payload})))}async function capture(step,phase){const file=path8.join(shotDir,`${step.seq}-${slug(step.name)}-${phase}.png`);try{await writeFile2(file,await page.screenshot({type:"png"}));step.screenshots[phase]=file}catch(error){record({kind:"warning",scope:`screenshot:${phase}`,step:step.seq,message:messageOf(error)})}}function drainNetwork(){for(const entry of snoop?.pop()??[]){if(typeof entry.body==="string"&&Buffer.byteLength(entry.body)>maxBodyBytes){entry.body=null;entry.bodySkipped=true}netEntries.push(entry);record({kind:"network",...entry})}}async function drainConsole(){if(!consoleLogs)return;let entries;try{entries=await readConsole(page)}catch{return}if(entries.length<consoleSeen)consoleSeen=0;for(const entry of entries.slice(consoleSeen))record({kind:"console",...entry});consoleSeen=entries.length}async function drain(){drainNetwork();await drainConsole()}async function step(name,fn){if(typeof fn!=="function")throw new TypeError("trace.step requires a function");await ready;const entry=record({kind:"step",name:String(name),startedAt:Date.now(),screenshots:{}});if(screenshots)await capture(entry,"before");try{return await fn()}catch(error){entry.error=messageOf(error);throw error}finally{entry.endedAt=Date.now();entry.durationMs=entry.endedAt-entry.startedAt;if(screenshots)await capture(entry,"after");await drain()}}function mark(name,data){return record({kind:"mark",name:String(name),data:data??null})}async function finish(){await ready;await drain();stopped=true;for(const off of unsubscribers.splice(0,unsubscribers.length))off();snoop?.dispose();const ordered=[...records].sort((a,b)=>a.seq-b.seq);const summary={steps:ordered.filter((entry)=>entry.kind==="step").length,events:ordered.length,network:netEntries.length,startedAt,endedAt:Date.now(),url:page.url()};await writeFile2(path8.join(dir,"trace.jsonl"),ordered.map((entry)=>`${JSON.stringify(entry)}
1520
- `).join(""));await writeFile2(path8.join(dir,"trace.har"),`${JSON.stringify(toHar(netEntries),null,2)}
1521
- `);await writeFile2(path8.join(dir,"summary.json"),`${JSON.stringify(summary,null,2)}
1522
- `);return summary}function stop(){return stopping??=finish()}return{step,mark,stop,get dir(){return dir}}}import{connect as connect2}from"node:net";import{existsSync as existsSync3}from"node:fs";import path10 from"node:path";import{randomBytes}from"node:crypto";import{existsSync as existsSync2,readFileSync as readFileSync3}from"node:fs";import{homedir as homedir2}from"node:os";import path9 from"node:path";import{spawn as spawn3}from"node:child_process";import{createHash}from"node:crypto";function resolveBskHome(env=process.env){const override=env.BSK_HOME;if(typeof override==="string"&&override.length>0)return override;const home=env.HOME&&env.HOME.length>0?env.HOME:homedir2();return path9.join(home,".bsk")}function daemonInfoPath(home){return path9.join(home,"daemon.json")}function readDaemonInfo(home){let raw;try{raw=readFileSync3(daemonInfoPath(home),"utf8")}catch{return null}let info;try{info=JSON.parse(raw)}catch{return null}if(!info||typeof info.sock_path!=="string"||info.sock_path.length===0)return null;return info}function findBskBinary(env=process.env){const home=env.HOME&&env.HOME.length>0?env.HOME:homedir2();const candidates=[env.BSK_BIN,path9.join(home,".local","bin",process.platform==="win32"?"bsk.exe":"bsk")].filter(Boolean);for(const candidate of candidates)if(existsSync2(candidate))return candidate;return"bsk"}var NO_BREAKAWAY=/Job Object/;function windowsDaemonTaskName(home){return`bsk-daemon-${createHash("sha256").update(path9.resolve(home).toLowerCase()).digest("hex").slice(0,12)}`}function windowsDaemonLaunch(home,bskBin){const literal=(value)=>`'${value.replace(/['\u2018\u2019\u201A\u201B]/g,(quote)=>quote+quote)}'`;const script=`$env:BSK_HOME = ${literal(home)}; & ${literal(bskBin)} daemon start --foreground; exit $LASTEXITCODE`;return`--headless powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function startDaemonInWindowsTask({home,bskBin,timeoutMs}){const script=["$action = New-ScheduledTaskAction -Execute (Join-Path $env:SystemRoot 'System32\\conhost.exe') -Argument $env:BSK_TASK_ARGUMENT","$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew","Register-ScheduledTask -TaskName $env:BSK_TASK_NAME -Action $action -Settings $settings -Force | Out-Null","Start-ScheduledTask -TaskName $env:BSK_TASK_NAME"].join("; ");return runToExit("powershell.exe",["-NoProfile","-NonInteractive","-Command",script],{env:{...process.env,BSK_TASK_NAME:windowsDaemonTaskName(home),BSK_TASK_ARGUMENT:windowsDaemonLaunch(home,bskBin)},timeoutMs,label:"registering the bsk daemon task"})}function runToExit(command,args,{env,timeoutMs,label}){return new Promise((resolve,reject)=>{const child=spawn3(command,args,{env,stdio:["ignore","pipe","pipe"],windowsHide:true});let output="";const keep=(chunk)=>{output=(output+chunk).slice(-4096)};child.stdout.on("data",keep);child.stderr.on("data",keep);const timer=setTimeout(()=>{child.kill("SIGKILL");reject(new Error(`${label} did not return within ${timeoutMs}ms`))},timeoutMs);child.on("error",(error)=>{clearTimeout(timer);reject(new Error(`could not run ${command}: ${error.message}`))});child.on("exit",(code)=>{clearTimeout(timer);resolve({code,output:output.trim()})})})}async function startDaemonWithCli({home,env=process.env,bskBin=findBskBinary(env),timeoutMs=20000}={}){const status=await runToExit(bskBin,["status","--json"],{env:{...env,BSK_HOME:home},timeoutMs,label:"bsk status"});if(status.code===0)return;if(process.platform==="win32"&&NO_BREAKAWAY.test(status.output)){const task=await startDaemonInWindowsTask({home,bskBin,timeoutMs});if(task.code===0)return;throw new Error(`registering the bsk daemon task exited with ${task.code}${task.output?`: ${task.output}`:""}`)}throw new Error(`bsk status exited with ${status.code}${status.output?`: ${status.output}`:""}`)}var DEFAULT_TIMEOUT_MS2=35000;var DISCOVERY_RETRY_MS=250;var DISCOVERY_BUDGET_MS=15000;var TOOL_TIMEOUT_GRACE_MS=5000;var HUMAN_WAIT_METHODS=new Set(["tool.request_help","tool.tab_borrow"]);var HUMAN_WAIT_BACKSTOP_MS=3600000;function ownBudgetMs(params){const budgets=[params?.timeout_ms,params?.confirmation_timeout_ms].filter((value)=>typeof value==="number");return budgets.length>0?Math.max(...budgets)+TOOL_TIMEOUT_GRACE_MS:undefined}var PROBE_TIMEOUT_MS=2000;function defaultSocketPath(home){return path10.join(home,"run","daemon.sock")}function probeSocket(sockPath){if(process.platform==="win32"||!existsSync3(sockPath))return Promise.resolve(false);return new Promise((resolve)=>{const socket=connect2(sockPath);const done=(alive)=>{clearTimeout(timer);socket.destroy();resolve(alive)};const timer=setTimeout(()=>done(false),PROBE_TIMEOUT_MS);socket.on("error",()=>done(false));socket.on("connect",()=>socket.write(JSON.stringify({id:"probe-orphan",method:"system.ping"})+`
1523
- `));socket.on("data",()=>done(true))})}class BskRpcError extends Error{constructor(code,message,data){super(message);this.name="BskRpcError";this.code=code;this.data=data}}function shortId(){return randomBytes(6).toString("hex")}function sleep2(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}class BskIpcClient{#home;#sockPath;#autoStart;#startDaemon;#timeoutMs;#starting=null;constructor({home,env=process.env,sockPath,autoStart,startDaemon,timeoutMs=DEFAULT_TIMEOUT_MS2,bskBin}={}){this.#home=home??resolveBskHome(env);this.#sockPath=sockPath??null;this.#autoStart=autoStart??env.BSK_AUTO_START!=="0";this.#startDaemon=startDaemon??(()=>startDaemonWithCli({home:this.#home,env,bskBin}));this.#timeoutMs=timeoutMs}get home(){return this.#home}async resolveSocket({isAborted=()=>false}={}){if(this.#sockPath)return this.#sockPath;const found=readDaemonInfo(this.#home);if(found)return found.sock_path;const orphan=defaultSocketPath(this.#home);if(existsSync3(orphan)){if(await probeSocket(orphan))return orphan;if(isAborted())throw new BskRpcError("cancelled","cancelled before the daemon was located")}if(!this.#autoStart){throw new BskRpcError("no_daemon",`no BrowserSkill daemon published at ${this.#home}/daemon.json and automatic start is disabled (BSK_AUTO_START=0); run \`bsk daemon start\` in the environment that owns it`)}if(!this.#starting)this.#starting=this.#startDaemon().finally(()=>{this.#starting=null});await this.#starting;const deadline=Date.now()+DISCOVERY_BUDGET_MS;while(Date.now()<deadline&&!isAborted()){const info=readDaemonInfo(this.#home);if(info)return info.sock_path;await sleep2(DISCOVERY_RETRY_MS)}if(isAborted())throw new BskRpcError("cancelled","cancelled while waiting for the daemon to publish daemon.json");throw new BskRpcError("no_daemon",`daemon start was requested but ${this.#home}/daemon.json never appeared`)}call(method,params,options={}){return this.callWithHandle(method,params,options).promise}callWithHandle(method,params,{idPrefix=method.replace(/[^a-z0-9]+/gi,"-"),timeoutMs}={}){const ownBudget=ownBudgetMs(params);const humanWait=HUMAN_WAIT_METHODS.has(method);const waitMs=humanWait&&ownBudget===undefined&&timeoutMs===undefined?HUMAN_WAIT_BACKSTOP_MS:Math.max(timeoutMs??this.#timeoutMs,ownBudget??0);const rpcId=`${idPrefix}-${shortId()}`;const frame={id:rpcId,method};if(params!==undefined)frame.params=params;let aborted=false;let abortSocket=()=>{};const promise=(async()=>{const sockPath=await this.resolveSocket({isAborted:()=>aborted});if(aborted)throw new BskRpcError("cancelled",`${method} cancelled by caller`);return new Promise((resolve,reject)=>{const socket=connect2(sockPath);let buffer="";let settled=false;const finish=(fn,value)=>{if(settled)return;settled=true;clearTimeout(timer);socket.destroy();fn(value)};const timer=setTimeout(()=>{const cancels=method!=="cancel"&&!humanWait;finish(reject,new BskRpcError("timeout",`${method} did not answer within ${waitMs}ms${cancels?"; a cancel was requested at the daemon":""}`));if(cancels)this.cancel(rpcId).catch(()=>{})},waitMs);abortSocket=()=>finish(reject,new BskRpcError("cancelled",`${method} cancelled by caller`));socket.on("error",(error)=>finish(reject,new BskRpcError("no_daemon",`IPC socket ${sockPath}: ${error.code??error.message}`)));socket.on("connect",()=>socket.write(JSON.stringify(frame)+`
1510
+ `)}function dispose(){if(disposed)return;disposed=true;for(const off of unsubscribers.splice(0,unsubscribers.length))off();for(const waiter of[...waiters])waiter.reject(Error("Network snoop disposed"));waiters.clear();inflight.clear()}return{pop,peek,popJson,waitFor,summary,dispose}}function globToRegExp(glob){let source="";for(const char of glob){if(char==="*")source+=".*";else if(char==="?")source+=".";else if("\\^$+{}[]()|.".includes(char))source+=`\\${char}`;else source+=char}return new RegExp(`^${source}$`)}function hasGlobChars(value){return value.includes("*")||value.includes("?")}function matches(match,request){if(typeof match==="function"){return Boolean(match({url:request.url,method:request.method,resourceType:request.resourceType,headers:request.headers}))}if(match instanceof RegExp)return match.test(request.url);if(typeof match==="string"){if(hasGlobChars(match))return globToRegExp(match).test(request.url);return request.url.includes(match)}return false}function sameMatch(left,right){if(left===right)return true;if(left instanceof RegExp&&right instanceof RegExp)return left.source===right.source&&left.flags===right.flags;return false}function toHeaderEntries(headers){if(!headers)return[];if(Array.isArray(headers)){return headers.map((header)=>({name:String(header.name),value:String(header.value??"")}))}return Object.entries(headers).map(([name,value])=>({name,value:String(value??"")}))}function encodeBody(body){if(body==null)return"";if(Buffer.isBuffer(body))return body.toString("base64");if(body instanceof Uint8Array)return Buffer.from(body).toString("base64");return Buffer.from(String(body)).toString("base64")}function buildContinue(requestId,{url,method,headers,postData}={}){const params={requestId};if(url!==undefined)params.url=url;if(method!==undefined)params.method=method;if(headers!==undefined)params.headers=toHeaderEntries(headers);if(postData!==undefined)params.postData=encodeBody(postData);return params}function buildFulfill(requestId,{status=200,headers={},contentType,body=""}={}){const responseHeaders=toHeaderEntries(headers);if(contentType!=null&&String(contentType).length>0){const hasType=responseHeaders.some((header)=>header.name.toLowerCase()==="content-type");if(!hasType)responseHeaders.push({name:"content-type",value:String(contentType)})}return{requestId,responseCode:status,responseHeaders,body:encodeBody(body)}}function createRoutes(page){if(!page?.cdp)throw new TypeError("createRoutes requires a page with cdp");const entries=[];const warned=new WeakSet;const settledIds=new Set;let enabled=false;let sessionId;let unsubscribe=null;let enablePromise=null;function warnOnce(handler,error){if(typeof handler==="function"){if(warned.has(handler))return;warned.add(handler)}if(error)console.warn("[routes] route handler failed; continuing request",error);else console.warn("[routes] route handler did not settle the request; continuing")}function findHandler(request){for(const entry of entries){if(matches(entry.match,request))return entry.handler}return}async function handlePaused(params,meta){if(!sessionId||meta?.sessionId!==sessionId)return;const requestId=params?.requestId;if(!requestId||settledIds.has(requestId))return;const request={url:params.request?.url??"",method:params.request?.method??"GET",headers:params.request?.headers??{},postData:params.request?.postData,resourceType:params.resourceType};let settled=false;const settle=(method,cdpParams)=>{if(settled)return Promise.resolve();settled=true;settledIds.add(requestId);return page.cdp.send(method,cdpParams,sessionId)};const route={request,continue(overrides={}){return settle("Fetch.continueRequest",buildContinue(requestId,overrides))},fulfill(options={}){return settle("Fetch.fulfillRequest",buildFulfill(requestId,options))},abort(errorReason="Failed"){return settle("Fetch.failRequest",{requestId,errorReason})}};const handler=findHandler(request);if(!handler){await settle("Fetch.continueRequest",{requestId});return}try{await handler(route)}catch(error){warnOnce(handler,error)}if(!settled){warnOnce(handler);await settle("Fetch.continueRequest",{requestId})}}function onPaused(params,meta){handlePaused(params,meta).catch((error)=>{console.warn("[routes] requestPaused handling failed",error)})}async function ensureEnabled(){if(enabled)return;if(!enablePromise){enablePromise=(async()=>{sessionId=await page.resolveSessionId();if(!unsubscribe)unsubscribe=page.cdp.on("Fetch.requestPaused",onPaused);await page.cdp.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]},sessionId);enabled=true})()}try{await enablePromise}catch(error){enablePromise=null;throw error}}async function disableFetch(){const pending=enablePromise;enablePromise=null;if(pending)await pending.catch(()=>{});if(unsubscribe){unsubscribe();unsubscribe=null}if(!enabled)return;enabled=false;await page.cdp.send("Fetch.disable",{},sessionId)}async function route(match,handler){if(typeof handler!=="function")throw new TypeError("handler must be a function");entries.push({match,handler});await ensureEnabled()}async function unroute(match){if(match===undefined)entries.length=0;else{for(let index=entries.length-1;index>=0;index-=1){if(sameMatch(entries[index].match,match))entries.splice(index,1)}}if(entries.length===0)await disableFetch()}async function dispose(){entries.length=0;await disableFetch()}return{route,unroute,dispose,get enabled(){return enabled}}}async function viewportOf(page){return page.viewportSize()??await page.evaluate(()=>({width:innerWidth,height:innerHeight}))}async function scrollOnce(page,mode){if(mode==="end"){await page.evaluate(()=>scrollTo(0,document.scrollingElement.scrollHeight));return}const viewport=await viewportOf(page);await page.mouse.move(Math.floor(viewport.width/2),Math.floor(viewport.height/2));await page.mouse.wheel(0,Math.floor(viewport.height*0.9))}async function*collectWhileScrolling(page,snoop,options={}){const{minItems=Infinity,maxScrolls=10,extract=(json)=>Array.isArray(json)?json:[],scroll="wheel",settleMs=800}=options;if(scroll!=="wheel"&&scroll!=="end")throw new TypeError(`Unknown scroll mode: ${String(scroll)}`);let rounds=0;let total=0;let lastHeight=null;let unchanged=0;let stoppedBecause="maxScrolls";for(;;){for(const json of snoop.popJson()){for(const item of extract(json)){total+=1;yield item}}if(total>=minItems){stoppedBecause="minItems";break}if(rounds>=maxScrolls){stoppedBecause="maxScrolls";break}const height=await page.evaluate(()=>document.scrollingElement.scrollHeight);if(lastHeight!==null&&height===lastHeight){unchanged+=1;if(unchanged>=2){stoppedBecause="noGrowth";break}}else{unchanged=0}lastHeight=height;await scrollOnce(page,scroll);rounds+=1;await new Promise((resolve)=>setTimeout(resolve,settleMs))}return{rounds,total,stoppedBecause}}import{mkdir as mkdir6,writeFile as writeFile2}from"node:fs/promises";import path11 from"node:path";var SLUG_MAX=48;var SNOOP_MAX_ENTRIES=5000;function slug(name){const value=String(name??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return(value||"step").slice(0,SLUG_MAX)}function messageOf(error){return error instanceof Error?error.message:String(error)}async function readConsole(page){const api=page.console;const entries=typeof api==="function"?await api.call(page):await api?.logs?.();return Array.isArray(entries)?entries:[]}function createTrace(page,options={}){if(!page?.cdp||typeof page.resolveSessionId!=="function"){throw new TypeError("createTrace requires a page with cdp and resolveSessionId")}const{dir,screenshots=true,network=true,console:consoleLogs=true,maxBodyBytes=1e6,events}=options;if(typeof dir!=="string"||dir.length===0)throw new TypeError("createTrace requires a dir");const shotDir=path11.join(dir,"screenshots");const ready=mkdir6(shotDir,{recursive:true});const startedAt=Date.now();const records=[];const netEntries=[];const unsubscribers=[];const snoop=network?createNetworkSnoop(page,{bodies:true,maxBodyBytes,maxEntries:SNOOP_MAX_ENTRIES}):null;let seq=0;let consoleSeen=0;let sessionId=null;let stopped=false;let stopping=null;function record(event){const entry={...event,ts:Date.now(),seq:seq++};records.push(entry);return entry}const sessionReady=Promise.resolve(page.resolveSessionId()).then((id)=>{sessionId=id});sessionReady.catch((error)=>record({kind:"warning",scope:"session",message:messageOf(error)}));unsubscribers.push(page.cdp.on("Page.frameNavigated",(params,meta)=>{if(stopped||params?.frame?.parentId)return;const add=()=>record({kind:"navigation",url:params?.frame?.url??"",frameId:params?.frame?.id??null});if(sessionId===null){sessionReady.then(()=>{if(!stopped&&meta?.sessionId===sessionId)add()}).catch(()=>{});return}if(meta?.sessionId===sessionId)add()}));unsubscribers.push(page.on("dialog",(dialog)=>record({kind:"dialog",type:dialog?.type??null,message:dialog?.message??"",defaultPrompt:dialog?.defaultPrompt??"",url:dialog?.url??null})));if(events){unsubscribers.push(events.on("downloadStarted",(payload)=>record({kind:"download",phase:"started",...payload})));unsubscribers.push(events.on("downloadFinished",(payload)=>record({kind:"download",phase:"finished",...payload})))}async function capture(step,phase){const file=path11.join(shotDir,`${step.seq}-${slug(step.name)}-${phase}.png`);try{await writeFile2(file,await page.screenshot({type:"png"}));step.screenshots[phase]=file}catch(error){record({kind:"warning",scope:`screenshot:${phase}`,step:step.seq,message:messageOf(error)})}}function drainNetwork(){for(const entry of snoop?.pop()??[]){if(typeof entry.body==="string"&&Buffer.byteLength(entry.body)>maxBodyBytes){entry.body=null;entry.bodySkipped=true}netEntries.push(entry);record({kind:"network",...entry})}}async function drainConsole(){if(!consoleLogs)return;let entries;try{entries=await readConsole(page)}catch{return}if(entries.length<consoleSeen)consoleSeen=0;for(const entry of entries.slice(consoleSeen))record({kind:"console",...entry});consoleSeen=entries.length}async function drain(){drainNetwork();await drainConsole()}async function step(name,fn){if(typeof fn!=="function")throw new TypeError("trace.step requires a function");await ready;const entry=record({kind:"step",name:String(name),startedAt:Date.now(),screenshots:{}});if(screenshots)await capture(entry,"before");try{return await fn()}catch(error){entry.error=messageOf(error);throw error}finally{entry.endedAt=Date.now();entry.durationMs=entry.endedAt-entry.startedAt;if(screenshots)await capture(entry,"after");await drain()}}function mark(name,data){return record({kind:"mark",name:String(name),data:data??null})}async function finish(){await ready;await drain();stopped=true;for(const off of unsubscribers.splice(0,unsubscribers.length))off();snoop?.dispose();const ordered=[...records].sort((a,b)=>a.seq-b.seq);const summary={steps:ordered.filter((entry)=>entry.kind==="step").length,events:ordered.length,network:netEntries.length,startedAt,endedAt:Date.now(),url:page.url()};await writeFile2(path11.join(dir,"trace.jsonl"),ordered.map((entry)=>`${JSON.stringify(entry)}
1511
+ `).join(""));await writeFile2(path11.join(dir,"trace.har"),`${JSON.stringify(toHar(netEntries),null,2)}
1512
+ `);await writeFile2(path11.join(dir,"summary.json"),`${JSON.stringify(summary,null,2)}
1513
+ `);return summary}function stop(){return stopping??=finish()}return{step,mark,stop,get dir(){return dir}}}import{connect as connect2}from"node:net";import{existsSync as existsSync3}from"node:fs";import path13 from"node:path";import{randomBytes}from"node:crypto";import{existsSync as existsSync2,readFileSync as readFileSync3}from"node:fs";import{homedir as homedir2}from"node:os";import path12 from"node:path";import{spawn as spawn4}from"node:child_process";import{createHash as createHash2}from"node:crypto";function resolveBskHome(env=process.env){const override=env.BSK_HOME;if(typeof override==="string"&&override.length>0)return override;const home=env.HOME&&env.HOME.length>0?env.HOME:homedir2();return path12.join(home,".bsk")}function daemonInfoPath(home){return path12.join(home,"daemon.json")}function readDaemonInfo(home){let raw;try{raw=readFileSync3(daemonInfoPath(home),"utf8")}catch{return null}let info;try{info=JSON.parse(raw)}catch{return null}if(!info||typeof info.sock_path!=="string"||info.sock_path.length===0)return null;return info}function findBskBinary(env=process.env){const home=env.HOME&&env.HOME.length>0?env.HOME:homedir2();const candidates=[env.BSK_BIN,path12.join(home,".local","bin",process.platform==="win32"?"bsk.exe":"bsk")].filter(Boolean);for(const candidate of candidates)if(existsSync2(candidate))return candidate;return"bsk"}var NO_BREAKAWAY=/Job Object/;function windowsDaemonTaskName(home){return`bsk-daemon-${createHash2("sha256").update(path12.resolve(home).toLowerCase()).digest("hex").slice(0,12)}`}function windowsDaemonLaunch(home,bskBin){const literal=(value)=>`'${value.replace(/['\u2018\u2019\u201A\u201B]/g,(quote)=>quote+quote)}'`;const script=`$env:BSK_HOME = ${literal(home)}; & ${literal(bskBin)} daemon start --foreground; exit $LASTEXITCODE`;return`--headless powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function startDaemonInWindowsTask({home,bskBin,timeoutMs}){const script=["$action = New-ScheduledTaskAction -Execute (Join-Path $env:SystemRoot 'System32\\conhost.exe') -Argument $env:BSK_TASK_ARGUMENT","$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew","Register-ScheduledTask -TaskName $env:BSK_TASK_NAME -Action $action -Settings $settings -Force | Out-Null","Start-ScheduledTask -TaskName $env:BSK_TASK_NAME"].join("; ");return runToExit("powershell.exe",["-NoProfile","-NonInteractive","-Command",script],{env:{...process.env,BSK_TASK_NAME:windowsDaemonTaskName(home),BSK_TASK_ARGUMENT:windowsDaemonLaunch(home,bskBin)},timeoutMs,label:"registering the bsk daemon task"})}function runToExit(command,args,{env,timeoutMs,label}){return new Promise((resolve,reject)=>{const child=spawn4(command,args,{env,stdio:["ignore","pipe","pipe"],windowsHide:true});let output="";const keep=(chunk)=>{output=(output+chunk).slice(-4096)};child.stdout.on("data",keep);child.stderr.on("data",keep);const timer=setTimeout(()=>{child.kill("SIGKILL");reject(new Error(`${label} did not return within ${timeoutMs}ms`))},timeoutMs);child.on("error",(error)=>{clearTimeout(timer);reject(new Error(`could not run ${command}: ${error.message}`))});child.on("exit",(code)=>{clearTimeout(timer);resolve({code,output:output.trim()})})})}async function startDaemonWithCli({home,env=process.env,bskBin=findBskBinary(env),timeoutMs=20000}={}){const status=await runToExit(bskBin,["status","--json"],{env:{...env,BSK_HOME:home},timeoutMs,label:"bsk status"});if(status.code===0)return;if(process.platform==="win32"&&NO_BREAKAWAY.test(status.output)){const task=await startDaemonInWindowsTask({home,bskBin,timeoutMs});if(task.code===0)return;throw new Error(`registering the bsk daemon task exited with ${task.code}${task.output?`: ${task.output}`:""}`)}throw new Error(`bsk status exited with ${status.code}${status.output?`: ${status.output}`:""}`)}var DEFAULT_TIMEOUT_MS2=35000;var DISCOVERY_RETRY_MS=250;var DISCOVERY_BUDGET_MS=15000;var TOOL_TIMEOUT_GRACE_MS=5000;var HUMAN_WAIT_METHODS=new Set(["tool.request_help","tool.tab_borrow"]);var HUMAN_WAIT_BACKSTOP_MS=3600000;function ownBudgetMs(params){const budgets=[params?.timeout_ms,params?.confirmation_timeout_ms].filter((value)=>typeof value==="number");return budgets.length>0?Math.max(...budgets)+TOOL_TIMEOUT_GRACE_MS:undefined}var PROBE_TIMEOUT_MS=2000;function defaultSocketPath(home){return path13.join(home,"run","daemon.sock")}function probeSocket(sockPath){if(process.platform==="win32"||!existsSync3(sockPath))return Promise.resolve(false);return new Promise((resolve)=>{const socket=connect2(sockPath);const done=(alive)=>{clearTimeout(timer);socket.destroy();resolve(alive)};const timer=setTimeout(()=>done(false),PROBE_TIMEOUT_MS);socket.on("error",()=>done(false));socket.on("connect",()=>socket.write(JSON.stringify({id:"probe-orphan",method:"system.ping"})+`
1514
+ `));socket.on("data",()=>done(true))})}class BskRpcError extends Error{constructor(code,message,data){super(message);this.name="BskRpcError";this.code=code;this.data=data}}function shortId(){return randomBytes(6).toString("hex")}function sleep3(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}class BskIpcClient{#home;#sockPath;#autoStart;#startDaemon;#timeoutMs;#starting=null;constructor({home,env=process.env,sockPath,autoStart,startDaemon,timeoutMs=DEFAULT_TIMEOUT_MS2,bskBin}={}){this.#home=home??resolveBskHome(env);this.#sockPath=sockPath??null;this.#autoStart=autoStart??env.BSK_AUTO_START!=="0";this.#startDaemon=startDaemon??(()=>startDaemonWithCli({home:this.#home,env,bskBin}));this.#timeoutMs=timeoutMs}get home(){return this.#home}async resolveSocket({isAborted=()=>false}={}){if(this.#sockPath)return this.#sockPath;const found=readDaemonInfo(this.#home);if(found)return found.sock_path;const orphan=defaultSocketPath(this.#home);if(existsSync3(orphan)){if(await probeSocket(orphan))return orphan;if(isAborted())throw new BskRpcError("cancelled","cancelled before the daemon was located")}if(!this.#autoStart){throw new BskRpcError("no_daemon",`no BrowserSkill daemon published at ${this.#home}/daemon.json and automatic start is disabled (BSK_AUTO_START=0); run \`bsk daemon start\` in the environment that owns it`)}if(!this.#starting)this.#starting=this.#startDaemon().finally(()=>{this.#starting=null});await this.#starting;const deadline=Date.now()+DISCOVERY_BUDGET_MS;while(Date.now()<deadline&&!isAborted()){const info=readDaemonInfo(this.#home);if(info)return info.sock_path;await sleep3(DISCOVERY_RETRY_MS)}if(isAborted())throw new BskRpcError("cancelled","cancelled while waiting for the daemon to publish daemon.json");throw new BskRpcError("no_daemon",`daemon start was requested but ${this.#home}/daemon.json never appeared`)}call(method,params,options={}){return this.callWithHandle(method,params,options).promise}callWithHandle(method,params,{idPrefix=method.replace(/[^a-z0-9]+/gi,"-"),timeoutMs}={}){const ownBudget=ownBudgetMs(params);const humanWait=HUMAN_WAIT_METHODS.has(method);const waitMs=humanWait&&ownBudget===undefined&&timeoutMs===undefined?HUMAN_WAIT_BACKSTOP_MS:Math.max(timeoutMs??this.#timeoutMs,ownBudget??0);const rpcId=`${idPrefix}-${shortId()}`;const frame={id:rpcId,method};if(params!==undefined)frame.params=params;let aborted=false;let abortSocket=()=>{};const promise=(async()=>{const sockPath=await this.resolveSocket({isAborted:()=>aborted});if(aborted)throw new BskRpcError("cancelled",`${method} cancelled by caller`);return new Promise((resolve,reject)=>{const socket=connect2(sockPath);let buffer="";let settled=false;const finish=(fn,value)=>{if(settled)return;settled=true;clearTimeout(timer);socket.destroy();fn(value)};const timer=setTimeout(()=>{const cancels=method!=="cancel"&&!humanWait;finish(reject,new BskRpcError("timeout",`${method} did not answer within ${waitMs}ms${cancels?"; a cancel was requested at the daemon":""}`));if(cancels)this.cancel(rpcId).catch(()=>{})},waitMs);abortSocket=()=>finish(reject,new BskRpcError("cancelled",`${method} cancelled by caller`));socket.on("error",(error)=>finish(reject,new BskRpcError("no_daemon",`IPC socket ${sockPath}: ${error.code??error.message}`)));socket.on("connect",()=>socket.write(JSON.stringify(frame)+`
1524
1515
  `));socket.on("data",(chunk)=>{buffer+=chunk.toString("utf8");const idx=buffer.indexOf(`
1525
1516
  `);if(idx===-1)return;try{finish(resolve,decodeResponse(buffer.slice(0,idx),rpcId,method))}catch(error){finish(reject,error)}});socket.on("close",()=>finish(reject,new BskRpcError("protocol_error",`${method}: daemon closed the connection without a reply`)))})})();return{rpcId,promise,abort:()=>{aborted=true;abortSocket()}}}async cancel(rpcId){return this.call("cancel",{rpc_id:rpcId},{idPrefix:"cancel",timeoutMs:2000})}}function decodeResponse(line,rpcId,method){let reply;try{reply=JSON.parse(line)}catch{throw new BskRpcError("protocol_error",`${method}: daemon reply is not JSON: ${line.slice(0,120)}`)}const undecodableFrame=reply.id==="0"&&reply.error;if(reply.id!==rpcId&&!undecodableFrame){throw new BskRpcError("protocol_error",`${method}: reply id ${reply.id} does not match request ${rpcId}`)}if(reply.error){const{code="protocol_error",message="daemon error",data}=reply.error;throw new BskRpcError(code,message,data)}return reply.result}var REF_SHAPE=/^@?e\d+$/;function resolveTarget(target){if(typeof target==="string"){return REF_SHAPE.test(target)?{ref:target}:{selector:target}}if(target&&typeof target==="object"){if(typeof target.ref==="string")return{ref:target.ref};if(typeof target.selector==="string")return{selector:target.selector};if(typeof target.captureId==="string"){return{capture_id:target.captureId,image_x:target.x,image_y:target.y}}}throw new TypeError("target must be a ref ('e3' / '@e3'), a CSS selector, or {captureId, x, y}")}function optionalTarget(target){return target===undefined?{}:resolveTarget(target)}function compact(params){const out={};for(const[key,value]of Object.entries(params))if(value!==undefined)out[key]=value;return out}async function captureScreenshot(session,{ref,tabId,fullPage=false,scope,timeoutMs}={}){if(!fullPage){const result=await session.tool("screenshot",{ref,tab_id:tabId});return{buffer:Buffer.from(result.image_base64,"base64"),width:result.width,height:result.height,format:result.format,captureId:result.capture_id??null,captureUnavailable:result.capture_unavailable??null,tabId:result.tab_id,dialogs:result.dialogs??[]}}const started=await session.tool("screenshot_full_page",{scope,tab_id:tabId,timeout_ms:timeoutMs});const buffer=await readCapture(session,started.capture_id,started.byte_size);return{buffer,width:started.width,height:started.height,format:started.format,captureId:started.capture_id,scope:started.scope??scope??null,tabId:started.tab_id,dialogs:started.dialogs??[]}}async function readCapture(session,captureId,byteSize){const chunks=[];let offset=0;try{for(;;){const chunk=await session.tool("screenshot_read",{capture_id:captureId,offset});const bytes=Buffer.from(chunk.data_base64??"","base64");chunks.push(bytes);if(chunk.eof||bytes.length===0)break;if(chunk.next_offset<=offset)throw new Error(`screenshot_read did not advance past offset ${offset}`);offset=chunk.next_offset}}finally{await session.tool("screenshot_release",{capture_id:captureId}).catch(()=>{})}const buffer=Buffer.concat(chunks);if(typeof byteSize==="number"&&buffer.length!==byteSize){throw new Error(`screenshot capture ${captureId}: expected ${byteSize} bytes, assembled ${buffer.length}`)}return buffer}var SESSION_STOP_TIMEOUT_MS=3600000;class BskSession{#client;#stopped=false;constructor(client,{sessionId,browserInstanceId=null,agentWindowId=null,interaction=null}={}){if(typeof sessionId!=="string"||sessionId.length===0)throw new TypeError("BskSession requires a sessionId");this.#client=client;this.sessionId=sessionId;this.browserInstanceId=browserInstanceId;this.agentWindowId=agentWindowId;this.interaction=interaction}get client(){return this.#client}get stopped(){return this.#stopped}tool(name,params={}){if(this.#stopped)return Promise.reject(new Error(`BrowserSkill session ${this.sessionId} is stopped`));return this.#client.call(`tool.${name}`,compact({session_id:this.sessionId,...params}),{idPrefix:name.replace(/_/g,"-")})}navigate(url,{tabId,waitUntil,timeoutMs}={}){return this.tool("navigate",{url,tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs})}back({tabId,waitUntil,timeoutMs}={}){return this.tool("navigate_back",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs})}forward({tabId,waitUntil,timeoutMs}={}){return this.tool("navigate_forward",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs})}reload({tabId,waitUntil,timeoutMs,hard}={}){return this.tool("reload",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs,hard})}observe({cursor,tabId,maxDepth,maxTokens,debugSurfaces,probeHover}={}){return this.tool("observe",{cursor,tab_id:tabId,max_depth:maxDepth,max_tokens:maxTokens,debug_surfaces:debugSurfaces,probe_hover:probeHover})}snapshot({tabId,maxDepth,maxTokens}={}){return this.tool("snapshot",{tab_id:tabId,max_depth:maxDepth,max_tokens:maxTokens})}getHtml({ref,tabId,maxBytes}={}){return this.tool("get_html",{ref,tab_id:tabId,max_bytes:maxBytes})}screenshot(options){return captureScreenshot(this,options)}click(target,{button,clickCount,modifiers,tabId,timeoutMs}={}){return this.tool("click",{...resolveTarget(target),button,click_count:clickCount,modifiers,tab_id:tabId,timeout_ms:timeoutMs})}hover(target,{modifiers,settleMs,tabId,timeoutMs}={}){return this.tool("hover",{...resolveTarget(target),modifiers,settle_ms:settleMs,tab_id:tabId,timeout_ms:timeoutMs})}focus(target,{tabId,timeoutMs}={}){return this.tool("focus",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs})}blur(target,{tabId,timeoutMs}={}){return this.tool("blur",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs})}fill(target,value,{clearBefore,tabId,timeoutMs}={}){return this.tool("fill",{...resolveTarget(target),value,clear_before:clearBefore,tab_id:tabId,timeout_ms:timeoutMs})}press(key,{target,modifiers,holdMs,tabId,timeoutMs}={}){return this.tool("press",{key,...optionalTarget(target),modifiers,hold_ms:holdMs,tab_id:tabId,timeout_ms:timeoutMs})}select(target,values,{tabId,timeoutMs}={}){return this.tool("select",{...resolveTarget(target),values:Array.isArray(values)?values:[values],tab_id:tabId,timeout_ms:timeoutMs})}scrollTo(target,{tabId,timeoutMs}={}){return this.tool("scroll_to",{...resolveTarget(target),tab_id:tabId,timeout_ms:timeoutMs})}wheel({deltaX=0,deltaY=0,target,modifiers,tabId,timeoutMs}={}){return this.tool("wheel",{...optionalTarget(target),delta_x:deltaX,delta_y:deltaY,modifiers,tab_id:tabId,timeout_ms:timeoutMs})}evaluate(expression,{tabId,awaitPromise,returnByValue,timeoutMs}={}){return this.tool("evaluate",{expression,tab_id:tabId,await_promise:awaitPromise,return_by_value:returnByValue,timeout_ms:timeoutMs})}tabList({scope}={}){return this.tool("tab_list",{scope})}tabCreate({url,active,index}={}){return this.tool("tab_create",{url,active,index})}tabClose(tabId){return this.tool("tab_close",{tab_id:tabId})}tabSelect(tabId){return this.tool("tab_select",{tab_id:tabId})}tabBorrow(tabId,{confirmationTimeoutMs}={}){return this.tool("tab_borrow",{tab_id:tabId,confirmation_timeout_ms:confirmationTimeoutMs})}tabReturn(tabId){return this.tool("tab_return",{tab_id:tabId})}waitForNavigation({tabId,waitUntil,timeoutMs}={}){return this.tool("wait_for_navigation",{tab_id:tabId,wait_until:waitUntil,timeout_ms:timeoutMs})}requestHelp({prompt,title,targets,completionCriteria,tabId,timeoutMs}={}){return this.tool("request_help",{prompt,title,tab_id:tabId,timeout_ms:timeoutMs,targets:targets?.map((t)=>resolveTarget(t)),completion_criteria:completionCriteria})}console({tabId,since,limit,maxTextChars,includeStack}={}){return this.tool("console",{tab_id:tabId,since,limit,max_text_chars:maxTextChars,include_stack:includeStack})}network({tabId,since,limit,maxTextChars}={}){return this.tool("network",{tab_id:tabId,since,limit,max_text_chars:maxTextChars})}resize(width,height){return this.tool("window_resize",{width,height})}emulate({tabId,off,overrides}={}){return this.tool("emulate",{tab_id:tabId,off,overrides})}async stop(){if(this.#stopped)return null;this.#stopped=true;return this.#client.call("session.stop",{session_id:this.sessionId},{idPrefix:"session-stop",timeoutMs:SESSION_STOP_TIMEOUT_MS})}}var DEFAULT_WAIT_FOR_BROWSER_MS=15000;async function listBrowsers(client,{waitForBrowserMs}={}){const status=await client.call("system.status",compact({wait_for_browser_ms:waitForBrowserMs}),{idPrefix:"status"});return status.browsers??[]}async function connectBrowserSkill({client,home,env,sockPath,autoStart,timeoutMs,bskBin,name,browser,width,height,focused=false,waitForBrowserMs=DEFAULT_WAIT_FOR_BROWSER_MS}={}){const ipc=client??new BskIpcClient({home,env,sockPath,autoStart,timeoutMs,bskBin});const browsers=await listBrowsers(ipc,{waitForBrowserMs});if(browsers.length===0){throw new BskRpcError("no_browser_connected","the BrowserSkill daemon is up but no browser extension is connected; open the browser that has the BrowserSkill extension enabled (bskDoctor() explains the remaining step) instead of falling back to a headless browser")}const started=await ipc.call("session.start",compact({task_name:name,browser_instance_id:browser,width,height,focused}),{idPrefix:"session-start"});return new BskSession(ipc,{sessionId:started.session_id,browserInstanceId:started.browser_instance_id??null,agentWindowId:started.agent_window_id??null,interaction:started.interaction??null})}var CSS_PATH_FN=String(function cssPath(el){if(!(el instanceof Element))return null;if(el.getRootNode()!==document)return null;const parts=[];let node=el;while(node&&node.nodeType===1&&node!==document.documentElement){let part=node.localName;if(node.id&&/^[A-Za-z_][\w-]*$/.test(node.id)&&document.querySelectorAll("#"+node.id).length===1){parts.unshift("#"+node.id);return parts.join(" > ")}const parent=node.parentElement;if(parent){const same=Array.from(parent.children).filter((c)=>c.localName===node.localName);if(same.length>1)part+=`:nth-of-type(${same.indexOf(node)+1})`}parts.unshift(part);node=parent}parts.unshift("html");return parts.join(" > ")});function buildSnapshotExpression(options={}){return`(function () {
1526
1517
  const globalThis = {};
@@ -1531,5 +1522,5 @@ ${snapshot.tree}`}}var DEFAULT_TIMEOUT_MS=30000;var JSON_MIME=/^application\/jso
1531
1522
  const css = {};
1532
1523
  for (const ref of Object.keys(result.refs || {})) css[ref] = cssPath(api.elementRegistry.get(ref));
1533
1524
  return { tree: result.tree, refs: result.refs || {}, css, error: result.error };
1534
- })()`}async function bskSnapshot(session,{tabId,timeoutMs,...snapshotOptions}={}){const reply=await session.evaluate(buildSnapshotExpression(snapshotOptions),{tabId,timeoutMs,awaitPromise:false,returnByValue:true});if(!reply||reply.ok===false){const text=reply?.error?.text??"unknown error";throw new Error(`bskSnapshot failed inside the page: ${text}`)}const value=reply.value;if(!value||typeof value.tree!=="string")throw new Error("bskSnapshot: page returned no tree");if(value.error)throw new Error(`bskSnapshot: ${value.error}`);return{tree:value.tree,refs:value.refs,css:value.css}}import{existsSync as existsSync5,mkdirSync as mkdirSync2,readFileSync as readFileSync4,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{spawn as spawn4}from"node:child_process";import path12 from"node:path";import{existsSync as existsSync4}from"node:fs";import{homedir as homedir3}from"node:os";import path11 from"node:path";var BROWSERSKILL_EXTENSION_IDS=Object.freeze({chrome:"hhcmgoofomhgciiibhipgmgkgnoenaoi",edge:"emacgiaaaiojkkpkddmmdfhmokgmnikg"});var STORE_UPDATE_URLS=Object.freeze({chrome:"https://clients2.google.com/service/update2/crx",edge:"https://edge.microsoft.com/extensionwebstorebase/v1/crx"});var STORE_PAGE_URLS=Object.freeze({chrome:`https://chromewebstore.google.com/detail/${BROWSERSKILL_EXTENSION_IDS.chrome}`,edge:`https://microsoftedge.microsoft.com/addons/detail/browserskill/${BROWSERSKILL_EXTENSION_IDS.edge}`});var NON_CHROMIUM_DEFAULTS=Object.freeze([{id:"safari",label:"Safari",match:["com.apple.safari","safarihtml"]},{id:"firefox",label:"Firefox",match:["org.mozilla.firefox","firefox.desktop","firefoxurl","firefoxhtml"]},{id:"zen",label:"Zen",match:["app.zen-browser.zen","zen.desktop","zenhtml"]},{id:"orion",label:"Orion",match:["com.kagi.kagimacos"]}]);var MAC=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Library/Application Support/Google/Chrome",app:"Google Chrome",bundleId:"com.google.Chrome"},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Library/Application Support/Microsoft Edge",app:"Microsoft Edge",bundleId:"com.microsoft.edgemac"},{id:"brave",label:"Brave",store:"chrome",userData:"Library/Application Support/BraveSoftware/Brave-Browser",app:"Brave Browser",bundleId:"com.brave.Browser"},{id:"chromium",label:"Chromium",store:"chrome",userData:"Library/Application Support/Chromium",app:"Chromium",bundleId:"org.chromium.Chromium"},{id:"arc",label:"Arc",store:"chrome",userData:"Library/Application Support/Arc/User Data",app:"Arc",bundleId:"company.thebrowser.Browser"},{id:"dia",label:"Dia",store:"chrome",userData:"Library/Application Support/Dia/User Data",app:"Dia",bundleId:"company.thebrowser.dia"},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Library/Application Support/Vivaldi",app:"Vivaldi",bundleId:"com.vivaldi.Vivaldi"},{id:"opera",label:"Opera",store:"chrome",userData:"Library/Application Support/com.operasoftware.Opera",app:"Opera",bundleId:"com.operasoftware.Opera",externalExtensions:false},{id:"comet",label:"Comet",store:"chrome",userData:"Library/Application Support/Comet",app:"Comet",bundleId:"ai.perplexity.comet"},{id:"aside",label:"Aside",store:"chrome",userData:"Library/Application Support/Aside",app:"Aside",bundleId:"at.studio.AsideBrowser"},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Library/Application Support/Naver/Whale",app:"Naver Whale",bundleId:"com.naver.Whale"}];var LINUX=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:".config/google-chrome",binaries:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/opt/google/chrome/chrome"],externalDir:"/opt/google/chrome/extensions",userExternalDir:false,desktopIds:["google-chrome.desktop","google-chrome-stable.desktop","com.google.Chrome.desktop"],processNames:["chrome","google-chrome"]},{id:"chromium",label:"Chromium",store:"chrome",userData:".config/chromium",binaries:["/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],externalDir:"/usr/share/chromium/extensions",userExternalDir:true,desktopIds:["chromium.desktop","chromium-browser.desktop","chromium_chromium.desktop","org.chromium.Chromium.desktop"],processNames:["chromium","chromium-browse"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:".config/microsoft-edge",binaries:["/usr/bin/microsoft-edge","/opt/microsoft/msedge/msedge"],externalDir:"/usr/share/microsoft-edge/extensions",userExternalDir:false,desktopIds:["microsoft-edge.desktop","microsoft-edge-stable.desktop","com.microsoft.Edge.desktop"],processNames:["msedge"]},{id:"brave",label:"Brave",store:"chrome",userData:".config/BraveSoftware/Brave-Browser",binaries:["/usr/bin/brave-browser","/opt/brave.com/brave/brave"],externalDir:"/usr/share/brave/extensions",userExternalDir:false,desktopIds:["brave-browser.desktop","com.brave.Browser.desktop"],processNames:["brave"]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:".config/vivaldi",binaries:["/usr/bin/vivaldi","/opt/vivaldi/vivaldi"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["vivaldi-stable.desktop","vivaldi.desktop"],processNames:["vivaldi-bin"]},{id:"opera",label:"Opera",store:"chrome",userData:".config/opera",binaries:["/usr/bin/opera"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["opera.desktop"],processNames:["opera"]}];var WINDOWS=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Google/Chrome/User Data",registryKey:"HKCU\\Software\\Google\\Chrome\\Extensions",binaryRel:"Google/Chrome/Application/chrome.exe",progIds:["chromehtml"],processNames:["chrome.exe"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Microsoft/Edge/User Data",registryKey:"HKCU\\Software\\Microsoft\\Edge\\Extensions",binaryRel:"Microsoft/Edge/Application/msedge.exe",progIds:["msedgehtm"],processNames:["msedge.exe"]},{id:"brave",label:"Brave",store:"chrome",userData:"BraveSoftware/Brave-Browser/User Data",registryKey:"HKCU\\Software\\BraveSoftware\\Brave-Browser\\Extensions",binaryRel:"BraveSoftware/Brave-Browser/Application/brave.exe",progIds:["bravehtml"],processNames:["brave.exe"]},{id:"chromium",label:"Chromium",store:"chrome",userData:"Chromium/User Data",registryKey:"HKCU\\Software\\Chromium\\Extensions",binaryRel:"Chromium/Application/chrome.exe",progIds:["chromiumhtm"],processNames:[]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Vivaldi/User Data",registryKey:null,externalExtensions:false,binaryRel:"Vivaldi/Application/vivaldi.exe",progIds:["vivaldihtm"],processNames:["vivaldi.exe"]},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Naver/Naver Whale/User Data",registryKey:null,externalExtensions:false,binaryRel:"Naver/Naver Whale/Application/whale.exe",progIds:["whalehtml"],processNames:["whale.exe"]}];var BROWSER_IDS=Object.freeze([...new Set([...MAC,...LINUX,...WINDOWS].map((b)=>b.id))]);function macRow(b,home,exists){const apps=[path11.join("/Applications",`${b.app}.app`),path11.join(home,"Applications",`${b.app}.app`)];const appPath=apps.find((p)=>exists(p))??null;const userDataDir=path11.join(home,b.userData);return{id:b.id,label:b.label,store:b.store,userDataDir,binary:path11.join(appPath??apps[0],"Contents","MacOS",b.app),bundleId:b.bundleId,processNames:apps.map((a)=>path11.join(a,"Contents","MacOS",b.app)),defaultIds:[b.bundleId.toLowerCase()],externalExtensions:b.externalExtensions!==false,installed:appPath!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function linuxRow(b,home,exists){const userDataDir=path11.join(home,b.userData);const binary=b.binaries.find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,binary,externalDir:b.externalDir,userExternalDir:b.userExternalDir,processNames:b.processNames,defaultIds:b.desktopIds.map((d)=>d.toLowerCase()),externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function windowsRow(b,env,home,exists){const localAppData=env.LOCALAPPDATA??path11.join(home,"AppData","Local");const programFiles=[localAppData,env.PROGRAMFILES,env["PROGRAMFILES(X86)"],"C:\\Program Files","C:\\Program Files (x86)"].filter(Boolean);const userDataDir=path11.join(localAppData,b.userData);const binary=programFiles.map((root)=>path11.join(root,b.binaryRel)).find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,registryKey:b.registryKey,binary,processNames:b.processNames,defaultIds:b.progIds,externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function catalogBrowsers({platform=process.platform,home=homedir3(),env=process.env,exists=existsSync4}={}){if(platform==="darwin")return MAC.map((b)=>macRow(b,home,exists));if(platform==="linux")return LINUX.map((b)=>linuxRow(b,home,exists));if(platform==="win32")return WINDOWS.map((b)=>windowsRow(b,env,home,exists));return[]}function detectBrowsers(options={}){return catalogBrowsers(options).filter((b)=>b.installed)}var ENABLE_STEP=(browser)=>`Quit ${browser} completely and open it again; a dialog offers to enable "BrowserSkill" — click Enable.`;var BADGE_STEP=(browser)=>`In ${browser}, open the menu (the badge on the toolbar) and enable "BrowserSkill" when prompted; no restart is needed.`;var storeStep=(browser,label)=>`Open ${STORE_PAGE_URLS[browser.store]} in ${label} and click the "Add" button.`;function externalExtensionEntry({platform=process.platform,browser}){const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const updateUrl=STORE_UPDATE_URLS[browser.store];const label=browser.label??browser.id.charAt(0).toUpperCase()+browser.id.slice(1);if(browser.externalExtensions===false){return{kind:"store",needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:storeStep(browser,label)}}if(platform==="win32"){const key=`${browser.registryKey}\\${id}`;return{kind:"registry",key,needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],regAddArgs:["add",key,"/v","update_url","/t","REG_SZ","/d",updateUrl,"/f"],regDeleteArgs:["delete",key,"/f"],humanStep:BADGE_STEP(label)}}const content=JSON.stringify({external_update_url:updateUrl},null,2)+`
1535
- `;if(platform==="linux"&&!browser.userExternalDir){return{kind:"file",path:path12.join(browser.externalDir,`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:`Quit ${label} completely and open it again; the extension installs without a prompt.`}}return{kind:"file",path:path12.join(browser.userDataDir,"External Extensions",`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:platform==="linux"?`Quit ${label} completely and open it again; the extension installs without a prompt.`:ENABLE_STEP(label)}}function isBlocklisted(browser,id,{readFile=readFileSync4}={}){if(!browser.userDataDir)return false;for(const profile of["Default","Profile 1","Profile 2","Profile 3"]){const file=path12.join(browser.userDataDir,profile,"Preferences");let prefs;try{prefs=JSON.parse(readFile(file,"utf8"))}catch{continue}if(Array.isArray(prefs?.extensions?.external_uninstalls)&&prefs.extensions.external_uninstalls.includes(id))return true}return false}function runRegDefault(args){return new Promise((resolve)=>{const child=spawn4("reg",args,{stdio:["ignore","ignore","pipe"],windowsHide:true});let stderr="";child.stderr.on("data",(c)=>{stderr+=c});child.on("error",(error)=>resolve({code:-1,stderr:error.message}));child.on("exit",(code)=>resolve({code,stderr}))})}async function registerExternalExtension({platform=process.platform,browser,writeFile=writeFileSync2,readFile=readFileSync4,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const label=browser.label??browser.id;const storeStep=`Open ${entry.storeUrl} in ${label} and click the "Add" button.`;if(entry.kind==="store")return{...entry,registered:false,alreadyPresent:false,reason:"store_only"};if(isBlocklisted(browser,id,{readFile})){return{...entry,registered:false,alreadyPresent:false,reason:"blocklisted",humanStep:`The extension was removed from ${label} before, so external registration is ignored. ${storeStep}`}}if(entry.kind==="registry"){const result=await runReg(entry.regAddArgs);if(result.code!==0)return{...entry,registered:false,alreadyPresent:false,reason:"reg_failed",detail:result.stderr,humanStep:storeStep};return{...entry,registered:true,alreadyPresent:false}}let alreadyPresent=false;try{alreadyPresent=readFile(entry.path,"utf8")===entry.content}catch{}if(alreadyPresent)return{...entry,registered:true,alreadyPresent:true};try{mkdirSync2(path12.dirname(entry.path),{recursive:true});writeFile(entry.path,entry.content)}catch(error){if(error.code==="EACCES"||error.code==="EPERM"||error.code==="EROFS"){return{...entry,registered:false,alreadyPresent:false,reason:"not_writable",humanStep:`${entry.path} is not writable without administrator rights. ${storeStep}`}}throw error}return{...entry,registered:true,alreadyPresent:false}}async function unregisterExternalExtension({platform=process.platform,browser,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});if(entry.kind==="store")return{...entry,removed:false};if(entry.kind==="registry"){const result=await runReg(entry.regDeleteArgs);return{...entry,removed:result.code===0,detail:result.stderr}}const present=existsSync5(entry.path);if(present)rmSync2(entry.path,{force:true});return{...entry,removed:present}}import{execFile}from"node:child_process";import{statSync}from"node:fs";import{homedir as homedir4}from"node:os";import path13 from"node:path";var PROBE_TIMEOUT_MS2=3000;function runDefault(command,args){return new Promise((resolve)=>{execFile(command,args,{timeout:PROBE_TIMEOUT_MS2,windowsHide:true,maxBuffer:8*1024*1024},(error,stdout)=>{resolve(error?null:String(stdout))})})}function parseMacDefaultBrowser(plistJson){let handlers;try{handlers=JSON.parse(plistJson)?.LSHandlers}catch{return null}if(!Array.isArray(handlers))return null;const pick=(scheme)=>handlers.find((h)=>h?.LSHandlerURLScheme===scheme&&typeof h.LSHandlerRoleAll==="string");const handler=pick("https")??pick("http");return handler?handler.LSHandlerRoleAll.toLowerCase():"com.apple.safari"}function parseWindowsProgId(regOutput){const match=/ProgId\s+REG_SZ\s+(\S+)/i.exec(regOutput??"");return match?match[1].toLowerCase():null}function parseProcessNames(platform,output){const names=new Set;for(const raw of String(output??"").split(/\r?\n/)){const line=raw.trim();if(!line)continue;if(platform==="win32"){const image=/^"([^"]+)"/.exec(line)?.[1];if(image)names.add(image.toLowerCase())}else if(platform==="darwin"){if(/\.app\/Contents\/MacOS\/[^/]+$/.test(line))names.add(line)}else{names.add(path13.basename(line))}}return[...names]}async function probeDefault({platform,home,run}){if(platform==="darwin"){const plist=path13.join(home,"Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist");const json=await run("plutil",["-convert","json","-o","-",plist]);return json===null?null:parseMacDefaultBrowser(json)}if(platform==="linux"){const out=await run("xdg-settings",["get","default-web-browser"]);return out?.trim()?out.trim().toLowerCase():null}if(platform==="win32"){const key="HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice";return parseWindowsProgId(await run("reg",["query",key,"/v","ProgId"]))}return null}async function probeRunning({platform,run}){const out=platform==="win32"?await run("tasklist",["/fo","csv","/nh"]):await run("ps",platform==="darwin"?["-axo","comm="]:["-eo","comm="]);return out===null?null:parseProcessNames(platform,out)}function lastUsedAt(browser,stat){let latest=null;for(const rel of["Local State",path13.join("Default","History"),path13.join("Default","Preferences")]){try{const mtime=stat(path13.join(browser.userDataDir,rel)).mtimeMs;if(latest===null||mtime>latest)latest=mtime}catch{}}return latest}async function probeBrowserSignals({platform=process.platform,home=homedir4(),browsers=[],run=runDefault,stat=statSync}={}){const[defaultBrowser,running]=await Promise.all([probeDefault({platform,home,run}),probeRunning({platform,run})]);const lastUsed=Object.fromEntries(browsers.map((b)=>[b.id,lastUsedAt(b,stat)]));return{defaultBrowser,running,lastUsed}}var RECENT_USE_MS=7*24*60*60*1000;function matchesDefault(browser,defaultId){if(!defaultId)return false;return browser.defaultIds.some((id)=>defaultId===id||defaultId.startsWith(id))}function describeDefault(defaultId,catalog){if(defaultId===null||defaultId===undefined)return{raw:null,id:null,label:null,supported:null};const hit=catalog.find((b)=>matchesDefault(b,defaultId));if(hit)return{raw:defaultId,id:hit.id,label:hit.label,supported:true};const other=NON_CHROMIUM_DEFAULTS.find((b)=>b.match.some((m)=>defaultId===m||defaultId.startsWith(m)));return other?{raw:defaultId,id:other.id,label:other.label,supported:false}:{raw:defaultId,id:null,label:defaultId,supported:false}}function candidateRow(browser,{defaultBrowser,running,lastUsed},now){const isDefault=defaultBrowser.id===browser.id;const isRunning=Array.isArray(running)?browser.processNames.some((n)=>running.includes(n)||running.includes(n.toLowerCase())):null;const last=lastUsed?.[browser.id]??null;const recentlyUsed=last!==null&&now-last<=RECENT_USE_MS;const signals=[isDefault&&"default browser",isRunning&&"running now",recentlyUsed&&"used in the last 7 days"].filter(Boolean);return{id:browser.id,label:browser.label,installed:browser.installed,isDefault,running:isRunning,lastUsedAt:last===null?null:new Date(last).toISOString(),recentlyUsed,signals,browser}}function choose(candidates,primary,confidence,reason,defaultBrowser){return{primary:primary.browser,primaryId:primary.id,confidence,needsChoice:false,reason,defaultBrowser,candidates:candidates.map(({browser,...row})=>row)}}function ask(candidates,reason,defaultBrowser,suggested=null){return{primary:null,primaryId:null,confidence:null,needsChoice:true,reason,suggested,defaultBrowser,candidates:candidates.map(({browser,...row})=>row)}}function identifyBrowser({catalog,signals={},explicit=null,now=Date.now()}){const defaultBrowser=describeDefault(signals.defaultBrowser??null,catalog);const installed=catalog.filter((b)=>b.installed||b.id===explicit);const candidates=installed.map((b)=>candidateRow(b,{defaultBrowser,running:signals.running??null,lastUsed:signals.lastUsed},now));if(explicit){const hit=candidates.find((c)=>c.id===explicit);if(hit)return choose(candidates,hit,"explicit",`${hit.label} was chosen explicitly`,defaultBrowser);return ask(candidates,`"${explicit}" is not a Chromium-family browser this library knows; pick one of the candidates`,defaultBrowser)}if(candidates.length===0)return ask(candidates,"no Chromium-family browser is installed",defaultBrowser);const inUse=candidates.filter((c)=>c.running||c.recentlyUsed);const def=candidates.find((c)=>c.isDefault);if(def&&(def.running||def.recentlyUsed))return choose(candidates,def,"default-and-in-use",`${def.label} is the default browser and ${def.signals.slice(1).join(", ")}`,defaultBrowser);if(def&&inUse.length===0)return choose(candidates,def,"default",`${def.label} is the default browser`,defaultBrowser);if(def)return ask(candidates,`${def.label} is the default browser, but ${inUse.map((c)=>c.label).join(" and ")} ${inUse.length===1?"is":"are"} the one in use`,defaultBrowser);if(defaultBrowser.supported===false){const suggested=inUse.length===1?inUse[0].id:null;return ask(candidates,`the default browser is ${defaultBrowser.label}, which BrowserSkill cannot drive; the user has to name the Chromium browser to use`,defaultBrowser,suggested)}const runningNow=inUse.filter((c)=>c.running);if(inUse.length===1)return choose(candidates,inUse[0],"only-in-use",`${inUse[0].label} is the only browser ${inUse[0].signals.join(", ")}`,defaultBrowser);if(runningNow.length===1)return choose(candidates,runningNow[0],"only-running",`${runningNow[0].label} is the only browser running now`,defaultBrowser);if(inUse.length===0&&candidates.length===1)return choose(candidates,candidates[0],"only-installed",`${candidates[0].label} is the only Chromium-family browser installed`,defaultBrowser);return ask(candidates,inUse.length>1?`several browsers are in use (${inUse.map((c)=>c.label).join(", ")})`:"no browser shows recent use",defaultBrowser)}import{existsSync as existsSync6,readFileSync as readFileSync5,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{homedir as homedir5}from"node:os";import path14 from"node:path";import{spawn as spawn5}from"node:child_process";var INSTALL_SH="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.sh";var INSTALL_PS1="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.ps1";var RC_FILES=[".zshrc",".bashrc",".profile"];function cliInstallCommand({platform=process.platform,installDir,version}={}){const env={BSK_INSTALL_DIR:installDir};if(version)env.BSK_VERSION=version;if(platform==="win32"){return{command:"powershell",args:["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${INSTALL_PS1} | iex`],env}}return{command:"sh",args:["-c",`curl -fsSL ${INSTALL_SH} | sh`],env}}function runDefault2(command,args,env){return new Promise((resolve)=>{const child=spawn5(command,args,{env:{...process.env,...env},stdio:["ignore","pipe","pipe"],windowsHide:true});let stdout="",stderr="";child.stdout.on("data",(c)=>{stdout=(stdout+c).slice(-8192)});child.stderr.on("data",(c)=>{stderr=(stderr+c).slice(-8192)});child.on("error",(error)=>resolve({code:-1,stdout,stderr:error.message}));child.on("exit",(code)=>resolve({code,stdout,stderr}))})}function snapshotRcFiles(home){const snapshot=new Map;for(const name of RC_FILES){const file=path14.join(home,name);snapshot.set(file,existsSync6(file)?readFileSync5(file):null)}return snapshot}function restoreRcFiles(snapshot){const restored=[];for(const[file,before]of snapshot){const after=existsSync6(file)?readFileSync5(file):null;if(before===null&&after===null)continue;if(before!==null&&after!==null&&before.equals(after))continue;if(before===null)rmSync3(file,{force:true});else writeFileSync3(file,before);restored.push(file)}return restored}async function installBskCli({platform=process.platform,home=homedir5(),installDir=path14.join(home,".local","bin"),version,run=runDefault2}={}){const spec=cliInstallCommand({platform,installDir,version});const rcBefore=platform==="win32"?new Map:snapshotRcFiles(home);const result=await run(spec.command,spec.args,spec.env);const restoredRcFiles=restoreRcFiles(rcBefore);const bskBin=path14.join(installDir,platform==="win32"?"bsk.exe":"bsk");const installed=result.code===0&&existsSync6(bskBin);return{installed,bskBin:installed?bskBin:null,code:result.code,stdout:result.stdout,stderr:result.stderr,restoredRcFiles}}function cliVersionDefault(bskBin){return new Promise((resolve)=>{const child=spawn5(bskBin,["--version"],{stdio:["ignore","pipe","ignore"],windowsHide:true});let out="";child.stdout.on("data",(c)=>{out+=c});child.on("error",()=>resolve(null));child.on("exit",(code)=>resolve(code===0?out.trim():null))})}import{homedir as homedir6}from"node:os";import{existsSync as existsSync7,readFileSync as readFileSync6}from"node:fs";var DEFAULT_WAIT_TOTAL_MS=180000;function resolveBskBin(bskBin,env){if(bskBin===null)return null;return bskBin??findBskBinary(env)}async function cliReport({bskBin,env,cliVersion}){const bin=resolveBskBin(bskBin,env);if(!bin)return{installed:false,bskBin:null,version:null};const raw=await cliVersion(bin);return raw?{installed:true,bskBin:bin,version:raw.replace(/^bsk\s+/,"")}:{installed:false,bskBin:bin,version:null}}async function daemonReport(client,waitForBrowserMs){try{const status=await client.call("system.status",waitForBrowserMs>0?{wait_for_browser_ms:waitForBrowserMs}:{},{idPrefix:"status"});return{running:true,version:status.daemon_version,protocolVersion:status.protocol_version,browsers:status.browsers??[],sessions:status.sessions??[]}}catch(error){return{running:false,error:error.message,code:error.code,browsers:[],sessions:[]}}}var NO_BROWSER_STEP=`No Chromium-family browser was found. Install one (Chrome, Edge, Brave, Arc, ...), then add the extension from ${STORE_PAGE_URLS.chrome}.`;function withRegistration(platform,browser){const entry=externalExtensionEntry({platform,browser});const extensionRegistered=entry.kind==="file"&&existsSync7(entry.path)&&readFileSync6(entry.path,"utf8")===entry.content;return{...browser,registration:entry,extensionRegistered}}async function identify({platform,home,env,exists,browser,signals,probeSignals,now}){const catalog=catalogBrowsers({platform,home,env,exists}).map((b)=>withRegistration(platform,b));const observed=signals??await probeSignals({platform,home,browsers:catalog.filter((b)=>b.hasProfile)});const explicit=browser??env.OMOWRIGHT_BROWSER??null;const{primary,...identification}=identifyBrowser({catalog,signals:observed,explicit:explicit||null,now});const browsers=catalog.filter((b)=>b.installed);const registeredElsewhere=browsers.filter((b)=>b.extensionRegistered&&b.id!==identification.primaryId).map((b)=>b.id);return{browsers,identification:{...identification,registeredElsewhere},primary}}function choiceStep(identification){const listed=identification.candidates.map((c)=>`${c.label} [${c.id}]${c.signals.length?` — ${c.signals.join(", ")}`:""}`).join("; ");const hint=identification.suggested?` Likely ${identification.suggested}, but confirm first.`:"";return`Ask the user which browser they actually use (${identification.reason}). Candidates: ${listed}.${hint} Then re-run with browser: "<id>"; register nothing until they answer.`}function nextStepFor({cli,daemon,browsers,browsersConnected,identification,primary}){if(browsersConnected.length>0)return null;if(!cli.installed)return"Install the bsk CLI (bskOnboard() runs the official installer).";if(!daemon.running)return"Start the BrowserSkill daemon: run `bsk status` once, or `bsk daemon start` in the environment that owns it.";if(browsers.length===0&&!primary)return NO_BROWSER_STEP;if(identification.needsChoice)return choiceStep(identification);if(!primary.extensionRegistered&&primary.registration.kind!=="store")return`Register the BrowserSkill extension for ${primary.label} (bskOnboard() does this), then let the user enable it.`;return primary.registration.humanStep}async function bskDoctor({platform=process.platform,home=homedir6(),env=process.env,client,bskBin,cliVersion=cliVersionDefault,waitForBrowserMs=0,exists=existsSync7,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){const cli=await cliReport({bskBin,env,cliVersion});const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:false});const daemon=await daemonReport(ipc,waitForBrowserMs);const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,signals,probeSignals,now});const browsersConnected=daemon.browsers;const report={cli,daemon,browsers,primary:primary??null,identification,browsersConnected,ready:browsersConnected.length>0};report.nextStep=nextStepFor(report);return report}async function bskOnboard({platform=process.platform,home=homedir6(),env=process.env,client,bskBin,installDir,installCli=installBskCli,cliVersion=cliVersionDefault,onHumanStep=()=>{},waitForBrowserMs=15000,waitTotalMs=DEFAULT_WAIT_TOTAL_MS,exists=existsSync7,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){let cli=await cliReport({bskBin,env,cliVersion});let install=null;if(!cli.installed){install=await installCli({platform,home,installDir});cli=install.installed?await cliReport({bskBin:install.bskBin,env,cliVersion}):cli}const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:true});let daemon=await daemonReport(ipc,0);const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,signals,probeSignals,now});const registrations=[];let humanStep=null;let needsChoice=false;if(daemon.browsers.length===0){if(browsers.length===0&&!primary){humanStep=NO_BROWSER_STEP}else if(identification.needsChoice){needsChoice=true;humanStep=choiceStep(identification)}else{const registration=await registerExternalExtension({platform,browser:primary});registrations.push({browser:primary.id,...registration});humanStep=registration.humanStep;onHumanStep({browser:primary.id,step:registration.humanStep,registered:registration.registered,needsRestart:registration.needsRestart})}}const deadline=Date.now()+waitTotalMs;let browsersConnected=daemon.browsers;while(!needsChoice&&browsersConnected.length===0&&daemon.running&&Date.now()<deadline){browsersConnected=await listBrowsers(ipc,{waitForBrowserMs});if(waitForBrowserMs===0)break}daemon={...daemon,browsers:browsersConnected};const ready=browsersConnected.length>0;return{cli,install,daemon,browsers,primary:primary??null,identification,needsChoice,registrations,humanStep:ready?null:humanStep,browsersConnected,ready}}export{AgentTabManager,BROWSERSKILL_EXTENSION_IDS,BROWSER_EVENT_NAMES,BridgeProtocolError,BridgeUnavailableError,BrowserCdpCommandError,BrowserConnection,BskIpcClient,BskRpcError,BskSession,CdpClient,CommandSchema,DEFAULT_AGENT_VIEWPORT,DEVICE_PRESETS,ElementHandle,EventSchema,ExtensionHelloSchema,FrameLocator,FrameManager,HostHelloSchema,Locator,ModifierState,OmOKeyboard,OmOMouse,OmOPage,PipeCdpClient,ResponseSchema,STORE_PAGE_URLS,SessionManager,TabRepository,UnsupportedOperationError,bskDoctor,bskOnboard,bskSnapshot,buildCloakBrowserArgs,buildSnapshotExpression,catalogBrowsers,collectWhileScrolling,compactSnapshot,connect,connectBrowserSkill,connectCloakProfile,connectPipe,createAgentTabs,createBridgeClient,createCaptcha,createChromeApi2 as createChromeApi,createCua,createEvents,createNativeMessagingHost,createNetworkSnoop,createRoutes,createTrace,decodeFrames,describeLayers,detectBrowsers,emulate,encodeFrame,externalExtensionEntry,findCloakBrowserPath,identifyBrowser,injectCookies,installBskCli,installNativeMessagingHost,layersHeader,listBrowsers,macOSVisionOcr,normalizeDialogPolicy,pageBundle,probeBrowserSignals,readDaemonInfo,reconcileFrames,registerExternalExtension,repinViewport,requestHuman,resolveBskHome,resolveCloakProfile,resolveDialogAction,sanitizeCookies,snapshotTokens,snapshotWithFrames,snapshotWithLayers,takeSnapshot,toHar,toolSchemas,unregisterExternalExtension};
1525
+ })()`}async function bskSnapshot(session,{tabId,timeoutMs,...snapshotOptions}={}){const reply=await session.evaluate(buildSnapshotExpression(snapshotOptions),{tabId,timeoutMs,awaitPromise:false,returnByValue:true});if(!reply||reply.ok===false){const text=reply?.error?.text??"unknown error";throw new Error(`bskSnapshot failed inside the page: ${text}`)}const value=reply.value;if(!value||typeof value.tree!=="string")throw new Error("bskSnapshot: page returned no tree");if(value.error)throw new Error(`bskSnapshot: ${value.error}`);return{tree:value.tree,refs:value.refs,css:value.css}}import{existsSync as existsSync5,mkdirSync as mkdirSync2,readFileSync as readFileSync4,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{spawn as spawn5}from"node:child_process";import path15 from"node:path";import{existsSync as existsSync4}from"node:fs";import{homedir as homedir3}from"node:os";import path14 from"node:path";var BROWSERSKILL_EXTENSION_IDS=Object.freeze({chrome:"hhcmgoofomhgciiibhipgmgkgnoenaoi",edge:"emacgiaaaiojkkpkddmmdfhmokgmnikg"});var STORE_UPDATE_URLS=Object.freeze({chrome:"https://clients2.google.com/service/update2/crx",edge:"https://edge.microsoft.com/extensionwebstorebase/v1/crx"});var STORE_PAGE_URLS=Object.freeze({chrome:`https://chromewebstore.google.com/detail/${BROWSERSKILL_EXTENSION_IDS.chrome}`,edge:`https://microsoftedge.microsoft.com/addons/detail/browserskill/${BROWSERSKILL_EXTENSION_IDS.edge}`});var NON_CHROMIUM_DEFAULTS=Object.freeze([{id:"safari",label:"Safari",match:["com.apple.safari","safarihtml"]},{id:"firefox",label:"Firefox",match:["org.mozilla.firefox","firefox.desktop","firefoxurl","firefoxhtml"]},{id:"zen",label:"Zen",match:["app.zen-browser.zen","zen.desktop","zenhtml"]},{id:"orion",label:"Orion",match:["com.kagi.kagimacos"]}]);var MAC=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Library/Application Support/Google/Chrome",app:"Google Chrome",bundleId:"com.google.Chrome"},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Library/Application Support/Microsoft Edge",app:"Microsoft Edge",bundleId:"com.microsoft.edgemac"},{id:"brave",label:"Brave",store:"chrome",userData:"Library/Application Support/BraveSoftware/Brave-Browser",app:"Brave Browser",bundleId:"com.brave.Browser"},{id:"chromium",label:"Chromium",store:"chrome",userData:"Library/Application Support/Chromium",app:"Chromium",bundleId:"org.chromium.Chromium"},{id:"arc",label:"Arc",store:"chrome",userData:"Library/Application Support/Arc/User Data",app:"Arc",bundleId:"company.thebrowser.Browser"},{id:"dia",label:"Dia",store:"chrome",userData:"Library/Application Support/Dia/User Data",app:"Dia",bundleId:"company.thebrowser.dia"},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Library/Application Support/Vivaldi",app:"Vivaldi",bundleId:"com.vivaldi.Vivaldi"},{id:"opera",label:"Opera",store:"chrome",userData:"Library/Application Support/com.operasoftware.Opera",app:"Opera",bundleId:"com.operasoftware.Opera",externalExtensions:false},{id:"comet",label:"Comet",store:"chrome",userData:"Library/Application Support/Comet",app:"Comet",bundleId:"ai.perplexity.comet"},{id:"aside",label:"Aside",store:"chrome",userData:"Library/Application Support/Aside",app:"Aside",bundleId:"at.studio.AsideBrowser"},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Library/Application Support/Naver/Whale",app:"Naver Whale",bundleId:"com.naver.Whale"}];var LINUX=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:".config/google-chrome",binaries:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/opt/google/chrome/chrome"],externalDir:"/opt/google/chrome/extensions",userExternalDir:false,desktopIds:["google-chrome.desktop","google-chrome-stable.desktop","com.google.Chrome.desktop"],processNames:["chrome","google-chrome"]},{id:"chromium",label:"Chromium",store:"chrome",userData:".config/chromium",binaries:["/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],externalDir:"/usr/share/chromium/extensions",userExternalDir:true,desktopIds:["chromium.desktop","chromium-browser.desktop","chromium_chromium.desktop","org.chromium.Chromium.desktop"],processNames:["chromium","chromium-browse"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:".config/microsoft-edge",binaries:["/usr/bin/microsoft-edge","/opt/microsoft/msedge/msedge"],externalDir:"/usr/share/microsoft-edge/extensions",userExternalDir:false,desktopIds:["microsoft-edge.desktop","microsoft-edge-stable.desktop","com.microsoft.Edge.desktop"],processNames:["msedge"]},{id:"brave",label:"Brave",store:"chrome",userData:".config/BraveSoftware/Brave-Browser",binaries:["/usr/bin/brave-browser","/opt/brave.com/brave/brave"],externalDir:"/usr/share/brave/extensions",userExternalDir:false,desktopIds:["brave-browser.desktop","com.brave.Browser.desktop"],processNames:["brave"]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:".config/vivaldi",binaries:["/usr/bin/vivaldi","/opt/vivaldi/vivaldi"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["vivaldi-stable.desktop","vivaldi.desktop"],processNames:["vivaldi-bin"]},{id:"opera",label:"Opera",store:"chrome",userData:".config/opera",binaries:["/usr/bin/opera"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["opera.desktop"],processNames:["opera"]}];var WINDOWS=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Google/Chrome/User Data",registryKey:"HKCU\\Software\\Google\\Chrome\\Extensions",binaryRel:"Google/Chrome/Application/chrome.exe",progIds:["chromehtml"],processNames:["chrome.exe"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Microsoft/Edge/User Data",registryKey:"HKCU\\Software\\Microsoft\\Edge\\Extensions",binaryRel:"Microsoft/Edge/Application/msedge.exe",progIds:["msedgehtm"],processNames:["msedge.exe"]},{id:"brave",label:"Brave",store:"chrome",userData:"BraveSoftware/Brave-Browser/User Data",registryKey:"HKCU\\Software\\BraveSoftware\\Brave-Browser\\Extensions",binaryRel:"BraveSoftware/Brave-Browser/Application/brave.exe",progIds:["bravehtml"],processNames:["brave.exe"]},{id:"chromium",label:"Chromium",store:"chrome",userData:"Chromium/User Data",registryKey:"HKCU\\Software\\Chromium\\Extensions",binaryRel:"Chromium/Application/chrome.exe",progIds:["chromiumhtm"],processNames:[]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Vivaldi/User Data",registryKey:null,externalExtensions:false,binaryRel:"Vivaldi/Application/vivaldi.exe",progIds:["vivaldihtm"],processNames:["vivaldi.exe"]},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Naver/Naver Whale/User Data",registryKey:null,externalExtensions:false,binaryRel:"Naver/Naver Whale/Application/whale.exe",progIds:["whalehtml"],processNames:["whale.exe"]}];var BROWSER_IDS=Object.freeze([...new Set([...MAC,...LINUX,...WINDOWS].map((b)=>b.id))]);function macRow(b,home,exists){const apps=[path14.join("/Applications",`${b.app}.app`),path14.join(home,"Applications",`${b.app}.app`)];const appPath=apps.find((p)=>exists(p))??null;const userDataDir=path14.join(home,b.userData);return{id:b.id,label:b.label,store:b.store,userDataDir,binary:path14.join(appPath??apps[0],"Contents","MacOS",b.app),bundleId:b.bundleId,processNames:apps.map((a)=>path14.join(a,"Contents","MacOS",b.app)),defaultIds:[b.bundleId.toLowerCase()],externalExtensions:b.externalExtensions!==false,installed:appPath!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function linuxRow(b,home,exists){const userDataDir=path14.join(home,b.userData);const binary=b.binaries.find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,binary,externalDir:b.externalDir,userExternalDir:b.userExternalDir,processNames:b.processNames,defaultIds:b.desktopIds.map((d)=>d.toLowerCase()),externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function windowsRow(b,env,home,exists){const localAppData=env.LOCALAPPDATA??path14.join(home,"AppData","Local");const programFiles=[localAppData,env.PROGRAMFILES,env["PROGRAMFILES(X86)"],"C:\\Program Files","C:\\Program Files (x86)"].filter(Boolean);const userDataDir=path14.join(localAppData,b.userData);const binary=programFiles.map((root)=>path14.join(root,b.binaryRel)).find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,registryKey:b.registryKey,binary,processNames:b.processNames,defaultIds:b.progIds,externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function catalogBrowsers({platform=process.platform,home=homedir3(),env=process.env,exists=existsSync4}={}){if(platform==="darwin")return MAC.map((b)=>macRow(b,home,exists));if(platform==="linux")return LINUX.map((b)=>linuxRow(b,home,exists));if(platform==="win32")return WINDOWS.map((b)=>windowsRow(b,env,home,exists));return[]}function detectBrowsers(options={}){return catalogBrowsers(options).filter((b)=>b.installed)}var ENABLE_STEP=(browser)=>`Quit ${browser} completely and open it again; a dialog offers to enable "BrowserSkill" — click Enable.`;var BADGE_STEP=(browser)=>`In ${browser}, open the menu (the badge on the toolbar) and enable "BrowserSkill" when prompted; no restart is needed.`;var storeStep=(browser,label)=>`Open ${STORE_PAGE_URLS[browser.store]} in ${label} and click the "Add" button.`;function externalExtensionEntry({platform=process.platform,browser}){const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const updateUrl=STORE_UPDATE_URLS[browser.store];const label=browser.label??browser.id.charAt(0).toUpperCase()+browser.id.slice(1);if(browser.externalExtensions===false){return{kind:"store",needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:storeStep(browser,label)}}if(platform==="win32"){const key=`${browser.registryKey}\\${id}`;return{kind:"registry",key,needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],regAddArgs:["add",key,"/v","update_url","/t","REG_SZ","/d",updateUrl,"/f"],regDeleteArgs:["delete",key,"/f"],humanStep:BADGE_STEP(label)}}const content=JSON.stringify({external_update_url:updateUrl},null,2)+`
1526
+ `;if(platform==="linux"&&!browser.userExternalDir){return{kind:"file",path:path15.join(browser.externalDir,`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:`Quit ${label} completely and open it again; the extension installs without a prompt.`}}return{kind:"file",path:path15.join(browser.userDataDir,"External Extensions",`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:platform==="linux"?`Quit ${label} completely and open it again; the extension installs without a prompt.`:ENABLE_STEP(label)}}function isBlocklisted(browser,id,{readFile=readFileSync4}={}){if(!browser.userDataDir)return false;for(const profile of["Default","Profile 1","Profile 2","Profile 3"]){const file=path15.join(browser.userDataDir,profile,"Preferences");let prefs;try{prefs=JSON.parse(readFile(file,"utf8"))}catch{continue}if(Array.isArray(prefs?.extensions?.external_uninstalls)&&prefs.extensions.external_uninstalls.includes(id))return true}return false}function runRegDefault(args){return new Promise((resolve)=>{const child=spawn5("reg",args,{stdio:["ignore","ignore","pipe"],windowsHide:true});let stderr="";child.stderr.on("data",(c)=>{stderr+=c});child.on("error",(error)=>resolve({code:-1,stderr:error.message}));child.on("exit",(code)=>resolve({code,stderr}))})}async function registerExternalExtension({platform=process.platform,browser,writeFile=writeFileSync2,readFile=readFileSync4,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const label=browser.label??browser.id;const storeStep=`Open ${entry.storeUrl} in ${label} and click the "Add" button.`;if(entry.kind==="store")return{...entry,registered:false,alreadyPresent:false,reason:"store_only"};if(isBlocklisted(browser,id,{readFile})){return{...entry,registered:false,alreadyPresent:false,reason:"blocklisted",humanStep:`The extension was removed from ${label} before, so external registration is ignored. ${storeStep}`}}if(entry.kind==="registry"){const result=await runReg(entry.regAddArgs);if(result.code!==0)return{...entry,registered:false,alreadyPresent:false,reason:"reg_failed",detail:result.stderr,humanStep:storeStep};return{...entry,registered:true,alreadyPresent:false}}let alreadyPresent=false;try{alreadyPresent=readFile(entry.path,"utf8")===entry.content}catch{}if(alreadyPresent)return{...entry,registered:true,alreadyPresent:true};try{mkdirSync2(path15.dirname(entry.path),{recursive:true});writeFile(entry.path,entry.content)}catch(error){if(error.code==="EACCES"||error.code==="EPERM"||error.code==="EROFS"){return{...entry,registered:false,alreadyPresent:false,reason:"not_writable",humanStep:`${entry.path} is not writable without administrator rights. ${storeStep}`}}throw error}return{...entry,registered:true,alreadyPresent:false}}async function unregisterExternalExtension({platform=process.platform,browser,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});if(entry.kind==="store")return{...entry,removed:false};if(entry.kind==="registry"){const result=await runReg(entry.regDeleteArgs);return{...entry,removed:result.code===0,detail:result.stderr}}const present=existsSync5(entry.path);if(present)rmSync2(entry.path,{force:true});return{...entry,removed:present}}import{execFile as execFile2}from"node:child_process";import{statSync}from"node:fs";import{homedir as homedir4}from"node:os";import path16 from"node:path";var PROBE_TIMEOUT_MS2=3000;function runDefault(command,args){return new Promise((resolve)=>{execFile2(command,args,{timeout:PROBE_TIMEOUT_MS2,windowsHide:true,maxBuffer:8*1024*1024},(error,stdout)=>{resolve(error?null:String(stdout))})})}function parseMacDefaultBrowser(plistJson){let handlers;try{handlers=JSON.parse(plistJson)?.LSHandlers}catch{return null}if(!Array.isArray(handlers))return null;const pick=(scheme)=>handlers.find((h)=>h?.LSHandlerURLScheme===scheme&&typeof h.LSHandlerRoleAll==="string");const handler=pick("https")??pick("http");return handler?handler.LSHandlerRoleAll.toLowerCase():"com.apple.safari"}function parseWindowsProgId(regOutput){const match=/ProgId\s+REG_SZ\s+(\S+)/i.exec(regOutput??"");return match?match[1].toLowerCase():null}function parseProcessNames(platform,output){const names=new Set;for(const raw of String(output??"").split(/\r?\n/)){const line=raw.trim();if(!line)continue;if(platform==="win32"){const image=/^"([^"]+)"/.exec(line)?.[1];if(image)names.add(image.toLowerCase())}else if(platform==="darwin"){if(/\.app\/Contents\/MacOS\/[^/]+$/.test(line))names.add(line)}else{names.add(path16.basename(line))}}return[...names]}async function probeDefault({platform,home,run}){if(platform==="darwin"){const plist=path16.join(home,"Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist");const json=await run("plutil",["-convert","json","-o","-",plist]);return json===null?null:parseMacDefaultBrowser(json)}if(platform==="linux"){const out=await run("xdg-settings",["get","default-web-browser"]);return out?.trim()?out.trim().toLowerCase():null}if(platform==="win32"){const key="HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice";return parseWindowsProgId(await run("reg",["query",key,"/v","ProgId"]))}return null}async function probeRunning({platform,run}){const out=platform==="win32"?await run("tasklist",["/fo","csv","/nh"]):await run("ps",platform==="darwin"?["-axo","comm="]:["-eo","comm="]);return out===null?null:parseProcessNames(platform,out)}function lastUsedAt(browser,stat){let latest=null;for(const rel of["Local State",path16.join("Default","History"),path16.join("Default","Preferences")]){try{const mtime=stat(path16.join(browser.userDataDir,rel)).mtimeMs;if(latest===null||mtime>latest)latest=mtime}catch{}}return latest}async function probeBrowserSignals({platform=process.platform,home=homedir4(),browsers=[],run=runDefault,stat=statSync}={}){const[defaultBrowser,running]=await Promise.all([probeDefault({platform,home,run}),probeRunning({platform,run})]);const lastUsed=Object.fromEntries(browsers.map((b)=>[b.id,lastUsedAt(b,stat)]));return{defaultBrowser,running,lastUsed}}var RECENT_USE_MS=7*24*60*60*1000;function matchesDefault(browser,defaultId){if(!defaultId)return false;return browser.defaultIds.some((id)=>defaultId===id||defaultId.startsWith(id))}function describeDefault(defaultId,catalog){if(defaultId===null||defaultId===undefined)return{raw:null,id:null,label:null,supported:null};const hit=catalog.find((b)=>matchesDefault(b,defaultId));if(hit)return{raw:defaultId,id:hit.id,label:hit.label,supported:true};const other=NON_CHROMIUM_DEFAULTS.find((b)=>b.match.some((m)=>defaultId===m||defaultId.startsWith(m)));return other?{raw:defaultId,id:other.id,label:other.label,supported:false}:{raw:defaultId,id:null,label:defaultId,supported:false}}function candidateRow(browser,{defaultBrowser,running,lastUsed},now){const isDefault=defaultBrowser.id===browser.id;const isRunning=Array.isArray(running)?browser.processNames.some((n)=>running.includes(n)||running.includes(n.toLowerCase())):null;const last=lastUsed?.[browser.id]??null;const recentlyUsed=last!==null&&now-last<=RECENT_USE_MS;const signals=[isDefault&&"default browser",isRunning&&"running now",recentlyUsed&&"used in the last 7 days"].filter(Boolean);return{id:browser.id,label:browser.label,installed:browser.installed,isDefault,running:isRunning,lastUsedAt:last===null?null:new Date(last).toISOString(),recentlyUsed,signals,browser}}function choose(candidates,primary,confidence,reason,defaultBrowser){return{primary:primary.browser,primaryId:primary.id,confidence,needsChoice:false,reason,defaultBrowser,candidates:candidates.map(({browser,...row})=>row)}}function ask(candidates,reason,defaultBrowser,suggested=null){return{primary:null,primaryId:null,confidence:null,needsChoice:true,reason,suggested,defaultBrowser,candidates:candidates.map(({browser,...row})=>row)}}function identifyBrowser({catalog,signals={},explicit=null,now=Date.now()}){const defaultBrowser=describeDefault(signals.defaultBrowser??null,catalog);const installed=catalog.filter((b)=>b.installed||b.id===explicit);const candidates=installed.map((b)=>candidateRow(b,{defaultBrowser,running:signals.running??null,lastUsed:signals.lastUsed},now));if(explicit){const hit=candidates.find((c)=>c.id===explicit);if(hit)return choose(candidates,hit,"explicit",`${hit.label} was chosen explicitly`,defaultBrowser);return ask(candidates,`"${explicit}" is not a Chromium-family browser this library knows; pick one of the candidates`,defaultBrowser)}if(candidates.length===0)return ask(candidates,"no Chromium-family browser is installed",defaultBrowser);const inUse=candidates.filter((c)=>c.running||c.recentlyUsed);const def=candidates.find((c)=>c.isDefault);if(def&&(def.running||def.recentlyUsed))return choose(candidates,def,"default-and-in-use",`${def.label} is the default browser and ${def.signals.slice(1).join(", ")}`,defaultBrowser);if(def&&inUse.length===0)return choose(candidates,def,"default",`${def.label} is the default browser`,defaultBrowser);if(def)return ask(candidates,`${def.label} is the default browser, but ${inUse.map((c)=>c.label).join(" and ")} ${inUse.length===1?"is":"are"} the one in use`,defaultBrowser);if(defaultBrowser.supported===false){const suggested=inUse.length===1?inUse[0].id:null;return ask(candidates,`the default browser is ${defaultBrowser.label}, which BrowserSkill cannot drive; the user has to name the Chromium browser to use`,defaultBrowser,suggested)}const runningNow=inUse.filter((c)=>c.running);if(inUse.length===1)return choose(candidates,inUse[0],"only-in-use",`${inUse[0].label} is the only browser ${inUse[0].signals.join(", ")}`,defaultBrowser);if(runningNow.length===1)return choose(candidates,runningNow[0],"only-running",`${runningNow[0].label} is the only browser running now`,defaultBrowser);if(inUse.length===0&&candidates.length===1)return choose(candidates,candidates[0],"only-installed",`${candidates[0].label} is the only Chromium-family browser installed`,defaultBrowser);return ask(candidates,inUse.length>1?`several browsers are in use (${inUse.map((c)=>c.label).join(", ")})`:"no browser shows recent use",defaultBrowser)}import{existsSync as existsSync6,readFileSync as readFileSync5,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{homedir as homedir5}from"node:os";import path17 from"node:path";import{spawn as spawn6}from"node:child_process";var INSTALL_SH="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.sh";var INSTALL_PS1="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.ps1";var RC_FILES=[".zshrc",".bashrc",".profile"];function cliInstallCommand({platform=process.platform,installDir,version}={}){const env={BSK_INSTALL_DIR:installDir};if(version)env.BSK_VERSION=version;if(platform==="win32"){return{command:"powershell",args:["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${INSTALL_PS1} | iex`],env}}return{command:"sh",args:["-c",`curl -fsSL ${INSTALL_SH} | sh`],env}}function runDefault2(command,args,env){return new Promise((resolve)=>{const child=spawn6(command,args,{env:{...process.env,...env},stdio:["ignore","pipe","pipe"],windowsHide:true});let stdout="",stderr="";child.stdout.on("data",(c)=>{stdout=(stdout+c).slice(-8192)});child.stderr.on("data",(c)=>{stderr=(stderr+c).slice(-8192)});child.on("error",(error)=>resolve({code:-1,stdout,stderr:error.message}));child.on("exit",(code)=>resolve({code,stdout,stderr}))})}function snapshotRcFiles(home){const snapshot=new Map;for(const name of RC_FILES){const file=path17.join(home,name);snapshot.set(file,existsSync6(file)?readFileSync5(file):null)}return snapshot}function restoreRcFiles(snapshot){const restored=[];for(const[file,before]of snapshot){const after=existsSync6(file)?readFileSync5(file):null;if(before===null&&after===null)continue;if(before!==null&&after!==null&&before.equals(after))continue;if(before===null)rmSync3(file,{force:true});else writeFileSync3(file,before);restored.push(file)}return restored}async function installBskCli({platform=process.platform,home=homedir5(),installDir=path17.join(home,".local","bin"),version,run=runDefault2}={}){const spec=cliInstallCommand({platform,installDir,version});const rcBefore=platform==="win32"?new Map:snapshotRcFiles(home);const result=await run(spec.command,spec.args,spec.env);const restoredRcFiles=restoreRcFiles(rcBefore);const bskBin=path17.join(installDir,platform==="win32"?"bsk.exe":"bsk");const installed=result.code===0&&existsSync6(bskBin);return{installed,bskBin:installed?bskBin:null,code:result.code,stdout:result.stdout,stderr:result.stderr,restoredRcFiles}}function cliVersionDefault(bskBin){return new Promise((resolve)=>{const child=spawn6(bskBin,["--version"],{stdio:["ignore","pipe","ignore"],windowsHide:true});let out="";child.stdout.on("data",(c)=>{out+=c});child.on("error",()=>resolve(null));child.on("exit",(code)=>resolve(code===0?out.trim():null))})}import{homedir as homedir6}from"node:os";import{existsSync as existsSync7,readFileSync as readFileSync6}from"node:fs";var DEFAULT_WAIT_TOTAL_MS=180000;function resolveBskBin(bskBin,env){if(bskBin===null)return null;return bskBin??findBskBinary(env)}async function cliReport({bskBin,env,cliVersion}){const bin=resolveBskBin(bskBin,env);if(!bin)return{installed:false,bskBin:null,version:null};const raw=await cliVersion(bin);return raw?{installed:true,bskBin:bin,version:raw.replace(/^bsk\s+/,"")}:{installed:false,bskBin:bin,version:null}}async function daemonReport(client,waitForBrowserMs){try{const status=await client.call("system.status",waitForBrowserMs>0?{wait_for_browser_ms:waitForBrowserMs}:{},{idPrefix:"status"});return{running:true,version:status.daemon_version,protocolVersion:status.protocol_version,browsers:status.browsers??[],sessions:status.sessions??[]}}catch(error){return{running:false,error:error.message,code:error.code,browsers:[],sessions:[]}}}var NO_BROWSER_STEP=`No Chromium-family browser was found. Install one (Chrome, Edge, Brave, Arc, ...), then add the extension from ${STORE_PAGE_URLS.chrome}.`;function withRegistration(platform,browser){const entry=externalExtensionEntry({platform,browser});const extensionRegistered=entry.kind==="file"&&existsSync7(entry.path)&&readFileSync6(entry.path,"utf8")===entry.content;return{...browser,registration:entry,extensionRegistered}}async function identify({platform,home,env,exists,browser,signals,probeSignals,now}){const catalog=catalogBrowsers({platform,home,env,exists}).map((b)=>withRegistration(platform,b));const observed=signals??await probeSignals({platform,home,browsers:catalog.filter((b)=>b.hasProfile)});const explicit=browser??env.OMOWRIGHT_BROWSER??null;const{primary,...identification}=identifyBrowser({catalog,signals:observed,explicit:explicit||null,now});const browsers=catalog.filter((b)=>b.installed);const registeredElsewhere=browsers.filter((b)=>b.extensionRegistered&&b.id!==identification.primaryId).map((b)=>b.id);return{browsers,identification:{...identification,registeredElsewhere},primary}}function choiceStep(identification){const listed=identification.candidates.map((c)=>`${c.label} [${c.id}]${c.signals.length?` — ${c.signals.join(", ")}`:""}`).join("; ");const hint=identification.suggested?` Likely ${identification.suggested}, but confirm first.`:"";return`Ask the user which browser they actually use (${identification.reason}). Candidates: ${listed}.${hint} Then re-run with browser: "<id>"; register nothing until they answer.`}function nextStepFor({cli,daemon,browsers,browsersConnected,identification,primary}){if(browsersConnected.length>0)return null;if(!cli.installed)return"Install the bsk CLI (bskOnboard() runs the official installer).";if(!daemon.running)return"Start the BrowserSkill daemon: run `bsk status` once, or `bsk daemon start` in the environment that owns it.";if(browsers.length===0&&!primary)return NO_BROWSER_STEP;if(identification.needsChoice)return choiceStep(identification);if(!primary.extensionRegistered&&primary.registration.kind!=="store")return`Register the BrowserSkill extension for ${primary.label} (bskOnboard() does this), then let the user enable it.`;return primary.registration.humanStep}async function bskDoctor({platform=process.platform,home=homedir6(),env=process.env,client,bskBin,cliVersion=cliVersionDefault,waitForBrowserMs=0,exists=existsSync7,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){const cli=await cliReport({bskBin,env,cliVersion});const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:false});const daemon=await daemonReport(ipc,waitForBrowserMs);const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,signals,probeSignals,now});const browsersConnected=daemon.browsers;const report={cli,daemon,browsers,primary:primary??null,identification,browsersConnected,ready:browsersConnected.length>0};report.nextStep=nextStepFor(report);return report}async function bskOnboard({platform=process.platform,home=homedir6(),env=process.env,client,bskBin,installDir,installCli=installBskCli,cliVersion=cliVersionDefault,onHumanStep=()=>{},waitForBrowserMs=15000,waitTotalMs=DEFAULT_WAIT_TOTAL_MS,exists=existsSync7,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){let cli=await cliReport({bskBin,env,cliVersion});let install=null;if(!cli.installed){install=await installCli({platform,home,installDir});cli=install.installed?await cliReport({bskBin:install.bskBin,env,cliVersion}):cli}const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:true});let daemon=await daemonReport(ipc,0);const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,signals,probeSignals,now});const registrations=[];let humanStep=null;let needsChoice=false;if(daemon.browsers.length===0){if(browsers.length===0&&!primary){humanStep=NO_BROWSER_STEP}else if(identification.needsChoice){needsChoice=true;humanStep=choiceStep(identification)}else{const registration=await registerExternalExtension({platform,browser:primary});registrations.push({browser:primary.id,...registration});humanStep=registration.humanStep;onHumanStep({browser:primary.id,step:registration.humanStep,registered:registration.registered,needsRestart:registration.needsRestart})}}const deadline=Date.now()+waitTotalMs;let browsersConnected=daemon.browsers;while(!needsChoice&&browsersConnected.length===0&&daemon.running&&Date.now()<deadline){browsersConnected=await listBrowsers(ipc,{waitForBrowserMs});if(waitForBrowserMs===0)break}daemon={...daemon,browsers:browsersConnected};const ready=browsersConnected.length>0;return{cli,install,daemon,browsers,primary:primary??null,identification,needsChoice,registrations,humanStep:ready?null:humanStep,browsersConnected,ready}}export{AgentTabManager,BROWSERSKILL_EXTENSION_IDS,BROWSER_EVENT_NAMES,BridgeProtocolError,BridgeUnavailableError,BrowserCdpCommandError,BrowserConnection,BskIpcClient,BskRpcError,BskSession,CdpClient,CommandSchema,DEFAULT_AGENT_VIEWPORT,DEVICE_PRESETS,ElementHandle,EventSchema,ExtensionHelloSchema,FrameLocator,FrameManager,HostHelloSchema,Locator,ModifierState,OMOWRIGHT_PAGE_CDP_METHODS,OmOKeyboard,OmOMouse,OmOPage,PipeCdpClient,ResponseSchema,STORE_PAGE_URLS,SessionManager,SharedConnectionError,TabRepository,UnsupportedOperationError,bskDoctor,bskOnboard,bskSnapshot,buildCloakBrowserArgs,buildSnapshotExpression,catalogBrowsers,collectWhileScrolling,compactSnapshot,connect,connectBrowserSkill,connectCloakProfile,connectNamed,connectPipe,createAgentTabs,createBridgeClient,createCaptcha,createChromeApi2 as createChromeApi,createCua,createEvents,createNativeMessagingHost,createNetworkSnoop,createRoutes,createTrace,decodeFrames,describeLayers,detectBrowsers,emulate,encodeFrame,externalExtensionEntry,findCloakBrowserPath,identifyBrowser,injectCookies,installBskCli,installNativeMessagingHost,layersHeader,listBrowsers,listInstances,macOSVisionOcr,normalizeDialogPolicy,pageBundle,probeBrowserSignals,readDaemonInfo,reconcileFrames,registerExternalExtension,repinViewport,requestHuman,resolveBskHome,resolveCloakProfile,resolveDialogAction,sanitizeCookies,snapshotTokens,snapshotWithFrames,snapshotWithLayers,takeSnapshot,toHar,toolSchemas,unregisterExternalExtension};