@opentiny/next-sdk 0.4.0 → 0.4.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.
Files changed (130) hide show
  1. package/agent/AgentModelProvider.ts +78 -81
  2. package/agent/type.ts +6 -9
  3. package/agent/utils/getAISDKTools.ts +0 -1
  4. package/agent/utils/getBuiltinMcpTools.ts +7 -7
  5. package/core.ts +0 -3
  6. package/dist/SimulatorMask-BHVXyogh-iNUb4dyF.js +361 -0
  7. package/dist/agent/type.d.ts +4 -12
  8. package/dist/agent/utils/getBuiltinMcpTools.d.ts +3 -3
  9. package/dist/core.d.ts +0 -1
  10. package/dist/core.js +16 -17
  11. package/dist/index-CXK8CcKq.js +6076 -0
  12. package/dist/index.d.ts +0 -3
  13. package/dist/index.js +57 -4969
  14. package/dist/{initialize-builtin-WebMCP-HgObT902.js → initialize-builtin-WebMCP-rALfqS-o.js} +1166 -1056
  15. package/dist/page-tools/a11y/build.d.ts +11 -0
  16. package/dist/page-tools/a11y/constants.d.ts +9 -0
  17. package/dist/page-tools/a11y/search.d.ts +17 -0
  18. package/dist/page-tools/a11y/types.d.ts +104 -0
  19. package/dist/page-tools/a11y/utils.d.ts +34 -0
  20. package/dist/page-tools/a11y/vnode.d.ts +37 -0
  21. package/dist/page-tools/a11y-tree.d.ts +8 -99
  22. package/dist/page-tools/constants.d.ts +22 -0
  23. package/dist/page-tools/context.d.ts +28 -0
  24. package/dist/page-tools/handlers/browserState.d.ts +8 -0
  25. package/dist/page-tools/handlers/click.d.ts +8 -0
  26. package/dist/page-tools/handlers/executeJavascript.d.ts +8 -0
  27. package/dist/page-tools/handlers/fill.d.ts +8 -0
  28. package/dist/page-tools/handlers/scroll.d.ts +8 -0
  29. package/dist/page-tools/handlers/searchTree.d.ts +8 -0
  30. package/dist/page-tools/handlers/select.d.ts +8 -0
  31. package/dist/page-tools/page-agent-highlight/index.d.ts +9 -0
  32. package/dist/page-tools/page-agent-mask/SimulatorMask.d.ts +14 -0
  33. package/dist/page-tools/page-agent-mask/checkDarkMode.d.ts +5 -0
  34. package/dist/page-tools/page-agent-tool.d.ts +3 -8
  35. package/dist/page-tools/schema.d.ts +43 -0
  36. package/dist/page-tools/utils/dom.d.ts +6 -0
  37. package/dist/page-tools/utils/scroll.d.ts +15 -0
  38. package/dist/runtime.d.ts +4 -0
  39. package/dist/runtime.js +744 -0
  40. package/dist/utils/builtinProxy.d.ts +1 -1
  41. package/index.ts +0 -5
  42. package/package.json +6 -17
  43. package/page-tools/a11y/build.ts +70 -0
  44. package/page-tools/a11y/constants.ts +110 -0
  45. package/page-tools/a11y/search.ts +129 -0
  46. package/page-tools/a11y/types.ts +108 -0
  47. package/page-tools/a11y/utils.ts +266 -0
  48. package/page-tools/a11y/vnode.ts +229 -0
  49. package/page-tools/a11y-tree.ts +8 -527
  50. package/page-tools/bridge.ts +1 -1
  51. package/page-tools/constants.ts +72 -0
  52. package/page-tools/context.ts +13 -0
  53. package/page-tools/handlers/browserState.ts +12 -0
  54. package/page-tools/handlers/click.ts +26 -0
  55. package/page-tools/handlers/executeJavascript.ts +22 -0
  56. package/page-tools/handlers/fill.ts +60 -0
  57. package/page-tools/handlers/scroll.ts +66 -0
  58. package/page-tools/handlers/searchTree.ts +30 -0
  59. package/page-tools/handlers/select.ts +34 -0
  60. package/page-tools/page-agent-highlight/index.ts +198 -0
  61. package/page-tools/page-agent-mask/SimulatorMask.module.css +14 -0
  62. package/page-tools/page-agent-mask/SimulatorMask.ts +279 -0
  63. package/page-tools/page-agent-mask/checkDarkMode.ts +181 -0
  64. package/page-tools/page-agent-mask/cursor-border.svg +3 -0
  65. package/page-tools/page-agent-mask/cursor-fill.svg +5 -0
  66. package/page-tools/page-agent-mask/cursor.module.css +70 -0
  67. package/page-tools/page-agent-prompt.md +34 -18
  68. package/page-tools/page-agent-tool.ts +104 -152
  69. package/page-tools/schema.ts +51 -0
  70. package/page-tools/utils/dom.ts +155 -0
  71. package/page-tools/utils/scroll.ts +58 -0
  72. package/runtime.ts +13 -0
  73. package/utils/builtinProxy.ts +45 -13
  74. package/vite.config.runtime.ts +22 -0
  75. package/vite.config.ts +52 -8
  76. package/McpSdk.ts +0 -14
  77. package/WebAgent.ts +0 -5
  78. package/WebMcp.ts +0 -26
  79. package/Zod.ts +0 -1
  80. package/dist/McpSdk.d.ts +0 -14
  81. package/dist/SimulatorMask-BHVXyogh-BFEGpD5S.js +0 -1048
  82. package/dist/SimulatorMask-BHVXyogh-CCYbrb84.js +0 -801
  83. package/dist/WebAgent.d.ts +0 -5
  84. package/dist/WebMcp.d.ts +0 -23
  85. package/dist/Zod.d.ts +0 -1
  86. package/dist/index.es.dev.js +0 -59017
  87. package/dist/index.es.js +0 -46795
  88. package/dist/index.umd.dev.js +0 -60355
  89. package/dist/index.umd.js +0 -1248
  90. package/dist/mcpsdk@1.25.3.dev.js +0 -22780
  91. package/dist/mcpsdk@1.25.3.es.dev.js +0 -22778
  92. package/dist/mcpsdk@1.25.3.es.js +0 -16960
  93. package/dist/mcpsdk@1.25.3.js +0 -48
  94. package/dist/transport/ExtensionClientTransport.d.ts +0 -24
  95. package/dist/transport/ExtensionContentServerTransport.d.ts +0 -39
  96. package/dist/transport/ExtensionPageServerTransport.d.ts +0 -36
  97. package/dist/transport/messages.d.ts +0 -9
  98. package/dist/vite.config.mcpSdk.d.ts +0 -2
  99. package/dist/vite.config.webAgent.d.ts +0 -2
  100. package/dist/vite.config.webMcp.d.ts +0 -2
  101. package/dist/vite.config.webMcpFull.d.ts +0 -2
  102. package/dist/vite.config.zod.d.ts +0 -2
  103. package/dist/webagent.dev.js +0 -49360
  104. package/dist/webagent.es.dev.js +0 -49071
  105. package/dist/webagent.es.js +0 -39219
  106. package/dist/webagent.js +0 -642
  107. package/dist/webmcp-full.dev.js +0 -31336
  108. package/dist/webmcp-full.es.dev.js +0 -30283
  109. package/dist/webmcp-full.es.js +0 -22889
  110. package/dist/webmcp-full.js +0 -645
  111. package/dist/webmcp.dev.js +0 -9572
  112. package/dist/webmcp.es.dev.js +0 -8518
  113. package/dist/webmcp.es.js +0 -6727
  114. package/dist/webmcp.js +0 -602
  115. package/dist/zod@3.25.76.dev.js +0 -4037
  116. package/dist/zod@3.25.76.es.dev.js +0 -4033
  117. package/dist/zod@3.25.76.es.js +0 -2945
  118. package/dist/zod@3.25.76.js +0 -1
  119. package/transport/ExtensionClientTransport.ts +0 -100
  120. package/transport/ExtensionContentServerTransport.ts +0 -162
  121. package/transport/ExtensionPageServerTransport.ts +0 -149
  122. package/transport/messages.ts +0 -63
  123. package/vite-build-tsc.ts +0 -63
  124. package/vite-env.d.ts +0 -10
  125. package/vite.config.mcpSdk.ts +0 -28
  126. package/vite.config.webAgent.ts +0 -19
  127. package/vite.config.webMcp.ts +0 -40
  128. package/vite.config.webMcpFull.ts +0 -19
  129. package/vite.config.zod.ts +0 -23
  130. /package/dist/{vite-build-tsc.d.ts → vite.config.runtime.d.ts} +0 -0
