page-agent 1.8.2 → 1.9.1
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.
- package/README.md +5 -3
- package/dist/esm/PageAgent.d.ts +9 -0
- package/dist/esm/page-agent.js.map +1 -1
- package/dist/iife/page-agent.demo.js +12 -13
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -13,7 +13,9 @@ The GUI Agent Living in Your Webpage. Control web interfaces with natural langua
|
|
|
13
13
|
|
|
14
14
|
<a href="https://alibaba.github.io/page-agent/" target="_blank"><b>🚀 Demo</b></a> | <a href="https://alibaba.github.io/page-agent/docs/introduction/overview" target="_blank"><b>📖 Docs</b></a> | <a href="https://news.ycombinator.com/item?id=47264138" target="_blank"><b>📢 HN Discussion</b></a> | <a href="https://x.com/simonluvramen" target="_blank"><b>𝕏 Follow on X</b></a>
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
<!-- demo video -->
|
|
17
|
+
|
|
18
|
+
https://github.com/user-attachments/assets/a1f2eae2-13fb-4aae-98cf-a3fc1620a6c2
|
|
17
19
|
|
|
18
20
|
---
|
|
19
21
|
|
|
@@ -50,8 +52,8 @@ Fastest way to try PageAgent with our free Demo LLM:
|
|
|
50
52
|
|
|
51
53
|
| Mirrors | URL |
|
|
52
54
|
| ------- | ---------------------------------------------------------------------------------- |
|
|
53
|
-
| Global | https://cdn.jsdelivr.net/npm/page-agent@1.
|
|
54
|
-
| China | https://registry.npmmirror.com/page-agent/1.
|
|
55
|
+
| Global | https://cdn.jsdelivr.net/npm/page-agent@1.9.1/dist/iife/page-agent.demo.js |
|
|
56
|
+
| China | https://registry.npmmirror.com/page-agent/1.9.1/files/dist/iife/page-agent.demo.js |
|
|
55
57
|
|
|
56
58
|
Add `?autoInit=false` to load the script without creating the demo agent automatically. You can then instantiate it with `new window.PageAgent(...)`.
|
|
57
59
|
|
package/dist/esm/PageAgent.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"page-agent.js","names":[],"sources":["../../src/PageAgent.ts"],"sourcesContent":["/**\n * Copyright (C) 2025 Alibaba Group Holding Limited\n * All rights reserved.\n */\nimport { type AgentConfig, PageAgentCore } from '@page-agent/core'\nimport { PageController, type PageControllerConfig } from '@page-agent/page-controller'\nimport { Panel, type PanelConfig } from '@page-agent/ui'\n\nexport * from '@page-agent/core'\n\nexport type PageAgentConfig = AgentConfig & PageControllerConfig & Omit<PanelConfig, 'language'>\n\nexport class PageAgent extends PageAgentCore {\n\tpanel: Panel\n\n\tconstructor(config: PageAgentConfig) {\n\t\tconst pageController = new PageController({\n\t\t\t...config,\n\t\t\tenableMask: config.enableMask ?? true,\n\t\t})\n\n\t\tsuper({ ...config, pageController })\n\n\t\tthis.panel = new Panel(this, {\n\t\t\tlanguage: config.language,\n\t\t\tpromptForNextTask: config.promptForNextTask,\n\t\t})\n\t}\n}\n"],"mappings":";;;;;;;;;AAYA,IAAa,YAAb,cAA+B,cAAc;CAC5C;CAEA,YAAY,QAAyB;EACpC,MAAM,iBAAiB,IAAI,eAAe;GACzC,GAAG;GACH,YAAY,OAAO,cAAc;
|
|
1
|
+
{"version":3,"file":"page-agent.js","names":[],"sources":["../../src/PageAgent.ts"],"sourcesContent":["/**\n * Copyright (C) 2025 Alibaba Group Holding Limited\n * All rights reserved.\n */\nimport { type AgentConfig, PageAgentCore } from '@page-agent/core'\nimport { PageController, type PageControllerConfig } from '@page-agent/page-controller'\nimport { Panel, type PanelConfig } from '@page-agent/ui'\n\nexport * from '@page-agent/core'\n\nexport type PageAgentConfig = AgentConfig & PageControllerConfig & Omit<PanelConfig, 'language'>\n\nexport class PageAgent extends PageAgentCore {\n\tpanel: Panel\n\n\tconstructor(config: PageAgentConfig) {\n\t\tconst pageController = new PageController({\n\t\t\t...config,\n\t\t\tenableMask: config.enableMask ?? true,\n\t\t})\n\n\t\tsuper({ ...config, pageController })\n\n\t\tthis.panel = new Panel(this, {\n\t\t\tlanguage: config.language,\n\t\t\tpromptForNextTask: config.promptForNextTask,\n\t\t})\n\t}\n}\n"],"mappings":";;;;;;;;;AAYA,IAAa,YAAb,cAA+B,cAAc;CAC5C;CAEA,YAAY,QAAyB;EACpC,MAAM,iBAAiB,IAAI,eAAe;GACzC,GAAG;GACH,YAAY,OAAO,cAAc;EAClC,CAAC;EAED,MAAM;GAAE,GAAG;GAAQ;EAAe,CAAC;EAEnC,KAAK,QAAQ,IAAI,MAAM,MAAM;GAC5B,UAAU,OAAO;GACjB,mBAAmB,OAAO;EAC3B,CAAC;CACF;AACD"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
(function(){var __vite_style__=document.createElement(`style`);__vite_style__.textContent=`._wrapper_1ooyb_1{z-index:2147483641;cursor:wait;display:none;position:fixed;inset:0;overflow:hidden}._wrapper_1ooyb_1._visible_1ooyb_11{display:block}._cursor_1dgwb_2{width:var(--cursor-size,75px);height:var(--cursor-size,75px);pointer-events:none;z-index:10000;position:absolute}._cursorBorder_1dgwb_10{transform-origin:50%;background:linear-gradient(45deg,#39b6ff,#bd45fb);width:100%;height:100%;margin-top:-18px;margin-left:-10px;position:absolute;transform:rotate(-135deg)scale(1.2);-webkit-mask-image:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20100%20100'%20fill='none'%3e%3cg%3e%3cpath%20d='M%2015%2042%20L%2015%2036.99%20Q%2015%2031.99%2023.7%2031.99%20L%2028.05%2031.99%20Q%2032.41%2031.99%2032.41%2021.99%20L%2032.41%2017%20Q%2032.41%2012%2041.09%2016.95%20L%2076.31%2037.05%20Q%2085%2042%2076.31%2046.95%20L%2041.09%2067.05%20Q%2032.41%2072%2032.41%2062.01%20L%2032.41%2057.01%20Q%2032.41%2052.01%2023.7%2052.01%20L%2019.35%2052.01%20Q%2015%2052.01%2015%2047.01%20Z'%20fill='none'%20stroke='%23000000'%20stroke-width='6'%20stroke-miterlimit='10'%20style='stroke:%20light-dark(rgb(0,%200,%200),%20rgb(255,%20255,%20255));'/%3e%3c/g%3e%3c/svg%3e");mask-image:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20100%20100'%20fill='none'%3e%3cg%3e%3cpath%20d='M%2015%2042%20L%2015%2036.99%20Q%2015%2031.99%2023.7%2031.99%20L%2028.05%2031.99%20Q%2032.41%2031.99%2032.41%2021.99%20L%2032.41%2017%20Q%2032.41%2012%2041.09%2016.95%20L%2076.31%2037.05%20Q%2085%2042%2076.31%2046.95%20L%2041.09%2067.05%20Q%2032.41%2072%2032.41%2062.01%20L%2032.41%2057.01%20Q%2032.41%2052.01%2023.7%2052.01%20L%2019.35%2052.01%20Q%2015%2052.01%2015%2047.01%20Z'%20fill='none'%20stroke='%23000000'%20stroke-width='6'%20stroke-miterlimit='10'%20style='stroke:%20light-dark(rgb(0,%200,%200),%20rgb(255,%20255,%20255));'/%3e%3c/g%3e%3c/svg%3e");-webkit-mask-size:100% 100%;mask-size:100% 100%;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat}._cursorFilling_1dgwb_25{transform-origin:50%;background:url("data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20100%20100'%3e%3cdefs%3e%3c/defs%3e%3cg%20xmlns='http://www.w3.org/2000/svg'%20style='filter:%20drop-shadow(light-dark(rgba(0,%200,%200,%200.4),%20rgba(237,%20237,%20237,%200.4))%203px%204px%204px);'%3e%3cpath%20d='M%2015%2042%20L%2015%2036.99%20Q%2015%2031.99%2023.7%2031.99%20L%2028.05%2031.99%20Q%2032.41%2031.99%2032.41%2021.99%20L%2032.41%2017%20Q%2032.41%2012%2041.09%2016.95%20L%2076.31%2037.05%20Q%2085%2042%2076.31%2046.95%20L%2041.09%2067.05%20Q%2032.41%2072%2032.41%2062.01%20L%2032.41%2057.01%20Q%2032.41%2052.01%2023.7%2052.01%20L%2019.35%2052.01%20Q%2015%2052.01%2015%2047.01%20Z'%20fill='%23ffffff'%20stroke='none'%20style='fill:%20%23ffffff;'/%3e%3c/g%3e%3c/svg%3e") 0 0/100% 100% no-repeat;width:100%;height:100%;margin-top:-18px;margin-left:-10px;position:absolute;transform:rotate(-135deg)scale(1.2)}._cursorRipple_1dgwb_39{pointer-events:none;width:100%;height:100%;margin-top:-50%;margin-left:-50%;position:absolute}._cursorRipple_1dgwb_39:after{content:"";opacity:0;border:4px solid #39b6ff;border-radius:50%;position:absolute;inset:0}._cursor_1dgwb_2._clicking_1dgwb_57 ._cursorRipple_1dgwb_39:after{animation:.3s ease-out forwards _cursor-ripple_1dgwb_1}@keyframes _cursor-ripple_1dgwb_1{0%{opacity:1;transform:scale(0)}to{opacity:0;transform:scale(2)}}._wrapper_1tu05_1{opacity:0;z-index:2147483642;box-sizing:border-box;position:fixed;bottom:100px;left:50%;overflow:visible;transform:translate(-50%)translateY(20px)}._wrapper_1tu05_1 *{box-sizing:border-box}._wrapper_1tu05_1{--width:360px;--height:40px;--border-radius:12px;--side-space:12px;--history-width:calc(var(--width) - var(--side-space) * 2);--color-1:#39b6ff;--color-2:#bd45fb;--color-3:#ff5733;--color-4:#ffd600;width:var(--width);height:var(--height);transition:all .3s ease-in-out}@media (width<=480px){._wrapper_1tu05_1{--width:calc(100vw - 40px);width:calc(100vw - 40px)}}._wrapper_1tu05_1 ._background_1tu05_39{border-radius:calc(var(--border-radius) + 4px);filter:blur(16px);position:absolute;inset:-2px -8px;overflow:hidden}._wrapper_1tu05_1 ._background_1tu05_39:before{content:"";z-index:-1;pointer-events:none;background-image:linear-gradient(to bottom left, var(--color-1), var(--color-2), var(--color-1));width:100%;height:100%;animation:2s linear infinite _mask-running_1tu05_1;position:absolute;top:0;left:0}._wrapper_1tu05_1 ._background_1tu05_39:after{content:"";z-index:-1;pointer-events:none;background-image:linear-gradient(to bottom left, var(--color-2), var(--color-1), var(--color-2));width:100%;height:100%;animation:2s linear 1s infinite _mask-running_1tu05_1;position:absolute;top:0;left:0}@keyframes _mask-running_1tu05_1{0%{transform:translate(-100%)}to{transform:translate(100%)}}._header_1tu05_99{-webkit-user-select:none;user-select:none;cursor:pointer;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);border-radius:var(--border-radius);background:#00000080 padding-box padding-box;flex-shrink:0;justify-content:space-between;align-items:center;padding:8px 12px;display:flex;position:absolute;inset:0;box-shadow:0 0 0 2px #fff6,0 0 5px 1px #ffffff4d}._header_1tu05_99 ._statusSection_1tu05_121{flex:1;align-items:center;gap:8px;min-height:24px;display:flex}._header_1tu05_99 ._statusSection_1tu05_121 ._indicator_1tu05_128{background:#ffffff80;border-radius:50%;flex-shrink:0;width:6px;height:6px;animation:none}._header_1tu05_99 ._statusSection_1tu05_121 ._indicator_1tu05_128._thinking_1tu05_137{background:#39b6ff;animation:.8s ease-in-out infinite _pulse_1tu05_1}._header_1tu05_99 ._statusSection_1tu05_121 ._indicator_1tu05_128._tool_executing_1tu05_142{background:#bd45fb;animation:.6s ease-in-out infinite _pulse_1tu05_1}._header_1tu05_99 ._statusSection_1tu05_121 ._indicator_1tu05_128._retry_1tu05_147{background:#ffd600;animation:1s ease-in-out infinite _retryPulse_1tu05_1}._header_1tu05_99 ._statusSection_1tu05_121 ._indicator_1tu05_128._completed_1tu05_153,._header_1tu05_99 ._statusSection_1tu05_121 ._indicator_1tu05_128._input_1tu05_154,._header_1tu05_99 ._statusSection_1tu05_121 ._indicator_1tu05_128._output_1tu05_155{background:#22c55e;animation:none}._header_1tu05_99 ._statusSection_1tu05_121 ._indicator_1tu05_128._error_1tu05_160{background:#ef4444;animation:none}._header_1tu05_99 ._statusSection_1tu05_121 ._statusText_1tu05_166{color:#fff;align-items:center;min-height:24px;font-size:12px;font-weight:500;line-height:1;transition:all .3s ease-in-out;display:flex;position:relative;overflow:hidden}._header_1tu05_99 ._statusSection_1tu05_121 ._statusText_1tu05_166._fadeOut_1tu05_178{animation:.3s forwards _statusTextFadeOut_1tu05_1}._header_1tu05_99 ._statusSection_1tu05_121 ._statusText_1tu05_166._fadeIn_1tu05_182{animation:.3s forwards _statusTextFadeIn_1tu05_1}._header_1tu05_99 ._controls_1tu05_188{align-items:center;gap:4px;display:flex}._header_1tu05_99 ._controls_1tu05_188 ._controlButton_1tu05_193{color:#fff;cursor:pointer;background:#ffffff1a;border:none;border-radius:4px;justify-content:center;align-items:center;width:24px;height:24px;font-size:12px;line-height:1;display:flex}._header_1tu05_99 ._controls_1tu05_188 ._controlButton_1tu05_193:hover{background:#fff3}._header_1tu05_99 ._controls_1tu05_188 ._stopButton_1tu05_212{color:#ff2929;background:#ef444433;font-weight:600}._header_1tu05_99 ._controls_1tu05_188 ._stopButton_1tu05_212:hover{background:#ef44444d}@keyframes _statusTextFadeIn_1tu05_1{0%{opacity:0;transform:translateY(5px)}to{opacity:1;transform:translateY(0)}}@keyframes _statusTextFadeOut_1tu05_1{0%{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-5px)}}._historySectionWrapper_1tu05_246{width:var(--history-width);bottom:var(--height);left:var(--side-space);z-index:-2;visibility:collapse;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);text-shadow:0 0 1px #0003;border-top-left-radius:calc(var(--border-radius) + 4px);border-top-right-radius:calc(var(--border-radius) + 4px);background:#02001480;border:2px solid #fff6;padding-top:0;transition:all .2s;position:absolute;overflow:hidden;box-shadow:0 4px 16px #0009}._expanded_1tu05_278 ._historySectionWrapper_1tu05_246{visibility:visible;padding-top:8px}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246{overscroll-behavior:contain;scrollbar-width:none;max-height:0;padding-inline:8px;transition:max-height .2s;position:relative;overflow-y:auto}._expanded_1tu05_278 :is(._historySectionWrapper_1tu05_246 ._historySection_1tu05_246){max-height:min(500px, calc(100vh - 200px - var(--height)))}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297{color:#fff;background:linear-gradient(135deg,#ffffff14,#ffffff08);border-left:2px solid #39b6ff80;border-radius:8px;margin-bottom:6px;padding:8px 10px;font-size:12px;line-height:1.3;position:relative;overflow:hidden;box-shadow:inset 0 1px #ffffff1a,0 1px 3px #0000001a}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297:before{content:"";background:linear-gradient(90deg,#0000,#fff3,#0000);height:1px;position:absolute;top:0;left:0;right:0}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297:hover{background:linear-gradient(135deg,#ffffff1f,#ffffff0f);box-shadow:inset 0 1px #ffffff26,0 2px 4px #00000026}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297:last-child{margin-bottom:10px}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._completed_1tu05_153,._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._input_1tu05_154,._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._output_1tu05_155{background:linear-gradient(135deg,#22c55e1a,#22c55e0d);border-left-color:#22c55e}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._error_1tu05_160{background:linear-gradient(135deg,#ef44441a,#ef44440d);border-left-color:#ef4444}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._retry_1tu05_147{background:linear-gradient(135deg,#ffd6001a,#ffd6000d);border-left-color:#ffd600}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._observation_1tu05_355{background:linear-gradient(135deg,#9333ea1a,#9333ea0d);border-left-color:#9333ea}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._question_1tu05_360{background:linear-gradient(135deg,#ff9f4326,#ff9f4314);border-left-color:#ff9f43}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._doneSuccess_1tu05_366{color:#dcfce7;background:linear-gradient(135deg,#22c55e40,#22c55e26,#22c55e14);border:none;border-left:4px solid #22c55e;border-radius:8px;margin-bottom:8px;padding:10px 12px;font-weight:600;position:relative;overflow:hidden;box-shadow:0 4px 12px #22c55e4d,inset 0 1px #fff3,0 0 20px #22c55e1a}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._doneSuccess_1tu05_366:before{background:linear-gradient(90deg,#0000,#22c55e66,#0000)}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._doneSuccess_1tu05_366:after{content:"";background:linear-gradient(90deg,#0000,#ffffff1a,#0000);width:100%;height:100%;animation:2s ease-in-out infinite _shimmer_1tu05_1;position:absolute;top:0;left:-100%}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._doneSuccess_1tu05_366 ._historyContent_1tu05_402 ._statusIcon_1tu05_403{filter:drop-shadow(0 2px 4px #22c55e80);font-size:16px;animation:.8s ease-in-out _celebrate_1tu05_1}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._doneError_1tu05_412{color:#fee2e2;background:linear-gradient(135deg,#ef444440,#ef444426,#ef444414);border:none;border-left:4px solid #ef4444;border-radius:8px;margin-bottom:8px;padding:10px 12px;font-weight:600;position:relative;overflow:hidden;box-shadow:0 4px 12px #ef44444d,inset 0 1px #fff3,0 0 20px #ef44441a}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._doneError_1tu05_412:before{background:linear-gradient(90deg,#0000,#ef444466,#0000)}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297._doneError_1tu05_412 ._historyContent_1tu05_402 ._statusIcon_1tu05_403{filter:drop-shadow(0 2px 4px #ef444480);font-size:16px}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297 ._historyContent_1tu05_402{word-break:break-all;white-space:pre-wrap;align-items:flex-start;gap:8px;display:flex}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297 ._historyContent_1tu05_402 ._statusIcon_1tu05_403{flex-shrink:0;font-size:12px;line-height:1;transition:all .3s}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297 ._historyContent_1tu05_402 ._reflectionLines_1tu05_462{flex-direction:column;gap:4px;display:flex}._historySectionWrapper_1tu05_246 ._historySection_1tu05_246 ._historyItem_1tu05_297 ._historyMeta_1tu05_469{color:#fff9;margin-top:8px;font-size:10px;line-height:1}@keyframes _pulse_1tu05_1{0%,to{opacity:1;transform:scale(1)}50%{opacity:.4;transform:scale(1.3)}}@keyframes _retryPulse_1tu05_1{0%,to{opacity:1;transform:scale(1)rotate(0)}25%{opacity:.6;transform:scale(1.2)rotate(90deg)}50%{opacity:.8;transform:scale(1.1)rotate(180deg)}75%{opacity:.6;transform:scale(1.2)rotate(270deg)}}@keyframes _celebrate_1tu05_1{0%,to{transform:scale(1)}25%{transform:scale(1.2)rotate(-5deg)}75%{transform:scale(1.2)rotate(5deg)}}@keyframes _shimmer_1tu05_1{0%{left:-100%}to{left:100%}}._inputSectionWrapper_1tu05_539{width:var(--history-width);top:var(--height);left:var(--side-space);z-index:-1;visibility:visible;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);border-bottom-left-radius:calc(var(--border-radius) + 4px);border-bottom-right-radius:calc(var(--border-radius) + 4px);background:#bababa33;border:2px solid #ffffff4d;height:48px;transition:all .2s;position:absolute;overflow:hidden;box-shadow:0 1px 16px #0006}._inputSectionWrapper_1tu05_539._hidden_1tu05_562{visibility:collapse;height:0}._inputSectionWrapper_1tu05_539 ._inputSection_1tu05_539{align-items:center;gap:4px;padding:8px;display:flex}._inputSectionWrapper_1tu05_539 ._inputSection_1tu05_539 ._taskInput_1tu05_573{color:#141414;background:#fff6;border:1px solid #ffffff4d;border-radius:10px;outline:none;flex:1;height:28px;padding-inline:10px;font-size:12px;line-height:1;transition:all .2s}._inputSectionWrapper_1tu05_539 ._inputSection_1tu05_539 ._taskInput_1tu05_573::placeholder{color:#353535}._inputSectionWrapper_1tu05_539 ._inputSection_1tu05_539 ._taskInput_1tu05_573:focus{background:#fffc;border-color:#39b6ff99;box-shadow:0 0 0 2px #39b6ff33}
|
|
2
|
-
/*$vite$:1*/`,document.head.appendChild(__vite_style__);var __defProp=Object.defineProperty,__esmMin=(e,t)=>()=>(e&&(t=e(e=0)),t),__exportAll=(e,t)=>{let n={};for(var r in e)__defProp(n,r,{get:e[r],enumerable:!0});return t||__defProp(n,Symbol.toStringTag,{value:`Module`}),n},_a$1;function $constructor(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n
|
|
2
|
+
/*$vite$:1*/`,document.head.appendChild(__vite_style__);var __defProp=Object.defineProperty,__esmMin=(e,t)=>()=>(e&&(t=e(e=0)),t),__exportAll=(e,t)=>{let n={};for(var r in e)__defProp(n,r,{get:e[r],enumerable:!0});return t||__defProp(n,Symbol.toStringTag,{value:`Module`}),n},_a$1;function $constructor(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var $ZodAsyncError=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$ZodEncodeError=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(_a$1=globalThis).__zod_globalConfig??(_a$1.__zod_globalConfig={});var globalConfig=globalThis.__zod_globalConfig;function config(e){return e&&Object.assign(globalConfig,e),globalConfig}function getEnumValues(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function jsonStringifyReplacer(e,t){return typeof t==`bigint`?t.toString():t}function cached(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}throw Error(`cached value already set`)}}}function nullish(e){return e==null}function cleanRegex(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function floatSafeRemainder(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}var EVALUATING=Symbol(`evaluating`);function defineLazy(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==EVALUATING)return r===void 0&&(r=EVALUATING,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function assignProp(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...e){let t={};for(let n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function esc(e){return JSON.stringify(e)}function slugify(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var captureStackTrace=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var allowsEval=cached(()=>{if(globalConfig.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function isPlainObject(e){if(isObject(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(isObject(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function shallowClone(e){return isPlainObject(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var propertyKeyTypes=new Set([`string`,`number`,`symbol`]);function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function clone(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function normalizeParams(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function optionalKeys(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}var NUMBER_FORMAT_RANGES={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function pick(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return clone(e,mergeDefs(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return assignProp(this,`shape`,e),e},checks:[]}))}function omit(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return clone(e,mergeDefs(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return assignProp(this,`shape`,r),r},checks:[]}))}function extend(e,t){if(!isPlainObject(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return clone(e,mergeDefs(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return assignProp(this,`shape`,n),n}}))}function safeExtend(e,t){if(!isPlainObject(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return clone(e,mergeDefs(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return assignProp(this,`shape`,n),n}}))}function merge(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return clone(e,mergeDefs(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return assignProp(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function partial(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return clone(t,mergeDefs(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return assignProp(this,`shape`,i),i},checks:[]}))}function required(e,t,n){return clone(t,mergeDefs(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return assignProp(this,`shape`,i),i}}))}function aborted(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function explicitlyAborted(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function prefixIssues(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function unwrapMessage(e){return typeof e==`string`?e:e?.message}function finalizeIssue(e,t,n){let r=e.message?e.message:unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(n.customError?.(e))??unwrapMessage(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function getLengthableOrigin(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function issue(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var initializer$1=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,jsonStringifyReplacer,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},$ZodError=$constructor(`$ZodError`,initializer$1),$ZodRealError=$constructor(`$ZodError`,initializer$1,{Parent:Error});function flattenError(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function formatError(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}function toDotPath(e){let t=[],n=e.map(e=>typeof e==`object`?e.key:e);for(let e of n)typeof e==`number`?t.push(`[${e}]`):typeof e==`symbol`?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push(`.`),t.push(e));return t.join(``)}function prettifyError(e){let t=[],n=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(let e of n)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${toDotPath(e.path)}`);return t.join(`
|
|
3
3
|
`)}var _parse=e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new $ZodAsyncError;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>finalizeIssue(e,a,config())));throw captureStackTrace(t,i?.callee),t}return o.value},_parseAsync=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>finalizeIssue(e,a,config())));throw captureStackTrace(t,i?.callee),t}return o.value},_safeParse=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new $ZodAsyncError;return a.issues.length?{success:!1,error:new(e??$ZodError)(a.issues.map(e=>finalizeIssue(e,i,config())))}:{success:!0,data:a.value}},safeParse$1=_safeParse($ZodRealError),_safeParseAsync=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>finalizeIssue(e,i,config())))}:{success:!0,data:a.value}},safeParseAsync$1=_safeParseAsync($ZodRealError),_encode=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _parse(e)(t,n,i)},_decode=e=>(t,n,r)=>_parse(e)(t,n,r),_encodeAsync=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _parseAsync(e)(t,n,i)},_decodeAsync=e=>async(t,n,r)=>_parseAsync(e)(t,n,r),_safeEncode=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParse(e)(t,n,i)},_safeDecode=e=>(t,n,r)=>_safeParse(e)(t,n,r),_safeEncodeAsync=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParseAsync(e)(t,n,i)},_safeDecodeAsync=e=>async(t,n,r)=>_safeParseAsync(e)(t,n,r),cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration$1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji$1=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function emoji(){return new RegExp(_emoji$1,`u`)}var ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/,dateSource=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,date$1=RegExp(`^${dateSource}$`);function timeSource(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time$1(e){return RegExp(`^${timeSource(e)}$`)}function datetime$1(e){let t=timeSource({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${dateSource}T(?:${r})$`)}var string$1=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},integer=/^-?\d+$/,number$1=/^-?\d+(?:\.\d+)?$/,boolean$1=/^(?:true|false)$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/,$ZodCheck=$constructor(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),numericOriginMap={number:`number`,bigint:`bigint`,object:`date`},$ZodCheckLessThan=$constructor(`$ZodCheckLessThan`,(e,t)=>{$ZodCheck.init(e,t);let n=numericOriginMap[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$ZodCheckGreaterThan=$constructor(`$ZodCheckGreaterThan`,(e,t)=>{$ZodCheck.init(e,t);let n=numericOriginMap[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$ZodCheckMultipleOf=$constructor(`$ZodCheckMultipleOf`,(e,t)=>{$ZodCheck.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):floatSafeRemainder(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckNumberFormat=$constructor(`$ZodCheckNumberFormat`,(e,t)=>{$ZodCheck.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=NUMBER_FORMAT_RANGES[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=integer)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),$ZodCheckMaxLength=$constructor(`$ZodCheckMaxLength`,(e,t)=>{var n;$ZodCheck.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!nullish(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=getLengthableOrigin(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),$ZodCheckMinLength=$constructor(`$ZodCheckMinLength`,(e,t)=>{var n;$ZodCheck.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!nullish(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=getLengthableOrigin(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),$ZodCheckLengthEquals=$constructor(`$ZodCheckLengthEquals`,(e,t)=>{var n;$ZodCheck.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!nullish(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=getLengthableOrigin(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckStringFormat=$constructor(`$ZodCheckStringFormat`,(e,t)=>{var n,r;$ZodCheck.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),$ZodCheckRegex=$constructor(`$ZodCheckRegex`,(e,t)=>{$ZodCheckStringFormat.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),$ZodCheckLowerCase=$constructor(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=lowercase,$ZodCheckStringFormat.init(e,t)}),$ZodCheckUpperCase=$constructor(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=uppercase,$ZodCheckStringFormat.init(e,t)}),$ZodCheckIncludes=$constructor(`$ZodCheckIncludes`,(e,t)=>{$ZodCheck.init(e,t);let n=escapeRegex(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckStartsWith=$constructor(`$ZodCheckStartsWith`,(e,t)=>{$ZodCheck.init(e,t);let n=RegExp(`^${escapeRegex(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckEndsWith=$constructor(`$ZodCheckEndsWith`,(e,t)=>{$ZodCheck.init(e,t);let n=RegExp(`.*${escapeRegex(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),$ZodCheckOverwrite=$constructor(`$ZodCheckOverwrite`,(e,t)=>{$ZodCheck.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Doc=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
4
4
|
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
|
|
5
|
-
`))}},version={major:4,minor:4,patch:3},$ZodType=$constructor(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=version;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=aborted(e),i;for(let a of t){if(a._zod.def.when){if(explicitlyAborted(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new $ZodAsyncError;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=aborted(e,t))});else{if(e.issues.length===t)continue;r||=aborted(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(aborted(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new $ZodAsyncError;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new $ZodAsyncError;return o.then(e=>t(e,r,a))}return t(o,r,a)}}defineLazy(e,`~standard`,()=>({validate:t=>{try{let n=safeParse$1(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return safeParseAsync$1(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),$ZodString=$constructor(`$ZodString`,(e,t)=>{$ZodType.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??string$1(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),$ZodStringFormat=$constructor(`$ZodStringFormat`,(e,t)=>{$ZodCheckStringFormat.init(e,t),$ZodString.init(e,t)}),$ZodGUID=$constructor(`$ZodGUID`,(e,t)=>{t.pattern??=guid,$ZodStringFormat.init(e,t)}),$ZodUUID=$constructor(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=uuid(e)}else t.pattern??=uuid();$ZodStringFormat.init(e,t)}),$ZodEmail=$constructor(`$ZodEmail`,(e,t)=>{t.pattern??=email,$ZodStringFormat.init(e,t)}),$ZodURL=$constructor(`$ZodURL`,(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),$ZodEmoji=$constructor(`$ZodEmoji`,(e,t)=>{t.pattern??=emoji(),$ZodStringFormat.init(e,t)}),$ZodNanoID=$constructor(`$ZodNanoID`,(e,t)=>{t.pattern??=nanoid,$ZodStringFormat.init(e,t)}),$ZodCUID=$constructor(`$ZodCUID`,(e,t)=>{t.pattern??=cuid,$ZodStringFormat.init(e,t)}),$ZodCUID2=$constructor(`$ZodCUID2`,(e,t)=>{t.pattern??=cuid2,$ZodStringFormat.init(e,t)}),$ZodULID=$constructor(`$ZodULID`,(e,t)=>{t.pattern??=ulid,$ZodStringFormat.init(e,t)}),$ZodXID=$constructor(`$ZodXID`,(e,t)=>{t.pattern??=xid,$ZodStringFormat.init(e,t)}),$ZodKSUID=$constructor(`$ZodKSUID`,(e,t)=>{t.pattern??=ksuid,$ZodStringFormat.init(e,t)}),$ZodISODateTime=$constructor(`$ZodISODateTime`,(e,t)=>{t.pattern??=datetime$1(t),$ZodStringFormat.init(e,t)}),$ZodISODate=$constructor(`$ZodISODate`,(e,t)=>{t.pattern??=date$1,$ZodStringFormat.init(e,t)}),$ZodISOTime=$constructor(`$ZodISOTime`,(e,t)=>{t.pattern??=time$1(t),$ZodStringFormat.init(e,t)}),$ZodISODuration=$constructor(`$ZodISODuration`,(e,t)=>{t.pattern??=duration$1,$ZodStringFormat.init(e,t)}),$ZodIPv4=$constructor(`$ZodIPv4`,(e,t)=>{t.pattern??=ipv4,$ZodStringFormat.init(e,t),e._zod.bag.format=`ipv4`}),$ZodIPv6=$constructor(`$ZodIPv6`,(e,t)=>{t.pattern??=ipv6,$ZodStringFormat.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),$ZodCIDRv4=$constructor(`$ZodCIDRv4`,(e,t)=>{t.pattern??=cidrv4,$ZodStringFormat.init(e,t)}),$ZodCIDRv6=$constructor(`$ZodCIDRv6`,(e,t)=>{t.pattern??=cidrv6,$ZodStringFormat.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function isValidBase64(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var $ZodBase64=$constructor(`$ZodBase64`,(e,t)=>{t.pattern??=base64,$ZodStringFormat.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{isValidBase64(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function isValidBase64URL(e){if(!base64url.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return isValidBase64(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var $ZodBase64URL=$constructor(`$ZodBase64URL`,(e,t)=>{t.pattern??=base64url,$ZodStringFormat.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{isValidBase64URL(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),$ZodE164=$constructor(`$ZodE164`,(e,t)=>{t.pattern??=e164,$ZodStringFormat.init(e,t)});function isValidJWT(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var $ZodJWT=$constructor(`$ZodJWT`,(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=n=>{isValidJWT(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),$ZodNumber=$constructor(`$ZodNumber`,(e,t)=>{$ZodType.init(e,t),e._zod.pattern=e._zod.bag.pattern??number$1,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),$ZodNumberFormat=$constructor(`$ZodNumberFormat`,(e,t)=>{$ZodCheckNumberFormat.init(e,t),$ZodNumber.init(e,t)}),$ZodBoolean=$constructor(`$ZodBoolean`,(e,t)=>{$ZodType.init(e,t),e._zod.pattern=boolean$1,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),$ZodUnknown=$constructor(`$ZodUnknown`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=e=>e}),$ZodNever=$constructor(`$ZodNever`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function handleArrayResult(e,t,n){e.issues.length&&t.issues.push(...prefixIssues(n,e.issues)),t.value[n]=e.value}var $ZodArray=$constructor(`$ZodArray`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>handleArrayResult(t,n,e))):handleArrayResult(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function handlePropertyResult(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...prefixIssues(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function normalizeDef(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=optionalKeys(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function handleCatchall(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>handlePropertyResult(e,n,i,t,u,d))):handlePropertyResult(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var $ZodObject=$constructor(`$ZodObject`,(e,t)=>{if($ZodType.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,`shape`,{get:()=>{let n={...e};return Object.defineProperty(t,`shape`,{value:n}),n}})}let n=cached(()=>normalizeDef(t));defineLazy(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=isObject,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>handlePropertyResult(n,t,e,s,r,i))):handlePropertyResult(a,t,e,s,r,i)}return i?handleCatchall(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),$ZodObjectJIT=$constructor(`$ZodObjectJIT`,(e,t)=>{$ZodObject.init(e,t);let n=e._zod.parse,r=cached(()=>normalizeDef(t)),i=e=>{let t=new Doc([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=esc(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=esc(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`
|
|
5
|
+
`))}},version={major:4,minor:4,patch:3},$ZodType=$constructor(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=version;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=aborted(e),i;for(let a of t){if(a._zod.def.when){if(explicitlyAborted(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new $ZodAsyncError;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=aborted(e,t))});else{if(e.issues.length===t)continue;r||=aborted(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(aborted(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new $ZodAsyncError;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new $ZodAsyncError;return o.then(e=>t(e,r,a))}return t(o,r,a)}}defineLazy(e,`~standard`,()=>({validate:t=>{try{let n=safeParse$1(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return safeParseAsync$1(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),$ZodString=$constructor(`$ZodString`,(e,t)=>{$ZodType.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??string$1(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),$ZodStringFormat=$constructor(`$ZodStringFormat`,(e,t)=>{$ZodCheckStringFormat.init(e,t),$ZodString.init(e,t)}),$ZodGUID=$constructor(`$ZodGUID`,(e,t)=>{t.pattern??=guid,$ZodStringFormat.init(e,t)}),$ZodUUID=$constructor(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=uuid(e)}else t.pattern??=uuid();$ZodStringFormat.init(e,t)}),$ZodEmail=$constructor(`$ZodEmail`,(e,t)=>{t.pattern??=email,$ZodStringFormat.init(e,t)}),$ZodURL=$constructor(`$ZodURL`,(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),$ZodEmoji=$constructor(`$ZodEmoji`,(e,t)=>{t.pattern??=emoji(),$ZodStringFormat.init(e,t)}),$ZodNanoID=$constructor(`$ZodNanoID`,(e,t)=>{t.pattern??=nanoid,$ZodStringFormat.init(e,t)}),$ZodCUID=$constructor(`$ZodCUID`,(e,t)=>{t.pattern??=cuid,$ZodStringFormat.init(e,t)}),$ZodCUID2=$constructor(`$ZodCUID2`,(e,t)=>{t.pattern??=cuid2,$ZodStringFormat.init(e,t)}),$ZodULID=$constructor(`$ZodULID`,(e,t)=>{t.pattern??=ulid,$ZodStringFormat.init(e,t)}),$ZodXID=$constructor(`$ZodXID`,(e,t)=>{t.pattern??=xid,$ZodStringFormat.init(e,t)}),$ZodKSUID=$constructor(`$ZodKSUID`,(e,t)=>{t.pattern??=ksuid,$ZodStringFormat.init(e,t)}),$ZodISODateTime=$constructor(`$ZodISODateTime`,(e,t)=>{t.pattern??=datetime$1(t),$ZodStringFormat.init(e,t)}),$ZodISODate=$constructor(`$ZodISODate`,(e,t)=>{t.pattern??=date$1,$ZodStringFormat.init(e,t)}),$ZodISOTime=$constructor(`$ZodISOTime`,(e,t)=>{t.pattern??=time$1(t),$ZodStringFormat.init(e,t)}),$ZodISODuration=$constructor(`$ZodISODuration`,(e,t)=>{t.pattern??=duration$1,$ZodStringFormat.init(e,t)}),$ZodIPv4=$constructor(`$ZodIPv4`,(e,t)=>{t.pattern??=ipv4,$ZodStringFormat.init(e,t),e._zod.bag.format=`ipv4`}),$ZodIPv6=$constructor(`$ZodIPv6`,(e,t)=>{t.pattern??=ipv6,$ZodStringFormat.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),$ZodCIDRv4=$constructor(`$ZodCIDRv4`,(e,t)=>{t.pattern??=cidrv4,$ZodStringFormat.init(e,t)}),$ZodCIDRv6=$constructor(`$ZodCIDRv6`,(e,t)=>{t.pattern??=cidrv6,$ZodStringFormat.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function isValidBase64(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var $ZodBase64=$constructor(`$ZodBase64`,(e,t)=>{t.pattern??=base64,$ZodStringFormat.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{isValidBase64(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function isValidBase64URL(e){if(!base64url.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return isValidBase64(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var $ZodBase64URL=$constructor(`$ZodBase64URL`,(e,t)=>{t.pattern??=base64url,$ZodStringFormat.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{isValidBase64URL(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),$ZodE164=$constructor(`$ZodE164`,(e,t)=>{t.pattern??=e164,$ZodStringFormat.init(e,t)});function isValidJWT(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var $ZodJWT=$constructor(`$ZodJWT`,(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=n=>{isValidJWT(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),$ZodNumber=$constructor(`$ZodNumber`,(e,t)=>{$ZodType.init(e,t),e._zod.pattern=e._zod.bag.pattern??number$1,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),$ZodNumberFormat=$constructor(`$ZodNumberFormat`,(e,t)=>{$ZodCheckNumberFormat.init(e,t),$ZodNumber.init(e,t)}),$ZodBoolean=$constructor(`$ZodBoolean`,(e,t)=>{$ZodType.init(e,t),e._zod.pattern=boolean$1,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),$ZodUnknown=$constructor(`$ZodUnknown`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=e=>e}),$ZodNever=$constructor(`$ZodNever`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function handleArrayResult(e,t,n){e.issues.length&&t.issues.push(...prefixIssues(n,e.issues)),t.value[n]=e.value}var $ZodArray=$constructor(`$ZodArray`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>handleArrayResult(t,n,e))):handleArrayResult(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function handlePropertyResult(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...prefixIssues(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function normalizeDef(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=optionalKeys(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function handleCatchall(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>handlePropertyResult(e,n,i,t,u,d))):handlePropertyResult(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}var $ZodObject=$constructor(`$ZodObject`,(e,t)=>{if($ZodType.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=cached(()=>normalizeDef(t));defineLazy(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=isObject,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>handlePropertyResult(n,t,e,s,r,i))):handlePropertyResult(a,t,e,s,r,i)}return i?handleCatchall(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),$ZodObjectJIT=$constructor(`$ZodObjectJIT`,(e,t)=>{$ZodObject.init(e,t);let n=e._zod.parse,r=cached(()=>normalizeDef(t)),i=e=>{let t=new Doc([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=esc(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=esc(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`
|
|
6
6
|
if (${n}.issues.length) {
|
|
7
7
|
if (${o} in input) {
|
|
8
8
|
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
@@ -63,11 +63,11 @@
|
|
|
63
63
|
|
|
64
64
|
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=isObject,s=!globalConfig.jitless,c=s&&allowsEval.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?handleCatchall([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function handleUnionResults(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!aborted(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>finalizeIssue(e,r,config())))}),t)}var $ZodUnion=$constructor(`$ZodUnion`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),defineLazy(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),defineLazy(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),defineLazy(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>cleanRegex(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>handleUnionResults(t,r,e,i)):handleUnionResults(o,r,e,i)}}),$ZodIntersection=$constructor(`$ZodIntersection`,(e,t)=>{$ZodType.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>handleIntersectionResults(e,t,n)):handleIntersectionResults(e,i,a)}});function mergeValues(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(isPlainObject(e)&&isPlainObject(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=mergeValues(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=mergeValues(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),aborted(e))return e;let o=mergeValues(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var $ZodEnum=$constructor(`$ZodEnum`,(e,t)=>{$ZodType.init(e,t);let n=getEnumValues(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>propertyKeyTypes.has(typeof e)).map(e=>typeof e==`string`?escapeRegex(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),$ZodTransform=$constructor(`$ZodTransform`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new $ZodAsyncError;return n.value=i,n.fallback=!0,n}});function handleOptionalResult(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var $ZodOptional=$constructor(`$ZodOptional`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,defineLazy(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),defineLazy(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${cleanRegex(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>handleOptionalResult(e,r)):handleOptionalResult(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),$ZodExactOptional=$constructor(`$ZodExactOptional`,(e,t)=>{$ZodOptional.init(e,t),defineLazy(e._zod,`values`,()=>t.innerType._zod.values),defineLazy(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),$ZodNullable=$constructor(`$ZodNullable`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`optin`,()=>t.innerType._zod.optin),defineLazy(e._zod,`optout`,()=>t.innerType._zod.optout),defineLazy(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${cleanRegex(e.source)}|null)$`):void 0}),defineLazy(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),$ZodDefault=$constructor(`$ZodDefault`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`optional`,defineLazy(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>handleDefaultResult(e,t)):handleDefaultResult(r,t)}});function handleDefaultResult(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var $ZodPrefault=$constructor(`$ZodPrefault`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`optional`,defineLazy(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),$ZodNonOptional=$constructor(`$ZodNonOptional`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>handleNonOptionalResult(t,e)):handleNonOptionalResult(i,e)}});function handleNonOptionalResult(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var $ZodCatch=$constructor(`$ZodCatch`,(e,t)=>{$ZodType.init(e,t),e._zod.optin=`optional`,defineLazy(e._zod,`optout`,()=>t.innerType._zod.optout),defineLazy(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>finalizeIssue(e,n,config()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>finalizeIssue(e,n,config()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),$ZodPipe=$constructor(`$ZodPipe`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`values`,()=>t.in._zod.values),defineLazy(e._zod,`optin`,()=>t.in._zod.optin),defineLazy(e._zod,`optout`,()=>t.out._zod.optout),defineLazy(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>handlePipeResult(e,t.in,n)):handlePipeResult(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>handlePipeResult(e,t.out,n)):handlePipeResult(r,t.out,n)}});function handlePipeResult(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var $ZodReadonly=$constructor(`$ZodReadonly`,(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,`propValues`,()=>t.innerType._zod.propValues),defineLazy(e._zod,`values`,()=>t.innerType._zod.values),defineLazy(e._zod,`optin`,()=>t.innerType?._zod?.optin),defineLazy(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(handleReadonlyResult):handleReadonlyResult(r)}});function handleReadonlyResult(e){return e.value=Object.freeze(e.value),e}var $ZodCustom=$constructor(`$ZodCustom`,(e,t)=>{$ZodCheck.init(e,t),$ZodType.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>handleRefineResult(t,n,r,e));handleRefineResult(i,n,r,e)}});function handleRefineResult(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(issue(e))}}var _a,$ZodRegistry=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function registry(){return new $ZodRegistry}(_a=globalThis).__zod_globalRegistry??(_a.__zod_globalRegistry=registry());var globalRegistry=globalThis.__zod_globalRegistry;function _string(e,t){return new e({type:`string`,...normalizeParams(t)})}function _email(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _guid(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _uuid(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _uuidv4(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...normalizeParams(t)})}function _uuidv6(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...normalizeParams(t)})}function _uuidv7(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...normalizeParams(t)})}function _url(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _emoji(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _nanoid(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cuid(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cuid2(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ulid(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _xid(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ksuid(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ipv4(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _ipv6(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cidrv4(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _cidrv6(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _base64(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _base64url(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _e164(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _jwt(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...normalizeParams(t)})}function _isoDateTime(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...normalizeParams(t)})}function _isoDate(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...normalizeParams(t)})}function _isoTime(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...normalizeParams(t)})}function _isoDuration(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...normalizeParams(t)})}function _number(e,t){return new e({type:`number`,checks:[],...normalizeParams(t)})}function _int(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...normalizeParams(t)})}function _boolean(e,t){return new e({type:`boolean`,...normalizeParams(t)})}function _unknown(e){return new e({type:`unknown`})}function _never(e,t){return new e({type:`never`,...normalizeParams(t)})}function _lt(e,t){return new $ZodCheckLessThan({check:`less_than`,...normalizeParams(t),value:e,inclusive:!1})}function _lte(e,t){return new $ZodCheckLessThan({check:`less_than`,...normalizeParams(t),value:e,inclusive:!0})}function _gt(e,t){return new $ZodCheckGreaterThan({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!1})}function _gte(e,t){return new $ZodCheckGreaterThan({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!0})}function _multipleOf(e,t){return new $ZodCheckMultipleOf({check:`multiple_of`,...normalizeParams(t),value:e})}function _maxLength(e,t){return new $ZodCheckMaxLength({check:`max_length`,...normalizeParams(t),maximum:e})}function _minLength(e,t){return new $ZodCheckMinLength({check:`min_length`,...normalizeParams(t),minimum:e})}function _length(e,t){return new $ZodCheckLengthEquals({check:`length_equals`,...normalizeParams(t),length:e})}function _regex(e,t){return new $ZodCheckRegex({check:`string_format`,format:`regex`,...normalizeParams(t),pattern:e})}function _lowercase(e){return new $ZodCheckLowerCase({check:`string_format`,format:`lowercase`,...normalizeParams(e)})}function _uppercase(e){return new $ZodCheckUpperCase({check:`string_format`,format:`uppercase`,...normalizeParams(e)})}function _includes(e,t){return new $ZodCheckIncludes({check:`string_format`,format:`includes`,...normalizeParams(t),includes:e})}function _startsWith(e,t){return new $ZodCheckStartsWith({check:`string_format`,format:`starts_with`,...normalizeParams(t),prefix:e})}function _endsWith(e,t){return new $ZodCheckEndsWith({check:`string_format`,format:`ends_with`,...normalizeParams(t),suffix:e})}function _overwrite(e){return new $ZodCheckOverwrite({check:`overwrite`,tx:e})}function _normalize(e){return _overwrite(t=>t.normalize(e))}function _trim(){return _overwrite(e=>e.trim())}function _toLowerCase(){return _overwrite(e=>e.toLowerCase())}function _toUpperCase(){return _overwrite(e=>e.toUpperCase())}function _slugify(){return _overwrite(e=>slugify(e))}function _array(e,t,n){return new e({type:`array`,element:t,...normalizeParams(n)})}function _refine(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...normalizeParams(n)})}function _superRefine(e,t){let n=_check(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(issue(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(issue(r))}},e(t.value,t)),t);return n}function _check(e,t){let n=new $ZodCheck({check:`custom`,...normalizeParams(t)});return n._zod.check=e,n}function initializeContext(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??globalRegistry,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function process(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,process(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&isTransforming(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function extractDefs(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
65
65
|
|
|
66
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function finalize(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(t,`input`,e.processors),output:createStandardJSONSchemaMethod(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function isTransforming(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return isTransforming(r.element,n);if(r.type===`set`)return isTransforming(r.valueType,n);if(r.type===`lazy`)return isTransforming(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return isTransforming(r.innerType,n);if(r.type===`intersection`)return isTransforming(r.left,n)||isTransforming(r.right,n);if(r.type===`record`||r.type===`map`)return isTransforming(r.keyType,n)||isTransforming(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:isTransforming(r.in,n)||isTransforming(r.out,n);if(r.type===`object`){for(let e in r.shape)if(isTransforming(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(isTransforming(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(isTransforming(e,n))return!0;return!!(r.rest&&isTransforming(r.rest,n))}return!1}var createToJSONSchemaMethod=(e,t={})=>n=>{let r=initializeContext({...n,processors:t});return process(e,r),extractDefs(r,e),finalize(r,e)},createStandardJSONSchemaMethod=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=initializeContext({...i??{},target:a,io:t,processors:n});return process(e,o),extractDefs(o,e),finalize(o,e)},formatMap={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},stringProcessor=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=formatMap[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},numberProcessor=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},booleanProcessor=(e,t,n,r)=>{n.type=`boolean`},bigintProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},symbolProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},nullProcessor=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},undefinedProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},voidProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},neverProcessor=(e,t,n,r)=>{n.not={}},anyProcessor=(e,t,n,r)=>{},unknownProcessor=(e,t,n,r)=>{},dateProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},enumProcessor=(e,t,n,r)=>{let i=e._zod.def,a=getEnumValues(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},literalProcessor=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},nanProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},templateLiteralProcessor=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},fileProcessor=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},successProcessor=(e,t,n,r)=>{n.type=`boolean`},customProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},functionProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},transformProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},mapProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},setProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},arrayProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=process(a.element,t,{...r,path:[...r.path,`items`]})},objectProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=process(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=process(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},unionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>process(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},intersectionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=process(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=process(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},tupleProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>process(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?process(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},recordProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=process(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=process(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=process(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},nullableProcessor=(e,t,n,r)=>{let i=e._zod.def,a=process(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},nonoptionalProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},defaultProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},prefaultProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},catchProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},pipeProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;process(o,t,r);let s=t.seen.get(e);s.ref=o},readonlyProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},promiseProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},optionalProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},lazyProcessor=(e,t,n,r)=>{let i=e._zod.innerType;process(i,t,r);let a=t.seen.get(e);a.ref=i},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(e,t){if(`_idmap`in e){let n=e,r=initializeContext({...t,processors:allProcessors}),i={};for(let e of n._idmap.entries()){let[t,n]=e;process(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;extractDefs(r,n),a[t]=finalize(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=initializeContext({...t,processors:allProcessors});return process(e,n),extractDefs(n,e),finalize(n,e)}var ZodISODateTime=$constructor(`ZodISODateTime`,(e,t)=>{$ZodISODateTime.init(e,t),ZodStringFormat.init(e,t)});function datetime(e){return _isoDateTime(ZodISODateTime,e)}var ZodISODate=$constructor(`ZodISODate`,(e,t)=>{$ZodISODate.init(e,t),ZodStringFormat.init(e,t)});function date(e){return _isoDate(ZodISODate,e)}var ZodISOTime=$constructor(`ZodISOTime`,(e,t)=>{$ZodISOTime.init(e,t),ZodStringFormat.init(e,t)});function time(e){return _isoTime(ZodISOTime,e)}var ZodISODuration=$constructor(`ZodISODuration`,(e,t)=>{$ZodISODuration.init(e,t),ZodStringFormat.init(e,t)});function duration(e){return _isoDuration(ZodISODuration,e)}var initializer=(e,t)=>{$ZodError.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>formatError(e,t)},flatten:{value:t=>flattenError(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return e.issues.length===0}}})},ZodRealError=$constructor(`ZodError`,initializer,{Parent:Error}),parse=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError),encode=_encode(ZodRealError),decode=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError),_installedGroups=new WeakMap;function _installLazyMethods(e,t,n){let r=Object.getPrototypeOf(e),i=_installedGroups.get(r);if(i||(i=new Set,_installedGroups.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var ZodType=$constructor(`ZodType`,(e,t)=>($ZodType.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:createStandardJSONSchemaMethod(e,`input`),output:createStandardJSONSchemaMethod(e,`output`)}}),e.toJSONSchema=createToJSONSchemaMethod(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.parse=(t,n)=>parse(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>safeParse(e,t,n),e.parseAsync=async(t,n)=>parseAsync(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>safeParseAsync(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>encode(e,t,n),e.decode=(t,n)=>decode(e,t,n),e.encodeAsync=async(t,n)=>encodeAsync(e,t,n),e.decodeAsync=async(t,n)=>decodeAsync(e,t,n),e.safeEncode=(t,n)=>safeEncode(e,t,n),e.safeDecode=(t,n)=>safeDecode(e,t,n),e.safeEncodeAsync=async(t,n)=>safeEncodeAsync(e,t,n),e.safeDecodeAsync=async(t,n)=>safeDecodeAsync(e,t,n),_installLazyMethods(e,`ZodType`,{check(...e){let t=this.def;return this.clone(mergeDefs(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return clone(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(refine(e,t))},superRefine(e,t){return this.check(superRefine(e,t))},overwrite(e){return this.check(_overwrite(e))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(e){return nonoptional(this,e)},array(){return array(this)},or(e){return union([this,e])},and(e){return intersection(this,e)},transform(e){return pipe(this,transform(e))},default(e){return _default(this,e)},prefault(e){return prefault(this,e)},catch(e){return _catch(this,e)},pipe(e){return pipe(this,e)},readonly(){return readonly(this)},describe(e){let t=this.clone();return globalRegistry.add(t,{description:e}),t},meta(...e){if(e.length===0)return globalRegistry.get(this);let t=this.clone();return globalRegistry.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,`description`,{get(){return globalRegistry.get(e)?.description},configurable:!0}),e)),_ZodString=$constructor(`_ZodString`,(e,t)=>{$ZodString.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>stringProcessor(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,_installLazyMethods(e,`_ZodString`,{regex(...e){return this.check(_regex(...e))},includes(...e){return this.check(_includes(...e))},startsWith(...e){return this.check(_startsWith(...e))},endsWith(...e){return this.check(_endsWith(...e))},min(...e){return this.check(_minLength(...e))},max(...e){return this.check(_maxLength(...e))},length(...e){return this.check(_length(...e))},nonempty(...e){return this.check(_minLength(1,...e))},lowercase(e){return this.check(_lowercase(e))},uppercase(e){return this.check(_uppercase(e))},trim(){return this.check(_trim())},normalize(...e){return this.check(_normalize(...e))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})}),ZodString=$constructor(`ZodString`,(e,t)=>{$ZodString.init(e,t),_ZodString.init(e,t),e.email=t=>e.check(_email(ZodEmail,t)),e.url=t=>e.check(_url(ZodURL,t)),e.jwt=t=>e.check(_jwt(ZodJWT,t)),e.emoji=t=>e.check(_emoji(ZodEmoji,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.uuid=t=>e.check(_uuid(ZodUUID,t)),e.uuidv4=t=>e.check(_uuidv4(ZodUUID,t)),e.uuidv6=t=>e.check(_uuidv6(ZodUUID,t)),e.uuidv7=t=>e.check(_uuidv7(ZodUUID,t)),e.nanoid=t=>e.check(_nanoid(ZodNanoID,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.cuid=t=>e.check(_cuid(ZodCUID,t)),e.cuid2=t=>e.check(_cuid2(ZodCUID2,t)),e.ulid=t=>e.check(_ulid(ZodULID,t)),e.base64=t=>e.check(_base64(ZodBase64,t)),e.base64url=t=>e.check(_base64url(ZodBase64URL,t)),e.xid=t=>e.check(_xid(ZodXID,t)),e.ksuid=t=>e.check(_ksuid(ZodKSUID,t)),e.ipv4=t=>e.check(_ipv4(ZodIPv4,t)),e.ipv6=t=>e.check(_ipv6(ZodIPv6,t)),e.cidrv4=t=>e.check(_cidrv4(ZodCIDRv4,t)),e.cidrv6=t=>e.check(_cidrv6(ZodCIDRv6,t)),e.e164=t=>e.check(_e164(ZodE164,t)),e.datetime=t=>e.check(datetime(t)),e.date=t=>e.check(date(t)),e.time=t=>e.check(time(t)),e.duration=t=>e.check(duration(t))});function string(e){return _string(ZodString,e)}var ZodStringFormat=$constructor(`ZodStringFormat`,(e,t)=>{$ZodStringFormat.init(e,t),_ZodString.init(e,t)}),ZodEmail=$constructor(`ZodEmail`,(e,t)=>{$ZodEmail.init(e,t),ZodStringFormat.init(e,t)}),ZodGUID=$constructor(`ZodGUID`,(e,t)=>{$ZodGUID.init(e,t),ZodStringFormat.init(e,t)}),ZodUUID=$constructor(`ZodUUID`,(e,t)=>{$ZodUUID.init(e,t),ZodStringFormat.init(e,t)}),ZodURL=$constructor(`ZodURL`,(e,t)=>{$ZodURL.init(e,t),ZodStringFormat.init(e,t)}),ZodEmoji=$constructor(`ZodEmoji`,(e,t)=>{$ZodEmoji.init(e,t),ZodStringFormat.init(e,t)}),ZodNanoID=$constructor(`ZodNanoID`,(e,t)=>{$ZodNanoID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID=$constructor(`ZodCUID`,(e,t)=>{$ZodCUID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID2=$constructor(`ZodCUID2`,(e,t)=>{$ZodCUID2.init(e,t),ZodStringFormat.init(e,t)}),ZodULID=$constructor(`ZodULID`,(e,t)=>{$ZodULID.init(e,t),ZodStringFormat.init(e,t)}),ZodXID=$constructor(`ZodXID`,(e,t)=>{$ZodXID.init(e,t),ZodStringFormat.init(e,t)}),ZodKSUID=$constructor(`ZodKSUID`,(e,t)=>{$ZodKSUID.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv4=$constructor(`ZodIPv4`,(e,t)=>{$ZodIPv4.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv6=$constructor(`ZodIPv6`,(e,t)=>{$ZodIPv6.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv4=$constructor(`ZodCIDRv4`,(e,t)=>{$ZodCIDRv4.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv6=$constructor(`ZodCIDRv6`,(e,t)=>{$ZodCIDRv6.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64=$constructor(`ZodBase64`,(e,t)=>{$ZodBase64.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64URL=$constructor(`ZodBase64URL`,(e,t)=>{$ZodBase64URL.init(e,t),ZodStringFormat.init(e,t)}),ZodE164=$constructor(`ZodE164`,(e,t)=>{$ZodE164.init(e,t),ZodStringFormat.init(e,t)}),ZodJWT=$constructor(`ZodJWT`,(e,t)=>{$ZodJWT.init(e,t),ZodStringFormat.init(e,t)}),ZodNumber=$constructor(`ZodNumber`,(e,t)=>{$ZodNumber.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>numberProcessor(e,t,n,r),_installLazyMethods(e,`ZodNumber`,{gt(e,t){return this.check(_gt(e,t))},gte(e,t){return this.check(_gte(e,t))},min(e,t){return this.check(_gte(e,t))},lt(e,t){return this.check(_lt(e,t))},lte(e,t){return this.check(_lte(e,t))},max(e,t){return this.check(_lte(e,t))},int(e){return this.check(int(e))},safe(e){return this.check(int(e))},positive(e){return this.check(_gt(0,e))},nonnegative(e){return this.check(_gte(0,e))},negative(e){return this.check(_lt(0,e))},nonpositive(e){return this.check(_lte(0,e))},multipleOf(e,t){return this.check(_multipleOf(e,t))},step(e,t){return this.check(_multipleOf(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function number(e){return _number(ZodNumber,e)}var ZodNumberFormat=$constructor(`ZodNumberFormat`,(e,t)=>{$ZodNumberFormat.init(e,t),ZodNumber.init(e,t)});function int(e){return _int(ZodNumberFormat,e)}var ZodBoolean=$constructor(`ZodBoolean`,(e,t)=>{$ZodBoolean.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>booleanProcessor(e,t,n,r)});function boolean(e){return _boolean(ZodBoolean,e)}var ZodUnknown=$constructor(`ZodUnknown`,(e,t)=>{$ZodUnknown.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor(`ZodNever`,(e,t)=>{$ZodNever.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>neverProcessor(e,t,n,r)});function never(e){return _never(ZodNever,e)}var ZodArray=$constructor(`ZodArray`,(e,t)=>{$ZodArray.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>arrayProcessor(e,t,n,r),e.element=t.element,_installLazyMethods(e,`ZodArray`,{min(e,t){return this.check(_minLength(e,t))},nonempty(e){return this.check(_minLength(1,e))},max(e,t){return this.check(_maxLength(e,t))},length(e,t){return this.check(_length(e,t))},unwrap(){return this.element}})});function array(e,t){return _array(ZodArray,e,t)}var ZodObject=$constructor(`ZodObject`,(e,t)=>{$ZodObjectJIT.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>objectProcessor(e,t,n,r),defineLazy(e,`shape`,()=>t.shape),_installLazyMethods(e,`ZodObject`,{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:unknown()})},loose(){return this.clone({...this._zod.def,catchall:unknown()})},strict(){return this.clone({...this._zod.def,catchall:never()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return extend(this,e)},safeExtend(e){return safeExtend(this,e)},merge(e){return merge(this,e)},pick(e){return pick(this,e)},omit(e){return omit(this,e)},partial(...e){return partial(ZodOptional,this,e[0])},required(...e){return required(ZodNonOptional,this,e[0])}})});function object(e,t){return new ZodObject({type:`object`,shape:e??{},...normalizeParams(t)})}var ZodUnion=$constructor(`ZodUnion`,(e,t)=>{$ZodUnion.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>unionProcessor(e,t,n,r),e.options=t.options});function union(e,t){return new ZodUnion({type:`union`,options:e,...normalizeParams(t)})}var ZodIntersection=$constructor(`ZodIntersection`,(e,t)=>{$ZodIntersection.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>intersectionProcessor(e,t,n,r)});function intersection(e,t){return new ZodIntersection({type:`intersection`,left:e,right:t})}var ZodEnum=$constructor(`ZodEnum`,(e,t)=>{$ZodEnum.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>enumProcessor(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new ZodEnum({...t,checks:[],...normalizeParams(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new ZodEnum({...t,checks:[],...normalizeParams(r),entries:i})}});function _enum(e,t){return new ZodEnum({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...normalizeParams(t)})}var ZodTransform=$constructor(`ZodTransform`,(e,t)=>{$ZodTransform.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>transformProcessor(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(issue(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(issue(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function transform(e){return new ZodTransform({type:`transform`,transform:e})}var ZodOptional=$constructor(`ZodOptional`,(e,t)=>{$ZodOptional.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new ZodOptional({type:`optional`,innerType:e})}var ZodExactOptional=$constructor(`ZodExactOptional`,(e,t)=>{$ZodExactOptional.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function exactOptional(e){return new ZodExactOptional({type:`optional`,innerType:e})}var ZodNullable=$constructor(`ZodNullable`,(e,t)=>{$ZodNullable.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nullableProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new ZodNullable({type:`nullable`,innerType:e})}var ZodDefault=$constructor(`ZodDefault`,(e,t)=>{$ZodDefault.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>defaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new ZodDefault({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}var ZodPrefault=$constructor(`ZodPrefault`,(e,t)=>{$ZodPrefault.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>prefaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new ZodPrefault({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}var ZodNonOptional=$constructor(`ZodNonOptional`,(e,t)=>{$ZodNonOptional.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nonoptionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new ZodNonOptional({type:`nonoptional`,innerType:e,...normalizeParams(t)})}var ZodCatch=$constructor(`ZodCatch`,(e,t)=>{$ZodCatch.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>catchProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new ZodCatch({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var ZodPipe=$constructor(`ZodPipe`,(e,t)=>{$ZodPipe.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pipeProcessor(e,t,n,r),e.in=t.in,e.out=t.out});function pipe(e,t){return new ZodPipe({type:`pipe`,in:e,out:t})}var ZodReadonly=$constructor(`ZodReadonly`,(e,t)=>{$ZodReadonly.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>readonlyProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new ZodReadonly({type:`readonly`,innerType:e})}var ZodCustom=$constructor(`ZodCustom`,(e,t)=>{$ZodCustom.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>customProcessor(e,t,n,r)});function refine(e,t={}){return _refine(ZodCustom,e,t)}function superRefine(e,t){return _superRefine(e,t)}var InvokeErrorTypes={NETWORK_ERROR:`network_error`,RATE_LIMIT:`rate_limit`,SERVER_ERROR:`server_error`,NO_TOOL_CALL:`no_tool_call`,INVALID_TOOL_ARGS:`invalid_tool_args`,TOOL_EXECUTION_ERROR:`tool_execution_error`,UNKNOWN:`unknown`,CONFIG_ERROR:`config_error`,AUTH_ERROR:`auth_error`,CONTEXT_LENGTH:`context_length`,CONTENT_FILTER:`content_filter`},InvokeError=class extends Error{type;retryable;statusCode;rawError;rawResponse;constructor(e,t,n,r){super(t),this.name=`InvokeError`,this.type=e,this.retryable=this.isRetryable(e,n),this.rawError=n,this.rawResponse=r}isRetryable(e,t){return t?.name===`AbortError`?!1:[InvokeErrorTypes.NETWORK_ERROR,InvokeErrorTypes.RATE_LIMIT,InvokeErrorTypes.SERVER_ERROR,InvokeErrorTypes.NO_TOOL_CALL,InvokeErrorTypes.INVALID_TOOL_ARGS,InvokeErrorTypes.TOOL_EXECUTION_ERROR,InvokeErrorTypes.UNKNOWN].includes(e)}},ANSI_BACKGROUND_OFFSET=10,wrapAnsi16=(e=0)=>t=>`\u001B[${t+e}m`,wrapAnsi256=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,wrapAnsi16m=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,styles$1={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},modifierNames=Object.keys(styles$1.modifier),foregroundColorNames=Object.keys(styles$1.color),backgroundColorNames=Object.keys(styles$1.bgColor),colorNames=[...foregroundColorNames,...backgroundColorNames];function assembleStyles(){let e=new Map;for(let[t,n]of Object.entries(styles$1)){for(let[t,r]of Object.entries(n))styles$1[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=styles$1[t],e.set(r[0],r[1]);Object.defineProperty(styles$1,t,{value:n,enumerable:!1})}return Object.defineProperty(styles$1,`codes`,{value:e,enumerable:!1}),styles$1.color.close=`\x1B[39m`,styles$1.bgColor.close=`\x1B[49m`,styles$1.color.ansi=wrapAnsi16(),styles$1.color.ansi256=wrapAnsi256(),styles$1.color.ansi16m=wrapAnsi16m(),styles$1.bgColor.ansi=wrapAnsi16(ANSI_BACKGROUND_OFFSET),styles$1.bgColor.ansi256=wrapAnsi256(ANSI_BACKGROUND_OFFSET),styles$1.bgColor.ansi16m=wrapAnsi16m(ANSI_BACKGROUND_OFFSET),Object.defineProperties(styles$1,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>styles$1.rgbToAnsi256(...styles$1.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(e)),enumerable:!1}}),styles$1}var ansiStyles=assembleStyles(),level=(()=>{if(!(`navigator`in globalThis))return 0;if(globalThis.navigator.userAgentData){let e=navigator.userAgentData.brands.find(({brand:e})=>e===`Chromium`);if(e&&e.version>93)return 3}return+!!/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)})(),colorSupport=level!==0&&{level,hasBasic:!0,has256:level>=2,has16m:level>=3},supportsColor={stdout:colorSupport,stderr:colorSupport};function stringReplaceAll(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.slice(a),o}function stringEncaseCRLFWithFirstIndex(e,t,n,r){let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.slice(i,o?r-1:r)+t+(o?`\r
|
|
66
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function finalize(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(t,`input`,e.processors),output:createStandardJSONSchemaMethod(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function isTransforming(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return isTransforming(r.element,n);if(r.type===`set`)return isTransforming(r.valueType,n);if(r.type===`lazy`)return isTransforming(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return isTransforming(r.innerType,n);if(r.type===`intersection`)return isTransforming(r.left,n)||isTransforming(r.right,n);if(r.type===`record`||r.type===`map`)return isTransforming(r.keyType,n)||isTransforming(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:isTransforming(r.in,n)||isTransforming(r.out,n);if(r.type===`object`){for(let e in r.shape)if(isTransforming(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(isTransforming(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(isTransforming(e,n))return!0;return!!(r.rest&&isTransforming(r.rest,n))}return!1}var createToJSONSchemaMethod=(e,t={})=>n=>{let r=initializeContext({...n,processors:t});return process(e,r),extractDefs(r,e),finalize(r,e)},createStandardJSONSchemaMethod=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=initializeContext({...i??{},target:a,io:t,processors:n});return process(e,o),extractDefs(o,e),finalize(o,e)},formatMap={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},stringProcessor=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=formatMap[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},numberProcessor=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},booleanProcessor=(e,t,n,r)=>{n.type=`boolean`},bigintProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},symbolProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},nullProcessor=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},undefinedProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},voidProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},neverProcessor=(e,t,n,r)=>{n.not={}},anyProcessor=(e,t,n,r)=>{},unknownProcessor=(e,t,n,r)=>{},dateProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},enumProcessor=(e,t,n,r)=>{let i=e._zod.def,a=getEnumValues(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},literalProcessor=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},nanProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},templateLiteralProcessor=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},fileProcessor=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},successProcessor=(e,t,n,r)=>{n.type=`boolean`},customProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},functionProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},transformProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},mapProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},setProcessor=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},arrayProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=process(a.element,t,{...r,path:[...r.path,`items`]})},objectProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=process(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=process(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},unionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>process(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},intersectionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=process(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=process(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},tupleProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>process(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?process(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},recordProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=process(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=process(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=process(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},nullableProcessor=(e,t,n,r)=>{let i=e._zod.def,a=process(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},nonoptionalProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},defaultProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},prefaultProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},catchProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},pipeProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;process(o,t,r);let s=t.seen.get(e);s.ref=o},readonlyProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},promiseProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},optionalProcessor=(e,t,n,r)=>{let i=e._zod.def;process(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},lazyProcessor=(e,t,n,r)=>{let i=e._zod.innerType;process(i,t,r);let a=t.seen.get(e);a.ref=i},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(e,t){if(`_idmap`in e){let n=e,r=initializeContext({...t,processors:allProcessors}),i={};for(let e of n._idmap.entries()){let[t,n]=e;process(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;extractDefs(r,n),a[t]=finalize(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=initializeContext({...t,processors:allProcessors});return process(e,n),extractDefs(n,e),finalize(n,e)}var ZodISODateTime=$constructor(`ZodISODateTime`,(e,t)=>{$ZodISODateTime.init(e,t),ZodStringFormat.init(e,t)});function datetime(e){return _isoDateTime(ZodISODateTime,e)}var ZodISODate=$constructor(`ZodISODate`,(e,t)=>{$ZodISODate.init(e,t),ZodStringFormat.init(e,t)});function date(e){return _isoDate(ZodISODate,e)}var ZodISOTime=$constructor(`ZodISOTime`,(e,t)=>{$ZodISOTime.init(e,t),ZodStringFormat.init(e,t)});function time(e){return _isoTime(ZodISOTime,e)}var ZodISODuration=$constructor(`ZodISODuration`,(e,t)=>{$ZodISODuration.init(e,t),ZodStringFormat.init(e,t)});function duration(e){return _isoDuration(ZodISODuration,e)}var initializer=(e,t)=>{$ZodError.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>formatError(e,t)},flatten:{value:t=>flattenError(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return e.issues.length===0}}})},ZodRealError=$constructor(`ZodError`,initializer,{Parent:Error}),parse=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError),encode=_encode(ZodRealError),decode=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError),_installedGroups=new WeakMap;function _installLazyMethods(e,t,n){let r=Object.getPrototypeOf(e),i=_installedGroups.get(r);if(i||(i=new Set,_installedGroups.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var ZodType=$constructor(`ZodType`,(e,t)=>($ZodType.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:createStandardJSONSchemaMethod(e,`input`),output:createStandardJSONSchemaMethod(e,`output`)}}),e.toJSONSchema=createToJSONSchemaMethod(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>parse(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>safeParse(e,t,n),e.parseAsync=async(t,n)=>parseAsync(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>safeParseAsync(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>encode(e,t,n),e.decode=(t,n)=>decode(e,t,n),e.encodeAsync=async(t,n)=>encodeAsync(e,t,n),e.decodeAsync=async(t,n)=>decodeAsync(e,t,n),e.safeEncode=(t,n)=>safeEncode(e,t,n),e.safeDecode=(t,n)=>safeDecode(e,t,n),e.safeEncodeAsync=async(t,n)=>safeEncodeAsync(e,t,n),e.safeDecodeAsync=async(t,n)=>safeDecodeAsync(e,t,n),_installLazyMethods(e,`ZodType`,{check(...e){let t=this.def;return this.clone(mergeDefs(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return clone(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(refine(e,t))},superRefine(e,t){return this.check(superRefine(e,t))},overwrite(e){return this.check(_overwrite(e))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(e){return nonoptional(this,e)},array(){return array(this)},or(e){return union([this,e])},and(e){return intersection(this,e)},transform(e){return pipe(this,transform(e))},default(e){return _default(this,e)},prefault(e){return prefault(this,e)},catch(e){return _catch(this,e)},pipe(e){return pipe(this,e)},readonly(){return readonly(this)},describe(e){let t=this.clone();return globalRegistry.add(t,{description:e}),t},meta(...e){if(e.length===0)return globalRegistry.get(this);let t=this.clone();return globalRegistry.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return globalRegistry.get(e)?.description},configurable:!0}),e)),_ZodString=$constructor(`_ZodString`,(e,t)=>{$ZodString.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>stringProcessor(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,_installLazyMethods(e,`_ZodString`,{regex(...e){return this.check(_regex(...e))},includes(...e){return this.check(_includes(...e))},startsWith(...e){return this.check(_startsWith(...e))},endsWith(...e){return this.check(_endsWith(...e))},min(...e){return this.check(_minLength(...e))},max(...e){return this.check(_maxLength(...e))},length(...e){return this.check(_length(...e))},nonempty(...e){return this.check(_minLength(1,...e))},lowercase(e){return this.check(_lowercase(e))},uppercase(e){return this.check(_uppercase(e))},trim(){return this.check(_trim())},normalize(...e){return this.check(_normalize(...e))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})}),ZodString=$constructor(`ZodString`,(e,t)=>{$ZodString.init(e,t),_ZodString.init(e,t),e.email=t=>e.check(_email(ZodEmail,t)),e.url=t=>e.check(_url(ZodURL,t)),e.jwt=t=>e.check(_jwt(ZodJWT,t)),e.emoji=t=>e.check(_emoji(ZodEmoji,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.uuid=t=>e.check(_uuid(ZodUUID,t)),e.uuidv4=t=>e.check(_uuidv4(ZodUUID,t)),e.uuidv6=t=>e.check(_uuidv6(ZodUUID,t)),e.uuidv7=t=>e.check(_uuidv7(ZodUUID,t)),e.nanoid=t=>e.check(_nanoid(ZodNanoID,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.cuid=t=>e.check(_cuid(ZodCUID,t)),e.cuid2=t=>e.check(_cuid2(ZodCUID2,t)),e.ulid=t=>e.check(_ulid(ZodULID,t)),e.base64=t=>e.check(_base64(ZodBase64,t)),e.base64url=t=>e.check(_base64url(ZodBase64URL,t)),e.xid=t=>e.check(_xid(ZodXID,t)),e.ksuid=t=>e.check(_ksuid(ZodKSUID,t)),e.ipv4=t=>e.check(_ipv4(ZodIPv4,t)),e.ipv6=t=>e.check(_ipv6(ZodIPv6,t)),e.cidrv4=t=>e.check(_cidrv4(ZodCIDRv4,t)),e.cidrv6=t=>e.check(_cidrv6(ZodCIDRv6,t)),e.e164=t=>e.check(_e164(ZodE164,t)),e.datetime=t=>e.check(datetime(t)),e.date=t=>e.check(date(t)),e.time=t=>e.check(time(t)),e.duration=t=>e.check(duration(t))});function string(e){return _string(ZodString,e)}var ZodStringFormat=$constructor(`ZodStringFormat`,(e,t)=>{$ZodStringFormat.init(e,t),_ZodString.init(e,t)}),ZodEmail=$constructor(`ZodEmail`,(e,t)=>{$ZodEmail.init(e,t),ZodStringFormat.init(e,t)}),ZodGUID=$constructor(`ZodGUID`,(e,t)=>{$ZodGUID.init(e,t),ZodStringFormat.init(e,t)}),ZodUUID=$constructor(`ZodUUID`,(e,t)=>{$ZodUUID.init(e,t),ZodStringFormat.init(e,t)}),ZodURL=$constructor(`ZodURL`,(e,t)=>{$ZodURL.init(e,t),ZodStringFormat.init(e,t)}),ZodEmoji=$constructor(`ZodEmoji`,(e,t)=>{$ZodEmoji.init(e,t),ZodStringFormat.init(e,t)}),ZodNanoID=$constructor(`ZodNanoID`,(e,t)=>{$ZodNanoID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID=$constructor(`ZodCUID`,(e,t)=>{$ZodCUID.init(e,t),ZodStringFormat.init(e,t)}),ZodCUID2=$constructor(`ZodCUID2`,(e,t)=>{$ZodCUID2.init(e,t),ZodStringFormat.init(e,t)}),ZodULID=$constructor(`ZodULID`,(e,t)=>{$ZodULID.init(e,t),ZodStringFormat.init(e,t)}),ZodXID=$constructor(`ZodXID`,(e,t)=>{$ZodXID.init(e,t),ZodStringFormat.init(e,t)}),ZodKSUID=$constructor(`ZodKSUID`,(e,t)=>{$ZodKSUID.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv4=$constructor(`ZodIPv4`,(e,t)=>{$ZodIPv4.init(e,t),ZodStringFormat.init(e,t)}),ZodIPv6=$constructor(`ZodIPv6`,(e,t)=>{$ZodIPv6.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv4=$constructor(`ZodCIDRv4`,(e,t)=>{$ZodCIDRv4.init(e,t),ZodStringFormat.init(e,t)}),ZodCIDRv6=$constructor(`ZodCIDRv6`,(e,t)=>{$ZodCIDRv6.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64=$constructor(`ZodBase64`,(e,t)=>{$ZodBase64.init(e,t),ZodStringFormat.init(e,t)}),ZodBase64URL=$constructor(`ZodBase64URL`,(e,t)=>{$ZodBase64URL.init(e,t),ZodStringFormat.init(e,t)}),ZodE164=$constructor(`ZodE164`,(e,t)=>{$ZodE164.init(e,t),ZodStringFormat.init(e,t)}),ZodJWT=$constructor(`ZodJWT`,(e,t)=>{$ZodJWT.init(e,t),ZodStringFormat.init(e,t)}),ZodNumber=$constructor(`ZodNumber`,(e,t)=>{$ZodNumber.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>numberProcessor(e,t,n,r),_installLazyMethods(e,`ZodNumber`,{gt(e,t){return this.check(_gt(e,t))},gte(e,t){return this.check(_gte(e,t))},min(e,t){return this.check(_gte(e,t))},lt(e,t){return this.check(_lt(e,t))},lte(e,t){return this.check(_lte(e,t))},max(e,t){return this.check(_lte(e,t))},int(e){return this.check(int(e))},safe(e){return this.check(int(e))},positive(e){return this.check(_gt(0,e))},nonnegative(e){return this.check(_gte(0,e))},negative(e){return this.check(_lt(0,e))},nonpositive(e){return this.check(_lte(0,e))},multipleOf(e,t){return this.check(_multipleOf(e,t))},step(e,t){return this.check(_multipleOf(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function number(e){return _number(ZodNumber,e)}var ZodNumberFormat=$constructor(`ZodNumberFormat`,(e,t)=>{$ZodNumberFormat.init(e,t),ZodNumber.init(e,t)});function int(e){return _int(ZodNumberFormat,e)}var ZodBoolean=$constructor(`ZodBoolean`,(e,t)=>{$ZodBoolean.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>booleanProcessor(e,t,n,r)});function boolean(e){return _boolean(ZodBoolean,e)}var ZodUnknown=$constructor(`ZodUnknown`,(e,t)=>{$ZodUnknown.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor(`ZodNever`,(e,t)=>{$ZodNever.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>neverProcessor(e,t,n,r)});function never(e){return _never(ZodNever,e)}var ZodArray=$constructor(`ZodArray`,(e,t)=>{$ZodArray.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>arrayProcessor(e,t,n,r),e.element=t.element,_installLazyMethods(e,`ZodArray`,{min(e,t){return this.check(_minLength(e,t))},nonempty(e){return this.check(_minLength(1,e))},max(e,t){return this.check(_maxLength(e,t))},length(e,t){return this.check(_length(e,t))},unwrap(){return this.element}})});function array(e,t){return _array(ZodArray,e,t)}var ZodObject=$constructor(`ZodObject`,(e,t)=>{$ZodObjectJIT.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>objectProcessor(e,t,n,r),defineLazy(e,`shape`,()=>t.shape),_installLazyMethods(e,`ZodObject`,{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:unknown()})},loose(){return this.clone({...this._zod.def,catchall:unknown()})},strict(){return this.clone({...this._zod.def,catchall:never()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return extend(this,e)},safeExtend(e){return safeExtend(this,e)},merge(e){return merge(this,e)},pick(e){return pick(this,e)},omit(e){return omit(this,e)},partial(...e){return partial(ZodOptional,this,e[0])},required(...e){return required(ZodNonOptional,this,e[0])}})});function object(e,t){return new ZodObject({type:`object`,shape:e??{},...normalizeParams(t)})}var ZodUnion=$constructor(`ZodUnion`,(e,t)=>{$ZodUnion.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>unionProcessor(e,t,n,r),e.options=t.options});function union(e,t){return new ZodUnion({type:`union`,options:e,...normalizeParams(t)})}var ZodIntersection=$constructor(`ZodIntersection`,(e,t)=>{$ZodIntersection.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>intersectionProcessor(e,t,n,r)});function intersection(e,t){return new ZodIntersection({type:`intersection`,left:e,right:t})}var ZodEnum=$constructor(`ZodEnum`,(e,t)=>{$ZodEnum.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>enumProcessor(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new ZodEnum({...t,checks:[],...normalizeParams(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new ZodEnum({...t,checks:[],...normalizeParams(r),entries:i})}});function _enum(e,t){return new ZodEnum({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...normalizeParams(t)})}var ZodTransform=$constructor(`ZodTransform`,(e,t)=>{$ZodTransform.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>transformProcessor(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(issue(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(issue(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function transform(e){return new ZodTransform({type:`transform`,transform:e})}var ZodOptional=$constructor(`ZodOptional`,(e,t)=>{$ZodOptional.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new ZodOptional({type:`optional`,innerType:e})}var ZodExactOptional=$constructor(`ZodExactOptional`,(e,t)=>{$ZodExactOptional.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function exactOptional(e){return new ZodExactOptional({type:`optional`,innerType:e})}var ZodNullable=$constructor(`ZodNullable`,(e,t)=>{$ZodNullable.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nullableProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new ZodNullable({type:`nullable`,innerType:e})}var ZodDefault=$constructor(`ZodDefault`,(e,t)=>{$ZodDefault.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>defaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new ZodDefault({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}var ZodPrefault=$constructor(`ZodPrefault`,(e,t)=>{$ZodPrefault.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>prefaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new ZodPrefault({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}var ZodNonOptional=$constructor(`ZodNonOptional`,(e,t)=>{$ZodNonOptional.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nonoptionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new ZodNonOptional({type:`nonoptional`,innerType:e,...normalizeParams(t)})}var ZodCatch=$constructor(`ZodCatch`,(e,t)=>{$ZodCatch.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>catchProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new ZodCatch({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var ZodPipe=$constructor(`ZodPipe`,(e,t)=>{$ZodPipe.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pipeProcessor(e,t,n,r),e.in=t.in,e.out=t.out});function pipe(e,t){return new ZodPipe({type:`pipe`,in:e,out:t})}var ZodReadonly=$constructor(`ZodReadonly`,(e,t)=>{$ZodReadonly.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>readonlyProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new ZodReadonly({type:`readonly`,innerType:e})}var ZodCustom=$constructor(`ZodCustom`,(e,t)=>{$ZodCustom.init(e,t),ZodType.init(e,t),e._zod.processJSONSchema=(t,n,r)=>customProcessor(e,t,n,r)});function refine(e,t={}){return _refine(ZodCustom,e,t)}function superRefine(e,t){return _superRefine(e,t)}var InvokeErrorTypes={NETWORK_ERROR:`network_error`,RATE_LIMIT:`rate_limit`,SERVER_ERROR:`server_error`,NO_TOOL_CALL:`no_tool_call`,INVALID_TOOL_ARGS:`invalid_tool_args`,TOOL_EXECUTION_ERROR:`tool_execution_error`,INVALID_RESPONSE:`invalid_response`,INVALID_SCHEMA:`invalid_schema`,UNKNOWN:`unknown`,CONFIG_ERROR:`config_error`,AUTH_ERROR:`auth_error`,CONTEXT_LENGTH:`context_length`,CONTENT_FILTER:`content_filter`},RETRYABLE_TYPES=[InvokeErrorTypes.NETWORK_ERROR,InvokeErrorTypes.RATE_LIMIT,InvokeErrorTypes.SERVER_ERROR,InvokeErrorTypes.NO_TOOL_CALL,InvokeErrorTypes.INVALID_TOOL_ARGS,InvokeErrorTypes.TOOL_EXECUTION_ERROR,InvokeErrorTypes.INVALID_RESPONSE,InvokeErrorTypes.INVALID_SCHEMA,InvokeErrorTypes.UNKNOWN],InvokeError=class extends Error{type;retryable;statusCode;rawError;rawResponse;constructor(e,t,n,r){super(t),this.name=`InvokeError`,this.type=e,this.retryable=RETRYABLE_TYPES.includes(e),this.rawError=n,this.rawResponse=r}},ANSI_BACKGROUND_OFFSET=10,wrapAnsi16=(e=0)=>t=>`\u001B[${t+e}m`,wrapAnsi256=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,wrapAnsi16m=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,styles$1={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},modifierNames=Object.keys(styles$1.modifier),foregroundColorNames=Object.keys(styles$1.color),backgroundColorNames=Object.keys(styles$1.bgColor),colorNames=[...foregroundColorNames,...backgroundColorNames];function assembleStyles(){let e=new Map;for(let[t,n]of Object.entries(styles$1)){for(let[t,r]of Object.entries(n))styles$1[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=styles$1[t],e.set(r[0],r[1]);Object.defineProperty(styles$1,t,{value:n,enumerable:!1})}return Object.defineProperty(styles$1,"codes",{value:e,enumerable:!1}),styles$1.color.close=`\x1B[39m`,styles$1.bgColor.close=`\x1B[49m`,styles$1.color.ansi=wrapAnsi16(),styles$1.color.ansi256=wrapAnsi256(),styles$1.color.ansi16m=wrapAnsi16m(),styles$1.bgColor.ansi=wrapAnsi16(ANSI_BACKGROUND_OFFSET),styles$1.bgColor.ansi256=wrapAnsi256(ANSI_BACKGROUND_OFFSET),styles$1.bgColor.ansi16m=wrapAnsi16m(ANSI_BACKGROUND_OFFSET),Object.defineProperties(styles$1,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>styles$1.rgbToAnsi256(...styles$1.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(e)),enumerable:!1}}),styles$1}var ansiStyles=assembleStyles(),level=(()=>{if(!(`navigator`in globalThis))return 0;if(globalThis.navigator.userAgentData){let e=navigator.userAgentData.brands.find(({brand:e})=>e===`Chromium`);if(e&&e.version>93)return 3}return+!!/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)})(),colorSupport=level!==0&&{level,hasBasic:!0,has256:level>=2,has16m:level>=3},supportsColor={stdout:colorSupport,stderr:colorSupport};function stringReplaceAll(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.slice(a),o}function stringEncaseCRLFWithFirstIndex(e,t,n,r){let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.slice(i,o?r-1:r)+t+(o?`\r
|
|
67
67
|
`:`
|
|
68
68
|
`)+n,i=r+1,r=e.indexOf(`
|
|
69
|
-
`,i)}while(r!==-1);return a+=e.slice(i),a}var{stdout:stdoutColor,stderr:stderrColor}=supportsColor,GENERATOR=Symbol(`GENERATOR`),STYLER=Symbol(`STYLER`),IS_EMPTY=Symbol(`IS_EMPTY`),levelMapping=[`ansi`,`ansi`,`ansi256`,`ansi16m`],styles=Object.create(null),applyOptions=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let n=stdoutColor?stdoutColor.level:0;e.level=t.level===void 0?n:t.level},chalkFactory=e=>{let t=(...e)=>e.join(` `);return applyOptions(t,e),Object.setPrototypeOf(t,createChalk.prototype),t};function createChalk(e){return chalkFactory(e)}Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(let[e,t]of Object.entries(ansiStyles))styles[e]={get(){let n=createBuilder(this,createStyler(t.open,t.close,this[STYLER]),this[IS_EMPTY]);return Object.defineProperty(this,e,{value:n}),n}};styles.visible={get(){let e=createBuilder(this,this[STYLER],!0);return Object.defineProperty(this
|
|
70
|
-
`);return a!==-1&&(t=stringEncaseCRLFWithFirstIndex(t,i,r,a)),r+t+i};Object.defineProperties(createChalk.prototype,styles);var chalk=createChalk(),chalkStderr=createChalk({level:stderrColor?stderrColor.level:0}),debug=console.debug.bind(console,chalk.gray(`[LLM]`));function zodToOpenAITool(e,t){return{type:`function`,function:{name:e,description:t.description,parameters:toJSONSchema(t.inputSchema,{target:`openapi-3.0`})}}}function modelPatch(e){let t=e.model||``;if(!t)return e;let n=normalizeModelName(t);return n.startsWith(`qwen`)&&(debug(`Applying Qwen patch: use higher temperature for auto fixing`),e.temperature=Math.max(e.temperature||0,1),e.enable_thinking=!1),n.startsWith(`claude`)&&(debug(`Applying Claude patch: disable thinking`),e.thinking={type:`disabled`},e.tool_choice===`required`?(debug(`Applying Claude patch: convert tool_choice "required" to { type: "any" }`),e.tool_choice={type:`any`}):e.tool_choice?.function?.name&&(debug(`Applying Claude patch: convert tool_choice format`),e.tool_choice={type:`tool`,name:e.tool_choice.function.name}),(n.startsWith(`claude-opus-4-7`)||n.startsWith(`claude-opus-47`))&&(debug(`Applying Claude-4.7 patch: remove temperature`),delete e.temperature)),n.startsWith(`grok`)&&(debug(`Applying Grok patch: removing tool_choice`),delete e.tool_choice,debug(`Applying Grok patch: disable reasoning and thinking`),e.thinking={type:`disabled`,effort:`minimal`},e.reasoning={enabled:!1,effort:`low`}),n.startsWith(`gpt`)&&(debug(`Applying GPT patch: set verbosity to low`),e.verbosity=`low`,n.startsWith(`gpt-52`)?(debug(`Applying GPT-52 patch: disable reasoning`),e.reasoning_effort=`none`):n.startsWith(`gpt-51`)?(debug(`Applying GPT-51 patch: disable reasoning`),e.reasoning_effort=`none`):n.startsWith(`gpt-54`)?(debug(`Applying GPT-5.4 patch: remove reasoning_effort`),delete e.reasoning_effort):n.startsWith(`gpt-55`)?(debug(`Applying GPT-5.4 patch: remove reasoning_effort and temperature`),delete e.reasoning_effort,delete e.temperature):n.startsWith(`gpt-5-mini`)?(debug(`Applying GPT-5-mini patch: set reasoning effort to low, temperature to 1`),e.reasoning_effort=`low`,e.temperature=1):n.startsWith(`gpt-5`)&&(debug(`Applying GPT-5 patch: set reasoning effort to low`),e.reasoning_effort=`low`)),n.startsWith(`gemini`)&&(debug(`Applying Gemini patch: set reasoning effort to minimal`),e.reasoning_effort=`minimal`),n.startsWith(`deepseek`)&&(debug(`Applying DeepSeek patch: remove tool_choice`),delete e.tool_choice),n.startsWith(`minimax`)&&(debug(`Applying MiniMax patch: clamp temperature to (0, 1]`),e.temperature=Math.max(e.temperature||0,.01),e.temperature>1&&(e.temperature=1),delete e.parallel_tool_calls),e}function normalizeModelName(e){let t=e.toLowerCase();return t.includes(`/`)&&(t=t.split(`/`)[1]),t=t.replace(/_/g,``),t=t.replace(/\./g,``),t}var OpenAIClient=class{config;fetch;constructor(e){this.config=e,this.fetch=e.customFetch}async invoke(e,t,n,r){let i=Object.entries(t).map(([e,t])=>zodToOpenAITool(e,t)),a=`required`;r?.toolChoiceName&&!this.config.disableNamedToolChoice&&(a={type:`function`,function:{name:r.toolChoiceName}});let o={model:this.config.model,temperature:this.config.temperature,messages:e,tools:i,parallel_tool_calls:!1,tool_choice:a};modelPatch(o);let s;try{s=this.config.transformRequestBody(o)}catch(e){throw new InvokeError(InvokeErrorTypes.CONFIG_ERROR,`transformRequestBody failed: ${e.message}`,e)}let c=s??o,l;try{l=await this.fetch(`${this.config.baseURL}/chat/completions`,{method:`POST`,headers:{"Content-Type":`application/json`,...this.config.apiKey&&{Authorization:`Bearer ${this.config.apiKey}`}},body:JSON.stringify(c),signal:n})}catch(e){
|
|
69
|
+
`,i)}while(r!==-1);return a+=e.slice(i),a}var{stdout:stdoutColor,stderr:stderrColor}=supportsColor,GENERATOR=Symbol(`GENERATOR`),STYLER=Symbol(`STYLER`),IS_EMPTY=Symbol(`IS_EMPTY`),levelMapping=[`ansi`,`ansi`,`ansi256`,`ansi16m`],styles=Object.create(null),applyOptions=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let n=stdoutColor?stdoutColor.level:0;e.level=t.level===void 0?n:t.level},chalkFactory=e=>{let t=(...e)=>e.join(` `);return applyOptions(t,e),Object.setPrototypeOf(t,createChalk.prototype),t};function createChalk(e){return chalkFactory(e)}Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(let[e,t]of Object.entries(ansiStyles))styles[e]={get(){let n=createBuilder(this,createStyler(t.open,t.close,this[STYLER]),this[IS_EMPTY]);return Object.defineProperty(this,e,{value:n}),n}};styles.visible={get(){let e=createBuilder(this,this[STYLER],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var getModelAnsi=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?ansiStyles[n].ansi16m(...r):t===`ansi256`?ansiStyles[n].ansi256(ansiStyles.rgbToAnsi256(...r)):ansiStyles[n].ansi(ansiStyles.rgbToAnsi(...r)):e===`hex`?getModelAnsi(`rgb`,t,n,...ansiStyles.hexToRgb(...r)):ansiStyles[n][e](...r);for(let e of[`rgb`,`hex`,`ansi256`]){styles[e]={get(){let{level:t}=this;return function(...n){let r=createStyler(getModelAnsi(e,levelMapping[t],`color`,...n),ansiStyles.color.close,this[STYLER]);return createBuilder(this,r,this[IS_EMPTY])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);styles[t]={get(){let{level:t}=this;return function(...n){let r=createStyler(getModelAnsi(e,levelMapping[t],`bgColor`,...n),ansiStyles.bgColor.close,this[STYLER]);return createBuilder(this,r,this[IS_EMPTY])}}}}var proto=Object.defineProperties(()=>{},{...styles,level:{enumerable:!0,get(){return this[GENERATOR].level},set(e){this[GENERATOR].level=e}}}),createStyler=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},createBuilder=(e,t,n)=>{let r=(...e)=>applyStyle(r,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(r,proto),r[GENERATOR]=e,r[STYLER]=t,r[IS_EMPTY]=n,r},applyStyle=(e,t)=>{if(e.level<=0||!t)return e[IS_EMPTY]?``:t;let n=e[STYLER];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes(`\x1B`))for(;n!==void 0;)t=stringReplaceAll(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
|
|
70
|
+
`);return a!==-1&&(t=stringEncaseCRLFWithFirstIndex(t,i,r,a)),r+t+i};Object.defineProperties(createChalk.prototype,styles);var chalk=createChalk(),chalkStderr=createChalk({level:stderrColor?stderrColor.level:0}),debug=console.debug.bind(console,chalk.gray(`[LLM]`));function zodToOpenAITool(e,t){return{type:`function`,function:{name:e,description:t.description,parameters:toJSONSchema(t.inputSchema,{target:`openapi-3.0`})}}}function modelPatch(e){let t=e.model||``;if(!t)return e;let n=normalizeModelName(t);return n.startsWith(`qwen`)&&(debug(`Applying Qwen patch: use higher temperature for auto fixing`),e.temperature=Math.max(e.temperature||0,1),e.enable_thinking=!1),n.startsWith(`claude`)&&(debug(`Applying Claude patch: disable thinking`),e.thinking={type:`disabled`},e.tool_choice===`required`?(debug(`Applying Claude patch: convert tool_choice "required" to { type: "any" }`),e.tool_choice={type:`any`}):e.tool_choice?.function?.name&&(debug(`Applying Claude patch: convert tool_choice format`),e.tool_choice={type:`tool`,name:e.tool_choice.function.name}),(n.startsWith(`claude-opus-4-7`)||n.startsWith(`claude-opus-47`)||n.startsWith(`claude-opus-4-8`)||n.startsWith(`claude-opus-48`))&&(debug(`Applying Claude-4.7/4.8 patch: remove temperature`),delete e.temperature)),n.startsWith(`grok`)&&(debug(`Applying Grok patch: removing tool_choice`),delete e.tool_choice,debug(`Applying Grok patch: disable reasoning and thinking`),e.thinking={type:`disabled`,effort:`minimal`},e.reasoning={enabled:!1,effort:`low`}),n.startsWith(`gpt`)&&(debug(`Applying GPT patch: set verbosity to low`),e.verbosity=`low`,n.startsWith(`gpt-52`)?(debug(`Applying GPT-52 patch: disable reasoning`),e.reasoning_effort=`none`):n.startsWith(`gpt-51`)?(debug(`Applying GPT-51 patch: disable reasoning`),e.reasoning_effort=`none`):n.startsWith(`gpt-54`)?(debug(`Applying GPT-5.4 patch: remove reasoning_effort`),delete e.reasoning_effort):n.startsWith(`gpt-55`)?(debug(`Applying GPT-5.4 patch: remove reasoning_effort and temperature`),delete e.reasoning_effort,delete e.temperature):n.startsWith(`gpt-5-mini`)?(debug(`Applying GPT-5-mini patch: set reasoning effort to low, temperature to 1`),e.reasoning_effort=`low`,e.temperature=1):n.startsWith(`gpt-5`)&&(debug(`Applying GPT-5 patch: set reasoning effort to low`),e.reasoning_effort=`low`)),n.startsWith(`gemini`)&&(debug(`Applying Gemini patch: set reasoning effort to minimal`),e.reasoning_effort=`minimal`),n.startsWith(`deepseek`)&&(debug(`Applying DeepSeek patch: remove tool_choice`),delete e.tool_choice),n.startsWith(`minimax`)&&(debug(`Applying MiniMax patch: clamp temperature to (0, 1]`),e.temperature=Math.max(e.temperature||0,.01),e.temperature>1&&(e.temperature=1),delete e.parallel_tool_calls),e}function normalizeModelName(e){let t=e.toLowerCase();return t.includes(`/`)&&(t=t.split(`/`)[1]),t=t.replace(/_/g,``),t=t.replace(/\./g,``),t}var OpenAIClient=class{config;fetch;constructor(e){this.config=e,this.fetch=e.customFetch}async invoke(e,t,n,r){n?.throwIfAborted();let i=Object.entries(t).map(([e,t])=>zodToOpenAITool(e,t)),a=`required`;r?.toolChoiceName&&!this.config.disableNamedToolChoice&&(a={type:`function`,function:{name:r.toolChoiceName}});let o={model:this.config.model,temperature:this.config.temperature,messages:e,tools:i,parallel_tool_calls:!1,tool_choice:a};modelPatch(o);let s;try{s=this.config.transformRequestBody(o)}catch(e){throw new InvokeError(InvokeErrorTypes.CONFIG_ERROR,`transformRequestBody failed: ${e.message}`,e)}let c=s??o,l;try{l=await this.fetch(`${this.config.baseURL}/chat/completions`,{method:`POST`,headers:{"Content-Type":`application/json`,...this.config.apiKey&&{Authorization:`Bearer ${this.config.apiKey}`}},body:JSON.stringify(c),signal:n})}catch(e){throw e?.name===`AbortError`?e:(console.error(e),new InvokeError(InvokeErrorTypes.NETWORK_ERROR,`Network request failed`,e))}if(!l.ok){let e;try{e=await l.json()}catch(e){if(e?.name===`AbortError`)throw e}let t=e?.error?.message||l.statusText;throw l.status===401||l.status===403?new InvokeError(InvokeErrorTypes.AUTH_ERROR,`Authentication failed: ${t}`,e):l.status===429?new InvokeError(InvokeErrorTypes.RATE_LIMIT,`Rate limit exceeded: ${t}`,e):l.status>=500?new InvokeError(InvokeErrorTypes.SERVER_ERROR,`Server error: ${t}`,e):new InvokeError(InvokeErrorTypes.UNKNOWN,`HTTP ${l.status}: ${t}`,e)}let u;try{u=await l.json()}catch(e){throw e?.name===`AbortError`?e:new InvokeError(InvokeErrorTypes.INVALID_RESPONSE,`Response body is not valid JSON`,e)}let d=u.choices?.[0];if(!d)throw new InvokeError(InvokeErrorTypes.INVALID_SCHEMA,`No choices in response`,u);switch(d.finish_reason){case`tool_calls`:case`function_call`:case`stop`:break;case`length`:throw new InvokeError(InvokeErrorTypes.CONTEXT_LENGTH,`Response truncated: max tokens reached`,void 0,u);case`content_filter`:throw new InvokeError(InvokeErrorTypes.CONTENT_FILTER,`Content filtered by safety system`,void 0,u);default:throw new InvokeError(InvokeErrorTypes.INVALID_SCHEMA,`Unexpected finish_reason: ${d.finish_reason}`,void 0,u)}let f=(r?.normalizeResponse?r.normalizeResponse(u):u).choices?.[0],p=f?.message?.tool_calls?.[0]?.function?.name;if(!p)throw new InvokeError(InvokeErrorTypes.NO_TOOL_CALL,`No tool call found in response`,void 0,u);let m=t[p];if(!m)throw new InvokeError(InvokeErrorTypes.UNKNOWN,`Tool "${p}" not found in tools`,void 0,u);let h=f.message?.tool_calls?.[0]?.function?.arguments;if(!h)throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`No tool call arguments found`,void 0,u);let g;try{g=JSON.parse(h)}catch(e){throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Failed to parse tool arguments as JSON`,e,u)}let _=m.inputSchema.safeParse(g);if(!_.success)throw console.error(prettifyError(_.error)),new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Tool arguments validation failed`,_.error,u);let v=_.data,y;try{y=await m.execute(v)}catch(e){throw e?.name===`AbortError`?e:new InvokeError(InvokeErrorTypes.TOOL_EXECUTION_ERROR,`Tool execution failed: ${e?.message}`,e,u)}return{toolCall:{name:p,args:v},toolResult:y,usage:{promptTokens:u.usage?.prompt_tokens??0,completionTokens:u.usage?.completion_tokens??0,totalTokens:u.usage?.total_tokens??0,cachedTokens:u.usage?.prompt_tokens_details?.cached_tokens,reasoningTokens:u.usage?.completion_tokens_details?.reasoning_tokens},rawResponse:u,rawRequest:c}}},DEFAULT_TEMPERATURE=.7;function parseLLMConfig(e){if(!e.baseURL||!e.model)throw Error(`[PageAgent] LLM configuration required. Please provide: baseURL, model. See: https://alibaba.github.io/page-agent/docs/features/models`);return{baseURL:e.baseURL,model:e.model,apiKey:e.apiKey||``,temperature:e.temperature??.7,maxRetries:e.maxRetries??2,transformRequestBody:e.transformRequestBody??(e=>e),disableNamedToolChoice:e.disableNamedToolChoice??!1,customFetch:(e.customFetch??fetch).bind(globalThis)}}var LLM=class extends EventTarget{config;client;constructor(e){super(),this.config=parseLLMConfig(e),this.client=new OpenAIClient(this.config)}async invoke(e,t,n,r){return await withRetry(async()=>this.client.invoke(e,t,n,r),{maxRetries:this.config.maxRetries,onRetry:(e,t)=>{this.dispatchEvent(new CustomEvent(`retry`,{detail:{attempt:e,maxAttempts:this.config.maxRetries,lastError:t}}))}})}};async function withRetry(e,t){let n=0;for(;;)try{return await e()}catch(e){if(e?.name===`AbortError`||e instanceof InvokeError&&!e.retryable||(n++,n>t.maxRetries))throw e;console.debug(`[LLM] retryable failure, will retry:`,e),t.onRetry(n,e),await new Promise(e=>setTimeout(e,100))}}var system_prompt_default=`You are an AI agent designed to operate in an iterative loop to automate browser tasks. Your ultimate goal is accomplishing the task provided in <user_request>.
|
|
71
71
|
|
|
72
72
|
<intro>
|
|
73
73
|
You excel at following tasks:
|
|
@@ -139,7 +139,6 @@ Strictly follow these rules while using the browser and navigating the web:
|
|
|
139
139
|
- You can scroll by a specific number of pages using the num_pages parameter (e.g., 0.5 for half page, 2.0 for two pages).
|
|
140
140
|
- All the elements that are scrollable are marked with \`data-scrollable\` attribute. Including the scrollable distance in every directions. You can scroll *the element* in case some area are overflowed.
|
|
141
141
|
- If a captcha appears, tell user you can not solve captcha. Finish the task and ask user to solve it.
|
|
142
|
-
- If expected elements are missing, try scrolling, or navigating back.
|
|
143
142
|
- If the page is not fully loaded, use the \`wait\` action.
|
|
144
143
|
- Do not repeat one action for more than 3 times unless some conditions changed.
|
|
145
144
|
- If you fill an input field and your action sequence is interrupted, most often something changed e.g. suggestions popped up under the field.
|
|
@@ -220,11 +219,11 @@ Here are examples of good output patterns. Use them as reference but never copy
|
|
|
220
219
|
}
|
|
221
220
|
}
|
|
222
221
|
</output>
|
|
223
|
-
`,log=console.log.bind(console,chalk.yellow(`[autoFixer]`));function normalizeResponse(e,t){let n,r=e.choices?.[0];if(!r)throw Error(`No choices in response`);let i=r.message;if(!i)throw Error(`No message in choice`);let a=i.tool_calls?.[0];if(a?.function?.arguments)n=safeJsonParse(a.function.arguments),a.function.name&&a.function.name!==`AgentOutput`&&(log(`#1: fixing tool_call`),n={action:safeJsonParse(n)});else if(i.content){let e=retrieveJsonFromString(i.content.trim());if(e)n=safeJsonParse(e),n?.name===`AgentOutput`&&(log(`#2: fixing tool_call`),n=safeJsonParse(n.arguments)),n?.type===`function`&&(log(`#3: fixing tool_call`),n=safeJsonParse(n.function.arguments)),!n?.action&&!n?.evaluation_previous_goal&&!n?.memory&&!n?.next_goal&&!n?.thinking&&(log(`#4: fixing tool_call`),n={action:safeJsonParse(n)});else throw Error(`No tool_call and the message content does not contain valid JSON`)}else throw Error(`No tool_call nor message content is present`);return n=safeJsonParse(n),n.action&&=safeJsonParse(n.action),n.action&&t&&(n.action=validateAction(n.action,t)),n.action||(log(`#5: fixing tool_call`),n.action={wait:{seconds:1}}),{...e,choices:[{...r,message:{...i,tool_calls:[{...a||{},function:{...a?.function||{},name:`AgentOutput`,arguments:JSON.stringify(n)}}]}}]}}function validateAction(e,t){if(typeof e!=`object`||!e)return e;let n=Object.keys(e)[0];if(!n)return e;let r=t.get(n);if(!r){let e=Array.from(t.keys()).join(`, `);throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Unknown action "${n}". Available: ${e}`)}let i=e[n],a=r.inputSchema;if(a instanceof ZodObject&&i!==null&&typeof i!=`object`){let e=Object.keys(a.shape).find(e=>!a.shape[e].safeParse(void 0).success);e&&(log(`coercing primitive action input for "${n}"`),i={[e]:i})}let o=a.safeParse(i);if(!o.success)throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Invalid input for action "${n}": ${prettifyError(o.error)}`);return{[n]:o.data}}function safeJsonParse(e){if(typeof e==`string`)try{return JSON.parse(e.trim())}catch{return e}return e}function retrieveJsonFromString(e){try{let t=/({[\s\S]*})/.exec(e)??[];return t.length===0?null:JSON.parse(t[0])}catch{return null}}async function waitFor$1(e){await new Promise(t=>setTimeout(t,e*1e3))}function truncate$1(e,t){return e.length>t?e.substring(0,t)+`...`:e}function randomID(e){let t=Math.random().toString(36).substring(2,11);if(!e)return t;let n=1e3,r=0;for(;e.includes(t);)if(t=Math.random().toString(36).substring(2,11),r++,r>1e3)throw Error(`randomID: too many tries`);return t}var _global=globalThis;_global.__PAGE_AGENT_IDS__||=[];var ids=_global.__PAGE_AGENT_IDS__;function uid(){let e=randomID(ids);return ids.push(e),e}var llmsTxtCache=new Map;async function fetchLlmsTxt(e){let t;try{t=new URL(e).origin}catch{return null}if(t===`null`)return null;if(llmsTxtCache.has(t))return llmsTxtCache.get(t);let n=`${t}/llms.txt`,r=null;try{console.log(chalk.gray(`[llms.txt] Fetching ${n}`));let e=await fetch(n,{signal:AbortSignal.timeout(3e3)});e.ok?(r=await e.text(),console.log(chalk.green(`[llms.txt] Found (${r.length} chars)`)),r.length>1e3&&(console.log(chalk.yellow(`[llms.txt] Truncating to 1000 chars`)),r=truncate$1(r,1e3))):console.debug(chalk.gray(`[llms.txt] ${e.status} for ${n}`))}catch(e){console.debug(chalk.gray(`[llms.txt] not found for ${n}`),e)}return llmsTxtCache.set(t,r),r}function assert(e,t,n){if(!e){let e=t??`Assertion failed`;throw n||console.error(chalk.red(`❌ assert: ${e}`)),Error(e)}}function tool(e){return e}var tools=new Map;tools.set(`done`,tool({description:`Complete task. Text is your final response to the user — keep it concise unless the user explicitly asks for detail.`,inputSchema:object({text:string(),success:boolean().default(!0)}),execute:async function(e){return Promise.resolve(`Task completed`)}})),tools.set(`wait`,tool({description:`Wait for x seconds. Can be used to wait until the page or data is fully loaded.`,inputSchema:object({seconds:number().min(1).max(10).default(1)}),execute:async function(e){let t=await this.pageController.getLastUpdateTime(),n=Math.max(0,e.seconds-(Date.now()-t)/1e3);return console.log(`actualWaitTime: ${n} seconds`),await waitFor$1(n),`✅ Waited for ${e.seconds} seconds.`}})),tools.set(`ask_user`,tool({description:`Ask the user a question and wait for their answer. Use this if you need more information or clarification.`,inputSchema:object({question:string()}),execute:async function(e){if(!this.onAskUser)throw Error(`ask_user tool requires onAskUser callback to be set`);return`User answered: ${await this.onAskUser(e.question)}`}})),tools.set(`click_element_by_index`,tool({description:`Click element by index`,inputSchema:object({index:int().min(0)}),execute:async function(e){return(await this.pageController.clickElement(e.index)).message}})),tools.set(`input_text`,tool({description:`Click and type text into an interactive input element`,inputSchema:object({index:int().min(0),text:string()}),execute:async function(e){return(await this.pageController.inputText(e.index,e.text)).message}})),tools.set(`select_dropdown_option`,tool({description:`Select dropdown option for interactive element index by the text of the option you want to select`,inputSchema:object({index:int().min(0),text:string()}),execute:async function(e){return(await this.pageController.selectOption(e.index,e.text)).message}})),tools.set(`scroll`,tool({description:`Scroll vertically. Without index: scrolls the document. With index: scrolls the container at that index (or its nearest scrollable ancestor). Use index of a data-scrollable element to scroll a specific area.`,inputSchema:object({down:boolean().default(!0),num_pages:number().min(0).max(10).optional().default(.1),pixels:number().int().min(0).optional(),index:number().int().min(0).optional()}),execute:async function(e){return(await this.pageController.scroll({...e,numPages:e.num_pages})).message}})),tools.set(`scroll_horizontally`,tool({description:`Scroll horizontally. Without index: scrolls the document. With index: scrolls the container at that index (or its nearest scrollable ancestor). Use index of a data-scrollable element to scroll a specific area.`,inputSchema:object({right:boolean().default(!0),pixels:number().int().min(0),index:number().int().min(0).optional()}),execute:async function(e){return(await this.pageController.scrollHorizontally(e)).message}})),tools.set(`execute_javascript`,tool({description:`Execute JavaScript code on the current page. Supports async/await syntax. Use with caution!`,inputSchema:object({script:string()}),execute:async function(e){return(await this.pageController.executeJavascript(e.script)).message}}));var PageAgentCore=class extends EventTarget{id=uid();config;tools;pageController;task=``;taskId=``;history=[];disposed=!1;onAskUser;#e=`idle`;#t;#n=new AbortController;#r=[];#i={totalWaitTime:0,lastURL:``,browserState:null};constructor(e){if(super(),this.config={...e,maxSteps:e.maxSteps??40},this.#t=new LLM(this.config),this.tools=new Map(tools),this.pageController=e.pageController,this.#t.addEventListener(`retry`,e=>{let{attempt:t,maxAttempts:n}=e.detail;this.#s({type:`retrying`,attempt:t,maxAttempts:n}),this.history.push({type:`retry`,message:`LLM retry attempt ${t} of ${n}`,attempt:t,maxAttempts:n}),this.#o()}),this.#t.addEventListener(`error`,e=>{let t=e.detail.error;if(t?.rawError?.name===`AbortError`)return;let n=String(t);this.#s({type:`error`,message:n}),this.history.push({type:`error`,message:n,rawResponse:t.rawResponse}),this.#o()}),this.config.customTools)for(let[e,t]of Object.entries(this.config.customTools)){if(t===null){this.tools.delete(e);continue}this.tools.set(e,t)}this.config.experimentalScriptExecutionTool||this.tools.delete(`execute_javascript`)}get status(){return this.#e}#a(){this.dispatchEvent(new Event(`statuschange`))}#o(){this.dispatchEvent(new Event(`historychange`))}#s(e){this.dispatchEvent(new CustomEvent(`activity`,{detail:e}))}#c(e){this.#e!==e&&(this.#e=e,this.#a())}pushObservation(e){this.#r.push(e)}stop(){this.pageController.cleanUpHighlights(),this.pageController.hideMask(),this.#n.abort()}async execute(e){if(this.disposed)throw Error(`PageAgent has been disposed. Create a new instance.`);if(!e)throw Error(`Task is required`);this.task=e,this.taskId=uid(),this.onAskUser||this.tools.delete(`ask_user`);let t=this.config.onBeforeStep,n=this.config.onAfterStep,r=this.config.onBeforeTask,i=this.config.onAfterTask;await r?.(this),await this.pageController.showMask(),this.#n&&=(this.#n.abort(),new AbortController),this.history=[],this.#c(`running`),this.#o(),this.#r=[],this.#i={totalWaitTime:0,lastURL:``,browserState:null};let a=0;for(;;){try{console.group(`step: ${a}`),await t?.(this,a),console.log(chalk.blue.bold(`👀 Observing...`)),this.#i.browserState=await this.pageController.getBrowserState(),await this.#f(a);let e=[{role:`system`,content:this.#u()},{role:`user`,content:await this.#p()}],r={AgentOutput:this.#l()};console.log(chalk.blue.bold(`🧠 Thinking...`)),this.#s({type:`thinking`});let o=await this.#t.invoke(e,r,this.#n.signal,{toolChoiceName:`AgentOutput`,normalizeResponse:e=>normalizeResponse(e,this.tools)}),s=o.toolResult,c=s.input,l=s.output,u={evaluation_previous_goal:c.evaluation_previous_goal,memory:c.memory,next_goal:c.next_goal},d=Object.keys(c.action)[0],f={name:d,input:c.action[d],output:l};if(this.history.push({type:`step`,stepIndex:a,reflection:u,action:f,usage:o.usage,rawResponse:o.rawResponse,rawRequest:o.rawRequest}),this.#o(),await n?.(this,this.history),console.groupEnd(),d===`done`){let e=f.input?.success??!1,t=f.input?.text||`no text provided`;console.log(chalk.green.bold(`Task completed`),e,t),this.#m(e);let n={success:e,data:t,history:this.history};return await i?.(this,n),n}}catch(e){console.groupEnd();let t=e?.rawError?.name===`AbortError`;console.error(`Task failed`,e);let n=t?`Task stopped`:String(e);this.#s({type:`error`,message:n}),this.history.push({type:`error`,message:n,rawResponse:e}),this.#o(),this.#m(!1);let r={success:!1,data:n,history:this.history};return await i?.(this,r),r}if(a++,a>this.config.maxSteps){let e=`Step count exceeded maximum limit`;this.history.push({type:`error`,message:e}),this.#o(),this.#m(!1);let t={success:!1,data:e,history:this.history};return await i?.(this,t),t}await waitFor$1(this.config.stepDelay??.4)}}#l(){let e=this.tools,t=union(Array.from(e.entries()).map(([e,t])=>object({[e]:t.inputSchema}).describe(t.description)));return{description:`You MUST call this tool every step!`,inputSchema:object({evaluation_previous_goal:string().optional(),memory:string().optional(),next_goal:string().optional(),action:t}),execute:async t=>{if(this.#n.signal.aborted)throw Error(`AbortError`);console.log(chalk.blue.bold(`MacroTool input`),t);let n=t.action,r=Object.keys(n)[0],i=n[r],a=[];t.evaluation_previous_goal&&a.push(`✅: ${t.evaluation_previous_goal}`),t.memory&&a.push(`💾: ${t.memory}`),t.next_goal&&a.push(`🎯: ${t.next_goal}`);let o=a.length>0?a.join(`
|
|
224
|
-
`):``;
|
|
222
|
+
`,log=console.log.bind(console,chalk.yellow(`[autoFixer]`));function normalizeResponse(e,t){let n,r=e.choices?.[0];if(!r)throw Error(`No choices in response`);let i=r.message;if(!i)throw Error(`No message in choice`);let a=i.tool_calls?.[0];if(a?.function?.arguments)n=safeJsonParse(a.function.arguments),a.function.name&&a.function.name!==`AgentOutput`&&(log(`#1: fixing tool_call`),n={action:safeJsonParse(n)});else if(i.content){let e=retrieveJsonFromString(i.content.trim());if(e)n=safeJsonParse(e),n?.name===`AgentOutput`&&(log(`#2: fixing tool_call`),n=safeJsonParse(n.arguments)),n?.type===`function`&&(log(`#3: fixing tool_call`),n=safeJsonParse(n.function.arguments)),!n?.action&&!n?.evaluation_previous_goal&&!n?.memory&&!n?.next_goal&&!n?.thinking&&(log(`#4: fixing tool_call`),n={action:safeJsonParse(n)});else throw Error(`No tool_call and the message content does not contain valid JSON`)}else throw Error(`No tool_call nor message content is present`);return n=safeJsonParse(n),n.action&&=safeJsonParse(n.action),n.action&&t&&(n.action=validateAction(n.action,t)),n.action||(log(`#5: fixing tool_call`),n.action={wait:{seconds:1}}),{...e,choices:[{...r,message:{...i,tool_calls:[{...a||{},function:{...a?.function||{},name:`AgentOutput`,arguments:JSON.stringify(n)}}]}}]}}function validateAction(e,t){if(typeof e!=`object`||!e)return e;let n=Object.keys(e)[0];if(!n)return e;let r=t.get(n);if(!r){let e=Array.from(t.keys()).join(`, `);throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Unknown action "${n}". Available: ${e}`)}let i=e[n],a=r.inputSchema;if(a instanceof ZodObject&&i!==null&&typeof i!=`object`){let e=Object.keys(a.shape).find(e=>!a.shape[e].safeParse(void 0).success);e&&(log(`coercing primitive action input for "${n}"`),i={[e]:i})}let o=a.safeParse(i);if(!o.success)throw new InvokeError(InvokeErrorTypes.INVALID_TOOL_ARGS,`Invalid input for action "${n}": ${prettifyError(o.error)}`);return{[n]:o.data}}function safeJsonParse(e){if(typeof e==`string`)try{return JSON.parse(e.trim())}catch{return e}return e}function retrieveJsonFromString(e){try{let t=/({[\s\S]*})/.exec(e)??[];return t.length===0?null:JSON.parse(t[0])}catch{return null}}async function waitFor$1(e,t){if(!t){await new Promise(t=>setTimeout(t,e*1e3));return}t.throwIfAborted(),await new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e*1e3),a=()=>{clearTimeout(i),r(t.reason)};t.addEventListener(`abort`,a,{once:!0})})}function truncate$1(e,t){return e.length>t?e.substring(0,t)+`...`:e}function randomID(e){let t=Math.random().toString(36).substring(2,11);if(!e)return t;let n=1e3,r=0;for(;e.includes(t);)if(t=Math.random().toString(36).substring(2,11),r++,r>1e3)throw Error(`randomID: too many tries`);return t}var _global=globalThis;_global.__PAGE_AGENT_IDS__||=[];var ids=_global.__PAGE_AGENT_IDS__;function uid(){let e=randomID(ids);return ids.push(e),e}var llmsTxtCache=new Map;async function fetchLlmsTxt(e){let t;try{t=new URL(e).origin}catch{return null}if(t===`null`)return null;if(llmsTxtCache.has(t))return llmsTxtCache.get(t);let n=`${t}/llms.txt`,r=null;try{console.log(chalk.gray(`[llms.txt] Fetching ${n}`));let e=await fetch(n,{signal:AbortSignal.timeout(3e3)});e.ok?(r=await e.text(),console.log(chalk.green(`[llms.txt] Found (${r.length} chars)`)),r.length>1e3&&(console.log(chalk.yellow(`[llms.txt] Truncating to 1000 chars`)),r=truncate$1(r,1e3))):console.debug(chalk.gray(`[llms.txt] ${e.status} for ${n}`))}catch(e){console.debug(chalk.gray(`[llms.txt] not found for ${n}`),e)}return llmsTxtCache.set(t,r),r}function assert(e,t,n){if(!e){let e=t??`Assertion failed`;throw n||console.error(chalk.red(`❌ assert: ${e}`)),Error(e)}}async function suppress(e){try{return await e()}catch(e){console.error(e);return}}function tool(e){return e}var tools=new Map;tools.set(`done`,tool({description:`Complete task. Text is your final response to the user — keep it concise unless the user explicitly asks for detail.`,inputSchema:object({text:string(),success:boolean().default(!0)}),execute:async function(e){return Promise.resolve(`Task completed`)}})),tools.set(`wait`,tool({description:`Wait for x seconds. Can be used to wait until the page or data is fully loaded.`,inputSchema:object({seconds:number().min(1).max(10).default(1)}),execute:async function(e,{signal:t}){let n=await this.pageController.getLastUpdateTime(),r=(Date.now()-n)/1e3,i=Math.max(0,e.seconds-r);return console.log(`actualWaitTime: ${i} seconds`),await waitFor$1(i,t),`✅ Waited for ${(r+i).toFixed(2)} seconds.`}})),tools.set(`ask_user`,tool({description:`Ask the user a question and wait for their answer. Use this if you need more information or clarification.`,inputSchema:object({question:string()}),execute:async function(e,{signal:t}){if(!this.onAskUser)throw Error(`ask_user tool requires onAskUser callback to be set`);return`User answered: ${await this.onAskUser(e.question,{signal:t})}`}})),tools.set(`click_element_by_index`,tool({description:`Click element by index`,inputSchema:object({index:int().min(0)}),execute:async function(e){return(await this.pageController.clickElement(e.index)).message}})),tools.set(`input_text`,tool({description:`Click and type text into an interactive input element`,inputSchema:object({index:int().min(0),text:string()}),execute:async function(e){return(await this.pageController.inputText(e.index,e.text)).message}})),tools.set(`select_dropdown_option`,tool({description:`Select dropdown option for interactive element index by the text of the option you want to select`,inputSchema:object({index:int().min(0),text:string()}),execute:async function(e){return(await this.pageController.selectOption(e.index,e.text)).message}})),tools.set(`scroll`,tool({description:`Scroll vertically. Without index: scrolls the document. With index: scrolls the container at that index (or its nearest scrollable ancestor). Use index of a data-scrollable element to scroll a specific area.`,inputSchema:object({down:boolean().default(!0),num_pages:number().min(0).max(10).optional().default(.1),pixels:number().int().min(0).optional(),index:number().int().min(0).optional()}),execute:async function(e){return(await this.pageController.scroll({...e,numPages:e.num_pages})).message}})),tools.set(`scroll_horizontally`,tool({description:`Scroll horizontally. Without index: scrolls the document. With index: scrolls the container at that index (or its nearest scrollable ancestor). Use index of a data-scrollable element to scroll a specific area.`,inputSchema:object({right:boolean().default(!0),pixels:number().int().min(0),index:number().int().min(0).optional()}),execute:async function(e){return(await this.pageController.scrollHorizontally(e)).message}})),tools.set(`execute_javascript`,tool({description:"Execute JavaScript code on the current page. Supports async/await syntax. Use with caution! An `AbortSignal` named `signal` is available in scope: long-running async code MUST honor it (e.g. `await fetch(url, { signal })`, or `signal.throwIfAborted()` in loops)",inputSchema:object({script:string()}),execute:async function(e,{signal:t}){let n=await this.pageController.executeJavascript(e.script,t);return t.throwIfAborted(),n.message}}));var PageAgentCore=class extends EventTarget{id=uid();config;tools;pageController;task=``;taskId=``;history=[];disposed=!1;onAskUser;#e=`idle`;#t;#n=new AbortController;#r=[];#i=Promise.resolve();#a=null;#o={totalWaitTime:0,lastURL:``,browserState:null};constructor(e){if(super(),this.config={...e,maxSteps:e.maxSteps??40},this.#t=new LLM(this.config),this.tools=new Map(tools),this.pageController=e.pageController,this.#t.addEventListener(`retry`,e=>{let{attempt:t,maxAttempts:n,lastError:r}=e.detail;this.#l({type:`retrying`,attempt:t,maxAttempts:n}),this.history.push({type:`error`,message:String(r),rawResponse:r.rawResponse}),this.history.push({type:`retry`,message:`LLM retry attempt ${t} of ${n}`,attempt:t,maxAttempts:n}),this.#c()}),this.config.customTools)for(let[e,t]of Object.entries(this.config.customTools)){if(t===null){this.tools.delete(e);continue}this.tools.set(e,t)}this.config.experimentalScriptExecutionTool||this.tools.delete(`execute_javascript`)}get status(){return this.#e}get lastResult(){return this.#a}#s(){this.dispatchEvent(new Event(`statuschange`))}#c(e){e&&this.history.push(e),this.dispatchEvent(new Event(`historychange`))}#l(e){this.dispatchEvent(new CustomEvent(`activity`,{detail:e}))}#u(e){this.#e!==e&&(this.#e=e,this.#s())}pushObservation(e){this.#r.push(e)}async stop(){this.#e===`running`&&(this.#n.abort(),await this.#i)}async execute(e){if(this.disposed)throw Error(`PageAgent has been disposed. Create a new instance.`);if(this.#e===`running`)throw Error(`A task is already running.`);if(!e)throw Error(`Task is required`);this.task=e,this.taskId=uid(),this.history=[],this.#r=[],this.#o={totalWaitTime:0,lastURL:``,browserState:null},this.#n=new AbortController;let t=this.#n.signal,n;this.#i=new Promise(e=>n=e),this.#u(`running`),this.#c(),this.onAskUser||this.tools.delete(`ask_user`);let r=this.config.onBeforeStep,i=this.config.onAfterStep,a=this.config.onBeforeTask,o=this.config.onAfterTask,s=this.config.stepDelay??.4,c=this.config.maxSteps,l=0,u,d=`error`;await suppress(()=>this.pageController.showMask());try{for(await a?.(this);;){await r?.(this,l);try{console.group(`step: ${l}`),l>0&&await waitFor$1(s,t),t.throwIfAborted(),console.log(chalk.blue.bold(`👀 Observing...`)),this.#o.browserState=await this.pageController.getBrowserState(),await this.#m(l);let e=[{role:`system`,content:this.#f()},{role:`user`,content:await this.#h()}],n={AgentOutput:this.#d()};console.log(chalk.blue.bold(`🧠 Thinking...`)),this.#l({type:`thinking`});let r=await this.#t.invoke(e,n,t,{toolChoiceName:`AgentOutput`,normalizeResponse:e=>normalizeResponse(e,this.tools)}),i=r.toolResult,a=i.input,o=i.output,c={evaluation_previous_goal:a.evaluation_previous_goal,memory:a.memory,next_goal:a.next_goal},f=Object.keys(a.action)[0],p={name:f,input:a.action[f],output:o};if(this.#c({type:`step`,stepIndex:l,reflection:c,action:p,usage:r.usage,rawResponse:r.rawResponse,rawRequest:r.rawRequest}),f===`done`){let e=p.input?.success??!1,t=p.input?.text||`no text provided`;console.log(chalk.green.bold(`Task completed`),e,t),u={success:e,data:t,history:this.history},this.#a=u,d=`completed`;break}}catch(e){let t=e?.name===`AbortError`;t||console.error(`Task failed`,e);let n=t?`Task aborted`:String(e);this.#l({type:`error`,message:n}),this.#c({type:`error`,message:n,rawResponse:e}),u={success:!1,data:n,history:this.history},this.#a=u,d=t?`stopped`:`error`;break}finally{console.groupEnd(),await i?.(this,this.history)}if(l++,l>c){let e=`Step count exceeded maximum limit`;console.error(e),this.#l({type:`error`,message:e}),this.#c({type:`error`,message:e}),u={success:!1,data:e,history:this.history},this.#a=u,d=`error`;break}}return await o?.(this,u),u}catch(e){throw this.#l({type:`error`,message:String(e)}),d=`error`,e}finally{await suppress(()=>this.pageController.cleanUpHighlights()),await suppress(()=>this.pageController.hideMask()),this.#n.abort(),n(),this.#u(d)}}#d(){let e=this.tools,t=union(Array.from(e.entries()).map(([e,t])=>object({[e]:t.inputSchema}).describe(t.description)));return{description:`You MUST call this tool every step!`,inputSchema:object({evaluation_previous_goal:string().optional(),memory:string().optional(),next_goal:string().optional(),action:t}),execute:async t=>{let n=this.#n.signal;n.throwIfAborted(),console.log(chalk.blue.bold(`MacroTool input`),t);let r=t.action,i=Object.keys(r)[0],a=r[i],o=[];t.evaluation_previous_goal&&o.push(`✅: ${t.evaluation_previous_goal}`),t.memory&&o.push(`💾: ${t.memory}`),t.next_goal&&o.push(`🎯: ${t.next_goal}`);let s=o.length>0?o.join(`
|
|
223
|
+
`):``;s&&console.log(s);let c=e.get(i);assert(c,`Tool ${i} not found`),console.log(chalk.blue.bold(`Executing tool: ${i}`),a),this.#l({type:`executing`,tool:i,input:a});let l=Date.now(),u=await c.execute.bind(this)(a,{signal:n});n.throwIfAborted();let d=Date.now()-l;return console.log(chalk.green.bold(`Tool (${i}) executed for ${d}ms`),u),this.#l({type:`executed`,tool:i,input:a,output:u,duration:d}),i===`wait`?this.#o.totalWaitTime+=a?.seconds||0:this.#o.totalWaitTime=0,{input:t,output:u}}}}#f(){if(this.config.customSystemPrompt)return this.config.customSystemPrompt;let e=this.config.language===`zh-CN`?`中文`:`English`;return system_prompt_default.replace(/Default working language: \*\*.*?\*\*/,`Default working language: **${e}**`)}async#p(){let{instructions:e,experimentalLlmsTxt:t}=this.config,n=e?.system?.trim(),r,i=this.#o.browserState?.url||``;if(e?.getPageInstructions&&i)try{r=e.getPageInstructions(i)?.trim()}catch(e){console.error(chalk.red(`[PageAgent] Failed to execute getPageInstructions callback:`),e)}let a=t&&i?await fetchLlmsTxt(i):void 0;if(!n&&!r&&!a)return``;let o=`<instructions>
|
|
225
224
|
`;return n&&(o+=`<system_instructions>\n${n}\n</system_instructions>\n`),r&&(o+=`<page_instructions>\n${r}\n</page_instructions>\n`),a&&(o+=`<llms_txt>\n${a}\n</llms_txt>\n`),o+=`</instructions>
|
|
226
225
|
|
|
227
|
-
`,o}async#
|
|
226
|
+
`,o}async#m(e){this.#o.totalWaitTime>=3&&this.pushObservation(`You have waited ${this.#o.totalWaitTime} seconds accumulatively. DO NOT wait any longer unless you have a good reason.`);let t=this.#o.browserState?.url||``;t!==this.#o.lastURL&&(this.pushObservation(`Page navigated to → ${t}`),this.#o.lastURL=t,await waitFor$1(.5));let n=this.config.maxSteps-e;if(n===5?this.pushObservation(`⚠️ Only ${n} steps remaining. Consider wrapping up or calling done with partial results.`):n===2&&this.pushObservation(`⚠️ Critical: Only ${n} steps left! You must finish the task or call done immediately.`),this.#r.length>0){for(let e of this.#r)this.history.push({type:`observation`,content:e}),console.log(chalk.cyan(`Observation:`),e);this.#r=[],this.#c()}}async#h(){let e=this.#o.browserState,t=``;t+=await this.#p();let n=this.history.filter(e=>e.type===`step`).length;t+=`<agent_state>
|
|
228
227
|
`,t+=`<user_request>
|
|
229
228
|
`,t+=`${this.task}\n`,t+=`</user_request>
|
|
230
229
|
`,t+=`<step_info>
|
|
@@ -242,7 +241,7 @@ Here are examples of good output patterns. Use them as reference but never copy
|
|
|
242
241
|
|
|
243
242
|
`,t+=`</browser_state>
|
|
244
243
|
|
|
245
|
-
`,t}#m(e=!0){this.pageController.cleanUpHighlights(),this.pageController.hideMask(),this.#c(e?`completed`:`error`),this.#n.abort()}dispose(){console.log(`Disposing PageAgent...`),this.disposed=!0,this.pageController.dispose(),this.#n.abort(),this.dispatchEvent(new Event(`dispose`)),this.config.onDispose?.(this)}};function isHTMLElement(e){return!!e&&e.nodeType===1}function isInputElement(e){return e?.nodeType===1&&e.tagName===`INPUT`}function isTextAreaElement(e){return e?.nodeType===1&&e.tagName===`TEXTAREA`}function isSelectElement(e){return e?.nodeType===1&&e.tagName===`SELECT`}function isAnchorElement(e){return e?.nodeType===1&&e.tagName===`A`}function getIframeOffset(e){let t=e.ownerDocument.defaultView?.frameElement;if(!t)return{x:0,y:0};let n=t.getBoundingClientRect();return{x:n.left,y:n.top}}function getNativeValueSetter(e){return Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),`value`).set}async function waitFor(e){await new Promise(t=>setTimeout(t,e*1e3))}async function movePointerToElement(e,t,n){let r=getIframeOffset(e);window.dispatchEvent(new CustomEvent(`PageAgent::MovePointerTo`,{detail:{x:t+r.x,y:n+r.y}})),await waitFor(.3)}async function clickPointer(){window.dispatchEvent(new CustomEvent(`PageAgent::ClickPointer`))}async function enablePassThrough(){window.dispatchEvent(new CustomEvent(`PageAgent::EnablePassThrough`))}async function disablePassThrough(){window.dispatchEvent(new CustomEvent(`PageAgent::DisablePassThrough`))}function getElementByIndex(e,t){let n=e.get(t);if(!n)throw Error(`No interactive element found at index ${t}`);let r=n.ref;if(!r)throw Error(`Element at index ${t} does not have a reference`);if(!isHTMLElement(r))throw Error(`Element at index ${t} is not an HTMLElement`);return r}var lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&=(lastClickedElement.dispatchEvent(new PointerEvent(`pointerout`,{bubbles:!0})),lastClickedElement.dispatchEvent(new PointerEvent(`pointerleave`,{bubbles:!1})),lastClickedElement.dispatchEvent(new MouseEvent(`mouseout`,{bubbles:!0})),lastClickedElement.dispatchEvent(new MouseEvent(`mouseleave`,{bubbles:!1})),lastClickedElement.blur(),null)}async function clickElement(e){blurLastClickedElement(),lastClickedElement=e,await scrollIntoViewIfNeeded(e);let t=e.ownerDocument.defaultView?.frameElement;t&&await scrollIntoViewIfNeeded(t);let n=e.getBoundingClientRect(),r=n.left+n.width/2,i=n.top+n.height/2;await movePointerToElement(e,r,i),await clickPointer(),await waitFor(.1);let a=e.ownerDocument;await enablePassThrough();let o=a.elementFromPoint(r,i);await disablePassThrough();let s=o instanceof HTMLElement&&e.contains(o)?o:e,c={bubbles:!0,cancelable:!0,clientX:r,clientY:i,pointerType:`mouse`},l={bubbles:!0,cancelable:!0,clientX:r,clientY:i,button:0};s.dispatchEvent(new PointerEvent(`pointerover`,c)),s.dispatchEvent(new PointerEvent(`pointerenter`,{...c,bubbles:!1})),s.dispatchEvent(new MouseEvent(`mouseover`,l)),s.dispatchEvent(new MouseEvent(`mouseenter`,{...l,bubbles:!1})),s.dispatchEvent(new PointerEvent(`pointerdown`,c)),s.dispatchEvent(new MouseEvent(`mousedown`,l)),e.focus({preventScroll:!0}),s.dispatchEvent(new PointerEvent(`pointerup`,c)),s.dispatchEvent(new MouseEvent(`mouseup`,l)),s.click(),await waitFor(.2)}async function inputTextElement(e,t){let n=e.isContentEditable;if(!isInputElement(e)&&!isTextAreaElement(e)&&!n)throw Error(`Element is not an input, textarea, or contenteditable`);if(await clickElement(e),n){if(e.dispatchEvent(new InputEvent(`beforeinput`,{bubbles:!0,cancelable:!0,inputType:`deleteContent`}))&&(e.innerText=``,e.dispatchEvent(new InputEvent(`input`,{bubbles:!0,inputType:`deleteContent`}))),e.dispatchEvent(new InputEvent(`beforeinput`,{bubbles:!0,cancelable:!0,inputType:`insertText`,data:t}))&&(e.innerText=t,e.dispatchEvent(new InputEvent(`input`,{bubbles:!0,inputType:`insertText`,data:t}))),e.innerText.trim()!==t.trim()){e.focus();let n=e.ownerDocument,r=(n.defaultView||window).getSelection(),i=n.createRange();i.selectNodeContents(e),r?.removeAllRanges(),r?.addRange(i),n.execCommand(`delete`,!1),n.execCommand(`insertText`,!1,t)}e.dispatchEvent(new Event(`change`,{bubbles:!0})),e.blur()}else getNativeValueSetter(e).call(e,t);n||e.dispatchEvent(new Event(`input`,{bubbles:!0})),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(e,t){if(!isSelectElement(e))throw Error(`Element is not a select element`);let n=Array.from(e.options).find(e=>e.textContent?.trim()===t.trim());if(!n)throw Error(`Option with text "${t}" not found in select element`);e.value=n.value,e.dispatchEvent(new Event(`change`,{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(e){let t=e;typeof t.scrollIntoViewIfNeeded==`function`?t.scrollIntoViewIfNeeded():e.scrollIntoView({behavior:`auto`,block:`center`,inline:`nearest`})}async function scrollVertically(e,t){if(t){let n=t,r=n,i=!1,a=null,o=0,s=0,c=e;for(;r&&s<10;){let e=window.getComputedStyle(r),t=/(auto|scroll|overlay)/.test(e.overflowY)||e.scrollbarWidth&&e.scrollbarWidth!==`auto`||e.scrollbarGutter&&e.scrollbarGutter!==`auto`,n=r.scrollHeight>r.clientHeight;if(t&&n){let e=r.scrollTop,t=r.scrollHeight-r.clientHeight,n=c/3;n=n>0?Math.min(n,t-e):Math.max(n,-e),r.scrollTop=e+n;let s=r.scrollTop-e;if(Math.abs(s)>.5){i=!0,a=r,o=s;break}}if(r===document.body||r===document.documentElement)break;r=r.parentElement,s++}return i?`Scrolled container (${a?.tagName}) by ${o}px`:`No scrollable container found for element (${n.tagName})`}let n=e,r=e=>e.clientHeight>=window.innerHeight*.5,i=e=>e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowY)&&e.scrollHeight>e.clientHeight&&r(e),a=document.activeElement;for(;a&&!i(a)&&a!==document.body;)a=a.parentElement;if(a=i(a)?a:Array.from(document.querySelectorAll(`*`)).find(i)||document.scrollingElement||document.documentElement,a===document.scrollingElement||a===document.documentElement||a===document.body){let e=window.scrollY,t=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,n);let r=window.scrollY,i=r-e;return Math.abs(i)<1?n>0?`⚠️ Already at the bottom of the page, cannot scroll down further.`:`⚠️ Already at the top of the page, cannot scroll up further.`:n>0&&r>=t-1?`✅ Scrolled page by ${i}px. Reached the bottom of the page.`:n<0&&r<=1?`✅ Scrolled page by ${i}px. Reached the top of the page.`:`✅ Scrolled page by ${i}px.`}else{let e=`The document is not scrollable. Falling back to container scroll.`;console.log(`[PageController] ${e}`);let t=a.scrollTop,r=a.scrollHeight-a.clientHeight;a.scrollBy({top:n,behavior:`smooth`}),await waitFor(.1);let i=a.scrollTop,o=i-t;return Math.abs(o)<1?n>0?`⚠️ ${e} Already at the bottom of container (${a.tagName}), cannot scroll down further.`:`⚠️ ${e} Already at the top of container (${a.tagName}), cannot scroll up further.`:n>0&&i>=r-1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the bottom.`:n<0&&i<=1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the top.`:`✅ ${e} Scrolled container (${a.tagName}) by ${o}px.`}}async function scrollHorizontally(e,t){if(t){let n=t,r=n,i=!1,a=null,o=0,s=0,c=e;for(;r&&s<10;){let e=window.getComputedStyle(r),t=/(auto|scroll|overlay)/.test(e.overflowX)||e.scrollbarWidth&&e.scrollbarWidth!==`auto`||e.scrollbarGutter&&e.scrollbarGutter!==`auto`,n=r.scrollWidth>r.clientWidth;if(t&&n){let e=r.scrollLeft,t=r.scrollWidth-r.clientWidth,n=c/3;n=n>0?Math.min(n,t-e):Math.max(n,-e),r.scrollLeft=e+n;let s=r.scrollLeft-e;if(Math.abs(s)>.5){i=!0,a=r,o=s;break}}if(r===document.body||r===document.documentElement)break;r=r.parentElement,s++}return i?`Scrolled container (${a?.tagName}) horizontally by ${o}px`:`No horizontally scrollable container found for element (${n.tagName})`}let n=e,r=e=>e.clientWidth>=window.innerWidth*.5,i=e=>e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowX)&&e.scrollWidth>e.clientWidth&&r(e),a=document.activeElement;for(;a&&!i(a)&&a!==document.body;)a=a.parentElement;if(a=i(a)?a:Array.from(document.querySelectorAll(`*`)).find(i)||document.scrollingElement||document.documentElement,a===document.scrollingElement||a===document.documentElement||a===document.body){let e=window.scrollX,t=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(n,0);let r=window.scrollX,i=r-e;return Math.abs(i)<1?n>0?`⚠️ Already at the right edge of the page, cannot scroll right further.`:`⚠️ Already at the left edge of the page, cannot scroll left further.`:n>0&&r>=t-1?`✅ Scrolled page by ${i}px. Reached the right edge of the page.`:n<0&&r<=1?`✅ Scrolled page by ${i}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${i}px.`}else{let e=`The document is not scrollable. Falling back to container scroll.`;console.log(`[PageController] ${e}`);let t=a.scrollLeft,r=a.scrollWidth-a.clientWidth;a.scrollBy({left:n,behavior:`smooth`}),await waitFor(.1);let i=a.scrollLeft,o=i-t;return Math.abs(o)<1?n>0?`⚠️ ${e} Already at the right edge of container (${a.tagName}), cannot scroll right further.`:`⚠️ ${e} Already at the left edge of container (${a.tagName}), cannot scroll left further.`:n>0&&i>=r-1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the right edge.`:n<0&&i<=1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the left edge.`:`✅ ${e} Scrolled container (${a.tagName}) horizontally by ${o}px.`}}var dom_tree_default=(e={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{let{interactiveBlacklist:t,interactiveWhitelist:n,highlightOpacity:r,highlightLabelOpacity:i}=e,{doHighlightElements:a,focusHighlightIndex:o,viewportExpansion:s,debugMode:c}=e,l=0,u=new WeakMap;function d(e,t){!e||e.nodeType!==Node.ELEMENT_NODE||u.set(e,{...u.get(e),...t})}let f={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{f.boundingRects=new WeakMap,f.clientRects=new WeakMap,f.computedStyles=new WeakMap}};function p(e){if(!e)return null;if(f.boundingRects.has(e))return f.boundingRects.get(e);let t=e.getBoundingClientRect();return t&&f.boundingRects.set(e,t),t}function m(e){if(!e)return null;if(f.computedStyles.has(e))return f.computedStyles.get(e);let t=window.getComputedStyle(e);return t&&f.computedStyles.set(e,t),t}function h(e){if(!e)return null;if(f.clientRects.has(e))return f.clientRects.get(e);let t=e.getClientRects();return t&&f.clientRects.set(e,t),t}let g={},_={current:0},v=`playwright-highlight-container`;function y(e,t,n=null){if(!e)return t;let a=[],o=null,s=20,c=16,l=null;try{let u=document.getElementById(v);u||(u=document.createElement(`div`),u.id=v,u.style.position=`fixed`,u.style.pointerEvents=`none`,u.style.top=`0`,u.style.left=`0`,u.style.width=`100%`,u.style.height=`100%`,u.style.zIndex=`2147483640`,u.style.backgroundColor=`transparent`,document.body.appendChild(u));let d=e.getClientRects();if(!d||d.length===0)return t;let f=[`#FF0000`,`#00FF00`,`#0000FF`,`#FFA500`,`#800080`,`#008080`,`#FF69B4`,`#4B0082`,`#FF4500`,`#2E8B57`,`#DC143C`,`#4682B4`],p=f[t%f.length],m=p+Math.floor(r*255).toString(16).padStart(2,`0`);p+=Math.floor(i*255).toString(16).padStart(2,`0`);let h={x:0,y:0};if(n){let e=n.getBoundingClientRect();h.x=e.left,h.y=e.top}let g=document.createDocumentFragment();for(let e of d){if(e.width===0||e.height===0)continue;let t=document.createElement(`div`);t.style.position=`fixed`,t.style.border=`2px solid ${p}`,t.style.backgroundColor=m,t.style.pointerEvents=`none`,t.style.boxSizing=`border-box`;let n=e.top+h.y,r=e.left+h.x;t.style.top=`${n}px`,t.style.left=`${r}px`,t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,g.appendChild(t),a.push({element:t,initialRect:e})}let _=d[0];o=document.createElement(`div`),o.className=`playwright-highlight-label`,o.style.position=`fixed`,o.style.background=p,o.style.color=`white`,o.style.padding=`1px 4px`,o.style.borderRadius=`4px`,o.style.fontSize=`${Math.min(12,Math.max(8,_.height/2))}px`,o.textContent=t.toString(),s=o.offsetWidth>0?o.offsetWidth:s,c=o.offsetHeight>0?o.offsetHeight:c;let y=_.top+h.y,b=_.left+h.x,x=y+2,S=b+_.width-s-2;(_.width<s+4||_.height<c+4)&&(x=y-c-2,S=b+_.width-s,S<h.x&&(S=b)),x=Math.max(0,Math.min(x,window.innerHeight-c)),S=Math.max(0,Math.min(S,window.innerWidth-s)),o.style.top=`${x}px`,o.style.left=`${S}px`,g.appendChild(o);let C=((e,t)=>{let n=0;return(...r)=>{let i=performance.now();if(!(i-n<t))return n=i,e(...r)}})(()=>{let t=e.getClientRects(),r={x:0,y:0};if(n){let e=n.getBoundingClientRect();r.x=e.left,r.y=e.top}if(a.forEach((e,n)=>{if(n<t.length){let i=t[n],a=i.top+r.y,o=i.left+r.x;e.element.style.top=`${a}px`,e.element.style.left=`${o}px`,e.element.style.width=`${i.width}px`,e.element.style.height=`${i.height}px`,e.element.style.display=i.width===0||i.height===0?`none`:`block`}else e.element.style.display=`none`}),t.length<a.length)for(let e=t.length;e<a.length;e++)a[e].element.style.display=`none`;if(o&&t.length>0){let e=t[0],n=e.top+r.y,i=e.left+r.x,a=n+2,l=i+e.width-s-2;(e.width<s+4||e.height<c+4)&&(a=n-c-2,l=i+e.width-s,l<r.x&&(l=i)),a=Math.max(0,Math.min(a,window.innerHeight-c)),l=Math.max(0,Math.min(l,window.innerWidth-s)),o.style.top=`${a}px`,o.style.left=`${l}px`,o.style.display=`block`}else o&&(o.style.display=`none`)},16);return window.addEventListener(`scroll`,C,!0),window.addEventListener(`resize`,C),l=()=>{window.removeEventListener(`scroll`,C,!0),window.removeEventListener(`resize`,C),a.forEach(e=>e.element.remove()),o&&o.remove()},u.appendChild(g),t+1}finally{l&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(l)}}function b(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return null;let t=m(e);if(!t)return null;let n=t.display;if(n===`inline`||n===`inline-block`)return null;let r=t.overflowX,i=t.overflowY,a=t.scrollbarWidth&&t.scrollbarWidth!==`auto`||t.scrollbarGutter&&t.scrollbarGutter!==`auto`,o=r===`auto`||r===`scroll`,s=i===`auto`||i===`scroll`;if(!o&&!s&&!a)return null;let c=e.scrollWidth-e.clientWidth,l=e.scrollHeight-e.clientHeight,u=4;if(c<4&&l<4||!s&&!a&&c<4||!o&&!a&&l<4)return null;let f=e.scrollTop,p=e.scrollLeft,h={top:f,right:e.scrollWidth-e.clientWidth-e.scrollLeft,bottom:e.scrollHeight-e.clientHeight-e.scrollTop,left:p};return d(e,{scrollable:!0,scrollData:h}),console.log(`scrollData!!!`,h),h}function x(e){try{if(s===-1){let t=e.parentElement;if(!t)return!1;try{return t.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{let e=window.getComputedStyle(t);return e.display!==`none`&&e.visibility!==`hidden`&&e.opacity!==`0`}}let t=document.createRange();t.selectNodeContents(e);let n=t.getClientRects();if(!n||n.length===0)return!1;let r=!1,i=!1;for(let e of n)if(e.width>0&&e.height>0&&(r=!0,!(e.bottom<-s||e.top>window.innerHeight+s||e.right<-s||e.left>window.innerWidth+s))){i=!0;break}if(!r||!i)return!1;let a=e.parentElement;if(!a)return!1;try{return a.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{let e=window.getComputedStyle(a);return e.display!==`none`&&e.visibility!==`hidden`&&e.opacity!==`0`}}catch(e){return console.warn(`Error checking text node visibility:`,e),!1}}function S(e){if(!e||!e.tagName)return!1;let t=new Set([`body`,`div`,`main`,`article`,`section`,`nav`,`header`,`footer`]),n=e.tagName.toLowerCase();return t.has(n)?!0:!new Set([`svg`,`script`,`style`,`link`,`meta`,`noscript`,`template`]).has(n)}function C(e){let t=m(e);return e.offsetWidth>0&&e.offsetHeight>0&&t?.visibility!==`hidden`&&t?.display!==`none`}function w(e){if(!e||e.nodeType!==Node.ELEMENT_NODE||t.includes(e))return!1;if(n.includes(e))return!0;let r=e.tagName.toLowerCase(),i=m(e),a=new Set(`pointer.move.text.grab.grabbing.cell.copy.alias.all-scroll.col-resize.context-menu.crosshair.e-resize.ew-resize.help.n-resize.ne-resize.nesw-resize.ns-resize.nw-resize.nwse-resize.row-resize.s-resize.se-resize.sw-resize.vertical-text.w-resize.zoom-in.zoom-out`.split(`.`)),o=new Set([`not-allowed`,`no-drop`,`wait`,`progress`,`initial`,`inherit`]);function s(e){return e.tagName.toLowerCase()===`html`?!1:!!(i?.cursor&&a.has(i.cursor))}if(s(e))return!0;let c=new Set([`a`,`button`,`input`,`select`,`textarea`,`details`,`summary`,`label`,`option`,`optgroup`,`fieldset`,`legend`]),l=new Set([`disabled`,`readonly`]);if(c.has(r)){if(i?.cursor&&o.has(i.cursor))return!1;for(let t of l)if(e.hasAttribute(t)||e.getAttribute(t)===`true`||e.getAttribute(t)===``)return!1;return!(e.disabled||e.readOnly||e.inert)}let u=e.getAttribute(`role`),d=e.getAttribute(`aria-role`);if(e.getAttribute(`contenteditable`)===`true`||e.isContentEditable||e.classList&&(e.classList.contains(`button`)||e.classList.contains(`dropdown-toggle`)||e.getAttribute(`data-index`)||e.getAttribute(`data-toggle`)===`dropdown`||e.getAttribute(`aria-haspopup`)===`true`))return!0;let f=new Set([`button`,`menu`,`menubar`,`menuitem`,`menuitemradio`,`menuitemcheckbox`,`radio`,`checkbox`,`tab`,`switch`,`slider`,`spinbutton`,`combobox`,`searchbox`,`textbox`,`listbox`,`option`,`scrollbar`]);if(c.has(r)||u&&f.has(u)||d&&f.has(d))return!0;try{if(typeof getEventListeners==`function`){let t=getEventListeners(e);for(let e of[`click`,`mousedown`,`mouseup`,`dblclick`])if(t[e]&&t[e].length>0)return!0}let t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof t==`function`){let n=t(e);for(let e of[`click`,`mousedown`,`mouseup`,`keydown`,`keyup`,`submit`,`change`,`input`,`focus`,`blur`])for(let t of n)if(t.type===e)return!0}for(let t of[`onclick`,`onmousedown`,`onmouseup`,`ondblclick`])if(e.hasAttribute(t)||typeof e[t]==`function`)return!0}catch{}return!!b(e)}function T(e){if(s===-1)return!0;let t=h(e);if(!t||t.length===0)return!1;let n=!1;for(let e of t)if(e.width>0&&e.height>0&&!(e.bottom<-s||e.top>window.innerHeight+s||e.right<-s||e.left>window.innerWidth+s)){n=!0;break}if(!n)return!1;if(e.ownerDocument!==window.document)return!0;let r=Array.from(t).find(e=>e.width>0&&e.height>0);if(!r)return!1;let i=e.getRootNode();if(i instanceof ShadowRoot){let t=r.left+r.width/2,n=r.top+r.height/2;try{let r=i.elementFromPoint(t,n);if(!r)return!1;let a=r;for(;a&&a!==i;){if(a===e)return!0;a=a.parentElement}return!1}catch{return!0}}let a=5;return[{x:r.left+r.width/2,y:r.top+r.height/2},{x:r.left+5,y:r.top+5},{x:r.right-5,y:r.bottom-5}].some(({x:t,y:n})=>{try{let r=document.elementFromPoint(t,n);if(!r)return!1;let i=r;for(;i&&i!==document.documentElement;){if(i===e)return!0;i=i.parentElement}return!1}catch{return!0}})}function E(e,t){if(t===-1)return!0;let n=e.getClientRects();if(!n||n.length===0){let n=p(e);return!n||n.width===0||n.height===0?!1:!(n.bottom<-t||n.top>window.innerHeight+t||n.right<-t||n.left>window.innerWidth+t)}for(let e of n)if(!(e.width===0||e.height===0)&&!(e.bottom<-t||e.top>window.innerHeight+t||e.right<-t||e.left>window.innerWidth+t))return!0;return!1}let D=[`aria-expanded`,`aria-checked`,`aria-selected`,`aria-pressed`,`aria-haspopup`,`aria-controls`,`aria-owns`,`aria-activedescendant`,`aria-valuenow`,`aria-valuetext`,`aria-valuemax`,`aria-valuemin`,`aria-autocomplete`];function O(e){for(let t=0;t<D.length;t++)if(e.hasAttribute(D[t]))return!0;return!1}function k(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;let t=e.tagName.toLowerCase();return new Set([`a`,`button`,`input`,`select`,`textarea`,`details`,`summary`,`label`]).has(t)?!0:e.hasAttribute(`onclick`)||e.hasAttribute(`role`)||e.hasAttribute(`tabindex`)||O(e)||e.hasAttribute(`data-action`)||e.getAttribute(`contenteditable`)===`true`}let A=new Set([`a`,`button`,`input`,`select`,`textarea`,`summary`,`details`,`label`,`option`,`li`]),j=new Set([`button`,`link`,`menuitem`,`menuitemradio`,`menuitemcheckbox`,`radio`,`checkbox`,`tab`,`switch`,`slider`,`spinbutton`,`combobox`,`searchbox`,`textbox`,`listbox`,`listitem`,`treeitem`,`row`,`option`,`scrollbar`]);function M(e){if(!e||e.nodeType!==Node.ELEMENT_NODE||!C(e))return!1;let t=e.hasAttribute(`role`)||e.hasAttribute(`tabindex`)||e.hasAttribute(`onclick`)||typeof e.onclick==`function`,n=/\b(btn|clickable|menu|item|entry|link)\b/i.test(e.className||``),r=!!e.closest(`button,a,[role="button"],.menu,.dropdown,.list,.toolbar`),i=[...e.children].some(C),a=e.parentElement&&e.parentElement.isSameNode(document.body);return(w(e)||t||n)&&i&&r&&!a}function N(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;let t=e.tagName.toLowerCase(),n=e.getAttribute(`role`);if(t===`iframe`||A.has(t)||n&&j.has(n)||e.isContentEditable||e.getAttribute(`contenteditable`)===`true`||e.hasAttribute(`data-testid`)||e.hasAttribute(`data-cy`)||e.hasAttribute(`data-test`)||e.hasAttribute(`onclick`)||typeof e.onclick==`function`||O(e))return!0;try{let t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof t==`function`){let n=t(e);for(let e of[`click`,`mousedown`,`mouseup`,`keydown`,`keyup`,`submit`,`change`,`input`,`focus`,`blur`])for(let t of n)if(t.type===e)return!0}if([`onmousedown`,`onmouseup`,`onkeydown`,`onkeyup`,`onsubmit`,`onchange`,`oninput`,`onfocus`,`onblur`].some(t=>e.hasAttribute(t)))return!0}catch{}return!!(M(e)||u.get(e)?.scrollable)}function P(e,t,n,r){if(!e.isInteractive)return!1;let i=!1;return i=r?!!N(t):!0,i&&(e.isInViewport=E(t,s),(e.isInViewport||s===-1)&&(e.highlightIndex=l++,a))?(o>=0?o===e.highlightIndex&&y(t,e.highlightIndex,n):y(t,e.highlightIndex,n),!0):!1}function F(e,t=null,n=!1){if(!e||e.id===v||e.nodeType!==Node.ELEMENT_NODE&&e.nodeType!==Node.TEXT_NODE||!e||e.id===v||e.dataset?.browserUseIgnore===`true`||e.dataset?.pageAgentIgnore===`true`||e.getAttribute&&e.getAttribute(`aria-hidden`)===`true`)return null;if(e===document.body){let n={tagName:`body`,attributes:{},xpath:`/body`,children:[]};for(let r of e.childNodes){let e=F(r,t,!1);e&&n.children.push(e)}let r=`${_.current++}`;return g[r]=n,r}if(e.nodeType!==Node.ELEMENT_NODE&&e.nodeType!==Node.TEXT_NODE)return null;if(e.nodeType===Node.TEXT_NODE){let t=e.textContent?.trim();if(!t)return null;let n=e.parentElement;if(!n||n.tagName.toLowerCase()===`script`)return null;let r=`${_.current++}`;return g[r]={type:`TEXT_NODE`,text:t,isVisible:x(e)},r}if(e.nodeType===Node.ELEMENT_NODE&&!S(e))return null;if(s!==-1&&!e.shadowRoot){let t=p(e),n=m(e),r=n&&(n.position===`fixed`||n.position===`sticky`),i=e.offsetWidth>0||e.offsetHeight>0;if(!t||!r&&!i&&(t.bottom<-s||t.top>window.innerHeight+s||t.right<-s||t.left>window.innerWidth+s))return null}let r={tagName:e.tagName.toLowerCase(),attributes:{},children:[]};if(k(e)||e.tagName.toLowerCase()===`iframe`||e.tagName.toLowerCase()===`body`){let t=e.getAttributeNames?.()||[];for(let n of t){let t=e.getAttribute(n);r.attributes[n]=t}e.tagName.toLowerCase()===`input`&&(e.type===`checkbox`||e.type===`radio`)&&(r.attributes.checked=e.checked?`true`:`false`)}let i=!1;if(e.nodeType===Node.ELEMENT_NODE&&(r.isVisible=C(e),r.isVisible)){r.isTopElement=T(e);let a=e.getAttribute(`role`),o=a===`menu`||a===`menubar`||a===`listbox`;if((r.isTopElement||o)&&(r.isInteractive=w(e),i=P(r,e,t,n),r.ref=e,r.isInteractive&&Object.keys(r.attributes).length===0)){let t=e.getAttributeNames?.()||[];for(let n of t){let t=e.getAttribute(n);r.attributes[n]=t}}}if(e.tagName){let a=e.tagName.toLowerCase();if(a===`iframe`)try{let t=e.contentDocument||e.contentWindow?.document;if(t)for(let n of t.childNodes){let t=F(n,e,!1);t&&r.children.push(t)}}catch(e){console.warn(`Unable to access iframe:`,e)}else if(e.isContentEditable||e.getAttribute(`contenteditable`)===`true`||e.id===`tinymce`||e.classList.contains(`mce-content-body`)||a===`body`&&e.getAttribute(`data-id`)?.startsWith(`mce_`))for(let n of e.childNodes){let e=F(n,t,i);e&&r.children.push(e)}else{if(e.shadowRoot){r.shadowRoot=!0;for(let n of e.shadowRoot.childNodes){let e=F(n,t,i);e&&r.children.push(e)}}for(let a of e.childNodes){let e=F(a,t,i||n);e&&r.children.push(e)}}}if(r.tagName===`a`&&r.children.length===0&&!r.attributes.href){let t=p(e);if(!(t&&t.width>0&&t.height>0||e.offsetWidth>0||e.offsetHeight>0))return null}r.extra=u.get(e)||null;let a=`${_.current++}`;return g[a]=r,a}let I=F(document.body);return f.clearCache(),{rootId:I,map:g}},dom_exports=__exportAll({cleanUpHighlights:()=>cleanUpHighlights,flatTreeToString:()=>flatTreeToString,getAllTextTillNextClickableElement:()=>getAllTextTillNextClickableElement,getElementTextMap:()=>getElementTextMap,getFlatTree:()=>getFlatTree,getSelectorMap:()=>getSelectorMap,resolveViewportExpansion:()=>resolveViewportExpansion}),DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(e){return e??DEFAULT_VIEWPORT_EXPANSION}var SEMANTIC_TAGS=new Set([`nav`,`menu`,`header`,`footer`,`aside`,`dialog`]),newElementsCache=new WeakMap;function getFlatTree(e){let t=resolveViewportExpansion(e.viewportExpansion),n=[];for(let t of e.interactiveBlacklist||[])typeof t==`function`?n.push(t()):n.push(t);let r=[];for(let t of e.interactiveWhitelist||[])typeof t==`function`?r.push(t()):r.push(t);let i=dom_tree_default({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:t,interactiveBlacklist:n,interactiveWhitelist:r,highlightOpacity:e.highlightOpacity??0,highlightLabelOpacity:e.highlightLabelOpacity??.1}),a=window.location.href;for(let e in i.map){let t=i.map[e];if(t.isInteractive&&t.ref){let e=t.ref;newElementsCache.has(e)||(newElementsCache.set(e,a),t.isNew=!0)}}return i}var globRegexCache=new Map;function globToRegex(e){let t=globRegexCache.get(e);if(!t){let n=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`);t=RegExp(`^${n.replace(/\*/g,`.*`)}$`),globRegexCache.set(e,t)}return t}function matchAttributes(e,t){let n={};for(let r of t)if(r.includes(`*`)){let t=globToRegex(r);for(let r of Object.keys(e))t.test(r)&&e[r].trim()&&(n[r]=e[r].trim())}else{let t=e[r];t&&t.trim()&&(n[r]=t.trim())}return n}function flatTreeToString(e,t=[],n=!1){let r=[`title`,`type`,`checked`,`name`,`role`,`value`,`placeholder`,`data-date-format`,`alt`,`aria-label`,`aria-expanded`,`data-state`,`aria-checked`,`id`,`for`,`target`,`aria-haspopup`,`aria-controls`,`aria-owns`,`contenteditable`],i=[...t,...r],a=(e,t)=>e.length>t?e.substring(0,t)+`...`:e,o=t=>{let n=e.map[t];if(!n)return null;if(n.type===`TEXT_NODE`){let e=n;return{type:`text`,text:e.text,isVisible:e.isVisible,parent:null,children:[]}}else{let e=n,t=[];if(e.children)for(let n of e.children){let e=o(n);e&&(e.parent=null,t.push(e))}return{type:`element`,tagName:e.tagName,attributes:e.attributes??{},isVisible:e.isVisible??!1,isInteractive:e.isInteractive??!1,isTopElement:e.isTopElement??!1,isNew:e.isNew??!1,highlightIndex:e.highlightIndex,parent:null,children:t,extra:e.extra??{}}}},s=(e,t=null)=>{e.parent=t;for(let t of e.children)s(t,e)},c=o(e.rootId);if(!c)return``;s(c);let l=e=>{let t=e.parent;for(;t;){if(t.type===`element`&&t.highlightIndex!==void 0)return!0;t=t.parent}return!1},u=(e,t,r)=>{let o=t,s=` `.repeat(t);if(e.type===`element`){let t=n&&e.tagName&&SEMANTIC_TAGS.has(e.tagName);if(e.highlightIndex!==void 0){o+=1;let t=getAllTextTillNextClickableElement(e),n=``;if(i.length>0&&e.attributes){let r=matchAttributes(e.attributes,i),o=Object.keys(r);if(o.length>1){let e=new Set,t={};for(let n of o){let i=r[n];i.length>5&&(i in t?e.add(n):t[i]=n)}for(let t of e)delete r[t]}r.role===e.tagName&&delete r.role;for(let e of[`aria-label`,`placeholder`,`title`])r[e]&&r[e].toLowerCase().trim()===t.toLowerCase().trim()&&delete r[e];Object.keys(r).length>0&&(n=Object.entries(r).map(([e,t])=>`${e}=${a(t,20)}`).join(` `))}let c=`${s}${e.isNew?`*[${e.highlightIndex}]`:`[${e.highlightIndex}]`}<${e.tagName??``}`;if(n&&(c+=` ${n}`),e.extra&&e.extra.scrollable){let t=``;e.extra.scrollData?.left&&(t+=`left=${e.extra.scrollData.left}, `),e.extra.scrollData?.top&&(t+=`top=${e.extra.scrollData.top}, `),e.extra.scrollData?.right&&(t+=`right=${e.extra.scrollData.right}, `),e.extra.scrollData?.bottom&&(t+=`bottom=${e.extra.scrollData.bottom}`),c+=` data-scrollable="${t}"`}if(t){let e=t.trim();n||(c+=` `),c+=`>${e}`}else n||(c+=` `);c+=` />`,r.push(c)}let c=t&&e.highlightIndex===void 0,l=c?r.length:-1;c&&(r.push(`${s}<${e.tagName}>`),o+=1);for(let t of e.children)u(t,o,r);c&&(r.length===l+1?r.pop():r.push(`${s}</${e.tagName}>`))}else if(e.type===`text`){if(l(e))return;e.parent&&e.parent.type===`element`&&e.parent.isVisible&&e.parent.isTopElement&&r.push(`${s}${e.text??``}`)}},d=[];return u(c,0,d),d.join(`
|
|
244
|
+
`,t}dispose(){console.log(`Disposing PageAgent...`),this.disposed=!0,this.pageController.dispose(),this.#n.abort(),this.dispatchEvent(new Event(`dispose`)),this.config.onDispose?.(this)}};function isHTMLElement(e){return!!e&&e.nodeType===1}function isInputElement(e){return e?.nodeType===1&&e.tagName===`INPUT`}function isTextAreaElement(e){return e?.nodeType===1&&e.tagName===`TEXTAREA`}function isSelectElement(e){return e?.nodeType===1&&e.tagName===`SELECT`}function isAnchorElement(e){return e?.nodeType===1&&e.tagName===`A`}function getIframeOffset(e){let t=e.ownerDocument.defaultView?.frameElement;if(!t)return{x:0,y:0};let n=t.getBoundingClientRect();return{x:n.left,y:n.top}}function getNativeValueSetter(e){return Object.getOwnPropertyDescriptor(Object.getPrototypeOf(e),`value`).set}async function waitFor(e){await new Promise(t=>setTimeout(t,e*1e3))}async function movePointerToElement(e,t,n){let r=getIframeOffset(e);window.dispatchEvent(new CustomEvent(`PageAgent::MovePointerTo`,{detail:{x:t+r.x,y:n+r.y}})),await waitFor(.3)}async function clickPointer(){window.dispatchEvent(new CustomEvent(`PageAgent::ClickPointer`))}async function enablePassThrough(){window.dispatchEvent(new CustomEvent(`PageAgent::EnablePassThrough`))}async function disablePassThrough(){window.dispatchEvent(new CustomEvent(`PageAgent::DisablePassThrough`))}function getElementByIndex(e,t){let n=e.get(t);if(!n)throw Error(`No interactive element found at index ${t}`);let r=n.ref;if(!r)throw Error(`Element at index ${t} does not have a reference`);if(!isHTMLElement(r))throw Error(`Element at index ${t} is not an HTMLElement`);return r}var lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&=(lastClickedElement.dispatchEvent(new PointerEvent(`pointerout`,{bubbles:!0})),lastClickedElement.dispatchEvent(new PointerEvent(`pointerleave`,{bubbles:!1})),lastClickedElement.dispatchEvent(new MouseEvent(`mouseout`,{bubbles:!0})),lastClickedElement.dispatchEvent(new MouseEvent(`mouseleave`,{bubbles:!1})),lastClickedElement.blur(),null)}async function clickElement(e){blurLastClickedElement(),lastClickedElement=e,await scrollIntoViewIfNeeded(e);let t=e.ownerDocument.defaultView?.frameElement;t&&await scrollIntoViewIfNeeded(t);let n=e.getBoundingClientRect(),r=n.left+n.width/2,i=n.top+n.height/2;await movePointerToElement(e,r,i),await clickPointer(),await waitFor(.1);let a=e.ownerDocument;await enablePassThrough();let o=a.elementFromPoint(r,i);await disablePassThrough();let s=o instanceof HTMLElement&&e.contains(o)?o:e,c={bubbles:!0,cancelable:!0,clientX:r,clientY:i,pointerType:`mouse`},l={bubbles:!0,cancelable:!0,clientX:r,clientY:i,button:0};s.dispatchEvent(new PointerEvent(`pointerover`,c)),s.dispatchEvent(new PointerEvent(`pointerenter`,{...c,bubbles:!1})),s.dispatchEvent(new MouseEvent(`mouseover`,l)),s.dispatchEvent(new MouseEvent(`mouseenter`,{...l,bubbles:!1})),s.dispatchEvent(new PointerEvent(`pointerdown`,c)),s.dispatchEvent(new MouseEvent(`mousedown`,l)),e.focus({preventScroll:!0}),s.dispatchEvent(new PointerEvent(`pointerup`,c)),s.dispatchEvent(new MouseEvent(`mouseup`,l)),s.click(),await waitFor(.2)}async function inputTextElement(e,t){let n=e.isContentEditable;if(!isInputElement(e)&&!isTextAreaElement(e)&&!n)throw Error(`Element is not an input, textarea, or contenteditable`);if(await clickElement(e),n){if(e.dispatchEvent(new InputEvent(`beforeinput`,{bubbles:!0,cancelable:!0,inputType:`deleteContent`}))&&(e.innerText=``,e.dispatchEvent(new InputEvent(`input`,{bubbles:!0,inputType:`deleteContent`}))),e.dispatchEvent(new InputEvent(`beforeinput`,{bubbles:!0,cancelable:!0,inputType:`insertText`,data:t}))&&(e.innerText=t,e.dispatchEvent(new InputEvent(`input`,{bubbles:!0,inputType:`insertText`,data:t}))),e.innerText.trim()!==t.trim()){e.focus();let n=e.ownerDocument,r=(n.defaultView||window).getSelection(),i=n.createRange();i.selectNodeContents(e),r?.removeAllRanges(),r?.addRange(i),n.execCommand(`delete`,!1),n.execCommand(`insertText`,!1,t)}e.dispatchEvent(new Event(`change`,{bubbles:!0})),e.blur()}else getNativeValueSetter(e).call(e,t);n||e.dispatchEvent(new Event(`input`,{bubbles:!0})),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(e,t){if(!isSelectElement(e))throw Error(`Element is not a select element`);let n=Array.from(e.options).find(e=>e.textContent?.trim()===t.trim());if(!n)throw Error(`Option with text "${t}" not found in select element`);e.value=n.value,e.dispatchEvent(new Event(`change`,{bubbles:!0})),await waitFor(.1)}async function scrollIntoViewIfNeeded(e){let t=e;typeof t.scrollIntoViewIfNeeded==`function`?t.scrollIntoViewIfNeeded():e.scrollIntoView({behavior:`auto`,block:`center`,inline:`nearest`})}async function scrollVertically(e,t){if(t){let n=t,r=n,i=!1,a=null,o=0,s=0,c=e;for(;r&&s<10;){let e=window.getComputedStyle(r),t=/(auto|scroll|overlay)/.test(e.overflowY)||e.scrollbarWidth&&e.scrollbarWidth!==`auto`||e.scrollbarGutter&&e.scrollbarGutter!==`auto`,n=r.scrollHeight>r.clientHeight;if(t&&n){let e=r.scrollTop,t=r.scrollHeight-r.clientHeight,n=c/3;n=n>0?Math.min(n,t-e):Math.max(n,-e),r.scrollTop=e+n;let s=r.scrollTop-e;if(Math.abs(s)>.5){i=!0,a=r,o=s;break}}if(r===document.body||r===document.documentElement)break;r=r.parentElement,s++}return i?`Scrolled container (${a?.tagName}) by ${o}px`:`No scrollable container found for element (${n.tagName})`}let n=e,r=e=>e.clientHeight>=window.innerHeight*.5,i=e=>!!(e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowY)&&e.scrollHeight>e.clientHeight&&r(e)),a=document.activeElement;for(;a&&!i(a)&&a!==document.body;)a=a.parentElement;if(a=i(a)?a:Array.from(document.querySelectorAll(`*`)).find(i)||document.scrollingElement||document.documentElement,a===document.scrollingElement||a===document.documentElement||a===document.body){let e=window.scrollY,t=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,n);let r=window.scrollY,i=r-e;return Math.abs(i)<1?n>0?`⚠️ Already at the bottom of the page, cannot scroll down further.`:`⚠️ Already at the top of the page, cannot scroll up further.`:n>0&&r>=t-1?`✅ Scrolled page by ${i}px. Reached the bottom of the page.`:n<0&&r<=1?`✅ Scrolled page by ${i}px. Reached the top of the page.`:`✅ Scrolled page by ${i}px.`}else{let e=`The document is not scrollable. Falling back to container scroll.`;console.log(`[PageController] ${e}`);let t=a.scrollTop,r=a.scrollHeight-a.clientHeight;a.scrollBy({top:n,behavior:`smooth`}),await waitFor(.1);let i=a.scrollTop,o=i-t;return Math.abs(o)<1?n>0?`⚠️ ${e} Already at the bottom of container (${a.tagName}), cannot scroll down further.`:`⚠️ ${e} Already at the top of container (${a.tagName}), cannot scroll up further.`:n>0&&i>=r-1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the bottom.`:n<0&&i<=1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the top.`:`✅ ${e} Scrolled container (${a.tagName}) by ${o}px.`}}async function scrollHorizontally(e,t){if(t){let n=t,r=n,i=!1,a=null,o=0,s=0,c=e;for(;r&&s<10;){let e=window.getComputedStyle(r),t=/(auto|scroll|overlay)/.test(e.overflowX)||e.scrollbarWidth&&e.scrollbarWidth!==`auto`||e.scrollbarGutter&&e.scrollbarGutter!==`auto`,n=r.scrollWidth>r.clientWidth;if(t&&n){let e=r.scrollLeft,t=r.scrollWidth-r.clientWidth,n=c/3;n=n>0?Math.min(n,t-e):Math.max(n,-e),r.scrollLeft=e+n;let s=r.scrollLeft-e;if(Math.abs(s)>.5){i=!0,a=r,o=s;break}}if(r===document.body||r===document.documentElement)break;r=r.parentElement,s++}return i?`Scrolled container (${a?.tagName}) horizontally by ${o}px`:`No horizontally scrollable container found for element (${n.tagName})`}let n=e,r=e=>e.clientWidth>=window.innerWidth*.5,i=e=>!!(e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowX)&&e.scrollWidth>e.clientWidth&&r(e)),a=document.activeElement;for(;a&&!i(a)&&a!==document.body;)a=a.parentElement;if(a=i(a)?a:Array.from(document.querySelectorAll(`*`)).find(i)||document.scrollingElement||document.documentElement,a===document.scrollingElement||a===document.documentElement||a===document.body){let e=window.scrollX,t=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(n,0);let r=window.scrollX,i=r-e;return Math.abs(i)<1?n>0?`⚠️ Already at the right edge of the page, cannot scroll right further.`:`⚠️ Already at the left edge of the page, cannot scroll left further.`:n>0&&r>=t-1?`✅ Scrolled page by ${i}px. Reached the right edge of the page.`:n<0&&r<=1?`✅ Scrolled page by ${i}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${i}px.`}else{let e=`The document is not scrollable. Falling back to container scroll.`;console.log(`[PageController] ${e}`);let t=a.scrollLeft,r=a.scrollWidth-a.clientWidth;a.scrollBy({left:n,behavior:`smooth`}),await waitFor(.1);let i=a.scrollLeft,o=i-t;return Math.abs(o)<1?n>0?`⚠️ ${e} Already at the right edge of container (${a.tagName}), cannot scroll right further.`:`⚠️ ${e} Already at the left edge of container (${a.tagName}), cannot scroll left further.`:n>0&&i>=r-1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the right edge.`:n<0&&i<=1?`✅ ${e} Scrolled container (${a.tagName}) by ${o}px. Reached the left edge.`:`✅ ${e} Scrolled container (${a.tagName}) horizontally by ${o}px.`}}var dom_tree_default=(e={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{let{interactiveBlacklist:t,interactiveWhitelist:n,highlightOpacity:r,highlightLabelOpacity:i}=e,{doHighlightElements:a,focusHighlightIndex:o,viewportExpansion:s,debugMode:c}=e,l=0,u=new WeakMap;function d(e,t){!e||e.nodeType!==Node.ELEMENT_NODE||u.set(e,{...u.get(e),...t})}let f={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{f.boundingRects=new WeakMap,f.clientRects=new WeakMap,f.computedStyles=new WeakMap}};function p(e){if(!e)return null;if(f.boundingRects.has(e))return f.boundingRects.get(e);let t=e.getBoundingClientRect();return t&&f.boundingRects.set(e,t),t}function m(e){if(!e)return null;if(f.computedStyles.has(e))return f.computedStyles.get(e);let t=window.getComputedStyle(e);return t&&f.computedStyles.set(e,t),t}function h(e){if(!e)return null;if(f.clientRects.has(e))return f.clientRects.get(e);let t=e.getClientRects();return t&&f.clientRects.set(e,t),t}let g={},_={current:0},v=`playwright-highlight-container`;function y(e,t,n=null){if(!e)return t;let a=[],o=null,s=20,c=16,l=null;try{let u=document.getElementById(v);u||(u=document.createElement(`div`),u.id=v,u.style.position=`fixed`,u.style.pointerEvents=`none`,u.style.top=`0`,u.style.left=`0`,u.style.width=`100%`,u.style.height=`100%`,u.style.zIndex=`2147483640`,u.style.backgroundColor=`transparent`,document.body.appendChild(u));let d=e.getClientRects();if(!d||d.length===0)return t;let f=[`#FF0000`,`#00FF00`,`#0000FF`,`#FFA500`,`#800080`,`#008080`,`#FF69B4`,`#4B0082`,`#FF4500`,`#2E8B57`,`#DC143C`,`#4682B4`],p=f[t%f.length],m=p+Math.floor(r*255).toString(16).padStart(2,`0`);p+=Math.floor(i*255).toString(16).padStart(2,`0`);let h={x:0,y:0};if(n){let e=n.getBoundingClientRect();h.x=e.left,h.y=e.top}let g=document.createDocumentFragment();for(let e of d){if(e.width===0||e.height===0)continue;let t=document.createElement(`div`);t.style.position=`fixed`,t.style.border=`2px solid ${p}`,t.style.backgroundColor=m,t.style.pointerEvents=`none`,t.style.boxSizing=`border-box`;let n=e.top+h.y,r=e.left+h.x;t.style.top=`${n}px`,t.style.left=`${r}px`,t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,g.appendChild(t),a.push({element:t,initialRect:e})}let _=d[0];o=document.createElement(`div`),o.className=`playwright-highlight-label`,o.style.position=`fixed`,o.style.background=p,o.style.color=`white`,o.style.padding=`1px 4px`,o.style.borderRadius=`4px`,o.style.fontSize=`${Math.min(12,Math.max(8,_.height/2))}px`,o.textContent=t.toString(),s=o.offsetWidth>0?o.offsetWidth:s,c=o.offsetHeight>0?o.offsetHeight:c;let y=_.top+h.y,b=_.left+h.x,x=y+2,S=b+_.width-s-2;(_.width<s+4||_.height<c+4)&&(x=y-c-2,S=b+_.width-s,S<h.x&&(S=b)),x=Math.max(0,Math.min(x,window.innerHeight-c)),S=Math.max(0,Math.min(S,window.innerWidth-s)),o.style.top=`${x}px`,o.style.left=`${S}px`,g.appendChild(o);let C=((e,t)=>{let n=0;return(...r)=>{let i=performance.now();if(!(i-n<t))return n=i,e(...r)}})(()=>{let t=e.getClientRects(),r={x:0,y:0};if(n){let e=n.getBoundingClientRect();r.x=e.left,r.y=e.top}if(a.forEach((e,n)=>{if(n<t.length){let i=t[n],a=i.top+r.y,o=i.left+r.x;e.element.style.top=`${a}px`,e.element.style.left=`${o}px`,e.element.style.width=`${i.width}px`,e.element.style.height=`${i.height}px`,e.element.style.display=i.width===0||i.height===0?`none`:`block`}else e.element.style.display=`none`}),t.length<a.length)for(let e=t.length;e<a.length;e++)a[e].element.style.display=`none`;if(o&&t.length>0){let e=t[0],n=e.top+r.y,i=e.left+r.x,a=n+2,l=i+e.width-s-2;(e.width<s+4||e.height<c+4)&&(a=n-c-2,l=i+e.width-s,l<r.x&&(l=i)),a=Math.max(0,Math.min(a,window.innerHeight-c)),l=Math.max(0,Math.min(l,window.innerWidth-s)),o.style.top=`${a}px`,o.style.left=`${l}px`,o.style.display=`block`}else o&&(o.style.display=`none`)},16);return window.addEventListener(`scroll`,C,!0),window.addEventListener(`resize`,C),l=()=>{window.removeEventListener(`scroll`,C,!0),window.removeEventListener(`resize`,C),a.forEach(e=>e.element.remove()),o&&o.remove()},u.appendChild(g),t+1}finally{l&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(l)}}function b(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return null;let t=m(e);if(!t)return null;let n=t.display;if(n===`inline`||n===`inline-block`)return null;let r=t.overflowX,i=t.overflowY,a=t.scrollbarWidth&&t.scrollbarWidth!==`auto`||t.scrollbarGutter&&t.scrollbarGutter!==`auto`,o=r===`auto`||r===`scroll`,s=i===`auto`||i===`scroll`;if(!o&&!s&&!a)return null;let c=e.scrollWidth-e.clientWidth,l=e.scrollHeight-e.clientHeight,u=4;if(c<4&&l<4||!s&&!a&&c<4||!o&&!a&&l<4)return null;let f=e.scrollTop,p=e.scrollLeft,h={top:f,right:e.scrollWidth-e.clientWidth-e.scrollLeft,bottom:e.scrollHeight-e.clientHeight-e.scrollTop,left:p};return d(e,{scrollable:!0,scrollData:h}),h}function x(e){try{if(s===-1){let t=e.parentElement;if(!t)return!1;try{return t.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{let e=window.getComputedStyle(t);return e.display!==`none`&&e.visibility!==`hidden`&&e.opacity!==`0`}}let t=document.createRange();t.selectNodeContents(e);let n=t.getClientRects();if(!n||n.length===0)return!1;let r=!1,i=!1;for(let e of n)if(e.width>0&&e.height>0&&(r=!0,!(e.bottom<-s||e.top>window.innerHeight+s||e.right<-s||e.left>window.innerWidth+s))){i=!0;break}if(!r||!i)return!1;let a=e.parentElement;if(!a)return!1;try{return a.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{let e=window.getComputedStyle(a);return e.display!==`none`&&e.visibility!==`hidden`&&e.opacity!==`0`}}catch(e){return console.warn(`Error checking text node visibility:`,e),!1}}function S(e){if(!e||!e.tagName)return!1;let t=new Set([`body`,`div`,`main`,`article`,`section`,`nav`,`header`,`footer`]),n=e.tagName.toLowerCase();return t.has(n)?!0:!new Set([`svg`,`script`,`style`,`link`,`meta`,`noscript`,`template`]).has(n)}function C(e){let t=m(e);return e.offsetWidth>0&&e.offsetHeight>0&&t?.visibility!==`hidden`&&t?.display!==`none`}function w(e){if(!e||e.nodeType!==Node.ELEMENT_NODE||t.includes(e))return!1;if(n.includes(e))return!0;let r=e.tagName.toLowerCase(),i=m(e),a=new Set(`pointer.move.text.grab.grabbing.cell.copy.alias.all-scroll.col-resize.context-menu.crosshair.e-resize.ew-resize.help.n-resize.ne-resize.nesw-resize.ns-resize.nw-resize.nwse-resize.row-resize.s-resize.se-resize.sw-resize.vertical-text.w-resize.zoom-in.zoom-out`.split(`.`)),o=new Set([`not-allowed`,`no-drop`,`wait`,`progress`,`initial`,`inherit`]);function s(e){return e.tagName.toLowerCase()===`html`?!1:!!(i?.cursor&&a.has(i.cursor))}if(s(e))return!0;let c=new Set([`a`,`button`,`input`,`select`,`textarea`,`details`,`summary`,`label`,`option`,`optgroup`,`fieldset`,`legend`]),l=new Set([`disabled`,`readonly`]);if(c.has(r)){if(i?.cursor&&o.has(i.cursor))return!1;for(let t of l)if(e.hasAttribute(t)||e.getAttribute(t)===`true`||e.getAttribute(t)===``)return!1;return!(e.disabled||e.readOnly||e.inert)}let u=e.getAttribute(`role`),d=e.getAttribute(`aria-role`);if(e.getAttribute(`contenteditable`)===`true`||e.isContentEditable||e.classList&&(e.classList.contains(`button`)||e.classList.contains(`dropdown-toggle`)||e.getAttribute(`data-index`)||e.getAttribute(`data-toggle`)===`dropdown`||e.getAttribute(`aria-haspopup`)===`true`))return!0;let f=new Set([`button`,`menu`,`menubar`,`menuitem`,`menuitemradio`,`menuitemcheckbox`,`radio`,`checkbox`,`tab`,`switch`,`slider`,`spinbutton`,`combobox`,`searchbox`,`textbox`,`listbox`,`option`,`scrollbar`]);if(c.has(r)||u&&f.has(u)||d&&f.has(d))return!0;try{if(typeof getEventListeners==`function`){let t=getEventListeners(e);for(let e of[`click`,`mousedown`,`mouseup`,`dblclick`])if(t[e]&&t[e].length>0)return!0}let t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof t==`function`){let n=t(e);for(let e of[`click`,`mousedown`,`mouseup`,`keydown`,`keyup`,`submit`,`change`,`input`,`focus`,`blur`])for(let t of n)if(t.type===e)return!0}for(let t of[`onclick`,`onmousedown`,`onmouseup`,`ondblclick`])if(e.hasAttribute(t)||typeof e[t]==`function`)return!0}catch{}return!!b(e)}function T(e){if(s===-1)return!0;let t=h(e);if(!t||t.length===0)return!1;let n=!1;for(let e of t)if(e.width>0&&e.height>0&&!(e.bottom<-s||e.top>window.innerHeight+s||e.right<-s||e.left>window.innerWidth+s)){n=!0;break}if(!n)return!1;if(e.ownerDocument!==window.document)return!0;let r=Array.from(t).find(e=>e.width>0&&e.height>0);if(!r)return!1;let i=e.getRootNode();if(i instanceof ShadowRoot){let t=r.left+r.width/2,n=r.top+r.height/2;try{let r=i.elementFromPoint(t,n);if(!r)return!1;let a=r;for(;a&&a!==i;){if(a===e)return!0;a=a.parentElement}return!1}catch{return!0}}let a=5;return[{x:r.left+r.width/2,y:r.top+r.height/2},{x:r.left+5,y:r.top+5},{x:r.right-5,y:r.bottom-5}].some(({x:t,y:n})=>{try{let r=document.elementFromPoint(t,n);if(!r)return!1;let i=r;for(;i&&i!==document.documentElement;){if(i===e)return!0;i=i.parentElement}return!1}catch{return!0}})}function E(e,t){if(t===-1)return!0;let n=e.getClientRects();if(!n||n.length===0){let n=p(e);return!n||n.width===0||n.height===0?!1:!(n.bottom<-t||n.top>window.innerHeight+t||n.right<-t||n.left>window.innerWidth+t)}for(let e of n)if(!(e.width===0||e.height===0)&&!(e.bottom<-t||e.top>window.innerHeight+t||e.right<-t||e.left>window.innerWidth+t))return!0;return!1}let D=[`aria-expanded`,`aria-checked`,`aria-selected`,`aria-pressed`,`aria-haspopup`,`aria-controls`,`aria-owns`,`aria-activedescendant`,`aria-valuenow`,`aria-valuetext`,`aria-valuemax`,`aria-valuemin`,`aria-autocomplete`];function O(e){for(let t=0;t<D.length;t++)if(e.hasAttribute(D[t]))return!0;return!1}function k(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;let t=e.tagName.toLowerCase();return new Set([`a`,`button`,`input`,`select`,`textarea`,`details`,`summary`,`label`]).has(t)?!0:e.hasAttribute(`onclick`)||e.hasAttribute(`role`)||e.hasAttribute(`tabindex`)||O(e)||e.hasAttribute(`data-action`)||e.getAttribute(`contenteditable`)===`true`}let A=new Set([`a`,`button`,`input`,`select`,`textarea`,`summary`,`details`,`label`,`option`,`li`]),j=new Set([`button`,`link`,`menuitem`,`menuitemradio`,`menuitemcheckbox`,`radio`,`checkbox`,`tab`,`switch`,`slider`,`spinbutton`,`combobox`,`searchbox`,`textbox`,`listbox`,`listitem`,`treeitem`,`row`,`option`,`scrollbar`]);function M(e){if(!e||e.nodeType!==Node.ELEMENT_NODE||!C(e))return!1;let t=e.hasAttribute(`role`)||e.hasAttribute(`tabindex`)||e.hasAttribute(`onclick`)||typeof e.onclick==`function`,n=/\b(btn|clickable|menu|item|entry|link)\b/i.test(e.className||``),r=!!e.closest(`button,a,[role="button"],.menu,.dropdown,.list,.toolbar`),i=[...e.children].some(C),a=e.parentElement&&e.parentElement.isSameNode(document.body);return(w(e)||t||n)&&i&&r&&!a}function N(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;let t=e.tagName.toLowerCase(),n=e.getAttribute(`role`);if(t===`iframe`||A.has(t)||n&&j.has(n)||e.isContentEditable||e.getAttribute(`contenteditable`)===`true`||e.hasAttribute(`data-testid`)||e.hasAttribute(`data-cy`)||e.hasAttribute(`data-test`)||e.hasAttribute(`onclick`)||typeof e.onclick==`function`||O(e))return!0;try{let t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof t==`function`){let n=t(e);for(let e of[`click`,`mousedown`,`mouseup`,`keydown`,`keyup`,`submit`,`change`,`input`,`focus`,`blur`])for(let t of n)if(t.type===e)return!0}if([`onmousedown`,`onmouseup`,`onkeydown`,`onkeyup`,`onsubmit`,`onchange`,`oninput`,`onfocus`,`onblur`].some(t=>e.hasAttribute(t)))return!0}catch{}return!!(M(e)||u.get(e)?.scrollable)}function P(e,t,n,r){if(!e.isInteractive)return!1;let i=!1;return i=r?!!N(t):!0,i&&(e.isInViewport=E(t,s),(e.isInViewport||s===-1)&&(e.highlightIndex=l++,a))?(o>=0?o===e.highlightIndex&&y(t,e.highlightIndex,n):y(t,e.highlightIndex,n),!0):!1}function F(e,t=null,n=!1){if(!e||e.id===v||e.nodeType!==Node.ELEMENT_NODE&&e.nodeType!==Node.TEXT_NODE||!e||e.id===v||e.dataset?.browserUseIgnore===`true`||e.dataset?.pageAgentIgnore===`true`||e.getAttribute&&e.getAttribute(`aria-hidden`)===`true`)return null;if(e===document.body){let n={tagName:`body`,attributes:{},xpath:`/body`,children:[]};for(let r of e.childNodes){let e=F(r,t,!1);e&&n.children.push(e)}let r=`${_.current++}`;return g[r]=n,r}if(e.nodeType!==Node.ELEMENT_NODE&&e.nodeType!==Node.TEXT_NODE)return null;if(e.nodeType===Node.TEXT_NODE){let t=e.textContent?.trim();if(!t)return null;let n=e.parentElement;if(!n||n.tagName.toLowerCase()===`script`)return null;let r=`${_.current++}`;return g[r]={type:`TEXT_NODE`,text:t,isVisible:x(e)},r}if(e.nodeType===Node.ELEMENT_NODE&&!S(e))return null;if(s!==-1&&!e.shadowRoot){let t=p(e),n=m(e),r=n&&(n.position===`fixed`||n.position===`sticky`),i=e.offsetWidth>0||e.offsetHeight>0;if(!t||!r&&!i&&(t.bottom<-s||t.top>window.innerHeight+s||t.right<-s||t.left>window.innerWidth+s))return null}let r={tagName:e.tagName.toLowerCase(),attributes:{},children:[]};if(k(e)||e.tagName.toLowerCase()===`iframe`||e.tagName.toLowerCase()===`body`){let t=e.getAttributeNames?.()||[];for(let n of t){let t=e.getAttribute(n);r.attributes[n]=t}e.tagName.toLowerCase()===`input`&&(e.type===`checkbox`||e.type===`radio`)&&(r.attributes.checked=e.checked?`true`:`false`)}let i=!1;if(e.nodeType===Node.ELEMENT_NODE&&(r.isVisible=C(e),r.isVisible)){r.isTopElement=T(e);let a=e.getAttribute(`role`),o=a===`menu`||a===`menubar`||a===`listbox`;if((r.isTopElement||o)&&(r.isInteractive=w(e),i=P(r,e,t,n),r.ref=e,r.isInteractive&&Object.keys(r.attributes).length===0)){let t=e.getAttributeNames?.()||[];for(let n of t){let t=e.getAttribute(n);r.attributes[n]=t}}}if(e.tagName){let a=e.tagName.toLowerCase();if(a===`iframe`)try{let t=e.contentDocument||e.contentWindow?.document;if(t)for(let n of t.childNodes){let t=F(n,e,!1);t&&r.children.push(t)}}catch(e){console.warn(`Unable to access iframe:`,e)}else if(e.isContentEditable||e.getAttribute(`contenteditable`)===`true`||e.id===`tinymce`||e.classList.contains(`mce-content-body`)||a===`body`&&e.getAttribute(`data-id`)?.startsWith(`mce_`))for(let n of e.childNodes){let e=F(n,t,i);e&&r.children.push(e)}else{if(e.shadowRoot){r.shadowRoot=!0;for(let n of e.shadowRoot.childNodes){let e=F(n,t,i);e&&r.children.push(e)}}for(let a of e.childNodes){let e=F(a,t,i||n);e&&r.children.push(e)}}}if(r.tagName===`a`&&r.children.length===0&&!r.attributes.href){let t=p(e);if(!(t&&t.width>0&&t.height>0||e.offsetWidth>0||e.offsetHeight>0))return null}r.extra=u.get(e)||null;let a=`${_.current++}`;return g[a]=r,a}let I=F(document.body);return f.clearCache(),{rootId:I,map:g}},dom_exports=__exportAll({cleanUpHighlights:()=>cleanUpHighlights,flatTreeToString:()=>flatTreeToString,getAllTextTillNextClickableElement:()=>getAllTextTillNextClickableElement,getElementTextMap:()=>getElementTextMap,getFlatTree:()=>getFlatTree,getSelectorMap:()=>getSelectorMap,resolveViewportExpansion:()=>resolveViewportExpansion}),DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(e){return e??DEFAULT_VIEWPORT_EXPANSION}var SEMANTIC_TAGS=new Set([`nav`,`menu`,`header`,`footer`,`aside`,`dialog`]),newElementsCache=new WeakMap;function getFlatTree(e){let t=resolveViewportExpansion(e.viewportExpansion),n=[];for(let t of e.interactiveBlacklist||[])typeof t==`function`?n.push(t()):n.push(t);let r=[];for(let t of e.interactiveWhitelist||[])typeof t==`function`?r.push(t()):r.push(t);let i=dom_tree_default({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:t,interactiveBlacklist:n,interactiveWhitelist:r,highlightOpacity:e.highlightOpacity??0,highlightLabelOpacity:e.highlightLabelOpacity??.1}),a=window.location.href;for(let e in i.map){let t=i.map[e];if(t.isInteractive&&t.ref){let e=t.ref;newElementsCache.has(e)||(newElementsCache.set(e,a),t.isNew=!0)}}return i}var globRegexCache=new Map;function globToRegex(e){let t=globRegexCache.get(e);if(!t){let n=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`);t=RegExp(`^${n.replace(/\*/g,`.*`)}$`),globRegexCache.set(e,t)}return t}function matchAttributes(e,t){let n={};for(let r of t)if(r.includes(`*`)){let t=globToRegex(r);for(let r of Object.keys(e))t.test(r)&&e[r].trim()&&(n[r]=e[r].trim())}else{let t=e[r];t&&t.trim()&&(n[r]=t.trim())}return n}function flatTreeToString(e,t=[],n=!1){let r=[`title`,`type`,`checked`,`name`,`role`,`value`,`placeholder`,`data-date-format`,`alt`,`aria-label`,`aria-expanded`,`data-state`,`aria-checked`,`id`,`for`,`target`,`aria-haspopup`,`aria-controls`,`aria-owns`,`contenteditable`],i=[...t,...r],a=(e,t)=>e.length>t?e.substring(0,t)+`...`:e,o=t=>{let n=e.map[t];if(!n)return null;if(n.type===`TEXT_NODE`){let e=n;return{type:`text`,text:e.text,isVisible:e.isVisible,parent:null,children:[]}}else{let e=n,t=[];if(e.children)for(let n of e.children){let e=o(n);e&&(e.parent=null,t.push(e))}return{type:`element`,tagName:e.tagName,attributes:e.attributes??{},isVisible:e.isVisible??!1,isInteractive:e.isInteractive??!1,isTopElement:e.isTopElement??!1,isNew:e.isNew??!1,highlightIndex:e.highlightIndex,parent:null,children:t,extra:e.extra??{}}}},s=(e,t=null)=>{e.parent=t;for(let t of e.children)s(t,e)},c=o(e.rootId);if(!c)return``;s(c);let l=e=>{let t=e.parent;for(;t;){if(t.type===`element`&&t.highlightIndex!==void 0)return!0;t=t.parent}return!1},u=(e,t,r)=>{let o=t,s=` `.repeat(t);if(e.type===`element`){let t=n&&e.tagName&&SEMANTIC_TAGS.has(e.tagName);if(e.highlightIndex!==void 0){o+=1;let t=getAllTextTillNextClickableElement(e),n=``;if(i.length>0&&e.attributes){let r=matchAttributes(e.attributes,i),o=Object.keys(r);if(o.length>1){let e=new Set,t={};for(let n of o){let i=r[n];i.length>5&&(i in t?e.add(n):t[i]=n)}for(let t of e)delete r[t]}r.role===e.tagName&&delete r.role;for(let e of[`aria-label`,`placeholder`,`title`])r[e]&&r[e].toLowerCase().trim()===t.toLowerCase().trim()&&delete r[e];Object.keys(r).length>0&&(n=Object.entries(r).map(([e,t])=>`${e}=${a(t,20)}`).join(` `))}let c=`${s}${e.isNew?`*[${e.highlightIndex}]`:`[${e.highlightIndex}]`}<${e.tagName??``}`;if(n&&(c+=` ${n}`),e.extra&&e.extra.scrollable){let t=``;e.extra.scrollData?.left&&(t+=`left=${e.extra.scrollData.left}, `),e.extra.scrollData?.top&&(t+=`top=${e.extra.scrollData.top}, `),e.extra.scrollData?.right&&(t+=`right=${e.extra.scrollData.right}, `),e.extra.scrollData?.bottom&&(t+=`bottom=${e.extra.scrollData.bottom}`),c+=` data-scrollable="${t}"`}if(t){let e=t.trim();n||(c+=` `),c+=`>${e}`}else n||(c+=` `);c+=` />`,r.push(c)}let c=t&&e.highlightIndex===void 0,l=c?r.length:-1;c&&(r.push(`${s}<${e.tagName}>`),o+=1);for(let t of e.children)u(t,o,r);c&&(r.length===l+1?r.pop():r.push(`${s}</${e.tagName}>`))}else if(e.type===`text`){if(l(e))return;e.parent&&e.parent.type===`element`&&e.parent.isVisible&&e.parent.isTopElement&&r.push(`${s}${e.text??``}`)}},d=[];return u(c,0,d),d.join(`
|
|
246
245
|
`)}var getAllTextTillNextClickableElement=(e,t=-1)=>{let n=[],r=(i,a)=>{if(!(t!==-1&&a>t)&&!(i.type===`element`&&i!==e&&i.highlightIndex!==void 0)){if(i.type===`text`&&i.text)n.push(i.text);else if(i.type===`element`)for(let e of i.children)r(e,a+1)}};return r(e,0),n.join(`
|
|
247
246
|
`).trim()};function getSelectorMap(e){let t=new Map,n=Object.keys(e.map);for(let r of n){let n=e.map[r];n.isInteractive&&typeof n.highlightIndex==`number`&&t.set(n.highlightIndex,n)}return t}function getElementTextMap(e){let t=e.split(`
|
|
248
247
|
`).map(e=>e.trim()).filter(e=>e.length>0),n=new Map;for(let e of t){let t=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(e);if(t){let r=parseInt(t[1],10);n.set(r,e)}}return n}function cleanUpHighlights(){let e=window._highlightCleanupFunctions||[];for(let t of e)typeof t==`function`&&t();window._highlightCleanupFunctions=[]}window.addEventListener(`popstate`,()=>{cleanUpHighlights()}),window.addEventListener(`hashchange`,()=>{cleanUpHighlights()}),window.addEventListener(`beforeunload`,()=>{cleanUpHighlights()});var navigation=window.navigation;if(navigation&&typeof navigation.addEventListener==`function`)navigation.addEventListener(`navigate`,()=>{cleanUpHighlights()});else{let e=window.location.href;setInterval(()=>{window.location.href!==e&&(e=window.location.href,cleanUpHighlights())},500)}function getPageInfo(){let e=window.innerWidth,t=window.innerHeight,n=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),r=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),i=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,a=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,o=Math.max(0,r-(window.innerHeight+a)),s=Math.max(0,n-(window.innerWidth+i));return{viewport_width:e,viewport_height:t,page_width:n,page_height:r,scroll_x:i,scroll_y:a,pixels_above:a,pixels_below:o,pages_above:t>0?a/t:0,pages_below:t>0?o/t:0,total_pages:t>0?r/t:0,current_page_position:a/Math.max(1,r-t),pixels_left:i,pixels_right:s}}function patchReact(e){let t=document.querySelectorAll(`[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root`);for(let e of t)e.setAttribute(`data-page-agent-not-interactive`,`true`)}function computeBorderGeometry(e,t,n,r){let i=Math.max(1,Math.min(e,t)),a=Math.min(Math.min(n,20)+r,i),o=Math.min(a,Math.floor(e/2)),s=Math.min(a,Math.floor(t/2)),c=t=>t/e*2-1,l=e=>e/t*2-1,u=0,d=e,f=0,p=t,m=o,h=e-o,g=s,_=t-s,v=c(0),y=c(d),b=l(0),x=l(p),S=c(m),C=c(h),w=l(g),T=l(_),E=0,D=0,O=1,k=1,A=o/e,j=1-o/e,M=s/t,N=1-s/t;return{positions:new Float32Array([v,b,y,b,v,w,v,w,y,b,y,w,v,T,y,T,v,x,v,x,y,T,y,x,v,w,S,w,v,T,v,T,S,w,S,T,C,w,y,w,C,T,C,T,y,w,y,T]),uvs:new Float32Array([0,0,1,0,0,M,0,M,1,0,1,M,0,N,1,N,0,1,0,1,1,N,1,1,0,M,A,M,0,N,0,N,A,M,A,N,j,M,1,M,j,N,j,N,1,M,1,N])}}function compileShader(e,t,n){let r=e.createShader(t);if(!r)throw Error(`Failed to create shader`);if(e.shaderSource(r,n),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){let t=e.getShaderInfoLog(r)||`Unknown shader error`;throw e.deleteShader(r),Error(t)}return r}function createProgram(e,t,n){let r=compileShader(e,e.VERTEX_SHADER,t),i=compileShader(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error(`Failed to create program`);if(e.attachShader(a,r),e.attachShader(a,i),e.linkProgram(a),!e.getProgramParameter(a,e.LINK_STATUS)){let t=e.getProgramInfoLog(a)||`Unknown link error`;throw e.deleteProgram(a),e.deleteShader(r),e.deleteShader(i),Error(t)}return e.deleteShader(r),e.deleteShader(i),a}function parseColor(e){let t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!t)throw Error(`Invalid color format: ${e}`);let[,n,r,i]=t;return[parseInt(n)/255,parseInt(r)/255,parseInt(i)/255]}var fragmentShaderSource,vertexShaderSource,DEFAULT_COLORS,Motion,init_Motion=__esmMin((()=>{fragmentShaderSource=`#version 300 es
|
|
@@ -355,7 +354,7 @@ out vec2 vUV;
|
|
|
355
354
|
void main() {
|
|
356
355
|
vUV = aUV;
|
|
357
356
|
gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
358
|
-
}`,DEFAULT_COLORS=[`rgb(57, 182, 255)`,`rgb(189, 69, 251)`,`rgb(255, 87, 51)`,`rgb(255, 214, 0)`],Motion=class{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(e={}){this.options={width:e.width??600,height:e.height??600,ratio:e.ratio??window.devicePixelRatio??1,borderWidth:e.borderWidth??8,glowWidth:e.glowWidth??200,borderRadius:e.borderRadius??8,mode:e.mode??`light`,...e},this.canvas=document.createElement(`canvas`),this.options.classNames&&(this.canvas.className=this.options.classNames),this.options.styles&&Object.assign(this.canvas.style,this.options.styles),this.canvas.style.display=`block`,this.canvas.style.transformOrigin=`center`,this.canvas.style.pointerEvents=`none`,this.element=this.canvas,this.setupGL(),this.options.skipGreeting||this.greet()}start(){if(this.disposed)throw Error(`Motion instance has been disposed.`);if(this.running)return;if(!this.glr){console.error(`WebGL resources are not initialized.`);return}this.running=!0,this.startTime=performance.now(),this.resize(this.options.width??600,this.options.height??600,this.options.ratio),this.glr.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.glr.gl.useProgram(this.glr.program),this.glr.gl.uniform2f(this.glr.uResolution,this.canvas.width,this.canvas.height),this.checkGLError(this.glr.gl,`start: after initial setup`);let e=()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(e);let t=performance.now();if(t-this.lastTime<1e3/32)return;this.lastTime=t;let n=(t-this.startTime)*.001;this.render(n)};this.rafId=requestAnimationFrame(e)}pause(){if(this.disposed)throw Error(`Motion instance has been disposed.`);this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId)}dispose(){if(this.disposed)return;this.disposed=!0,this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId);let{gl:e,vao:t,positionBuffer:n,uvBuffer:r,program:i}=this.glr;t&&e.deleteVertexArray(t),n&&e.deleteBuffer(n),r&&e.deleteBuffer(r),e.deleteProgram(i),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(e,t,n){if(this.disposed)throw Error(`Motion instance has been disposed.`);if(this.options.width=e,this.options.height=t,n&&(this.options.ratio=n),!this.running)return;let{gl:r,program:i,vao:a,positionBuffer:o,uvBuffer:s,uResolution:c}=this.glr,l=n??this.options.ratio??window.devicePixelRatio??1,u=Math.max(1,Math.floor(e*l)),d=Math.max(1,Math.floor(t*l));this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,(this.canvas.width!==u||this.canvas.height!==d)&&(this.canvas.width=u,this.canvas.height=d),r.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(r,`resize: after viewport setup`);let{positions:f,uvs:p}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*l,this.options.glowWidth*l);r.bindVertexArray(a),r.bindBuffer(r.ARRAY_BUFFER,o),r.bufferData(r.ARRAY_BUFFER,f,r.STATIC_DRAW);let m=r.getAttribLocation(i,`aPosition`);r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,0),this.checkGLError(r,`resize: after position buffer update`),r.bindBuffer(r.ARRAY_BUFFER,s),r.bufferData(r.ARRAY_BUFFER,p,r.STATIC_DRAW);let h=r.getAttribLocation(i,`aUV`);r.enableVertexAttribArray(h),r.vertexAttribPointer(h,2,r.FLOAT,!1,0,0),this.checkGLError(r,`resize: after UV buffer update`),r.useProgram(i),r.uniform2f(c,this.canvas.width,this.canvas.height),r.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*l),r.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*l),r.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*l),this.checkGLError(r,`resize: after uniform updates`);let g=performance.now();this.lastTime=g;let _=(g-this.startTime)*.001;this.render(_)}autoResize(e){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{let t=e.getBoundingClientRect();this.resize(t.width,t.height)}),this.observer.observe(e)}fadeIn(){if(this.disposed)throw Error(`Motion instance has been disposed.`);return new Promise((e,t)=>{let n=this.canvas.animate([{opacity:0,transform:`scale(1.2)`},{opacity:1,transform:`scale(1)`}],{duration:300,easing:`ease-out`,fill:`forwards`});n.onfinish=()=>e(),n.oncancel=()=>t(`canceled`)})}fadeOut(){if(this.disposed)throw Error(`Motion instance has been disposed.`);return new Promise((e,t)=>{let n=this.canvas.animate([{opacity:1,transform:`scale(1)`},{opacity:0,transform:`scale(1.2)`}],{duration:300,easing:`ease-in`,fill:`forwards`});n.onfinish=()=>e(),n.oncancel=()=>t(`canceled`)})}checkGLError(e,t){let n=e.getError();if(n!==e.NO_ERROR){for(console.group(`🔴 WebGL Error in ${t}`);n!==e.NO_ERROR;){let t=this.getGLErrorName(e,n);console.error(`${t} (0x${n.toString(16)})`),n=e.getError()}console.groupEnd()}}getGLErrorName(e,t){switch(t){case e.INVALID_ENUM:return`INVALID_ENUM`;case e.INVALID_VALUE:return`INVALID_VALUE`;case e.INVALID_OPERATION:return`INVALID_OPERATION`;case e.INVALID_FRAMEBUFFER_OPERATION:return`INVALID_FRAMEBUFFER_OPERATION`;case e.OUT_OF_MEMORY:return`OUT_OF_MEMORY`;case e.CONTEXT_LOST_WEBGL:return`CONTEXT_LOST_WEBGL`;default:return`UNKNOWN_ERROR`}}setupGL(){let e=this.canvas.getContext(`webgl2`,{antialias:!1,alpha:!0});if(!e)throw Error(`WebGL2 is required but not available.`);let t=createProgram(e,vertexShaderSource,fragmentShaderSource);this.checkGLError(e,`setupGL: after createProgram`);let n=e.createVertexArray();e.bindVertexArray(n),this.checkGLError(e,`setupGL: after VAO creation`);let{positions:r,uvs:i}=computeBorderGeometry(this.canvas.width||2,this.canvas.height||2,this.options.borderWidth,this.options.glowWidth),a=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,a),e.bufferData(e.ARRAY_BUFFER,r,e.STATIC_DRAW);let o=e.getAttribLocation(t,`aPosition`);e.enableVertexAttribArray(o),e.vertexAttribPointer(o,2,e.FLOAT,!1,0,0),this.checkGLError(e,`setupGL: after position buffer setup`);let s=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,s),e.bufferData(e.ARRAY_BUFFER,i,e.STATIC_DRAW);let c=e.getAttribLocation(t,`aUV`);e.enableVertexAttribArray(c),e.vertexAttribPointer(c,2,e.FLOAT,!1,0,0),this.checkGLError(e,`setupGL: after UV buffer setup`);let l=e.getUniformLocation(t,`uResolution`),u=e.getUniformLocation(t,`uTime`),d=e.getUniformLocation(t,`uBorderWidth`),f=e.getUniformLocation(t,`uGlowWidth`),p=e.getUniformLocation(t,`uBorderRadius`),m=e.getUniformLocation(t,`uColors`),h=e.getUniformLocation(t,`uGlowExponent`),g=e.getUniformLocation(t,`uGlowFactor`);e.useProgram(t),e.uniform1f(d,this.options.borderWidth),e.uniform1f(f,this.options.glowWidth),e.uniform1f(p,this.options.borderRadius),this.options.mode===`dark`?(e.uniform1f(h,2),e.uniform1f(g,1.8)):(e.uniform1f(h,1),e.uniform1f(g,1));let _=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let n=0;n<_.length;n++)e.uniform3f(e.getUniformLocation(t,`uColors[${n}]`),..._[n]);this.checkGLError(e,`setupGL: after uniform setup`),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),this.glr={gl:e,program:t,vao:n,positionBuffer:a,uvBuffer:s,uResolution:l,uTime:u,uBorderWidth:d,uGlowWidth:f,uBorderRadius:p,uColors:m}}render(e){if(!this.glr)return;let{gl:t,program:n,vao:r,uTime:i}=this.glr;t.useProgram(n),t.bindVertexArray(r),t.uniform1f(i,e),t.disable(t.DEPTH_TEST),t.disable(t.CULL_FACE),t.disable(t.BLEND),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLES,0,24),this.checkGLError(t,`render: after draw call`),t.bindVertexArray(null)}greet(){console.log(`%c🌈 ai-motion 0.4.8 🌈`,`background: linear-gradient(90deg, #39b6ff, #bd45fb, #ff5733, #ffd600); color: white; text-shadow: 0 0 2px rgba(0, 0, 0, 0.2); font-weight: bold; font-size: 1em; padding: 2px 12px; border-radius: 6px;`)}}}));function hasDarkModeClass(){let e=[`dark`,`dark-mode`,`theme-dark`,`night`,`night-mode`],t=document.documentElement,n=document.body||document.documentElement;for(let r of e)if(t.classList.contains(r)||n?.classList.contains(r))return!0;return!!t.getAttribute(`data-theme`)?.toLowerCase().includes(`dark`)}function parseRgbColor(e){let t=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(e);return t?{r:parseInt(t[1]),g:parseInt(t[2]),b:parseInt(t[3])}:null}function isColorDark(e,t=128){if(!e||e===`transparent`||e.startsWith(`rgba(0, 0, 0, 0)`))return!1;let n=parseRgbColor(e);return n?.299*n.r+.587*n.g+.114*n.b<t:!1}function isBackgroundDark(){let e=window.getComputedStyle(document.documentElement),t=window.getComputedStyle(document.body||document.documentElement),n=e.backgroundColor,r=t.backgroundColor;return isColorDark(r)?!0:r===`transparent`||r.startsWith(`rgba(0, 0, 0, 0)`)?isColorDark(n):!1}function isPageDark(){try{return!!(hasDarkModeClass()||isBackgroundDark())}catch(e){return console.warn(`Error determining if page is dark:`,e),!1}}var init_checkDarkMode=__esmMin((()=>{})),wrapper$1,visible,SimulatorMask_module_default,init_SimulatorMask_module=__esmMin((()=>{wrapper$1=`_wrapper_1ooyb_1`,visible=`_visible_1ooyb_11`,SimulatorMask_module_default={wrapper:wrapper$1,visible}})),cursor,cursorBorder,cursorFilling,cursorRipple,clicking,cursor_module_default,init_cursor_module=__esmMin((()=>{cursor=`_cursor_1dgwb_2`,cursorBorder=`_cursorBorder_1dgwb_10`,cursorFilling=`_cursorFilling_1dgwb_25`,cursorRipple=`_cursorRipple_1dgwb_39`,clicking=`_clicking_1dgwb_57`,cursor_module_default={cursor,cursorBorder,cursorFilling,cursorRipple,clicking,"cursor-ripple":`_cursor-ripple_1dgwb_1`}})),SimulatorMask_exports=__exportAll({SimulatorMask:()=>SimulatorMask}),SimulatorMask,init_SimulatorMask=__esmMin((()=>{init_Motion(),init_checkDarkMode(),init_SimulatorMask_module(),init_cursor_module(),SimulatorMask=class extends EventTarget{shown=!1;wrapper=document.createElement(`div`);motion=null;#e=!1;#t=document.createElement(`div`);#n=0;#r=0;#i=0;#a=0;constructor(){super(),this.wrapper.id=`page-agent-runtime_simulator-mask`,this.wrapper.className=SimulatorMask_module_default.wrapper,this.wrapper.setAttribute(`data-browser-use-ignore`,`true`),this.wrapper.setAttribute(`data-page-agent-ignore`,`true`);try{let e=new Motion({mode:isPageDark()?`dark`:`light`,styles:{position:`absolute`,inset:`0`}});this.motion=e,this.wrapper.appendChild(e.element),e.autoResize(this.wrapper)}catch(e){console.warn(`[SimulatorMask] Motion overlay unavailable:`,e)}this.wrapper.addEventListener(`click`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mousedown`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mouseup`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mousemove`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`wheel`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`keydown`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`keyup`,e=>{e.stopPropagation(),e.preventDefault()}),this.#o(),document.body.appendChild(this.wrapper),this.#s();let e=e=>{let{x:t,y:n}=e.detail;this.setCursorPosition(t,n)},t=()=>{this.triggerClickAnimation()},n=()=>{this.wrapper.style.pointerEvents=`none`},r=()=>{this.wrapper.style.pointerEvents=`auto`};window.addEventListener(`PageAgent::MovePointerTo`,e),window.addEventListener(`PageAgent::ClickPointer`,t),window.addEventListener(`PageAgent::EnablePassThrough`,n),window.addEventListener(`PageAgent::DisablePassThrough`,r),this.addEventListener(`dispose`,()=>{window.removeEventListener(`PageAgent::MovePointerTo`,e),window.removeEventListener(`PageAgent::ClickPointer`,t),window.removeEventListener(`PageAgent::EnablePassThrough`,n),window.removeEventListener(`PageAgent::DisablePassThrough`,r)})}#o(){this.#t.className=cursor_module_default.cursor;let e=document.createElement(`div`);e.className=cursor_module_default.cursorRipple,this.#t.appendChild(e);let t=document.createElement(`div`);t.className=cursor_module_default.cursorFilling,this.#t.appendChild(t);let n=document.createElement(`div`);n.className=cursor_module_default.cursorBorder,this.#t.appendChild(n),this.wrapper.appendChild(this.#t)}#s(){if(this.#e)return;let e=this.#n+(this.#i-this.#n)*.2,t=this.#r+(this.#a-this.#r)*.2,n=Math.abs(e-this.#i);n>0&&(n<2?this.#n=this.#i:this.#n=e,this.#t.style.left=`${this.#n}px`);let r=Math.abs(t-this.#a);r>0&&(r<2?this.#r=this.#a:this.#r=t,this.#t.style.top=`${this.#r}px`),requestAnimationFrame(()=>this.#s())}setCursorPosition(e,t){this.#e||(this.#i=e,this.#a=t)}triggerClickAnimation(){this.#e||(this.#t.classList.remove(cursor_module_default.clicking),this.#t.offsetHeight,this.#t.classList.add(cursor_module_default.clicking))}show(){this.shown||this.#e||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.classList.add(SimulatorMask_module_default.visible),this.#n=window.innerWidth/2,this.#r=window.innerHeight/2,this.#i=this.#n,this.#a=this.#r,this.#t.style.left=`${this.#n}px`,this.#t.style.top=`${this.#r}px`)}hide(){!this.shown||this.#e||(this.shown=!1,this.motion?.fadeOut(),this.motion?.pause(),this.#t.classList.remove(cursor_module_default.clicking),setTimeout(()=>{this.wrapper.classList.remove(SimulatorMask_module_default.visible)},800))}dispose(){this.#e=!0,console.log(`dispose SimulatorMask`),this.motion?.dispose(),this.wrapper.remove(),this.dispatchEvent(new Event(`dispose`))}}})),PageController=class extends EventTarget{config;flatTree=null;selectorMap=new Map;elementTextMap=new Map;simplifiedHTML=`<EMPTY>`;lastTimeUpdate=0;isIndexed=!1;mask=null;maskReady=null;constructor(e={}){super(),this.config=e,patchReact(this),e.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{let{SimulatorMask:e}=await Promise.resolve().then(()=>(init_SimulatorMask(),SimulatorMask_exports));this.mask=new e})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){let e=window.location.href,t=document.title,n=getPageInfo(),r=resolveViewportExpansion(this.config.viewportExpansion);await this.updateTree();let i=this.simplifiedHTML;return{url:e,title:t,header:`${`Current Page: [${t}](${e})`}\n${`Page info: ${n.viewport_width}x${n.viewport_height}px viewport, ${n.page_width}x${n.page_height}px total page size, ${n.pages_above.toFixed(1)} pages above, ${n.pages_below.toFixed(1)} pages below, ${n.total_pages.toFixed(1)} total pages, at ${(n.current_page_position*100).toFixed(0)}% of page`}\n\n${r===-1?`Interactive elements from top layer of the current page (full page):`:`Interactive elements from top layer of the current page inside the viewport:`}\n\n${n.pixels_above>4&&r!==-1?`... ${n.pixels_above} pixels above (${n.pages_above.toFixed(1)} pages) - scroll to see more ...`:`[Start of page]`}`,content:i,footer:n.pixels_below>4&&r!==-1?`... ${n.pixels_below} pixels below (${n.pages_below.toFixed(1)} pages) - scroll to see more ...`:`[End of page]`}}async updateTree(){this.dispatchEvent(new Event(`beforeUpdate`)),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents=`none`),cleanUpHighlights();let e=[...this.config.interactiveBlacklist||[],...Array.from(document.querySelectorAll(`[data-page-agent-not-interactive]`))];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:e}),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.includeAttributes,this.config.keepSemanticTags),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.mask&&(this.mask.wrapper.style.pointerEvents=`auto`),this.dispatchEvent(new Event(`afterUpdate`)),this.simplifiedHTML}async cleanUpHighlights(){console.log(`[PageController] cleanUpHighlights`),cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw Error(`DOM tree not indexed yet. Can not perform actions on elements.`)}async clickElement(e){try{this.assertIndexed();let t=getElementByIndex(this.selectorMap,e),n=this.elementTextMap.get(e);return await clickElement(t),isAnchorElement(t)&&t.target===`_blank`?{success:!0,message:`✅ Clicked element (${n??e}). ⚠️ Link opened in a new tab.`}:{success:!0,message:`✅ Clicked element (${n??e}).`}}catch(e){return{success:!1,message:`❌ Failed to click element: ${e}`}}}async inputText(e,t){try{this.assertIndexed();let n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return await inputTextElement(n,t),{success:!0,message:`✅ Input text (${t}) into element (${r??e}).`}}catch(e){return{success:!1,message:`❌ Failed to input text: ${e}`}}}async selectOption(e,t){try{this.assertIndexed();let n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return await selectOptionElement(n,t),{success:!0,message:`✅ Selected option (${t}) in element (${r??e}).`}}catch(e){return{success:!1,message:`❌ Failed to select option: ${e}`}}}async scroll(e){try{let{down:t,numPages:n,pixels:r,index:i}=e;return this.assertIndexed(),{success:!0,message:await scrollVertically((r??n*window.innerHeight)*(t?1:-1),i===void 0?null:getElementByIndex(this.selectorMap,i))}}catch(e){return{success:!1,message:`❌ Failed to scroll: ${e}`}}}async scrollHorizontally(e){try{let{right:t,pixels:n,index:r}=e;return this.assertIndexed(),{success:!0,message:await scrollHorizontally(n*(t?1:-1),r===void 0?null:getElementByIndex(this.selectorMap,r))}}catch(e){return{success:!1,message:`❌ Failed to scroll horizontally: ${e}`}}}async executeJavascript(script){try{const asyncFunction=eval(`(async () => { ${script} })`),result=await asyncFunction();return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(e){return{success:!1,message:`❌ Error executing JavaScript: ${e}`}}}async showMask(){await this.maskReady,this.mask?.show()}async hideMask(){await this.maskReady,this.mask?.hide()}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML=`<EMPTY>`,this.isIndexed=!1,this.mask?.dispose(),this.mask=null}},enUS={ui:{panel:{ready:`Ready`,thinking:`Thinking...`,taskInput:`Enter new task, describe steps in detail, press Enter to submit`,userAnswerPrompt:`Please answer the question above, press Enter to submit`,taskTerminated:`Task terminated`,taskCompleted:`Task completed`,userAnswer:`User answer: {{input}}`,question:`Question: {{question}}`,waitingPlaceholder:`Waiting for task to start...`,stop:`Stop`,close:`Close`,expand:`Expand history`,collapse:`Collapse history`,step:`Step {{number}}`},tools:{clicking:`Clicking element [{{index}}]...`,inputting:`Inputting text to element [{{index}}]...`,selecting:`Selecting option "{{text}}"...`,scrolling:`Scrolling page...`,waiting:`Waiting {{seconds}} seconds...`,askingUser:`Asking user...`,done:`Task done`,clicked:`🖱️ Clicked element [{{index}}]`,inputted:`⌨️ Inputted text "{{text}}"`,selected:`☑️ Selected option "{{text}}"`,scrolled:`🛞 Page scrolled`,waited:`⌛️ Wait completed`,executing:`Executing {{toolName}}...`,resultSuccess:`success`,resultFailure:`failed`,resultError:`error`},errors:{elementNotFound:`No interactive element found at index {{index}}`,taskRequired:`Task description is required`,executionFailed:`Task execution failed`,notInputElement:`Element is not an input or textarea`,notSelectElement:`Element is not a select element`,optionNotFound:`Option "{{text}}" not found`}}},zhCN={ui:{panel:{ready:`准备就绪`,thinking:`正在思考...`,taskInput:`输入新任务,详细描述步骤,回车提交`,userAnswerPrompt:`请回答上面问题,回车提交`,taskTerminated:`任务已终止`,taskCompleted:`任务结束`,userAnswer:`用户回答: {{input}}`,question:`询问: {{question}}`,waitingPlaceholder:`等待任务开始...`,stop:`终止`,close:`关闭`,expand:`展开历史`,collapse:`收起历史`,step:`步骤 {{number}}`},tools:{clicking:`正在点击元素 [{{index}}]...`,inputting:`正在输入文本到元素 [{{index}}]...`,selecting:`正在选择选项 "{{text}}"...`,scrolling:`正在滚动页面...`,waiting:`等待 {{seconds}} 秒...`,askingUser:`正在询问用户...`,done:`结束任务`,clicked:`🖱️ 已点击元素 [{{index}}]`,inputted:`⌨️ 已输入文本 "{{text}}"`,selected:`☑️ 已选择选项 "{{text}}"`,scrolled:`🛞 页面滚动完成`,waited:`⌛️ 等待完成`,executing:`正在执行 {{toolName}}...`,resultSuccess:`成功`,resultFailure:`失败`,resultError:`错误`},errors:{elementNotFound:`未找到索引为 {{index}} 的交互元素`,taskRequired:`任务描述不能为空`,executionFailed:`任务执行失败`,notInputElement:`元素不是输入框或文本域`,notSelectElement:`元素不是选择框`,optionNotFound:`未找到选项 "{{text}}"`}}},locales={"en-US":enUS,"zh-CN":zhCN},I18n=class{language;translations;constructor(e=`en-US`){this.language=e in locales?e:`en-US`,this.translations=locales[this.language]}t(e,t){let n=this.getNestedValue(this.translations,e);return n?t?this.interpolate(n,t):n:(console.warn(`Translation key "${e}" not found for language "${this.language}"`),e)}getNestedValue(e,t){return t.split(`.`).reduce((e,t)=>e?.[t],e)}interpolate(e,t){return e.replace(/\{\{(\w+)\}\}/g,(e,n)=>t[n]==null?e:t[n].toString())}getLanguage(){return this.language}};function truncate(e,t){return e.length>t?e.substring(0,t)+`...`:e}function escapeHtml(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}var wrapper=`_wrapper_1tu05_1`,background=`_background_1tu05_39`,header=`_header_1tu05_99`,pulse=`_pulse_1tu05_1`,retryPulse=`_retryPulse_1tu05_1`,statusTextFadeOut=`_statusTextFadeOut_1tu05_1`,statusTextFadeIn=`_statusTextFadeIn_1tu05_1`,statusSection=`_statusSection_1tu05_121`,indicator=`_indicator_1tu05_128`,thinking=`_thinking_1tu05_137`,tool_executing=`_tool_executing_1tu05_142`,retry=`_retry_1tu05_147`,completed=`_completed_1tu05_153`,input=`_input_1tu05_154`,output=`_output_1tu05_155`,error=`_error_1tu05_160`,statusText=`_statusText_1tu05_166`,fadeOut=`_fadeOut_1tu05_178`,fadeIn=`_fadeIn_1tu05_182`,controls=`_controls_1tu05_188`,controlButton=`_controlButton_1tu05_193`,stopButton=`_stopButton_1tu05_212`,historySectionWrapper=`_historySectionWrapper_1tu05_246`,shimmer=`_shimmer_1tu05_1`,celebrate=`_celebrate_1tu05_1`,expanded=`_expanded_1tu05_278`,historySection=`_historySection_1tu05_246`,historyItem=`_historyItem_1tu05_297`,observation=`_observation_1tu05_355`,question=`_question_1tu05_360`,doneSuccess=`_doneSuccess_1tu05_366`,historyContent=`_historyContent_1tu05_402`,statusIcon=`_statusIcon_1tu05_403`,doneError=`_doneError_1tu05_412`,reflectionLines=`_reflectionLines_1tu05_462`,historyMeta=`_historyMeta_1tu05_469`,inputSectionWrapper=`_inputSectionWrapper_1tu05_539`,hidden=`_hidden_1tu05_562`,inputSection=`_inputSection_1tu05_539`,taskInput=`_taskInput_1tu05_573`,Panel_module_default={wrapper,"mask-running":`_mask-running_1tu05_1`,background,header,pulse,retryPulse,statusTextFadeOut,statusTextFadeIn,statusSection,indicator,thinking,tool_executing,retry,completed,input,output,error,statusText,fadeOut,fadeIn,controls,controlButton,stopButton,historySectionWrapper,shimmer,celebrate,expanded,historySection,historyItem,observation,question,doneSuccess,historyContent,statusIcon,doneError,reflectionLines,historyMeta,inputSectionWrapper,hidden,inputSection,taskInput};function createCard({icon:e,content:t,meta:n,type:r}){let i=r?Panel_module_default[r]:``,a=Array.isArray(t)?`<div class="${Panel_module_default.reflectionLines}">${t.map(e=>`<span>${escapeHtml(e)}</span>`).join(``)}</div>`:`<span>${escapeHtml(t)}</span>`;return`
|
|
357
|
+
}`,DEFAULT_COLORS=[`rgb(57, 182, 255)`,`rgb(189, 69, 251)`,`rgb(255, 87, 51)`,`rgb(255, 214, 0)`],Motion=class{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(e={}){this.options={width:e.width??600,height:e.height??600,ratio:e.ratio??window.devicePixelRatio??1,borderWidth:e.borderWidth??8,glowWidth:e.glowWidth??200,borderRadius:e.borderRadius??8,mode:e.mode??`light`,...e},this.canvas=document.createElement(`canvas`),this.options.classNames&&(this.canvas.className=this.options.classNames),this.options.styles&&Object.assign(this.canvas.style,this.options.styles),this.canvas.style.display=`block`,this.canvas.style.transformOrigin=`center`,this.canvas.style.pointerEvents=`none`,this.element=this.canvas,this.setupGL(),this.options.skipGreeting||this.greet()}start(){if(this.disposed)throw Error(`Motion instance has been disposed.`);if(this.running)return;if(!this.glr){console.error(`WebGL resources are not initialized.`);return}this.running=!0,this.startTime=performance.now(),this.resize(this.options.width??600,this.options.height??600,this.options.ratio),this.glr.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.glr.gl.useProgram(this.glr.program),this.glr.gl.uniform2f(this.glr.uResolution,this.canvas.width,this.canvas.height),this.checkGLError(this.glr.gl,`start: after initial setup`);let e=()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(e);let t=performance.now();if(t-this.lastTime<1e3/32)return;this.lastTime=t;let n=(t-this.startTime)*.001;this.render(n)};this.rafId=requestAnimationFrame(e)}pause(){if(this.disposed)throw Error(`Motion instance has been disposed.`);this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId)}dispose(){if(this.disposed)return;this.disposed=!0,this.running=!1,this.rafId!==null&&cancelAnimationFrame(this.rafId);let{gl:e,vao:t,positionBuffer:n,uvBuffer:r,program:i}=this.glr;t&&e.deleteVertexArray(t),n&&e.deleteBuffer(n),r&&e.deleteBuffer(r),e.deleteProgram(i),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(e,t,n){if(this.disposed)throw Error(`Motion instance has been disposed.`);if(this.options.width=e,this.options.height=t,n&&(this.options.ratio=n),!this.running)return;let{gl:r,program:i,vao:a,positionBuffer:o,uvBuffer:s,uResolution:c}=this.glr,l=n??this.options.ratio??window.devicePixelRatio??1,u=Math.max(1,Math.floor(e*l)),d=Math.max(1,Math.floor(t*l));this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,(this.canvas.width!==u||this.canvas.height!==d)&&(this.canvas.width=u,this.canvas.height=d),r.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(r,`resize: after viewport setup`);let{positions:f,uvs:p}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*l,this.options.glowWidth*l);r.bindVertexArray(a),r.bindBuffer(r.ARRAY_BUFFER,o),r.bufferData(r.ARRAY_BUFFER,f,r.STATIC_DRAW);let m=r.getAttribLocation(i,`aPosition`);r.enableVertexAttribArray(m),r.vertexAttribPointer(m,2,r.FLOAT,!1,0,0),this.checkGLError(r,`resize: after position buffer update`),r.bindBuffer(r.ARRAY_BUFFER,s),r.bufferData(r.ARRAY_BUFFER,p,r.STATIC_DRAW);let h=r.getAttribLocation(i,`aUV`);r.enableVertexAttribArray(h),r.vertexAttribPointer(h,2,r.FLOAT,!1,0,0),this.checkGLError(r,`resize: after UV buffer update`),r.useProgram(i),r.uniform2f(c,this.canvas.width,this.canvas.height),r.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*l),r.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*l),r.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*l),this.checkGLError(r,`resize: after uniform updates`);let g=performance.now();this.lastTime=g;let _=(g-this.startTime)*.001;this.render(_)}autoResize(e){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{let t=e.getBoundingClientRect();this.resize(t.width,t.height)}),this.observer.observe(e)}fadeIn(){if(this.disposed)throw Error(`Motion instance has been disposed.`);return new Promise((e,t)=>{let n=this.canvas.animate([{opacity:0,transform:`scale(1.2)`},{opacity:1,transform:`scale(1)`}],{duration:300,easing:`ease-out`,fill:`forwards`});n.onfinish=()=>e(),n.oncancel=()=>t(`canceled`)})}fadeOut(){if(this.disposed)throw Error(`Motion instance has been disposed.`);return new Promise((e,t)=>{let n=this.canvas.animate([{opacity:1,transform:`scale(1)`},{opacity:0,transform:`scale(1.2)`}],{duration:300,easing:`ease-in`,fill:`forwards`});n.onfinish=()=>e(),n.oncancel=()=>t(`canceled`)})}checkGLError(e,t){let n=e.getError();if(n!==e.NO_ERROR){for(console.group(`🔴 WebGL Error in ${t}`);n!==e.NO_ERROR;){let t=this.getGLErrorName(e,n);console.error(`${t} (0x${n.toString(16)})`),n=e.getError()}console.groupEnd()}}getGLErrorName(e,t){switch(t){case e.INVALID_ENUM:return`INVALID_ENUM`;case e.INVALID_VALUE:return`INVALID_VALUE`;case e.INVALID_OPERATION:return`INVALID_OPERATION`;case e.INVALID_FRAMEBUFFER_OPERATION:return`INVALID_FRAMEBUFFER_OPERATION`;case e.OUT_OF_MEMORY:return`OUT_OF_MEMORY`;case e.CONTEXT_LOST_WEBGL:return`CONTEXT_LOST_WEBGL`;default:return`UNKNOWN_ERROR`}}setupGL(){let e=this.canvas.getContext(`webgl2`,{antialias:!1,alpha:!0});if(!e)throw Error(`WebGL2 is required but not available.`);let t=createProgram(e,vertexShaderSource,fragmentShaderSource);this.checkGLError(e,`setupGL: after createProgram`);let n=e.createVertexArray();e.bindVertexArray(n),this.checkGLError(e,`setupGL: after VAO creation`);let{positions:r,uvs:i}=computeBorderGeometry(this.canvas.width||2,this.canvas.height||2,this.options.borderWidth,this.options.glowWidth),a=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,a),e.bufferData(e.ARRAY_BUFFER,r,e.STATIC_DRAW);let o=e.getAttribLocation(t,`aPosition`);e.enableVertexAttribArray(o),e.vertexAttribPointer(o,2,e.FLOAT,!1,0,0),this.checkGLError(e,`setupGL: after position buffer setup`);let s=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,s),e.bufferData(e.ARRAY_BUFFER,i,e.STATIC_DRAW);let c=e.getAttribLocation(t,`aUV`);e.enableVertexAttribArray(c),e.vertexAttribPointer(c,2,e.FLOAT,!1,0,0),this.checkGLError(e,`setupGL: after UV buffer setup`);let l=e.getUniformLocation(t,`uResolution`),u=e.getUniformLocation(t,`uTime`),d=e.getUniformLocation(t,`uBorderWidth`),f=e.getUniformLocation(t,`uGlowWidth`),p=e.getUniformLocation(t,`uBorderRadius`),m=e.getUniformLocation(t,`uColors`),h=e.getUniformLocation(t,`uGlowExponent`),g=e.getUniformLocation(t,`uGlowFactor`);e.useProgram(t),e.uniform1f(d,this.options.borderWidth),e.uniform1f(f,this.options.glowWidth),e.uniform1f(p,this.options.borderRadius),this.options.mode===`dark`?(e.uniform1f(h,2),e.uniform1f(g,1.8)):(e.uniform1f(h,1),e.uniform1f(g,1));let _=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let n=0;n<_.length;n++)e.uniform3f(e.getUniformLocation(t,`uColors[${n}]`),..._[n]);this.checkGLError(e,`setupGL: after uniform setup`),e.bindVertexArray(null),e.bindBuffer(e.ARRAY_BUFFER,null),this.glr={gl:e,program:t,vao:n,positionBuffer:a,uvBuffer:s,uResolution:l,uTime:u,uBorderWidth:d,uGlowWidth:f,uBorderRadius:p,uColors:m}}render(e){if(!this.glr)return;let{gl:t,program:n,vao:r,uTime:i}=this.glr;t.useProgram(n),t.bindVertexArray(r),t.uniform1f(i,e),t.disable(t.DEPTH_TEST),t.disable(t.CULL_FACE),t.disable(t.BLEND),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.drawArrays(t.TRIANGLES,0,24),this.checkGLError(t,`render: after draw call`),t.bindVertexArray(null)}greet(){console.log(`%c🌈 ai-motion 0.4.8 🌈`,`background: linear-gradient(90deg, #39b6ff, #bd45fb, #ff5733, #ffd600); color: white; text-shadow: 0 0 2px rgba(0, 0, 0, 0.2); font-weight: bold; font-size: 1em; padding: 2px 12px; border-radius: 6px;`)}}}));function isPageDark(){try{return!!(hasDarkModeClass()||hasDarkModeDataAttribute()||isColorSchemeDark()||isBackgroundDark()||isMainContentBackgroundDark()||isTextColorLight())}catch(e){return console.warn(`Error determining if page is dark:`,e),!1}}function hasDarkModeClass(){let e=[`dark`,`dark-mode`,`theme-dark`,`night`,`night-mode`],t=document.documentElement,n=document.body||document.documentElement;for(let r of e)if(t.classList.contains(r)||n?.classList.contains(r))return!0;return!1}function hasDarkModeDataAttribute(){let e=document.documentElement,t=document.body||document.documentElement;for(let n of[`data-theme`,`data-color-mode`,`data-bs-theme`,`data-mui-color-scheme`]){let r=t?.getAttribute(n),i=e.getAttribute(n);if(r?.toLowerCase()===`dark`||i?.toLowerCase()===`dark`)return!0}return!1}function isColorSchemeDark(){let e=document.querySelector(`meta[name="color-scheme"]`)?.content.toLowerCase();if(e===`dark`||e===`only dark`)return!0;let t=window.getComputedStyle(document.documentElement).getPropertyValue(`color-scheme`).trim().toLowerCase();return t===`dark`||t===`only dark`}function isBackgroundDark(){let e=window.getComputedStyle(document.documentElement),t=window.getComputedStyle(document.body||document.documentElement),n=e.backgroundColor,r=t.backgroundColor;return isColorDark(r)?!0:r===`transparent`||r.startsWith(`rgba(0, 0, 0, 0)`)?isColorDark(n):!1}function isTextColorLight(){let e=200,t=getLuminance(window.getComputedStyle(document.body||document.documentElement).color);return t!==null&&t>200}function isMainContentBackgroundDark(){let{innerWidth:e,innerHeight:t}=window,n=e*t*.5;for(let e of[`#app`,`#root`,`#__next`]){let t=document.querySelector(e);if(!t)continue;let r=t.getBoundingClientRect();if(!(r.width*r.height<n)&&isColorDark(window.getComputedStyle(t).backgroundColor))return!0}return!1}function parseRgbColor(e){let t=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(e);return t?{r:parseInt(t[1]),g:parseInt(t[2]),b:parseInt(t[3])}:null}function getLuminance(e){if(!e||e===`transparent`||e.startsWith(`rgba(0, 0, 0, 0)`))return null;let t=parseRgbColor(e);return t?.299*t.r+.587*t.g+.114*t.b:null}function isColorDark(e,t=128){let n=getLuminance(e);return n!==null&&n<t}var init_checkDarkMode=__esmMin((()=>{})),wrapper$1,visible,SimulatorMask_module_default,init_SimulatorMask_module=__esmMin((()=>{wrapper$1=`_wrapper_1ooyb_1`,visible=`_visible_1ooyb_11`,SimulatorMask_module_default={wrapper:wrapper$1,visible}})),cursor,cursorBorder,cursorFilling,cursorRipple,clicking,cursor_module_default,init_cursor_module=__esmMin((()=>{cursor=`_cursor_1dgwb_2`,cursorBorder=`_cursorBorder_1dgwb_10`,cursorFilling=`_cursorFilling_1dgwb_25`,cursorRipple=`_cursorRipple_1dgwb_39`,clicking=`_clicking_1dgwb_57`,cursor_module_default={cursor,cursorBorder,cursorFilling,cursorRipple,clicking,"cursor-ripple":`_cursor-ripple_1dgwb_1`}})),SimulatorMask_exports=__exportAll({SimulatorMask:()=>SimulatorMask}),SimulatorMask,init_SimulatorMask=__esmMin((()=>{init_Motion(),init_checkDarkMode(),init_SimulatorMask_module(),init_cursor_module(),SimulatorMask=class extends EventTarget{shown=!1;wrapper=document.createElement(`div`);motion=null;#e=!1;#t=document.createElement(`div`);#n=0;#r=0;#i=0;#a=0;constructor(){super(),this.wrapper.id=`page-agent-runtime_simulator-mask`,this.wrapper.className=SimulatorMask_module_default.wrapper,this.wrapper.setAttribute(`data-browser-use-ignore`,`true`),this.wrapper.setAttribute(`data-page-agent-ignore`,`true`);try{let e=new Motion({mode:isPageDark()?`dark`:`light`,styles:{position:`absolute`,inset:`0`}});this.motion=e,this.wrapper.appendChild(e.element),e.autoResize(this.wrapper)}catch(e){console.warn(`[SimulatorMask] Motion overlay unavailable:`,e)}this.wrapper.addEventListener(`click`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mousedown`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mouseup`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`mousemove`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`wheel`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`keydown`,e=>{e.stopPropagation(),e.preventDefault()}),this.wrapper.addEventListener(`keyup`,e=>{e.stopPropagation(),e.preventDefault()}),this.#o(),document.body.appendChild(this.wrapper),this.#s();let e=e=>{let{x:t,y:n}=e.detail;this.setCursorPosition(t,n)},t=()=>{this.triggerClickAnimation()},n=()=>{this.wrapper.style.pointerEvents=`none`},r=()=>{this.wrapper.style.pointerEvents=`auto`};window.addEventListener(`PageAgent::MovePointerTo`,e),window.addEventListener(`PageAgent::ClickPointer`,t),window.addEventListener(`PageAgent::EnablePassThrough`,n),window.addEventListener(`PageAgent::DisablePassThrough`,r),this.addEventListener(`dispose`,()=>{window.removeEventListener(`PageAgent::MovePointerTo`,e),window.removeEventListener(`PageAgent::ClickPointer`,t),window.removeEventListener(`PageAgent::EnablePassThrough`,n),window.removeEventListener(`PageAgent::DisablePassThrough`,r)})}#o(){this.#t.className=cursor_module_default.cursor;let e=document.createElement(`div`);e.className=cursor_module_default.cursorRipple,this.#t.appendChild(e);let t=document.createElement(`div`);t.className=cursor_module_default.cursorFilling,this.#t.appendChild(t);let n=document.createElement(`div`);n.className=cursor_module_default.cursorBorder,this.#t.appendChild(n),this.wrapper.appendChild(this.#t)}#s(){if(this.#e)return;let e=this.#n+(this.#i-this.#n)*.2,t=this.#r+(this.#a-this.#r)*.2,n=Math.abs(e-this.#i);n>0&&(n<2?this.#n=this.#i:this.#n=e,this.#t.style.left=`${this.#n}px`);let r=Math.abs(t-this.#a);r>0&&(r<2?this.#r=this.#a:this.#r=t,this.#t.style.top=`${this.#r}px`),requestAnimationFrame(()=>this.#s())}setCursorPosition(e,t){this.#e||(this.#i=e,this.#a=t)}triggerClickAnimation(){this.#e||(this.#t.classList.remove(cursor_module_default.clicking),this.#t.offsetHeight,this.#t.classList.add(cursor_module_default.clicking))}show(){this.shown||this.#e||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.classList.add(SimulatorMask_module_default.visible),this.#n=window.innerWidth/2,this.#r=window.innerHeight/2,this.#i=this.#n,this.#a=this.#r,this.#t.style.left=`${this.#n}px`,this.#t.style.top=`${this.#r}px`)}hide(){!this.shown||this.#e||(this.shown=!1,this.motion?.fadeOut(),this.motion?.pause(),this.#t.classList.remove(cursor_module_default.clicking),setTimeout(()=>{this.wrapper.classList.remove(SimulatorMask_module_default.visible)},800))}dispose(){this.#e=!0,this.motion?.dispose(),this.wrapper.remove(),this.dispatchEvent(new Event(`dispose`))}}})),PageController=class extends EventTarget{config;flatTree=null;selectorMap=new Map;elementTextMap=new Map;simplifiedHTML=`<EMPTY>`;lastTimeUpdate=0;isIndexed=!1;mask=null;maskReady=null;constructor(e={}){super(),this.config=e,patchReact(this),e.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{let{SimulatorMask:e}=await Promise.resolve().then(()=>(init_SimulatorMask(),SimulatorMask_exports));this.mask=new e})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){let e=window.location.href,t=document.title,n=getPageInfo(),r=resolveViewportExpansion(this.config.viewportExpansion);await this.updateTree();let i=this.simplifiedHTML;return{url:e,title:t,header:`${`Current Page: [${t}](${e})`}\n${`Page info: ${n.viewport_width}x${n.viewport_height}px viewport, ${n.page_width}x${n.page_height}px total page size, ${n.pages_above.toFixed(1)} pages above, ${n.pages_below.toFixed(1)} pages below, ${n.total_pages.toFixed(1)} total pages, at ${(n.current_page_position*100).toFixed(0)}% of page`}\n\n${r===-1?`Interactive elements from top layer of the current page (full page):`:`Interactive elements from top layer of the current page inside the viewport:`}\n\n${n.pixels_above>4&&r!==-1?`... ${n.pixels_above} pixels above (${n.pages_above.toFixed(1)} pages) - scroll to see more ...`:`[Start of page]`}`,content:i,footer:n.pixels_below>4&&r!==-1?`... ${n.pixels_below} pixels below (${n.pages_below.toFixed(1)} pages) - scroll to see more ...`:`[End of page]`}}async updateTree(){this.dispatchEvent(new Event(`beforeUpdate`)),this.lastTimeUpdate=Date.now(),this.mask&&(this.mask.wrapper.style.pointerEvents=`none`),cleanUpHighlights();let e=[...this.config.interactiveBlacklist||[],...Array.from(document.querySelectorAll(`[data-page-agent-not-interactive]`))];return this.flatTree=getFlatTree({...this.config,interactiveBlacklist:e}),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.includeAttributes,this.config.keepSemanticTags),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.mask&&(this.mask.wrapper.style.pointerEvents=`auto`),this.dispatchEvent(new Event(`afterUpdate`)),this.simplifiedHTML}async cleanUpHighlights(){console.log(`[PageController] cleanUpHighlights`),cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw Error(`DOM tree not indexed yet. Can not perform actions on elements.`)}async clickElement(e){try{this.assertIndexed();let t=getElementByIndex(this.selectorMap,e),n=this.elementTextMap.get(e);return await clickElement(t),isAnchorElement(t)&&t.target===`_blank`?{success:!0,message:`✅ Clicked element (${n??e}). ⚠️ Link opened in a new tab.`}:{success:!0,message:`✅ Clicked element (${n??e}).`}}catch(e){return{success:!1,message:`❌ Failed to click element: ${e}`}}}async inputText(e,t){try{this.assertIndexed();let n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return await inputTextElement(n,t),{success:!0,message:`✅ Input text (${t}) into element (${r??e}).`}}catch(e){return{success:!1,message:`❌ Failed to input text: ${e}`}}}async selectOption(e,t){try{this.assertIndexed();let n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return await selectOptionElement(n,t),{success:!0,message:`✅ Selected option (${t}) in element (${r??e}).`}}catch(e){return{success:!1,message:`❌ Failed to select option: ${e}`}}}async scroll(e){try{let{down:t,numPages:n,pixels:r,index:i}=e;return this.assertIndexed(),{success:!0,message:await scrollVertically((r??n*window.innerHeight)*(t?1:-1),i===void 0?null:getElementByIndex(this.selectorMap,i))}}catch(e){return{success:!1,message:`❌ Failed to scroll: ${e}`}}}async scrollHorizontally(e){try{let{right:t,pixels:n,index:r}=e;return this.assertIndexed(),{success:!0,message:await scrollHorizontally(n*(t?1:-1),r===void 0?null:getElementByIndex(this.selectorMap,r))}}catch(e){return{success:!1,message:`❌ Failed to scroll horizontally: ${e}`}}}async executeJavascript(script,signal){try{const asyncFunction=eval(`(async (signal) => { ${script} })`),result=await asyncFunction(signal);return{success:!0,message:`✅ Executed JavaScript. Result: ${result}`}}catch(e){return{success:!1,message:`❌ Error executing JavaScript: ${e}`}}}async showMask(){await this.maskReady,this.mask?.show()}async hideMask(){await this.maskReady,this.mask?.hide()}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML=`<EMPTY>`,this.isIndexed=!1,this.mask?.dispose(),this.mask=null}},enUS={ui:{panel:{ready:`Ready`,thinking:`Thinking...`,taskInput:`Enter new task, describe steps in detail, press Enter to submit`,userAnswerPrompt:`Please answer the question above, press Enter to submit`,taskTerminated:`Task terminated`,taskCompleted:`Task completed`,userAnswer:`User answer: {{input}}`,question:`Question: {{question}}`,waitingPlaceholder:`Waiting for task to start...`,stop:`Stop`,close:`Close`,expand:`Expand history`,collapse:`Collapse history`,step:`Step {{number}}`},tools:{clicking:`Clicking element [{{index}}]...`,inputting:`Inputting text to element [{{index}}]...`,selecting:`Selecting option "{{text}}"...`,scrolling:`Scrolling page...`,waiting:`Waiting {{seconds}} seconds...`,askingUser:`Asking user...`,done:`Task done`,clicked:`🖱️ Clicked element [{{index}}]`,inputted:`⌨️ Inputted text "{{text}}"`,selected:`☑️ Selected option "{{text}}"`,scrolled:`🛞 Page scrolled`,waited:`⌛️ Wait completed`,executing:`Executing {{toolName}}...`,resultSuccess:`success`,resultFailure:`failed`,resultError:`error`},errors:{elementNotFound:`No interactive element found at index {{index}}`,taskRequired:`Task description is required`,executionFailed:`Task execution failed`,notInputElement:`Element is not an input or textarea`,notSelectElement:`Element is not a select element`,optionNotFound:`Option "{{text}}" not found`}}},zhCN={ui:{panel:{ready:`准备就绪`,thinking:`正在思考...`,taskInput:`输入新任务,详细描述步骤,回车提交`,userAnswerPrompt:`请回答上面问题,回车提交`,taskTerminated:`任务已终止`,taskCompleted:`任务结束`,userAnswer:`用户回答: {{input}}`,question:`询问: {{question}}`,waitingPlaceholder:`等待任务开始...`,stop:`终止`,close:`关闭`,expand:`展开历史`,collapse:`收起历史`,step:`步骤 {{number}}`},tools:{clicking:`正在点击元素 [{{index}}]...`,inputting:`正在输入文本到元素 [{{index}}]...`,selecting:`正在选择选项 "{{text}}"...`,scrolling:`正在滚动页面...`,waiting:`等待 {{seconds}} 秒...`,askingUser:`正在询问用户...`,done:`结束任务`,clicked:`🖱️ 已点击元素 [{{index}}]`,inputted:`⌨️ 已输入文本 "{{text}}"`,selected:`☑️ 已选择选项 "{{text}}"`,scrolled:`🛞 页面滚动完成`,waited:`⌛️ 等待完成`,executing:`正在执行 {{toolName}}...`,resultSuccess:`成功`,resultFailure:`失败`,resultError:`错误`},errors:{elementNotFound:`未找到索引为 {{index}} 的交互元素`,taskRequired:`任务描述不能为空`,executionFailed:`任务执行失败`,notInputElement:`元素不是输入框或文本域`,notSelectElement:`元素不是选择框`,optionNotFound:`未找到选项 "{{text}}"`}}},locales={"en-US":enUS,"zh-CN":zhCN},I18n=class{language;translations;constructor(e=`en-US`){this.language=e in locales?e:`en-US`,this.translations=locales[this.language]}t(e,t){let n=this.getNestedValue(this.translations,e);return n?t?this.interpolate(n,t):n:(console.warn(`Translation key "${e}" not found for language "${this.language}"`),e)}getNestedValue(e,t){return t.split(`.`).reduce((e,t)=>e?.[t],e)}interpolate(e,t){return e.replace(/\{\{(\w+)\}\}/g,(e,n)=>t[n]==null?e:t[n].toString())}getLanguage(){return this.language}};function truncate(e,t){return e.length>t?e.substring(0,t)+`...`:e}function escapeHtml(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}var wrapper=`_wrapper_1tu05_1`,background=`_background_1tu05_39`,header=`_header_1tu05_99`,pulse=`_pulse_1tu05_1`,retryPulse=`_retryPulse_1tu05_1`,statusTextFadeOut=`_statusTextFadeOut_1tu05_1`,statusTextFadeIn=`_statusTextFadeIn_1tu05_1`,statusSection=`_statusSection_1tu05_121`,indicator=`_indicator_1tu05_128`,thinking=`_thinking_1tu05_137`,tool_executing=`_tool_executing_1tu05_142`,retry=`_retry_1tu05_147`,completed=`_completed_1tu05_153`,input=`_input_1tu05_154`,output=`_output_1tu05_155`,error=`_error_1tu05_160`,statusText=`_statusText_1tu05_166`,fadeOut=`_fadeOut_1tu05_178`,fadeIn=`_fadeIn_1tu05_182`,controls=`_controls_1tu05_188`,controlButton=`_controlButton_1tu05_193`,stopButton=`_stopButton_1tu05_212`,historySectionWrapper=`_historySectionWrapper_1tu05_246`,shimmer=`_shimmer_1tu05_1`,celebrate=`_celebrate_1tu05_1`,expanded=`_expanded_1tu05_278`,historySection=`_historySection_1tu05_246`,historyItem=`_historyItem_1tu05_297`,observation=`_observation_1tu05_355`,question=`_question_1tu05_360`,doneSuccess=`_doneSuccess_1tu05_366`,historyContent=`_historyContent_1tu05_402`,statusIcon=`_statusIcon_1tu05_403`,doneError=`_doneError_1tu05_412`,reflectionLines=`_reflectionLines_1tu05_462`,historyMeta=`_historyMeta_1tu05_469`,inputSectionWrapper=`_inputSectionWrapper_1tu05_539`,hidden=`_hidden_1tu05_562`,inputSection=`_inputSection_1tu05_539`,taskInput=`_taskInput_1tu05_573`,Panel_module_default={wrapper,"mask-running":`_mask-running_1tu05_1`,background,header,pulse,retryPulse,statusTextFadeOut,statusTextFadeIn,statusSection,indicator,thinking,tool_executing,retry,completed,input,output,error,statusText,fadeOut,fadeIn,controls,controlButton,stopButton,historySectionWrapper,shimmer,celebrate,expanded,historySection,historyItem,observation,question,doneSuccess,historyContent,statusIcon,doneError,reflectionLines,historyMeta,inputSectionWrapper,hidden,inputSection,taskInput};function createCard({icon:e,content:t,meta:n,type:r}){let i=r?Panel_module_default[r]:``,a=Array.isArray(t)?`<div class="${Panel_module_default.reflectionLines}">${t.map(e=>`<span>${escapeHtml(e)}</span>`).join(``)}</div>`:`<span>${escapeHtml(t)}</span>`;return`
|
|
359
358
|
<div class="${Panel_module_default.historyItem} ${i}">
|
|
360
359
|
<div class="${Panel_module_default.historyContent}">
|
|
361
360
|
<span class="${Panel_module_default.statusIcon}">${e}</span>
|
|
@@ -363,7 +362,7 @@ gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
|
363
362
|
</div>
|
|
364
363
|
${n?`<div class="${Panel_module_default.historyMeta}">${n}</div>`:``}
|
|
365
364
|
</div>
|
|
366
|
-
`}function createReflectionLines(e){let t=[];return e.evaluation_previous_goal&&t.push(`🔍 ${e.evaluation_previous_goal}`),e.memory&&t.push(`💾 ${e.memory}`),e.next_goal&&t.push(`🎯 ${e.next_goal}`),t}var Panel=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u=!1;#d;#f=null;#p=!1;#m=null;#h=null;#g=!1;#_=()=>this.#x();#v=()=>this.#S();#y=e=>this.#C(e.detail);#b=()=>this.dispose();get wrapper(){return this.#e}constructor(e,t={}){this.#c=e,this.#l=t,this.#d=new I18n(t.language??`en-US`),this.#c.onAskUser=e=>this.#w(e),this.#e=this.#
|
|
365
|
+
`}function createReflectionLines(e){let t=[];return e.evaluation_previous_goal&&t.push(`🔍 ${e.evaluation_previous_goal}`),e.memory&&t.push(`💾 ${e.memory}`),e.next_goal&&t.push(`🎯 ${e.next_goal}`),t}var Panel=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u=!1;#d;#f=null;#p=!1;#m=null;#h=null;#g=!1;#_=()=>this.#x();#v=()=>this.#S();#y=e=>this.#C(e.detail);#b=()=>this.dispose();get wrapper(){return this.#e}constructor(e,t={}){this.#c=e,this.#l=t,this.#d=new I18n(t.language??`en-US`),this.#c.onAskUser=(e,t)=>this.#w(e,t?.signal),this.#e=this.#N(),this.#t=this.#e.querySelector(`.${Panel_module_default.indicator}`),this.#n=this.#e.querySelector(`.${Panel_module_default.statusText}`),this.#r=this.#e.querySelector(`.${Panel_module_default.historySection}`),this.#i=this.#e.querySelector(`.${Panel_module_default.expandButton}`),this.#a=this.#e.querySelector(`.${Panel_module_default.stopButton}`),this.#o=this.#e.querySelector(`.${Panel_module_default.inputSectionWrapper}`),this.#s=this.#e.querySelector(`.${Panel_module_default.taskInput}`),this.#c.addEventListener(`statuschange`,this.#_),this.#c.addEventListener(`historychange`,this.#v),this.#c.addEventListener(`activity`,this.#y),this.#c.addEventListener(`dispose`,this.#b),this.#P(),this.#R(),this.#A(),this.hide()}#x(){let e=this.#c.status,t=e===`completed`&&this.#c.lastResult?.success===!1;this.#H(t?`error`:e),e===`running`?(this.#a.textContent=`■`,this.#a.title=this.#d.t(`ui.panel.stop`)):(this.#a.textContent=`X`,this.#a.title=this.#d.t(`ui.panel.close`)),e===`running`&&(this.show(),this.#j()),(e===`completed`||e===`error`||e===`stopped`)&&(this.#u||this.#I(),this.#M()&&this.#A())}#S(){this.#W()}#C(e){switch(e.type){case`thinking`:this.#h=this.#d.t(`ui.panel.thinking`),this.#H(`thinking`);break;case`executing`:this.#h=this.#E(e.tool,e.input),this.#H(`executing`);break;case`executed`:this.#h=truncate(e.output,50);break;case`retrying`:this.#h=`Retrying (${e.attempt}/${e.maxAttempts})`,this.#H(`retrying`);break;case`error`:this.#h=truncate(e.message,50),this.#H(`error`);break}}#w(e,t){return new Promise((n,r)=>{this.#p=!0,this.#f=n,this.#u||this.#I();let i=document.createElement(`div`);i.innerHTML=createCard({icon:`❓`,content:`Question: ${e}`,type:`question`});let a=i.firstElementChild;a.setAttribute(`data-temp-card`,`true`),this.#r.appendChild(a),this.#U(),this.#A(this.#d.t(`ui.panel.userAnswerPrompt`)),t?.addEventListener(`abort`,()=>{this.#T(),this.#p=!1,this.#f=null,r(t.reason)},{once:!0})})}#T(){Array.from(this.#r.children).forEach(e=>{e.getAttribute(`data-temp-card`)===`true`&&e.remove()})}show(){this.wrapper.style.display=`block`,this.wrapper.offsetHeight,this.wrapper.style.opacity=`1`,this.wrapper.style.transform=`translateX(-50%) translateY(0)`}hide(){this.wrapper.style.opacity=`0`,this.wrapper.style.transform=`translateX(-50%) translateY(20px)`,this.wrapper.style.display=`none`}reset(){this.#n.textContent=this.#d.t(`ui.panel.ready`),this.#H(`thinking`),this.#W(),this.#L(),this.#p=!1,this.#f=null,this.#A()}expand(){this.#I()}collapse(){this.#L()}dispose(){this.#c.removeEventListener(`statuschange`,this.#_),this.#c.removeEventListener(`historychange`,this.#v),this.#c.removeEventListener(`activity`,this.#y),this.#c.removeEventListener(`dispose`,this.#b),this.#p=!1,this.#z(),this.wrapper.remove()}#E(e,t){let n=t;switch(e){case`click_element_by_index`:return this.#d.t(`ui.tools.clicking`,{index:n.index});case`input_text`:return this.#d.t(`ui.tools.inputting`,{index:n.index});case`select_dropdown_option`:return this.#d.t(`ui.tools.selecting`,{text:n.text});case`scroll`:return this.#d.t(`ui.tools.scrolling`);case`wait`:return this.#d.t(`ui.tools.waiting`,{seconds:n.seconds});case`ask_user`:return this.#d.t(`ui.tools.askingUser`);case`done`:return this.#d.t(`ui.tools.done`);default:return this.#d.t(`ui.tools.executing`,{toolName:e})}}#D(){this.#c.status===`running`?this.#c.stop():this.#c.dispose()}#O(){let e=this.#s.value.trim();e&&(this.#j(),this.#p?this.#k(e):this.#c.execute(e))}#k(e){this.#T(),this.#p=!1,this.#f&&=(this.#f(e),null)}#A(e){this.#s.value=``,this.#s.placeholder=e||this.#d.t(`ui.panel.taskInput`),this.#o.classList.remove(Panel_module_default.hidden),setTimeout(()=>{this.#s.focus()},100)}#j(){this.#o.classList.add(Panel_module_default.hidden)}#M(){if(this.#p||this.#c.history.length===0)return!0;let e=this.#c.status;return e===`completed`||e===`error`||e===`stopped`?this.#l.promptForNextTask??!0:!1}#N(){let e=1e3,t=document.createElement(`div`);return t.id=`page-agent-runtime_agent-panel`,t.className=Panel_module_default.wrapper,t.setAttribute(`data-browser-use-ignore`,`true`),t.setAttribute(`data-page-agent-ignore`,`true`),t.innerHTML=`
|
|
367
366
|
<div class="${Panel_module_default.background}"></div>
|
|
368
367
|
<div class="${Panel_module_default.historySectionWrapper}">
|
|
369
368
|
<div class="${Panel_module_default.historySection}">
|
|
@@ -398,4 +397,4 @@ gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
|
398
397
|
/>
|
|
399
398
|
</div>
|
|
400
399
|
</div>
|
|
401
|
-
`,document.body.appendChild(t),t}#
|
|
400
|
+
`,document.body.appendChild(t),t}#P(){this.wrapper.querySelector(`.${Panel_module_default.header}`).addEventListener(`click`,e=>{e.target.closest(`.${Panel_module_default.controlButton}`)||this.#F()}),this.#i.addEventListener(`click`,e=>{e.stopPropagation(),this.#F()}),this.#a.addEventListener(`click`,e=>{e.stopPropagation(),this.#D()}),this.#s.addEventListener(`keydown`,e=>{e.isComposing||e.key===`Enter`&&(e.preventDefault(),this.#O())}),this.#o.addEventListener(`click`,e=>{e.stopPropagation()})}#F(){this.#u?this.#L():this.#I()}#I(){this.#u=!0,this.wrapper.classList.add(Panel_module_default.expanded),this.#i.textContent=`▲`}#L(){this.#u=!1,this.wrapper.classList.remove(Panel_module_default.expanded),this.#i.textContent=`▼`}#R(){this.#m=setInterval(()=>{this.#B()},450)}#z(){this.#m&&=(clearInterval(this.#m),null)}#B(){if(!this.#h||this.#g)return;if(this.#n.textContent===this.#h){this.#h=null;return}let e=this.#h;this.#h=null,this.#V(e)}#V(e){this.#g=!0,this.#n.classList.add(Panel_module_default.fadeOut),setTimeout(()=>{this.#n.textContent=e,this.#n.classList.remove(Panel_module_default.fadeOut),this.#n.classList.add(Panel_module_default.fadeIn),setTimeout(()=>{this.#n.classList.remove(Panel_module_default.fadeIn),this.#g=!1},300)},150)}#H(e){let t=e===`running`?`thinking`:e;this.#t.className=Panel_module_default.indicator,t!==`idle`&&t!==`stopped`&&this.#t.classList.add(Panel_module_default[t])}#U(){setTimeout(()=>{this.#r.scrollTop=this.#r.scrollHeight},0)}#W(){let e=[],t=this.#c.task;t&&e.push(this.#G(t));let n=this.#c.history;for(let t of n)e.push(...this.#K(t));this.#r.innerHTML=e.join(``),this.#U()}#G(e){return createCard({icon:`🎯`,content:e,type:`input`})}#K(e){let t=[],n=e.type===`step`&&e.stepIndex!==void 0?this.#d.t(`ui.panel.step`,{number:(e.stepIndex+1).toString()}):void 0;if(e.type===`step`){if(e.reflection){let r=createReflectionLines(e.reflection);r.length>0&&t.push(createCard({icon:`🧠`,content:r,meta:n}))}let r=e.action;r&&t.push(...this.#q(r,n))}else if(e.type===`observation`)t.push(createCard({icon:`👁️`,content:e.content||``,meta:n,type:`observation`}));else if(e.type===`user_takeover`)t.push(createCard({icon:`👤`,content:`User takeover`,meta:n,type:`input`}));else if(e.type===`retry`){let r=`${e.message||`Retrying`} (${e.attempt}/${e.maxAttempts})`;t.push(createCard({icon:`🔄`,content:r,meta:n,type:`observation`}))}else e.type===`error`&&t.push(createCard({icon:`❌`,content:e.message||`Error`,meta:n,type:`observation`}));return t}#q(e,t){let n=[];if(e.name===`done`){let r=e.input.text||e.output||``;r&&n.push(createCard({icon:`🤖`,content:r,meta:t,type:`output`}))}else if(e.name===`ask_user`){let r=e.input,i=e.output.replace(/^User answered:\s*/i,``);n.push(createCard({icon:`❓`,content:`Question: ${r.question||``}`,meta:t,type:`question`})),n.push(createCard({icon:`💬`,content:`Answer: ${i}`,meta:t,type:`input`}))}else{let r=this.#E(e.name,e.input);n.push(createCard({icon:`🔨`,content:r,meta:t})),e.output?.length>0&&n.push(createCard({icon:`🔨`,content:e.output,meta:t,type:`output`}))}return n}},PageAgent=class extends PageAgentCore{panel;constructor(e){let t=new PageController({...e,enableMask:e.enableMask??!0});super({...e,pageController:t}),this.panel=new Panel(this,{language:e.language,promptForNextTask:e.promptForNextTask})}},currentScript=document.currentScript,currentScriptURL=currentScript?.src?new URL(currentScript.src):null,autoInit=currentScriptURL?.searchParams.get(`autoInit`)!==`false`;autoInit&&window.pageAgent&&window.pageAgent.dispose(),window.PageAgent=PageAgent,console.log(`🚀 page-agent.js loaded!`);var DEMO_MODEL=`qwen3.5-plus`,DEMO_BASE_URL=`https://page-ag-testing-ohftxirgbn.cn-shanghai.fcapp.run`,DEMO_API_KEY=`NA`;autoInit&&setTimeout(()=>{let e,t=!0;if(currentScriptURL){let n=currentScriptURL,r=n.searchParams.get(`model`)||DEMO_MODEL,i=n.searchParams.get(`baseURL`)||DEMO_BASE_URL,a=n.searchParams.get(`apiKey`)||DEMO_API_KEY,o=n.searchParams.get(`lang`)||`zh-CN`;t=(n.searchParams.get(`showPanel`)||`true`)===`true`,e={model:r,baseURL:i,apiKey:a,language:o}}else console.log(`🚀 page-agent.js no current script detected, using default demo config`),e={model:DEMO_MODEL,baseURL:DEMO_BASE_URL,apiKey:DEMO_API_KEY};window.pageAgent=new PageAgent(e),t&&window.pageAgent.panel.show(),console.log(`🚀 page-agent.js initialized with config:`,window.pageAgent.config)})})();
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "page-agent",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.9.1",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/esm/page-agent.js",
|
|
7
7
|
"types": "./dist/esm/PageAgent.d.ts",
|
|
@@ -43,10 +43,10 @@
|
|
|
43
43
|
"postpublish": "node ../../scripts/post-publish.js"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@page-agent/core": "1.
|
|
47
|
-
"@page-agent/llms": "1.
|
|
48
|
-
"@page-agent/page-controller": "1.
|
|
49
|
-
"@page-agent/ui": "1.
|
|
46
|
+
"@page-agent/core": "1.9.1",
|
|
47
|
+
"@page-agent/llms": "1.9.1",
|
|
48
|
+
"@page-agent/page-controller": "1.9.1",
|
|
49
|
+
"@page-agent/ui": "1.9.1",
|
|
50
50
|
"chalk": "^5.6.2"
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|