package/dist/webmcp.js DELETED
@@ -1,602 +0,0 @@
1
- (function(e,t){typeof exports=="object"&&typeof module<"u"?t(exports,require("ajv"),require("@modelcontextprotocol/sdk/types.js"),require("@modelcontextprotocol/sdk/client/index.js"),require("@modelcontextprotocol/sdk/client/sse.js"),require("@modelcontextprotocol/sdk/client/streamableHttp.js"),require("@modelcontextprotocol/sdk/client/websocket.js"),require("@modelcontextprotocol/sdk/client/auth.js"),require("@modelcontextprotocol/sdk/server/mcp.js"),require("zod"),require("@modelcontextprotocol/sdk/shared/uriTemplate.js"),require("@modelcontextprotocol/sdk/server/completable.js"),require("@modelcontextprotocol/sdk/shared/metadataUtils.js")):typeof define=="function"&&define.amd?define(["exports","ajv","@modelcontextprotocol/sdk/types.js","@modelcontextprotocol/sdk/client/index.js","@modelcontextprotocol/sdk/client/sse.js","@modelcontextprotocol/sdk/client/streamableHttp.js","@modelcontextprotocol/sdk/client/websocket.js","@modelcontextprotocol/sdk/client/auth.js","@modelcontextprotocol/sdk/server/mcp.js","zod","@modelcontextprotocol/sdk/shared/uriTemplate.js","@modelcontextprotocol/sdk/server/completable.js","@modelcontextprotocol/sdk/shared/metadataUtils.js"],t):(e=typeof globalThis<"u"?globalThis:e||self,t(e.WebMCP={},e.MCPSDK,e.MCPSDK,e.MCPSDK,e.MCPSDK,e.MCPSDK,e.websocket_js,e.MCPSDK,e.MCPSDK,e.Zod,e.MCPSDK,e.MCPSDK,e.MCPSDK))})(this,(function(exports,ajv,types_js,index_js,sse_js,streamableHttp_js,websocket_js,auth_js,mcp_js,zod,uriTemplate_js,completable_js,metadataUtils_js){"use strict";const _0x4f2826=_0xad7a;(function(e,t){const n=_0xad7a,r=_0xad7a,o=e();for(;;)try{if(parseInt(n(403))/1+-parseInt(n(411))/2*(-parseInt(r(406))/3)+-parseInt(r(425))/4*(parseInt(n(387))/5)+-parseInt(r(426))/6+parseInt(r(395))/7*(-parseInt(n(419))/8)+-parseInt(n(413))/9+parseInt(r(400))/10===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(_0xf7c7,-118057+3521*-35+-2099*-233);const getGlobalObject=()=>{const e=_0xad7a,t=_0xad7a,n={};n[e(420)]="3|0|2|1|4",n.vQYJZ=function(s,a){return s!==a},n[t(394)]=t(414),n.ktWqD=function(s,a){return s!==a},n[e(424)]=e(391);const r=n,o=r[t(420)].split("|");let i=859*2+-3*-1039+-4835*1;for(;;){switch(o[i++]){case"0":if(r[t(407)](typeof window,"undefined"))return window;continue;case"1":if(r.vQYJZ(typeof self,r.NZmUq))return self;continue;case"2":if(r[t(405)](typeof global,"undefined"))return global;continue;case"3":if(r[t(405)](typeof globalThis,r[e(394)]))return globalThis;continue;case"4":return Function(r[e(424)])()}break}},sendMessage=(e,t,n)=>{const r=_0xad7a,o=_0xad7a,i={};i.eOzBp=function(a,l){return a!==l},i.ooaJk="undefined",i[r(402)]=function(a,l){return a===l},i[r(421)]="function";const s=i;s[o(389)](typeof window,s.ooaJk)?e[o(423)](t,"*",n):r(423)in e&&s.pTvSc(typeof e[o(423)],s[r(421)])&&e.postMessage(t,n)},setMessageHandler=(e,t)=>{const n=_0xad7a,r=_0xad7a,o={};o.nTCfA=function(s,a){return s in a},o[n(390)]="addEventListener",o[n(385)]=function(s,a){return s===a},o[n(409)]="function",o.VaHpd=r(392),o[r(384)]=n(417),o.FPOYW=function(s,a){return s!==a};const i=o;i.nTCfA(i.ogKey,e)&&i[r(385)](typeof e.addEventListener,i[r(409)])?e[r(386)](i.VaHpd,t):i[r(384)]in e&&i[n(398)](typeof e[r(417)],n(414))&&(e.onmessage=t)};class MessageChannelTransport{constructor(t){this._port=t}async[_0x4f2826(401)](){const t=_0x4f2826,n=_0x4f2826;this[t(422)]&&(this[n(422)].onmessage=r=>{var o,i;const s=t;try{const a=types_js.JSONRPCMessageSchema.parse(r.data.message);(o=this.onmessage)==null||o.call(this,a,r[s(412)][s(428)])}catch(a){const l=new Error("MessageChannel failed to parse message: "+a);(i=this[s(383)])==null||i.call(this,l)}},this._port.onmessageerror=r=>{var o;const i=n,s=new Error("MessageChannel transport error: "+JSON[i(415)](r));(o=this.onerror)==null||o.call(this,s)},this[n(422)].start())}async send(t,n){const r={EoBZE:function(o){return o()},leEiG:function(o,i){return o instanceof i},cDUwk:function(o,i){return o(i)}};return new Promise((o,i)=>{var s;const a=_0xad7a,l=_0xad7a;try{const c={};c[a(404)]=n?.[a(404)];const u={};u[a(392)]=t,u.extra=c,this._port&&this._port[l(423)](u),r[a(399)](o)}catch(c){const u=r.leEiG(c,Error)?c:new Error(r.cDUwk(String,c));(s=this.onerror)==null||s.call(this,u),i(u)}})}async close(){var t,n;const r=_0x4f2826,o=_0x4f2826;(t=this._port)==null||t[r(393)](),this[r(422)]=void 0,(n=this[o(408)])==null||n.call(this)}}class MessageChannelClientTransport extends MessageChannelTransport{constructor(t,n=getGlobalObject()){const r=_0x4f2826,o={lSpBh:function(s,a,l,c){return s(a,l,c)}};super(),this._endpoint=t,this._globalObject=n;const i=new MessageChannel;this._port=i[r(410)],o[r(418)](sendMessage,this._globalObject,{endpoint:this[r(397)]},[i[r(429)]])}}class MessageChannelServerTransport extends MessageChannelTransport{constructor(t,n=getGlobalObject()){const r=_0x4f2826,o=_0x4f2826,i={HITdC:function(s,a){return s===a},QdDxM:function(s){return s()},jowPp:function(s,a,l){return s(a,l)}};super(),this[r(397)]=t,this[o(388)]=n,this[o(416)]=new Promise(s=>{const a=r,l={XlglK:function(c,u){return i.HITdC(c,u)},pXlad:function(c){return i.QdDxM(c)}};i[a(427)](setMessageHandler,this._globalObject,c=>{const u=a,p=a;c[u(412)]&&l.XlglK(c.data[p(396)],this._endpoint)&&(this[u(422)]=c[p(430)][-3036+-1518*-2],l.pXlad(s))})})}async listen(){return this._listen}}function _0xf7c7(){const e=["message","close","NZmUq","177464iLQCGm","endpoint","_endpoint","FPOYW","EoBZE","3022630ngzRBs","start","pTvSc","272809yMhhPJ","authInfo","ktWqD","21849KofsKk","vQYJZ","onclose","mkHJS","port1","22dUTKmE","data","608229RXNlUs","undefined","stringify","_listen","onmessage","lSpBh","8FmlYyF","XwdDB","cHbAW","_port","postMessage","kFtNB","72572mbPnfL","689424jqaGZE","jowPp","extra","port2","ports","onerror","Fzdib","mkuHv","addEventListener","55juYkZZ","_globalObject","eOzBp","ogKey","return this"];return _0xf7c7=function(){return e},_0xf7c7()}function _0xad7a(e,t){const n=_0xf7c7();return _0xad7a=function(r,o){return r=r-(17227+1*-16844),n[r]},_0xad7a(e,t)}const createTransportPair=()=>{const e=new MessageChannel;return[new MessageChannelTransport(e.port1),new MessageChannelTransport(e.port2)]};(function(e,t){const n=_0x21a3,r=_0x21a3,o=e();for(;;)try{if(parseInt(n(452))/1*(parseInt(r(441))/2)+parseInt(r(434))/3*(-parseInt(r(418))/4)+parseInt(n(459))/5+parseInt(n(482))/6*(-parseInt(n(479))/7)+-parseInt(n(458))/8*(parseInt(n(457))/9)+-parseInt(r(416))/10+-parseInt(n(450))/11*(-parseInt(n(433))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(_0x3610,-411935*1+228107+208149*2);const forwardServerRequest=async(e,t,n)=>{var r;const o=_0x21a3,i=_0x21a3,s={};s.VRyiJ="tools/list",s.VkPYu="tools/call",s[o(475)]=o(411),s.SoCaE="resources/templates/list",s[i(484)]="resources/read",s[o(461)]="prompts/get",s.srIIC=i(477),s[i(436)]=i(478),s[i(442)]=o(437),s.dEmVs=o(465);const a=s,{id:l,method:c,params:u}=n;let p={};switch(c){case a.VRyiJ:p=await t.listTools(u);break;case a.VkPYu:p=await t.callTool(u);break;case a.fgMSD:p=await t.listResources(u);break;case a[i(466)]:p=await t.listResourceTemplates(u);break;case a.sthgI:p=await t[o(455)](u);break;case i(486):p=await t.subscribeResource(u);break;case o(410):p=await t.unsubscribeResource(u);break;case a[i(461)]:p=await t[i(414)](u);break;case a[o(412)]:p=await t[o(491)](u);break;case a[o(436)]:p=await t[o(478)]();break;case a.kkNqg:p=await t.complete(u);break;case o(464):p=await t.setLoggingLevel(u?.[i(443)]);break}const f={};f.result=p,f.jsonrpc=a[i(472)],f.id=l,await((r=e?.[i(488)])==null?void 0:r[o(460)](f))},forwardClientRequest=async(e,t,n)=>{var r;const o=_0x21a3,i=_0x21a3,s={};s[o(487)]=i(462),s.ypHTC="ping",s.fPExS=o(465);const a=s,{id:l,method:c,params:u}=n;let p={};switch(c){case"roots/list":const m={};m.method=c,m[i(446)]=u,p=await t[o(469)](m,types_js.ListRootsResultSchema);break;case"sampling/createMessage":const g={};g[o(481)]=c,g[o(446)]=u,p=await t.request(g,types_js.CreateMessageResultSchema);break;case a[o(487)]:const x={};x.method=c,x[i(446)]=u,p=await t.request(x,types_js.ElicitResultSchema);break;case a.ypHTC:const b={};b.method=c,p=await t.request(b,types_js.EmptyResultSchema);break}const f={};return f.result=p,f.jsonrpc=a.fPExS,f.id=l,await((r=e?.transport)==null?void 0:r.send(f)),p};function _0x21a3(e,t){const n=_0x3610();return _0x21a3=function(r,o){return r=r-(-8023+4*-2344+-17809*-1),n[r]},_0x21a3(e,t)}const forwardServerOnRequest=(e,t)=>{const n=_0x21a3,r=_0x21a3,o={vYlhn:function(s,a){return s===a},DhPFX:n(470),NYVNC:function(s,a,l,c){return s(a,l,c)},yfZbw:"2.0"},i=e._onrequest;e[r(463)]=async(s,a)=>{var l,c,u,p,f;const m=r,g=n,{id:x,method:b}=s;try{o[m(451)](b,o.DhPFX)?await i.call(e,s,a):await o[g(474)](forwardServerRequest,e,t,s)}catch(h){const{code:_,message:E,data:S}=h;try{if(_){const A={};A[g(485)]=_,A[m(422)]=E,A.data=S;const D={};D[g(448)]=A,D.jsonrpc=o[m(417)],D.id=x,await((l=e?.transport)==null?void 0:l[g(460)](D))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,h)}catch(A){(f=(p=e?.transport)==null?void 0:p.onerror)==null||f.call(p,A)}}}},forwardServerOnNotification=(e,t)=>{const n=_0x21a3,r=_0x21a3,o={};o[n(476)]=n(439),o[n(431)]=function(s,a){return s!==a},o.UPdQt="notifications/cancelled";const i=o;e[n(421)]=async s=>{var a,l;const c=n,u=r,{method:p,params:f}=s;if(p!==i[c(476)]&&(i.QWYMz(p,i.UPdQt)||f?.[u(490)]))try{await t[c(445)](s)}catch(m){(l=(a=e?.[c(488)])==null?void 0:a[c(480)])==null||l.call(a,m)}}},forwardClientOnRequest=(e,t)=>async n=>{var r,o,i,s,a;const l=_0x21a3,c=_0x21a3,u={TJhyV:function(p,f,m,g){return p(f,m,g)},MMNTY:l(465)};try{return await u.TJhyV(forwardClientRequest,e,t,n)}catch(p){const{code:f,message:m,data:g}=p;try{if(f){const x={};x.code=f,x[l(422)]=m,x[c(419)]=g;const b={};b[l(448)]=x,b[l(424)]=u.MMNTY,b.id=n.id,await((r=e?.transport)==null?void 0:r[c(460)](b))}else(i=(o=e?.transport)==null?void 0:o[l(480)])==null||i.call(o,p)}catch(x){(a=(s=e?.[l(488)])==null?void 0:s.onerror)==null||a.call(s,x)}}},forwardClientOnNotification=(e,t)=>async n=>{var r,o,i;const s=_0x21a3,a=_0x21a3,l={};l.xmcLM=function(f,m){return f!==m},l.xSWLt="notifications/initialized",l[s(420)]=a(453);const c=l,{method:u,params:p}=n;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[a(420)])||p?.[a(490)]))try{const f={...n};f.jsonrpc=s(465),await((r=t?.[s(488)])==null?void 0:r.send(f))}catch(f){(i=(o=e?.transport)==null?void 0:o.onerror)==null||i.call(o,f)}};function _0x3610(){const e=["JMaxV","cNneM","completion/complete","addResponseListener","notifications/initialized","call","570686biwZQB","kkNqg","level","addNotificationListener","notification","params","addListener","error","_onresponse","164054EGcqjc","vYlhn","1PDRdga","notifications/cancelled","_requestHandlers","readResource","FjTAY","1782ueLDLp","4496TJFZWc","1767765yPcVQJ","send","HefvS","elicitation/create","_onrequest","logging/setLevel","2.0","SoCaE","HucXo","function","request","initialize","push","dEmVs","addRequestListener","NYVNC","fgMSD","CSjwA","prompts/list","ping","35pZrnNj","onerror","method","238086YifXhM","get","sthgI","code","resources/subscribe","sttJM","transport","jsmFN","forward","listPrompts","resources/unsubscribe","resources/list","srIIC","originalOnResponse","getPrompt","indexOf","3653560KcjkMk","yfZbw","4SAWlvk","data","rCDHw","_onnotification","message","UlqiY","jsonrpc","yCyFn","clearNotificationListener","VWsxO","name","UynHf","length","QWYMz","fallbackRequestHandler","492jTClKn","1028589HsbHVQ"];return _0x3610=function(){return e},_0x3610()}const forwardClientOnResponse=(e,t)=>async n=>{var r,o,i,s,a,l;const c=_0x21a3,u=_0x21a3,p={};p.kSvAZ=c(465);const f=p;try{await((r=t?.[u(488)])==null?void 0:r[u(460)](n))}catch(m){const{code:g,message:x,data:b}=m;try{if(g){const h={};h.code=g,h.message=x,h.data=b;const _={};_.error=h,_[u(424)]=f.kSvAZ,_.id=n.id,await((o=e?.transport)==null?void 0:o.send(_))}else(s=(i=e?.transport)==null?void 0:i[c(480)])==null||s.call(i,m)}catch(h){(l=(a=e?.[c(488)])==null?void 0:a[u(480)])==null||l.call(a,h)}}},createHandleListener=()=>{const e=_0x21a3,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},n=[],r=(l,c)=>{const u=_0x21a3;if(c){const p=[];for(const f of n)try{p.push(f(l,c))}catch{}for(const f of p)if(t.rgPZO(f,null))return f}else for(const p of n)try{t[u(427)](p,l)}catch{}},o=l=>{const c=_0x21a3,u=_0x21a3;typeof l===t[c(456)]&&!n.includes(l)&&n[u(471)](l)},i=l=>{const c=_0x21a3,u=n[c(415)](l);u!==-1&&n.splice(u,-17591+6*2932)},s=()=>{const l=_0x21a3;n[l(430)]=-505*7+1322+2213},a={};return a.handleListener=r,a[e(447)]=o,a.removeListener=i,a.clearListener=s,a},setClientListener=e=>{const t=_0x21a3,n=_0x21a3,r={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:i,removeListener:s,clearListener:a}=r[t(423)](createHandleListener);e._onresponse=o,e[n(438)]=i,e.removeResponseListener=s,e.clearResponseListener=a}{const{handleListener:o,addListener:i,removeListener:s,clearListener:a}=r[t(489)](createHandleListener);e[t(432)]=o,e[n(473)]=i,e.removeRequestListener=s,e.clearRequestListener=a}{const{handleListener:o,addListener:i,removeListener:s,clearListener:a}=r.jsmFN(createHandleListener);e.fallbackNotificationHandler=o,e[t(444)]=i,e.removeNotificationListener=s,e[n(426)]=a}},initClientHandler=(e,{beforeInit:t,afterInit:n}={})=>{const r=_0x21a3,o=_0x21a3,i={HucXo:function(a,l){return a===l},HicFO:r(468),JMaxV:function(a){return a()},DclXr:function(a,l){return a(l)},UynHf:function(a,l){return a===l},yCyFn:function(a){return a()}},s=new Map(e._notificationHandlers);e[r(454)].clear(),e._notificationHandlers.clear(),i.HucXo(typeof t,i.HicFO)&&i[r(435)](t),i[r(467)](e[r(449)][o(428)],r(449))&&(e[o(413)]=e[o(449)]),i.DclXr(setClientListener,e),e[o(438)](a=>{const l=r;e.originalOnResponse[l(440)](e,a)}),i[r(429)](typeof n,i.HicFO)&&i[o(425)](n),e[o(444)](a=>{const l=o,{method:c}=a,u=s[l(483)](c);i[l(467)](typeof u,"function")&&u(a)})},_0x580c11=_0x3345;(function(e,t){const n=_0x3345,r=_0x3345,o=e();for(;;)try{if(parseInt(n(215))/1*(-parseInt(r(217))/2)+parseInt(n(216))/3+parseInt(n(210))/4*(parseInt(r(223))/5)+-parseInt(r(214))/6*(parseInt(r(220))/7)+parseInt(r(212))/8*(parseInt(n(228))/9)+parseInt(n(219))/10+parseInt(n(222))/11*(parseInt(n(224))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(_0x15b2,995159+-6*-266138+-1619768);const randomUUID$1=()=>{const e=_0x3345,t=_0x3345,n={};n.svuxn=function(o,i){return o&i},n.ZUPdr=function(o,i){return o===i},n[e(227)]=function(o,i){return o===i},n.SpRzi="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const r=n;return r[t(227)](typeof crypto,"object")&&crypto[e(211)]?crypto.randomUUID():r.SpRzi.replace(/[xy]/g,o=>{const i=e,s=r.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(r[i(225)](o,"x")?s:r[i(209)](s,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},randomBytes=e=>{const t=_0x3345,n=_0x3345,r=new Uint8Array(e);return crypto[t(221)](r),Array[n(218)](r,o=>o[n(226)](11424+4*-2852).padStart(8950+2237*-4,"0"))[t(213)]("")},_0x5e2e0a={};_0x5e2e0a[_0x580c11(211)]=randomUUID$1,_0x5e2e0a.randomBytes=randomBytes;function _0x3345(e,t){const n=_0x15b2();return _0x3345=function(r,o){return r=r-(-7373+7187*1+395),n[r]},_0x3345(e,t)}function _0x15b2(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return _0x15b2=function(){return e},_0x15b2()}function _0xd139(e,t){const n=_0x3ca7();return _0xd139=function(r,o){return r=r-(-1483*3+-5564+20*513),n[r]},_0xd139(e,t)}const _0x403f63=_0xd139,_0x165645=_0xd139;(function(e,t){const n=_0xd139,r=_0xd139,o=e();for(;;)try{if(parseInt(n(302))/1+-parseInt(r(249))/2+-parseInt(n(291))/3+-parseInt(n(292))/4*(parseInt(n(264))/5)+-parseInt(r(273))/6*(parseInt(n(266))/7)+parseInt(n(300))/8*(parseInt(n(269))/9)+parseInt(r(255))/10*(parseInt(n(284))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(_0x3ca7,-4*308317+753182*2+658196);const forwardProxyClient=(e,t)=>{const n=_0xd139,r=_0xd139,o={olCWX:function(l,c,u){return l(c,u)},sfXDX:function(l,c,u){return l(c,u)},ksWFu:function(l,c,u){return l(c,u)}};o[n(283)](forwardServerOnRequest,e,t),forwardServerOnNotification(e,t);const i=o[r(283)](forwardClientOnRequest,t,e),s=o[r(294)](forwardClientOnResponse,t,e),a=o[n(277)](forwardClientOnNotification,t,e);t.addRequestListener(i),t.addResponseListener(s),t[r(287)](a),e.onclose=()=>{const l=n,c=r;t[l(247)](i),t.removeResponseListener(s),t[c(252)](a)}},initWebClientHandler=(e,t,n)=>{const r={QhPqi:function(s,a){return s instanceof a},AIICR:"close",Qalmc:function(s,a,l){return s(a,l)}},o=()=>{var s;r.QhPqi(n,sse_js.SSEClientTransport)&&((s=n._eventSource)==null||s.addEventListener(r.AIICR,()=>{var a;(a=n[_0xd139(295)])==null||a.close()})),r.Qalmc(forwardProxyClient,e,t)},i={};i.afterInit=o,r.Qalmc(initClientHandler,t,i)},sseOptions=(e,t=_0x5e2e0a[_0x403f63(299)]())=>{const n=_0x403f63,r=_0x403f63,o={RVabx:function(u,p,f){return u(p,f)},crCTs:"include"},i={};i["sse-session-id"]=t;const s=i,a={};a["sse-session-id"]=t;const l={};l.headers=a,l.credentials=o[n(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,p){const f=n,m=n,g=new Headers(p?.[f(268)]||{});Object.entries(s).forEach(([b,h])=>{g.set(b,h)});const x={...p};return x.headers=g,o[m(279)](fetch,u,x)},withCredentials:!0}};return e&&(c[n(280)].headers.Authorization="Bearer "+e,s.Authorization=r(256)+e),c},streamOptions=(e,t=_0x5e2e0a[_0x403f63(299)]())=>{const n=_0x165645,r=_0x403f63,o={};o[n(271)]="include";const i=o,s={};s["stream-session-id"]=t;const a={};a[r(268)]=s,a.credentials=i[n(271)];const l={};l.requestInit=a;const c=l;return e&&(c[r(280)][n(268)][r(301)]=n(256)+e),c},attemptConnection=async(e,t,n)=>{const r=_0x403f63,o=_0x403f63,i={rRtFD:function(a){return a()},ToRAF:function(a,l){return a instanceof l}},s=i[r(276)](n);try{return await e[o(260)](s),s}catch(a){if(i[r(275)](a,auth_js.UnauthorizedError)){const l=await t();return await s[r(257)](l),await attemptConnection(e,t,n)}else throw a}},getWaitForOAuthCodeFunction=(e,t)=>{const n=_0x165645,r=_0x165645,o={};o[n(267)]=function(s,a){return s in a},o.timcZ="waitForOAuthCode",o[n(253)]=function(s,a){return s===a},o.ufiEQ=n(285),o[r(250)]=n(293);const i=o;if(i.oGmBG(i[n(258)],e))return e[r(278)];if(i[r(253)](typeof t,i.ufiEQ))return t;throw new Error(i.daYBw)};function _0x3ca7(){const e=["oGmBG","headers","1233BqDPfE","eventSourceInit","jmVYh","wfHUn","1336686qzpbXm","_endpoint","ToRAF","rRtFD","ksWFu","waitForOAuthCode","RVabx","requestInit","mcp-sse-proxy-client","CfBXU","olCWX","341WrxLOu","function","sessionId","addNotificationListener","version","GKDjq","roots","5390433vAXkON","4NpGpPF","waitForOAuthCode need to be provided when authProvider is provided","sfXDX","_eventSource","PdsSn","get","sampling","randomUUID","4064jocfPO","Authorization","452565rqIeHi","elicitation","crCTs","authProvider","removeRequestListener","1.0.0","104070FoHgyi","daYBw","capabilities","removeNotificationListener","lauIp","listChanged","1255910ovFXHu","Bearer ","finishAuth","timcZ","eZwNI","connect","JzpWy","tUMle","kdowC","379385gxVFVP","&token=","49TIzdXg"];return _0x3ca7=function(){return e},_0x3ca7()}const createSseProxy=async e=>{const t=_0x165645,n=_0x403f63,r={GKDjq:function(N,H,V){return N(H,V)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(N){return N()},kdowC:function(N,H,V,Z){return N(H,V,Z)},KkViY:"sessionId"},{client:o,url:i,token:s,sessionId:a,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:p}=e,f={};f[n(305)]=l,f.requestInit=c,f.eventSourceInit=u;const m=f,g=a||_0x5e2e0a[n(299)](),x=r[t(289)](sseOptions,s,g);if(c){const N={...x.requestInit,...c};N[n(268)]={...x[n(280)][t(268)],...c.headers},m.requestInit=N}else m.requestInit=x[t(280)];if(u){const N={...x[t(270)],...u};m.eventSourceInit=N}else m.eventSourceInit=x[t(270)];const b={};b[t(254)]=!0;const h={};h.roots=b,h[t(298)]={},h[n(303)]={};const _=h,E={};E.name=r[n(261)],E[t(288)]=r.mcbiU;const S={};S[t(251)]=_;const A=new index_js.Client(E,S),D=()=>new sse_js.SSEClientTransport(new URL(i),m);let M=r[t(282)](D);if(l){const N=getWaitForOAuthCodeFunction(l,p);M=await r[t(263)](attemptConnection,A,N,D)}else await A.connect(M);initWebClientHandler(A,o,M),M.sessionId=M[n(274)].searchParams[t(297)](r.KkViY);const W={};return W.transport=M,W.sessionId=M[n(286)],W},createStreamProxy=async e=>{const t=_0x165645,n=_0x403f63,r={wfHUn:function(N,H,V){return N(H,V)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(N){return N()},PdsSn:function(N,H,V,Z){return N(H,V,Z)}},{client:o,url:i,token:s,sessionId:a,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:p}=e,f={};f.authProvider=l,f.requestInit=c,f.reconnectionOptions=u;const m=f,g=a||_0x5e2e0a.randomUUID(),x=r[n(272)](streamOptions,s,g);if(c){const N={...x[t(280)],...c};N.headers={...x.requestInit[t(268)],...c.headers},m.requestInit=N}else m[n(280)]=x[n(280)];const b={};b[n(254)]=!0;const h={};h.roots=b,h[t(298)]={},h[t(303)]={};const _=h,E={};E.name=r[t(262)],E.version=r.omKPe;const S={};S.capabilities=_;const A=new index_js.Client(E,S),D=()=>new streamableHttp_js.StreamableHTTPClientTransport(new URL(i),m);let M=r.rSiEq(D);if(l){const N=r[t(272)](getWaitForOAuthCodeFunction,l,p);M=await r[t(296)](attemptConnection,A,N,D)}else await A[t(260)](M);r.PdsSn(initWebClientHandler,A,o,M);const W={};return W.transport=M,W[n(286)]=M[n(286)],W},createSocketProxy=async e=>{const t=_0x403f63,n=_0x403f63,r={eZwNI:function(h,_,E,S){return h(_,E,S)}},{client:o,url:i,token:s,sessionId:a}=e,l={};l[t(254)]=!0;const c={};c[n(290)]=l,c.sampling={},c.elicitation={};const u=c,p={};p.name="mcp-socket-proxy-client",p.version=n(248);const f={};f[n(251)]=u;const m=new index_js.Client(p,f),g=a||_0x5e2e0a[n(299)](),x=new websocket_js.WebSocketClientTransport(new URL(i+"?sessionId="+g+n(265)+s));await m.connect(x),r[t(259)](initWebClientHandler,m,o,x);const b={};return b.transport=x,b[n(286)]=g,b},_0x5d6a74=_0x155f,_0x2395ea=_0x155f;(function(e,t){const n=_0x155f,r=_0x155f,o=e();for(;;)try{if(parseInt(n(216))/1+-parseInt(r(219))/2+-parseInt(n(203))/3*(-parseInt(r(204))/4)+-parseInt(r(199))/5*(parseInt(n(193))/6)+-parseInt(n(211))/7*(-parseInt(n(192))/8)+-parseInt(r(221))/9+parseInt(r(201))/10*(parseInt(n(220))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(_0x3878,1297719+-42747*-22+-1289197);function _0x155f(e,t){const n=_0x3878();return _0x155f=function(r,o){return r=r-(-4158*1+-2*581+-1*-5510),n[r]},_0x155f(e,t)}const generateStateFunction=()=>_0x5e2e0a.randomBytes(-8746+-382*-23);class AuthClientProvider{constructor(t){const n=_0x155f,r=_0x155f,o={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:i,state:s,redirectCallback:a,getAuthCodeByState:l,waitForOAuthCode:c}=t;this._clientMetadata=i,this[n(206)]=i.redirect_uris[-10*629+1*7646+-1356],this[r(197)]=s||o.HbwOh(generateStateFunction),this._redirectCallback=a||this[r(202)],this[r(195)]=l||this[n(191)],this.waitForOAuthCode=c||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var n,r,o,i,s,a;const l=_0x155f,c=_0x155f,u={};u[l(198)]="GET";const p=await fetch(t,u);!p.ok&&((r=(n=this[c(207)])[c(196)])==null||r.call(n,l(208)+p[c(205)]));const f=await this[c(195)](this._redirectUrl,this[l(197)]);if(!f.ok){(i=(o=this[l(207)]).reject)==null||i.call(o,"Failed to fetch auth code: "+f[c(205)]);return}const m=await f.json();(a=(s=this._callBackPromise).resolve)==null||a.call(s,m.code)}async[_0x5d6a74(191)](t,n){const r=_0x5d6a74,o={};o.xAOmI="POST";const i=o,s={};s["Content-Type"]=r(217);const a={};return a.state=n,fetch(t,{method:i.xAOmI,headers:s,body:new URLSearchParams(a)})}waitForOAuthCodeFunction(){const t=this._callBackPromise;return()=>new Promise((n,r)=>{const o=_0x155f;t.resolve=n,t[o(196)]=r})}get redirectUrl(){return this[_0x5d6a74(206)]}get[_0x2395ea(190)](){return this._clientMetadata}[_0x5d6a74(213)](){return this[_0x5d6a74(197)]}[_0x2395ea(218)](){return this[_0x2395ea(200)]}[_0x5d6a74(194)](t){this._clientInformation=t}tokens(){return this[_0x2395ea(210)]}saveTokens(t){const n=_0x2395ea;this[n(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[_0x5d6a74(212)](){const t=_0x5d6a74,n={};n[t(215)]=t(214);const r=n;if(!this[t(209)])throw new Error(r.mMdVl);return this[t(209)]}}function _0x3878(){const e=["370aKMzOb","redirectCallbackFunction","6AWGiLu","697420WEpDtk","statusText","_redirectUrl","_callBackPromise","Failed to redirect: ","_codeVerifier","_tokens","21ofrYNd","codeVerifier","state","No code verifier saved","mMdVl","1546908KURscU","application/x-www-form-urlencoded","clientInformation","2551694UzDoIS","571637jVsNJQ","4355271orhxAD","clientMetadata","getAuthCodeByStateFunction","1400360ybYjeP","30zRTJNb","saveClientInformation","_getAuthCodeByState","reject","_state","method","1634810cQPomO","_clientInformation"];return _0x3878=function(){return e},_0x3878()}(function(e,t){for(var n=_0x275e,r=_0x275e,o=e();;)try{var i=parseInt(n(291))/1+-parseInt(n(295))/2*(parseInt(n(288))/3)+parseInt(n(290))/4*(parseInt(n(296))/5)+-parseInt(r(289))/6+parseInt(n(293))/7*(-parseInt(r(294))/8)+parseInt(r(287))/9+parseInt(r(292))/10;if(i===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(_0x204d,262*-2438+1346066*-1+2*1373311);function _0x204d(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return _0x204d=function(){return e},_0x204d()}function _0x275e(e,t){var n=_0x204d();return _0x275e=function(r,o){r=r-287;var i=n[r];return i},_0x275e(e,t)}class WebMcpServer{constructor(t,n){const r={name:"web-mcp-server",version:"1.0.0"},o={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new mcp_js.McpServer(t||r,n||{capabilities:o}),this.server.server.oninitialized=()=>{this.oninitialized?.()},this.server.server.onclose=()=>{this.onclose?.()},this.server.server.onerror=i=>{this.onerror?.(i)},this.server.server.setRequestHandler(types_js.SetLevelRequestSchema,async()=>({}))}async connect(t){return typeof t.start=="function"?(this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0):(this.transport=new MessageChannelServerTransport(t),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(t,n,r){return this.server.registerTool(t,n,r)}registerPrompt(t,n,r){return this.server.registerPrompt(t,n,r)}registerResource(t,n,r,o){return typeof n=="string"?this.server.registerResource(t,n,r,o):this.server.registerResource(t,n,r,o)}isConnected(){return this.server.isConnected()}sendResourceListChanged(){this.server.sendResourceListChanged()}sendToolListChanged(){this.server.sendToolListChanged()}sendPromptListChanged(){this.server.sendPromptListChanged()}getClientCapabilities(){return this.server.server.getClientCapabilities()}getClientVersion(){return this.server.server.getClientVersion()}async ping(){return await this.server.server.ping()}async createMessage(t,n){return await this.server.server.createMessage(t,n)}async elicitInput(t,n){return await this.server.server.elicitInput(t,n)}async listRoots(t,n){return await this.server.server.listRoots(t,n)}async sendLoggingMessage(t){return await this.server.server.sendLoggingMessage(t)}async sendResourceUpdated(t){return await this.server.server.sendResourceUpdated(t)}request(t,n,r){return this.server.server.request(t,n,r)}async notification(t,n){return await this.server.server.notification(t,n)}setRequestHandler(t,n){this.server.server.setRequestHandler(t,n)}removeRequestHandler(t){this.server.server.removeRequestHandler(t)}setNotificationHandler(t,n){this.server.server.setNotificationHandler(t,n)}removeNotificationHandler(t){this.server.server.removeNotificationHandler(t)}onSubscribe(t){this.server.server.setRequestHandler(types_js.SubscribeRequestSchema,t)}onUnsubscribe(t){this.server.server.setRequestHandler(types_js.UnsubscribeRequestSchema,t)}onSetLogLevel(t){this.server.server.setRequestHandler(types_js.SetLevelRequestSchema,t)}onListResources(t){this.server.server.setRequestHandler(types_js.ListResourcesRequestSchema,t)}onRootsListChanged(t){this.server.server.setNotificationHandler(types_js.RootsListChangedNotificationSchema,t)}async onPagehide(t){t.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const createMessageChannelServerTransport=(e,t)=>new MessageChannelServerTransport(e,t),createMessageChannelPairTransport=()=>createTransportPair(),isMessageChannelServerTransport=e=>e instanceof MessageChannelServerTransport,isMcpServer=e=>e instanceof mcp_js.McpServer,setupBuiltinProxy=e=>{const t=()=>typeof navigator>"u"?null:navigator.modelContextTesting||null;e.onmessage=async n=>{if(!n||typeof n!="object")return;const r=n.id,o=n.method;try{if(o==="initialize")await e.send({jsonrpc:"2.0",id:r,result:{protocolVersion:"2024-11-05",capabilities:{tools:{listChanged:!0},logging:{}},serverInfo:{name:"browser-builtin-webmcp-proxy",version:"1.0.0"}}});else if(o!=="notifications/initialized")if(o==="ping"||o==="custom_ping")await e.send({jsonrpc:"2.0",id:r,result:{}});else if(o==="tools/list"){const i=t();if(i&&i.listTools){const a=(await i.listTools()).map(l=>{let c={};if(typeof l.inputSchema=="string")try{c=JSON.parse(l.inputSchema)}catch(u){console.error("Failed to parse inputSchema:",u)}else typeof l.inputSchema=="object"&&l.inputSchema!==null&&(c=l.inputSchema);return{name:l.name,description:l.description||"",inputSchema:{type:"object",properties:c.properties||{},required:c.required||[]}}});await e.send({jsonrpc:"2.0",id:r,result:{tools:a}})}else await e.send({jsonrpc:"2.0",id:r,result:{tools:[]}})}else if(o==="tools/call"){const i=t();if(i&&i.executeTool){if(!n.params||typeof n.params!="object"||!n.params.name){const u=new Error('Invalid params: "name" is required and params must be an object');throw u.code=-32602,u}const{name:s,arguments:a}=n.params,l=await i.executeTool(s,JSON.stringify(a||{})),c=l&&typeof l=="object"&&"content"in l?l:{content:[{type:"text",text:typeof l=="string"?l:JSON.stringify(l)}]};await e.send({jsonrpc:"2.0",id:r,result:c})}else{const s=new Error("executeTool not implemented in Browser built-in WebMCP");throw s.code=-32601,s}}else o==="logging/setLevel"?await e.send({jsonrpc:"2.0",id:r,result:{}}):o==="prompts/list"?await e.send({jsonrpc:"2.0",id:r,result:{prompts:[]}}):o==="resources/list"?await e.send({jsonrpc:"2.0",id:r,result:{resources:[]}}):r!==void 0&&await e.send({jsonrpc:"2.0",id:r,error:{code:-32601,message:`Method not found: ${o}`}})}catch(i){r!==void 0&&await e.send({jsonrpc:"2.0",id:r,error:{code:i.code||-32e3,message:i.message||String(i)}})}}};class WebMcpClient{constructor(t,n){const r={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new index_js.Client(t||r,n||{capabilities:o}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=i=>{this.onerror?.(i)}}async connect(t){if(typeof t.start=="function")return this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:n,token:r,sessionId:o,type:i,agent:s,builtin:a,onError:l}=t;if(s){const p={client:this.client,url:n,token:r,sessionId:o},f=i==="sse"?await createSseProxy(p):i==="socket"?await createSocketProxy(p):await createStreamProxy(p);return f.transport.onerror=async m=>{l?.(m)},a&&setupBuiltinProxy(f.transport),f}const c=new URL(n);let u;if(i==="channel"&&(u=new MessageChannelClientTransport(n),await this.client.connect(u)),i==="sse"){const p=sseOptions(r,o);u=new sse_js.SSEClientTransport(c,p),await this.client.connect(u)}if(i==="socket"&&(u=new websocket_js.WebSocketClientTransport(new URL(`${n}?sessionId=${o}&token=${r}`)),u.sessionId=o,await this.client.connect(u)),i==="stream"||typeof u>"u"){const p=streamOptions(r,o);u=new streamableHttp_js.StreamableHTTPClientTransport(c,p),await this.client.connect(u)}return this.transport=u,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(t){return await this.client.ping(t)}async complete(t,n){return await this.client.complete(t,n)}async setLoggingLevel(t,n){return await this.client.setLoggingLevel(t,n)}async getPrompt(t,n){return await this.client.getPrompt(t,n)}async listPrompts(t,n){return await this.client.listPrompts(t,n)}async listResources(t,n){return await this.client.listResources(t,n)}async listResourceTemplates(t,n){return await this.client.listResourceTemplates(t,n)}async readResource(t,n){return await this.client.readResource(t,n)}async subscribeResource(t,n){return await this.client.subscribeResource(t,n)}async unsubscribeResource(t,n){return await this.client.unsubscribeResource(t,n)}async callTool(t,n){return await this.client.callTool(t,types_js.CallToolResultSchema,n)}async listTools(t,n){return await this.client.listTools(t,n)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(t,n,r){return this.client.request(t,n,r)}async notification(t,n){return await this.client.notification(t,n)}setRequestHandler(t,n){this.client.setRequestHandler(t,n)}removeRequestHandler(t){this.client.removeRequestHandler(t)}setNotificationHandler(t,n){this.client.setNotificationHandler(t,n)}removeNotificationHandler(t){this.client.removeNotificationHandler(t)}onElicit(t){this.client.setRequestHandler(types_js.ElicitRequestSchema,t)}onCreateMessage(t){this.client.setRequestHandler(types_js.CreateMessageRequestSchema,t)}onListRoots(t){this.client.setRequestHandler(types_js.ListRootsRequestSchema,t)}onToolListChanged(t){this.client.setNotificationHandler(types_js.ToolListChangedNotificationSchema,t)}onPromptListChanged(t){this.client.setNotificationHandler(types_js.PromptListChangedNotificationSchema,t)}onResourceListChanged(t){this.client.setNotificationHandler(types_js.ResourceListChangedNotificationSchema,t)}onResourceUpdated(t){this.client.setNotificationHandler(types_js.ResourceUpdatedNotificationSchema,t)}onLoggingMessage(t){this.client.setNotificationHandler(types_js.LoggingMessageNotificationSchema,t)}async onPagehide(t){t.persisted||(isStreamableHTTPClientTransport(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const createSSEClientTransport=(e,t)=>new sse_js.SSEClientTransport(e,t),createStreamableHTTPClientTransport=(e,t)=>new streamableHttp_js.StreamableHTTPClientTransport(e,t),createMessageChannelClientTransport=(e,t)=>new MessageChannelClientTransport(e,t),isSSEClientTransport=e=>e instanceof sse_js.SSEClientTransport,isStreamableHTTPClientTransport=e=>e instanceof streamableHttp_js.StreamableHTTPClientTransport,isMessageChannelClientTransport=e=>e instanceof MessageChannelClientTransport,isMcpClient=e=>e instanceof index_js.Client,randomUUID=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)}),sendWindowMessage=(e,t,n)=>{window.postMessage({type:e,direction:n,data:t},"*")},onWindowMessage=(e,t,n)=>{const r=async function(o){o.source===window&&o.data.type===e&&o.data.direction===n&&await t(o.data.data)};return window.addEventListener("message",r),()=>window.removeEventListener("message",r)};class ExtensionPageServerTransport{constructor(t=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||randomUUID(),this._messageListener2=onWindowMessage("mcp-client-to-server-to-page",n=>{if(n.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",n.mcpMessage);const r=types_js.JSONRPCMessageSchema.parse(n.mcpMessage);this.onmessage?.(r),n.mcpMessage.params?.name&&sendWindowMessage("update-page-app-message",{status:"run",message:n.mcpMessage.params?.name},"page->content")},"content->page")}_throwError(t,n){if(t()){const r=new Error(n);throw console.log(n,r),this.onerror&&this.onerror(r),r}}async start(){if(!this._isStarted){if(this._isClosed)throw new Error("【Page Svr Transport】 已关闭,无法重新启动");this._isStarted=!0}}async send(t,n){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),sendWindowMessage("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:t},"page->content"),"result"in t&&t.result?.content&&sendWindowMessage("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(t){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=t;try{sendWindowMessage("mcp-server-register-from-page",{sessionId:this.sessionId,serverInfo:{...t,url:window.location.origin,title:document.title}},"page->content")}catch(n){this._throwError(()=>!0,"【Page Svr Transport】 注册 server 失败"+String(n))}}async close(){if(!this._isClosed)try{this._messageListener2&&this._messageListener2(),this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(t){this._throwError(()=>!0,"【Page Svr Transport】 关闭时发生错误"+String(t))}}}function deepCompareStrict(e,t){const n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const r=e.length;if(r!==t.length)return!1;for(let o=0;o<r;o++)if(!deepCompareStrict(e[o],t[o]))return!1;return!0}if(n==="object"){if(!e||!t)return e===t;const r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(const s of r)if(!deepCompareStrict(e[s],t[s]))return!1;return!0}return e===t}function encodePointer(e){return encodeURI(escapePointer(e))}function escapePointer(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}const schemaArrayKeyword={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},schemaMapKeyword={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},ignoredKeyword={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let initialBaseURI=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function dereference(e,t=Object.create(null),n=initialBaseURI,r=""){if(e&&typeof e=="object"&&!Array.isArray(e)){const i=e.$id||e.id;if(i){const s=new URL(i,n.href);s.hash.length>1?t[s.href]=e:(s.hash="",r===""?n=s:dereference(e,t,n))}}else if(e!==!0&&e!==!1)return t;const o=n.href+(r?"#"+r:"");if(t[o]!==void 0)throw new Error(`Duplicate schema URI "${o}".`);if(t[o]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:o}),e.$ref&&e.__absolute_ref__===void 0){const i=new URL(e.$ref,n.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){const i=new URL(e.$recursiveRef,n.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){const i=new URL("#"+e.$anchor,n.href);t[i.href]=e}for(let i in e){if(ignoredKeyword[i])continue;const s=`${r}/${encodePointer(i)}`,a=e[i];if(Array.isArray(a)){if(schemaArrayKeyword[i]){const l=a.length;for(let c=0;c<l;c++)dereference(a[c],t,n,`${s}/${c}`)}}else if(schemaMapKeyword[i])for(let l in a)dereference(a[l],t,n,`${s}/${encodePointer(l)}`);else dereference(a,t,n,s)}return t}const DATE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DAYS=[0,31,28,31,30,31,30,31,31,30,31,30,31],TIME=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,HOSTNAME=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,URIREF=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,URITEMPLATE=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,URL_=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,UUID=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,JSON_POINTER=/^(?:\/(?:[^~/]|~0|~1)*)*$/,JSON_POINTER_URI_FRAGMENT=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,RELATIVE_JSON_POINTER=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,EMAIL=e=>{if(e[0]==='"')return!1;const[t,n,...r]=e.split("@");return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},IPV4=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,IPV6=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,DURATION=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function bind(e){return e.test.bind(e)}const format={date,time:time.bind(void 0,!1),"date-time":date_time,duration:DURATION,uri,"uri-reference":bind(URIREF),"uri-template":bind(URITEMPLATE),url:bind(URL_),email:EMAIL,hostname:bind(HOSTNAME),ipv4:bind(IPV4),ipv6:bind(IPV6),regex,uuid:bind(UUID),"json-pointer":bind(JSON_POINTER),"json-pointer-uri-fragment":bind(JSON_POINTER_URI_FRAGMENT),"relative-json-pointer":bind(RELATIVE_JSON_POINTER)};function isLeapYear(e){return e%4===0&&(e%100!==0||e%400===0)}function date(e){const t=e.match(DATE);if(!t)return!1;const n=+t[1],r=+t[2],o=+t[3];return r>=1&&r<=12&&o>=1&&o<=(r==2&&isLeapYear(n)?29:DAYS[r])}function time(e,t){const n=t.match(TIME);if(!n)return!1;const r=+n[1],o=+n[2],i=+n[3],s=!!n[5];return(r<=23&&o<=59&&i<=59||r==23&&o==59&&i==60)&&(!e||s)}const DATE_TIME_SEPARATOR=/t|\s/i;function date_time(e){const t=e.split(DATE_TIME_SEPARATOR);return t.length==2&&date(t[0])&&time(!0,t[1])}const NOT_URI_FRAGMENT=/\/|:/,URI_PATTERN=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function uri(e){return NOT_URI_FRAGMENT.test(e)&&URI_PATTERN.test(e)}const Z_ANCHOR=/[^\\]\\Z/;function regex(e){if(Z_ANCHOR.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function ucs2length(e){let t=0,n=e.length,r=0,o;for(;r<n;)t++,o=e.charCodeAt(r++),o>=55296&&o<=56319&&r<n&&(o=e.charCodeAt(r),(o&64512)==56320&&r++);return t}function validate(e,t,n="2019-09",r=dereference(t),o=!0,i=null,s="#",a="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};const c=typeof e;let u;switch(c){case"boolean":case"number":case"string":u=c;break;case"object":e===null?u="null":Array.isArray(e)?u="array":u="object";break;default:throw new Error(`Instances of "${c}" type are not supported.`)}const{$ref:p,$recursiveRef:f,$recursiveAnchor:m,type:g,const:x,enum:b,required:h,not:_,anyOf:E,allOf:S,oneOf:A,if:D,then:M,else:W,format:N,properties:H,patternProperties:V,additionalProperties:Z,unevaluatedProperties:oe,minProperties:Q,maxProperties:te,propertyNames:ie,dependentRequired:ne,dependentSchemas:K,dependencies:J,prefixItems:ce,items:d,additionalItems:w,unevaluatedItems:U,contains:T,minContains:I,maxContains:B,minItems:k,maxItems:F,uniqueItems:O,minimum:z,maximum:Y,exclusiveMinimum:q,exclusiveMaximum:ee,multipleOf:X,minLength:ae,maxLength:re,pattern:de,__absolute_ref__:le,__absolute_recursive_ref__:ue}=t,C=[];if(m===!0&&i===null&&(i=t),f==="#"){const j=i===null?r[ue]:i,$=`${a}/$recursiveRef`,P=validate(e,i===null?t:i,n,r,o,j,s,$,l);P.valid||C.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:$,error:"A subschema had errors."},...P.errors)}if(p!==void 0){const $=r[le||p];if($===void 0){let y=`Unresolved $ref "${p}".`;throw le&&le!==p&&(y+=` Absolute URI "${le}".`),y+=`
2
- Known schemas:
3
- - ${Object.keys(r).join(`
4
- - `)}`,new Error(y)}const P=`${a}/$ref`,v=validate(e,$,n,r,o,i,s,P,l);if(v.valid||C.push({instanceLocation:s,keyword:"$ref",keywordLocation:P,error:"A subschema had errors."},...v.errors),n==="4"||n==="7")return{valid:C.length===0,errors:C}}if(Array.isArray(g)){let j=g.length,$=!1;for(let P=0;P<j;P++)if(u===g[P]||g[P]==="integer"&&u==="number"&&e%1===0&&e===e){$=!0;break}$||C.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${g.join('", "')}".`})}else g==="integer"?(u!=="number"||e%1||e!==e)&&C.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${g}".`}):g!==void 0&&u!==g&&C.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${g}".`});if(x!==void 0&&(u==="object"||u==="array"?deepCompareStrict(e,x)||C.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(x)}.`}):e!==x&&C.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(x)}.`})),b!==void 0&&(u==="object"||u==="array"?b.some(j=>deepCompareStrict(e,j))||C.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(j=>e===j)||C.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),_!==void 0){const j=`${a}/not`;validate(e,_,n,r,o,i,s,j).valid&&C.push({instanceLocation:s,keyword:"not",keywordLocation:j,error:'Instance matched "not" schema.'})}let fe=[];if(E!==void 0){const j=`${a}/anyOf`,$=C.length;let P=!1;for(let v=0;v<E.length;v++){const y=E[v],L=Object.create(l),R=validate(e,y,n,r,o,m===!0?i:null,s,`${j}/${v}`,L);C.push(...R.errors),P=P||R.valid,R.valid&&fe.push(L)}P?C.length=$:C.splice($,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:j,error:"Instance does not match any subschemas."})}if(S!==void 0){const j=`${a}/allOf`,$=C.length;let P=!0;for(let v=0;v<S.length;v++){const y=S[v],L=Object.create(l),R=validate(e,y,n,r,o,m===!0?i:null,s,`${j}/${v}`,L);C.push(...R.errors),P=P&&R.valid,R.valid&&fe.push(L)}P?C.length=$:C.splice($,0,{instanceLocation:s,keyword:"allOf",keywordLocation:j,error:"Instance does not match every subschema."})}if(A!==void 0){const j=`${a}/oneOf`,$=C.length,P=A.filter((v,y)=>{const L=Object.create(l),R=validate(e,v,n,r,o,m===!0?i:null,s,`${j}/${y}`,L);return C.push(...R.errors),R.valid&&fe.push(L),R.valid}).length;P===1?C.length=$:C.splice($,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:j,error:`Instance does not match exactly one subschema (${P} matches).`})}if((u==="object"||u==="array")&&Object.assign(l,...fe),D!==void 0){const j=`${a}/if`;if(validate(e,D,n,r,o,i,s,j,l).valid){if(M!==void 0){const P=validate(e,M,n,r,o,i,s,`${a}/then`,l);P.valid||C.push({instanceLocation:s,keyword:"if",keywordLocation:j,error:'Instance does not match "then" schema.'},...P.errors)}}else if(W!==void 0){const P=validate(e,W,n,r,o,i,s,`${a}/else`,l);P.valid||C.push({instanceLocation:s,keyword:"if",keywordLocation:j,error:'Instance does not match "else" schema.'},...P.errors)}}if(u==="object"){if(h!==void 0)for(const v of h)v in e||C.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${v}".`});const j=Object.keys(e);if(Q!==void 0&&j.length<Q&&C.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${Q} properties.`}),te!==void 0&&j.length>te&&C.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${te} properties.`}),ie!==void 0){const v=`${a}/propertyNames`;for(const y in e){const L=`${s}/${encodePointer(y)}`,R=validate(y,ie,n,r,o,i,L,v);R.valid||C.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:v,error:`Property name "${y}" does not match schema.`},...R.errors)}}if(ne!==void 0){const v=`${a}/dependantRequired`;for(const y in ne)if(y in e){const L=ne[y];for(const R of L)R in e||C.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:v,error:`Instance has "${y}" but does not have "${R}".`})}}if(K!==void 0)for(const v in K){const y=`${a}/dependentSchemas`;if(v in e){const L=validate(e,K[v],n,r,o,i,s,`${y}/${encodePointer(v)}`,l);L.valid||C.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:y,error:`Instance has "${v}" but does not match dependant schema.`},...L.errors)}}if(J!==void 0){const v=`${a}/dependencies`;for(const y in J)if(y in e){const L=J[y];if(Array.isArray(L))for(const R of L)R in e||C.push({instanceLocation:s,keyword:"dependencies",keywordLocation:v,error:`Instance has "${y}" but does not have "${R}".`});else{const R=validate(e,L,n,r,o,i,s,`${v}/${encodePointer(y)}`);R.valid||C.push({instanceLocation:s,keyword:"dependencies",keywordLocation:v,error:`Instance has "${y}" but does not match dependant schema.`},...R.errors)}}}const $=Object.create(null);let P=!1;if(H!==void 0){const v=`${a}/properties`;for(const y in H){if(!(y in e))continue;const L=`${s}/${encodePointer(y)}`,R=validate(e[y],H[y],n,r,o,i,L,`${v}/${encodePointer(y)}`);if(R.valid)l[y]=$[y]=!0;else if(P=o,C.push({instanceLocation:s,keyword:"properties",keywordLocation:v,error:`Property "${y}" does not match schema.`},...R.errors),P)break}}if(!P&&V!==void 0){const v=`${a}/patternProperties`;for(const y in V){const L=new RegExp(y,"u"),R=V[y];for(const G in e){if(!L.test(G))continue;const se=`${s}/${encodePointer(G)}`,pe=validate(e[G],R,n,r,o,i,se,`${v}/${encodePointer(y)}`);pe.valid?l[G]=$[G]=!0:(P=o,C.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:v,error:`Property "${G}" matches pattern "${y}" but does not match associated schema.`},...pe.errors))}}}if(!P&&Z!==void 0){const v=`${a}/additionalProperties`;for(const y in e){if($[y])continue;const L=`${s}/${encodePointer(y)}`,R=validate(e[y],Z,n,r,o,i,L,v);R.valid?l[y]=!0:(P=o,C.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:v,error:`Property "${y}" does not match additional properties schema.`},...R.errors))}}else if(!P&&oe!==void 0){const v=`${a}/unevaluatedProperties`;for(const y in e)if(!l[y]){const L=`${s}/${encodePointer(y)}`,R=validate(e[y],oe,n,r,o,i,L,v);R.valid?l[y]=!0:C.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:v,error:`Property "${y}" does not match unevaluated properties schema.`},...R.errors)}}}else if(u==="array"){F!==void 0&&e.length>F&&C.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${F}).`}),k!==void 0&&e.length<k&&C.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${k}).`});const j=e.length;let $=0,P=!1;if(ce!==void 0){const v=`${a}/prefixItems`,y=Math.min(ce.length,j);for(;$<y;$++){const L=validate(e[$],ce[$],n,r,o,i,`${s}/${$}`,`${v}/${$}`);if(l[$]=!0,!L.valid&&(P=o,C.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:v,error:"Items did not match schema."},...L.errors),P))break}}if(d!==void 0){const v=`${a}/items`;if(Array.isArray(d)){const y=Math.min(d.length,j);for(;$<y;$++){const L=validate(e[$],d[$],n,r,o,i,`${s}/${$}`,`${v}/${$}`);if(l[$]=!0,!L.valid&&(P=o,C.push({instanceLocation:s,keyword:"items",keywordLocation:v,error:"Items did not match schema."},...L.errors),P))break}}else for(;$<j;$++){const y=validate(e[$],d,n,r,o,i,`${s}/${$}`,v);if(l[$]=!0,!y.valid&&(P=o,C.push({instanceLocation:s,keyword:"items",keywordLocation:v,error:"Items did not match schema."},...y.errors),P))break}if(!P&&w!==void 0){const y=`${a}/additionalItems`;for(;$<j;$++){const L=validate(e[$],w,n,r,o,i,`${s}/${$}`,y);l[$]=!0,L.valid||(P=o,C.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:y,error:"Items did not match additional items schema."},...L.errors))}}}if(T!==void 0)if(j===0&&I===void 0)C.push({instanceLocation:s,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(I!==void 0&&j<I)C.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${j}) than minContains (${I}).`});else{const v=`${a}/contains`,y=C.length;let L=0;for(let R=0;R<j;R++){const G=validate(e[R],T,n,r,o,i,`${s}/${R}`,v);G.valid?(l[R]=!0,L++):C.push(...G.errors)}L>=(I||0)&&(C.length=y),I===void 0&&B===void 0&&L===0?C.splice(y,0,{instanceLocation:s,keyword:"contains",keywordLocation:v,error:"Array does not contain item matching schema."}):I!==void 0&&L<I?C.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${I} items matching schema. Only ${L} items were found.`}):B!==void 0&&L>B&&C.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${B} items matching schema. ${L} items were found.`})}if(!P&&U!==void 0){const v=`${a}/unevaluatedItems`;for($;$<j;$++){if(l[$])continue;const y=validate(e[$],U,n,r,o,i,`${s}/${$}`,v);l[$]=!0,y.valid||C.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:v,error:"Items did not match unevaluated items schema."},...y.errors)}}if(O)for(let v=0;v<j;v++){const y=e[v],L=typeof y=="object"&&y!==null;for(let R=0;R<j;R++){if(v===R)continue;const G=e[R];(y===G||L&&(typeof G=="object"&&G!==null)&&deepCompareStrict(y,G))&&(C.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${v} and ${R}.`}),v=Number.MAX_SAFE_INTEGER,R=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(n==="4"?(z!==void 0&&(q===!0&&e<=z||e<z)&&C.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${q?"or equal to ":""} ${z}.`}),Y!==void 0&&(ee===!0&&e>=Y||e>Y)&&C.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${ee?"or equal to ":""} ${Y}.`})):(z!==void 0&&e<z&&C.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${z}.`}),Y!==void 0&&e>Y&&C.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Y}.`}),q!==void 0&&e<=q&&C.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${q}.`}),ee!==void 0&&e>=ee&&C.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${ee}.`})),X!==void 0){const j=e%X;Math.abs(0-j)>=11920929e-14&&Math.abs(X-j)>=11920929e-14&&C.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${X}.`})}}else if(u==="string"){const j=ae===void 0&&re===void 0?0:ucs2length(e);ae!==void 0&&j<ae&&C.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${j} < ${ae}).`}),re!==void 0&&j>re&&C.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${j} > ${re}).`}),de!==void 0&&!new RegExp(de,"u").test(e)&&C.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),N!==void 0&&format[N]&&!format[N](e)&&C.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${N}".`})}return{valid:C.length===0,errors:C}}class Validator{schema;draft;shortCircuit;lookup;constructor(t,n="2019-09",r=!0){this.schema=t,this.draft=n,this.shortCircuit=r,this.lookup=dereference(t)}validate(t){return validate(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),dereference(t,this.lookup)}}const FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE="Failed to parse input arguments",TOOL_INVOCATION_FAILED_MESSAGE="Tool was executed but the invocation failed. For example, the script function threw an error",TOOL_CANCELLED_MESSAGE="Tool was cancelled",DEFAULT_INPUT_SCHEMA={type:"object",properties:{}},STANDARD_JSON_SCHEMA_TARGETS=["draft-2020-12","draft-07"],POLYFILL_MARKER_PROPERTY="__isWebMCPPolyfill",STANDARD_VALIDATOR_SYMBOL=Symbol("standardValidator"),installState={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1};var StrictWebMCPContext=class extends EventTarget{tools=new Map;testingShim=null;_ontoolchange=null;unregisterToolDeprecationWarned=!1;get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerTool(e,t){const n=t?.signal;if(n?.aborted){console.warn(`[WebMCPPolyfill] registerTool("${e?.name??"<unknown>"}") skipped: options.signal was already aborted.`);return}const r=normalizeToolDescriptor(e,this.tools);this.tools.set(r.name,r),this.notifyToolsChanged(),n&&n.addEventListener("abort",()=>{this.tools.delete(r.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(e){this.warnUnregisterToolDeprecationOnce();const t=getToolNameForUnregister(e);this.tools.delete(t)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(e,t,n){return this.executeToolByName(e.name,t,n,!1)}getTestingShim(){return this.testingShim||(this.testingShim=new PolyfillTestingShim(this)),this.testingShim}getToolInfos(){return[...this.tools.values()].map(e=>{let t;try{t=JSON.stringify(e.inputSchema??{type:"object"})}catch{t='{"type":"object"}'}return{name:e.name,description:e.description,inputSchema:t}})}getRegisteredToolInfos(){return this.getToolInfos().map(e=>{const t=this.tools.get(e.name);return{...e,title:t?.title??"",origin:globalThis.location?.origin??"",window:globalThis.window}})}async executeToolForTesting(e,t,n){return this.executeToolByName(e,t,n,!0)}async executeToolByName(e,t,n,r){if(n?.signal?.aborted)throw createUnknownError(TOOL_CANCELLED_MESSAGE);const o=this.tools.get(e);if(!o)throw createUnknownError(`Tool not found: ${e}`);const i=parseInputArgsJson(t),s=await validateArgsForTool(i,o);if(s)throw createUnknownError(s);let a=!0;const l={requestUserInteraction:async c=>{if(!a)throw new Error(`ModelContextClient for tool "${e}" is no longer active after execute() resolved`);if(typeof c!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return c()}};try{const c=o.execute(i,l),u=await withAbortSignal(Promise.resolve(c),n?.signal);if(r)return toSerializedTestingResult(normalizeToolResponse(u));const p=JSON.stringify(u);return p===void 0?null:p}catch(c){throw createUnknownError(c instanceof Error?`${TOOL_INVOCATION_FAILED_MESSAGE}: ${c.message}`:TOOL_INVOCATION_FAILED_MESSAGE)}finally{a=!1}}notifyToolsChanged(){queueMicrotask(()=>{const e=new Event("toolchange");try{this._ontoolchange?.call(this,e)}catch(t){console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:",t)}this.dispatchEvent(e),this.testingShim?.dispatchToolChange()})}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) — pass an AbortSignal and abort it to unregister."))}},PolyfillTestingShim=class extends EventTarget{context;_ontoolchange=null;constructor(e){super(),this.context=e}listTools(){return this.context.getToolInfos()}executeTool(e,t,n){return this.context.executeToolForTesting(e,t,n)}getCrossDocumentScriptToolResult(){return Promise.resolve("[]")}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerToolsChangedCallback(e){if(typeof e!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.addEventListener("toolchange",e)}dispatchToolChange(){const e=new Event("toolchange");try{this._ontoolchange?.call(this,e)}catch(t){console.warn("[WebMCPPolyfill] ontoolchange handler threw:",t)}this.dispatchEvent(e),this.dispatchEvent(new Event("toolschanged"))}};function createUnknownError(e){try{return new DOMException(e,"UnknownError")}catch{const t=new Error(e);return t.name="UnknownError",t}}function parseInputArgsJson(e){let t;try{t=JSON.parse(e)}catch{throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE)}if(!t||typeof t!="object"||Array.isArray(t))throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE);return t}function getToolNameForUnregister(e){if(typeof e=="string")return e;if(isPlainObject(e)&&typeof e.name=="string")return e.name;throw new TypeError("Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.")}function isPlainObject(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function getStandardProps(e){if(!isPlainObject(e))return null;const t=e["~standard"];return isPlainObject(t)?t:null}function isStandardInputValidatorSchema(e){const t=getStandardProps(e);return!!(t&&t.version===1&&typeof t.validate=="function")}function isStandardInputJsonSchema(e){const t=getStandardProps(e);return!t||t.version!==1||!isPlainObject(t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function createStandardValidatorFromJsonSchema(e){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(t){if(!isPlainObject(t))return{issues:[{message:"expected object arguments"}]};const n=validateArgsWithSchema(t,e);return n?{issues:[n]}:{value:t}}}}}function convertStandardInputSchema(e){for(const t of STANDARD_JSON_SCHEMA_TARGETS)try{const n=e["~standard"].jsonSchema.input({target:t});return validateInputSchema(n),n}catch(n){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${t}":`,n)}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function normalizeInputSchema(e){if(e===void 0){const n=DEFAULT_INPUT_SCHEMA;return{inputSchema:n,standardValidator:createStandardValidatorFromJsonSchema(n)}}if(isStandardInputJsonSchema(e)){const n=convertStandardInputSchema(e);return{inputSchema:n,standardValidator:createStandardValidatorFromJsonSchema(n)}}if(isStandardInputValidatorSchema(e))return{inputSchema:DEFAULT_INPUT_SCHEMA,standardValidator:e};if(validateInputSchema(e),Object.keys(e).length===0)return{inputSchema:DEFAULT_INPUT_SCHEMA,standardValidator:createStandardValidatorFromJsonSchema(DEFAULT_INPUT_SCHEMA)};const t=e.type===void 0?{type:"object",...e}:e;return{inputSchema:t,standardValidator:createStandardValidatorFromJsonSchema(t)}}function validateInputSchema(e){if(!isPlainObject(e))throw new Error("inputSchema must be a JSON Schema object");validateJsonSchemaNode(e,"$")}function validateJsonSchemaNode(e,t){const n=e.type;if(n!==void 0&&typeof n!="string"&&!(Array.isArray(n)&&n.every(a=>typeof a=="string"&&a.length>0)))throw new Error(`Invalid JSON Schema at ${t}: "type" must be a string or string[]`);const r=e.required;if(r!==void 0&&!(Array.isArray(r)&&r.every(a=>typeof a=="string")))throw new Error(`Invalid JSON Schema at ${t}: "required" must be an array of strings`);const o=e.properties;if(o!==void 0){if(!isPlainObject(o))throw new Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(const[a,l]of Object.entries(o)){if(!isPlainObject(l))throw new Error(`Invalid JSON Schema at ${t}.properties.${a}: expected object schema`);validateJsonSchemaNode(l,`${t}.properties.${a}`)}}const i=e.items;if(i!==void 0)if(Array.isArray(i))for(const[a,l]of i.entries()){if(!isPlainObject(l))throw new Error(`Invalid JSON Schema at ${t}.items[${a}]: expected object schema`);validateJsonSchemaNode(l,`${t}.items[${a}]`)}else if(isPlainObject(i))validateJsonSchemaNode(i,`${t}.items`);else throw new Error(`Invalid JSON Schema at ${t}: "items" must be an object or object[]`);for(const a of["allOf","anyOf","oneOf"]){const l=e[a];if(l!==void 0){if(!Array.isArray(l))throw new Error(`Invalid JSON Schema at ${t}: "${a}" must be an array`);for(const[c,u]of l.entries()){if(!isPlainObject(u))throw new Error(`Invalid JSON Schema at ${t}.${a}[${c}]: expected object schema`);validateJsonSchemaNode(u,`${t}.${a}[${c}]`)}}}const s=e.not;if(s!==void 0){if(!isPlainObject(s))throw new Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);validateJsonSchemaNode(s,`${t}.not`)}try{JSON.stringify(e)}catch{throw new Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function normalizeToolDescriptor(e,t){if(!e||typeof e!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof e.name!="string"||e.name.length===0)throw new TypeError('Tool "name" must be a non-empty string');if(typeof e.description!="string"||e.description.length===0)throw new TypeError('Tool "description" must be a non-empty string');if(typeof e.execute!="function")throw new TypeError('Tool "execute" must be a function');if(t.has(e.name))throw new Error(`Tool already registered: ${e.name}`);const n=normalizeInputSchema(e.inputSchema),r=e.annotations,o=r?{...r,...r.readOnlyHint==="true"?{readOnlyHint:!0}:r.readOnlyHint==="false"?{readOnlyHint:!1}:{},...r.destructiveHint==="true"?{destructiveHint:!0}:r.destructiveHint==="false"?{destructiveHint:!1}:{},...r.idempotentHint==="true"?{idempotentHint:!0}:r.idempotentHint==="false"?{idempotentHint:!1}:{},...r.openWorldHint==="true"?{openWorldHint:!0}:r.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...e,...o?{annotations:o}:{},inputSchema:n.inputSchema,[STANDARD_VALIDATOR_SYMBOL]:n.standardValidator}}function validateArgsWithSchema(e,t){const n=new Validator(t,"2020-12",!0).validate(e);if(n.valid)return null;const r=n.errors[n.errors.length-1];return r?{message:r.error}:{message:"Input validation failed"}}function formatStandardIssuePath(e){if(!e||e.length===0)return null;const t=e.map(n=>isPlainObject(n)&&"key"in n?n.key:n).map(n=>String(n)).filter(n=>n.length>0);return t.length===0?null:t.join(".")}async function validateArgsWithStandardSchema(e,t){let n;try{n=await Promise.resolve(t["~standard"].validate(e))}catch(i){const s=i instanceof Error?`: ${i.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",i),`Input validation error: schema validation failed${s}`}if(!n.issues||n.issues.length===0)return null;const r=n.issues[0];if(!r)return"Input validation error";const o=formatStandardIssuePath(r?.path);return o?`Input validation error: ${r.message} at ${o}`:`Input validation error: ${r.message}`}async function validateArgsForTool(e,t){return validateArgsWithStandardSchema(e,t[STANDARD_VALIDATOR_SYMBOL])}function isCallToolResult(e){return isPlainObject(e)&&Array.isArray(e.content)}function isJsonPrimitive(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function isJsonValue(e){return isJsonPrimitive(e)?Number.isFinite(e)||typeof e!="number":Array.isArray(e)?e.every(t=>isJsonValue(t)):isPlainObject(e)?Object.values(e).every(t=>isJsonValue(t)):!1}function toStructuredContent(e){if(!(!isPlainObject(e)||!isJsonValue(e)))return e}function serializeTextContent(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function normalizeToolResponse(e){if(isCallToolResult(e))return e;const t=toStructuredContent(e);return{content:[{type:"text",text:serializeTextContent(e)}],...t?{structuredContent:t}:{},isError:!1}}function getFirstTextBlock(e){for(const t of e.content??[])if(t.type==="text"&&"text"in t&&typeof t.text=="string")return t.text;return null}function toSerializedTestingResult(e){if(e.isError)throw createUnknownError(getFirstTextBlock(e)?.replace(/^Error:\s*/i,"").trim()||TOOL_INVOCATION_FAILED_MESSAGE);const t=e.metadata;if(t&&typeof t=="object"&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw createUnknownError(TOOL_INVOCATION_FAILED_MESSAGE)}}function withAbortSignal(e,t){return t?t.aborted?Promise.reject(createUnknownError(TOOL_CANCELLED_MESSAGE)):new Promise((n,r)=>{const o=()=>{i(),r(createUnknownError(TOOL_CANCELLED_MESSAGE))},i=()=>{t.removeEventListener("abort",o)};t.addEventListener("abort",o,{once:!0}),e.then(s=>{i(),n(s)},s=>{i(),r(s)})}):e}function getNavigator(){return typeof navigator<"u"?navigator:null}function getDocument(){return typeof document<"u"?document:null}function defineNavigatorProperty(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:n})}function defineDocumentModelContextProperty(e,t){Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:t})}let navigatorModelContextDeprecationWarned=!1;function defineDeprecatedNavigatorModelContext(e,t){Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,get(){return navigatorModelContextDeprecationWarned||(navigatorModelContextDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document — use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.")),t}})}function initializeWebMCPPolyfill(e){const t=getNavigator(),n=getDocument();if(!t&&!n||n?.modelContext)return;const o=t?.modelContext,i=!!o;if(installState.installed&&cleanupWebMCPPolyfill(),n&&o){installState.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(n,"modelContext"),defineDocumentModelContextProperty(n,o),installState.installedDocumentModelContext=!0,installState.installed=!0;return}if(i)return;const s=new StrictWebMCPContext,a=s;if(a[POLYFILL_MARKER_PROPERTY]=!0,n&&(installState.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(n,"modelContext"),defineDocumentModelContextProperty(n,a),installState.installedDocumentModelContext=!0),t){installState.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(t,"modelContext"),installState.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,"modelContextTesting"),navigatorModelContextDeprecationWarned=!1,defineDeprecatedNavigatorModelContext(t,a),installState.installedNavigatorModelContext=!0;const l=e?.installTestingShim??"if-missing",c=!!t.modelContextTesting;(l==="always"||(l===!0||l==="if-missing")&&!c)&&(defineNavigatorProperty(t,"modelContextTesting",s.getTestingShim()),installState.installedNavigatorModelContextTesting=!0)}installState.installed=!0}function cleanupWebMCPPolyfill(){if(!installState.installed)return;const e=(r,o,i)=>{if(i){Object.defineProperty(r,o,i);return}delete r[o]},t=getNavigator(),n=getDocument();n&&installState.installedDocumentModelContext&&e(n,"modelContext",installState.previousDocumentModelContextDescriptor),t&&installState.installedNavigatorModelContext&&e(t,"modelContext",installState.previousNavigatorModelContextDescriptor),t&&installState.installedNavigatorModelContextTesting&&e(t,"modelContextTesting",installState.previousNavigatorModelContextTestingDescriptor),installState.installed=!1,installState.previousDocumentModelContextDescriptor=void 0,installState.previousNavigatorModelContextDescriptor=void 0,installState.previousNavigatorModelContextTestingDescriptor=void 0,installState.installedDocumentModelContext=!1,installState.installedNavigatorModelContext=!1,installState.installedNavigatorModelContextTesting=!1,navigatorModelContextDeprecationWarned=!1}if(typeof window<"u"&&typeof document<"u"){const e=window.__webMCPPolyfillOptions;if(e?.autoInitialize!==!1)try{initializeWebMCPPolyfill(e)}catch(t){console.error("[WebMCPPolyfill] Auto-initialization failed:",t)}}const isBrowser=()=>typeof window<"u"&&typeof navigator<"u",isDomAvailable=()=>isBrowser()&&typeof document<"u";let overlayElement=null,labelElement=null,styleElement=null,activeCount=0;const BODY_GLOW_CLASS="next-sdk-tool-body-glow";function ensureDomReady(){return isDomAvailable()}function ensureStyleElement(){if(!ensureDomReady()||styleElement)return;const e=document.createElement("style");e.textContent=`
5
- .${BODY_GLOW_CLASS} {
6
- position: relative;
7
- }
8
-
9
- .next-sdk-tool-overlay {
10
- position: fixed;
11
- inset: 0;
12
- z-index: 999999;
13
- pointer-events: none;
14
- display: flex;
15
- align-items: flex-end;
16
- justify-content: flex-start;
17
- padding: 0 0 18px 18px;
18
- background: transparent;
19
- animation: next-sdk-overlay-fade-in 260ms ease-out;
20
- }
21
-
22
- .next-sdk-tool-overlay--exit {
23
- animation: next-sdk-overlay-fade-out 220ms ease-in forwards;
24
- }
25
-
26
- .next-sdk-tool-overlay__glow-ring {
27
- display: none;
28
- }
29
-
30
- .next-sdk-tool-overlay__panel {
31
- position: relative;
32
- min-width: min(320px, 78vw);
33
- max-width: min(420px, 82vw);
34
- padding: 10px 14px;
35
- border-radius: 999px;
36
- background:
37
- linear-gradient(135deg, rgba(15, 23, 42, 0.9), rgba(17, 24, 39, 0.9)),
38
- radial-gradient(circle at top left, rgba(96, 165, 250, 0.25), transparent 55%),
39
- radial-gradient(circle at bottom right, rgba(45, 212, 191, 0.22), transparent 60%);
40
- box-shadow:
41
- 0 12px 28px rgba(15, 23, 42, 0.78),
42
- 0 0 0 1px rgba(148, 163, 184, 0.26);
43
- display: flex;
44
- align-items: center;
45
- gap: 10px;
46
- pointer-events: none;
47
- transform-origin: center;
48
- animation: next-sdk-panel-pop-in 260ms cubic-bezier(0.18, 0.89, 0.32, 1.28);
49
- color: #e5e7eb;
50
- font-family: system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Text", sans-serif;
51
- }
52
-
53
- .next-sdk-tool-overlay__indicator {
54
- width: 26px;
55
- height: 26px;
56
- border-radius: 999px;
57
- background: radial-gradient(circle at 30% 10%, #f9fafb, #93c5fd);
58
- box-shadow:
59
- 0 0 0 1px rgba(191, 219, 254, 0.6),
60
- 0 8px 18px rgba(37, 99, 235, 0.8),
61
- 0 0 28px rgba(56, 189, 248, 0.9);
62
- position: relative;
63
- flex-shrink: 0;
64
- display: flex;
65
- align-items: center;
66
- justify-content: center;
67
- overflow: hidden;
68
- }
69
-
70
- .next-sdk-tool-overlay__indicator-orbit {
71
- position: absolute;
72
- inset: 2px;
73
- border-radius: inherit;
74
- border: 1px solid rgba(248, 250, 252, 0.6);
75
- box-sizing: border-box;
76
- opacity: 0.9;
77
- }
78
-
79
- .next-sdk-tool-overlay__indicator-orbit::before {
80
- content: '';
81
- position: absolute;
82
- width: 6px;
83
- height: 6px;
84
- border-radius: 999px;
85
- background: #f9fafb;
86
- box-shadow:
87
- 0 0 12px rgba(248, 250, 252, 0.9),
88
- 0 0 24px rgba(250, 249, 246, 0.9);
89
- top: 0;
90
- left: 50%;
91
- transform: translate(-50%, -50%);
92
- transform-origin: 50% 18px;
93
- animation: next-sdk-indicator-orbit 1.4s linear infinite;
94
- }
95
-
96
- .next-sdk-tool-overlay__indicator-core {
97
- width: 14px;
98
- height: 14px;
99
- border-radius: inherit;
100
- background: radial-gradient(circle at 30% 20%, #f9fafb, #bfdbfe);
101
- box-shadow:
102
- 0 0 12px rgba(248, 250, 252, 0.9),
103
- 0 0 32px rgba(191, 219, 254, 0.8);
104
- opacity: 0.96;
105
- }
106
-
107
- .next-sdk-tool-overlay__content {
108
- display: flex;
109
- flex-direction: column;
110
- gap: 1px;
111
- min-width: 0;
112
- }
113
-
114
- .next-sdk-tool-overlay__title {
115
- font-size: 11px;
116
- letter-spacing: 0.08em;
117
- text-transform: uppercase;
118
- color: rgba(156, 163, 175, 0.96);
119
- display: flex;
120
- align-items: center;
121
- gap: 6px;
122
- }
123
-
124
- .next-sdk-tool-overlay__title-dot {
125
- width: 6px;
126
- height: 6px;
127
- border-radius: 999px;
128
- background: #22c55e;
129
- box-shadow:
130
- 0 0 8px rgba(34, 197, 94, 0.9),
131
- 0 0 14px rgba(22, 163, 74, 0.9);
132
- }
133
-
134
- .next-sdk-tool-overlay__label {
135
- font-size: 12px;
136
- font-weight: 500;
137
- color: #e5e7eb;
138
- white-space: nowrap;
139
- text-overflow: ellipsis;
140
- overflow: hidden;
141
- }
142
-
143
- @keyframes next-sdk-overlay-fade-in {
144
- from { opacity: 0; }
145
- to { opacity: 1; }
146
- }
147
-
148
- @keyframes next-sdk-overlay-fade-out {
149
- from { opacity: 1; }
150
- to { opacity: 0; }
151
- }
152
-
153
- @keyframes next-sdk-indicator-orbit {
154
- from {
155
- transform: translate(-50%, -50%) rotate(0deg) translateY(0);
156
- }
157
- to {
158
- transform: translate(-50%, -50%) rotate(360deg) translateY(0);
159
- }
160
- }
161
-
162
- @keyframes next-sdk-panel-pop-in {
163
- 0% {
164
- opacity: 0;
165
- transform: scale(0.92) translateY(10px);
166
- }
167
- 100% {
168
- opacity: 1;
169
- transform: scale(1) translateY(0);
170
- }
171
- }
172
- `,document.head.appendChild(e),styleElement=e}function ensureOverlayElement(){if(!ensureDomReady()||overlayElement)return;ensureStyleElement();const e=document.createElement("div");e.className="next-sdk-tool-overlay";const t=document.createElement("div");t.className="next-sdk-tool-overlay__glow-ring";const n=document.createElement("div");n.className="next-sdk-tool-overlay__panel";const r=document.createElement("div");r.className="next-sdk-tool-overlay__indicator";const o=document.createElement("div");o.className="next-sdk-tool-overlay__indicator-orbit";const i=document.createElement("div");i.className="next-sdk-tool-overlay__indicator-core";const s=document.createElement("div");s.className="next-sdk-tool-overlay__content";const a=document.createElement("div");a.className="next-sdk-tool-overlay__title",a.textContent="AI 正在调用页面工具";const l=document.createElement("span");l.className="next-sdk-tool-overlay__title-dot";const c=document.createElement("div");c.className="next-sdk-tool-overlay__label",a.prepend(l),s.appendChild(a),s.appendChild(c),r.appendChild(o),r.appendChild(i),n.appendChild(r),n.appendChild(s),e.appendChild(t),e.appendChild(n),document.body.appendChild(e),overlayElement=e,labelElement=c}function updateOverlay(e){ensureDomReady()&&(ensureOverlayElement(),!(!overlayElement||!labelElement)&&(overlayElement.classList.remove("next-sdk-tool-overlay--exit"),labelElement.textContent=e.label))}function removeOverlayWithAnimation(){if(!overlayElement)return;overlayElement.classList.add("next-sdk-tool-overlay--exit");const e=overlayElement;let t=!1,n;const r=()=>{t||(t=!0,n!==void 0&&(clearTimeout(n),n=void 0),e.parentNode&&e.parentNode.removeChild(e),overlayElement===e&&(overlayElement=null,labelElement=null),e.removeEventListener("animationend",r))};e.addEventListener("animationend",r),n=setTimeout(r,500)}function showToolInvokeEffect(e){ensureDomReady()&&(activeCount+=1,updateOverlay(e))}function hideToolInvokeEffect(){!ensureDomReady()||activeCount<=0||(activeCount-=1,activeCount===0&&removeOverlayWithAnimation())}function resolveRuntimeEffectConfig(e,t,n){if(!n)return;const r=t||e;return typeof n=="boolean"?n?{label:r}:void 0:{label:n.label||r}}const MSG_TOOL_CALL="next-sdk:tool-call",MSG_TOOL_RESPONSE="next-sdk:tool-response",MSG_TOOL_REGISTERED="next-sdk:tool-registered",MSG_TOOL_UNREGISTERED="next-sdk:tool-unregistered",MSG_REMOTER_READY="next-sdk:remoter-ready",activePages=new Map,normalizeRoute=e=>e.replace(/\/+$/,"")||"/",broadcastTargets=new Set;function initBroadcastTargets(){isBrowser()&&broadcastTargets.add({win:window,origin:window.location.origin||"*"})}initBroadcastTargets();function broadcastToolChange(e){if(!isBrowser())return;const t={type:e};broadcastTargets.forEach(({win:n,origin:r})=>{try{n.postMessage(t,r)}catch{}})}function setupIframeRemoterBridge(){isBrowser()&&window.addEventListener("message",e=>{if(e.data?.type!==MSG_REMOTER_READY||!e.source||e.origin!==window.location.origin)return;const t=e.source;broadcastTargets.add({win:t,origin:e.origin||"*"})})}setupIframeRemoterBridge();function isToolReadyOnRoute(e,t){const n=activePages.get(e);return!!n&&n.has(t)}let _navigator=null;function buildPageHandler(e,t,n=3e4,r){return o=>{const i=randomUUID();return new Promise((s,a)=>{let l,c;const u=()=>{clearTimeout(l),window.removeEventListener("message",p),c&&window.removeEventListener("message",c),r&&hideToolInvokeEffect()};l=setTimeout(()=>{u(),a(new Error(`工具 [${e}] 调用超时 (${n}ms),请检查目标页面是否正确调用了 registerPageTool`))},n);const p=b=>{b.source===window&&b.data?.type===MSG_TOOL_RESPONSE&&b.data.callId===i&&(u(),b.data.error?a(new Error(b.data.error)):s(b.data.result))};window.addEventListener("message",p);const f=()=>{window.postMessage({type:MSG_TOOL_CALL,callId:i,toolName:e,route:t,input:o},window.location.origin||"*")};let m=!1;const g=()=>{m||(m=!0,f())};(async()=>{try{if(r&&showToolInvokeEffect(r),isToolReadyOnRoute(t,e)){g();return}c=b=>{b.source!==window||b.data?.type!==MSG_TOOL_REGISTERED||(window.removeEventListener("message",c),g())},window.addEventListener("message",c),isToolReadyOnRoute(t,e)&&(window.removeEventListener("message",c),g())}catch(b){u(),a(b instanceof Error?b:new Error(String(b)))}})()})}}const _registeredTools=new Map;function setupModelContextBridge(){if(typeof document>"u")return;const t=document.modelContext;if(!t||t.__isNextSdkBridgeSetup)return;isBrowser()&&(window.__nextSdkRegisteredTools=()=>Array.from(_registeredTools.values()));const n=t.registerTool?.bind(t),r=t.unregisterTool?.bind(t);typeof n=="function"&&(t.registerTool=(o,i)=>{const s=o.name,a={...o};i?.signal&&i.signal.addEventListener("abort",()=>{_registeredTools.delete(s),broadcastToolChange(MSG_TOOL_UNREGISTERED)});const l=a.routeConfig&&typeof a.routeConfig=="object"&&"route"in a.routeConfig?a.routeConfig:null;if(l){const c=normalizeRoute(l.route),u=resolveRuntimeEffectConfig(s,a.title,l.invokeEffect),p=buildPageHandler(s,c,l.timeout,u);a.execute=p,delete a.routeConfig}_registeredTools.set(s,{name:s,title:o.title,description:o.description,inputSchema:o.inputSchema});try{n(a,i),broadcastToolChange(MSG_TOOL_REGISTERED)}catch{_registeredTools.delete(s)}}),t.unregisterTool=o=>{try{typeof r=="function"&&r(o)}catch{}finally{_registeredTools.delete(o),broadcastToolChange(MSG_TOOL_UNREGISTERED)}},t.__isNextSdkBridgeSetup=!0}let initialized=!1;const initializeBuiltinWebMCP=()=>{if(isBrowser())try{if(initialized)return;initializeWebMCPPolyfill(),setupModelContextBridge(),initialized=!0}catch(e){console.warn("[next-sdk] 自动注入 modelContext polyfill 和桥接同步失败:",e)}},ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use"),defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions=e=>({...defaultOptions,...e}),getRefs=e=>{const t=getDefaultOptions(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}};function addErrorMessage(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function setResponseValueAndErrors(e,t,n,r,o){e[t]=n,addErrorMessage(e,t,r,o)}const getRelativePath=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};var ZodFirstPartyTypeKind;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));function parseAnyDef(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?getRelativePath(t,e.currentPath):t.join("/")}}function parseArrayDef(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(n.items=parseDef(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&setResponseValueAndErrors(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors(n,"minItems",e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function parseBigintDef(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":t.target==="jsonSchema7"?r.inclusive?setResponseValueAndErrors(n,"minimum",r.value,r.message,t):setResponseValueAndErrors(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),setResponseValueAndErrors(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?setResponseValueAndErrors(n,"maximum",r.value,r.message,t):setResponseValueAndErrors(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),setResponseValueAndErrors(n,"maximum",r.value,r.message,t));break;case"multipleOf":setResponseValueAndErrors(n,"multipleOf",r.value,r.message,t);break}return n}function parseBooleanDef(){return{type:"boolean"}}function parseBrandedDef(e,t){return parseDef(e.type._def,t)}const parseCatchDef=(e,t)=>parseDef(e.innerType._def,t);function parseDateDef(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,i)=>parseDateDef(e,t,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(e,t)}}const integerDateParser=(e,t)=>{const n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(const r of e.checks)switch(r.kind){case"min":setResponseValueAndErrors(n,"minimum",r.value,r.message,t);break;case"max":setResponseValueAndErrors(n,"maximum",r.value,r.message,t);break}return n};function parseDefaultDef(e,t){return{...parseDef(e.innerType._def,t),default:e.defaultValue()}}function parseEffectsDef(e,t){return t.effectStrategy==="input"?parseDef(e.schema._def,t):parseAnyDef(t)}function parseEnumDef(e){return{type:"string",enum:Array.from(e.values)}}const isJsonSchema7AllOfType=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function parseIntersectionDef(e,t){const n=[parseDef(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),parseDef(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(i=>!!i);let r=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const o=[];return n.forEach(i=>{if(isJsonSchema7AllOfType(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(r=void 0);else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){const{additionalProperties:a,...l}=i;s=l}else r=void 0;o.push(s)}}),o.length?{allOf:o,...r}:void 0}function parseLiteralDef(e,t){const n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}let emojiRegex;const zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(emojiRegex===void 0&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,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])$/,ipv4Cidr:/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(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:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":setResponseValueAndErrors(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":setResponseValueAndErrors(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":addFormat(n,"email",r.message,t);break;case"format:idn-email":addFormat(n,"idn-email",r.message,t);break;case"pattern:zod":addPattern(n,zodPatterns.email,r.message,t);break}break;case"url":addFormat(n,"uri",r.message,t);break;case"uuid":addFormat(n,"uuid",r.message,t);break;case"regex":addPattern(n,r.regex,r.message,t);break;case"cuid":addPattern(n,zodPatterns.cuid,r.message,t);break;case"cuid2":addPattern(n,zodPatterns.cuid2,r.message,t);break;case"startsWith":addPattern(n,RegExp(`^${escapeLiteralCheckValue(r.value,t)}`),r.message,t);break;case"endsWith":addPattern(n,RegExp(`${escapeLiteralCheckValue(r.value,t)}$`),r.message,t);break;case"datetime":addFormat(n,"date-time",r.message,t);break;case"date":addFormat(n,"date",r.message,t);break;case"time":addFormat(n,"time",r.message,t);break;case"duration":addFormat(n,"duration",r.message,t);break;case"length":setResponseValueAndErrors(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,t),setResponseValueAndErrors(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":{addPattern(n,RegExp(escapeLiteralCheckValue(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&addFormat(n,"ipv4",r.message,t),r.version!=="v4"&&addFormat(n,"ipv6",r.message,t);break}case"base64url":addPattern(n,zodPatterns.base64url,r.message,t);break;case"jwt":addPattern(n,zodPatterns.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&addPattern(n,zodPatterns.ipv4Cidr,r.message,t),r.version!=="v4"&&addPattern(n,zodPatterns.ipv6Cidr,r.message,t);break}case"emoji":addPattern(n,zodPatterns.emoji(),r.message,t);break;case"ulid":{addPattern(n,zodPatterns.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{addFormat(n,"binary",r.message,t);break}case"contentEncoding:base64":{setResponseValueAndErrors(n,"contentEncoding","base64",r.message,t);break}case"pattern:zod":{addPattern(n,zodPatterns.base64,r.message,t);break}}break}case"nanoid":addPattern(n,zodPatterns.nanoid,r.message,t)}return n}function escapeLiteralCheckValue(e,t){return t.patternStrategy==="escape"?escapeNonAlphaNumeric(e):e}const ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(e){let t="";for(let n=0;n<e.length;n++)ALPHA_NUMERIC.has(e[n])||(t+="\\"),t+=e[n];return t}function addFormat(e,t,n,r){e.format||e.anyOf?.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):setResponseValueAndErrors(e,"format",t,n,r)}function addPattern(e,t,n,r){e.pattern||e.allOf?.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:stringifyRegExpWithFlags(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):setResponseValueAndErrors(e,"pattern",stringifyRegExpWithFlags(t,r),n,r)}function stringifyRegExpWithFlags(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},r=n.i?e.source.toLowerCase():e.source;let o="",i=!1,s=!1,a=!1;for(let l=0;l<r.length;l++){if(i){o+=r[l],i=!1;continue}if(n.i){if(s){if(r[l].match(/[a-z]/)){a?(o+=r[l],o+=`${r[l-2]}-${r[l]}`.toUpperCase(),a=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(o+=r[l],a=!0):o+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){o+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(n.m){if(r[l]==="^"){o+=`(^|(?<=[\r
173
- ]))`;continue}else if(r[l]==="$"){o+=`($|(?=[\r
174
- ]))`;continue}}if(n.s&&r[l]==="."){o+=s?`${r[l]}\r
175
- `:`[${r[l]}\r
176
- ]`;continue}o+=r[l],r[l]==="\\"?i=!0:s&&r[l]==="]"?s=!1:!s&&r[l]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function parseRecordDef(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,o)=>({...r,[o]:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??parseAnyDef(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.checks?.length){const{type:r,...o}=parseStringDef(e.keyType._def,t);return{...n,propertyNames:o}}else{if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&e.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...o}=parseBrandedDef(e.keyType._def,t);return{...n,propertyNames:o}}}return n}function parseMapDef(e,t){if(t.mapStrategy==="record")return parseRecordDef(e,t);const n=parseDef(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||parseAnyDef(t),r=parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||parseAnyDef(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function parseNativeEnumDef(e){const t=e.values,r=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),o=Array.from(new Set(r.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}function parseNeverDef(e){return e.target==="openAi"?void 0:{not:parseAnyDef({...e,currentPath:[...e.currentPath,"not"]})}}function parseNullDef(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(e,t){if(t.target==="openApi3")return asAnyOf(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in primitiveMappings&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,i)=>{const s=primitiveMappings[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((o,i)=>{const s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){const o=r.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:n.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(i=>!r.includes(i))],[])};return asAnyOf(e,t)}const asAnyOf=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>parseDef(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function parseNullableDef(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:primitiveMappings[e.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const r=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function parseNumberDef(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",addErrorMessage(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?setResponseValueAndErrors(n,"minimum",r.value,r.message,t):setResponseValueAndErrors(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),setResponseValueAndErrors(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?setResponseValueAndErrors(n,"maximum",r.value,r.message,t):setResponseValueAndErrors(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),setResponseValueAndErrors(n,"maximum",r.value,r.message,t));break;case"multipleOf":setResponseValueAndErrors(n,"multipleOf",r.value,r.message,t);break}return n}function parseObjectDef(e,t){const n=t.target==="openAi",r={type:"object",properties:{}},o=[],i=e.shape();for(const a in i){let l=i[a];if(l===void 0||l._def===void 0)continue;let c=safeIsOptional(l);c&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=parseDef(l._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});u!==void 0&&(r.properties[a]=u,c||o.push(a))}o.length&&(r.required=o);const s=decideAdditionalProperties(e,t);return s!==void 0&&(r.additionalProperties=s),r}function decideAdditionalProperties(e,t){if(e.catchall._def.typeName!=="ZodNever")return parseDef(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function safeIsOptional(e){try{return e.isOptional()}catch{return!0}}const parseOptionalDef=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return parseDef(e.innerType._def,t);const n=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:parseAnyDef(t)},n]}:parseAnyDef(t)},parsePipelineDef=(e,t)=>{if(t.pipeStrategy==="input")return parseDef(e.in._def,t);if(t.pipeStrategy==="output")return parseDef(e.out._def,t);const n=parseDef(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=parseDef(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function parsePromiseDef(e,t){return parseDef(e.type._def,t)}function parseSetDef(e,t){const r={type:"array",uniqueItems:!0,items:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&setResponseValueAndErrors(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&setResponseValueAndErrors(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function parseTupleDef(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>parseDef(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:parseDef(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>parseDef(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function parseUndefinedDef(e){return{not:parseAnyDef(e)}}function parseUnknownDef(e){return parseAnyDef(e)}const parseReadonlyDef=(e,t)=>parseDef(e.innerType._def,t),selectParser=(e,t,n)=>{switch(t){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(e,n);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(e,n);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(e,n);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(e,n);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(e,n);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef(n);case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(n);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(e,n);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(e,n);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(e,n);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(e,n);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(e,n);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(e,n);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(e);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(e);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(e,n);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(e,n);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(e,n);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(e,n);case ZodFirstPartyTypeKind.ZodLazy:return()=>e.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(e,n);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef(n);case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(e,n);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef(n);case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef(n);case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(e,n);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(e,n);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(e,n);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(e,n);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(e,n);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return;default:return(r=>{})()}};function parseDef(e,t,n=!1){const r=t.seen.get(e);if(t.override){const a=t.override?.(e,t,r,n);if(a!==ignoreOverride)return a}if(r&&!n){const a=get$ref(r,t);if(a!==void 0)return a}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const i=selectParser(e,e.typeName,t),s=typeof i=="function"?parseDef(i(),t):i;if(s&&addMeta(e,t,s),t.postProcess){const a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}const get$ref=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:getRelativePath(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),parseAnyDef(t)):t.$refStrategy==="seen"?parseAnyDef(t):void 0}},addMeta=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),zodToJsonSchema=(e,t)=>{const n=getRefs(t);let r;const o=t?.name,i=parseDef(e._def,n,!1)??parseAnyDef(n);n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const s=o===void 0?r?{...i,[n.definitionPath]:r}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:i}};return n.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s},pageAgentPrompt=`## 角色
177
-
178
- 你是浏览器页面的操作工具,你拥有识别网页内容,点击,填写,选择下拉框和滚动页面等功能。
179
-
180
- 在执行页面操作之前,你必须先调用\`browserState\`工具一次,根据最新的网页状态,再调用操作动作,比如 'click','fill','select' 等动作。
181
-
182
- <intro>
183
- 你擅长以下任务:
184
- 1. 导航复杂网站并提取精确信息
185
- 2. 自动化表单提交和交互式网页操作
186
- 3. 收集和保存信息
187
- 4. 在代理循环中有效运行
188
- 5. 高效执行多样化的网页任务
189
- </intro>
190
-
191
- <input>
192
- 在每一步,你的输入将包括:
193
- 1. <agent_history>:一个按时间顺序排列的事件流,包括你之前的操作及其结果。
194
- 2. <agent_state>:当前的 <user_request> 和 <step_info>。
195
- 3. <browser_state>:当前 URL、页面标题、可交互元素总数以及语义化 YAML 树。
196
- </input>
197
-
198
- <browser_state>
199
-
200
- 浏览器状态包含以下内容:
201
-
202
- - url: 当前查看页面的 URL。
203
- - title: 当前查看页面的标题。
204
- - 可交互元素总数:带有 \`[ref=N]\` 标记的元素数量。
205
- - YAML 树:页面的语义化结构,格式如下:
206
-
207
- \`\`\`yaml
208
- - region:
209
- - main:
210
- - button [cursor=pointer] [ref=9]: 产品文档
211
- - button [selected] [cursor=pointer] [ref=47]: 40元/月 2核CPU 2GB内存
212
- - radio [checked] [cursor=pointer] [ref=53]: 自动生成密码
213
- - button [cursor=pointer] [ref=74]: 立即购买
214
- \`\`\`
215
-
216
- 节点格式说明:
217
- - \`- role [state1] [state2] [ref=N]: accessible name\`
218
- - \`role\`:ARIA 语义角色(如 button/link/radio/heading/list/listitem 等)
219
- - \`[state]\`:可选状态标记,如 \`[checked]\` \`[selected]\` \`[disabled]\` \`[expanded]\` \`[cursor=pointer]\`
220
- - \`[ref=N]\`:可交互元素的唯一操作索引,**只有带 ref 的节点才能被操作**
221
- - \`accessible name\`:元素的语义化名称(通过 aria-label/aria-labelledby/innerText 等计算得出)
222
- - 缩进表示父子关系
223
-
224
- </browser_state>
225
-
226
- <browser_state_diff>
227
-
228
- 在交互过程中,为了提高效率和减少上下文占用,工具会生成页面的增量差异(Diff)信息。
229
- Diff 格式示例如下:
230
- \`\`\`diff
231
- - button [ref=9]: 产品文档
232
- + button [ref=9]: 产品文档 (已点击)
233
- \`\`\`
234
- 或者,当页面结构发生改变时,会展示新增或移除的节点差异。
235
-
236
- ### 页面状态获取四原则(重要,请严格遵守):
237
-
238
- > 与业界 AI 编辑器(Cursor / Windsurf)按需读取文件而非全量加载的理念完全一致——**先精准搜索,再按需拉取全量**,将发送给大模型的 token 降至最低。
239
-
240
- 1. **按关键词精准搜索(最高优先级)**:当你已知要找什么类型的元素(如按钮、输入框、特定名称的链接)时,**优先使用 \`searchTree\` 动作**,传入 role 名称、元素文本或状态关键词搜索。它只返回命中行和上下文,token 消耗比全量树减少 80%+ 。
241
- - 示例:查找所有按钮 → \`{"action": "searchTree", "query": "button"}\`
242
- - 示例:查找含"提交"文本的节点 → \`{"action": "searchTree", "query": "提交"}\`
243
- - 示例:查找已勾选的复选框 → \`{"action": "searchTree", "query": "checked"}\`
244
- - 示例:精确定位某个 ref → \`{"action": "searchTree", "query": "#5"}\`
245
- 2. **首次获取全量**:首次进入页面、页面发生重大刷新、或 \`searchTree\` 无法找到所需信息时,调用 \`browserState\` 并指定 \`responseMode\` 为 \`full\` 或 \`both\` 获取完整 A11y 树。
246
- 3. **增量优先**:执行 \`click\`、\`fill\`、\`select\`、\`scroll\` 操作后,工具默认自动返回 \`diff\` 增量信息。优先阅读这些 Diff,以便快速确认操作是否生效。
247
- 4. **按需拉取全量**:如果增量 Diff 不足以支持下一步操作,或需要寻找不在 Diff 中的 \`[ref=N]\` 节点,且 \`searchTree\` 也无法定位时,再显式调用 \`browserState\` 拉取完整树。
248
-
249
- </browser_state_diff>
250
-
251
-
252
-
253
- <browser_rules>
254
- 在使用浏览器和浏览网页时严格遵守以下规则:
255
-
256
- - 仅与分配有 \`[ref=N]\` 的元素进行交互。
257
- - 仅使用明确提供的 ref 索引。
258
- - 每次操作后 ref 索引会重新分配,不要使用旧的 ref 索引。
259
- - 如果页面在执行操作后发生变化(例如输入文本操作),分析是否需要与新元素进行交互,例如从列表中选择正确的选项。
260
- - 默认情况下,仅列出可见视口中的元素。如果你怀疑需要交互的相关内容在屏幕外,请使用滚动操作。仅在页面下方或上方还有更多像素时才滚动。
261
- - 你可以使用 num_pages 参数滚动特定页数(例如,0.5 表示半页,2.0 表示两页)。
262
- - 如果出现验证码,告诉用户你无法解决验证码。完成任务并请用户解决它。
263
- - 如果缺少预期元素,尝试滚动或导航回退。
264
- - 除非某些条件发生变化,否则不要重复同一操作超过 3 次。
265
- - 如果你向输入字段填充文本且操作序列被中断,通常意味着某些内容发生了变化,例如下拉建议弹出。
266
- - 如果 <user_request> 包含特定的页面信息,如产品类型、评分、价格、位置等,尝试应用过滤器以提高效率。
267
- - <user_request> 是最终目标。如果用户指定了明确的步骤,它们始终具有最高优先级。
268
- - 如果你向字段输入文本,可能需要按回车键、点击搜索按钮或从下拉列表中选择以完成操作。
269
- - 如果不需要,不要登录页面。如果没有凭据,不要登录。
270
- - 有两种类型的任务,首先思考你正在处理哪种类型的请求:
271
-
272
- 1. 非常具体的逐步说明:
273
-
274
- - 非常精确地遵循它们,不要跳过步骤。尝试按要求完成所有内容。
275
-
276
- 2. 开放式任务。自己规划,在实现目标时保持创造性。
277
-
278
- - 如果在开放式任务中陷入困境(例如登录或验证码),可以重新评估任务并尝试替代方法,例如有时即使页面的某些部分可访问或通过 Web 搜索获取一些信息,也会意外弹出登录框。
279
- </browser_rules>
280
-
281
- <capability>
282
- - 你只能处理单页应用。不要跳出当前页面。
283
- - 如果链接将在新页面中打开(例如,<a target="_blank">),不要点击该链接。
284
- - 任务失败是可以接受的。
285
- - 用户可能是错的。如果用户的请求无法实现、不适当,或者你没有足够的信息或工具来实现它。告诉用户提出更好的请求。
286
- - 网页可能已损坏。所有网页或应用都有 bug。有些 bug 会使你的工作变得困难。鼓励你告诉用户当前页面的问题。你的反馈(包括失败)对用户很有价值。
287
- - 过于努力可能有害。来回重复某些操作或在知识有限的情况下推动复杂程序可能导致不良结果和有害副作用。用户宁愿你以失败告终完成任务。
288
- - 如果你对当前网页或任务没有相关知识。你必须要求用户提供具体说明和详细步骤。
289
- </capability>
290
-
291
- <task_completion_rules>
292
- 你必须在以下情况时结束任务:
293
-
294
- - 当你完全完成用户请求时。
295
- - 当你感到困惑或无法解决用户请求时。或者用户请求不清楚或包含不当内容。
296
- - 如果绝对不可能继续。
297
-
298
- </task_completion_rules>
299
- `;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){const t=e.ownerDocument.defaultView?.frameElement;if(!t)return{x:0,y:0};const 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){const 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){const n=e.get(t);if(!n)throw new Error(`No interactive element found at index ${t}`);const r=n.ref;if(!r)throw new Error(`Element at index ${t} does not have a reference`);if(!isHTMLElement(r))throw new 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(),lastClickedElement=null)}async function clickElement(e){blurLastClickedElement(),lastClickedElement=e,await scrollIntoViewIfNeeded(e);const t=e.ownerDocument.defaultView?.frameElement;t&&await scrollIntoViewIfNeeded(t);const n=e.getBoundingClientRect(),r=n.left+n.width/2,o=n.top+n.height/2;await movePointerToElement(e,r,o),await clickPointer(),await waitFor(.1);const i=e.ownerDocument;await enablePassThrough();const s=i.elementFromPoint(r,o);await disablePassThrough();const a=s instanceof HTMLElement&&e.contains(s)?s:e,l={bubbles:!0,cancelable:!0,clientX:r,clientY:o,pointerType:"mouse"},c={bubbles:!0,cancelable:!0,clientX:r,clientY:o,button:0};a.dispatchEvent(new PointerEvent("pointerover",l)),a.dispatchEvent(new PointerEvent("pointerenter",{...l,bubbles:!1})),a.dispatchEvent(new MouseEvent("mouseover",c)),a.dispatchEvent(new MouseEvent("mouseenter",{...c,bubbles:!1})),a.dispatchEvent(new PointerEvent("pointerdown",l)),a.dispatchEvent(new MouseEvent("mousedown",c)),e.focus({preventScroll:!0}),a.dispatchEvent(new PointerEvent("pointerup",l)),a.dispatchEvent(new MouseEvent("mouseup",c)),a.click(),await waitFor(.2)}async function inputTextElement(e,t){const n=e.isContentEditable;if(!isInputElement(e)&&!isTextAreaElement(e)&&!n)throw new 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();const r=e.ownerDocument,o=(r.defaultView||window).getSelection(),i=r.createRange();i.selectNodeContents(e),o?.removeAllRanges(),o?.addRange(i),r.execCommand("delete",!1),r.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 new Error("Element is not a select element");const n=Array.from(e.options).find(r=>r.textContent?.trim()===t.trim());if(!n)throw new 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){const t=e;typeof t.scrollIntoViewIfNeeded=="function"?t.scrollIntoViewIfNeeded():e.scrollIntoView({behavior:"auto",block:"center",inline:"nearest"})}async function scrollVertically(e,t){if(t){const s=t;let a=s,l=!1,c=null,u=0,p=0;const f=e;for(;a&&p<10;){const m=window.getComputedStyle(a),g=/(auto|scroll|overlay)/.test(m.overflowY)||m.scrollbarWidth&&m.scrollbarWidth!=="auto"||m.scrollbarGutter&&m.scrollbarGutter!=="auto",x=a.scrollHeight>a.clientHeight;if(g&&x){const b=a.scrollTop,h=a.scrollHeight-a.clientHeight;let _=f/3;_>0?_=Math.min(_,h-b):_=Math.max(_,-b),a.scrollTop=b+_;const E=a.scrollTop-b;if(Math.abs(E)>.5){l=!0,c=a,u=E;break}}if(a===document.body||a===document.documentElement)break;a=a.parentElement,p++}return l?`Scrolled container (${c?.tagName}) by ${u}px`:`No scrollable container found for element (${s.tagName})`}const n=e,r=s=>s.clientHeight>=window.innerHeight*.5,o=s=>!!(s&&/(auto|scroll|overlay)/.test(getComputedStyle(s).overflowY)&&s.scrollHeight>s.clientHeight&&r(s));let i=document.activeElement;for(;i&&!o(i)&&i!==document.body;)i=i.parentElement;if(i=o(i)?i:Array.from(document.querySelectorAll("*")).find(o)||document.scrollingElement||document.documentElement,i===document.scrollingElement||i===document.documentElement||i===document.body){const s=window.scrollY,a=document.documentElement.scrollHeight-window.innerHeight;window.scrollBy(0,n);const l=window.scrollY,c=l-s;if(Math.abs(c)<1)return n>0?"⚠️ Already at the bottom of the page, cannot scroll down further.":"⚠️ Already at the top of the page, cannot scroll up further.";const u=n>0&&l>=a-1,p=n<0&&l<=1;return u?`✅ Scrolled page by ${c}px. Reached the bottom of the page.`:p?`✅ Scrolled page by ${c}px. Reached the top of the page.`:`✅ Scrolled page by ${c}px.`}else{const s="The document is not scrollable. Falling back to container scroll.";console.log(`[PageController] ${s}`);const a=i.scrollTop,l=i.scrollHeight-i.clientHeight;i.scrollBy({top:n,behavior:"smooth"}),await waitFor(.1);const c=i.scrollTop,u=c-a;if(Math.abs(u)<1)return n>0?`⚠️ ${s} Already at the bottom of container (${i.tagName}), cannot scroll down further.`:`⚠️ ${s} Already at the top of container (${i.tagName}), cannot scroll up further.`;const p=n>0&&c>=l-1,f=n<0&&c<=1;return p?`✅ ${s} Scrolled container (${i.tagName}) by ${u}px. Reached the bottom.`:f?`✅ ${s} Scrolled container (${i.tagName}) by ${u}px. Reached the top.`:`✅ ${s} Scrolled container (${i.tagName}) by ${u}px.`}}async function scrollHorizontally(e,t){if(t){const s=t;let a=s,l=!1,c=null,u=0,p=0;const f=e;for(;a&&p<10;){const m=window.getComputedStyle(a),g=/(auto|scroll|overlay)/.test(m.overflowX)||m.scrollbarWidth&&m.scrollbarWidth!=="auto"||m.scrollbarGutter&&m.scrollbarGutter!=="auto",x=a.scrollWidth>a.clientWidth;if(g&&x){const b=a.scrollLeft,h=a.scrollWidth-a.clientWidth;let _=f/3;_>0?_=Math.min(_,h-b):_=Math.max(_,-b),a.scrollLeft=b+_;const E=a.scrollLeft-b;if(Math.abs(E)>.5){l=!0,c=a,u=E;break}}if(a===document.body||a===document.documentElement)break;a=a.parentElement,p++}return l?`Scrolled container (${c?.tagName}) horizontally by ${u}px`:`No horizontally scrollable container found for element (${s.tagName})`}const n=e,r=s=>s.clientWidth>=window.innerWidth*.5,o=s=>!!(s&&/(auto|scroll|overlay)/.test(getComputedStyle(s).overflowX)&&s.scrollWidth>s.clientWidth&&r(s));let i=document.activeElement;for(;i&&!o(i)&&i!==document.body;)i=i.parentElement;if(i=o(i)?i:Array.from(document.querySelectorAll("*")).find(o)||document.scrollingElement||document.documentElement,i===document.scrollingElement||i===document.documentElement||i===document.body){const s=window.scrollX,a=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(n,0);const l=window.scrollX,c=l-s;if(Math.abs(c)<1)return 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.";const u=n>0&&l>=a-1,p=n<0&&l<=1;return u?`✅ Scrolled page by ${c}px. Reached the right edge of the page.`:p?`✅ Scrolled page by ${c}px. Reached the left edge of the page.`:`✅ Scrolled page horizontally by ${c}px.`}else{const s="The document is not scrollable. Falling back to container scroll.";console.log(`[PageController] ${s}`);const a=i.scrollLeft,l=i.scrollWidth-i.clientWidth;i.scrollBy({left:n,behavior:"smooth"}),await waitFor(.1);const c=i.scrollLeft,u=c-a;if(Math.abs(u)<1)return n>0?`⚠️ ${s} Already at the right edge of container (${i.tagName}), cannot scroll right further.`:`⚠️ ${s} Already at the left edge of container (${i.tagName}), cannot scroll left further.`;const p=n>0&&c>=l-1,f=n<0&&c<=1;return p?`✅ ${s} Scrolled container (${i.tagName}) by ${u}px. Reached the right edge.`:f?`✅ ${s} Scrolled container (${i.tagName}) by ${u}px. Reached the left edge.`:`✅ ${s} Scrolled container (${i.tagName}) horizontally by ${u}px.`}}var dom_tree_default=(e={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:t,interactiveWhitelist:n,highlightOpacity:r,highlightLabelOpacity:o}=e,{doHighlightElements:i,focusHighlightIndex:s,viewportExpansion:a,debugMode:l}=e;let c=0;const u=new WeakMap;function p(d,w){!d||d.nodeType!==Node.ELEMENT_NODE||u.set(d,{...u.get(d),...w})}const f={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{f.boundingRects=new WeakMap,f.clientRects=new WeakMap,f.computedStyles=new WeakMap}};function m(d){if(!d)return null;if(f.boundingRects.has(d))return f.boundingRects.get(d);const w=d.getBoundingClientRect();return w&&f.boundingRects.set(d,w),w}function g(d){if(!d)return null;if(f.computedStyles.has(d))return f.computedStyles.get(d);const w=window.getComputedStyle(d);return w&&f.computedStyles.set(d,w),w}function x(d){if(!d)return null;if(f.clientRects.has(d))return f.clientRects.get(d);const w=d.getClientRects();return w&&f.clientRects.set(d,w),w}const b={},h={current:0},_="playwright-highlight-container";function E(d,w,U=null){if(!d)return w;const T=[];let I=null,B=20,k=16,F=null;try{let O=document.getElementById(_);O||(O=document.createElement("div"),O.id=_,O.style.position="fixed",O.style.pointerEvents="none",O.style.top="0",O.style.left="0",O.style.width="100%",O.style.height="100%",O.style.zIndex="2147483640",O.style.backgroundColor="transparent",document.body.appendChild(O));const z=d.getClientRects();if(!z||z.length===0)return w;const Y=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];let q=Y[w%Y.length];const ee=q+Math.floor(r*255).toString(16).padStart(2,"0");q=q+Math.floor(o*255).toString(16).padStart(2,"0");let X={x:0,y:0};if(U){const P=U.getBoundingClientRect();X.x=P.left,X.y=P.top}const ae=document.createDocumentFragment();for(const P of z){if(P.width===0||P.height===0)continue;const v=document.createElement("div");v.style.position="fixed",v.style.border=`2px solid ${q}`,v.style.backgroundColor=ee,v.style.pointerEvents="none",v.style.boxSizing="border-box";const y=P.top+X.y,L=P.left+X.x;v.style.top=`${y}px`,v.style.left=`${L}px`,v.style.width=`${P.width}px`,v.style.height=`${P.height}px`,ae.appendChild(v),T.push({element:v,initialRect:P})}const re=z[0];I=document.createElement("div"),I.className="playwright-highlight-label",I.style.position="fixed",I.style.background=q,I.style.color="white",I.style.padding="1px 4px",I.style.borderRadius="4px",I.style.fontSize=`${Math.min(12,Math.max(8,re.height/2))}px`,I.textContent=w.toString(),B=I.offsetWidth>0?I.offsetWidth:B,k=I.offsetHeight>0?I.offsetHeight:k;const de=re.top+X.y,le=re.left+X.x;let ue=de+2,C=le+re.width-B-2;(re.width<B+4||re.height<k+4)&&(ue=de-k-2,C=le+re.width-B,C<X.x&&(C=le)),ue=Math.max(0,Math.min(ue,window.innerHeight-k)),C=Math.max(0,Math.min(C,window.innerWidth-B)),I.style.top=`${ue}px`,I.style.left=`${C}px`,ae.appendChild(I);const $=((P,v)=>{let y=0;return(...L)=>{const R=performance.now();if(!(R-y<v))return y=R,P(...L)}})(()=>{const P=d.getClientRects();let v={x:0,y:0};if(U){const y=U.getBoundingClientRect();v.x=y.left,v.y=y.top}if(T.forEach((y,L)=>{if(L<P.length){const R=P[L],G=R.top+v.y,se=R.left+v.x;y.element.style.top=`${G}px`,y.element.style.left=`${se}px`,y.element.style.width=`${R.width}px`,y.element.style.height=`${R.height}px`,y.element.style.display=R.width===0||R.height===0?"none":"block"}else y.element.style.display="none"}),P.length<T.length)for(let y=P.length;y<T.length;y++)T[y].element.style.display="none";if(I&&P.length>0){const y=P[0],L=y.top+v.y,R=y.left+v.x;let G=L+2,se=R+y.width-B-2;(y.width<B+4||y.height<k+4)&&(G=L-k-2,se=R+y.width-B,se<v.x&&(se=R)),G=Math.max(0,Math.min(G,window.innerHeight-k)),se=Math.max(0,Math.min(se,window.innerWidth-B)),I.style.top=`${G}px`,I.style.left=`${se}px`,I.style.display="block"}else I&&(I.style.display="none")},16);return window.addEventListener("scroll",$,!0),window.addEventListener("resize",$),F=()=>{window.removeEventListener("scroll",$,!0),window.removeEventListener("resize",$),T.forEach(P=>P.element.remove()),I&&I.remove()},O.appendChild(ae),w+1}finally{F&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(F)}}function S(d){if(!d||d.nodeType!==Node.ELEMENT_NODE)return null;const w=g(d);if(!w)return null;const U=w.display;if(U==="inline"||U==="inline-block")return null;const T=w.overflowX,I=w.overflowY,B=w.scrollbarWidth&&w.scrollbarWidth!=="auto"||w.scrollbarGutter&&w.scrollbarGutter!=="auto",k=T==="auto"||T==="scroll",F=I==="auto"||I==="scroll";if(!k&&!F&&!B)return null;const O=d.scrollWidth-d.clientWidth,z=d.scrollHeight-d.clientHeight,Y=4;if(O<Y&&z<Y||!F&&!B&&O<Y||!k&&!B&&z<Y)return null;const q=d.scrollTop,ee=d.scrollLeft,X={top:q,right:d.scrollWidth-d.clientWidth-d.scrollLeft,bottom:d.scrollHeight-d.clientHeight-d.scrollTop,left:ee};return p(d,{scrollable:!0,scrollData:X}),X}function A(d){try{if(a===-1){const k=d.parentElement;if(!k)return!1;try{return k.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const O=window.getComputedStyle(k);return O.display!=="none"&&O.visibility!=="hidden"&&O.opacity!=="0"}}const w=document.createRange();w.selectNodeContents(d);const U=w.getClientRects();if(!U||U.length===0)return!1;let T=!1,I=!1;for(const k of U)if(k.width>0&&k.height>0&&(T=!0,!(k.bottom<-a||k.top>window.innerHeight+a||k.right<-a||k.left>window.innerWidth+a))){I=!0;break}if(!T||!I)return!1;const B=d.parentElement;if(!B)return!1;try{return B.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch{const F=window.getComputedStyle(B);return F.display!=="none"&&F.visibility!=="hidden"&&F.opacity!=="0"}}catch(w){return console.warn("Error checking text node visibility:",w),!1}}function D(d){if(!d||!d.tagName)return!1;const w=new Set(["body","div","main","article","section","nav","header","footer"]),U=d.tagName.toLowerCase();return w.has(U)?!0:!new Set(["svg","script","style","link","meta","noscript","template"]).has(U)}function M(d){const w=g(d);return d.offsetWidth>0&&d.offsetHeight>0&&w?.visibility!=="hidden"&&w?.display!=="none"}function W(d){if(!d||d.nodeType!==Node.ELEMENT_NODE||t.includes(d))return!1;if(n.includes(d))return!0;const w=d.tagName.toLowerCase(),U=g(d),T=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"]),I=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);function B(q){return q.tagName.toLowerCase()==="html"?!1:!!(U?.cursor&&T.has(U.cursor))}if(B(d))return!0;const k=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),F=new Set(["disabled","readonly"]);if(k.has(w)){if(U?.cursor&&I.has(U.cursor))return!1;for(const q of F)if(d.hasAttribute(q)||d.getAttribute(q)==="true"||d.getAttribute(q)==="")return!1;return!(d.disabled||d.readOnly||d.inert)}const O=d.getAttribute("role"),z=d.getAttribute("aria-role");if(d.getAttribute("contenteditable")==="true"||d.isContentEditable||d.classList&&(d.classList.contains("button")||d.classList.contains("dropdown-toggle")||d.getAttribute("data-index")||d.getAttribute("data-toggle")==="dropdown"||d.getAttribute("aria-haspopup")==="true"))return!0;const Y=new Set(["button","menu","menubar","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);if(k.has(w)||O&&Y.has(O)||z&&Y.has(z))return!0;try{if(typeof getEventListeners=="function"){const ee=getEventListeners(d);for(const X of["click","mousedown","mouseup","dblclick"])if(ee[X]&&ee[X].length>0)return!0}const q=d?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof q=="function"){const ee=q(d);for(const X of["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"])for(const ae of ee)if(ae.type===X)return!0}for(const ee of["onclick","onmousedown","onmouseup","ondblclick"])if(d.hasAttribute(ee)||typeof d[ee]=="function")return!0}catch{}return!!S(d)}function N(d){if(a===-1)return!0;const w=x(d);if(!w||w.length===0)return!1;let U=!1;for(const k of w)if(k.width>0&&k.height>0&&!(k.bottom<-a||k.top>window.innerHeight+a||k.right<-a||k.left>window.innerWidth+a)){U=!0;break}if(!U)return!1;if(d.ownerDocument!==window.document)return!0;let T=Array.from(w).find(k=>k.width>0&&k.height>0);if(!T)return!1;const I=d.getRootNode();if(I instanceof ShadowRoot){const k=T.left+T.width/2,F=T.top+T.height/2;try{const O=I.elementFromPoint(k,F);if(!O)return!1;let z=O;for(;z&&z!==I;){if(z===d)return!0;z=z.parentElement}return!1}catch{return!0}}const B=5;return[{x:T.left+T.width/2,y:T.top+T.height/2},{x:T.left+B,y:T.top+B},{x:T.right-B,y:T.bottom-B}].some(({x:k,y:F})=>{try{const O=document.elementFromPoint(k,F);if(!O)return!1;let z=O;for(;z&&z!==document.documentElement;){if(z===d)return!0;z=z.parentElement}return!1}catch{return!0}})}function H(d,w){if(w===-1)return!0;const U=d.getClientRects();if(!U||U.length===0){const T=m(d);return!T||T.width===0||T.height===0?!1:!(T.bottom<-w||T.top>window.innerHeight+w||T.right<-w||T.left>window.innerWidth+w)}for(const T of U)if(!(T.width===0||T.height===0)&&!(T.bottom<-w||T.top>window.innerHeight+w||T.right<-w||T.left>window.innerWidth+w))return!0;return!1}const V=["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 Z(d){for(let w=0;w<V.length;w++)if(d.hasAttribute(V[w]))return!0;return!1}function oe(d){if(!d||d.nodeType!==Node.ELEMENT_NODE)return!1;const w=d.tagName.toLowerCase();return new Set(["a","button","input","select","textarea","details","summary","label"]).has(w)?!0:d.hasAttribute("onclick")||d.hasAttribute("role")||d.hasAttribute("tabindex")||Z(d)||d.hasAttribute("data-action")||d.getAttribute("contenteditable")==="true"}const Q=new Set(["a","button","input","select","textarea","summary","details","label","option","li"]),te=new Set(["button","link","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","listitem","treeitem","row","option","scrollbar"]);function ie(d){if(!d||d.nodeType!==Node.ELEMENT_NODE||!M(d))return!1;const w=d.hasAttribute("role")||d.hasAttribute("tabindex")||d.hasAttribute("onclick")||typeof d.onclick=="function",U=/\b(btn|clickable|menu|item|entry|link)\b/i.test(d.className||""),T=!!d.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar'),I=[...d.children].some(M),B=d.parentElement&&d.parentElement.isSameNode(document.body);return(W(d)||w||U)&&I&&T&&!B}function ne(d){if(!d||d.nodeType!==Node.ELEMENT_NODE)return!1;const w=d.tagName.toLowerCase(),U=d.getAttribute("role");if(w==="iframe"||Q.has(w)||U&&te.has(U)||d.isContentEditable||d.getAttribute("contenteditable")==="true"||d.hasAttribute("data-testid")||d.hasAttribute("data-cy")||d.hasAttribute("data-test")||d.hasAttribute("onclick")||typeof d.onclick=="function"||Z(d))return!0;try{const T=d?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if(typeof T=="function"){const I=T(d);for(const B of["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"])for(const k of I)if(k.type===B)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(I=>d.hasAttribute(I)))return!0}catch{}return!!(ie(d)||u.get(d)?.scrollable)}function K(d,w,U,T){if(!d.isInteractive)return!1;let I=!1;return T?ne(w)?I=!0:I=!1:I=!0,I&&(d.isInViewport=H(w,a),(d.isInViewport||a===-1)&&(d.highlightIndex=c++,i))?(s>=0?s===d.highlightIndex&&E(w,d.highlightIndex,U):E(w,d.highlightIndex,U),!0):!1}function J(d,w=null,U=!1){if(!d||d.id===_||d.nodeType!==Node.ELEMENT_NODE&&d.nodeType!==Node.TEXT_NODE||!d||d.id===_||d.dataset?.browserUseIgnore==="true"||d.dataset?.pageAgentIgnore==="true"||d.getAttribute&&d.getAttribute("aria-hidden")==="true")return null;if(d===document.body){const k={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const O of d.childNodes){const z=J(O,w,!1);z&&k.children.push(z)}const F=`${h.current++}`;return b[F]=k,F}if(d.nodeType!==Node.ELEMENT_NODE&&d.nodeType!==Node.TEXT_NODE)return null;if(d.nodeType===Node.TEXT_NODE){const k=d.textContent?.trim();if(!k)return null;const F=d.parentElement;if(!F||F.tagName.toLowerCase()==="script")return null;const O=`${h.current++}`;return b[O]={type:"TEXT_NODE",text:k,isVisible:A(d)},O}if(d.nodeType===Node.ELEMENT_NODE&&!D(d))return null;if(a!==-1&&!d.shadowRoot){const k=m(d),F=g(d),O=F&&(F.position==="fixed"||F.position==="sticky"),z=d.offsetWidth>0||d.offsetHeight>0;if(!k||!O&&!z&&(k.bottom<-a||k.top>window.innerHeight+a||k.right<-a||k.left>window.innerWidth+a))return null}const T={tagName:d.tagName.toLowerCase(),attributes:{},children:[]};if(oe(d)||d.tagName.toLowerCase()==="iframe"||d.tagName.toLowerCase()==="body"){const k=d.getAttributeNames?.()||[];for(const F of k){const O=d.getAttribute(F);T.attributes[F]=O}d.tagName.toLowerCase()==="input"&&(d.type==="checkbox"||d.type==="radio")&&(T.attributes.checked=d.checked?"true":"false")}let I=!1;if(d.nodeType===Node.ELEMENT_NODE&&(T.isVisible=M(d),T.isVisible)){T.isTopElement=N(d);const k=d.getAttribute("role"),F=k==="menu"||k==="menubar"||k==="listbox";if((T.isTopElement||F)&&(T.isInteractive=W(d),I=K(T,d,w,U),T.ref=d,T.isInteractive&&Object.keys(T.attributes).length===0)){const O=d.getAttributeNames?.()||[];for(const z of O){const Y=d.getAttribute(z);T.attributes[z]=Y}}}if(d.tagName){const k=d.tagName.toLowerCase();if(k==="iframe")try{const F=d.contentDocument||d.contentWindow?.document;if(F)for(const O of F.childNodes){const z=J(O,d,!1);z&&T.children.push(z)}}catch(F){console.warn("Unable to access iframe:",F)}else if(d.isContentEditable||d.getAttribute("contenteditable")==="true"||d.id==="tinymce"||d.classList.contains("mce-content-body")||k==="body"&&d.getAttribute("data-id")?.startsWith("mce_"))for(const F of d.childNodes){const O=J(F,w,I);O&&T.children.push(O)}else{if(d.shadowRoot){T.shadowRoot=!0;for(const F of d.shadowRoot.childNodes){const O=J(F,w,I);O&&T.children.push(O)}}for(const F of d.childNodes){const O=J(F,w,I||U);O&&T.children.push(O)}}}if(T.tagName==="a"&&T.children.length===0&&!T.attributes.href){const k=m(d);if(!(k&&k.width>0&&k.height>0||d.offsetWidth>0||d.offsetHeight>0))return null}T.extra=u.get(d)||null;const B=`${h.current++}`;return b[B]=T,B}const ce=J(document.body);return f.clearCache(),{rootId:ce,map:b}},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){const t=resolveViewportExpansion(e.viewportExpansion),n=[];for(const s of e.interactiveBlacklist||[])typeof s=="function"?n.push(s()):n.push(s);const r=[];for(const s of e.interactiveWhitelist||[])typeof s=="function"?r.push(s()):r.push(s);const o=dom_tree_default({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:t,interactiveBlacklist:n,interactiveWhitelist:r,highlightOpacity:e.highlightOpacity??0,highlightLabelOpacity:e.highlightLabelOpacity??.1}),i=window.location.href;for(const s in o.map){const a=o.map[s];if(a.isInteractive&&a.ref){const l=a.ref;newElementsCache.has(l)||(newElementsCache.set(l,i),a.isNew=!0)}}return o}var globRegexCache=new Map;function globToRegex(e){let t=globRegexCache.get(e);if(!t){const n=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");t=new RegExp(`^${n.replace(/\*/g,".*")}$`),globRegexCache.set(e,t)}return t}function matchAttributes(e,t){const n={};for(const r of t)if(r.includes("*")){const o=globToRegex(r);for(const i of Object.keys(e))o.test(i)&&e[i].trim()&&(n[i]=e[i].trim())}else{const o=e[r];o&&o.trim()&&(n[r]=o.trim())}return n}function flatTreeToString(e,t=[],n=!1){const 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"],o=[...t,...r],i=(f,m)=>f.length>m?f.substring(0,m)+"...":f,s=f=>{const m=e.map[f];if(!m)return null;if(m.type==="TEXT_NODE"){const g=m;return{type:"text",text:g.text,isVisible:g.isVisible,parent:null,children:[]}}else{const g=m,x=[];if(g.children)for(const b of g.children){const h=s(b);h&&(h.parent=null,x.push(h))}return{type:"element",tagName:g.tagName,attributes:g.attributes??{},isVisible:g.isVisible??!1,isInteractive:g.isInteractive??!1,isTopElement:g.isTopElement??!1,isNew:g.isNew??!1,highlightIndex:g.highlightIndex,parent:null,children:x,extra:g.extra??{}}}},a=(f,m=null)=>{f.parent=m;for(const g of f.children)a(g,f)},l=s(e.rootId);if(!l)return"";a(l);const c=f=>{let m=f.parent;for(;m;){if(m.type==="element"&&m.highlightIndex!==void 0)return!0;m=m.parent}return!1},u=(f,m,g)=>{let x=m;const b=" ".repeat(m);if(f.type==="element"){const h=n&&f.tagName&&SEMANTIC_TAGS.has(f.tagName);if(f.highlightIndex!==void 0){x+=1;const S=getAllTextTillNextClickableElement(f);let A="";if(o.length>0&&f.attributes){const M=matchAttributes(f.attributes,o),W=Object.keys(M);if(W.length>1){const N=new Set,H={};for(const V of W){const Z=M[V];Z.length>5&&(Z in H?N.add(V):H[Z]=V)}for(const V of N)delete M[V]}M.role===f.tagName&&delete M.role;for(const N of["aria-label","placeholder","title"])M[N]&&M[N].toLowerCase().trim()===S.toLowerCase().trim()&&delete M[N];Object.keys(M).length>0&&(A=Object.entries(M).map(([N,H])=>`${N}=${i(H,20)}`).join(" "))}let D=`${b}${f.isNew?`*[${f.highlightIndex}]`:`[${f.highlightIndex}]`}<${f.tagName??""}`;if(A&&(D+=` ${A}`),f.extra&&f.extra.scrollable){let M="";f.extra.scrollData?.left&&(M+=`left=${f.extra.scrollData.left}, `),f.extra.scrollData?.top&&(M+=`top=${f.extra.scrollData.top}, `),f.extra.scrollData?.right&&(M+=`right=${f.extra.scrollData.right}, `),f.extra.scrollData?.bottom&&(M+=`bottom=${f.extra.scrollData.bottom}`),D+=` data-scrollable="${M}"`}if(S){const M=S.trim();A||(D+=" "),D+=`>${M}`}else A||(D+=" ");D+=" />",g.push(D)}const _=h&&f.highlightIndex===void 0,E=_?g.length:-1;_&&(g.push(`${b}<${f.tagName}>`),x+=1);for(const S of f.children)u(S,x,g);_&&(g.length===E+1?g.pop():g.push(`${b}</${f.tagName}>`))}else if(f.type==="text"){if(c(f))return;f.parent&&f.parent.type==="element"&&f.parent.isVisible&&f.parent.isTopElement&&g.push(`${b}${f.text??""}`)}},p=[];return u(l,0,p),p.join(`
300
- `)}var getAllTextTillNextClickableElement=(e,t=-1)=>{const n=[],r=(o,i)=>{if(!(t!==-1&&i>t)&&!(o.type==="element"&&o!==e&&o.highlightIndex!==void 0)){if(o.type==="text"&&o.text)n.push(o.text);else if(o.type==="element")for(const s of o.children)r(s,i+1)}};return r(e,0),n.join(`
301
- `).trim()};function getSelectorMap(e){const t=new Map,n=Object.keys(e.map);for(const r of n){const o=e.map[r];o.isInteractive&&typeof o.highlightIndex=="number"&&t.set(o.highlightIndex,o)}return t}function getElementTextMap(e){const t=e.split(`
302
- `).map(r=>r.trim()).filter(r=>r.length>0),n=new Map;for(const r of t){const o=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(r);if(o){const i=parseInt(o[1],10);n.set(i,r)}}return n}function cleanUpHighlights(){const e=window._highlightCleanupFunctions||[];for(const 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(){const 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),o=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,i=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,s=Math.max(0,r-(window.innerHeight+i)),a=Math.max(0,n-(window.innerWidth+o));return{viewport_width:e,viewport_height:t,page_width:n,page_height:r,scroll_x:o,scroll_y:i,pixels_above:i,pixels_below:s,pages_above:t>0?i/t:0,pages_below:t>0?s/t:0,total_pages:t>0?r/t:0,current_page_position:i/Math.max(1,r-t),pixels_left:o,pixels_right:a}}function patchReact(e){const t=document.querySelectorAll('[data-reactroot], [data-reactid], [data-react-checksum], #root, #app, [id^="root-"], [id^="app-"], #adex-wrapper, #adex-root');for(const n of t)n.setAttribute("data-page-agent-not-interactive","true")}var 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(),e.enableMask&&this.initMask()}initMask(){this.maskReady===null&&(this.maskReady=(async()=>{const{SimulatorMask:e}=await Promise.resolve().then(()=>SimulatorMaskBHVXyogh);this.mask=new e})())}async getCurrentUrl(){return window.location.href}async getLastUpdateTime(){return this.lastTimeUpdate}async getBrowserState(){const e=window.location.href,t=document.title,n=getPageInfo(),r=resolveViewportExpansion(this.config.viewportExpansion);await this.updateTree();const o=this.simplifiedHTML;return{url:e,title:t,header:`${`Current Page: [${t}](${e})`}
303
- ${`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`}
304
-
305
- ${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:"}
306
-
307
- ${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:o,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();const 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 new Error("DOM tree not indexed yet. Can not perform actions on elements.")}async clickElement(e){try{this.assertIndexed();const 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(t){return{success:!1,message:`❌ Failed to click element: ${t}`}}}async inputText(e,t){try{this.assertIndexed();const 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(n){return{success:!1,message:`❌ Failed to input text: ${n}`}}}async selectOption(e,t){try{this.assertIndexed();const 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(n){return{success:!1,message:`❌ Failed to select option: ${n}`}}}async scroll(e){try{const{down:t,numPages:n,pixels:r,index:o}=e;return this.assertIndexed(),{success:!0,message:await scrollVertically((r??n*window.innerHeight)*(t?1:-1),o!==void 0?getElementByIndex(this.selectorMap,o):null)}}catch(t){return{success:!1,message:`❌ Failed to scroll: ${t}`}}}async scrollHorizontally(e){try{const{right:t,pixels:n,index:r}=e;return this.assertIndexed(),{success:!0,message:await scrollHorizontally(n*(t?1:-1),r!==void 0?getElementByIndex(this.selectorMap,r):null)}}catch(t){return{success:!1,message:`❌ Failed to scroll horizontally: ${t}`}}}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}},toStr=Object.prototype.toString;function isCallable(e){return typeof e=="function"||toStr.call(e)==="[object Function]"}function toInteger(e){var t=Number(e);return isNaN(t)?0:t===0||!isFinite(t)?t:(t>0?1:-1)*Math.floor(Math.abs(t))}var maxSafeInteger=Math.pow(2,53)-1;function toLength(e){var t=toInteger(e);return Math.min(Math.max(t,0),maxSafeInteger)}function arrayFrom(e,t){var n=Array,r=Object(e);if(e==null)throw new TypeError("Array.from requires an array-like object - not null or undefined");for(var o=toLength(r.length),i=isCallable(n)?Object(new n(o)):new Array(o),s=0,a;s<o;)a=r[s],i[s]=a,s+=1;return i.length=o,i}function _typeof$1(e){"@babel/helpers - typeof";return _typeof$1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_typeof$1(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,_toPropertyKey(r.key),r)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function _defineProperty(e,t,n){return t=_toPropertyKey(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _toPropertyKey(e){var t=_toPrimitive(e,"string");return _typeof$1(t)==="symbol"?t:String(t)}function _toPrimitive(e,t){if(_typeof$1(e)!=="object"||e===null)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(_typeof$1(r)!=="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var SetLike=(function(){function e(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];_classCallCheck(this,e),_defineProperty(this,"items",void 0),this.items=t}return _createClass(e,[{key:"add",value:function(n){return this.has(n)===!1&&this.items.push(n),this}},{key:"clear",value:function(){this.items=[]}},{key:"delete",value:function(n){var r=this.items.length;return this.items=this.items.filter(function(o){return o!==n}),r!==this.items.length}},{key:"forEach",value:function(n){var r=this;this.items.forEach(function(o){n(o,o,r)})}},{key:"has",value:function(n){return this.items.indexOf(n)!==-1}},{key:"size",get:function(){return this.items.length}}]),e})();const SetLike$1=typeof Set>"u"?Set:SetLike;function getLocalName(e){var t;return(t=e.localName)!==null&&t!==void 0?t:e.tagName.toLowerCase()}var localNameToRoleMappings={article:"article",aside:"complementary",button:"button",datalist:"listbox",dd:"definition",details:"group",dialog:"dialog",dt:"term",fieldset:"group",figure:"figure",form:"form",footer:"contentinfo",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",header:"banner",hr:"separator",html:"document",legend:"legend",li:"listitem",math:"math",main:"main",menu:"list",nav:"navigation",ol:"list",optgroup:"group",option:"option",output:"status",progress:"progressbar",section:"region",summary:"button",table:"table",tbody:"rowgroup",textarea:"textbox",tfoot:"rowgroup",td:"cell",th:"columnheader",thead:"rowgroup",tr:"row",ul:"list"},prohibitedAttributes={caption:new Set(["aria-label","aria-labelledby"]),code:new Set(["aria-label","aria-labelledby"]),deletion:new Set(["aria-label","aria-labelledby"]),emphasis:new Set(["aria-label","aria-labelledby"]),generic:new Set(["aria-label","aria-labelledby","aria-roledescription"]),insertion:new Set(["aria-label","aria-labelledby"]),none:new Set(["aria-label","aria-labelledby"]),paragraph:new Set(["aria-label","aria-labelledby"]),presentation:new Set(["aria-label","aria-labelledby"]),strong:new Set(["aria-label","aria-labelledby"]),subscript:new Set(["aria-label","aria-labelledby"]),superscript:new Set(["aria-label","aria-labelledby"])};function hasGlobalAriaAttributes(e,t){return["aria-atomic","aria-busy","aria-controls","aria-current","aria-description","aria-describedby","aria-details","aria-dropeffect","aria-flowto","aria-grabbed","aria-hidden","aria-keyshortcuts","aria-label","aria-labelledby","aria-live","aria-owns","aria-relevant","aria-roledescription"].some(function(n){var r;return e.hasAttribute(n)&&!((r=prohibitedAttributes[t])!==null&&r!==void 0&&r.has(n))})}function ignorePresentationalRole(e,t){return hasGlobalAriaAttributes(e,t)}function getRole(e){var t=getExplicitRole(e);if(t===null||presentationRoles.indexOf(t)!==-1){var n=getImplicitRole(e);if(presentationRoles.indexOf(t||"")===-1||ignorePresentationalRole(e,n||""))return n}return t}function getImplicitRole(e){var t=localNameToRoleMappings[getLocalName(e)];if(t!==void 0)return t;switch(getLocalName(e)){case"a":case"area":case"link":if(e.hasAttribute("href"))return"link";break;case"img":return e.getAttribute("alt")===""&&!ignorePresentationalRole(e,"img")?"presentation":"img";case"input":{var n=e,r=n.type;switch(r){case"button":case"image":case"reset":case"submit":return"button";case"checkbox":case"radio":return r;case"range":return"slider";case"email":case"tel":case"text":case"url":return e.hasAttribute("list")?"combobox":"textbox";case"search":return e.hasAttribute("list")?"combobox":"searchbox";case"number":return"spinbutton";default:return null}}case"select":return e.hasAttribute("multiple")||e.size>1?"listbox":"combobox"}return null}function getExplicitRole(e){var t=e.getAttribute("role");if(t!==null){var n=t.trim().split(" ")[0];if(n.length>0)return n}return null}var presentationRoles=["presentation","none"];function isElement(e){return e!==null&&e.nodeType===e.ELEMENT_NODE}function isHTMLTableCaptionElement(e){return isElement(e)&&getLocalName(e)==="caption"}function isHTMLInputElement(e){return isElement(e)&&getLocalName(e)==="input"}function isHTMLOptGroupElement(e){return isElement(e)&&getLocalName(e)==="optgroup"}function isHTMLSelectElement(e){return isElement(e)&&getLocalName(e)==="select"}function isHTMLTableElement(e){return isElement(e)&&getLocalName(e)==="table"}function isHTMLTextAreaElement(e){return isElement(e)&&getLocalName(e)==="textarea"}function safeWindow(e){var t=e.ownerDocument===null?e:e.ownerDocument,n=t.defaultView;if(n===null)throw new TypeError("no window available");return n}function isHTMLFieldSetElement(e){return isElement(e)&&getLocalName(e)==="fieldset"}function isHTMLLegendElement(e){return isElement(e)&&getLocalName(e)==="legend"}function isHTMLSlotElement(e){return isElement(e)&&getLocalName(e)==="slot"}function isSVGElement(e){return isElement(e)&&e.ownerSVGElement!==void 0}function isSVGSVGElement(e){return isElement(e)&&getLocalName(e)==="svg"}function isSVGTitleElement(e){return isSVGElement(e)&&getLocalName(e)==="title"}function queryIdRefs(e,t){if(isElement(e)&&e.hasAttribute(t)){var n=e.getAttribute(t).split(" "),r=e.getRootNode?e.getRootNode():e.ownerDocument;return n.map(function(o){return r.getElementById(o)}).filter(function(o){return o!==null})}return[]}function hasAnyConcreteRoles(e,t){return isElement(e)?t.indexOf(getRole(e))!==-1:!1}function asFlatString(e){return e.trim().replace(/\s\s+/g," ")}function isHidden$2(e,t){if(!isElement(e))return!1;if(e.hasAttribute("hidden")||e.getAttribute("aria-hidden")==="true")return!0;var n=t(e);return n.getPropertyValue("display")==="none"||n.getPropertyValue("visibility")==="hidden"}function isControl(e){return hasAnyConcreteRoles(e,["button","combobox","listbox","textbox"])||hasAbstractRole(e,"range")}function hasAbstractRole(e,t){if(!isElement(e))return!1;switch(t){case"range":return hasAnyConcreteRoles(e,["meter","progressbar","scrollbar","slider","spinbutton"]);default:throw new TypeError("No knowledge about abstract role '".concat(t,"'. This is likely a bug :("))}}function querySelectorAllSubtree(e,t){var n=arrayFrom(e.querySelectorAll(t));return queryIdRefs(e,"aria-owns").forEach(function(r){n.push.apply(n,arrayFrom(r.querySelectorAll(t)))}),n}function querySelectedOptions(e){return isHTMLSelectElement(e)?e.selectedOptions||querySelectorAllSubtree(e,"[selected]"):querySelectorAllSubtree(e,'[aria-selected="true"]')}function isMarkedPresentational(e){return hasAnyConcreteRoles(e,presentationRoles)}function isNativeHostLanguageTextAlternativeElement(e){return isHTMLTableCaptionElement(e)}function allowsNameFromContent(e){return hasAnyConcreteRoles(e,["button","cell","checkbox","columnheader","gridcell","heading","label","legend","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","row","rowheader","switch","tab","tooltip","treeitem"])}function isDescendantOfNativeHostLanguageTextAlternativeElement(e){return!1}function getValueOfTextbox(e){return isHTMLInputElement(e)||isHTMLTextAreaElement(e)?e.value:e.textContent||""}function getTextualContent(e){var t=e.getPropertyValue("content");return/^["'].*["']$/.test(t)?t.slice(1,-1):""}function isLabelableElement(e){var t=getLocalName(e);return t==="button"||t==="input"&&e.getAttribute("type")!=="hidden"||t==="meter"||t==="output"||t==="progress"||t==="select"||t==="textarea"}function findLabelableElement(e){if(isLabelableElement(e))return e;var t=null;return e.childNodes.forEach(function(n){if(t===null&&isElement(n)){var r=findLabelableElement(n);r!==null&&(t=r)}}),t}function getControlOfLabel(e){if(e.control!==void 0)return e.control;var t=e.getAttribute("for");return t!==null?e.ownerDocument.getElementById(t):findLabelableElement(e)}function getLabels(e){var t=e.labels;if(t===null)return t;if(t!==void 0)return arrayFrom(t);if(!isLabelableElement(e))return null;var n=e.ownerDocument;return arrayFrom(n.querySelectorAll("label")).filter(function(r){return getControlOfLabel(r)===e})}function getSlotContents(e){var t=e.assignedNodes();return t.length===0?arrayFrom(e.childNodes):t}function computeTextAlternative(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=new SetLike$1,r=safeWindow(e),o=t.compute,i=o===void 0?"name":o,s=t.computedStyleSupportsPseudoElements,a=s===void 0?t.getComputedStyle!==void 0:s,l=t.getComputedStyle,c=l===void 0?r.getComputedStyle.bind(r):l,u=t.hidden,p=u===void 0?!1:u;function f(h,_){var E="";if(isElement(h)&&a){var S=c(h,"::before"),A=getTextualContent(S);E="".concat(A," ").concat(E)}var D=isHTMLSlotElement(h)?getSlotContents(h):arrayFrom(h.childNodes).concat(queryIdRefs(h,"aria-owns"));if(D.forEach(function(N){var H=b(N,{isEmbeddedInLabel:_.isEmbeddedInLabel,isReferenced:!1,recursion:!0}),V=isElement(N)?c(N).getPropertyValue("display"):"inline",Z=V!=="inline"?" ":"";E+="".concat(Z).concat(H).concat(Z)}),isElement(h)&&a){var M=c(h,"::after"),W=getTextualContent(M);E="".concat(E," ").concat(W)}return E.trim()}function m(h,_){var E=h.getAttributeNode(_);return E!==null&&!n.has(E)&&E.value.trim()!==""?(n.add(E),E.value):null}function g(h){return isElement(h)?m(h,"title"):null}function x(h){if(!isElement(h))return null;if(isHTMLFieldSetElement(h)){n.add(h);for(var _=arrayFrom(h.childNodes),E=0;E<_.length;E+=1){var S=_[E];if(isHTMLLegendElement(S))return b(S,{isEmbeddedInLabel:!1,isReferenced:!1,recursion:!1})}}else if(isHTMLTableElement(h)){n.add(h);for(var A=arrayFrom(h.childNodes),D=0;D<A.length;D+=1){var M=A[D];if(isHTMLTableCaptionElement(M))return b(M,{isEmbeddedInLabel:!1,isReferenced:!1,recursion:!1})}}else if(isSVGSVGElement(h)){n.add(h);for(var W=arrayFrom(h.childNodes),N=0;N<W.length;N+=1){var H=W[N];if(isSVGTitleElement(H))return H.textContent}return null}else if(getLocalName(h)==="img"||getLocalName(h)==="area"){var V=m(h,"alt");if(V!==null)return V}else if(isHTMLOptGroupElement(h)){var Z=m(h,"label");if(Z!==null)return Z}if(isHTMLInputElement(h)&&(h.type==="button"||h.type==="submit"||h.type==="reset")){var oe=m(h,"value");if(oe!==null)return oe;if(h.type==="submit")return"Submit";if(h.type==="reset")return"Reset"}var Q=getLabels(h);if(Q!==null&&Q.length!==0)return n.add(h),arrayFrom(Q).map(function(K){return b(K,{isEmbeddedInLabel:!0,isReferenced:!1,recursion:!0})}).filter(function(K){return K.length>0}).join(" ");if(isHTMLInputElement(h)&&h.type==="image"){var te=m(h,"alt");if(te!==null)return te;var ie=m(h,"title");return ie!==null?ie:"Submit Query"}if(hasAnyConcreteRoles(h,["button"])){var ne=f(h,{isEmbeddedInLabel:!1});if(ne!=="")return ne}return null}function b(h,_){if(n.has(h))return"";if(!p&&isHidden$2(h,c)&&!_.isReferenced)return n.add(h),"";var E=isElement(h)?h.getAttributeNode("aria-labelledby"):null,S=E!==null&&!n.has(E)?queryIdRefs(h,"aria-labelledby"):[];if(i==="name"&&!_.isReferenced&&S.length>0)return n.add(E),S.map(function(V){return b(V,{isEmbeddedInLabel:_.isEmbeddedInLabel,isReferenced:!0,recursion:!1})}).join(" ");var A=_.recursion&&isControl(h)&&i==="name";if(!A){var D=(isElement(h)&&h.getAttribute("aria-label")||"").trim();if(D!==""&&i==="name")return n.add(h),D;if(!isMarkedPresentational(h)){var M=x(h);if(M!==null)return n.add(h),M}}if(hasAnyConcreteRoles(h,["menu"]))return n.add(h),"";if(A||_.isEmbeddedInLabel||_.isReferenced){if(hasAnyConcreteRoles(h,["combobox","listbox"])){n.add(h);var W=querySelectedOptions(h);return W.length===0?isHTMLInputElement(h)?h.value:"":arrayFrom(W).map(function(V){return b(V,{isEmbeddedInLabel:_.isEmbeddedInLabel,isReferenced:!1,recursion:!0})}).join(" ")}if(hasAbstractRole(h,"range"))return n.add(h),h.hasAttribute("aria-valuetext")?h.getAttribute("aria-valuetext"):h.hasAttribute("aria-valuenow")?h.getAttribute("aria-valuenow"):h.getAttribute("value")||"";if(hasAnyConcreteRoles(h,["textbox"]))return n.add(h),getValueOfTextbox(h)}if(allowsNameFromContent(h)||isElement(h)&&_.isReferenced||isNativeHostLanguageTextAlternativeElement(h)||isDescendantOfNativeHostLanguageTextAlternativeElement()){var N=f(h,{isEmbeddedInLabel:_.isEmbeddedInLabel});if(N!=="")return n.add(h),N}if(h.nodeType===h.TEXT_NODE)return n.add(h),h.textContent||"";if(_.recursion)return n.add(h),f(h,{isEmbeddedInLabel:_.isEmbeddedInLabel});var H=g(h);return H!==null?(n.add(h),H):(n.add(h),"")}return asFlatString(b(e,{isEmbeddedInLabel:!1,isReferenced:i==="description",recursion:!1}))}function prohibitsNaming(e){return hasAnyConcreteRoles(e,["caption","code","deletion","emphasis","generic","insertion","none","paragraph","presentation","strong","subscript","superscript"])}function computeAccessibleName(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return prohibitsNaming(e)?"":computeTextAlternative(e,t)}var candidateSelectors=["input:not([inert]):not([inert] *)","select:not([inert]):not([inert] *)","textarea:not([inert]):not([inert] *)","a[href]:not([inert]):not([inert] *)","area[href]:not([inert]):not([inert] *)","button:not([inert]):not([inert] *)","[tabindex]:not(slot):not([inert]):not([inert] *)","audio[controls]:not([inert]):not([inert] *)","video[controls]:not([inert]):not([inert] *)",'[contenteditable]:not([contenteditable="false"]):not([inert]):not([inert] *)',"details>summary:first-of-type:not([inert]):not([inert] *)","details:not([inert]):not([inert] *)"],NoElement=typeof Element>"u",matches=NoElement?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector,getRootNode=!NoElement&&Element.prototype.getRootNode?function(e){var t;return e==null||(t=e.getRootNode)===null||t===void 0?void 0:t.call(e)}:function(e){return e?.ownerDocument},isInput=function e(t){return t.tagName==="INPUT"},isHiddenInput=function e(t){return isInput(t)&&t.type==="hidden"},isDetailsWithSummary=function e(t){var n=t.tagName==="DETAILS"&&Array.prototype.slice.apply(t.children).some(function(r){return r.tagName==="SUMMARY"});return n},isNodeAttached=function e(t){var n,r=t&&getRootNode(t),o=(n=r)===null||n===void 0?void 0:n.host,i=!1;if(r&&r!==t){var s,a,l;for(i=!!((s=o)!==null&&s!==void 0&&(a=s.ownerDocument)!==null&&a!==void 0&&a.contains(o)||t!=null&&(l=t.ownerDocument)!==null&&l!==void 0&&l.contains(t));!i&&o;){var c,u,p;r=getRootNode(o),o=(c=r)===null||c===void 0?void 0:c.host,i=!!((u=o)!==null&&u!==void 0&&(p=u.ownerDocument)!==null&&p!==void 0&&p.contains(o))}}return i},isZeroArea=function e(t){var n=t.getBoundingClientRect(),r=n.width,o=n.height;return r===0&&o===0},isHidden$1=function e(t,n){var r=n.displayCheck,o=n.getShadowRoot;if(r==="full-native"&&"checkVisibility"in t){var i=t.checkVisibility({checkOpacity:!1,opacityProperty:!1,contentVisibilityAuto:!0,visibilityProperty:!0,checkVisibilityCSS:!0});return!i}var s=getComputedStyle(t),a=s.visibility;if(a==="hidden"||a==="collapse")return!0;var l=matches.call(t,"details>summary:first-of-type"),c=l?t.parentElement:t;if(matches.call(c,"details:not([open]) *"))return!0;if(!r||r==="full"||r==="full-native"||r==="legacy-full"){if(typeof o=="function"){for(var u=t;t;){var p=t.parentElement,f=getRootNode(t);if(p&&!p.shadowRoot&&o(p)===!0)return isZeroArea(t);t.assignedSlot?t=t.assignedSlot:!p&&f!==t.ownerDocument?t=f.host:t=p}t=u}if(isNodeAttached(t))return!t.getClientRects().length;if(r!=="legacy-full")return!0}else if(r==="non-zero-area")return isZeroArea(t);return!1},isDisabledFromFieldset=function e(t){if(/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(t.tagName))for(var n=t.parentElement;n;){if(n.tagName==="FIELDSET"&&n.disabled){for(var r=0;r<n.children.length;r++){var o=n.children.item(r);if(o.tagName==="LEGEND")return matches.call(n,"fieldset[disabled] *")?!0:!o.contains(t)}return!0}n=n.parentElement}return!1},isNodeMatchingSelectorFocusable=function e(t,n){return!(n.disabled||isHiddenInput(n)||isHidden$1(n,t)||isDetailsWithSummary(n)||isDisabledFromFieldset(n))},focusableCandidateSelector=candidateSelectors.concat("iframe:not([inert]):not([inert] *)").join(","),isFocusable=function e(t,n){if(n=n||{},!t)throw new Error("No node provided");return matches.call(t,focusableCandidateSelector)===!1?!1:isNodeMatchingSelectorFocusable(n,t)};const TAG_ROLE_MAP={a:"link",article:"article",aside:"complementary",button:"button",caption:"caption",cell:"cell",checkbox:"checkbox",code:"code",columnheader:"columnheader",combobox:"combobox",datalist:"listbox",dd:"definition",details:"group",dialog:"dialog",dt:"term",em:"emphasis",fieldset:"group",figure:"figure",footer:"contentinfo",form:"form",h1:"heading",h2:"heading",h3:"heading",h4:"heading",h5:"heading",h6:"heading",header:"banner",hr:"separator",img:"img",input:"textbox",li:"listitem",link:"link",main:"main",mark:"mark",math:"math",menu:"list",menuitem:"menuitem",meter:"meter",nav:"navigation",ol:"list",option:"option",output:"status",p:"paragraph",progress:"progressbar",rowheader:"rowheader",search:"search",section:"region",select:"listbox",strong:"strong",summary:"button",table:"table",tbody:"rowgroup",td:"cell",tfoot:"rowgroup",th:"columnheader",thead:"rowgroup",time:"time",tr:"row",ul:"list"},INPUT_TYPE_ROLE={button:"button",checkbox:"checkbox",color:"textbox",email:"textbox",file:"textbox",image:"button",number:"spinbutton",radio:"radio",range:"slider",reset:"button",search:"searchbox",submit:"button",tel:"textbox",text:"textbox",url:"textbox"};function inferRole(e){const t=e.getAttribute("role");if(t&&t!=="presentation"&&t!=="none")return t;const n=e.tagName.toLowerCase();if(n==="input"){const r=e.type?.toLowerCase()??"text";return INPUT_TYPE_ROLE[r]??"textbox"}return TAG_ROLE_MAP[n]??"generic"}function getStateTokens(e){const t=[],n=u=>e.getAttribute(u),r=n("aria-checked");r==="true"?t.push("checked"):r==="false"&&t.push("unchecked"),n("aria-selected")==="true"&&t.push("selected"),(n("aria-disabled")==="true"||e.disabled)&&t.push("disabled");const i=n("aria-haspopup");i&&i!=="false"&&t.push("hasPopup"),n("aria-expanded")==="true"&&t.push("expanded");const s=e.tagName.match(/^H([1-6])$/);s&&t.push(`level=${s[1]}`);const a=n("aria-level");a&&!s&&t.push(`level=${a}`);try{window.getComputedStyle(e).cursor==="pointer"&&t.push("cursor=pointer")}catch{}const l=e.tagName.toLowerCase();if(l==="input"||l==="textarea"||l==="select"){const u=e.value;u!==void 0&&u!==""&&t.push(`value="${u}"`)}const c=e.getAttribute("aria-valuenow");return c&&t.push(`valuenow="${c}"`),t}function isHidden(e){if(e.getAttribute("aria-hidden")==="true"||e.hidden)return!0;try{const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!0}catch{}return!1}function buildVNode(e,t,n,r,o){if(isHidden(e)||r.has(e))return null;const i=inferRole(e),s=getStateTokens(e),a=computeAccessibleName(e),l=isFocusable(e),c=s.includes("cursor=pointer"),u=o.has(e),p=l||u||c&&(i!=="generic"||a!=="");let f;p&&(f=t.value,n.set(f,e),t.value++);const m=[];for(const g of Array.from(e.children)){const x=buildVNode(g,t,n,r,o);x&&m.push(x)}return{role:i,name:a,tokens:s,ref:f,el:e,children:m}}function hasValue(e){return e.ref!==void 0||e.name.trim()!==""?!0:e.children.some(hasValue)}function shouldPassThrough(e,t){return!(!t.pruneUnnamed||t.preserveRoles.includes(e.role)||e.ref!==void 0||e.name.trim()!=="")}function serializeVNode(e,t,n){if(shouldPassThrough(e,n))return e.children.filter(c=>hasValue(c)).flatMap(c=>serializeVNode(c,t,n));const r=" ".repeat(t),o=e.ref!==void 0?` #${e.ref}`:"",i=e.tokens.length>0?` [${e.tokens.join(" ")}]`:"",s=e.name?` "${e.name}"`:"",a=`${r}- ${e.role}${o}${i}${s}`,l=e.children.flatMap(c=>serializeVNode(c,t+1,n));return[a,...l]}const DEFAULT_OPTIONS={pruneUnnamed:!0,preserveRoles:[]};function buildA11yTree(e=document.body,t=[],n=[],r){const o={...DEFAULT_OPTIONS,...r},i={value:0},s=new Map,a=new Set(t),l=new Set(n),c=[];for(const p of Array.from(e.children)){const f=buildVNode(p,i,s,a,l);f&&c.push(...serializeVNode(f,0,o))}return{yaml:"```yaml\n"+c.join(`
308
- `)+"\n```",refMap:s,interactiveCount:s.size,lines:c}}function searchA11yTree(e,t=document.body,n=[],r=[],o){const{contextLines:i=2,caseInsensitive:s=!0,maxMatches:a=20,...l}=o??{},{lines:c}=buildA11yTree(t,n,r,l),u=s?e.toLowerCase():e,p=c.length,m=/^#\d+$/.test(e)?new RegExp(`\\s${e}(?:\\s|[\\[]|$)`):null,g=[];for(let E=0;E<c.length;E++){let S=!1;m?S=m.test(c[E]):S=(s?c[E].toLowerCase():c[E]).includes(u),S&&g.push(E)}const x=[];let b=!1;for(const E of g){const S=Math.max(0,E-i),A=Math.min(p-1,E+i),D=x[x.length-1];if(D&&S<=D.end+1)D.end=Math.max(D.end,A),D.hits.push(E);else{if(x.length>=a){b=!0;break}x.push({start:S,end:A,hits:[E]})}}const h=x.map(E=>({lineNumber:E.hits[0]+1,line:c[E.hits[0]],context:Array.from({length:E.end-E.start+1},(S,A)=>({lineNumber:E.start+A+1,line:c[E.start+A]}))})),_=[`无障碍树搜索结果 — 关键词: "${e}" | 总行数: ${p} | 命中: ${g.length} 行 | 返回分组: ${h.length}`,""];return h.length===0?_.push("(未找到匹配项)"):(h.forEach((E,S)=>{const A=x[S];_.push(`── 分组 ${S+1}(第 ${A.start+1}–${A.end+1} 行)──`),E.context.forEach(({lineNumber:D,line:M})=>{const W=A.hits.includes(D-1),N=String(D).padStart(4);_.push(W?`>>>${N} | ${M}`:` ${N} | ${M}`)}),_.push("")}),b&&_.push(`⚠️ 命中过多,已截断至前 ${a} 个分组,建议缩小搜索范围`),_.push("提示:如需操作命中元素,使用其 #N 索引;如需查看完整树,请使用 browserState。")),{text:_.join(`
309
- `),matches:h,totalLines:p,matchCount:g.length}}function Diff(){}Diff.prototype={diff:function e(t,n){var r,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=o.callback;typeof o=="function"&&(i=o,o={});var s=this;function a(S){return S=s.postProcess(S,o),i?(setTimeout(function(){i(S)},0),!0):S}t=this.castInput(t,o),n=this.castInput(n,o),t=this.removeEmpty(this.tokenize(t,o)),n=this.removeEmpty(this.tokenize(n,o));var l=n.length,c=t.length,u=1,p=l+c;o.maxEditLength!=null&&(p=Math.min(p,o.maxEditLength));var f=(r=o.timeout)!==null&&r!==void 0?r:1/0,m=Date.now()+f,g=[{oldPos:-1,lastComponent:void 0}],x=this.extractCommon(g[0],n,t,0,o);if(g[0].oldPos+1>=c&&x+1>=l)return a(buildValues(s,g[0].lastComponent,n,t,s.useLongestToken));var b=-1/0,h=1/0;function _(){for(var S=Math.max(b,-u);S<=Math.min(h,u);S+=2){var A=void 0,D=g[S-1],M=g[S+1];D&&(g[S-1]=void 0);var W=!1;if(M){var N=M.oldPos-S;W=M&&0<=N&&N<l}var H=D&&D.oldPos+1<c;if(!W&&!H){g[S]=void 0;continue}if(!H||W&&D.oldPos<M.oldPos?A=s.addToPath(M,!0,!1,0,o):A=s.addToPath(D,!1,!0,1,o),x=s.extractCommon(A,n,t,S,o),A.oldPos+1>=c&&x+1>=l)return a(buildValues(s,A.lastComponent,n,t,s.useLongestToken));g[S]=A,A.oldPos+1>=c&&(h=Math.min(h,S-1)),x+1>=l&&(b=Math.max(b,S+1))}u++}if(i)(function S(){setTimeout(function(){if(u>p||Date.now()>m)return i();_()||S()},0)})();else for(;u<=p&&Date.now()<=m;){var E=_();if(E)return E}},addToPath:function e(t,n,r,o,i){var s=t.lastComponent;return s&&!i.oneChangePerToken&&s.added===n&&s.removed===r?{oldPos:t.oldPos+o,lastComponent:{count:s.count+1,added:n,removed:r,previousComponent:s.previousComponent}}:{oldPos:t.oldPos+o,lastComponent:{count:1,added:n,removed:r,previousComponent:s}}},extractCommon:function e(t,n,r,o,i){for(var s=n.length,a=r.length,l=t.oldPos,c=l-o,u=0;c+1<s&&l+1<a&&this.equals(r[l+1],n[c+1],i);)c++,l++,u++,i.oneChangePerToken&&(t.lastComponent={count:1,previousComponent:t.lastComponent,added:!1,removed:!1});return u&&!i.oneChangePerToken&&(t.lastComponent={count:u,previousComponent:t.lastComponent,added:!1,removed:!1}),t.oldPos=l,c},equals:function e(t,n,r){return r.comparator?r.comparator(t,n):t===n||r.ignoreCase&&t.toLowerCase()===n.toLowerCase()},removeEmpty:function e(t){for(var n=[],r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n},castInput:function e(t){return t},tokenize:function e(t){return Array.from(t)},join:function e(t){return t.join("")},postProcess:function e(t){return t}};function buildValues(e,t,n,r,o){for(var i=[],s;t;)i.push(t),s=t.previousComponent,delete t.previousComponent,t=s;i.reverse();for(var a=0,l=i.length,c=0,u=0;a<l;a++){var p=i[a];if(p.removed)p.value=e.join(r.slice(u,u+p.count)),u+=p.count;else{if(!p.added&&o){var f=n.slice(c,c+p.count);f=f.map(function(m,g){var x=r[u+g];return x.length>m.length?x:m}),p.value=e.join(f)}else p.value=e.join(n.slice(c,c+p.count));c+=p.count,p.added||(u+=p.count)}}return i}function longestCommonPrefix(e,t){var n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function longestCommonSuffix(e,t){var n;if(!e||!t||e[e.length-1]!=t[t.length-1])return"";for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function replacePrefix(e,t,n){if(e.slice(0,t.length)!=t)throw Error("string ".concat(JSON.stringify(e)," doesn't start with prefix ").concat(JSON.stringify(t),"; this is a bug"));return n+e.slice(t.length)}function replaceSuffix(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error("string ".concat(JSON.stringify(e)," doesn't end with suffix ").concat(JSON.stringify(t),"; this is a bug"));return e.slice(0,-t.length)+n}function removePrefix(e,t){return replacePrefix(e,t,"")}function removeSuffix(e,t){return replaceSuffix(e,t,"")}function maximumOverlap(e,t){return t.slice(0,overlapCount(e,t))}function overlapCount(e,t){var n=0;e.length>t.length&&(n=e.length-t.length);var r=t.length;e.length<t.length&&(r=e.length);var o=Array(r),i=0;o[0]=0;for(var s=1;s<r;s++){for(t[s]==t[i]?o[s]=o[i]:o[s]=i;i>0&&t[s]!=t[i];)i=o[i];t[s]==t[i]&&i++}i=0;for(var a=n;a<e.length;a++){for(;i>0&&e[a]!=t[i];)i=o[i];e[a]==t[i]&&i++}return i}var extendedWordChars="a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}",tokenizeIncludingWhitespace=new RegExp("[".concat(extendedWordChars,"]+|\\s+|[^").concat(extendedWordChars,"]"),"ug"),wordDiff=new Diff;wordDiff.equals=function(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()},wordDiff.tokenize=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;if(t.intlSegmenter){if(t.intlSegmenter.resolvedOptions().granularity!="word")throw new Error('The segmenter passed must have a granularity of "word"');n=Array.from(t.intlSegmenter.segment(e),function(i){return i.segment})}else n=e.match(tokenizeIncludingWhitespace)||[];var r=[],o=null;return n.forEach(function(i){/\s/.test(i)?o==null?r.push(i):r.push(r.pop()+i):/\s/.test(o)?r[r.length-1]==o?r.push(r.pop()+i):r.push(o+i):r.push(i),o=i}),r},wordDiff.join=function(e){return e.map(function(t,n){return n==0?t:t.replace(/^\s+/,"")}).join("")},wordDiff.postProcess=function(e,t){if(!e||t.oneChangePerToken)return e;var n=null,r=null,o=null;return e.forEach(function(i){i.added?r=i:i.removed?o=i:((r||o)&&dedupeWhitespaceInChangeObjects(n,o,r,i),n=i,r=null,o=null)}),(r||o)&&dedupeWhitespaceInChangeObjects(n,o,r,null),e};function dedupeWhitespaceInChangeObjects(e,t,n,r){if(t&&n){var o=t.value.match(/^\s*/)[0],i=t.value.match(/\s*$/)[0],s=n.value.match(/^\s*/)[0],a=n.value.match(/\s*$/)[0];if(e){var l=longestCommonPrefix(o,s);e.value=replaceSuffix(e.value,s,l),t.value=removePrefix(t.value,l),n.value=removePrefix(n.value,l)}if(r){var c=longestCommonSuffix(i,a);r.value=replacePrefix(r.value,a,c),t.value=removeSuffix(t.value,c),n.value=removeSuffix(n.value,c)}}else if(n)e&&(n.value=n.value.replace(/^\s*/,"")),r&&(r.value=r.value.replace(/^\s*/,""));else if(e&&r){var u=r.value.match(/^\s*/)[0],p=t.value.match(/^\s*/)[0],f=t.value.match(/\s*$/)[0],m=longestCommonPrefix(u,p);t.value=removePrefix(t.value,m);var g=longestCommonSuffix(removePrefix(u,m),f);t.value=removeSuffix(t.value,g),r.value=replacePrefix(r.value,u,g),e.value=replaceSuffix(e.value,u,u.slice(0,u.length-g.length))}else if(r){var x=r.value.match(/^\s*/)[0],b=t.value.match(/\s*$/)[0],h=maximumOverlap(b,x);t.value=removeSuffix(t.value,h)}else if(e){var _=e.value.match(/\s*$/)[0],E=t.value.match(/^\s*/)[0],S=maximumOverlap(_,E);t.value=removePrefix(t.value,S)}}var wordWithSpaceDiff=new Diff;wordWithSpaceDiff.tokenize=function(e){var t=new RegExp("(\\r?\\n)|[".concat(extendedWordChars,"]+|[^\\S\\n\\r]+|[^").concat(extendedWordChars,"]"),"ug");return e.match(t)||[]};var lineDiff=new Diff;lineDiff.tokenize=function(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
310
- `));var n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var o=0;o<r.length;o++){var i=r[o];o%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n},lineDiff.equals=function(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
311
- `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
312
- `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
313
- `)&&(e=e.slice(0,-1)),t.endsWith(`
314
- `)&&(t=t.slice(0,-1))),Diff.prototype.equals.call(this,e,t,n)};function diffLines(e,t,n){return lineDiff.diff(e,t,n)}var sentenceDiff=new Diff;sentenceDiff.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var cssDiff=new Diff;cssDiff.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function _typeof(e){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_typeof(e)}var jsonDiff=new Diff;jsonDiff.useLongestToken=!0,jsonDiff.tokenize=lineDiff.tokenize,jsonDiff.castInput=function(e,t){var n=t.undefinedReplacement,r=t.stringifyReplacer,o=r===void 0?function(i,s){return typeof s>"u"?n:s}:r;return typeof e=="string"?e:JSON.stringify(canonicalize(e,null,null,o),o," ")},jsonDiff.equals=function(e,t,n){return Diff.prototype.equals.call(jsonDiff,e.replace(/,([\r\n])/g,"$1"),t.replace(/,([\r\n])/g,"$1"),n)};function canonicalize(e,t,n,r,o){t=t||[],n=n||[],r&&(e=r(o,e));var i;for(i=0;i<t.length;i+=1)if(t[i]===e)return n[i];var s;if(Object.prototype.toString.call(e)==="[object Array]"){for(t.push(e),s=new Array(e.length),n.push(s),i=0;i<e.length;i+=1)s[i]=canonicalize(e[i],t,n,r,o);return t.pop(),n.pop(),s}if(e&&e.toJSON&&(e=e.toJSON()),_typeof(e)==="object"&&e!==null){t.push(e),s={},n.push(s);var a=[],l;for(l in e)Object.prototype.hasOwnProperty.call(e,l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],s[l]=canonicalize(e[l],t,n,r,l);t.pop(),n.pop()}else s=e;return s}var arrayDiff=new Diff;arrayDiff.tokenize=function(e){return e.slice()},arrayDiff.join=arrayDiff.removeEmpty=function(e){return e};class PageStateCache{constructor(){this.prev=null}isFullRefresh(t){return!this.prev||this.prev.url!==t}update(t,n){const r=this.isFullRefresh(t),o=this.prev?.url??"";let i=0,s=0,a="";if(!r&&this.prev){const l=diffLines(this.prev.yaml,n),c=[];l.forEach(u=>{if(!u.added&&!u.removed)return;const p=u.value.split(`
315
- `).filter(Boolean);u.added?(i+=p.length,p.forEach(f=>c.push(`+ ${f}`))):(s+=p.length,p.forEach(f=>c.push(`- ${f}`)))}),a=c.join(`
316
- `)}return this.prev={url:t,yaml:n},{isFullRefresh:r,prevUrl:o,addedLines:i,removedLines:s,diffText:a}}invalidate(){this.prev=null}}function registerPageAgentTool(){initializeBuiltinWebMCP(),window.__webmcpcli_interactiveWhitelist=[],window.__webmcpcli_interactiveBlacklist=[],window.__webmcpcli_beforeGetBrowserState=null;const e=new PageController({enableMask:!0}),t=new PageStateCache;let n=new Map;const r=zod.z.object({action:zod.z.enum(["browserState","click","fill","select","scroll","executeJavascript","searchTree"]).describe(`执行的动作名称, 每一次执行 'click', 'fill', 'select'动作之前,**必须**要先调用 'browserState' 去获取页面的最新状态。
317
- browserState: '查询整个页面的浏览器状态;返回页面的标题、URL、YAML格式的语义化页面树',
318
- click: '根据元素索引点击;',
319
- fill: '根据元素索引填写文本;';
320
- select: '根据元素索引选择下拉框选项;';
321
- scroll: '滚动页面的动作,可以指定水平滚动还是上下滚动; 不带元素索引时:滚动整个文档。带元素索引时:滚动该索引处的容器(或其最近的可滚动祖先元素)'
322
- executeJavascript: '执行javascript代码'
323
- searchTree: '按关键词搜索无障碍树,返回带行号的匹配节点及上下文,无需获取全量树。适合快速定位特定元素(如所有按钮、特定名称的链接等),显著减少上下文消耗。必须提供 query 参数。'
324
- `),index:zod.z.number().min(0).optional().describe("执行动作 of the element index, 动作为 click,fill,select时,必须提供元素索引"),text:zod.z.string().optional().describe("执行动作的文本内容, 动作为 fill,select 时,必须提供文本内容"),down:zod.z.boolean().optional().describe("执行上下滚动时,必须提供down参数"),right:zod.z.boolean().optional().describe("执行水平滚动方向, 必须提供right参数"),numPages:zod.z.number().optional().describe("执行动作的滚动页数, 动作为 scroll时,可以提供滚动页数,建议每次滚动0.1页,该值不要大于5."),pixels:zod.z.number().int().min(0).optional().describe("执行动作的滚动像素数,动作为 scroll时,可以提供滚动像素数"),script:zod.z.string().optional().describe("执行的javascript代码,动作为 executeJavascript时,必须提供script参数"),query:zod.z.string().optional().describe("搜索关键词,动作为 searchTree 时必须提供。支持按 role(如 button、link)、节点名称、状态(如 checked)或 ref 索引(如 #3)搜索"),contextLines:zod.z.number().int().min(0).max(10).default(2).describe("searchTree 时每个命中行前后保留的上下文行数,默认 2"),maxMatches:zod.z.number().int().min(1).max(50).default(20).describe("searchTree 时最大返回分组数,默认 20"),responseMode:zod.z.enum(["full","diff","both"]).optional().default("diff").describe("返回浏览器状态的模式。full: 仅返回当前全量 A11y 树;diff: 仅返回与上一次状态的增量差异;both: 同时返回全量 A11y 树与增量差异。默认值为 diff。")});async function o(s){return await e.hideMask(),{content:[{type:"text",text:s}]}}async function i(s="diff"){const a=window.location.href,l=document.title,c=window.__webmcpcli_interactiveBlacklist??[],u=window.__webmcpcli_interactiveWhitelist??[],{yaml:p,refMap:f}=buildA11yTree(document.body,c,u);n=f;const m=t.update(a,p);await e.hideMask();let g="";return s==="full"?g=p:s==="diff"?g=m.isFullRefresh?p:m.diffText:s==="both"&&(g=`【全量页面树】:
325
- ${p}
326
-
327
- 【增量差异】:
328
- ${m.isFullRefresh?"(首次/刷新,无增量差异)":m.diffText}`),{content:[{type:"text",text:`浏览器状态: ${JSON.stringify({url:a,title:l,content:g})}`}]}}document.modelContext.registerTool({name:"page-agent-tool",description:pageAgentPrompt,inputSchema:zodToJsonSchema(r),async execute(s){await e.showMask();const a=s.responseMode??"diff";try{if(s.action==="browserState")return window.__webmcpcli_beforeGetBrowserState&&window.__webmcpcli_beforeGetBrowserState(),i(a);if(s.action==="click"){if(s.index===void 0)return o("点击结果: 缺少元素索引");const l=n.get(s.index);return l?(await clickElement(l),i(a)):o(`点击结果: 无效的 ref 索引 ${s.index},请先调用 browserState 刷新页面状态`)}else if(s.action==="fill"){if(s.index===void 0||!s.text)return o("填写结果: 缺少元素索引或文本内容");const l=n.get(s.index);if(!l)return o(`填写结果: 无效的 ref 索引 ${s.index},请先调用 browserState 刷新页面状态`);let c=l;if(!(c instanceof HTMLInputElement)&&!(c instanceof HTMLTextAreaElement)){const u=l.querySelector("input, textarea");u&&(c=u)}return c instanceof HTMLInputElement&&c.readOnly?(c.value=s.text,c.dispatchEvent(new Event("input",{bubbles:!0})),c.dispatchEvent(new Event("change",{bubbles:!0})),c.dispatchEvent(new Event("blur",{bubbles:!0}))):await inputTextElement(c,s.text),i(a)}else if(s.action==="select"){if(s.index===void 0||!s.text)return o("选择结果: 缺少元素索引或文本内容");const l=n.get(s.index);return l?(await selectOptionElement(l,s.text),i(a)):o(`选择结果: 无效的 ref 索引 ${s.index},请先调用 browserState 刷新页面状态`)}else if(s.action==="scroll"){if(!s.down&&!s.right)return o("滚动结果: 缺少滚动方向参数");const l=s.index!==void 0?n.get(s.index)??window:window;if(s.right){const c=s.pixels??300;l.scrollBy({left:s.right?c:-c,behavior:"smooth"})}else{const c=s.pixels??Math.round((s.numPages??1)*window.innerHeight);l.scrollBy({top:s.down?c:-c,behavior:"smooth"})}return await new Promise(c=>setTimeout(c,400)),i(a)}else if(s.action==="executeJavascript"){if(!s.script)return o("脚本执行异常: 缺少javascript代码");const l=await new Function(`return (async () => { ${s.script} })()`)();return await e.hideMask(),{content:[{type:"text",text:`脚本执行结果: ${JSON.stringify(l)}`}]}}else if(s.action==="searchTree"){if(!s.query)return o("搜索失败: 缺少 query 参数");const l=window.__webmcpcli_interactiveBlacklist??[],c=window.__webmcpcli_interactiveWhitelist??[],{text:u}=searchA11yTree(s.query,document.body,l,c,{contextLines:s.contextLines,maxMatches:s.maxMatches});return await e.hideMask(),{content:[{type:"text",text:u}]}}}catch(l){return await e.hideMask(),{content:[{type:"text",text:`异常: ${String(l)}`}]}}}})}function computeBorderGeometry(e,t,n,r){const o=Math.max(1,Math.min(e,t)),i=Math.min(n,20),a=Math.min(i+r,o),l=Math.min(a,Math.floor(e/2)),c=Math.min(a,Math.floor(t/2)),u=w=>w/e*2-1,p=w=>w/t*2-1,f=0,m=e,g=0,x=t,b=l,h=e-l,_=c,E=t-c,S=u(f),A=u(m),D=p(g),M=p(x),W=u(b),N=u(h),H=p(_),V=p(E),Z=0,oe=0,Q=1,te=1,ie=l/e,ne=1-l/e,K=c/t,J=1-c/t,ce=new Float32Array([S,D,A,D,S,H,S,H,A,D,A,H,S,V,A,V,S,M,S,M,A,V,A,M,S,H,W,H,S,V,S,V,W,H,W,V,N,H,A,H,N,V,N,V,A,H,A,V]),d=new Float32Array([Z,oe,Q,oe,Z,K,Z,K,Q,oe,Q,K,Z,J,Q,J,Z,te,Z,te,Q,J,Q,te,Z,K,ie,K,Z,J,Z,J,ie,K,ie,J,ne,K,Q,K,ne,J,ne,J,Q,K,Q,J]);return{positions:ce,uvs:d}}function compileShader(e,t,n){const r=e.createShader(t);if(!r)throw new Error("Failed to create shader");if(e.shaderSource(r,n),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){const o=e.getShaderInfoLog(r)||"Unknown shader error";throw e.deleteShader(r),new Error(o)}return r}function createProgram(e,t,n){const r=compileShader(e,e.VERTEX_SHADER,t),o=compileShader(e,e.FRAGMENT_SHADER,n),i=e.createProgram();if(!i)throw new Error("Failed to create program");if(e.attachShader(i,r),e.attachShader(i,o),e.linkProgram(i),!e.getProgramParameter(i,e.LINK_STATUS)){const s=e.getProgramInfoLog(i)||"Unknown link error";throw e.deleteProgram(i),e.deleteShader(r),e.deleteShader(o),new Error(s)}return e.deleteShader(r),e.deleteShader(o),i}const fragmentShaderSource=`#version 300 es
329
- precision lowp float;
330
- in vec2 vUV;
331
- out vec4 outColor;
332
- uniform vec2 uResolution;
333
- uniform float uTime;
334
- uniform float uBorderWidth;
335
- uniform float uGlowWidth;
336
- uniform float uBorderRadius;
337
- uniform vec3 uColors[4];
338
- uniform float uGlowExponent;
339
- uniform float uGlowFactor;
340
- const float PI = 3.14159265359;
341
- const float TWO_PI = 2.0 * PI;
342
- const float HALF_PI = 0.5 * PI;
343
- const vec4 startPositions = vec4(0.0, PI, HALF_PI, 1.5 * PI);
344
- const vec4 speeds = vec4(-1.9, -1.9, -1.5, 2.1);
345
- const vec4 innerRadius = vec4(PI * 0.8, PI * 0.7, PI * 0.3, PI * 0.1);
346
- const vec4 outerRadius = vec4(PI * 1.2, PI * 0.9, PI * 0.6, PI * 0.4);
347
- float random(vec2 st) {
348
- return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123);
349
- }
350
- vec2 random2(vec2 st) {
351
- return vec2(random(st), random(st + 1.0));
352
- }
353
- float aaStep(float edge, float d) {
354
- float width = fwidth(d);
355
- return smoothstep(edge - width * 0.5, edge + width * 0.5, d);
356
- }
357
- float aaFract(float x) {
358
- float f = fract(x);
359
- float w = fwidth(x);
360
- float smooth_f = f * (1.0 - smoothstep(1.0 - w, 1.0, f));
361
- return smooth_f;
362
- }
363
- float sdRoundedBox(in vec2 p, in vec2 b, in float r) {
364
- vec2 q = abs(p) - b + r;
365
- return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r;
366
- }
367
- float getInnerGlow(vec2 p, vec2 b, float radius) {
368
- float dist_x = b.x - abs(p.x);
369
- float dist_y = b.y - abs(p.y);
370
- float glow_x = smoothstep(radius, 0.0, dist_x);
371
- float glow_y = smoothstep(radius, 0.0, dist_y);
372
- return 1.0 - (1.0 - glow_x) * (1.0 - glow_y);
373
- }
374
- float getVignette(vec2 uv) {
375
- vec2 vignetteUv = uv;
376
- vignetteUv = vignetteUv * (1.0 - vignetteUv);
377
- float vignette = vignetteUv.x * vignetteUv.y * 25.0;
378
- vignette = pow(vignette, 0.16);
379
- vignette = 1.0 - vignette;
380
- return vignette;
381
- }
382
- float uvToAngle(vec2 uv) {
383
- vec2 center = vec2(0.5);
384
- vec2 dir = uv - center;
385
- return atan(dir.y, dir.x) + PI;
386
- }
387
- void main() {
388
- vec2 uv = vUV;
389
- vec2 pos = uv * uResolution;
390
- vec2 centeredPos = pos - uResolution * 0.5;
391
- vec2 size = uResolution - uBorderWidth;
392
- vec2 halfSize = size * 0.5;
393
- float dBorderBox = sdRoundedBox(centeredPos, halfSize, uBorderRadius);
394
- float border = aaStep(0.0, dBorderBox);
395
- float glow = getInnerGlow(centeredPos, halfSize, uGlowWidth);
396
- float vignette = getVignette(uv);
397
- glow *= vignette;
398
- float posAngle = uvToAngle(uv);
399
- vec4 lightCenter = mod(startPositions + speeds * uTime, TWO_PI);
400
- vec4 angleDist = abs(posAngle - lightCenter);
401
- vec4 disToLight = min(angleDist, TWO_PI - angleDist) / TWO_PI;
402
- float intensityBorder[4];
403
- intensityBorder[0] = 1.0;
404
- intensityBorder[1] = smoothstep(0.4, 0.0, disToLight.y);
405
- intensityBorder[2] = smoothstep(0.4, 0.0, disToLight.z);
406
- intensityBorder[3] = smoothstep(0.2, 0.0, disToLight.w) * 0.5;
407
- vec3 borderColor = vec3(0.0);
408
- for(int i = 0; i < 4; i++) {
409
- borderColor = mix(borderColor, uColors[i], intensityBorder[i]);
410
- }
411
- borderColor *= 1.1;
412
- borderColor = clamp(borderColor, 0.0, 1.0);
413
- float intensityGlow[4];
414
- intensityGlow[0] = smoothstep(0.9, 0.0, disToLight.x);
415
- intensityGlow[1] = smoothstep(0.7, 0.0, disToLight.y);
416
- intensityGlow[2] = smoothstep(0.4, 0.0, disToLight.z);
417
- intensityGlow[3] = smoothstep(0.1, 0.0, disToLight.w) * 0.7;
418
- vec4 breath = smoothstep(0.0, 1.0, sin(uTime * 1.0 + startPositions * PI) * 0.2 + 0.8);
419
- vec3 glowColor = vec3(0.0);
420
- glowColor += uColors[0] * intensityGlow[0] * breath.x;
421
- glowColor += uColors[1] * intensityGlow[1] * breath.y;
422
- glowColor += uColors[2] * intensityGlow[2] * breath.z;
423
- glowColor += uColors[3] * intensityGlow[3] * breath.w * glow;
424
- glow = pow(glow, uGlowExponent);
425
- glow *= random(pos + uTime) * 0.1 + 1.0;
426
- glowColor *= glow * uGlowFactor;
427
- glowColor = clamp(glowColor, 0.0, 1.0);
428
- vec3 color = mix(glowColor, borderColor + glowColor * 0.2, border);
429
- float alpha = mix(glow, 1.0, border);
430
- outColor = vec4(color, alpha);
431
- }`,vertexShaderSource=`#version 300 es
432
- in vec2 aPosition;
433
- in vec2 aUV;
434
- out vec2 vUV;
435
- void main() {
436
- vUV = aUV;
437
- gl_Position = vec4(aPosition, 0.0, 1.0);
438
- }`;const DEFAULT_COLORS=["rgb(57, 182, 255)","rgb(189, 69, 251)","rgb(255, 87, 51)","rgb(255, 214, 0)"];function parseColor(e){const t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!t)throw new Error(`Invalid color format: ${e}`);const[,n,r,o]=t;return[parseInt(n)/255,parseInt(r)/255,parseInt(o)/255]}class Motion{element;canvas;options;running=!1;disposed=!1;startTime=0;lastTime=0;rafId=null;glr;observer;constructor(t={}){this.options={width:t.width??600,height:t.height??600,ratio:t.ratio??window.devicePixelRatio??1,borderWidth:t.borderWidth??8,glowWidth:t.glowWidth??200,borderRadius:t.borderRadius??8,mode:t.mode??"light",...t},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 new 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");const t=()=>{if(!this.running||!this.glr)return;this.rafId=requestAnimationFrame(t);const n=performance.now();if(n-this.lastTime<1e3/32)return;this.lastTime=n;const o=(n-this.startTime)*.001;this.render(o)};this.rafId=requestAnimationFrame(t)}pause(){if(this.disposed)throw new 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);const{gl:t,vao:n,positionBuffer:r,uvBuffer:o,program:i}=this.glr;n&&t.deleteVertexArray(n),r&&t.deleteBuffer(r),o&&t.deleteBuffer(o),t.deleteProgram(i),this.observer&&this.observer.disconnect(),this.canvas.remove()}resize(t,n,r){if(this.disposed)throw new Error("Motion instance has been disposed.");if(this.options.width=t,this.options.height=n,r&&(this.options.ratio=r),!this.running)return;const{gl:o,program:i,vao:s,positionBuffer:a,uvBuffer:l,uResolution:c}=this.glr,u=r??this.options.ratio??window.devicePixelRatio??1,p=Math.max(1,Math.floor(t*u)),f=Math.max(1,Math.floor(n*u));this.canvas.style.width=`${t}px`,this.canvas.style.height=`${n}px`,(this.canvas.width!==p||this.canvas.height!==f)&&(this.canvas.width=p,this.canvas.height=f),o.viewport(0,0,this.canvas.width,this.canvas.height),this.checkGLError(o,"resize: after viewport setup");const{positions:m,uvs:g}=computeBorderGeometry(this.canvas.width,this.canvas.height,this.options.borderWidth*u,this.options.glowWidth*u);o.bindVertexArray(s),o.bindBuffer(o.ARRAY_BUFFER,a),o.bufferData(o.ARRAY_BUFFER,m,o.STATIC_DRAW);const x=o.getAttribLocation(i,"aPosition");o.enableVertexAttribArray(x),o.vertexAttribPointer(x,2,o.FLOAT,!1,0,0),this.checkGLError(o,"resize: after position buffer update"),o.bindBuffer(o.ARRAY_BUFFER,l),o.bufferData(o.ARRAY_BUFFER,g,o.STATIC_DRAW);const b=o.getAttribLocation(i,"aUV");o.enableVertexAttribArray(b),o.vertexAttribPointer(b,2,o.FLOAT,!1,0,0),this.checkGLError(o,"resize: after UV buffer update"),o.useProgram(i),o.uniform2f(c,this.canvas.width,this.canvas.height),o.uniform1f(this.glr.uBorderWidth,this.options.borderWidth*u),o.uniform1f(this.glr.uGlowWidth,this.options.glowWidth*u),o.uniform1f(this.glr.uBorderRadius,this.options.borderRadius*u),this.checkGLError(o,"resize: after uniform updates");const h=performance.now();this.lastTime=h;const _=(h-this.startTime)*.001;this.render(_)}autoResize(t){this.observer&&this.observer.disconnect(),this.observer=new ResizeObserver(()=>{const n=t.getBoundingClientRect();this.resize(n.width,n.height)}),this.observer.observe(t)}fadeIn(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((t,n)=>{const r=this.canvas.animate([{opacity:0,transform:"scale(1.2)"},{opacity:1,transform:"scale(1)"}],{duration:300,easing:"ease-out",fill:"forwards"});r.onfinish=()=>t(),r.oncancel=()=>n("canceled")})}fadeOut(){if(this.disposed)throw new Error("Motion instance has been disposed.");return new Promise((t,n)=>{const r=this.canvas.animate([{opacity:1,transform:"scale(1)"},{opacity:0,transform:"scale(1.2)"}],{duration:300,easing:"ease-in",fill:"forwards"});r.onfinish=()=>t(),r.oncancel=()=>n("canceled")})}checkGLError(t,n){let r=t.getError();if(r!==t.NO_ERROR){for(console.group(`🔴 WebGL Error in ${n}`);r!==t.NO_ERROR;){const o=this.getGLErrorName(t,r);console.error(`${o} (0x${r.toString(16)})`),r=t.getError()}console.groupEnd()}}getGLErrorName(t,n){switch(n){case t.INVALID_ENUM:return"INVALID_ENUM";case t.INVALID_VALUE:return"INVALID_VALUE";case t.INVALID_OPERATION:return"INVALID_OPERATION";case t.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case t.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case t.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"UNKNOWN_ERROR"}}setupGL(){const t=this.canvas.getContext("webgl2",{antialias:!1,alpha:!0});if(!t)throw new Error("WebGL2 is required but not available.");const n=createProgram(t,vertexShaderSource,fragmentShaderSource);this.checkGLError(t,"setupGL: after createProgram");const r=t.createVertexArray();t.bindVertexArray(r),this.checkGLError(t,"setupGL: after VAO creation");const o=this.canvas.width||2,i=this.canvas.height||2,{positions:s,uvs:a}=computeBorderGeometry(o,i,this.options.borderWidth,this.options.glowWidth),l=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,l),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW);const c=t.getAttribLocation(n,"aPosition");t.enableVertexAttribArray(c),t.vertexAttribPointer(c,2,t.FLOAT,!1,0,0),this.checkGLError(t,"setupGL: after position buffer setup");const u=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,u),t.bufferData(t.ARRAY_BUFFER,a,t.STATIC_DRAW);const p=t.getAttribLocation(n,"aUV");t.enableVertexAttribArray(p),t.vertexAttribPointer(p,2,t.FLOAT,!1,0,0),this.checkGLError(t,"setupGL: after UV buffer setup");const f=t.getUniformLocation(n,"uResolution"),m=t.getUniformLocation(n,"uTime"),g=t.getUniformLocation(n,"uBorderWidth"),x=t.getUniformLocation(n,"uGlowWidth"),b=t.getUniformLocation(n,"uBorderRadius"),h=t.getUniformLocation(n,"uColors"),_=t.getUniformLocation(n,"uGlowExponent"),E=t.getUniformLocation(n,"uGlowFactor");t.useProgram(n),t.uniform1f(g,this.options.borderWidth),t.uniform1f(x,this.options.glowWidth),t.uniform1f(b,this.options.borderRadius),this.options.mode==="dark"?(t.uniform1f(_,2),t.uniform1f(E,1.8)):(t.uniform1f(_,1),t.uniform1f(E,1));const S=(this.options.colors||DEFAULT_COLORS).map(parseColor);for(let A=0;A<S.length;A++)t.uniform3f(t.getUniformLocation(n,`uColors[${A}]`),...S[A]);this.checkGLError(t,"setupGL: after uniform setup"),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),this.glr={gl:t,program:n,vao:r,positionBuffer:l,uvBuffer:u,uResolution:f,uTime:m,uBorderWidth:g,uGlowWidth:x,uBorderRadius:b,uColors:h}}render(t){if(!this.glr)return;const{gl:n,program:r,vao:o,uTime:i}=this.glr;n.useProgram(r),n.bindVertexArray(o),n.uniform1f(i,t),n.disable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.drawArrays(n.TRIANGLES,0,24),this.checkGLError(n,"render: after draw call"),n.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(){try{if(typeof document<"u"){var e=document.createElement("style");e.appendChild(document.createTextNode(`._wrapper_1ooyb_1 {
439
- position: fixed;
440
- inset: 0;
441
- z-index: 2147483641; /* 确保在所有元素之上,除了 panel */
442
- cursor: wait;
443
- overflow: hidden;
444
-
445
- display: none;
446
- }
447
-
448
- ._wrapper_1ooyb_1._visible_1ooyb_11 {
449
- display: block;
450
- }
451
- /* AI 光标样式 */
452
- ._cursor_1dgwb_2 {
453
- position: absolute;
454
- width: var(--cursor-size, 75px);
455
- height: var(--cursor-size, 75px);
456
- pointer-events: none;
457
- z-index: 10000;
458
- }
459
-
460
- ._cursorBorder_1dgwb_10 {
461
- position: absolute;
462
- width: 100%;
463
- height: 100%;
464
- background: linear-gradient(45deg, rgb(57, 182, 255), rgb(189, 69, 251));
465
- 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");
466
- mask-size: 100% 100%;
467
- mask-repeat: no-repeat;
468
-
469
- transform-origin: center;
470
- transform: rotate(-135deg) scale(1.2);
471
- margin-left: -10px;
472
- margin-top: -18px;
473
- }
474
-
475
- ._cursorFilling_1dgwb_25 {
476
- position: absolute;
477
- width: 100%;
478
- height: 100%;
479
- 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");
480
- background-size: 100% 100%;
481
- background-repeat: no-repeat;
482
-
483
- transform-origin: center;
484
- transform: rotate(-135deg) scale(1.2);
485
- margin-left: -10px;
486
- margin-top: -18px;
487
- }
488
-
489
- ._cursorRipple_1dgwb_39 {
490
- position: absolute;
491
- width: 100%;
492
- height: 100%;
493
- pointer-events: none;
494
- margin-left: -50%;
495
- margin-top: -50%;
496
-
497
- &::after {
498
- content: '';
499
- opacity: 0;
500
- position: absolute;
501
- inset: 0;
502
- border: 4px solid rgba(57, 182, 255, 1);
503
- border-radius: 50%;
504
- }
505
- }
506
-
507
- ._cursor_1dgwb_2._clicking_1dgwb_57 ._cursorRipple_1dgwb_39::after {
508
- animation: _cursor-ripple_1dgwb_1 300ms ease-out forwards;
509
- }
510
-
511
- @keyframes _cursor-ripple_1dgwb_1 {
512
- 0% {
513
- transform: scale(0);
514
- opacity: 1;
515
- }
516
- 100% {
517
- transform: scale(2);
518
- opacity: 0;
519
- }
520
- }`)),document.head.appendChild(e)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}})(),(function(){try{if(typeof document<"u"){var e=document.createElement("style");e.appendChild(document.createTextNode(`._wrapper_1ooyb_1 {
521
- position: fixed;
522
- inset: 0;
523
- z-index: 2147483641; /* 确保在所有元素之上,除了 panel */
524
- cursor: wait;
525
- overflow: hidden;
526
-
527
- display: none;
528
- }
529
-
530
- ._wrapper_1ooyb_1._visible_1ooyb_11 {
531
- display: block;
532
- }
533
- /* AI 光标样式 */
534
- ._cursor_1dgwb_2 {
535
- position: absolute;
536
- width: var(--cursor-size, 75px);
537
- height: var(--cursor-size, 75px);
538
- pointer-events: none;
539
- z-index: 10000;
540
- }
541
-
542
- ._cursorBorder_1dgwb_10 {
543
- position: absolute;
544
- width: 100%;
545
- height: 100%;
546
- background: linear-gradient(45deg, rgb(57, 182, 255), rgb(189, 69, 251));
547
- 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");
548
- mask-size: 100% 100%;
549
- mask-repeat: no-repeat;
550
-
551
- transform-origin: center;
552
- transform: rotate(-135deg) scale(1.2);
553
- margin-left: -10px;
554
- margin-top: -18px;
555
- }
556
-
557
- ._cursorFilling_1dgwb_25 {
558
- position: absolute;
559
- width: 100%;
560
- height: 100%;
561
- 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");
562
- background-size: 100% 100%;
563
- background-repeat: no-repeat;
564
-
565
- transform-origin: center;
566
- transform: rotate(-135deg) scale(1.2);
567
- margin-left: -10px;
568
- margin-top: -18px;
569
- }
570
-
571
- ._cursorRipple_1dgwb_39 {
572
- position: absolute;
573
- width: 100%;
574
- height: 100%;
575
- pointer-events: none;
576
- margin-left: -50%;
577
- margin-top: -50%;
578
-
579
- &::after {
580
- content: '';
581
- opacity: 0;
582
- position: absolute;
583
- inset: 0;
584
- border: 4px solid rgba(57, 182, 255, 1);
585
- border-radius: 50%;
586
- }
587
- }
588
-
589
- ._cursor_1dgwb_2._clicking_1dgwb_57 ._cursorRipple_1dgwb_39::after {
590
- animation: _cursor-ripple_1dgwb_1 300ms ease-out forwards;
591
- }
592
-
593
- @keyframes _cursor-ripple_1dgwb_1 {
594
- 0% {
595
- transform: scale(0);
596
- opacity: 1;
597
- }
598
- 100% {
599
- transform: scale(2);
600
- opacity: 0;
601
- }
602
- }`)),document.head.appendChild(e)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}})();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(){const e=["dark","dark-mode","theme-dark","night","night-mode"],t=document.documentElement,n=document.body||document.documentElement;for(const r of e)if(t.classList.contains(r)||n?.classList.contains(r))return!0;return!1}function hasDarkModeDataAttribute(){const e=document.documentElement,t=document.body||document.documentElement;for(const n of["data-theme","data-color-mode","data-bs-theme","data-mui-color-scheme"]){const r=t?.getAttribute(n),o=e.getAttribute(n);if(r?.toLowerCase()==="dark"||o?.toLowerCase()==="dark")return!0}return!1}function isColorSchemeDark(){const e=document.querySelector('meta[name="color-scheme"]')?.content.toLowerCase();if(e==="dark"||e==="only dark")return!0;const t=window.getComputedStyle(document.documentElement).getPropertyValue("color-scheme").trim().toLowerCase();return t==="dark"||t==="only dark"}function isBackgroundDark(){const 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(){const t=getLuminance(window.getComputedStyle(document.body||document.documentElement).color);return t!==null&&t>200}function isMainContentBackgroundDark(){const{innerWidth:e,innerHeight:t}=window,n=e*t*.5;for(const r of["#app","#root","#__next"]){const o=document.querySelector(r);if(!o)continue;const i=o.getBoundingClientRect();if(!(i.width*i.height<n)&&isColorDark(window.getComputedStyle(o).backgroundColor))return!0}return!1}function parseRgbColor(e){const 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;const t=parseRgbColor(e);return t?.299*t.r+.587*t.g+.114*t.b:null}function isColorDark(e,t=128){const n=getLuminance(e);return n!==null&&n<t}var SimulatorMask_module_default={wrapper:"_wrapper_1ooyb_1",visible:"_visible_1ooyb_11"},cursor_module_default={cursor:"_cursor_1dgwb_2",cursorBorder:"_cursorBorder_1dgwb_10",cursorFilling:"_cursorFilling_1dgwb_25",cursorRipple:"_cursorRipple_1dgwb_39",clicking:"_clicking_1dgwb_57"},SimulatorMask=class extends EventTarget{shown=!1;wrapper=document.createElement("div");motion=null;#r=!1;#e=document.createElement("div");#t=0;#n=0;#o=0;#i=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{const o=new Motion({mode:isPageDark()?"dark":"light",styles:{position:"absolute",inset:"0"}});this.motion=o,this.wrapper.appendChild(o.element),o.autoResize(this.wrapper)}catch(o){console.warn("[SimulatorMask] Motion overlay unavailable:",o)}this.wrapper.addEventListener("click",o=>{o.stopPropagation(),o.preventDefault()}),this.wrapper.addEventListener("mousedown",o=>{o.stopPropagation(),o.preventDefault()}),this.wrapper.addEventListener("mouseup",o=>{o.stopPropagation(),o.preventDefault()}),this.wrapper.addEventListener("mousemove",o=>{o.stopPropagation(),o.preventDefault()}),this.wrapper.addEventListener("wheel",o=>{o.stopPropagation(),o.preventDefault()}),this.wrapper.addEventListener("keydown",o=>{o.stopPropagation(),o.preventDefault()}),this.wrapper.addEventListener("keyup",o=>{o.stopPropagation(),o.preventDefault()}),this.#a(),document.body.appendChild(this.wrapper),this.#s();const e=o=>{const{x:i,y:s}=o.detail;this.setCursorPosition(i,s)},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)})}#a(){this.#e.className=cursor_module_default.cursor;const e=document.createElement("div");e.className=cursor_module_default.cursorRipple,this.#e.appendChild(e);const t=document.createElement("div");t.className=cursor_module_default.cursorFilling,this.#e.appendChild(t);const n=document.createElement("div");n.className=cursor_module_default.cursorBorder,this.#e.appendChild(n),this.wrapper.appendChild(this.#e)}#s(){if(this.#r)return;const e=this.#t+(this.#o-this.#t)*.2,t=this.#n+(this.#i-this.#n)*.2,n=Math.abs(e-this.#o);n>0&&(n<2?this.#t=this.#o:this.#t=e,this.#e.style.left=`${this.#t}px`);const r=Math.abs(t-this.#i);r>0&&(r<2?this.#n=this.#i:this.#n=t,this.#e.style.top=`${this.#n}px`),requestAnimationFrame(()=>this.#s())}setCursorPosition(e,t){this.#r||(this.#o=e,this.#i=t)}triggerClickAnimation(){this.#r||(this.#e.classList.remove(cursor_module_default.clicking),this.#e.offsetHeight,this.#e.classList.add(cursor_module_default.clicking))}show(){this.shown||this.#r||(this.shown=!0,this.motion?.start(),this.motion?.fadeIn(),this.wrapper.classList.add(SimulatorMask_module_default.visible),this.#t=window.innerWidth/2,this.#n=window.innerHeight/2,this.#o=this.#t,this.#i=this.#n,this.#e.style.left=`${this.#t}px`,this.#e.style.top=`${this.#n}px`)}hide(){!this.shown||this.#r||(this.shown=!1,this.motion?.fadeOut(),this.motion?.pause(),this.#e.classList.remove(cursor_module_default.clicking),setTimeout(()=>{this.wrapper.classList.remove(SimulatorMask_module_default.visible)},800))}dispose(){this.#r=!0,this.motion?.dispose(),this.wrapper.remove(),this.dispatchEvent(new Event("dispose"))}};const SimulatorMaskBHVXyogh=Object.freeze(Object.defineProperty({__proto__:null,SimulatorMask},Symbol.toStringTag,{value:"Module"}));exports.Ajv=ajv,Object.defineProperty(exports,"ResourceTemplate",{enumerable:!0,get:()=>mcp_js.ResourceTemplate}),Object.defineProperty(exports,"z",{enumerable:!0,get:()=>zod.z}),Object.defineProperty(exports,"UriTemplate",{enumerable:!0,get:()=>uriTemplate_js.UriTemplate}),Object.defineProperty(exports,"completable",{enumerable:!0,get:()=>completable_js.completable}),Object.defineProperty(exports,"getDisplayName",{enumerable:!0,get:()=>metadataUtils_js.getDisplayName}),exports.AuthClientProvider=AuthClientProvider,exports.ExtensionPageServerTransport=ExtensionPageServerTransport,exports.WebMcpClient=WebMcpClient,exports.WebMcpServer=WebMcpServer,exports.createMessageChannelClientTransport=createMessageChannelClientTransport,exports.createMessageChannelPairTransport=createMessageChannelPairTransport,exports.createMessageChannelServerTransport=createMessageChannelServerTransport,exports.createSSEClientTransport=createSSEClientTransport,exports.createStreamableHTTPClientTransport=createStreamableHTTPClientTransport,exports.initializeBuiltinWebMCP=initializeBuiltinWebMCP,exports.isMcpClient=isMcpClient,exports.isMcpServer=isMcpServer,exports.isMessageChannelClientTransport=isMessageChannelClientTransport,exports.isMessageChannelServerTransport=isMessageChannelServerTransport,exports.isSSEClientTransport=isSSEClientTransport,exports.isStreamableHTTPClientTransport=isStreamableHTTPClientTransport,exports.registerPageAgentTool=registerPageAgentTool,exports.setupModelContextBridge=setupModelContextBridge,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})}));